Merge "Increase heap size for fast capture in stereo" into oc-mr1-dev am: 9ea2cb3908
am: 8e9dad0cf9

Change-Id: Id82e063af84476a5b93dda6ce179a2737cdfb4ba
diff --git a/cmds/stagefright/audioloop.cpp b/cmds/stagefright/audioloop.cpp
index ed44b4d..67017eb 100644
--- a/cmds/stagefright/audioloop.cpp
+++ b/cmds/stagefright/audioloop.cpp
@@ -112,7 +112,7 @@
     looper->setName("audioloop");
     looper->start();
 
-    sp<IMediaSource> encoder = MediaCodecSource::Create(looper, meta, source);
+    sp<MediaSource> encoder = MediaCodecSource::Create(looper, meta, source);
 
     if (fileOut != NULL) {
         // target file specified, write encoded AMR output
@@ -128,7 +128,7 @@
         writer->stop();
     } else {
         // otherwise decode to speaker
-        sp<IMediaSource> decoder = SimpleDecodingSource::Create(encoder);
+        sp<MediaSource> decoder = SimpleDecodingSource::Create(encoder);
 
         if (playToSpeaker) {
             AudioPlayer *player = new AudioPlayer(NULL);
diff --git a/cmds/stagefright/record.cpp b/cmds/stagefright/record.cpp
index 94c2e96..69b00c9 100644
--- a/cmds/stagefright/record.cpp
+++ b/cmds/stagefright/record.cpp
@@ -320,7 +320,7 @@
     looper->setName("record");
     looper->start();
 
-    sp<IMediaSource> encoder =
+    sp<MediaSource> encoder =
         MediaCodecSource::Create(looper, encMeta, audioSource);
 
     encoder->start();
diff --git a/cmds/stagefright/recordvideo.cpp b/cmds/stagefright/recordvideo.cpp
index 7a3c842..af39d46 100644
--- a/cmds/stagefright/recordvideo.cpp
+++ b/cmds/stagefright/recordvideo.cpp
@@ -303,7 +303,7 @@
     looper->setName("recordvideo");
     looper->start();
 
-    sp<IMediaSource> encoder =
+    sp<MediaSource> encoder =
         MediaCodecSource::Create(
                 looper, enc_meta, source, NULL /* consumer */,
                 preferSoftwareCodec ? MediaCodecSource::FLAG_PREFER_SOFTWARE_CODEC : 0);
diff --git a/cmds/stagefright/stagefright.cpp b/cmds/stagefright/stagefright.cpp
index d70282b..7a5d129 100644
--- a/cmds/stagefright/stagefright.cpp
+++ b/cmds/stagefright/stagefright.cpp
@@ -141,7 +141,7 @@
     }
 }
 
-static void dumpSource(const sp<IMediaSource> &source, const String8 &filename) {
+static void dumpSource(const sp<MediaSource> &source, const String8 &filename) {
     FILE *out = fopen(filename.string(), "wb");
 
     CHECK_EQ((status_t)OK, source->start());
@@ -174,13 +174,13 @@
     out = NULL;
 }
 
-static void playSource(sp<IMediaSource> &source) {
+static void playSource(sp<MediaSource> &source) {
     sp<MetaData> meta = source->getFormat();
 
     const char *mime;
     CHECK(meta->findCString(kKeyMIMEType, &mime));
 
-    sp<IMediaSource> rawSource;
+    sp<MediaSource> rawSource;
     if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mime)) {
         rawSource = source;
     } else {
@@ -404,7 +404,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct DetectSyncSource : public MediaSource {
-    explicit DetectSyncSource(const sp<IMediaSource> &source);
+    explicit DetectSyncSource(const sp<MediaSource> &source);
 
     virtual status_t start(MetaData *params = NULL);
     virtual status_t stop();
@@ -421,14 +421,14 @@
         OTHER,
     };
 
-    sp<IMediaSource> mSource;
+    sp<MediaSource> mSource;
     StreamType mStreamType;
     bool mSawFirstIDRFrame;
 
     DISALLOW_EVIL_CONSTRUCTORS(DetectSyncSource);
 };
 
-DetectSyncSource::DetectSyncSource(const sp<IMediaSource> &source)
+DetectSyncSource::DetectSyncSource(const sp<MediaSource> &source)
     : mSource(source),
       mStreamType(OTHER),
       mSawFirstIDRFrame(false) {
@@ -510,7 +510,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 static void writeSourcesToMP4(
-        Vector<sp<IMediaSource> > &sources, bool syncInfoPresent) {
+        Vector<sp<MediaSource> > &sources, bool syncInfoPresent) {
 #if 0
     sp<MPEG4Writer> writer =
         new MPEG4Writer(gWriteMP4Filename.string());
@@ -528,7 +528,7 @@
     writer->setMaxFileDuration(60000000ll);
 
     for (size_t i = 0; i < sources.size(); ++i) {
-        sp<IMediaSource> source = sources.editItemAt(i);
+        sp<MediaSource> source = sources.editItemAt(i);
 
         CHECK_EQ(writer->addSource(
                     syncInfoPresent ? source : new DetectSyncSource(source)),
@@ -545,7 +545,7 @@
     writer->stop();
 }
 
-static void performSeekTest(const sp<IMediaSource> &source) {
+static void performSeekTest(const sp<MediaSource> &source) {
     CHECK_EQ((status_t)OK, source->start());
 
     int64_t durationUs;
@@ -1002,8 +1002,8 @@
             isJPEG = true;
         }
 
-        Vector<sp<IMediaSource> > mediaSources;
-        sp<IMediaSource> mediaSource;
+        Vector<sp<MediaSource> > mediaSources;
+        sp<MediaSource> mediaSource;
 
         if (isJPEG) {
             mediaSource = new JPEGSource(dataSource);
@@ -1049,7 +1049,8 @@
                 bool haveAudio = false;
                 bool haveVideo = false;
                 for (size_t i = 0; i < numTracks; ++i) {
-                    sp<IMediaSource> source = extractor->getTrack(i);
+                    sp<MediaSource> source = MediaSource::CreateFromIMediaSource(
+                            extractor->getTrack(i));
                     if (source == nullptr) {
                         fprintf(stderr, "skip NULL track %zu, track count %zu.\n", i, numTracks);
                         continue;
@@ -1115,7 +1116,7 @@
                            thumbTimeUs, thumbTimeUs / 1E6);
                 }
 
-                mediaSource = extractor->getTrack(i);
+                mediaSource = MediaSource::CreateFromIMediaSource(extractor->getTrack(i));
                 if (mediaSource == nullptr) {
                     fprintf(stderr, "skip NULL track %zu, total tracks %zu.\n", i, numTracks);
                     return -1;
@@ -1128,7 +1129,7 @@
         } else if (dumpStream) {
             dumpSource(mediaSource, dumpStreamFilename);
         } else if (dumpPCMStream) {
-            sp<IMediaSource> decSource = SimpleDecodingSource::Create(mediaSource);
+            sp<MediaSource> decSource = SimpleDecodingSource::Create(mediaSource);
             dumpSource(decSource, dumpStreamFilename);
         } else if (seekTest) {
             performSeekTest(mediaSource);
diff --git a/cmds/stagefright/stream.cpp b/cmds/stagefright/stream.cpp
index 2e1d240..3b7a0e0 100644
--- a/cmds/stagefright/stream.cpp
+++ b/cmds/stagefright/stream.cpp
@@ -182,7 +182,7 @@
             continue;
         }
 
-        sp<IMediaSource> track = extractor->getTrack(i);
+        sp<MediaSource> track = MediaSource::CreateFromIMediaSource(extractor->getTrack(i));
         if (track == nullptr) {
             fprintf(stderr, "skip NULL track %zu, total tracks %zu\n", i, numTracks);
             continue;
diff --git a/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp b/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp
index cb69f91..eaa3390 100644
--- a/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp
+++ b/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp
@@ -89,7 +89,7 @@
     // asset_id change. If it sends an EcmContainer with 2 Ecms with different
     // asset_ids (old and new) then it might be best to prefetch the Emm.
     if ((asset_.id() != 0) && (*asset_id != asset_.id())) {
-        ALOGW("Asset_id change from %" PRIu64 " to %" PRIu64, asset_.id(), *asset_id);
+        ALOGW("Asset_id change from %llu to %" PRIu64, asset_.id(), *asset_id);
         asset_.Clear();
     }
 
diff --git a/drm/mediacas/plugins/mock/MockCasPlugin.cpp b/drm/mediacas/plugins/mock/MockCasPlugin.cpp
index 18cd9a4..500208b 100644
--- a/drm/mediacas/plugins/mock/MockCasPlugin.cpp
+++ b/drm/mediacas/plugins/mock/MockCasPlugin.cpp
@@ -146,7 +146,7 @@
     if (session == NULL) {
         return BAD_VALUE;
     }
-    ALOGV("ECM: size=%d", ecm.size());
+    ALOGV("ECM: size=%zu", ecm.size());
     ALOGV("ECM: data=%s", arrayToString(ecm).string());
 
     return OK;
@@ -156,7 +156,7 @@
     ALOGV("processEmm");
     Mutex::Autolock lock(mLock);
 
-    ALOGV("EMM: size=%d", emm.size());
+    ALOGV("EMM: size=%zu", emm.size());
     ALOGV("EMM: data=%s", arrayToString(emm).string());
 
     return OK;
diff --git a/include/OWNERS b/include/OWNERS
index 3cb6d9c..d6bd998 100644
--- a/include/OWNERS
+++ b/include/OWNERS
@@ -1,5 +1,5 @@
 elaurent@google.com
-gkasten@android.com
+gkasten@google.com
 hunga@google.com
 jtinker@google.com
 lajos@google.com
diff --git a/include/common_time/OWNERS b/include/common_time/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/include/common_time/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/include/media/IAudioRecord.h b/include/media/IAudioRecord.h
deleted file mode 120000
index 7fbf8f2..0000000
--- a/include/media/IAudioRecord.h
+++ /dev/null
@@ -1 +0,0 @@
-../../media/libaudioclient/include/media/IAudioRecord.h
\ No newline at end of file
diff --git a/include/media/IHDCP.h b/include/media/IHDCP.h
deleted file mode 120000
index 9d4568e..0000000
--- a/include/media/IHDCP.h
+++ /dev/null
@@ -1 +0,0 @@
-../../media/libmedia/include/media/IHDCP.h
\ No newline at end of file
diff --git a/include/media/VolumeShaper.h b/include/media/VolumeShaper.h
index 302641f..a3aaece 100644
--- a/include/media/VolumeShaper.h
+++ b/include/media/VolumeShaper.h
@@ -37,6 +37,8 @@
 
 namespace android {
 
+namespace media {
+
 // The native VolumeShaper class mirrors the java VolumeShaper class;
 // in addition, the native class contains implementation for actual operation.
 //
@@ -101,7 +103,7 @@
      * See "frameworks/base/media/java/android/media/VolumeShaper.java" for
      * details on the Java implementation.
      */
-    class Configuration : public Interpolator<S, T>, public RefBase {
+    class Configuration : public Interpolator<S, T>, public RefBase, public Parcelable {
     public:
         // Must match with VolumeShaper.java in frameworks/base.
         enum Type : int32_t {
@@ -283,7 +285,7 @@
         }
 
         // The parcel layout must match VolumeShaper.java
-        status_t writeToParcel(Parcel *parcel) const {
+        status_t writeToParcel(Parcel *parcel) const override {
             if (parcel == nullptr) return BAD_VALUE;
             return parcel->writeInt32((int32_t)mType)
                     ?: parcel->writeInt32(mId)
@@ -294,17 +296,17 @@
                             ?: Interpolator<S, T>::writeToParcel(parcel);
         }
 
-        status_t readFromParcel(const Parcel &parcel) {
+        status_t readFromParcel(const Parcel *parcel) override {
             int32_t type, optionFlags;
-            return parcel.readInt32(&type)
+            return parcel->readInt32(&type)
                     ?: setType((Type)type)
-                    ?: parcel.readInt32(&mId)
+                    ?: parcel->readInt32(&mId)
                     ?: mType == TYPE_ID
                         ? NO_ERROR
-                        : parcel.readInt32(&optionFlags)
+                        : parcel->readInt32(&optionFlags)
                             ?: setOptionFlags((OptionFlag)optionFlags)
-                            ?: parcel.readDouble(&mDurationMs)
-                            ?: Interpolator<S, T>::readFromParcel(parcel)
+                            ?: parcel->readDouble(&mDurationMs)
+                            ?: Interpolator<S, T>::readFromParcel(*parcel)
                             ?: checkCurve();
         }
 
@@ -336,7 +338,7 @@
      * See "frameworks/base/media/java/android/media/VolumeShaper.java" for
      * details on the Java implementation.
      */
-    class Operation : public RefBase {
+    class Operation : public RefBase, public Parcelable {
     public:
         // Must match with VolumeShaper.java.
         enum Flag : int32_t {
@@ -418,18 +420,18 @@
             return NO_ERROR;
         }
 
-        status_t writeToParcel(Parcel *parcel) const {
+        status_t writeToParcel(Parcel *parcel) const override {
             if (parcel == nullptr) return BAD_VALUE;
             return parcel->writeInt32((int32_t)mFlags)
                     ?: parcel->writeInt32(mReplaceId)
                     ?: parcel->writeFloat(mXOffset);
         }
 
-        status_t readFromParcel(const Parcel &parcel) {
+        status_t readFromParcel(const Parcel *parcel) override {
             int32_t flags;
-            return parcel.readInt32(&flags)
-                    ?: parcel.readInt32(&mReplaceId)
-                    ?: parcel.readFloat(&mXOffset)
+            return parcel->readInt32(&flags)
+                    ?: parcel->readInt32(&mReplaceId)
+                    ?: parcel->readFloat(&mXOffset)
                     ?: setFlags((Flag)flags);
         }
 
@@ -455,7 +457,7 @@
      * See "frameworks/base/media/java/android/media/VolumeShaper.java" for
      * details on the Java implementation.
      */
-    class State : public RefBase {
+    class State : public RefBase, public Parcelable {
     public:
         State(T volume, S xOffset)
             : mVolume(volume)
@@ -481,15 +483,15 @@
             mXOffset = xOffset;
         }
 
-        status_t writeToParcel(Parcel *parcel) const {
+        status_t writeToParcel(Parcel *parcel) const override {
             if (parcel == nullptr) return BAD_VALUE;
             return parcel->writeFloat(mVolume)
                     ?: parcel->writeFloat(mXOffset);
         }
 
-        status_t readFromParcel(const Parcel &parcel) {
-            return parcel.readFloat(&mVolume)
-                     ?: parcel.readFloat(&mXOffset);
+        status_t readFromParcel(const Parcel *parcel) override {
+            return parcel->readFloat(&mVolume)
+                     ?: parcel->readFloat(&mXOffset);
         }
 
         std::string toString() const {
@@ -1020,6 +1022,8 @@
     std::list<VolumeShaper> mVolumeShapers; // list provides stable iterators on erase
 }; // VolumeHandler
 
+} // namespace media
+
 } // namespace android
 
 #pragma pop_macro("LOG_TAG")
diff --git a/include/media/nbaio/NBLog.h b/include/media/nbaio/NBLog.h
deleted file mode 120000
index c35401e..0000000
--- a/include/media/nbaio/NBLog.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../media/libnbaio/include/media/nbaio/NBLog.h
\ No newline at end of file
diff --git a/include/media/nbaio/PerformanceAnalysis.h b/include/media/nbaio/PerformanceAnalysis.h
deleted file mode 120000
index 7acfc90..0000000
--- a/include/media/nbaio/PerformanceAnalysis.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../media/libnbaio/include/media/nbaio/PerformanceAnalysis.h
\ No newline at end of file
diff --git a/include/media/nblog/NBLog.h b/include/media/nblog/NBLog.h
new file mode 120000
index 0000000..3cc366c
--- /dev/null
+++ b/include/media/nblog/NBLog.h
@@ -0,0 +1 @@
+../../../media/libnblog/include/media/nblog/NBLog.h
\ No newline at end of file
diff --git a/include/media/nblog/PerformanceAnalysis.h b/include/media/nblog/PerformanceAnalysis.h
new file mode 120000
index 0000000..6ead3bc
--- /dev/null
+++ b/include/media/nblog/PerformanceAnalysis.h
@@ -0,0 +1 @@
+../../../media/libnblog/include/media/nblog/PerformanceAnalysis.h
\ No newline at end of file
diff --git a/include/media/nblog/ReportPerformance.h b/include/media/nblog/ReportPerformance.h
new file mode 120000
index 0000000..e9b8e80
--- /dev/null
+++ b/include/media/nblog/ReportPerformance.h
@@ -0,0 +1 @@
+../../../media/libnblog/include/media/nblog/ReportPerformance.h
\ No newline at end of file
diff --git a/include/private/media/OWNERS b/include/private/media/OWNERS
new file mode 100644
index 0000000..21723ba
--- /dev/null
+++ b/include/private/media/OWNERS
@@ -0,0 +1,3 @@
+elaurent@google.com
+gkasten@google.com
+hunga@google.com
diff --git a/include/soundtrigger/OWNERS b/include/soundtrigger/OWNERS
new file mode 100644
index 0000000..e83f6b9
--- /dev/null
+++ b/include/soundtrigger/OWNERS
@@ -0,0 +1,2 @@
+elaurent@google.com
+thorntonc@google.com
diff --git a/media/audioserver/Android.mk b/media/audioserver/Android.mk
index 3ee7494..0777890 100644
--- a/media/audioserver/Android.mk
+++ b/media/audioserver/Android.mk
@@ -3,7 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := \
-	main_audioserver.cpp
+	main_audioserver.cpp \
+	../libaudioclient/aidl/android/media/IAudioRecord.aidl
 
 LOCAL_SHARED_LIBRARIES := \
 	libaaudioservice \
@@ -36,6 +37,9 @@
 	$(call include-path-for, audio-utils) \
 	external/sonic \
 
+LOCAL_AIDL_INCLUDES := \
+        frameworks/av/media/libaudioclient/aidl
+
 # If AUDIOSERVER_MULTILIB in device.mk is non-empty then it is used to control
 # the LOCAL_MULTILIB for all audioserver exclusive libraries.
 # This is relevant for 64 bit architectures where either or both
diff --git a/media/audioserver/OWNERS b/media/audioserver/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/media/audioserver/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/media/audioserver/audioserver.rc b/media/audioserver/audioserver.rc
index 9d42bce..75675a9 100644
--- a/media/audioserver/audioserver.rc
+++ b/media/audioserver/audioserver.rc
@@ -1,10 +1,13 @@
 service audioserver /system/bin/audioserver
-    class main
+    class core
     user audioserver
     # media gid needed for /dev/fm (radio) and for /data/misc/media (tee)
     group audio camera drmrpc inet media mediadrm net_bt net_bt_admin net_bw_acct
     ioprio rt 4
     writepid /dev/cpuset/foreground/tasks /dev/stune/foreground/tasks
+    onrestart restart vendor.audio-hal-2-0
+    # Keep the original service name for backward compatibility when upgrading
+    # O-MR1 devices with framework-only.
     onrestart restart audio-hal-2-0
 
 on property:vts.native_server.on=1
diff --git a/media/common_time/OWNERS b/media/common_time/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/media/common_time/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/media/extractors/Android.bp b/media/extractors/Android.bp
new file mode 100644
index 0000000..e8176cf
--- /dev/null
+++ b/media/extractors/Android.bp
@@ -0,0 +1,3 @@
+subdirs = [
+    "*",
+]
diff --git a/media/libstagefright/AACExtractor.cpp b/media/extractors/aac/AACExtractor.cpp
similarity index 91%
rename from media/libstagefright/AACExtractor.cpp
rename to media/extractors/aac/AACExtractor.cpp
index 7449aa7..ce5f976 100644
--- a/media/libstagefright/AACExtractor.cpp
+++ b/media/extractors/aac/AACExtractor.cpp
@@ -18,7 +18,7 @@
 #define LOG_TAG "AACExtractor"
 #include <utils/Log.h>
 
-#include "include/AACExtractor.h"
+#include "AACExtractor.h"
 #include "include/avc_utils.h"
 
 #include <media/stagefright/foundation/ABuffer.h>
@@ -140,13 +140,8 @@
     sp<AMessage> meta = _meta;
 
     if (meta == NULL) {
-        String8 mimeType;
-        float confidence;
-        sp<AMessage> _meta;
-
-        if (!SniffAAC(mDataSource, &mimeType, &confidence, &meta)) {
-            return;
-        }
+        ALOGE("no metadata specified");
+        return;
     }
 
     int64_t offset;
@@ -213,7 +208,7 @@
     return mInitCheck == OK ? 1 : 0;
 }
 
-sp<IMediaSource> AACExtractor::getTrack(size_t index) {
+sp<MediaSource> AACExtractor::getTrack(size_t index) {
     if (mInitCheck != OK || index != 0) {
         return NULL;
     }
@@ -333,7 +328,13 @@
 
 ////////////////////////////////////////////////////////////////////////////////
 
-bool SniffAAC(
+static MediaExtractor* CreateExtractor(
+        const sp<DataSource> &source,
+        const sp<AMessage>& meta) {
+    return new AACExtractor(source, meta);
+}
+
+static MediaExtractor::CreatorFunc Sniff(
         const sp<DataSource> &source, String8 *mimeType, float *confidence,
         sp<AMessage> *meta) {
     off64_t pos = 0;
@@ -342,7 +343,7 @@
         uint8_t id3header[10];
         if (source->readAt(pos, id3header, sizeof(id3header))
                 < (ssize_t)sizeof(id3header)) {
-            return false;
+            return NULL;
         }
 
         if (memcmp("ID3", id3header, 3)) {
@@ -368,7 +369,7 @@
     uint8_t header[2];
 
     if (source->readAt(pos, &header, 2) != 2) {
-        return false;
+        return NULL;
     }
 
     // ADTS syncword
@@ -379,10 +380,26 @@
         *meta = new AMessage;
         (*meta)->setInt64("offset", pos);
 
-        return true;
+        return CreateExtractor;
     }
 
-    return false;
+    return NULL;
 }
 
-}  // namespace android
+
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+        UUID("4fd80eae-03d2-4d72-9eb9-48fa6bb54613"),
+        1, // version
+        "AAC Extractor",
+        Sniff
+    };
+}
+
+} // extern "C"
+
+} // namespace android
diff --git a/media/libstagefright/include/AACExtractor.h b/media/extractors/aac/AACExtractor.h
similarity index 96%
rename from media/libstagefright/include/AACExtractor.h
rename to media/extractors/aac/AACExtractor.h
index bd4c41c..91e2eed 100644
--- a/media/libstagefright/include/AACExtractor.h
+++ b/media/extractors/aac/AACExtractor.h
@@ -32,7 +32,7 @@
     AACExtractor(const sp<DataSource> &source, const sp<AMessage> &meta);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
diff --git a/media/extractors/aac/Android.bp b/media/extractors/aac/Android.bp
new file mode 100644
index 0000000..b4ef53e
--- /dev/null
+++ b/media/extractors/aac/Android.bp
@@ -0,0 +1,39 @@
+cc_library_shared {
+
+    srcs: ["AACExtractor.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libutils",
+        "liblog",
+    ],
+
+    name: "libaacextractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-fvisibility=hidden",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        diag: {
+            cfi: true,
+        },
+    },
+
+}
diff --git a/media/libstagefright/matroska/MODULE_LICENSE_APACHE2 b/media/extractors/aac/MODULE_LICENSE_APACHE2
similarity index 100%
rename from media/libstagefright/matroska/MODULE_LICENSE_APACHE2
rename to media/extractors/aac/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/matroska/NOTICE b/media/extractors/aac/NOTICE
similarity index 100%
rename from media/libstagefright/matroska/NOTICE
rename to media/extractors/aac/NOTICE
diff --git a/media/libstagefright/AMRExtractor.cpp b/media/extractors/amr/AMRExtractor.cpp
similarity index 90%
rename from media/libstagefright/AMRExtractor.cpp
rename to media/extractors/amr/AMRExtractor.cpp
index 2892520..d8b92bd 100644
--- a/media/libstagefright/AMRExtractor.cpp
+++ b/media/extractors/amr/AMRExtractor.cpp
@@ -18,7 +18,7 @@
 #define LOG_TAG "AMRExtractor"
 #include <utils/Log.h>
 
-#include "include/AMRExtractor.h"
+#include "AMRExtractor.h"
 
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/DataSource.h>
@@ -186,7 +186,7 @@
     return mInitCheck == OK ? 1 : 0;
 }
 
-sp<IMediaSource> AMRExtractor::getTrack(size_t index) {
+sp<MediaSource> AMRExtractor::getTrack(size_t index) {
     if (mInitCheck != OK || index != 0) {
         return NULL;
     }
@@ -362,4 +362,31 @@
     return false;
 }
 
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+        UUID("c86639c9-2f31-40ac-a715-fa01b4493aaf"),
+        1,
+        "AMR Extractor",
+        [](
+                const sp<DataSource> &source,
+                String8 *mimeType,
+                float *confidence,
+                sp<AMessage> *meta __unused) -> MediaExtractor::CreatorFunc {
+            if (SniffAMR(source, mimeType, confidence, meta)) {
+                return [](
+                        const sp<DataSource> &source,
+                        const sp<AMessage>& meta __unused) -> MediaExtractor* {
+                    return new AMRExtractor(source);};
+            }
+            return NULL;
+        }
+    };
+}
+
+} // extern "C"
+
 }  // namespace android
diff --git a/media/libstagefright/include/AMRExtractor.h b/media/extractors/amr/AMRExtractor.h
similarity index 96%
rename from media/libstagefright/include/AMRExtractor.h
rename to media/extractors/amr/AMRExtractor.h
index 8abcb12..06cd387 100644
--- a/media/libstagefright/include/AMRExtractor.h
+++ b/media/extractors/amr/AMRExtractor.h
@@ -32,7 +32,7 @@
     explicit AMRExtractor(const sp<DataSource> &source);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
diff --git a/media/extractors/amr/Android.bp b/media/extractors/amr/Android.bp
new file mode 100644
index 0000000..85e4777
--- /dev/null
+++ b/media/extractors/amr/Android.bp
@@ -0,0 +1,39 @@
+cc_library_shared {
+
+    srcs: ["AMRExtractor.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/include",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libutils",
+        "liblog",
+    ],
+
+    name: "libamrextractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-fvisibility=hidden",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        diag: {
+            cfi: true,
+        },
+    },
+
+}
diff --git a/media/libstagefright/matroska/MODULE_LICENSE_APACHE2 b/media/extractors/amr/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/matroska/MODULE_LICENSE_APACHE2
copy to media/extractors/amr/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/matroska/NOTICE b/media/extractors/amr/NOTICE
similarity index 100%
copy from media/libstagefright/matroska/NOTICE
copy to media/extractors/amr/NOTICE
diff --git a/media/extractors/flac/Android.bp b/media/extractors/flac/Android.bp
new file mode 100644
index 0000000..5edc182
--- /dev/null
+++ b/media/extractors/flac/Android.bp
@@ -0,0 +1,44 @@
+cc_library_shared {
+
+    srcs: ["FLACExtractor.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/include",
+        "external/flac/include",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libutils",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libFLAC",
+    ],
+
+    name: "libflacextractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-fvisibility=hidden",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        diag: {
+            cfi: true,
+        },
+    },
+
+}
diff --git a/media/libstagefright/FLACExtractor.cpp b/media/extractors/flac/FLACExtractor.cpp
similarity index 84%
rename from media/libstagefright/FLACExtractor.cpp
rename to media/extractors/flac/FLACExtractor.cpp
index 1b88e5d..dda8100 100644
--- a/media/libstagefright/FLACExtractor.cpp
+++ b/media/extractors/flac/FLACExtractor.cpp
@@ -18,22 +18,147 @@
 #define LOG_TAG "FLACExtractor"
 #include <utils/Log.h>
 
-#include "include/FLACExtractor.h"
-// Vorbis comments
-#include "include/OggExtractor.h"
+#include "FLACExtractor.h"
 // libFLAC parser
 #include "FLAC/stream_decoder.h"
 
+#include <media/stagefright/foundation/ABuffer.h>
 #include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/foundation/base64.h>
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/MediaBufferGroup.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/MediaSource.h>
 #include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/Utils.h>
 
 namespace android {
 
+// also exists in OggExtractor, candidate for moving to utility/support library?
+static void extractAlbumArt(
+        const sp<MetaData> &fileMeta, const void *data, size_t size) {
+    ALOGV("extractAlbumArt from '%s'", (const char *)data);
+
+    sp<ABuffer> flacBuffer = decodeBase64(AString((const char *)data, size));
+    if (flacBuffer == NULL) {
+        ALOGE("malformed base64 encoded data.");
+        return;
+    }
+
+    size_t flacSize = flacBuffer->size();
+    uint8_t *flac = flacBuffer->data();
+    ALOGV("got flac of size %zu", flacSize);
+
+    uint32_t picType;
+    uint32_t typeLen;
+    uint32_t descLen;
+    uint32_t dataLen;
+    char type[128];
+
+    if (flacSize < 8) {
+        return;
+    }
+
+    picType = U32_AT(flac);
+
+    if (picType != 3) {
+        // This is not a front cover.
+        return;
+    }
+
+    typeLen = U32_AT(&flac[4]);
+    if (typeLen > sizeof(type) - 1) {
+        return;
+    }
+
+    // we've already checked above that flacSize >= 8
+    if (flacSize - 8 < typeLen) {
+        return;
+    }
+
+    memcpy(type, &flac[8], typeLen);
+    type[typeLen] = '\0';
+
+    ALOGV("picType = %d, type = '%s'", picType, type);
+
+    if (!strcmp(type, "-->")) {
+        // This is not inline cover art, but an external url instead.
+        return;
+    }
+
+    if (flacSize < 32 || flacSize - 32 < typeLen) {
+        return;
+    }
+
+    descLen = U32_AT(&flac[8 + typeLen]);
+    if (flacSize - 32 - typeLen < descLen) {
+        return;
+    }
+
+    dataLen = U32_AT(&flac[8 + typeLen + 4 + descLen + 16]);
+
+    // we've already checked above that (flacSize - 32 - typeLen - descLen) >= 0
+    if (flacSize - 32 - typeLen - descLen < dataLen) {
+        return;
+    }
+
+    ALOGV("got image data, %zu trailing bytes",
+         flacSize - 32 - typeLen - descLen - dataLen);
+
+    fileMeta->setData(
+            kKeyAlbumArt, 0, &flac[8 + typeLen + 4 + descLen + 20], dataLen);
+
+    fileMeta->setCString(kKeyAlbumArtMIME, type);
+}
+
+// also exists in OggExtractor, candidate for moving to utility/support library?
+static void parseVorbisComment(
+        const sp<MetaData> &fileMeta, const char *comment, size_t commentLength)
+{
+    struct {
+        const char *const mTag;
+        uint32_t mKey;
+    } kMap[] = {
+        { "TITLE", kKeyTitle },
+        { "ARTIST", kKeyArtist },
+        { "ALBUMARTIST", kKeyAlbumArtist },
+        { "ALBUM ARTIST", kKeyAlbumArtist },
+        { "COMPILATION", kKeyCompilation },
+        { "ALBUM", kKeyAlbum },
+        { "COMPOSER", kKeyComposer },
+        { "GENRE", kKeyGenre },
+        { "AUTHOR", kKeyAuthor },
+        { "TRACKNUMBER", kKeyCDTrackNumber },
+        { "DISCNUMBER", kKeyDiscNumber },
+        { "DATE", kKeyDate },
+        { "YEAR", kKeyYear },
+        { "LYRICIST", kKeyWriter },
+        { "METADATA_BLOCK_PICTURE", kKeyAlbumArt },
+        { "ANDROID_LOOP", kKeyAutoLoop },
+    };
+
+        for (size_t j = 0; j < sizeof(kMap) / sizeof(kMap[0]); ++j) {
+            size_t tagLen = strlen(kMap[j].mTag);
+            if (!strncasecmp(kMap[j].mTag, comment, tagLen)
+                    && comment[tagLen] == '=') {
+                if (kMap[j].mKey == kKeyAlbumArt) {
+                    extractAlbumArt(
+                            fileMeta,
+                            &comment[tagLen + 1],
+                            commentLength - tagLen - 1);
+                } else if (kMap[j].mKey == kKeyAutoLoop) {
+                    if (!strcasecmp(&comment[tagLen + 1], "true")) {
+                        fileMeta->setInt32(kKeyAutoLoop, true);
+                    }
+                } else {
+                    fileMeta->setCString(kMap[j].mKey, &comment[tagLen + 1]);
+                }
+            }
+        }
+
+}
+
 class FLACParser;
 
 class FLACSource : public MediaSource {
@@ -811,7 +936,7 @@
     return mInitCheck == OK ? 1 : 0;
 }
 
-sp<IMediaSource> FLACExtractor::getTrack(size_t index)
+sp<MediaSource> FLACExtractor::getTrack(size_t index)
 {
     if (mInitCheck != OK || index > 0) {
         return NULL;
@@ -864,4 +989,32 @@
     return true;
 }
 
+
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+            UUID("1364b048-cc45-4fda-9934-327d0ebf9829"),
+            1,
+            "FLAC Extractor",
+            [](
+                    const sp<DataSource> &source,
+                    String8 *mimeType,
+                    float *confidence,
+                    sp<AMessage> *meta __unused) -> MediaExtractor::CreatorFunc {
+                if (SniffFLAC(source, mimeType, confidence, meta)) {
+                    return [](
+                            const sp<DataSource> &source,
+                            const sp<AMessage>& meta __unused) -> MediaExtractor* {
+                        return new FLACExtractor(source);};
+                }
+                return NULL;
+            }
+     };
+}
+
+} // extern "C"
+
 }  // namespace android
diff --git a/media/libstagefright/include/FLACExtractor.h b/media/extractors/flac/FLACExtractor.h
similarity index 96%
rename from media/libstagefright/include/FLACExtractor.h
rename to media/extractors/flac/FLACExtractor.h
index 51bc139..e945cf6 100644
--- a/media/libstagefright/include/FLACExtractor.h
+++ b/media/extractors/flac/FLACExtractor.h
@@ -32,7 +32,7 @@
     explicit FLACExtractor(const sp<DataSource> &source);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
diff --git a/media/libstagefright/matroska/MODULE_LICENSE_APACHE2 b/media/extractors/flac/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/matroska/MODULE_LICENSE_APACHE2
copy to media/extractors/flac/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/matroska/NOTICE b/media/extractors/flac/NOTICE
similarity index 100%
copy from media/libstagefright/matroska/NOTICE
copy to media/extractors/flac/NOTICE
diff --git a/media/extractors/midi/Android.bp b/media/extractors/midi/Android.bp
new file mode 100644
index 0000000..1b84b94
--- /dev/null
+++ b/media/extractors/midi/Android.bp
@@ -0,0 +1,40 @@
+cc_library_shared {
+
+    srcs: ["MidiExtractor.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/include",
+    ],
+
+    shared_libs: [
+        "libsonivox",
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libutils",
+        "liblog",
+    ],
+
+    name: "libmidiextractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-fvisibility=hidden",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        diag: {
+            cfi: true,
+        },
+    },
+
+}
diff --git a/media/libstagefright/matroska/MODULE_LICENSE_APACHE2 b/media/extractors/midi/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/matroska/MODULE_LICENSE_APACHE2
copy to media/extractors/midi/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/MidiExtractor.cpp b/media/extractors/midi/MidiExtractor.cpp
similarity index 89%
rename from media/libstagefright/MidiExtractor.cpp
rename to media/extractors/midi/MidiExtractor.cpp
index 7930bbb..1f32cb3 100644
--- a/media/libstagefright/MidiExtractor.cpp
+++ b/media/extractors/midi/MidiExtractor.cpp
@@ -18,7 +18,7 @@
 #define LOG_TAG "MidiExtractor"
 #include <utils/Log.h>
 
-#include "include/MidiExtractor.h"
+#include "MidiExtractor.h"
 
 #include <media/MidiIoWrapper.h>
 #include <media/stagefright/foundation/ADebug.h>
@@ -282,7 +282,7 @@
     return mInitCheck == OK ? 1 : 0;
 }
 
-sp<IMediaSource> MidiExtractor::getTrack(size_t index)
+sp<MediaSource> MidiExtractor::getTrack(size_t index)
 {
     if (mInitCheck != OK || index > 0) {
         return NULL;
@@ -323,4 +323,31 @@
 
 }
 
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+        UUID("ef6cca0a-f8a2-43e6-ba5f-dfcd7c9a7ef2"),
+        1,
+        "MIDI Extractor",
+        [](
+                const sp<DataSource> &source,
+                String8 *mimeType,
+                float *confidence,
+                sp<AMessage> *meta __unused) -> MediaExtractor::CreatorFunc {
+            if (SniffMidi(source, mimeType, confidence, meta)) {
+                return [](
+                        const sp<DataSource> &source,
+                        const sp<AMessage>& meta __unused) -> MediaExtractor* {
+                    return new MidiExtractor(source);};
+            }
+            return NULL;
+        }
+    };
+}
+
+} // extern "C"
+
 }  // namespace android
diff --git a/media/libstagefright/include/MidiExtractor.h b/media/extractors/midi/MidiExtractor.h
similarity index 97%
rename from media/libstagefright/include/MidiExtractor.h
rename to media/extractors/midi/MidiExtractor.h
index 94d2d08..87a4a02 100644
--- a/media/libstagefright/include/MidiExtractor.h
+++ b/media/extractors/midi/MidiExtractor.h
@@ -56,7 +56,7 @@
     explicit MidiExtractor(const sp<DataSource> &source);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
diff --git a/media/libstagefright/matroska/NOTICE b/media/extractors/midi/NOTICE
similarity index 100%
copy from media/libstagefright/matroska/NOTICE
copy to media/extractors/midi/NOTICE
diff --git a/media/libstagefright/matroska/Android.bp b/media/extractors/mkv/Android.bp
similarity index 62%
rename from media/libstagefright/matroska/Android.bp
rename to media/extractors/mkv/Android.bp
index ec2fb4b..f855bbb 100644
--- a/media/libstagefright/matroska/Android.bp
+++ b/media/extractors/mkv/Android.bp
@@ -1,35 +1,47 @@
-cc_library_static {
-    name: "libstagefright_matroska",
+cc_library_shared {
 
     srcs: ["MatroskaExtractor.cpp"],
 
     include_dirs: [
         "external/flac/include",
         "external/libvpx/libwebm",
-        "frameworks/native/include/media/openmax",
-        "frameworks/av/media/libstagefright/flac/dec",
         "frameworks/av/media/libstagefright/include",
+        "frameworks/av/media/libstagefright/flac/dec",
     ],
 
+    shared_libs: [
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libstagefright_flacdec",
+        "libutils",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libwebm",
+    ],
+
+    name: "libmkvextractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
     cflags: [
-        "-Wno-multichar",
         "-Werror",
         "-Wall",
+        "-fvisibility=hidden",
     ],
 
     sanitize: {
-        misc_undefined: [
-            "signed-integer-overflow",
-            "unsigned-integer-overflow",
-        ],
         cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
         diag: {
             cfi: true,
         },
     },
 
-    shared_libs: [
-        "libmedia",
-        "libstagefright_flacdec"
-    ],
 }
diff --git a/media/libstagefright/matroska/MODULE_LICENSE_APACHE2 b/media/extractors/mkv/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/matroska/MODULE_LICENSE_APACHE2
copy to media/extractors/mkv/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/matroska/MatroskaExtractor.cpp b/media/extractors/mkv/MatroskaExtractor.cpp
similarity index 97%
rename from media/libstagefright/matroska/MatroskaExtractor.cpp
rename to media/extractors/mkv/MatroskaExtractor.cpp
index 4b38906..1de6f90 100644
--- a/media/libstagefright/matroska/MatroskaExtractor.cpp
+++ b/media/extractors/mkv/MatroskaExtractor.cpp
@@ -899,7 +899,7 @@
     return mTracks.size();
 }
 
-sp<IMediaSource> MatroskaExtractor::getTrack(size_t index) {
+sp<MediaSource> MatroskaExtractor::getTrack(size_t index) {
     if (index >= mTracks.size()) {
         return NULL;
     }
@@ -1527,4 +1527,32 @@
     return true;
 }
 
+
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+        UUID("abbedd92-38c4-4904-a4c1-b3f45f899980"),
+        1,
+        "Matroska Extractor",
+        [](
+                const sp<DataSource> &source,
+                String8 *mimeType,
+                float *confidence,
+                sp<AMessage> *meta __unused) -> MediaExtractor::CreatorFunc {
+            if (SniffMatroska(source, mimeType, confidence, meta)) {
+                return [](
+                        const sp<DataSource> &source,
+                        const sp<AMessage>& meta __unused) -> MediaExtractor* {
+                    return new MatroskaExtractor(source);};
+            }
+            return NULL;
+        }
+    };
+}
+
+} // extern "C"
+
 }  // namespace android
diff --git a/media/libstagefright/matroska/MatroskaExtractor.h b/media/extractors/mkv/MatroskaExtractor.h
similarity index 97%
rename from media/libstagefright/matroska/MatroskaExtractor.h
rename to media/extractors/mkv/MatroskaExtractor.h
index 19775ce..832463f 100644
--- a/media/libstagefright/matroska/MatroskaExtractor.h
+++ b/media/extractors/mkv/MatroskaExtractor.h
@@ -38,7 +38,7 @@
 
     virtual size_t countTracks();
 
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
 
     virtual sp<MetaData> getTrackMetaData(
             size_t index, uint32_t flags);
diff --git a/media/libstagefright/matroska/NOTICE b/media/extractors/mkv/NOTICE
similarity index 100%
copy from media/libstagefright/matroska/NOTICE
copy to media/extractors/mkv/NOTICE
diff --git a/media/extractors/mp3/Android.bp b/media/extractors/mp3/Android.bp
new file mode 100644
index 0000000..b189ddf
--- /dev/null
+++ b/media/extractors/mp3/Android.bp
@@ -0,0 +1,47 @@
+cc_library_shared {
+
+    srcs: [
+            "MP3Extractor.cpp",
+            "VBRISeeker.cpp",
+            "XINGSeeker.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/include",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libutils",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libstagefright_id3",
+    ],
+
+    name: "libmp3extractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-fvisibility=hidden",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        diag: {
+            cfi: true,
+        },
+    },
+
+}
diff --git a/media/libstagefright/MP3Extractor.cpp b/media/extractors/mp3/MP3Extractor.cpp
similarity index 95%
rename from media/libstagefright/MP3Extractor.cpp
rename to media/extractors/mp3/MP3Extractor.cpp
index 22df522..63ef8cf 100644
--- a/media/libstagefright/MP3Extractor.cpp
+++ b/media/extractors/mp3/MP3Extractor.cpp
@@ -18,12 +18,12 @@
 #define LOG_TAG "MP3Extractor"
 #include <utils/Log.h>
 
-#include "include/MP3Extractor.h"
+#include "MP3Extractor.h"
 
-#include "include/avc_utils.h"
-#include "include/ID3.h"
-#include "include/VBRISeeker.h"
-#include "include/XINGSeeker.h"
+#include "avc_utils.h"
+#include "ID3.h"
+#include "VBRISeeker.h"
+#include "XINGSeeker.h"
 
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/AMessage.h>
@@ -407,7 +407,7 @@
     return mInitCheck != OK ? 0 : 1;
 }
 
-sp<IMediaSource> MP3Extractor::getTrack(size_t index) {
+sp<MediaSource> MP3Extractor::getTrack(size_t index) {
     if (mInitCheck != OK || index != 0) {
         return NULL;
     }
@@ -666,14 +666,20 @@
     return meta;
 }
 
-bool SniffMP3(
+static MediaExtractor* CreateExtractor(
+        const sp<DataSource> &source,
+        const sp<AMessage>& meta) {
+    return new MP3Extractor(source, meta);
+}
+
+static MediaExtractor::CreatorFunc Sniff(
         const sp<DataSource> &source, String8 *mimeType,
         float *confidence, sp<AMessage> *meta) {
     off64_t pos = 0;
     off64_t post_id3_pos;
     uint32_t header;
     if (!Resync(source, 0, &pos, &post_id3_pos, &header)) {
-        return false;
+        return NULL;
     }
 
     *meta = new AMessage;
@@ -684,7 +690,22 @@
     *mimeType = MEDIA_MIMETYPE_AUDIO_MPEG;
     *confidence = 0.2f;
 
-    return true;
+    return CreateExtractor;
 }
 
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+        UUID("812a3f6c-c8cf-46de-b529-3774b14103d4"),
+        1, // version
+        "MP3 Extractor",
+        Sniff
+    };
+}
+
+} // extern "C"
+
 }  // namespace android
diff --git a/media/libstagefright/include/MP3Extractor.h b/media/extractors/mp3/MP3Extractor.h
similarity index 96%
rename from media/libstagefright/include/MP3Extractor.h
rename to media/extractors/mp3/MP3Extractor.h
index 2fd04f2..2b16c24 100644
--- a/media/libstagefright/include/MP3Extractor.h
+++ b/media/extractors/mp3/MP3Extractor.h
@@ -34,7 +34,7 @@
     MP3Extractor(const sp<DataSource> &source, const sp<AMessage> &meta);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
diff --git a/media/libstagefright/include/MP3Seeker.h b/media/extractors/mp3/MP3Seeker.h
similarity index 100%
rename from media/libstagefright/include/MP3Seeker.h
rename to media/extractors/mp3/MP3Seeker.h
diff --git a/media/libstagefright/VBRISeeker.cpp b/media/extractors/mp3/VBRISeeker.cpp
similarity index 97%
rename from media/libstagefright/VBRISeeker.cpp
rename to media/extractors/mp3/VBRISeeker.cpp
index 5b8f23a..24002db 100644
--- a/media/libstagefright/VBRISeeker.cpp
+++ b/media/extractors/mp3/VBRISeeker.cpp
@@ -21,10 +21,9 @@
 
 #include <utils/Log.h>
 
-#include "include/VBRISeeker.h"
+#include "VBRISeeker.h"
 
-#include "include/avc_utils.h"
-#include "include/MP3Extractor.h"
+#include "avc_utils.h"
 
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/DataSource.h>
diff --git a/media/libstagefright/include/VBRISeeker.h b/media/extractors/mp3/VBRISeeker.h
similarity index 97%
rename from media/libstagefright/include/VBRISeeker.h
rename to media/extractors/mp3/VBRISeeker.h
index c57d571..87258b0 100644
--- a/media/libstagefright/include/VBRISeeker.h
+++ b/media/extractors/mp3/VBRISeeker.h
@@ -18,7 +18,7 @@
 
 #define VBRI_SEEKER_H_
 
-#include "include/MP3Seeker.h"
+#include "MP3Seeker.h"
 
 #include <utils/Vector.h>
 
diff --git a/media/libstagefright/XINGSeeker.cpp b/media/extractors/mp3/XINGSeeker.cpp
similarity index 98%
rename from media/libstagefright/XINGSeeker.cpp
rename to media/extractors/mp3/XINGSeeker.cpp
index 81ed9c6..954e61b 100644
--- a/media/libstagefright/XINGSeeker.cpp
+++ b/media/extractors/mp3/XINGSeeker.cpp
@@ -17,8 +17,8 @@
 #define LOG_TAG "XINGSEEKER"
 #include <utils/Log.h>
 
-#include "include/XINGSeeker.h"
-#include "include/avc_utils.h"
+#include "XINGSeeker.h"
+#include "avc_utils.h"
 
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/Utils.h>
diff --git a/media/libstagefright/include/XINGSeeker.h b/media/extractors/mp3/XINGSeeker.h
similarity index 97%
rename from media/libstagefright/include/XINGSeeker.h
rename to media/extractors/mp3/XINGSeeker.h
index cce04f0..37077c4 100644
--- a/media/libstagefright/include/XINGSeeker.h
+++ b/media/extractors/mp3/XINGSeeker.h
@@ -18,7 +18,7 @@
 
 #define XING_SEEKER_H_
 
-#include "include/MP3Seeker.h"
+#include "MP3Seeker.h"
 
 namespace android {
 
diff --git a/media/extractors/mp4/Android.bp b/media/extractors/mp4/Android.bp
new file mode 100644
index 0000000..a957e98
--- /dev/null
+++ b/media/extractors/mp4/Android.bp
@@ -0,0 +1,48 @@
+cc_library_shared {
+
+    srcs: [
+        "ItemTable.cpp",
+        "MPEG4Extractor.cpp",
+        "SampleIterator.cpp",
+        "SampleTable.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libutils",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libstagefright_id3",
+    ],
+
+    name: "libmp4extractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-fvisibility=hidden",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        diag: {
+            cfi: true,
+        },
+    },
+
+}
diff --git a/media/libstagefright/ItemTable.cpp b/media/extractors/mp4/ItemTable.cpp
similarity index 99%
rename from media/libstagefright/ItemTable.cpp
rename to media/extractors/mp4/ItemTable.cpp
index 3ec416b..558a2bc 100644
--- a/media/libstagefright/ItemTable.cpp
+++ b/media/extractors/mp4/ItemTable.cpp
@@ -17,7 +17,7 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "ItemTable"
 
-#include <include/ItemTable.h>
+#include <ItemTable.h>
 #include <media/MediaDefs.h>
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/MetaData.h>
diff --git a/media/libstagefright/include/ItemTable.h b/media/extractors/mp4/ItemTable.h
similarity index 100%
rename from media/libstagefright/include/ItemTable.h
rename to media/extractors/mp4/ItemTable.h
diff --git a/media/libstagefright/matroska/MODULE_LICENSE_APACHE2 b/media/extractors/mp4/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/matroska/MODULE_LICENSE_APACHE2
copy to media/extractors/mp4/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp
similarity index 99%
rename from media/libstagefright/MPEG4Extractor.cpp
rename to media/extractors/mp4/MPEG4Extractor.cpp
index 27599be..a625e24 100644
--- a/media/libstagefright/MPEG4Extractor.cpp
+++ b/media/extractors/mp4/MPEG4Extractor.cpp
@@ -26,9 +26,9 @@
 
 #include <utils/Log.h>
 
-#include "include/MPEG4Extractor.h"
-#include "include/SampleTable.h"
-#include "include/ItemTable.h"
+#include "MPEG4Extractor.h"
+#include "SampleTable.h"
+#include "ItemTable.h"
 #include "include/ESDS.h"
 
 #include <media/stagefright/foundation/ABitReader.h>
@@ -3344,7 +3344,7 @@
     }
 }
 
-sp<IMediaSource> MPEG4Extractor::getTrack(size_t index) {
+sp<MediaSource> MPEG4Extractor::getTrack(size_t index) {
     status_t err;
     if ((err = readMetaData()) != OK) {
         return NULL;
@@ -5474,19 +5474,42 @@
     return true;
 }
 
-bool SniffMPEG4(
-        const sp<DataSource> &source, String8 *mimeType, float *confidence,
+static MediaExtractor* CreateExtractor(
+        const sp<DataSource> &source,
+        const sp<AMessage>& meta __unused) {
+    return new MPEG4Extractor(source);
+}
+
+static MediaExtractor::CreatorFunc Sniff(
+        const sp<DataSource> &source,
+        String8 *mimeType,
+        float *confidence,
         sp<AMessage> *meta) {
     if (BetterSniffMPEG4(source, mimeType, confidence, meta)) {
-        return true;
+        return CreateExtractor;
     }
 
     if (LegacySniffMPEG4(source, mimeType, confidence)) {
         ALOGW("Identified supported mpeg4 through LegacySniffMPEG4.");
-        return true;
+        return CreateExtractor;
     }
 
-    return false;
+    return NULL;
 }
 
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+        UUID("27575c67-4417-4c54-8d3d-8e626985a164"),
+        1, // version
+        "MP4 Extractor",
+        Sniff
+    };
+}
+
+} // extern "C"
+
 }  // namespace android
diff --git a/media/libstagefright/include/MPEG4Extractor.h b/media/extractors/mp4/MPEG4Extractor.h
similarity index 98%
rename from media/libstagefright/include/MPEG4Extractor.h
rename to media/extractors/mp4/MPEG4Extractor.h
index 214a3de..bd404d2 100644
--- a/media/libstagefright/include/MPEG4Extractor.h
+++ b/media/extractors/mp4/MPEG4Extractor.h
@@ -56,7 +56,7 @@
     explicit MPEG4Extractor(const sp<DataSource> &source);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
diff --git a/media/libstagefright/matroska/NOTICE b/media/extractors/mp4/NOTICE
similarity index 100%
copy from media/libstagefright/matroska/NOTICE
copy to media/extractors/mp4/NOTICE
diff --git a/media/libstagefright/SampleIterator.cpp b/media/extractors/mp4/SampleIterator.cpp
similarity index 98%
rename from media/libstagefright/SampleIterator.cpp
rename to media/extractors/mp4/SampleIterator.cpp
index 75f744d..c4c6faf 100644
--- a/media/libstagefright/SampleIterator.cpp
+++ b/media/extractors/mp4/SampleIterator.cpp
@@ -18,7 +18,7 @@
 //#define LOG_NDEBUG 0
 #include <utils/Log.h>
 
-#include "include/SampleIterator.h"
+#include "SampleIterator.h"
 
 #include <arpa/inet.h>
 
@@ -26,7 +26,7 @@
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/Utils.h>
 
-#include "include/SampleTable.h"
+#include "SampleTable.h"
 
 namespace android {
 
diff --git a/media/libstagefright/include/SampleIterator.h b/media/extractors/mp4/SampleIterator.h
similarity index 100%
rename from media/libstagefright/include/SampleIterator.h
rename to media/extractors/mp4/SampleIterator.h
diff --git a/media/libstagefright/SampleTable.cpp b/media/extractors/mp4/SampleTable.cpp
similarity index 99%
rename from media/libstagefright/SampleTable.cpp
rename to media/extractors/mp4/SampleTable.cpp
index 1d2a931..d87d1b6 100644
--- a/media/libstagefright/SampleTable.cpp
+++ b/media/extractors/mp4/SampleTable.cpp
@@ -20,8 +20,8 @@
 
 #include <limits>
 
-#include "include/SampleTable.h"
-#include "include/SampleIterator.h"
+#include "SampleTable.h"
+#include "SampleIterator.h"
 
 #include <arpa/inet.h>
 
diff --git a/media/libstagefright/include/SampleTable.h b/media/extractors/mp4/SampleTable.h
similarity index 100%
rename from media/libstagefright/include/SampleTable.h
rename to media/extractors/mp4/SampleTable.h
diff --git a/media/extractors/mpeg2/Android.bp b/media/extractors/mpeg2/Android.bp
new file mode 100644
index 0000000..e69afd8
--- /dev/null
+++ b/media/extractors/mpeg2/Android.bp
@@ -0,0 +1,56 @@
+cc_library_shared {
+
+    srcs: [
+        "ExtractorBundle.cpp",
+        "MPEG2PSExtractor.cpp",
+        "MPEG2TSExtractor.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright",
+        "frameworks/av/media/libstagefright/include",
+    ],
+
+    shared_libs: [
+        "libbinder",
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libcutils",
+        "libutils",
+        "liblog",
+        "libcrypto",
+        "libmedia",
+        "libhidlbase",
+        "android.hidl.token@1.0-utils",
+        "android.hardware.cas@1.0",
+        "android.hardware.cas.native@1.0",
+    ],
+
+    static_libs: [
+        "libstagefright_mpeg2support",
+    ],
+
+    name: "libmpeg2extractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-fvisibility=hidden",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        diag: {
+            cfi: true,
+        },
+    },
+
+}
diff --git a/media/extractors/mpeg2/ExtractorBundle.cpp b/media/extractors/mpeg2/ExtractorBundle.cpp
new file mode 100644
index 0000000..076515e
--- /dev/null
+++ b/media/extractors/mpeg2/ExtractorBundle.cpp
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2017 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 "MPEG2ExtractorBundle"
+#include <utils/Log.h>
+
+#include <media/stagefright/MediaExtractor.h>
+#include "MPEG2PSExtractor.h"
+#include "MPEG2TSExtractor.h"
+
+namespace android {
+
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+        UUID("3d1dcfeb-e40a-436d-a574-c2438a555e5f"),
+        1,
+        "MPEG2-PS/TS Extractor",
+        [](
+                const sp<DataSource> &source,
+                String8 *mimeType,
+                float *confidence,
+                sp<AMessage> *meta __unused) -> MediaExtractor::CreatorFunc {
+            if (SniffMPEG2TS(source, mimeType, confidence, meta)) {
+                return [](
+                        const sp<DataSource> &source,
+                        const sp<AMessage>& meta __unused) -> MediaExtractor* {
+                    return new MPEG2TSExtractor(source);};
+            } else if (SniffMPEG2PS(source, mimeType, confidence, meta)) {
+                        return [](
+                                const sp<DataSource> &source,
+                                const sp<AMessage>& meta __unused) -> MediaExtractor* {
+                            return new MPEG2PSExtractor(source);};
+            }
+            return NULL;
+        }
+    };
+}
+
+} // extern "C"
+
+} // namespace android
diff --git a/media/libstagefright/matroska/MODULE_LICENSE_APACHE2 b/media/extractors/mpeg2/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/matroska/MODULE_LICENSE_APACHE2
copy to media/extractors/mpeg2/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp b/media/extractors/mpeg2/MPEG2PSExtractor.cpp
similarity index 98%
rename from media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp
rename to media/extractors/mpeg2/MPEG2PSExtractor.cpp
index 078a5f0..a8a35bd 100644
--- a/media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp
+++ b/media/extractors/mpeg2/MPEG2PSExtractor.cpp
@@ -18,10 +18,10 @@
 #define LOG_TAG "MPEG2PSExtractor"
 #include <utils/Log.h>
 
-#include "include/MPEG2PSExtractor.h"
+#include "MPEG2PSExtractor.h"
 
-#include "AnotherPacketSource.h"
-#include "ESQueue.h"
+#include "mpeg2ts/AnotherPacketSource.h"
+#include "mpeg2ts/ESQueue.h"
 
 #include <media/stagefright/foundation/ABitReader.h>
 #include <media/stagefright/foundation/ABuffer.h>
@@ -125,7 +125,7 @@
     return mTracks.size();
 }
 
-sp<IMediaSource> MPEG2PSExtractor::getTrack(size_t index) {
+sp<MediaSource> MPEG2PSExtractor::getTrack(size_t index) {
     if (index >= mTracks.size()) {
         return NULL;
     }
diff --git a/media/libstagefright/include/MPEG2PSExtractor.h b/media/extractors/mpeg2/MPEG2PSExtractor.h
similarity index 97%
rename from media/libstagefright/include/MPEG2PSExtractor.h
rename to media/extractors/mpeg2/MPEG2PSExtractor.h
index f5471b3..75e1346 100644
--- a/media/libstagefright/include/MPEG2PSExtractor.h
+++ b/media/extractors/mpeg2/MPEG2PSExtractor.h
@@ -34,7 +34,7 @@
     explicit MPEG2PSExtractor(const sp<DataSource> &source);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
diff --git a/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp b/media/extractors/mpeg2/MPEG2TSExtractor.cpp
similarity index 98%
rename from media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp
rename to media/extractors/mpeg2/MPEG2TSExtractor.cpp
index 9d684e0..d42e901 100644
--- a/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp
+++ b/media/extractors/mpeg2/MPEG2TSExtractor.cpp
@@ -20,8 +20,7 @@
 #include <inttypes.h>
 #include <utils/Log.h>
 
-#include "include/MPEG2TSExtractor.h"
-#include "include/NuCachedSource2.h"
+#include "MPEG2TSExtractor.h"
 
 #include <media/stagefright/foundation/ABuffer.h>
 #include <media/stagefright/foundation/ADebug.h>
@@ -35,8 +34,8 @@
 #include <media/IStreamSource.h>
 #include <utils/String8.h>
 
-#include "AnotherPacketSource.h"
-#include "ATSParser.h"
+#include "mpeg2ts/AnotherPacketSource.h"
+#include "mpeg2ts/ATSParser.h"
 
 #include <hidl/HybridInterface.h>
 #include <android/hardware/cas/1.0/ICas.h>
@@ -129,7 +128,7 @@
     return mSourceImpls.size();
 }
 
-sp<IMediaSource> MPEG2TSExtractor::getTrack(size_t index) {
+sp<MediaSource> MPEG2TSExtractor::getTrack(size_t index) {
     if (index >= mSourceImpls.size()) {
         return NULL;
     }
diff --git a/media/libstagefright/include/MPEG2TSExtractor.h b/media/extractors/mpeg2/MPEG2TSExtractor.h
similarity index 98%
rename from media/libstagefright/include/MPEG2TSExtractor.h
rename to media/extractors/mpeg2/MPEG2TSExtractor.h
index ac93b5e..1702157 100644
--- a/media/libstagefright/include/MPEG2TSExtractor.h
+++ b/media/extractors/mpeg2/MPEG2TSExtractor.h
@@ -40,7 +40,7 @@
     explicit MPEG2TSExtractor(const sp<DataSource> &source);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
diff --git a/media/libstagefright/matroska/NOTICE b/media/extractors/mpeg2/NOTICE
similarity index 100%
copy from media/libstagefright/matroska/NOTICE
copy to media/extractors/mpeg2/NOTICE
diff --git a/media/extractors/ogg/Android.bp b/media/extractors/ogg/Android.bp
new file mode 100644
index 0000000..17b939a
--- /dev/null
+++ b/media/extractors/ogg/Android.bp
@@ -0,0 +1,41 @@
+cc_library_shared {
+
+    srcs: ["OggExtractor.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/include",
+        "external/tremolo",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libutils",
+        "liblog",
+        "libvorbisidec",
+    ],
+
+    name: "liboggextractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-fvisibility=hidden",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        diag: {
+            cfi: true,
+        },
+    },
+
+}
diff --git a/media/libstagefright/matroska/MODULE_LICENSE_APACHE2 b/media/extractors/ogg/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/matroska/MODULE_LICENSE_APACHE2
copy to media/extractors/ogg/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/matroska/NOTICE b/media/extractors/ogg/NOTICE
similarity index 100%
copy from media/libstagefright/matroska/NOTICE
copy to media/extractors/ogg/NOTICE
diff --git a/media/libstagefright/OggExtractor.cpp b/media/extractors/ogg/OggExtractor.cpp
similarity index 97%
rename from media/libstagefright/OggExtractor.cpp
rename to media/extractors/ogg/OggExtractor.cpp
index 766230a..db4fc4d 100644
--- a/media/libstagefright/OggExtractor.cpp
+++ b/media/extractors/ogg/OggExtractor.cpp
@@ -18,7 +18,7 @@
 #define LOG_TAG "OggExtractor"
 #include <utils/Log.h>
 
-#include "include/OggExtractor.h"
+#include "OggExtractor.h"
 
 #include <cutils/properties.h>
 #include <media/stagefright/foundation/ABuffer.h>
@@ -1176,19 +1176,8 @@
     return (mVi.bitrate_lower + mVi.bitrate_upper) / 2;
 }
 
-void MyOggExtractor::parseFileMetaData() {
-    mFileMeta = new MetaData;
-    mFileMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_CONTAINER_OGG);
-
-    for (int i = 0; i < mVc.comments; ++i) {
-        const char *comment = mVc.user_comments[i];
-        size_t commentLength = mVc.comment_lengths[i];
-        parseVorbisComment(mFileMeta, comment, commentLength);
-        //ALOGI("comment #%d: '%s'", i + 1, mVc.user_comments[i]);
-    }
-}
-
-void parseVorbisComment(
+// also exists in FLACExtractor, candidate for moving to utility/support library?
+static void parseVorbisComment(
         const sp<MetaData> &fileMeta, const char *comment, size_t commentLength)
 {
     struct {
@@ -1234,6 +1223,7 @@
 
 }
 
+// also exists in FLACExtractor, candidate for moving to utility/support library?
 static void extractAlbumArt(
         const sp<MetaData> &fileMeta, const void *data, size_t size) {
     ALOGV("extractAlbumArt from '%s'", (const char *)data);
@@ -1310,6 +1300,19 @@
     fileMeta->setCString(kKeyAlbumArtMIME, type);
 }
 
+void MyOggExtractor::parseFileMetaData() {
+    mFileMeta = new MetaData;
+    mFileMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_CONTAINER_OGG);
+
+    for (int i = 0; i < mVc.comments; ++i) {
+        const char *comment = mVc.user_comments[i];
+        size_t commentLength = mVc.comment_lengths[i];
+        parseVorbisComment(mFileMeta, comment, commentLength);
+        //ALOGI("comment #%d: '%s'", i + 1, mVc.user_comments[i]);
+    }
+}
+
+
 ////////////////////////////////////////////////////////////////////////////////
 
 OggExtractor::OggExtractor(const sp<DataSource> &source)
@@ -1345,7 +1348,7 @@
     return mInitCheck != OK ? 0 : 1;
 }
 
-sp<IMediaSource> OggExtractor::getTrack(size_t index) {
+sp<MediaSource> OggExtractor::getTrack(size_t index) {
     if (index >= 1) {
         return NULL;
     }
@@ -1366,18 +1369,41 @@
     return mImpl->getFileMetaData();
 }
 
-bool SniffOgg(
-        const sp<DataSource> &source, String8 *mimeType, float *confidence,
+static MediaExtractor* CreateExtractor(
+        const sp<DataSource> &source,
+        const sp<AMessage>& meta __unused) {
+    return new OggExtractor(source);
+}
+
+static MediaExtractor::CreatorFunc Sniff(
+        const sp<DataSource> &source,
+        String8 *mimeType,
+        float *confidence,
         sp<AMessage> *) {
     char tmp[4];
     if (source->readAt(0, tmp, 4) < 4 || memcmp(tmp, "OggS", 4)) {
-        return false;
+        return NULL;
     }
 
     mimeType->setTo(MEDIA_MIMETYPE_CONTAINER_OGG);
     *confidence = 0.2f;
 
-    return true;
+    return CreateExtractor;
 }
 
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+        UUID("8cc5cd06-f772-495e-8a62-cba9649374e9"),
+        1, // version
+        "Ogg Extractor",
+        Sniff
+    };
+}
+
+} // extern "C"
+
 }  // namespace android
diff --git a/media/libstagefright/include/OggExtractor.h b/media/extractors/ogg/OggExtractor.h
similarity index 90%
rename from media/libstagefright/include/OggExtractor.h
rename to media/extractors/ogg/OggExtractor.h
index 55aafed..f42c105 100644
--- a/media/libstagefright/include/OggExtractor.h
+++ b/media/extractors/ogg/OggExtractor.h
@@ -34,7 +34,7 @@
     explicit OggExtractor(const sp<DataSource> &source);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
@@ -59,9 +59,6 @@
         const sp<DataSource> &source, String8 *mimeType, float *confidence,
         sp<AMessage> *);
 
-void parseVorbisComment(
-        const sp<MetaData> &fileMeta, const char *comment, size_t commentLength);
-
 }  // namespace android
 
 #endif  // OGG_EXTRACTOR_H_
diff --git a/media/extractors/wav/Android.bp b/media/extractors/wav/Android.bp
new file mode 100644
index 0000000..ead02a9
--- /dev/null
+++ b/media/extractors/wav/Android.bp
@@ -0,0 +1,43 @@
+cc_library_shared {
+
+    srcs: ["WAVExtractor.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/include",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libmedia",
+        "libstagefright_foundation",
+        "libutils",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libfifo",
+    ],
+
+    name: "libwavextractor",
+    relative_install_path: "extractors",
+
+    compile_multilib: "first",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-fvisibility=hidden",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        diag: {
+            cfi: true,
+        },
+    },
+
+}
diff --git a/media/libstagefright/matroska/MODULE_LICENSE_APACHE2 b/media/extractors/wav/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/matroska/MODULE_LICENSE_APACHE2
copy to media/extractors/wav/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/matroska/NOTICE b/media/extractors/wav/NOTICE
similarity index 100%
copy from media/libstagefright/matroska/NOTICE
copy to media/extractors/wav/NOTICE
diff --git a/media/libstagefright/WAVExtractor.cpp b/media/extractors/wav/WAVExtractor.cpp
similarity index 95%
rename from media/libstagefright/WAVExtractor.cpp
rename to media/extractors/wav/WAVExtractor.cpp
index 780b746..cce488b 100644
--- a/media/libstagefright/WAVExtractor.cpp
+++ b/media/extractors/wav/WAVExtractor.cpp
@@ -18,7 +18,7 @@
 #define LOG_TAG "WAVExtractor"
 #include <utils/Log.h>
 
-#include "include/WAVExtractor.h"
+#include "WAVExtractor.h"
 
 #include <audio_utils/primitives.h>
 #include <media/stagefright/foundation/ADebug.h>
@@ -120,7 +120,7 @@
     return mInitCheck == OK ? 1 : 0;
 }
 
-sp<IMediaSource> WAVExtractor::getTrack(size_t index) {
+sp<MediaSource> WAVExtractor::getTrack(size_t index) {
     if (mInitCheck != OK || index > 0) {
         return NULL;
     }
@@ -544,27 +544,50 @@
 
 ////////////////////////////////////////////////////////////////////////////////
 
-bool SniffWAV(
-        const sp<DataSource> &source, String8 *mimeType, float *confidence,
+static MediaExtractor* CreateExtractor(
+        const sp<DataSource> &source,
+        const sp<AMessage>& meta __unused) {
+    return new WAVExtractor(source);
+}
+
+static MediaExtractor::CreatorFunc Sniff(
+        const sp<DataSource> &source,
+        String8 *mimeType,
+        float *confidence,
         sp<AMessage> *) {
     char header[12];
     if (source->readAt(0, header, sizeof(header)) < (ssize_t)sizeof(header)) {
-        return false;
+        return NULL;
     }
 
     if (memcmp(header, "RIFF", 4) || memcmp(&header[8], "WAVE", 4)) {
-        return false;
+        return NULL;
     }
 
     sp<MediaExtractor> extractor = new WAVExtractor(source);
     if (extractor->countTracks() == 0) {
-        return false;
+        return NULL;
     }
 
     *mimeType = MEDIA_MIMETYPE_CONTAINER_WAV;
     *confidence = 0.3f;
 
-    return true;
+    return CreateExtractor;
 }
 
-}  // namespace android
+extern "C" {
+// This is the only symbol that needs to be exported
+__attribute__ ((visibility ("default")))
+MediaExtractor::ExtractorDef GETEXTRACTORDEF() {
+    return {
+        MediaExtractor::EXTRACTORDEF_VERSION,
+        UUID("7d613858-5837-4a38-84c5-332d1cddee27"),
+        1, // version
+        "WAV Extractor",
+        Sniff
+    };
+}
+
+} // extern "C"
+
+} // namespace android
diff --git a/media/libstagefright/include/WAVExtractor.h b/media/extractors/wav/WAVExtractor.h
similarity index 90%
rename from media/libstagefright/include/WAVExtractor.h
rename to media/extractors/wav/WAVExtractor.h
index 12ad441..9fe0335 100644
--- a/media/libstagefright/include/WAVExtractor.h
+++ b/media/extractors/wav/WAVExtractor.h
@@ -33,7 +33,7 @@
     explicit WAVExtractor(const sp<DataSource> &source);
 
     virtual size_t countTracks();
-    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MediaSource> getTrack(size_t index);
     virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
 
     virtual sp<MetaData> getMetaData();
@@ -61,10 +61,6 @@
     WAVExtractor &operator=(const WAVExtractor &);
 };
 
-bool SniffWAV(
-        const sp<DataSource> &source, String8 *mimeType, float *confidence,
-        sp<AMessage> *);
-
 }  // namespace android
 
 #endif  // WAV_EXTRACTOR_H_
diff --git a/media/libaaudio/src/Android.mk b/media/libaaudio/src/Android.mk
index 6861248..f7a5f9b 100644
--- a/media/libaaudio/src/Android.mk
+++ b/media/libaaudio/src/Android.mk
@@ -27,6 +27,8 @@
     $(LOCAL_PATH)/legacy \
     $(LOCAL_PATH)/utility
 
+LOCAL_AIDL_INCLUDES := frameworks/av/media/libaudioclient/aidl
+
 # If you add a file here then also add it below in the SHARED target
 LOCAL_SRC_FILES = \
     core/AudioStream.cpp \
@@ -56,7 +58,9 @@
     binding/IAAudioService.cpp \
     binding/RingBufferParcelable.cpp \
     binding/SharedMemoryParcelable.cpp \
-    binding/SharedRegionParcelable.cpp
+    binding/SharedRegionParcelable.cpp \
+    ../../libaudioclient/aidl/android/media/IAudioRecord.aidl \
+    ../../libaudioclient/aidl/android/media/IPlayer.aidl
 
 LOCAL_CFLAGS += -Wno-unused-parameter -Wall -Werror
 
diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp
index 61c946c..98e8d95 100644
--- a/media/libaudioclient/Android.bp
+++ b/media/libaudioclient/Android.bp
@@ -6,7 +6,22 @@
 
 cc_library_shared {
     name: "libaudioclient",
+
+    aidl: {
+        export_aidl_headers: true,
+        local_include_dirs: ["aidl"],
+        include_dirs: [
+            "frameworks/av/media/libaudioclient/aidl",
+        ],
+    },
+
     srcs: [
+        // AIDL files for audioclient interfaces
+        // The headers for these interfaces will be available to any modules that
+        // include libaudioclient, at the path "aidl/package/path/BnFoo.h"
+        "aidl/android/media/IAudioRecord.aidl",
+        "aidl/android/media/IPlayer.aidl",
+
         "AudioEffect.cpp",
         "AudioPolicy.cpp",
         "AudioRecord.cpp",
@@ -17,7 +32,6 @@
         "IAudioFlingerClient.cpp",
         "IAudioPolicyService.cpp",
         "IAudioPolicyServiceClient.cpp",
-        "IAudioRecord.cpp",
         "IAudioTrack.cpp",
         "IEffect.cpp",
         "IEffectClient.cpp",
@@ -36,7 +50,7 @@
     ],
     export_shared_lib_headers: ["libbinder"],
 
-    local_include_dirs: ["include/media"],
+    local_include_dirs: ["include/media", "aidl"],
     header_libs: ["libaudioclient_headers"],
     export_header_lib_headers: ["libaudioclient_headers"],
 
diff --git a/media/libaudioclient/AudioRecord.cpp b/media/libaudioclient/AudioRecord.cpp
index ba4acc6..26a320c 100644
--- a/media/libaudioclient/AudioRecord.cpp
+++ b/media/libaudioclient/AudioRecord.cpp
@@ -323,7 +323,7 @@
 
     status_t status = NO_ERROR;
     if (!(flags & CBLK_INVALID)) {
-        status = mAudioRecord->start(event, triggerSession);
+        status = mAudioRecord->start(event, triggerSession).transactionError();
         if (status == DEAD_OBJECT) {
             flags |= CBLK_INVALID;
         }
@@ -656,22 +656,22 @@
 
     sp<IMemory> iMem;           // for cblk
     sp<IMemory> bufferMem;
-    sp<IAudioRecord> record = audioFlinger->openRecord(input,
-                                                       mSampleRate,
-                                                       mFormat,
-                                                       mChannelMask,
-                                                       opPackageName,
-                                                       &temp,
-                                                       &flags,
-                                                       mClientPid,
-                                                       tid,
-                                                       mClientUid,
-                                                       &mSessionId,
-                                                       &notificationFrames,
-                                                       iMem,
-                                                       bufferMem,
-                                                       &status,
-                                                       mPortId);
+    sp<media::IAudioRecord> record = audioFlinger->openRecord(input,
+                                                              mSampleRate,
+                                                              mFormat,
+                                                              mChannelMask,
+                                                              opPackageName,
+                                                              &temp,
+                                                              &flags,
+                                                              mClientPid,
+                                                              tid,
+                                                              mClientUid,
+                                                              &mSessionId,
+                                                              &notificationFrames,
+                                                              iMem,
+                                                              bufferMem,
+                                                              &status,
+                                                              mPortId);
     ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
             "session ID changed from %d to %d", originalSessionId, mSessionId);
 
@@ -1228,7 +1228,8 @@
         if (mActive) {
             // callback thread or sync event hasn't changed
             // FIXME this fails if we have a new AudioFlinger instance
-            result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, AUDIO_SESSION_NONE);
+            result = mAudioRecord->start(
+                AudioSystem::SYNC_EVENT_SAME, AUDIO_SESSION_NONE).transactionError();
         }
         mFramesReadServerOffset = mFramesRead; // server resets to zero so we need an offset.
     }
diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp
index 3529d2c..6206be0 100644
--- a/media/libaudioclient/AudioTrack.cpp
+++ b/media/libaudioclient/AudioTrack.cpp
@@ -39,6 +39,8 @@
 namespace android {
 // ---------------------------------------------------------------------------
 
+using media::VolumeShaper;
+
 // TODO: Move to a separate .h
 
 template <typename T>
@@ -562,7 +564,7 @@
     mFramesWritten = 0;
     mFramesWrittenServerOffset = 0;
     mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
-    mVolumeHandler = new VolumeHandler();
+    mVolumeHandler = new media::VolumeHandler();
     return NO_ERROR;
 }
 
diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp
index 14feada..fc8c11a 100644
--- a/media/libaudioclient/IAudioFlinger.cpp
+++ b/media/libaudioclient/IAudioFlinger.cpp
@@ -175,7 +175,7 @@
         return track;
     }
 
-    virtual sp<IAudioRecord> openRecord(
+    virtual sp<media::IAudioRecord> openRecord(
                                 audio_io_handle_t input,
                                 uint32_t sampleRate,
                                 audio_format_t format,
@@ -194,7 +194,7 @@
                                 audio_port_handle_t portId)
     {
         Parcel data, reply;
-        sp<IAudioRecord> record;
+        sp<media::IAudioRecord> record;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
         data.writeInt32((int32_t) input);
         data.writeInt32(sampleRate);
@@ -238,7 +238,7 @@
                 *notificationFrames = lNotificationFrames;
             }
             lStatus = reply.readInt32();
-            record = interface_cast<IAudioRecord>(reply.readStrongBinder());
+            record = interface_cast<media::IAudioRecord>(reply.readStrongBinder());
             cblk = interface_cast<IMemory>(reply.readStrongBinder());
             if (cblk != 0 && cblk->pointer() == NULL) {
                 cblk.clear();
@@ -1025,7 +1025,7 @@
             sp<IMemory> cblk;
             sp<IMemory> buffers;
             status_t status = NO_ERROR;
-            sp<IAudioRecord> record = openRecord(input,
+            sp<media::IAudioRecord> record = openRecord(input,
                     sampleRate, format, channelMask, opPackageName, &frameCount, &flags,
                     pid, tid, clientUid, &sessionId, &notificationFrames, cblk, buffers,
                     &status, portId);
diff --git a/media/libaudioclient/IAudioRecord.cpp b/media/libaudioclient/IAudioRecord.cpp
deleted file mode 100644
index 1331c0d..0000000
--- a/media/libaudioclient/IAudioRecord.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
-**
-** Copyright 2007, 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 "IAudioRecord"
-//#define LOG_NDEBUG 0
-#include <utils/Log.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <binder/Parcel.h>
-
-#include <media/IAudioRecord.h>
-
-namespace android {
-
-enum {
-    UNUSED_WAS_GET_CBLK = IBinder::FIRST_CALL_TRANSACTION,
-    START,
-    STOP
-};
-
-class BpAudioRecord : public BpInterface<IAudioRecord>
-{
-public:
-    explicit BpAudioRecord(const sp<IBinder>& impl)
-        : BpInterface<IAudioRecord>(impl)
-    {
-    }
-
-    virtual status_t start(int /*AudioSystem::sync_event_t*/ event, audio_session_t triggerSession)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioRecord::getInterfaceDescriptor());
-        data.writeInt32(event);
-        data.writeInt32(triggerSession);
-        status_t status = remote()->transact(START, data, &reply);
-        if (status == NO_ERROR) {
-            status = reply.readInt32();
-        } else {
-            ALOGW("start() error: %s", strerror(-status));
-        }
-        return status;
-    }
-
-    virtual void stop()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioRecord::getInterfaceDescriptor());
-        remote()->transact(STOP, data, &reply);
-    }
-
-};
-
-IMPLEMENT_META_INTERFACE(AudioRecord, "android.media.IAudioRecord");
-
-// ----------------------------------------------------------------------
-
-status_t BnAudioRecord::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-        case START: {
-            CHECK_INTERFACE(IAudioRecord, data, reply);
-            int /*AudioSystem::sync_event_t*/ event = data.readInt32();
-            audio_session_t triggerSession = (audio_session_t) data.readInt32();
-            reply->writeInt32(start(event, triggerSession));
-            return NO_ERROR;
-        } break;
-        case STOP: {
-            CHECK_INTERFACE(IAudioRecord, data, reply);
-            stop();
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-} // namespace android
diff --git a/media/libaudioclient/IAudioTrack.cpp b/media/libaudioclient/IAudioTrack.cpp
index 79e864d..adff057 100644
--- a/media/libaudioclient/IAudioTrack.cpp
+++ b/media/libaudioclient/IAudioTrack.cpp
@@ -28,6 +28,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 enum {
     GET_CBLK = IBinder::FIRST_CALL_TRANSACTION,
     START,
@@ -185,7 +187,7 @@
             return nullptr;
         }
         sp<VolumeShaper::State> state = new VolumeShaper::State;
-        status = state->readFromParcel(reply);
+        status = state->readFromParcel(&reply);
         if (status != NO_ERROR) {
             return nullptr;
         }
@@ -263,12 +265,12 @@
             status_t status = data.readInt32(&present);
             if (status == NO_ERROR && present != 0) {
                 configuration = new VolumeShaper::Configuration();
-                status = configuration->readFromParcel(data);
+                status = configuration->readFromParcel(&data);
             }
             status = status ?: data.readInt32(&present);
             if (status == NO_ERROR && present != 0) {
                 operation = new VolumeShaper::Operation();
-                status = operation->readFromParcel(data);
+                status = operation->readFromParcel(&data);
             }
             if (status == NO_ERROR) {
                 status = (status_t)applyVolumeShaper(configuration, operation);
diff --git a/media/libaudioclient/PlayerBase.cpp b/media/libaudioclient/PlayerBase.cpp
index 7868318..b0c68e5 100644
--- a/media/libaudioclient/PlayerBase.cpp
+++ b/media/libaudioclient/PlayerBase.cpp
@@ -22,6 +22,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 //--------------------------------------------------------------------------------------------------
 PlayerBase::PlayerBase() : BnPlayer(),
         mPanMultiplierL(1.0f), mPanMultiplierR(1.0f),
@@ -117,23 +119,26 @@
 
 //------------------------------------------------------------------------------
 // Implementation of IPlayer
-void PlayerBase::start() {
+binder::Status PlayerBase::start() {
     ALOGD("PlayerBase::start() from IPlayer");
     (void)startWithStatus();
+    return binder::Status::ok();
 }
 
-void PlayerBase::pause() {
+binder::Status PlayerBase::pause() {
     ALOGD("PlayerBase::pause() from IPlayer");
     (void)pauseWithStatus();
+    return binder::Status::ok();
 }
 
 
-void PlayerBase::stop() {
+binder::Status PlayerBase::stop() {
     ALOGD("PlayerBase::stop() from IPlayer");
     (void)stopWithStatus();
+    return binder::Status::ok();
 }
 
-void PlayerBase::setVolume(float vol) {
+binder::Status PlayerBase::setVolume(float vol) {
     ALOGD("PlayerBase::setVolume() from IPlayer");
     {
         Mutex::Autolock _l(mSettingsLock);
@@ -144,9 +149,10 @@
     if (status != NO_ERROR) {
         ALOGW("PlayerBase::setVolume() error %d", status);
     }
+    return binder::Status::fromStatusT(status);
 }
 
-void PlayerBase::setPan(float pan) {
+binder::Status PlayerBase::setPan(float pan) {
     ALOGD("PlayerBase::setPan() from IPlayer");
     {
         Mutex::Autolock _l(mSettingsLock);
@@ -163,22 +169,19 @@
     if (status != NO_ERROR) {
         ALOGW("PlayerBase::setPan() error %d", status);
     }
+    return binder::Status::fromStatusT(status);
 }
 
-void PlayerBase::setStartDelayMs(int32_t delayMs __unused) {
+binder::Status PlayerBase::setStartDelayMs(int32_t delayMs __unused) {
     ALOGW("setStartDelay() is not supported");
+    return binder::Status::ok();
 }
 
-void PlayerBase::applyVolumeShaper(
-        const sp<VolumeShaper::Configuration>& configuration  __unused,
-        const sp<VolumeShaper::Operation>& operation __unused) {
+binder::Status PlayerBase::applyVolumeShaper(
+            const VolumeShaper::Configuration& configuration __unused,
+            const VolumeShaper::Operation& operation __unused) {
     ALOGW("applyVolumeShaper() is not supported");
-}
-
-status_t PlayerBase::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    return BnPlayer::onTransact(code, data, reply, flags);
+    return binder::Status::ok();
 }
 
 } // namespace android
diff --git a/media/libaudioclient/TrackPlayerBase.cpp b/media/libaudioclient/TrackPlayerBase.cpp
index 48cd803..0a914fc 100644
--- a/media/libaudioclient/TrackPlayerBase.cpp
+++ b/media/libaudioclient/TrackPlayerBase.cpp
@@ -18,6 +18,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 //--------------------------------------------------------------------------------------------------
 TrackPlayerBase::TrackPlayerBase() : PlayerBase(),
         mPlayerVolumeL(1.0f), mPlayerVolumeR(1.0f)
@@ -103,18 +105,24 @@
 }
 
 
-void TrackPlayerBase::applyVolumeShaper(
-        const sp<VolumeShaper::Configuration>& configuration,
-        const sp<VolumeShaper::Operation>& operation) {
+binder::Status TrackPlayerBase::applyVolumeShaper(
+        const VolumeShaper::Configuration& configuration,
+        const VolumeShaper::Operation& operation) {
+
+    sp<VolumeShaper::Configuration> spConfiguration = new VolumeShaper::Configuration(configuration);
+    sp<VolumeShaper::Operation> spOperation = new VolumeShaper::Operation(operation);
+
     if (mAudioTrack != 0) {
         ALOGD("TrackPlayerBase::applyVolumeShaper() from IPlayer");
-        VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(configuration, operation);
+        VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(spConfiguration, spOperation);
         if (status < 0) { // a non-negative value is the volume shaper id.
             ALOGE("TrackPlayerBase::applyVolumeShaper() failed with status %d", status);
         }
+        return binder::Status::fromStatusT(status);
     } else {
         ALOGD("TrackPlayerBase::applyVolumeShaper()"
-                " no AudioTrack for volume control from IPlayer");
+              " no AudioTrack for volume control from IPlayer");
+        return binder::Status::ok();
     }
 }
 
diff --git a/media/libaudioclient/aidl/android/media/IAudioRecord.aidl b/media/libaudioclient/aidl/android/media/IAudioRecord.aidl
new file mode 100644
index 0000000..50ce78f
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/IAudioRecord.aidl
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2016 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.
+ */
+
+package android.media;
+
+interface IAudioRecord {
+
+  /* After it's created the track is not active. Call start() to
+   * make it active.
+   */
+  void start(int /*AudioSystem::sync_event_t*/ event,
+             int /*audio_session_t*/ triggerSession);
+
+  /* Stop a track. If set, the callback will cease being called and
+   * obtainBuffer will return an error. Buffers that are already released
+   * will be processed, unless flush() is called.
+   */
+  void stop();
+}
diff --git a/media/libaudioclient/aidl/android/media/IPlayer.aidl b/media/libaudioclient/aidl/android/media/IPlayer.aidl
new file mode 100644
index 0000000..a90fcdd
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/IPlayer.aidl
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+package android.media;
+
+import android.media.VolumeShaper.Configuration;
+import android.media.VolumeShaper.Operation;
+
+/**
+ * @hide
+ */
+interface IPlayer {
+    oneway void start();
+    oneway void pause();
+    oneway void stop();
+    oneway void setVolume(float vol);
+    oneway void setPan(float pan);
+    oneway void setStartDelayMs(int delayMs);
+    oneway void applyVolumeShaper(in Configuration configuration,
+                                  in Operation operation);
+}
diff --git a/media/libaudioclient/aidl/android/media/VolumeShaper/Configuration.aidl b/media/libaudioclient/aidl/android/media/VolumeShaper/Configuration.aidl
new file mode 100644
index 0000000..fd0e60f
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/VolumeShaper/Configuration.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.media.VolumeShaper;
+
+parcelable Configuration cpp_header "media/VolumeShaper.h";
diff --git a/media/libaudioclient/aidl/android/media/VolumeShaper/Operation.aidl b/media/libaudioclient/aidl/android/media/VolumeShaper/Operation.aidl
new file mode 100644
index 0000000..4290d9d
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/VolumeShaper/Operation.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.media.VolumeShaper;
+
+parcelable Operation cpp_header "media/VolumeShaper.h";
diff --git a/media/libaudioclient/aidl/android/media/VolumeShaper/State.aidl b/media/libaudioclient/aidl/android/media/VolumeShaper/State.aidl
new file mode 100644
index 0000000..f6a22b8
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/VolumeShaper/State.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.media.VolumeShaper;
+
+parcelable State cpp_header "media/VolumeShaper.h";
diff --git a/media/libaudioclient/include/media/AudioMixer.h b/media/libaudioclient/include/media/AudioMixer.h
index 2bd2d01..dcd4a5d 100644
--- a/media/libaudioclient/include/media/AudioMixer.h
+++ b/media/libaudioclient/include/media/AudioMixer.h
@@ -25,7 +25,7 @@
 #include <media/AudioResampler.h>
 #include <media/AudioResamplerPublic.h>
 #include <media/BufferProviders.h>
-#include <media/nbaio/NBLog.h>
+#include <media/nblog/NBLog.h>
 #include <system/audio.h>
 #include <utils/Compat.h>
 #include <utils/threads.h>
diff --git a/media/libaudioclient/include/media/AudioRecord.h b/media/libaudioclient/include/media/AudioRecord.h
index dd72170..c6ad1b5 100644
--- a/media/libaudioclient/include/media/AudioRecord.h
+++ b/media/libaudioclient/include/media/AudioRecord.h
@@ -17,13 +17,16 @@
 #ifndef ANDROID_AUDIORECORD_H
 #define ANDROID_AUDIORECORD_H
 
+#include <binder/IMemory.h>
 #include <cutils/sched_policy.h>
 #include <media/AudioSystem.h>
 #include <media/AudioTimestamp.h>
-#include <media/IAudioRecord.h>
 #include <media/Modulo.h>
+#include <utils/RefBase.h>
 #include <utils/threads.h>
 
+#include "android/media/IAudioRecord.h"
+
 namespace android {
 
 // ----------------------------------------------------------------------------
@@ -635,7 +638,7 @@
 
     // Next 5 fields may be changed if IAudioRecord is re-created, but always != 0
     // provided the initial set() was successful
-    sp<IAudioRecord>        mAudioRecord;
+    sp<media::IAudioRecord> mAudioRecord;
     sp<IMemory>             mCblkMemory;
     audio_track_cblk_t*     mCblk;              // re-load after mLock.unlock()
     sp<IMemory>             mBufferMemory;
diff --git a/media/libaudioclient/include/media/AudioTrack.h b/media/libaudioclient/include/media/AudioTrack.h
index 47d87e9..2adacd7 100644
--- a/media/libaudioclient/include/media/AudioTrack.h
+++ b/media/libaudioclient/include/media/AudioTrack.h
@@ -748,12 +748,12 @@
             status_t    setParameters(const String8& keyValuePairs);
 
     /* Sets the volume shaper object */
-            VolumeShaper::Status applyVolumeShaper(
-                    const sp<VolumeShaper::Configuration>& configuration,
-                    const sp<VolumeShaper::Operation>& operation);
+            media::VolumeShaper::Status applyVolumeShaper(
+                    const sp<media::VolumeShaper::Configuration>& configuration,
+                    const sp<media::VolumeShaper::Operation>& operation);
 
     /* Gets the volume shaper state */
-            sp<VolumeShaper::State> getVolumeShaperState(int id);
+            sp<media::VolumeShaper::State> getVolumeShaperState(int id);
 
     /* Get parameters */
             String8     getParameters(const String8& keys);
@@ -1160,7 +1160,7 @@
                                               // May not match the app selection depending on other
                                               // activity and connected devices.
 
-    sp<VolumeHandler>       mVolumeHandler;
+    sp<media::VolumeHandler>       mVolumeHandler;
 
 private:
     class DeathNotifier : public IBinder::DeathRecipient {
diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h
index 0ad4231..133d6c9 100644
--- a/media/libaudioclient/include/media/IAudioFlinger.h
+++ b/media/libaudioclient/include/media/IAudioFlinger.h
@@ -25,7 +25,6 @@
 #include <utils/Errors.h>
 #include <binder/IInterface.h>
 #include <media/IAudioTrack.h>
-#include <media/IAudioRecord.h>
 #include <media/IAudioFlingerClient.h>
 #include <system/audio.h>
 #include <system/audio_effect.h>
@@ -34,6 +33,8 @@
 #include <media/IEffectClient.h>
 #include <utils/String8.h>
 
+#include "android/media/IAudioRecord.h"
+
 namespace android {
 
 // ----------------------------------------------------------------------------
@@ -69,7 +70,7 @@
                                 status_t *status,
                                 audio_port_handle_t portId) = 0;
 
-    virtual sp<IAudioRecord> openRecord(
+    virtual sp<media::IAudioRecord> openRecord(
                                 // On successful return, AudioFlinger takes over the handle
                                 // reference and will release it when the track is destroyed.
                                 // However on failure, the client is responsible for release.
diff --git a/media/libaudioclient/include/media/IAudioRecord.h b/media/libaudioclient/include/media/IAudioRecord.h
deleted file mode 100644
index 7768176..0000000
--- a/media/libaudioclient/include/media/IAudioRecord.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2007 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 IAUDIORECORD_H_
-#define IAUDIORECORD_H_
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/RefBase.h>
-#include <utils/Errors.h>
-#include <binder/IInterface.h>
-#include <binder/IMemory.h>
-#include <system/audio.h>
-
-namespace android {
-
-// ----------------------------------------------------------------------------
-
-class IAudioRecord : public IInterface
-{
-public:
-    DECLARE_META_INTERFACE(AudioRecord);
-
-    /* After it's created the track is not active. Call start() to
-     * make it active.
-     */
-    virtual status_t    start(int /*AudioSystem::sync_event_t*/ event,
-                              audio_session_t triggerSession) = 0;
-
-    /* Stop a track. If set, the callback will cease being called and
-     * obtainBuffer will return an error. Buffers that are already released
-     * will be processed, unless flush() is called.
-     */
-    virtual void        stop() = 0;
-};
-
-// ----------------------------------------------------------------------------
-
-class BnAudioRecord : public BnInterface<IAudioRecord>
-{
-public:
-    virtual status_t    onTransact( uint32_t code,
-                                    const Parcel& data,
-                                    Parcel* reply,
-                                    uint32_t flags = 0);
-};
-
-// ----------------------------------------------------------------------------
-
-}; // namespace android
-
-#endif /*IAUDIORECORD_H_*/
diff --git a/media/libaudioclient/include/media/IAudioTrack.h b/media/libaudioclient/include/media/IAudioTrack.h
index 27a62d6..94afe3c 100644
--- a/media/libaudioclient/include/media/IAudioTrack.h
+++ b/media/libaudioclient/include/media/IAudioTrack.h
@@ -77,12 +77,12 @@
     virtual void        signal() = 0;
 
     /* Sets the volume shaper */
-    virtual VolumeShaper::Status applyVolumeShaper(
-            const sp<VolumeShaper::Configuration>& configuration,
-            const sp<VolumeShaper::Operation>& operation) = 0;
+    virtual media::VolumeShaper::Status applyVolumeShaper(
+            const sp<media::VolumeShaper::Configuration>& configuration,
+            const sp<media::VolumeShaper::Operation>& operation) = 0;
 
     /* gets the volume shaper state */
-    virtual sp<VolumeShaper::State> getVolumeShaperState(int id) = 0;
+    virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/media/libaudioclient/include/media/PlayerBase.h b/media/libaudioclient/include/media/PlayerBase.h
index e63090b..e7a8abc 100644
--- a/media/libaudioclient/include/media/PlayerBase.h
+++ b/media/libaudioclient/include/media/PlayerBase.h
@@ -17,35 +17,31 @@
 #ifndef __ANDROID_PLAYER_BASE_H__
 #define __ANDROID_PLAYER_BASE_H__
 
-#include <audiomanager/IPlayer.h>
 #include <audiomanager/AudioManager.h>
 #include <audiomanager/IAudioManager.h>
 
+#include "android/media/BnPlayer.h"
 
 namespace android {
 
-class PlayerBase : public BnPlayer
+class PlayerBase : public ::android::media::BnPlayer
 {
 public:
     explicit PlayerBase();
-    virtual ~PlayerBase();
+    virtual ~PlayerBase() override;
 
     virtual void destroy() = 0;
 
     //IPlayer implementation
-    virtual void start();
-    virtual void pause();
-    virtual void stop();
-    virtual void setVolume(float vol);
-    virtual void setPan(float pan);
-    virtual void setStartDelayMs(int32_t delayMs);
-    virtual void applyVolumeShaper(
-            const sp<VolumeShaper::Configuration>& configuration,
-            const sp<VolumeShaper::Operation>& operation) override;
-
-    virtual status_t onTransact(
-                uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
-
+    virtual binder::Status start() override;
+    virtual binder::Status pause() override;
+    virtual binder::Status stop() override;
+    virtual binder::Status setVolume(float vol) override;
+    virtual binder::Status setPan(float pan) override;
+    virtual binder::Status setStartDelayMs(int32_t delayMs) override;
+    virtual binder::Status applyVolumeShaper(
+            const media::VolumeShaper::Configuration& configuration,
+            const media::VolumeShaper::Operation& operation) override;
 
             status_t startWithStatus();
             status_t pauseWithStatus();
diff --git a/media/libaudioclient/include/media/TrackPlayerBase.h b/media/libaudioclient/include/media/TrackPlayerBase.h
index 2d113c0..66e9b3b 100644
--- a/media/libaudioclient/include/media/TrackPlayerBase.h
+++ b/media/libaudioclient/include/media/TrackPlayerBase.h
@@ -32,9 +32,9 @@
     virtual void destroy();
 
     //IPlayer implementation
-    virtual void applyVolumeShaper(
-            const sp<VolumeShaper::Configuration>& configuration,
-            const sp<VolumeShaper::Operation>& operation);
+    virtual binder::Status applyVolumeShaper(
+            const media::VolumeShaper::Configuration& configuration,
+            const media::VolumeShaper::Operation& operation);
 
     //FIXME move to protected field, so far made public to minimize changes to AudioTrack logic
     sp<AudioTrack> mAudioTrack;
diff --git a/media/libaudioprocessing/Android.mk b/media/libaudioprocessing/Android.mk
index c850984..da1ecc2 100644
--- a/media/libaudioprocessing/Android.mk
+++ b/media/libaudioprocessing/Android.mk
@@ -24,6 +24,7 @@
     libcutils \
     liblog \
     libnbaio \
+    libnblog \
     libsonic \
     libutils \
 
diff --git a/media/libaudioprocessing/OWNERS b/media/libaudioprocessing/OWNERS
new file mode 100644
index 0000000..96d0ea0
--- /dev/null
+++ b/media/libaudioprocessing/OWNERS
@@ -0,0 +1,3 @@
+gkasten@google.com
+hunga@google.com
+rago@google.com
diff --git a/media/libcpustats/OWNERS b/media/libcpustats/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/media/libcpustats/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/media/libeffects/OWNERS b/media/libeffects/OWNERS
index 7e3de13..7f9ae81 100644
--- a/media/libeffects/OWNERS
+++ b/media/libeffects/OWNERS
@@ -1,3 +1,4 @@
+hunga@google.com
 krocard@google.com
 mnaganov@google.com
 rago@google.com
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h b/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
index f32ed30..4ecaf14 100644
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
@@ -534,246 +534,246 @@
 
  /* Coefficients for centre frequency 55Hz */
 #define HPF_Fs8000_Fc55_A0                        0.958849f
-#define HPF_Fs8000_Fc55_A1                        -1.917698f
+#define HPF_Fs8000_Fc55_A1                        (-1.917698f)
 #define HPF_Fs8000_Fc55_A2                        0.958849f
-#define HPF_Fs8000_Fc55_B1                        -1.939001f
+#define HPF_Fs8000_Fc55_B1                        (-1.939001f)
 #define HPF_Fs8000_Fc55_B2                        0.940807f
 #define HPF_Fs11025_Fc55_A0                       0.966909f
-#define HPF_Fs11025_Fc55_A1                       -1.933818f
+#define HPF_Fs11025_Fc55_A1                       (-1.933818f)
 #define HPF_Fs11025_Fc55_A2                       0.966909f
-#define HPF_Fs11025_Fc55_B1                       -1.955732f
+#define HPF_Fs11025_Fc55_B1                       (-1.955732f)
 #define HPF_Fs11025_Fc55_B2                       0.956690f
 #define HPF_Fs12000_Fc55_A0                       0.968650f
-#define HPF_Fs12000_Fc55_A1                       -1.937300f
+#define HPF_Fs12000_Fc55_A1                       (-1.937300f)
 #define HPF_Fs12000_Fc55_A2                       0.968650f
-#define HPF_Fs12000_Fc55_B1                       -1.959327f
+#define HPF_Fs12000_Fc55_B1                       (-1.959327f)
 #define HPF_Fs12000_Fc55_B2                       0.960138f
 #define HPF_Fs16000_Fc55_A0                       0.973588f
-#define HPF_Fs16000_Fc55_A1                       -1.947176f
+#define HPF_Fs16000_Fc55_A1                       (-1.947176f)
 #define HPF_Fs16000_Fc55_A2                       0.973588f
-#define HPF_Fs16000_Fc55_B1                       -1.969494f
+#define HPF_Fs16000_Fc55_B1                       (-1.969494f)
 #define HPF_Fs16000_Fc55_B2                       0.969952f
 #define HPF_Fs22050_Fc55_A0                       0.977671f
-#define HPF_Fs22050_Fc55_A1                       -1.955343f
+#define HPF_Fs22050_Fc55_A1                       (-1.955343f)
 #define HPF_Fs22050_Fc55_A2                       0.977671f
-#define HPF_Fs22050_Fc55_B1                       -1.977863f
+#define HPF_Fs22050_Fc55_B1                       (-1.977863f)
 #define HPF_Fs22050_Fc55_B2                       0.978105f
 #define HPF_Fs24000_Fc55_A0                       0.978551f
-#define HPF_Fs24000_Fc55_A1                       -1.957102f
+#define HPF_Fs24000_Fc55_A1                       (-1.957102f)
 #define HPF_Fs24000_Fc55_A2                       0.978551f
-#define HPF_Fs24000_Fc55_B1                       -1.979662f
+#define HPF_Fs24000_Fc55_B1                       (-1.979662f)
 #define HPF_Fs24000_Fc55_B2                       0.979866f
 #define HPF_Fs32000_Fc55_A0                       0.981042f
-#define HPF_Fs32000_Fc55_A1                       -1.962084f
+#define HPF_Fs32000_Fc55_A1                       (-1.962084f)
 #define HPF_Fs32000_Fc55_A2                       0.981042f
-#define HPF_Fs32000_Fc55_B1                       -1.984746f
+#define HPF_Fs32000_Fc55_B1                       (-1.984746f)
 #define HPF_Fs32000_Fc55_B2                       0.984861f
 #define HPF_Fs44100_Fc55_A0                       0.983097f
-#define HPF_Fs44100_Fc55_A1                       -1.966194f
+#define HPF_Fs44100_Fc55_A1                       (-1.966194f)
 #define HPF_Fs44100_Fc55_A2                       0.983097f
-#define HPF_Fs44100_Fc55_B1                       -1.988931f
+#define HPF_Fs44100_Fc55_B1                       (-1.988931f)
 #define HPF_Fs44100_Fc55_B2                       0.988992f
 #define HPF_Fs48000_Fc55_A0                       0.983539f
-#define HPF_Fs48000_Fc55_A1                       -1.967079f
+#define HPF_Fs48000_Fc55_A1                       (-1.967079f)
 #define HPF_Fs48000_Fc55_A2                       0.983539f
-#define HPF_Fs48000_Fc55_B1                       -1.989831f
+#define HPF_Fs48000_Fc55_B1                       (-1.989831f)
 #define HPF_Fs48000_Fc55_B2                       0.989882f
 
 #ifdef HIGHER_FS
 #define HPF_Fs96000_Fc55_A0                       0.986040f
-#define HPF_Fs96000_Fc55_A1                       -1.972080f
+#define HPF_Fs96000_Fc55_A1                       (-1.972080f)
 #define HPF_Fs96000_Fc55_A2                       0.986040f
-#define HPF_Fs96000_Fc55_B1                       -1.994915f
+#define HPF_Fs96000_Fc55_B1                       (-1.994915f)
 #define HPF_Fs96000_Fc55_B2                       0.994928f
 
 #define HPF_Fs192000_Fc55_A0                      0.987294f
-#define HPF_Fs192000_Fc55_A1                      -1.974588f
+#define HPF_Fs192000_Fc55_A1                      (-1.974588f)
 #define HPF_Fs192000_Fc55_A2                      0.987294f
-#define HPF_Fs192000_Fc55_B1                      -1.997458f
+#define HPF_Fs192000_Fc55_B1                      (-1.997458f)
 #define HPF_Fs192000_Fc55_B2                      0.997461f
 #endif
 
 
  /* Coefficients for centre frequency 66Hz */
 #define HPF_Fs8000_Fc66_A0                        0.953016f
-#define HPF_Fs8000_Fc66_A1                        -1.906032f
+#define HPF_Fs8000_Fc66_A1                        (-1.906032f)
 #define HPF_Fs8000_Fc66_A2                        0.953016f
-#define HPF_Fs8000_Fc66_B1                        -1.926810f
+#define HPF_Fs8000_Fc66_B1                        (-1.926810f)
 #define HPF_Fs8000_Fc66_B2                        0.929396f
 #define HPF_Fs11025_Fc66_A0                       0.962638f
-#define HPF_Fs11025_Fc66_A1                       -1.925275f
+#define HPF_Fs11025_Fc66_A1                       (-1.925275f)
 #define HPF_Fs11025_Fc66_A2                       0.962638f
-#define HPF_Fs11025_Fc66_B1                       -1.946881f
+#define HPF_Fs11025_Fc66_B1                       (-1.946881f)
 #define HPF_Fs11025_Fc66_B2                       0.948256f
 #define HPF_Fs12000_Fc66_A0                       0.964718f
-#define HPF_Fs12000_Fc66_A1                       -1.929435f
+#define HPF_Fs12000_Fc66_A1                       (-1.929435f)
 #define HPF_Fs12000_Fc66_A2                       0.964718f
-#define HPF_Fs12000_Fc66_B1                       -1.951196f
+#define HPF_Fs12000_Fc66_B1                       (-1.951196f)
 #define HPF_Fs12000_Fc66_B2                       0.952359f
 #define HPF_Fs16000_Fc66_A0                       0.970622f
-#define HPF_Fs16000_Fc66_A1                       -1.941244f
+#define HPF_Fs16000_Fc66_A1                       (-1.941244f)
 #define HPF_Fs16000_Fc66_A2                       0.970622f
-#define HPF_Fs16000_Fc66_B1                       -1.963394f
+#define HPF_Fs16000_Fc66_B1                       (-1.963394f)
 #define HPF_Fs16000_Fc66_B2                       0.964052f
 #define HPF_Fs22050_Fc66_A0                       0.975509f
-#define HPF_Fs22050_Fc66_A1                       -1.951019f
+#define HPF_Fs22050_Fc66_A1                       (-1.951019f)
 #define HPF_Fs22050_Fc66_A2                       0.975509f
-#define HPF_Fs22050_Fc66_B1                       -1.973436f
+#define HPF_Fs22050_Fc66_B1                       (-1.973436f)
 #define HPF_Fs22050_Fc66_B2                       0.973784f
 #define HPF_Fs24000_Fc66_A0                       0.976563f
-#define HPF_Fs24000_Fc66_A1                       -1.953125f
+#define HPF_Fs24000_Fc66_A1                       (-1.953125f)
 #define HPF_Fs24000_Fc66_A2                       0.976563f
-#define HPF_Fs24000_Fc66_B1                       -1.975594f
+#define HPF_Fs24000_Fc66_B1                       (-1.975594f)
 #define HPF_Fs24000_Fc66_B2                       0.975889f
 #define HPF_Fs32000_Fc66_A0                       0.979547f
-#define HPF_Fs32000_Fc66_A1                       -1.959093f
+#define HPF_Fs32000_Fc66_A1                       (-1.959093f)
 #define HPF_Fs32000_Fc66_A2                       0.979547f
-#define HPF_Fs32000_Fc66_B1                       -1.981695f
+#define HPF_Fs32000_Fc66_B1                       (-1.981695f)
 #define HPF_Fs32000_Fc66_B2                       0.981861f
 #define HPF_Fs44100_Fc66_A0                       0.982010f
-#define HPF_Fs44100_Fc66_A1                       -1.964019f
+#define HPF_Fs44100_Fc66_A1                       (-1.964019f)
 #define HPF_Fs44100_Fc66_A2                       0.982010f
-#define HPF_Fs44100_Fc66_B1                       -1.986718f
+#define HPF_Fs44100_Fc66_B1                       (-1.986718f)
 #define HPF_Fs44100_Fc66_B2                       0.986805f
 #define HPF_Fs48000_Fc66_A0                       0.982540f
-#define HPF_Fs48000_Fc66_A1                       -1.965079f
+#define HPF_Fs48000_Fc66_A1                       (-1.965079f)
 #define HPF_Fs48000_Fc66_A2                       0.982540f
-#define HPF_Fs48000_Fc66_B1                       -1.987797f
+#define HPF_Fs48000_Fc66_B1                       (-1.987797f)
 #define HPF_Fs48000_Fc66_B2                       0.987871f
 
 #ifdef HIGHER_FS
 #define HPF_Fs96000_Fc66_A0                       0.985539f
-#define HPF_Fs96000_Fc66_A1                       -1.971077f
+#define HPF_Fs96000_Fc66_A1                       (-1.971077f)
 #define HPF_Fs96000_Fc66_A2                       0.985539f
-#define HPF_Fs96000_Fc66_B1                       -1.993898f
+#define HPF_Fs96000_Fc66_B1                       (-1.993898f)
 #define HPF_Fs96000_Fc66_B2                       0.993917f
 
 #define HPF_Fs192000_Fc66_A0                      0.987043f
-#define HPF_Fs192000_Fc66_A1                      -1.974086f
+#define HPF_Fs192000_Fc66_A1                      (-1.974086f)
 #define HPF_Fs192000_Fc66_A2                      0.987043f
-#define HPF_Fs192000_Fc66_B1                      -1.996949f
+#define HPF_Fs192000_Fc66_B1                      (-1.996949f)
 #define HPF_Fs192000_Fc66_B2                      0.996954f
 #endif
 
 /* Coefficients for centre frequency 78Hz */
 #define HPF_Fs8000_Fc78_A0                        0.946693f
-#define HPF_Fs8000_Fc78_A1                        -1.893387f
+#define HPF_Fs8000_Fc78_A1                        (-1.893387f)
 #define HPF_Fs8000_Fc78_A2                        0.946693f
-#define HPF_Fs8000_Fc78_B1                        -1.913517f
+#define HPF_Fs8000_Fc78_B1                        (-1.913517f)
 #define HPF_Fs8000_Fc78_B2                        0.917105f
 #define HPF_Fs11025_Fc78_A0                       0.957999f
-#define HPF_Fs11025_Fc78_A1                       -1.915998f
+#define HPF_Fs11025_Fc78_A1                       (-1.915998f)
 #define HPF_Fs11025_Fc78_A2                       0.957999f
-#define HPF_Fs11025_Fc78_B1                       -1.937229f
+#define HPF_Fs11025_Fc78_B1                       (-1.937229f)
 #define HPF_Fs11025_Fc78_B2                       0.939140f
 #define HPF_Fs12000_Fc78_A0                       0.960446f
-#define HPF_Fs12000_Fc78_A1                       -1.920892f
+#define HPF_Fs12000_Fc78_A1                       (-1.920892f)
 #define HPF_Fs12000_Fc78_A2                       0.960446f
-#define HPF_Fs12000_Fc78_B1                       -1.942326f
+#define HPF_Fs12000_Fc78_B1                       (-1.942326f)
 #define HPF_Fs12000_Fc78_B2                       0.943944f
 #define HPF_Fs16000_Fc78_A0                       0.967397f
-#define HPF_Fs16000_Fc78_A1                       -1.934794f
+#define HPF_Fs16000_Fc78_A1                       (-1.934794f)
 #define HPF_Fs16000_Fc78_A2                       0.967397f
-#define HPF_Fs16000_Fc78_B1                       -1.956740f
+#define HPF_Fs16000_Fc78_B1                       (-1.956740f)
 #define HPF_Fs16000_Fc78_B2                       0.957656f
 #define HPF_Fs22050_Fc78_A0                       0.973156f
-#define HPF_Fs22050_Fc78_A1                       -1.946313f
+#define HPF_Fs22050_Fc78_A1                       (-1.946313f)
 #define HPF_Fs22050_Fc78_A2                       0.973156f
-#define HPF_Fs22050_Fc78_B1                       -1.968607f
+#define HPF_Fs22050_Fc78_B1                       (-1.968607f)
 #define HPF_Fs22050_Fc78_B2                       0.969092f
 #define HPF_Fs24000_Fc78_A0                       0.974398f
-#define HPF_Fs24000_Fc78_A1                       -1.948797f
+#define HPF_Fs24000_Fc78_A1                       (-1.948797f)
 #define HPF_Fs24000_Fc78_A2                       0.974398f
-#define HPF_Fs24000_Fc78_B1                       -1.971157f
+#define HPF_Fs24000_Fc78_B1                       (-1.971157f)
 #define HPF_Fs24000_Fc78_B2                       0.971568f
 #define HPF_Fs32000_Fc78_A0                       0.977918f
-#define HPF_Fs32000_Fc78_A1                       -1.955836f
+#define HPF_Fs32000_Fc78_A1                       (-1.955836f)
 #define HPF_Fs32000_Fc78_A2                       0.977918f
-#define HPF_Fs32000_Fc78_B1                       -1.978367f
+#define HPF_Fs32000_Fc78_B1                       (-1.978367f)
 #define HPF_Fs32000_Fc78_B2                       0.978599f
 #define HPF_Fs44100_Fc78_A0                       0.980824f
-#define HPF_Fs44100_Fc78_A1                       -1.961649f
+#define HPF_Fs44100_Fc78_A1                       (-1.961649f)
 #define HPF_Fs44100_Fc78_A2                       0.980824f
-#define HPF_Fs44100_Fc78_B1                       -1.984303f
+#define HPF_Fs44100_Fc78_B1                       (-1.984303f)
 #define HPF_Fs44100_Fc78_B2                       0.984425f
 #define HPF_Fs48000_Fc78_A0                       0.981450f
-#define HPF_Fs48000_Fc78_A1                       -1.962900f
+#define HPF_Fs48000_Fc78_A1                       (-1.962900f)
 #define HPF_Fs48000_Fc78_A2                       0.981450f
-#define HPF_Fs48000_Fc78_B1                       -1.985578f
+#define HPF_Fs48000_Fc78_B1                       (-1.985578f)
 #define HPF_Fs48000_Fc78_B2                       0.985681f
 
 #ifdef HIGHER_FS
 #define HPF_Fs96000_Fc78_A0                       0.984992f
-#define HPF_Fs96000_Fc78_A1                       -1.969984f
+#define HPF_Fs96000_Fc78_A1                       (-1.969984f)
 #define HPF_Fs96000_Fc78_A2                       0.984992f
-#define HPF_Fs96000_Fc78_B1                       -1.992789f
+#define HPF_Fs96000_Fc78_B1                       (-1.992789f)
 #define HPF_Fs96000_Fc78_B2                       0.992815f
 
 #define HPF_Fs192000_Fc78_A0                      0.986769f
-#define HPF_Fs192000_Fc78_A1                      -1.973539f
+#define HPF_Fs192000_Fc78_A1                      (-1.973539f)
 #define HPF_Fs192000_Fc78_A2                      0.986769f
-#define HPF_Fs192000_Fc78_B1                      -1.996394f
+#define HPF_Fs192000_Fc78_B1                      (-1.996394f)
 #define HPF_Fs192000_Fc78_B2                      0.996401f
 #endif
 
 /* Coefficients for centre frequency 90Hz */
 #define HPF_Fs8000_Fc90_A0                       0.940412f
-#define HPF_Fs8000_Fc90_A1                       -1.880825f
+#define HPF_Fs8000_Fc90_A1                       (-1.880825f)
 #define HPF_Fs8000_Fc90_A2                       0.940412f
-#define HPF_Fs8000_Fc90_B1                       -1.900231f
+#define HPF_Fs8000_Fc90_B1                       (-1.900231f)
 #define HPF_Fs8000_Fc90_B2                       0.904977f
 #define HPF_Fs11025_Fc90_A0                      0.953383f
-#define HPF_Fs11025_Fc90_A1                      -1.906766f
+#define HPF_Fs11025_Fc90_A1                      (-1.906766f)
 #define HPF_Fs11025_Fc90_A2                      0.953383f
-#define HPF_Fs11025_Fc90_B1                      -1.927579f
+#define HPF_Fs11025_Fc90_B1                      (-1.927579f)
 #define HPF_Fs11025_Fc90_B2                      0.930111f
 #define HPF_Fs12000_Fc90_A0                      0.956193f
-#define HPF_Fs12000_Fc90_A1                      -1.912387f
+#define HPF_Fs12000_Fc90_A1                      (-1.912387f)
 #define HPF_Fs12000_Fc90_A2                      0.956193f
-#define HPF_Fs12000_Fc90_B1                      -1.933459f
+#define HPF_Fs12000_Fc90_B1                      (-1.933459f)
 #define HPF_Fs12000_Fc90_B2                      0.935603f
 #define HPF_Fs16000_Fc90_A0                      0.964183f
-#define HPF_Fs16000_Fc90_A1                      -1.928365f
+#define HPF_Fs16000_Fc90_A1                      (-1.928365f)
 #define HPF_Fs16000_Fc90_A2                      0.964183f
-#define HPF_Fs16000_Fc90_B1                      -1.950087f
+#define HPF_Fs16000_Fc90_B1                      (-1.950087f)
 #define HPF_Fs16000_Fc90_B2                      0.951303f
 #define HPF_Fs22050_Fc90_A0                      0.970809f
-#define HPF_Fs22050_Fc90_A1                      -1.941618f
+#define HPF_Fs22050_Fc90_A1                      (-1.941618f)
 #define HPF_Fs22050_Fc90_A2                      0.970809f
-#define HPF_Fs22050_Fc90_B1                      -1.963778f
+#define HPF_Fs22050_Fc90_B1                      (-1.963778f)
 #define HPF_Fs22050_Fc90_B2                      0.964423f
 #define HPF_Fs24000_Fc90_A0                      0.972239f
-#define HPF_Fs24000_Fc90_A1                      -1.944477f
+#define HPF_Fs24000_Fc90_A1                      (-1.944477f)
 #define HPF_Fs24000_Fc90_A2                      0.972239f
-#define HPF_Fs24000_Fc90_B1                      -1.966721f
+#define HPF_Fs24000_Fc90_B1                      (-1.966721f)
 #define HPF_Fs24000_Fc90_B2                      0.967266f
 #define HPF_Fs32000_Fc90_A0                      0.976292f
-#define HPF_Fs32000_Fc90_A1                      -1.952584f
+#define HPF_Fs32000_Fc90_A1                      (-1.952584f)
 #define HPF_Fs32000_Fc90_A2                      0.976292f
-#define HPF_Fs32000_Fc90_B1                      -1.975040f
+#define HPF_Fs32000_Fc90_B1                      (-1.975040f)
 #define HPF_Fs32000_Fc90_B2                      0.975347f
 #define HPF_Fs44100_Fc90_A0                      0.979641f
-#define HPF_Fs44100_Fc90_A1                      -1.959282f
+#define HPF_Fs44100_Fc90_A1                      (-1.959282f)
 #define HPF_Fs44100_Fc90_A2                      0.979641f
-#define HPF_Fs44100_Fc90_B1                      -1.981888f
+#define HPF_Fs44100_Fc90_B1                      (-1.981888f)
 #define HPF_Fs44100_Fc90_B2                      0.982050f
 #define HPF_Fs48000_Fc90_A0                      0.980362f
-#define HPF_Fs48000_Fc90_A1                      -1.960724f
+#define HPF_Fs48000_Fc90_A1                      (-1.960724f)
 #define HPF_Fs48000_Fc90_A2                      0.980362f
-#define HPF_Fs48000_Fc90_B1                      -1.983359f
+#define HPF_Fs48000_Fc90_B1                      (-1.983359f)
 #define HPF_Fs48000_Fc90_B2                      0.983497f
 
 #ifdef HIGHER_FS
 #define HPF_Fs96000_Fc90_A0                       0.984446f
-#define HPF_Fs96000_Fc90_A1                       -1.968892f
+#define HPF_Fs96000_Fc90_A1                       (-1.968892f)
 #define HPF_Fs96000_Fc90_A2                       0.984446f
-#define HPF_Fs96000_Fc90_B1                       -1.991680f
+#define HPF_Fs96000_Fc90_B1                       (-1.991680f)
 #define HPF_Fs96000_Fc90_B2                       0.991714f
 
 #define HPF_Fs192000_Fc90_A0                      0.986496f
-#define HPF_Fs192000_Fc90_A1                      -1.972992f
+#define HPF_Fs192000_Fc90_A1                      (-1.972992f)
 #define HPF_Fs192000_Fc90_A2                      0.986496f
-#define HPF_Fs192000_Fc90_B1                      -1.995840f
+#define HPF_Fs192000_Fc90_B1                      (-1.995840f)
 #define HPF_Fs192000_Fc90_B2                      0.995848f
 #endif
 
@@ -786,244 +786,244 @@
 /* Coefficients for centre frequency 55Hz */
 #define BPF_Fs8000_Fc55_A0                       0.009197f
 #define BPF_Fs8000_Fc55_A1                       0.000000f
-#define BPF_Fs8000_Fc55_A2                       -0.009197f
-#define BPF_Fs8000_Fc55_B1                       -1.979545f
+#define BPF_Fs8000_Fc55_A2                       (-0.009197f)
+#define BPF_Fs8000_Fc55_B1                       (-1.979545f)
 #define BPF_Fs8000_Fc55_B2                       0.981393f
 #define BPF_Fs11025_Fc55_A0                      0.006691f
 #define BPF_Fs11025_Fc55_A1                      0.000000f
-#define BPF_Fs11025_Fc55_A2                      -0.006691f
-#define BPF_Fs11025_Fc55_B1                      -1.985488f
+#define BPF_Fs11025_Fc55_A2                      (-0.006691f)
+#define BPF_Fs11025_Fc55_B1                      (-1.985488f)
 #define BPF_Fs11025_Fc55_B2                      0.986464f
 #define BPF_Fs12000_Fc55_A0                      0.006150f
 #define BPF_Fs12000_Fc55_A1                      0.000000f
-#define BPF_Fs12000_Fc55_A2                      -0.006150f
-#define BPF_Fs12000_Fc55_B1                      -1.986733f
+#define BPF_Fs12000_Fc55_A2                      (-0.006150f)
+#define BPF_Fs12000_Fc55_B1                      (-1.986733f)
 #define BPF_Fs12000_Fc55_B2                      0.987557f
 #define BPF_Fs16000_Fc55_A0                      0.004620f
 #define BPF_Fs16000_Fc55_A1                      0.000000f
-#define BPF_Fs16000_Fc55_A2                      -0.004620f
-#define BPF_Fs16000_Fc55_B1                      -1.990189f
+#define BPF_Fs16000_Fc55_A2                      (-0.004620f)
+#define BPF_Fs16000_Fc55_B1                      (-1.990189f)
 #define BPF_Fs16000_Fc55_B2                      0.990653f
 #define BPF_Fs22050_Fc55_A0                      0.003357f
 #define BPF_Fs22050_Fc55_A1                      0.000000f
-#define BPF_Fs22050_Fc55_A2                      -0.003357f
-#define BPF_Fs22050_Fc55_B1                      -1.992964f
+#define BPF_Fs22050_Fc55_A2                      (-0.003357f)
+#define BPF_Fs22050_Fc55_B1                      (-1.992964f)
 #define BPF_Fs22050_Fc55_B2                      0.993209f
 #define BPF_Fs24000_Fc55_A0                      0.003085f
 #define BPF_Fs24000_Fc55_A1                      0.000000f
-#define BPF_Fs24000_Fc55_A2                      -0.003085f
-#define BPF_Fs24000_Fc55_B1                      -1.993552f
+#define BPF_Fs24000_Fc55_A2                      (-0.003085f)
+#define BPF_Fs24000_Fc55_B1                      (-1.993552f)
 #define BPF_Fs24000_Fc55_B2                      0.993759f
 #define BPF_Fs32000_Fc55_A0                      0.002315f
 #define BPF_Fs32000_Fc55_A1                      0.000000f
-#define BPF_Fs32000_Fc55_A2                      -0.002315f
-#define BPF_Fs32000_Fc55_B1                      -1.995199f
+#define BPF_Fs32000_Fc55_A2                      (-0.002315f)
+#define BPF_Fs32000_Fc55_B1                      (-1.995199f)
 #define BPF_Fs32000_Fc55_B2                      0.995316f
 #define BPF_Fs44100_Fc55_A0                      0.001681f
 #define BPF_Fs44100_Fc55_A1                      0.000000f
-#define BPF_Fs44100_Fc55_A2                      -0.001681f
-#define BPF_Fs44100_Fc55_B1                      -1.996537f
+#define BPF_Fs44100_Fc55_A2                      (-0.001681f)
+#define BPF_Fs44100_Fc55_B1                      (-1.996537f)
 #define BPF_Fs44100_Fc55_B2                      0.996599f
 #define BPF_Fs48000_Fc55_A0                      0.001545f
 #define BPF_Fs48000_Fc55_A1                      0.000000f
-#define BPF_Fs48000_Fc55_A2                      -0.001545f
-#define BPF_Fs48000_Fc55_B1                      -1.996823f
+#define BPF_Fs48000_Fc55_A2                      (-0.001545f)
+#define BPF_Fs48000_Fc55_B1                      (-1.996823f)
 #define BPF_Fs48000_Fc55_B2                      0.996875f
 
 #ifdef HIGHER_FS
 #define BPF_Fs96000_Fc55_A0                      0.000762f
 #define BPF_Fs96000_Fc55_A1                      0.000000f
-#define BPF_Fs96000_Fc55_A2                      -0.000762f
-#define BPF_Fs96000_Fc55_B1                      -1.998461f
+#define BPF_Fs96000_Fc55_A2                      (-0.000762f)
+#define BPF_Fs96000_Fc55_B1                      (-1.998461f)
 #define BPF_Fs96000_Fc55_B2                      0.998477f
 
 #define BPF_Fs192000_Fc55_A0                     0.000381f
 #define BPF_Fs192000_Fc55_A1                     0.000000f
-#define BPF_Fs192000_Fc55_A2                     -0.000381f
-#define BPF_Fs192000_Fc55_B1                     -1.999234f
+#define BPF_Fs192000_Fc55_A2                     (-0.000381f)
+#define BPF_Fs192000_Fc55_B1                     (-1.999234f)
 #define BPF_Fs192000_Fc55_B2                     0.999238f
 #endif
 
 /* Coefficients for centre frequency 66Hz */
 #define BPF_Fs8000_Fc66_A0                      0.012648f
 #define BPF_Fs8000_Fc66_A1                      0.000000f
-#define BPF_Fs8000_Fc66_A2                      -0.012648f
-#define BPF_Fs8000_Fc66_B1                      -1.971760f
+#define BPF_Fs8000_Fc66_A2                      (-0.012648f)
+#define BPF_Fs8000_Fc66_B1                      (-1.971760f)
 #define BPF_Fs8000_Fc66_B2                      0.974412f
 #define BPF_Fs11025_Fc66_A0                     0.009209f
 #define BPF_Fs11025_Fc66_A1                     0.000000f
-#define BPF_Fs11025_Fc66_A2                     -0.009209f
-#define BPF_Fs11025_Fc66_B1                     -1.979966f
+#define BPF_Fs11025_Fc66_A2                     (-0.009209f)
+#define BPF_Fs11025_Fc66_B1                     (-1.979966f)
 #define BPF_Fs11025_Fc66_B2                     0.981368f
 #define BPF_Fs12000_Fc66_A0                     0.008468f
 #define BPF_Fs12000_Fc66_A1                     0.000000f
-#define BPF_Fs12000_Fc66_A2                     -0.008468f
-#define BPF_Fs12000_Fc66_B1                     -1.981685f
+#define BPF_Fs12000_Fc66_A2                     (-0.008468f)
+#define BPF_Fs12000_Fc66_B1                     (-1.981685f)
 #define BPF_Fs12000_Fc66_B2                     0.982869f
 #define BPF_Fs16000_Fc66_A0                     0.006364f
 #define BPF_Fs16000_Fc66_A1                     0.000000f
-#define BPF_Fs16000_Fc66_A2                     -0.006364f
-#define BPF_Fs16000_Fc66_B1                     -1.986457f
+#define BPF_Fs16000_Fc66_A2                     (-0.006364f)
+#define BPF_Fs16000_Fc66_B1                     (-1.986457f)
 #define BPF_Fs16000_Fc66_B2                     0.987124f
 #define BPF_Fs22050_Fc66_A0                     0.004626f
 #define BPF_Fs22050_Fc66_A1                     0.000000f
-#define BPF_Fs22050_Fc66_A2                     -0.004626f
-#define BPF_Fs22050_Fc66_B1                     -1.990288f
+#define BPF_Fs22050_Fc66_A2                     (-0.004626f)
+#define BPF_Fs22050_Fc66_B1                     (-1.990288f)
 #define BPF_Fs22050_Fc66_B2                     0.990641f
 #define BPF_Fs24000_Fc66_A0                     0.004252f
 #define BPF_Fs24000_Fc66_A1                     0.000000f
-#define BPF_Fs24000_Fc66_A2                     -0.004252f
-#define BPF_Fs24000_Fc66_B1                     -1.991100f
+#define BPF_Fs24000_Fc66_A2                     (-0.004252f)
+#define BPF_Fs24000_Fc66_B1                     (-1.991100f)
 #define BPF_Fs24000_Fc66_B2                     0.991398f
 #define BPF_Fs32000_Fc66_A0                     0.003192f
 #define BPF_Fs32000_Fc66_A1                     0.000000f
-#define BPF_Fs32000_Fc66_A2                     -0.003192f
-#define BPF_Fs32000_Fc66_B1                     -1.993374f
+#define BPF_Fs32000_Fc66_A2                     (-0.003192f)
+#define BPF_Fs32000_Fc66_B1                     (-1.993374f)
 #define BPF_Fs32000_Fc66_B2                     0.993541f
 #define BPF_Fs44100_Fc66_A0                     0.002318f
 #define BPF_Fs44100_Fc66_A1                     0.000000f
-#define BPF_Fs44100_Fc66_A2                     -0.002318f
-#define BPF_Fs44100_Fc66_B1                     -1.995221f
+#define BPF_Fs44100_Fc66_A2                     (-0.002318f)
+#define BPF_Fs44100_Fc66_B1                     (-1.995221f)
 #define BPF_Fs44100_Fc66_B2                     0.995309f
 #define BPF_Fs48000_Fc66_A0                     0.002131f
 #define BPF_Fs48000_Fc66_A1                     0.000000f
-#define BPF_Fs48000_Fc66_A2                     -0.002131f
-#define BPF_Fs48000_Fc66_B1                     -1.995615f
+#define BPF_Fs48000_Fc66_A2                     (-0.002131f)
+#define BPF_Fs48000_Fc66_B1                     (-1.995615f)
 #define BPF_Fs48000_Fc66_B2                     0.995690f
 
 #ifdef HIGHER_FS
 #define BPF_Fs96000_Fc66_A0                     0.001055f
 #define BPF_Fs96000_Fc66_A1                     0.000000f
-#define BPF_Fs96000_Fc66_A2                     -0.001055f
-#define BPF_Fs96000_Fc66_B1                     -1.997868f
+#define BPF_Fs96000_Fc66_A2                     (-0.001055f)
+#define BPF_Fs96000_Fc66_B1                     (-1.997868f)
 #define BPF_Fs96000_Fc66_B2                     0.997891f
 
 #define BPF_Fs192000_Fc66_A0                    0.000528f
 #define BPF_Fs192000_Fc66_A1                    0.000000f
-#define BPF_Fs192000_Fc66_A2                   -0.000528f
-#define BPF_Fs192000_Fc66_B1                   -1.998939f
+#define BPF_Fs192000_Fc66_A2                   (-0.000528f)
+#define BPF_Fs192000_Fc66_B1                   (-1.998939f)
 #define BPF_Fs192000_Fc66_B2                    0.998945f
 #endif
 
 /* Coefficients for centre frequency 78Hz */
 #define BPF_Fs8000_Fc78_A0                      0.018572f
 #define BPF_Fs8000_Fc78_A1                      0.000000f
-#define BPF_Fs8000_Fc78_A2                      -0.018572f
-#define BPF_Fs8000_Fc78_B1                      -1.958745f
+#define BPF_Fs8000_Fc78_A2                      (-0.018572f)
+#define BPF_Fs8000_Fc78_B1                      (-1.958745f)
 #define BPF_Fs8000_Fc78_B2                      0.962427f
 #define BPF_Fs11025_Fc78_A0                     0.013545f
 #define BPF_Fs11025_Fc78_A1                     0.000000f
-#define BPF_Fs11025_Fc78_A2                     -0.013545f
-#define BPF_Fs11025_Fc78_B1                     -1.970647f
+#define BPF_Fs11025_Fc78_A2                     (-0.013545f)
+#define BPF_Fs11025_Fc78_B1                     (-1.970647f)
 #define BPF_Fs11025_Fc78_B2                     0.972596f
 #define BPF_Fs12000_Fc78_A0                     0.012458f
 #define BPF_Fs12000_Fc78_A1                     0.000000f
-#define BPF_Fs12000_Fc78_A2                     -0.012458f
-#define BPF_Fs12000_Fc78_B1                     -1.973148f
+#define BPF_Fs12000_Fc78_A2                     (-0.012458f)
+#define BPF_Fs12000_Fc78_B1                     (-1.973148f)
 #define BPF_Fs12000_Fc78_B2                     0.974795f
 #define BPF_Fs16000_Fc78_A0                     0.009373f
 #define BPF_Fs16000_Fc78_A1                     0.000000f
-#define BPF_Fs16000_Fc78_A2                     -0.009373f
-#define BPF_Fs16000_Fc78_B1                     -1.980108f
+#define BPF_Fs16000_Fc78_A2                     (-0.009373f)
+#define BPF_Fs16000_Fc78_B1                     (-1.980108f)
 #define BPF_Fs16000_Fc78_B2                     0.981037f
 #define BPF_Fs22050_Fc78_A0                     0.006819f
 #define BPF_Fs22050_Fc78_A1                     0.000000f
-#define BPF_Fs22050_Fc78_A2                     -0.006819f
-#define BPF_Fs22050_Fc78_B1                     -1.985714f
+#define BPF_Fs22050_Fc78_A2                     (-0.006819f)
+#define BPF_Fs22050_Fc78_B1                     (-1.985714f)
 #define BPF_Fs22050_Fc78_B2                     0.986204f
 #define BPF_Fs24000_Fc78_A0                     0.006268f
 #define BPF_Fs24000_Fc78_A1                     0.000000f
-#define BPF_Fs24000_Fc78_A2                     -0.006268f
-#define BPF_Fs24000_Fc78_B1                     -1.986904f
+#define BPF_Fs24000_Fc78_A2                     (-0.006268f)
+#define BPF_Fs24000_Fc78_B1                     (-1.986904f)
 #define BPF_Fs24000_Fc78_B2                     0.987318f
 #define BPF_Fs32000_Fc78_A0                     0.004709f
 #define BPF_Fs32000_Fc78_A1                     0.000000f
-#define BPF_Fs32000_Fc78_A2                     -0.004709f
-#define BPF_Fs32000_Fc78_B1                     -1.990240f
+#define BPF_Fs32000_Fc78_A2                     (-0.004709f)
+#define BPF_Fs32000_Fc78_B1                     (-1.990240f)
 #define BPF_Fs32000_Fc78_B2                     0.990473f
 #define BPF_Fs44100_Fc78_A0                     0.003421f
 #define BPF_Fs44100_Fc78_A1                     0.000000f
-#define BPF_Fs44100_Fc78_A2                     -0.003421f
-#define BPF_Fs44100_Fc78_B1                     -1.992955f
+#define BPF_Fs44100_Fc78_A2                     (-0.003421f)
+#define BPF_Fs44100_Fc78_B1                     (-1.992955f)
 #define BPF_Fs44100_Fc78_B2                     0.993078f
 #define BPF_Fs48000_Fc78_A0                     0.003144f
 #define BPF_Fs48000_Fc78_A1                     0.000000f
-#define BPF_Fs48000_Fc78_A2                     -0.003144f
-#define BPF_Fs48000_Fc78_B1                     -1.993535f
+#define BPF_Fs48000_Fc78_A2                     (-0.003144f)
+#define BPF_Fs48000_Fc78_B1                     (-1.993535f)
 #define BPF_Fs48000_Fc78_B2                     0.993639f
 
 #ifdef HIGHER_FS
 #define BPF_Fs96000_Fc78_A0                     0.001555f
 #define BPF_Fs96000_Fc78_A1                     0.000000f
-#define BPF_Fs96000_Fc78_A2                    -0.0015555f
-#define BPF_Fs96000_Fc78_B1                    -1.996860f
+#define BPF_Fs96000_Fc78_A2                    (-0.0015555f)
+#define BPF_Fs96000_Fc78_B1                    (-1.996860f)
 #define BPF_Fs96000_Fc78_B2                     0.996891f
 
 #define BPF_Fs192000_Fc78_A0                    0.000778f
 #define BPF_Fs192000_Fc78_A1                    0.000000f
-#define BPF_Fs192000_Fc78_A2                   -0.000778f
-#define BPF_Fs192000_Fc78_B1                   -1.998437f
+#define BPF_Fs192000_Fc78_A2                   (-0.000778f)
+#define BPF_Fs192000_Fc78_B1                   (-1.998437f)
 #define BPF_Fs192000_Fc78_B2                    0.998444f
 #endif
 
 /* Coefficients for centre frequency 90Hz */
 #define BPF_Fs8000_Fc90_A0                       0.022760f
 #define BPF_Fs8000_Fc90_A1                       0.000000f
-#define BPF_Fs8000_Fc90_A2                       -0.022760f
-#define BPF_Fs8000_Fc90_B1                       -1.949073f
+#define BPF_Fs8000_Fc90_A2                       (-0.022760f)
+#define BPF_Fs8000_Fc90_B1                       (-1.949073f)
 #define BPF_Fs8000_Fc90_B2                       0.953953f
 #define BPF_Fs11025_Fc90_A0                      0.016619f
 #define BPF_Fs11025_Fc90_A1                      0.000000f
-#define BPF_Fs11025_Fc90_A2                      -0.016619f
-#define BPF_Fs11025_Fc90_B1                      -1.963791f
+#define BPF_Fs11025_Fc90_A2                      (-0.016619f)
+#define BPF_Fs11025_Fc90_B1                      (-1.963791f)
 #define BPF_Fs11025_Fc90_B2                      0.966377f
 #define BPF_Fs12000_Fc90_A0                      0.015289f
 #define BPF_Fs12000_Fc90_A1                      0.000000f
-#define BPF_Fs12000_Fc90_A2                      -0.015289f
-#define BPF_Fs12000_Fc90_B1                      -1.966882f
+#define BPF_Fs12000_Fc90_A2                      (-0.015289f)
+#define BPF_Fs12000_Fc90_B1                      (-1.966882f)
 #define BPF_Fs12000_Fc90_B2                      0.969067f
 #define BPF_Fs16000_Fc90_A0                      0.011511f
 #define BPF_Fs16000_Fc90_A1                      0.000000f
-#define BPF_Fs16000_Fc90_A2                      -0.011511f
-#define BPF_Fs16000_Fc90_B1                      -1.975477f
+#define BPF_Fs16000_Fc90_A2                      (-0.011511f)
+#define BPF_Fs16000_Fc90_B1                      (-1.975477f)
 #define BPF_Fs16000_Fc90_B2                      0.976711f
 #define BPF_Fs22050_Fc90_A0                      0.008379f
 #define BPF_Fs22050_Fc90_A1                      0.000000f
-#define BPF_Fs22050_Fc90_A2                      -0.008379f
-#define BPF_Fs22050_Fc90_B1                      -1.982395f
+#define BPF_Fs22050_Fc90_A2                      (-0.008379f)
+#define BPF_Fs22050_Fc90_B1                      (-1.982395f)
 #define BPF_Fs22050_Fc90_B2                      0.983047f
 #define BPF_Fs24000_Fc90_A0                      0.007704f
 #define BPF_Fs24000_Fc90_A1                      0.000000f
-#define BPF_Fs24000_Fc90_A2                      -0.007704f
-#define BPF_Fs24000_Fc90_B1                      -1.983863f
+#define BPF_Fs24000_Fc90_A2                      (-0.007704f)
+#define BPF_Fs24000_Fc90_B1                      (-1.983863f)
 #define BPF_Fs24000_Fc90_B2                      0.984414f
 #define BPF_Fs32000_Fc90_A0                      0.005789f
 #define BPF_Fs32000_Fc90_A1                      0.000000f
-#define BPF_Fs32000_Fc90_A2                      -0.005789f
-#define BPF_Fs32000_Fc90_B1                      -1.987977f
+#define BPF_Fs32000_Fc90_A2                      (-0.005789f)
+#define BPF_Fs32000_Fc90_B1                      (-1.987977f)
 #define BPF_Fs32000_Fc90_B2                      0.988288f
 #define BPF_Fs44100_Fc90_A0                      0.004207f
 #define BPF_Fs44100_Fc90_A1                      0.000000f
-#define BPF_Fs44100_Fc90_A2                      -0.004207f
-#define BPF_Fs44100_Fc90_B1                      -1.991324f
+#define BPF_Fs44100_Fc90_A2                      (-0.004207f)
+#define BPF_Fs44100_Fc90_B1                      (-1.991324f)
 #define BPF_Fs44100_Fc90_B2                      0.991488f
 #define BPF_Fs48000_Fc90_A0                      0.003867f
 #define BPF_Fs48000_Fc90_A1                      0.000000f
-#define BPF_Fs48000_Fc90_A2                      -0.003867f
-#define BPF_Fs48000_Fc90_B1                      -1.992038f
+#define BPF_Fs48000_Fc90_A2                      (-0.003867f)
+#define BPF_Fs48000_Fc90_B1                      (-1.992038f)
 #define BPF_Fs48000_Fc90_B2                      0.992177f
 
 #ifdef HIGHER_FS
 #define BPF_Fs96000_Fc90_A0                      0.001913f
 #define BPF_Fs96000_Fc90_A1                      0.000000f
-#define BPF_Fs96000_Fc90_A2                     -0.001913f
-#define BPF_Fs96000_Fc90_B1                     -1.996134f
+#define BPF_Fs96000_Fc90_A2                     (-0.001913f)
+#define BPF_Fs96000_Fc90_B1                     (-1.996134f)
 #define BPF_Fs96000_Fc90_B2                      0.996174f
 
 #define BPF_Fs192000_Fc90_A0                     0.000958f
 #define BPF_Fs192000_Fc90_A1                     0.000000f
-#define BPF_Fs192000_Fc90_A2                    -0.000958f
-#define BPF_Fs192000_Fc90_B1                    -1.998075f
+#define BPF_Fs192000_Fc90_A2                    (-0.000958f)
+#define BPF_Fs192000_Fc90_B1                    (-1.998075f)
 #define BPF_Fs192000_Fc90_B2                     0.998085f
 #endif
 
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h b/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
index 353560c..8c04847 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
@@ -69,55 +69,55 @@
 #define HPF_Fs22050_Gain6_B2                            0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs22050_Gain7_A0                            1.390177
-#define HPF_Fs22050_Gain7_A1                            -0.020144
+#define HPF_Fs22050_Gain7_A1                            (-0.020144)
 #define HPF_Fs22050_Gain7_A2                            0.000000
 #define HPF_Fs22050_Gain7_B1                            0.370033
 #define HPF_Fs22050_Gain7_B2                            0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs22050_Gain8_A0                            1.476219
-#define HPF_Fs22050_Gain8_A1                            -0.106187
+#define HPF_Fs22050_Gain8_A1                            (-0.106187)
 #define HPF_Fs22050_Gain8_A2                            0.000000
 #define HPF_Fs22050_Gain8_B1                            0.370033
 #define HPF_Fs22050_Gain8_B2                            0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs22050_Gain9_A0                            1.572761
-#define HPF_Fs22050_Gain9_A1                            -0.202728
+#define HPF_Fs22050_Gain9_A1                            (-0.202728)
 #define HPF_Fs22050_Gain9_A2                            0.000000
 #define HPF_Fs22050_Gain9_B1                            0.370033
 #define HPF_Fs22050_Gain9_B2                            0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs22050_Gain10_A0                           1.681082
-#define HPF_Fs22050_Gain10_A1                           -0.311049
+#define HPF_Fs22050_Gain10_A1                           (-0.311049)
 #define HPF_Fs22050_Gain10_A2                           0.000000
 #define HPF_Fs22050_Gain10_B1                           0.370033
 #define HPF_Fs22050_Gain10_B2                           0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs22050_Gain11_A0                           1.802620
-#define HPF_Fs22050_Gain11_A1                           -0.432588
+#define HPF_Fs22050_Gain11_A1                           (-0.432588)
 #define HPF_Fs22050_Gain11_A2                           0.000000
 #define HPF_Fs22050_Gain11_B1                           0.370033
 #define HPF_Fs22050_Gain11_B2                           0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs22050_Gain12_A0                           1.938989
-#define HPF_Fs22050_Gain12_A1                           -0.568956
+#define HPF_Fs22050_Gain12_A1                           (-0.568956)
 #define HPF_Fs22050_Gain12_A2                           0.000000
 #define HPF_Fs22050_Gain12_B1                           0.370033
 #define HPF_Fs22050_Gain12_B2                           0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs22050_Gain13_A0                           2.091997
-#define HPF_Fs22050_Gain13_A1                           -0.721964
+#define HPF_Fs22050_Gain13_A1                           (-0.721964)
 #define HPF_Fs22050_Gain13_A2                           0.000000
 #define HPF_Fs22050_Gain13_B1                           0.370033
 #define HPF_Fs22050_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs22050_Gain14_A0                           2.263674
-#define HPF_Fs22050_Gain14_A1                           -0.893641
+#define HPF_Fs22050_Gain14_A1                           (-0.893641)
 #define HPF_Fs22050_Gain14_A2                           0.000000
 #define HPF_Fs22050_Gain14_B1                           0.370033
 #define HPF_Fs22050_Gain14_B2                           0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs22050_Gain15_A0                           2.456300
-#define HPF_Fs22050_Gain15_A1                           -1.086267
+#define HPF_Fs22050_Gain15_A1                           (-1.086267)
 #define HPF_Fs22050_Gain15_A2                           0.000000
 #define HPF_Fs22050_Gain15_B1                           0.370033
 #define HPF_Fs22050_Gain15_B2                           0.000000
@@ -148,342 +148,342 @@
 #define HPF_Fs24000_Gain4_B2                            0.000000
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs24000_Gain5_A0                            1.284870
-#define HPF_Fs24000_Gain5_A1                            -0.016921
+#define HPF_Fs24000_Gain5_A1                            (-0.016921)
 #define HPF_Fs24000_Gain5_A2                            0.000000
 #define HPF_Fs24000_Gain5_B1                            0.267949
 #define HPF_Fs24000_Gain5_B2                            0.000000
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs24000_Gain6_A0                           1.364291
-#define HPF_Fs24000_Gain6_A1                           -0.096342
+#define HPF_Fs24000_Gain6_A1                           (-0.096342)
 #define HPF_Fs24000_Gain6_A2                           0.000000
 #define HPF_Fs24000_Gain6_B1                           0.267949
 #define HPF_Fs24000_Gain6_B2                           0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs24000_Gain7_A0                            1.453403
-#define HPF_Fs24000_Gain7_A1                            -0.185454
+#define HPF_Fs24000_Gain7_A1                            (-0.185454)
 #define HPF_Fs24000_Gain7_A2                            0.000000
 #define HPF_Fs24000_Gain7_B1                            0.267949
 #define HPF_Fs24000_Gain7_B2                            0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs24000_Gain8_A0                            1.553389
-#define HPF_Fs24000_Gain8_A1                            -0.285440
+#define HPF_Fs24000_Gain8_A1                            (-0.285440)
 #define HPF_Fs24000_Gain8_A2                            0.000000
 #define HPF_Fs24000_Gain8_B1                            0.267949
 #define HPF_Fs24000_Gain8_B2                            0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs24000_Gain9_A0                            1.665574
-#define HPF_Fs24000_Gain9_A1                            -0.397625
+#define HPF_Fs24000_Gain9_A1                            (-0.397625)
 #define HPF_Fs24000_Gain9_A2                            0.000000
 #define HPF_Fs24000_Gain9_B1                            0.267949
 #define HPF_Fs24000_Gain9_B2                            0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs24000_Gain10_A0                           1.791449
-#define HPF_Fs24000_Gain10_A1                           -0.523499
+#define HPF_Fs24000_Gain10_A1                           (-0.523499)
 #define HPF_Fs24000_Gain10_A2                           0.000000
 #define HPF_Fs24000_Gain10_B1                           0.267949
 #define HPF_Fs24000_Gain10_B2                           0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs24000_Gain11_A0                           1.932682
-#define HPF_Fs24000_Gain11_A1                           -0.664733
+#define HPF_Fs24000_Gain11_A1                           (-0.664733)
 #define HPF_Fs24000_Gain11_A2                           0.000000
 #define HPF_Fs24000_Gain11_B1                           0.267949
 #define HPF_Fs24000_Gain11_B2                           0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs24000_Gain12_A0                           2.091148
-#define HPF_Fs24000_Gain12_A1                           -0.823199
+#define HPF_Fs24000_Gain12_A1                           (-0.823199)
 #define HPF_Fs24000_Gain12_A2                           0.000000
 #define HPF_Fs24000_Gain12_B1                           0.267949
 #define HPF_Fs24000_Gain12_B2                           0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs24000_Gain13_A0                           2.268950
-#define HPF_Fs24000_Gain13_A1                           -1.001001
+#define HPF_Fs24000_Gain13_A1                           (-1.001001)
 #define HPF_Fs24000_Gain13_A2                           0.000000
 #define HPF_Fs24000_Gain13_B1                           0.267949
 #define HPF_Fs24000_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs24000_Gain14_A0                           2.468447
-#define HPF_Fs24000_Gain14_A1                           -1.200498
+#define HPF_Fs24000_Gain14_A1                           (-1.200498)
 #define HPF_Fs24000_Gain14_A2                           0.000000
 #define HPF_Fs24000_Gain14_B1                           0.267949
 #define HPF_Fs24000_Gain14_B2                           0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs24000_Gain15_A0                           2.692287
-#define HPF_Fs24000_Gain15_A1                           -1.424338
+#define HPF_Fs24000_Gain15_A1                           (-1.424338)
 #define HPF_Fs24000_Gain15_A2                           0.000000
 #define HPF_Fs24000_Gain15_B1                           0.267949
 #define HPF_Fs24000_Gain15_B2                           0.000000
 /* Coefficients for sample rate 32000Hz */
                                                                     /* Gain =  1.000000 dB */
 #define HPF_Fs32000_Gain1_A0                            1.061009
-#define HPF_Fs32000_Gain1_A1                            -0.061009
+#define HPF_Fs32000_Gain1_A1                            (-0.061009)
 #define HPF_Fs32000_Gain1_A2                            0.000000
-#define HPF_Fs32000_Gain1_B1                            -0.000000
+#define HPF_Fs32000_Gain1_B1                            (-0.000000)
 #define HPF_Fs32000_Gain1_B2                            0.000000
                                                                     /* Gain =  2.000000 dB */
 #define HPF_Fs32000_Gain2_A0                             1.129463
-#define HPF_Fs32000_Gain2_A1                             -0.129463
+#define HPF_Fs32000_Gain2_A1                             (-0.129463)
 #define HPF_Fs32000_Gain2_A2                             0.000000
-#define HPF_Fs32000_Gain2_B1                             -0.000000
+#define HPF_Fs32000_Gain2_B1                             (-0.000000)
 #define HPF_Fs32000_Gain2_B2                             0.000000
                                                                     /* Gain =  3.000000 dB */
 #define HPF_Fs32000_Gain3_A0                             1.206267
-#define HPF_Fs32000_Gain3_A1                             -0.206267
+#define HPF_Fs32000_Gain3_A1                             (-0.206267)
 #define HPF_Fs32000_Gain3_A2                             0.000000
-#define HPF_Fs32000_Gain3_B1                             -0.000000
+#define HPF_Fs32000_Gain3_B1                             (-0.000000)
 #define HPF_Fs32000_Gain3_B2                             0.000000
                                                                     /* Gain =  4.000000 dB */
 #define HPF_Fs32000_Gain4_A0                            1.292447
-#define HPF_Fs32000_Gain4_A1                            -0.292447
+#define HPF_Fs32000_Gain4_A1                            (-0.292447)
 #define HPF_Fs32000_Gain4_A2                            0.000000
-#define HPF_Fs32000_Gain4_B1                            -0.000000
+#define HPF_Fs32000_Gain4_B1                            (-0.000000)
 #define HPF_Fs32000_Gain4_B2                            0.000000
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs32000_Gain5_A0                            1.389140
-#define HPF_Fs32000_Gain5_A1                            -0.389140
+#define HPF_Fs32000_Gain5_A1                            (-0.389140)
 #define HPF_Fs32000_Gain5_A2                            0.000000
-#define HPF_Fs32000_Gain5_B1                            -0.000000
+#define HPF_Fs32000_Gain5_B1                            (-0.000000)
 #define HPF_Fs32000_Gain5_B2                            0.000000
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs32000_Gain6_A0                             1.497631
-#define HPF_Fs32000_Gain6_A1                             -0.497631
+#define HPF_Fs32000_Gain6_A1                             (-0.497631)
 #define HPF_Fs32000_Gain6_A2                             0.000000
-#define HPF_Fs32000_Gain6_B1                             -0.000000
+#define HPF_Fs32000_Gain6_B1                             (-0.000000)
 #define HPF_Fs32000_Gain6_B2                             0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs32000_Gain7_A0                             1.619361
-#define HPF_Fs32000_Gain7_A1                             -0.619361
+#define HPF_Fs32000_Gain7_A1                             (-0.619361)
 #define HPF_Fs32000_Gain7_A2                             0.000000
-#define HPF_Fs32000_Gain7_B1                             -0.000000
+#define HPF_Fs32000_Gain7_B1                             (-0.000000)
 #define HPF_Fs32000_Gain7_B2                             0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs32000_Gain8_A0                             1.755943
-#define HPF_Fs32000_Gain8_A1                             -0.755943
+#define HPF_Fs32000_Gain8_A1                             (-0.755943)
 #define HPF_Fs32000_Gain8_A2                             0.000000
-#define HPF_Fs32000_Gain8_B1                             -0.000000
+#define HPF_Fs32000_Gain8_B1                             (-0.000000)
 #define HPF_Fs32000_Gain8_B2                             0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs32000_Gain9_A0                             1.909191
-#define HPF_Fs32000_Gain9_A1                             -0.909191
+#define HPF_Fs32000_Gain9_A1                             (-0.909191)
 #define HPF_Fs32000_Gain9_A2                             0.000000
-#define HPF_Fs32000_Gain9_B1                             -0.000000
+#define HPF_Fs32000_Gain9_B1                             (-0.000000)
 #define HPF_Fs32000_Gain9_B2                             0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs32000_Gain10_A0                            2.081139
-#define HPF_Fs32000_Gain10_A1                            -1.081139
+#define HPF_Fs32000_Gain10_A1                            (-1.081139)
 #define HPF_Fs32000_Gain10_A2                            0.000000
-#define HPF_Fs32000_Gain10_B1                            -0.000000
+#define HPF_Fs32000_Gain10_B1                            (-0.000000)
 #define HPF_Fs32000_Gain10_B2                            0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs32000_Gain11_A0                           2.274067
-#define HPF_Fs32000_Gain11_A1                           -1.274067
+#define HPF_Fs32000_Gain11_A1                           (-1.274067)
 #define HPF_Fs32000_Gain11_A2                           0.000000
-#define HPF_Fs32000_Gain11_B1                           -0.000000
+#define HPF_Fs32000_Gain11_B1                           (-0.000000)
 #define HPF_Fs32000_Gain11_B2                           0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs32000_Gain12_A0                          2.490536
-#define HPF_Fs32000_Gain12_A1                          -1.490536
+#define HPF_Fs32000_Gain12_A1                          (-1.490536)
 #define HPF_Fs32000_Gain12_A2                          0.000000
-#define HPF_Fs32000_Gain12_B1                          -0.000000
+#define HPF_Fs32000_Gain12_B1                          (-0.000000)
 #define HPF_Fs32000_Gain12_B2                          0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs32000_Gain13_A0                           2.733418
-#define HPF_Fs32000_Gain13_A1                           -1.733418
+#define HPF_Fs32000_Gain13_A1                           (-1.733418)
 #define HPF_Fs32000_Gain13_A2                           0.000000
-#define HPF_Fs32000_Gain13_B1                           -0.000000
+#define HPF_Fs32000_Gain13_B1                           (-0.000000)
 #define HPF_Fs32000_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs32000_Gain14_A0                           3.005936
-#define HPF_Fs32000_Gain14_A1                           -2.005936
+#define HPF_Fs32000_Gain14_A1                           (-2.005936)
 #define HPF_Fs32000_Gain14_A2                           0.000000
-#define HPF_Fs32000_Gain14_B1                           -0.000000
+#define HPF_Fs32000_Gain14_B1                           (-0.000000)
 #define HPF_Fs32000_Gain14_B2                           0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs32000_Gain15_A0                          3.311707
-#define HPF_Fs32000_Gain15_A1                          -2.311707
+#define HPF_Fs32000_Gain15_A1                          (-2.311707)
 #define HPF_Fs32000_Gain15_A2                          0.000000
-#define HPF_Fs32000_Gain15_B1                          -0.000000
+#define HPF_Fs32000_Gain15_B1                          (-0.000000)
 #define HPF_Fs32000_Gain15_B2                          0.000000
 /* Coefficients for sample rate 44100Hz */
                                                                     /* Gain =  1.000000 dB */
 #define HPF_Fs44100_Gain1_A0                            1.074364
-#define HPF_Fs44100_Gain1_A1                            -0.293257
+#define HPF_Fs44100_Gain1_A1                            (-0.293257)
 #define HPF_Fs44100_Gain1_A2                            0.000000
-#define HPF_Fs44100_Gain1_B1                            -0.218894
+#define HPF_Fs44100_Gain1_B1                            (-0.218894)
 #define HPF_Fs44100_Gain1_B2                            0.000000
                                                                     /* Gain =  2.000000 dB */
 #define HPF_Fs44100_Gain2_A0                            1.157801
-#define HPF_Fs44100_Gain2_A1                            -0.376695
+#define HPF_Fs44100_Gain2_A1                            (-0.376695)
 #define HPF_Fs44100_Gain2_A2                            0.000000
-#define HPF_Fs44100_Gain2_B1                            -0.218894
+#define HPF_Fs44100_Gain2_B1                            (-0.218894)
 #define HPF_Fs44100_Gain2_B2                            0.000000
                                                                     /* Gain =  3.000000 dB */
 #define HPF_Fs44100_Gain3_A0                           1.251420
-#define HPF_Fs44100_Gain3_A1                           -0.470313
+#define HPF_Fs44100_Gain3_A1                           (-0.470313)
 #define HPF_Fs44100_Gain3_A2                           0.000000
-#define HPF_Fs44100_Gain3_B1                           -0.218894
+#define HPF_Fs44100_Gain3_B1                           (-0.218894)
 #define HPF_Fs44100_Gain3_B2                           0.000000
                                                                     /* Gain =  4.000000 dB */
 #define HPF_Fs44100_Gain4_A0                            1.356461
-#define HPF_Fs44100_Gain4_A1                            -0.575355
+#define HPF_Fs44100_Gain4_A1                            (-0.575355)
 #define HPF_Fs44100_Gain4_A2                            0.000000
-#define HPF_Fs44100_Gain4_B1                            -0.218894
+#define HPF_Fs44100_Gain4_B1                            (-0.218894)
 #define HPF_Fs44100_Gain4_B2                            0.000000
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs44100_Gain5_A0                            1.474320
-#define HPF_Fs44100_Gain5_A1                            -0.693213
+#define HPF_Fs44100_Gain5_A1                            (-0.693213)
 #define HPF_Fs44100_Gain5_A2                            0.000000
-#define HPF_Fs44100_Gain5_B1                            -0.218894
+#define HPF_Fs44100_Gain5_B1                            (-0.218894)
 #define HPF_Fs44100_Gain5_B2                            0.000000
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs44100_Gain6_A0                           1.606559
-#define HPF_Fs44100_Gain6_A1                           -0.825453
+#define HPF_Fs44100_Gain6_A1                           (-0.825453)
 #define HPF_Fs44100_Gain6_A2                           0.000000
-#define HPF_Fs44100_Gain6_B1                           -0.218894
+#define HPF_Fs44100_Gain6_B1                           (-0.218894)
 #define HPF_Fs44100_Gain6_B2                           0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs44100_Gain7_A0                           1.754935
-#define HPF_Fs44100_Gain7_A1                           -0.973828
+#define HPF_Fs44100_Gain7_A1                           (-0.973828)
 #define HPF_Fs44100_Gain7_A2                           0.000000
-#define HPF_Fs44100_Gain7_B1                           -0.218894
+#define HPF_Fs44100_Gain7_B1                           (-0.218894)
 #define HPF_Fs44100_Gain7_B2                           0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs44100_Gain8_A0                            1.921414
-#define HPF_Fs44100_Gain8_A1                            -1.140308
+#define HPF_Fs44100_Gain8_A1                            (-1.140308)
 #define HPF_Fs44100_Gain8_A2                            0.000000
-#define HPF_Fs44100_Gain8_B1                            -0.218894
+#define HPF_Fs44100_Gain8_B1                            (-0.218894)
 #define HPF_Fs44100_Gain8_B2                            0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs44100_Gain9_A0                            2.108208
-#define HPF_Fs44100_Gain9_A1                            -1.327101
+#define HPF_Fs44100_Gain9_A1                            (-1.327101)
 #define HPF_Fs44100_Gain9_A2                            0.000000
-#define HPF_Fs44100_Gain9_B1                            -0.218894
+#define HPF_Fs44100_Gain9_B1                            (-0.218894)
 #define HPF_Fs44100_Gain9_B2                            0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs44100_Gain10_A0                          2.317793
-#define HPF_Fs44100_Gain10_A1                          -1.536687
+#define HPF_Fs44100_Gain10_A1                          (-1.536687)
 #define HPF_Fs44100_Gain10_A2                          0.000000
-#define HPF_Fs44100_Gain10_B1                          -0.218894
+#define HPF_Fs44100_Gain10_B1                          (-0.218894)
 #define HPF_Fs44100_Gain10_B2                          0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs44100_Gain11_A0                          2.552952
-#define HPF_Fs44100_Gain11_A1                          -1.771846
+#define HPF_Fs44100_Gain11_A1                          (-1.771846)
 #define HPF_Fs44100_Gain11_A2                          0.000000
-#define HPF_Fs44100_Gain11_B1                          -0.218894
+#define HPF_Fs44100_Gain11_B1                          (-0.218894)
 #define HPF_Fs44100_Gain11_B2                          0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs44100_Gain12_A0                          2.816805
-#define HPF_Fs44100_Gain12_A1                          -2.035698
+#define HPF_Fs44100_Gain12_A1                          (-2.035698)
 #define HPF_Fs44100_Gain12_A2                          0.000000
-#define HPF_Fs44100_Gain12_B1                          -0.218894
+#define HPF_Fs44100_Gain12_B1                          (-0.218894)
 #define HPF_Fs44100_Gain12_B2                          0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs44100_Gain13_A0                           3.112852
-#define HPF_Fs44100_Gain13_A1                           -2.331746
+#define HPF_Fs44100_Gain13_A1                           (-2.331746)
 #define HPF_Fs44100_Gain13_A2                           0.000000
-#define HPF_Fs44100_Gain13_B1                           -0.218894
+#define HPF_Fs44100_Gain13_B1                           (-0.218894)
 #define HPF_Fs44100_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs44100_Gain14_A0                          3.445023
-#define HPF_Fs44100_Gain14_A1                          -2.663916
+#define HPF_Fs44100_Gain14_A1                          (-2.663916)
 #define HPF_Fs44100_Gain14_A2                          0.000000
-#define HPF_Fs44100_Gain14_B1                          -0.218894
+#define HPF_Fs44100_Gain14_B1                          (-0.218894)
 #define HPF_Fs44100_Gain14_B2                          0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs44100_Gain15_A0                          3.817724
-#define HPF_Fs44100_Gain15_A1                          -3.036618
+#define HPF_Fs44100_Gain15_A1                          (-3.036618)
 #define HPF_Fs44100_Gain15_A2                          0.000000
-#define HPF_Fs44100_Gain15_B1                          -0.218894
+#define HPF_Fs44100_Gain15_B1                          (-0.218894)
 #define HPF_Fs44100_Gain15_B2                          0.000000
 /* Coefficients for sample rate 48000Hz */
                                                                     /* Gain =  1.000000 dB */
 #define HPF_Fs48000_Gain1_A0                          1.077357
-#define HPF_Fs48000_Gain1_A1                          -0.345306
+#define HPF_Fs48000_Gain1_A1                          (-0.345306)
 #define HPF_Fs48000_Gain1_A2                          0.000000
-#define HPF_Fs48000_Gain1_B1                          -0.267949
+#define HPF_Fs48000_Gain1_B1                          (-0.267949)
 #define HPF_Fs48000_Gain1_B2                          0.000000
                                                                     /* Gain =  2.000000 dB */
 #define HPF_Fs48000_Gain2_A0                          1.164152
-#define HPF_Fs48000_Gain2_A1                          -0.432101
+#define HPF_Fs48000_Gain2_A1                          (-0.432101)
 #define HPF_Fs48000_Gain2_A2                          0.000000
-#define HPF_Fs48000_Gain2_B1                          -0.267949
+#define HPF_Fs48000_Gain2_B1                          (-0.267949)
 #define HPF_Fs48000_Gain2_B2                          0.000000
                                                                     /* Gain =  3.000000 dB */
 #define HPF_Fs48000_Gain3_A0                          1.261538
-#define HPF_Fs48000_Gain3_A1                          -0.529488
+#define HPF_Fs48000_Gain3_A1                          (-0.529488)
 #define HPF_Fs48000_Gain3_A2                          0.000000
-#define HPF_Fs48000_Gain3_B1                          -0.267949
+#define HPF_Fs48000_Gain3_B1                          (-0.267949)
 #define HPF_Fs48000_Gain3_B2                          0.000000
                                                                     /* Gain =  4.000000 dB */
 #define HPF_Fs48000_Gain4_A0                           1.370807
-#define HPF_Fs48000_Gain4_A1                           -0.638757
+#define HPF_Fs48000_Gain4_A1                           (-0.638757)
 #define HPF_Fs48000_Gain4_A2                           0.000000
-#define HPF_Fs48000_Gain4_B1                           -0.267949
+#define HPF_Fs48000_Gain4_B1                           (-0.267949)
 #define HPF_Fs48000_Gain4_B2                           0.000000
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs48000_Gain5_A0                           1.493409
-#define HPF_Fs48000_Gain5_A1                           -0.761359
+#define HPF_Fs48000_Gain5_A1                           (-0.761359)
 #define HPF_Fs48000_Gain5_A2                           0.000000
-#define HPF_Fs48000_Gain5_B1                           -0.267949
+#define HPF_Fs48000_Gain5_B1                           (-0.267949)
 #define HPF_Fs48000_Gain5_B2                           0.000000
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs48000_Gain6_A0                            1.630971
-#define HPF_Fs48000_Gain6_A1                            -0.898920
+#define HPF_Fs48000_Gain6_A1                            (-0.898920)
 #define HPF_Fs48000_Gain6_A2                            0.000000
-#define HPF_Fs48000_Gain6_B1                            -0.267949
+#define HPF_Fs48000_Gain6_B1                            (-0.267949)
 #define HPF_Fs48000_Gain6_B2                            0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs48000_Gain7_A0                            1.785318
-#define HPF_Fs48000_Gain7_A1                            -1.053267
+#define HPF_Fs48000_Gain7_A1                            (-1.053267)
 #define HPF_Fs48000_Gain7_A2                            0.000000
-#define HPF_Fs48000_Gain7_B1                            -0.267949
+#define HPF_Fs48000_Gain7_B1                            (-0.267949)
 #define HPF_Fs48000_Gain7_B2                            0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs48000_Gain8_A0                           1.958498
-#define HPF_Fs48000_Gain8_A1                           -1.226447
+#define HPF_Fs48000_Gain8_A1                           (-1.226447)
 #define HPF_Fs48000_Gain8_A2                           0.000000
-#define HPF_Fs48000_Gain8_B1                           -0.267949
+#define HPF_Fs48000_Gain8_B1                           (-0.267949)
 #define HPF_Fs48000_Gain8_B2                           0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs48000_Gain9_A0                          2.152809
-#define HPF_Fs48000_Gain9_A1                          -1.420758
+#define HPF_Fs48000_Gain9_A1                          (-1.420758)
 #define HPF_Fs48000_Gain9_A2                          0.000000
-#define HPF_Fs48000_Gain9_B1                          -0.267949
+#define HPF_Fs48000_Gain9_B1                          (-0.267949)
 #define HPF_Fs48000_Gain9_B2                          0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs48000_Gain10_A0                         2.370829
-#define HPF_Fs48000_Gain10_A1                         -1.638778
+#define HPF_Fs48000_Gain10_A1                         (-1.638778)
 #define HPF_Fs48000_Gain10_A2                         0.000000
-#define HPF_Fs48000_Gain10_B1                         -0.267949
+#define HPF_Fs48000_Gain10_B1                         (-0.267949)
 #define HPF_Fs48000_Gain10_B2                         0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs48000_Gain11_A0                          2.615452
-#define HPF_Fs48000_Gain11_A1                          -1.883401
+#define HPF_Fs48000_Gain11_A1                          (-1.883401)
 #define HPF_Fs48000_Gain11_A2                          0.000000
-#define HPF_Fs48000_Gain11_B1                          -0.267949
+#define HPF_Fs48000_Gain11_B1                          (-0.267949)
 #define HPF_Fs48000_Gain11_B2                          0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs48000_Gain12_A0                          2.889924
-#define HPF_Fs48000_Gain12_A1                          -2.157873
+#define HPF_Fs48000_Gain12_A1                          (-2.157873)
 #define HPF_Fs48000_Gain12_A2                          0.000000
-#define HPF_Fs48000_Gain12_B1                          -0.267949
+#define HPF_Fs48000_Gain12_B1                          (-0.267949)
 #define HPF_Fs48000_Gain12_B2                          0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs48000_Gain13_A0                           3.197886
-#define HPF_Fs48000_Gain13_A1                           -2.465835
+#define HPF_Fs48000_Gain13_A1                           (-2.465835)
 #define HPF_Fs48000_Gain13_A2                           0.000000
-#define HPF_Fs48000_Gain13_B1                           -0.267949
+#define HPF_Fs48000_Gain13_B1                           (-0.267949)
 #define HPF_Fs48000_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs48000_Gain14_A0                          3.543425
-#define HPF_Fs48000_Gain14_A1                          -2.811374
+#define HPF_Fs48000_Gain14_A1                          (-2.811374)
 #define HPF_Fs48000_Gain14_A2                          0.000000
-#define HPF_Fs48000_Gain14_B1                          -0.267949
+#define HPF_Fs48000_Gain14_B1                          (-0.267949)
 #define HPF_Fs48000_Gain14_B2                          0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs48000_Gain15_A0                         3.931127
-#define HPF_Fs48000_Gain15_A1                         -3.199076
+#define HPF_Fs48000_Gain15_A1                         (-3.199076)
 #define HPF_Fs48000_Gain15_A2                         0.000000
-#define HPF_Fs48000_Gain15_B1                         -0.267949
+#define HPF_Fs48000_Gain15_B1                         (-0.267949)
 #define HPF_Fs48000_Gain15_B2                         0.000000
 
 #ifdef HIGHER_FS
@@ -491,185 +491,185 @@
 /* Coefficients for sample rate 96000Hz */
                                                                  /* Gain =  1.000000 dB */
 #define HPF_Fs96000_Gain1_A0                          1.096233
-#define HPF_Fs96000_Gain1_A1                          -0.673583
+#define HPF_Fs96000_Gain1_A1                          (-0.673583)
 #define HPF_Fs96000_Gain1_A2                          0.000000
-#define HPF_Fs96000_Gain1_B1                          -0.577350
+#define HPF_Fs96000_Gain1_B1                          (-0.577350)
 #define HPF_Fs96000_Gain1_B2                          0.000000
                                                                  /* Gain =  2.000000 dB */
 #define HPF_Fs96000_Gain2_A0                          1.204208
-#define HPF_Fs96000_Gain2_A1                          -0.781558
+#define HPF_Fs96000_Gain2_A1                          (-0.781558)
 #define HPF_Fs96000_Gain2_A2                          0.000000
-#define HPF_Fs96000_Gain2_B1                          -0.577350
+#define HPF_Fs96000_Gain2_B1                          (-0.577350)
 #define HPF_Fs96000_Gain2_B2                          0.000000
                                                                  /* Gain =  3.000000 dB */
 #define HPF_Fs96000_Gain3_A0                          1.325358
-#define HPF_Fs96000_Gain3_A1                          -0.902708
+#define HPF_Fs96000_Gain3_A1                          (-0.902708)
 #define HPF_Fs96000_Gain3_A2                          0.000000
-#define HPF_Fs96000_Gain3_B1                          -0.577350
+#define HPF_Fs96000_Gain3_B1                          (-0.577350)
 #define HPF_Fs96000_Gain3_B2                          0.000000
                                                                  /* Gain =  4.000000 dB */
 #define HPF_Fs96000_Gain4_A0                           1.461291
-#define HPF_Fs96000_Gain4_A1                           -1.038641
+#define HPF_Fs96000_Gain4_A1                           (-1.038641)
 #define HPF_Fs96000_Gain4_A2                           0.000000
-#define HPF_Fs96000_Gain4_B1                           -0.577350
+#define HPF_Fs96000_Gain4_B1                           (-0.577350)
 #define HPF_Fs96000_Gain4_B2                           0.000000
                                                                  /* Gain =  5.000000 dB */
 #define HPF_Fs96000_Gain5_A0                           1.613810
-#define HPF_Fs96000_Gain5_A1                           -1.191160
+#define HPF_Fs96000_Gain5_A1                           (-1.191160)
 #define HPF_Fs96000_Gain5_A2                           0.000000
-#define HPF_Fs96000_Gain5_B1                           -0.577350
+#define HPF_Fs96000_Gain5_B1                           (-0.577350)
 #define HPF_Fs96000_Gain5_B2                           0.000000
                                                                  /* Gain =  6.000000 dB */
 #define HPF_Fs96000_Gain6_A0                            1.784939
-#define HPF_Fs96000_Gain6_A1                            -1.362289
+#define HPF_Fs96000_Gain6_A1                            (-1.362289)
 #define HPF_Fs96000_Gain6_A2                            0.000000
-#define HPF_Fs96000_Gain6_B1                            -0.577350
+#define HPF_Fs96000_Gain6_B1                            (-0.577350)
 #define HPF_Fs96000_Gain6_B2                            0.000000
                                                                 /* Gain =  7.000000 dB */
 #define HPF_Fs96000_Gain7_A0                            1.976949
-#define HPF_Fs96000_Gain7_A1                            -1.554299
+#define HPF_Fs96000_Gain7_A1                            (-1.554299)
 #define HPF_Fs96000_Gain7_A2                            0.000000
-#define HPF_Fs96000_Gain7_B1                            -0.577350
+#define HPF_Fs96000_Gain7_B1                            (-0.577350)
 #define HPF_Fs96000_Gain7_B2                            0.000000
                                                                  /* Gain =  8.000000 dB */
 #define HPF_Fs96000_Gain8_A0                           2.192387
-#define HPF_Fs96000_Gain8_A1                           -1.769738
+#define HPF_Fs96000_Gain8_A1                           (-1.769738)
 #define HPF_Fs96000_Gain8_A2                           0.000000
-#define HPF_Fs96000_Gain8_B1                           -0.577350
+#define HPF_Fs96000_Gain8_B1                           (-0.577350)
 #define HPF_Fs96000_Gain8_B2                           0.000000
                                                                 /* Gain =  9.000000 dB */
 #define HPF_Fs96000_Gain9_A0                          2.434113
-#define HPF_Fs96000_Gain9_A1                          -2.011464
+#define HPF_Fs96000_Gain9_A1                          (-2.011464)
 #define HPF_Fs96000_Gain9_A2                          0.000000
-#define HPF_Fs96000_Gain9_B1                          -0.577350
+#define HPF_Fs96000_Gain9_B1                          (-0.577350)
 #define HPF_Fs96000_Gain9_B2                          0.000000
                                                                /* Gain =  10.000000 dB */
 #define HPF_Fs96000_Gain10_A0                        2.705335
-#define HPF_Fs96000_Gain10_A1                        -2.282685
+#define HPF_Fs96000_Gain10_A1                        (-2.282685)
 #define HPF_Fs96000_Gain10_A2                         0.000000
-#define HPF_Fs96000_Gain10_B1                         -0.577350
+#define HPF_Fs96000_Gain10_B1                         (-0.577350)
 #define HPF_Fs96000_Gain10_B2                         0.000000
                                                               /* Gain =  11.000000 dB */
 #define HPF_Fs96000_Gain11_A0                          3.009650
-#define HPF_Fs96000_Gain11_A1                          -2.587000
+#define HPF_Fs96000_Gain11_A1                          (-2.587000)
 #define HPF_Fs96000_Gain11_A2                          0.000000
-#define HPF_Fs96000_Gain11_B1                          -0.577350
+#define HPF_Fs96000_Gain11_B1                          (-0.577350)
 #define HPF_Fs96000_Gain11_B2                          0.000000
                                                                   /* Gain =  12.000000 dB */
 #define HPF_Fs96000_Gain12_A0                          3.351097
-#define HPF_Fs96000_Gain12_A1                          -2.928447
+#define HPF_Fs96000_Gain12_A1                          (-2.928447)
 #define HPF_Fs96000_Gain12_A2                          0.000000
-#define HPF_Fs96000_Gain12_B1                          -0.577350
+#define HPF_Fs96000_Gain12_B1                          (-0.577350)
 #define HPF_Fs96000_Gain12_B2                          0.000000
                                                                 /* Gain =  13.000000 dB */
 #define HPF_Fs96000_Gain13_A0                           3.734207
-#define HPF_Fs96000_Gain13_A1                           -3.311558
+#define HPF_Fs96000_Gain13_A1                           (-3.311558)
 #define HPF_Fs96000_Gain13_A2                           0.000000
-#define HPF_Fs96000_Gain13_B1                           -0.577350
+#define HPF_Fs96000_Gain13_B1                           (-0.577350)
 #define HPF_Fs96000_Gain13_B2                           0.000000
                                                                  /* Gain =  14.000000 dB */
 #define HPF_Fs96000_Gain14_A0                         4.164064
-#define HPF_Fs96000_Gain14_A1                         -3.741414
+#define HPF_Fs96000_Gain14_A1                         (-3.741414)
 #define HPF_Fs96000_Gain14_A2                          0.000000
-#define HPF_Fs96000_Gain14_B1                          -0.577350
+#define HPF_Fs96000_Gain14_B1                          (-0.577350)
 #define HPF_Fs96000_Gain14_B2                          0.000000
                                                                  /* Gain =  15.000000 dB */
 #define HPF_Fs96000_Gain15_A0                         4.646371
-#define HPF_Fs96000_Gain15_A1                         -4.223721
+#define HPF_Fs96000_Gain15_A1                         (-4.223721)
 #define HPF_Fs96000_Gain15_A2                         0.000000
-#define HPF_Fs96000_Gain15_B1                         -0.577350
+#define HPF_Fs96000_Gain15_B1                         (-0.577350)
 #define HPF_Fs96000_Gain15_B2                         0.000000
 
 /* Coefficients for sample rate 192000Hz */
                                                                   /* Gain =  1.000000 dB */
 #define HPF_Fs192000_Gain1_A0                          1.107823
-#define HPF_Fs192000_Gain1_A1                          -0.875150
+#define HPF_Fs192000_Gain1_A1                          (-0.875150)
 #define HPF_Fs192000_Gain1_A2                          0.000000
-#define HPF_Fs192000_Gain1_B1                          -0.767327
+#define HPF_Fs192000_Gain1_B1                          (-0.767327)
 #define HPF_Fs192000_Gain1_B2                          0.000000
                                                                   /* Gain =  2.000000 dB */
 #define HPF_Fs192000_Gain2_A0                          1.228803
-#define HPF_Fs192000_Gain2_A1                          -0.996130
+#define HPF_Fs192000_Gain2_A1                          (-0.996130)
 #define HPF_Fs192000_Gain2_A2                          0.000000
-#define HPF_Fs192000_Gain2_B1                          -0.767327
+#define HPF_Fs192000_Gain2_B1                          (-0.767327)
 #define HPF_Fs192000_Gain2_B2                          0.000000
                                                                    /* Gain =  3.000000 dB */
 #define HPF_Fs192000_Gain3_A0                          1.364544
-#define HPF_Fs192000_Gain3_A1                          -1.131871
+#define HPF_Fs192000_Gain3_A1                          (-1.131871)
 #define HPF_Fs192000_Gain3_A2                          0.000000
-#define HPF_Fs192000_Gain3_B1                          -0.767327
+#define HPF_Fs192000_Gain3_B1                          (-0.767327)
 #define HPF_Fs192000_Gain3_B2                          0.000000
                                                                    /* Gain =  4.000000 dB */
 #define HPF_Fs192000_Gain4_A0                          1.516849
-#define HPF_Fs192000_Gain4_A1                          -1.284176
+#define HPF_Fs192000_Gain4_A1                          (-1.284176)
 #define HPF_Fs192000_Gain4_A2                           0.000000
-#define HPF_Fs192000_Gain4_B1                           -0.767327
+#define HPF_Fs192000_Gain4_B1                           (-0.767327)
 #define HPF_Fs192000_Gain4_B2                           0.000000
                                                                    /* Gain =  5.000000 dB */
 #define HPF_Fs192000_Gain5_A0                           1.687737
-#define HPF_Fs192000_Gain5_A1                           -1.455064
+#define HPF_Fs192000_Gain5_A1                           (-1.455064)
 #define HPF_Fs192000_Gain5_A2                           0.000000
-#define HPF_Fs192000_Gain5_B1                           -0.767327
+#define HPF_Fs192000_Gain5_B1                           (-0.767327)
 #define HPF_Fs192000_Gain5_B2                           0.000000
                                                                    /* Gain =  6.000000 dB */
 #define HPF_Fs192000_Gain6_A0                            1.879477
-#define HPF_Fs192000_Gain6_A1                            -1.646804
+#define HPF_Fs192000_Gain6_A1                            (-1.646804)
 #define HPF_Fs192000_Gain6_A2                            0.000000
-#define HPF_Fs192000_Gain6_B1                            -0.767327
+#define HPF_Fs192000_Gain6_B1                            (-0.767327)
 #define HPF_Fs192000_Gain6_B2                            0.000000
                                                                  /* Gain =  7.000000 dB */
 #define HPF_Fs192000_Gain7_A0                            2.094613
-#define HPF_Fs192000_Gain7_A1                            -1.861940
+#define HPF_Fs192000_Gain7_A1                            (-1.861940)
 #define HPF_Fs192000_Gain7_A2                            0.000000
-#define HPF_Fs192000_Gain7_B1                            -0.767327
+#define HPF_Fs192000_Gain7_B1                            (-0.767327)
 #define HPF_Fs192000_Gain7_B2                            0.000000
                                                                    /* Gain =  8.000000 dB */
 #define HPF_Fs192000_Gain8_A0                           2.335999
-#define HPF_Fs192000_Gain8_A1                           -2.103326
+#define HPF_Fs192000_Gain8_A1                           (-2.103326)
 #define HPF_Fs192000_Gain8_A2                           0.000000
-#define HPF_Fs192000_Gain8_B1                           -0.767327
+#define HPF_Fs192000_Gain8_B1                           (-0.767327)
 #define HPF_Fs192000_Gain8_B2                           0.000000
                                                                    /* Gain =  9.000000 dB */
 #define HPF_Fs192000_Gain9_A0                          2.606839
-#define HPF_Fs192000_Gain9_A1                          -2.374166
+#define HPF_Fs192000_Gain9_A1                          (-2.374166)
 #define HPF_Fs192000_Gain9_A2                          0.000000
-#define HPF_Fs192000_Gain9_B1                          -0.767327
+#define HPF_Fs192000_Gain9_B1                          (-0.767327)
 #define HPF_Fs192000_Gain9_B2                          0.000000
                                                                  /* Gain =  10.000000 dB */
 #define HPF_Fs192000_Gain10_A0                        2.910726
-#define HPF_Fs192000_Gain10_A1                        -2.678053
+#define HPF_Fs192000_Gain10_A1                        (-2.678053)
 #define HPF_Fs192000_Gain10_A2                         0.000000
-#define HPF_Fs192000_Gain10_B1                         -0.767327
+#define HPF_Fs192000_Gain10_B1                         (-0.767327)
 #define HPF_Fs192000_Gain10_B2                         0.000000
                                                                   /* Gain =  11.000000 dB */
 #define HPF_Fs192000_Gain11_A0                          3.251693
-#define HPF_Fs192000_Gain11_A1                          -3.019020
+#define HPF_Fs192000_Gain11_A1                          (-3.019020)
 #define HPF_Fs192000_Gain11_A2                          0.000000
-#define HPF_Fs192000_Gain11_B1                          -0.767327
+#define HPF_Fs192000_Gain11_B1                          (-0.767327)
 #define HPF_Fs192000_Gain11_B2                          0.000000
                                                                   /* Gain =  12.000000 dB */
 #define HPF_Fs192000_Gain12_A0                          3.634264
-#define HPF_Fs192000_Gain12_A1                          -3.401591
+#define HPF_Fs192000_Gain12_A1                          (-3.401591)
 #define HPF_Fs192000_Gain12_A2                          0.000000
-#define HPF_Fs192000_Gain12_B1                          -0.767327
+#define HPF_Fs192000_Gain12_B1                          (-0.767327)
 #define HPF_Fs192000_Gain12_B2                          0.000000
                                                                 /* Gain =  13.000000 dB */
 #define HPF_Fs192000_Gain13_A0                           4.063516
-#define HPF_Fs192000_Gain13_A1                           -3.830843
+#define HPF_Fs192000_Gain13_A1                           (-3.830843)
 #define HPF_Fs192000_Gain13_A2                           0.000000
-#define HPF_Fs192000_Gain13_B1                           -0.767327
+#define HPF_Fs192000_Gain13_B1                           (-0.767327)
 #define HPF_Fs192000_Gain13_B2                           0.000000
                                                                 /* Gain =  14.000000 dB */
 #define HPF_Fs192000_Gain14_A0                          4.545145
-#define HPF_Fs192000_Gain14_A1                          -4.312472
+#define HPF_Fs192000_Gain14_A1                          (-4.312472)
 #define HPF_Fs192000_Gain14_A2                          0.000000
-#define HPF_Fs192000_Gain14_B1                          -0.767327
+#define HPF_Fs192000_Gain14_B1                          (-0.767327)
 #define HPF_Fs192000_Gain14_B2                          0.000000
                                                                   /* Gain =  15.000000 dB */
 #define HPF_Fs192000_Gain15_A0                         5.085542
-#define HPF_Fs192000_Gain15_A1                         -4.852868
+#define HPF_Fs192000_Gain15_A1                         (-4.852868)
 #define HPF_Fs192000_Gain15_A2                         0.000000
-#define HPF_Fs192000_Gain15_B1                         -0.767327
+#define HPF_Fs192000_Gain15_B1                         (-0.767327)
 #define HPF_Fs192000_Gain15_B2                         0.000000
 
 #endif
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
index f0deb6c..42ea46f 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
@@ -26,21 +26,21 @@
 /*                                                                                  */
 /************************************************************************************/
 #ifdef BUILD_FLOAT
-#define LVEQNB_Gain_Neg15_dB                             -0.822172f
-#define LVEQNB_Gain_Neg14_dB                             -0.800474f
-#define LVEQNB_Gain_Neg13_dB                             -0.776128f
-#define LVEQNB_Gain_Neg12_dB                             -0.748811f
-#define LVEQNB_Gain_Neg11_dB                             -0.718162f
-#define LVEQNB_Gain_Neg10_dB                             -0.683772f
-#define LVEQNB_Gain_Neg9_dB                              -0.645187f
-#define LVEQNB_Gain_Neg8_dB                              -0.601893f
-#define LVEQNB_Gain_Neg7_dB                              -0.553316f
-#define LVEQNB_Gain_Neg6_dB                              -0.498813f
-#define LVEQNB_Gain_Neg5_dB                              -0.437659f
-#define LVEQNB_Gain_Neg4_dB                              -0.369043f
-#define LVEQNB_Gain_Neg3_dB                              -0.292054f
-#define LVEQNB_Gain_Neg2_dB                              -0.205672f
-#define LVEQNB_Gain_Neg1_dB                              -0.108749f
+#define LVEQNB_Gain_Neg15_dB                             (-0.822172f)
+#define LVEQNB_Gain_Neg14_dB                             (-0.800474f)
+#define LVEQNB_Gain_Neg13_dB                             (-0.776128f)
+#define LVEQNB_Gain_Neg12_dB                             (-0.748811f)
+#define LVEQNB_Gain_Neg11_dB                             (-0.718162f)
+#define LVEQNB_Gain_Neg10_dB                             (-0.683772f)
+#define LVEQNB_Gain_Neg9_dB                              (-0.645187f)
+#define LVEQNB_Gain_Neg8_dB                              (-0.601893f)
+#define LVEQNB_Gain_Neg7_dB                              (-0.553316f)
+#define LVEQNB_Gain_Neg6_dB                              (-0.498813f)
+#define LVEQNB_Gain_Neg5_dB                              (-0.437659f)
+#define LVEQNB_Gain_Neg4_dB                              (-0.369043f)
+#define LVEQNB_Gain_Neg3_dB                              (-0.292054f)
+#define LVEQNB_Gain_Neg2_dB                              (-0.205672f)
+#define LVEQNB_Gain_Neg1_dB                              (-0.108749f)
 #define LVEQNB_Gain_0_dB                                  0.000000f
 #define LVEQNB_Gain_1_dB                                  0.122018f
 #define LVEQNB_Gain_2_dB                                  0.258925f
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h
index 4f5221a..0c2fe53 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h
@@ -27,127 +27,127 @@
 #ifdef BUILD_FLOAT
 /* Stereo Enhancer coefficients for 8000 Hz sample rate, scaled with 0.161258 */
 #define CS_MIDDLE_8000_A0                           0.227720
-#define CS_MIDDLE_8000_A1                          -0.215125
+#define CS_MIDDLE_8000_A1                          (-0.215125)
 #define CS_MIDDLE_8000_A2                           0.000000
-#define CS_MIDDLE_8000_B1                          -0.921899
+#define CS_MIDDLE_8000_B1                          (-0.921899)
 #define CS_MIDDLE_8000_B2                           0.000000
 #define CS_MIDDLE_8000_SCALE                        15
 #define CS_SIDE_8000_A0                             0.611441
-#define CS_SIDE_8000_A1                            -0.380344
-#define CS_SIDE_8000_A2                            -0.231097
-#define CS_SIDE_8000_B1                            -0.622470
-#define CS_SIDE_8000_B2                            -0.130759
+#define CS_SIDE_8000_A1                            (-0.380344)
+#define CS_SIDE_8000_A2                            (-0.231097)
+#define CS_SIDE_8000_B1                            (-0.622470)
+#define CS_SIDE_8000_B2                            (-0.130759)
 #define CS_SIDE_8000_SCALE                         15
 
 /* Stereo Enhancer coefficients for 11025Hz sample rate, scaled with 0.162943 */
 #define CS_MIDDLE_11025_A0                       0.230838
-#define CS_MIDDLE_11025_A1                      -0.221559
+#define CS_MIDDLE_11025_A1                      (-0.221559)
 #define CS_MIDDLE_11025_A2                       0.000000
-#define CS_MIDDLE_11025_B1                      -0.943056
+#define CS_MIDDLE_11025_B1                      (-0.943056)
 #define CS_MIDDLE_11025_B2                       0.000000
 #define CS_MIDDLE_11025_SCALE                    15
 #define CS_SIDE_11025_A0                         0.557372
-#define CS_SIDE_11025_A1                        -0.391490
-#define CS_SIDE_11025_A2                        -0.165881
-#define CS_SIDE_11025_B1                        -0.880608
+#define CS_SIDE_11025_A1                        (-0.391490)
+#define CS_SIDE_11025_A2                        (-0.165881)
+#define CS_SIDE_11025_B1                        (-0.880608)
 #define CS_SIDE_11025_B2                         0.032397
 #define CS_SIDE_11025_SCALE                      15
 
 /* Stereo Enhancer coefficients for 12000Hz sample rate, scaled with 0.162191 */
 #define CS_MIDDLE_12000_A0                        0.229932
-#define CS_MIDDLE_12000_A1                       -0.221436
+#define CS_MIDDLE_12000_A1                       (-0.221436)
 #define CS_MIDDLE_12000_A2                        0.000000
-#define CS_MIDDLE_12000_B1                       -0.947616
+#define CS_MIDDLE_12000_B1                       (-0.947616)
 #define CS_MIDDLE_12000_B2                        0.000000
 #define CS_MIDDLE_12000_SCALE                        15
 #define CS_SIDE_12000_A0                         0.558398
-#define CS_SIDE_12000_A1                        -0.392211
-#define CS_SIDE_12000_A2                        -0.166187
-#define CS_SIDE_12000_B1                        -0.892550
+#define CS_SIDE_12000_A1                        (-0.392211)
+#define CS_SIDE_12000_A2                        (-0.166187)
+#define CS_SIDE_12000_B1                        (-0.892550)
 #define CS_SIDE_12000_B2                         0.032856
 #define CS_SIDE_12000_SCALE                          15
 
 /* Stereo Enhancer coefficients for 16000Hz sample rate, scaled with 0.162371 */
 #define CS_MIDDLE_16000_A0                       0.230638
-#define CS_MIDDLE_16000_A1                      -0.224232
+#define CS_MIDDLE_16000_A1                      (-0.224232)
 #define CS_MIDDLE_16000_A2                       0.000000
-#define CS_MIDDLE_16000_B1                      -0.960550
+#define CS_MIDDLE_16000_B1                      (-0.960550)
 #define CS_MIDDLE_16000_B2                       0.000000
 #define CS_MIDDLE_16000_SCALE                        15
 #define CS_SIDE_16000_A0                         0.499695
-#define CS_SIDE_16000_A1                        -0.355543
-#define CS_SIDE_16000_A2                        -0.144152
-#define CS_SIDE_16000_B1                        -1.050788
+#define CS_SIDE_16000_A1                        (-0.355543)
+#define CS_SIDE_16000_A2                        (-0.144152)
+#define CS_SIDE_16000_B1                        (-1.050788)
 #define CS_SIDE_16000_B2                         0.144104
 #define CS_SIDE_16000_SCALE                          14
 
 /* Stereo Enhancer coefficients for 22050Hz sample rate, scaled with 0.160781 */
 #define CS_MIDDLE_22050_A0                       0.228749
-#define CS_MIDDLE_22050_A1                      -0.224128
+#define CS_MIDDLE_22050_A1                      (-0.224128)
 #define CS_MIDDLE_22050_A2                       0.000000
-#define CS_MIDDLE_22050_B1                      -0.971262
+#define CS_MIDDLE_22050_B1                      (-0.971262)
 #define CS_MIDDLE_22050_B2                       0.000000
 #define CS_MIDDLE_22050_SCALE                        15
 #define CS_SIDE_22050_A0                          0.440112
-#define CS_SIDE_22050_A1                         -0.261096
-#define CS_SIDE_22050_A2                         -0.179016
-#define CS_SIDE_22050_B1                         -1.116786
+#define CS_SIDE_22050_A1                         (-0.261096)
+#define CS_SIDE_22050_A2                         (-0.179016)
+#define CS_SIDE_22050_B1                         (-1.116786)
 #define CS_SIDE_22050_B2                          0.182507
 #define CS_SIDE_22050_SCALE                          14
 
 /* Stereo Enhancer coefficients for 24000Hz sample rate, scaled with 0.161882 */
 #define CS_MIDDLE_24000_A0                         0.230395
-#define CS_MIDDLE_24000_A1                        -0.226117
+#define CS_MIDDLE_24000_A1                        (-0.226117)
 #define CS_MIDDLE_24000_A2                         0.000000
-#define CS_MIDDLE_24000_B1                        -0.973573
+#define CS_MIDDLE_24000_B1                        (-0.973573)
 #define CS_MIDDLE_24000_B2                         0.000000
 #define CS_MIDDLE_24000_SCALE                        15
 #define CS_SIDE_24000_A0                           0.414770
-#define CS_SIDE_24000_A1                          -0.287182
-#define CS_SIDE_24000_A2                          -0.127588
-#define CS_SIDE_24000_B1                          -1.229648
+#define CS_SIDE_24000_A1                          (-0.287182)
+#define CS_SIDE_24000_A2                          (-0.127588)
+#define CS_SIDE_24000_B1                          (-1.229648)
 #define CS_SIDE_24000_B2                           0.282177
 #define CS_SIDE_24000_SCALE                          14
 
 /* Stereo Enhancer coefficients for 32000Hz sample rate, scaled with 0.160322 */
 #define CS_MIDDLE_32000_A0                          0.228400
-#define CS_MIDDLE_32000_A1                         -0.225214
+#define CS_MIDDLE_32000_A1                         (-0.225214)
 #define CS_MIDDLE_32000_A2                          0.000000
-#define CS_MIDDLE_32000_B1                         -0.980126
+#define CS_MIDDLE_32000_B1                         (-0.980126)
 #define CS_MIDDLE_32000_B2                          0.000000
 #define CS_MIDDLE_32000_SCALE                        15
 #define CS_SIDE_32000_A0                            0.364579
-#define CS_SIDE_32000_A1                           -0.207355
-#define CS_SIDE_32000_A2                           -0.157224
-#define CS_SIDE_32000_B1                           -1.274231
+#define CS_SIDE_32000_A1                           (-0.207355)
+#define CS_SIDE_32000_A2                           (-0.157224)
+#define CS_SIDE_32000_B1                           (-1.274231)
 #define CS_SIDE_32000_B2                            0.312495
 #define CS_SIDE_32000_SCALE                          14
 
 /* Stereo Enhancer coefficients for 44100Hz sample rate, scaled with 0.163834 */
 #define CS_MIDDLE_44100_A0                     0.233593
-#define CS_MIDDLE_44100_A1                    -0.231225
+#define CS_MIDDLE_44100_A1                    (-0.231225)
 #define CS_MIDDLE_44100_A2                     0.000000
-#define CS_MIDDLE_44100_B1                    -0.985545
+#define CS_MIDDLE_44100_B1                    (-0.985545)
 #define CS_MIDDLE_44100_B2                     0.000000
 #define CS_MIDDLE_44100_SCALE                        15
 #define CS_SIDE_44100_A0                       0.284573
-#define CS_SIDE_44100_A1                      -0.258910
-#define CS_SIDE_44100_A2                      -0.025662
-#define CS_SIDE_44100_B1                      -1.572248
+#define CS_SIDE_44100_A1                      (-0.258910)
+#define CS_SIDE_44100_A2                      (-0.025662)
+#define CS_SIDE_44100_B1                      (-1.572248)
 #define CS_SIDE_44100_B2                       0.588399
 #define CS_SIDE_44100_SCALE                  14
 
 /* Stereo Enhancer coefficients for 48000Hz sample rate, scaled with 0.164402 */
 #define CS_MIDDLE_48000_A0                     0.234445
-#define CS_MIDDLE_48000_A1                    -0.232261
+#define CS_MIDDLE_48000_A1                    (-0.232261)
 #define CS_MIDDLE_48000_A2                     0.000000
-#define CS_MIDDLE_48000_B1                    -0.986713
+#define CS_MIDDLE_48000_B1                    (-0.986713)
 #define CS_MIDDLE_48000_B2                     0.000000
 #define CS_MIDDLE_48000_SCALE                        15
 #define CS_SIDE_48000_A0                     0.272606
-#define CS_SIDE_48000_A1                    -0.266952
-#define CS_SIDE_48000_A2                    -0.005654
-#define CS_SIDE_48000_B1                    -1.617141
+#define CS_SIDE_48000_A1                    (-0.266952)
+#define CS_SIDE_48000_A2                    (-0.005654)
+#define CS_SIDE_48000_B1                    (-1.617141)
 #define CS_SIDE_48000_B2                     0.630405
 #define CS_SIDE_48000_SCALE                          14
 
@@ -155,31 +155,31 @@
 /* Stereo Enhancer coefficients for 96000Hz sample rate, scaled with  0.165*/
 /* high pass filter with cutoff frequency 102.18 Hz*/
 #define CS_MIDDLE_96000_A0                     0.235532
-#define CS_MIDDLE_96000_A1                    -0.234432
+#define CS_MIDDLE_96000_A1                    (-0.234432)
 #define CS_MIDDLE_96000_A2                     0.000000
-#define CS_MIDDLE_96000_B1                    -0.993334
+#define CS_MIDDLE_96000_B1                    (-0.993334)
 #define CS_MIDDLE_96000_B2                     0.000000
 #define CS_MIDDLE_96000_SCALE                        15
 /* bandpass filter with fc1 270 and fc2 3703, designed using 2nd order butterworth */
 #define CS_SIDE_96000_A0                     0.016727
 #define CS_SIDE_96000_A1                     0.000000
-#define CS_SIDE_96000_A2                    -0.016727
-#define CS_SIDE_96000_B1                    -1.793372
+#define CS_SIDE_96000_A2                    (-0.016727)
+#define CS_SIDE_96000_B1                    (-1.793372)
 #define CS_SIDE_96000_B2                     0.797236
 #define CS_SIDE_96000_SCALE                        14
 
 /* Stereo Enhancer coefficients for 192000Hz sample rate, scaled with  0.1689*/
 #define CS_MIDDLE_192000_A0                     0.241219
-#define CS_MIDDLE_192000_A1                    -0.240656
+#define CS_MIDDLE_192000_A1                    (-0.240656)
 #define CS_MIDDLE_192000_A2                     0.000000
-#define CS_MIDDLE_192000_B1                    -0.996661
+#define CS_MIDDLE_192000_B1                    (-0.996661)
 #define CS_MIDDLE_192000_B2                     0.000000
 #define CS_MIDDLE_192000_SCALE                        15
 /* bandpass filter with fc1 270 and fc2 3703, designed using 2nd order butterworth */
 #define CS_SIDE_192000_A0                     0.008991
-#define CS_SIDE_192000_A1                    -0.000000
-#define CS_SIDE_192000_A2                    -0.008991
-#define CS_SIDE_192000_B1                    -1.892509
+#define CS_SIDE_192000_A1                    (-0.000000)
+#define CS_SIDE_192000_A2                    (-0.008991)
+#define CS_SIDE_192000_B1                    (-1.892509)
 #define CS_SIDE_192000_B2                     0.893524
 #define CS_SIDE_192000_SCALE                       14
 #endif
@@ -203,74 +203,74 @@
 
 /* Reverb coefficients for 8000 Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_8000_A0                          0.667271
-#define CS_REVERB_8000_A1                         -0.667271
+#define CS_REVERB_8000_A1                         (-0.667271)
 #define CS_REVERB_8000_A2                          0.000000
-#define CS_REVERB_8000_B1                         -0.668179
+#define CS_REVERB_8000_B1                         (-0.668179)
 #define CS_REVERB_8000_B2                          0.000000
 #define CS_REVERB_8000_SCALE                         15
 
 /* Reverb coefficients for 11025Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_11025_A0                     0.699638
-#define CS_REVERB_11025_A1                    -0.699638
+#define CS_REVERB_11025_A1                    (-0.699638)
 #define CS_REVERB_11025_A2                     0.000000
-#define CS_REVERB_11025_B1                    -0.749096
+#define CS_REVERB_11025_B1                    (-0.749096)
 #define CS_REVERB_11025_B2                     0.000000
 #define CS_REVERB_11025_SCALE                  15
 
 /* Reverb coefficients for 12000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_12000_A0                   0.706931
-#define CS_REVERB_12000_A1                  -0.706931
+#define CS_REVERB_12000_A1                  (-0.706931)
 #define CS_REVERB_12000_A2                   0.000000
-#define CS_REVERB_12000_B1                  -0.767327
+#define CS_REVERB_12000_B1                  (-0.767327)
 #define CS_REVERB_12000_B2                   0.000000
 #define CS_REVERB_12000_SCALE                15
 
 /* Reverb coefficients for 16000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_16000_A0                      0.728272
-#define CS_REVERB_16000_A1                     -0.728272
+#define CS_REVERB_16000_A1                     (-0.728272)
 #define CS_REVERB_16000_A2                      0.000000
-#define CS_REVERB_16000_B1                     -0.820679
+#define CS_REVERB_16000_B1                     (-0.820679)
 #define CS_REVERB_16000_B2                      0.000000
 #define CS_REVERB_16000_SCALE                        15
 
 /* Reverb coefficients for 22050Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_22050_A0                     0.516396
 #define CS_REVERB_22050_A1                     0.000000
-#define CS_REVERB_22050_A2                    -0.516396
-#define CS_REVERB_22050_B1                    -0.518512
-#define CS_REVERB_22050_B2                    -0.290990
+#define CS_REVERB_22050_A2                    (-0.516396)
+#define CS_REVERB_22050_B1                    (-0.518512)
+#define CS_REVERB_22050_B2                    (-0.290990)
 #define CS_REVERB_22050_SCALE                        15
 
 
 /* Reverb coefficients for 24000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_24000_A0                       0.479565
 #define CS_REVERB_24000_A1                       0.000000
-#define CS_REVERB_24000_A2                      -0.479565
-#define CS_REVERB_24000_B1                      -0.637745
-#define CS_REVERB_24000_B2                      -0.198912
+#define CS_REVERB_24000_A2                      (-0.479565)
+#define CS_REVERB_24000_B1                      (-0.637745)
+#define CS_REVERB_24000_B2                      (-0.198912)
 #define CS_REVERB_24000_SCALE                        15
 
 /* Reverb coefficients for 32000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_32000_A0                      0.380349
 #define CS_REVERB_32000_A1                      0.000000
-#define CS_REVERB_32000_A2                     -0.380349
-#define CS_REVERB_32000_B1                     -0.950873
+#define CS_REVERB_32000_A2                     (-0.380349)
+#define CS_REVERB_32000_B1                     (-0.950873)
 #define CS_REVERB_32000_B2                      0.049127
 #define CS_REVERB_32000_SCALE                        15
 
 /* Reverb coefficients for 44100Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_44100_A0                         0.297389
 #define CS_REVERB_44100_A1                         0.000000
-#define CS_REVERB_44100_A2                        -0.297389
-#define CS_REVERB_44100_B1                        -1.200423
+#define CS_REVERB_44100_A2                        (-0.297389)
+#define CS_REVERB_44100_B1                        (-1.200423)
 #define CS_REVERB_44100_B2                         0.256529
 #define CS_REVERB_44100_SCALE                        14
 
 /* Reverb coefficients for 48000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_48000_A0                       0.278661
 #define CS_REVERB_48000_A1                       0.000000
-#define CS_REVERB_48000_A2                      -0.278661
-#define CS_REVERB_48000_B1                      -1.254993
+#define CS_REVERB_48000_A2                      (-0.278661)
+#define CS_REVERB_48000_B1                      (-1.254993)
 #define CS_REVERB_48000_B2                       0.303347
 #define CS_REVERB_48000_SCALE                        14
 
@@ -279,8 +279,8 @@
 /* Band pass filter with fc1=500 and fc2=8000*/
 #define CS_REVERB_96000_A0                       0.1602488
 #define CS_REVERB_96000_A1                       0.000000
-#define CS_REVERB_96000_A2                      -0.1602488
-#define CS_REVERB_96000_B1                      -1.585413
+#define CS_REVERB_96000_A2                      (-0.1602488)
+#define CS_REVERB_96000_B1                      (-1.585413)
 #define CS_REVERB_96000_B2                       0.599377
 #define CS_REVERB_96000_SCALE                        14
 
@@ -288,8 +288,8 @@
 /* Band pass filter with fc1=500 and fc2=8000*/
 #define CS_REVERB_192000_A0                       0.0878369
 #define CS_REVERB_192000_A1                       0.000000
-#define CS_REVERB_192000_A2                      -0.0878369
-#define CS_REVERB_192000_B1                      -1.7765764
+#define CS_REVERB_192000_A2                      (-0.0878369)
+#define CS_REVERB_192000_B1                      (-1.7765764)
 #define CS_REVERB_192000_B2                       0.7804076
 #define CS_REVERB_192000_SCALE                        14
 
@@ -312,163 +312,163 @@
 /* Equaliser coefficients for 8000 Hz sample rate, \
    CS scaled with 1.038497 and CSEX scaled with 0.775480 */
 #define CS_EQUALISER_8000_A0                     1.263312
-#define CS_EQUALISER_8000_A1                    -0.601748
-#define CS_EQUALISER_8000_A2                    -0.280681
-#define CS_EQUALISER_8000_B1                    -0.475865
-#define CS_EQUALISER_8000_B2                    -0.408154
+#define CS_EQUALISER_8000_A1                    (-0.601748)
+#define CS_EQUALISER_8000_A2                    (-0.280681)
+#define CS_EQUALISER_8000_B1                    (-0.475865)
+#define CS_EQUALISER_8000_B2                    (-0.408154)
 #define CS_EQUALISER_8000_SCALE                      14
 #define CSEX_EQUALISER_8000_A0                    0.943357
-#define CSEX_EQUALISER_8000_A1                   -0.449345
-#define CSEX_EQUALISER_8000_A2                   -0.209594
-#define CSEX_EQUALISER_8000_B1                   -0.475865
-#define CSEX_EQUALISER_8000_B2                   -0.408154
+#define CSEX_EQUALISER_8000_A1                   (-0.449345)
+#define CSEX_EQUALISER_8000_A2                   (-0.209594)
+#define CSEX_EQUALISER_8000_B1                   (-0.475865)
+#define CSEX_EQUALISER_8000_B2                   (-0.408154)
 #define CSEX_EQUALISER_8000_SCALE                    15
 
 /* Equaliser coefficients for 11025Hz sample rate, \
    CS scaled with 1.027761 and CSEX scaled with 0.767463 */
 #define CS_EQUALISER_11025_A0                    1.101145
 #define CS_EQUALISER_11025_A1                    0.139020
-#define CS_EQUALISER_11025_A2                   -0.864423
+#define CS_EQUALISER_11025_A2                   (-0.864423)
 #define CS_EQUALISER_11025_B1                    0.024541
-#define CS_EQUALISER_11025_B2                   -0.908930
+#define CS_EQUALISER_11025_B2                   (-0.908930)
 #define CS_EQUALISER_11025_SCALE                     14
 #define CSEX_EQUALISER_11025_A0                    0.976058
-#define CSEX_EQUALISER_11025_A1                   -0.695326
-#define CSEX_EQUALISER_11025_A2                   -0.090809
-#define CSEX_EQUALISER_11025_B1                   -0.610594
-#define CSEX_EQUALISER_11025_B2                   -0.311149
+#define CSEX_EQUALISER_11025_A1                   (-0.695326)
+#define CSEX_EQUALISER_11025_A2                   (-0.090809)
+#define CSEX_EQUALISER_11025_B1                   (-0.610594)
+#define CSEX_EQUALISER_11025_B2                   (-0.311149)
 #define CSEX_EQUALISER_11025_SCALE                   15
 
 /* Equaliser coefficients for 12000Hz sample rate, \
    CS scaled with 1.032521 and CSEX scaled with 0.771017 */
 #define CS_EQUALISER_12000_A0                      1.276661
-#define CS_EQUALISER_12000_A1                     -1.017519
-#define CS_EQUALISER_12000_A2                     -0.044128
-#define CS_EQUALISER_12000_B1                     -0.729616
-#define CS_EQUALISER_12000_B2                     -0.204532
+#define CS_EQUALISER_12000_A1                     (-1.017519)
+#define CS_EQUALISER_12000_A2                     (-0.044128)
+#define CS_EQUALISER_12000_B1                     (-0.729616)
+#define CS_EQUALISER_12000_B2                     (-0.204532)
 #define CS_EQUALISER_12000_SCALE                     14
 #define CSEX_EQUALISER_12000_A0                 1.007095
-#define CSEX_EQUALISER_12000_A1                -0.871912
+#define CSEX_EQUALISER_12000_A1                (-0.871912)
 #define CSEX_EQUALISER_12000_A2                 0.023232
-#define CSEX_EQUALISER_12000_B1                -0.745857
-#define CSEX_EQUALISER_12000_B2                -0.189171
+#define CSEX_EQUALISER_12000_B1                (-0.745857)
+#define CSEX_EQUALISER_12000_B2                (-0.189171)
 #define CSEX_EQUALISER_12000_SCALE                   14
 
 /* Equaliser coefficients for 16000Hz sample rate, \
    CS scaled with 1.031378 and CSEX scaled with 0.770164 */
 #define CS_EQUALISER_16000_A0                     1.281629
-#define CS_EQUALISER_16000_A1                    -1.075872
-#define CS_EQUALISER_16000_A2                    -0.041365
-#define CS_EQUALISER_16000_B1                    -0.725239
-#define CS_EQUALISER_16000_B2                    -0.224358
+#define CS_EQUALISER_16000_A1                    (-1.075872)
+#define CS_EQUALISER_16000_A2                    (-0.041365)
+#define CS_EQUALISER_16000_B1                    (-0.725239)
+#define CS_EQUALISER_16000_B2                    (-0.224358)
 #define CS_EQUALISER_16000_SCALE                     14
 #define CSEX_EQUALISER_16000_A0                  1.081091
-#define CSEX_EQUALISER_16000_A1                 -0.867183
-#define CSEX_EQUALISER_16000_A2                 -0.070247
-#define CSEX_EQUALISER_16000_B1                 -0.515121
-#define CSEX_EQUALISER_16000_B2                 -0.425893
+#define CSEX_EQUALISER_16000_A1                 (-0.867183)
+#define CSEX_EQUALISER_16000_A2                 (-0.070247)
+#define CSEX_EQUALISER_16000_B1                 (-0.515121)
+#define CSEX_EQUALISER_16000_B2                 (-0.425893)
 #define CSEX_EQUALISER_16000_SCALE                   14
 
 /* Equaliser coefficients for 22050Hz sample rate, \
    CS scaled with 1.041576 and CSEX scaled with 0.777779 */
 #define CS_EQUALISER_22050_A0                   1.388605
-#define CS_EQUALISER_22050_A1                  -1.305799
+#define CS_EQUALISER_22050_A1                  (-1.305799)
 #define CS_EQUALISER_22050_A2                   0.039922
-#define CS_EQUALISER_22050_B1                  -0.719494
-#define CS_EQUALISER_22050_B2                  -0.243245
+#define CS_EQUALISER_22050_B1                  (-0.719494)
+#define CS_EQUALISER_22050_B2                  (-0.243245)
 #define CS_EQUALISER_22050_SCALE                     14
 #define CSEX_EQUALISER_22050_A0                   1.272910
-#define CSEX_EQUALISER_22050_A1                  -1.341014
+#define CSEX_EQUALISER_22050_A1                  (-1.341014)
 #define CSEX_EQUALISER_22050_A2                   0.167462
-#define CSEX_EQUALISER_22050_B1                  -0.614219
-#define CSEX_EQUALISER_22050_B2                  -0.345384
+#define CSEX_EQUALISER_22050_B1                  (-0.614219)
+#define CSEX_EQUALISER_22050_B2                  (-0.345384)
 #define CSEX_EQUALISER_22050_SCALE                   14
 
 /* Equaliser coefficients for 24000Hz sample rate, \
    CS scaled with 1.034495 and CSEX scaled with 0.772491 */
 #define CS_EQUALISER_24000_A0                    1.409832
-#define CS_EQUALISER_24000_A1                   -1.456506
+#define CS_EQUALISER_24000_A1                   (-1.456506)
 #define CS_EQUALISER_24000_A2                    0.151410
-#define CS_EQUALISER_24000_B1                   -0.804201
-#define CS_EQUALISER_24000_B2                   -0.163783
+#define CS_EQUALISER_24000_B1                   (-0.804201)
+#define CS_EQUALISER_24000_B2                   (-0.163783)
 #define CS_EQUALISER_24000_SCALE                     14
 #define CSEX_EQUALISER_24000_A0                  1.299198
-#define CSEX_EQUALISER_24000_A1                 -1.452447
+#define CSEX_EQUALISER_24000_A1                 (-1.452447)
 #define CSEX_EQUALISER_24000_A2                  0.240489
-#define CSEX_EQUALISER_24000_B1                 -0.669303
-#define CSEX_EQUALISER_24000_B2                 -0.294984
+#define CSEX_EQUALISER_24000_B1                 (-0.669303)
+#define CSEX_EQUALISER_24000_B2                 (-0.294984)
 #define CSEX_EQUALISER_24000_SCALE                   14
 
 /* Equaliser coefficients for 32000Hz sample rate, \
    CS scaled with 1.044559 and CSEX scaled with 0.780006 */
 #define CS_EQUALISER_32000_A0                     1.560988
-#define CS_EQUALISER_32000_A1                    -1.877724
+#define CS_EQUALISER_32000_A1                    (-1.877724)
 #define CS_EQUALISER_32000_A2                     0.389741
-#define CS_EQUALISER_32000_B1                    -0.907410
-#define CS_EQUALISER_32000_B2                    -0.070489
+#define CS_EQUALISER_32000_B1                    (-0.907410)
+#define CS_EQUALISER_32000_B2                    (-0.070489)
 #define CS_EQUALISER_32000_SCALE                     14
 #define CSEX_EQUALISER_32000_A0                  1.785049
-#define CSEX_EQUALISER_32000_A1                 -2.233497
+#define CSEX_EQUALISER_32000_A1                 (-2.233497)
 #define CSEX_EQUALISER_32000_A2                  0.526431
-#define CSEX_EQUALISER_32000_B1                 -0.445939
-#define CSEX_EQUALISER_32000_B2                 -0.522446
+#define CSEX_EQUALISER_32000_B1                 (-0.445939)
+#define CSEX_EQUALISER_32000_B2                 (-0.522446)
 #define CSEX_EQUALISER_32000_SCALE                   13
 
 /* Equaliser coefficients for 44100Hz sample rate, \
    CS scaled with 1.022170 and CSEX scaled with 0.763288 */
 #define CS_EQUALISER_44100_A0                  1.623993
-#define CS_EQUALISER_44100_A1                 -2.270743
+#define CS_EQUALISER_44100_A1                 (-2.270743)
 #define CS_EQUALISER_44100_A2                  0.688829
-#define CS_EQUALISER_44100_B1                 -1.117190
+#define CS_EQUALISER_44100_B1                 (-1.117190)
 #define CS_EQUALISER_44100_B2                  0.130208
 #define CS_EQUALISER_44100_SCALE                     13
 #define CSEX_EQUALISER_44100_A0                   2.028315
-#define CSEX_EQUALISER_44100_A1                  -2.882459
+#define CSEX_EQUALISER_44100_A1                  (-2.882459)
 #define CSEX_EQUALISER_44100_A2                   0.904535
-#define CSEX_EQUALISER_44100_B1                  -0.593308
-#define CSEX_EQUALISER_44100_B2                  -0.385816
+#define CSEX_EQUALISER_44100_B1                  (-0.593308)
+#define CSEX_EQUALISER_44100_B2                  (-0.385816)
 #define CSEX_EQUALISER_44100_SCALE                   13
 
 /* Equaliser coefficients for 48000Hz sample rate, \
    CS scaled with 1.018635 and CSEX scaled with 0.760648 */
 #define CS_EQUALISER_48000_A0                    1.641177
-#define CS_EQUALISER_48000_A1                   -2.364687
+#define CS_EQUALISER_48000_A1                   (-2.364687)
 #define CS_EQUALISER_48000_A2                    0.759910
-#define CS_EQUALISER_48000_B1                   -1.166774
+#define CS_EQUALISER_48000_B1                   (-1.166774)
 #define CS_EQUALISER_48000_B2                    0.178074
 #define CS_EQUALISER_48000_SCALE                     13
 #define CSEX_EQUALISER_48000_A0                  2.099655
-#define CSEX_EQUALISER_48000_A1                 -3.065220
+#define CSEX_EQUALISER_48000_A1                 (-3.065220)
 #define CSEX_EQUALISER_48000_A2                  1.010417
-#define CSEX_EQUALISER_48000_B1                 -0.634021
-#define CSEX_EQUALISER_48000_B2                 -0.347332
+#define CSEX_EQUALISER_48000_B1                 (-0.634021)
+#define CSEX_EQUALISER_48000_B2                 (-0.347332)
 #define CSEX_EQUALISER_48000_SCALE                   13
 
 
 #ifdef HIGHER_FS
 #define CS_EQUALISER_96000_A0                    1.784497
-#define CS_EQUALISER_96000_A1                   -3.001435
+#define CS_EQUALISER_96000_A1                   (-3.001435)
 #define CS_EQUALISER_96000_A2                    1.228422
-#define CS_EQUALISER_96000_B1                   -1.477804
+#define CS_EQUALISER_96000_B1                   (-1.477804)
 #define CS_EQUALISER_96000_B2                    0.481369
 #define CS_EQUALISER_96000_SCALE                     13
 #define CSEX_EQUALISER_96000_A0                  2.7573
-#define CSEX_EQUALISER_96000_A1                 -4.6721
+#define CSEX_EQUALISER_96000_A1                 (-4.6721)
 #define CSEX_EQUALISER_96000_A2                  1.9317
-#define CSEX_EQUALISER_96000_B1                 -0.971718
-#define CSEX_EQUALISER_96000_B2                 -0.021216
+#define CSEX_EQUALISER_96000_B1                 (-0.971718)
+#define CSEX_EQUALISER_96000_B2                 (-0.021216)
 #define CSEX_EQUALISER_96000_SCALE                   13
 
 #define CS_EQUALISER_192000_A0                    1.889582
-#define CS_EQUALISER_192000_A1                   -3.456140
+#define CS_EQUALISER_192000_A1                   (-3.456140)
 #define CS_EQUALISER_192000_A2                    1.569864
-#define CS_EQUALISER_192000_B1                   -1.700798
+#define CS_EQUALISER_192000_B1                   (-1.700798)
 #define CS_EQUALISER_192000_B2                    0.701824
 #define CS_EQUALISER_192000_SCALE                     13
 #define CSEX_EQUALISER_192000_A0                  3.4273
-#define CSEX_EQUALISER_192000_A1                 -6.2936
+#define CSEX_EQUALISER_192000_A1                 (-6.2936)
 #define CSEX_EQUALISER_192000_A2                  2.8720
-#define CSEX_EQUALISER_192000_B1                 -1.31074
+#define CSEX_EQUALISER_192000_B1                 (-1.31074)
 #define CSEX_EQUALISER_192000_B2                 0.31312
 #define CSEX_EQUALISER_192000_SCALE                   13
 #endif
diff --git a/media/libmedia/Android.bp b/media/libmedia/Android.bp
index a462f3a..58ce17b 100644
--- a/media/libmedia/Android.bp
+++ b/media/libmedia/Android.bp
@@ -24,7 +24,7 @@
         "-Wno-error=deprecated-declarations",
         "-Wall",
     ],
-    shared_libs: ["libutils", "liblog", "libgui"],
+    shared_libs: ["libutils", "liblog"],
     header_libs: [
         "libmedia_headers",
         "libaudioclient_headers",
@@ -63,18 +63,13 @@
     },
 
     shared_libs: [
-        "android.hidl.memory@1.0",
         "android.hidl.token@1.0-utils",
         "android.hardware.media.omx@1.0",
-        "android.hardware.media@1.0",
-        "libbase",
         "libbinder",
         "libcutils",
         "libgui",
         "libhidlbase",
-        "libhidlmemory",
         "libhidltransport",
-        "libhwbinder",
         "liblog",
         "libstagefright_foundation",
         "libui",
@@ -82,11 +77,8 @@
     ],
 
     export_shared_lib_headers: [
-        "android.hidl.memory@1.0",
         "android.hidl.token@1.0-utils",
         "android.hardware.media.omx@1.0",
-        "android.hardware.media@1.0",
-        "libhidlmemory",
         "libstagefright_foundation",
         "libui",
     ],
@@ -137,7 +129,6 @@
 
     srcs: [
         "IDataSource.cpp",
-        "IHDCP.cpp",
         "BufferingSettings.cpp",
         "mediaplayer.cpp",
         "IMediaHTTPConnection.cpp",
@@ -190,27 +181,16 @@
         "libdl",
         "libaudioutils",
         "libaudioclient",
-        "libmedia_helper",
-        "libmediadrm",
-        "libmediametrics",
-        "libbase",
         "libhidlbase",
         "libhidltransport",
-        "libhwbinder",
-        "libhidlmemory",
-        "android.hidl.memory@1.0",
-        "android.hardware.graphics.common@1.0",
-        "android.hardware.graphics.bufferqueue@1.0",
     ],
 
     export_shared_lib_headers: [
+        "libaudioclient",
         "libbinder",
         "libicuuc",
         "libicui18n",
         "libsonivox",
-        "libmediadrm",
-        "libmedia_helper",
-        "android.hidl.memory@1.0",
     ],
 
     // for memory heap analysis
diff --git a/media/libmedia/IHDCP.cpp b/media/libmedia/IHDCP.cpp
deleted file mode 100644
index a46017f..0000000
--- a/media/libmedia/IHDCP.cpp
+++ /dev/null
@@ -1,359 +0,0 @@
-/*
- * Copyright (C) 2012 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 "IHDCP"
-#include <utils/Log.h>
-
-#include <binder/Parcel.h>
-#include <media/IHDCP.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/foundation/ADebug.h>
-
-namespace android {
-
-enum {
-    OBSERVER_NOTIFY = IBinder::FIRST_CALL_TRANSACTION,
-    HDCP_SET_OBSERVER,
-    HDCP_INIT_ASYNC,
-    HDCP_SHUTDOWN_ASYNC,
-    HDCP_GET_CAPS,
-    HDCP_ENCRYPT,
-    HDCP_ENCRYPT_NATIVE,
-    HDCP_DECRYPT,
-};
-
-struct BpHDCPObserver : public BpInterface<IHDCPObserver> {
-    explicit BpHDCPObserver(const sp<IBinder> &impl)
-        : BpInterface<IHDCPObserver>(impl) {
-    }
-
-    virtual void notify(
-            int msg, int ext1, int ext2, const Parcel *obj) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IHDCPObserver::getInterfaceDescriptor());
-        data.writeInt32(msg);
-        data.writeInt32(ext1);
-        data.writeInt32(ext2);
-        if (obj && obj->dataSize() > 0) {
-            data.appendFrom(const_cast<Parcel *>(obj), 0, obj->dataSize());
-        }
-        remote()->transact(OBSERVER_NOTIFY, data, &reply, IBinder::FLAG_ONEWAY);
-    }
-};
-
-IMPLEMENT_META_INTERFACE(HDCPObserver, "android.hardware.IHDCPObserver");
-
-struct BpHDCP : public BpInterface<IHDCP> {
-    explicit BpHDCP(const sp<IBinder> &impl)
-        : BpInterface<IHDCP>(impl) {
-    }
-
-    virtual status_t setObserver(const sp<IHDCPObserver> &observer) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IHDCP::getInterfaceDescriptor());
-        data.writeStrongBinder(IInterface::asBinder(observer));
-        remote()->transact(HDCP_SET_OBSERVER, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t initAsync(const char *host, unsigned port) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IHDCP::getInterfaceDescriptor());
-        data.writeCString(host);
-        data.writeInt32(port);
-        remote()->transact(HDCP_INIT_ASYNC, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t shutdownAsync() {
-        Parcel data, reply;
-        data.writeInterfaceToken(IHDCP::getInterfaceDescriptor());
-        remote()->transact(HDCP_SHUTDOWN_ASYNC, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual uint32_t getCaps() {
-        Parcel data, reply;
-        data.writeInterfaceToken(IHDCP::getInterfaceDescriptor());
-        remote()->transact(HDCP_GET_CAPS, data, &reply);
-        return reply.readInt32();
-    }
-
-    virtual status_t encrypt(
-            const void *inData, size_t size, uint32_t streamCTR,
-            uint64_t *outInputCTR, void *outData) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IHDCP::getInterfaceDescriptor());
-        data.writeInt32(size);
-        data.write(inData, size);
-        data.writeInt32(streamCTR);
-        remote()->transact(HDCP_ENCRYPT, data, &reply);
-
-        status_t err = reply.readInt32();
-
-        if (err != OK) {
-            *outInputCTR = 0;
-
-            return err;
-        }
-
-        *outInputCTR = reply.readInt64();
-        reply.read(outData, size);
-
-        return err;
-    }
-
-    virtual status_t encryptNative(
-            const sp<GraphicBuffer> &graphicBuffer,
-            size_t offset, size_t size, uint32_t streamCTR,
-            uint64_t *outInputCTR, void *outData) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IHDCP::getInterfaceDescriptor());
-        data.write(*graphicBuffer);
-        data.writeInt32(offset);
-        data.writeInt32(size);
-        data.writeInt32(streamCTR);
-        remote()->transact(HDCP_ENCRYPT_NATIVE, data, &reply);
-
-        status_t err = reply.readInt32();
-
-        if (err != OK) {
-            *outInputCTR = 0;
-            return err;
-        }
-
-        *outInputCTR = reply.readInt64();
-        reply.read(outData, size);
-
-        return err;
-    }
-
-    virtual status_t decrypt(
-            const void *inData, size_t size,
-            uint32_t streamCTR, uint64_t inputCTR,
-            void *outData) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IHDCP::getInterfaceDescriptor());
-        data.writeInt32(size);
-        data.write(inData, size);
-        data.writeInt32(streamCTR);
-        data.writeInt64(inputCTR);
-        remote()->transact(HDCP_DECRYPT, data, &reply);
-
-        status_t err = reply.readInt32();
-
-        if (err != OK) {
-            return err;
-        }
-
-        reply.read(outData, size);
-
-        return err;
-    }
-};
-
-IMPLEMENT_META_INTERFACE(HDCP, "android.hardware.IHDCP");
-
-status_t BnHDCPObserver::onTransact(
-        uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
-    switch (code) {
-        case OBSERVER_NOTIFY:
-        {
-            CHECK_INTERFACE(IHDCPObserver, data, reply);
-
-            int msg = data.readInt32();
-            int ext1 = data.readInt32();
-            int ext2 = data.readInt32();
-
-            Parcel obj;
-            if (data.dataAvail() > 0) {
-                obj.appendFrom(
-                        const_cast<Parcel *>(&data),
-                        data.dataPosition(),
-                        data.dataAvail());
-            }
-
-            notify(msg, ext1, ext2, &obj);
-
-            return OK;
-        }
-
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-status_t BnHDCP::onTransact(
-        uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
-    switch (code) {
-        case HDCP_SET_OBSERVER:
-        {
-            CHECK_INTERFACE(IHDCP, data, reply);
-
-            sp<IHDCPObserver> observer =
-                interface_cast<IHDCPObserver>(data.readStrongBinder());
-
-            reply->writeInt32(setObserver(observer));
-            return OK;
-        }
-
-        case HDCP_INIT_ASYNC:
-        {
-            CHECK_INTERFACE(IHDCP, data, reply);
-
-            const char *host = data.readCString();
-            unsigned port = data.readInt32();
-
-            reply->writeInt32(initAsync(host, port));
-            return OK;
-        }
-
-        case HDCP_SHUTDOWN_ASYNC:
-        {
-            CHECK_INTERFACE(IHDCP, data, reply);
-
-            reply->writeInt32(shutdownAsync());
-            return OK;
-        }
-
-        case HDCP_GET_CAPS:
-        {
-            CHECK_INTERFACE(IHDCP, data, reply);
-
-            reply->writeInt32(getCaps());
-            return OK;
-        }
-
-        case HDCP_ENCRYPT:
-        {
-            CHECK_INTERFACE(IHDCP, data, reply);
-
-            size_t size = data.readInt32();
-            void *inData = NULL;
-            // watch out for overflow
-            if (size <= SIZE_MAX / 2) {
-                inData = malloc(2 * size);
-            }
-            if (inData == NULL) {
-                reply->writeInt32(ERROR_OUT_OF_RANGE);
-                return OK;
-            }
-
-            void *outData = (uint8_t *)inData + size;
-
-            status_t err = data.read(inData, size);
-            if (err != OK) {
-                free(inData);
-                reply->writeInt32(err);
-                return OK;
-            }
-
-            uint32_t streamCTR = data.readInt32();
-            uint64_t inputCTR;
-            err = encrypt(inData, size, streamCTR, &inputCTR, outData);
-
-            reply->writeInt32(err);
-
-            if (err == OK) {
-                reply->writeInt64(inputCTR);
-                reply->write(outData, size);
-            }
-
-            free(inData);
-            inData = outData = NULL;
-
-            return OK;
-        }
-
-        case HDCP_ENCRYPT_NATIVE:
-        {
-            CHECK_INTERFACE(IHDCP, data, reply);
-
-            sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
-            data.read(*graphicBuffer);
-            size_t offset = data.readInt32();
-            size_t size = data.readInt32();
-            uint32_t streamCTR = data.readInt32();
-            void *outData = NULL;
-            uint64_t inputCTR;
-
-            status_t err = ERROR_OUT_OF_RANGE;
-
-            outData = malloc(size);
-
-            if (outData != NULL) {
-                err = encryptNative(graphicBuffer, offset, size,
-                                             streamCTR, &inputCTR, outData);
-            }
-
-            reply->writeInt32(err);
-
-            if (err == OK) {
-                reply->writeInt64(inputCTR);
-                reply->write(outData, size);
-            }
-
-            free(outData);
-            outData = NULL;
-
-            return OK;
-        }
-
-        case HDCP_DECRYPT:
-        {
-            CHECK_INTERFACE(IHDCP, data, reply);
-
-            size_t size = data.readInt32();
-            size_t bufSize = 2 * size;
-
-            // watch out for overflow
-            void *inData = NULL;
-            if (bufSize > size) {
-                inData = malloc(bufSize);
-            }
-
-            if (inData == NULL) {
-                reply->writeInt32(ERROR_OUT_OF_RANGE);
-                return OK;
-            }
-
-            void *outData = (uint8_t *)inData + size;
-
-            data.read(inData, size);
-
-            uint32_t streamCTR = data.readInt32();
-            uint64_t inputCTR = data.readInt64();
-            status_t err = decrypt(inData, size, streamCTR, inputCTR, outData);
-
-            reply->writeInt32(err);
-
-            if (err == OK) {
-                reply->write(outData, size);
-            }
-
-            free(inData);
-            inData = outData = NULL;
-
-            return OK;
-        }
-
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-}  // namespace android
diff --git a/media/libmedia/IMediaPlayer.cpp b/media/libmedia/IMediaPlayer.cpp
index 3996227..903e503 100644
--- a/media/libmedia/IMediaPlayer.cpp
+++ b/media/libmedia/IMediaPlayer.cpp
@@ -35,6 +35,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 enum {
     DISCONNECT = IBinder::FIRST_CALL_TRANSACTION,
     SET_DATA_SOURCE_URL,
@@ -56,6 +58,7 @@
     GET_CURRENT_POSITION,
     GET_DURATION,
     RESET,
+    NOTIFY_AT,
     SET_AUDIO_STREAM_TYPE,
     SET_LOOPING,
     SET_VOLUME,
@@ -326,6 +329,15 @@
         return reply.readInt32();
     }
 
+    status_t notifyAt(int64_t mediaTimeUs)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IMediaPlayer::getInterfaceDescriptor());
+        data.writeInt64(mediaTimeUs);
+        remote()->transact(NOTIFY_AT, data, &reply);
+        return reply.readInt32();
+    }
+
     status_t setAudioStreamType(audio_stream_type_t stream)
     {
         Parcel data, reply;
@@ -509,7 +521,7 @@
             return nullptr;
         }
         sp<VolumeShaper::State> state = new VolumeShaper::State();
-        status = state->readFromParcel(reply);
+        status = state->readFromParcel(&reply);
         if (status != NO_ERROR) {
             return nullptr;
         }
@@ -744,6 +756,11 @@
             reply->writeInt32(reset());
             return NO_ERROR;
         } break;
+        case NOTIFY_AT: {
+            CHECK_INTERFACE(IMediaPlayer, data, reply);
+            reply->writeInt32(notifyAt(data.readInt64()));
+            return NO_ERROR;
+        } break;
         case SET_AUDIO_STREAM_TYPE: {
             CHECK_INTERFACE(IMediaPlayer, data, reply);
             reply->writeInt32(setAudioStreamType((audio_stream_type_t) data.readInt32()));
@@ -851,14 +868,14 @@
             status_t status = data.readInt32(&present);
             if (status == NO_ERROR && present != 0) {
                 configuration = new VolumeShaper::Configuration();
-                status = configuration->readFromParcel(data);
+                status = configuration->readFromParcel(&data);
             }
             if (status == NO_ERROR) {
                 status = data.readInt32(&present);
             }
             if (status == NO_ERROR && present != 0) {
                 operation = new VolumeShaper::Operation();
-                status = operation->readFromParcel(data);
+                status = operation->readFromParcel(&data);
             }
             if (status == NO_ERROR) {
                 status = (status_t)applyVolumeShaper(configuration, operation);
diff --git a/media/libmedia/IMediaPlayerService.cpp b/media/libmedia/IMediaPlayerService.cpp
index a01852c..d135878 100644
--- a/media/libmedia/IMediaPlayerService.cpp
+++ b/media/libmedia/IMediaPlayerService.cpp
@@ -20,7 +20,6 @@
 
 #include <binder/Parcel.h>
 #include <binder/IMemory.h>
-#include <media/IHDCP.h>
 #include <media/IMediaCodecList.h>
 #include <media/IMediaHTTPService.h>
 #include <media/IMediaPlayerService.h>
@@ -40,7 +39,6 @@
     CREATE_MEDIA_RECORDER,
     CREATE_METADATA_RETRIEVER,
     GET_OMX,
-    MAKE_HDCP,
     ADD_BATTERY_DATA,
     PULL_BATTERY_DATA,
     LISTEN_FOR_REMOTE_DISPLAY,
@@ -90,14 +88,6 @@
         return interface_cast<IOMX>(reply.readStrongBinder());
     }
 
-    virtual sp<IHDCP> makeHDCP(bool createEncryptionModule) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor());
-        data.writeInt32(createEncryptionModule);
-        remote()->transact(MAKE_HDCP, data, &reply);
-        return interface_cast<IHDCP>(reply.readStrongBinder());
-    }
-
     virtual void addBatteryData(uint32_t params) {
         Parcel data, reply;
         data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor());
@@ -167,13 +157,6 @@
             reply->writeStrongBinder(IInterface::asBinder(omx));
             return NO_ERROR;
         } break;
-        case MAKE_HDCP: {
-            CHECK_INTERFACE(IMediaPlayerService, data, reply);
-            bool createEncryptionModule = data.readInt32();
-            sp<IHDCP> hdcp = makeHDCP(createEncryptionModule);
-            reply->writeStrongBinder(IInterface::asBinder(hdcp));
-            return NO_ERROR;
-        } break;
         case ADD_BATTERY_DATA: {
             CHECK_INTERFACE(IMediaPlayerService, data, reply);
             uint32_t params = data.readInt32();
diff --git a/media/libmedia/include/media/IHDCP.h b/media/libmedia/include/media/IHDCP.h
deleted file mode 100644
index 352561e..0000000
--- a/media/libmedia/include/media/IHDCP.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2012 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 <binder/IInterface.h>
-#include <media/hardware/HDCPAPI.h>
-#include <media/stagefright/foundation/ABase.h>
-#include <ui/GraphicBuffer.h>
-
-namespace android {
-
-struct IHDCPObserver : public IInterface {
-    DECLARE_META_INTERFACE(HDCPObserver);
-
-    virtual void notify(
-            int msg, int ext1, int ext2, const Parcel *obj) = 0;
-
-private:
-    DISALLOW_EVIL_CONSTRUCTORS(IHDCPObserver);
-};
-
-struct IHDCP : public IInterface {
-    DECLARE_META_INTERFACE(HDCP);
-
-    // Called to specify the observer that receives asynchronous notifications
-    // from the HDCP implementation to signal completion/failure of asynchronous
-    // operations (such as initialization) or out of band events.
-    virtual status_t setObserver(const sp<IHDCPObserver> &observer) = 0;
-
-    // Request to setup an HDCP session with the specified host listening
-    // on the specified port.
-    virtual status_t initAsync(const char *host, unsigned port) = 0;
-
-    // Request to shutdown the active HDCP session.
-    virtual status_t shutdownAsync() = 0;
-
-    // Returns the capability bitmask of this HDCP session.
-    // Possible return values (please refer to HDCAPAPI.h):
-    //   HDCP_CAPS_ENCRYPT: mandatory, meaning the HDCP module can encrypt
-    //   from an input byte-array buffer to an output byte-array buffer
-    //   HDCP_CAPS_ENCRYPT_NATIVE: the HDCP module supports encryption from
-    //   a native buffer to an output byte-array buffer. The format of the
-    //   input native buffer is specific to vendor's encoder implementation.
-    //   It is the same format as that used by the encoder when
-    //   "storeMetaDataInBuffers" extension is enabled on its output port.
-    virtual uint32_t getCaps() = 0;
-
-    // ENCRYPTION only:
-    // Encrypt data according to the HDCP spec. "size" bytes of data are
-    // available at "inData" (virtual address), "size" may not be a multiple
-    // of 128 bits (16 bytes). An equal number of encrypted bytes should be
-    // written to the buffer at "outData" (virtual address).
-    // This operation is to be synchronous, i.e. this call does not return
-    // until outData contains size bytes of encrypted data.
-    // streamCTR will be assigned by the caller (to 0 for the first PES stream,
-    // 1 for the second and so on)
-    // inputCTR _will_be_maintained_by_the_callee_ for each PES stream.
-    virtual status_t encrypt(
-            const void *inData, size_t size, uint32_t streamCTR,
-            uint64_t *outInputCTR, void *outData) = 0;
-
-    // Encrypt data according to the HDCP spec. "size" bytes of data starting
-    // at location "offset" are available in "buffer" (buffer handle). "size"
-    // may not be a multiple of 128 bits (16 bytes). An equal number of
-    // encrypted bytes should be written to the buffer at "outData" (virtual
-    // address). This operation is to be synchronous, i.e. this call does not
-    // return until outData contains size bytes of encrypted data.
-    // streamCTR will be assigned by the caller (to 0 for the first PES stream,
-    // 1 for the second and so on)
-    // inputCTR _will_be_maintained_by_the_callee_ for each PES stream.
-    virtual status_t encryptNative(
-            const sp<GraphicBuffer> &graphicBuffer,
-            size_t offset, size_t size, uint32_t streamCTR,
-            uint64_t *outInputCTR, void *outData) = 0;
-
-    // DECRYPTION only:
-    // Decrypt data according to the HDCP spec.
-    // "size" bytes of encrypted data are available at "inData"
-    // (virtual address), "size" may not be a multiple of 128 bits (16 bytes).
-    // An equal number of decrypted bytes should be written to the buffer
-    // at "outData" (virtual address).
-    // This operation is to be synchronous, i.e. this call does not return
-    // until outData contains size bytes of decrypted data.
-    // Both streamCTR and inputCTR will be provided by the caller.
-    virtual status_t decrypt(
-            const void *inData, size_t size,
-            uint32_t streamCTR, uint64_t inputCTR,
-            void *outData) = 0;
-
-private:
-    DISALLOW_EVIL_CONSTRUCTORS(IHDCP);
-};
-
-struct BnHDCPObserver : public BnInterface<IHDCPObserver> {
-    virtual status_t onTransact(
-            uint32_t code, const Parcel &data, Parcel *reply,
-            uint32_t flags = 0);
-};
-
-struct BnHDCP : public BnInterface<IHDCP> {
-    virtual status_t onTransact(
-            uint32_t code, const Parcel &data, Parcel *reply,
-            uint32_t flags = 0);
-};
-
-}  // namespace android
-
-
diff --git a/media/libmedia/include/media/IMediaPlayer.h b/media/libmedia/include/media/IMediaPlayer.h
index e5a98dd..e181338 100644
--- a/media/libmedia/include/media/IMediaPlayer.h
+++ b/media/libmedia/include/media/IMediaPlayer.h
@@ -79,6 +79,7 @@
             MediaPlayerSeekMode mode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC) = 0;
     virtual status_t        getCurrentPosition(int* msec) = 0;
     virtual status_t        getDuration(int* msec) = 0;
+    virtual status_t        notifyAt(int64_t mediaTimeUs) = 0;
     virtual status_t        reset() = 0;
     virtual status_t        setAudioStreamType(audio_stream_type_t type) = 0;
     virtual status_t        setLooping(int loop) = 0;
@@ -91,10 +92,10 @@
     virtual status_t        getRetransmitEndpoint(struct sockaddr_in* endpoint) = 0;
     virtual status_t        setNextPlayer(const sp<IMediaPlayer>& next) = 0;
 
-    virtual VolumeShaper::Status applyVolumeShaper(
-                                    const sp<VolumeShaper::Configuration>& configuration,
-                                    const sp<VolumeShaper::Operation>& operation) = 0;
-    virtual sp<VolumeShaper::State> getVolumeShaperState(int id) = 0;
+    virtual media::VolumeShaper::Status applyVolumeShaper(
+                                    const sp<media::VolumeShaper::Configuration>& configuration,
+                                    const sp<media::VolumeShaper::Operation>& operation) = 0;
+    virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) = 0;
 
     // Modular DRM
     virtual status_t        prepareDrm(const uint8_t uuid[16],
diff --git a/media/libmedia/include/media/IMediaPlayerService.h b/media/libmedia/include/media/IMediaPlayerService.h
index f21bb3a..398a8c7 100644
--- a/media/libmedia/include/media/IMediaPlayerService.h
+++ b/media/libmedia/include/media/IMediaPlayerService.h
@@ -31,7 +31,6 @@
 
 namespace android {
 
-struct IHDCP;
 class IMediaCodecList;
 struct IMediaHTTPService;
 class IMediaRecorder;
@@ -50,7 +49,6 @@
     virtual sp<IMediaPlayer> create(const sp<IMediaPlayerClient>& client,
             audio_session_t audioSessionId = AUDIO_SESSION_ALLOCATE) = 0;
     virtual sp<IOMX>            getOMX() = 0;
-    virtual sp<IHDCP>           makeHDCP(bool createEncryptionModule) = 0;
     virtual sp<IMediaCodecList> getCodecList() const = 0;
 
     // Connects to a remote display.
diff --git a/media/libmedia/include/media/mediaplayer.h b/media/libmedia/include/media/mediaplayer.h
index 623c374..25741d3 100644
--- a/media/libmedia/include/media/mediaplayer.h
+++ b/media/libmedia/include/media/mediaplayer.h
@@ -50,6 +50,7 @@
     MEDIA_PAUSED            = 7,
     MEDIA_STOPPED           = 8,
     MEDIA_SKIPPED           = 9,
+    MEDIA_NOTIFY_TIME       = 98,
     MEDIA_TIMED_TEXT        = 99,
     MEDIA_ERROR             = 100,
     MEDIA_INFO              = 200,
@@ -245,6 +246,7 @@
             status_t        seekTo(
                     int msec,
                     MediaPlayerSeekMode mode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC);
+            status_t        notifyAt(int64_t mediaTimeUs);
             status_t        getCurrentPosition(int *msec);
             status_t        getDuration(int *msec);
             status_t        reset();
@@ -266,10 +268,10 @@
             status_t        setRetransmitEndpoint(const char* addrString, uint16_t port);
             status_t        setNextMediaPlayer(const sp<MediaPlayer>& player);
 
-            VolumeShaper::Status applyVolumeShaper(
-                                    const sp<VolumeShaper::Configuration>& configuration,
-                                    const sp<VolumeShaper::Operation>& operation);
-            sp<VolumeShaper::State> getVolumeShaperState(int id);
+            media::VolumeShaper::Status applyVolumeShaper(
+                                    const sp<media::VolumeShaper::Configuration>& configuration,
+                                    const sp<media::VolumeShaper::Operation>& operation);
+            sp<media::VolumeShaper::State> getVolumeShaperState(int id);
             // Modular DRM
             status_t        prepareDrm(const uint8_t uuid[16], const Vector<uint8_t>& drmSessionId);
             status_t        releaseDrm();
diff --git a/media/libmedia/include/media/omx/1.0/Conversion.h b/media/libmedia/include/media/omx/1.0/Conversion.h
index 9816fe1..94f2e8d 100644
--- a/media/libmedia/include/media/omx/1.0/Conversion.h
+++ b/media/libmedia/include/media/omx/1.0/Conversion.h
@@ -24,7 +24,6 @@
 
 #include <hidl/MQDescriptor.h>
 #include <hidl/Status.h>
-#include <hidlmemory/mapping.h>
 
 #include <binder/Binder.h>
 #include <binder/Status.h>
@@ -36,7 +35,6 @@
 #include <media/OMXBuffer.h>
 #include <media/hardware/VideoAPI.h>
 
-#include <android/hidl/memory/1.0/IMemory.h>
 #include <android/hardware/media/omx/1.0/types.h>
 #include <android/hardware/media/omx/1.0/IOmx.h>
 #include <android/hardware/media/omx/1.0/IOmxNode.h>
diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp
index b976721..00084c1 100644
--- a/media/libmedia/mediaplayer.cpp
+++ b/media/libmedia/mediaplayer.cpp
@@ -48,6 +48,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 MediaPlayer::MediaPlayer()
 {
     ALOGV("constructor");
@@ -608,6 +610,15 @@
     return result;
 }
 
+status_t MediaPlayer::notifyAt(int64_t mediaTimeUs)
+{
+    Mutex::Autolock _l(mLock);
+    if (mPlayer != 0) {
+        return mPlayer->notifyAt(mediaTimeUs);
+    }
+    return INVALID_OPERATION;
+}
+
 status_t MediaPlayer::reset_l()
 {
     mLoop = false;
@@ -649,8 +660,12 @@
 status_t MediaPlayer::reset()
 {
     ALOGV("reset");
+    mLockThreadId = getThreadId();
     Mutex::Autolock _l(mLock);
-    return reset_l();
+    status_t result = reset_l();
+    mLockThreadId = 0;
+
+    return result;
 }
 
 status_t MediaPlayer::setAudioStreamType(audio_stream_type_t type)
@@ -860,7 +875,7 @@
     // this will deadlock.
     //
     // The threadId hack below works around this for the care of prepare,
-    // seekTo and start within the same process.
+    // seekTo, start, and reset within the same process.
     // FIXME: Remember, this is a hack, it's not even a hack that is applied
     // consistently for all use-cases, this needs to be revisited.
     if (mLockThreadId != getThreadId()) {
@@ -944,6 +959,9 @@
         mVideoWidth = ext1;
         mVideoHeight = ext2;
         break;
+    case MEDIA_NOTIFY_TIME:
+        ALOGV("Received notify time message");
+        break;
     case MEDIA_TIMED_TEXT:
         ALOGV("Received timed text message");
         break;
diff --git a/media/libmediaplayerservice/Android.mk b/media/libmediaplayerservice/Android.mk
index 1fc74a9..11066b2 100644
--- a/media/libmediaplayerservice/Android.mk
+++ b/media/libmediaplayerservice/Android.mk
@@ -8,12 +8,10 @@
 
 LOCAL_SRC_FILES:=               \
     ActivityManager.cpp         \
-    HDCP.cpp                    \
     MediaPlayerFactory.cpp      \
     MediaPlayerService.cpp      \
     MediaRecorderClient.cpp     \
     MetadataRetrieverClient.cpp \
-    RemoteDisplay.cpp           \
     StagefrightRecorder.cpp     \
     TestPlayerStub.cpp          \
 
@@ -21,7 +19,6 @@
     libbinder                   \
     libcrypto                   \
     libcutils                   \
-    libdrmframework             \
     liblog                      \
     libdl                       \
     libgui                      \
@@ -35,10 +32,9 @@
     libstagefright_foundation   \
     libstagefright_httplive     \
     libstagefright_omx          \
-    libstagefright_wfd          \
     libutils                    \
-    libnativewindow             \
     libhidlbase                 \
+    libhidlmemory               \
     android.hardware.media.omx@1.0 \
 
 LOCAL_STATIC_LIBRARIES :=       \
@@ -51,7 +47,6 @@
 LOCAL_C_INCLUDES :=                                                 \
     frameworks/av/media/libstagefright/include               \
     frameworks/av/media/libstagefright/rtsp                  \
-    frameworks/av/media/libstagefright/wifi-display          \
     frameworks/av/media/libstagefright/webm                  \
     $(LOCAL_PATH)/include/media                              \
     frameworks/av/include/camera                             \
diff --git a/media/libmediaplayerservice/HDCP.cpp b/media/libmediaplayerservice/HDCP.cpp
deleted file mode 100644
index afe3936..0000000
--- a/media/libmediaplayerservice/HDCP.cpp
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2012 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 "HDCP"
-#include <utils/Log.h>
-
-#include "HDCP.h"
-
-#include <media/stagefright/foundation/ADebug.h>
-
-#include <dlfcn.h>
-
-namespace android {
-
-HDCP::HDCP(bool createEncryptionModule)
-    : mIsEncryptionModule(createEncryptionModule),
-      mLibHandle(NULL),
-      mHDCPModule(NULL) {
-    mLibHandle = dlopen("libstagefright_hdcp.so", RTLD_NOW);
-
-    if (mLibHandle == NULL) {
-        ALOGE("Unable to locate libstagefright_hdcp.so");
-        return;
-    }
-
-    typedef HDCPModule *(*CreateHDCPModuleFunc)(
-            void *, HDCPModule::ObserverFunc);
-
-    CreateHDCPModuleFunc createHDCPModule =
-        mIsEncryptionModule
-            ? (CreateHDCPModuleFunc)dlsym(mLibHandle, "createHDCPModule")
-            : (CreateHDCPModuleFunc)dlsym(
-                    mLibHandle, "createHDCPModuleForDecryption");
-
-    if (createHDCPModule == NULL) {
-        ALOGE("Unable to find symbol 'createHDCPModule'.");
-    } else if ((mHDCPModule = createHDCPModule(
-                    this, &HDCP::ObserveWrapper)) == NULL) {
-        ALOGE("createHDCPModule failed.");
-    }
-}
-
-HDCP::~HDCP() {
-    Mutex::Autolock autoLock(mLock);
-
-    if (mHDCPModule != NULL) {
-        delete mHDCPModule;
-        mHDCPModule = NULL;
-    }
-
-    if (mLibHandle != NULL) {
-        dlclose(mLibHandle);
-        mLibHandle = NULL;
-    }
-}
-
-status_t HDCP::setObserver(const sp<IHDCPObserver> &observer) {
-    Mutex::Autolock autoLock(mLock);
-
-    if (mHDCPModule == NULL) {
-        return NO_INIT;
-    }
-
-    mObserver = observer;
-
-    return OK;
-}
-
-status_t HDCP::initAsync(const char *host, unsigned port) {
-    Mutex::Autolock autoLock(mLock);
-
-    if (mHDCPModule == NULL) {
-        return NO_INIT;
-    }
-
-    return mHDCPModule->initAsync(host, port);
-}
-
-status_t HDCP::shutdownAsync() {
-    Mutex::Autolock autoLock(mLock);
-
-    if (mHDCPModule == NULL) {
-        return NO_INIT;
-    }
-
-    return mHDCPModule->shutdownAsync();
-}
-
-uint32_t HDCP::getCaps() {
-    Mutex::Autolock autoLock(mLock);
-
-    if (mHDCPModule == NULL) {
-        return NO_INIT;
-    }
-
-    return mHDCPModule->getCaps();
-}
-
-status_t HDCP::encrypt(
-        const void *inData, size_t size, uint32_t streamCTR,
-        uint64_t *outInputCTR, void *outData) {
-    Mutex::Autolock autoLock(mLock);
-
-    CHECK(mIsEncryptionModule);
-
-    if (mHDCPModule == NULL) {
-        *outInputCTR = 0;
-
-        return NO_INIT;
-    }
-
-    return mHDCPModule->encrypt(inData, size, streamCTR, outInputCTR, outData);
-}
-
-status_t HDCP::encryptNative(
-        const sp<GraphicBuffer> &graphicBuffer,
-        size_t offset, size_t size, uint32_t streamCTR,
-        uint64_t *outInputCTR, void *outData) {
-    Mutex::Autolock autoLock(mLock);
-
-    CHECK(mIsEncryptionModule);
-
-    if (mHDCPModule == NULL) {
-        *outInputCTR = 0;
-
-        return NO_INIT;
-    }
-
-    return mHDCPModule->encryptNative(graphicBuffer->handle,
-                    offset, size, streamCTR, outInputCTR, outData);
-}
-
-status_t HDCP::decrypt(
-        const void *inData, size_t size,
-        uint32_t streamCTR, uint64_t outInputCTR, void *outData) {
-    Mutex::Autolock autoLock(mLock);
-
-    CHECK(!mIsEncryptionModule);
-
-    if (mHDCPModule == NULL) {
-        return NO_INIT;
-    }
-
-    return mHDCPModule->decrypt(inData, size, streamCTR, outInputCTR, outData);
-}
-
-// static
-void HDCP::ObserveWrapper(void *me, int msg, int ext1, int ext2) {
-    static_cast<HDCP *>(me)->observe(msg, ext1, ext2);
-}
-
-void HDCP::observe(int msg, int ext1, int ext2) {
-    Mutex::Autolock autoLock(mLock);
-
-    if (mObserver != NULL) {
-        mObserver->notify(msg, ext1, ext2, NULL /* obj */);
-    }
-}
-
-}  // namespace android
-
diff --git a/media/libmediaplayerservice/HDCP.h b/media/libmediaplayerservice/HDCP.h
deleted file mode 100644
index 83c61b5..0000000
--- a/media/libmediaplayerservice/HDCP.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2012 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 HDCP_H_
-
-#define HDCP_H_
-
-#include <media/IHDCP.h>
-#include <utils/Mutex.h>
-
-namespace android {
-
-struct HDCP : public BnHDCP {
-    explicit HDCP(bool createEncryptionModule);
-    virtual ~HDCP();
-
-    virtual status_t setObserver(const sp<IHDCPObserver> &observer);
-    virtual status_t initAsync(const char *host, unsigned port);
-    virtual status_t shutdownAsync();
-    virtual uint32_t getCaps();
-
-    virtual status_t encrypt(
-            const void *inData, size_t size, uint32_t streamCTR,
-            uint64_t *outInputCTR, void *outData);
-
-    virtual status_t encryptNative(
-            const sp<GraphicBuffer> &graphicBuffer,
-            size_t offset, size_t size, uint32_t streamCTR,
-            uint64_t *outInputCTR, void *outData);
-
-    virtual status_t decrypt(
-            const void *inData, size_t size,
-            uint32_t streamCTR, uint64_t outInputCTR, void *outData);
-
-private:
-    Mutex mLock;
-
-    bool mIsEncryptionModule;
-
-    void *mLibHandle;
-    HDCPModule *mHDCPModule;
-    sp<IHDCPObserver> mObserver;
-
-    static void ObserveWrapper(void *me, int msg, int ext1, int ext2);
-    void observe(int msg, int ext1, int ext2);
-
-    DISALLOW_EVIL_CONSTRUCTORS(HDCP);
-};
-
-}  // namespace android
-
-#endif  // HDCP_H_
-
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index 496db0d..44ab5da 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -79,9 +79,7 @@
 
 #include <media/stagefright/omx/OMX.h>
 
-#include "HDCP.h"
 #include "HTTPBase.h"
-#include "RemoteDisplay.h"
 
 static const int kDumpLockRetries = 50;
 static const int kDumpLockSleepUs = 20000;
@@ -93,6 +91,7 @@
 using android::BAD_VALUE;
 using android::NOT_ENOUGH_DATA;
 using android::Parcel;
+using android::media::VolumeShaper;
 
 // Max number of entries in the filter.
 const int kMaxFilterSize = 64;  // I pulled that out of thin air.
@@ -348,18 +347,13 @@
     return mOMX;
 }
 
-sp<IHDCP> MediaPlayerService::makeHDCP(bool createEncryptionModule) {
-    return new HDCP(createEncryptionModule);
-}
-
 sp<IRemoteDisplay> MediaPlayerService::listenForRemoteDisplay(
-        const String16 &opPackageName,
-        const sp<IRemoteDisplayClient>& client, const String8& iface) {
-    if (!checkPermission("android.permission.CONTROL_WIFI_DISPLAY")) {
-        return NULL;
-    }
+        const String16 &/*opPackageName*/,
+        const sp<IRemoteDisplayClient>& /*client*/,
+        const String8& /*iface*/) {
+    ALOGE("listenForRemoteDisplay is no longer supported!");
 
-    return new RemoteDisplay(opPackageName, client, iface.string());
+    return NULL;
 }
 
 status_t MediaPlayerService::AudioOutput::dump(int fd, const Vector<String16>& args) const
@@ -1268,6 +1262,14 @@
     return p->reset();
 }
 
+status_t MediaPlayerService::Client::notifyAt(int64_t mediaTimeUs)
+{
+    ALOGV("[%d] notifyAt(%lld)", mConnId, (long long)mediaTimeUs);
+    sp<MediaPlayerBase> p = getPlayer();
+    if (p == 0) return UNKNOWN_ERROR;
+    return p->notifyAt(mediaTimeUs);
+}
+
 status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
 {
     ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
@@ -1577,7 +1579,7 @@
       mSendLevel(0.0),
       mAuxEffectId(0),
       mFlags(AUDIO_OUTPUT_FLAG_NONE),
-      mVolumeHandler(new VolumeHandler())
+      mVolumeHandler(new media::VolumeHandler())
 {
     ALOGV("AudioOutput(%d)", sessionId);
     if (attr != NULL) {
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index 06b9cad..d62dd52 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -132,10 +132,10 @@
         virtual status_t        setParameters(const String8& keyValuePairs);
         virtual String8         getParameters(const String8& keys);
 
-        virtual VolumeShaper::Status applyVolumeShaper(
-                                        const sp<VolumeShaper::Configuration>& configuration,
-                                        const sp<VolumeShaper::Operation>& operation) override;
-        virtual sp<VolumeShaper::State> getVolumeShaperState(int id) override;
+        virtual media::VolumeShaper::Status applyVolumeShaper(
+                                        const sp<media::VolumeShaper::Configuration>& configuration,
+                                        const sp<media::VolumeShaper::Operation>& operation) override;
+        virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
 
     private:
         static void             setMinBufferCount();
@@ -165,7 +165,7 @@
         float                   mSendLevel;
         int                     mAuxEffectId;
         audio_output_flags_t    mFlags;
-        sp<VolumeHandler>       mVolumeHandler;
+        sp<media::VolumeHandler>       mVolumeHandler;
         mutable Mutex           mLock;
 
         // static variables below not protected by mutex
@@ -229,7 +229,6 @@
 
     virtual sp<IMediaCodecList> getCodecList() const;
     virtual sp<IOMX>            getOMX();
-    virtual sp<IHDCP>           makeHDCP(bool createEncryptionModule);
 
     virtual sp<IRemoteDisplay> listenForRemoteDisplay(const String16 &opPackageName,
             const sp<IRemoteDisplayClient>& client, const String8& iface);
@@ -327,6 +326,7 @@
         virtual status_t        getCurrentPosition(int* msec);
         virtual status_t        getDuration(int* msec);
         virtual status_t        reset();
+        virtual status_t        notifyAt(int64_t mediaTimeUs);
         virtual status_t        setAudioStreamType(audio_stream_type_t type);
         virtual status_t        setLooping(int loop);
         virtual status_t        setVolume(float leftVolume, float rightVolume);
@@ -343,10 +343,10 @@
         virtual status_t        getRetransmitEndpoint(struct sockaddr_in* endpoint);
         virtual status_t        setNextPlayer(const sp<IMediaPlayer>& player);
 
-        virtual VolumeShaper::Status applyVolumeShaper(
-                                        const sp<VolumeShaper::Configuration>& configuration,
-                                        const sp<VolumeShaper::Operation>& operation) override;
-        virtual sp<VolumeShaper::State> getVolumeShaperState(int id) override;
+        virtual media::VolumeShaper::Status applyVolumeShaper(
+                                        const sp<media::VolumeShaper::Configuration>& configuration,
+                                        const sp<media::VolumeShaper::Operation>& operation) override;
+        virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
 
         sp<MediaPlayerBase>     createPlayer(player_type playerType);
 
diff --git a/media/libmediaplayerservice/RemoteDisplay.cpp b/media/libmediaplayerservice/RemoteDisplay.cpp
deleted file mode 100644
index 0eb4b5d..0000000
--- a/media/libmediaplayerservice/RemoteDisplay.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright 2012, 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 "RemoteDisplay.h"
-
-#include "source/WifiDisplaySource.h"
-
-#include <media/IRemoteDisplayClient.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/foundation/ANetworkSession.h>
-
-namespace android {
-
-RemoteDisplay::RemoteDisplay(
-        const String16 &opPackageName,
-        const sp<IRemoteDisplayClient> &client,
-        const char *iface)
-    : mLooper(new ALooper),
-      mNetSession(new ANetworkSession) {
-    mLooper->setName("wfd_looper");
-
-    mSource = new WifiDisplaySource(opPackageName, mNetSession, client);
-    mLooper->registerHandler(mSource);
-
-    mNetSession->start();
-    mLooper->start();
-
-    mSource->start(iface);
-}
-
-RemoteDisplay::~RemoteDisplay() {
-}
-
-status_t RemoteDisplay::pause() {
-    return mSource->pause();
-}
-
-status_t RemoteDisplay::resume() {
-    return mSource->resume();
-}
-
-status_t RemoteDisplay::dispose() {
-    mSource->stop();
-    mSource.clear();
-
-    mLooper->stop();
-    mNetSession->stop();
-
-    return OK;
-}
-
-}  // namespace android
diff --git a/media/libmediaplayerservice/RemoteDisplay.h b/media/libmediaplayerservice/RemoteDisplay.h
deleted file mode 100644
index d4573e9..0000000
--- a/media/libmediaplayerservice/RemoteDisplay.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright 2012, 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 REMOTE_DISPLAY_H_
-
-#define REMOTE_DISPLAY_H_
-
-#include <media/IMediaPlayerService.h>
-#include <media/IRemoteDisplay.h>
-#include <media/stagefright/foundation/ABase.h>
-#include <utils/Errors.h>
-#include <utils/RefBase.h>
-
-namespace android {
-
-struct ALooper;
-struct ANetworkSession;
-class IRemoteDisplayClient;
-struct WifiDisplaySource;
-
-struct RemoteDisplay : public BnRemoteDisplay {
-    RemoteDisplay(
-            const String16 &opPackageName,
-            const sp<IRemoteDisplayClient> &client,
-            const char *iface);
-
-    virtual status_t pause();
-    virtual status_t resume();
-    virtual status_t dispose();
-
-protected:
-    virtual ~RemoteDisplay();
-
-private:
-    sp<ALooper> mNetLooper;
-    sp<ALooper> mLooper;
-    sp<ANetworkSession> mNetSession;
-    sp<WifiDisplaySource> mSource;
-
-    DISALLOW_EVIL_CONSTRUCTORS(RemoteDisplay);
-};
-
-}  // namespace android
-
-#endif  // REMOTE_DISPLAY_H_
-
diff --git a/media/libmediaplayerservice/include/MediaPlayerInterface.h b/media/libmediaplayerservice/include/MediaPlayerInterface.h
index e8d59a7..764df70 100644
--- a/media/libmediaplayerservice/include/MediaPlayerInterface.h
+++ b/media/libmediaplayerservice/include/MediaPlayerInterface.h
@@ -146,10 +146,10 @@
         virtual status_t    setParameters(const String8& /* keyValuePairs */) { return NO_ERROR; }
         virtual String8     getParameters(const String8& /* keys */) { return String8::empty(); }
 
-        virtual VolumeShaper::Status applyVolumeShaper(
-                                    const sp<VolumeShaper::Configuration>& configuration,
-                                    const sp<VolumeShaper::Operation>& operation);
-        virtual sp<VolumeShaper::State> getVolumeShaperState(int id);
+        virtual media::VolumeShaper::Status applyVolumeShaper(
+                                    const sp<media::VolumeShaper::Configuration>& configuration,
+                                    const sp<media::VolumeShaper::Operation>& operation);
+        virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id);
     };
 
                         MediaPlayerBase() : mCookie(0), mNotify(0) {}
@@ -225,6 +225,9 @@
     virtual status_t    getCurrentPosition(int *msec) = 0;
     virtual status_t    getDuration(int *msec) = 0;
     virtual status_t    reset() = 0;
+    virtual status_t    notifyAt(int64_t /* mediaTimeUs */) {
+        return INVALID_OPERATION;
+    }
     virtual status_t    setLooping(int loop) = 0;
     virtual player_type playerType() = 0;
     virtual status_t    setParameter(int key, const Parcel &request) = 0;
diff --git a/media/libmediaplayerservice/nuplayer/GenericSource.cpp b/media/libmediaplayerservice/nuplayer/GenericSource.cpp
index aa21fff..45a5f27 100644
--- a/media/libmediaplayerservice/nuplayer/GenericSource.cpp
+++ b/media/libmediaplayerservice/nuplayer/GenericSource.cpp
@@ -31,6 +31,7 @@
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/FileSource.h>
 #include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaClock.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MediaExtractor.h>
 #include <media/stagefright/MediaSource.h>
@@ -51,7 +52,8 @@
 NuPlayer::GenericSource::GenericSource(
         const sp<AMessage> &notify,
         bool uidValid,
-        uid_t uid)
+        uid_t uid,
+        const sp<MediaClock> &mediaClock)
     : Source(notify),
       mAudioTimeUs(0),
       mAudioLastDequeueTimeUs(0),
@@ -65,10 +67,12 @@
       mIsStreaming(false),
       mUIDValid(uidValid),
       mUID(uid),
+      mMediaClock(mediaClock),
       mFd(-1),
       mBitrate(-1ll),
       mPendingReadBufferTypes(0) {
     ALOGV("GenericSource");
+    CHECK(mediaClock != NULL);
 
     mBufferingMonitor = new BufferingMonitor(notify);
     resetDataSource();
@@ -729,17 +733,20 @@
     int64_t timeUs;
     CHECK(msg->findInt64("timeUs", &timeUs));
 
-    int64_t subTimeUs;
+    int64_t subTimeUs = 0;
     readBuffer(type, timeUs, MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC /* mode */, &subTimeUs);
 
-    int64_t delayUs = subTimeUs - timeUs;
+    status_t eosResult;
+    if (!packets->hasBufferAvailable(&eosResult)) {
+        return;
+    }
+
     if (msg->what() == kWhatFetchSubtitleData) {
-        const int64_t oneSecUs = 1000000ll;
-        delayUs -= oneSecUs;
+        subTimeUs -= 1000000ll;  // send subtile data one second earlier
     }
     sp<AMessage> msg2 = new AMessage(sendWhat, this);
     msg2->setInt32("generation", msgGeneration);
-    msg2->post(delayUs < 0 ? 0 : delayUs);
+    mMediaClock->addTimer(msg2, subTimeUs);
 }
 
 void NuPlayer::GenericSource::sendTextData(
@@ -771,8 +778,10 @@
         notify->setBuffer("buffer", buffer);
         notify->post();
 
-        const int64_t delayUs = nextSubTimeUs - subTimeUs;
-        msg->post(delayUs < 0 ? 0 : delayUs);
+        if (msg->what() == kWhatSendSubtitleData) {
+            nextSubTimeUs -= 1000000ll;  // send subtile data one second earlier
+        }
+        mMediaClock->addTimer(msg, nextSubTimeUs);
     }
 }
 
@@ -847,10 +856,6 @@
 
 status_t NuPlayer::GenericSource::dequeueAccessUnit(
         bool audio, sp<ABuffer> *accessUnit) {
-    if (audio && !mStarted) {
-        return -EWOULDBLOCK;
-    }
-
     // If has gone through stop/releaseDrm sequence, we no longer send down any buffer b/c
     // the codec's crypto object has gone away (b/37960096).
     // Note: This will be unnecessary when stop() changes behavior and releases codec (b/35248283).
@@ -1238,7 +1243,7 @@
     }
 
     if (mAudioTrack.mSource != NULL) {
-        readBuffer(MEDIA_TRACK_TYPE_AUDIO, seekTimeUs);
+        readBuffer(MEDIA_TRACK_TYPE_AUDIO, seekTimeUs, MediaPlayerSeekMode::SEEK_CLOSEST);
         mAudioLastDequeueTimeUs = seekTimeUs;
     }
 
diff --git a/media/libmediaplayerservice/nuplayer/GenericSource.h b/media/libmediaplayerservice/nuplayer/GenericSource.h
index 4064133..381bcac 100644
--- a/media/libmediaplayerservice/nuplayer/GenericSource.h
+++ b/media/libmediaplayerservice/nuplayer/GenericSource.h
@@ -35,12 +35,14 @@
 struct IMediaHTTPService;
 struct MediaSource;
 class MediaBuffer;
+struct MediaClock;
 struct NuCachedSource2;
 
 struct NuPlayer::GenericSource : public NuPlayer::Source,
                                  public MediaBufferObserver // Modular DRM
 {
-    GenericSource(const sp<AMessage> &notify, bool uidValid, uid_t uid);
+    GenericSource(const sp<AMessage> &notify, bool uidValid, uid_t uid,
+                  const sp<MediaClock> &mediaClock);
 
     status_t setDataSource(
             const sp<IMediaHTTPService> &httpService,
@@ -227,6 +229,7 @@
     bool mIsStreaming;
     bool mUIDValid;
     uid_t mUID;
+    const sp<MediaClock> mMediaClock;
     sp<IMediaHTTPService> mHTTPService;
     AString mUri;
     KeyedVector<String8, String8> mUriHeaders;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index df36046..29b1781 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -49,6 +49,7 @@
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/AMessage.h>
 #include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaClock.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/MetaData.h>
@@ -172,9 +173,10 @@
 
 ////////////////////////////////////////////////////////////////////////////////
 
-NuPlayer::NuPlayer(pid_t pid)
+NuPlayer::NuPlayer(pid_t pid, const sp<MediaClock> &mediaClock)
     : mUIDValid(false),
       mPID(pid),
+      mMediaClock(mediaClock),
       mSourceFlags(0),
       mOffloadAudio(false),
       mAudioDecoderGeneration(0),
@@ -204,6 +206,7 @@
       mPausedForBuffering(false),
       mIsDrmProtected(false),
       mDataSourceType(DATA_SOURCE_TYPE_NONE) {
+    CHECK(mediaClock != NULL);
     clearFlushComplete();
 }
 
@@ -278,7 +281,7 @@
         ALOGV("setDataSourceAsync GenericSource %s", url);
 
         sp<GenericSource> genericSource =
-                new GenericSource(notify, mUIDValid, mUID);
+                new GenericSource(notify, mUIDValid, mUID, mMediaClock);
 
         status_t err = genericSource->setDataSource(httpService, url, headers);
 
@@ -301,7 +304,7 @@
     sp<AMessage> notify = new AMessage(kWhatSourceNotify, this);
 
     sp<GenericSource> source =
-            new GenericSource(notify, mUIDValid, mUID);
+            new GenericSource(notify, mUIDValid, mUID, mMediaClock);
 
     ALOGV("setDataSourceAsync fd %d/%lld/%lld source: %p",
             fd, (long long)offset, (long long)length, source.get());
@@ -322,7 +325,7 @@
     sp<AMessage> msg = new AMessage(kWhatSetDataSource, this);
     sp<AMessage> notify = new AMessage(kWhatSourceNotify, this);
 
-    sp<GenericSource> source = new GenericSource(notify, mUIDValid, mUID);
+    sp<GenericSource> source = new GenericSource(notify, mUIDValid, mUID, mMediaClock);
     status_t err = source->setDataSource(dataSource);
 
     if (err != OK) {
@@ -470,6 +473,13 @@
     (new AMessage(kWhatReset, this))->post();
 }
 
+status_t NuPlayer::notifyAt(int64_t mediaTimeUs) {
+    sp<AMessage> notify = new AMessage(kWhatNotifyTime, this);
+    notify->setInt64("timerUs", mediaTimeUs);
+    mMediaClock->addTimer(notify, mediaTimeUs);
+    return OK;
+}
+
 void NuPlayer::seekToAsync(int64_t seekTimeUs, MediaPlayerSeekMode mode, bool needNotify) {
     sp<AMessage> msg = new AMessage(kWhatSeek, this);
     msg->setInt64("seekTimeUs", seekTimeUs);
@@ -1312,6 +1322,16 @@
             break;
         }
 
+        case kWhatNotifyTime:
+        {
+            ALOGV("kWhatNotifyTime");
+            int64_t timerUs;
+            CHECK(msg->findInt64("timerUs", &timerUs));
+
+            notifyListener(MEDIA_NOTIFY_TIME, timerUs, 0);
+            break;
+        }
+
         case kWhatSeek:
         {
             int64_t seekTimeUs;
@@ -1523,7 +1543,7 @@
     sp<AMessage> notify = new AMessage(kWhatRendererNotify, this);
     ++mRendererGeneration;
     notify->setInt32("generation", mRendererGeneration);
-    mRenderer = new Renderer(mAudioSink, notify, flags);
+    mRenderer = new Renderer(mAudioSink, mMediaClock, notify, flags);
     mRendererLooper = new ALooper;
     mRendererLooper->setName("NuPlayerRenderer");
     mRendererLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.h b/media/libmediaplayerservice/nuplayer/NuPlayer.h
index c69835f..eefc2a6 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.h
@@ -30,11 +30,12 @@
 struct AudioPlaybackRate;
 struct AVSyncSettings;
 class IDataSource;
+struct MediaClock;
 class MetaData;
 struct NuPlayerDriver;
 
 struct NuPlayer : public AHandler {
-    explicit NuPlayer(pid_t pid);
+    explicit NuPlayer(pid_t pid, const sp<MediaClock> &mediaClock);
 
     void setUID(uid_t uid);
 
@@ -72,6 +73,9 @@
     // Will notify the driver through "notifyResetComplete" once finished.
     void resetAsync();
 
+    // Request a notification when specified media time is reached.
+    status_t notifyAt(int64_t mediaTimeUs);
+
     // Will notify the driver through "notifySeekComplete" once finished
     // and needNotify is true.
     void seekToAsync(
@@ -139,6 +143,7 @@
         kWhatClosedCaptionNotify        = 'capN',
         kWhatRendererNotify             = 'renN',
         kWhatReset                      = 'rset',
+        kWhatNotifyTime                 = 'nfyT',
         kWhatSeek                       = 'seek',
         kWhatPause                      = 'paus',
         kWhatResume                     = 'rsme',
@@ -157,6 +162,7 @@
     bool mUIDValid;
     uid_t mUID;
     pid_t mPID;
+    const sp<MediaClock> mMediaClock;
     Mutex mSourceLock;  // guard |mSource|.
     sp<Source> mSource;
     uint32_t mSourceFlags;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
index ac187cc..cd770b6 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
@@ -750,12 +750,20 @@
 
         buffer->meta()->setInt32("eos", true);
         reply->setInt32("eos", true);
-    } else if (mSkipRenderingUntilMediaTimeUs >= 0) {
+    }
+
+    if (mSkipRenderingUntilMediaTimeUs >= 0) {
         if (timeUs < mSkipRenderingUntilMediaTimeUs) {
             ALOGV("[%s] dropping buffer at time %lld as requested.",
                      mComponentName.c_str(), (long long)timeUs);
 
             reply->post();
+            if (eos) {
+                notifyResumeCompleteIfNecessary();
+                if (mRenderer != NULL && !isDiscontinuityPending()) {
+                    mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
+                }
+            }
             return true;
         }
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
index dc29761..4005be8 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
@@ -28,6 +28,7 @@
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/ALooper.h>
 #include <media/stagefright/foundation/AUtils.h>
+#include <media/stagefright/MediaClock.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/Utils.h>
 
@@ -66,7 +67,8 @@
       mSeekInProgress(false),
       mPlayingTimeUs(0),
       mLooper(new ALooper),
-      mPlayer(new NuPlayer(pid)),
+      mMediaClock(new MediaClock),
+      mPlayer(new NuPlayer(pid, mMediaClock)),
       mPlayerFlags(0),
       mAnalyticsItem(NULL),
       mClientUid(-1),
@@ -76,6 +78,8 @@
     ALOGD("NuPlayerDriver(%p) created, clientPid(%d)", this, pid);
     mLooper->setName("NuPlayerDriver Looper");
 
+    mMediaClock->init();
+
     // set up an analytics record
     mAnalyticsItem = new MediaAnalyticsItem(kKeyPlayer);
     mAnalyticsItem->generateSessionID();
@@ -660,6 +664,11 @@
     return OK;
 }
 
+status_t NuPlayerDriver::notifyAt(int64_t mediaTimeUs) {
+    ALOGV("notifyAt(%p), time:%lld", this, (long long)mediaTimeUs);
+    return mPlayer->notifyAt(mediaTimeUs);
+}
+
 status_t NuPlayerDriver::setLooping(int loop) {
     mLooping = loop != 0;
     return OK;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h
index d0cf1dd..666359a 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h
@@ -22,6 +22,7 @@
 namespace android {
 
 struct ALooper;
+struct MediaClock;
 struct NuPlayer;
 
 struct NuPlayerDriver : public MediaPlayerInterface {
@@ -64,6 +65,7 @@
     virtual status_t getCurrentPosition(int *msec);
     virtual status_t getDuration(int *msec);
     virtual status_t reset();
+    virtual status_t notifyAt(int64_t mediaTimeUs) override;
     virtual status_t setLooping(int loop);
     virtual player_type playerType();
     virtual status_t invoke(const Parcel &request, Parcel *reply);
@@ -127,6 +129,7 @@
     // <<<
 
     sp<ALooper> mLooper;
+    const sp<MediaClock> mMediaClock;
     const sp<NuPlayer> mPlayer;
     sp<AudioSink> mAudioSink;
     uint32_t mPlayerFlags;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
index bd866cb..50db4c9 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
@@ -89,6 +89,7 @@
 
 NuPlayer::Renderer::Renderer(
         const sp<MediaPlayerBase::AudioSink> &sink,
+        const sp<MediaClock> &mediaClock,
         const sp<AMessage> &notify,
         uint32_t flags)
     : mAudioSink(sink),
@@ -103,6 +104,7 @@
       mAudioDrainGeneration(0),
       mVideoDrainGeneration(0),
       mAudioEOSGeneration(0),
+      mMediaClock(mediaClock),
       mPlaybackSettings(AUDIO_PLAYBACK_RATE_DEFAULT),
       mAudioFirstAnchorTimeMediaUs(-1),
       mAnchorTimeMediaUs(-1),
@@ -130,7 +132,7 @@
       mLastAudioBufferDrained(0),
       mUseAudioCallback(false),
       mWakeLock(new AWakeLock()) {
-    mMediaClock = new MediaClock;
+    CHECK(mediaClock != NULL);
     mPlaybackRate = mPlaybackSettings.mSpeed;
     mMediaClock->setPlaybackRate(mPlaybackRate);
 }
@@ -149,7 +151,6 @@
         flushQueue(&mVideoQueue);
     }
     mWakeLock.clear();
-    mMediaClock.clear();
     mVideoScheduler.clear();
     mNotify.clear();
     mAudioSink.clear();
@@ -548,8 +549,10 @@
                 CHECK_EQ(mAudioSink->getPosition(&numFramesPlayed),
                          (status_t)OK);
 
+                // Handle AudioTrack race when start is immediately called after flush.
                 uint32_t numFramesPendingPlayout =
-                    mNumFramesWritten - numFramesPlayed;
+                    (mNumFramesWritten > numFramesPlayed ?
+                        mNumFramesWritten - numFramesPlayed : 0);
 
                 // This is how long the audio sink will have data to
                 // play back.
@@ -1245,82 +1248,48 @@
         return;
     }
 
-    bool needRepostDrainVideoQueue = false;
-    int64_t delayUs;
     int64_t nowUs = ALooper::GetNowUs();
-    int64_t realTimeUs;
     if (mFlags & FLAG_REAL_TIME) {
-        int64_t mediaTimeUs;
-        CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
-        realTimeUs = mediaTimeUs;
-    } else {
-        int64_t mediaTimeUs;
-        CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
+        int64_t realTimeUs;
+        CHECK(entry.mBuffer->meta()->findInt64("timeUs", &realTimeUs));
 
-        {
-            Mutex::Autolock autoLock(mLock);
-            if (mAnchorTimeMediaUs < 0) {
-                mMediaClock->updateAnchor(mediaTimeUs, nowUs, mediaTimeUs);
-                mAnchorTimeMediaUs = mediaTimeUs;
-                realTimeUs = nowUs;
-            } else if (!mVideoSampleReceived) {
-                // Always render the first video frame.
-                realTimeUs = nowUs;
-            } else if (mAudioFirstAnchorTimeMediaUs < 0
-                || mMediaClock->getRealTimeFor(mediaTimeUs, &realTimeUs) == OK) {
-                realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
-            } else if (mediaTimeUs - mAudioFirstAnchorTimeMediaUs >= 0) {
-                needRepostDrainVideoQueue = true;
-                realTimeUs = nowUs;
-            } else {
-                realTimeUs = nowUs;
-            }
-        }
-        if (!mHasAudio) {
-            // smooth out videos >= 10fps
-            mMediaClock->updateMaxTimeMedia(mediaTimeUs + 100000);
-        }
+        realTimeUs = mVideoScheduler->schedule(realTimeUs * 1000) / 1000;
 
-        // Heuristics to handle situation when media time changed without a
-        // discontinuity. If we have not drained an audio buffer that was
-        // received after this buffer, repost in 10 msec. Otherwise repost
-        // in 500 msec.
-        delayUs = realTimeUs - nowUs;
-        int64_t postDelayUs = -1;
-        if (delayUs > 500000) {
-            postDelayUs = 500000;
-            if (mHasAudio && (mLastAudioBufferDrained - entry.mBufferOrdinal) <= 0) {
-                postDelayUs = 10000;
-            }
-        } else if (needRepostDrainVideoQueue) {
-            // CHECK(mPlaybackRate > 0);
-            // CHECK(mAudioFirstAnchorTimeMediaUs >= 0);
-            // CHECK(mediaTimeUs - mAudioFirstAnchorTimeMediaUs >= 0);
-            postDelayUs = mediaTimeUs - mAudioFirstAnchorTimeMediaUs;
-            postDelayUs /= mPlaybackRate;
-        }
+        int64_t twoVsyncsUs = 2 * (mVideoScheduler->getVsyncPeriod() / 1000);
 
-        if (postDelayUs >= 0) {
-            msg->setWhat(kWhatPostDrainVideoQueue);
-            msg->post(postDelayUs);
-            mVideoScheduler->restart();
-            ALOGI("possible video time jump of %dms (%lld : %lld) or uninitialized media clock,"
-                    " retrying in %dms",
-                    (int)(delayUs / 1000), (long long)mediaTimeUs,
-                    (long long)mAudioFirstAnchorTimeMediaUs, (int)(postDelayUs / 1000));
-            mDrainVideoQueuePending = true;
-            return;
-        }
+        int64_t delayUs = realTimeUs - nowUs;
+
+        ALOGW_IF(delayUs > 500000, "unusually high delayUs: %lld", (long long)delayUs);
+        // post 2 display refreshes before rendering is due
+        msg->post(delayUs > twoVsyncsUs ? delayUs - twoVsyncsUs : 0);
+
+        mDrainVideoQueuePending = true;
+        return;
     }
 
-    realTimeUs = mVideoScheduler->schedule(realTimeUs * 1000) / 1000;
-    int64_t twoVsyncsUs = 2 * (mVideoScheduler->getVsyncPeriod() / 1000);
+    int64_t mediaTimeUs;
+    CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
 
-    delayUs = realTimeUs - nowUs;
+    {
+        Mutex::Autolock autoLock(mLock);
+        if (mAnchorTimeMediaUs < 0) {
+            mMediaClock->updateAnchor(mediaTimeUs, nowUs, mediaTimeUs);
+            mAnchorTimeMediaUs = mediaTimeUs;
+        }
+    }
+    if (!mHasAudio) {
+        // smooth out videos >= 10fps
+        mMediaClock->updateMaxTimeMedia(mediaTimeUs + 100000);
+    }
 
-    ALOGW_IF(delayUs > 500000, "unusually high delayUs: %" PRId64, delayUs);
-    // post 2 display refreshes before rendering is due
-    msg->post(delayUs > twoVsyncsUs ? delayUs - twoVsyncsUs : 0);
+    if (!mVideoSampleReceived || mediaTimeUs < mAudioFirstAnchorTimeMediaUs) {
+        msg->post();
+    } else {
+        int64_t twoVsyncsUs = 2 * (mVideoScheduler->getVsyncPeriod() / 1000);
+
+        // post 2 display refreshes before rendering is due
+        mMediaClock->addTimer(msg, mediaTimeUs, -twoVsyncsUs);
+    }
 
     mDrainVideoQueuePending = true;
 }
@@ -1354,6 +1323,7 @@
 
         realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
     }
+    realTimeUs = mVideoScheduler->schedule(realTimeUs * 1000) / 1000;
 
     bool tooLate = false;
 
@@ -1440,6 +1410,7 @@
     if (audio) {
         // Video might outlive audio. Clear anchor to enable video only case.
         mAnchorTimeMediaUs = -1;
+        mHasAudio = false;
     }
 }
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
index f58b79c..567f8f1 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
@@ -36,6 +36,7 @@
         FLAG_OFFLOAD_AUDIO = 2,
     };
     Renderer(const sp<MediaPlayerBase::AudioSink> &sink,
+             const sp<MediaClock> &mediaClock,
              const sp<AMessage> &notify,
              uint32_t flags = 0);
 
@@ -165,7 +166,7 @@
     int32_t mVideoDrainGeneration;
     int32_t mAudioEOSGeneration;
 
-    sp<MediaClock> mMediaClock;
+    const sp<MediaClock> mMediaClock;
     float mPlaybackRate; // audio track rate
 
     AudioPlaybackRate mPlaybackSettings;
diff --git a/media/libnbaio/Android.bp b/media/libnbaio/Android.bp
index 4220b77..a4df38d 100644
--- a/media/libnbaio/Android.bp
+++ b/media/libnbaio/Android.bp
@@ -41,11 +41,8 @@
         "AudioBufferProviderSource.cpp",
         "AudioStreamInSource.cpp",
         "AudioStreamOutSink.cpp",
-        "NBLog.cpp",
-        "PerformanceAnalysis.cpp",
         "Pipe.cpp",
         "PipeReader.cpp",
-        "ReportPerformance.cpp",
         "SourceAudioBufferProvider.cpp",
     ],
 
diff --git a/media/libnbaio/OWNERS b/media/libnbaio/OWNERS
index f9cb567..eece71f 100644
--- a/media/libnbaio/OWNERS
+++ b/media/libnbaio/OWNERS
@@ -1 +1,2 @@
 gkasten@google.com
+hunga@google.com
diff --git a/media/libnbaio/PerformanceAnalysis.cpp b/media/libnbaio/PerformanceAnalysis.cpp
deleted file mode 100644
index fb3bddc..0000000
--- a/media/libnbaio/PerformanceAnalysis.cpp
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Copyright (C) 2017 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 "PerformanceAnalysis"
-// #define LOG_NDEBUG 0
-
-#include <algorithm>
-#include <climits>
-#include <deque>
-#include <iostream>
-#include <math.h>
-#include <numeric>
-#include <vector>
-#include <stdarg.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/prctl.h>
-#include <time.h>
-#include <new>
-#include <audio_utils/roundup.h>
-#include <media/nbaio/NBLog.h>
-#include <media/nbaio/PerformanceAnalysis.h>
-#include <media/nbaio/ReportPerformance.h>
-// #include <utils/CallStack.h> // used to print callstack
-#include <utils/Log.h>
-#include <utils/String8.h>
-
-#include <queue>
-#include <utility>
-
-namespace android {
-
-namespace ReportPerformance {
-
-PerformanceAnalysis::PerformanceAnalysis() {
-    // These variables will be (FIXME) learned from the data
-    kPeriodMs = 4; // typical buffer period (mode)
-    // average number of Ms spent processing buffer
-    kPeriodMsCPU = static_cast<int>(kPeriodMs * kRatio);
-}
-
-// converts a time series into a map. key: buffer period length. value: count
-static std::map<int, int> buildBuckets(const std::vector<int64_t> &samples) {
-    // TODO allow buckets of variable resolution
-    std::map<int, int> buckets;
-    for (size_t i = 1; i < samples.size(); ++i) {
-        ++buckets[deltaMs(samples[i - 1], samples[i])];
-    }
-    return buckets;
-}
-
-static int widthOf(int x) {
-    int width = 0;
-    while (x > 0) {
-        ++width;
-        x /= 10;
-    }
-    return width;
-}
-
-// Given a series of audio processing wakeup timestamps,
-// buckets the time intervals into a histogram, searches for
-// outliers, analyzes the outlier series for unexpectedly
-// small or large values and stores these as peaks, and flushes
-// the timestamp series from memory.
-void PerformanceAnalysis::processAndFlushTimeStampSeries() {
-    // 1) analyze the series to store all outliers and their exact timestamps:
-    storeOutlierData(mTimeStampSeries);
-
-    // 2) detect peaks in the outlier series
-    detectPeaks();
-
-    // 3) compute its histogram, append to mRecentHists and clear the time series
-    mRecentHists.emplace_back(static_cast<timestamp>(mTimeStampSeries[0]),
-                              buildBuckets(mTimeStampSeries));
-    // do not let mRecentHists exceed capacity
-    // ALOGD("mRecentHists size: %d", static_cast<int>(mRecentHists.size()));
-    if (mRecentHists.size() >= kRecentHistsCapacity) {
-        //  ALOGD("popped back mRecentHists");
-        mRecentHists.pop_front();
-    }
-    mTimeStampSeries.clear();
-}
-
-// forces short-term histogram storage to avoid adding idle audio time interval
-// to buffer period data
-void PerformanceAnalysis::handleStateChange() {
-    ALOGD("handleStateChange");
-    processAndFlushTimeStampSeries();
-    return;
-}
-
-// Takes a single buffer period timestamp entry information and stores it in a
-// temporary series of timestamps. Once the series is full, the data is analyzed,
-// stored, and emptied.
-void PerformanceAnalysis::logTsEntry(int64_t ts) {
-    // TODO might want to filter excessively high outliers, which are usually caused
-    // by the thread being inactive.
-    // Store time series data for each reader in order to bucket it once there
-    // is enough data. Then, write to recentHists as a histogram.
-    mTimeStampSeries.push_back(ts);
-    // if length of the time series has reached kShortHistSize samples,
-    // analyze the data and flush the timestamp series from memory
-    if (mTimeStampSeries.size() >= kShortHistSize) {
-        processAndFlushTimeStampSeries();
-    }
-}
-
-// When the short-term histogram array mRecentHists has reached capacity,
-// merge histograms for data compression and store them in mLongTermHists
-// clears mRecentHists
-// TODO: have logTsEntry write directly to mLongTermHists, discard mRecentHists,
-// start a new histogram when a peak occurs
-void PerformanceAnalysis::processAndFlushRecentHists() {
-
-    // Buckets is used to aggregate short-term histograms.
-    Histogram buckets;
-    timestamp startingTs = mRecentHists[0].first;
-
-    for (const auto &shortHist: mRecentHists) {
-        // If the time between starting and ending timestamps has reached the maximum,
-        // add the current histogram (buckets) to the long-term histogram buffer,
-        // clear buckets, and start a new long-term histogram aggregation process.
-        if (deltaMs(startingTs, shortHist.first) >= kMaxHistTimespanMs) {
-            mLongTermHists.emplace_back(startingTs, std::move(buckets));
-            buckets.clear();
-            startingTs = shortHist.first;
-            // When memory is full, delete oldest histogram
-            // TODO use a circular buffer
-            if (mLongTermHists.size() >= kLongTermHistsCapacity) {
-                mLongTermHists.pop_front();
-            }
-        }
-
-        // add current histogram to buckets
-        for (const auto &countPair : shortHist.second) {
-            buckets[countPair.first] += countPair.second;
-        }
-    }
-    mRecentHists.clear();
-    // TODO: decide when/where to call writeToFile
-    // TODO: add a thread-specific extension to the file name
-    static const char* const kName = (const char *) "/data/misc/audioserver/sample_results.txt";
-    writeToFile(mOutlierData, mLongTermHists, kName, false);
-}
-
-// Given a series of outlier intervals (mOutlier data),
-// looks for changes in distribution (peaks), which can be either positive or negative.
-// The function sets the mean to the starting value and sigma to 0, and updates
-// them as long as no peak is detected. When a value is more than 'threshold'
-// standard deviations from the mean, a peak is detected and the mean and sigma
-// are set to the peak value and 0.
-void PerformanceAnalysis::detectPeaks() {
-    if (mOutlierData.empty()) {
-        return;
-    }
-
-    // compute mean of the distribution. Used to check whether a value is large
-    const double kTypicalDiff = std::accumulate(
-        mOutlierData.begin(), mOutlierData.end(), 0,
-        [](auto &a, auto &b){return a + b.first;}) / mOutlierData.size();
-    // ALOGD("typicalDiff %f", kTypicalDiff);
-
-    // iterator at the beginning of a sequence, or updated to the most recent peak
-    std::deque<std::pair<uint64_t, uint64_t>>::iterator start = mOutlierData.begin();
-    // the mean and standard deviation are updated every time a peak is detected
-    // initialize first time. The mean from the previous sequence is stored
-    // for the next sequence. Here, they are initialized for the first time.
-    if (mPeakDetectorMean < 0) {
-        mPeakDetectorMean = static_cast<double>(start->first);
-        mPeakDetectorSd = 0;
-    }
-    auto sqr = [](auto x){ return x * x; };
-    for (auto it = mOutlierData.begin(); it != mOutlierData.end(); ++it) {
-        // no surprise occurred:
-        // the new element is a small number of standard deviations from the mean
-        if ((fabs(it->first - mPeakDetectorMean) < kStddevThreshold * mPeakDetectorSd) ||
-             // or: right after peak has been detected, the delta is smaller than average
-            (mPeakDetectorSd == 0 && fabs(it->first - mPeakDetectorMean) < kTypicalDiff)) {
-            // update the mean and sd:
-            // count number of elements (distance between start interator and current)
-            const int kN = std::distance(start, it) + 1;
-            // usual formulas for mean and sd
-            mPeakDetectorMean = std::accumulate(start, it + 1, 0.0,
-                                   [](auto &a, auto &b){return a + b.first;}) / kN;
-            mPeakDetectorSd = sqrt(std::accumulate(start, it + 1, 0.0,
-                      [=](auto &a, auto &b){ return a + sqr(b.first - mPeakDetectorMean);})) /
-                      ((kN > 1)? kN - 1 : kN); // kN - 1: mean is correlated with variance
-        }
-        // surprising value: store peak timestamp and reset mean, sd, and start iterator
-        else {
-            mPeakTimestamps.emplace_back(it->second);
-            // TODO: remove pop_front once a circular buffer is in place
-            if (mPeakTimestamps.size() >= kPeakSeriesSize) {
-                mPeakTimestamps.pop_front();
-            }
-            mPeakDetectorMean = static_cast<double>(it->first);
-            mPeakDetectorSd = 0;
-            start = it;
-        }
-    }
-    return;
-}
-
-// Called by LogTsEntry. The input is a vector of timestamps.
-// Finds outliers and writes to mOutlierdata.
-// Each value in mOutlierdata consists of: <outlier timestamp, time elapsed since previous outlier>.
-// e.g. timestamps (ms) 1, 4, 5, 16, 18, 28 will produce pairs (4, 5), (13, 18).
-// This function is applied to the time series before it is converted into a histogram.
-void PerformanceAnalysis::storeOutlierData(const std::vector<int64_t> &timestamps) {
-    if (timestamps.size() < 1) {
-        return;
-    }
-    // first pass: need to initialize
-    if (mElapsed == 0) {
-        mPrevNs = timestamps[0];
-    }
-    for (const auto &ts: timestamps) {
-        const uint64_t diffMs = static_cast<uint64_t>(deltaMs(mPrevNs, ts));
-        if (diffMs >= static_cast<uint64_t>(kOutlierMs)) {
-            mOutlierData.emplace_back(mElapsed, static_cast<uint64_t>(mPrevNs));
-            // Remove oldest value if the vector is full
-            // TODO: remove pop_front once circular buffer is in place
-            // FIXME: make sure kShortHistSize is large enough that that data will never be lost
-            // before being written to file or to a FIFO
-            if (mOutlierData.size() >= kOutlierSeriesSize) {
-                mOutlierData.pop_front();
-            }
-            mElapsed = 0;
-        }
-        mElapsed += diffMs;
-        mPrevNs = ts;
-    }
-}
-
-
-// FIXME: delete this temporary test code, recycled for various new functions
-void PerformanceAnalysis::testFunction() {
-    // produces values (4: 5000000), (13: 18000000)
-    // ns timestamps of buffer periods
-    const std::vector<int64_t>kTempTestData = {1000000, 4000000, 5000000,
-                                               16000000, 18000000, 28000000};
-    PerformanceAnalysis::storeOutlierData(kTempTestData);
-    for (const auto &outlier: mOutlierData) {
-        ALOGE("PerformanceAnalysis test %lld: %lld",
-              static_cast<long long>(outlier.first), static_cast<long long>(outlier.second));
-    }
-    detectPeaks();
-}
-
-// TODO Make it return a std::string instead of modifying body --> is this still relevant?
-// TODO consider changing all ints to uint32_t or uint64_t
-// TODO: move this to ReportPerformance, probably make it a friend function of PerformanceAnalysis
-void PerformanceAnalysis::reportPerformance(String8 *body, int maxHeight) {
-    if (mRecentHists.size() < 1) {
-        ALOGD("reportPerformance: mRecentHists is empty");
-        return;
-    }
-    ALOGD("reportPerformance: hists size %d", static_cast<int>(mRecentHists.size()));
-    // TODO: more elaborate data analysis
-    std::map<int, int> buckets;
-    for (const auto &shortHist: mRecentHists) {
-        for (const auto &countPair : shortHist.second) {
-            buckets[countPair.first] += countPair.second;
-        }
-    }
-
-    // underscores and spaces length corresponds to maximum width of histogram
-    static const int kLen = 40;
-    std::string underscores(kLen, '_');
-    std::string spaces(kLen, ' ');
-
-    auto it = buckets.begin();
-    int maxDelta = it->first;
-    int maxCount = it->second;
-    // Compute maximum values
-    while (++it != buckets.end()) {
-        if (it->first > maxDelta) {
-            maxDelta = it->first;
-        }
-        if (it->second > maxCount) {
-            maxCount = it->second;
-        }
-    }
-    int height = log2(maxCount) + 1; // maxCount > 0, safe to call log2
-    const int leftPadding = widthOf(1 << height);
-    const int colWidth = std::max(std::max(widthOf(maxDelta) + 1, 3), leftPadding + 2);
-    int scalingFactor = 1;
-    // scale data if it exceeds maximum height
-    if (height > maxHeight) {
-        scalingFactor = (height + maxHeight) / maxHeight;
-        height /= scalingFactor;
-    }
-    body->appendFormat("\n%*s", leftPadding + 11, "Occurrences");
-    // write histogram label line with bucket values
-    body->appendFormat("\n%s", " ");
-    body->appendFormat("%*s", leftPadding, " ");
-    for (auto const &x : buckets) {
-        body->appendFormat("%*d", colWidth, x.second);
-    }
-    // write histogram ascii art
-    body->appendFormat("\n%s", " ");
-    for (int row = height * scalingFactor; row >= 0; row -= scalingFactor) {
-        const int value = 1 << row;
-        body->appendFormat("%.*s", leftPadding, spaces.c_str());
-        for (auto const &x : buckets) {
-          body->appendFormat("%.*s%s", colWidth - 1, spaces.c_str(), x.second < value ? " " : "|");
-        }
-        body->appendFormat("\n%s", " ");
-    }
-    // print x-axis
-    const int columns = static_cast<int>(buckets.size());
-    body->appendFormat("%*c", leftPadding, ' ');
-    body->appendFormat("%.*s", (columns + 1) * colWidth, underscores.c_str());
-    body->appendFormat("\n%s", " ");
-
-    // write footer with bucket labels
-    body->appendFormat("%*s", leftPadding, " ");
-    for (auto const &x : buckets) {
-        body->appendFormat("%*d", colWidth, x.first);
-    }
-    body->appendFormat("%.*s%s", colWidth, spaces.c_str(), "ms\n");
-
-    // Now report glitches
-    body->appendFormat("\ntime elapsed between glitches and glitch timestamps\n");
-    for (const auto &outlier: mOutlierData) {
-        body->appendFormat("%lld: %lld\n", static_cast<long long>(outlier.first),
-                           static_cast<long long>(outlier.second));
-    }
-
-}
-
-
-// Produces a log warning if the timing of recent buffer periods caused a glitch
-// Computes sum of running window of three buffer periods
-// Checks whether the buffer periods leave enough CPU time for the next one
-// e.g. if a buffer period is expected to be 4 ms and a buffer requires 3 ms of CPU time,
-// here are some glitch cases:
-// 4 + 4 + 6 ; 5 + 4 + 5; 2 + 2 + 10
-// TODO: develop this code to track changes in histogram distribution in addition
-// to / instead of glitches.
-void PerformanceAnalysis::alertIfGlitch(const std::vector<int64_t> &samples) {
-    std::deque<int> periods(kNumBuff, kPeriodMs);
-    for (size_t i = 2; i < samples.size(); ++i) { // skip first time entry
-        periods.push_front(deltaMs(samples[i - 1], samples[i]));
-        periods.pop_back();
-        // TODO: check that all glitch cases are covered
-        if (std::accumulate(periods.begin(), periods.end(), 0) > kNumBuff * kPeriodMs +
-            kPeriodMs - kPeriodMsCPU) {
-                ALOGW("A glitch occurred");
-                periods.assign(kNumBuff, kPeriodMs);
-        }
-    }
-    return;
-}
-
-} // namespace ReportPerformance
-
-}   // namespace android
diff --git a/media/libnbaio/ReportPerformance.cpp b/media/libnbaio/ReportPerformance.cpp
deleted file mode 100644
index dc50ada..0000000
--- a/media/libnbaio/ReportPerformance.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2017 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 "ReportPerformance"
-
-#include <fstream>
-#include <iostream>
-#include <queue>
-#include <stdarg.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/prctl.h>
-#include <utility>
-#include <media/nbaio/NBLog.h>
-#include <media/nbaio/PerformanceAnalysis.h>
-#include <media/nbaio/ReportPerformance.h>
-// #include <utils/CallStack.h> // used to print callstack
-#include <utils/Log.h>
-#include <utils/String8.h>
-
-namespace android {
-
-namespace ReportPerformance {
-
-// Writes outlier intervals, timestamps, and histograms spanning long time intervals to a file.
-// TODO: format the data efficiently and write different types of data to different files
-void writeToFile(std::deque<std::pair<outlierInterval, timestamp>> &outlierData,
-                                    std::deque<std::pair<timestamp, Histogram>> &hists,
-                                    const char * kName,
-                                    bool append) {
-    ALOGD("writing performance data to file");
-    if (outlierData.empty() || hists.empty()) {
-        return;
-    }
-
-    std::ofstream ofs;
-    ofs.open(kName, append ? std::ios::app : std::ios::trunc);
-    if (!ofs.is_open()) {
-        ALOGW("couldn't open file %s", kName);
-        return;
-    }
-    ofs << "Outlier data: interval and timestamp\n";
-    for (const auto &outlier : outlierData) {
-        ofs << outlier.first << ": " << outlier.second << "\n";
-    }
-    ofs << "Histogram data\n";
-    for (const auto &hist : hists) {
-        ofs << "\ttimestamp\n";
-        ofs << hist.first << "\n";
-        ofs << "\tbuckets and counts\n";
-        for (const auto &bucket : hist.second) {
-            ofs << bucket.first << ": " << bucket.second << "\n";
-        }
-    }
-    ofs.close();
-}
-
-} // namespace ReportPerformance
-
-}   // namespace android
diff --git a/media/libnbaio/include/media/nbaio/NBLog.h b/media/libnbaio/include/media/nbaio/NBLog.h
deleted file mode 100644
index 3e48ee1..0000000
--- a/media/libnbaio/include/media/nbaio/NBLog.h
+++ /dev/null
@@ -1,595 +0,0 @@
-/*
- * Copyright (C) 2017 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.
- */
-
-// Non-blocking event logger intended for safe communication between processes via shared memory
-
-#ifndef ANDROID_MEDIA_NBLOG_H
-#define ANDROID_MEDIA_NBLOG_H
-
-#include <binder/IMemory.h>
-#include <audio_utils/fifo.h>
-#include <utils/Mutex.h>
-#include <utils/threads.h>
-
-#include <map>
-#include <deque>
-#include <set>
-#include <vector>
-
-namespace android {
-
-class String8;
-
-class NBLog {
-
-public:
-
-typedef uint64_t log_hash_t;
-
-// FIXME Everything needed for client (writer API and registration) should be isolated
-//       from the rest of the implementation.
-class Writer;
-class Reader;
-
-enum Event : uint8_t {
-    EVENT_RESERVED,
-    EVENT_STRING,               // ASCII string, not NUL-terminated
-    // TODO: make timestamp optional
-    EVENT_TIMESTAMP,            // clock_gettime(CLOCK_MONOTONIC)
-    EVENT_INTEGER,              // integer value entry
-    EVENT_FLOAT,                // floating point value entry
-    EVENT_PID,                  // process ID and process name
-    EVENT_AUTHOR,               // author index (present in merged logs) tracks entry's original log
-    EVENT_START_FMT,            // logFormat start event: entry includes format string, following
-                                // entries contain format arguments
-    EVENT_HASH,                 // unique HASH of log origin, originates from hash of file name
-                                // and line number
-    EVENT_HISTOGRAM_ENTRY_TS,   // single datum for timestamp histogram
-    EVENT_AUDIO_STATE,          // audio on/off event: logged upon FastMixer::onStateChange() call
-    EVENT_END_FMT,              // end of logFormat argument list
-
-    EVENT_UPPER_BOUND,          // to check for invalid events
-};
-
-private:
-
-// ---------------------------------------------------------------------------
-// API for handling format entry operations
-
-// a formatted entry has the following structure:
-//    * START_FMT entry, containing the format string
-//    * TIMESTAMP entry
-//    * HASH entry
-//    * author entry of the thread that generated it (optional, present in merged log)
-//    * format arg1
-//    * format arg2
-//    * ...
-//    * END_FMT entry
-
-// entry representation in memory
-struct entry {
-    const uint8_t type;
-    const uint8_t length;
-    const uint8_t data[0];
-};
-
-// entry tail representation (after data)
-struct ending {
-    uint8_t length;
-    uint8_t next[0];
-};
-
-// entry iterator
-class EntryIterator {
-public:
-    EntryIterator();
-    explicit EntryIterator(const uint8_t *entry);
-    EntryIterator(const EntryIterator &other);
-
-    // dereference underlying entry
-    const entry&    operator*() const;
-    const entry*    operator->() const;
-    // advance to next entry
-    EntryIterator&       operator++(); // ++i
-    // back to previous entry
-    EntryIterator&       operator--(); // --i
-    EntryIterator        next() const;
-    EntryIterator        prev() const;
-    bool            operator!=(const EntryIterator &other) const;
-    int             operator-(const EntryIterator &other) const;
-
-    bool            hasConsistentLength() const;
-    void            copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const;
-    void            copyData(uint8_t *dst) const;
-
-    template<typename T>
-    inline const T& payload() {
-        return *reinterpret_cast<const T *>(ptr + offsetof(entry, data));
-    }
-
-    inline operator const uint8_t*() const {
-        return ptr;
-    }
-
-private:
-    const uint8_t  *ptr;
-};
-
-class AbstractEntry {
-public:
-
-    // Entry starting in the given pointer
-    explicit AbstractEntry(const uint8_t *entry);
-    virtual ~AbstractEntry() {}
-
-    // build concrete entry of appropriate class from pointer
-    static std::unique_ptr<AbstractEntry> buildEntry(const uint8_t *ptr);
-
-    // get format entry timestamp
-    // TODO consider changing to uint64_t
-    virtual int64_t      timestamp() const = 0;
-
-    // get format entry's unique id
-    virtual log_hash_t   hash() const = 0;
-
-    // entry's author index (-1 if none present)
-    // a Merger has a vector of Readers, author simply points to the index of the
-    // Reader that originated the entry
-    // TODO consider changing to uint32_t
-    virtual int          author() const = 0;
-
-    // copy entry, adding author before timestamp, returns iterator to end of entry
-    virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
-                                       int author) const = 0;
-
-protected:
-    // copies ordinary entry from src to dst, and returns length of entry
-    // size_t      copyEntry(audio_utils_fifo_writer *dst, const iterator &it);
-    const uint8_t  *mEntry;
-};
-
-class FormatEntry : public AbstractEntry {
-public:
-    // explicit FormatEntry(const EntryIterator &it);
-    explicit FormatEntry(const uint8_t *ptr) : AbstractEntry(ptr) {}
-    virtual ~FormatEntry() {}
-
-    EntryIterator begin() const;
-
-    // Entry's format string
-    const   char* formatString() const;
-
-    // Enrty's format string length
-            size_t      formatStringLength() const;
-
-    // Format arguments (excluding format string, timestamp and author)
-            EntryIterator    args() const;
-
-    // get format entry timestamp
-    virtual int64_t     timestamp() const override;
-
-    // get format entry's unique id
-    virtual log_hash_t  hash() const override;
-
-    // entry's author index (-1 if none present)
-    // a Merger has a vector of Readers, author simply points to the index of the
-    // Reader that originated the entry
-    virtual int         author() const override;
-
-    // copy entry, adding author before timestamp, returns size of original entry
-    virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
-                                       int author) const override;
-
-};
-
-class HistogramEntry : public AbstractEntry {
-public:
-    explicit HistogramEntry(const uint8_t *ptr) : AbstractEntry(ptr) {
-    }
-    virtual ~HistogramEntry() {}
-
-    virtual int64_t     timestamp() const override;
-
-    virtual log_hash_t  hash() const override;
-
-    virtual int         author() const override;
-
-    virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
-                                       int author) const override;
-
-};
-
-// ---------------------------------------------------------------------------
-
-// representation of a single log entry in private memory
-struct Entry {
-    Entry(Event event, const void *data, size_t length)
-        : mEvent(event), mLength(length), mData(data) { }
-    /*virtual*/ ~Entry() { }
-
-    // used during writing to format Entry information as follows: [type][length][data ... ][length]
-    int     copyEntryDataAt(size_t offset) const;
-
-private:
-    friend class Writer;
-    Event       mEvent;     // event type
-    uint8_t     mLength;    // length of additional data, 0 <= mLength <= kMaxLength
-    const void *mData;      // event type-specific data
-    static const size_t kMaxLength = 255;
-public:
-    // mEvent, mLength, mData[...], duplicate mLength
-    static const size_t kOverhead = sizeof(entry) + sizeof(ending);
-    // endind length of previous entry
-    static const size_t kPreviousLengthOffset = - sizeof(ending) +
-                                                offsetof(ending, length);
-};
-
-struct HistTsEntry {
-    log_hash_t hash;
-    int64_t ts;
-}; //TODO __attribute__((packed));
-
-struct HistTsEntryWithAuthor {
-    log_hash_t hash;
-    int64_t ts;
-    int author;
-}; //TODO __attribute__((packed));
-
-using StateTsEntryWithAuthor = HistTsEntryWithAuthor;
-
-struct HistIntEntry {
-    log_hash_t hash;
-    int value;
-}; //TODO __attribute__((packed));
-
-// representation of a single log entry in shared memory
-//  byte[0]             mEvent
-//  byte[1]             mLength
-//  byte[2]             mData[0]
-//  ...
-//  byte[2+i]           mData[i]
-//  ...
-//  byte[2+mLength-1]   mData[mLength-1]
-//  byte[2+mLength]     duplicate copy of mLength to permit reverse scan
-//  byte[3+mLength]     start of next log entry
-
-    static void    appendInt(String8 *body, const void *data);
-    static void    appendFloat(String8 *body, const void *data);
-    static void    appendPID(String8 *body, const void *data, size_t length);
-    static void    appendTimestamp(String8 *body, const void *data);
-    static size_t  fmtEntryLength(const uint8_t *data);
-    static String8 bufferDump(const uint8_t *buffer, size_t size);
-    static String8 bufferDump(const EntryIterator &it);
-public:
-
-// Located in shared memory, must be POD.
-// Exactly one process must explicitly call the constructor or use placement new.
-// Since this is a POD, the destructor is empty and unnecessary to call it explicitly.
-struct Shared {
-    Shared() /* mRear initialized via default constructor */ { }
-    /*virtual*/ ~Shared() { }
-
-    audio_utils_fifo_index  mRear;  // index one byte past the end of most recent Entry
-    char    mBuffer[0];             // circular buffer for entries
-};
-
-public:
-
-// ---------------------------------------------------------------------------
-
-// FIXME Timeline was intended to wrap Writer and Reader, but isn't actually used yet.
-// For now it is just a namespace for sharedSize().
-class Timeline : public RefBase {
-public:
-#if 0
-    Timeline(size_t size, void *shared = NULL);
-    virtual ~Timeline();
-#endif
-
-    // Input parameter 'size' is the desired size of the timeline in byte units.
-    // Returns the size rounded up to a power-of-2, plus the constant size overhead for indices.
-    static size_t sharedSize(size_t size);
-
-#if 0
-private:
-    friend class    Writer;
-    friend class    Reader;
-
-    const size_t    mSize;      // circular buffer size in bytes, must be a power of 2
-    bool            mOwn;       // whether I own the memory at mShared
-    Shared* const   mShared;    // pointer to shared memory
-#endif
-};
-
-// ---------------------------------------------------------------------------
-
-// Writer is thread-safe with respect to Reader, but not with respect to multiple threads
-// calling Writer methods.  If you need multi-thread safety for writing, use LockedWriter.
-class Writer : public RefBase {
-public:
-    Writer();                   // dummy nop implementation without shared memory
-
-    // Input parameter 'size' is the desired size of the timeline in byte units.
-    // The size of the shared memory must be at least Timeline::sharedSize(size).
-    Writer(void *shared, size_t size);
-    Writer(const sp<IMemory>& iMemory, size_t size);
-
-    virtual ~Writer();
-
-    // FIXME needs comments, and some should be private
-    virtual void    log(const char *string);
-    virtual void    logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
-    virtual void    logvf(const char *fmt, va_list ap);
-    virtual void    logTimestamp();
-    virtual void    logTimestamp(const int64_t ts);
-    virtual void    logInteger(const int x);
-    virtual void    logFloat(const float x);
-    virtual void    logPID();
-    virtual void    logFormat(const char *fmt, log_hash_t hash, ...);
-    virtual void    logVFormat(const char *fmt, log_hash_t hash, va_list ap);
-    virtual void    logStart(const char *fmt);
-    virtual void    logEnd();
-    virtual void    logHash(log_hash_t hash);
-    virtual void    logEventHistTs(Event event, log_hash_t hash);
-
-    virtual bool    isEnabled() const;
-
-    // return value for all of these is the previous isEnabled()
-    virtual bool    setEnabled(bool enabled);   // but won't enable if no shared memory
-            bool    enable()    { return setEnabled(true); }
-            bool    disable()   { return setEnabled(false); }
-
-    sp<IMemory>     getIMemory() const  { return mIMemory; }
-
-private:
-    // 0 <= length <= kMaxLength
-    // writes a single Entry to the FIFO
-    void    log(Event event, const void *data, size_t length);
-    // checks validity of an event before calling log above this one
-    void    log(const Entry *entry, bool trusted = false);
-
-    Shared* const   mShared;    // raw pointer to shared memory
-    sp<IMemory>     mIMemory;   // ref-counted version, initialized in constructor and then const
-    audio_utils_fifo * const mFifo;                 // FIFO itself,
-                                                    // non-NULL unless constructor fails
-    audio_utils_fifo_writer * const mFifoWriter;    // used to write to FIFO,
-                                                    // non-NULL unless dummy constructor used
-    bool            mEnabled;   // whether to actually log
-
-    // cached pid and process name to use in %p format specifier
-    // total tag length is mPidTagSize and process name is not zero terminated
-    char   *mPidTag;
-    size_t  mPidTagSize;
-};
-
-// ---------------------------------------------------------------------------
-
-// Similar to Writer, but safe for multiple threads to call concurrently
-class LockedWriter : public Writer {
-public:
-    LockedWriter();
-    LockedWriter(void *shared, size_t size);
-
-    virtual void    log(const char *string);
-    virtual void    logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
-    virtual void    logvf(const char *fmt, va_list ap);
-    virtual void    logTimestamp();
-    virtual void    logTimestamp(const int64_t ts);
-    virtual void    logInteger(const int x);
-    virtual void    logFloat(const float x);
-    virtual void    logPID();
-    virtual void    logStart(const char *fmt);
-    virtual void    logEnd();
-    virtual void    logHash(log_hash_t hash);
-
-    virtual bool    isEnabled() const;
-    virtual bool    setEnabled(bool enabled);
-
-private:
-    mutable Mutex   mLock;
-};
-
-// ---------------------------------------------------------------------------
-
-class Reader : public RefBase {
-public:
-
-    // A snapshot of a readers buffer
-    // This is raw data. No analysis has been done on it
-    class Snapshot {
-    public:
-        Snapshot() : mData(NULL), mLost(0) {}
-
-        Snapshot(size_t bufferSize) : mData(new uint8_t[bufferSize]) {}
-
-        ~Snapshot() { delete[] mData; }
-
-        // copy of the buffer
-        uint8_t *data() const { return mData; }
-
-        // amount of data lost (given by audio_utils_fifo_reader)
-        size_t   lost() const { return mLost; }
-
-        // iterator to beginning of readable segment of snapshot
-        // data between begin and end has valid entries
-        EntryIterator begin() { return mBegin; }
-
-        // iterator to end of readable segment of snapshot
-        EntryIterator end() { return mEnd; }
-
-    private:
-        friend class Reader;
-        uint8_t              *mData;
-        size_t                mLost;
-        EntryIterator mBegin;
-        EntryIterator mEnd;
-    };
-
-    // Input parameter 'size' is the desired size of the timeline in byte units.
-    // The size of the shared memory must be at least Timeline::sharedSize(size).
-    Reader(const void *shared, size_t size);
-    Reader(const sp<IMemory>& iMemory, size_t size);
-
-    virtual ~Reader();
-
-    // get snapshot of readers fifo buffer, effectively consuming the buffer
-    std::unique_ptr<Snapshot> getSnapshot();
-    // dump a particular snapshot of the reader
-    // TODO: move dump to PerformanceAnalysis. Model/view/controller design
-    void     dump(int fd, size_t indent, Snapshot & snap);
-    // dump the current content of the reader's buffer (call getSnapshot() and previous dump())
-    void     dump(int fd, size_t indent = 0);
-    bool     isIMemory(const sp<IMemory>& iMemory) const;
-
-private:
-
-    static const std::set<Event> startingTypes;
-    static const std::set<Event> endingTypes;
-    /*const*/ Shared* const mShared;    // raw pointer to shared memory, actually const but not
-                                        // declared as const because audio_utils_fifo() constructor
-    sp<IMemory> mIMemory;       // ref-counted version, assigned only in constructor
-    int     mFd;                // file descriptor
-    int     mIndent;            // indentation level
-    audio_utils_fifo * const mFifo;                 // FIFO itself,
-                                                    // non-NULL unless constructor fails
-    audio_utils_fifo_reader * const mFifoReader;    // used to read from FIFO,
-                                                    // non-NULL unless constructor fails
-
-    // TODO: it might be clearer, instead of a direct map from source location to vector of
-    // timestamps, if we instead first mapped from source location to an object that
-    // represented that location. And one_of its fields would be a vector of timestamps.
-    // That would allow us to record other information about the source location beyond timestamps.
-    void    dumpLine(const String8& timestamp, String8& body);
-
-    EntryIterator   handleFormat(const FormatEntry &fmtEntry,
-                                         String8 *timestamp,
-                                         String8 *body);
-    // dummy method for handling absent author entry
-    virtual void handleAuthor(const AbstractEntry& /*fmtEntry*/, String8* /*body*/) {}
-
-    // Searches for the last entry of type <type> in the range [front, back)
-    // back has to be entry-aligned. Returns nullptr if none enconuntered.
-    static const uint8_t *findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
-                                         const std::set<Event> &types);
-
-    static const size_t kSquashTimestamp = 5; // squash this many or more adjacent timestamps
-};
-
-// Wrapper for a reader with a name. Contains a pointer to the reader and a pointer to the name
-class NamedReader {
-public:
-    NamedReader() { mName[0] = '\0'; } // for Vector
-    NamedReader(const sp<NBLog::Reader>& reader, const char *name) :
-        mReader(reader)
-        { strlcpy(mName, name, sizeof(mName)); }
-    ~NamedReader() { }
-    const sp<NBLog::Reader>&  reader() const { return mReader; }
-    const char*               name() const { return mName; }
-
-private:
-    sp<NBLog::Reader>   mReader;
-    static const size_t kMaxName = 32;
-    char                mName[kMaxName];
-};
-
-// ---------------------------------------------------------------------------
-
-class Merger : public RefBase {
-public:
-    Merger(const void *shared, size_t size);
-
-    virtual ~Merger() {}
-
-    void addReader(const NamedReader &reader);
-    // TODO add removeReader
-    void merge();
-    // FIXME This is returning a reference to a shared variable that needs a lock
-    const std::vector<NamedReader>& getNamedReaders() const;
-private:
-    // vector of the readers the merger is supposed to merge from.
-    // every reader reads from a writer's buffer
-    // FIXME Needs to be protected by a lock
-    std::vector<NamedReader> mNamedReaders;
-
-    // TODO Need comments on all of these
-    Shared * const mShared;
-    std::unique_ptr<audio_utils_fifo> mFifo;
-    std::unique_ptr<audio_utils_fifo_writer> mFifoWriter;
-};
-
-class MergeReader : public Reader {
-public:
-    MergeReader(const void *shared, size_t size, Merger &merger);
-private:
-    // FIXME Needs to be protected by a lock,
-    //       because even though our use of it is read-only there may be asynchronous updates
-    const std::vector<NamedReader>& mNamedReaders;
-    // handle author entry by looking up the author's name and appending it to the body
-    // returns number of bytes read from fmtEntry
-    void handleAuthor(const AbstractEntry &fmtEntry, String8 *body);
-};
-
-// MergeThread is a thread that contains a Merger. It works as a retriggerable one-shot:
-// when triggered, it awakes for a lapse of time, during which it periodically merges; if
-// retriggered, the timeout is reset.
-// The thread is triggered on AudioFlinger binder activity.
-class MergeThread : public Thread {
-public:
-    MergeThread(Merger &merger);
-    virtual ~MergeThread() override;
-
-    // Reset timeout and activate thread to merge periodically if it's idle
-    void wakeup();
-
-    // Set timeout period until the merging thread goes idle again
-    void setTimeoutUs(int time);
-
-private:
-    virtual bool threadLoop() override;
-
-    // the merger who actually does the work of merging the logs
-    Merger&     mMerger;
-
-    // mutex for the condition variable
-    Mutex       mMutex;
-
-    // condition variable to activate merging on timeout >= 0
-    Condition   mCond;
-
-    // time left until the thread blocks again (in microseconds)
-    int         mTimeoutUs;
-
-    // merging period when the thread is awake
-    static const int  kThreadSleepPeriodUs = 1000000 /*1s*/;
-
-    // initial timeout value when triggered
-    static const int  kThreadWakeupPeriodUs = 3000000 /*3s*/;
-};
-
-};  // class NBLog
-
-// TODO put somewhere else
-static inline int64_t get_monotonic_ns() {
-    timespec ts;
-    if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
-        return (uint64_t) ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
-    }
-    return 0; // should not happen.
-}
-
-}   // namespace android
-
-#endif  // ANDROID_MEDIA_NBLOG_H
diff --git a/media/libnbaio/include/media/nbaio/PerformanceAnalysis.h b/media/libnbaio/include/media/nbaio/PerformanceAnalysis.h
deleted file mode 100644
index b0dc148..0000000
--- a/media/libnbaio/include/media/nbaio/PerformanceAnalysis.h
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright (C) 2017 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.
- */
-
-// Non-blocking event logger intended for safe communication between processes via shared memory
-
-#ifndef ANDROID_MEDIA_PERFORMANCEANALYSIS_H
-#define ANDROID_MEDIA_PERFORMANCEANALYSIS_H
-
-#include <map>
-#include <deque>
-#include <vector>
-#include "NBLog.h"
-#include "ReportPerformance.h"
-
-namespace android {
-
-namespace ReportPerformance {
-
-class PerformanceAnalysis {
-    // This class stores and analyzes audio processing wakeup timestamps from NBLog
-    // FIXME: currently, all performance data is stored in deques. Need to add a mutex.
-    // FIXME: continue this way until analysis is done in a separate thread. Then, use
-    // the fifo writer utilities.
-public:
-
-    PerformanceAnalysis();
-
-    // Given a series of audio processing wakeup timestamps,
-    // compresses and and analyzes the data, and flushes
-    // the timestamp series from memory.
-    void processAndFlushTimeStampSeries();
-
-    // Called when an audio on/off event is read from the buffer,
-    // e.g. EVENT_AUDIO_STATE.
-    // calls flushTimeStampSeries on the data up to the event,
-    // effectively discarding the idle audio time interval
-    void handleStateChange();
-
-    // When the short-term histogram array mRecentHists has reached capacity,
-    // merges histograms for data compression and stores them in mLongTermHists
-    void processAndFlushRecentHists();
-
-    // Writes wakeup timestamp entry to log and runs analysis
-    // TODO: make this thread safe. Each thread should have its own instance
-    // of PerformanceAnalysis.
-    void logTsEntry(timestamp_raw ts);
-
-    // FIXME: make peakdetector and storeOutlierData a single function
-    // Input: mOutlierData. Looks at time elapsed between outliers
-    // finds significant changes in the distribution
-    // writes timestamps of significant changes to mPeakTimestamps
-    void detectPeaks();
-
-    // runs analysis on timestamp series before it is converted to a histogram
-    // finds outliers
-    // writes to mOutlierData <time elapsed since previous outlier, outlier timestamp>
-    void storeOutlierData(const std::vector<timestamp_raw> &timestamps);
-
-    // input: series of short histograms. Generates a string of analysis of the buffer periods
-    // TODO: WIP write more detailed analysis
-    // FIXME: move this data visualization to a separate class. Model/view/controller
-    void reportPerformance(String8 *body, int maxHeight = 10);
-
-    // TODO: delete this. temp for testing
-    void testFunction();
-
-    // This function used to detect glitches in a time series
-    // TODO incorporate this into the analysis (currently unused)
-    void alertIfGlitch(const std::vector<timestamp_raw> &samples);
-
-private:
-
-    // stores outlier analysis: <elapsed time between outliers in ms, outlier timestamp>
-    std::deque<std::pair<outlierInterval, timestamp>> mOutlierData;
-
-    // stores each timestamp at which a peak was detected
-    // a peak is a moment at which the average outlier interval changed significantly
-    std::deque<timestamp> mPeakTimestamps;
-
-    // TODO: turn these into circular buffers for better data flow
-    // FIFO of small histograms
-    // stores fixed-size short buffer period histograms with timestamp of first sample
-    std::deque<std::pair<timestamp, Histogram>> mRecentHists;
-
-    // FIFO of small histograms
-    // stores fixed-size long-term buffer period histograms with timestamp of first sample
-    std::deque<std::pair<timestamp, Histogram>> mLongTermHists;
-
-    // vector of timestamps, collected from NBLog for a (TODO) specific thread
-    // when a vector reaches its maximum size, the data is processed and flushed
-    std::vector<timestamp_raw> mTimeStampSeries;
-
-    static const int kMsPerSec = 1000;
-
-    // Parameters used when detecting outliers
-    // TODO: learn some of these from the data, delete unused ones
-    // FIXME: decide whether to make kPeriodMs static.
-    static const int kNumBuff = 3; // number of buffers considered in local history
-    int kPeriodMs; // current period length is ideally 4 ms
-    static const int kOutlierMs = 7; // values greater or equal to this cause glitches
-    // DAC processing time for 4 ms buffer
-    static constexpr double kRatio = 0.75; // estimate of CPU time as ratio of period length
-    int kPeriodMsCPU; // compute based on kPeriodLen and kRatio
-
-    // Peak detection: number of standard deviations from mean considered a significant change
-    static const int kStddevThreshold = 5;
-
-    // capacity allocated to data structures
-    // TODO: adjust all of these values
-    static const int kRecentHistsCapacity = 100; // number of short-term histograms stored in memory
-    static const int kShortHistSize = 50; // number of samples in a short-term histogram
-    static const int kOutlierSeriesSize = 100; // number of values stored in outlier array
-    static const int kPeakSeriesSize = 100; // number of values stored in peak array
-    static const int kLongTermHistsCapacity = 20; // number of long-term histogram stored in memory
-    // maximum elapsed time between first and last timestamp of a long-term histogram
-    static const int kMaxHistTimespanMs = 5 * kMsPerSec;
-
-    // these variables are stored in-class to ensure continuity while analyzing the timestamp
-    // series one short sequence at a time: the variables are not re-initialized every time.
-    // FIXME: create inner class for these variables and decide which other ones to add to it
-    double mPeakDetectorMean = -1;
-    double mPeakDetectorSd = -1;
-    // variables for storeOutlierData
-    uint64_t mElapsed = 0;
-    int64_t mPrevNs = -1;
-
-};
-
-} // namespace ReportPerformance
-
-}   // namespace android
-
-#endif  // ANDROID_MEDIA_PERFORMANCEANALYSIS_H
diff --git a/media/libnbaio/include/media/nbaio/ReportPerformance.h b/media/libnbaio/include/media/nbaio/ReportPerformance.h
deleted file mode 100644
index 27d2810..0000000
--- a/media/libnbaio/include/media/nbaio/ReportPerformance.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2017 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 ANDROID_MEDIA_REPORTPERFORMANCE_H
-#define ANDROID_MEDIA_REPORTPERFORMANCE_H
-
-#include <deque>
-#include <map>
-#include <vector>
-
-namespace android {
-
-// This class is used by reportPerformance function
-// TODO move reportPerformance function to ReportPerformance.cpp
-class String8;
-
-namespace ReportPerformance {
-
-// stores a histogram: key: observed buffer period. value: count
-// TODO: unsigned, unsigned
-using Histogram = std::map<int, int>;
-
-using outlierInterval = uint64_t;
-// int64_t timestamps are converted to uint64_t in PerformanceAnalysis::storeOutlierData,
-// and all analysis functions use uint64_t.
-using timestamp = uint64_t;
-using timestamp_raw = int64_t;
-
-// FIXME: decide whether to use 64 or 32 bits
-// TODO: the code has a mix of typedef and using. Standardize to one or the other.
-typedef uint64_t log_hash_t;
-
-static inline int deltaMs(int64_t ns1, int64_t ns2) {
-    return (ns2 - ns1) / (1000 * 1000);
-}
-
-static inline uint32_t log2(uint32_t x) {
-    // This works for x > 0
-    return 31 - __builtin_clz(x);
-}
-
-// Writes outlier intervals, timestamps, and histograms spanning long time
-// intervals to a file.
-void writeToFile(std::deque<std::pair<outlierInterval, timestamp>> &outlierData,
-                 std::deque<std::pair<timestamp, Histogram>> &hists,
-                 const char * kName,
-                 bool append);
-
-} // namespace ReportPerformance
-
-}   // namespace android
-
-#endif  // ANDROID_MEDIA_REPORTPERFORMANCE_H
diff --git a/media/libnblog/Android.bp b/media/libnblog/Android.bp
new file mode 100644
index 0000000..74aaf77
--- /dev/null
+++ b/media/libnblog/Android.bp
@@ -0,0 +1,28 @@
+cc_library_shared {
+
+    name: "libnblog",
+
+    srcs: [
+        "NBLog.cpp",
+        "PerformanceAnalysis.cpp",
+        "ReportPerformance.cpp",
+    ],
+
+    shared_libs: [
+        "libaudioutils",
+        "libbinder",
+        "libcutils",
+        "liblog",
+        "libutils",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+
+    include_dirs: ["system/media/audio_utils/include"],
+
+    export_include_dirs: ["include"],
+
+}
diff --git a/media/libnbaio/NBLog.cpp b/media/libnblog/NBLog.cpp
similarity index 86%
rename from media/libnbaio/NBLog.cpp
rename to media/libnblog/NBLog.cpp
index 2f639d2..c8c7195 100644
--- a/media/libnbaio/NBLog.cpp
+++ b/media/libnblog/NBLog.cpp
@@ -12,88 +12,16 @@
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
+ *
+ *
  */
 
-/*
-* Documentation: Workflow summary for histogram data processing:
-* For more details on FIFO, please see system/media/audio_utils; doxygen
-* TODO: add this documentation to doxygen once it is further developed
-* 1) Writing buffer period timestamp to the circular buffer
-* onWork()
-*     Called every period length (e.g., 4ms)
-*     Calls LOG_HIST_TS
-* LOG_HIST_TS
-*     Hashes file name and line number, and writes single timestamp to buffer
-*     calls NBLOG::Writer::logEventHistTS once
-* NBLOG::Writer::logEventHistTS
-*     calls NBLOG::Writer::log on hash and current timestamp
-*     time is in CLOCK_MONOTONIC converted to ns
-* NBLOG::Writer::log(Event, const void*, size_t)
-*     Initializes Entry, a struct containing one log entry
-*     Entry contains the event type (mEvent), data length (mLength),
-*     and data pointer (mData)
-*     TODO: why mLength (max length of buffer data)  must be <= kMaxLength = 255?
-*     calls NBLOG::Writer::log(Entry *, bool)
-* NBLog::Writer::log(Entry *, bool)
-*     Calls copyEntryDataAt to format data as follows in temp array:
-*     [type][length][data ... ][length]
-*     calls audio_utils_fifo_writer.write on temp
-* audio_utils_fifo_writer.write
-*     calls obtain(), memcpy (reference in doxygen)
-*     returns number of frames written
-* ssize_t audio_utils_fifo_reader::obtain
-*     Determines readable buffer section via pointer arithmetic on reader
-*     and writer pointers
-* Similarly, LOG_AUDIO_STATE() is called by onStateChange whenever audio is
-* turned on or off, and writes this notification to the FIFO.
-*
-* 2) reading the data from shared memory
-* Thread::threadloop()
-*     TODO: add description?
-* NBLog::MergeThread::threadLoop()
-*     calls NBLog::Merger::merge
-* NBLog::Merger::merge
-*     Merges snapshots sorted by timestamp
-*     for each reader in vector of class NamedReader,
-*     callsNamedReader::reader()->getSnapshot
-*     TODO: check whether the rest of this function is relevant
-* NBLog::Reader::getSnapshot
-*     copies snapshot of reader's fifo buffer into its own buffer
-*     calls mFifoReader->obtain to find readable data
-*     sets snapshot.begin() and .end() iterators to boundaries of valid entries
-*     moves the fifo reader index to after the last entry read
-*     in this case, the buffer is in shared memory. in (4), the buffer is private
-*
-* 3) reading the data from private buffer
-* MediaLogService::dump
-*     calls NBLog::Reader::dump(CONSOLE)
-*     The private buffer contains all logs for all readers in shared memory
-* NBLog::Reader::dump(int)
-*     calls getSnapshot on the current reader
-*     calls dump(int, size_t, Snapshot)
-* NBLog::Reader::dump(int, size, snapshot)
-*     iterates through snapshot's events and switches based on their type
-*     (string, timestamp, etc...)
-*     In the case of EVENT_HISTOGRAM_ENTRY_TS, adds a list of timestamp sequences
-*     (histogram entry) to NBLog::mHists
-*     TODO: add every HISTOGRAM_ENTRY_TS to two
-*     circular buffers: one short-term and one long-term (can add even longer-term
-*     structures in the future). When dump is called, print everything currently
-*     in the buffer.
-* NBLog::drawHistogram
-*     input: timestamp array
-*     buckets this to a histogram and prints
-*
-*/
-
 #define LOG_TAG "NBLog"
-// #define LOG_NDEBUG 0
 
 #include <algorithm>
 #include <climits>
 #include <deque>
 #include <fstream>
-// #include <inttypes.h>
 #include <iostream>
 #include <math.h>
 #include <numeric>
@@ -106,10 +34,10 @@
 #include <time.h>
 #include <new>
 #include <audio_utils/roundup.h>
-#include <media/nbaio/NBLog.h>
-#include <media/nbaio/PerformanceAnalysis.h>
-#include <media/nbaio/ReportPerformance.h>
-// #include <utils/CallStack.h> // used to print callstack
+#include <media/nblog/NBLog.h>
+#include <media/nblog/PerformanceAnalysis.h>
+#include <media/nblog/ReportPerformance.h>
+#include <utils/CallStack.h>
 #include <utils/Log.h>
 #include <utils/String8.h>
 
@@ -760,14 +688,15 @@
 // ---------------------------------------------------------------------------
 
 const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
-                                                           NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
+        NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
+        NBLog::Event::EVENT_AUDIO_STATE};
 const std::set<NBLog::Event> NBLog::Reader::endingTypes   {NBLog::Event::EVENT_END_FMT,
-                                                           NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
-                                                           NBLog::Event::EVENT_AUDIO_STATE};
+        NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
+        NBLog::Event::EVENT_AUDIO_STATE};
 
 NBLog::Reader::Reader(const void *shared, size_t size)
-    : mShared((/*const*/ Shared *) shared), /*mIMemory*/
-      mFd(-1), mIndent(0),
+    : mFd(-1), mIndent(0), mLost(0),
+      mShared((/*const*/ Shared *) shared), /*mIMemory*/
       mFifo(mShared != NULL ?
         new audio_utils_fifo(size, sizeof(uint8_t),
             mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
@@ -805,6 +734,9 @@
     return nullptr; // no entry found
 }
 
+// Copies content of a Reader FIFO into its Snapshot
+// The Snapshot has the same raw data, but represented as a sequence of entries
+// and an EntryIterator making it possible to process the data.
 std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
 {
     if (mFifoReader == NULL) {
@@ -870,24 +802,11 @@
 
 }
 
-// TODO: move this to PerformanceAnalysis
-// TODO: make call to dump periodic so that data in shared FIFO does not get overwritten
-void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
+// Takes raw content of the local merger FIFO, processes log entries, and
+// writes the data to a map of class PerformanceAnalysis, based on their thread ID.
+void NBLog::MergeReader::getAndProcessSnapshot(NBLog::Reader::Snapshot &snapshot)
 {
-    mFd = fd;
-    mIndent = indent;
     String8 timestamp, body;
-    // FIXME: this is not thread safe
-    // TODO: need a separate instance of performanceAnalysis for each thread
-    // used to store data and to call analysis functions
-    static ReportPerformance::PerformanceAnalysis performanceAnalysis;
-    size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
-    if (lost > 0) {
-        body.appendFormat("warning: lost %zu bytes worth of events", lost);
-        // TODO timestamp empty here, only other choice to wait for the first timestamp event in the
-        //      log to push it out.  Consider keeping the timestamp/body between calls to copyEntryDataAt().
-        dumpLine(timestamp, body);
-    }
 
     for (auto entry = snapshot.begin(); entry != snapshot.end();) {
         switch (entry->type) {
@@ -902,12 +821,22 @@
             memcpy(&hash, &(data->hash), sizeof(hash));
             int64_t ts;
             memcpy(&ts, &data->ts, sizeof(ts));
-            performanceAnalysis.logTsEntry(ts);
+            // TODO: hash for histogram ts and audio state need to match
+            // and correspond to audio production source file location
+            mThreadPerformanceAnalysis[data->author][0 /*hash*/].logTsEntry(ts);
             ++entry;
             break;
         }
         case EVENT_AUDIO_STATE: {
-            performanceAnalysis.handleStateChange();
+            HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
+            // TODO This memcpies are here to avoid unaligned memory access crash.
+            // There's probably a more efficient way to do it
+            log_hash_t hash;
+            memcpy(&hash, &(data->hash), sizeof(hash));
+            // TODO: remove ts if unused
+            int64_t ts;
+            memcpy(&ts, &data->ts, sizeof(ts));
+            mThreadPerformanceAnalysis[data->author][0 /*hash*/].handleStateChange();
             ++entry;
             break;
         }
@@ -922,19 +851,25 @@
             break;
         }
     }
-    performanceAnalysis.reportPerformance(&body);
+    // FIXME: decide whether to print the warnings here or elsewhere
     if (!body.isEmpty()) {
         dumpLine(timestamp, body);
     }
 }
 
-void NBLog::Reader::dump(int fd, size_t indent)
+void NBLog::MergeReader::getAndProcessSnapshot()
 {
-    // get a snapshot, dump it
+    // get a snapshot, process it
     std::unique_ptr<Snapshot> snap = getSnapshot();
-    dump(fd, indent, *snap);
+    getAndProcessSnapshot(*snap);
 }
 
+void NBLog::MergeReader::dump(int fd, int indent) {
+    // TODO: add a mutex around media.log dump
+    ReportPerformance::dump(fd, indent, mThreadPerformanceAnalysis);
+}
+
+// Writes a string to the console
 void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
 {
     if (mFd >= 0) {
@@ -1093,6 +1028,7 @@
       {}
 
 void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
+
     // FIXME This is called by binder thread in MediaLogService::registerWriter
     //       but the access to shared variable mNamedReaders is not yet protected by a lock.
     mNamedReaders.push_back(reader);
@@ -1116,7 +1052,7 @@
     return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
 }
 
-// Merge registered readers, sorted by timestamp
+// Merge registered readers, sorted by timestamp, and write data to a single FIFO in local memory
 void NBLog::Merger::merge() {
     // FIXME This is called by merge thread
     //       but the access to shared variable mNamedReaders is not yet protected by a lock.
@@ -1173,8 +1109,9 @@
 
 // ---------------------------------------------------------------------------
 
-NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
+NBLog::MergeThread::MergeThread(NBLog::Merger &merger, NBLog::MergeReader &mergeReader)
     : mMerger(merger),
+      mMergeReader(mergeReader),
       mTimeoutUs(0) {}
 
 NBLog::MergeThread::~MergeThread() {
@@ -1196,7 +1133,12 @@
         mTimeoutUs -= kThreadSleepPeriodUs;
     }
     if (doMerge) {
+        // Merge data from all the readers
         mMerger.merge();
+        // Process the data collected by mMerger and write it to PerformanceAnalysis
+        // FIXME: decide whether to call getAndProcessSnapshot every time
+        // or whether to have a separate thread that calls it with a lower frequency
+        mMergeReader.getAndProcessSnapshot();
     }
     return true;
 }
diff --git a/media/libnblog/PerformanceAnalysis.cpp b/media/libnblog/PerformanceAnalysis.cpp
new file mode 100644
index 0000000..478c460
--- /dev/null
+++ b/media/libnblog/PerformanceAnalysis.cpp
@@ -0,0 +1,377 @@
+/*
+ * Copyright (C) 2017 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 "PerformanceAnalysis"
+// #define LOG_NDEBUG 0
+
+#include <algorithm>
+#include <climits>
+#include <deque>
+#include <iostream>
+#include <math.h>
+#include <numeric>
+#include <vector>
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <time.h>
+#include <new>
+#include <audio_utils/roundup.h>
+#include <media/nblog/NBLog.h>
+#include <media/nblog/PerformanceAnalysis.h>
+#include <media/nblog/ReportPerformance.h>
+#include <utils/Log.h>
+#include <utils/String8.h>
+
+#include <queue>
+#include <utility>
+
+namespace android {
+
+namespace ReportPerformance {
+
+// Given an audio processing wakeup timestamp, buckets the time interval
+// since the previous timestamp into a histogram, searches for
+// outliers, analyzes the outlier series for unexpectedly
+// small or large values and stores these as peaks
+void PerformanceAnalysis::logTsEntry(timestamp ts) {
+    // after a state change, start a new series and do not
+    // record time intervals in-between
+    if (mBufferPeriod.mPrevTs == 0) {
+        mBufferPeriod.mPrevTs = ts;
+        return;
+    }
+
+    // calculate time interval between current and previous timestamp
+    const msInterval diffMs = static_cast<msInterval>(
+        deltaMs(mBufferPeriod.mPrevTs, ts));
+
+    const int diffJiffy = deltaJiffy(mBufferPeriod.mPrevTs, ts);
+
+    // old versus new weight ratio when updating the buffer period mean
+    static constexpr double exponentialWeight = 0.999;
+    // update buffer period mean with exponential weighting
+    mBufferPeriod.mMean = (mBufferPeriod.mMean < 0) ? diffMs :
+            exponentialWeight * mBufferPeriod.mMean + (1.0 - exponentialWeight) * diffMs;
+    // set mOutlierFactor to a smaller value for the fastmixer thread
+    const int kFastMixerMax = 10;
+    // NormalMixer times vary much more than FastMixer times.
+    // TODO: mOutlierFactor values are set empirically based on what appears to be
+    // an outlier. Learn these values from the data.
+    mBufferPeriod.mOutlierFactor = mBufferPeriod.mMean < kFastMixerMax ? 1.8 : 2.0;
+    // set outlier threshold
+    mBufferPeriod.mOutlier = mBufferPeriod.mMean * mBufferPeriod.mOutlierFactor;
+
+    // Check whether the time interval between the current timestamp
+    // and the previous one is long enough to count as an outlier
+    const bool isOutlier = detectAndStoreOutlier(diffMs);
+    // If an outlier was found, check whether it was a peak
+    if (isOutlier) {
+        /*bool isPeak =*/ detectAndStorePeak(
+            mOutlierData[0].first, mOutlierData[0].second);
+        // TODO: decide whether to insert a new empty histogram if a peak
+        // TODO: remove isPeak if unused to avoid "unused variable" error
+        // occurred at the current timestamp
+    }
+
+    // Insert a histogram to mHists if it is empty, or
+    // close the current histogram and insert a new empty one if
+    // if the current histogram has spanned its maximum time interval.
+    if (mHists.empty() ||
+        deltaMs(mHists[0].first, ts) >= kMaxLength.HistTimespanMs) {
+        mHists.emplace_front(ts, std::map<int, int>());
+        // When memory is full, delete oldest histogram
+        // TODO: use a circular buffer
+        if (mHists.size() >= kMaxLength.Hists) {
+            mHists.resize(kMaxLength.Hists);
+        }
+    }
+    // add current time intervals to histogram
+    ++mHists[0].second[diffJiffy];
+    // update previous timestamp
+    mBufferPeriod.mPrevTs = ts;
+}
+
+
+// forces short-term histogram storage to avoid adding idle audio time interval
+// to buffer period data
+void PerformanceAnalysis::handleStateChange() {
+    mBufferPeriod.mPrevTs = 0;
+    return;
+}
+
+
+// Checks whether the time interval between two outliers is far enough from
+// a typical delta to be considered a peak.
+// looks for changes in distribution (peaks), which can be either positive or negative.
+// The function sets the mean to the starting value and sigma to 0, and updates
+// them as long as no peak is detected. When a value is more than 'threshold'
+// standard deviations from the mean, a peak is detected and the mean and sigma
+// are set to the peak value and 0.
+bool PerformanceAnalysis::detectAndStorePeak(msInterval diff, timestamp ts) {
+    bool isPeak = false;
+    if (mOutlierData.empty()) {
+        return false;
+    }
+    // Update mean of the distribution
+    // TypicalDiff is used to check whether a value is unusually large
+    // when we cannot use standard deviations from the mean because the sd is set to 0.
+    mOutlierDistribution.mTypicalDiff = (mOutlierDistribution.mTypicalDiff *
+            (mOutlierData.size() - 1) + diff) / mOutlierData.size();
+
+    // Initialize short-term mean at start of program
+    if (mOutlierDistribution.mMean == 0) {
+        mOutlierDistribution.mMean = diff;
+    }
+    // Update length of current sequence of outliers
+    mOutlierDistribution.mN++;
+
+    // Check whether a large deviation from the mean occurred.
+    // If the standard deviation has been reset to zero, the comparison is
+    // instead to the mean of the full mOutlierInterval sequence.
+    if ((fabs(diff - mOutlierDistribution.mMean) <
+            mOutlierDistribution.kMaxDeviation * mOutlierDistribution.mSd) ||
+            (mOutlierDistribution.mSd == 0 &&
+            fabs(diff - mOutlierDistribution.mMean) <
+            mOutlierDistribution.mTypicalDiff)) {
+        // update the mean and sd using online algorithm
+        // https://en.wikipedia.org/wiki/
+        // Algorithms_for_calculating_variance#Online_algorithm
+        mOutlierDistribution.mN++;
+        const double kDelta = diff - mOutlierDistribution.mMean;
+        mOutlierDistribution.mMean += kDelta / mOutlierDistribution.mN;
+        const double kDelta2 = diff - mOutlierDistribution.mMean;
+        mOutlierDistribution.mM2 += kDelta * kDelta2;
+        mOutlierDistribution.mSd = (mOutlierDistribution.mN < 2) ? 0 :
+                sqrt(mOutlierDistribution.mM2 / (mOutlierDistribution.mN - 1));
+    } else {
+        // new value is far from the mean:
+        // store peak timestamp and reset mean, sd, and short-term sequence
+        isPeak = true;
+        mPeakTimestamps.emplace_front(ts);
+        // if mPeaks has reached capacity, delete oldest data
+        // Note: this means that mOutlierDistribution values do not exactly
+        // match the data we have in mPeakTimestamps, but this is not an issue
+        // in practice for estimating future peaks.
+        // TODO: turn this into a circular buffer
+        if (mPeakTimestamps.size() >= kMaxLength.Peaks) {
+            mPeakTimestamps.resize(kMaxLength.Peaks);
+        }
+        mOutlierDistribution.mMean = 0;
+        mOutlierDistribution.mSd = 0;
+        mOutlierDistribution.mN = 0;
+        mOutlierDistribution.mM2 = 0;
+    }
+    return isPeak;
+}
+
+
+// Determines whether the difference between a timestamp and the previous
+// one is beyond a threshold. If yes, stores the timestamp as an outlier
+// and writes to mOutlierdata in the following format:
+// Time elapsed since previous outlier: Timestamp of start of outlier
+// e.g. timestamps (ms) 1, 4, 5, 16, 18, 28 will produce pairs (4, 5), (13, 18).
+// TODO: learn what timestamp sequences correlate with glitches instead of
+// manually designing a heuristic.
+bool PerformanceAnalysis::detectAndStoreOutlier(const msInterval diffMs) {
+    bool isOutlier = false;
+    if (diffMs >= mBufferPeriod.mOutlier) {
+        isOutlier = true;
+        mOutlierData.emplace_front(
+                mOutlierDistribution.mElapsed, mBufferPeriod.mPrevTs);
+        // Remove oldest value if the vector is full
+        // TODO: turn this into a circular buffer
+        // TODO: make sure kShortHistSize is large enough that that data will never be lost
+        // before being written to file or to a FIFO
+        if (mOutlierData.size() >= kMaxLength.Outliers) {
+            mOutlierData.resize(kMaxLength.Outliers);
+        }
+        mOutlierDistribution.mElapsed = 0;
+    }
+    mOutlierDistribution.mElapsed += diffMs;
+    return isOutlier;
+}
+
+static int widthOf(int x) {
+    int width = 0;
+    if (x < 0) {
+        width++;
+        x = x == INT_MIN ? INT_MAX : -x;
+    }
+    // assert (x >= 0)
+    do {
+        ++width;
+        x /= 10;
+    } while (x > 0);
+    return width;
+}
+
+// computes the column width required for a specific histogram value
+inline int numberWidth(double number, int leftPadding) {
+    // Added values account for whitespaces needed around numbers, and for the
+    // dot and decimal digit not accounted for by widthOf
+    return std::max(std::max(widthOf(static_cast<int>(number)) + 3, 2), leftPadding + 1);
+}
+
+// rounds value to precision based on log-distance from mean
+inline double logRound(double x, double mean) {
+    // Larger values decrease range of high resolution and prevent overflow
+    // of a histogram on the console.
+    // The following formula adjusts kBase based on the buffer period length.
+    // Different threads have buffer periods ranging from 2 to 40. The
+    // formula below maps buffer period 2 to kBase = ~1, 4 to ~2, 20 to ~3, 40 to ~4.
+    // TODO: tighten this for higher means, the data still overflows
+    const double kBase = log(mean) / log(2.2);
+    const double power = floor(
+        log(abs(x - mean) / mean) / log(kBase)) + 2;
+    // do not round values close to the mean
+    if (power < 1) {
+        return x;
+    }
+    const int factor = static_cast<int>(pow(10, power));
+    return (static_cast<int>(x) * factor) / factor;
+}
+
+// TODO Make it return a std::string instead of modifying body
+// TODO: move this to ReportPerformance, probably make it a friend function
+// of PerformanceAnalysis
+void PerformanceAnalysis::reportPerformance(String8 *body, int author, log_hash_t hash,
+                                            int maxHeight) {
+    if (mHists.empty()) {
+        return;
+    }
+
+    // ms of active audio in displayed histogram
+    double elapsedMs = 0;
+    // starting timestamp of histogram
+    timestamp startingTs = mHists[0].first;
+
+    // histogram which stores .1 precision ms counts instead of Jiffy multiple counts
+    std::map<double, int> buckets;
+    for (const auto &shortHist: mHists) {
+        for (const auto &countPair : shortHist.second) {
+            const double ms = static_cast<double>(countPair.first) / kJiffyPerMs;
+            buckets[logRound(ms, mBufferPeriod.mMean)] += countPair.second;
+            elapsedMs += ms * countPair.second;
+        }
+    }
+
+    // underscores and spaces length corresponds to maximum width of histogram
+    static const int kLen = 200;
+    std::string underscores(kLen, '_');
+    std::string spaces(kLen, ' ');
+
+    auto it = buckets.begin();
+    double maxDelta = it->first;
+    int maxCount = it->second;
+    // Compute maximum values
+    while (++it != buckets.end()) {
+        if (it->first > maxDelta) {
+            maxDelta = it->first;
+        }
+        if (it->second > maxCount) {
+            maxCount = it->second;
+        }
+    }
+    int height = log2(maxCount) + 1; // maxCount > 0, safe to call log2
+    const int leftPadding = widthOf(1 << height);
+    const int bucketWidth = numberWidth(maxDelta, leftPadding);
+    int scalingFactor = 1;
+    // scale data if it exceeds maximum height
+    if (height > maxHeight) {
+        scalingFactor = (height + maxHeight) / maxHeight;
+        height /= scalingFactor;
+    }
+    body->appendFormat("\n%*s %3.2f %s", leftPadding + 11,
+            "Occurrences in", (elapsedMs / kMsPerSec), "seconds of audio:");
+    body->appendFormat("\n%*s%d, %lld, %lld\n", leftPadding + 11,
+            "Thread, hash, starting timestamp: ", author,
+            static_cast<long long int>(hash), static_cast<long long int>(startingTs));
+    // write histogram label line with bucket values
+    body->appendFormat("\n%s", " ");
+    body->appendFormat("%*s", leftPadding, " ");
+    for (auto const &x : buckets) {
+        const int colWidth = numberWidth(x.first, leftPadding);
+        body->appendFormat("%*d", colWidth, x.second);
+    }
+    // write histogram ascii art
+    body->appendFormat("\n%s", " ");
+    for (int row = height * scalingFactor; row >= 0; row -= scalingFactor) {
+        const int value = 1 << row;
+        body->appendFormat("%.*s", leftPadding, spaces.c_str());
+        for (auto const &x : buckets) {
+            const int colWidth = numberWidth(x.first, leftPadding);
+            body->appendFormat("%.*s%s", colWidth - 1,
+                               spaces.c_str(), x.second < value ? " " : "|");
+        }
+        body->appendFormat("\n%s", " ");
+    }
+    // print x-axis
+    const int columns = static_cast<int>(buckets.size());
+    body->appendFormat("%*c", leftPadding, ' ');
+    body->appendFormat("%.*s", (columns + 1) * bucketWidth, underscores.c_str());
+    body->appendFormat("\n%s", " ");
+
+    // write footer with bucket labels
+    body->appendFormat("%*s", leftPadding, " ");
+    for (auto const &x : buckets) {
+        const int colWidth = numberWidth(x.first, leftPadding);
+        body->appendFormat("%*.*f", colWidth, 1, x.first);
+    }
+    body->appendFormat("%.*s%s", bucketWidth, spaces.c_str(), "ms\n");
+
+    // Now report glitches
+    body->appendFormat("\ntime elapsed between glitches and glitch timestamps:\n");
+    for (const auto &outlier: mOutlierData) {
+        body->appendFormat("%lld: %lld\n", static_cast<long long>(outlier.first),
+                           static_cast<long long>(outlier.second));
+    }
+}
+
+//------------------------------------------------------------------------------
+
+// writes summary of performance into specified file descriptor
+void dump(int fd, int indent, PerformanceAnalysisMap &threadPerformanceAnalysis) {
+    String8 body;
+    const char* const kDirectory = "/data/misc/audioserver/";
+    for (auto & thread : threadPerformanceAnalysis) {
+        for (auto & hash: thread.second) {
+            PerformanceAnalysis& curr = hash.second;
+            // write performance data to console
+            curr.reportPerformance(&body, thread.first, hash.first);
+            if (!body.isEmpty()) {
+                dumpLine(fd, indent, body);
+                body.clear();
+            }
+            // write to file
+            writeToFile(curr.mHists, curr.mOutlierData, curr.mPeakTimestamps,
+                        kDirectory, false, thread.first, hash.first);
+        }
+    }
+}
+
+
+// Writes a string into specified file descriptor
+void dumpLine(int fd, int indent, const String8 &body) {
+    dprintf(fd, "%.*s%s \n", indent, "", body.string());
+}
+
+} // namespace ReportPerformance
+
+}   // namespace android
diff --git a/media/libnblog/ReportPerformance.cpp b/media/libnblog/ReportPerformance.cpp
new file mode 100644
index 0000000..827e731
--- /dev/null
+++ b/media/libnblog/ReportPerformance.cpp
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2017 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 "ReportPerformance"
+
+#include <fstream>
+#include <iostream>
+#include <queue>
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <sstream>
+#include <sys/prctl.h>
+#include <sys/time.h>
+#include <utility>
+#include <media/nblog/NBLog.h>
+#include <media/nblog/PerformanceAnalysis.h>
+#include <media/nblog/ReportPerformance.h>
+#include <utils/Log.h>
+#include <utils/String8.h>
+
+namespace android {
+
+namespace ReportPerformance {
+
+
+// TODO: use a function like this to extract logic from writeToFile
+// https://stackoverflow.com/a/9279620
+
+// Writes outlier intervals, timestamps, and histograms spanning long time intervals to file.
+// TODO: write data in binary format
+void writeToFile(const std::deque<std::pair<timestamp, Histogram>> &hists,
+                 const std::deque<std::pair<msInterval, timestamp>> &outlierData,
+                 const std::deque<timestamp> &peakTimestamps,
+                 const char * directory, bool append, int author, log_hash_t hash) {
+
+    // TODO: remove old files, implement rotating files as in AudioFlinger.cpp
+
+    if (outlierData.empty() && hists.empty() && peakTimestamps.empty()) {
+        ALOGW("No data, returning.");
+        return;
+    }
+
+    std::stringstream outlierName;
+    std::stringstream histogramName;
+    std::stringstream peakName;
+
+    // get current time
+    char currTime[16]; //YYYYMMDDHHMMSS + '\0' + one unused
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    struct tm tm;
+    localtime_r(&tv.tv_sec, &tm);
+    strftime(currTime, sizeof(currTime), "%Y%m%d%H%M%S", &tm);
+
+    // generate file names
+    std::stringstream common;
+    common << author << "_" << hash << "_" << currTime << ".csv";
+
+    histogramName << directory << "histograms_" << common.str();
+    outlierName << directory << "outliers_" << common.str();
+    peakName << directory << "peaks_" << common.str();
+
+    std::ofstream hfs;
+    hfs.open(histogramName.str(), append ? std::ios::app : std::ios::trunc);
+    if (!hfs.is_open()) {
+        ALOGW("couldn't open file %s", histogramName.str().c_str());
+        return;
+    }
+    // each histogram is written as a line where the first value is the timestamp and
+    // subsequent values are pairs of buckets and counts. Each value is separated
+    // by a comma, and each histogram is separated by a newline.
+    for (auto hist = hists.begin(); hist != hists.end(); ++hist) {
+        hfs << hist->first << ", ";
+        for (auto bucket = hist->second.begin(); bucket != hist->second.end(); ++bucket) {
+            hfs << bucket->first / static_cast<double>(kJiffyPerMs)
+                << ", " << bucket->second;
+            if (std::next(bucket) != end(hist->second)) {
+                hfs << ", ";
+            }
+        }
+        if (std::next(hist) != end(hists)) {
+            hfs << "\n";
+        }
+    }
+    hfs.close();
+
+    std::ofstream ofs;
+    ofs.open(outlierName.str(), append ? std::ios::app : std::ios::trunc);
+    if (!ofs.is_open()) {
+        ALOGW("couldn't open file %s", outlierName.str().c_str());
+        return;
+    }
+    // outliers are written as pairs separated by newlines, where each
+    // pair's values are separated by a comma
+    for (const auto &outlier : outlierData) {
+        ofs << outlier.first << ", " << outlier.second << "\n";
+    }
+    ofs.close();
+
+    std::ofstream pfs;
+    pfs.open(peakName.str(), append ? std::ios::app : std::ios::trunc);
+    if (!pfs.is_open()) {
+        ALOGW("couldn't open file %s", peakName.str().c_str());
+        return;
+    }
+    // peaks are simply timestamps separated by commas
+    for (auto peak = peakTimestamps.begin(); peak != peakTimestamps.end(); ++peak) {
+        pfs << *peak;
+        if (std::next(peak) != end(peakTimestamps)) {
+            pfs << ", ";
+        }
+    }
+    pfs.close();
+}
+
+} // namespace ReportPerformance
+
+}   // namespace android
diff --git a/media/libnblog/include/media/nblog/NBLog.h b/media/libnblog/include/media/nblog/NBLog.h
new file mode 100644
index 0000000..ebb88f0
--- /dev/null
+++ b/media/libnblog/include/media/nblog/NBLog.h
@@ -0,0 +1,613 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+// Non-blocking event logger intended for safe communication between processes via shared memory
+
+#ifndef ANDROID_MEDIA_NBLOG_H
+#define ANDROID_MEDIA_NBLOG_H
+
+#include <deque>
+#include <map>
+#include <set>
+#include <vector>
+
+#include <audio_utils/fifo.h>
+#include <binder/IMemory.h>
+#include <media/nblog/PerformanceAnalysis.h>
+#include <media/nblog/ReportPerformance.h>
+#include <utils/Mutex.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class String8;
+
+class NBLog {
+
+public:
+
+    using log_hash_t = ReportPerformance::log_hash_t;
+
+    // FIXME Everything needed for client (writer API and registration) should be isolated
+    //       from the rest of the implementation.
+    class Writer;
+    class Reader;
+
+    enum Event : uint8_t {
+        EVENT_RESERVED,
+        EVENT_STRING,               // ASCII string, not NUL-terminated
+                                    // TODO: make timestamp optional
+        EVENT_TIMESTAMP,            // clock_gettime(CLOCK_MONOTONIC)
+        EVENT_INTEGER,              // integer value entry
+        EVENT_FLOAT,                // floating point value entry
+        EVENT_PID,                  // process ID and process name
+        EVENT_AUTHOR,               // author index (present in merged logs) tracks entry's
+                                    // original log
+        EVENT_START_FMT,            // logFormat start event: entry includes format string,
+                                    // following entries contain format arguments
+        EVENT_HASH,                 // unique HASH of log origin, originates from hash of file name
+                                    // and line number
+        EVENT_HISTOGRAM_ENTRY_TS,   // single datum for timestamp histogram
+        EVENT_AUDIO_STATE,          // audio on/off event: logged on FastMixer::onStateChange call
+        EVENT_END_FMT,              // end of logFormat argument list
+
+        EVENT_UPPER_BOUND,          // to check for invalid events
+    };
+
+private:
+
+    // ---------------------------------------------------------------------------
+    // API for handling format entry operations
+
+    // a formatted entry has the following structure:
+    //    * START_FMT entry, containing the format string
+    //    * TIMESTAMP entry
+    //    * HASH entry
+    //    * author entry of the thread that generated it (optional, present in merged log)
+    //    * format arg1
+    //    * format arg2
+    //    * ...
+    //    * END_FMT entry
+
+    // entry representation in memory
+    struct entry {
+        const uint8_t type;
+        const uint8_t length;
+        const uint8_t data[0];
+    };
+
+    // entry tail representation (after data)
+    struct ending {
+        uint8_t length;
+        uint8_t next[0];
+    };
+
+    // entry iterator
+    class EntryIterator {
+    public:
+        EntryIterator();
+        explicit EntryIterator(const uint8_t *entry);
+        EntryIterator(const EntryIterator &other);
+
+        // dereference underlying entry
+        const entry&    operator*() const;
+        const entry*    operator->() const;
+        // advance to next entry
+        EntryIterator&       operator++(); // ++i
+        // back to previous entry
+        EntryIterator&       operator--(); // --i
+        EntryIterator        next() const;
+        EntryIterator        prev() const;
+        bool            operator!=(const EntryIterator &other) const;
+        int             operator-(const EntryIterator &other) const;
+
+        bool            hasConsistentLength() const;
+        void            copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const;
+        void            copyData(uint8_t *dst) const;
+
+        template<typename T>
+        inline const T& payload() {
+            return *reinterpret_cast<const T *>(ptr + offsetof(entry, data));
+        }
+
+        inline operator const uint8_t*() const {
+            return ptr;
+        }
+
+    private:
+        const uint8_t  *ptr;
+    };
+
+    class AbstractEntry {
+    public:
+
+        // Entry starting in the given pointer
+        explicit AbstractEntry(const uint8_t *entry);
+        virtual ~AbstractEntry() {}
+
+        // build concrete entry of appropriate class from pointer
+        static std::unique_ptr<AbstractEntry> buildEntry(const uint8_t *ptr);
+
+        // get format entry timestamp
+        virtual int64_t      timestamp() const = 0;
+
+        // get format entry's unique id
+        virtual log_hash_t   hash() const = 0;
+
+        // entry's author index (-1 if none present)
+        // a Merger has a vector of Readers, author simply points to the index of the
+        // Reader that originated the entry
+        // TODO consider changing to uint32_t
+        virtual int          author() const = 0;
+
+        // copy entry, adding author before timestamp, returns iterator to end of entry
+        virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
+                                                int author) const = 0;
+
+    protected:
+        // copies ordinary entry from src to dst, and returns length of entry
+        // size_t      copyEntry(audio_utils_fifo_writer *dst, const iterator &it);
+        const uint8_t  *mEntry;
+    };
+
+    class FormatEntry : public AbstractEntry {
+    public:
+        // explicit FormatEntry(const EntryIterator &it);
+        explicit FormatEntry(const uint8_t *ptr) : AbstractEntry(ptr) {}
+        virtual ~FormatEntry() {}
+
+        EntryIterator begin() const;
+
+        // Entry's format string
+        const   char* formatString() const;
+
+        // Enrty's format string length
+        size_t      formatStringLength() const;
+
+        // Format arguments (excluding format string, timestamp and author)
+        EntryIterator    args() const;
+
+        // get format entry timestamp
+        virtual int64_t     timestamp() const override;
+
+        // get format entry's unique id
+        virtual log_hash_t  hash() const override;
+
+        // entry's author index (-1 if none present)
+        // a Merger has a vector of Readers, author simply points to the index of the
+        // Reader that originated the entry
+        virtual int         author() const override;
+
+        // copy entry, adding author before timestamp, returns size of original entry
+        virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
+                                                int author) const override;
+
+    };
+
+    class HistogramEntry : public AbstractEntry {
+    public:
+        explicit HistogramEntry(const uint8_t *ptr) : AbstractEntry(ptr) {
+        }
+        virtual ~HistogramEntry() {}
+
+        virtual int64_t     timestamp() const override;
+
+        virtual log_hash_t  hash() const override;
+
+        virtual int         author() const override;
+
+        virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
+                                                int author) const override;
+
+    };
+
+    // ---------------------------------------------------------------------------
+
+    // representation of a single log entry in private memory
+    struct Entry {
+        Entry(Event event, const void *data, size_t length)
+            : mEvent(event), mLength(length), mData(data) { }
+        /*virtual*/ ~Entry() { }
+
+        // used during writing to format Entry information as follows:
+        // [type][length][data ... ][length]
+        int     copyEntryDataAt(size_t offset) const;
+
+    private:
+        friend class Writer;
+        Event       mEvent;     // event type
+        uint8_t     mLength;    // length of additional data, 0 <= mLength <= kMaxLength
+        const void *mData;      // event type-specific data
+        static const size_t kMaxLength = 255;
+    public:
+        // mEvent, mLength, mData[...], duplicate mLength
+        static const size_t kOverhead = sizeof(entry) + sizeof(ending);
+        // endind length of previous entry
+        static const size_t kPreviousLengthOffset = - sizeof(ending) +
+            offsetof(ending, length);
+    };
+
+    struct HistTsEntry {
+        log_hash_t hash;
+        int64_t ts;
+    }; //TODO __attribute__((packed));
+
+    struct HistTsEntryWithAuthor {
+        log_hash_t hash;
+        int64_t ts;
+        int author;
+    }; //TODO __attribute__((packed));
+
+    struct HistIntEntry {
+        log_hash_t hash;
+        int value;
+    }; //TODO __attribute__((packed));
+
+    // representation of a single log entry in shared memory
+    //  byte[0]             mEvent
+    //  byte[1]             mLength
+    //  byte[2]             mData[0]
+    //  ...
+    //  byte[2+i]           mData[i]
+    //  ...
+    //  byte[2+mLength-1]   mData[mLength-1]
+    //  byte[2+mLength]     duplicate copy of mLength to permit reverse scan
+    //  byte[3+mLength]     start of next log entry
+
+    static void    appendInt(String8 *body, const void *data);
+    static void    appendFloat(String8 *body, const void *data);
+    static void    appendPID(String8 *body, const void *data, size_t length);
+    static void    appendTimestamp(String8 *body, const void *data);
+    static size_t  fmtEntryLength(const uint8_t *data);
+    static String8 bufferDump(const uint8_t *buffer, size_t size);
+    static String8 bufferDump(const EntryIterator &it);
+public:
+
+    // Located in shared memory, must be POD.
+    // Exactly one process must explicitly call the constructor or use placement new.
+    // Since this is a POD, the destructor is empty and unnecessary to call it explicitly.
+    struct Shared {
+        Shared() /* mRear initialized via default constructor */ { }
+        /*virtual*/ ~Shared() { }
+
+        audio_utils_fifo_index  mRear;  // index one byte past the end of most recent Entry
+        char    mBuffer[0];             // circular buffer for entries
+    };
+
+public:
+
+    // ---------------------------------------------------------------------------
+
+    // FIXME Timeline was intended to wrap Writer and Reader, but isn't actually used yet.
+    // For now it is just a namespace for sharedSize().
+    class Timeline : public RefBase {
+    public:
+#if 0
+        Timeline(size_t size, void *shared = NULL);
+        virtual ~Timeline();
+#endif
+
+        // Input parameter 'size' is the desired size of the timeline in byte units.
+        // Returns the size rounded up to a power-of-2, plus the constant size overhead for indices.
+        static size_t sharedSize(size_t size);
+
+#if 0
+    private:
+        friend class    Writer;
+        friend class    Reader;
+
+        const size_t    mSize;      // circular buffer size in bytes, must be a power of 2
+        bool            mOwn;       // whether I own the memory at mShared
+        Shared* const   mShared;    // pointer to shared memory
+#endif
+    };
+
+    // ---------------------------------------------------------------------------
+
+    // Writer is thread-safe with respect to Reader, but not with respect to multiple threads
+    // calling Writer methods.  If you need multi-thread safety for writing, use LockedWriter.
+    class Writer : public RefBase {
+    public:
+        Writer();                   // dummy nop implementation without shared memory
+
+        // Input parameter 'size' is the desired size of the timeline in byte units.
+        // The size of the shared memory must be at least Timeline::sharedSize(size).
+        Writer(void *shared, size_t size);
+        Writer(const sp<IMemory>& iMemory, size_t size);
+
+        virtual ~Writer();
+
+        // FIXME needs comments, and some should be private
+        virtual void    log(const char *string);
+        virtual void    logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
+        virtual void    logvf(const char *fmt, va_list ap);
+        virtual void    logTimestamp();
+        virtual void    logTimestamp(const int64_t ts);
+        virtual void    logInteger(const int x);
+        virtual void    logFloat(const float x);
+        virtual void    logPID();
+        virtual void    logFormat(const char *fmt, log_hash_t hash, ...);
+        virtual void    logVFormat(const char *fmt, log_hash_t hash, va_list ap);
+        virtual void    logStart(const char *fmt);
+        virtual void    logEnd();
+        virtual void    logHash(log_hash_t hash);
+        virtual void    logEventHistTs(Event event, log_hash_t hash);
+
+        virtual bool    isEnabled() const;
+
+        // return value for all of these is the previous isEnabled()
+        virtual bool    setEnabled(bool enabled);   // but won't enable if no shared memory
+        bool    enable()    { return setEnabled(true); }
+        bool    disable()   { return setEnabled(false); }
+
+        sp<IMemory>     getIMemory() const  { return mIMemory; }
+
+    private:
+        // 0 <= length <= kMaxLength
+        // writes a single Entry to the FIFO
+        void    log(Event event, const void *data, size_t length);
+        // checks validity of an event before calling log above this one
+        void    log(const Entry *entry, bool trusted = false);
+
+        Shared* const   mShared;    // raw pointer to shared memory
+        sp<IMemory>     mIMemory;   // ref-counted version, initialized in constructor
+                                    // and then const
+        audio_utils_fifo * const mFifo;                 // FIFO itself, non-NULL
+                                                        // unless constructor fails
+        audio_utils_fifo_writer * const mFifoWriter;    // used to write to FIFO, non-NULL
+                                                        // unless dummy constructor used
+        bool            mEnabled;   // whether to actually log
+
+        // cached pid and process name to use in %p format specifier
+        // total tag length is mPidTagSize and process name is not zero terminated
+        char   *mPidTag;
+        size_t  mPidTagSize;
+    };
+
+    // ---------------------------------------------------------------------------
+
+    // Similar to Writer, but safe for multiple threads to call concurrently
+    class LockedWriter : public Writer {
+    public:
+        LockedWriter();
+        LockedWriter(void *shared, size_t size);
+
+        virtual void    log(const char *string);
+        virtual void    logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
+        virtual void    logvf(const char *fmt, va_list ap);
+        virtual void    logTimestamp();
+        virtual void    logTimestamp(const int64_t ts);
+        virtual void    logInteger(const int x);
+        virtual void    logFloat(const float x);
+        virtual void    logPID();
+        virtual void    logStart(const char *fmt);
+        virtual void    logEnd();
+        virtual void    logHash(log_hash_t hash);
+
+        virtual bool    isEnabled() const;
+        virtual bool    setEnabled(bool enabled);
+
+    private:
+        mutable Mutex   mLock;
+    };
+
+    // ---------------------------------------------------------------------------
+
+    class Reader : public RefBase {
+    public:
+        // A snapshot of a readers buffer
+        // This is raw data. No analysis has been done on it
+        class Snapshot {
+        public:
+            Snapshot() : mData(NULL), mLost(0) {}
+
+            Snapshot(size_t bufferSize) : mData(new uint8_t[bufferSize]) {}
+
+            ~Snapshot() { delete[] mData; }
+
+            // copy of the buffer
+            uint8_t *data() const { return mData; }
+
+            // amount of data lost (given by audio_utils_fifo_reader)
+            size_t   lost() const { return mLost; }
+
+            // iterator to beginning of readable segment of snapshot
+            // data between begin and end has valid entries
+            EntryIterator begin() { return mBegin; }
+
+            // iterator to end of readable segment of snapshot
+            EntryIterator end() { return mEnd; }
+
+        private:
+            friend class MergeReader;
+            friend class Reader;
+            uint8_t              *mData;
+            size_t                mLost;
+            EntryIterator mBegin;
+            EntryIterator mEnd;
+        };
+
+        // Input parameter 'size' is the desired size of the timeline in byte units.
+        // The size of the shared memory must be at least Timeline::sharedSize(size).
+        Reader(const void *shared, size_t size);
+        Reader(const sp<IMemory>& iMemory, size_t size);
+
+        virtual ~Reader();
+
+        // get snapshot of readers fifo buffer, effectively consuming the buffer
+        std::unique_ptr<Snapshot> getSnapshot();
+
+        bool     isIMemory(const sp<IMemory>& iMemory) const;
+
+    protected:
+        // print a summary of the performance to the console
+        void    dumpLine(const String8& timestamp, String8& body);
+        EntryIterator   handleFormat(const FormatEntry &fmtEntry,
+                                     String8 *timestamp,
+                                     String8 *body);
+        int mFd;                // file descriptor
+        int mIndent;            // indentation level
+        int mLost;              // bytes of data lost before buffer was read
+
+    private:
+        static const std::set<Event> startingTypes;
+        static const std::set<Event> endingTypes;
+
+        // declared as const because audio_utils_fifo() constructor
+        sp<IMemory> mIMemory;       // ref-counted version, assigned only in constructor
+
+        /*const*/ Shared* const mShared;    // raw pointer to shared memory, actually const but not
+        audio_utils_fifo * const mFifo;                 // FIFO itself,
+        // non-NULL unless constructor fails
+        audio_utils_fifo_reader * const mFifoReader;    // used to read from FIFO,
+        // non-NULL unless constructor fails
+
+        // Searches for the last entry of type <type> in the range [front, back)
+        // back has to be entry-aligned. Returns nullptr if none enconuntered.
+        static const uint8_t *findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
+                                                   const std::set<Event> &types);
+
+        // dummy method for handling absent author entry
+        virtual void handleAuthor(const AbstractEntry& /*fmtEntry*/, String8* /*body*/) {}
+    };
+
+    // Wrapper for a reader with a name. Contains a pointer to the reader and a pointer to the name
+    class NamedReader {
+    public:
+        NamedReader() { mName[0] = '\0'; } // for Vector
+        NamedReader(const sp<NBLog::Reader>& reader, const char *name) :
+            mReader(reader)
+            { strlcpy(mName, name, sizeof(mName)); }
+        ~NamedReader() { }
+        const sp<NBLog::Reader>&  reader() const { return mReader; }
+        const char*               name() const { return mName; }
+
+    private:
+        sp<NBLog::Reader>   mReader;
+        static const size_t kMaxName = 32;
+        char                mName[kMaxName];
+    };
+
+    // ---------------------------------------------------------------------------
+
+    // This class is used to read data from each thread's individual FIFO in shared memory
+    // and write it to a single FIFO in local memory.
+    class Merger : public RefBase {
+    public:
+        Merger(const void *shared, size_t size);
+
+        virtual ~Merger() {}
+
+        void addReader(const NamedReader &reader);
+        // TODO add removeReader
+        void merge();
+
+        // FIXME This is returning a reference to a shared variable that needs a lock
+        const std::vector<NamedReader>& getNamedReaders() const;
+
+    private:
+        // vector of the readers the merger is supposed to merge from.
+        // every reader reads from a writer's buffer
+        // FIXME Needs to be protected by a lock
+        std::vector<NamedReader> mNamedReaders;
+
+        Shared * const mShared; // raw pointer to shared memory
+        std::unique_ptr<audio_utils_fifo> mFifo; // FIFO itself
+        std::unique_ptr<audio_utils_fifo_writer> mFifoWriter; // used to write to FIFO
+    };
+
+    // This class has a pointer to the FIFO in local memory which stores the merged
+    // data collected by NBLog::Merger from all NamedReaders. It is used to process
+    // this data and write the result to PerformanceAnalysis.
+    class MergeReader : public Reader {
+    public:
+        MergeReader(const void *shared, size_t size, Merger &merger);
+
+        void dump(int fd, int indent = 0);
+        // process a particular snapshot of the reader
+        void getAndProcessSnapshot(Snapshot & snap);
+        // call getSnapshot of the content of the reader's buffer and process the data
+        void getAndProcessSnapshot();
+
+    private:
+        // FIXME Needs to be protected by a lock,
+        //       because even though our use of it is read-only there may be asynchronous updates
+        const std::vector<NamedReader>& mNamedReaders;
+
+        // analyzes, compresses and stores the merged data
+        // contains a separate instance for every author (thread), and for every source file
+        // location within each author
+        ReportPerformance::PerformanceAnalysisMap mThreadPerformanceAnalysis;
+
+        // handle author entry by looking up the author's name and appending it to the body
+        // returns number of bytes read from fmtEntry
+        void handleAuthor(const AbstractEntry &fmtEntry, String8 *body);
+    };
+
+    // MergeThread is a thread that contains a Merger. It works as a retriggerable one-shot:
+    // when triggered, it awakes for a lapse of time, during which it periodically merges; if
+    // retriggered, the timeout is reset.
+    // The thread is triggered on AudioFlinger binder activity.
+    class MergeThread : public Thread {
+    public:
+        MergeThread(Merger &merger, MergeReader &mergeReader);
+        virtual ~MergeThread() override;
+
+        // Reset timeout and activate thread to merge periodically if it's idle
+        void wakeup();
+
+        // Set timeout period until the merging thread goes idle again
+        void setTimeoutUs(int time);
+
+    private:
+        virtual bool threadLoop() override;
+
+        // the merger who actually does the work of merging the logs
+        Merger&     mMerger;
+
+        // the mergereader used to process data merged by mMerger
+        MergeReader& mMergeReader;
+
+        // mutex for the condition variable
+        Mutex       mMutex;
+
+        // condition variable to activate merging on timeout >= 0
+        Condition   mCond;
+
+        // time left until the thread blocks again (in microseconds)
+        int         mTimeoutUs;
+
+        // merging period when the thread is awake
+        static const int  kThreadSleepPeriodUs = 1000000 /*1s*/;
+
+        // initial timeout value when triggered
+        static const int  kThreadWakeupPeriodUs = 3000000 /*3s*/;
+    };
+
+};  // class NBLog
+
+// TODO put somewhere else
+static inline int64_t get_monotonic_ns() {
+    timespec ts;
+    if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
+        return (uint64_t) ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
+    }
+    return 0; // should not happen.
+}
+
+}   // namespace android
+
+#endif  // ANDROID_MEDIA_NBLOG_H
diff --git a/media/libnblog/include/media/nblog/PerformanceAnalysis.h b/media/libnblog/include/media/nblog/PerformanceAnalysis.h
new file mode 100644
index 0000000..ddfe9d6
--- /dev/null
+++ b/media/libnblog/include/media/nblog/PerformanceAnalysis.h
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2017 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 ANDROID_MEDIA_PERFORMANCEANALYSIS_H
+#define ANDROID_MEDIA_PERFORMANCEANALYSIS_H
+
+#include <deque>
+#include <map>
+#include <vector>
+
+#include <media/nblog/ReportPerformance.h>
+
+namespace android {
+
+namespace ReportPerformance {
+
+class PerformanceAnalysis;
+
+// a map of PerformanceAnalysis instances
+// The outer key is for the thread, the inner key for the source file location.
+using PerformanceAnalysisMap = std::map<int, std::map<log_hash_t, PerformanceAnalysis>>;
+
+class PerformanceAnalysis {
+    // This class stores and analyzes audio processing wakeup timestamps from NBLog
+    // FIXME: currently, all performance data is stored in deques. Turn these into circular
+    // buffers.
+    // TODO: add a mutex.
+public:
+
+    PerformanceAnalysis() {};
+
+    friend void dump(int fd, int indent,
+                     PerformanceAnalysisMap &threadPerformanceAnalysis);
+
+    // Called in the case of an audio on/off event, e.g., EVENT_AUDIO_STATE.
+    // Used to discard idle time intervals
+    void handleStateChange();
+
+    // Writes wakeup timestamp entry to log and runs analysis
+    void logTsEntry(timestamp ts);
+
+    // FIXME: make peakdetector and storeOutlierData a single function
+    // Input: mOutlierData. Looks at time elapsed between outliers
+    // finds significant changes in the distribution
+    // writes timestamps of significant changes to mPeakTimestamps
+    bool detectAndStorePeak(msInterval delta, timestamp ts);
+
+    // stores timestamps of intervals above a threshold: these are assumed outliers.
+    // writes to mOutlierData <time elapsed since previous outlier, outlier timestamp>
+    bool detectAndStoreOutlier(const msInterval diffMs);
+
+    // Generates a string of analysis of the buffer periods and prints to console
+    // FIXME: move this data visualization to a separate class. Model/view/controller
+    void reportPerformance(String8 *body, int author, log_hash_t hash,
+                           int maxHeight = 10);
+
+private:
+
+    // TODO use a circular buffer for the deques and vectors below
+
+    // stores outlier analysis:
+    // <elapsed time between outliers in ms, outlier beginning timestamp>
+    std::deque<std::pair<msInterval, timestamp>> mOutlierData;
+
+    // stores each timestamp at which a peak was detected
+    // a peak is a moment at which the average outlier interval changed significantly
+    std::deque<timestamp> mPeakTimestamps;
+
+    // stores buffer period histograms with timestamp of first sample
+    std::deque<std::pair<timestamp, Histogram>> mHists;
+
+    // Parameters used when detecting outliers
+    struct BufferPeriod {
+        double    mMean = -1;          // average time between audio processing wakeups
+        double    mOutlierFactor = -1; // values > mMean * mOutlierFactor are outliers
+        double    mOutlier = -1;       // this is set to mMean * mOutlierFactor
+        timestamp mPrevTs = -1;        // previous timestamp
+    } mBufferPeriod;
+
+    // capacity allocated to data structures
+    struct MaxLength {
+        size_t Hists; // number of histograms stored in memory
+        size_t Outliers; // number of values stored in outlier array
+        size_t Peaks; // number of values stored in peak array
+        int HistTimespanMs; // maximum histogram timespan
+    };
+    // These values allow for 10 hours of data allowing for a glitch and a peak
+    // as often as every 3 seconds
+    static constexpr MaxLength kMaxLength = {.Hists = 60, .Outliers = 12000,
+            .Peaks = 12000, .HistTimespanMs = 10 * kSecPerMin * kMsPerSec };
+
+    // these variables ensure continuity while analyzing the timestamp
+    // series one sample at a time.
+    // TODO: change this to a running variance/mean class
+    struct OutlierDistribution {
+        msInterval mMean = 0;         // sample mean since previous peak
+        msInterval mSd = 0;           // sample sd since previous peak
+        msInterval mElapsed = 0;      // time since previous detected outlier
+        const int  kMaxDeviation = 5; // standard deviations from the mean threshold
+        msInterval mTypicalDiff = 0;  // global mean of outliers
+        double     mN = 0;            // length of sequence since the last peak
+        double     mM2 = 0;           // used to calculate sd
+    } mOutlierDistribution;
+};
+
+void dump(int fd, int indent, PerformanceAnalysisMap &threadPerformanceAnalysis);
+void dumpLine(int fd, int indent, const String8 &body);
+
+} // namespace ReportPerformance
+
+}   // namespace android
+
+#endif  // ANDROID_MEDIA_PERFORMANCEANALYSIS_H
diff --git a/media/libnblog/include/media/nblog/ReportPerformance.h b/media/libnblog/include/media/nblog/ReportPerformance.h
new file mode 100644
index 0000000..ec0842f
--- /dev/null
+++ b/media/libnblog/include/media/nblog/ReportPerformance.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2017 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 ANDROID_MEDIA_REPORTPERFORMANCE_H
+#define ANDROID_MEDIA_REPORTPERFORMANCE_H
+
+#include <deque>
+#include <map>
+#include <vector>
+
+namespace android {
+
+// The String8 class is used by reportPerformance function
+class String8;
+
+namespace ReportPerformance {
+
+constexpr int kMsPerSec = 1000;
+constexpr int kSecPerMin = 60;
+
+constexpr int kJiffyPerMs = 10; // time unit for histogram as a multiple of milliseconds
+
+// stores a histogram: key: observed buffer period (multiple of jiffy). value: count
+using Histogram = std::map<int, int>;
+
+using msInterval = double;
+using jiffyInterval = double;
+
+using timestamp = int64_t;
+
+using log_hash_t = uint64_t;
+
+static inline int deltaMs(int64_t ns1, int64_t ns2) {
+    return (ns2 - ns1) / (1000 * 1000);
+}
+
+static inline int deltaJiffy(int64_t ns1, int64_t ns2) {
+    return (kJiffyPerMs * (ns2 - ns1)) / (1000 * 1000);
+}
+
+static inline uint32_t log2(uint32_t x) {
+    // This works for x > 0
+    return 31 - __builtin_clz(x);
+}
+
+// Writes outlier intervals, timestamps, peaks timestamps, and histograms to a file.
+void writeToFile(const std::deque<std::pair<timestamp, Histogram>> &hists,
+                 const std::deque<std::pair<msInterval, timestamp>> &outlierData,
+                 const std::deque<timestamp> &peakTimestamps,
+                 const char * kDirectory, bool append, int author, log_hash_t hash);
+
+} // namespace ReportPerformance
+
+}   // namespace android
+
+#endif  // ANDROID_MEDIA_REPORTPERFORMANCE_H
diff --git a/media/libstagefright/AACWriter.cpp b/media/libstagefright/AACWriter.cpp
index 8b1e1c3..9d90dbd 100644
--- a/media/libstagefright/AACWriter.cpp
+++ b/media/libstagefright/AACWriter.cpp
@@ -67,7 +67,7 @@
 }
 
 
-status_t AACWriter::addSource(const sp<IMediaSource> &source) {
+status_t AACWriter::addSource(const sp<MediaSource> &source) {
     if (mInitCheck != OK) {
         return mInitCheck;
     }
diff --git a/media/libstagefright/AMRWriter.cpp b/media/libstagefright/AMRWriter.cpp
index 961b57f..f53d7f0 100644
--- a/media/libstagefright/AMRWriter.cpp
+++ b/media/libstagefright/AMRWriter.cpp
@@ -54,7 +54,7 @@
     return mInitCheck;
 }
 
-status_t AMRWriter::addSource(const sp<IMediaSource> &source) {
+status_t AMRWriter::addSource(const sp<MediaSource> &source) {
     if (mInitCheck != OK) {
         return mInitCheck;
     }
diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp
index c8d4e4a..fc2bff3 100644
--- a/media/libstagefright/Android.bp
+++ b/media/libstagefright/Android.bp
@@ -10,15 +10,14 @@
     srcs: [
         "ACodec.cpp",
         "ACodecBufferChannel.cpp",
-        "AACExtractor.cpp",
         "AACWriter.cpp",
-        "AMRExtractor.cpp",
         "AMRWriter.cpp",
         "AudioPlayer.cpp",
         "AudioSource.cpp",
         "BufferImpl.cpp",
         "CodecBase.cpp",
         "CallbackDataSource.cpp",
+        "CallbackMediaSource.cpp",
         "CameraSource.cpp",
         "CameraSourceTimeLapse.cpp",
         "DataConverter.cpp",
@@ -26,15 +25,11 @@
         "DataURISource.cpp",
         "ESDS.cpp",
         "FileSource.cpp",
-        "FLACExtractor.cpp",
         "FrameRenderTracker.cpp",
         "HTTPBase.cpp",
         "HevcUtils.cpp",
-        "ItemTable.cpp",
         "JPEGSource.cpp",
-        "MP3Extractor.cpp",
         "MPEG2TSWriter.cpp",
-        "MPEG4Extractor.cpp",
         "MPEG4Writer.cpp",
         "MediaAdapter.cpp",
         "MediaClock.cpp",
@@ -44,7 +39,6 @@
         "MediaCodecSource.cpp",
         "MediaExtractor.cpp",
         "MediaSync.cpp",
-        "MidiExtractor.cpp",
         "http/MediaHTTP.cpp",
         "MediaMuxer.cpp",
         "MediaSource.cpp",
@@ -52,9 +46,8 @@
         "NuMediaExtractor.cpp",
         "OMXClient.cpp",
         "OmxInfoBuilder.cpp",
-        "OggExtractor.cpp",
-        "SampleIterator.cpp",
-        "SampleTable.cpp",
+        "RemoteMediaExtractor.cpp",
+        "RemoteMediaSource.cpp",
         "SimpleDecodingSource.cpp",
         "SkipCutBuffer.cpp",
         "StagefrightMediaScanner.cpp",
@@ -63,10 +56,7 @@
         "SurfaceUtils.cpp",
         "ThrottledSource.cpp",
         "Utils.cpp",
-        "VBRISeeker.cpp",
         "VideoFrameScheduler.cpp",
-        "WAVExtractor.cpp",
-        "XINGSeeker.cpp",
         "avc_utils.cpp",
     ],
 
@@ -74,11 +64,9 @@
         "libaudioutils",
         "libbinder",
         "libcamera_client",
-        "libcrypto",
         "libcutils",
         "libdl",
         "libdrmframework",
-        "libexpat",
         "libgui",
         "liblog",
         "libmedia",
@@ -86,26 +74,16 @@
         "libmediametrics",
         "libmediautils",
         "libnetd_client",
-        "libsonivox",
         "libui",
         "libutils",
-        "libvorbisidec",
-        "libmediadrm",
-        "libnativewindow",
-
         "libmedia_helper",
         "libstagefright_omx_utils",
-        "libstagefright_flacdec",
         "libstagefright_foundation",
-        "libstagefright_xmlparser",
         "libdl",
         "libRScpp",
         "libhidlbase",
         "libhidlmemory",
         "android.hidl.allocator@1.0",
-        "android.hidl.memory@1.0",
-        "android.hidl.token@1.0-utils",
-        "android.hardware.cas@1.0",
         "android.hardware.cas.native@1.0",
         "android.hardware.media.omx@1.0",
     ],
@@ -113,14 +91,12 @@
     static_libs: [
         "libstagefright_color_conversion",
         "libyuv_static",
-        "libstagefright_aacenc",
-        "libstagefright_matroska",
         "libstagefright_mediafilter",
         "libstagefright_webm",
         "libstagefright_timedtext",
         "libvpx",
         "libwebm",
-        "libstagefright_mpeg2ts",
+        "libstagefright_mpeg2support",
         "libstagefright_id3",
         "libFLAC",
     ],
@@ -161,6 +137,7 @@
 }
 
 subdirs = [
+    "codec2",
     "codecs/*",
     "colorconversion",
     "filters",
@@ -169,13 +146,11 @@
     "http",
     "httplive",
     "id3",
-    "matroska",
     "mpeg2ts",
     "omx",
     "rtsp",
     "tests",
     "timedtext",
     "webm",
-    "wifi-display",
     "xmlparser",
 ]
diff --git a/media/libstagefright/AudioPlayer.cpp b/media/libstagefright/AudioPlayer.cpp
index b3fb8d4..1d441eb 100644
--- a/media/libstagefright/AudioPlayer.cpp
+++ b/media/libstagefright/AudioPlayer.cpp
@@ -67,7 +67,7 @@
     }
 }
 
-void AudioPlayer::setSource(const sp<IMediaSource> &source) {
+void AudioPlayer::setSource(const sp<MediaSource> &source) {
     CHECK(mSource == NULL);
     mSource = source;
 }
@@ -363,7 +363,7 @@
     // When offloading, the OMX component is not used so this hack
     // is not needed
     if (!useOffload()) {
-        wp<IMediaSource> tmp = mSource;
+        wp<MediaSource> tmp = mSource;
         mSource.clear();
         while (tmp.promote() != NULL) {
             usleep(1000);
diff --git a/media/libstagefright/CallbackMediaSource.cpp b/media/libstagefright/CallbackMediaSource.cpp
new file mode 100644
index 0000000..cc7147e
--- /dev/null
+++ b/media/libstagefright/CallbackMediaSource.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2017, 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/CallbackMediaSource.h>
+
+namespace android {
+
+CallbackMediaSource::CallbackMediaSource(const sp<IMediaSource> &source)
+    :mSource(source) {}
+
+CallbackMediaSource::~CallbackMediaSource() {}
+
+status_t CallbackMediaSource::start(MetaData *params) {
+    return mSource->start(params);
+}
+
+status_t CallbackMediaSource::stop() {
+    return mSource->stop();
+}
+
+sp<MetaData> CallbackMediaSource::getFormat() {
+    return mSource->getFormat();
+}
+
+status_t CallbackMediaSource::read(MediaBuffer **buffer, const ReadOptions *options) {
+    return mSource->read(buffer, reinterpret_cast<const MediaSource::ReadOptions*>(options));
+}
+
+status_t CallbackMediaSource::pause() {
+    return mSource->pause();
+}
+
+status_t CallbackMediaSource::setBuffers(const Vector<MediaBuffer *> &buffers) {
+    return mSource->setBuffers(buffers);
+}
+
+}  // namespace android
diff --git a/media/libstagefright/MPEG2TSWriter.cpp b/media/libstagefright/MPEG2TSWriter.cpp
index 03ea959..7ed8fce 100644
--- a/media/libstagefright/MPEG2TSWriter.cpp
+++ b/media/libstagefright/MPEG2TSWriter.cpp
@@ -35,7 +35,7 @@
 namespace android {
 
 struct MPEG2TSWriter::SourceInfo : public AHandler {
-    explicit SourceInfo(const sp<IMediaSource> &source);
+    explicit SourceInfo(const sp<MediaSource> &source);
 
     void start(const sp<AMessage> &notify, const sp<MetaData> &params);
     void stop();
@@ -69,7 +69,7 @@
         kWhatRead  = 'read',
     };
 
-    sp<IMediaSource> mSource;
+    sp<MediaSource> mSource;
     sp<ALooper> mLooper;
     sp<AMessage> mNotify;
 
@@ -91,7 +91,7 @@
     DISALLOW_EVIL_CONSTRUCTORS(SourceInfo);
 };
 
-MPEG2TSWriter::SourceInfo::SourceInfo(const sp<IMediaSource> &source)
+MPEG2TSWriter::SourceInfo::SourceInfo(const sp<MediaSource> &source)
     : mSource(source),
       mLooper(new ALooper),
       mEOSReceived(false),
@@ -499,7 +499,7 @@
     }
 }
 
-status_t MPEG2TSWriter::addSource(const sp<IMediaSource> &source) {
+status_t MPEG2TSWriter::addSource(const sp<MediaSource> &source) {
     CHECK(!mStarted);
 
     sp<MetaData> meta = source->getFormat();
diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp
index 7786c4d..8c121b3 100644
--- a/media/libstagefright/MPEG4Writer.cpp
+++ b/media/libstagefright/MPEG4Writer.cpp
@@ -100,7 +100,7 @@
 
 class MPEG4Writer::Track {
 public:
-    Track(MPEG4Writer *owner, const sp<IMediaSource> &source, size_t trackId);
+    Track(MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId);
 
     ~Track();
 
@@ -271,7 +271,7 @@
 
     MPEG4Writer *mOwner;
     sp<MetaData> mMeta;
-    sp<IMediaSource> mSource;
+    sp<MediaSource> mSource;
     volatile bool mDone;
     volatile bool mPaused;
     volatile bool mResumed;
@@ -572,7 +572,7 @@
     return NULL;
 }
 
-status_t MPEG4Writer::addSource(const sp<IMediaSource> &source) {
+status_t MPEG4Writer::addSource(const sp<MediaSource> &source) {
     Mutex::Autolock l(mLock);
     if (mStarted) {
         ALOGE("Attempt to add source AFTER recording is started");
@@ -1626,7 +1626,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 MPEG4Writer::Track::Track(
-        MPEG4Writer *owner, const sp<IMediaSource> &source, size_t trackId)
+        MPEG4Writer *owner, const sp<MediaSource> &source, size_t trackId)
     : mOwner(owner),
       mMeta(source->getFormat()),
       mSource(source),
diff --git a/media/libstagefright/MediaClock.cpp b/media/libstagefright/MediaClock.cpp
index 3aa0061..15843a2 100644
--- a/media/libstagefright/MediaClock.cpp
+++ b/media/libstagefright/MediaClock.cpp
@@ -17,11 +17,12 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "MediaClock"
 #include <utils/Log.h>
+#include <map>
 
 #include <media/stagefright/MediaClock.h>
 
 #include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/ALooper.h>
+#include <media/stagefright/foundation/AMessage.h>
 
 namespace android {
 
@@ -29,15 +30,52 @@
 // If larger than this threshold, it's treated as discontinuity.
 static const int64_t kAnchorFluctuationAllowedUs = 10000ll;
 
+MediaClock::Timer::Timer(const sp<AMessage> &notify, int64_t mediaTimeUs, int64_t adjustRealUs)
+    : mNotify(notify),
+      mMediaTimeUs(mediaTimeUs),
+      mAdjustRealUs(adjustRealUs) {
+}
+
 MediaClock::MediaClock()
     : mAnchorTimeMediaUs(-1),
       mAnchorTimeRealUs(-1),
       mMaxTimeMediaUs(INT64_MAX),
       mStartingTimeMediaUs(-1),
-      mPlaybackRate(1.0) {
+      mPlaybackRate(1.0),
+      mGeneration(0) {
+    mLooper = new ALooper;
+    mLooper->setName("MediaClock");
+    mLooper->start(false /* runOnCallingThread */,
+                   false /* canCallJava */,
+                   ANDROID_PRIORITY_AUDIO);
+}
+
+void MediaClock::init() {
+    mLooper->registerHandler(this);
 }
 
 MediaClock::~MediaClock() {
+    reset();
+    if (mLooper != NULL) {
+        mLooper->unregisterHandler(id());
+        mLooper->stop();
+    }
+}
+
+void MediaClock::reset() {
+    Mutex::Autolock autoLock(mLock);
+    auto it = mTimers.begin();
+    while (it != mTimers.end()) {
+        it->mNotify->setInt32("reason", TIMER_REASON_RESET);
+        it->mNotify->post();
+        it = mTimers.erase(it);
+    }
+    mAnchorTimeMediaUs = -1;
+    mAnchorTimeRealUs = -1;
+    mMaxTimeMediaUs = INT64_MAX;
+    mStartingTimeMediaUs = -1;
+    mPlaybackRate = 1.0;
+    ++mGeneration;
 }
 
 void MediaClock::setStartingTimeMedia(int64_t startingTimeMediaUs) {
@@ -82,6 +120,9 @@
     }
     mAnchorTimeRealUs = nowUs;
     mAnchorTimeMediaUs = nowMediaUs;
+
+    ++mGeneration;
+    processTimers_l();
 }
 
 void MediaClock::updateMaxTimeMedia(int64_t maxTimeMediaUs) {
@@ -105,6 +146,11 @@
     }
     mAnchorTimeRealUs = nowUs;
     mPlaybackRate = rate;
+
+    if (rate > 0.0) {
+        ++mGeneration;
+        processTimers_l();
+    }
 }
 
 float MediaClock::getPlaybackRate() const {
@@ -165,4 +211,106 @@
     return OK;
 }
 
+void MediaClock::addTimer(const sp<AMessage> &notify, int64_t mediaTimeUs,
+                          int64_t adjustRealUs) {
+    Mutex::Autolock autoLock(mLock);
+
+    bool updateTimer = (mPlaybackRate != 0.0);
+    if (updateTimer) {
+        auto it = mTimers.begin();
+        while (it != mTimers.end()) {
+            if (((it->mAdjustRealUs - (double)adjustRealUs) * (double)mPlaybackRate
+                + (it->mMediaTimeUs - mediaTimeUs)) <= 0) {
+                updateTimer = false;
+                break;
+            }
+            ++it;
+        }
+    }
+
+    mTimers.emplace_back(notify, mediaTimeUs, adjustRealUs);
+
+    if (updateTimer) {
+        ++mGeneration;
+        processTimers_l();
+    }
+}
+
+void MediaClock::onMessageReceived(const sp<AMessage> &msg) {
+    switch (msg->what()) {
+        case kWhatTimeIsUp:
+        {
+            int32_t generation;
+            CHECK(msg->findInt32("generation", &generation));
+
+            Mutex::Autolock autoLock(mLock);
+            if (generation != mGeneration) {
+                break;
+            }
+            processTimers_l();
+            break;
+        }
+
+        default:
+            TRESPASS();
+            break;
+    }
+}
+
+void MediaClock::processTimers_l() {
+    int64_t nowMediaTimeUs;
+    status_t status = getMediaTime_l(
+            ALooper::GetNowUs(), &nowMediaTimeUs, false /* allowPastMaxTime */);
+
+    if (status != OK) {
+        return;
+    }
+
+    int64_t nextLapseRealUs = INT64_MAX;
+    std::multimap<int64_t, Timer> notifyList;
+    auto it = mTimers.begin();
+    while (it != mTimers.end()) {
+        double diff = it->mAdjustRealUs * (double)mPlaybackRate
+            + it->mMediaTimeUs - nowMediaTimeUs;
+        int64_t diffMediaUs;
+        if (diff > (double)INT64_MAX) {
+            diffMediaUs = INT64_MAX;
+        } else if (diff < (double)INT64_MIN) {
+            diffMediaUs = INT64_MIN;
+        } else {
+            diffMediaUs = diff;
+        }
+
+        if (diffMediaUs <= 0) {
+            notifyList.emplace(diffMediaUs, *it);
+            it = mTimers.erase(it);
+        } else {
+            if (mPlaybackRate != 0.0
+                && (double)diffMediaUs < INT64_MAX * (double)mPlaybackRate) {
+                int64_t targetRealUs = diffMediaUs / (double)mPlaybackRate;
+                if (targetRealUs < nextLapseRealUs) {
+                    nextLapseRealUs = targetRealUs;
+                }
+            }
+            ++it;
+        }
+    }
+
+    auto itNotify = notifyList.begin();
+    while (itNotify != notifyList.end()) {
+        itNotify->second.mNotify->setInt32("reason", TIMER_REASON_REACHED);
+        itNotify->second.mNotify->post();
+        itNotify = notifyList.erase(itNotify);
+    }
+
+    if (mTimers.empty() || mPlaybackRate == 0.0 || mAnchorTimeMediaUs < 0
+        || nextLapseRealUs == INT64_MAX) {
+        return;
+    }
+
+    sp<AMessage> msg = new AMessage(kWhatTimeIsUp, this);
+    msg->setInt32("generation", mGeneration);
+    msg->post(nextLapseRealUs);
+}
+
 }  // namespace android
diff --git a/media/libstagefright/MediaCodecList.cpp b/media/libstagefright/MediaCodecList.cpp
index 4652594..32a9f0a 100644
--- a/media/libstagefright/MediaCodecList.cpp
+++ b/media/libstagefright/MediaCodecList.cpp
@@ -34,13 +34,12 @@
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/OmxInfoBuilder.h>
 #include <media/stagefright/omx/OMXUtils.h>
-#include <media/stagefright/xmlparser/MediaCodecsXmlParser.h>
+#include <xmlparser/include/media/stagefright/xmlparser/MediaCodecsXmlParser.h>
 
 #include <sys/stat.h>
 #include <utils/threads.h>
 
 #include <cutils/properties.h>
-#include <expat.h>
 
 #include <algorithm>
 
diff --git a/media/libstagefright/MediaExtractor.cpp b/media/libstagefright/MediaExtractor.cpp
index c91c82b..e7e42b2 100644
--- a/media/libstagefright/MediaExtractor.cpp
+++ b/media/libstagefright/MediaExtractor.cpp
@@ -20,19 +20,6 @@
 #include <inttypes.h>
 #include <pwd.h>
 
-#include "include/AMRExtractor.h"
-#include "include/MP3Extractor.h"
-#include "include/MPEG4Extractor.h"
-#include "include/WAVExtractor.h"
-#include "include/OggExtractor.h"
-#include "include/MPEG2PSExtractor.h"
-#include "include/MPEG2TSExtractor.h"
-#include "include/FLACExtractor.h"
-#include "include/AACExtractor.h"
-#include "include/MidiExtractor.h"
-
-#include "matroska/MatroskaExtractor.h"
-
 #include <binder/IServiceManager.h>
 #include <binder/MemoryDealer.h>
 
@@ -43,7 +30,10 @@
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MediaExtractor.h>
 #include <media/stagefright/MetaData.h>
+#include <media/stagefright/RemoteMediaExtractor.h>
+#include <media/IMediaExtractor.h>
 #include <media/IMediaExtractorService.h>
+#include <media/IMediaSource.h>
 #include <cutils/properties.h>
 #include <utils/String8.h>
 #include <private/android_filesystem_config.h>
@@ -51,6 +41,9 @@
 // still doing some on/off toggling here.
 #define MEDIA_LOG       1
 
+#include <sys/types.h>
+#include <dirent.h>
+#include <dlfcn.h>
 
 namespace android {
 
@@ -65,7 +58,7 @@
     if (!LOG_NDEBUG) {
         uid_t uid = getuid();
         struct passwd *pw = getpwuid(uid);
-        ALOGI("extractor created in uid: %d (%s)", getuid(), pw->pw_name);
+        ALOGV("extractor created in uid: %d (%s)", getuid(), pw->pw_name);
     }
 
     mAnalyticsItem = NULL;
@@ -92,6 +85,10 @@
     }
 }
 
+sp<IMediaExtractor> MediaExtractor::asIMediaExtractor() {
+    return RemoteMediaExtractor::wrap(sp<MediaExtractor>(this));
+}
+
 sp<MetaData> MediaExtractor::getMetaData() {
     return new MetaData;
 }
@@ -125,7 +122,8 @@
     if (!property_get_bool("media.stagefright.extractremote", true)) {
         // local extractor
         ALOGW("creating media extractor in calling process");
-        return CreateFromService(source, mime);
+        sp<MediaExtractor> extractor = CreateFromService(source, mime);
+        return (extractor.get() == nullptr) ? nullptr : extractor->asIMediaExtractor();
     } else {
         // remote extractor
         ALOGV("get service manager");
@@ -154,12 +152,13 @@
 
     sp<AMessage> meta;
 
+    CreatorFunc creator = NULL;
     String8 tmp;
     if (mime == NULL) {
         float confidence;
-        if (!sniff(source, &tmp, &confidence, &meta)) {
-            ALOGW("FAILED to autodetect media content.");
-
+        creator = sniff(source, &tmp, &confidence, &meta);
+        if (!creator) {
+            ALOGV("FAILED to autodetect media content.");
             return NULL;
         }
 
@@ -168,66 +167,41 @@
              mime, confidence);
     }
 
-    MediaExtractor *ret = NULL;
-    if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG4)
-            || !strcasecmp(mime, "audio/mp4")) {
-        ret = new MPEG4Extractor(source);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_MPEG)) {
-        ret = new MP3Extractor(source, meta);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AMR_NB)
-            || !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AMR_WB)) {
-        ret = new AMRExtractor(source);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_FLAC)) {
-        ret = new FLACExtractor(source);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WAV)) {
-        ret = new WAVExtractor(source);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_OGG)) {
-        ret = new OggExtractor(source);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MATROSKA)) {
-        ret = new MatroskaExtractor(source);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2TS)) {
-        ret = new MPEG2TSExtractor(source);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC_ADTS)) {
-        ret = new AACExtractor(source, meta);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2PS)) {
-        ret = new MPEG2PSExtractor(source);
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_MIDI)) {
-        ret = new MidiExtractor(source);
-    }
+    MediaExtractor *ret = creator(source, meta);
 
     if (ret != NULL) {
-       // track the container format (mpeg, aac, wvm, etc)
-       if (MEDIA_LOG) {
-          if (ret->mAnalyticsItem != NULL) {
-              size_t ntracks = ret->countTracks();
-              ret->mAnalyticsItem->setCString(kExtractorFormat,  ret->name());
-              // tracks (size_t)
-              ret->mAnalyticsItem->setInt32(kExtractorTracks,  ntracks);
-              // metadata
-              sp<MetaData> pMetaData = ret->getMetaData();
-              if (pMetaData != NULL) {
-                String8 xx = pMetaData->toString();
-                // 'titl' -- but this verges into PII
-                // 'mime'
-                const char *mime = NULL;
-                if (pMetaData->findCString(kKeyMIMEType, &mime)) {
-                    ret->mAnalyticsItem->setCString(kExtractorMime,  mime);
+        // track the container format (mpeg, aac, wvm, etc)
+        if (MEDIA_LOG) {
+            if (ret->mAnalyticsItem != NULL) {
+                size_t ntracks = ret->countTracks();
+                ret->mAnalyticsItem->setCString(kExtractorFormat,  ret->name());
+                // tracks (size_t)
+                ret->mAnalyticsItem->setInt32(kExtractorTracks,  ntracks);
+                // metadata
+                sp<MetaData> pMetaData = ret->getMetaData();
+                if (pMetaData != NULL) {
+                    String8 xx = pMetaData->toString();
+                    // 'titl' -- but this verges into PII
+                    // 'mime'
+                    const char *mime = NULL;
+                    if (pMetaData->findCString(kKeyMIMEType, &mime)) {
+                        ret->mAnalyticsItem->setCString(kExtractorMime,  mime);
+                    }
+                    // what else is interesting and not already available?
                 }
-                // what else is interesting and not already available?
-              }
-	  }
-       }
+            }
+        }
     }
 
     return ret;
 }
 
 Mutex MediaExtractor::gSnifferMutex;
-List<MediaExtractor::SnifferFunc> MediaExtractor::gSniffers;
+List<MediaExtractor::ExtractorDef> MediaExtractor::gSniffers;
 bool MediaExtractor::gSniffersRegistered = false;
 
 // static
-bool MediaExtractor::sniff(
+MediaExtractor::CreatorFunc MediaExtractor::sniff(
         const sp<DataSource> &source, String8 *mimeType, float *confidence, sp<AMessage> *meta) {
     *mimeType = "";
     *confidence = 0.0f;
@@ -236,37 +210,69 @@
     {
         Mutex::Autolock autoLock(gSnifferMutex);
         if (!gSniffersRegistered) {
-            return false;
+            return NULL;
         }
     }
 
-    for (List<SnifferFunc>::iterator it = gSniffers.begin();
+    CreatorFunc curCreator = NULL;
+    CreatorFunc bestCreator = NULL;
+    for (List<ExtractorDef>::iterator it = gSniffers.begin();
          it != gSniffers.end(); ++it) {
         String8 newMimeType;
         float newConfidence;
         sp<AMessage> newMeta;
-        if ((*it)(source, &newMimeType, &newConfidence, &newMeta)) {
+        if ((curCreator = (*it).sniff(source, &newMimeType, &newConfidence, &newMeta))) {
             if (newConfidence > *confidence) {
                 *mimeType = newMimeType;
                 *confidence = newConfidence;
                 *meta = newMeta;
+                bestCreator = curCreator;
             }
         }
     }
 
-    return *confidence > 0.0;
+    return bestCreator;
 }
 
 // static
-void MediaExtractor::RegisterSniffer_l(SnifferFunc func) {
-    for (List<SnifferFunc>::iterator it = gSniffers.begin();
-         it != gSniffers.end(); ++it) {
-        if (*it == func) {
-            return;
-        }
+void MediaExtractor::RegisterSniffer_l(const ExtractorDef &def) {
+    // sanity check check struct version, uuid, name
+    if (def.def_version == 0 || def.def_version > EXTRACTORDEF_VERSION) {
+        ALOGE("don't understand extractor format %u, ignoring.", def.def_version);
+        return;
+    }
+    if (memcmp(&def.extractor_uuid, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 16) == 0) {
+        ALOGE("invalid UUID, ignoring");
+        return;
+    }
+    if (def.extractor_name == NULL || strlen(def.extractor_name) == 0) {
+        ALOGE("extractors should have a name, ignoring");
+        return;
     }
 
-    gSniffers.push_back(func);
+    for (List<ExtractorDef>::iterator it = gSniffers.begin();
+            it != gSniffers.end(); ++it) {
+        if (memcmp(&((*it).extractor_uuid), &def.extractor_uuid, 16) == 0) {
+            // there's already an extractor with the same uuid
+            if ((*it).extractor_version < def.extractor_version) {
+                // this one is newer, replace the old one
+                ALOGW("replacing extractor '%s' version %u with version %u",
+                        def.extractor_name,
+                        (*it).extractor_version,
+                        def.extractor_version);
+                gSniffers.erase(it);
+                break;
+            } else {
+                ALOGW("ignoring extractor '%s' version %u in favor of version %u",
+                        def.extractor_name,
+                        def.extractor_version,
+                        (*it).extractor_version);
+                return;
+            }
+        }
+    }
+    ALOGV("registering extractor for %s", def.extractor_name);
+    gSniffers.push_back(def);
 }
 
 // static
@@ -276,17 +282,44 @@
         return;
     }
 
-    RegisterSniffer_l(SniffMPEG4);
-    RegisterSniffer_l(SniffMatroska);
-    RegisterSniffer_l(SniffOgg);
-    RegisterSniffer_l(SniffWAV);
-    RegisterSniffer_l(SniffFLAC);
-    RegisterSniffer_l(SniffAMR);
-    RegisterSniffer_l(SniffMPEG2TS);
-    RegisterSniffer_l(SniffMP3);
-    RegisterSniffer_l(SniffAAC);
-    RegisterSniffer_l(SniffMPEG2PS);
-    RegisterSniffer_l(SniffMidi);
+    auto registerExtractors = [](const char *libDirPath) -> void {
+        DIR *libDir = opendir(libDirPath);
+        if (libDir) {
+            struct dirent* libEntry;
+            while ((libEntry = readdir(libDir))) {
+                String8 libPath = String8(libDirPath) + libEntry->d_name;
+                void *libHandle = dlopen(libPath.string(), RTLD_NOW | RTLD_LOCAL);
+                if (libHandle) {
+                    GetExtractorDef getsniffer = (GetExtractorDef) dlsym(libHandle, "GETEXTRACTORDEF");
+                    if (getsniffer) {
+                        ALOGV("registering sniffer for %s", libPath.string());
+                        RegisterSniffer_l(getsniffer());
+                    } else {
+                        ALOGW("%s does not contain sniffer", libPath.string());
+                        dlclose(libHandle);
+                    }
+                } else {
+                    ALOGW("couldn't dlopen(%s)", libPath.string());
+                }
+            }
+
+            closedir(libDir);
+        } else {
+            ALOGE("couldn't opendir(%s)", libDirPath);
+        }
+    };
+
+    registerExtractors("/system/lib"
+#ifdef __LP64__
+            "64"
+#endif
+            "/extractors/");
+
+    registerExtractors("/vendor/lib"
+#ifdef __LP64__
+            "64"
+#endif
+            "/extractors/");
 
     gSniffersRegistered = true;
 }
diff --git a/media/libstagefright/MediaSource.cpp b/media/libstagefright/MediaSource.cpp
index a17757a..8b92a6b 100644
--- a/media/libstagefright/MediaSource.cpp
+++ b/media/libstagefright/MediaSource.cpp
@@ -14,7 +14,9 @@
  * limitations under the License.
  */
 
+#include <media/stagefright/CallbackMediaSource.h>
 #include <media/stagefright/MediaSource.h>
+#include <media/stagefright/RemoteMediaSource.h>
 
 namespace android {
 
@@ -22,4 +24,16 @@
 
 MediaSource::~MediaSource() {}
 
+// static
+sp<MediaSource> MediaSource::CreateFromIMediaSource(const sp<IMediaSource> &source) {
+    if (source == nullptr) {
+        return nullptr;
+    }
+    return new CallbackMediaSource(source);
+}
+
+sp<IMediaSource> MediaSource::asIMediaSource() {
+    return RemoteMediaSource::wrap(sp<MediaSource>(this));
+}
+
 }  // namespace android
diff --git a/media/libstagefright/MediaSync.cpp b/media/libstagefright/MediaSync.cpp
index 9278381..ba14e5d 100644
--- a/media/libstagefright/MediaSync.cpp
+++ b/media/libstagefright/MediaSync.cpp
@@ -61,6 +61,7 @@
         mNextBufferItemMediaUs(-1),
         mPlaybackRate(0.0) {
     mMediaClock = new MediaClock;
+    mMediaClock->init();
 
     // initialize settings
     mPlaybackSettings = AUDIO_PLAYBACK_RATE_DEFAULT;
diff --git a/media/libstagefright/RemoteMediaExtractor.cpp b/media/libstagefright/RemoteMediaExtractor.cpp
new file mode 100644
index 0000000..db2c20c
--- /dev/null
+++ b/media/libstagefright/RemoteMediaExtractor.cpp
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2017, 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/RemoteMediaExtractor.h>
+#include <media/stagefright/MediaSource.h>
+
+namespace android {
+
+RemoteMediaExtractor::RemoteMediaExtractor(const sp<MediaExtractor> &extractor)
+    :mExtractor(extractor) {}
+
+RemoteMediaExtractor::~RemoteMediaExtractor() {}
+
+size_t RemoteMediaExtractor::countTracks() {
+    return mExtractor->countTracks();
+}
+
+sp<IMediaSource> RemoteMediaExtractor::getTrack(size_t index) {
+    sp<MediaSource> source = mExtractor->getTrack(index);
+    return (source.get() == nullptr) ? nullptr : source->asIMediaSource();
+}
+
+sp<MetaData> RemoteMediaExtractor::getTrackMetaData(size_t index, uint32_t flags) {
+    return mExtractor->getTrackMetaData(index, flags);
+}
+
+sp<MetaData> RemoteMediaExtractor::getMetaData() {
+    return mExtractor->getMetaData();
+}
+
+status_t RemoteMediaExtractor::getMetrics(Parcel *reply) {
+    return mExtractor->getMetrics(reply);
+}
+
+uint32_t RemoteMediaExtractor::flags() const {
+    return mExtractor->flags();
+}
+
+char* RemoteMediaExtractor::getDrmTrackInfo(size_t trackID, int * len) {
+    return mExtractor->getDrmTrackInfo(trackID, len);
+}
+
+void RemoteMediaExtractor::setUID(uid_t uid) {
+    return mExtractor->setUID(uid);
+}
+
+status_t RemoteMediaExtractor::setMediaCas(const HInterfaceToken &casToken) {
+    return mExtractor->setMediaCas(casToken);
+}
+
+const char * RemoteMediaExtractor::name() {
+    return mExtractor->name();
+}
+
+void RemoteMediaExtractor::release() {
+    return mExtractor->release();
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+// static
+sp<IMediaExtractor> RemoteMediaExtractor::wrap(const sp<MediaExtractor> &extractor) {
+    if (extractor.get() == nullptr) {
+        return nullptr;
+    }
+    return new RemoteMediaExtractor(extractor);
+}
+
+}  // namespace android
diff --git a/media/libstagefright/RemoteMediaSource.cpp b/media/libstagefright/RemoteMediaSource.cpp
new file mode 100644
index 0000000..4060526
--- /dev/null
+++ b/media/libstagefright/RemoteMediaSource.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2017, 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/RemoteMediaSource.h>
+
+namespace android {
+
+RemoteMediaSource::RemoteMediaSource(const sp<MediaSource> &source)
+    :mSource(source) {}
+
+RemoteMediaSource::~RemoteMediaSource() {}
+
+status_t RemoteMediaSource::start(MetaData *params) {
+    return mSource->start(params);
+}
+
+status_t RemoteMediaSource::stop() {
+    return mSource->stop();
+}
+
+sp<MetaData> RemoteMediaSource::getFormat() {
+    return mSource->getFormat();
+}
+
+status_t RemoteMediaSource::read(MediaBuffer **buffer, const ReadOptions *options) {
+    return mSource->read(buffer, reinterpret_cast<const MediaSource::ReadOptions*>(options));
+}
+
+status_t RemoteMediaSource::pause() {
+    return mSource->pause();
+}
+
+status_t RemoteMediaSource::setBuffers(const Vector<MediaBuffer *> &buffers) {
+    return mSource->setBuffers(buffers);
+}
+
+status_t RemoteMediaSource::setStopTimeUs(int64_t stopTimeUs) {
+    return mSource->setStopTimeUs(stopTimeUs);
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+// static
+sp<IMediaSource> RemoteMediaSource::wrap(const sp<MediaSource> &source) {
+    if (source.get() == nullptr) {
+        return nullptr;
+    }
+    return new RemoteMediaSource(source);
+}
+
+}  // namespace android
diff --git a/media/libstagefright/SimpleDecodingSource.cpp b/media/libstagefright/SimpleDecodingSource.cpp
index 90b8603..67e6748 100644
--- a/media/libstagefright/SimpleDecodingSource.cpp
+++ b/media/libstagefright/SimpleDecodingSource.cpp
@@ -36,13 +36,13 @@
 
 //static
 sp<SimpleDecodingSource> SimpleDecodingSource::Create(
-        const sp<IMediaSource> &source, uint32_t flags) {
+        const sp<MediaSource> &source, uint32_t flags) {
     return SimpleDecodingSource::Create(source, flags, nullptr, nullptr);
 }
 
 //static
 sp<SimpleDecodingSource> SimpleDecodingSource::Create(
-        const sp<IMediaSource> &source, uint32_t flags, const sp<ANativeWindow> &nativeWindow,
+        const sp<MediaSource> &source, uint32_t flags, const sp<ANativeWindow> &nativeWindow,
         const char *desiredCodec) {
     sp<Surface> surface = static_cast<Surface*>(nativeWindow.get());
     const char *mime = NULL;
@@ -99,7 +99,7 @@
 }
 
 SimpleDecodingSource::SimpleDecodingSource(
-        const sp<MediaCodec> &codec, const sp<IMediaSource> &source, const sp<ALooper> &looper,
+        const sp<MediaCodec> &codec, const sp<MediaSource> &source, const sp<ALooper> &looper,
         bool usingSurface, bool isVorbis, const sp<AMessage> &format)
     : mCodec(codec),
       mSource(source),
@@ -212,7 +212,7 @@
     status_t res;
 
     // flush codec on seek
-    IMediaSource::ReadOptions::SeekMode mode;
+    MediaSource::ReadOptions::SeekMode mode;
     if (options != NULL && options->getSeekTo(&out_pts, &mode)) {
         me->mQueuedInputEOS = false;
         me->mGotOutputEOS = false;
diff --git a/media/libstagefright/codec2/Android.bp b/media/libstagefright/codec2/Android.bp
new file mode 100644
index 0000000..f79e058
--- /dev/null
+++ b/media/libstagefright/codec2/Android.bp
@@ -0,0 +1,32 @@
+cc_library_shared {
+    name: "libstagefright_codec2",
+
+    tags: [
+        "optional",
+    ],
+
+    srcs: ["C2.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/native/include/media/hardware",
+    ],
+
+    sanitize: {
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+        diag: {
+            cfi: true,
+        },
+    },
+
+    ldflags: ["-Wl,-Bsymbolic"],
+}
+
+subdirs = [
+    "tests",
+    "vndk",
+]
diff --git a/media/libstagefright/codec2/Android.mk b/media/libstagefright/codec2/Android.mk
deleted file mode 100644
index ef06ed7..0000000
--- a/media/libstagefright/codec2/Android.mk
+++ /dev/null
@@ -1,21 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-        C2.cpp    \
-
-LOCAL_C_INCLUDES += \
-        $(TOP)/frameworks/av/media/libstagefright/codec2/include \
-        $(TOP)/frameworks/native/include/media/hardware \
-
-LOCAL_MODULE:= libstagefright_codec2
-LOCAL_CFLAGS += -Werror -Wall
-LOCAL_CLANG := true
-LOCAL_SANITIZE := unsigned-integer-overflow signed-integer-overflow cfi
-LOCAL_SANITIZE_DIAG := cfi
-
-include $(BUILD_SHARED_LIBRARY)
-
-################################################################################
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/media/libstagefright/codec2/include/C2Buffer.h b/media/libstagefright/codec2/include/C2Buffer.h
index 9f6b487..b5ea381 100644
--- a/media/libstagefright/codec2/include/C2Buffer.h
+++ b/media/libstagefright/codec2/include/C2Buffer.h
@@ -223,7 +223,11 @@
      *
      * \return acquired object potentially invalidated if waiting for the fence failed.
      */
-    T get();
+    T get() {
+        // TODO:
+        // wait();
+        return mT;
+    }
 
 protected:
     C2Acquirable(C2Error error, C2Fence fence, T t) : C2Fence(fence), mInitialError(error), mT(t) { }
@@ -268,7 +272,7 @@
         : mCapacity(parent == nullptr ? 0 : parent->capacity()) { }
 
 private:
-    const uint32_t mCapacity;
+    uint32_t mCapacity;
 /// @}
 };
 
@@ -429,7 +433,7 @@
     /**
      * \return pointer to the start of the block or nullptr on error.
      */
-    const uint8_t *data();
+    const uint8_t *data() const;
 
     /**
      * Returns a portion of this view.
@@ -447,6 +451,10 @@
      */
     C2Error error();
 
+protected:
+    C2ReadView(const _C2LinearCapacityAspect *parent, const uint8_t *data);
+    explicit C2ReadView(C2Error error);
+
 private:
     class Impl;
     std::shared_ptr<Impl> mImpl;
@@ -476,6 +484,10 @@
      */
     C2Error error();
 
+protected:
+    C2WriteView(const _C2LinearRangeAspect *parent, uint8_t *base);
+    explicit C2WriteView(C2Error error);
+
 private:
     class Impl;
     /// \todo should this be unique_ptr to make this movable only - to avoid inconsistent regions
@@ -516,7 +528,13 @@
      */
     C2Fence fence() const { return mFence; }
 
+protected:
+    C2ConstLinearBlock(std::shared_ptr<C2LinearAllocation> alloc);
+    C2ConstLinearBlock(std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size);
+
 private:
+    class Impl;
+    std::shared_ptr<Impl> mImpl;
     C2Fence mFence;
 };
 
@@ -544,6 +562,14 @@
      *    The block shall be modified only until firing the event for the fence.
      */
     C2ConstLinearBlock share(size_t offset, size_t size, C2Fence fence);
+
+protected:
+    C2LinearBlock(std::shared_ptr<C2LinearAllocation> alloc);
+    C2LinearBlock(std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size);
+
+private:
+    class Impl;
+    std::shared_ptr<Impl> mImpl;
 };
 
 /// @}
@@ -741,10 +767,10 @@
     uint32_t mWidth;
     uint32_t mHeight;
 
-    inline C2Rect(uint32_t width, uint32_t height)
+    constexpr inline C2Rect(uint32_t width, uint32_t height)
         : C2Rect(width, height, 0, 0) { }
 
-    inline C2Rect(uint32_t width, uint32_t height, uint32_t left, uint32_t top)
+    constexpr inline C2Rect(uint32_t width, uint32_t height, uint32_t left, uint32_t top)
         : mLeft(left), mTop(top), mWidth(width), mHeight(height) { }
 
     // utility methods
@@ -895,29 +921,51 @@
 public:
     // crop can be an empty rect, does not have to line up with subsampling
     // NOTE: we do not support floating-point crop
-    inline const C2Rect crop() { return mCrop; }
+    inline const C2Rect crop() const { return mCrop; }
 
     /**
      *  Sets crop to crop intersected with [(0,0) .. (width, height)]
      */
-    inline void setCrop_be(const C2Rect &crop);
+    inline void setCrop_be(const C2Rect &crop) {
+        mCrop.mLeft = std::min(width(), crop.mLeft);
+        mCrop.mTop = std::min(height(), crop.mTop);
+        // It's guaranteed that mCrop.mLeft <= width() && mCrop.mTop <= height()
+        mCrop.mWidth = std::min(width() - mCrop.mLeft, crop.mWidth);
+        mCrop.mHeight = std::min(height() - mCrop.mTop, crop.mHeight);
+    }
 
     /**
      * If crop is within the dimensions of this object, it sets crop to it.
      *
      * \return true iff crop is within the dimensions of this object
      */
-    inline bool setCrop(const C2Rect &crop);
+    inline bool setCrop(const C2Rect &crop) {
+        if (width() < crop.mWidth || height() < crop.mHeight
+                || width() - crop.mWidth < crop.mLeft || height() - crop.mHeight < crop.mTop) {
+            return false;
+        }
+        mCrop = crop;
+        return true;
+    }
+
+protected:
+    inline _C2PlanarSection(const _C2PlanarCapacityAspect *parent)
+        : _C2PlanarCapacityAspect(parent), mCrop(width(), height()) {}
 
 private:
     C2Rect mCrop;
 /// @}
 };
 
+class C2GraphicAllocation;
+
 class C2Block2D : public _C2PlanarSection {
 public:
     const C2Handle *handle() const;
 
+protected:
+    C2Block2D(const std::shared_ptr<C2GraphicAllocation> &alloc);
+
 private:
     class Impl;
     std::shared_ptr<Impl> mImpl;
@@ -935,14 +983,25 @@
 class C2GraphicView : public _C2PlanarSection {
 public:
     /**
-     * \return pointer to the start of the block or nullptr on error.
+     * \return array of pointers to the start of the planes or nullptr on error.
+     * Regardless of crop rect, they always point to the top-left corner of
+     * each plane.  Access outside of the crop rect results in an undefined
+     * behavior.
      */
-    const uint8_t *data() const;
+    const uint8_t *const *data() const;
 
     /**
-     * \return pointer to the start of the block or nullptr on error.
+     * \return array of pointers to the start of the planes or nullptr on error.
+     * Regardless of crop rect, they always point to the top-left corner of
+     * each plane.  Access outside of the crop rect results in an undefined
+     * behavior.
      */
-    uint8_t *data();
+    uint8_t *const *data();
+
+    /**
+     * \return layout of the graphic block to interpret the returned data.
+     */
+    const C2PlaneLayout layout() const;
 
     /**
      * Returns a section of this view.
@@ -959,6 +1018,13 @@
      */
     C2Error error() const;
 
+protected:
+    C2GraphicView(
+            const _C2PlanarCapacityAspect *parent,
+            uint8_t *const *data,
+            const C2PlaneLayout& layout);
+    explicit C2GraphicView(C2Error error);
+
 private:
     class Impl;
     std::shared_ptr<Impl> mImpl;
@@ -996,7 +1062,12 @@
      */
     C2Fence fence() const { return mFence; }
 
+protected:
+    C2ConstGraphicBlock(const std::shared_ptr<C2GraphicAllocation> &alloc, C2Fence fence);
+
 private:
+    class Impl;
+    std::shared_ptr<Impl> mImpl;
     C2Fence mFence;
 };
 
@@ -1024,6 +1095,13 @@
      *    The block shall be modified only until firing the event for the fence.
      */
     C2ConstGraphicBlock share(const C2Rect &crop, C2Fence fence);
+
+protected:
+    explicit C2GraphicBlock(const std::shared_ptr<C2GraphicAllocation> &alloc);
+
+private:
+    class Impl;
+    std::shared_ptr<Impl> mImpl;
 };
 
 /// @}
@@ -1089,7 +1167,8 @@
 
 protected:
     // no public constructor
-    // C2BufferData(const std::shared_ptr<const Impl> &impl) : mImpl(impl) {}
+    explicit C2BufferData(const std::list<C2ConstLinearBlock> &blocks);
+    explicit C2BufferData(const std::list<C2ConstGraphicBlock> &blocks);
 };
 
 /**
@@ -1145,7 +1224,7 @@
      * \retval C2_NO_MEMORY not enough memory to register for this callback
      * \retval C2_CORRUPTED an unknown error prevented the registration (unexpected)
      */
-    C2Error registerOnDestroyNotify(OnDestroyNotify *onDestroyNotify, void *arg = nullptr);
+    C2Error registerOnDestroyNotify(OnDestroyNotify onDestroyNotify, void *arg = nullptr);
 
     /**
      * Unregisters a previously registered pre-destroy notification.
@@ -1157,7 +1236,7 @@
      * \retval C2_NOT_FOUND the notification was not found
      * \retval C2_CORRUPTED an unknown error prevented the registration (unexpected)
      */
-    C2Error unregisterOnDestroyNotify(OnDestroyNotify *onDestroyNotify, void *arg = nullptr);
+    C2Error unregisterOnDestroyNotify(OnDestroyNotify onDestroyNotify);
 
     ///@}
 
@@ -1193,14 +1272,17 @@
      * \return true iff there is a metadata with the parameter type attached to this buffer.
      */
     bool hasInfo(C2Param::Type index) const;
-    std::shared_ptr<C2Info> removeInfo(C2Param::Type index) const;
+    std::shared_ptr<C2Info> removeInfo(C2Param::Type index);
     ///@}
 
 protected:
     // no public constructor
-    inline C2Buffer() = default;
+    explicit C2Buffer(const std::list<C2ConstLinearBlock> &blocks);
+    explicit C2Buffer(const std::list<C2ConstGraphicBlock> &blocks);
 
 private:
+    class Impl;
+    std::shared_ptr<Impl> mImpl;
 //    Type _mType;
 };
 
@@ -1425,10 +1507,11 @@
     /**
      * Returns true if this is the same allocation as |other|.
      */
-    virtual bool equals(const std::shared_ptr<const C2GraphicAllocation> &other) = 0;
+    virtual bool equals(const std::shared_ptr<const C2GraphicAllocation> &other) const = 0;
 
 protected:
-    virtual ~C2GraphicAllocation();
+    using _C2PlanarCapacityAspect::_C2PlanarCapacityAspect;
+    virtual ~C2GraphicAllocation() = default;
 };
 
 /**
diff --git a/media/libstagefright/codec2/include/C2Component.h b/media/libstagefright/codec2/include/C2Component.h
index 1ee9302..94312fb 100644
--- a/media/libstagefright/codec2/include/C2Component.h
+++ b/media/libstagefright/codec2/include/C2Component.h
@@ -52,7 +52,7 @@
     // virtual void onComponentReleased(<id>) = 0;
 
 protected:
-    virtual ~C2ComponentListener();
+    virtual ~C2ComponentListener() = default;
 };
 
 /**
@@ -282,7 +282,7 @@
      * fields in the same list?
      */
     virtual status_t getSupportedValues(
-            const std::vector<const C2ParamField> fields,
+            const std::vector<const C2ParamField> &fields,
             std::vector<C2FieldSupportedValues>* const values) const = 0;
 
     virtual ~C2ComponentInterface() = default;
@@ -543,6 +543,7 @@
 };
 
 class C2ComponentStore {
+public:
     /**
      * Creates a component.
      *
diff --git a/media/libstagefright/codec2/include/C2Config.h b/media/libstagefright/codec2/include/C2Config.h
index 30e9193..18e0a47 100644
--- a/media/libstagefright/codec2/include/C2Config.h
+++ b/media/libstagefright/codec2/include/C2Config.h
@@ -67,6 +67,7 @@
     kParamIndexStructStart = 0x1,
     kParamIndexVideoSize,
     kParamIndexMaxVideoSizeHint,
+    kParamIndexVideoSizeTuning,
 
     kParamIndexParamStart = 0x800,
 };
@@ -230,19 +231,22 @@
     int32_t mWidth;     ///< video width
     int32_t mHeight;    ///< video height
 
-    DEFINE_AND_DESCRIBE_C2STRUCT(VideoSize)
+    DEFINE_C2STRUCT_NO_BASE(VideoSize)
+} C2_PACK;
+
+DESCRIBE_C2STRUCT(VideoSize, {
     C2FIELD(mWidth, "width")
     C2FIELD(mHeight, "height")
-};
+})
 
 // video size for video decoder [OUT]
-typedef C2StreamParam<C2Info, C2VideoSizeStruct> C2VideoSizeStreamInfo;
+typedef C2StreamParam<C2Info, C2VideoSizeStruct, kParamIndexVideoSize> C2VideoSizeStreamInfo;
 
 // max video size for video decoder [IN]
 typedef C2PortParam<C2Setting, C2VideoSizeStruct, kParamIndexMaxVideoSizeHint> C2MaxVideoSizeHintPortSetting;
 
 // video encoder size [IN]
-typedef C2StreamParam<C2Tuning, C2VideoSizeStruct> C2VideoSizeStreamTuning;
+typedef C2StreamParam<C2Tuning, C2VideoSizeStruct, kParamIndexVideoSizeTuning> C2VideoSizeStreamTuning;
 
 /// @}
 
diff --git a/media/libstagefright/codec2/include/C2Param.h b/media/libstagefright/codec2/include/C2Param.h
index fd43061..aab0474 100644
--- a/media/libstagefright/codec2/include/C2Param.h
+++ b/media/libstagefright/codec2/include/C2Param.h
@@ -362,6 +362,17 @@
         return param;
     }
 
+    /// Returns managed clone of |orig| at heap.
+    inline static std::unique_ptr<C2Param> Copy(const C2Param &orig) {
+        if (orig.size() == 0) {
+            return nullptr;
+        }
+        void *mem = ::operator new (orig.size());
+        C2Param *param = new (mem) C2Param(orig.size(), orig._mIndex);
+        param->updateFrom(orig);
+        return std::unique_ptr<C2Param>(param);
+    }
+
 #if 0
     template<typename P, class=decltype(C2Param(P()))>
     P *As() { return P::From(this); }
@@ -661,11 +672,11 @@
     Primitive mValue;
 };
 
-template<> const int32_t &C2Value::Primitive::ref<int32_t>() const { return i32; }
-template<> const int64_t &C2Value::Primitive::ref<int64_t>() const { return i64; }
-template<> const uint32_t &C2Value::Primitive::ref<uint32_t>() const { return u32; }
-template<> const uint64_t &C2Value::Primitive::ref<uint64_t>() const { return u64; }
-template<> const float &C2Value::Primitive::ref<float>() const { return fp; }
+template<> inline const int32_t &C2Value::Primitive::ref<int32_t>() const { return i32; }
+template<> inline const int64_t &C2Value::Primitive::ref<int64_t>() const { return i64; }
+template<> inline const uint32_t &C2Value::Primitive::ref<uint32_t>() const { return u32; }
+template<> inline const uint64_t &C2Value::Primitive::ref<uint64_t>() const { return u64; }
+template<> inline const float &C2Value::Primitive::ref<float>() const { return fp; }
 
 template<> constexpr C2Value::Type C2Value::typeFor<int32_t>() { return INT32; }
 template<> constexpr C2Value::Type C2Value::typeFor<int64_t>() { return INT64; }
diff --git a/media/libstagefright/codec2/include/C2Work.h b/media/libstagefright/codec2/include/C2Work.h
index a42d11a..a378623 100644
--- a/media/libstagefright/codec2/include/C2Work.h
+++ b/media/libstagefright/codec2/include/C2Work.h
@@ -60,9 +60,9 @@
 typedef uint32_t node_id;
 
 enum flags_t : uint32_t {
-    BUFFERFLAG_CODEC_CONFIG,
-    BUFFERFLAG_DROP_FRAME,
-    BUFFERFLAG_END_OF_STREAM,
+    BUFFERFLAG_CODEC_CONFIG  = (1 << 0),
+    BUFFERFLAG_DROP_FRAME    = (1 << 1),
+    BUFFERFLAG_END_OF_STREAM = (1 << 2),
 };
 
 enum {
diff --git a/media/libstagefright/codec2/tests/Android.bp b/media/libstagefright/codec2/tests/Android.bp
new file mode 100644
index 0000000..8a18f7d
--- /dev/null
+++ b/media/libstagefright/codec2/tests/Android.bp
@@ -0,0 +1,77 @@
+cc_test {
+    name: "codec2_test",
+
+    tags: [
+        "tests",
+    ],
+
+    srcs: [
+        "vndk/C2BufferTest.cpp",
+        "vndk/C2UtilTest.cpp",
+        "C2_test.cpp",
+        "C2Param_test.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/av/media/libstagefright/codec2/vndk/include",
+    ],
+
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "android.hardware.graphics.mapper@2.0",
+        "libcutils",
+        "libhidlbase",
+        "libion",
+        "liblog",
+        "libstagefright_codec2",
+        "libutils",
+    ],
+
+    static_libs: [
+        "libstagefright_codec2_vndk",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-std=c++14",
+    ],
+}
+
+cc_test {
+    name: "codec2_interface_test",
+
+    tags: [
+        "tests",
+    ],
+
+    srcs: [
+        "C2ComponentInterface_test.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/av/media/libstagefright/codec2/vndk/include",
+        "frameworks/native/include/media/openmax",
+    ],
+
+    shared_libs: [
+        "libcutils",
+        "libhidlbase",
+        "libion",
+        "liblog",
+        "libstagefright_codec2",
+        "libutils",
+    ],
+
+    static_libs: [
+        "libstagefright_codec2_vndk",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-std=c++14",
+    ],
+}
diff --git a/media/libstagefright/codec2/tests/Android.mk b/media/libstagefright/codec2/tests/Android.mk
deleted file mode 100644
index 49c4253..0000000
--- a/media/libstagefright/codec2/tests/Android.mk
+++ /dev/null
@@ -1,37 +0,0 @@
-# Build the unit tests.
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-LOCAL_MODULE := codec2_test
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := \
-	vndk/C2UtilTest.cpp \
-	C2_test.cpp \
-	C2Param_test.cpp \
-
-LOCAL_SHARED_LIBRARIES := \
-	libcutils \
-	libstagefright_codec2 \
-	liblog
-
-LOCAL_C_INCLUDES := \
-	frameworks/av/media/libstagefright/codec2/include \
-	frameworks/av/media/libstagefright/codec2/vndk/include \
-	$(TOP)/frameworks/native/include/media/openmax \
-
-LOCAL_CFLAGS += -Werror -Wall -std=c++14
-LOCAL_CLANG := true
-
-include $(BUILD_NATIVE_TEST)
-
-# Include subdirectory makefiles
-# ============================================================
-
-# If we're building with ONE_SHOT_MAKEFILE (mm, mmm), then what the framework
-# team really wants is to build the stuff defined by this makefile.
-ifeq (,$(ONE_SHOT_MAKEFILE))
-include $(call first-makefiles-under,$(LOCAL_PATH))
-endif
diff --git a/media/libstagefright/codec2/tests/C2ComponentInterface_test.cpp b/media/libstagefright/codec2/tests/C2ComponentInterface_test.cpp
new file mode 100644
index 0000000..0c8ca3e
--- /dev/null
+++ b/media/libstagefright/codec2/tests/C2ComponentInterface_test.cpp
@@ -0,0 +1,708 @@
+/*
+ * Copyright 2017 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 "C2ComponentInterface_test"
+
+#include <dlfcn.h>
+#include <stdio.h>
+
+#include <gtest/gtest.h>
+#include <utils/Log.h>
+
+#include <C2Component.h>
+#include <C2Param.h>
+
+#if !defined(UNUSED)
+#define UNUSED(expr)                                                           \
+  do {                                                                         \
+      (void)(expr);                                                            \
+  } while (0)
+
+#endif //!defined(UNUSED)
+
+namespace android {
+
+template <class T> std::unique_ptr<T> alloc_unique_cstr(const char *cstr) {
+    size_t len = strlen(cstr);
+    std::unique_ptr<T> ptr = T::alloc_unique(len);
+    memcpy(ptr->m.mValue, cstr, len);
+    return ptr;
+}
+
+class C2CompIntfTest : public ::testing::Test {
+protected:
+    C2CompIntfTest() {}
+    ~C2CompIntfTest() override {}
+
+    void setComponent(std::shared_ptr<C2ComponentInterface> intf) {
+        mIntf = intf;
+    }
+
+    void resetResults() {
+        mIntf = nullptr;
+        mParamResults.clear();
+    }
+
+    template <typename T> void testUnsupportedParam();
+
+    template <typename T> void testSupportedParam();
+
+    // testReadOnlyParam() and testWritableParam() are the main functions for testing a parameter.
+    // A caller should find out if a tested parameter is read-only or writable before calling them
+    // and it must call one of the corresponded them.
+
+    // If a parameter is read-only this is called.
+    // Test read-only parameter |preParam|. The test expects failure while config() with |newParam|,
+    // and make sure |preParam| stay unchanged.
+    template <typename T>
+    void testReadOnlyParam(const T &preParam, const T &newParam);
+
+    // If a parameter is writable this is called.
+    // Test one filed |writableField| for given writable parameter |param|.
+    // |validValues| contains all values obtained from getSupportedValues() for |writableField|.
+    // The test checks validity for config() with each value, and make sure values are config-ed
+    // by query() them out. |invalidValues| contains some values which are not in |validValues|.
+    // The test expects C2_BAD_VALUE while config() with these values,
+    // and |param| should stay unchanged.
+    template <typename TParam, typename TRealField, typename TField>
+    void testWritableParam(TParam *const param, TRealField *const writableField,
+                           const std::vector<TField> &validValues,
+                           const std::vector<TField> &invalidValues);
+
+    // Test all the defined parameters in C2Param.h.
+    void testMain(std::shared_ptr<C2ComponentInterface> intf,
+                  const std::string &componentName);
+
+    // Check permission of parameter type |T| for testing interface.
+    // This should be called first of the testing per parameter type,
+    // therefore different testing process is applied according to the permission type.
+    template <typename T>
+    void checkParamPermission(
+            int *const writable,
+            const std::vector<std::shared_ptr<C2ParamDescriptor>> &supportedParams);
+
+private:
+    enum ParamPermission : int {
+        WRITABLE,
+        READONLY,
+        UNSUPPORTED,
+    };
+
+    struct paramTestInfo {
+        std::string name;
+        int result;
+        paramTestInfo(const char *name_, int result_)
+            : name(name_), result(result_) {}
+    };
+
+    // queryOnStack() and queryonHeap() both call an interface's query_nb() and
+    // check if a component has a parameter whose type is |T|.
+    // If a component has, the value should be copied into an argument, that is
+    // |p| in queryOnStack() and |heapParams| in queryOnHeap().
+    // The return value is status_t (e.g. C2_OK).
+    template <typename T> status_t queryOnStack(T *const p);
+
+    template <typename T>
+    status_t queryOnHeap(const T &p,
+                         std::vector<std::unique_ptr<C2Param>> *const heapParams);
+
+    // Get a value whose type is |T| in a component. The value is copied to |param|.
+    // This should be called only if a component has the parameter.
+    template <typename T> void getValue(T *const param);
+
+    // Check if the parameter's value in component is equal to |expected| and
+    // queryOnStack() and queryOnHeap() are succeeded. When this function called,
+    // it should be guaranteed a component has the parameter.
+    template <typename T> void queryParamAsExpected(const T &expected);
+
+    // Test if query functions works correctly for supported parameters.
+    // "Support" means here a component has the parameter.
+    template <typename T> void querySupportedParam();
+
+    // Test query functions works correctly for unsupported parameters.
+    // "Unsupport" means here a component doesn't have the parameter.
+    template <typename T> void queryUnsupportedParam();
+
+    // Execute an interface's config_nb(). |T| is a single parameter type, not std::vector.
+    // config() creates std::vector<C2Param *const> {p} and passes it to config_nb().
+    template <typename T>
+    status_t
+    config(T *const p,
+           std::vector<std::unique_ptr<C2SettingResult>> *const failures);
+
+    // Test if config works correctly for read-only parameters.
+    // Because the failure of config() is assumed, |newParam| doesn't matter.
+    template <typename T> void configReadOnlyParam(const T &newParam);
+
+    // Test if config works correctly for writable parameters.
+    // This changes the parameter's value to |newParam|.
+    // |stConfig| is a return value of config().
+    template <typename T> void configWritableParamValidValue(const T &newParam, status_t *stConfig);
+
+    // Test if config works correctly in the case an invalid value |newParam| is tried to write
+    // to an writable parameter.
+    template <typename T> void configWritableParamInvalidValue(const T &newParam);
+
+    // Create values for testing from |validValueInfos|. The values are returned as arguments.
+    // |validValues| : valid values, which can be written for the parameter.
+    // |InvalidValues| : invalid values, which cannot be written for the parameter.
+    //                   config() should be failed if these values are used as new values.
+    // This function should be called only for writable and supported parameters.
+    template <typename TField>
+    void getTestValues(const std::vector<C2FieldSupportedValues> &validValueInfos,
+                       std::vector<TField> *const validValues,
+                       std::vector<TField> *const invalidValues);
+
+    // Output the summary of test results. Categorizes parameters with their configuration.
+    void outputResults(const std::string &name);
+
+    std::shared_ptr<C2ComponentInterface> mIntf;
+    std::vector<paramTestInfo> mParamResults;
+    std::string mCurrentParamName;
+};
+
+// factory function
+// TODO(hiroh): Add factory functions for other types.
+template <typename T> std::unique_ptr<T> makeParam() {
+    return std::make_unique<T>();
+}
+
+template <> std::unique_ptr<C2PortMimeConfig::input> makeParam() {
+    // TODO(hiroh): Set more precise length.
+    return C2PortMimeConfig::input::alloc_unique(100);
+}
+
+#define TRACED_FAILURE(func)                            \
+    do {                                                \
+        SCOPED_TRACE(mCurrentParamName);             \
+        func;                                           \
+        if (::testing::Test::HasFatalFailure()) {       \
+            return;                                     \
+        }                                               \
+    } while (false)
+
+template <typename T> status_t C2CompIntfTest::queryOnStack(T *const p) {
+    std::vector<C2Param *const> stackParams{p};
+    return mIntf->query_nb(stackParams, {}, nullptr);
+}
+
+template <typename T>
+status_t C2CompIntfTest::queryOnHeap(
+        const T &p, std::vector<std::unique_ptr<C2Param>> *const heapParams) {
+    uint32_t index = p.type();
+    if (p.forStream()) {
+        index |= ((p.stream() << 17) & 0x01FE0000) | 0x02000000;
+    }
+    return mIntf->query_nb({}, {index}, heapParams);
+}
+
+template <typename T> void C2CompIntfTest::getValue(T *const param) {
+    // When getValue() is called, a component has to have the parameter.
+    ASSERT_EQ(C2_OK, queryOnStack(param));
+}
+
+template <typename T>
+void C2CompIntfTest::queryParamAsExpected(const T &expected) {
+    // TODO(hiroh): Don't create param on stack and call queryOnStack for flex params.
+    // Note that all the current supported parameters are non-flex params.
+    T stack;
+    std::unique_ptr<T> pHeap = makeParam<T>();
+    std::vector<std::unique_ptr<C2Param>> heapParams;
+
+    ASSERT_EQ(C2_OK, queryOnStack(&stack));
+
+    // |stack| is a parameter value. The parameter size shouldn't be 0.
+    EXPECT_NE(0u, stack.size());
+    EXPECT_EQ(stack, expected);
+
+    ASSERT_EQ(C2_OK, queryOnHeap(*pHeap, &heapParams));
+
+    // |*heapParams[0]| is a parameter value. The size of |heapParams| has to be one.
+    ASSERT_EQ(1u, heapParams.size());
+    EXPECT_TRUE(heapParams[0]);
+    EXPECT_EQ(*heapParams[0], expected);
+}
+
+template <typename T> void C2CompIntfTest::querySupportedParam() {
+    std::unique_ptr<T> param = makeParam<T>();
+    // The current parameter's value is acquired by getValue(), which should be succeeded.
+    getValue(param.get());
+    queryParamAsExpected(*param);
+}
+
+template <typename T> void C2CompIntfTest::queryUnsupportedParam() {
+    // TODO(hiroh): Don't create param on stack and call queryOnStack for flex params.
+    // Note that all the current supported parameters are non-flex params.
+    T stack;
+    std::unique_ptr<T> pHeap = makeParam<T>();
+    std::vector<std::unique_ptr<C2Param>> heapParams;
+    // If a component doesn't have the parameter, queryOnStack() and queryOnHeap()
+    // should return C2_BAD_INDEX.
+    ASSERT_EQ(C2_BAD_INDEX, queryOnStack(&stack));
+    EXPECT_FALSE(stack);
+    ASSERT_EQ(C2_BAD_INDEX, queryOnHeap(*pHeap, &heapParams));
+    EXPECT_EQ(0u, heapParams.size());
+}
+
+template <typename T>
+status_t C2CompIntfTest::config(
+        T *const p, std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
+    std::vector<C2Param *const> params{p};
+    return mIntf->config_nb(params, failures);
+}
+
+// Create a new parameter copied from |p|.
+template <typename T> std::unique_ptr<T> makeParamFrom(const T &p) {
+    std::unique_ptr<T> retP = makeParam<T>();
+    EXPECT_TRUE(retP->updateFrom(p));
+    EXPECT_TRUE(memcmp(retP.get(), &p, sizeof(T)) == 0);
+    return retP;
+}
+
+template <typename T>
+void C2CompIntfTest::configReadOnlyParam(const T &newParam) {
+    std::unique_ptr<T> p = makeParamFrom(newParam);
+
+    std::vector<C2Param *const> params{p.get()};
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+
+    // config_nb should be failed because a parameter is read-only.
+    ASSERT_EQ(C2_BAD_VALUE, mIntf->config_nb(params, &failures));
+    ASSERT_EQ(1u, failures.size());
+    EXPECT_EQ(C2SettingResult::READ_ONLY, failures[0]->failure);
+}
+
+template <typename T>
+void C2CompIntfTest::configWritableParamValidValue(const T &newParam, status_t *configResult) {
+    std::unique_ptr<T> p = makeParamFrom(newParam);
+
+    std::vector<C2Param *const> params{p.get()};
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+    // In most cases, config_nb return C2_OK and the parameter's value should be changed
+    // to |newParam|, which is confirmed in a caller of configWritableParamValueValue().
+    // However, this can return ~~~~ and the parameter's values is not changed,
+    // because there may be dependent limitations between fields or between parameters.
+    // TODO(hiroh): I have to fill the return value. Comments in C2Component.h doesn't mention
+    // about the return value when conflict happens. I set C2_BAD_VALUE to it temporarily now.
+    status_t stConfig = mIntf->config_nb(params, &failures);
+    if (stConfig == C2_OK) {
+        EXPECT_EQ(0u, failures.size());
+    } else {
+        ASSERT_EQ(C2_BAD_VALUE, stConfig);
+        EXPECT_EQ(1u, failures.size());
+        EXPECT_EQ(C2SettingResult::CONFLICT, failures[0]->failure);
+    }
+    *configResult = stConfig;
+}
+
+template <typename T>
+void C2CompIntfTest::configWritableParamInvalidValue(const T &newParam) {
+    std::unique_ptr<T> p = makeParamFrom(newParam);
+
+    std::vector<C2Param *const> params{p.get()};
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+    // Although a parameter is writable, config_nb should be failed,
+    // because a new value is invalid.
+    ASSERT_EQ(C2_BAD_VALUE, mIntf->config_nb(params, &failures));
+    ASSERT_EQ(1u, failures.size());
+    EXPECT_EQ(C2SettingResult::BAD_VALUE, failures[0]->failure);
+}
+
+// There is only used enum type for the field type, that is C2DomainKind.
+// If another field type is added, it is necessary to add function for that.
+template <>
+void C2CompIntfTest::getTestValues(
+        const std::vector<C2FieldSupportedValues> &validValueInfos,
+        std::vector<C2DomainKind> *const validValues,
+        std::vector<C2DomainKind> *const invalidValues) {
+    UNUSED(validValueInfos);
+    validValues->emplace_back(C2DomainVideo);
+    validValues->emplace_back(C2DomainAudio);
+    validValues->emplace_back(C2DomainOther);
+
+    // There is no invalid value.
+    UNUSED(invalidValues);
+}
+
+template <typename TField>
+void C2CompIntfTest::getTestValues(
+        const std::vector<C2FieldSupportedValues> &validValueInfos,
+        std::vector<TField> *const validValues,
+        std::vector<TField> *const invalidValues) {
+
+    // The supported values are represented by C2Values. C2Value::Primitive needs to
+    // be transformed to a primitive value. This function is one to do that.
+    auto prim2Value = [](const C2Value::Primitive &prim) -> TField {
+        if (std::is_same<TField, int32_t>::value) {
+            return prim.i32;
+        } else if (std::is_same<TField, uint32_t>::value) {
+            return prim.u32;
+        } else if (std::is_same<TField, int64_t>::value) {
+            return prim.i64;
+        } else if (std::is_same<TField, uint64_t>::value) {
+            return prim.u64;
+        } else if (std::is_same<TField, float>::value) {
+            return prim.fp;
+        }
+        static_assert(std::is_same<TField, int32_t>::value ||
+                      std::is_same<TField, uint32_t>::value ||
+                      std::is_same<TField, int64_t>::value ||
+                      std::is_same<TField, uint64_t>::value ||
+                      std::is_same<TField, float>::value, "Invalid TField type.");
+        return 0;
+    };
+
+    // The size of validValueInfos is one.
+    const auto &c2FSV = validValueInfos[0];
+
+    switch (c2FSV.type) {
+    case C2FieldSupportedValues::Type::RANGE: {
+        const auto &range = c2FSV.range;
+        auto rmin = prim2Value(range.min);
+        auto rmax = prim2Value(range.max);
+        auto rstep = prim2Value(range.step);
+
+        ASSERT_LE(rmin, rmax);
+
+        if (rstep != 0) {
+            // Increase linear
+            for (auto v = rmin; v <= rmax; v += rstep) {
+                validValues->emplace_back(v);
+            }
+            if (rmin > std::numeric_limits<TField>::min()) {
+                invalidValues->emplace_back(rmin - 1);
+            }
+            if (rmax < std::numeric_limits<TField>::max()) {
+                invalidValues->emplace_back(rmax + 1);
+            }
+            const unsigned int N = validValues->size();
+            if (N >= 2) {
+                if (std::is_same<TField, float>::value) {
+                    invalidValues->emplace_back((validValues->at(0) + validValues->at(1)) / 2);
+                    invalidValues->emplace_back((validValues->at(N - 2) + validValues->at(N - 1)) / 2);
+                } else {
+                    if (rstep > 1) {
+                        invalidValues->emplace_back(validValues->at(0) + 1);
+                        invalidValues->emplace_back(validValues->at(N - 1) - 1);
+                    }
+                }
+            }
+        } else {
+            // There should be two cases, except linear case.
+            // 1. integer geometric case
+            // 2. float geometric case
+
+            auto nom = prim2Value(range.nom);
+            auto denom = prim2Value(range.denom);
+
+            // If both range.nom and range.denom are 1 and step is 0, we should use
+            // VALUES, shouldn't we?
+            ASSERT_FALSE(nom == 1 && denom == 1);
+
+            // (nom / denom) is not less than 1.
+            ASSERT_FALSE(denom == 0);
+            ASSERT_LE(denom, nom);
+            for (auto v = rmin; v <= rmax; v = v * nom / denom) {
+                validValues->emplace_back(v);
+            }
+
+            if (rmin > std::numeric_limits<TField>::min()) {
+                invalidValues->emplace_back(rmin - 1);
+            }
+            if (rmax < std::numeric_limits<TField>::max()) {
+                invalidValues->emplace_back(rmax + 1);
+            }
+
+            const unsigned int N = validValues->size();
+            if (N >= 2) {
+                if (std::is_same<TField, float>::value) {
+                    invalidValues->emplace_back((validValues->at(0) + validValues->at(1)) / 2);
+                    invalidValues->emplace_back((validValues->at(N - 2) + validValues->at(N - 1)) / 2);
+                } else {
+                    if (validValues->at(1) - validValues->at(0) > 1) {
+                        invalidValues->emplace_back(validValues->at(0) + 1);
+                    }
+                    if (validValues->at(N - 1) - validValues->at(N - 2) > 1) {
+                        invalidValues->emplace_back(validValues->at(N - 1) - 1);
+                    }
+                }
+            }
+        }
+        break;
+    }
+    case C2FieldSupportedValues::Type::VALUES: {
+        for (const C2Value::Primitive &prim : c2FSV.values) {
+            validValues->emplace_back(prim2Value(prim));
+        }
+        auto minv = *std::min_element(validValues->begin(), validValues->end());
+        auto maxv = *std::max_element(validValues->begin(), validValues->end());
+        if (minv - 1 > std::numeric_limits<TField>::min()) {
+            invalidValues->emplace_back(minv - 1);
+        }
+        if (maxv + 1 < std::numeric_limits<TField>::max()) {
+            invalidValues->emplace_back(maxv + 1);
+        }
+        break;
+    }
+    case C2FieldSupportedValues::Type::FLAGS: {
+        // TODO(hiroh) : Implement the case that param.type is FLAGS.
+        break;
+    }
+    }
+}
+
+template <typename T>
+void C2CompIntfTest::testReadOnlyParam(const T &preParam, const T &newParam) {
+    TRACED_FAILURE(configReadOnlyParam(newParam));
+    // Parameter value must not be changed
+    TRACED_FAILURE(queryParamAsExpected(preParam));
+}
+
+template <typename TParam, typename TRealField, typename TField>
+void C2CompIntfTest::testWritableParam(
+        TParam *const param, TRealField *const writableField,
+        const std::vector<TField> &validValues,
+        const std::vector<TField> &invalidValues) {
+    status_t stConfig;
+
+    // Get the parameter's value in the beginning in order to reset the value at the end.
+    TRACED_FAILURE(getValue(param));
+    std::unique_ptr<TParam> defaultParam = makeParamFrom(*param);
+
+    // Test valid values
+    for (const auto &val : validValues) {
+        std::unique_ptr<TParam> preParam = makeParamFrom(*param);
+
+        // Param is try to be changed
+        *writableField = val;
+        TRACED_FAILURE(configWritableParamValidValue(*param, &stConfig));
+        if (stConfig == C2_OK) {
+            TRACED_FAILURE(queryParamAsExpected(*param));
+        } else {
+            // Param is unchanged because a field value conflicts with other field or parameter.
+            TRACED_FAILURE(queryParamAsExpected(*preParam));
+        }
+    }
+
+    // Store the current parameter in order to test |param| is unchanged
+    // after trying to write an invalid value.
+    std::unique_ptr<TParam> lastValidParam = makeParamFrom(*param);
+
+    // Test invalid values
+    for (const auto &val : invalidValues) {
+        // Param is changed
+        *writableField = val;
+        TRACED_FAILURE(configWritableParamInvalidValue(*param));
+        TRACED_FAILURE(queryParamAsExpected(*lastValidParam));
+    }
+    // Reset the parameter by config().
+    TRACED_FAILURE(configWritableParamValidValue(*defaultParam, &stConfig));
+}
+
+template <typename T> void C2CompIntfTest::testUnsupportedParam() {
+    TRACED_FAILURE(queryUnsupportedParam<T>());
+}
+
+template <typename T> void C2CompIntfTest::testSupportedParam() {
+    TRACED_FAILURE(querySupportedParam<T>());
+}
+
+bool isSupportedParam(
+        const C2Param &param,
+        const std::vector<std::shared_ptr<C2ParamDescriptor>> &sParams) {
+    for (const auto &pd : sParams) {
+        if (param.type() == pd->type().type()) {
+            return true;
+        }
+    }
+    return false;
+}
+
+template <typename T>
+void C2CompIntfTest::checkParamPermission(
+    int *const result,
+    const std::vector<std::shared_ptr<C2ParamDescriptor>> &supportedParams) {
+    std::unique_ptr<T> param = makeParam<T>();
+
+    if (!isSupportedParam(*param, supportedParams)) {
+        // If a parameter isn't supported, it just finish after calling testUnsupportedParam().
+        testUnsupportedParam<T>();
+        *result = ParamPermission::UNSUPPORTED;
+        return;
+    }
+
+    testSupportedParam<T>();
+
+    TRACED_FAILURE(getValue(param.get()));
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+    // Config does not change the parameter, because param is the present param.
+    // This config is executed to find out if a parameter is read-only or writable.
+    status_t stStack = config(param.get(), &failures);
+    if (stStack == C2_BAD_VALUE) {
+        // Read-only
+        std::unique_ptr<T> newParam = makeParam<T>();
+        testReadOnlyParam(*param, *newParam);
+        *result = ParamPermission::READONLY;
+    } else {
+        // Writable
+        EXPECT_EQ(stStack, C2_OK);
+        *result = ParamPermission::WRITABLE;
+    }
+}
+
+void C2CompIntfTest::outputResults(const std::string &name) {
+    std::vector<std::string> params[3];
+    for (const auto &testInfo : mParamResults) {
+        int result = testInfo.result;
+        ASSERT_TRUE(0 <= result && result <= 2);
+        params[result].emplace_back(testInfo.name);
+    }
+    const char *resultString[] = {"Writable", "Read-Only", "Unsupported"};
+    printf("\n----TEST RESULTS (%s)----\n\n", name.c_str());
+    for (int i = 0; i < 3; i++) {
+        printf("[ %s ]\n", resultString[i]);
+        for (const auto &t : params[i]) {
+            printf("%s\n", t.c_str());
+        }
+        printf("\n");
+    }
+}
+
+#define TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, field_name_) \
+    do {                                                                \
+        std::unique_ptr<TParam_> param = makeParam<TParam_>();          \
+        std::vector<C2FieldSupportedValues> validValueInfos;            \
+        ASSERT_EQ(C2_OK,                                                \
+                  mIntf->getSupportedValues(                            \
+                          {C2ParamField(param.get(), &field_type_name_::field_name_)}, \
+                          &validValueInfos));                           \
+        ASSERT_EQ(1u, validValueInfos.size());                          \
+        std::vector<decltype(param->field_name_)> validValues;          \
+        std::vector<decltype(param->field_name_)> invalidValues;        \
+        getTestValues(validValueInfos, &validValues, &invalidValues);   \
+        testWritableParam(param.get(), &param->field_name_, validValues,\
+                          invalidValues);                               \
+    } while (0)
+
+#define TEST_VSSTRUCT_WRITABLE_FIELD(TParam_, field_type_name_)         \
+    do {                                                                \
+        TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, mWidth); \
+        TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, mHeight);\
+    } while (0)
+
+#define TEST_U32_WRITABLE_FIELD(TParam_, field_type_name_)              \
+  TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, mValue)
+
+#define TEST_ENUM_WRITABLE_FIELD(TParam_, field_type_name_)             \
+  TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, mValue)
+
+// TODO(hiroh): Support parameters based on char[] and uint32_t[].
+//#define TEST_STRING_WRITABLE_FIELD(TParam_, field_type_name_)
+// TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, m.mValue)
+//#define TEST_U32ARRAY_WRITABLE_FIELD(Tparam_, field_type_name_)
+// TEST_GENERAL_WRITABLE_FIELD(Tparam_, uint32_t[], field_type_name_, mValues)
+
+#define EACH_TEST(TParam_, field_type_name_, test_name)                 \
+    do {                                                                \
+      int result = 0;                                                   \
+      this->mCurrentParamName = #TParam_;                            \
+      checkParamPermission<TParam_>(&result, supportedParams);          \
+      if (result == ParamPermission::WRITABLE) {                        \
+          test_name(TParam_, field_type_name_);                         \
+      }                                                                 \
+      mParamResults.emplace_back(#TParam_, result);                      \
+  } while (0)
+
+#define EACH_TEST_SELF(type_, test_name) EACH_TEST(type_, type_, test_name)
+#define EACH_TEST_INPUT(type_, test_name) EACH_TEST(type_::input, type_, test_name)
+#define EACH_TEST_OUTPUT(type_, test_name) EACH_TEST(type_::output, type_, test_name)
+void C2CompIntfTest::testMain(std::shared_ptr<C2ComponentInterface> intf,
+                              const std::string &componentName) {
+    setComponent(intf);
+
+    std::vector<std::shared_ptr<C2ParamDescriptor>> supportedParams;
+    ASSERT_EQ(C2_OK, mIntf->getSupportedParams(&supportedParams));
+
+    EACH_TEST_SELF(C2ComponentLatencyInfo, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_SELF(C2ComponentTemporalInfo, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2PortLatencyInfo, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2PortLatencyInfo, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2StreamFormatConfig, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2StreamFormatConfig, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2PortStreamCountConfig, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2PortStreamCountConfig, TEST_U32_WRITABLE_FIELD);
+
+    EACH_TEST_SELF(C2ComponentDomainInfo, TEST_ENUM_WRITABLE_FIELD);
+
+    // TODO(hiroh): Support parameters based on uint32_t[] and char[].
+    // EACH_TEST_INPUT(C2PortMimeConfig, TEST_STRING_WRITABLE_FIELD);
+    // EACH_TEST_OUTPUT(C2PortMimeConfig, TEST_STRING_WRITABLE_FIELD);
+    // EACH_TEST_INPUT(C2StreamMimeConfig, TEST_STRING_WRITABLE_FIELD);
+    // EACH_TEST_OUTPUT(C2StreamMimeConfig, TEST_STRING_WRITABLE_FIELD);
+
+    // EACH_TEST_SELF(C2SupportedParamsInfo, TEST_U32ARRAY_WRITABLE_FIELD);
+    // EACH_TEST_SELF(C2RequiredParamsInfo, TEST_U32ARRAY_WRITABLE_FIELD);
+    // EACH_TEST_SELF(C2ReadOnlyParamsInfo, TEST_U32ARRAY_WRITABLE_FIELD);
+    // EACH_TEST_SELF(C2RequestedInfosInfo, TEST_U32ARRAY_WRITABLE_FIELD);
+
+    EACH_TEST_INPUT(C2VideoSizeStreamInfo, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2VideoSizeStreamInfo, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2VideoSizeStreamTuning, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2VideoSizeStreamTuning, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2MaxVideoSizeHintPortSetting, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2MaxVideoSizeHintPortSetting, TEST_VSSTRUCT_WRITABLE_FIELD);
+
+    outputResults(componentName);
+    resetResults();
+}
+
+TEST_F(C2CompIntfTest, C2V4L2CodecIntf) {
+
+    // Read a shared object library.
+    void* compLib = dlopen("system/lib/libv4l2_codec2.so", RTLD_NOW);
+
+    if (!compLib) {
+        printf("Cannot open library: %s.\n", dlerror());
+        FAIL();
+        return;
+    }
+
+    typedef C2ComponentStore* create_t();
+    create_t* create_store= (create_t*) dlsym(compLib, "create_store");
+    const char* dlsym_error = dlerror();
+    if (dlsym_error) {
+        printf("Cannot load symbol create: %s.\n", dlsym_error);
+        FAIL();
+        return;
+    }
+
+    typedef void destroy_t(C2ComponentStore*);
+    destroy_t* destroy_store = (destroy_t*) dlsym(compLib, "destroy_store");
+    dlsym_error = dlerror();
+    if (dlsym_error) {
+        printf("Cannot load symbol destroy: %s.\n", dlsym_error);
+        FAIL();
+        return;
+    }
+
+    std::shared_ptr<C2ComponentStore> componentStore(create_store(), destroy_store);
+    std::shared_ptr<C2ComponentInterface> componentIntf;
+    componentStore->createInterface("v4l2.decoder", &componentIntf);
+    auto componentName = "C2V4L2Codec";
+    testMain(componentIntf, componentName);
+}
+
+} // namespace android
diff --git a/media/libstagefright/codec2/tests/C2Param_test.cpp b/media/libstagefright/codec2/tests/C2Param_test.cpp
index ec82c84..9165aad 100644
--- a/media/libstagefright/codec2/tests/C2Param_test.cpp
+++ b/media/libstagefright/codec2/tests/C2Param_test.cpp
@@ -968,6 +968,10 @@
         EXPECT_EQ(C2NumberStreamTuning::From(&tun), nullptr);
         EXPECT_EQ(C2NumberStreamTuning::input::From(&tun), nullptr);
         EXPECT_EQ(C2NumberStreamTuning::output::From(&tun), nullptr);
+
+        EXPECT_EQ(*(C2Param::Copy(btun)), btun);
+        btun.invalidate();
+        EXPECT_FALSE(C2Param::Copy(btun));
     }
 
     const C2NumberPortTuning outp1(true, 100), inp1(false, 100);
@@ -1171,6 +1175,11 @@
         EXPECT_EQ(C2NumberStreamTuning::output::From(&inp2), nullptr);
         EXPECT_EQ(C2NumberStreamTuning::output::From(&outp1), nullptr);
         EXPECT_EQ(C2NumberStreamTuning::output::From(&outp2), nullptr);
+
+        EXPECT_EQ(*(C2Param::Copy(inp1)), inp1);
+        EXPECT_EQ(*(C2Param::Copy(inp2)), inp2);
+        EXPECT_EQ(*(C2Param::Copy(outp1)), outp1);
+        EXPECT_EQ(*(C2Param::Copy(outp2)), outp2);
     }
 
     const C2NumberStreamTuning outs1(true, 1u, 100), ins1(false, 1u, 100);
@@ -1383,6 +1392,10 @@
         EXPECT_EQ(C2NumberStreamTuning::output::From(&outs1), (C2NumberStreamTuning::output*)&outs1);
         EXPECT_EQ(C2NumberStreamTuning::output::From(&outs2), &outs2);
 
+        EXPECT_EQ(*(C2Param::Copy(ins1)), ins1);
+        EXPECT_EQ(*(C2Param::Copy(ins2)), ins2);
+        EXPECT_EQ(*(C2Param::Copy(outs1)), outs1);
+        EXPECT_EQ(*(C2Param::Copy(outs2)), outs2);
     }
 
     {
@@ -1518,6 +1531,8 @@
         EXPECT_EQ(C2NumbersStreamTuning::From(tun.get()), nullptr);
         EXPECT_EQ(C2NumbersStreamTuning::input::From(tun.get()), nullptr);
         EXPECT_EQ(C2NumbersStreamTuning::output::From(tun.get()), nullptr);
+
+        EXPECT_EQ(*(C2Param::Copy(*tun)), *tun);
     }
 
     std::unique_ptr<C2NumbersPortTuning> outp1_(C2NumbersPortTuning::alloc_unique(1, true)),
@@ -1739,6 +1754,10 @@
         EXPECT_EQ(C2NumbersStreamTuning::output::From(outp1.get()), nullptr);
         EXPECT_EQ(C2NumbersStreamTuning::output::From(outp2.get()), nullptr);
 
+        EXPECT_EQ(*(C2Param::Copy(*inp1)), *inp1);
+        EXPECT_EQ(*(C2Param::Copy(*inp2)), *inp2);
+        EXPECT_EQ(*(C2Param::Copy(*outp1)), *outp1);
+        EXPECT_EQ(*(C2Param::Copy(*outp2)), *outp2);
     }
 
     std::unique_ptr<C2NumbersStreamTuning> outs1_(C2NumbersStreamTuning::alloc_unique(1, true, 1u));
@@ -1968,6 +1987,10 @@
         EXPECT_EQ(C2NumbersStreamTuning::output::From(outs1.get()), (C2NumbersStreamTuning::output*)outs1.get());
         EXPECT_EQ(C2NumbersStreamTuning::output::From(outs2.get()), outs2.get());
 
+        EXPECT_EQ(*(C2Param::Copy(*ins1)), *ins1);
+        EXPECT_EQ(*(C2Param::Copy(*ins2)), *ins2);
+        EXPECT_EQ(*(C2Param::Copy(*outs1)), *outs1);
+        EXPECT_EQ(*(C2Param::Copy(*outs2)), *outs2);
     }
 
     {
@@ -2262,7 +2285,7 @@
         for (const C2Param::Index index : heapParamIndices) {
             if (mMyParams.count(index)) {
                 C2Param & myParam = mMyParams.find(index)->second;
-                std::unique_ptr<C2Param> paramCopy(C2Param::From(&myParam, myParam.size()));
+                std::unique_ptr<C2Param> paramCopy(C2Param::Copy(myParam));
                 heapParams->push_back(std::move(paramCopy));
             }
         }
@@ -2303,7 +2326,7 @@
     };
 
     virtual status_t getSupportedValues(
-            const std::vector<const C2ParamField> fields,
+            const std::vector<const C2ParamField> &fields,
             std::vector<C2FieldSupportedValues>* const values) const {
         for (const C2ParamField &field : fields) {
             if (field == C2ParamField(&mDomainInfo, &C2ComponentDomainInfo::mValue)) {
diff --git a/media/libstagefright/codec2/tests/vndk/C2BufferTest.cpp b/media/libstagefright/codec2/tests/vndk/C2BufferTest.cpp
new file mode 100644
index 0000000..97c4a7d
--- /dev/null
+++ b/media/libstagefright/codec2/tests/vndk/C2BufferTest.cpp
@@ -0,0 +1,530 @@
+/*
+ * Copyright 2017 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 <gtest/gtest.h>
+
+#include <C2Buffer.h>
+#include <C2BufferPriv.h>
+#include <C2ParamDef.h>
+
+#include <system/graphics.h>
+
+namespace android {
+
+class C2BufferTest : public ::testing::Test {
+public:
+    C2BufferTest()
+        : mLinearAllocator(std::make_shared<C2AllocatorIon>()),
+          mSize(0u),
+          mAddr(nullptr),
+          mGraphicAllocator(std::make_shared<C2AllocatorGralloc>()) {
+    }
+
+    ~C2BufferTest() = default;
+
+    void allocateLinear(size_t capacity) {
+        C2Error err = mLinearAllocator->allocateLinearBuffer(
+                capacity,
+                { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                &mLinearAllocation);
+        if (err != C2_OK) {
+            mLinearAllocation.reset();
+            FAIL() << "C2Allocator::allocateLinearBuffer() failed: " << err;
+        }
+    }
+
+    void mapLinear(size_t offset, size_t size, uint8_t **addr) {
+        ASSERT_TRUE(mLinearAllocation);
+        C2Error err = mLinearAllocation->map(
+                offset,
+                size,
+                { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                // TODO: fence
+                nullptr,
+                &mAddr);
+        if (err != C2_OK) {
+            mAddr = nullptr;
+            FAIL() << "C2LinearAllocation::map() failed: " << err;
+        }
+        ASSERT_NE(nullptr, mAddr);
+        mSize = size;
+        *addr = (uint8_t *)mAddr;
+    }
+
+    void unmapLinear() {
+        ASSERT_TRUE(mLinearAllocation);
+        ASSERT_NE(nullptr, mAddr);
+        ASSERT_NE(0u, mSize);
+
+        // TODO: fence
+        ASSERT_EQ(C2_OK, mLinearAllocation->unmap(mAddr, mSize, nullptr));
+        mSize = 0u;
+        mAddr = nullptr;
+    }
+
+    std::shared_ptr<C2BlockAllocator> makeLinearBlockAllocator() {
+        return std::make_shared<C2DefaultBlockAllocator>(mLinearAllocator);
+    }
+
+    void allocateGraphic(uint32_t width, uint32_t height) {
+        C2Error err = mGraphicAllocator->allocateGraphicBuffer(
+                width,
+                height,
+                HAL_PIXEL_FORMAT_YCBCR_420_888,
+                { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                &mGraphicAllocation);
+        if (err != C2_OK) {
+            mGraphicAllocation.reset();
+            FAIL() << "C2Allocator::allocateLinearBuffer() failed: " << err;
+        }
+    }
+
+    void mapGraphic(C2Rect rect, C2PlaneLayout *layout, uint8_t **addr) {
+        ASSERT_TRUE(mGraphicAllocation);
+        C2Error err = mGraphicAllocation->map(
+                rect,
+                { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                // TODO: fence
+                nullptr,
+                layout,
+                addr);
+        if (err != C2_OK) {
+            addr[C2PlaneLayout::Y] = nullptr;
+            addr[C2PlaneLayout::U] = nullptr;
+            addr[C2PlaneLayout::V] = nullptr;
+            FAIL() << "C2GraphicAllocation::map() failed: " << err;
+        }
+    }
+
+    void unmapGraphic() {
+        ASSERT_TRUE(mGraphicAllocation);
+
+        // TODO: fence
+        ASSERT_EQ(C2_OK, mGraphicAllocation->unmap(nullptr));
+    }
+
+    std::shared_ptr<C2BlockAllocator> makeGraphicBlockAllocator() {
+        return std::make_shared<C2DefaultGraphicBlockAllocator>(mGraphicAllocator);
+    }
+
+private:
+    std::shared_ptr<C2Allocator> mLinearAllocator;
+    std::shared_ptr<C2LinearAllocation> mLinearAllocation;
+    size_t mSize;
+    void *mAddr;
+
+    std::shared_ptr<C2Allocator> mGraphicAllocator;
+    std::shared_ptr<C2GraphicAllocation> mGraphicAllocation;
+};
+
+TEST_F(C2BufferTest, LinearAllocationTest) {
+    constexpr size_t kCapacity = 1024u * 1024u;
+
+    allocateLinear(kCapacity);
+
+    uint8_t *addr = nullptr;
+    mapLinear(0u, kCapacity, &addr);
+    ASSERT_NE(nullptr, addr);
+
+    for (size_t i = 0; i < kCapacity; ++i) {
+        addr[i] = i % 100u;
+    }
+
+    unmapLinear();
+    addr = nullptr;
+
+    mapLinear(kCapacity / 3, kCapacity / 3, &addr);
+    ASSERT_NE(nullptr, addr);
+    for (size_t i = 0; i < kCapacity / 3; ++i) {
+        ASSERT_EQ((i + kCapacity / 3) % 100, addr[i]) << " at i = " << i;
+    }
+}
+
+TEST_F(C2BufferTest, BlockAllocatorTest) {
+    constexpr size_t kCapacity = 1024u * 1024u;
+
+    std::shared_ptr<C2BlockAllocator> blockAllocator(makeLinearBlockAllocator());
+
+    std::shared_ptr<C2LinearBlock> block;
+    ASSERT_EQ(C2_OK, blockAllocator->allocateLinearBlock(
+            kCapacity,
+            { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+            &block));
+    ASSERT_TRUE(block);
+
+    C2Acquirable<C2WriteView> writeViewHolder = block->map();
+    C2WriteView writeView = writeViewHolder.get();
+    ASSERT_EQ(C2_OK, writeView.error());
+    ASSERT_EQ(kCapacity, writeView.capacity());
+    ASSERT_EQ(0u, writeView.offset());
+    ASSERT_EQ(kCapacity, writeView.size());
+
+    uint8_t *data = writeView.data();
+    ASSERT_NE(nullptr, data);
+    for (size_t i = 0; i < writeView.size(); ++i) {
+        data[i] = i % 100u;
+    }
+
+    C2Fence fence;
+    C2ConstLinearBlock constBlock = block->share(
+            kCapacity / 3, kCapacity / 3, fence);
+
+    C2Acquirable<C2ReadView> readViewHolder = constBlock.map();
+    C2ReadView readView = readViewHolder.get();
+    ASSERT_EQ(C2_OK, readView.error());
+    ASSERT_EQ(kCapacity / 3, readView.capacity());
+
+    // TODO: fence
+    const uint8_t *constData = readView.data();
+    ASSERT_NE(nullptr, constData);
+    for (size_t i = 0; i < readView.capacity(); ++i) {
+        ASSERT_EQ((i + kCapacity / 3) % 100u, constData[i]) << " at i = " << i
+                << "; data = " << static_cast<void *>(data)
+                << "; constData = " << static_cast<const void *>(constData);
+    }
+
+    readView = readView.subView(333u, 100u);
+    ASSERT_EQ(C2_OK, readView.error());
+    ASSERT_EQ(100u, readView.capacity());
+
+    constData = readView.data();
+    ASSERT_NE(nullptr, constData);
+    for (size_t i = 0; i < readView.capacity(); ++i) {
+        ASSERT_EQ((i + 333u + kCapacity / 3) % 100u, constData[i]) << " at i = " << i;
+    }
+}
+
+void fillPlane(const C2Rect rect, const C2PlaneInfo info, uint8_t *addr, uint8_t value) {
+    for (uint32_t row = 0; row < rect.mHeight / info.mVertSubsampling; ++row) {
+        int32_t rowOffset = (row + rect.mTop / info.mVertSubsampling) * info.mRowInc;
+        for (uint32_t col = 0; col < rect.mWidth / info.mHorizSubsampling; ++col) {
+            int32_t colOffset = (col + rect.mLeft / info.mHorizSubsampling) * info.mColInc;
+            addr[rowOffset + colOffset] = value;
+        }
+    }
+}
+
+bool verifyPlane(const C2Rect rect, const C2PlaneInfo info, const uint8_t *addr, uint8_t value) {
+    for (uint32_t row = 0; row < rect.mHeight / info.mVertSubsampling; ++row) {
+        int32_t rowOffset = (row + rect.mTop / info.mVertSubsampling) * info.mRowInc;
+        for (uint32_t col = 0; col < rect.mWidth / info.mHorizSubsampling; ++col) {
+            int32_t colOffset = (col + rect.mLeft / info.mHorizSubsampling) * info.mColInc;
+            if (addr[rowOffset + colOffset] != value) {
+                return false;
+            }
+        }
+    }
+    return true;
+}
+
+TEST_F(C2BufferTest, GraphicAllocationTest) {
+    constexpr uint32_t kWidth = 320;
+    constexpr uint32_t kHeight = 240;
+
+    allocateGraphic(kWidth, kHeight);
+
+    uint8_t *addr[C2PlaneLayout::MAX_NUM_PLANES];
+    C2Rect rect{ 0, 0, kWidth, kHeight };
+    C2PlaneLayout layout;
+    mapGraphic(rect, &layout, addr);
+    ASSERT_NE(nullptr, addr[C2PlaneLayout::Y]);
+    ASSERT_NE(nullptr, addr[C2PlaneLayout::U]);
+    ASSERT_NE(nullptr, addr[C2PlaneLayout::V]);
+
+    uint8_t *y = addr[C2PlaneLayout::Y];
+    C2PlaneInfo yInfo = layout.mPlanes[C2PlaneLayout::Y];
+    uint8_t *u = addr[C2PlaneLayout::U];
+    C2PlaneInfo uInfo = layout.mPlanes[C2PlaneLayout::U];
+    uint8_t *v = addr[C2PlaneLayout::V];
+    C2PlaneInfo vInfo = layout.mPlanes[C2PlaneLayout::V];
+
+    fillPlane(rect, yInfo, y, 0);
+    fillPlane(rect, uInfo, u, 0);
+    fillPlane(rect, vInfo, v, 0);
+    fillPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, yInfo, y, 0x12);
+    fillPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, uInfo, u, 0x34);
+    fillPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, vInfo, v, 0x56);
+
+    unmapGraphic();
+
+    mapGraphic(rect, &layout, addr);
+    ASSERT_NE(nullptr, addr[C2PlaneLayout::Y]);
+    ASSERT_NE(nullptr, addr[C2PlaneLayout::U]);
+    ASSERT_NE(nullptr, addr[C2PlaneLayout::V]);
+
+    y = addr[C2PlaneLayout::Y];
+    yInfo = layout.mPlanes[C2PlaneLayout::Y];
+    u = addr[C2PlaneLayout::U];
+    uInfo = layout.mPlanes[C2PlaneLayout::U];
+    v = addr[C2PlaneLayout::V];
+    vInfo = layout.mPlanes[C2PlaneLayout::V];
+
+    ASSERT_TRUE(verifyPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, yInfo, y, 0x12));
+    ASSERT_TRUE(verifyPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, uInfo, u, 0x34));
+    ASSERT_TRUE(verifyPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, vInfo, v, 0x56));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth, kHeight / 4 }, yInfo, y, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth, kHeight / 4 }, uInfo, u, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth, kHeight / 4 }, vInfo, v, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth / 4, kHeight }, yInfo, y, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth / 4, kHeight }, uInfo, u, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth / 4, kHeight }, vInfo, v, 0));
+}
+
+TEST_F(C2BufferTest, GraphicBlockAllocatorTest) {
+    constexpr uint32_t kWidth = 320;
+    constexpr uint32_t kHeight = 240;
+
+    std::shared_ptr<C2BlockAllocator> blockAllocator(makeGraphicBlockAllocator());
+
+    std::shared_ptr<C2GraphicBlock> block;
+    ASSERT_EQ(C2_OK, blockAllocator->allocateGraphicBlock(
+            kWidth,
+            kHeight,
+            HAL_PIXEL_FORMAT_YCBCR_420_888,
+            { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+            &block));
+    ASSERT_TRUE(block);
+
+    C2Acquirable<C2GraphicView> graphicViewHolder = block->map();
+    C2GraphicView graphicView = graphicViewHolder.get();
+    ASSERT_EQ(C2_OK, graphicView.error());
+    ASSERT_EQ(kWidth, graphicView.width());
+    ASSERT_EQ(kHeight, graphicView.height());
+
+    uint8_t *const *data = graphicView.data();
+    C2PlaneLayout layout = graphicView.layout();
+    ASSERT_NE(nullptr, data);
+
+    uint8_t *y = data[C2PlaneLayout::Y];
+    C2PlaneInfo yInfo = layout.mPlanes[C2PlaneLayout::Y];
+    uint8_t *u = data[C2PlaneLayout::U];
+    C2PlaneInfo uInfo = layout.mPlanes[C2PlaneLayout::U];
+    uint8_t *v = data[C2PlaneLayout::V];
+    C2PlaneInfo vInfo = layout.mPlanes[C2PlaneLayout::V];
+
+    fillPlane({ 0, 0, kWidth, kHeight }, yInfo, y, 0);
+    fillPlane({ 0, 0, kWidth, kHeight }, uInfo, u, 0);
+    fillPlane({ 0, 0, kWidth, kHeight }, vInfo, v, 0);
+    fillPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, yInfo, y, 0x12);
+    fillPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, uInfo, u, 0x34);
+    fillPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, vInfo, v, 0x56);
+
+    C2Fence fence;
+    C2ConstGraphicBlock constBlock = block->share(
+            { 0, 0, kWidth, kHeight }, fence);
+    block.reset();
+
+    C2Acquirable<const C2GraphicView> constViewHolder = constBlock.map();
+    const C2GraphicView constGraphicView = constViewHolder.get();
+    ASSERT_EQ(C2_OK, constGraphicView.error());
+    ASSERT_EQ(kWidth, constGraphicView.width());
+    ASSERT_EQ(kHeight, constGraphicView.height());
+
+    const uint8_t *const *constData = constGraphicView.data();
+    layout = graphicView.layout();
+    ASSERT_NE(nullptr, constData);
+
+    const uint8_t *cy = constData[C2PlaneLayout::Y];
+    yInfo = layout.mPlanes[C2PlaneLayout::Y];
+    const uint8_t *cu = constData[C2PlaneLayout::U];
+    uInfo = layout.mPlanes[C2PlaneLayout::U];
+    const uint8_t *cv = constData[C2PlaneLayout::V];
+    vInfo = layout.mPlanes[C2PlaneLayout::V];
+
+    ASSERT_TRUE(verifyPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, yInfo, cy, 0x12));
+    ASSERT_TRUE(verifyPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, uInfo, cu, 0x34));
+    ASSERT_TRUE(verifyPlane({ kWidth / 4, kHeight / 4, kWidth / 2, kHeight / 2 }, vInfo, cv, 0x56));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth, kHeight / 4 }, yInfo, cy, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth, kHeight / 4 }, uInfo, cu, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth, kHeight / 4 }, vInfo, cv, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth / 4, kHeight }, yInfo, cy, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth / 4, kHeight }, uInfo, cu, 0));
+    ASSERT_TRUE(verifyPlane({ 0, 0, kWidth / 4, kHeight }, vInfo, cv, 0));
+}
+
+class BufferData : public C2BufferData {
+public:
+    explicit BufferData(const std::list<C2ConstLinearBlock> &blocks) : C2BufferData(blocks) {}
+    explicit BufferData(const std::list<C2ConstGraphicBlock> &blocks) : C2BufferData(blocks) {}
+};
+
+class Buffer : public C2Buffer {
+public:
+    explicit Buffer(const std::list<C2ConstLinearBlock> &blocks) : C2Buffer(blocks) {}
+    explicit Buffer(const std::list<C2ConstGraphicBlock> &blocks) : C2Buffer(blocks) {}
+};
+
+TEST_F(C2BufferTest, BufferDataTest) {
+    std::shared_ptr<C2BlockAllocator> linearBlockAllocator(makeLinearBlockAllocator());
+    std::shared_ptr<C2BlockAllocator> graphicBlockAllocator(makeGraphicBlockAllocator());
+
+    constexpr uint32_t kWidth1 = 320;
+    constexpr uint32_t kHeight1 = 240;
+    constexpr C2Rect kCrop1(kWidth1, kHeight1);
+    constexpr uint32_t kWidth2 = 176;
+    constexpr uint32_t kHeight2 = 144;
+    constexpr C2Rect kCrop2(kWidth2, kHeight2);
+    constexpr size_t kCapacity1 = 1024u;
+    constexpr size_t kCapacity2 = 2048u;
+
+    std::shared_ptr<C2LinearBlock> linearBlock1;
+    std::shared_ptr<C2LinearBlock> linearBlock2;
+    ASSERT_EQ(C2_OK, linearBlockAllocator->allocateLinearBlock(
+            kCapacity1,
+            { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+            &linearBlock1));
+    ASSERT_EQ(C2_OK, linearBlockAllocator->allocateLinearBlock(
+            kCapacity2,
+            { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+            &linearBlock2));
+    std::shared_ptr<C2GraphicBlock> graphicBlock1;
+    std::shared_ptr<C2GraphicBlock> graphicBlock2;
+    ASSERT_EQ(C2_OK, graphicBlockAllocator->allocateGraphicBlock(
+            kWidth1,
+            kHeight1,
+            HAL_PIXEL_FORMAT_YCBCR_420_888,
+            { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+            &graphicBlock1));
+    ASSERT_EQ(C2_OK, graphicBlockAllocator->allocateGraphicBlock(
+            kWidth2,
+            kHeight2,
+            HAL_PIXEL_FORMAT_YCBCR_420_888,
+            { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+            &graphicBlock2));
+
+    std::shared_ptr<C2BufferData> data(new BufferData({ linearBlock1->share(0, kCapacity1, C2Fence()) }));
+    EXPECT_EQ(C2BufferData::LINEAR, data->type());
+    ASSERT_EQ(1u, data->linearBlocks().size());
+    EXPECT_EQ(linearBlock1->handle(), data->linearBlocks().front().handle());
+    EXPECT_TRUE(data->graphicBlocks().empty());
+
+    data.reset(new BufferData({
+        linearBlock1->share(0, kCapacity1, C2Fence()),
+        linearBlock2->share(0, kCapacity2, C2Fence()),
+    }));
+    EXPECT_EQ(C2BufferData::LINEAR_CHUNKS, data->type());
+    ASSERT_EQ(2u, data->linearBlocks().size());
+    EXPECT_EQ(linearBlock1->handle(), data->linearBlocks().front().handle());
+    EXPECT_EQ(linearBlock2->handle(), data->linearBlocks().back().handle());
+    EXPECT_TRUE(data->graphicBlocks().empty());
+
+    data.reset(new BufferData({ graphicBlock1->share(kCrop1, C2Fence()) }));
+    EXPECT_EQ(C2BufferData::GRAPHIC, data->type());
+    ASSERT_EQ(1u, data->graphicBlocks().size());
+    EXPECT_EQ(graphicBlock1->handle(), data->graphicBlocks().front().handle());
+    EXPECT_TRUE(data->linearBlocks().empty());
+
+    data.reset(new BufferData({
+        graphicBlock1->share(kCrop1, C2Fence()),
+        graphicBlock2->share(kCrop2, C2Fence()),
+    }));
+    EXPECT_EQ(C2BufferData::GRAPHIC_CHUNKS, data->type());
+    ASSERT_EQ(2u, data->graphicBlocks().size());
+    EXPECT_EQ(graphicBlock1->handle(), data->graphicBlocks().front().handle());
+    EXPECT_EQ(graphicBlock2->handle(), data->graphicBlocks().back().handle());
+    EXPECT_TRUE(data->linearBlocks().empty());
+}
+
+void DestroyCallback(const C2Buffer * /* buf */, void *arg) {
+    std::function<void(void)> *cb = (std::function<void(void)> *)arg;
+    (*cb)();
+}
+
+enum : uint32_t {
+    kParamIndexNumber1,
+    kParamIndexNumber2,
+};
+
+typedef C2GlobalParam<C2Info, C2Int32Value, kParamIndexNumber1> C2Number1Info;
+typedef C2GlobalParam<C2Info, C2Int32Value, kParamIndexNumber2> C2Number2Info;
+
+TEST_F(C2BufferTest, BufferTest) {
+    std::shared_ptr<C2BlockAllocator> alloc(makeLinearBlockAllocator());
+    constexpr size_t kCapacity = 1024u;
+    std::shared_ptr<C2LinearBlock> block;
+
+    ASSERT_EQ(C2_OK, alloc->allocateLinearBlock(
+            kCapacity,
+            { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+            &block));
+
+    std::atomic_bool destroyed(false);
+    std::function<void(void)> arg = [&destroyed](){ destroyed = true; };
+
+    std::shared_ptr<C2Buffer> buffer(new Buffer( { block->share(0, kCapacity, C2Fence()) }));
+    ASSERT_EQ(C2_OK, buffer->registerOnDestroyNotify(&DestroyCallback, &arg));
+    EXPECT_FALSE(destroyed);
+    ASSERT_EQ(C2_DUPLICATE, buffer->registerOnDestroyNotify(&DestroyCallback, &arg));
+    buffer.reset();
+    EXPECT_TRUE(destroyed);
+
+    buffer.reset(new Buffer( { block->share(0, kCapacity, C2Fence()) }));
+    destroyed = false;
+    ASSERT_EQ(C2_OK, buffer->registerOnDestroyNotify(&DestroyCallback, &arg));
+    EXPECT_FALSE(destroyed);
+    ASSERT_EQ(C2_OK, buffer->unregisterOnDestroyNotify(&DestroyCallback));
+    EXPECT_FALSE(destroyed);
+    ASSERT_EQ(C2_NOT_FOUND, buffer->unregisterOnDestroyNotify(&DestroyCallback));
+    buffer.reset();
+    EXPECT_FALSE(destroyed);
+
+    std::shared_ptr<C2Info> info1(new C2Number1Info(1));
+    std::shared_ptr<C2Info> info2(new C2Number2Info(2));
+    buffer.reset(new Buffer( { block->share(0, kCapacity, C2Fence()) }));
+    EXPECT_TRUE(buffer->infos().empty());
+    EXPECT_FALSE(buffer->hasInfo(info1->type()));
+    EXPECT_FALSE(buffer->hasInfo(info2->type()));
+
+    ASSERT_EQ(C2_OK, buffer->setInfo(info1));
+    EXPECT_EQ(1u, buffer->infos().size());
+    EXPECT_EQ(*info1, *buffer->infos().front());
+    EXPECT_TRUE(buffer->hasInfo(info1->type()));
+    EXPECT_FALSE(buffer->hasInfo(info2->type()));
+
+    ASSERT_EQ(C2_OK, buffer->setInfo(info2));
+    EXPECT_EQ(2u, buffer->infos().size());
+    EXPECT_TRUE(buffer->hasInfo(info1->type()));
+    EXPECT_TRUE(buffer->hasInfo(info2->type()));
+
+    std::shared_ptr<C2Info> removed = buffer->removeInfo(info1->type());
+    ASSERT_TRUE(removed);
+    EXPECT_EQ(*removed, *info1);
+    EXPECT_EQ(1u, buffer->infos().size());
+    EXPECT_EQ(*info2, *buffer->infos().front());
+    EXPECT_FALSE(buffer->hasInfo(info1->type()));
+    EXPECT_TRUE(buffer->hasInfo(info2->type()));
+
+    removed = buffer->removeInfo(info1->type());
+    ASSERT_FALSE(removed);
+    EXPECT_EQ(1u, buffer->infos().size());
+    EXPECT_FALSE(buffer->hasInfo(info1->type()));
+    EXPECT_TRUE(buffer->hasInfo(info2->type()));
+
+    std::shared_ptr<C2Info> info3(new C2Number2Info(3));
+    ASSERT_EQ(C2_OK, buffer->setInfo(info3));
+    EXPECT_EQ(1u, buffer->infos().size());
+    EXPECT_FALSE(buffer->hasInfo(info1->type()));
+    EXPECT_TRUE(buffer->hasInfo(info2->type()));
+
+    removed = buffer->removeInfo(info2->type());
+    ASSERT_TRUE(removed);
+    EXPECT_EQ(*info3, *removed);
+    EXPECT_TRUE(buffer->infos().empty());
+    EXPECT_FALSE(buffer->hasInfo(info1->type()));
+    EXPECT_FALSE(buffer->hasInfo(info2->type()));
+}
+
+} // namespace android
diff --git a/media/libstagefright/codec2/vndk/Android.bp b/media/libstagefright/codec2/vndk/Android.bp
new file mode 100644
index 0000000..916a6a9
--- /dev/null
+++ b/media/libstagefright/codec2/vndk/Android.bp
@@ -0,0 +1,33 @@
+cc_library_static {
+    name: "libstagefright_codec2_vndk",
+
+    srcs: ["C2Buffer.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/av/media/libstagefright/codec2/vndk/include",
+        "frameworks/native/include/media/hardware",
+    ],
+
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "android.hardware.graphics.mapper@2.0",
+        "libbinder",
+        "libcutils",
+        "libdl",
+        "libhardware",
+        "libhidlbase",
+        "libion",
+        "liblog",
+        "libmedia",
+        "libstagefright_foundation",
+        "libui",
+        "libutils",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-std=c++14",
+    ],
+}
diff --git a/media/libstagefright/codec2/vndk/C2Buffer.cpp b/media/libstagefright/codec2/vndk/C2Buffer.cpp
new file mode 100644
index 0000000..1a0b55c
--- /dev/null
+++ b/media/libstagefright/codec2/vndk/C2Buffer.cpp
@@ -0,0 +1,1441 @@
+/*
+ * Copyright (C) 2016 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 "C2Buffer"
+#include <utils/Log.h>
+
+#include <C2BufferPriv.h>
+
+#include <android/hardware/graphics/allocator/2.0/IAllocator.h>
+#include <android/hardware/graphics/mapper/2.0/IMapper.h>
+
+#include <ion/ion.h>
+#include <hardware/gralloc.h>
+#include <sys/mman.h>
+
+namespace android {
+
+using ::android::hardware::graphics::allocator::V2_0::IAllocator;
+using ::android::hardware::graphics::common::V1_0::BufferUsage;
+using ::android::hardware::graphics::common::V1_0::PixelFormat;
+using ::android::hardware::graphics::mapper::V2_0::BufferDescriptor;
+using ::android::hardware::graphics::mapper::V2_0::Error;
+using ::android::hardware::graphics::mapper::V2_0::IMapper;
+using ::android::hardware::graphics::mapper::V2_0::YCbCrLayout;
+using ::android::hardware::hidl_handle;
+using ::android::hardware::hidl_vec;
+
+// standard ERRNO mappings
+template<int N> constexpr C2Error _c2_errno2error_impl();
+template<> constexpr C2Error _c2_errno2error_impl<0>()       { return C2_OK; }
+template<> constexpr C2Error _c2_errno2error_impl<EINVAL>()  { return C2_BAD_VALUE; }
+template<> constexpr C2Error _c2_errno2error_impl<EACCES>()  { return C2_NO_PERMISSION; }
+template<> constexpr C2Error _c2_errno2error_impl<EPERM>()   { return C2_NO_PERMISSION; }
+template<> constexpr C2Error _c2_errno2error_impl<ENOMEM>()  { return C2_NO_MEMORY; }
+
+// map standard errno-s to the equivalent C2Error
+template<int... N> struct _c2_map_errno_impl;
+template<int E, int ... N> struct _c2_map_errno_impl<E, N...> {
+    static C2Error map(int result) {
+        if (result == E) {
+            return _c2_errno2error_impl<E>();
+        } else {
+            return _c2_map_errno_impl<N...>::map(result);
+        }
+    }
+};
+template<> struct _c2_map_errno_impl<> {
+    static C2Error map(int result) {
+        return result == 0 ? C2_OK : C2_CORRUPTED;
+    }
+};
+
+template<int... N>
+C2Error c2_map_errno(int result) {
+    return _c2_map_errno_impl<N...>::map(result);
+}
+
+namespace {
+
+// Inherit from the parent, share with the friend.
+
+class DummyCapacityAspect : public _C2LinearCapacityAspect {
+    using _C2LinearCapacityAspect::_C2LinearCapacityAspect;
+    friend class ::android::C2ReadView;
+    friend class ::android::C2ConstLinearBlock;
+};
+
+class C2DefaultReadView : public C2ReadView {
+    using C2ReadView::C2ReadView;
+    friend class ::android::C2ConstLinearBlock;
+};
+
+class C2DefaultWriteView : public C2WriteView {
+    using C2WriteView::C2WriteView;
+    friend class ::android::C2LinearBlock;
+};
+
+class C2AcquirableReadView : public C2Acquirable<C2ReadView> {
+    using C2Acquirable::C2Acquirable;
+    friend class ::android::C2ConstLinearBlock;
+};
+
+class C2AcquirableWriteView : public C2Acquirable<C2WriteView> {
+    using C2Acquirable::C2Acquirable;
+    friend class ::android::C2LinearBlock;
+};
+
+class C2DefaultConstLinearBlock : public C2ConstLinearBlock {
+    using C2ConstLinearBlock::C2ConstLinearBlock;
+    friend class ::android::C2LinearBlock;
+};
+
+class C2DefaultLinearBlock : public C2LinearBlock {
+    using C2LinearBlock::C2LinearBlock;
+    friend class ::android::C2DefaultBlockAllocator;
+};
+
+class C2DefaultGraphicView : public C2GraphicView {
+    using C2GraphicView::C2GraphicView;
+    friend class ::android::C2ConstGraphicBlock;
+    friend class ::android::C2GraphicBlock;
+};
+
+class C2AcquirableConstGraphicView : public C2Acquirable<const C2GraphicView> {
+    using C2Acquirable::C2Acquirable;
+    friend class ::android::C2ConstGraphicBlock;
+};
+
+class C2AcquirableGraphicView : public C2Acquirable<C2GraphicView> {
+    using C2Acquirable::C2Acquirable;
+    friend class ::android::C2GraphicBlock;
+};
+
+class C2DefaultConstGraphicBlock : public C2ConstGraphicBlock {
+    using C2ConstGraphicBlock::C2ConstGraphicBlock;
+    friend class ::android::C2GraphicBlock;
+};
+
+class C2DefaultGraphicBlock : public C2GraphicBlock {
+    using C2GraphicBlock::C2GraphicBlock;
+    friend class ::android::C2DefaultGraphicBlockAllocator;
+};
+
+class C2DefaultBufferData : public C2BufferData {
+    using C2BufferData::C2BufferData;
+    friend class ::android::C2Buffer;
+};
+
+}  // namespace
+
+/* ======================================= ION ALLOCATION ====================================== */
+
+/**
+ * ION handle
+ */
+struct C2HandleIon : public C2Handle {
+    C2HandleIon(int ionFd, ion_user_handle_t buffer) : C2Handle(cHeader),
+          mFds{ ionFd, buffer },
+          mInts{ kMagic } { }
+
+    static bool isValid(const C2Handle * const o);
+
+    int ionFd() const { return mFds.mIon; }
+    ion_user_handle_t buffer() const { return mFds.mBuffer; }
+
+    void setBuffer(ion_user_handle_t bufferFd) { mFds.mBuffer = bufferFd; }
+
+protected:
+    struct {
+        int mIon;
+        int mBuffer; // ion_user_handle_t
+    } mFds;
+    struct {
+        int mMagic;
+    } mInts;
+
+private:
+    typedef C2HandleIon _type;
+    enum {
+        kMagic = 'ion1',
+        numFds = sizeof(mFds) / sizeof(int),
+        numInts = sizeof(mInts) / sizeof(int),
+        version = sizeof(C2Handle) + sizeof(mFds) + sizeof(mInts)
+    };
+    //constexpr static C2Handle cHeader = { version, numFds, numInts, {} };
+    const static C2Handle cHeader;
+};
+
+const C2Handle C2HandleIon::cHeader = {
+    C2HandleIon::version,
+    C2HandleIon::numFds,
+    C2HandleIon::numInts,
+    {}
+};
+
+// static
+bool C2HandleIon::isValid(const C2Handle * const o) {
+    if (!o || memcmp(o, &cHeader, sizeof(cHeader))) {
+        return false;
+    }
+    const C2HandleIon *other = static_cast<const C2HandleIon*>(o);
+    return other->mInts.mMagic == kMagic;
+}
+
+// TODO: is the dup of an ion fd identical to ion_share?
+
+class C2AllocationIon : public C2LinearAllocation {
+public:
+    virtual C2Error map(
+        size_t offset, size_t size, C2MemoryUsage usage, int *fence,
+        void **addr /* nonnull */);
+    virtual C2Error unmap(void *addr, size_t size, int *fenceFd);
+    virtual bool isValid() const;
+    virtual ~C2AllocationIon();
+    virtual const C2Handle *handle() const;
+    virtual bool equals(const std::shared_ptr<C2LinearAllocation> &other) const;
+
+    // internal methods
+    C2AllocationIon(int ionFd, size_t size, size_t align, unsigned heapMask, unsigned flags);
+    C2AllocationIon(int ionFd, size_t size, int shareFd);
+    int dup() const;
+    C2Error status() const;
+
+protected:
+    class Impl;
+    Impl *mImpl;
+};
+
+class C2AllocationIon::Impl {
+public:
+    // NOTE: using constructor here instead of a factory method as we will need the
+    // error value and this simplifies the error handling by the wrapper.
+    Impl(int ionFd, size_t capacity, size_t align, unsigned heapMask, unsigned flags)
+        : mInit(C2_OK),
+          mHandle(ionFd, -1),
+          mMapFd(-1),
+          mCapacity(capacity) {
+        ion_user_handle_t buffer = -1;
+        int ret = ion_alloc(mHandle.ionFd(), mCapacity, align, heapMask, flags, &buffer);
+        if (ret == 0) {
+            mHandle.setBuffer(buffer);
+        } else {
+            mInit = c2_map_errno<ENOMEM, EACCES, EINVAL>(-ret);
+        }
+    }
+
+    Impl(int ionFd, size_t capacity, int shareFd)
+        : mHandle(ionFd, -1),
+          mMapFd(-1),
+          mCapacity(capacity) {
+        ion_user_handle_t buffer;
+        mInit = ion_import(mHandle.ionFd(), shareFd, &buffer);
+        if (mInit == 0) {
+            mHandle.setBuffer(buffer);
+        }
+        (void)mCapacity; // TODO
+    }
+
+    C2Error map(size_t offset, size_t size, C2MemoryUsage usage, int *fenceFd, void **addr) {
+        (void)fenceFd; // TODO: wait for fence
+        *addr = nullptr;
+        int prot = PROT_NONE;
+        int flags = MAP_PRIVATE;
+        if (usage.mConsumer & GRALLOC_USAGE_SW_READ_MASK) {
+            prot |= PROT_READ;
+        }
+        if (usage.mProducer & GRALLOC_USAGE_SW_WRITE_MASK) {
+            prot |= PROT_WRITE;
+            flags = MAP_SHARED;
+        }
+
+        size_t alignmentBytes = offset % PAGE_SIZE;
+        size_t mapOffset = offset - alignmentBytes;
+        size_t mapSize = size + alignmentBytes;
+
+        C2Error err = C2_OK;
+        if (mMapFd == -1) {
+            int ret = ion_map(mHandle.ionFd(), mHandle.buffer(), mapSize, prot,
+                              flags, mapOffset, (unsigned char**)&mMapAddr, &mMapFd);
+            if (ret) {
+                mMapFd = -1;
+                *addr = nullptr;
+                err = c2_map_errno<EINVAL>(-ret);
+            } else {
+                *addr = (uint8_t *)mMapAddr + alignmentBytes;
+                mMapAlignmentBytes = alignmentBytes;
+                mMapSize = mapSize;
+            }
+        } else {
+            mMapAddr = mmap(nullptr, mapSize, prot, flags, mMapFd, mapOffset);
+            if (mMapAddr == MAP_FAILED) {
+                mMapAddr = *addr = nullptr;
+                err = c2_map_errno<EINVAL>(errno);
+            } else {
+                *addr = (uint8_t *)mMapAddr + alignmentBytes;
+                mMapAlignmentBytes = alignmentBytes;
+                mMapSize = mapSize;
+            }
+        }
+        return err;
+    }
+
+    C2Error unmap(void *addr, size_t size, int *fenceFd) {
+        if (addr != (uint8_t *)mMapAddr + mMapAlignmentBytes ||
+                size + mMapAlignmentBytes != mMapSize) {
+            return C2_BAD_VALUE;
+        }
+        int err = munmap(mMapAddr, mMapSize);
+        if (err != 0) {
+            return c2_map_errno<EINVAL>(errno);
+        }
+        if (fenceFd) {
+            *fenceFd = -1;
+        }
+        return C2_OK;
+    }
+
+    ~Impl() {
+        if (mMapFd != -1) {
+            close(mMapFd);
+            mMapFd = -1;
+        }
+
+        (void)ion_free(mHandle.ionFd(), mHandle.buffer());
+    }
+
+    C2Error status() const {
+        return mInit;
+    }
+
+    const C2Handle * handle() const {
+        return &mHandle;
+    }
+
+    int dup() const {
+        int fd = -1;
+        if (mInit != 0 || ion_share(mHandle.ionFd(), mHandle.buffer(), &fd) != 0) {
+            fd = -1;
+        }
+        return fd;
+    }
+
+private:
+    C2Error mInit;
+    C2HandleIon mHandle;
+    int mMapFd; // only one for now
+    void *mMapAddr;
+    size_t mMapAlignmentBytes;
+    size_t mMapSize;
+    size_t mCapacity;
+};
+
+C2Error C2AllocationIon::map(
+    size_t offset, size_t size, C2MemoryUsage usage, int *fenceFd, void **addr) {
+    return mImpl->map(offset, size, usage, fenceFd, addr);
+}
+
+C2Error C2AllocationIon::unmap(void *addr, size_t size, int *fenceFd) {
+    return mImpl->unmap(addr, size, fenceFd);
+}
+
+bool C2AllocationIon::isValid() const {
+    return mImpl->status() == C2_OK;
+}
+
+C2Error C2AllocationIon::status() const {
+    return mImpl->status();
+}
+
+bool C2AllocationIon::equals(const std::shared_ptr<C2LinearAllocation> &other) const {
+    return other != nullptr &&
+        other->handle(); // TODO
+}
+
+const C2Handle *C2AllocationIon::handle() const {
+    return mImpl->handle();
+}
+
+C2AllocationIon::~C2AllocationIon() {
+    delete mImpl;
+}
+
+C2AllocationIon::C2AllocationIon(int ionFd, size_t size, size_t align, unsigned heapMask, unsigned flags)
+    : C2LinearAllocation(size),
+      mImpl(new Impl(ionFd, size, align, heapMask, flags)) { }
+
+C2AllocationIon::C2AllocationIon(int ionFd, size_t size, int shareFd)
+    : C2LinearAllocation(size),
+      mImpl(new Impl(ionFd, size, shareFd)) { }
+
+int C2AllocationIon::dup() const {
+    return mImpl->dup();
+}
+
+/* ======================================= ION ALLOCATOR ====================================== */
+
+C2AllocatorIon::C2AllocatorIon() : mInit(C2_OK), mIonFd(ion_open()) {
+    if (mIonFd < 0) {
+        switch (errno) {
+        case ENOENT:    mInit = C2_UNSUPPORTED; break;
+        default:        mInit = c2_map_errno<EACCES>(errno); break;
+        }
+    }
+}
+
+C2AllocatorIon::~C2AllocatorIon() {
+    if (mInit == C2_OK) {
+        ion_close(mIonFd);
+    }
+}
+
+/**
+ * Allocates a 1D allocation of given |capacity| and |usage|. If successful, the allocation is
+ * stored in |allocation|. Otherwise, |allocation| is set to 'nullptr'.
+ *
+ * \param capacity        the size of requested allocation (the allocation could be slightly
+ *                      larger, e.g. to account for any system-required alignment)
+ * \param usage           the memory usage info for the requested allocation. \note that the
+ *                      returned allocation may be later used/mapped with different usage.
+ *                      The allocator should layout the buffer to be optimized for this usage,
+ *                      but must support any usage. One exception: protected buffers can
+ *                      only be used in a protected scenario.
+ * \param allocation      pointer to where the allocation shall be stored on success. nullptr
+ *                      will be stored here on failure
+ *
+ * \retval C2_OK        the allocation was successful
+ * \retval C2_NO_MEMORY not enough memory to complete the allocation
+ * \retval C2_TIMED_OUT the allocation timed out
+ * \retval C2_NO_PERMISSION     no permission to complete the allocation
+ * \retval C2_BAD_VALUE capacity or usage are not supported (invalid) (caller error)
+ * \retval C2_UNSUPPORTED       this allocator does not support 1D allocations
+ * \retval C2_CORRUPTED some unknown, unrecoverable error occured during allocation (unexpected)
+ */
+C2Error C2AllocatorIon::allocateLinearBuffer(
+        uint32_t capacity, C2MemoryUsage usage, std::shared_ptr<C2LinearAllocation> *allocation) {
+    *allocation = nullptr;
+    if (mInit != C2_OK) {
+        return C2_UNSUPPORTED;
+    }
+
+    // get align, heapMask and flags
+    //size_t align = 1;
+    size_t align = 0;
+    unsigned heapMask = ~0;
+    unsigned flags = 0;
+    //TODO
+    (void) usage;
+#if 0
+    int err = mUsageMapper(usage, capacity, &align, &heapMask, &flags);
+    if (err < 0) {
+        return c2_map_errno<EINVAL, ENOMEM, EACCES>(-err);
+    }
+#endif
+
+    std::shared_ptr<C2AllocationIon> alloc
+        = std::make_shared<C2AllocationIon>(mIonFd, capacity, align, heapMask, flags);
+    C2Error ret = alloc->status();
+    if (ret == C2_OK) {
+        *allocation = alloc;
+    }
+    return ret;
+}
+
+/**
+ * (Re)creates a 1D allocation from a native |handle|. If successful, the allocation is stored
+ * in |allocation|. Otherwise, |allocation| is set to 'nullptr'.
+ *
+ * \param handle      the handle for the existing allocation
+ * \param allocation  pointer to where the allocation shall be stored on success. nullptr
+ *                  will be stored here on failure
+ *
+ * \retval C2_OK        the allocation was recreated successfully
+ * \retval C2_NO_MEMORY not enough memory to recreate the allocation
+ * \retval C2_TIMED_OUT the recreation timed out (unexpected)
+ * \retval C2_NO_PERMISSION     no permission to recreate the allocation
+ * \retval C2_BAD_VALUE invalid handle (caller error)
+ * \retval C2_UNSUPPORTED       this allocator does not support 1D allocations
+ * \retval C2_CORRUPTED some unknown, unrecoverable error occured during allocation (unexpected)
+ */
+C2Error C2AllocatorIon::recreateLinearBuffer(
+        const C2Handle *handle, std::shared_ptr<C2LinearAllocation> *allocation) {
+    *allocation = nullptr;
+    if (mInit != C2_OK) {
+        return C2_UNSUPPORTED;
+    }
+
+    if (!C2HandleIon::isValid(handle)) {
+        return C2_BAD_VALUE;
+    }
+
+    // TODO: get capacity and validate it
+    const C2HandleIon *h = static_cast<const C2HandleIon*>(handle);
+    std::shared_ptr<C2AllocationIon> alloc
+        = std::make_shared<C2AllocationIon>(mIonFd, 0 /* capacity */, h->buffer());
+    C2Error ret = alloc->status();
+    if (ret == C2_OK) {
+        *allocation = alloc;
+    }
+    return ret;
+}
+
+/* ========================================== 1D BLOCK ========================================= */
+
+class C2Block1D::Impl {
+public:
+    const C2Handle *handle() const {
+        return mAllocation->handle();
+    }
+
+    Impl(std::shared_ptr<C2LinearAllocation> alloc)
+        : mAllocation(alloc) {}
+
+private:
+    std::shared_ptr<C2LinearAllocation> mAllocation;
+};
+
+const C2Handle *C2Block1D::handle() const {
+    return mImpl->handle();
+};
+
+C2Block1D::C2Block1D(std::shared_ptr<C2LinearAllocation> alloc)
+    : _C2LinearRangeAspect(alloc.get()), mImpl(new Impl(alloc)) {
+}
+
+C2Block1D::C2Block1D(std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size)
+    : _C2LinearRangeAspect(alloc.get(), offset, size), mImpl(new Impl(alloc)) {
+}
+
+class C2ReadView::Impl {
+public:
+    explicit Impl(const uint8_t *data)
+        : mData(data), mError(C2_OK) {}
+
+    explicit Impl(C2Error error)
+        : mData(nullptr), mError(error) {}
+
+    const uint8_t *data() const {
+        return mData;
+    }
+
+    C2Error error() const {
+        return mError;
+    }
+
+private:
+    const uint8_t *mData;
+    C2Error mError;
+};
+
+C2ReadView::C2ReadView(const _C2LinearCapacityAspect *parent, const uint8_t *data)
+    : _C2LinearCapacityAspect(parent), mImpl(std::make_shared<Impl>(data)) {}
+
+C2ReadView::C2ReadView(C2Error error)
+    : _C2LinearCapacityAspect(0u), mImpl(std::make_shared<Impl>(error)) {}
+
+const uint8_t *C2ReadView::data() const {
+    return mImpl->data();
+}
+
+C2ReadView C2ReadView::subView(size_t offset, size_t size) const {
+    if (offset > capacity()) {
+        offset = capacity();
+    }
+    if (size > capacity() - offset) {
+        size = capacity() - offset;
+    }
+    // TRICKY: newCapacity will just be used to grab the size.
+    DummyCapacityAspect newCapacity((uint32_t)size);
+    return C2ReadView(&newCapacity, data() + offset);
+}
+
+C2Error C2ReadView::error() {
+    return mImpl->error();
+}
+
+class C2WriteView::Impl {
+public:
+    explicit Impl(uint8_t *base)
+        : mBase(base), mError(C2_OK) {}
+
+    explicit Impl(C2Error error)
+        : mBase(nullptr), mError(error) {}
+
+    uint8_t *base() const {
+        return mBase;
+    }
+
+    C2Error error() const {
+        return mError;
+    }
+
+private:
+    uint8_t *mBase;
+    C2Error mError;
+};
+
+C2WriteView::C2WriteView(const _C2LinearRangeAspect *parent, uint8_t *base)
+    : _C2EditableLinearRange(parent), mImpl(std::make_shared<Impl>(base)) {}
+
+C2WriteView::C2WriteView(C2Error error)
+    : _C2EditableLinearRange(nullptr), mImpl(std::make_shared<Impl>(error)) {}
+
+uint8_t *C2WriteView::base() { return mImpl->base(); }
+
+uint8_t *C2WriteView::data() { return mImpl->base() + offset(); }
+
+C2Error C2WriteView::error() { return mImpl->error(); }
+
+class C2ConstLinearBlock::Impl {
+public:
+    explicit Impl(std::shared_ptr<C2LinearAllocation> alloc)
+        : mAllocation(alloc), mBase(nullptr), mSize(0u), mError(C2_CORRUPTED) {}
+
+    ~Impl() {
+        if (mBase != nullptr) {
+            // TODO: fence
+            C2Error err = mAllocation->unmap(mBase, mSize, nullptr);
+            if (err != C2_OK) {
+                // TODO: Log?
+            }
+        }
+    }
+
+    C2ConstLinearBlock subBlock(size_t offset, size_t size) const {
+        return C2ConstLinearBlock(mAllocation, offset, size);
+    }
+
+    void map(size_t offset, size_t size) {
+        if (mBase == nullptr) {
+            void *base = nullptr;
+            mError = mAllocation->map(
+                    offset, size, { C2MemoryUsage::kSoftwareRead, 0 }, nullptr, &base);
+            // TODO: fence
+            if (mError == C2_OK) {
+                mBase = (uint8_t *)base;
+                mSize = size;
+            }
+        }
+    }
+
+    const uint8_t *base() const { return mBase; }
+
+    C2Error error() const { return mError; }
+
+private:
+    std::shared_ptr<C2LinearAllocation> mAllocation;
+    uint8_t *mBase;
+    size_t mSize;
+    C2Error mError;
+};
+
+C2ConstLinearBlock::C2ConstLinearBlock(std::shared_ptr<C2LinearAllocation> alloc)
+    : C2Block1D(alloc), mImpl(std::make_shared<Impl>(alloc)) {}
+
+C2ConstLinearBlock::C2ConstLinearBlock(
+        std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size)
+    : C2Block1D(alloc, offset, size), mImpl(std::make_shared<Impl>(alloc)) {}
+
+C2Acquirable<C2ReadView> C2ConstLinearBlock::map() const {
+    mImpl->map(offset(), size());
+    if (mImpl->base() == nullptr) {
+        C2DefaultReadView view(mImpl->error());
+        return C2AcquirableReadView(mImpl->error(), mFence, view);
+    }
+    DummyCapacityAspect newCapacity(size());
+    C2DefaultReadView view(&newCapacity, mImpl->base());
+    return C2AcquirableReadView(mImpl->error(), mFence, view);
+}
+
+C2ConstLinearBlock C2ConstLinearBlock::subBlock(size_t offset, size_t size) const {
+    return mImpl->subBlock(offset, size);
+}
+
+class C2LinearBlock::Impl {
+public:
+    Impl(std::shared_ptr<C2LinearAllocation> alloc)
+        : mAllocation(alloc), mBase(nullptr), mSize(0u), mError(C2_CORRUPTED) {}
+
+    ~Impl() {
+        if (mBase != nullptr) {
+            // TODO: fence
+            C2Error err = mAllocation->unmap(mBase, mSize, nullptr);
+            if (err != C2_OK) {
+                // TODO: Log?
+            }
+        }
+    }
+
+    void map(size_t capacity) {
+        if (mBase == nullptr) {
+            void *base = nullptr;
+            // TODO: fence
+            mError = mAllocation->map(
+                    0u,
+                    capacity,
+                    { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                    nullptr,
+                    &base);
+            if (mError == C2_OK) {
+                mBase = (uint8_t *)base;
+                mSize = capacity;
+            }
+        }
+    }
+
+    C2ConstLinearBlock share(size_t offset, size_t size, C2Fence &fence) {
+        // TODO
+        (void) fence;
+        return C2DefaultConstLinearBlock(mAllocation, offset, size);
+    }
+
+    uint8_t *base() const { return mBase; }
+
+    C2Error error() const { return mError; }
+
+    C2Fence fence() const { return mFence; }
+
+private:
+    std::shared_ptr<C2LinearAllocation> mAllocation;
+    uint8_t *mBase;
+    size_t mSize;
+    C2Error mError;
+    C2Fence mFence;
+};
+
+C2LinearBlock::C2LinearBlock(std::shared_ptr<C2LinearAllocation> alloc)
+    : C2Block1D(alloc),
+      mImpl(new Impl(alloc)) {}
+
+C2LinearBlock::C2LinearBlock(std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size)
+    : C2Block1D(alloc, offset, size),
+      mImpl(new Impl(alloc)) {}
+
+C2Acquirable<C2WriteView> C2LinearBlock::map() {
+    mImpl->map(capacity());
+    if (mImpl->base() == nullptr) {
+        C2DefaultWriteView view(mImpl->error());
+        return C2AcquirableWriteView(mImpl->error(), mImpl->fence(), view);
+    }
+    C2DefaultWriteView view(this, mImpl->base());
+    view.setOffset_be(offset());
+    view.setSize_be(size());
+    return C2AcquirableWriteView(mImpl->error(), mImpl->fence(), view);
+}
+
+C2ConstLinearBlock C2LinearBlock::share(size_t offset, size_t size, C2Fence fence) {
+    return mImpl->share(offset, size, fence);
+}
+
+C2DefaultBlockAllocator::C2DefaultBlockAllocator(
+        const std::shared_ptr<C2Allocator> &allocator)
+  : mAllocator(allocator) {}
+
+C2Error C2DefaultBlockAllocator::allocateLinearBlock(
+        uint32_t capacity,
+        C2MemoryUsage usage,
+        std::shared_ptr<C2LinearBlock> *block /* nonnull */) {
+    block->reset();
+
+    std::shared_ptr<C2LinearAllocation> alloc;
+    C2Error err = mAllocator->allocateLinearBuffer(capacity, usage, &alloc);
+    if (err != C2_OK) {
+        return err;
+    }
+
+    block->reset(new C2DefaultLinearBlock(alloc));
+
+    return C2_OK;
+}
+
+/* ===================================== GRALLOC ALLOCATION ==================================== */
+
+static C2Error maperr2error(Error maperr) {
+    switch (maperr) {
+        case Error::NONE:           return C2_OK;
+        case Error::BAD_DESCRIPTOR: return C2_BAD_VALUE;
+        case Error::BAD_BUFFER:     return C2_BAD_VALUE;
+        case Error::BAD_VALUE:      return C2_BAD_VALUE;
+        case Error::NO_RESOURCES:   return C2_NO_MEMORY;
+        case Error::UNSUPPORTED:    return C2_UNSUPPORTED;
+    }
+    return C2_CORRUPTED;
+}
+
+class C2AllocationGralloc : public C2GraphicAllocation {
+public:
+    virtual ~C2AllocationGralloc();
+
+    virtual C2Error map(
+            C2Rect rect, C2MemoryUsage usage, int *fenceFd,
+            C2PlaneLayout *layout /* nonnull */, uint8_t **addr /* nonnull */) override;
+    virtual C2Error unmap(C2Fence *fenceFd /* nullable */) override;
+    virtual bool isValid() const override { return true; }
+    virtual const C2Handle *handle() const override { return mHandle; }
+    virtual bool equals(const std::shared_ptr<const C2GraphicAllocation> &other) const override;
+
+    // internal methods
+    // |handle| will be moved.
+    C2AllocationGralloc(
+              const IMapper::BufferDescriptorInfo &info,
+              const sp<IMapper> &mapper,
+              hidl_handle &handle);
+    int dup() const;
+    C2Error status() const;
+
+private:
+    const IMapper::BufferDescriptorInfo mInfo;
+    const sp<IMapper> mMapper;
+    const hidl_handle mHandle;
+    buffer_handle_t mBuffer;
+    bool mLocked;
+};
+
+C2AllocationGralloc::C2AllocationGralloc(
+          const IMapper::BufferDescriptorInfo &info,
+          const sp<IMapper> &mapper,
+          hidl_handle &handle)
+    : C2GraphicAllocation(info.width, info.height),
+      mInfo(info),
+      mMapper(mapper),
+      mHandle(std::move(handle)),
+      mBuffer(nullptr),
+      mLocked(false) {}
+
+C2AllocationGralloc::~C2AllocationGralloc() {
+    if (!mBuffer) {
+        return;
+    }
+    if (mLocked) {
+        unmap(nullptr);
+    }
+    mMapper->freeBuffer(const_cast<native_handle_t *>(mBuffer));
+}
+
+C2Error C2AllocationGralloc::map(
+        C2Rect rect, C2MemoryUsage usage, int *fenceFd,
+        C2PlaneLayout *layout /* nonnull */, uint8_t **addr /* nonnull */) {
+    // TODO
+    (void) fenceFd;
+    (void) usage;
+
+    if (mBuffer && mLocked) {
+        return C2_DUPLICATE;
+    }
+    if (!layout || !addr) {
+        return C2_BAD_VALUE;
+    }
+
+    C2Error err = C2_OK;
+    if (!mBuffer) {
+        mMapper->importBuffer(
+                mHandle, [&err, this](const auto &maperr, const auto &buffer) {
+                    err = maperr2error(maperr);
+                    if (err == C2_OK) {
+                        mBuffer = static_cast<buffer_handle_t>(buffer);
+                    }
+                });
+        if (err != C2_OK) {
+            return err;
+        }
+    }
+
+    if (mInfo.format == PixelFormat::YCBCR_420_888 || mInfo.format == PixelFormat::YV12) {
+        YCbCrLayout ycbcrLayout;
+        mMapper->lockYCbCr(
+                const_cast<native_handle_t *>(mBuffer),
+                BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN,
+                { (int32_t)rect.mLeft, (int32_t)rect.mTop, (int32_t)rect.mWidth, (int32_t)rect.mHeight },
+                // TODO: fence
+                hidl_handle(),
+                [&err, &ycbcrLayout](const auto &maperr, const auto &mapLayout) {
+                    err = maperr2error(maperr);
+                    if (err == C2_OK) {
+                        ycbcrLayout = mapLayout;
+                    }
+                });
+        if (err != C2_OK) {
+            return err;
+        }
+        addr[C2PlaneLayout::Y] = (uint8_t *)ycbcrLayout.y;
+        addr[C2PlaneLayout::U] = (uint8_t *)ycbcrLayout.cb;
+        addr[C2PlaneLayout::V] = (uint8_t *)ycbcrLayout.cr;
+        layout->mType = C2PlaneLayout::MEDIA_IMAGE_TYPE_YUV;
+        layout->mNumPlanes = 3;
+        layout->mPlanes[C2PlaneLayout::Y] = {
+            C2PlaneInfo::Y,                 // mChannel
+            1,                              // mColInc
+            (int32_t)ycbcrLayout.yStride,   // mRowInc
+            1,                              // mHorizSubsampling
+            1,                              // mVertSubsampling
+            8,                              // mBitDepth
+            8,                              // mAllocatedDepth
+        };
+        layout->mPlanes[C2PlaneLayout::U] = {
+            C2PlaneInfo::Cb,                  // mChannel
+            (int32_t)ycbcrLayout.chromaStep,  // mColInc
+            (int32_t)ycbcrLayout.cStride,     // mRowInc
+            2,                                // mHorizSubsampling
+            2,                                // mVertSubsampling
+            8,                                // mBitDepth
+            8,                                // mAllocatedDepth
+        };
+        layout->mPlanes[C2PlaneLayout::V] = {
+            C2PlaneInfo::Cr,                  // mChannel
+            (int32_t)ycbcrLayout.chromaStep,  // mColInc
+            (int32_t)ycbcrLayout.cStride,     // mRowInc
+            2,                                // mHorizSubsampling
+            2,                                // mVertSubsampling
+            8,                                // mBitDepth
+            8,                                // mAllocatedDepth
+        };
+    } else {
+        void *pointer = nullptr;
+        mMapper->lock(
+                const_cast<native_handle_t *>(mBuffer),
+                BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN,
+                { (int32_t)rect.mLeft, (int32_t)rect.mTop, (int32_t)rect.mWidth, (int32_t)rect.mHeight },
+                // TODO: fence
+                hidl_handle(),
+                [&err, &pointer](const auto &maperr, const auto &mapPointer) {
+                    err = maperr2error(maperr);
+                    if (err == C2_OK) {
+                        pointer = mapPointer;
+                    }
+                });
+        if (err != C2_OK) {
+            return err;
+        }
+        // TODO
+        return C2_UNSUPPORTED;
+    }
+    mLocked = true;
+
+    return C2_OK;
+}
+
+C2Error C2AllocationGralloc::unmap(C2Fence *fenceFd /* nullable */) {
+    // TODO: fence
+    C2Error err = C2_OK;
+    mMapper->unlock(
+            const_cast<native_handle_t *>(mBuffer),
+            [&err, &fenceFd](const auto &maperr, const auto &releaseFence) {
+                // TODO
+                (void) fenceFd;
+                (void) releaseFence;
+                err = maperr2error(maperr);
+                if (err == C2_OK) {
+                    // TODO: fence
+                }
+            });
+    if (err == C2_OK) {
+        mLocked = false;
+    }
+    return err;
+}
+
+bool C2AllocationGralloc::equals(const std::shared_ptr<const C2GraphicAllocation> &other) const {
+    return other && other->handle() == handle();
+}
+
+/* ===================================== GRALLOC ALLOCATOR ==================================== */
+
+class C2AllocatorGralloc::Impl {
+public:
+    Impl();
+
+    C2Error allocateGraphicBuffer(
+            uint32_t width, uint32_t height, uint32_t format, const C2MemoryUsage &usage,
+            std::shared_ptr<C2GraphicAllocation> *allocation);
+
+    C2Error recreateGraphicBuffer(
+            const C2Handle *handle,
+            std::shared_ptr<C2GraphicAllocation> *allocation);
+
+    C2Error status() const { return mInit; }
+
+private:
+    C2Error mInit;
+    sp<IAllocator> mAllocator;
+    sp<IMapper> mMapper;
+};
+
+C2AllocatorGralloc::Impl::Impl() : mInit(C2_OK) {
+    mAllocator = IAllocator::getService();
+    mMapper = IMapper::getService();
+    if (mAllocator == nullptr || mMapper == nullptr) {
+        mInit = C2_CORRUPTED;
+    }
+}
+
+C2Error C2AllocatorGralloc::Impl::allocateGraphicBuffer(
+        uint32_t width, uint32_t height, uint32_t format, const C2MemoryUsage &usage,
+        std::shared_ptr<C2GraphicAllocation> *allocation) {
+    // TODO: buffer usage should be determined according to |usage|
+    (void) usage;
+
+    IMapper::BufferDescriptorInfo info = {
+        width,
+        height,
+        1u,  // layerCount
+        (PixelFormat)format,
+        BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN,
+    };
+    C2Error err = C2_OK;
+    BufferDescriptor desc;
+    mMapper->createDescriptor(
+            info, [&err, &desc](const auto &maperr, const auto &descriptor) {
+                err = maperr2error(maperr);
+                if (err == C2_OK) {
+                    desc = descriptor;
+                }
+            });
+    if (err != C2_OK) {
+        return err;
+    }
+
+    // IAllocator shares IMapper error codes.
+    hidl_handle buffer;
+    mAllocator->allocate(
+            desc,
+            1u,
+            [&err, &buffer](const auto &maperr, const auto &stride, auto &buffers) {
+                (void) stride;
+                err = maperr2error(maperr);
+                if (err != C2_OK) {
+                    return;
+                }
+                if (buffers.size() != 1u) {
+                    err = C2_CORRUPTED;
+                    return;
+                }
+                buffer = std::move(buffers[0]);
+            });
+    if (err != C2_OK) {
+        return err;
+    }
+
+    allocation->reset(new C2AllocationGralloc(info, mMapper, buffer));
+    return C2_OK;
+}
+
+C2Error C2AllocatorGralloc::Impl::recreateGraphicBuffer(
+        const C2Handle *handle,
+        std::shared_ptr<C2GraphicAllocation> *allocation) {
+    (void) handle;
+
+    // TODO: need to figure out BufferDescriptorInfo from the handle.
+    allocation->reset();
+    return C2_UNSUPPORTED;
+}
+
+C2AllocatorGralloc::C2AllocatorGralloc() : mImpl(new Impl) {}
+C2AllocatorGralloc::~C2AllocatorGralloc() { delete mImpl; }
+
+C2Error C2AllocatorGralloc::allocateGraphicBuffer(
+        uint32_t width, uint32_t height, uint32_t format, C2MemoryUsage usage,
+        std::shared_ptr<C2GraphicAllocation> *allocation) {
+    return mImpl->allocateGraphicBuffer(width, height, format, usage, allocation);
+}
+
+C2Error C2AllocatorGralloc::recreateGraphicBuffer(
+        const C2Handle *handle,
+        std::shared_ptr<C2GraphicAllocation> *allocation) {
+    return mImpl->recreateGraphicBuffer(handle, allocation);
+}
+
+C2Error C2AllocatorGralloc::status() const { return mImpl->status(); }
+
+/* ========================================== 2D BLOCK ========================================= */
+
+class C2Block2D::Impl {
+public:
+    const C2Handle *handle() const {
+        return mAllocation->handle();
+    }
+
+    Impl(const std::shared_ptr<C2GraphicAllocation> &alloc)
+        : mAllocation(alloc) {}
+
+private:
+    std::shared_ptr<C2GraphicAllocation> mAllocation;
+};
+
+C2Block2D::C2Block2D(const std::shared_ptr<C2GraphicAllocation> &alloc)
+    : _C2PlanarSection(alloc.get()), mImpl(new Impl(alloc)) {}
+
+const C2Handle *C2Block2D::handle() const {
+    return mImpl->handle();
+}
+
+class C2GraphicView::Impl {
+public:
+    Impl(uint8_t *const *data, const C2PlaneLayout &layout)
+        : mData(data), mLayout(layout), mError(C2_OK) {}
+    explicit Impl(C2Error error) : mData(nullptr), mError(error) {}
+
+    uint8_t *const *data() const { return mData; }
+    const C2PlaneLayout &layout() const { return mLayout; }
+    C2Error error() const { return mError; }
+
+private:
+    uint8_t *const *mData;
+    C2PlaneLayout mLayout;
+    C2Error mError;
+};
+
+C2GraphicView::C2GraphicView(
+        const _C2PlanarCapacityAspect *parent,
+        uint8_t *const *data,
+        const C2PlaneLayout& layout)
+    : _C2PlanarSection(parent), mImpl(new Impl(data, layout)) {}
+
+C2GraphicView::C2GraphicView(C2Error error)
+    : _C2PlanarSection(nullptr), mImpl(new Impl(error)) {}
+
+const uint8_t *const *C2GraphicView::data() const {
+    return mImpl->data();
+}
+
+uint8_t *const *C2GraphicView::data() {
+    return mImpl->data();
+}
+
+const C2PlaneLayout C2GraphicView::layout() const {
+    return mImpl->layout();
+}
+
+const C2GraphicView C2GraphicView::subView(const C2Rect &rect) const {
+    C2GraphicView view(this, mImpl->data(), mImpl->layout());
+    view.setCrop_be(rect);
+    return view;
+}
+
+C2GraphicView C2GraphicView::subView(const C2Rect &rect) {
+    C2GraphicView view(this, mImpl->data(), mImpl->layout());
+    view.setCrop_be(rect);
+    return view;
+}
+
+C2Error C2GraphicView::error() const {
+    return mImpl->error();
+}
+
+class C2ConstGraphicBlock::Impl {
+public:
+    explicit Impl(const std::shared_ptr<C2GraphicAllocation> &alloc)
+        : mAllocation(alloc), mData{ nullptr } {}
+
+    ~Impl() {
+        if (mData[0] != nullptr) {
+            // TODO: fence
+            mAllocation->unmap(nullptr);
+        }
+    }
+
+    C2Error map(C2Rect rect) {
+        if (mData[0] != nullptr) {
+            // Already mapped.
+            return C2_OK;
+        }
+        C2Error err = mAllocation->map(
+                rect,
+                { C2MemoryUsage::kSoftwareRead, 0 },
+                nullptr,
+                &mLayout,
+                mData);
+        if (err != C2_OK) {
+            memset(mData, 0, sizeof(mData));
+        }
+        return err;
+    }
+
+    C2ConstGraphicBlock subBlock(const C2Rect &rect, C2Fence fence) const {
+        C2ConstGraphicBlock block(mAllocation, fence);
+        block.setCrop_be(rect);
+        return block;
+    }
+
+    uint8_t *const *data() const {
+        return mData[0] == nullptr ? nullptr : &mData[0];
+    }
+
+    const C2PlaneLayout &layout() const { return mLayout; }
+
+private:
+    std::shared_ptr<C2GraphicAllocation> mAllocation;
+    C2PlaneLayout mLayout;
+    uint8_t *mData[C2PlaneLayout::MAX_NUM_PLANES];
+};
+
+C2ConstGraphicBlock::C2ConstGraphicBlock(
+        const std::shared_ptr<C2GraphicAllocation> &alloc, C2Fence fence)
+    : C2Block2D(alloc), mImpl(new Impl(alloc)), mFence(fence) {}
+
+C2Acquirable<const C2GraphicView> C2ConstGraphicBlock::map() const {
+    C2Error err = mImpl->map(crop());
+    if (err != C2_OK) {
+        C2DefaultGraphicView view(err);
+        return C2AcquirableConstGraphicView(err, mFence, view);
+    }
+    C2DefaultGraphicView view(this, mImpl->data(), mImpl->layout());
+    return C2AcquirableConstGraphicView(err, mFence, view);
+}
+
+C2ConstGraphicBlock C2ConstGraphicBlock::subBlock(const C2Rect &rect) const {
+    return mImpl->subBlock(rect, mFence);
+}
+
+class C2GraphicBlock::Impl {
+public:
+    explicit Impl(const std::shared_ptr<C2GraphicAllocation> &alloc)
+        : mAllocation(alloc), mData{ nullptr } {}
+
+    ~Impl() {
+        if (mData[0] != nullptr) {
+            // TODO: fence
+            mAllocation->unmap(nullptr);
+        }
+    }
+
+    C2Error map(C2Rect rect) {
+        if (mData[0] != nullptr) {
+            // Already mapped.
+            return C2_OK;
+        }
+        uint8_t *data[C2PlaneLayout::MAX_NUM_PLANES];
+        C2Error err = mAllocation->map(
+                rect,
+                { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                nullptr,
+                &mLayout,
+                data);
+        if (err == C2_OK) {
+            memcpy(mData, data, sizeof(mData));
+        } else {
+            memset(mData, 0, sizeof(mData));
+        }
+        return err;
+    }
+
+    C2ConstGraphicBlock share(const C2Rect &crop, C2Fence fence) const {
+        C2DefaultConstGraphicBlock block(mAllocation, fence);
+        block.setCrop_be(crop);
+        return block;
+    }
+
+    uint8_t *const *data() const {
+        return mData[0] == nullptr ? nullptr : mData;
+    }
+
+    const C2PlaneLayout &layout() const { return mLayout; }
+
+private:
+    std::shared_ptr<C2GraphicAllocation> mAllocation;
+    C2PlaneLayout mLayout;
+    uint8_t *mData[C2PlaneLayout::MAX_NUM_PLANES];
+};
+
+C2GraphicBlock::C2GraphicBlock(const std::shared_ptr<C2GraphicAllocation> &alloc)
+    : C2Block2D(alloc), mImpl(new Impl(alloc)) {}
+
+C2Acquirable<C2GraphicView> C2GraphicBlock::map() {
+    C2Error err = mImpl->map(crop());
+    if (err != C2_OK) {
+        C2DefaultGraphicView view(err);
+        // TODO: fence
+        return C2AcquirableGraphicView(err, C2Fence(), view);
+    }
+    C2DefaultGraphicView view(this, mImpl->data(), mImpl->layout());
+    // TODO: fence
+    return C2AcquirableGraphicView(err, C2Fence(), view);
+}
+
+C2ConstGraphicBlock C2GraphicBlock::share(const C2Rect &crop, C2Fence fence) {
+    return mImpl->share(crop, fence);
+}
+
+C2DefaultGraphicBlockAllocator::C2DefaultGraphicBlockAllocator(
+        const std::shared_ptr<C2Allocator> &allocator)
+  : mAllocator(allocator) {}
+
+C2Error C2DefaultGraphicBlockAllocator::allocateGraphicBlock(
+        uint32_t width,
+        uint32_t height,
+        uint32_t format,
+        C2MemoryUsage usage,
+        std::shared_ptr<C2GraphicBlock> *block /* nonnull */) {
+    block->reset();
+
+    std::shared_ptr<C2GraphicAllocation> alloc;
+    C2Error err = mAllocator->allocateGraphicBuffer(width, height, format, usage, &alloc);
+    if (err != C2_OK) {
+        return err;
+    }
+
+    block->reset(new C2DefaultGraphicBlock(alloc));
+
+    return C2_OK;
+}
+
+/* ========================================== BUFFER ========================================= */
+
+class C2BufferData::Impl {
+public:
+    explicit Impl(const std::list<C2ConstLinearBlock> &blocks)
+        : mType(blocks.size() == 1 ? LINEAR : LINEAR_CHUNKS),
+          mLinearBlocks(blocks) {
+    }
+
+    explicit Impl(const std::list<C2ConstGraphicBlock> &blocks)
+        : mType(blocks.size() == 1 ? GRAPHIC : GRAPHIC_CHUNKS),
+          mGraphicBlocks(blocks) {
+    }
+
+    Type type() const { return mType; }
+    const std::list<C2ConstLinearBlock> &linearBlocks() const { return mLinearBlocks; }
+    const std::list<C2ConstGraphicBlock> &graphicBlocks() const { return mGraphicBlocks; }
+
+private:
+    Type mType;
+    std::list<C2ConstLinearBlock> mLinearBlocks;
+    std::list<C2ConstGraphicBlock> mGraphicBlocks;
+};
+
+C2BufferData::C2BufferData(const std::list<C2ConstLinearBlock> &blocks) : mImpl(new Impl(blocks)) {}
+C2BufferData::C2BufferData(const std::list<C2ConstGraphicBlock> &blocks) : mImpl(new Impl(blocks)) {}
+
+C2BufferData::Type C2BufferData::type() const { return mImpl->type(); }
+
+const std::list<C2ConstLinearBlock> C2BufferData::linearBlocks() const {
+    return mImpl->linearBlocks();
+}
+
+const std::list<C2ConstGraphicBlock> C2BufferData::graphicBlocks() const {
+    return mImpl->graphicBlocks();
+}
+
+class C2Buffer::Impl {
+public:
+    Impl(C2Buffer *thiz, const std::list<C2ConstLinearBlock> &blocks)
+        : mThis(thiz), mData(blocks) {}
+    Impl(C2Buffer *thiz, const std::list<C2ConstGraphicBlock> &blocks)
+        : mThis(thiz), mData(blocks) {}
+
+    ~Impl() {
+        for (const auto &pair : mNotify) {
+            pair.first(mThis, pair.second);
+        }
+    }
+
+    const C2BufferData &data() const { return mData; }
+
+    C2Error registerOnDestroyNotify(OnDestroyNotify onDestroyNotify, void *arg = nullptr) {
+        auto it = std::find_if(
+                mNotify.begin(), mNotify.end(),
+                [onDestroyNotify, arg] (const auto &pair) {
+                    return pair.first == onDestroyNotify && pair.second == arg;
+                });
+        if (it != mNotify.end()) {
+            return C2_DUPLICATE;
+        }
+        mNotify.emplace_back(onDestroyNotify, arg);
+        return C2_OK;
+    }
+
+    C2Error unregisterOnDestroyNotify(OnDestroyNotify onDestroyNotify) {
+        auto it = std::find_if(
+                mNotify.begin(), mNotify.end(),
+                [onDestroyNotify] (const auto &pair) {
+                    return pair.first == onDestroyNotify;
+                });
+        if (it == mNotify.end()) {
+            return C2_NOT_FOUND;
+        }
+        mNotify.erase(it);
+        return C2_OK;
+    }
+
+    std::list<std::shared_ptr<const C2Info>> infos() const {
+        std::list<std::shared_ptr<const C2Info>> result(mInfos.size());
+        std::transform(
+                mInfos.begin(), mInfos.end(), result.begin(),
+                [] (const auto &elem) { return elem.second; });
+        return result;
+    }
+
+    C2Error setInfo(const std::shared_ptr<C2Info> &info) {
+        // To "update" you need to erase the existing one if any, and then insert.
+        (void) mInfos.erase(info->type());
+        (void) mInfos.insert({ info->type(), info });
+        return C2_OK;
+    }
+
+    bool hasInfo(C2Param::Type index) const {
+        return mInfos.count(index.type()) > 0;
+    }
+
+    std::shared_ptr<C2Info> removeInfo(C2Param::Type index) {
+        auto it = mInfos.find(index.type());
+        if (it == mInfos.end()) {
+            return nullptr;
+        }
+        std::shared_ptr<C2Info> ret = it->second;
+        (void) mInfos.erase(it);
+        return ret;
+    }
+
+private:
+    C2Buffer * const mThis;
+    C2DefaultBufferData mData;
+    std::map<uint32_t, std::shared_ptr<C2Info>> mInfos;
+    std::list<std::pair<OnDestroyNotify, void *>> mNotify;
+};
+
+C2Buffer::C2Buffer(const std::list<C2ConstLinearBlock> &blocks)
+    : mImpl(new Impl(this, blocks)) {}
+
+C2Buffer::C2Buffer(const std::list<C2ConstGraphicBlock> &blocks)
+    : mImpl(new Impl(this, blocks)) {}
+
+const C2BufferData C2Buffer::data() const { return mImpl->data(); }
+
+C2Error C2Buffer::registerOnDestroyNotify(OnDestroyNotify onDestroyNotify, void *arg) {
+    return mImpl->registerOnDestroyNotify(onDestroyNotify, arg);
+}
+
+C2Error C2Buffer::unregisterOnDestroyNotify(OnDestroyNotify onDestroyNotify) {
+    return mImpl->unregisterOnDestroyNotify(onDestroyNotify);
+}
+
+const std::list<std::shared_ptr<const C2Info>> C2Buffer::infos() const {
+    return mImpl->infos();
+}
+
+C2Error C2Buffer::setInfo(const std::shared_ptr<C2Info> &info) {
+    return mImpl->setInfo(info);
+}
+
+bool C2Buffer::hasInfo(C2Param::Type index) const {
+    return mImpl->hasInfo(index);
+}
+
+std::shared_ptr<C2Info> C2Buffer::removeInfo(C2Param::Type index) {
+    return mImpl->removeInfo(index);
+}
+
+} // namespace android
diff --git a/media/libstagefright/codec2/vndk/include/C2BufferPriv.h b/media/libstagefright/codec2/vndk/include/C2BufferPriv.h
new file mode 100644
index 0000000..a536710
--- /dev/null
+++ b/media/libstagefright/codec2/vndk/include/C2BufferPriv.h
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2017 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_CODEC2_BUFFER_PRIV_H_
+#define STAGEFRIGHT_CODEC2_BUFFER_PRIV_H_
+
+#include <functional>
+
+#include <C2Buffer.h>
+
+namespace android {
+
+class C2AllocatorIon : public C2Allocator {
+public:
+    // (usage, capacity) => (align, heapMask, flags)
+    typedef std::function<int (C2MemoryUsage, size_t,
+                      /* => */ size_t*, unsigned*, unsigned*)> usage_mapper_fn;
+
+    virtual C2Error allocateLinearBuffer(
+            uint32_t capacity, C2MemoryUsage usage,
+            std::shared_ptr<C2LinearAllocation> *allocation) override;
+
+    virtual C2Error recreateLinearBuffer(
+            const C2Handle *handle,
+            std::shared_ptr<C2LinearAllocation> *allocation) override;
+
+    C2AllocatorIon();
+
+    C2Error status() const { return mInit; }
+
+    virtual ~C2AllocatorIon();
+
+private:
+    C2Error mInit;
+    int mIonFd;
+    usage_mapper_fn mUsageMapper;
+};
+
+class C2DefaultBlockAllocator : public C2BlockAllocator {
+public:
+    explicit C2DefaultBlockAllocator(const std::shared_ptr<C2Allocator> &allocator);
+
+    virtual ~C2DefaultBlockAllocator() = default;
+
+    virtual C2Error allocateLinearBlock(
+            uint32_t capacity,
+            C2MemoryUsage usage,
+            std::shared_ptr<C2LinearBlock> *block /* nonnull */) override;
+
+    // TODO:
+private:
+    const std::shared_ptr<C2Allocator> mAllocator;
+};
+
+class C2AllocatorGralloc : public C2Allocator {
+public:
+    // (usage, capacity) => (align, heapMask, flags)
+    typedef std::function<int (C2MemoryUsage, size_t,
+                      /* => */ size_t*, unsigned*, unsigned*)> usage_mapper_fn;
+
+    virtual C2Error allocateGraphicBuffer(
+            uint32_t width, uint32_t height, uint32_t format, C2MemoryUsage usage,
+            std::shared_ptr<C2GraphicAllocation> *allocation) override;
+
+    virtual C2Error recreateGraphicBuffer(
+            const C2Handle *handle,
+            std::shared_ptr<C2GraphicAllocation> *allocation) override;
+
+    C2AllocatorGralloc();
+
+    C2Error status() const;
+
+    virtual ~C2AllocatorGralloc();
+
+private:
+    class Impl;
+    Impl *mImpl;
+};
+
+class C2DefaultGraphicBlockAllocator : public C2BlockAllocator {
+public:
+    explicit C2DefaultGraphicBlockAllocator(const std::shared_ptr<C2Allocator> &allocator);
+
+    virtual ~C2DefaultGraphicBlockAllocator() = default;
+
+    virtual C2Error allocateGraphicBlock(
+            uint32_t width,
+            uint32_t height,
+            uint32_t format,
+            C2MemoryUsage usage,
+            std::shared_ptr<C2GraphicBlock> *block /* nonnull */) override;
+
+private:
+    const std::shared_ptr<C2Allocator> mAllocator;
+};
+
+
+#if 0
+class C2Allocation::Impl {
+public:
+    Impl() : mMapped(false), mBase(nullptr) { }
+    uint8_t* base() { return mMapped ? mBase : nullptr; }
+
+    // TODO: call map...
+
+private:
+    bool mMapped;
+    uint8_t *mBase;
+};
+#endif
+
+} // namespace android
+
+#endif // STAGEFRIGHT_CODEC2_BUFFER_PRIV_H_
diff --git a/media/libstagefright/codecs/aacenc/AACEncoder.cpp b/media/libstagefright/codecs/aacenc/AACEncoder.cpp
deleted file mode 100644
index 5656139..0000000
--- a/media/libstagefright/codecs/aacenc/AACEncoder.cpp
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- * Copyright (C) 2010 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 "AACEncoder"
-#include <utils/Log.h>
-
-#include "AACEncoder.h"
-#include "voAAC.h"
-#include "cmnMemory.h"
-
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/MediaBufferGroup.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MetaData.h>
-
-namespace android {
-
-AACEncoder::AACEncoder(const sp<IMediaSource> &source, const sp<MetaData> &meta)
-    : mSource(source),
-      mMeta(meta),
-      mStarted(false),
-      mBufferGroup(NULL),
-      mInputBuffer(NULL),
-      mInputFrame(NULL),
-      mEncoderHandle(NULL),
-      mApiHandle(NULL),
-      mMemOperator(NULL) {
-}
-
-status_t AACEncoder::initCheck() {
-    CHECK(mApiHandle == NULL && mEncoderHandle == NULL);
-    CHECK(mMeta->findInt32(kKeySampleRate, &mSampleRate));
-    CHECK(mMeta->findInt32(kKeyChannelCount, &mChannels));
-    CHECK(mChannels <= 2 && mChannels >= 1);
-    CHECK(mMeta->findInt32(kKeyBitRate, &mBitRate));
-
-    mApiHandle = new VO_AUDIO_CODECAPI;
-    CHECK(mApiHandle);
-
-    if (VO_ERR_NONE != voGetAACEncAPI(mApiHandle)) {
-        ALOGE("Failed to get api handle");
-        return UNKNOWN_ERROR;
-    }
-
-    mMemOperator = new VO_MEM_OPERATOR;
-    CHECK(mMemOperator != NULL);
-    mMemOperator->Alloc = cmnMemAlloc;
-    mMemOperator->Copy = cmnMemCopy;
-    mMemOperator->Free = cmnMemFree;
-    mMemOperator->Set = cmnMemSet;
-    mMemOperator->Check = cmnMemCheck;
-
-    VO_CODEC_INIT_USERDATA userData;
-    memset(&userData, 0, sizeof(userData));
-    userData.memflag = VO_IMF_USERMEMOPERATOR;
-    userData.memData = (VO_PTR) mMemOperator;
-    if (VO_ERR_NONE != mApiHandle->Init(&mEncoderHandle, VO_AUDIO_CodingAAC, &userData)) {
-        ALOGE("Failed to init AAC encoder");
-        return UNKNOWN_ERROR;
-    }
-    if (OK != setAudioSpecificConfigData()) {
-        ALOGE("Failed to configure AAC encoder");
-        return UNKNOWN_ERROR;
-    }
-
-    // Configure AAC encoder$
-    AACENC_PARAM params;
-    memset(&params, 0, sizeof(params));
-    params.sampleRate = mSampleRate;
-    params.bitRate = mBitRate;
-    params.nChannels = mChannels;
-    params.adtsUsed = 0;  // We add adts header in the file writer if needed.
-    if (VO_ERR_NONE != mApiHandle->SetParam(mEncoderHandle, VO_PID_AAC_ENCPARAM,  &params)) {
-        ALOGE("Failed to set AAC encoder parameters");
-        return UNKNOWN_ERROR;
-    }
-
-    return OK;
-}
-
-static status_t getSampleRateTableIndex(int32_t sampleRate, int32_t &index) {
-    static const int32_t kSampleRateTable[] = {
-        96000, 88200, 64000, 48000, 44100, 32000,
-        24000, 22050, 16000, 12000, 11025, 8000
-    };
-    const int32_t tableSize = sizeof(kSampleRateTable) / sizeof(kSampleRateTable[0]);
-    for (int32_t i = 0; i < tableSize; ++i) {
-        if (sampleRate == kSampleRateTable[i]) {
-            index = i;
-            return OK;
-        }
-    }
-
-    ALOGE("Sampling rate %d bps is not supported", sampleRate);
-    return UNKNOWN_ERROR;
-}
-
-status_t AACEncoder::setAudioSpecificConfigData() {
-    ALOGV("setAudioSpecificConfigData: %d hz, %d bps, and %d channels",
-         mSampleRate, mBitRate, mChannels);
-
-    int32_t index = 0;
-    CHECK_EQ((status_t)OK, getSampleRateTableIndex(mSampleRate, index));
-    if (mChannels > 2 || mChannels <= 0) {
-        ALOGE("Unsupported number of channels(%d)", mChannels);
-        return UNKNOWN_ERROR;
-    }
-
-    // OMX_AUDIO_AACObjectLC
-    mAudioSpecificConfigData[0] = ((0x02 << 3) | (index >> 1));
-    mAudioSpecificConfigData[1] = ((index & 0x01) << 7) | (mChannels << 3);
-    return OK;
-}
-
-AACEncoder::~AACEncoder() {
-    if (mStarted) {
-        stop();
-    }
-}
-
-status_t AACEncoder::start(MetaData *params) {
-    if (mStarted) {
-        ALOGW("Call start() when encoder already started");
-        return OK;
-    }
-
-    mBufferGroup = new MediaBufferGroup;
-    mBufferGroup->add_buffer(new MediaBuffer(2048));
-
-    CHECK_EQ((status_t)OK, initCheck());
-
-    mNumInputSamples = 0;
-    mAnchorTimeUs = 0;
-    mFrameCount = 0;
-
-    mInputFrame = new int16_t[mChannels * kNumSamplesPerFrame];
-    CHECK(mInputFrame != NULL);
-
-    status_t err = mSource->start(params);
-    if (err != OK) {
-         ALOGE("AudioSource is not available");
-        return err;
-    }
-
-    mStarted = true;
-
-    return OK;
-}
-
-status_t AACEncoder::stop() {
-    if (mInputBuffer) {
-        mInputBuffer->release();
-        mInputBuffer = NULL;
-    }
-
-    delete mBufferGroup;
-    mBufferGroup = NULL;
-
-    if (mInputFrame) {
-        delete[] mInputFrame;
-        mInputFrame = NULL;
-    }
-
-    if (!mStarted) {
-        ALOGW("Call stop() when encoder has not started");
-        return ERROR_END_OF_STREAM;
-    }
-
-    mSource->stop();
-    if (mEncoderHandle) {
-        CHECK_EQ((VO_U32)VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle));
-        mEncoderHandle = NULL;
-    }
-    delete mApiHandle;
-    mApiHandle = NULL;
-
-    delete mMemOperator;
-    mMemOperator = NULL;
-
-    mStarted = false;
-
-    return OK;
-}
-
-sp<MetaData> AACEncoder::getFormat() {
-    sp<MetaData> srcFormat = mSource->getFormat();
-
-    mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
-
-    int64_t durationUs;
-    if (srcFormat->findInt64(kKeyDuration, &durationUs)) {
-        mMeta->setInt64(kKeyDuration, durationUs);
-    }
-
-    mMeta->setCString(kKeyDecoderComponent, "AACEncoder");
-
-    return mMeta;
-}
-
-status_t AACEncoder::read(
-        MediaBuffer **out, const ReadOptions *options) {
-    *out = NULL;
-
-    int64_t seekTimeUs;
-    ReadOptions::SeekMode mode;
-    CHECK(options == NULL || !options->getSeekTo(&seekTimeUs, &mode));
-
-    MediaBuffer *buffer;
-    CHECK_EQ(mBufferGroup->acquire_buffer(&buffer), (status_t)OK);
-    uint8_t *outPtr = (uint8_t *)buffer->data();
-    bool readFromSource = false;
-    int64_t wallClockTimeUs = -1;
-
-    if (mFrameCount == 0) {
-        memcpy(outPtr, mAudioSpecificConfigData, 2);
-        buffer->set_range(0, 2);
-        buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
-        *out = buffer;
-        ++mFrameCount;
-        return OK;
-    } else if (mFrameCount == 1) {
-        buffer->meta_data()->setInt32(kKeyIsCodecConfig, false);
-    }
-
-    const int32_t nSamples = mChannels * kNumSamplesPerFrame;
-    while (mNumInputSamples < nSamples) {
-        if (mInputBuffer == NULL) {
-            if (mSource->read(&mInputBuffer, options) != OK) {
-                if (mNumInputSamples == 0) {
-                    buffer->release();
-                    return ERROR_END_OF_STREAM;
-                }
-                memset(&mInputFrame[mNumInputSamples],
-                       0,
-                       sizeof(int16_t) * (nSamples - mNumInputSamples));
-                mNumInputSamples = 0;
-                break;
-            }
-
-            size_t align = mInputBuffer->range_length() % sizeof(int16_t);
-            CHECK_EQ(align, (size_t)0);
-
-            int64_t timeUs;
-            if (mInputBuffer->meta_data()->findInt64(kKeyDriftTime, &timeUs)) {
-                wallClockTimeUs = timeUs;
-            }
-            if (mInputBuffer->meta_data()->findInt64(kKeyAnchorTime, &timeUs)) {
-                mAnchorTimeUs = timeUs;
-            }
-            readFromSource = true;
-        } else {
-            readFromSource = false;
-        }
-        size_t copy = (nSamples - 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);
-
-        mInputBuffer->set_range(
-               mInputBuffer->range_offset() + copy,
-               mInputBuffer->range_length() - copy);
-
-        if (mInputBuffer->range_length() == 0) {
-            mInputBuffer->release();
-            mInputBuffer = NULL;
-        }
-        mNumInputSamples += copy / sizeof(int16_t);
-        if (mNumInputSamples >= nSamples) {
-            mNumInputSamples %= nSamples;
-            break;
-        }
-    }
-
-    VO_CODECBUFFER inputData;
-    memset(&inputData, 0, sizeof(inputData));
-    inputData.Buffer = (unsigned char*) mInputFrame;
-    inputData.Length = nSamples * sizeof(int16_t);
-    CHECK((VO_U32)VO_ERR_NONE == mApiHandle->SetInputData(mEncoderHandle,&inputData));
-
-    VO_CODECBUFFER outputData;
-    memset(&outputData, 0, sizeof(outputData));
-    VO_AUDIO_OUTPUTINFO outputInfo;
-    memset(&outputInfo, 0, sizeof(outputInfo));
-
-    VO_U32 ret = VO_ERR_NONE;
-    size_t nOutputBytes = 0;
-    do {
-        outputData.Buffer = outPtr;
-        outputData.Length = buffer->size() - nOutputBytes;
-        ret = mApiHandle->GetOutputData(mEncoderHandle, &outputData, &outputInfo);
-        if (ret == VO_ERR_NONE) {
-            outPtr += outputData.Length;
-            nOutputBytes += outputData.Length;
-        }
-    } while (ret != VO_ERR_INPUT_BUFFER_SMALL);
-    buffer->set_range(0, nOutputBytes);
-
-    int64_t mediaTimeUs =
-        ((mFrameCount - 1) * 1000000LL * kNumSamplesPerFrame) / mSampleRate;
-
-    buffer->meta_data()->setInt64(kKeyTime, mAnchorTimeUs + mediaTimeUs);
-    if (readFromSource && wallClockTimeUs != -1) {
-        buffer->meta_data()->setInt64(kKeyDriftTime, mediaTimeUs - wallClockTimeUs);
-    }
-    ++mFrameCount;
-
-    *out = buffer;
-    return OK;
-}
-
-}  // namespace android
diff --git a/media/libstagefright/codecs/aacenc/Android.bp b/media/libstagefright/codecs/aacenc/Android.bp
index 1b4e35c..d734b9c 100644
--- a/media/libstagefright/codecs/aacenc/Android.bp
+++ b/media/libstagefright/codecs/aacenc/Android.bp
@@ -1,115 +1,3 @@
-cc_library_static {
-    name: "libstagefright_aacenc",
-    vendor_available: true,
-
-    srcs: [
-        "basic_op/basicop2.c",
-        "basic_op/oper_32b.c",
-
-        "AACEncoder.cpp",
-        "src/aac_rom.c",
-        "src/aacenc.c",
-        "src/aacenc_core.c",
-        "src/adj_thr.c",
-        "src/band_nrg.c",
-        "src/bit_cnt.c",
-        "src/bitbuffer.c",
-        "src/bitenc.c",
-        "src/block_switch.c",
-        "src/channel_map.c",
-        "src/dyn_bits.c",
-        "src/grp_data.c",
-        "src/interface.c",
-        "src/line_pe.c",
-        "src/ms_stereo.c",
-        "src/pre_echo_control.c",
-        "src/psy_configuration.c",
-        "src/psy_main.c",
-        "src/qc_main.c",
-        "src/quantize.c",
-        "src/sf_estim.c",
-        "src/spreading.c",
-        "src/stat_bits.c",
-        "src/tns.c",
-        "src/transform.c",
-        "src/memalign.c",
-    ],
-
-    arch: {
-        arm: {
-            srcs: [
-                "src/asm/ARMV5E/AutoCorrelation_v5.s",
-                "src/asm/ARMV5E/band_nrg_v5.s",
-                "src/asm/ARMV5E/CalcWindowEnergy_v5.s",
-                "src/asm/ARMV5E/PrePostMDCT_v5.s",
-                "src/asm/ARMV5E/R4R8First_v5.s",
-                "src/asm/ARMV5E/Radix4FFT_v5.s",
-            ],
-
-            cflags: [
-                "-DARMV5E",
-                "-DARM_INASM",
-                "-DARMV5_INASM",
-            ],
-
-            local_include_dirs: ["src/asm/ARMV5E"],
-
-            instruction_set: "arm",
-
-            neon: {
-                exclude_srcs: [
-                    "src/asm/ARMV5E/PrePostMDCT_v5.s",
-                    "src/asm/ARMV5E/R4R8First_v5.s",
-                    "src/asm/ARMV5E/Radix4FFT_v5.s",
-                ],
-                srcs: [
-                    "src/asm/ARMV7/PrePostMDCT_v7.s",
-                    "src/asm/ARMV7/R4R8First_v7.s",
-                    "src/asm/ARMV7/Radix4FFT_v7.s",
-                ],
-
-                cflags: [
-                    "-DARMV7Neon",
-                    "-DARMV6_INASM",
-                ],
-
-                local_include_dirs: ["src/asm/ARMV7"],
-            },
-        },
-    },
-
-    // libstagefright links this static library, so it probably isn't appropriate to
-    // link libstagefright.  However, this library includes libstagefright headers,
-    // and needs libbinder to be able to do so correctly.
-    shared_libs: [
-        "libbinder",
-        "libstagefright_enc_common",
-    ],
-
-    include_dirs: [
-        "frameworks/av/include",
-        "frameworks/av/media/libstagefright/include",
-    ],
-
-    local_include_dirs: [
-        "src",
-        "inc",
-        "basic_op",
-    ],
-
-    cflags: ["-Werror"],
-
-    sanitize: {
-        misc_undefined: [
-            "signed-integer-overflow",
-            "unsigned-integer-overflow",
-        ],
-    },
-
-}
-
-//###############################################################################
-
 cc_library_shared {
     name: "libstagefright_soft_aacenc",
     vendor_available: true,
@@ -147,36 +35,3 @@
     ],
     compile_multilib: "32",
 }
-
-cc_library_shared {
-    name: "libstagefright_soft_aacenc_visualon",
-
-    srcs: ["SoftAACEncoder.cpp"],
-
-    include_dirs: [
-        "frameworks/av/media/libstagefright/include",
-        "frameworks/native/include/media/openmax",
-    ],
-
-    cflags: [
-        "-DOSCL_IMPORT_REF=",
-        "-Werror",
-    ],
-
-    sanitize: {
-        misc_undefined: [
-            "signed-integer-overflow",
-            "unsigned-integer-overflow",
-        ],
-    },
-
-    static_libs: ["libstagefright_aacenc"],
-
-    shared_libs: [
-        "libstagefright_omx",
-        "libstagefright_foundation",
-        "libutils",
-        "liblog",
-        "libstagefright_enc_common",
-    ],
-}
diff --git a/media/libstagefright/codecs/aacenc/SampleCode/AAC_E_SAMPLES.c b/media/libstagefright/codecs/aacenc/SampleCode/AAC_E_SAMPLES.c
deleted file mode 100644
index 2f31de4..0000000
--- a/media/libstagefright/codecs/aacenc/SampleCode/AAC_E_SAMPLES.c
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		AAC_E_SAMPLES.h
-
-	Content:	sample code for AAC encoder
-
-*******************************************************************************/
-
-#include		<dlfcn.h>
-#include		<stdio.h>
-#include		<stdlib.h>
-#include		<string.h>
-#include		<time.h>
-#include		"voAAC.h"
-#include		"cmnMemory.h"
-
-#define  VO_AAC_E_OUTPUT	  1
-#define READ_SIZE	(1024*8)
-unsigned char outBuf[1024*8];
-unsigned char inBuf[READ_SIZE];
-
-const char* HelpString =
-"VisualOn AAC encoder Usage:\n"
-"voAACEncTest -if <inputfile.pcm> -of <outputfile.aac> -sr <samplerate> -ch <channel> -br <bitrate> -adts <adts> \n"
-"-if input file name \n"
-"-of output file name \n"
-"-sr input pcm samplerate, default 44100 \n"
-"-ch input pcm channel, default 2 channel \n"
-"-br encoded aac bitrate, default 64000 * (samplerate/100)*channel/441(480)\n"
-"-adts add or no adts header, default add adts header\n"
-"For example: \n"
-"./voAACEncTest -if raw.pcm -of raw.aac -sr 44100 -ch 2 -br 128000\n";
-
-static int parsecmdline(int argc, char **argv,char  **input_filename, char  **output_filename, AACENC_PARAM *param)
-{
-	// notice that:
-	// bitRate/nChannels > 8000
-	// bitRate/nChannels < 160000
-	// bitRate/nChannels < sampleRate*6
-	param->adtsUsed = 1;
-	param->bitRate = 0;
-	param->nChannels = 2;
-	param->sampleRate = 44100;
-
-	if(argc < 5 || argc > 13)
-	{
-		return -1;
-	}
-
-	argc--;
-	argv++;
-	while (argc > 0)
-	{
-		if (!strcmp(*argv, "-if"))
-		{
-			argv++;
-			argc--;
-			*input_filename = *argv;
-		}
-		else if (!strcmp(*argv, "-of"))
-		{
-			argv++;
-			argc--;
-			*output_filename = *argv;
-		}
-		else if (!strcmp(*argv, "-sr"))
-		{
-			argv++;
-			argc--;
-			param->sampleRate = atoi(*argv);
-		}
-		else if (!strcmp(*argv, "-ch"))
-		{
-			argv++;
-			argc--;
-			param->nChannels = atoi(*argv);
-		}
-		else if (!strcmp(*argv, "-br"))
-		{
-			argv++;
-			argc--;
-			param->bitRate = atoi(*argv);
-		}
-		else if(!strcmp(*argv, "-adts"))
-		{
-			argv++;
-			argc--;
-			param->adtsUsed = atoi(*argv);
-		}
-		else
-		{
-			return -1;
-		}
-
-		argv++;
-		argc--;
-	}
-
-	if(param->bitRate == 0)
-	{
-		int scale = 441;
-		if(param->sampleRate%8000 == 0)
-			scale = 480;
-		param->bitRate = 640*param->nChannels*param->sampleRate/scale;
-	}
-
-	return 0;
-}
-
-int ReadFile2Buf(FILE* infile,unsigned char* dest,int readSize)
-{
-	int readBytes = 0;
-	readBytes = fread(dest, 1, readSize, infile);
-	return readBytes;
-}
-
-typedef int (VO_API * VOGETAUDIODECAPI) (VO_AUDIO_CODECAPI * pDecHandle);
-
-int main(int argc, char **argv)
-{
-	FILE						*infile, *outfile;
-	int							t1, t2;
-	VO_AUDIO_CODECAPI			AudioAPI;
-	VO_MEM_OPERATOR				moper;
-	VO_CODEC_INIT_USERDATA		useData;
-	VO_HANDLE					hCodec;
-	VO_CODECBUFFER				inData;
-	VO_CODECBUFFER				outData;
-	VO_AUDIO_OUTPUTINFO			outInfo;
-    int							firstWrite = 1;
-	int							eofFile = 0;
-	int							*info=(int*)inBuf;
-	int							bytesLeft, nRead;
-	int							EncoderdFrame = 0;
-	int							total = 0;
-	int							isOutput = 1;
-	int							returnCode;
-	AACENC_PARAM				aacpara;
-	void						*handle;
-	void						*pfunc;
-	VOGETAUDIODECAPI			pGetAPI;
-	const char					*infileName = NULL;
-    const char					*outfileName = NULL;
-
-	returnCode = parsecmdline(argc,argv, &infileName, &outfileName, &aacpara);
-	if(returnCode)
-	{
-		printf("%s", HelpString);
-		return 0;
-	}
-
-	/* open input file */
-	infile = fopen(infileName, "rb");
-	if (!infile) {
-		printf("Open input file fail...");
-		return -1;
-	}
-
-	/* open output file */
-	if(isOutput)
-	{
-		outfile = fopen(outfileName, "wb");
-		if (!outfile) {
-			printf("Open output file fail...");
-			return -1;
-		}
-	}
-	// set memory operators;
-	moper.Alloc = cmnMemAlloc;
-	moper.Copy = cmnMemCopy;
-	moper.Free = cmnMemFree;
-	moper.Set = cmnMemSet;
-	moper.Check = cmnMemCheck;
-	useData.memflag = VO_IMF_USERMEMOPERATOR;
-	useData.memData = (VO_PTR)(&moper);
-	// open encoder dll;
-	handle = dlopen("libstagefright.so", RTLD_NOW);
-	if(handle == 0)
-	{
-		printf("open dll error......");
-		return -1;
-	}
-	// Get API;
-	pfunc = dlsym(handle, "voGetAACEncAPI");
-	if(pfunc == 0)
-	{
-		printf("open function error......");
-		return -1;
-	}
-	pGetAPI = (VOGETAUDIODECAPI)pfunc;
-	returnCode  = pGetAPI(&AudioAPI);
-	if(returnCode)
-		return -1;
-
-
-//#######################################   Init Encoding Section   #########################################
-	returnCode = AudioAPI.Init(&hCodec, VO_AUDIO_CodingAAC, &useData);
-	if(returnCode < 0)
-	{
-		printf("#### VOI_Error2:fail to initialize the Encoderr###\n");
-		return -1;
-	}
-
-	returnCode = AudioAPI.SetParam(hCodec, VO_PID_AAC_ENCPARAM, &aacpara);
-
-	inData.Buffer = inBuf;
-	bytesLeft = ReadFile2Buf(infile,inData.Buffer,READ_SIZE);
-
-//#######################################    Encoding Section   #########################################
-
-	do {
-
-		inData.Length    = bytesLeft;
-		outData.Buffer   = outBuf;
-		outData.Length = 1024*8;
-
-		t1 = clock();
-
-		returnCode = AudioAPI.SetInputData(hCodec,&inData);
-
-		do {
-			outData.Buffer   = outBuf;
-			outData.Length = 1024*8;
-
-			returnCode = AudioAPI.GetOutputData(hCodec,&outData, &outInfo);
-
-			if(returnCode == 0)
-				EncoderdFrame++;
-			if(returnCode == VO_ERR_LICENSE_ERROR)
-				break;
-
-#if VO_AAC_E_OUTPUT
-			if (isOutput && returnCode == 0)
-			{
-				fwrite(outData.Buffer, 1, outData.Length, outfile);
-			}
-#endif
-		} while(returnCode != (VO_ERR_INPUT_BUFFER_SMALL));
-
-		if(returnCode == VO_ERR_LICENSE_ERROR)
-			break;
-
-		t2 = clock();
-		total += t2 - t1;
-
-		if (!eofFile) {
-			nRead = ReadFile2Buf(infile, inBuf,READ_SIZE);
-			bytesLeft = nRead;
-			inData.Buffer = inBuf;
-			if (feof(infile))
-				eofFile = 1;
-		}
-
-	} while (!eofFile && returnCode);
-
-
-//################################################  End Encoding Section  #######################################################
-	returnCode = AudioAPI.Uninit(hCodec);
-
-	fclose(infile);
-	if (outfile)
-    {
-        fclose(outfile);
-    }
-	dlclose(handle);
-	return 0;
-}
-
-
diff --git a/media/libstagefright/codecs/aacenc/SampleCode/Android.bp b/media/libstagefright/codecs/aacenc/SampleCode/Android.bp
deleted file mode 100644
index c6ba4f3..0000000
--- a/media/libstagefright/codecs/aacenc/SampleCode/Android.bp
+++ /dev/null
@@ -1,18 +0,0 @@
-cc_binary {
-    name: "AACEncTest",
-
-    srcs: ["AAC_E_SAMPLES.c"],
-
-    arch: {
-        arm: {
-            instruction_set: "arm",
-        },
-    },
-
-    shared_libs: [
-        "libstagefright",
-        "libdl",
-    ],
-
-    static_libs: ["libstagefright_enc_common"],
-}
diff --git a/media/libstagefright/codecs/aacenc/SampleCode/MODULE_LICENSE_APACHE2 b/media/libstagefright/codecs/aacenc/SampleCode/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29..0000000
--- a/media/libstagefright/codecs/aacenc/SampleCode/MODULE_LICENSE_APACHE2
+++ /dev/null
diff --git a/media/libstagefright/codecs/aacenc/SampleCode/NOTICE b/media/libstagefright/codecs/aacenc/SampleCode/NOTICE
deleted file mode 100644
index c5b1efa..0000000
--- a/media/libstagefright/codecs/aacenc/SampleCode/NOTICE
+++ /dev/null
@@ -1,190 +0,0 @@
-
-   Copyright (c) 2005-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.
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
diff --git a/media/libstagefright/codecs/aacenc/SoftAACEncoder.cpp b/media/libstagefright/codecs/aacenc/SoftAACEncoder.cpp
deleted file mode 100644
index 0704294..0000000
--- a/media/libstagefright/codecs/aacenc/SoftAACEncoder.cpp
+++ /dev/null
@@ -1,594 +0,0 @@
-/*
- * Copyright (C) 2012 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 "SoftAACEncoder"
-#include <utils/Log.h>
-
-#include "SoftAACEncoder.h"
-
-#include "voAAC.h"
-#include "cmnMemory.h"
-
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/hexdump.h>
-
-namespace android {
-
-template<class T>
-static void InitOMXParams(T *params) {
-    params->nSize = sizeof(T);
-    params->nVersion.s.nVersionMajor = 1;
-    params->nVersion.s.nVersionMinor = 0;
-    params->nVersion.s.nRevision = 0;
-    params->nVersion.s.nStep = 0;
-}
-
-SoftAACEncoder::SoftAACEncoder(
-        const char *name,
-        const OMX_CALLBACKTYPE *callbacks,
-        OMX_PTR appData,
-        OMX_COMPONENTTYPE **component)
-    : SimpleSoftOMXComponent(name, callbacks, appData, component),
-      mEncoderHandle(NULL),
-      mApiHandle(NULL),
-      mMemOperator(NULL),
-      mNumChannels(1),
-      mSampleRate(44100),
-      mBitRate(0),
-      mSentCodecSpecificData(false),
-      mInputSize(0),
-      mInputFrame(NULL),
-      mInputTimeUs(-1ll),
-      mSawInputEOS(false),
-      mSignalledError(false) {
-    initPorts();
-    CHECK_EQ(initEncoder(), (status_t)OK);
-
-    setAudioParams();
-}
-
-SoftAACEncoder::~SoftAACEncoder() {
-    onReset();
-
-    if (mEncoderHandle) {
-        CHECK_EQ((VO_U32)VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle));
-        mEncoderHandle = NULL;
-    }
-
-    delete mApiHandle;
-    mApiHandle = NULL;
-
-    delete mMemOperator;
-    mMemOperator = NULL;
-}
-
-void SoftAACEncoder::initPorts() {
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-
-    def.nPortIndex = 0;
-    def.eDir = OMX_DirInput;
-    def.nBufferCountMin = kNumBuffers;
-    def.nBufferCountActual = def.nBufferCountMin;
-    def.nBufferSize = kNumSamplesPerFrame * sizeof(int16_t) * 2;
-    def.bEnabled = OMX_TRUE;
-    def.bPopulated = OMX_FALSE;
-    def.eDomain = OMX_PortDomainAudio;
-    def.bBuffersContiguous = OMX_FALSE;
-    def.nBufferAlignment = 1;
-
-    def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
-    def.format.audio.pNativeRender = NULL;
-    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
-    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
-
-    addPort(def);
-
-    def.nPortIndex = 1;
-    def.eDir = OMX_DirOutput;
-    def.nBufferCountMin = kNumBuffers;
-    def.nBufferCountActual = def.nBufferCountMin;
-    def.nBufferSize = 8192;
-    def.bEnabled = OMX_TRUE;
-    def.bPopulated = OMX_FALSE;
-    def.eDomain = OMX_PortDomainAudio;
-    def.bBuffersContiguous = OMX_FALSE;
-    def.nBufferAlignment = 2;
-
-    def.format.audio.cMIMEType = const_cast<char *>("audio/aac");
-    def.format.audio.pNativeRender = NULL;
-    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
-    def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
-
-    addPort(def);
-}
-
-status_t SoftAACEncoder::initEncoder() {
-    mApiHandle = new VO_AUDIO_CODECAPI;
-
-    if (VO_ERR_NONE != voGetAACEncAPI(mApiHandle)) {
-        ALOGE("Failed to get api handle");
-        return UNKNOWN_ERROR;
-    }
-
-    mMemOperator = new VO_MEM_OPERATOR;
-    mMemOperator->Alloc = cmnMemAlloc;
-    mMemOperator->Copy = cmnMemCopy;
-    mMemOperator->Free = cmnMemFree;
-    mMemOperator->Set = cmnMemSet;
-    mMemOperator->Check = cmnMemCheck;
-
-    VO_CODEC_INIT_USERDATA userData;
-    memset(&userData, 0, sizeof(userData));
-    userData.memflag = VO_IMF_USERMEMOPERATOR;
-    userData.memData = (VO_PTR) mMemOperator;
-    if (VO_ERR_NONE !=
-            mApiHandle->Init(&mEncoderHandle, VO_AUDIO_CodingAAC, &userData)) {
-        ALOGE("Failed to init AAC encoder");
-        return UNKNOWN_ERROR;
-    }
-
-    return OK;
-}
-
-OMX_ERRORTYPE SoftAACEncoder::internalGetParameter(
-        OMX_INDEXTYPE index, OMX_PTR params) {
-    switch (index) {
-        case OMX_IndexParamAudioPortFormat:
-        {
-            OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
-                (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
-
-            if (!isValidOMXParam(formatParams)) {
-                return OMX_ErrorBadParameter;
-            }
-
-            if (formatParams->nPortIndex > 1) {
-                return OMX_ErrorUndefined;
-            }
-
-            if (formatParams->nIndex > 0) {
-                return OMX_ErrorNoMore;
-            }
-
-            formatParams->eEncoding =
-                (formatParams->nPortIndex == 0)
-                    ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC;
-
-            return OMX_ErrorNone;
-        }
-
-        case OMX_IndexParamAudioAac:
-        {
-            OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
-                (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
-
-            if (!isValidOMXParam(aacParams)) {
-                return OMX_ErrorBadParameter;
-            }
-
-            if (aacParams->nPortIndex != 1) {
-                return OMX_ErrorUndefined;
-            }
-
-            aacParams->nBitRate = mBitRate;
-            aacParams->nAudioBandWidth = 0;
-            aacParams->nAACtools = 0;
-            aacParams->nAACERtools = 0;
-            aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
-            aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
-            aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
-
-            aacParams->nChannels = mNumChannels;
-            aacParams->nSampleRate = mSampleRate;
-            aacParams->nFrameLength = 0;
-
-            return OMX_ErrorNone;
-        }
-
-        case OMX_IndexParamAudioPcm:
-        {
-            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
-                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
-
-            if (!isValidOMXParam(pcmParams)) {
-                return OMX_ErrorBadParameter;
-            }
-
-            if (pcmParams->nPortIndex != 0) {
-                return OMX_ErrorUndefined;
-            }
-
-            pcmParams->eNumData = OMX_NumericalDataSigned;
-            pcmParams->eEndian = OMX_EndianBig;
-            pcmParams->bInterleaved = OMX_TRUE;
-            pcmParams->nBitPerSample = 16;
-            pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
-            pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
-            pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
-
-            pcmParams->nChannels = mNumChannels;
-            pcmParams->nSamplingRate = mSampleRate;
-
-            return OMX_ErrorNone;
-        }
-
-        default:
-            return SimpleSoftOMXComponent::internalGetParameter(index, params);
-    }
-}
-
-OMX_ERRORTYPE SoftAACEncoder::internalSetParameter(
-        OMX_INDEXTYPE index, const OMX_PTR params) {
-    switch (index) {
-        case OMX_IndexParamStandardComponentRole:
-        {
-            const OMX_PARAM_COMPONENTROLETYPE *roleParams =
-                (const OMX_PARAM_COMPONENTROLETYPE *)params;
-
-            if (!isValidOMXParam(roleParams)) {
-                return OMX_ErrorBadParameter;
-            }
-
-            if (strncmp((const char *)roleParams->cRole,
-                        "audio_encoder.aac",
-                        OMX_MAX_STRINGNAME_SIZE - 1)) {
-                return OMX_ErrorUndefined;
-            }
-
-            return OMX_ErrorNone;
-        }
-
-        case OMX_IndexParamAudioPortFormat:
-        {
-            const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
-                (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
-
-            if (!isValidOMXParam(formatParams)) {
-                return OMX_ErrorBadParameter;
-            }
-
-            if (formatParams->nPortIndex > 1) {
-                return OMX_ErrorUndefined;
-            }
-
-            if ((formatParams->nPortIndex == 0
-                        && formatParams->eEncoding != OMX_AUDIO_CodingPCM)
-                || (formatParams->nPortIndex == 1
-                        && formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
-                return OMX_ErrorUndefined;
-            }
-
-            return OMX_ErrorNone;
-        }
-
-        case OMX_IndexParamAudioAac:
-        {
-            OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
-                (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
-
-            if (!isValidOMXParam(aacParams)) {
-                return OMX_ErrorBadParameter;
-            }
-
-            if (aacParams->nPortIndex != 1) {
-                return OMX_ErrorUndefined;
-            }
-
-            mBitRate = aacParams->nBitRate;
-            mNumChannels = aacParams->nChannels;
-            mSampleRate = aacParams->nSampleRate;
-
-            if (setAudioParams() != OK) {
-                return OMX_ErrorUndefined;
-            }
-
-            return OMX_ErrorNone;
-        }
-
-        case OMX_IndexParamAudioPcm:
-        {
-            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
-                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
-
-            if (!isValidOMXParam(pcmParams)) {
-                return OMX_ErrorBadParameter;
-            }
-
-            if (pcmParams->nPortIndex != 0) {
-                return OMX_ErrorUndefined;
-            }
-
-            mNumChannels = pcmParams->nChannels;
-            mSampleRate = pcmParams->nSamplingRate;
-
-            if (setAudioParams() != OK) {
-                return OMX_ErrorUndefined;
-            }
-
-            return OMX_ErrorNone;
-        }
-
-
-        default:
-            return SimpleSoftOMXComponent::internalSetParameter(index, params);
-    }
-}
-
-status_t SoftAACEncoder::setAudioParams() {
-    // We call this whenever sample rate, number of channels or bitrate change
-    // in reponse to setParameter calls.
-
-    ALOGV("setAudioParams: %u Hz, %u channels, %u bps",
-         mSampleRate, mNumChannels, mBitRate);
-
-    status_t err = setAudioSpecificConfigData();
-
-    if (err != OK) {
-        return err;
-    }
-
-    AACENC_PARAM params;
-    memset(&params, 0, sizeof(params));
-    params.sampleRate = mSampleRate;
-    params.bitRate = mBitRate;
-    params.nChannels = mNumChannels;
-    params.adtsUsed = 0;  // We add adts header in the file writer if needed.
-    if (VO_ERR_NONE != mApiHandle->SetParam(
-                mEncoderHandle, VO_PID_AAC_ENCPARAM,  &params)) {
-        ALOGE("Failed to set AAC encoder parameters");
-        return UNKNOWN_ERROR;
-    }
-
-    return OK;
-}
-
-static status_t getSampleRateTableIndex(int32_t sampleRate, int32_t &index) {
-    static const int32_t kSampleRateTable[] = {
-        96000, 88200, 64000, 48000, 44100, 32000,
-        24000, 22050, 16000, 12000, 11025, 8000
-    };
-    const int32_t tableSize =
-        sizeof(kSampleRateTable) / sizeof(kSampleRateTable[0]);
-
-    for (int32_t i = 0; i < tableSize; ++i) {
-        if (sampleRate == kSampleRateTable[i]) {
-            index = i;
-            return OK;
-        }
-    }
-
-    return UNKNOWN_ERROR;
-}
-
-status_t SoftAACEncoder::setAudioSpecificConfigData() {
-    // The AAC encoder's audio specific config really only encodes
-    // number of channels and the sample rate (mapped to an index into
-    // a fixed sample rate table).
-
-    int32_t index;
-    status_t err = getSampleRateTableIndex(mSampleRate, index);
-    if (err != OK) {
-        ALOGE("Unsupported sample rate (%u Hz)", mSampleRate);
-        return err;
-    }
-
-    if (mNumChannels > 2 || mNumChannels <= 0) {
-        ALOGE("Unsupported number of channels(%u)", mNumChannels);
-        return UNKNOWN_ERROR;
-    }
-
-    // OMX_AUDIO_AACObjectLC
-    mAudioSpecificConfigData[0] = ((0x02 << 3) | (index >> 1));
-    mAudioSpecificConfigData[1] = ((index & 0x01) << 7) | (mNumChannels << 3);
-
-    return OK;
-}
-
-void SoftAACEncoder::onQueueFilled(OMX_U32 /*portIndex*/) {
-    if (mSignalledError) {
-        return;
-    }
-
-    List<BufferInfo *> &inQueue = getPortQueue(0);
-    List<BufferInfo *> &outQueue = getPortQueue(1);
-
-    if (!mSentCodecSpecificData) {
-        // The very first thing we want to output is the codec specific
-        // data. It does not require any input data but we will need an
-        // output buffer to store it in.
-
-        if (outQueue.empty()) {
-            return;
-        }
-
-        BufferInfo *outInfo = *outQueue.begin();
-        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
-        outHeader->nFilledLen = sizeof(mAudioSpecificConfigData);
-        outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG;
-
-        uint8_t *out = outHeader->pBuffer + outHeader->nOffset;
-        memcpy(out, mAudioSpecificConfigData, sizeof(mAudioSpecificConfigData));
-
-#if 0
-        ALOGI("sending codec specific data.");
-        hexdump(out, sizeof(mAudioSpecificConfigData));
-#endif
-
-        outQueue.erase(outQueue.begin());
-        outInfo->mOwnedByUs = false;
-        notifyFillBufferDone(outHeader);
-
-        mSentCodecSpecificData = true;
-    }
-
-    size_t numBytesPerInputFrame =
-        mNumChannels * kNumSamplesPerFrame * sizeof(int16_t);
-
-    for (;;) {
-        // We do the following until we run out of buffers.
-
-        while (mInputSize < numBytesPerInputFrame) {
-            // As long as there's still input data to be read we
-            // will drain "kNumSamplesPerFrame * mNumChannels" samples
-            // into the "mInputFrame" buffer and then encode those
-            // as a unit into an output buffer.
-
-            if (mSawInputEOS || inQueue.empty()) {
-                return;
-            }
-
-            BufferInfo *inInfo = *inQueue.begin();
-            OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
-
-            const void *inData = inHeader->pBuffer + inHeader->nOffset;
-
-            size_t copy = numBytesPerInputFrame - mInputSize;
-            if (copy > inHeader->nFilledLen) {
-                copy = inHeader->nFilledLen;
-            }
-
-            if (mInputFrame == NULL) {
-                mInputFrame = new int16_t[kNumSamplesPerFrame * mNumChannels];
-            }
-
-            if (mInputSize == 0) {
-                mInputTimeUs = inHeader->nTimeStamp;
-            }
-
-            memcpy((uint8_t *)mInputFrame + mInputSize, inData, copy);
-            mInputSize += copy;
-
-            inHeader->nOffset += copy;
-            inHeader->nFilledLen -= copy;
-
-            // "Time" on the input buffer has in effect advanced by the
-            // number of audio frames we just advanced nOffset by.
-            inHeader->nTimeStamp +=
-                (copy * 1000000ll / mSampleRate)
-                    / (mNumChannels * sizeof(int16_t));
-
-            if (inHeader->nFilledLen == 0) {
-                if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
-                    ALOGV("saw input EOS");
-                    mSawInputEOS = true;
-
-                    // Pad any remaining data with zeroes.
-                    memset((uint8_t *)mInputFrame + mInputSize,
-                           0,
-                           numBytesPerInputFrame - mInputSize);
-
-                    mInputSize = numBytesPerInputFrame;
-                }
-
-                inQueue.erase(inQueue.begin());
-                inInfo->mOwnedByUs = false;
-                notifyEmptyBufferDone(inHeader);
-
-                inData = NULL;
-                inHeader = NULL;
-                inInfo = NULL;
-            }
-        }
-
-        // At this  point we have all the input data necessary to encode
-        // a single frame, all we need is an output buffer to store the result
-        // in.
-
-        if (outQueue.empty()) {
-            return;
-        }
-
-        BufferInfo *outInfo = *outQueue.begin();
-        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
-
-        VO_CODECBUFFER inputData;
-        memset(&inputData, 0, sizeof(inputData));
-        inputData.Buffer = (unsigned char *)mInputFrame;
-        inputData.Length = numBytesPerInputFrame;
-        CHECK((VO_U32)VO_ERR_NONE ==
-                mApiHandle->SetInputData(mEncoderHandle, &inputData));
-
-        VO_CODECBUFFER outputData;
-        memset(&outputData, 0, sizeof(outputData));
-        VO_AUDIO_OUTPUTINFO outputInfo;
-        memset(&outputInfo, 0, sizeof(outputInfo));
-
-        uint8_t *outPtr = (uint8_t *)outHeader->pBuffer + outHeader->nOffset;
-        size_t outAvailable = outHeader->nAllocLen - outHeader->nOffset;
-
-        VO_U32 ret = VO_ERR_NONE;
-        size_t nOutputBytes = 0;
-        do {
-            outputData.Buffer = outPtr;
-            outputData.Length = outAvailable - nOutputBytes;
-            ret = mApiHandle->GetOutputData(
-                    mEncoderHandle, &outputData, &outputInfo);
-            if (ret == VO_ERR_NONE) {
-                outPtr += outputData.Length;
-                nOutputBytes += outputData.Length;
-            }
-        } while (ret != VO_ERR_INPUT_BUFFER_SMALL);
-
-        outHeader->nFilledLen = nOutputBytes;
-
-        outHeader->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
-
-        if (mSawInputEOS) {
-            // We also tag this output buffer with EOS if it corresponds
-            // to the final input buffer.
-            outHeader->nFlags = OMX_BUFFERFLAG_EOS;
-        }
-
-        outHeader->nTimeStamp = mInputTimeUs;
-
-#if 0
-        ALOGI("sending %d bytes of data (time = %lld us, flags = 0x%08lx)",
-              nOutputBytes, mInputTimeUs, outHeader->nFlags);
-
-        hexdump(outHeader->pBuffer + outHeader->nOffset, outHeader->nFilledLen);
-#endif
-
-        outQueue.erase(outQueue.begin());
-        outInfo->mOwnedByUs = false;
-        notifyFillBufferDone(outHeader);
-
-        outHeader = NULL;
-        outInfo = NULL;
-
-        mInputSize = 0;
-    }
-}
-
-void SoftAACEncoder::onReset() {
-    delete[] mInputFrame;
-    mInputFrame = NULL;
-    mInputSize = 0;
-
-    mSentCodecSpecificData = false;
-    mInputTimeUs = -1ll;
-    mSawInputEOS = false;
-    mSignalledError = false;
-}
-
-}  // namespace android
-
-android::SoftOMXComponent *createSoftOMXComponent(
-        const char *name, const OMX_CALLBACKTYPE *callbacks,
-        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
-    return new android::SoftAACEncoder(name, callbacks, appData, component);
-}
diff --git a/media/libstagefright/codecs/aacenc/SoftAACEncoder.h b/media/libstagefright/codecs/aacenc/SoftAACEncoder.h
deleted file mode 100644
index e64c1b7..0000000
--- a/media/libstagefright/codecs/aacenc/SoftAACEncoder.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2012 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 SOFT_AAC_ENCODER_H_
-
-#define SOFT_AAC_ENCODER_H_
-
-#include <media/stagefright/omx/SimpleSoftOMXComponent.h>
-
-struct VO_AUDIO_CODECAPI;
-struct VO_MEM_OPERATOR;
-
-namespace android {
-
-struct SoftAACEncoder : public SimpleSoftOMXComponent {
-    SoftAACEncoder(
-            const char *name,
-            const OMX_CALLBACKTYPE *callbacks,
-            OMX_PTR appData,
-            OMX_COMPONENTTYPE **component);
-
-protected:
-    virtual ~SoftAACEncoder();
-
-    virtual OMX_ERRORTYPE internalGetParameter(
-            OMX_INDEXTYPE index, OMX_PTR params);
-
-    virtual OMX_ERRORTYPE internalSetParameter(
-            OMX_INDEXTYPE index, const OMX_PTR params);
-
-    virtual void onQueueFilled(OMX_U32 portIndex);
-
-    virtual void onReset();
-
-private:
-    enum {
-        kNumBuffers             = 4,
-        kNumSamplesPerFrame     = 1024,
-    };
-
-    void *mEncoderHandle;
-    VO_AUDIO_CODECAPI *mApiHandle;
-    VO_MEM_OPERATOR  *mMemOperator;
-
-    OMX_U32 mNumChannels;
-    OMX_U32 mSampleRate;
-    OMX_U32 mBitRate;
-
-    bool mSentCodecSpecificData;
-    size_t mInputSize;
-    int16_t *mInputFrame;
-    int64_t mInputTimeUs;
-
-    bool mSawInputEOS;
-
-    uint8_t mAudioSpecificConfigData[2];
-
-    bool mSignalledError;
-
-    void initPorts();
-    status_t initEncoder();
-
-    status_t setAudioSpecificConfigData();
-    status_t setAudioParams();
-
-    DISALLOW_EVIL_CONSTRUCTORS(SoftAACEncoder);
-};
-
-}  // namespace android
-
-#endif  // SOFT_AAC_ENCODER_H_
diff --git a/media/libstagefright/codecs/aacenc/basic_op/basic_op.h b/media/libstagefright/codecs/aacenc/basic_op/basic_op.h
deleted file mode 100644
index bbc753b..0000000
--- a/media/libstagefright/codecs/aacenc/basic_op/basic_op.h
+++ /dev/null
@@ -1,1168 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		basicop2.h
-
-	Content:	Constants , Globals and Basic arithmetic operators.
-
-*******************************************************************************/
-
-#ifndef __BASIC_OP_H
-#define __BASIC_OP_H
-
-#include "typedef.h"
-
-#define MAX_32 (Word32)0x7fffffffL
-#define MIN_32 (Word32)0x80000000L
-
-#define MAX_16 (Word16)0x7fff
-#define MIN_16 (Word16)0x8000
-#define ABS(a)	((a) >= 0) ? (a) : (-(a))
-
-/* Short abs,           1   */
-#define abs_s(x)       ((Word16)(((x) != MIN_16) ? (((x) >= 0) ? (x) : (-(x))) : MAX_16))
-
-/* 16 bit var1 -> MSB,     2 */
-#define L_deposit_h(x) (((Word32)(x)) << 16)
-
-
-/* 16 bit var1 -> LSB,     2 */
-#define L_deposit_l(x) ((Word32)(x))
-
-
-/* Long abs,              3  */
-#define L_abs(x) (((x) != MIN_32) ? (((x) >= 0) ? (x) : (-(x))) : MAX_32)
-
-
-/* Short negate,        1   */
-#define negate(var1) ((Word16)(((var1) == MIN_16) ? MAX_16 : (-(var1))))
-
-
-/* Long negate,     2 */
-#define L_negate(L_var1) (((L_var1) == (MIN_32)) ? (MAX_32) : (-(L_var1)))
-
-
-#define MULHIGH(A,B) (int)(((Word64)(A)*(Word64)(B)) >> 32)
-#define fixmul(a, b) (int)((((Word64)(a)*(Word64)(b)) >> 32) << 1)
-
-
-#if  (SATRUATE_IS_INLINE)
-__inline Word16 saturate(Word32 L_var1);
-#else
-Word16 saturate(Word32 L_var1);
-#endif
-
-/* Short shift left,    1   */
-#if (SHL_IS_INLINE)
-__inline Word16 shl (Word16 var1, Word16 var2);
-#else
-Word16 shl (Word16 var1, Word16 var2);
-#endif
-
-/* Short shift right,   1   */
-#if (SHR_IS_INLINE)
-__inline Word16 shr (Word16 var1, Word16 var2);
-#else
-Word16 shr (Word16 var1, Word16 var2);
-#endif
-
-#if (L_MULT_IS_INLINE)
-__inline Word32 L_mult(Word16 var1, Word16 var2);
-#else
-Word32 L_mult(Word16 var1, Word16 var2);
-#endif
-
-/* Msu,  1  */
-#if (L_MSU_IS_INLINE)
-__inline Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);
-#else
-Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);
-#endif
-
-/* Long sub,        2 */
-#if (L_SUB_IS_INLINE)
-__inline Word32 L_sub(Word32 L_var1, Word32 L_var2);
-#else
-Word32 L_sub(Word32 L_var1, Word32 L_var2);
-#endif
-
-/* Long shift left, 2 */
-#if (L_SHL_IS_INLINE)
-__inline Word32 L_shl (Word32 L_var1, Word16 var2);
-#else
-Word32 L_shl (Word32 L_var1, Word16 var2);
-#endif
-
-/* Long shift right, 2*/
-#if (L_SHR_IS_INLINE)
-__inline Word32 L_shr (Word32 L_var1, Word16 var2);
-#else
-Word32 L_shr (Word32 L_var1, Word16 var2);
-#endif
-
-/* Short add,           1   */
-#if (ADD_IS_INLINE)
-__inline Word16 add (Word16 var1, Word16 var2);
-#else
-Word16 add (Word16 var1, Word16 var2);
-#endif
-
-/* Short sub,           1   */
-#if (SUB_IS_INLINE)
-__inline Word16 sub(Word16 var1, Word16 var2);
-#else
-Word16 sub(Word16 var1, Word16 var2);
-#endif
-
-/* Short division,       18  */
-#if (DIV_S_IS_INLINE)
-__inline Word16 div_s (Word16 var1, Word16 var2);
-#else
-Word16 div_s (Word16 var1, Word16 var2);
-#endif
-
-/* Short mult,          1   */
-#if (MULT_IS_INLINE)
-__inline Word16 mult (Word16 var1, Word16 var2);
-#else
-Word16 mult (Word16 var1, Word16 var2);
-#endif
-
-/* Short norm,           15  */
-#if (NORM_S_IS_INLINE)
-__inline Word16 norm_s (Word16 var1);
-#else
-Word16 norm_s (Word16 var1);
-#endif
-
-/* Long norm,            30  */
-#if (NORM_L_IS_INLINE)
-__inline Word16 norm_l (Word32 L_var1);
-#else
-Word16 norm_l (Word32 L_var1);
-#endif
-
-/* Round,               1   */
-#if (ROUND_IS_INLINE)
-__inline Word16 round16(Word32 L_var1);
-#else
-Word16 round16(Word32 L_var1);
-#endif
-
-/* Mac,  1  */
-#if (L_MAC_IS_INLINE)
-__inline Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);
-#else
-Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);
-#endif
-
-#if (L_ADD_IS_INLINE)
-__inline Word32 L_add (Word32 L_var1, Word32 L_var2);
-#else
-Word32 L_add (Word32 L_var1, Word32 L_var2);
-#endif
-
-/* Extract high,        1   */
-#if (EXTRACT_H_IS_INLINE)
-__inline Word16 extract_h (Word32 L_var1);
-#else
-Word16 extract_h (Word32 L_var1);
-#endif
-
-/* Extract low,         1   */
-#if (EXTRACT_L_IS_INLINE)
-__inline Word16 extract_l(Word32 L_var1);
-#else
-Word16 extract_l(Word32 L_var1);
-#endif
-
-/* Mult with round, 2 */
-#if (MULT_R_IS_INLINE)
-__inline Word16 mult_r(Word16 var1, Word16 var2);
-#else
-Word16 mult_r(Word16 var1, Word16 var2);
-#endif
-
-/* Shift right with round, 2           */
-#if (SHR_R_IS_INLINE)
-__inline Word16 shr_r (Word16 var1, Word16 var2);
-#else
-Word16 shr_r (Word16 var1, Word16 var2);
-#endif
-
-/* Mac with rounding,2 */
-#if (MAC_R_IS_INLINE)
-__inline Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2);
-#else
-Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2);
-#endif
-
-/* Msu with rounding,2 */
-#if (MSU_R_IS_INLINE)
-__inline Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2);
-#else
-Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2);
-#endif
-
-/* Long shift right with round,  3             */
-#if (L_SHR_R_IS_INLINE)
-__inline Word32 L_shr_r (Word32 L_var1, Word16 var2);
-#else
-Word32 L_shr_r (Word32 L_var1, Word16 var2);
-#endif
-
-#if ARMV4_INASM
-__inline Word32 ASM_L_shr(Word32 L_var1, Word16 var2)
-{
-	return L_var1 >> var2;
-}
-
-__inline Word32 ASM_L_shl(Word32 L_var1, Word16 var2)
-{
-	Word32 result;
-	asm (
-		"MOV	%[result], %[L_var1], ASL %[var2] \n"
-		"TEQ	%[L_var1], %[result], ASR %[var2]\n"
-		"EORNE  %[result], %[mask], %[L_var1], ASR #31\n"
-		:[result]"=&r"(result)
-		:[L_var1]"r"(L_var1), [var2]"r"(var2), [mask]"r"(0x7fffffff)
-		);
-	return result;
-}
-
-__inline Word32 ASM_shr(Word32 L_var1, Word16 var2)
-{
-	Word32 result;
-	asm (
-		"CMP	%[var2], #15\n"
-		"MOVLT	%[result], %[L_var1], ASR %[var2]\n"
-		"MOVGE	%[result], %[L_var1], ASR #15\n"
-		:[result]"=r"(result)
-		:[L_var1]"r"(L_var1), [var2]"r"(var2)
-		);
-	return result;
-}
-
-__inline Word32 ASM_shl(Word32 L_var1, Word16 var2)
-{
-#if ARMV6_SAT
-	Word32 result;
-	asm (
-		"CMP	%[var2], #16\n"
-		"MOVLT  %[result], %[L_var1], ASL %[var2]\n"
-		"MOVGE  %[result], %[L_var1], ASL #16\n"
-		"SSAT   %[result], #16, %[result]\n"
-		:[result]"=r"(result)
-		:[L_var1]"r"(L_var1), [var2]"r"(var2)
-		);
-	return result;
-#else
-	Word32 result;
-	Word32 tmp;
-	asm (
-		"CMP	%[var2], #16\n"
-		"MOVLT  %[result], %[L_var1], ASL %[var2]\n"
-		"MOVGE  %[result], %[L_var1], ASL #16\n"
-        "MOV    %[tmp], %[result], ASR #15\n"
-        "TEQ    %[tmp], %[result], ASR #31 \n"
-        "EORNE  %[result], %[mask], %[result],ASR #31"
-		:[result]"=&r"(result), [tmp]"=&r"(tmp)
-		:[L_var1]"r"(L_var1), [var2]"r"(var2), [mask]"r"(0x7fff)
-		);
-	return result;
-#endif
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   definitions for inline basic arithmetic operators                       |
- |___________________________________________________________________________|
-*/
-#if (SATRUATE_IS_INLINE)
-__inline Word16 saturate(Word32 L_var1)
-{
-#if ARMV6_SAT
-    Word16 result;
-	asm (
-		"SSAT %[result], #16, %[L_var1]"
-		: [result]"=r"(result)
-		: [L_var1]"r"(L_var1)
-		);
-	return result;
-#elif ARMV5TE_SAT
-	Word16 result;
-	Word32 tmp;
-	asm volatile (
-		"MOV	%[tmp], %[L_var1],ASR#15\n"
-		"TEQ	%[tmp], %[L_var1],ASR#31\n"
-		"EORNE	%[result], %[mask],%[L_var1],ASR#31\n"
-		"MOVEQ	%[result], %[L_var1]\n"
-		:[result]"=&r"(result), [tmp]"=&r"(tmp)
-		:[L_var1]"r"(L_var1), [mask]"r"(0x7fff)
-	);
-
-	return result;
-#else
-    Word16 var_out;
-
-    //var_out = (L_var1 > (Word32)0X00007fffL) ? (MAX_16) : ((L_var1 < (Word32)0xffff8000L) ? (MIN_16) : ((Word16)L_var1));
-
-    if (L_var1 > 0X00007fffL)
-    {
-        var_out = MAX_16;
-    }
-    else if (L_var1 < (Word32) 0xffff8000L)
-    {
-        var_out = MIN_16;
-    }
-    else
-    {
-        var_out = extract_l(L_var1);
-    }
-
-    return (var_out);
-#endif
-}
-#endif
-
-/* Short shift left,    1   */
-#if (SHL_IS_INLINE)
-__inline Word16 shl (Word16 var1, Word16 var2)
-{
-#if ARMV5TE_SHL
-	if(var2>=0)
-	{
-		return ASM_shl( var1, var2);
-	}
-	else
-	{
-		return ASM_shr( var1, -var2);
-	}
-#else
-    Word16 var_out;
-    Word32 result;
-
-    if (var2 < 0)
-    {
-        var_out = shr (var1, (Word16)-var2);
-    }
-    else
-    {
-        result = (Word32) var1 *((Word32) 1 << var2);
-
-        if ((var2 > 15 && var1 != 0) || (result != (Word32) ((Word16) result)))
-        {
-            var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);
-        }
-        else
-        {
-            var_out = extract_l(result);
-        }
-    }
-    return (var_out);
-#endif
-}
-#endif
-
-/* Short shift right,   1   */
-#if (SHR_IS_INLINE)
-__inline Word16 shr (Word16 var1, Word16 var2)
-{
-#if ARMV5TE_SHR
-	if(var2>=0)
-	{
-		return  ASM_shr( var1, var2);
-	}
-	else
-	{
-		return  ASM_shl( var1, -var2);
-	}
-#else
-    Word16 var_out;
-
-    if (var2 < 0)
-    {
-        var_out = shl (var1, (Word16)-var2);
-    }
-    else
-    {
-        if (var2 >= 15)
-        {
-            var_out = (Word16)((var1 < 0) ? -1 : 0);
-        }
-        else
-        {
-            if (var1 < 0)
-            {
-                var_out = (Word16)(~((~var1) >> var2));
-            }
-            else
-            {
-                var_out = (Word16)(var1 >> var2);
-            }
-        }
-    }
-
-    return (var_out);
-#endif
-}
-#endif
-
-
-#if (L_MULT_IS_INLINE)
-__inline Word32 L_mult(Word16 var1, Word16 var2)
-{
-#if ARMV5TE_L_MULT
-	Word32 result;
-	asm (
-		"SMULBB %[result], %[var1], %[var2] \n"
-		"QADD %[result], %[result], %[result] \n"
-		:[result]"=r"(result)
-		:[var1]"r"(var1), [var2]"r"(var2)
-		);
-	return result;
-#else
-    Word32 L_var_out;
-
-    L_var_out = (Word32) var1 *(Word32) var2;
-
-    if (L_var_out != (Word32) 0x40000000L)
-    {
-        L_var_out <<= 1;
-    }
-    else
-    {
-        L_var_out = MAX_32;
-    }
-    return (L_var_out);
-#endif
-}
-#endif
-
-#if (L_MSU_IS_INLINE)
-__inline Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2)
-{
-#if ARMV5TE_L_MSU
-	Word32 result;
-	asm (
-		"SMULBB %[result], %[var1], %[var2] \n"
-		"QDSUB %[result], %[L_var3], %[result]\n"
-		:[result]"=&r"(result)
-		:[L_var3]"r"(L_var3), [var1]"r"(var1), [var2]"r"(var2)
-		);
-	return result;
-#else
-    Word32 L_var_out;
-    Word32 L_product;
-
-    L_product = L_mult(var1, var2);
-    L_var_out = L_sub(L_var3, L_product);
-    return (L_var_out);
-#endif
-}
-#endif
-
-#if (L_SUB_IS_INLINE)
-__inline Word32 L_sub(Word32 L_var1, Word32 L_var2)
-{
-#if ARMV5TE_L_SUB
-	Word32 result;
-	asm (
-		"QSUB %[result], %[L_var1], %[L_var2]\n"
-		:[result]"=r"(result)
-		:[L_var1]"r"(L_var1), [L_var2]"r"(L_var2)
-		);
-	return result;
-#else
-    Word32 L_var_out;
-
-    L_var_out = L_var1 - L_var2;
-
-    if (((L_var1 ^ L_var2) & MIN_32) != 0)
-    {
-        if ((L_var_out ^ L_var1) & MIN_32)
-        {
-            L_var_out = (L_var1 < 0L) ? MIN_32 : MAX_32;
-        }
-    }
-
-    return (L_var_out);
-#endif
-}
-#endif
-
-#if (L_SHL_IS_INLINE)
-__inline Word32 L_shl(Word32 L_var1, Word16 var2)
-{
-#if ARMV5TE_L_SHL
-    if(var2>=0)
-    {
-        return  ASM_L_shl( L_var1, var2);
-    }
-    else
-    {
-        return  ASM_L_shr( L_var1, -var2);
-    }
-#else
-    if (var2 <= 0)
-    {
-        L_var1 = L_shr(L_var1, (Word16)-var2);
-    }
-    else
-    {
-        for (; var2 > 0; var2--)
-        {
-            if (L_var1 > (Word32) 0X3fffffffL)
-            {
-                return MAX_32;
-            }
-            else
-            {
-                if (L_var1 < (Word32) 0xc0000000L)
-                {
-                    return MIN_32;
-                }
-            }
-            L_var1 <<= 1;
-        }
-    }
-    return (L_var1);
-#endif
-}
-#endif
-
-#if (L_SHR_IS_INLINE)
-__inline Word32 L_shr (Word32 L_var1, Word16 var2)
-{
-#if ARMV5TE_L_SHR
-	if(var2>=0)
-	{
-		return ASM_L_shr( L_var1, var2);
-	}
-	else
-	{
-		return ASM_L_shl( L_var1, -var2);
-	}
-#else
-    Word32 L_var_out;
-
-    if (var2 < 0)
-    {
-        L_var_out = L_shl (L_var1, (Word16)-var2);
-    }
-    else
-    {
-        if (var2 >= 31)
-        {
-            L_var_out = (L_var1 < 0L) ? -1 : 0;
-        }
-        else
-        {
-            if (L_var1 < 0)
-            {
-                L_var_out = ~((~L_var1) >> var2);
-            }
-            else
-            {
-                L_var_out = L_var1 >> var2;
-            }
-        }
-    }
-    return (L_var_out);
-#endif
-}
-#endif
-
-/* Short add,           1   */
-#if (ADD_IS_INLINE)
-__inline Word16 add (Word16 var1, Word16 var2)
-{
-#if ARMV5TE_ADD
-	Word32 result;
-	Word32 tmp;
-	asm (
-		"ADD  %[result], %[var1], %[var2] \n"
-		"MOV  %[tmp], %[result], ASR #15 \n"
-		"TEQ  %[tmp], %[result], ASR #31 \n"
-		"EORNE %[result], %[mask], %[result], ASR #31"
-		:[result]"=&r"(result), [tmp]"=&r"(tmp)
-		:[var1]"r"(var1), [var2]"r"(var2), [mask]"r"(0x7fff)
-		);
-	return result;
-#else
-    Word16 var_out;
-    Word32 L_sum;
-
-    L_sum = (Word32) var1 + var2;
-    var_out = saturate(L_sum);
-
-    return (var_out);
-#endif
-}
-#endif
-
-/* Short sub,           1   */
-#if (SUB_IS_INLINE)
-__inline Word16 sub(Word16 var1, Word16 var2)
-{
-#if ARMV5TE_SUB
-	Word32 result;
-	Word32 tmp;
-	asm (
-		"SUB   %[result], %[var1], %[var2] \n"
-		"MOV   %[tmp], %[var1], ASR #15 \n"
-		"TEQ   %[tmp], %[var1], ASR #31 \n"
-		"EORNE %[result], %[mask], %[result], ASR #31 \n"
-		:[result]"=&r"(result), [tmp]"=&r"(tmp)
-		:[var1]"r"(var1), [var2]"r"(var2), [mask]"r"(0x7fff)
-		);
-	return result;
-#else
-    Word16 var_out;
-    Word32 L_diff;
-
-    L_diff = (Word32) var1 - var2;
-    var_out = saturate(L_diff);
-
-    return (var_out);
-#endif
-}
-#endif
-
-/* Short division,       18  */
-#if (DIV_S_IS_INLINE)
-__inline Word16 div_s (Word16 var1, Word16 var2)
-{
-    Word16 var_out = 0;
-    Word16 iteration;
-    Word32 L_num;
-    Word32 L_denom;
-
-    var_out = MAX_16;
-    if (var1!= var2)//var1!= var2
-    {
-    	var_out = 0;
-    	L_num = (Word32) var1;
-
-    	L_denom = (Word32) var2;
-
-		//return (L_num<<15)/var2;
-
-    	for (iteration = 0; iteration < 15; iteration++)
-    	{
-    		var_out <<= 1;
-    		L_num <<= 1;
-
-    		if (L_num >= L_denom)
-    		{
-    			L_num -= L_denom;
-    			var_out++;
-    		}
-    	}
-    }
-    return (var_out);
-}
-#endif
-
-/* Short mult,          1   */
-#if (MULT_IS_INLINE)
-__inline Word16 mult (Word16 var1, Word16 var2)
-{
-#if ARMV5TE_MULT && ARMV6_SAT
-	Word32 result;
-	asm (
-		"SMULBB %[result], %[var1], %[var2] \n"
-		"SSAT   %[result], #16, %[result], ASR #15 \n"
-		:[result]"=r"(result)
-		:[var1]"r"(var1), [var2]"r"(var2)
-		);
-	return result;
-#elif ARMV5TE_MULT
-	Word32 result, tmp;
-	asm (
-		"SMULBB %[tmp], %[var1], %[var2] \n"
-		"MOV	%[result], %[tmp], ASR #15\n"
-		"MOV	%[tmp], %[result], ASR #15\n"
-		"TEQ	%[tmp], %[result], ASR #31\n"
-		"EORNE  %[result], %[mask], %[result], ASR #31 \n"
-		:[result]"=&r"(result), [tmp]"=&r"(tmp)
-		:[var1]"r"(var1), [var2]"r"(var2), [mask]"r"(0x7fff)
-		);
-	return result;
-#else
-    Word16 var_out;
-    Word32 L_product;
-
-    L_product = (Word32) var1 *(Word32) var2;
-    L_product = (L_product & (Word32) 0xffff8000L) >> 15;
-    if (L_product & (Word32) 0x00010000L)
-        L_product = L_product | (Word32) 0xffff0000L;
-    var_out = saturate(L_product);
-
-    return (var_out);
-#endif
-}
-#endif
-
-
-/* Short norm,           15  */
-#if (NORM_S_IS_INLINE)
-__inline Word16 norm_s (Word16 var1)
-{
-#if ARMV5TE_NORM_S
-	Word16 result;
-	Word32 tmp;
-	asm (
-		"RSBS  %[tmp], %[var1], #0 \n"
-		"CLZLT %[result], %[var1]\n"
-		"CLZGT %[result], %[tmp]\n"
-		"SUBNE %[result], %[result], #17\n"
-		"MOVEQ %[result], #0\n"
-		"CMP   %[var1], #-1\n"
-		"MOVEQ %[result], #15\n"
-		:[result]"=&r"(result), [tmp]"=&r"(tmp)
-		:[var1]"r"(var1)
-		);
-	return result;
-#else
-    Word16 var_out;
-
-    if (var1 == 0)
-    {
-        var_out = 0;
-    }
-    else
-    {
-        if (var1 == -1)
-        {
-            var_out = 15;
-        }
-        else
-        {
-            if (var1 < 0)
-            {
-                var1 = (Word16)~var1;
-            }
-            for (var_out = 0; var1 < 0x4000; var_out++)
-            {
-                var1 <<= 1;
-            }
-        }
-    }
-    return (var_out);
-#endif
-}
-#endif
-
-/* Long norm,            30  */
-#if (NORM_L_IS_INLINE)
-__inline Word16 norm_l (Word32 L_var1)
-{
-#if ARMV5TE_NORM_L
-	Word16 result;
-	asm volatile(
-		"CMP    %[L_var1], #0\n"
-		"CLZNE  %[result], %[L_var1]\n"
-		"SUBNE  %[result], %[result], #1\n"
-		"MOVEQ  %[result], #0\n"
-		:[result]"=r"(result)
-		:[L_var1]"r"(L_var1)
-		);
-	return result;
-#else
-    //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;
-    //        }
-    //    }
-    //}
-    //return (var_out);
-  Word16 a16;
-  Word16 r = 0 ;
-
-
-  if ( L_var1 < 0 ) {
-    L_var1 = ~L_var1;
-  }
-
-  if (0 == (L_var1 & 0x7fff8000)) {
-    a16 = extract_l(L_var1);
-    r += 16;
-
-    if (0 == (a16 & 0x7f80)) {
-      r += 8;
-
-      if (0 == (a16 & 0x0078)) {
-        r += 4;
-
-        if (0 == (a16 & 0x0006)) {
-          r += 2;
-
-          if (0 == (a16 & 0x0001)) {
-            r += 1;
-          }
-        }
-        else {
-
-          if (0 == (a16 & 0x0004)) {
-            r += 1;
-          }
-        }
-      }
-      else {
-
-        if (0 == (a16 & 0x0060)) {
-          r += 2;
-
-          if (0 == (a16 & 0x0010)) {
-            r += 1;
-          }
-        }
-        else {
-
-          if (0 == (a16 & 0x0040)) {
-            r += 1;
-          }
-        }
-      }
-    }
-    else {
-
-      if (0 == (a16 & 0x7800)) {
-        r += 4;
-
-        if (0 == (a16 & 0x0600)) {
-          r += 2;
-
-          if (0 == (a16 & 0x0100)) {
-            r += 1;
-          }
-        }
-        else {
-
-          if (0 == (a16 & 0x0400)) {
-            r += 1;
-          }
-        }
-      }
-      else {
-
-        if (0 == (a16 & 0x6000)) {
-          r += 2;
-
-          if (0 == (a16 & 0x1000)) {
-            r += 1;
-          }
-        }
-        else {
-
-          if (0 == (a16 & 0x4000)) {
-            r += 1;
-          }
-        }
-      }
-    }
-  }
-  else {
-    a16 = extract_h(L_var1);
-
-    if (0 == (a16 & 0x7f80)) {
-      r += 8;
-
-      if (0 == (a16 & 0x0078)) {
-        r += 4 ;
-
-        if (0 == (a16 & 0x0006)) {
-          r += 2;
-
-          if (0 == (a16 & 0x0001)) {
-            r += 1;
-          }
-        }
-        else {
-
-          if (0 == (a16 & 0x0004)) {
-            r += 1;
-          }
-        }
-      }
-      else {
-
-        if (0 == (a16 & 0x0060)) {
-          r += 2;
-
-          if (0 == (a16 & 0x0010)) {
-            r += 1;
-          }
-        }
-        else {
-
-          if (0 == (a16 & 0x0040)) {
-            r += 1;
-          }
-        }
-      }
-    }
-    else {
-
-      if (0 == (a16 & 0x7800)) {
-        r += 4;
-
-        if (0 == (a16 & 0x0600)) {
-          r += 2;
-
-          if (0 == (a16 & 0x0100)) {
-            r += 1;
-          }
-        }
-        else {
-
-          if (0 == (a16 & 0x0400)) {
-            r += 1;
-          }
-        }
-      }
-      else {
-
-        if (0 == (a16 & 0x6000)) {
-          r += 2;
-
-          if (0 == (a16 & 0x1000)) {
-            r += 1;
-          }
-        }
-        else {
-
-          if (0 == (a16 & 0x4000)) {
-            return 1;
-          }
-        }
-      }
-    }
-  }
-
-  return r ;
-#endif
-}
-#endif
-
-/* Round,               1   */
-#if (ROUND_IS_INLINE)
-__inline Word16 round16(Word32 L_var1)
-{
-#if ARMV5TE_ROUND
-	Word16 result;
-	asm (
-		"QADD  %[result], %[L_var1], %[bias]\n"
-		"MOV   %[result], %[result], ASR #16 \n"
-		:[result]"=r"(result)
-		:[L_var1]"r"(L_var1), [bias]"r"(0x8000)
-		);
-	return result;
-#else
-    Word16 var_out;
-    Word32 L_rounded;
-
-    L_rounded = L_add (L_var1, (Word32) 0x00008000L);
-    var_out = extract_h (L_rounded);
-    return (var_out);
-#endif
-}
-#endif
-
-/* Mac,  1  */
-#if (L_MAC_IS_INLINE)
-__inline Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2)
-{
-#if ARMV5TE_L_MAC
-	Word32 result;
-	asm (
-		"SMULBB %[result], %[var1], %[var2]\n"
-		"QDADD  %[result], %[L_var3], %[result]\n"
-		:[result]"=&r"(result)
-		: [L_var3]"r"(L_var3), [var1]"r"(var1), [var2]"r"(var2)
-		);
-	return result;
-#else
-    Word32 L_var_out;
-    Word32 L_product;
-
-    L_product = L_mult(var1, var2);
-    L_var_out = L_add (L_var3, L_product);
-    return (L_var_out);
-#endif
-}
-#endif
-
-#if (L_ADD_IS_INLINE)
-__inline Word32 L_add (Word32 L_var1, Word32 L_var2)
-{
-#if ARMV5TE_L_ADD
-	Word32 result;
-	asm (
-		"QADD %[result], %[L_var1], %[L_var2]\n"
-		:[result]"=r"(result)
-		:[L_var1]"r"(L_var1), [L_var2]"r"(L_var2)
-		);
-	return result;
-#else
-    Word32 L_var_out;
-
-    L_var_out = L_var1 + L_var2;
-    if (((L_var1 ^ L_var2) & MIN_32) == 0)
-    {
-        if ((L_var_out ^ L_var1) & MIN_32)
-        {
-            L_var_out = (L_var1 < 0) ? MIN_32 : MAX_32;
-        }
-    }
-    return (L_var_out);
-#endif
-}
-#endif
-
-
-
-#if (MULT_R_IS_INLINE)
-__inline Word16 mult_r (Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-    Word32 L_product_arr;
-
-    L_product_arr = (Word32)var1 *(Word32)var2;       /* product */
-    L_product_arr += (Word32)0x00004000L;      /* round */
-    L_product_arr >>= 15;       /* shift */
-
-    var_out = saturate(L_product_arr);
-
-    return (var_out);
-}
-#endif
-
-#if (SHR_R_IS_INLINE)
-__inline Word16 shr_r (Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-
-    if (var2 > 15)
-    {
-        var_out = 0;
-    }
-    else
-    {
-        var_out = shr(var1, var2);
-
-        if (var2 > 0)
-        {
-            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)
-            {
-                var_out++;
-            }
-        }
-    }
-
-    return (var_out);
-}
-#endif
-
-#if (MAC_R_IS_INLINE)
-__inline Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-
-    L_var3 = L_mac (L_var3, var1, var2);
-    var_out = (Word16)((L_var3 + 0x8000L) >> 16);
-
-    return (var_out);
-}
-#endif
-
-#if (MSU_R_IS_INLINE)
-__inline Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-
-    L_var3 = L_msu (L_var3, var1, var2);
-    var_out = (Word16)((L_var3 + 0x8000L) >> 16);
-
-    return (var_out);
-}
-#endif
-
-#if (L_SHR_R_IS_INLINE)
-__inline Word32 L_shr_r (Word32 L_var1, Word16 var2)
-{
-    Word32 L_var_out;
-
-    if (var2 > 31)
-    {
-        L_var_out = 0;
-    }
-    else
-    {
-        L_var_out = L_shr(L_var1, var2);
-
-        if (var2 > 0)
-        {
-            if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)
-            {
-                L_var_out++;
-            }
-        }
-    }
-
-    return (L_var_out);
-}
-#endif
-
-#if (EXTRACT_H_IS_INLINE)
-__inline Word16 extract_h (Word32 L_var1)
-{
-    Word16 var_out;
-
-    var_out = (Word16) (L_var1 >> 16);
-
-    return (var_out);
-}
-#endif
-
-#if (EXTRACT_L_IS_INLINE)
-__inline Word16 extract_l(Word32 L_var1)
-{
-	return (Word16) L_var1;
-}
-#endif
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/basic_op/basicop2.c b/media/libstagefright/codecs/aacenc/basic_op/basicop2.c
deleted file mode 100644
index d43bbd9..0000000
--- a/media/libstagefright/codecs/aacenc/basic_op/basicop2.c
+++ /dev/null
@@ -1,1624 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		basicop2.c
-
-	Content:	Basic arithmetic operators.
-
-*******************************************************************************/
-
-#include "typedef.h"
-#include "basic_op.h"
-
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Functions                                                               |
- |___________________________________________________________________________|
-*/
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : saturate                                                |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |    Limit the 32 bit input to the range of a 16 bit word.                  |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1                                                                 |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-
-#if (!SATRUATE_IS_INLINE)
-Word16 saturate(Word32 L_var1)
-{
-    Word16 var_out;
-
-    if (L_var1 > 0X00007fffL)
-    {
-        var_out = MAX_16;
-    }
-    else if (L_var1 < (Word32) 0xffff8000L)
-    {
-        var_out = MIN_16;
-    }
-    else
-    {
-        var_out = extract_l(L_var1);
-    }
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : add                                                     |
- |                                                                           |
- |   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.                                                 |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-
-#if (!ADD_IS_INLINE)
-Word16 add (Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-    Word32 L_sum;
-
-    L_sum = (Word32)var1 + (Word32)var2;
-    var_out = saturate(L_sum);
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : sub                                                     |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |    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.                                          |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-#if (!SUB_IS_INLINE)
-Word16 sub(Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-    Word32 L_diff;
-
-    L_diff = (Word32) var1 - var2;
-    var_out = saturate(L_diff);
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : abs_s                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |    Absolute value of var1; abs_s(-32768) = 32767.                         |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    var1                                                                   |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0x0000 0000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-//Word16 abs_s (Word16 var1)
-//{
-//    Word16 var_out;
-//
-//    if (var1 == MIN_16)
-//    {
-//        var_out = MAX_16;
-//    }
-//    else
-//    {
-//        if (var1 < 0)
-//        {
-//            var_out = (Word16)-var1;
-//        }
-//        else
-//        {
-//            var_out = var1;
-//        }
-//    }
-//
-//    return (var_out);
-//}
-
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : shl                                                     |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   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.                                                |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-
-#if (!SHL_IS_INLINE)
-Word16 shl (Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-    Word32 result;
-
-    if (var2 < 0)
-    {
-        if (var2 < -16)
-            var2 = -16;
-        var_out = shr (var1, (Word16)-var2);
-    }
-    else
-    {
-        result = (Word32) var1 *((Word32) 1 << var2);
-
-        if ((var2 > 15 && var1 != 0) || (result != (Word32) ((Word16) result)))
-        {
-            //Overflow = 1;
-            var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);
-        }
-        else
-        {
-            var_out = extract_l(result);
-        }
-    }
-
-    return (var_out);
-}
-#endif
-// end
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : shr                                                     |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Arithmetically shift 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.                                                              |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-
-#if (!SHR_IS_INLINE)
-Word16 shr (Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-
-    if (var2 < 0)
-    {
-        if (var2 < -16)
-            var2 = -16;
-        var_out = shl (var1, (Word16)-var2);
-    }
-    else
-    {
-        if (var2 >= 15)
-        {
-            var_out = (Word16)((var1 < 0) ? -1 : 0);
-        }
-        else
-        {
-            if (var1 < 0)
-            {
-                var_out = (Word16)(~((~var1) >> var2));
-            }
-            else
-            {
-                var_out = (Word16)(var1 >> var2);
-            }
-        }
-    }
-
-    return (var_out);
-}
-#endif
-
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : mult                                                    |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |    Performs the multiplication of var1 by var2 and gives a 16 bit result  |
- |    which is scaled i.e.:                                                  |
- |             mult(var1,var2) = extract_l(L_shr((var1 times var2),15)) and  |
- |             mult(-32768,-32768) = 32767.                                  |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-#if (!MULT_IS_INLINE)
-Word16 mult (Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-    Word32 L_product;
-
-    L_product = (Word32) var1 *(Word32) var2;
-
-    L_product = (L_product & (Word32) 0xffff8000L) >> 15;
-
-    if (L_product & (Word32) 0x00010000L)
-        L_product = L_product | (Word32) 0xffff0000L;
-
-    var_out = saturate(L_product);
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_mult                                                  |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   L_mult 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.                                |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
- |___________________________________________________________________________|
-*/
-
-#if (!L_MULT_IS_INLINE)
-Word32 L_mult(Word16 var1, Word16 var2)
-{
-    Word32 L_var_out;
-
-    L_var_out = (Word32) var1 *(Word32) var2;
-
-    if (L_var_out != (Word32) 0x40000000L)
-    {
-        L_var_out <<= 1;
-    }
-    else
-    {
-        L_var_out = MAX_32;
-    }
-
-    return (L_var_out);
-}
-#endif
-// end
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : negate                                                  |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Negate var1 with saturation, saturate in the case where input is -32768:|
- |                negate(var1) = sub(0,var1).                                |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    var1                                                                   |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-//Word16 negate (Word16 var1)
-//{
-//    Word16 var_out;
-//
-//    var_out = (Word16)((var1 == MIN_16) ? MAX_16 : -var1);
-//
-//    return (var_out);
-//}
-
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : extract_h                                               |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Return the 16 MSB of L_var1.                                            |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1                                                                 |
- |             32 bit long signed integer (Word32 ) whose value falls in the |
- |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-#if (!EXTRACT_H_IS_INLINE)
-Word16 extract_h (Word32 L_var1)
-{
-    Word16 var_out;
-
-    var_out = (Word16) (L_var1 >> 16);
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : extract_l                                               |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Return the 16 LSB of L_var1.                                            |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1                                                                 |
- |             32 bit long signed integer (Word32 ) whose value falls in the |
- |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-#if (!EXTRACT_L_IS_INLINE)
-Word16 extract_l(Word32 L_var1)
-{
-    Word16 var_out;
-
-    var_out = (Word16) L_var1;
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : round                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   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))              |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1                                                                 |
- |             32 bit long signed integer (Word32 ) whose value falls in the |
- |             range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.                 |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-
-#if (!ROUND_IS_INLINE)
-Word16 round16(Word32 L_var1)
-{
-    Word16 var_out;
-    Word32 L_rounded;
-
-    L_rounded = L_add (L_var1, (Word32) 0x00008000L);
-    var_out = extract_h (L_rounded);
-
-    return (var_out);
-}
-#endif
-// end
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_mac                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   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)).         |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
- |___________________________________________________________________________|
-*/
-#if (!L_MSU_IS_INLINE)
-Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2)
-{
-    Word32 L_var_out;
-    Word32 L_product;
-
-    L_product = L_mult(var1, var2);
-    L_var_out = L_add (L_var3, L_product);
-
-    return (L_var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_msu                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   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)).         |
- |                                                                           |
- |   Complexity weight : 1                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
- |___________________________________________________________________________|
-*/
-
-#if (!L_MSU_IS_INLINE)
-Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2)
-{
-    Word32 L_var_out;
-    Word32 L_product;
-
-    L_product = L_mult(var1, var2);
-    L_var_out = L_sub (L_var3, L_product);
-
-    return (L_var_out);
-}
-#endif
-
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_add                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   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.                |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
- |                                                                           |
- |    L_var2   32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
- |___________________________________________________________________________|
-*/
-#if (!L_ADD_IS_INLINE)
-Word32 L_add (Word32 L_var1, Word32 L_var2)
-{
-    Word32 L_var_out;
-
-    L_var_out = L_var1 + L_var2;
-
-    if (((L_var1 ^ L_var2) & MIN_32) == 0)
-    {
-        if ((L_var_out ^ L_var1) & MIN_32)
-        {
-            L_var_out = (L_var1 < 0) ? MIN_32 : MAX_32;
-            //Overflow = 1;
-        }
-    }
-
-    return (L_var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_sub                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   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.                |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
- |                                                                           |
- |    L_var2   32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
- |___________________________________________________________________________|
-*/
-#if (!L_SUB_IS_INLINE)
-Word32 L_sub(Word32 L_var1, Word32 L_var2)
-{
-    Word32 L_var_out;
-
-    L_var_out = L_var1 - L_var2;
-
-    if (((L_var1 ^ L_var2) & MIN_32) != 0)
-    {
-        if ((L_var_out ^ L_var1) & MIN_32)
-        {
-            L_var_out = (L_var1 < 0L) ? MIN_32 : MAX_32;
-            //Overflow = 1;
-        }
-    }
-
-    return (L_var_out);
-}
-#endif
-
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_negate                                                |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Negate the 32 bit variable L_var1 with saturation; saturate in the case |
- |   where input is -2147483648 (0x8000 0000).                               |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
- |___________________________________________________________________________|
-*/
-//Word32 L_negate (Word32 L_var1)
-//{
-//    Word32 L_var_out;
-//
-//    L_var_out = (L_var1 == MIN_32) ? MAX_32 : -L_var1;
-//
-//    return (L_var_out);
-//}
-
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : mult_r                                                  |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Same as mult with rounding, i.e.:                                       |
- |     mult_r(var1,var2) = extract_l(L_shr(((var1 * var2) + 16384),15)) and  |
- |     mult_r(-32768,-32768) = 32767.                                        |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-#if (!MULT_R_IS_INLINE)
-Word16 mult_r (Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-    Word32 L_product_arr;
-
-    L_product_arr = (Word32) var1 *(Word32) var2;       /* product */
-    L_product_arr += (Word32) 0x00004000L;      /* round */
-    L_product_arr &= (Word32) 0xffff8000L;
-    L_product_arr >>= 15;       /* shift */
-
-    if (L_product_arr & (Word32) 0x00010000L)   /* sign extend when necessary */
-    {
-        L_product_arr |= (Word32) 0xffff0000L;
-    }
-    var_out = saturate(L_product_arr);
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_shl                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   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.                                        |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
- |                                                                           |
- |    var2                                                                   |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
- |___________________________________________________________________________|
-*/
-
-#if (!L_SHL_IS_INLINE)
-Word32 L_shl (Word32 L_var1, Word16 var2)
-{
-    Word32 L_var_out = 0L;
-
-    if (var2 <= 0)
-    {
-        L_var1 = L_shr(L_var1, (Word16)-var2);
-    }
-    else
-    {
-        for (; var2 > 0; var2--)
-        {
-            if (L_var1 > (Word32) 0X3fffffffL)
-            {
-                return MAX_32;
-            }
-            else
-            {
-                if (L_var1 < (Word32) 0xc0000000L)
-                {
-                    return MIN_32;
-                }
-            }
-            L_var1 <<= 1;
-        }
-    }
-    return (L_var1);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_shr                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   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.                                     |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1   32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.                 |
- |                                                                           |
- |    var2                                                                   |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.              |
- |___________________________________________________________________________|
-*/
-
-#if (!L_SHR_IS_INLINE)
-Word32 L_shr (Word32 L_var1, Word16 var2)
-{
-    Word32 L_var_out;
-
-    if (var2 < 0)
-    {
-        L_var_out = L_shl (L_var1, (Word16)-var2);
-    }
-    else
-    {
-        if (var2 >= 31)
-        {
-            L_var_out = (L_var1 < 0L) ? -1 : 0;
-        }
-        else
-        {
-            if (L_var1 < 0)
-            {
-                L_var_out = ~((~L_var1) >> var2);
-            }
-            else
-            {
-                L_var_out = L_var1 >> var2;
-            }
-        }
-    }
-    return (L_var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : shr_r                                                   |
- |                                                                           |
- |   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(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).                    |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-#if (!SHR_R_IS_INLINE)
-Word16 shr_r (Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-
-    if (var2 > 15)
-    {
-        var_out = 0;
-    }
-    else
-    {
-        var_out = shr (var1, var2);
-
-        if (var2 > 0)
-        {
-            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)
-            {
-                var_out++;
-            }
-        }
-    }
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : mac_r                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Multiply var1 by var2 and shift the result left by 1. Add the 32 bit    |
- |   result to L_var3 with saturation. Round the LS 16 bits of the result    |
- |   into the MS 16 bits with saturation and shift the result right by 16.   |
- |   Return a 16 bit result.                                                 |
- |            mac_r(L_var3,var1,var2) = round(L_mac(L_var3,var1,var2))       |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0x0000 8000 <= L_var_out <= 0x0000 7fff.              |
- |___________________________________________________________________________|
-*/
-#if (!MAC_R_IS_INLINE)
-Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-
-    L_var3 = L_mac (L_var3, var1, var2);
-    L_var3 = L_add (L_var3, (Word32) 0x00008000L);
-    var_out = extract_h (L_var3);
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : msu_r                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Multiply var1 by var2 and shift the result left by 1. Subtract the 32   |
- |   bit result to L_var3 with saturation. Round the LS 16 bits of the res-  |
- |   ult into the MS 16 bits with saturation and shift the result right by   |
- |   16. Return a 16 bit result.                                             |
- |            msu_r(L_var3,var1,var2) = round(L_msu(L_var3,var1,var2))       |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   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 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0x0000 8000 <= L_var_out <= 0x0000 7fff.              |
- |___________________________________________________________________________|
-*/
-#if (!MSU_R_IS_INLINE)
-Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2)
-{
-    Word16 var_out;
-
-    L_var3 = L_msu (L_var3, var1, var2);
-    L_var3 = L_add (L_var3, (Word32) 0x00008000L);
-    var_out = extract_h (L_var3);
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_deposit_h                                             |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Deposit the 16 bit var1 into the 16 MS bits of the 32 bit output. The   |
- |   16 LS bits of the output are zeroed.                                    |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    var1                                                                   |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= var_out <= 0x7fff 0000.                |
- |___________________________________________________________________________|
-*/
-//Word32 L_deposit_h (Word16 var1)
-//{
-//    Word32 L_var_out;
-//
-//    L_var_out = (Word32) var1 << 16;
-//
-//    return (L_var_out);
-//}
-
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_deposit_l                                             |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Deposit the 16 bit var1 into the 16 LS bits of the 32 bit output. The   |
- |   16 MS bits of the output are sign extended.                             |
- |                                                                           |
- |   Complexity weight : 2                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    var1                                                                   |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0xFFFF 8000 <= var_out <= 0x0000 7fff.                |
- |___________________________________________________________________________|
-*/
-//Word32 L_deposit_l (Word16 var1)
-//{
-//    Word32 L_var_out;
-//
-//    L_var_out = (Word32) var1;
-//
-//    return (L_var_out);
-//}
-
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_shr_r                                                 |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Same as L_shr(L_var1,var2) but with rounding. Saturate the result in    |
- |   case of underflows or overflows :                                       |
- |    - 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).            |
- |                                                                           |
- |   Complexity weight : 3                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1                                                                 |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |
- |                                                                           |
- |    var2                                                                   |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= var_out <= 0x7fff ffff.                |
- |___________________________________________________________________________|
-*/
-#if (!L_SHR_R_IS_INLINE)
-Word32 L_shr_r (Word32 L_var1, Word16 var2)
-{
-    Word32 L_var_out;
-
-    if (var2 > 31)
-    {
-        L_var_out = 0;
-    }
-    else
-    {
-        L_var_out = L_shr (L_var1, var2);
-
-        if (var2 > 0)
-        {
-            if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)
-            {
-                L_var_out++;
-            }
-        }
-    }
-
-    return (L_var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : L_abs                                                   |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |    Absolute value of L_var1; Saturate in case where the input is          |
- |                                                               -214783648  |
- |                                                                           |
- |   Complexity weight : 3                                                   |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1                                                                 |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    L_var_out                                                              |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x0000 0000 <= var_out <= 0x7fff ffff.                |
- |___________________________________________________________________________|
-*/
-//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;
-//        }
-//    }
-//
-//    return (L_var_out);
-//}
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : norm_s                                                  |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Produces the number of left shift needed to normalize the 16 bit varia- |
- |   ble var1 for positive values on the interval with minimum of 16384 and  |
- |   maximum of 32767, and for negative values on the interval with minimum  |
- |   of -32768 and maximum of -16384; in order to normalize the result, the  |
- |   following operation must be done :                                      |
- |                    norm_var1 = shl(var1,norm_s(var1)).                    |
- |                                                                           |
- |   Complexity weight : 15                                                  |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    var1                                                                   |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0xffff 8000 <= var1 <= 0x0000 7fff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0x0000 0000 <= var_out <= 0x0000 000f.                |
- |___________________________________________________________________________|
-*/
-
-#if (!NORM_S_IS_INLINE)
-Word16 norm_s (Word16 var1)
-{
-    Word16 var_out;
-
-    if (var1 == 0)
-    {
-        var_out = 0;
-    }
-    else
-    {
-        if (var1 == -1)
-        {
-            var_out = 15;
-        }
-        else
-        {
-            if (var1 < 0)
-            {
-                var1 = (Word16)~var1;
-            }
-            for (var_out = 0; var1 < 0x4000; var_out++)
-            {
-                var1 <<= 1;
-            }
-        }
-    }
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : div_s                                                   |
- |                                                                           |
- |   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 (Word16) whose value falls in the |
- |             range : 0x0000 0000 <= var1 <= var2 and var2 != 0.            |
- |                                                                           |
- |    var2                                                                   |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : var1 <= var2 <= 0x0000 7fff and var2 != 0.            |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0x0000 0000 <= var_out <= 0x0000 7fff.                |
- |             It's a Q15 value (point between b15 and b14).                 |
- |___________________________________________________________________________|
-*/
-
-#if (!DIV_S_IS_INLINE)
-Word16 div_s (Word16 var1, Word16 var2)
-{
-    Word16 var_out = 0;
-    Word16 iteration;
-    Word32 L_num;
-    Word32 L_denom;
-
-    if (var1 == 0)
-    {
-        var_out = 0;
-    }
-    else
-    {
-        if (var1 == var2)
-        {
-            var_out = MAX_16;
-        }
-        else
-        {
-            L_num = L_deposit_l (var1);
-            L_denom = L_deposit_l (var2);
-
-            for (iteration = 0; iteration < 15; iteration++)
-            {
-                var_out <<= 1;
-                L_num <<= 1;
-
-                if (L_num >= L_denom)
-                {
-                    L_num = L_sub(L_num, L_denom);
-                    var_out = add (var_out, 1);
-                }
-            }
-        }
-    }
-
-    return (var_out);
-}
-#endif
-
-/*___________________________________________________________________________
- |                                                                           |
- |   Function Name : norm_l                                                  |
- |                                                                           |
- |   Purpose :                                                               |
- |                                                                           |
- |   Produces the number of left shifts needed to normalize the 32 bit varia-|
- |   ble L_var1 for positive values on the interval with minimum of          |
- |   1073741824 and maximum of 2147483647, and for negative values on the in-|
- |   terval with minimum of -2147483648 and maximum of -1073741824; in order |
- |   to normalize the result, the following operation must be done :         |
- |                   norm_L_var1 = L_shl(L_var1,norm_l(L_var1)).             |
- |                                                                           |
- |   Complexity weight : 30                                                  |
- |                                                                           |
- |   Inputs :                                                                |
- |                                                                           |
- |    L_var1                                                                 |
- |             32 bit long signed integer (Word32) whose value falls in the  |
- |             range : 0x8000 0000 <= var1 <= 0x7fff ffff.                   |
- |                                                                           |
- |   Outputs :                                                               |
- |                                                                           |
- |    none                                                                   |
- |                                                                           |
- |   Return Value :                                                          |
- |                                                                           |
- |    var_out                                                                |
- |             16 bit short signed integer (Word16) whose value falls in the |
- |             range : 0x0000 0000 <= var_out <= 0x0000 001f.                |
- |___________________________________________________________________________|
-*/
-
-#if (!NORM_L_IS_INLINE)
-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;
-            }
-        }
-    }
-
-    return (var_out);
-}
-#endif
-
diff --git a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
deleted file mode 100644
index 78f032b..0000000
--- a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
+++ /dev/null
@@ -1,363 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		oper_32b.c
-
-	Content:	  This file contains operations in double precision.
-
-*******************************************************************************/
-
-#include "typedef.h"
-#include "basic_op.h"
-#include "oper_32b.h"
-
-#define UNUSED(x) (void)(x)
-
-/*****************************************************************************
- *                                                                           *
- *  Function L_Extract()                                                     *
- *                                                                           *
- *  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 L_Extract (Word32 L_32, Word16 *hi, Word16 *lo)
-{
-    *hi = extract_h (L_32);
-    *lo = extract_l (L_msu (L_shr (L_32, 1), *hi, 16384));
-    return;
-}
-
-/*****************************************************************************
- *                                                                           *
- *  Function L_Comp()                                                        *
- *                                                                           *
- *  Compose from two 16 bit DPF a 32 bit integer.                            *
- *                                                                           *
- *     L_32 = hi<<16 + lo<<1                                                 *
- *                                                                           *
- *  Arguments:                                                               *
- *                                                                           *
- *   hi        msb                                                           *
- *   lo        lsf (with sign)                                               *
- *                                                                           *
- *   Return Value :                                                          *
- *                                                                           *
- *             32 bit long signed integer (Word32) whose value falls in the  *
- *             range : 0x8000 0000 <= L_32 <= 0x7fff fff0.                   *
- *                                                                           *
- *****************************************************************************
-*/
-
-Word32 L_Comp (Word16 hi, Word16 lo)
-{
-    Word32 L_32;
-
-    L_32 = L_deposit_h (hi);
-    return (L_mac (L_32, lo, 1));       /* = hi<<16 + lo<<1 */
-}
-
-/*****************************************************************************
- * Function Mpy_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                                     *
- *                                                                           *
- *****************************************************************************
-*/
-
-Word32 Mpy_32 (Word16 hi1, Word16 lo1, Word16 hi2, Word16 lo2)
-{
-    Word32 L_32;
-
-    L_32 = L_mult (hi1, hi2);
-    L_32 = L_mac (L_32, mult (hi1, lo2), 1);
-    L_32 = L_mac (L_32, mult (lo1, hi2), 1);
-
-    return (L_32);
-}
-
-/*****************************************************************************
- * Function Mpy_32_16()                                                      *
- *                                                                           *
- *   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                                *
- *                                                                           *
- * Arguments:                                                                *
- *                                                                           *
- *  hi          hi part of 32 bit number.                                    *
- *  lo          lo part of 32 bit number.                                    *
- *  n           16 bit number.                                               *
- *                                                                           *
- *****************************************************************************
-*/
-
-Word32 Mpy_32_16 (Word16 hi, Word16 lo, Word16 n)
-{
-    Word32 L_32;
-
-    L_32 = L_mult (hi, n);
-    L_32 = L_mac (L_32, mult (lo, n), 1);
-
-    return (L_32);
-}
-
-/*****************************************************************************
- *                                                                           *
- *   Function Name : Div_32                                                  *
- *                                                                           *
- *   Purpose :                                                               *
- *             Fractional integer division of two 32 bit numbers.            *
- *             L_num / L_denom.                                              *
- *             L_num and L_denom must be positive and L_num < L_denom.       *
- *             L_denom = denom_hi<<16 + denom_lo<<1                          *
- *             denom_hi is a normalize number.                               *
- *                                                                           *
- *   Inputs :                                                                *
- *                                                                           *
- *    L_num                                                                  *
- *             32 bit long signed integer (Word32) whose value falls in the  *
- *             range : 0x0000 0000 < L_num < L_denom                         *
- *                                                                           *
- *    L_denom = denom_hi<<16 + denom_lo<<1      (DPF)                        *
- *                                                                           *
- *       denom_hi                                                            *
- *             16 bit positive normalized integer whose value falls in the   *
- *             range : 0x4000 < hi < 0x7fff                                  *
- *       denom_lo                                                            *
- *             16 bit positive integer whose value falls in the              *
- *             range : 0 < lo < 0x7fff                                       *
- *                                                                           *
- *   Return Value :                                                          *
- *                                                                           *
- *    L_div                                                                  *
- *             32 bit long signed integer (Word32) whose value falls in the  *
- *             range : 0x0000 0000 <= L_div <= 0x7fff ffff.                  *
- *                                                                           *
- *  Algorithm:                                                               *
- *                                                                           *
- *  - find = 1/L_denom.                                                      *
- *      First approximation: approx = 1 / denom_hi                           *
- *      1/L_denom = approx * (2.0 - L_denom * approx )                       *
- *                                                                           *
- *  -  result = L_num * (1/L_denom)                                          *
- *****************************************************************************
-*/
-
-Word32 Div_32 (Word32 L_num, Word32 denom)
-{
-    Word16 approx;
-    Word32 L_32;
-    /* First approximation: 1 / L_denom = 1/denom_hi */
-
-    approx = div_s ((Word16) 0x3fff, denom >> 16);
-
-    /* 1/L_denom = approx * (2.0 - L_denom * approx) */
-
-    L_32 = L_mpy_ls (denom, approx);
-
-    L_32 = L_sub ((Word32) 0x7fffffffL, L_32);
-
-	L_32 = L_mpy_ls (L_32, approx);
-    /* L_num * (1/L_denom) */
-
-	L_32 = MULHIGH(L_32, L_num);
-    L_32 = L_shl (L_32, 3);
-
-    return (L_32);
-}
-
-/*!
-
-  \brief  calculates the log dualis times 4 of argument
-          iLog4(x) = (Word32)(4 * log(value)/log(2.0))
-
-  \return ilog4 value
-
-*/
-Word16 iLog4(Word32 value)
-{
-  Word16 iLog4;
-
-  if(value != 0){
-    Word32 tmp;
-    Word16 tmp16;
-    iLog4 = norm_l(value);
-    tmp = (value << iLog4);
-    tmp16 = round16(tmp);
-    tmp = L_mult(tmp16, tmp16);
-    tmp16 = round16(tmp);
-    tmp = L_mult(tmp16, tmp16);
-    tmp16 = round16(tmp);
-
-    iLog4 = (-(iLog4 << 2) - norm_s(tmp16)) - 1;
-  }
-  else {
-    iLog4 = -128; /* -(INT_BITS*4); */
-  }
-
-  return iLog4;
-}
-
-#define step(shift) \
-    if ((0x40000000l >> (shift)) + root <= value)       \
-    {                                                 \
-        value -= (0x40000000l >> (shift)) + root;       \
-        root = (root >> 1) | (0x40000000l >> (shift));  \
-    } else {                                          \
-        root = root >> 1;                             \
-    }
-
-Word32 rsqrt(Word32 value,     /*!< Operand to square root (0.0 ... 1) */
-             Word32 accuracy)  /*!< Number of valid bits that will be calculated */
-{
-    Word32 root = 0;
-	Word32 scale;
-    UNUSED(accuracy);
-
-	if(value < 0)
-		return 0;
-
-	scale = norm_l(value);
-	if(scale & 1) scale--;
-
-	value <<= scale;
-
-	step( 0); step( 2); step( 4); step( 6);
-    step( 8); step(10); step(12); step(14);
-    step(16); step(18); step(20); step(22);
-    step(24); step(26); step(28); step(30);
-
-    scale >>= 1;
-	if (root < value)
-        ++root;
-
-	root >>= scale;
-    return root* 46334;
-}
-
-static const Word32 pow2Table[POW2_TABLE_SIZE] = {
-0x7fffffff, 0x7fa765ad, 0x7f4f08ae, 0x7ef6e8da,
-0x7e9f0606, 0x7e476009, 0x7deff6b6, 0x7d98c9e6,
-0x7d41d96e, 0x7ceb2523, 0x7c94acde, 0x7c3e7073,
-0x7be86fb9, 0x7b92aa88, 0x7b3d20b6, 0x7ae7d21a,
-0x7a92be8b, 0x7a3de5df, 0x79e947ef, 0x7994e492,
-0x7940bb9e, 0x78ecccec, 0x78991854, 0x78459dac,
-0x77f25cce, 0x779f5591, 0x774c87cc, 0x76f9f359,
-0x76a7980f, 0x765575c8, 0x76038c5b, 0x75b1dba2,
-0x75606374, 0x750f23ab, 0x74be1c20, 0x746d4cac,
-0x741cb528, 0x73cc556d, 0x737c2d55, 0x732c3cba,
-0x72dc8374, 0x728d015d, 0x723db650, 0x71eea226,
-0x719fc4b9, 0x71511de4, 0x7102ad80, 0x70b47368,
-0x70666f76, 0x7018a185, 0x6fcb096f, 0x6f7da710,
-0x6f307a41, 0x6ee382de, 0x6e96c0c3, 0x6e4a33c9,
-0x6dfddbcc, 0x6db1b8a8, 0x6d65ca38, 0x6d1a1057,
-0x6cce8ae1, 0x6c8339b2, 0x6c381ca6, 0x6bed3398,
-0x6ba27e66, 0x6b57fce9, 0x6b0daeff, 0x6ac39485,
-0x6a79ad56, 0x6a2ff94f, 0x69e6784d, 0x699d2a2c,
-0x69540ec9, 0x690b2601, 0x68c26fb1, 0x6879ebb6,
-0x683199ed, 0x67e97a34, 0x67a18c68, 0x6759d065,
-0x6712460b, 0x66caed35, 0x6683c5c3, 0x663ccf92,
-0x65f60a80, 0x65af766a, 0x6569132f, 0x6522e0ad,
-0x64dcdec3, 0x64970d4f, 0x64516c2e, 0x640bfb41,
-0x63c6ba64, 0x6381a978, 0x633cc85b, 0x62f816eb,
-0x62b39509, 0x626f4292, 0x622b1f66, 0x61e72b65,
-0x61a3666d, 0x615fd05f, 0x611c6919, 0x60d9307b,
-0x60962665, 0x60534ab7, 0x60109d51, 0x5fce1e12,
-0x5f8bccdb, 0x5f49a98c, 0x5f07b405, 0x5ec5ec26,
-0x5e8451d0, 0x5e42e4e3, 0x5e01a540, 0x5dc092c7,
-0x5d7fad59, 0x5d3ef4d7, 0x5cfe6923, 0x5cbe0a1c,
-0x5c7dd7a4, 0x5c3dd19c, 0x5bfdf7e5, 0x5bbe4a61,
-0x5b7ec8f2, 0x5b3f7377, 0x5b0049d4, 0x5ac14bea,
-0x5a82799a, 0x5a43d2c6, 0x5a055751, 0x59c7071c,
-0x5988e209, 0x594ae7fb, 0x590d18d3, 0x58cf7474,
-0x5891fac1, 0x5854ab9b, 0x581786e6, 0x57da8c83,
-0x579dbc57, 0x57611642, 0x57249a29, 0x56e847ef,
-0x56ac1f75, 0x567020a0, 0x56344b52, 0x55f89f70,
-0x55bd1cdb, 0x5581c378, 0x55469329, 0x550b8bd4,
-0x54d0ad5b, 0x5495f7a1, 0x545b6a8b, 0x542105fd,
-0x53e6c9db, 0x53acb607, 0x5372ca68, 0x533906e0,
-0x52ff6b55, 0x52c5f7aa, 0x528cabc3, 0x52538786,
-0x521a8ad7, 0x51e1b59a, 0x51a907b4, 0x5170810b,
-0x51382182, 0x50ffe8fe, 0x50c7d765, 0x508fec9c,
-0x50582888, 0x50208b0e, 0x4fe91413, 0x4fb1c37c,
-0x4f7a9930, 0x4f439514, 0x4f0cb70c, 0x4ed5ff00,
-0x4e9f6cd4, 0x4e69006e, 0x4e32b9b4, 0x4dfc988c,
-0x4dc69cdd, 0x4d90c68b, 0x4d5b157e, 0x4d25899c,
-0x4cf022ca, 0x4cbae0ef, 0x4c85c3f1, 0x4c50cbb8,
-0x4c1bf829, 0x4be7492b, 0x4bb2bea5, 0x4b7e587d,
-0x4b4a169c, 0x4b15f8e6, 0x4ae1ff43, 0x4aae299b,
-0x4a7a77d5, 0x4a46e9d6, 0x4a137f88, 0x49e038d0,
-0x49ad1598, 0x497a15c4, 0x4947393f, 0x49147fee,
-0x48e1e9ba, 0x48af768a, 0x487d2646, 0x484af8d6,
-0x4818ee22, 0x47e70611, 0x47b5408c, 0x47839d7b,
-0x47521cc6, 0x4720be55, 0x46ef8210, 0x46be67e0,
-0x468d6fae, 0x465c9961, 0x462be4e2, 0x45fb521a,
-0x45cae0f2, 0x459a9152, 0x456a6323, 0x453a564d,
-0x450a6abb, 0x44daa054, 0x44aaf702, 0x447b6ead,
-0x444c0740, 0x441cc0a3, 0x43ed9ac0, 0x43be9580,
-0x438fb0cb, 0x4360ec8d, 0x433248ae, 0x4303c517,
-0x42d561b4, 0x42a71e6c, 0x4278fb2b, 0x424af7da,
-0x421d1462, 0x41ef50ae, 0x41c1aca8, 0x41942839,
-0x4166c34c, 0x41397dcc, 0x410c57a2, 0x40df50b8,
-0x40b268fa, 0x4085a051, 0x4058f6a8, 0x402c6be9
-};
-
-/*!
-
-  \brief calculates 2 ^ (x/y) for x<=0, y > 0, x <= 32768 * y
-
-  avoids integer division
-
-  \return
-*/
-Word32 pow2_xy(Word32 x, Word32 y)
-{
-  UWord32 iPart;
-  UWord32 fPart;
-  Word32 res;
-  Word32 tmp;
-
-  tmp = -x;
-  iPart = tmp / y;
-  fPart = tmp - iPart*y;
-  iPart = min(iPart,INT_BITS-1);
-
-  res = pow2Table[(POW2_TABLE_SIZE*fPart)/y] >> iPart;
-
-  return(res);
-}
diff --git a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.h b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.h
deleted file mode 100644
index 6e5844f..0000000
--- a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		oper_32b.h
-
-	Content:	Double precision operations
-
-*******************************************************************************/
-
-#ifndef __OPER_32b_H
-#define __OPER_32b_H
-
-#include "typedef.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define POW2_TABLE_BITS 8
-#define POW2_TABLE_SIZE (1<<POW2_TABLE_BITS)
-
-void L_Extract (Word32 L_32, Word16 *hi, Word16 *lo);
-Word32 L_Comp (Word16 hi, Word16 lo);
-Word32 Mpy_32 (Word16 hi1, Word16 lo1, Word16 hi2, Word16 lo2);
-Word32 Mpy_32_16 (Word16 hi, Word16 lo, Word16 n);
-Word32 Div_32 (Word32 L_num, Word32 denom);
-Word16 iLog4(Word32 value);
-Word32 rsqrt(Word32 value,  Word32 accuracy);
-Word32 pow2_xy(Word32 x, Word32 y);
-
-__inline Word32 L_mpy_ls(Word32 L_var2, Word16 var1)
-{
-    unsigned short swLow1;
-    Word16 swHigh1;
-    Word32 l_var_out;
-
-    swLow1 = (unsigned short)(L_var2);
-    swHigh1 = (Word16)(L_var2 >> 16);
-
-    l_var_out = (long)swLow1 * (long)var1 >> 15;
-
-    l_var_out += swHigh1 * var1 << 1;
-
-    return(l_var_out);
-}
-
-__inline Word32 L_mpy_wx(Word32 L_var2, Word16 var1)
-{
-#if ARMV5TE_L_MPY_LS
-	Word32 result;
-	asm volatile(
-		"SMULWB  %[result], %[L_var2], %[var1] \n"
-		:[result]"=r"(result)
-		:[L_var2]"r"(L_var2), [var1]"r"(var1)
-		);
-	return result;
-#else
-    unsigned short swLow1;
-    Word16 swHigh1;
-    Word32 l_var_out;
-
-    swLow1 = (unsigned short)(L_var2);
-    swHigh1 = (Word16)(L_var2 >> 16);
-
-    l_var_out = (long)swLow1 * (long)var1 >> 16;
-    l_var_out += swHigh1 * var1;
-
-    return(l_var_out);
-#endif
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/basic_op/typedef.h b/media/libstagefright/codecs/aacenc/basic_op/typedef.h
deleted file mode 100644
index b1f8225..0000000
--- a/media/libstagefright/codecs/aacenc/basic_op/typedef.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		typedef.h
-
-	Content:	type defined for defferent paltform
-
-*******************************************************************************/
-
-#ifndef typedef_h
-#define typedef_h "$Id $"
-
-#undef ORIGINAL_TYPEDEF_H /* define to get "original" ETSI version
-                             of typedef.h                           */
-
-#ifdef ORIGINAL_TYPEDEF_H
-/*
- * this is the original code from the ETSI file typedef.h
- */
-
-#if defined(__BORLANDC__) || defined(__WATCOMC__) || defined(_MSC_VER) || defined(__ZTC__)
-typedef signed char Word8;
-typedef short Word16;
-typedef long Word32;
-typedef int Flag;
-
-#elif defined(__sun)
-typedef signed char Word8;
-typedef short Word16;
-typedef long Word32;
-typedef int Flag;
-
-#elif defined(__unix__) || defined(__unix)
-typedef signed char Word8;
-typedef short Word16;
-typedef int Word32;
-typedef int Flag;
-
-#endif
-#else /* not original typedef.h */
-
-/*
- * use (improved) type definition file typdefs.h and add a "Flag" type
- */
-#include "typedefs.h"
-typedef int Flag;
-
-#endif
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/basic_op/typedefs.h b/media/libstagefright/codecs/aacenc/basic_op/typedefs.h
deleted file mode 100644
index 80d350d..0000000
--- a/media/libstagefright/codecs/aacenc/basic_op/typedefs.h
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		typedefs.h
-
-	Content:	type defined or const defined
-
-*******************************************************************************/
-
-#ifndef typedefs_h
-#define typedefs_h "$Id $"
-
-#ifndef CHAR_BIT
-#define CHAR_BIT      8         /* number of bits in a char */
-#endif
-
-#ifndef VOAAC_SHRT_MAX
-#define VOAAC_SHRT_MAX    (32767)        /* maximum (signed) short value */
-#endif
-
-#ifndef VOAAC_SHRT_MIN
-#define VOAAC_SHRT_MIN    (-32768)        /* minimum (signed) short value */
-#endif
-
-/* Define NULL pointer value */
-#ifndef NULL
-#ifdef __cplusplus
-#define NULL    0
-#else
-#define NULL    ((void *)0)
-#endif
-#endif
-
-#ifndef assert
-#define assert(_Expression)     ((void)0)
-#endif
-
-#define __inline static __inline
-
-#define INT_BITS   32
-/*
-********************************************************************************
-*                         DEFINITION OF CONSTANTS
-********************************************************************************
-*/
-/*
- ********* define char type
- */
-typedef char Char;
-
-/*
- ********* define 8 bit signed/unsigned types & constants
- */
-typedef signed char Word8;
-typedef unsigned char UWord8;
-/*
- ********* define 16 bit signed/unsigned types & constants
- */
-typedef short Word16;
-typedef unsigned short UWord16;
-
-/*
- ********* define 32 bit signed/unsigned types & constants
- */
-typedef int Word32;
-typedef unsigned int UWord32;
-
-
-
-#ifndef _MSC_VER
-typedef long long Word64;
-typedef unsigned long long UWord64;
-#else
-typedef __int64 Word64;
-typedef unsigned __int64 UWord64;
-#endif
-
-#ifndef min
-#define min(a,b) ( (a) < (b) ? (a) : (b))
-#endif
-
-#ifndef max
-#define max(a,b) ( (a) > (b) ? (a) : (b))
-#endif
-
-#ifdef ARM_INASM
-#ifdef ARMV5_INASM
-#define ARMV5E_INASM	1
-#endif
-#define ARMV4_INASM		1
-#endif
-
-#if ARMV4_INASM
-	#define ARMV5TE_SAT           1
-    #define ARMV5TE_ADD           1
-    #define ARMV5TE_SUB           1
-	#define ARMV5TE_SHL           1
-    #define ARMV5TE_SHR           1
-	#define ARMV5TE_L_SHL         1
-    #define ARMV5TE_L_SHR         1
-#endif//ARMV4
-#if ARMV5E_INASM
-    #define ARMV5TE_L_ADD         1
-    #define ARMV5TE_L_SUB         1
-    #define ARMV5TE_L_MULT        1
-    #define ARMV5TE_L_MAC         1
-    #define ARMV5TE_L_MSU         1
-
-
-    #define ARMV5TE_DIV_S         1
-    #define ARMV5TE_ROUND         1
-    #define ARMV5TE_MULT          1
-
-    #define ARMV5TE_NORM_S        1
-    #define ARMV5TE_NORM_L        1
-	#define ARMV5TE_L_MPY_LS	  1
-#endif
-#if ARMV6_INASM
-    #undef  ARMV5TE_ADD
-    #define ARMV5TE_ADD           0
-    #undef  ARMV5TE_SUB
-    #define ARMV5TE_SUB           0
-    #define ARMV6_SAT             1
-#endif
-
-//basic operation functions optimization flags
-#define SATRUATE_IS_INLINE              1   //define saturate as inline function
-#define SHL_IS_INLINE                   1  //define shl as inline function
-#define SHR_IS_INLINE                   1   //define shr as inline function
-#define L_MULT_IS_INLINE                1   //define L_mult as inline function
-#define L_MSU_IS_INLINE                 1   //define L_msu as inline function
-#define L_SUB_IS_INLINE                 1   //define L_sub as inline function
-#define L_SHL_IS_INLINE                 1   //define L_shl as inline function
-#define L_SHR_IS_INLINE                 1   //define L_shr as inline function
-#define ADD_IS_INLINE                   1   //define add as inline function //add, inline is the best
-#define SUB_IS_INLINE                   1   //define sub as inline function //sub, inline is the best
-#define DIV_S_IS_INLINE                 1   //define div_s as inline function
-#define MULT_IS_INLINE                  1   //define mult as inline function
-#define NORM_S_IS_INLINE                1   //define norm_s as inline function
-#define NORM_L_IS_INLINE                1   //define norm_l as inline function
-#define ROUND_IS_INLINE                 1   //define round as inline function
-#define L_MAC_IS_INLINE                 1   //define L_mac as inline function
-#define L_ADD_IS_INLINE                 1   //define L_add as inline function
-#define EXTRACT_H_IS_INLINE             1   //define extract_h as inline function
-#define EXTRACT_L_IS_INLINE             1   //define extract_l as inline function        //???
-#define MULT_R_IS_INLINE                1   //define mult_r as inline function
-#define SHR_R_IS_INLINE                 1   //define shr_r as inline function
-#define MAC_R_IS_INLINE                 1   //define mac_r as inline function
-#define MSU_R_IS_INLINE                 1   //define msu_r as inline function
-#define L_SHR_R_IS_INLINE               1   //define L_shr_r as inline function
-
-#define PREFIX				voAACEnc
-#define LINK0(x, y, z)		LINK1(x,y,z)
-#define LINK1(x,y,z)		x##y##z
-#define ADD_PREFIX(func)	LINK0(PREFIX, _, func)
-
-#define  L_Extract		ADD_PREFIX(L_Extract)
-#define  L_Comp			ADD_PREFIX(L_Comp)
-#define  Mpy_32			ADD_PREFIX(Mpy_32)
-#define  Mpy_32_16		ADD_PREFIX(Mpy_32_16)
-#define  Div_32			ADD_PREFIX(Div_32)
-#define  iLog4			ADD_PREFIX(iLog4)
-#define  rsqrt			ADD_PREFIX(rsqrt)
-#define  pow2_xy		ADD_PREFIX(pow2_xy)
-#define  L_mpy_ls		ADD_PREFIX(L_mpy_ls)
-#define  L_mpy_wx		ADD_PREFIX(L_mpy_wx)
-
-#define mem_malloc		ADD_PREFIX(mem_malloc)
-#define mem_free		ADD_PREFIX(mem_free)
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/doc/voAACEncoderSDK.pdf b/media/libstagefright/codecs/aacenc/doc/voAACEncoderSDK.pdf
deleted file mode 100644
index 874d0f7..0000000
--- a/media/libstagefright/codecs/aacenc/doc/voAACEncoderSDK.pdf
+++ /dev/null
Binary files differ
diff --git a/media/libstagefright/codecs/aacenc/inc/aac_rom.h b/media/libstagefright/codecs/aacenc/inc/aac_rom.h
deleted file mode 100644
index 0b6f656..0000000
--- a/media/libstagefright/codecs/aacenc/inc/aac_rom.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		aac_rom.h
-
-	Content:	constant tables
-
-*******************************************************************************/
-
-#ifndef ROM_H
-#define ROM_H
-
-#include "config.h"
-#include "psy_const.h"
-#include "tns_param.h"
-
-/*
-  mdct
-*/
-extern const int ShortWindowSine[FRAME_LEN_SHORT/2];
-extern const int LongWindowKBD[FRAME_LEN_LONG/2];
-
-extern const unsigned char bitrevTab[17 + 129];
-extern const int cossintab[128 + 1024];
-
-#if defined (ARMV5E) && !defined (ARMV7Neon)
-extern const int twidTab64[(4*6 + 16*6)/2];
-extern const int twidTab512[(8*6 + 32*6 + 128*6)/2];
-#else
-extern const int twidTab64[4*6 + 16*6];
-extern const int twidTab512[8*6 + 32*6 + 128*6];
-#endif
-
-/*
-  form factor
-*/
-extern const Word32 formfac_sqrttable[96];
-
-/*
-  quantizer
-*/
-extern const Word32 mTab_3_4[512];
-extern const Word32 mTab_4_3[512];
-/*! $2^{-\frac{n}{16}}$ table */
-extern const Word16 pow2tominusNover16[17] ;
-
-extern const Word32 specExpMantTableComb_enc[4][14];
-extern const UWord8 specExpTableComb_enc[4][14];
-
-extern const Word16 quantBorders[4][4];
-//extern const Word16 quantRecon[3][4];
-extern const Word16 quantRecon[4][3];
-
-/*
-  huffman
-*/
-extern const UWord16 huff_ltab1_2[3][3][3][3];
-extern const UWord16 huff_ltab3_4[3][3][3][3];
-extern const UWord16 huff_ltab5_6[9][9];
-extern const UWord16 huff_ltab7_8[8][8];
-extern const UWord16 huff_ltab9_10[13][13];
-extern const UWord16 huff_ltab11[17][17];
-extern const UWord16 huff_ltabscf[121];
-extern const UWord16 huff_ctab1[3][3][3][3];
-extern const UWord16 huff_ctab2[3][3][3][3];
-extern const UWord16 huff_ctab3[3][3][3][3];
-extern const UWord16 huff_ctab4[3][3][3][3];
-extern const UWord16 huff_ctab5[9][9];
-extern const UWord16 huff_ctab6[9][9];
-extern const UWord16 huff_ctab7[8][8];
-extern const UWord16 huff_ctab8[8][8];
-extern const UWord16 huff_ctab9[13][13];
-extern const UWord16 huff_ctab10[13][13];
-extern const UWord16 huff_ctab11[17][17];
-extern const UWord32 huff_ctabscf[121];
-
-
-
-/*
-  misc
-*/
-extern const int sampRateTab[NUM_SAMPLE_RATES];
-extern const int BandwithCoefTab[8][NUM_SAMPLE_RATES];
-extern const int rates[8];
-extern const UWord8 sfBandTotalShort[NUM_SAMPLE_RATES];
-extern const UWord8 sfBandTotalLong[NUM_SAMPLE_RATES];
-extern const int sfBandTabShortOffset[NUM_SAMPLE_RATES];
-extern const short sfBandTabShort[76];
-extern const int sfBandTabLongOffset[NUM_SAMPLE_RATES];
-extern const short sfBandTabLong[325];
-
-extern const Word32 m_log2_table[INT_BITS];
-
-/*
-  TNS
-*/
-extern const Word32 tnsCoeff3[8];
-extern const Word32 tnsCoeff3Borders[8];
-extern const Word32 tnsCoeff4[16];
-extern const Word32 tnsCoeff4Borders[16];
-extern const Word32 invSBF[24];
-extern const Word16 sideInfoTabLong[MAX_SFB_LONG + 1];
-extern const Word16 sideInfoTabShort[MAX_SFB_SHORT + 1];
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/aacenc_core.h b/media/libstagefright/codecs/aacenc/inc/aacenc_core.h
deleted file mode 100644
index bb75b6d..0000000
--- a/media/libstagefright/codecs/aacenc/inc/aacenc_core.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		aacenc_core.h
-
-	Content:	aac encoder interface functions
-
-*******************************************************************************/
-
-#ifndef _aacenc_core_h_
-#define _aacenc_core_h_
-
-
-#include "typedef.h"
-#include "config.h"
-#include "bitenc.h"
-
-#include "psy_configuration.h"
-#include "psy_main.h"
-#include "qc_main.h"
-#include "psy_main.h"
-/*-------------------------- defines --------------------------------------*/
-
-
-/*-------------------- structure definitions ------------------------------*/
-typedef  struct {
-  Word32   sampleRate;            /* audio file sample rate */
-  Word32   bitRate;               /* encoder bit rate in bits/sec */
-  Word16   nChannelsIn;           /* number of channels on input (1,2) */
-  Word16   nChannelsOut;          /* number of channels on output (1,2) */
-  Word16   bandWidth;             /* targeted audio bandwidth in Hz */
-  Word16   adtsUsed;			  /* whether write adts header */
-} AACENC_CONFIG;
-
-
-typedef struct {
-
-  AACENC_CONFIG config;     /* Word16 size: 8 */
-
-  ELEMENT_INFO elInfo;      /* Word16 size: 4 */
-
-  QC_STATE qcKernel;        /* Word16 size: 6 + 5(PADDING) + 7(ELEMENT_BITS) + 54(ADJ_THR_STATE) = 72 */
-  QC_OUT   qcOut;           /* Word16 size: MAX_CHANNELS*920(QC_OUT_CHANNEL) + 5(QC_OUT_ELEMENT) + 7 = 932 / 1852 */
-
-  PSY_OUT    psyOut;        /* Word16 size: MAX_CHANNELS*186 + 2 = 188 / 374 */
-  PSY_KERNEL psyKernel;     /* Word16 size:  2587 / 4491 */
-
-  struct BITSTREAMENCODER_INIT bseInit; /* Word16 size: 6 */
-  struct BIT_BUF  bitStream;            /* Word16 size: 8 */
-  HANDLE_BIT_BUF  hBitStream;
-  int			  initOK;
-
-  short			*intbuf;
-  short			*encbuf;
-  short			*inbuf;
-  int			enclen;
-  int			inlen;
-  int			intlen;
-  int			uselength;
-
-  void			*hCheck;
-  VO_MEM_OPERATOR *voMemop;
-  VO_MEM_OPERATOR voMemoprator;
-
-}AAC_ENCODER; /* Word16 size: 3809 / 6851 */
-
-/*-----------------------------------------------------------------------------
-
-functionname: AacInitDefaultConfig
-description:  gives reasonable default configuration
-returns:      ---
-
-------------------------------------------------------------------------------*/
-void AacInitDefaultConfig(AACENC_CONFIG *config);
-
-/*---------------------------------------------------------------------------
-
-functionname:AacEncOpen
-description: allocate and initialize a new encoder instance
-returns:     AACENC_OK if success
-
----------------------------------------------------------------------------*/
-
-Word16  AacEncOpen (AAC_ENCODER				*hAacEnc,       /* pointer to an encoder handle, initialized on return */
-                    const  AACENC_CONFIG     config);        /* pre-initialized config struct */
-
-Word16 AacEncEncode(AAC_ENCODER		   *hAacEnc,
-                    Word16             *timeSignal,
-                    const UWord8       *ancBytes,      /*!< pointer to ancillary data bytes */
-                    Word16             *numAncBytes,   /*!< number of ancillary Data Bytes, send as fill element  */
-                    UWord8             *outBytes,      /*!< pointer to output buffer            */
-                    VO_U32             *numOutBytes    /*!< number of bytes in output buffer */
-                    );
-
-/*---------------------------------------------------------------------------
-
-functionname:AacEncClose
-description: deallocate an encoder instance
-
----------------------------------------------------------------------------*/
-
-void AacEncClose (AAC_ENCODER* hAacEnc, VO_MEM_OPERATOR *pMemOP); /* an encoder handle */
-
-#endif /* _aacenc_h_ */
diff --git a/media/libstagefright/codecs/aacenc/inc/adj_thr.h b/media/libstagefright/codecs/aacenc/inc/adj_thr.h
deleted file mode 100644
index 0f4bb5e..0000000
--- a/media/libstagefright/codecs/aacenc/inc/adj_thr.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		adj_thr.h
-
-	Content:	Threshold compensation function
-
-*******************************************************************************/
-
-#ifndef __ADJ_THR_H
-#define __ADJ_THR_H
-
-#include "adj_thr_data.h"
-#include "qc_data.h"
-#include "interface.h"
-
-Word16 bits2pe(const Word16 bits);
-
-Word32 AdjThrNew(ADJ_THR_STATE** phAdjThr,
-                 Word32 nElements);
-
-void AdjThrDelete(ADJ_THR_STATE *hAdjThr);
-
-void AdjThrInit(ADJ_THR_STATE *hAdjThr,
-                const Word32 peMean,
-                Word32 chBitrate);
-
-void AdjustThresholds(ADJ_THR_STATE *adjThrState,
-                      ATS_ELEMENT* AdjThrStateElement,
-                      PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-                      PSY_OUT_ELEMENT *psyOutElement,
-                      Word16 *chBitDistribution,
-                      Word16 logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                      Word16 sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
-                      QC_OUT_ELEMENT* qcOE,
-					  ELEMENT_BITS* elBits,
-					  const Word16 nChannels,
-                      const Word16 maxBitFac);
-
-void AdjThrUpdate(ATS_ELEMENT *AdjThrStateElement,
-                  const Word16 dynBitsUsed);
-
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/adj_thr_data.h b/media/libstagefright/codecs/aacenc/inc/adj_thr_data.h
deleted file mode 100644
index 30132d8..0000000
--- a/media/libstagefright/codecs/aacenc/inc/adj_thr_data.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		adj_thr_data.h
-
-	Content:	Threshold compensation parameter
-
-*******************************************************************************/
-
-#ifndef __ADJ_THR_DATA_H
-#define __ADJ_THR_DATA_H
-
-#include "typedef.h"
-#include "psy_const.h"
-#include "line_pe.h"
-
-typedef struct {
-   Word16 clipSaveLow, clipSaveHigh;
-   Word16 minBitSave, maxBitSave;
-   Word16 clipSpendLow, clipSpendHigh;
-   Word16 minBitSpend, maxBitSpend;
-} BRES_PARAM;
-
-typedef struct {
-   UWord8 modifyMinSnr;
-   Word16 startSfbL, startSfbS;
-} AH_PARAM;
-
-typedef struct {
-  Word32 maxRed;
-  Word32 startRatio, maxRatio;
-  Word32 redRatioFac;
-  Word32 redOffs;
-} MINSNR_ADAPT_PARAM;
-
-typedef struct {
-  /* parameters for bitreservoir control */
-  Word16 peMin, peMax;
-  /* constant offset to pe               */
-  Word16  peOffset;
-  /* avoid hole parameters               */
-  AH_PARAM ahParam;
-  /* paramters for adaptation of minSnr */
-  MINSNR_ADAPT_PARAM minSnrAdaptParam;
-  /* values for correction of pe */
-  Word16 peLast;
-  Word16 dynBitsLast;
-  Word16 peCorrectionFactor;
-} ATS_ELEMENT;
-
-typedef struct {
-  BRES_PARAM   bresParamLong, bresParamShort; /* Word16 size: 2*8 */
-  ATS_ELEMENT  adjThrStateElem;               /* Word16 size: 19 */
-} ADJ_THR_STATE;
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/band_nrg.h b/media/libstagefright/codecs/aacenc/inc/band_nrg.h
deleted file mode 100644
index 65453c0..0000000
--- a/media/libstagefright/codecs/aacenc/inc/band_nrg.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		band_nrg.h
-
-	Content:	Band/Line energy calculations functions
-
-*******************************************************************************/
-
-
-#ifndef _BAND_NRG_H
-#define _BAND_NRG_H
-
-#include "typedef.h"
-
-
-void CalcBandEnergy(const Word32 *mdctSpectrum,
-                    const Word16 *bandOffset,
-                    const Word16  numBands,
-                    Word32       *bandEnergy,
-                    Word32       *bandEnergySum);
-
-
-void CalcBandEnergyMS(const Word32 *mdctSpectrumLeft,
-                      const Word32 *mdctSpectrumRight,
-                      const Word16 *bandOffset,
-                      const Word16  numBands,
-                      Word32       *bandEnergyMid,
-                      Word32       *bandEnergyMidSum,
-                      Word32       *bandEnergySide,
-                      Word32       *bandEnergySideSum);
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/bit_cnt.h b/media/libstagefright/codecs/aacenc/inc/bit_cnt.h
deleted file mode 100644
index 266a219..0000000
--- a/media/libstagefright/codecs/aacenc/inc/bit_cnt.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		bit_cnt.h
-
-	Content:	Huffman Bitcounter & coder structure and functions
-
-*******************************************************************************/
-
-#ifndef __BITCOUNT_H
-#define __BITCOUNT_H
-
-#include "bitbuffer.h"
-#include "basic_op.h"
-#define INVALID_BITCOUNT (MAX_16/4)
-
-/*
-  code book number table
-*/
-
-enum codeBookNo{
-  CODE_BOOK_ZERO_NO=               0,
-  CODE_BOOK_1_NO=                  1,
-  CODE_BOOK_2_NO=                  2,
-  CODE_BOOK_3_NO=                  3,
-  CODE_BOOK_4_NO=                  4,
-  CODE_BOOK_5_NO=                  5,
-  CODE_BOOK_6_NO=                  6,
-  CODE_BOOK_7_NO=                  7,
-  CODE_BOOK_8_NO=                  8,
-  CODE_BOOK_9_NO=                  9,
-  CODE_BOOK_10_NO=                10,
-  CODE_BOOK_ESC_NO=               11,
-  CODE_BOOK_RES_NO=               12,
-  CODE_BOOK_PNS_NO=               13
-};
-
-/*
-  code book index table
-*/
-
-enum codeBookNdx{
-  CODE_BOOK_ZERO_NDX=0,
-  CODE_BOOK_1_NDX,
-  CODE_BOOK_2_NDX,
-  CODE_BOOK_3_NDX,
-  CODE_BOOK_4_NDX,
-  CODE_BOOK_5_NDX,
-  CODE_BOOK_6_NDX,
-  CODE_BOOK_7_NDX,
-  CODE_BOOK_8_NDX,
-  CODE_BOOK_9_NDX,
-  CODE_BOOK_10_NDX,
-  CODE_BOOK_ESC_NDX,
-  CODE_BOOK_RES_NDX,
-  CODE_BOOK_PNS_NDX,
-  NUMBER_OF_CODE_BOOKS
-};
-
-/*
-  code book lav table
-*/
-
-enum codeBookLav{
-  CODE_BOOK_ZERO_LAV=0,
-  CODE_BOOK_1_LAV=1,
-  CODE_BOOK_2_LAV=1,
-  CODE_BOOK_3_LAV=2,
-  CODE_BOOK_4_LAV=2,
-  CODE_BOOK_5_LAV=4,
-  CODE_BOOK_6_LAV=4,
-  CODE_BOOK_7_LAV=7,
-  CODE_BOOK_8_LAV=7,
-  CODE_BOOK_9_LAV=12,
-  CODE_BOOK_10_LAV=12,
-  CODE_BOOK_ESC_LAV=16,
-  CODE_BOOK_SCF_LAV=60,
-  CODE_BOOK_PNS_LAV=60
-};
-
-Word16 bitCount(const Word16 *aQuantSpectrum,
-                const Word16  noOfSpecLines,
-                Word16        maxVal,
-                Word16       *bitCountLut);
-
-Word16 codeValues(Word16 *values, Word16 width, Word16 codeBook, HANDLE_BIT_BUF hBitstream);
-
-Word16 bitCountScalefactorDelta(Word16 delta);
-Word16 codeScalefactorDelta(Word16 scalefactor, HANDLE_BIT_BUF hBitstream);
-
-
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/bitbuffer.h b/media/libstagefright/codecs/aacenc/inc/bitbuffer.h
deleted file mode 100644
index 7c79f07..0000000
--- a/media/libstagefright/codecs/aacenc/inc/bitbuffer.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		bitbuffer.h
-
-	Content:	Bit Buffer Management structure and functions
-
-*******************************************************************************/
-
-#ifndef BITBUFFER_H
-#define BITBUFFER_H
-
-#include "typedef.h"
-
-
-enum direction
-{
-  forwardDirection,
-  backwardDirection
-};
-
-
-/*!
-   The pointer 'pReadNext' points to the next available word, where bits can be read from. The pointer
-   'pWriteNext' points to the next available word, where bits can be written to. The pointer pBitBufBase
-   points to the start of the bitstream buffer and the pointer pBitBufEnd points to the end of the bitstream
-   buffer. The two pointers are used as lower-bound respectively upper-bound address for the modulo addressing
-   mode.
-
-   The element cntBits contains the currently available bits in the bit buffer. It will be incremented when
-   bits are written to the bitstream buffer and decremented when bits are read from the bitstream buffer.
-*/
-struct BIT_BUF
-{
-  UWord8 *pBitBufBase;          /*!< pointer points to first position in bitstream buffer */
-  UWord8 *pBitBufEnd;           /*!< pointer points to last position in bitstream buffer */
-
-  UWord8 *pWriteNext;           /*!< pointer points to next available word in bitstream buffer to write */
-
-  UWord32 cache;
-
-  Word16  wBitPos;              /*!< 31<=wBitPos<=0*/
-  Word16  cntBits;              /*!< number of available bits in the bitstream buffer
-                                     write bits to bitstream buffer  => increment cntBits
-                                     read bits from bitstream buffer => decrement cntBits */
-  Word16  size;                 /*!< size of bitbuffer in bits */
-  Word16  isValid;              /*!< indicates whether the instance has been initialized */
-}; /* size Word16: 8 */
-
-/*! Define pointer to bit buffer structure */
-typedef struct BIT_BUF *HANDLE_BIT_BUF;
-
-
-HANDLE_BIT_BUF CreateBitBuffer(HANDLE_BIT_BUF hBitBuf,
-                               UWord8 *pBitBufBase,
-                               Word16  bitBufSize);
-
-
-void DeleteBitBuffer(HANDLE_BIT_BUF *hBitBuf);
-
-
-Word16 GetBitsAvail(HANDLE_BIT_BUF hBitBuf);
-
-
-Word16 WriteBits(HANDLE_BIT_BUF hBitBuf,
-                 UWord32 writeValue,
-                 Word16 noBitsToWrite);
-
-void ResetBitBuf(HANDLE_BIT_BUF hBitBuf,
-                 UWord8 *pBitBufBase,
-                 Word16  bitBufSize);
-
-#define GetNrBitsAvailable(hBitBuf) ( (hBitBuf)->cntBits)
-#define GetNrBitsRead(hBitBuf)       ((hBitBuf)->size-(hBitBuf)->cntBits)
-
-#endif /* BITBUFFER_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/bitenc.h b/media/libstagefright/codecs/aacenc/inc/bitenc.h
deleted file mode 100644
index 6a58aeb..0000000
--- a/media/libstagefright/codecs/aacenc/inc/bitenc.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		bitenc.h
-
-	Content:	Bitstream encoder structure and functions
-
-*******************************************************************************/
-
-#ifndef _BITENC_H
-#define _BITENC_H
-
-#include "qc_data.h"
-#include "tns.h"
-#include "channel_map.h"
-#include "interface.h"
-
-struct BITSTREAMENCODER_INIT
-{
-  Word16 nChannels;
-  Word32 bitrate;
-  Word32 sampleRate;
-  Word16 profile;
-};
-
-
-
-Word16 WriteBitstream (HANDLE_BIT_BUF hBitstream,
-                       ELEMENT_INFO elInfo,
-                       QC_OUT *qcOut,
-                       PSY_OUT *psyOut,
-                       Word16 *globUsedBits,
-                       const UWord8 *ancBytes,
-					   Word16 samplerate
-                       );
-
-#endif /* _BITENC_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/block_switch.h b/media/libstagefright/codecs/aacenc/inc/block_switch.h
deleted file mode 100644
index a4d3e8f..0000000
--- a/media/libstagefright/codecs/aacenc/inc/block_switch.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		block_switch.h
-
-	Content:	Block switching structure and functions
-
-*******************************************************************************/
-
-#ifndef _BLOCK_SWITCH_H
-#define _BLOCK_SWITCH_H
-
-#include "typedef.h"
-
-
-/****************** Defines ******************************/
-#define BLOCK_SWITCHING_IIR_LEN 2                                           /* Length of HighPass-FIR-Filter for Attack-Detection */
-#define BLOCK_SWITCH_WINDOWS TRANS_FAC                                      /* number of windows for energy calculation */
-#define BLOCK_SWITCH_WINDOW_LEN FRAME_LEN_SHORT                             /* minimal granularity of energy calculation */
-
-
-
-/****************** Structures ***************************/
-typedef struct{
-  Word32 invAttackRatio;
-  Word16 windowSequence;
-  Word16 nextwindowSequence;
-  Flag attack;
-  Flag lastattack;
-  Word16 attackIndex;
-  Word16 lastAttackIndex;
-  Word16 noOfGroups;
-  Word16 groupLen[TRANS_FAC];
-  Word32 windowNrg[2][BLOCK_SWITCH_WINDOWS];     /* time signal energy in Subwindows (last and current) */
-  Word32 windowNrgF[2][BLOCK_SWITCH_WINDOWS];    /* filtered time signal energy in segments (last and current) */
-  Word32 iirStates[BLOCK_SWITCHING_IIR_LEN];     /* filter delay-line */
-  Word32 maxWindowNrg;                           /* max energy in subwindows */
-  Word32 accWindowNrg;                           /* recursively accumulated windowNrgF */
-}BLOCK_SWITCHING_CONTROL;
-
-
-
-
-
-Word16 InitBlockSwitching(BLOCK_SWITCHING_CONTROL *blockSwitchingControl,
-                          const Word32 bitRate, const Word16 nChannels);
-
-Word16 BlockSwitching(BLOCK_SWITCHING_CONTROL *blockSwitchingControl,
-                      Word16 *timeSignal,
-					  Word32  sampleRate,
-                      Word16 chIncrement);
-
-Word16 SyncBlockSwitching(BLOCK_SWITCHING_CONTROL *blockSwitchingControlLeft,
-                          BLOCK_SWITCHING_CONTROL *blockSwitchingControlRight,
-                          const Word16 noOfChannels);
-
-
-
-#endif  /* #ifndef _BLOCK_SWITCH_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/channel_map.h b/media/libstagefright/codecs/aacenc/inc/channel_map.h
deleted file mode 100644
index c361feb..0000000
--- a/media/libstagefright/codecs/aacenc/inc/channel_map.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		channel_map.h
-
-	Content:	channel mapping functions
-
-*******************************************************************************/
-
-#ifndef _CHANNEL_MAP_H
-#define _CHANNEL_MAP_H
-
-#include "psy_const.h"
-#include "qc_data.h"
-
-Word16 InitElementInfo (Word16 nChannels, ELEMENT_INFO* elInfo);
-
-Word16 InitElementBits(ELEMENT_BITS *elementBits,
-                       ELEMENT_INFO elInfo,
-                       Word32 bitrateTot,
-                       Word16 averageBitsTot,
-                       Word16 staticBitsTot);
-
-#endif /* CHANNEL_MAP_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/config.h b/media/libstagefright/codecs/aacenc/inc/config.h
deleted file mode 100644
index b0b4c26..0000000
--- a/media/libstagefright/codecs/aacenc/inc/config.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		config.h
-
-	Content:	aac encoder parameter
-
-*******************************************************************************/
-
-#ifndef _AACENC_CONFIG_H_
-#define _AACENC_CONFIG_H_
-
-#define MAX_CHANNELS        2
-
-#define AACENC_BLOCKSIZE    1024   /*! encoder only takes BLOCKSIZE samples at a time */
-#define AACENC_TRANS_FAC    8      /*! encoder short long ratio */
-
-
-#define MAXBITS_COEF		6144
-#define MINBITS_COEF		744
-
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/dyn_bits.h b/media/libstagefright/codecs/aacenc/inc/dyn_bits.h
deleted file mode 100644
index d3a8a67..0000000
--- a/media/libstagefright/codecs/aacenc/inc/dyn_bits.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		dyn_bits.h
-
-	Content:	Noiseless coder module structure and functions
-
-*******************************************************************************/
-
-#ifndef __DYN_BITS_H
-#define __DYN_BITS_H
-
-#include "psy_const.h"
-#include "tns.h"
-#include "bit_cnt.h"
-
-
-
-#define MAX_SECTIONS          MAX_GROUPED_SFB
-#define SECT_ESC_VAL_LONG    31
-#define SECT_ESC_VAL_SHORT    7
-#define CODE_BOOK_BITS        4
-#define SECT_BITS_LONG        5
-#define SECT_BITS_SHORT       3
-
-typedef struct
-{
-  Word16 codeBook;
-  Word16 sfbStart;
-  Word16 sfbCnt;
-  Word16 sectionBits;
-}
-SECTION_INFO;
-
-
-
-
-typedef struct
-{
-  Word16 blockType;
-  Word16 noOfGroups;
-  Word16 sfbCnt;
-  Word16 maxSfbPerGroup;
-  Word16 sfbPerGroup;
-  Word16 noOfSections;
-  SECTION_INFO sectionInfo[MAX_SECTIONS];
-  Word16 sideInfoBits;             /* sectioning bits       */
-  Word16 huffmanBits;              /* huffman    coded bits */
-  Word16 scalefacBits;             /* scalefac   coded bits */
-  Word16 firstScf;                 /* first scf to be coded */
-  Word16 bitLookUp[MAX_SFB_LONG*(CODE_BOOK_ESC_NDX+1)];
-  Word16 mergeGainLookUp[MAX_SFB_LONG];
-}
-SECTION_DATA; /*  Word16 size: 10 + 60(MAX_SECTIONS)*4(SECTION_INFO) + 51(MAX_SFB_LONG)*12(CODE_BOOK_ESC_NDX+1) + 51(MAX_SFB_LONG) = 913 */
-
-
-Word16 BCInit(void);
-
-Word16 dynBitCount(const Word16 *quantSpectrum,
-                   const UWord16 *maxValueInSfb,
-                   const Word16 *scalefac,
-                   const Word16 blockType,
-                   const Word16 sfbCnt,
-                   const Word16 maxSfbPerGroup,
-                   const Word16 sfbPerGroup,
-                   const Word16 *sfbOffset,
-                   SECTION_DATA *sectionData);
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/grp_data.h b/media/libstagefright/codecs/aacenc/inc/grp_data.h
deleted file mode 100644
index 4c1b2cb..0000000
--- a/media/libstagefright/codecs/aacenc/inc/grp_data.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		grp_data.h
-
-	Content:	Short block grouping function
-
-*******************************************************************************/
-
-#ifndef __GRP_DATA_H__
-#define __GRP_DATA_H__
-#include "psy_data.h"
-#include "typedefs.h"
-
-void
-groupShortData(Word32        *mdctSpectrum,
-               Word32        *tmpSpectrum,
-               SFB_THRESHOLD *sfbThreshold,
-               SFB_ENERGY    *sfbEnergy,
-               SFB_ENERGY    *sfbEnergyMS,
-               SFB_ENERGY    *sfbSpreadedEnergy,
-               const Word16   sfbCnt,
-               const Word16  *sfbOffset,
-               const Word16  *sfbMinSnr,
-               Word16        *groupedSfbOffset,
-               Word16        *maxSfbPerGroup,
-               Word16        *groupedSfbMinSnr,
-               const Word16   noOfGroups,
-               const Word16  *groupLen);
-
-#endif /* _INTERFACE_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/interface.h b/media/libstagefright/codecs/aacenc/inc/interface.h
deleted file mode 100644
index a42e6a9..0000000
--- a/media/libstagefright/codecs/aacenc/inc/interface.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		interface.h
-
-	Content:	psychoaccoustic/quantizer structures and interface
-
-*******************************************************************************/
-
-#ifndef _INTERFACE_H
-#define _INTERFACE_H
-
-#include "config.h"
-#include "psy_const.h"
-#include "psy_data.h"
-#include "typedefs.h"
-
-
-enum
-{
-  MS_NONE = 0,
-  MS_SOME = 1,
-  MS_ALL  = 2
-};
-
-enum
-{
-  MS_ON = 1
-};
-
-struct TOOLSINFO {
-  Word16 msDigest;
-  Word16 msMask[MAX_GROUPED_SFB];
-};
-
-
-typedef struct {
-  Word16  sfbCnt;
-  Word16  sfbPerGroup;
-  Word16  maxSfbPerGroup;
-  Word16  windowSequence;
-  Word16  windowShape;
-  Word16  groupingMask;
-  Word16  sfbOffsets[MAX_GROUPED_SFB+1];
-  Word16  mdctScale;
-  Word32 *sfbEnergy;
-  Word32 *sfbSpreadedEnergy;
-  Word32 *sfbThreshold;
-  Word32 *mdctSpectrum;
-  Word32  sfbEnSumLR;
-  Word32  sfbEnSumMS;
-  Word32 sfbDist[MAX_GROUPED_SFB];
-  Word32 sfbDistNew[MAX_GROUPED_SFB];
-  Word16  sfbMinSnr[MAX_GROUPED_SFB];
-  Word16 minSfMaxQuant[MAX_GROUPED_SFB];
-  Word16 minScfCalculated[MAX_GROUPED_SFB];
-  Word16 prevScfLast[MAX_GROUPED_SFB];
-  Word16 prevScfNext[MAX_GROUPED_SFB];
-  Word16 deltaPeLast[MAX_GROUPED_SFB];
-  TNS_INFO tnsInfo;
-} PSY_OUT_CHANNEL; /* Word16 size: 14 + 60(MAX_GROUPED_SFB) + 112(TNS_INFO) = 186 */
-
-typedef struct {
-  struct TOOLSINFO toolsInfo;
-  Word16 groupedSfbOffset[MAX_CHANNELS][MAX_GROUPED_SFB+1];  /* plus one for last dummy offset ! */
-  Word16 groupedSfbMinSnr[MAX_CHANNELS][MAX_GROUPED_SFB];
-} PSY_OUT_ELEMENT;
-
-typedef struct {
-  /* information shared by both channels  */
-  PSY_OUT_ELEMENT  psyOutElement;
-  /* information specific to each channel */
-  PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS];
-}PSY_OUT;
-
-void BuildInterface(Word32                 *mdctSpectrum,
-                    const Word16            mdctScale,
-                    SFB_THRESHOLD          *sfbThreshold,
-                    SFB_ENERGY             *sfbEnergy,
-                    SFB_ENERGY             *sfbSpreadedEnergy,
-                    const SFB_ENERGY_SUM    sfbEnergySumLR,
-                    const SFB_ENERGY_SUM    sfbEnergySumMS,
-                    const Word16            windowSequence,
-                    const Word16            windowShape,
-                    const Word16            sfbCnt,
-                    const Word16           *sfbOffset,
-                    const Word16            maxSfbPerGroup,
-                    const Word16           *groupedSfbMinSnr,
-                    const Word16            noOfGroups,
-                    const Word16           *groupLen,
-                    PSY_OUT_CHANNEL        *psyOutCh);
-
-#endif /* _INTERFACE_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/line_pe.h b/media/libstagefright/codecs/aacenc/inc/line_pe.h
deleted file mode 100644
index 116d5a8..0000000
--- a/media/libstagefright/codecs/aacenc/inc/line_pe.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		line_pe.h
-
-	Content:	Perceptual entropie module structure and functions
-
-*******************************************************************************/
-
-#ifndef __LINE_PE_H
-#define __LINE_PE_H
-
-
-#include "psy_const.h"
-#include "interface.h"
-
-
-typedef struct {
-   Word16 sfbLdEnergy[MAX_GROUPED_SFB];     /* 4*log(sfbEnergy)/log(2) */
-   Word16 sfbNLines4[MAX_GROUPED_SFB];      /* 4*number of relevant lines in sfb */
-   Word16 sfbPe[MAX_GROUPED_SFB];           /* pe for each sfb */
-   Word16 sfbConstPart[MAX_GROUPED_SFB];    /* constant part for each sfb */
-   Word16 sfbNActiveLines[MAX_GROUPED_SFB]; /* number of active lines in sfb */
-   Word16 pe;                               /* sum of sfbPe */
-   Word16 constPart;                        /* sum of sfbConstPart */
-   Word16 nActiveLines;                     /* sum of sfbNActiveLines */
-} PE_CHANNEL_DATA; /* size Word16: 303 */
-
-
-typedef struct {
-   PE_CHANNEL_DATA peChannelData[MAX_CHANNELS];
-   Word16 pe;
-   Word16 constPart;
-   Word16 nActiveLines;
-   Word16 offset;
-   Word16 ahFlag[MAX_CHANNELS][MAX_GROUPED_SFB];
-   Word32 thrExp[MAX_CHANNELS][MAX_GROUPED_SFB];
-   Word32 sfbPeFactors[MAX_CHANNELS][MAX_GROUPED_SFB];
-} PE_DATA; /* size Word16: 303 + 4 + 120 + 240 = 667 */
-
-
-
-
-void prepareSfbPe(PE_DATA *peData,
-                  PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
-                  Word16 logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                  Word16 sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
-                  const Word16 nChannels,
-                  const Word16 peOffset);
-
-
-
-
-
-void calcSfbPe(PE_DATA *peData,
-               PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-               const Word16 nChannels);
-
-
-
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/memalign.h b/media/libstagefright/codecs/aacenc/inc/memalign.h
deleted file mode 100644
index 30bbf45..0000000
--- a/media/libstagefright/codecs/aacenc/inc/memalign.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		memalign.h
-
-	Content:	Memory alloc alignments functions
-
-*******************************************************************************/
-
-#ifndef __VO_AACENC_MEM_ALIGN_H__
-#define __VO_AACENC_MEM_ALIGN_H__
-
-#include "voMem.h"
-#include "typedef.h"
-
-extern void *mem_malloc(VO_MEM_OPERATOR *pMemop, unsigned int size, unsigned char alignment, unsigned int CodecID);
-extern void mem_free(VO_MEM_OPERATOR *pMemop, void *mem_ptr, unsigned int CodecID);
-
-#endif	/* __VO_MEM_ALIGN_H__ */
-
-
-
diff --git a/media/libstagefright/codecs/aacenc/inc/ms_stereo.h b/media/libstagefright/codecs/aacenc/inc/ms_stereo.h
deleted file mode 100644
index 3c03dea..0000000
--- a/media/libstagefright/codecs/aacenc/inc/ms_stereo.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		ms_stereo.h
-
-	Content:	Declaration MS stereo processing structure and functions
-
-*******************************************************************************/
-
-#ifndef __MS_STEREO_H__
-#define __MS_STEREO_H__
-#include "typedef.h"
-
-void MsStereoProcessing(Word32       *sfbEnergyLeft,
-                        Word32       *sfbEnergyRight,
-                        const Word32 *sfbEnergyMid,
-                        const Word32 *sfbEnergySide,
-                        Word32       *mdctSpectrumLeft,
-                        Word32       *mdctSpectrumRight,
-                        Word32       *sfbThresholdLeft,
-                        Word32       *sfbThresholdRight,
-                        Word32       *sfbSpreadedEnLeft,
-                        Word32       *sfbSpreadedEnRight,
-                        Word16       *msDigest,
-                        Word16       *msMask,
-                        const Word16  sfbCnt,
-                        const Word16  sfbPerGroup,
-                        const Word16  maxSfbPerGroup,
-                        const Word16 *sfbOffset);
-
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/pre_echo_control.h b/media/libstagefright/codecs/aacenc/inc/pre_echo_control.h
deleted file mode 100644
index e719ba7..0000000
--- a/media/libstagefright/codecs/aacenc/inc/pre_echo_control.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		pre_echo_control.h
-
-	Content:	Pre echo control functions
-
-*******************************************************************************/
-
-#ifndef __PRE_ECHO_CONTROL_H
-#define __PRE_ECHO_CONTROL_H
-
-#include "typedefs.h"
-
-void InitPreEchoControl(Word32 *pbThresholdnm1,
-                        Word16  numPb,
-                        Word32 *pbThresholdQuiet);
-
-
-void PreEchoControl(Word32 *pbThresholdNm1,
-                    Word16  numPb,
-                    Word32  maxAllowedIncreaseFactor,
-                    Word16  minRemainingThresholdFactor,
-                    Word32 *pbThreshold,
-                    Word16  mdctScale,
-                    Word16  mdctScalenm1);
-
-#endif
-
diff --git a/media/libstagefright/codecs/aacenc/inc/psy_configuration.h b/media/libstagefright/codecs/aacenc/inc/psy_configuration.h
deleted file mode 100644
index f6981fa..0000000
--- a/media/libstagefright/codecs/aacenc/inc/psy_configuration.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		psy_configuration.h
-
-	Content:	Psychoaccoustic configuration structure and functions
-
-*******************************************************************************/
-
-#ifndef _PSY_CONFIGURATION_H
-#define _PSY_CONFIGURATION_H
-
-#include "typedefs.h"
-#include "psy_const.h"
-#include "tns.h"
-
-typedef struct{
-
-  Word16 sfbCnt;
-  Word16 sfbActive;   /* number of sf bands containing energy after lowpass */
-  const Word16 *sfbOffset;
-
-  Word32 sfbThresholdQuiet[MAX_SFB_LONG];
-
-  Word16 maxAllowedIncreaseFactor;   /* preecho control */
-  Word16 minRemainingThresholdFactor;
-
-  Word16 lowpassLine;
-  Word16 sampRateIdx;
-  Word32 clipEnergy;                 /* for level dependend tmn */
-
-  Word16 ratio;
-  Word16 sfbMaskLowFactor[MAX_SFB_LONG];
-  Word16 sfbMaskHighFactor[MAX_SFB_LONG];
-
-  Word16 sfbMaskLowFactorSprEn[MAX_SFB_LONG];
-  Word16 sfbMaskHighFactorSprEn[MAX_SFB_LONG];
-
-
-  Word16 sfbMinSnr[MAX_SFB_LONG];       /* minimum snr (formerly known as bmax) */
-
-  TNS_CONFIG tnsConf;
-
-}PSY_CONFIGURATION_LONG; /*Word16 size: 8 + 52 + 102 + 51 + 51 + 51 + 51 + 47 = 515 */
-
-
-typedef struct{
-
-  Word16 sfbCnt;
-  Word16 sfbActive;   /* number of sf bands containing energy after lowpass */
-  const Word16 *sfbOffset;
-
-  Word32 sfbThresholdQuiet[MAX_SFB_SHORT];
-
-  Word16 maxAllowedIncreaseFactor;   /* preecho control */
-  Word16 minRemainingThresholdFactor;
-
-  Word16 lowpassLine;
-  Word16 sampRateIdx;
-  Word32 clipEnergy;                 /* for level dependend tmn */
-
-  Word16 ratio;
-  Word16 sfbMaskLowFactor[MAX_SFB_SHORT];
-  Word16 sfbMaskHighFactor[MAX_SFB_SHORT];
-
-  Word16 sfbMaskLowFactorSprEn[MAX_SFB_SHORT];
-  Word16 sfbMaskHighFactorSprEn[MAX_SFB_SHORT];
-
-
-  Word16 sfbMinSnr[MAX_SFB_SHORT];       /* minimum snr (formerly known as bmax) */
-
-  TNS_CONFIG tnsConf;
-
-}PSY_CONFIGURATION_SHORT; /*Word16 size: 8 + 16 + 16 + 16 + 16 + 16 + 16 + 16 + 47 = 167 */
-
-
-/* Returns the sample rate index */
-Word32 GetSRIndex(Word32 sampleRate);
-
-
-Word16 InitPsyConfigurationLong(Word32 bitrate,
-                                Word32 samplerate,
-                                Word16 bandwidth,
-                                PSY_CONFIGURATION_LONG *psyConf);
-
-Word16 InitPsyConfigurationShort(Word32 bitrate,
-                                 Word32 samplerate,
-                                 Word16 bandwidth,
-                                 PSY_CONFIGURATION_SHORT *psyConf);
-
-#endif /* _PSY_CONFIGURATION_H */
-
-
-
diff --git a/media/libstagefright/codecs/aacenc/inc/psy_const.h b/media/libstagefright/codecs/aacenc/inc/psy_const.h
deleted file mode 100644
index 0b9f8c3..0000000
--- a/media/libstagefright/codecs/aacenc/inc/psy_const.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		psy_const.h
-
-	Content:	Global psychoacoustic constants structures
-
-*******************************************************************************/
-
-#ifndef _PSYCONST_H
-#define _PSYCONST_H
-
-#include "config.h"
-
-#define TRUE  1
-#define FALSE 0
-
-#define FRAME_LEN_LONG    AACENC_BLOCKSIZE
-#define TRANS_FAC         8
-#define FRAME_LEN_SHORT   (FRAME_LEN_LONG/TRANS_FAC)
-
-
-
-/* Block types */
-enum
-{
-  LONG_WINDOW = 0,
-  START_WINDOW,
-  SHORT_WINDOW,
-  STOP_WINDOW
-};
-
-/* Window shapes */
-enum
-{
-  SINE_WINDOW = 0,
-  KBD_WINDOW  = 1
-};
-
-/*
-  MS stuff
-*/
-enum
-{
-  SI_MS_MASK_NONE = 0,
-  SI_MS_MASK_SOME = 1,
-  SI_MS_MASK_ALL  = 2
-};
-
-#define MAX_NO_OF_GROUPS 4
-#define MAX_SFB_SHORT   15  /* 15 for a memory optimized implementation, maybe 16 for convenient debugging */
-#define MAX_SFB_LONG    51  /* 51 for a memory optimized implementation, maybe 64 for convenient debugging */
-#define MAX_SFB         (MAX_SFB_SHORT > MAX_SFB_LONG ? MAX_SFB_SHORT : MAX_SFB_LONG)   /* = MAX_SFB_LONG */
-#define MAX_GROUPED_SFB (MAX_NO_OF_GROUPS*MAX_SFB_SHORT > MAX_SFB_LONG ? \
-                         MAX_NO_OF_GROUPS*MAX_SFB_SHORT : MAX_SFB_LONG)
-
-#define BLOCK_SWITCHING_OFFSET		   (1*1024+3*128+64+128)
-#define BLOCK_SWITCHING_DATA_SIZE          FRAME_LEN_LONG
-
-#define TRANSFORM_OFFSET_LONG    0
-#define TRANSFORM_OFFSET_SHORT   448
-
-#define LOG_NORM_PCM          (-15)
-
-#define NUM_SAMPLE_RATES	12
-
-#endif /* _PSYCONST_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/psy_data.h b/media/libstagefright/codecs/aacenc/inc/psy_data.h
deleted file mode 100644
index 3ea6a84..0000000
--- a/media/libstagefright/codecs/aacenc/inc/psy_data.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		psy_data.h
-
-	Content:	Psychoacoustic data and structures
-
-*******************************************************************************/
-
-#ifndef _PSY_DATA_H
-#define _PSY_DATA_H
-
-#include "block_switch.h"
-#include "tns.h"
-
-/*
-  the structs can be implemented as unions
-*/
-
-typedef struct{
-  Word32 sfbLong[MAX_GROUPED_SFB];
-  Word32 sfbShort[TRANS_FAC][MAX_SFB_SHORT];
-}SFB_THRESHOLD; /* Word16 size: 260 */
-
-typedef struct{
-  Word32 sfbLong[MAX_GROUPED_SFB];
-  Word32 sfbShort[TRANS_FAC][MAX_SFB_SHORT];
-}SFB_ENERGY; /* Word16 size: 260 */
-
-typedef struct{
-  Word32 sfbLong;
-  Word32 sfbShort[TRANS_FAC];
-}SFB_ENERGY_SUM; /* Word16 size: 18 */
-
-
-typedef struct{
-  BLOCK_SWITCHING_CONTROL   blockSwitchingControl;          /* block switching */
-  Word16                    *mdctDelayBuffer;               /* mdct delay buffer [BLOCK_SWITCHING_OFFSET]*/
-  Word32                    sfbThresholdnm1[MAX_SFB];       /* PreEchoControl */
-  Word16                    mdctScalenm1;                   /* scale of last block's mdct (PreEchoControl) */
-
-  SFB_THRESHOLD             sfbThreshold;                   /* adapt           */
-  SFB_ENERGY                sfbEnergy;                      /* sfb Energy      */
-  SFB_ENERGY                sfbEnergyMS;
-  SFB_ENERGY_SUM            sfbEnergySum;
-  SFB_ENERGY_SUM            sfbEnergySumMS;
-  SFB_ENERGY                sfbSpreadedEnergy;
-
-  Word32                    *mdctSpectrum;                  /* mdct spectrum [FRAME_LEN_LONG] */
-  Word16                    mdctScale;                      /* scale of mdct   */
-}PSY_DATA; /* Word16 size: 4 + 87 + 102 + 360 + 360 + 360 + 18 + 18 + 360 = 1669 */
-
-#endif /* _PSY_DATA_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/psy_main.h b/media/libstagefright/codecs/aacenc/inc/psy_main.h
deleted file mode 100644
index 2ccac60..0000000
--- a/media/libstagefright/codecs/aacenc/inc/psy_main.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		psy_main.h
-
-	Content:	Psychoacoustic major function block
-
-*******************************************************************************/
-
-#ifndef _PSYMAIN_H
-#define _PSYMAIN_H
-
-#include "psy_configuration.h"
-#include "qc_data.h"
-#include "memalign.h"
-
-/*
-  psy kernel
-*/
-typedef struct  {
-  PSY_CONFIGURATION_LONG  psyConfLong;           /* Word16 size: 515 */
-  PSY_CONFIGURATION_SHORT psyConfShort;          /* Word16 size: 167 */
-  PSY_DATA                psyData[MAX_CHANNELS]; /* Word16 size: MAX_CHANNELS*1669*/
-  TNS_DATA                tnsData[MAX_CHANNELS]; /* Word16 size: MAX_CHANNELS*235 */
-  Word32*                 pScratchTns;
-  Word16				  sampleRateIdx;
-}PSY_KERNEL; /* Word16 size: 2587 / 4491 */
-
-
-Word16 PsyNew( PSY_KERNEL  *hPsy, Word32 nChan, VO_MEM_OPERATOR *pMemOP);
-Word16 PsyDelete( PSY_KERNEL  *hPsy, VO_MEM_OPERATOR *pMemOP);
-
-Word16 PsyOutNew( PSY_OUT *hPsyOut, VO_MEM_OPERATOR *pMemOP);
-Word16 PsyOutDelete( PSY_OUT *hPsyOut, VO_MEM_OPERATOR *pMemOP);
-
-Word16 psyMainInit( PSY_KERNEL *hPsy,
-                    Word32 sampleRate,
-                    Word32 bitRate,
-                    Word16 channels,
-                    Word16 tnsMask,
-                    Word16 bandwidth);
-
-
-Word16 psyMain(Word16                   nChannels,   /*!< total number of channels */
-               ELEMENT_INFO             *elemInfo,
-               Word16                   *timeSignal, /*!< interleaved time signal */
-               PSY_DATA                 psyData[MAX_CHANNELS],
-               TNS_DATA                 tnsData[MAX_CHANNELS],
-               PSY_CONFIGURATION_LONG*  psyConfLong,
-               PSY_CONFIGURATION_SHORT* psyConfShort,
-               PSY_OUT_CHANNEL          psyOutChannel[MAX_CHANNELS],
-               PSY_OUT_ELEMENT          *psyOutElement,
-               Word32                   *pScratchTns,
-			   Word32					sampleRate);
-
-#endif /* _PSYMAIN_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/qc_data.h b/media/libstagefright/codecs/aacenc/inc/qc_data.h
deleted file mode 100644
index 109922d..0000000
--- a/media/libstagefright/codecs/aacenc/inc/qc_data.h
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		qc_data.h
-
-	Content:	Quantizing & coding structures
-
-*******************************************************************************/
-
-#ifndef _QC_DATA_H
-#define _QC_DATA_H
-
-#include "psy_const.h"
-#include "dyn_bits.h"
-#include "adj_thr_data.h"
-
-
-#define MAX_MODES 10
-
-typedef enum {
-  MODE_INVALID = 0,
-  MODE_1,        /* mono      */
-  MODE_1_1,      /* dual mono */
-  MODE_2         /* stereo    */
-} ENCODER_MODE;
-
-typedef enum {
-  ID_SCE=0,     /* Single Channel Element   */
-  ID_CPE=1,     /* Channel Pair Element     */
-  ID_CCE=2,     /* Coupling Channel Element */
-  ID_LFE=3,     /* LFE Channel Element      */
-  ID_DSE=4,     /* current one DSE element for ancillary is supported */
-  ID_PCE=5,
-  ID_FIL=6,
-  ID_END=7
-}ELEMENT_TYPE;
-
-typedef struct {
-  ELEMENT_TYPE elType;
-  Word16 instanceTag;
-  Word16 nChannelsInEl;
-  Word16 ChannelIndex[MAX_CHANNELS];
-} ELEMENT_INFO;
-
-typedef struct {
-  Word32 paddingRest;
-} PADDING;
-
-
-/* Quantizing & coding stage */
-
-struct QC_INIT{
-  ELEMENT_INFO *elInfo;
-  Word16 maxBits;     /* maximum number of bits in reservoir  */
-  Word16 averageBits; /* average number of bits we should use */
-  Word16 bitRes;
-  Word16 meanPe;
-  Word32 chBitrate;
-  Word16 maxBitFac;
-  Word32 bitrate;
-
-  PADDING padding;
-};
-
-typedef struct
-{
-  Word16          *quantSpec;       /* [FRAME_LEN_LONG];                            */
-  UWord16         *maxValueInSfb;   /* [MAX_GROUPED_SFB];                           */
-  Word16          *scf;             /* [MAX_GROUPED_SFB];                           */
-  Word16          globalGain;
-  Word16          mdctScale;
-  Word16          groupingMask;
-  SECTION_DATA    sectionData;
-  Word16          windowShape;
-} QC_OUT_CHANNEL;
-
-typedef struct
-{
-  Word16		  adtsUsed;
-  Word16          staticBitsUsed; /* for verification purposes */
-  Word16          dynBitsUsed;    /* for verification purposes */
-  Word16          pe;
-  Word16          ancBitsUsed;
-  Word16          fillBits;
-} QC_OUT_ELEMENT;
-
-typedef struct
-{
-  QC_OUT_CHANNEL  qcChannel[MAX_CHANNELS];
-  QC_OUT_ELEMENT  qcElement;
-  Word16          totStaticBitsUsed; /* for verification purposes */
-  Word16          totDynBitsUsed;    /* for verification purposes */
-  Word16          totAncBitsUsed;    /* for verification purposes */
-  Word16          totFillBits;
-  Word16          alignBits;
-  Word16          bitResTot;
-  Word16          averageBitsTot;
-} QC_OUT;
-
-typedef struct {
-  Word32 chBitrate;
-  Word16 averageBits;               /* brutto -> look ancillary.h */
-  Word16 maxBits;
-  Word16 bitResLevel;
-  Word16 maxBitResBits;
-  Word16 relativeBits;            /* Bits relative to total Bits scaled down by 2 */
-} ELEMENT_BITS;
-
-typedef struct
-{
-  /* this is basically struct QC_INIT */
-  Word16 averageBitsTot;
-  Word16 maxBitsTot;
-  Word16 globStatBits;
-  Word16 nChannels;
-  Word16 bitResTot;
-
-  Word16 maxBitFac;
-
-  PADDING   padding;
-
-  ELEMENT_BITS  elementBits;
-  ADJ_THR_STATE adjThr;
-
-  Word16 logSfbFormFactor[MAX_CHANNELS][MAX_GROUPED_SFB];
-  Word16 sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB];
-  Word16 logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB];
-} QC_STATE;
-
-#endif /* _QC_DATA_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/qc_main.h b/media/libstagefright/codecs/aacenc/inc/qc_main.h
deleted file mode 100644
index 8f83973..0000000
--- a/media/libstagefright/codecs/aacenc/inc/qc_main.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		qc_main.h
-
-	Content:	Quantizing & coding functions
-
-*******************************************************************************/
-
-#ifndef _QC_MAIN_H
-#define _QC_MAIN_H
-
-#include "qc_data.h"
-#include "interface.h"
-#include "memalign.h"
-
-/* Quantizing & coding stage */
-
-Word16 QCOutNew(QC_OUT *hQC, Word16 nChannels, VO_MEM_OPERATOR *pMemOP);
-
-void QCOutDelete(QC_OUT *hQC, VO_MEM_OPERATOR *pMemOP);
-
-Word16 QCNew(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP);
-
-Word16 QCInit(QC_STATE *hQC,
-              struct QC_INIT *init);
-
-void QCDelete(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP);
-
-
-Word16 QCMain(QC_STATE *hQC,
-              ELEMENT_BITS* elBits,
-              ATS_ELEMENT* adjThrStateElement,
-              PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS], /* may be modified in-place */
-              PSY_OUT_ELEMENT* psyOutElement,
-              QC_OUT_CHANNEL  qcOutChannel[MAX_CHANNELS],   /* out                      */
-              QC_OUT_ELEMENT* qcOutElement,
-              Word16 nChannels,
-			  Word16 ancillaryDataBytes);     /* returns error code       */
-
-void updateBitres(QC_STATE* qcKernel,
-                  QC_OUT* qcOut);
-
-Word16 FinalizeBitConsumption(QC_STATE *hQC,
-                              QC_OUT* qcOut);
-
-Word16 AdjustBitrate(QC_STATE *hQC,
-                     Word32 bitRate,
-                     Word32 sampleRate);
-
-#endif /* _QC_MAIN_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/quantize.h b/media/libstagefright/codecs/aacenc/inc/quantize.h
deleted file mode 100644
index 1cafef6..0000000
--- a/media/libstagefright/codecs/aacenc/inc/quantize.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		quantize.h
-
-	Content:	Quantization functions
-
-*******************************************************************************/
-
-#ifndef _QUANTIZE_H_
-#define _QUANTIZE_H_
-#include "typedefs.h"
-
-/* quantizing */
-
-#define MAX_QUANT 8191
-
-void QuantizeSpectrum(Word16 sfbCnt,
-                      Word16 maxSfbPerGroup,
-                      Word16 sfbPerGroup,
-                      Word16 *sfbOffset, Word32 *mdctSpectrum,
-                      Word16 globalGain, Word16 *scalefactors,
-                      Word16 *quantizedSpectrum);
-
-Word32 calcSfbDist(const Word32 *spec,
-                   Word16  sfbWidth,
-                   Word16  gain);
-
-#endif /* _QUANTIZE_H_ */
diff --git a/media/libstagefright/codecs/aacenc/inc/sf_estim.h b/media/libstagefright/codecs/aacenc/inc/sf_estim.h
deleted file mode 100644
index 997eba5..0000000
--- a/media/libstagefright/codecs/aacenc/inc/sf_estim.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		sf_estim.h
-
-	Content:	Scale factor estimation functions
-
-*******************************************************************************/
-
-#ifndef __SF_ESTIM_H__
-#define __SF_ESTIM_H__
-/*
-   Scale factor estimation
- */
-#include "psy_const.h"
-#include "interface.h"
-#include "qc_data.h"
-
-void
-CalcFormFactor(Word16          logSfbFormFactor[MAX_CHANNELS][MAX_GROUPED_SFB],
-               Word16          sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
-               Word16          logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-               PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-               const Word16    nChannels);
-
-void
-EstimateScaleFactors(PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-                     QC_OUT_CHANNEL  qcOutChannel[MAX_CHANNELS],
-                     Word16          logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                     Word16          logSfbFormFactor[MAX_CHANNELS][MAX_GROUPED_SFB],
-                     Word16          sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
-                     const Word16    nChannels);
-#endif
diff --git a/media/libstagefright/codecs/aacenc/inc/spreading.h b/media/libstagefright/codecs/aacenc/inc/spreading.h
deleted file mode 100644
index 0c96fc7..0000000
--- a/media/libstagefright/codecs/aacenc/inc/spreading.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		spreading.h
-
-	Content:	Spreading of energy functions
-
-*******************************************************************************/
-
-#ifndef _SPREADING_H
-#define _SPREADING_H
-#include "typedefs.h"
-
-
-void SpreadingMax(const Word16 pbCnt,
-                  const Word16 *maskLowFactor,
-                  const Word16 *maskHighFactor,
-                  Word32       *pbSpreadedEnergy);
-
-#endif /* #ifndef _SPREADING_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/stat_bits.h b/media/libstagefright/codecs/aacenc/inc/stat_bits.h
deleted file mode 100644
index 9cddc1d..0000000
--- a/media/libstagefright/codecs/aacenc/inc/stat_bits.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		stat_bits.h
-
-	Content:	Static bit counter functions
-
-*******************************************************************************/
-
-#ifndef __STAT_BITS_H
-#define __STAT_BITS_H
-
-#include "psy_const.h"
-#include "interface.h"
-
-Word16 countStaticBitdemand(PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-                            PSY_OUT_ELEMENT *psyOutElement,
-                            Word16 nChannels,
-							Word16 adtsUsed);
-
-#endif /* __STAT_BITS_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/tns.h b/media/libstagefright/codecs/aacenc/inc/tns.h
deleted file mode 100644
index 40cfaee..0000000
--- a/media/libstagefright/codecs/aacenc/inc/tns.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		tns.h
-
-	Content:	TNS structures
-
-*******************************************************************************/
-
-#ifndef _TNS_H
-#define _TNS_H
-
-#include "typedef.h"
-#include "psy_const.h"
-
-
-
-#define TNS_MAX_ORDER 12
-#define TNS_MAX_ORDER_SHORT 5
-
-#define FILTER_DIRECTION    0
-
-typedef struct{ /*stuff that is tabulated dependent on bitrate etc. */
-  Word16     threshOn;                /* min. prediction gain for using tns TABUL * 100*/
-  Word32     lpcStartFreq;            /* lowest freq for lpc TABUL*/
-  Word32     lpcStopFreq;             /* TABUL */
-  Word32     tnsTimeResolution;
-}TNS_CONFIG_TABULATED;
-
-
-typedef struct {   /*assigned at InitTime*/
-  Word16 tnsActive;
-  Word16 tnsMaxSfb;
-
-  Word16 maxOrder;                /* max. order of tns filter */
-  Word16 tnsStartFreq;            /* lowest freq. for tns filtering */
-  Word16 coefRes;
-
-  TNS_CONFIG_TABULATED confTab;
-
-  Word32 acfWindow[TNS_MAX_ORDER+1];
-
-  Word16 tnsStartBand;
-  Word16 tnsStartLine;
-
-  Word16 tnsStopBand;
-  Word16 tnsStopLine;
-
-  Word16 lpcStartBand;
-  Word16 lpcStartLine;
-
-  Word16 lpcStopBand;
-  Word16 lpcStopLine;
-
-  Word16 tnsRatioPatchLowestCb;
-  Word16 tnsModifyBeginCb;
-
-  Word16 threshold; /* min. prediction gain for using tns TABUL * 100 */
-
-}TNS_CONFIG;
-
-
-typedef struct {
-  Word16 tnsActive;
-  Word32 parcor[TNS_MAX_ORDER];
-  Word16 predictionGain;
-} TNS_SUBBLOCK_INFO; /* Word16 size: 26 */
-
-typedef struct{
-  TNS_SUBBLOCK_INFO subBlockInfo[TRANS_FAC];
-} TNS_DATA_SHORT;
-
-typedef struct{
-  TNS_SUBBLOCK_INFO subBlockInfo;
-} TNS_DATA_LONG;
-
-typedef struct{
-  TNS_DATA_LONG tnsLong;
-  TNS_DATA_SHORT tnsShort;
-}TNS_DATA_RAW;
-
-typedef struct{
-  Word16 numOfSubblocks;
-  TNS_DATA_RAW dataRaw;
-}TNS_DATA; /* Word16 size: 1 + 8*26 + 26 = 235 */
-
-typedef struct{
-  Word16 tnsActive[TRANS_FAC];
-  Word16 coefRes[TRANS_FAC];
-  Word16 length[TRANS_FAC];
-  Word16 order[TRANS_FAC];
-  Word16 coef[TRANS_FAC*TNS_MAX_ORDER_SHORT];
-}TNS_INFO; /* Word16 size: 72 */
-
-#endif /* _TNS_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/tns_func.h b/media/libstagefright/codecs/aacenc/inc/tns_func.h
deleted file mode 100644
index 02df24d..0000000
--- a/media/libstagefright/codecs/aacenc/inc/tns_func.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		tns_func.h
-
-	Content:	TNS functions
-
-*******************************************************************************/
-
-/*
-   Temporal noise shaping
- */
-#ifndef _TNS_FUNC_H
-#define _TNS_FUNC_H
-#include "typedef.h"
-#include "psy_configuration.h"
-
-Word16 InitTnsConfigurationLong(Word32 bitrate,
-                                Word32 samplerate,
-                                Word16 channels,
-                                TNS_CONFIG *tnsConfig,
-                                PSY_CONFIGURATION_LONG *psyConfig,
-                                Word16 active);
-
-Word16 InitTnsConfigurationShort(Word32 bitrate,
-                                 Word32 samplerate,
-                                 Word16 channels,
-                                 TNS_CONFIG *tnsConfig,
-                                 PSY_CONFIGURATION_SHORT *psyConfig,
-                                 Word16 active);
-
-Word32 TnsDetect(TNS_DATA* tnsData,
-                 TNS_CONFIG tC,
-                 Word32* pScratchTns,
-                 const Word16 sfbOffset[],
-                 Word32* spectrum,
-                 Word16 subBlockNumber,
-                 Word16 blockType,
-                 Word32 * sfbEnergy);
-
-void TnsSync(TNS_DATA *tnsDataDest,
-             const TNS_DATA *tnsDataSrc,
-             const TNS_CONFIG tC,
-             const Word16 subBlockNumber,
-             const Word16 blockType);
-
-Word16 TnsEncode(TNS_INFO* tnsInfo,
-                 TNS_DATA* tnsData,
-                 Word16 numOfSfb,
-                 TNS_CONFIG tC,
-                 Word16 lowPassLine,
-                 Word32* spectrum,
-                 Word16 subBlockNumber,
-                 Word16 blockType);
-
-void ApplyTnsMultTableToRatios(Word16 startCb,
-                               Word16 stopCb,
-                               TNS_SUBBLOCK_INFO subInfo,
-                               Word32 *thresholds);
-
-
-#endif /* _TNS_FUNC_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/tns_param.h b/media/libstagefright/codecs/aacenc/inc/tns_param.h
deleted file mode 100644
index 0aa33c3..0000000
--- a/media/libstagefright/codecs/aacenc/inc/tns_param.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		tns_param.h
-
-	Content:	TNS parameters
-
-*******************************************************************************/
-
-/*
-   TNS parameters
- */
-#ifndef _TNS_PARAM_H
-#define _TNS_PARAM_H
-
-#include "tns.h"
-
-typedef struct{
-  Word32 samplingRate;
-  Word16 maxBandLong;
-  Word16 maxBandShort;
-}TNS_MAX_TAB_ENTRY;
-
-typedef struct{
-    Word32 bitRateFrom;
-    Word32 bitRateTo;
-    const TNS_CONFIG_TABULATED *paramMono_Long;  /* contains TNS parameters */
-    const TNS_CONFIG_TABULATED *paramMono_Short;
-    const TNS_CONFIG_TABULATED *paramStereo_Long;
-    const TNS_CONFIG_TABULATED *paramStereo_Short;
-}TNS_INFO_TAB;
-
-
-void GetTnsParam(TNS_CONFIG_TABULATED *tnsConfigTab,
-                 Word32 bitRate, Word16 channels, Word16 blockType);
-
-void GetTnsMaxBands(Word32 samplingRate, Word16 blockType, Word16* tnsMaxSfb);
-
-#endif /* _TNS_PARAM_H */
diff --git a/media/libstagefright/codecs/aacenc/inc/transform.h b/media/libstagefright/codecs/aacenc/inc/transform.h
deleted file mode 100644
index 311cef5..0000000
--- a/media/libstagefright/codecs/aacenc/inc/transform.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		transform.h
-
-	Content:	MDCT Transform functions
-
-*******************************************************************************/
-
-#ifndef  __TRANSFORM_H__
-#define __TRANSFORM_H__
-
-#include "typedef.h"
-
-void Transform_Real(Word16 *mdctDelayBuffer,
-                    Word16 *timeSignal,
-                    Word16 chIncrement,     /*! channel increment */
-                    Word32 *realOut,
-                    Word16 *mdctScale,
-                    Word16 windowSequence
-                    );
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/src/aac_rom.c b/media/libstagefright/codecs/aacenc/src/aac_rom.c
deleted file mode 100644
index f08f3a9..0000000
--- a/media/libstagefright/codecs/aacenc/src/aac_rom.c
+++ /dev/null
@@ -1,2363 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		aac_rom.c
-
-	Content:	constant tables
-
-*******************************************************************************/
-
-#include "aac_rom.h"
-
-#if defined (ARMV5E) && !defined (ARMV7Neon)
-
-/*
- *  Q30 for 128 and 1024
- *
- * for (i = 0; i < num/4; i++) {
- *   angle = (i + 0.125) * M_PI / num;
- *   x = cos(angle) * (1 << 30);
- *   x = sin(angle) * (1 << 30);
- *
- *   angle = (num/2 - 1 - i + 0.125) * M_PI / num;
- *   x = cos(angle) * (1 << 30);
- *   x = sin(angle) * (1 << 30);
- * }
- */
-const int cossintab[128 + 1024] = {
-	/* 128 */
-	0x3fffec43, 0x003243f1, 0x015fd4d2, 0x3ffc38d1, 0x3ff9c13a, 0x01c454f5, 0x02f1b755, 0x3feea776,
-	0x3fe9b8a9, 0x03562038, 0x0483259d, 0x3fd73a4a, 0x3fcfd50b, 0x04e767c5, 0x0613e1c5, 0x3fb5f4ea,
-	0x3fac1a5b, 0x0677edbb, 0x07a3adff, 0x3f8adc77, 0x3f7e8e1e, 0x08077457, 0x09324ca7, 0x3f55f796,
-	0x3f473759, 0x0995bdfd, 0x0abf8043, 0x3f174e70, 0x3f061e95, 0x0b228d42, 0x0c4b0b94, 0x3eceeaad,
-	0x3ebb4ddb, 0x0cada4f5, 0x0dd4b19a, 0x3e7cd778, 0x3e66d0b4, 0x0e36c82a, 0x0f5c35a3, 0x3e212179,
-	0x3e08b42a, 0x0fbdba40, 0x10e15b4e, 0x3dbbd6d4, 0x3da106bd, 0x11423ef0, 0x1263e699, 0x3d4d0728,
-	0x3d2fd86c, 0x12c41a4f, 0x13e39be9, 0x3cd4c38b, 0x3cb53aaa, 0x144310dd, 0x15604013, 0x3c531e88,
-	0x3c314060, 0x15bee78c, 0x16d99864, 0x3bc82c1f, 0x3ba3fde7, 0x173763c9, 0x184f6aab, 0x3b3401bb,
-	0x3b0d8909, 0x18ac4b87, 0x19c17d44, 0x3a96b636, 0x3a6df8f8, 0x1a1d6544, 0x1b2f971e, 0x39f061d2,
-	0x39c5664f, 0x1b8a7815, 0x1c997fc4, 0x39411e33, 0x3913eb0e, 0x1cf34baf, 0x1dfeff67, 0x38890663,
-	0x3859a292, 0x1e57a86d, 0x1f5fdee6, 0x37c836c2, 0x3796a996, 0x1fb7575c, 0x20bbe7d8, 0x36fecd0e,
-	0x36cb1e2a, 0x21122240, 0x2212e492, 0x362ce855, 0x35f71fb1, 0x2267d3a0, 0x2364a02e, 0x3552a8f4,
-	0x351acedd, 0x23b836ca, 0x24b0e699, 0x34703095, 0x34364da6, 0x250317df, 0x25f78497, 0x3385a222,
-	0x3349bf48, 0x264843d9, 0x273847c8, 0x329321c7, 0x32554840, 0x27878893, 0x2872feb6, 0x3198d4ea,
-	0x31590e3e, 0x28c0b4d2, 0x29a778db, 0x3096e223, 0x30553828, 0x29f3984c, 0x2ad586a3, 0x2f8d713a,
-	0x2f49ee0f, 0x2b2003ac, 0x2bfcf97c, 0x2e7cab1c, 0x2e37592c, 0x2c45c8a0, 0x2d1da3d5, 0x2d64b9da,
-	/* 1024 */
-	0x3fffffb1, 0x0006487f, 0x002bfb74, 0x3ffff0e3, 0x3fffe705, 0x00388c6e, 0x005e3f4c, 0x3fffba9b,
-	0x3fffa6de, 0x006ad03b, 0x009082ea, 0x3fff5cd8, 0x3fff3f3c, 0x009d13c5, 0x00c2c62f, 0x3ffed79b,
-	0x3ffeb021, 0x00cf56ef, 0x00f508fc, 0x3ffe2ae5, 0x3ffdf98c, 0x01019998, 0x01274b31, 0x3ffd56b5,
-	0x3ffd1b7e, 0x0133dba3, 0x01598cb1, 0x3ffc5b0c, 0x3ffc15f7, 0x01661cf0, 0x018bcd5b, 0x3ffb37ec,
-	0x3ffae8f9, 0x01985d60, 0x01be0d11, 0x3ff9ed53, 0x3ff99483, 0x01ca9cd4, 0x01f04bb4, 0x3ff87b44,
-	0x3ff81896, 0x01fcdb2e, 0x02228924, 0x3ff6e1bf, 0x3ff67534, 0x022f184d, 0x0254c544, 0x3ff520c5,
-	0x3ff4aa5d, 0x02615414, 0x0286fff3, 0x3ff33858, 0x3ff2b813, 0x02938e62, 0x02b93914, 0x3ff12878,
-	0x3ff09e56, 0x02c5c71a, 0x02eb7086, 0x3feef126, 0x3fee5d28, 0x02f7fe1c, 0x031da62b, 0x3fec9265,
-	0x3febf48b, 0x032a3349, 0x034fd9e5, 0x3fea0c35, 0x3fe96480, 0x035c6682, 0x03820b93, 0x3fe75e98,
-	0x3fe6ad08, 0x038e97a9, 0x03b43b17, 0x3fe48990, 0x3fe3ce26, 0x03c0c69e, 0x03e66852, 0x3fe18d1f,
-	0x3fe0c7da, 0x03f2f342, 0x04189326, 0x3fde6945, 0x3fdd9a27, 0x04251d77, 0x044abb73, 0x3fdb1e06,
-	0x3fda450f, 0x0457451d, 0x047ce11a, 0x3fd7ab64, 0x3fd6c894, 0x04896a16, 0x04af03fc, 0x3fd4115f,
-	0x3fd324b7, 0x04bb8c42, 0x04e123fa, 0x3fd04ffc, 0x3fcf597c, 0x04edab83, 0x051340f6, 0x3fcc673b,
-	0x3fcb66e4, 0x051fc7b9, 0x05455ad1, 0x3fc8571f, 0x3fc74cf3, 0x0551e0c7, 0x0577716b, 0x3fc41fac,
-	0x3fc30baa, 0x0583f68c, 0x05a984a6, 0x3fbfc0e3, 0x3fbea30c, 0x05b608eb, 0x05db9463, 0x3fbb3ac7,
-	0x3fba131b, 0x05e817c3, 0x060da083, 0x3fb68d5b, 0x3fb55bdc, 0x061a22f7, 0x063fa8e7, 0x3fb1b8a2,
-	0x3fb07d50, 0x064c2a67, 0x0671ad71, 0x3facbc9f, 0x3fab777b, 0x067e2df5, 0x06a3ae00, 0x3fa79954,
-	0x3fa64a5f, 0x06b02d81, 0x06d5aa77, 0x3fa24ec6, 0x3fa0f600, 0x06e228ee, 0x0707a2b7, 0x3f9cdcf7,
-	0x3f9b7a62, 0x0714201b, 0x073996a1, 0x3f9743eb, 0x3f95d787, 0x074612eb, 0x076b8616, 0x3f9183a5,
-	0x3f900d72, 0x0778013d, 0x079d70f7, 0x3f8b9c28, 0x3f8a1c29, 0x07a9eaf5, 0x07cf5726, 0x3f858d79,
-	0x3f8403ae, 0x07dbcff2, 0x08013883, 0x3f7f579b, 0x3f7dc405, 0x080db016, 0x083314f1, 0x3f78fa92,
-	0x3f775d31, 0x083f8b43, 0x0864ec4f, 0x3f727661, 0x3f70cf38, 0x08716159, 0x0896be80, 0x3f6bcb0e,
-	0x3f6a1a1c, 0x08a3323a, 0x08c88b65, 0x3f64f89b, 0x3f633de2, 0x08d4fdc6, 0x08fa52de, 0x3f5dff0e,
-	0x3f5c3a8f, 0x0906c3e0, 0x092c14ce, 0x3f56de6a, 0x3f551026, 0x09388469, 0x095dd116, 0x3f4f96b4,
-	0x3f4dbeac, 0x096a3f42, 0x098f8796, 0x3f4827f0, 0x3f464626, 0x099bf44c, 0x09c13831, 0x3f409223,
-	0x3f3ea697, 0x09cda368, 0x09f2e2c7, 0x3f38d552, 0x3f36e006, 0x09ff4c78, 0x0a24873a, 0x3f30f181,
-	0x3f2ef276, 0x0a30ef5e, 0x0a56256c, 0x3f28e6b6, 0x3f26ddec, 0x0a628bfa, 0x0a87bd3d, 0x3f20b4f5,
-	0x3f1ea26e, 0x0a94222f, 0x0ab94e8f, 0x3f185c43, 0x3f164001, 0x0ac5b1dc, 0x0aead944, 0x3f0fdca5,
-	0x3f0db6a9, 0x0af73ae5, 0x0b1c5d3d, 0x3f073621, 0x3f05066d, 0x0b28bd2a, 0x0b4dda5c, 0x3efe68bc,
-	0x3efc2f50, 0x0b5a388d, 0x0b7f5081, 0x3ef5747b, 0x3ef3315a, 0x0b8bacf0, 0x0bb0bf8f, 0x3eec5965,
-	0x3eea0c8e, 0x0bbd1a33, 0x0be22766, 0x3ee3177e, 0x3ee0c0f4, 0x0bee8038, 0x0c1387e9, 0x3ed9aecc,
-	0x3ed74e91, 0x0c1fdee1, 0x0c44e0f9, 0x3ed01f55, 0x3ecdb56a, 0x0c513610, 0x0c763278, 0x3ec66920,
-	0x3ec3f585, 0x0c8285a5, 0x0ca77c47, 0x3ebc8c31, 0x3eba0ee9, 0x0cb3cd84, 0x0cd8be47, 0x3eb2888f,
-	0x3eb0019c, 0x0ce50d8c, 0x0d09f85b, 0x3ea85e41, 0x3ea5cda3, 0x0d1645a0, 0x0d3b2a64, 0x3e9e0d4c,
-	0x3e9b7306, 0x0d4775a1, 0x0d6c5443, 0x3e9395b7, 0x3e90f1ca, 0x0d789d71, 0x0d9d75db, 0x3e88f788,
-	0x3e8649f5, 0x0da9bcf2, 0x0dce8f0d, 0x3e7e32c6, 0x3e7b7b90, 0x0ddad406, 0x0dff9fba, 0x3e734778,
-	0x3e70869f, 0x0e0be28e, 0x0e30a7c5, 0x3e6835a4, 0x3e656b2b, 0x0e3ce86b, 0x0e61a70f, 0x3e5cfd51,
-	0x3e5a2939, 0x0e6de580, 0x0e929d7a, 0x3e519e86, 0x3e4ec0d1, 0x0e9ed9af, 0x0ec38ae8, 0x3e46194a,
-	0x3e4331fa, 0x0ecfc4d9, 0x0ef46f3b, 0x3e3a6da4, 0x3e377cbb, 0x0f00a6df, 0x0f254a53, 0x3e2e9b9c,
-	0x3e2ba11b, 0x0f317fa5, 0x0f561c15, 0x3e22a338, 0x3e1f9f21, 0x0f624f0c, 0x0f86e460, 0x3e168480,
-	0x3e1376d5, 0x0f9314f5, 0x0fb7a317, 0x3e0a3f7b, 0x3e07283f, 0x0fc3d143, 0x0fe8581d, 0x3dfdd432,
-	0x3dfab365, 0x0ff483d7, 0x10190352, 0x3df142ab, 0x3dee1851, 0x10252c94, 0x1049a49a, 0x3de48aef,
-	0x3de15708, 0x1055cb5b, 0x107a3bd5, 0x3dd7ad05, 0x3dd46f94, 0x1086600e, 0x10aac8e6, 0x3dcaa8f5,
-	0x3dc761fc, 0x10b6ea90, 0x10db4baf, 0x3dbd7ec7, 0x3dba2e48, 0x10e76ac3, 0x110bc413, 0x3db02e84,
-	0x3dacd481, 0x1117e088, 0x113c31f3, 0x3da2b834, 0x3d9f54af, 0x11484bc2, 0x116c9531, 0x3d951bde,
-	0x3d91aed9, 0x1178ac53, 0x119cedaf, 0x3d87598c, 0x3d83e309, 0x11a9021d, 0x11cd3b50, 0x3d797145,
-	0x3d75f147, 0x11d94d02, 0x11fd7df6, 0x3d6b6313, 0x3d67d99b, 0x12098ce5, 0x122db583, 0x3d5d2efe,
-	0x3d599c0e, 0x1239c1a7, 0x125de1da, 0x3d4ed50f, 0x3d4b38aa, 0x1269eb2b, 0x128e02dc, 0x3d40554e,
-	0x3d3caf76, 0x129a0954, 0x12be186c, 0x3d31afc5, 0x3d2e007c, 0x12ca1c03, 0x12ee226c, 0x3d22e47c,
-	0x3d1f2bc5, 0x12fa231b, 0x131e20c0, 0x3d13f37e, 0x3d10315a, 0x132a1e7e, 0x134e1348, 0x3d04dcd2,
-	0x3d011145, 0x135a0e0e, 0x137df9e7, 0x3cf5a082, 0x3cf1cb8e, 0x1389f1af, 0x13add481, 0x3ce63e98,
-	0x3ce2603f, 0x13b9c943, 0x13dda2f7, 0x3cd6b71e, 0x3cd2cf62, 0x13e994ab, 0x140d652c, 0x3cc70a1c,
-	0x3cc318ff, 0x141953cb, 0x143d1b02, 0x3cb7379c, 0x3cb33d22, 0x14490685, 0x146cc45c, 0x3ca73fa9,
-	0x3ca33bd3, 0x1478acbc, 0x149c611d, 0x3c97224c, 0x3c93151d, 0x14a84652, 0x14cbf127, 0x3c86df8e,
-	0x3c82c909, 0x14d7d32a, 0x14fb745e, 0x3c76777b, 0x3c7257a2, 0x15075327, 0x152aeaa3, 0x3c65ea1c,
-	0x3c61c0f1, 0x1536c62b, 0x155a53d9, 0x3c55377b, 0x3c510501, 0x15662c18, 0x1589afe3, 0x3c445fa2,
-	0x3c4023dd, 0x159584d3, 0x15b8fea4, 0x3c33629d, 0x3c2f1d8e, 0x15c4d03e, 0x15e83fff, 0x3c224075,
-	0x3c1df21f, 0x15f40e3a, 0x161773d6, 0x3c10f935, 0x3c0ca19b, 0x16233eac, 0x16469a0d, 0x3bff8ce8,
-	0x3bfb2c0c, 0x16526176, 0x1675b286, 0x3bedfb99, 0x3be9917e, 0x1681767c, 0x16a4bd25, 0x3bdc4552,
-	0x3bd7d1fa, 0x16b07d9f, 0x16d3b9cc, 0x3bca6a1d, 0x3bc5ed8d, 0x16df76c3, 0x1702a85e, 0x3bb86a08,
-	0x3bb3e440, 0x170e61cc, 0x173188be, 0x3ba6451b, 0x3ba1b620, 0x173d3e9b, 0x17605ad0, 0x3b93fb63,
-	0x3b8f6337, 0x176c0d15, 0x178f1e76, 0x3b818ceb, 0x3b7ceb90, 0x179acd1c, 0x17bdd394, 0x3b6ef9be,
-	0x3b6a4f38, 0x17c97e93, 0x17ec7a0d, 0x3b5c41e8, 0x3b578e39, 0x17f8215e, 0x181b11c4, 0x3b496574,
-	0x3b44a8a0, 0x1826b561, 0x18499a9d, 0x3b36646e, 0x3b319e77, 0x18553a7d, 0x1878147a, 0x3b233ee1,
-	0x3b1e6fca, 0x1883b097, 0x18a67f3f, 0x3b0ff4d9, 0x3b0b1ca6, 0x18b21791, 0x18d4dad0, 0x3afc8663,
-	0x3af7a516, 0x18e06f50, 0x1903270f, 0x3ae8f38b, 0x3ae40926, 0x190eb7b7, 0x193163e1, 0x3ad53c5b,
-	0x3ad048e3, 0x193cf0a9, 0x195f9128, 0x3ac160e1, 0x3abc6458, 0x196b1a09, 0x198daec8, 0x3aad6129,
-	0x3aa85b92, 0x199933bb, 0x19bbbca6, 0x3a993d3e, 0x3a942e9d, 0x19c73da3, 0x19e9baa3, 0x3a84f52f,
-	0x3a7fdd86, 0x19f537a4, 0x1a17a8a5, 0x3a708906, 0x3a6b6859, 0x1a2321a2, 0x1a45868e, 0x3a5bf8d1,
-	0x3a56cf23, 0x1a50fb81, 0x1a735442, 0x3a47449c, 0x3a4211f0, 0x1a7ec524, 0x1aa111a6, 0x3a326c74,
-	0x3a2d30cd, 0x1aac7e6f, 0x1acebe9d, 0x3a1d7066, 0x3a182bc8, 0x1ada2746, 0x1afc5b0a, 0x3a08507f,
-	0x3a0302ed, 0x1b07bf8c, 0x1b29e6d2, 0x39f30ccc, 0x39edb649, 0x1b354727, 0x1b5761d8, 0x39dda55a,
-	0x39d845e9, 0x1b62bdf8, 0x1b84cc01, 0x39c81a36, 0x39c2b1da, 0x1b9023e5, 0x1bb22530, 0x39b26b6d,
-	0x39acfa2b, 0x1bbd78d2, 0x1bdf6d4a, 0x399c990d, 0x39971ee7, 0x1beabca1, 0x1c0ca432, 0x3986a324,
-	0x3981201e, 0x1c17ef39, 0x1c39c9cd, 0x397089bf, 0x396afddc, 0x1c45107c, 0x1c66ddfe, 0x395a4ceb,
-	0x3954b82e, 0x1c72204f, 0x1c93e0ab, 0x3943ecb6, 0x393e4f23, 0x1c9f1e96, 0x1cc0d1b6, 0x392d692f,
-	0x3927c2c9, 0x1ccc0b35, 0x1cedb106, 0x3916c262, 0x3911132d, 0x1cf8e611, 0x1d1a7e7d, 0x38fff85e,
-	0x38fa405e, 0x1d25af0d, 0x1d473a00, 0x38e90b31, 0x38e34a69, 0x1d52660f, 0x1d73e374, 0x38d1fae9,
-	0x38cc315d, 0x1d7f0afb, 0x1da07abc, 0x38bac795, 0x38b4f547, 0x1dab9db5, 0x1dccffbf, 0x38a37142,
-	0x389d9637, 0x1dd81e21, 0x1df9725f, 0x388bf7ff, 0x3886143b, 0x1e048c24, 0x1e25d282, 0x38745bdb,
-	0x386e6f60, 0x1e30e7a4, 0x1e52200c, 0x385c9ce3, 0x3856a7b6, 0x1e5d3084, 0x1e7e5ae2, 0x3844bb28,
-	0x383ebd4c, 0x1e8966a8, 0x1eaa82e9, 0x382cb6b7, 0x3826b030, 0x1eb589f7, 0x1ed69805, 0x38148f9f,
-	0x380e8071, 0x1ee19a54, 0x1f029a1c, 0x37fc45ef, 0x37f62e1d, 0x1f0d97a5, 0x1f2e8911, 0x37e3d9b7,
-	0x37ddb945, 0x1f3981ce, 0x1f5a64cb, 0x37cb4b04, 0x37c521f6, 0x1f6558b5, 0x1f862d2d, 0x37b299e7,
-	0x37ac6841, 0x1f911c3d, 0x1fb1e21d, 0x3799c66f, 0x37938c34, 0x1fbccc4d, 0x1fdd8381, 0x3780d0aa,
-	0x377a8ddf, 0x1fe868c8, 0x2009113c, 0x3767b8a9, 0x37616d51, 0x2013f196, 0x20348b35, 0x374e7e7b,
-	0x37482a9a, 0x203f6699, 0x205ff14f, 0x3735222f, 0x372ec5c9, 0x206ac7b8, 0x208b4372, 0x371ba3d4,
-	0x37153eee, 0x209614d9, 0x20b68181, 0x3702037c, 0x36fb9618, 0x20c14ddf, 0x20e1ab63, 0x36e84135,
-	0x36e1cb58, 0x20ec72b1, 0x210cc0fc, 0x36ce5d10, 0x36c7debd, 0x21178334, 0x2137c232, 0x36b4571b,
-	0x36add058, 0x21427f4d, 0x2162aeea, 0x369a2f69, 0x3693a038, 0x216d66e2, 0x218d870b, 0x367fe608,
-	0x36794e6e, 0x219839d8, 0x21b84a79, 0x36657b08, 0x365edb09, 0x21c2f815, 0x21e2f91a, 0x364aee7b,
-	0x3644461b, 0x21eda17f, 0x220d92d4, 0x36304070, 0x36298fb4, 0x221835fb, 0x2238178d, 0x361570f8,
-	0x360eb7e3, 0x2242b56f, 0x22628729, 0x35fa8023, 0x35f3beba, 0x226d1fc1, 0x228ce191, 0x35df6e03,
-	0x35d8a449, 0x229774d7, 0x22b726a8, 0x35c43aa7, 0x35bd68a1, 0x22c1b496, 0x22e15655, 0x35a8e621,
-	0x35a20bd3, 0x22ebdee5, 0x230b707e, 0x358d7081, 0x35868def, 0x2315f3a8, 0x23357509, 0x3571d9d9,
-	0x356aef08, 0x233ff2c8, 0x235f63dc, 0x35562239, 0x354f2f2c, 0x2369dc29, 0x23893cdd, 0x353a49b2,
-	0x35334e6f, 0x2393afb2, 0x23b2fff3, 0x351e5056, 0x35174ce0, 0x23bd6d48, 0x23dcad03, 0x35023636,
-	0x34fb2a92, 0x23e714d3, 0x240643f4, 0x34e5fb63, 0x34dee795, 0x2410a639, 0x242fc4ad, 0x34c99fef,
-	0x34c283fb, 0x243a215f, 0x24592f13, 0x34ad23eb, 0x34a5ffd5, 0x2463862c, 0x2482830d, 0x34908768,
-	0x34895b36, 0x248cd487, 0x24abc082, 0x3473ca79, 0x346c962f, 0x24b60c57, 0x24d4e757, 0x3456ed2f,
-	0x344fb0d1, 0x24df2d81, 0x24fdf775, 0x3439ef9c, 0x3432ab2e, 0x250837ed, 0x2526f0c1, 0x341cd1d2,
-	0x34158559, 0x25312b81, 0x254fd323, 0x33ff93e2, 0x33f83f62, 0x255a0823, 0x25789e80, 0x33e235df,
-	0x33dad95e, 0x2582cdbc, 0x25a152c0, 0x33c4b7db, 0x33bd535c, 0x25ab7c30, 0x25c9efca, 0x33a719e8,
-	0x339fad70, 0x25d41369, 0x25f27584, 0x33895c18, 0x3381e7ac, 0x25fc934b, 0x261ae3d6, 0x336b7e7e,
-	0x33640223, 0x2624fbbf, 0x26433aa7, 0x334d812d, 0x3345fce6, 0x264d4cac, 0x266b79dd, 0x332f6435,
-	0x3327d808, 0x267585f8, 0x2693a161, 0x331127ab, 0x3309939c, 0x269da78b, 0x26bbb119, 0x32f2cba1,
-	0x32eb2fb5, 0x26c5b14c, 0x26e3a8ec, 0x32d45029, 0x32ccac64, 0x26eda322, 0x270b88c2, 0x32b5b557,
-	0x32ae09be, 0x27157cf5, 0x27335082, 0x3296fb3d, 0x328f47d5, 0x273d3eac, 0x275b0014, 0x327821ee,
-	0x327066bc, 0x2764e82f, 0x27829760, 0x3259297d, 0x32516686, 0x278c7965, 0x27aa164c, 0x323a11fe,
-	0x32324746, 0x27b3f235, 0x27d17cc1, 0x321adb83, 0x3213090f, 0x27db5288, 0x27f8caa5, 0x31fb8620,
-	0x31f3abf5, 0x28029a45, 0x281fffe2, 0x31dc11e8, 0x31d4300b, 0x2829c954, 0x28471c5e, 0x31bc7eee,
-	0x31b49564, 0x2850df9d, 0x286e2002, 0x319ccd46, 0x3194dc14, 0x2877dd07, 0x28950ab6, 0x317cfd04,
-	0x3175042e, 0x289ec17a, 0x28bbdc61, 0x315d0e3b, 0x31550dc6, 0x28c58cdf, 0x28e294eb, 0x313d00ff,
-	0x3134f8f1, 0x28ec3f1e, 0x2909343e, 0x311cd564, 0x3114c5c0, 0x2912d81f, 0x292fba40, 0x30fc8b7d,
-	0x30f47449, 0x293957c9, 0x295626da, 0x30dc235e, 0x30d404a0, 0x295fbe06, 0x297c79f5, 0x30bb9d1c,
-	0x30b376d8, 0x29860abd, 0x29a2b378, 0x309af8ca, 0x3092cb05, 0x29ac3dd7, 0x29c8d34d, 0x307a367c,
-	0x3072013c, 0x29d2573c, 0x29eed95b, 0x30595648, 0x30511991, 0x29f856d5, 0x2a14c58b, 0x30385840,
-	0x30301418, 0x2a1e3c8a, 0x2a3a97c7, 0x30173c7a, 0x300ef0e5, 0x2a440844, 0x2a604ff5, 0x2ff6030a,
-	0x2fedb00d, 0x2a69b9ec, 0x2a85ee00, 0x2fd4ac04, 0x2fcc51a5, 0x2a8f516b, 0x2aab71d0, 0x2fb3377c,
-	0x2faad5c1, 0x2ab4cea9, 0x2ad0db4e, 0x2f91a589, 0x2f893c75, 0x2ada318e, 0x2af62a63, 0x2f6ff63d,
-	0x2f6785d7, 0x2aff7a05, 0x2b1b5ef8, 0x2f4e29af, 0x2f45b1fb, 0x2b24a7f6, 0x2b4078f5, 0x2f2c3ff2,
-	0x2f23c0f6, 0x2b49bb4a, 0x2b657844, 0x2f0a391d, 0x2f01b2de, 0x2b6eb3ea, 0x2b8a5cce, 0x2ee81543,
-	0x2edf87c6, 0x2b9391c0, 0x2baf267d, 0x2ec5d479, 0x2ebd3fc4, 0x2bb854b4, 0x2bd3d53a, 0x2ea376d6,
-	0x2e9adaee, 0x2bdcfcb0, 0x2bf868ed, 0x2e80fc6e, 0x2e785958, 0x2c01899e, 0x2c1ce181, 0x2e5e6556,
-	0x2e55bb17, 0x2c25fb66, 0x2c413edf, 0x2e3bb1a4, 0x2e330042, 0x2c4a51f3, 0x2c6580f1, 0x2e18e16d,
-	0x2e1028ed, 0x2c6e8d2e, 0x2c89a79f, 0x2df5f4c7, 0x2ded352f, 0x2c92ad01, 0x2cadb2d5, 0x2dd2ebc7,
-	0x2dca251c, 0x2cb6b155, 0x2cd1a27b, 0x2dafc683, 0x2da6f8ca, 0x2cda9a14, 0x2cf5767c, 0x2d8c8510,
-	0x2d83b04f, 0x2cfe6728, 0x2d192ec1, 0x2d692784, 0x2d604bc0, 0x2d22187a, 0x2d3ccb34, 0x2d45adf6
-};
-
-
-const int twidTab512[(8*6 + 32*6 + 128*6)/2] = {
-	0x40000000, 0x40000000, 0x40000000, 0x3b20187d,
-	0x3ec50c7c, 0x3536238e, 0x2d412d41, 0x3b20187d,
-	0x187d3b20, 0x187d3b20, 0x3536238e, 0xf3843ec5,
-	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xe7833b20,
-	0x238e3536, 0xc13b0c7c, 0xd2bf2d41, 0x187d3b20,
-	0xc4e0e783, 0xc4e0187d, 0x0c7c3ec5, 0xdc72caca,
-
-	0x40000000, 0x40000000, 0x40000000, 0x3fb10645,
-	0x3fec0323, 0x3f4e0964, 0x3ec50c7c, 0x3fb10645,
-	0x3d3e1294, 0x3d3e1294, 0x3f4e0964, 0x39da1b5d,
-	0x3b20187d, 0x3ec50c7c, 0x3536238e, 0x38711e2b,
-	0x3e140f8c, 0x2f6b2afa, 0x3536238e, 0x3d3e1294,
-	0x28993179, 0x31792899, 0x3c42158f, 0x20e736e5,
-	0x2d412d41, 0x3b20187d, 0x187d3b20, 0x28993179,
-	0x39da1b5d, 0x0f8c3e14, 0x238e3536, 0x38711e2b,
-	0x06453fb1, 0x1e2b3871, 0x36e520e7, 0xfcdd3fec,
-	0x187d3b20, 0x3536238e, 0xf3843ec5, 0x12943d3e,
-	0x3367261f, 0xea713c42, 0x0c7c3ec5, 0x31792899,
-	0xe1d53871, 0x06453fb1, 0x2f6b2afa, 0xd9e13367,
-	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xf9bb3fb1,
-	0x2afa2f6b, 0xcc99261f, 0xf3843ec5, 0x28993179,
-	0xc78f1e2b, 0xed6c3d3e, 0x261f3367, 0xc3be158f,
-	0xe7833b20, 0x238e3536, 0xc13b0c7c, 0xe1d53871,
-	0x20e736e5, 0xc0140323, 0xdc723536, 0x1e2b3871,
-	0xc04ff9bb, 0xd7673179, 0x1b5d39da, 0xc1ecf074,
-	0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 0xce872899,
-	0x158f3c42, 0xc91bdf19, 0xcaca238e, 0x12943d3e,
-	0xce87d767, 0xc78f1e2b, 0x0f8c3e14, 0xd506d095,
-	0xc4e0187d, 0x0c7c3ec5, 0xdc72caca, 0xc2c21294,
-	0x09643f4e, 0xe4a3c626, 0xc13b0c7c, 0x06453fb1,
-	0xed6cc2c2, 0xc04f0645, 0x03233fec, 0xf69cc0b2,
-
-	0x40000000, 0x40000000, 0x40000000, 0x3ffb0192,
-	0x3ffe00c9, 0x3ff4025b, 0x3fec0323, 0x3ffb0192,
-	0x3fd304b5, 0x3fd304b5, 0x3ff4025b, 0x3f9c070d,
-	0x3fb10645, 0x3fec0323, 0x3f4e0964, 0x3f8407d5,
-	0x3fe103ec, 0x3eeb0bb6, 0x3f4e0964, 0x3fd304b5,
-	0x3e710e05, 0x3f0e0af1, 0x3fc3057d, 0x3de2104f,
-	0x3ec50c7c, 0x3fb10645, 0x3d3e1294, 0x3e710e05,
-	0x3f9c070d, 0x3c8414d1, 0x3e140f8c, 0x3f8407d5,
-	0x3bb61708, 0x3dae1111, 0x3f6a089c, 0x3ad21937,
-	0x3d3e1294, 0x3f4e0964, 0x39da1b5d, 0x3cc51413,
-	0x3f2f0a2a, 0x38cf1d79, 0x3c42158f, 0x3f0e0af1,
-	0x37af1f8b, 0x3bb61708, 0x3eeb0bb6, 0x367c2192,
-	0x3b20187d, 0x3ec50c7c, 0x3536238e, 0x3a8219ef,
-	0x3e9c0d41, 0x33de257d, 0x39da1b5d, 0x3e710e05,
-	0x3274275f, 0x392a1cc6, 0x3e440ec9, 0x30f82934,
-	0x38711e2b, 0x3e140f8c, 0x2f6b2afa, 0x37af1f8b,
-	0x3de2104f, 0x2dce2cb2, 0x36e520e7, 0x3dae1111,
-	0x2c212e5a, 0x3612223d, 0x3d7711d3, 0x2a652ff1,
-	0x3536238e, 0x3d3e1294, 0x28993179, 0x345324da,
-	0x3d021354, 0x26c032ee, 0x3367261f, 0x3cc51413,
-	0x24da3453, 0x3274275f, 0x3c8414d1, 0x22e635a5,
-	0x31792899, 0x3c42158f, 0x20e736e5, 0x307629cd,
-	0x3bfd164c, 0x1edc3811, 0x2f6b2afa, 0x3bb61708,
-	0x1cc6392a, 0x2e5a2c21, 0x3b6c17c3, 0x1aa63a2f,
-	0x2d412d41, 0x3b20187d, 0x187d3b20, 0x2c212e5a,
-	0x3ad21937, 0x164c3bfd, 0x2afa2f6b, 0x3a8219ef,
-	0x14133cc5, 0x29cd3076, 0x3a2f1aa6, 0x11d33d77,
-	0x28993179, 0x39da1b5d, 0x0f8c3e14, 0x275f3274,
-	0x39831c12, 0x0d413e9c, 0x261f3367, 0x392a1cc6,
-	0x0af13f0e, 0x24da3453, 0x38cf1d79, 0x089c3f6a,
-	0x238e3536, 0x38711e2b, 0x06453fb1, 0x223d3612,
-	0x38111edc, 0x03ec3fe1, 0x20e736e5, 0x37af1f8b,
-	0x01923ffb, 0x1f8b37af, 0x374b2039, 0xff373ffe,
-	0x1e2b3871, 0x36e520e7, 0xfcdd3fec, 0x1cc6392a,
-	0x367c2192, 0xfa833fc3, 0x1b5d39da, 0x3612223d,
-	0xf82b3f84, 0x19ef3a82, 0x35a522e6, 0xf5d63f2f,
-	0x187d3b20, 0x3536238e, 0xf3843ec5, 0x17083bb6,
-	0x34c62434, 0xf1373e44, 0x158f3c42, 0x345324da,
-	0xeeef3dae, 0x14133cc5, 0x33de257d, 0xecac3d02,
-	0x12943d3e, 0x3367261f, 0xea713c42, 0x11113dae,
-	0x32ee26c0, 0xe83d3b6c, 0x0f8c3e14, 0x3274275f,
-	0xe6113a82, 0x0e053e71, 0x31f727fd, 0xe3ee3983,
-	0x0c7c3ec5, 0x31792899, 0xe1d53871, 0x0af13f0e,
-	0x30f82934, 0xdfc7374b, 0x09643f4e, 0x307629cd,
-	0xddc33612, 0x07d53f84, 0x2ff12a65, 0xdbcc34c6,
-	0x06453fb1, 0x2f6b2afa, 0xd9e13367, 0x04b53fd3,
-	0x2ee32b8e, 0xd80331f7, 0x03233fec, 0x2e5a2c21,
-	0xd6333076, 0x01923ffb, 0x2dce2cb2, 0xd4722ee3,
-	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xfe6e3ffb,
-	0x2cb22dce, 0xd11d2b8e, 0xfcdd3fec, 0x2c212e5a,
-	0xcf8a29cd, 0xfb4b3fd3, 0x2b8e2ee3, 0xce0927fd,
-	0xf9bb3fb1, 0x2afa2f6b, 0xcc99261f, 0xf82b3f84,
-	0x2a652ff1, 0xcb3a2434, 0xf69c3f4e, 0x29cd3076,
-	0xc9ee223d, 0xf50f3f0e, 0x293430f8, 0xc8b52039,
-	0xf3843ec5, 0x28993179, 0xc78f1e2b, 0xf1fb3e71,
-	0x27fd31f7, 0xc67d1c12, 0xf0743e14, 0x275f3274,
-	0xc57e19ef, 0xeeef3dae, 0x26c032ee, 0xc49417c3,
-	0xed6c3d3e, 0x261f3367, 0xc3be158f, 0xebed3cc5,
-	0x257d33de, 0xc2fe1354, 0xea713c42, 0x24da3453,
-	0xc2521111, 0xe8f83bb6, 0x243434c6, 0xc1bc0ec9,
-	0xe7833b20, 0x238e3536, 0xc13b0c7c, 0xe6113a82,
-	0x22e635a5, 0xc0d10a2a, 0xe4a339da, 0x223d3612,
-	0xc07c07d5, 0xe33a392a, 0x2192367c, 0xc03d057d,
-	0xe1d53871, 0x20e736e5, 0xc0140323, 0xe07537af,
-	0x2039374b, 0xc00200c9, 0xdf1936e5, 0x1f8b37af,
-	0xc005fe6e, 0xddc33612, 0x1edc3811, 0xc01ffc14,
-	0xdc723536, 0x1e2b3871, 0xc04ff9bb, 0xdb263453,
-	0x1d7938cf, 0xc096f764, 0xd9e13367, 0x1cc6392a,
-	0xc0f2f50f, 0xd8a13274, 0x1c123983, 0xc164f2bf,
-	0xd7673179, 0x1b5d39da, 0xc1ecf074, 0xd6333076,
-	0x1aa63a2f, 0xc289ee2d, 0xd5062f6b, 0x19ef3a82,
-	0xc33bebed, 0xd3df2e5a, 0x19373ad2, 0xc403e9b4,
-	0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 0xd1a62c21,
-	0x17c33b6c, 0xc5d1e55a, 0xd0952afa, 0x17083bb6,
-	0xc6d6e33a, 0xcf8a29cd, 0x164c3bfd, 0xc7efe124,
-	0xce872899, 0x158f3c42, 0xc91bdf19, 0xcd8c275f,
-	0x14d13c84, 0xca5bdd1a, 0xcc99261f, 0x14133cc5,
-	0xcbaddb26, 0xcbad24da, 0x13543d02, 0xcd12d940,
-	0xcaca238e, 0x12943d3e, 0xce87d767, 0xc9ee223d,
-	0x11d33d77, 0xd00fd59b, 0xc91b20e7, 0x11113dae,
-	0xd1a6d3df, 0xc8511f8b, 0x104f3de2, 0xd34ed232,
-	0xc78f1e2b, 0x0f8c3e14, 0xd506d095, 0xc6d61cc6,
-	0x0ec93e44, 0xd6cccf08, 0xc6261b5d, 0x0e053e71,
-	0xd8a1cd8c, 0xc57e19ef, 0x0d413e9c, 0xda83cc22,
-	0xc4e0187d, 0x0c7c3ec5, 0xdc72caca, 0xc44a1708,
-	0x0bb63eeb, 0xde6ec984, 0xc3be158f, 0x0af13f0e,
-	0xe075c851, 0xc33b1413, 0x0a2a3f2f, 0xe287c731,
-	0xc2c21294, 0x09643f4e, 0xe4a3c626, 0xc2521111,
-	0x089c3f6a, 0xe6c9c52e, 0xc1ec0f8c, 0x07d53f84,
-	0xe8f8c44a, 0xc18f0e05, 0x070d3f9c, 0xeb2fc37c,
-	0xc13b0c7c, 0x06453fb1, 0xed6cc2c2, 0xc0f20af1,
-	0x057d3fc3, 0xefb1c21e, 0xc0b20964, 0x04b53fd3,
-	0xf1fbc18f, 0xc07c07d5, 0x03ec3fe1, 0xf44ac115,
-	0xc04f0645, 0x03233fec, 0xf69cc0b2, 0xc02d04b5,
-	0x025b3ff4, 0xf8f3c064, 0xc0140323, 0x01923ffb,
-	0xfb4bc02d, 0xc0050192, 0x00c93ffe, 0xfda5c00c
-};
-
-const int twidTab64[(4*6 + 16*6)/2] = {
-	0x40000000, 0x40000000, 0x40000000, 0x2d412d41,
-	0x3b20187d, 0x187d3b20, 0x00004000, 0x2d412d41,
-	0xd2bf2d41, 0xd2bf2d41, 0x187d3b20, 0xc4e0e783,
-
-	0x40000000, 0x40000000, 0x40000000, 0x3ec50c7c,
-	0x3fb10645, 0x3d3e1294, 0x3b20187d, 0x3ec50c7c,
-	0x3536238e, 0x3536238e, 0x3d3e1294, 0x28993179,
-	0x2d412d41, 0x3b20187d, 0x187d3b20, 0x238e3536,
-	0x38711e2b, 0x06453fb1, 0x187d3b20, 0x3536238e,
-	0xf3843ec5, 0x0c7c3ec5, 0x31792899, 0xe1d53871,
-	0x00004000, 0x2d412d41, 0xd2bf2d41, 0xf3843ec5,
-	0x28993179, 0xc78f1e2b, 0xe7833b20, 0x238e3536,
-	0xc13b0c7c, 0xdc723536, 0x1e2b3871, 0xc04ff9bb,
-	0xd2bf2d41, 0x187d3b20, 0xc4e0e783, 0xcaca238e,
-	0x12943d3e, 0xce87d767, 0xc4e0187d, 0x0c7c3ec5,
-	0xdc72caca, 0xc13b0c7c, 0x06453fb1, 0xed6cc2c2
-};
-
-#elif defined ARMV7Neon
-/*
- *  Q29 for 128 and 1024
- *
- * for (i = 0; i < num/4; i++) {
- *   angle = (i + 0.125) * M_PI / num;
- *   x = cos(angle) * (1 << 29);
- *   x = sin(angle) * (1 << 29);
- *
- *   angle = (num/2 - 1 - i + 0.125) * M_PI / num;
- *   x = cos(angle) * (1 << 29);
- *   x = sin(angle) * (1 << 29);
- * }
- */
-const int cossintab[128 + 1024] = {
-	/* 128 */
-	0x1ffff621, 0x001921f9, 0x00afea69, 0x1ffe1c68, 0x1ffce09d, 0x00e22a7a, 0x0178dbaa, 0x1ff753bb,
-	0x1ff4dc55, 0x01ab101c, 0x024192cf, 0x1feb9d25, 0x1fe7ea85, 0x0273b3e2, 0x0309f0e2, 0x1fdafa75,
-	0x1fd60d2e, 0x033bf6dd, 0x03d1d700, 0x1fc56e3b, 0x1fbf470f, 0x0403ba2b, 0x04992653, 0x1faafbcb,
-	0x1fa39bac, 0x04cadefe, 0x055fc022, 0x1f8ba738, 0x1f830f4a, 0x059146a1, 0x062585ca, 0x1f677557,
-	0x1f5da6ed, 0x0656d27a, 0x06ea58cd, 0x1f3e6bbc, 0x1f33685a, 0x071b6415, 0x07ae1ad2, 0x1f1090bd,
-	0x1f045a15, 0x07dedd20, 0x0870ada7, 0x1eddeb6a, 0x1ed0835f, 0x08a11f78, 0x0931f34d, 0x1ea68394,
-	0x1e97ec36, 0x09620d27, 0x09f1cdf5, 0x1e6a61c5, 0x1e5a9d55, 0x0a21886e, 0x0ab02009, 0x1e298f44,
-	0x1e18a030, 0x0adf73c6, 0x0b6ccc32, 0x1de4160f, 0x1dd1fef4, 0x0b9bb1e5, 0x0c27b555, 0x1d9a00de,
-	0x1d86c484, 0x0c5625c3, 0x0ce0bea2, 0x1d4b5b1b, 0x1d36fc7c, 0x0d0eb2a2, 0x0d97cb8f, 0x1cf830e9,
-	0x1ce2b328, 0x0dc53c0a, 0x0e4cbfe2, 0x1ca08f1a, 0x1c89f587, 0x0e79a5d7, 0x0eff7fb3, 0x1c448331,
-	0x1c2cd149, 0x0f2bd437, 0x0fafef73, 0x1be41b61, 0x1bcb54cb, 0x0fdbabae, 0x105df3ec, 0x1b7f6687,
-	0x1b658f15, 0x10891120, 0x11097249, 0x1b16742a, 0x1afb8fd9, 0x1133e9d0, 0x11b25017, 0x1aa9547a,
-	0x1a8d676e, 0x11dc1b65, 0x1258734d, 0x1a38184a, 0x1a1b26d3, 0x12818bef, 0x12fbc24b, 0x19c2d111,
-	0x19a4dfa4, 0x132421ec, 0x139c23e4, 0x194990e4, 0x192aa420, 0x13c3c44a, 0x14397f5b, 0x18cc6a75,
-	0x18ac871f, 0x14605a69, 0x14d3bc6d, 0x184b7112, 0x182a9c14, 0x14f9cc26, 0x156ac352, 0x17c6b89d,
-	0x17a4f708, 0x159001d6, 0x15fe7cbe, 0x173e558e, 0x171bac96, 0x1622e450, 0x168ed1eb, 0x16b25ced,
-	/* 1024 */
-	0x1fffffd9, 0x0003243f, 0x0015fdba, 0x1ffff872, 0x1ffff382, 0x001c4637, 0x002f1fa6, 0x1fffdd4d,
-	0x1fffd36f, 0x0035681d, 0x00484175, 0x1fffae6c, 0x1fff9f9e, 0x004e89e3, 0x00616318, 0x1fff6bce,
-	0x1fff5811, 0x0067ab77, 0x007a847e, 0x1fff1572, 0x1ffefcc6, 0x0080cccc, 0x0093a599, 0x1ffeab5b,
-	0x1ffe8dbf, 0x0099edd2, 0x00acc658, 0x1ffe2d86, 0x1ffe0afc, 0x00b30e78, 0x00c5e6ad, 0x1ffd9bf6,
-	0x1ffd747c, 0x00cc2eb0, 0x00df0688, 0x1ffcf6aa, 0x1ffcca41, 0x00e54e6a, 0x00f825da, 0x1ffc3da2,
-	0x1ffc0c4b, 0x00fe6d97, 0x01114492, 0x1ffb70e0, 0x1ffb3a9a, 0x01178c27, 0x012a62a2, 0x1ffa9063,
-	0x1ffa552e, 0x0130aa0a, 0x01437ffa, 0x1ff99c2c, 0x1ff95c09, 0x0149c731, 0x015c9c8a, 0x1ff8943c,
-	0x1ff84f2b, 0x0162e38d, 0x0175b843, 0x1ff77893, 0x1ff72e94, 0x017bff0e, 0x018ed316, 0x1ff64932,
-	0x1ff5fa46, 0x019519a5, 0x01a7ecf2, 0x1ff5061b, 0x1ff4b240, 0x01ae3341, 0x01c105c9, 0x1ff3af4c,
-	0x1ff35684, 0x01c74bd5, 0x01da1d8c, 0x1ff244c8, 0x1ff1e713, 0x01e0634f, 0x01f33429, 0x1ff0c68f,
-	0x1ff063ed, 0x01f979a1, 0x020c4993, 0x1fef34a3, 0x1feecd14, 0x02128ebb, 0x02255db9, 0x1fed8f03,
-	0x1fed2287, 0x022ba28f, 0x023e708d, 0x1febd5b2, 0x1feb644a, 0x0244b50b, 0x025781fe, 0x1fea08b0,
-	0x1fe9925c, 0x025dc621, 0x027091fd, 0x1fe827fe, 0x1fe7acbe, 0x0276d5c1, 0x0289a07b, 0x1fe6339d,
-	0x1fe5b372, 0x028fe3dd, 0x02a2ad69, 0x1fe42b90, 0x1fe3a679, 0x02a8f063, 0x02bbb8b6, 0x1fe20fd6,
-	0x1fe185d5, 0x02c1fb46, 0x02d4c253, 0x1fdfe071, 0x1fdf5186, 0x02db0475, 0x02edca32, 0x1fdd9d64,
-	0x1fdd098e, 0x02f40be2, 0x0306d042, 0x1fdb46ae, 0x1fdaadee, 0x030d117c, 0x031fd474, 0x1fd8dc51,
-	0x1fd83ea8, 0x03261534, 0x0338d6b8, 0x1fd65e4f, 0x1fd5bbbd, 0x033f16fb, 0x0351d700, 0x1fd3ccaa,
-	0x1fd32530, 0x035816c1, 0x036ad53c, 0x1fd12763, 0x1fd07b00, 0x03711477, 0x0383d15c, 0x1fce6e7c,
-	0x1fcdbd31, 0x038a100e, 0x039ccb51, 0x1fcba1f5, 0x1fcaebc3, 0x03a30975, 0x03b5c30b, 0x1fc8c1d2,
-	0x1fc806b9, 0x03bc009f, 0x03ceb87c, 0x1fc5ce14, 0x1fc50e14, 0x03d4f57a, 0x03e7ab93, 0x1fc2c6bd,
-	0x1fc201d7, 0x03ede7f9, 0x04009c42, 0x1fbfabcd, 0x1fbee202, 0x0406d80b, 0x04198a78, 0x1fbc7d49,
-	0x1fbbae99, 0x041fc5a1, 0x04327628, 0x1fb93b31, 0x1fb8679c, 0x0438b0ac, 0x044b5f40, 0x1fb5e587,
-	0x1fb50d0e, 0x0451991d, 0x046445b2, 0x1fb27c4e, 0x1fb19ef1, 0x046a7ee3, 0x047d296f, 0x1faeff87,
-	0x1fae1d47, 0x048361f0, 0x04960a67, 0x1fab6f35, 0x1faa8813, 0x049c4235, 0x04aee88b, 0x1fa7cb5a,
-	0x1fa6df56, 0x04b51fa1, 0x04c7c3cb, 0x1fa413f8, 0x1fa32313, 0x04cdfa26, 0x04e09c18, 0x1fa04912,
-	0x1f9f534c, 0x04e6d1b4, 0x04f97163, 0x1f9c6aa9, 0x1f9b7003, 0x04ffa63c, 0x0512439d, 0x1f9878c1,
-	0x1f97793b, 0x051877af, 0x052b12b6, 0x1f94735b, 0x1f936ef6, 0x053145fd, 0x0543de9e, 0x1f905a7a,
-	0x1f8f5137, 0x054a1117, 0x055ca748, 0x1f8c2e21, 0x1f8b2000, 0x0562d8ee, 0x05756ca2, 0x1f87ee52,
-	0x1f86db55, 0x057b9d73, 0x058e2e9f, 0x1f839b10, 0x1f828336, 0x05945e95, 0x05a6ed2e, 0x1f7f345e,
-	0x1f7e17a8, 0x05ad1c47, 0x05bfa840, 0x1f7aba3e, 0x1f7998ad, 0x05c5d678, 0x05d85fc7, 0x1f762cb2,
-	0x1f750647, 0x05de8d19, 0x05f113b3, 0x1f718bbf, 0x1f70607a, 0x05f7401c, 0x0609c3f5, 0x1f6cd766,
-	0x1f6ba748, 0x060fef71, 0x0622707d, 0x1f680fab, 0x1f66dab5, 0x06289b08, 0x063b193c, 0x1f633490,
-	0x1f61fac3, 0x064142d3, 0x0653be23, 0x1f5e4619, 0x1f5d0775, 0x0659e6c2, 0x066c5f24, 0x1f594448,
-	0x1f5800ce, 0x067286c6, 0x0684fc2e, 0x1f542f21, 0x1f52e6d2, 0x068b22d0, 0x069d9532, 0x1f4f06a6,
-	0x1f4db983, 0x06a3bad0, 0x06b62a22, 0x1f49cadc, 0x1f4878e5, 0x06bc4eb9, 0x06cebaee, 0x1f447bc4,
-	0x1f4324fb, 0x06d4de79, 0x06e74786, 0x1f3f1963, 0x1f3dbdc8, 0x06ed6a03, 0x06ffcfdd, 0x1f39a3bc,
-	0x1f384350, 0x0705f147, 0x071853e3, 0x1f341ad2, 0x1f32b595, 0x071e7436, 0x0730d388, 0x1f2e7ea9,
-	0x1f2d149d, 0x0736f2c0, 0x07494ebd, 0x1f28cf43, 0x1f276069, 0x074f6cd7, 0x0761c574, 0x1f230ca5,
-	0x1f2198fd, 0x0767e26c, 0x077a379d, 0x1f1d36d2, 0x1f1bbe5d, 0x07805370, 0x0792a52a, 0x1f174dce,
-	0x1f15d08d, 0x0798bfd3, 0x07ab0e0a, 0x1f11519c, 0x1f0fcf91, 0x07b12786, 0x07c37230, 0x1f0b4240,
-	0x1f09bb6b, 0x07c98a7a, 0x07dbd18c, 0x1f051fbe, 0x1f03941f, 0x07e1e8a1, 0x07f42c0e, 0x1efeea19,
-	0x1efd59b3, 0x07fa41eb, 0x080c81a9, 0x1ef8a155, 0x1ef70c28, 0x0812964a, 0x0824d24d, 0x1ef24577,
-	0x1ef0ab84, 0x082ae5ad, 0x083d1dea, 0x1eebd682, 0x1eea37ca, 0x08433007, 0x08556473, 0x1ee5547a,
-	0x1ee3b0fe, 0x085b7548, 0x086da5d8, 0x1edebf64, 0x1edd1724, 0x0873b562, 0x0885e209, 0x1ed81742,
-	0x1ed66a41, 0x088bf044, 0x089e18f9, 0x1ed15c1a, 0x1ecfaa57, 0x08a425e1, 0x08b64a98, 0x1eca8def,
-	0x1ec8d76c, 0x08bc562a, 0x08ce76d8, 0x1ec3acc6, 0x1ec1f184, 0x08d4810f, 0x08e69da8, 0x1ebcb8a3,
-	0x1ebaf8a3, 0x08eca681, 0x08febefb, 0x1eb5b18a, 0x1eb3eccd, 0x0904c673, 0x0916dac2, 0x1eae977f,
-	0x1eacce07, 0x091ce0d4, 0x092ef0ed, 0x1ea76a87, 0x1ea59c55, 0x0934f596, 0x0947016e, 0x1ea02aa7,
-	0x1e9e57bb, 0x094d04aa, 0x095f0c36, 0x1e98d7e2, 0x1e97003e, 0x09650e01, 0x09771136, 0x1e91723e,
-	0x1e8f95e3, 0x097d118d, 0x098f1060, 0x1e89f9bf, 0x1e8818ad, 0x09950f3f, 0x09a709a4, 0x1e826e69,
-	0x1e8088a2, 0x09ad0707, 0x09befcf4, 0x1e7ad041, 0x1e78e5c7, 0x09c4f8d8, 0x09d6ea40, 0x1e731f4c,
-	0x1e71301f, 0x09dce4a1, 0x09eed17b, 0x1e6b5b8f, 0x1e6967b1, 0x09f4ca56, 0x0a06b296, 0x1e63850e,
-	0x1e618c80, 0x0a0ca9e6, 0x0a1e8d81, 0x1e5b9bce, 0x1e599e91, 0x0a248343, 0x0a36622e, 0x1e539fd4,
-	0x1e519dea, 0x0a3c565e, 0x0a4e308f, 0x1e4b9126, 0x1e498a8e, 0x0a542329, 0x0a65f894, 0x1e436fc7,
-	0x1e416485, 0x0a6be995, 0x0a7dba2f, 0x1e3b3bbd, 0x1e392bd1, 0x0a83a993, 0x0a957551, 0x1e32f50e,
-	0x1e30e079, 0x0a9b6315, 0x0aad29ec, 0x1e2a9bbd, 0x1e288281, 0x0ab3160c, 0x0ac4d7f1, 0x1e222fd1,
-	0x1e2011ee, 0x0acac26a, 0x0adc7f52, 0x1e19b14f, 0x1e178ec7, 0x0ae2681f, 0x0af41fff, 0x1e11203b,
-	0x1e0ef910, 0x0afa071d, 0x0b0bb9eb, 0x1e087c9b, 0x1e0650ce, 0x0b119f56, 0x0b234d07, 0x1dffc674,
-	0x1dfd9606, 0x0b2930bb, 0x0b3ad943, 0x1df6fdcc, 0x1df4c8bf, 0x0b40bb3e, 0x0b525e92, 0x1dee22a9,
-	0x1debe8fd, 0x0b583ecf, 0x0b69dce6, 0x1de5350f, 0x1de2f6c6, 0x0b6fbb62, 0x0b81542f, 0x1ddc3504,
-	0x1dd9f220, 0x0b8730e6, 0x0b98c45f, 0x1dd3228e, 0x1dd0db10, 0x0b9e9f4d, 0x0bb02d68, 0x1dc9fdb2,
-	0x1dc7b19b, 0x0bb6068a, 0x0bc78f3b, 0x1dc0c676, 0x1dbe75c8, 0x0bcd668e, 0x0bdee9ca, 0x1db77cdf,
-	0x1db5279c, 0x0be4bf4a, 0x0bf63d07, 0x1dae20f4, 0x1dabc71d, 0x0bfc10af, 0x0c0d88e2, 0x1da4b2ba,
-	0x1da25450, 0x0c135ab0, 0x0c24cd4e, 0x1d9b3237, 0x1d98cf3b, 0x0c2a9d3e, 0x0c3c0a3d, 0x1d919f70,
-	0x1d8f37e5, 0x0c41d84b, 0x0c533fa0, 0x1d87fa6d, 0x1d858e53, 0x0c590bc9, 0x0c6a6d68, 0x1d7e4332,
-	0x1d7bd28b, 0x0c7037a8, 0x0c819388, 0x1d7479c5, 0x1d720493, 0x0c875bdb, 0x0c98b1f0, 0x1d6a9e2e,
-	0x1d682472, 0x0c9e7854, 0x0cafc894, 0x1d60b070, 0x1d5e322c, 0x0cb58d04, 0x0cc6d764, 0x1d56b094,
-	0x1d542dc9, 0x0ccc99de, 0x0cddde53, 0x1d4c9e9f, 0x1d4a174f, 0x0ce39ed2, 0x0cf4dd52, 0x1d427a97,
-	0x1d3feec3, 0x0cfa9bd2, 0x0d0bd452, 0x1d384483, 0x1d35b42d, 0x0d1190d1, 0x0d22c347, 0x1d2dfc68,
-	0x1d2b6791, 0x0d287dc1, 0x0d39aa21, 0x1d23a24e, 0x1d2108f8, 0x0d3f6292, 0x0d5088d3, 0x1d19363a,
-	0x1d169867, 0x0d563f38, 0x0d675f4e, 0x1d0eb833, 0x1d0c15e4, 0x0d6d13a3, 0x0d7e2d85, 0x1d04283f,
-	0x1d018176, 0x0d83dfc6, 0x0d94f369, 0x1cf98666, 0x1cf6db24, 0x0d9aa393, 0x0dabb0ec, 0x1ceed2ad,
-	0x1cec22f4, 0x0db15efc, 0x0dc26600, 0x1ce40d1b, 0x1ce158ed, 0x0dc811f3, 0x0dd91298, 0x1cd935b7,
-	0x1cd67d15, 0x0ddebc69, 0x0defb6a5, 0x1cce4c87, 0x1ccb8f74, 0x0df55e51, 0x0e065219, 0x1cc35192,
-	0x1cc0900f, 0x0e0bf79c, 0x0e1ce4e6, 0x1cb844df, 0x1cb57eee, 0x0e22883e, 0x0e336eff, 0x1cad2675,
-	0x1caa5c17, 0x0e391027, 0x0e49f055, 0x1ca1f65b, 0x1c9f2792, 0x0e4f8f4b, 0x0e6068db, 0x1c96b497,
-	0x1c93e165, 0x0e66059a, 0x0e76d883, 0x1c8b6131, 0x1c888997, 0x0e7c7308, 0x0e8d3f3e, 0x1c7ffc2f,
-	0x1c7d202f, 0x0e92d787, 0x0ea39d00, 0x1c748599, 0x1c71a535, 0x0ea93308, 0x0eb9f1ba, 0x1c68fd75,
-	0x1c6618ae, 0x0ebf857d, 0x0ed03d5e, 0x1c5d63ca, 0x1c5a7aa4, 0x0ed5ceda, 0x0ee67fdf, 0x1c51b8a1,
-	0x1c4ecb1c, 0x0eec0f10, 0x0efcb92f, 0x1c45fc00, 0x1c430a1d, 0x0f024612, 0x0f12e941, 0x1c3a2ded,
-	0x1c3737b0, 0x0f1873d2, 0x0f291006, 0x1c2e4e72, 0x1c2b53db, 0x0f2e9842, 0x0f3f2d71, 0x1c225d94,
-	0x1c1f5ea6, 0x0f44b354, 0x0f554175, 0x1c165b5b, 0x1c135818, 0x0f5ac4fc, 0x0f6b4c03, 0x1c0a47cf,
-	0x1c074038, 0x0f70cd2a, 0x0f814d0e, 0x1bfe22f8, 0x1bfb170f, 0x0f86cbd3, 0x0f974489, 0x1bf1ecdb,
-	0x1beedca2, 0x0f9cc0e7, 0x0fad3265, 0x1be5a582, 0x1be290fb, 0x0fb2ac5a, 0x0fc31697, 0x1bd94cf4,
-	0x1bd63421, 0x0fc88e1e, 0x0fd8f10f, 0x1bcce337, 0x1bc9c61a, 0x0fde6626, 0x0feec1c0, 0x1bc06855,
-	0x1bbd46f0, 0x0ff43464, 0x1004889e, 0x1bb3dc55, 0x1bb0b6a9, 0x1009f8cb, 0x101a459a, 0x1ba73f3d,
-	0x1ba4154d, 0x101fb34d, 0x102ff8a8, 0x1b9a9117, 0x1b9762e4, 0x103563dc, 0x1045a1b9, 0x1b8dd1ea,
-	0x1b8a9f77, 0x104b0a6c, 0x105b40c1, 0x1b8101be, 0x1b7dcb0c, 0x1060a6ef, 0x1070d5b1, 0x1b74209b,
-	0x1b70e5ac, 0x10763958, 0x1086607e, 0x1b672e88, 0x1b63ef5f, 0x108bc19a, 0x109be119, 0x1b5a2b8e,
-	0x1b56e82c, 0x10a13fa6, 0x10b15775, 0x1b4d17b4, 0x1b49d01c, 0x10b6b371, 0x10c6c385, 0x1b3ff304,
-	0x1b3ca737, 0x10cc1cec, 0x10dc253c, 0x1b32bd84, 0x1b2f6d85, 0x10e17c0b, 0x10f17c8d, 0x1b25773d,
-	0x1b22230e, 0x10f6d0c0, 0x1106c96a, 0x1b182038, 0x1b14c7da, 0x110c1afe, 0x111c0bc6, 0x1b0ab87c,
-	0x1b075bf1, 0x11215ab8, 0x11314395, 0x1afd4012, 0x1af9df5d, 0x11368fe1, 0x114670c8, 0x1aefb702,
-	0x1aec5225, 0x114bba6b, 0x115b9354, 0x1ae21d54, 0x1adeb451, 0x1160da4b, 0x1170ab2a, 0x1ad47311,
-	0x1ad105e9, 0x1175ef72, 0x1185b83f, 0x1ac6b841, 0x1ac346f8, 0x118af9d4, 0x119aba84, 0x1ab8ecec,
-	0x1ab57784, 0x119ff964, 0x11afb1ee, 0x1aab111c, 0x1aa79796, 0x11b4ee14, 0x11c49e6f, 0x1a9d24d9,
-	0x1a99a737, 0x11c9d7d9, 0x11d97ff9, 0x1a8f282b, 0x1a8ba670, 0x11deb6a4, 0x11ee5682, 0x1a811b1b,
-	0x1a7d9549, 0x11f38a6a, 0x120321fa, 0x1a72fdb2, 0x1a6f73ca, 0x1208531c, 0x1217e256, 0x1a64cff8,
-	0x1a6141fd, 0x121d10af, 0x122c9789, 0x1a5691f5, 0x1a52ffeb, 0x1231c316, 0x12414186, 0x1a4843b4,
-	0x1a44ad9b, 0x12466a44, 0x1255e041, 0x1a39e53d, 0x1a364b17, 0x125b062b, 0x126a73ac, 0x1a2b7698,
-	0x1a27d868, 0x126f96c1, 0x127efbbb, 0x1a1cf7ce, 0x1a195597, 0x12841bf6, 0x12937861, 0x1a0e68e9,
-	0x1a0ac2ac, 0x129895c0, 0x12a7e991, 0x19ffc9f1, 0x19fc1fb1, 0x12ad0412, 0x12bc4f40, 0x19f11af0,
-	0x19ed6caf, 0x12c166de, 0x12d0a960, 0x19e25bee, 0x19dea9ae, 0x12d5be18, 0x12e4f7e5, 0x19d38cf4,
-	0x19cfd6b8, 0x12ea09b4, 0x12f93ac2, 0x19c4ae0c, 0x19c0f3d6, 0x12fe49a6, 0x130d71eb, 0x19b5bf3f,
-	0x19b20111, 0x13127de0, 0x13219d53, 0x19a6c096, 0x19a2fe73, 0x1326a656, 0x1335bcef, 0x1997b21b,
-	0x1993ec04, 0x133ac2fc, 0x1349d0b0, 0x198893d6, 0x1984c9ce, 0x134ed3c5, 0x135dd88c, 0x197965d0,
-	0x197597da, 0x1362d8a6, 0x1371d476, 0x196a2815, 0x19665632, 0x1376d191, 0x1385c461, 0x195adaab,
-	0x195704df, 0x138abe7b, 0x1399a841, 0x194b7d9e, 0x1947a3eb, 0x139e9f56, 0x13ad800a, 0x193c10f7,
-	0x1938335e, 0x13b27417, 0x13c14bb0, 0x192c94bf, 0x1928b343, 0x13c63cb2, 0x13d50b26, 0x191d08ff,
-	0x191923a3, 0x13d9f91b, 0x13e8be60, 0x190d6dc1, 0x19098488, 0x13eda944, 0x13fc6553, 0x18fdc310,
-	0x18f9d5fa, 0x14014d23, 0x140ffff1, 0x18ee08f4, 0x18ea1805, 0x1414e4aa, 0x14238e2f, 0x18de3f77,
-	0x18da4ab2, 0x14286fce, 0x14371001, 0x18ce66a3, 0x18ca6e0a, 0x143bee83, 0x144a855b, 0x18be7e82,
-	0x18ba8217, 0x144f60bd, 0x145dee30, 0x18ae871e, 0x18aa86e3, 0x1462c670, 0x14714a76, 0x189e8080,
-	0x189a7c78, 0x14761f8f, 0x14849a1f, 0x188e6ab2, 0x188a62e0, 0x14896c0f, 0x1497dd20, 0x187e45be,
-	0x187a3a25, 0x149cabe4, 0x14ab136d, 0x186e11af, 0x186a0250, 0x14afdf03, 0x14be3cfa, 0x185dce8e,
-	0x1859bb6c, 0x14c3055e, 0x14d159bc, 0x184d7c65, 0x18496583, 0x14d61eeb, 0x14e469a6, 0x183d1b3e,
-	0x1839009e, 0x14e92b9e, 0x14f76cad, 0x182cab24, 0x18288cc8, 0x14fc2b6a, 0x150a62c6, 0x181c2c20,
-	0x18180a0c, 0x150f1e45, 0x151d4be3, 0x180b9e3d, 0x18077873, 0x15220422, 0x153027fb, 0x17fb0185,
-	0x17f6d807, 0x1534dcf6, 0x1542f700, 0x17ea5602, 0x17e628d3, 0x1547a8b5, 0x1555b8e8, 0x17d99bbe,
-	0x17d56ae0, 0x155a6754, 0x15686da7, 0x17c8d2c4, 0x17c49e3b, 0x156d18c7, 0x157b1532, 0x17b7fb1f,
-	0x17b3c2ec, 0x157fbd03, 0x158daf7c, 0x17a714d7, 0x17a2d8fe, 0x159253fb, 0x15a03c7a, 0x17961ff9,
-	0x1791e07b, 0x15a4dda5, 0x15b2bc22, 0x17851c8e, 0x1780d96f, 0x15b759f5, 0x15c52e67, 0x17740aa1,
-	0x176fc3e3, 0x15c9c8e0, 0x15d7933f, 0x1762ea3d, 0x175e9fe2, 0x15dc2a5a, 0x15e9ea9d, 0x1751bb6b,
-	0x174d6d77, 0x15ee7e58, 0x15fc3477, 0x17407e37, 0x173c2cac, 0x1600c4cf, 0x160e70c1, 0x172f32ab,
-	0x172add8c, 0x1612fdb3, 0x16209f70, 0x171dd8d2, 0x17198021, 0x162528fa, 0x1632c078, 0x170c70b7,
-	0x17081477, 0x16374697, 0x1644d3d0, 0x16fafa64, 0x16f69a97, 0x16495680, 0x1656d96a, 0x16e975e4,
-	0x16e5128e, 0x165b58aa, 0x1668d13e, 0x16d7e341, 0x16d37c65, 0x166d4d0a, 0x167abb3e, 0x16c64288,
-	0x16c1d827, 0x167f3394, 0x168c9760, 0x16b493c2, 0x16b025e0, 0x16910c3d, 0x169e659a, 0x16a2d6fb
-};
-
-const int twidTab512[8*6 + 32*6 + 128*6] = {
-	0x20000000, 0x00000000, 0x1d906bcf, 0x0c3ef153, 0x16a09e66, 0x16a09e66, 0x0c3ef153, 0x1d906bcf,
-	0x20000000, 0x00000000, 0x1f6297d0, 0x063e2e0f, 0x1d906bcf, 0x0c3ef153, 0x1a9b6629, 0x11c73b3a,
-	0x20000000, 0x00000000, 0x1a9b6629, 0x11c73b3a, 0x0c3ef153, 0x1d906bcf, 0xf9c1d1f1, 0x1f6297d0,
-	0x00000000, 0x20000000, 0xf3c10ead, 0x1d906bcf, 0xe95f619a, 0x16a09e66, 0xe26f9431, 0x0c3ef153,
-	0x16a09e66, 0x16a09e66, 0x11c73b3a, 0x1a9b6629, 0x0c3ef153, 0x1d906bcf, 0x063e2e0f, 0x1f6297d0,
-	0xe95f619a, 0x16a09e66, 0xe09d6830, 0x063e2e0f, 0xe26f9431, 0xf3c10ead, 0xee38c4c6, 0xe56499d7,
-
-	0x20000000, 0x00000000, 0x1fd88da4, 0x0322f4d8, 0x1f6297d0, 0x063e2e0f, 0x1e9f4157, 0x094a0317,
-	0x20000000, 0x00000000, 0x1ff621e3, 0x0191f65f, 0x1fd88da4, 0x0322f4d8, 0x1fa7557f, 0x04b2041c,
-	0x20000000, 0x00000000, 0x1fa7557f, 0x04b2041c, 0x1e9f4157, 0x094a0317, 0x1ced7af4, 0x0dae8805,
-	0x1d906bcf, 0x0c3ef153, 0x1c38b2f2, 0x0f15ae9c, 0x1a9b6629, 0x11c73b3a, 0x18bc806b, 0x144cf325,
-	0x1f6297d0, 0x063e2e0f, 0x1f0a7efc, 0x07c67e5f, 0x1e9f4157, 0x094a0317, 0x1e212105, 0x0ac7cd3b,
-	0x1a9b6629, 0x11c73b3a, 0x17b5df22, 0x157d6935, 0x144cf325, 0x18bc806b, 0x10738799, 0x1b728345,
-	0x16a09e66, 0x16a09e66, 0x144cf325, 0x18bc806b, 0x11c73b3a, 0x1a9b6629, 0x0f15ae9c, 0x1c38b2f2,
-	0x1d906bcf, 0x0c3ef153, 0x1ced7af4, 0x0dae8805, 0x1c38b2f2, 0x0f15ae9c, 0x1b728345, 0x10738799,
-	0x0c3ef153, 0x1d906bcf, 0x07c67e5f, 0x1f0a7efc, 0x0322f4d8, 0x1fd88da4, 0xfe6e09a1, 0x1ff621e3,
-	0x0c3ef153, 0x1d906bcf, 0x094a0317, 0x1e9f4157, 0x063e2e0f, 0x1f6297d0, 0x0322f4d8, 0x1fd88da4,
-	0x1a9b6629, 0x11c73b3a, 0x19b3e048, 0x130ff7fd, 0x18bc806b, 0x144cf325, 0x17b5df22, 0x157d6935,
-	0xf9c1d1f1, 0x1f6297d0, 0xf53832c5, 0x1e212105, 0xf0ea5164, 0x1c38b2f2, 0xecf00803, 0x19b3e048,
-	0x00000000, 0x20000000, 0xfcdd0b28, 0x1fd88da4, 0xf9c1d1f1, 0x1f6297d0, 0xf6b5fce9, 0x1e9f4157,
-	0x16a09e66, 0x16a09e66, 0x157d6935, 0x17b5df22, 0x144cf325, 0x18bc806b, 0x130ff7fd, 0x19b3e048,
-	0xe95f619a, 0x16a09e66, 0xe64c1fb8, 0x130ff7fd, 0xe3c74d0e, 0x0f15ae9c, 0xe1dedefb, 0x0ac7cd3b,
-	0xf3c10ead, 0x1d906bcf, 0xf0ea5164, 0x1c38b2f2, 0xee38c4c6, 0x1a9b6629, 0xebb30cdb, 0x18bc806b,
-	0x11c73b3a, 0x1a9b6629, 0x10738799, 0x1b728345, 0x0f15ae9c, 0x1c38b2f2, 0x0dae8805, 0x1ced7af4,
-	0xe09d6830, 0x063e2e0f, 0xe009de1d, 0x0191f65f, 0xe027725c, 0xfcdd0b28, 0xe0f58104, 0xf83981a1,
-	0xe95f619a, 0x16a09e66, 0xe7437f95, 0x144cf325, 0xe56499d7, 0x11c73b3a, 0xe3c74d0e, 0x0f15ae9c,
-	0x0c3ef153, 0x1d906bcf, 0x0ac7cd3b, 0x1e212105, 0x094a0317, 0x1e9f4157, 0x07c67e5f, 0x1f0a7efc,
-	0xe26f9431, 0xf3c10ead, 0xe48d7cbb, 0xef8c7867, 0xe7437f95, 0xebb30cdb, 0xea8296cb, 0xe84a20de,
-	0xe26f9431, 0x0c3ef153, 0xe160bea9, 0x094a0317, 0xe09d6830, 0x063e2e0f, 0xe027725c, 0x0322f4d8,
-	0x063e2e0f, 0x1f6297d0, 0x04b2041c, 0x1fa7557f, 0x0322f4d8, 0x1fd88da4, 0x0191f65f, 0x1ff621e3,
-	0xee38c4c6, 0xe56499d7, 0xf25177fb, 0xe312850c, 0xf6b5fce9, 0xe160bea9, 0xfb4dfbe4, 0xe058aa81,
-
-	0x20000000, 0x00000000, 0x1ffd8861, 0x00c90ab0, 0x1ff621e3, 0x0191f65f, 0x1fe9cdad, 0x025aa412,
-	0x20000000, 0x00000000, 0x1fff6217, 0x00648748, 0x1ffd8861, 0x00c90ab0, 0x1ffa72f0, 0x012d8657,
-	0x20000000, 0x00000000, 0x1ffa72f0, 0x012d8657, 0x1fe9cdad, 0x025aa412, 0x1fce15fd, 0x0386f0b9,
-	0x1fd88da4, 0x0322f4d8, 0x1fc26471, 0x03eac9cb, 0x1fa7557f, 0x04b2041c, 0x1f8764fa, 0x05788511,
-	0x1ff621e3, 0x0191f65f, 0x1ff09566, 0x01f656e8, 0x1fe9cdad, 0x025aa412, 0x1fe1cafd, 0x02beda01,
-	0x1fa7557f, 0x04b2041c, 0x1f7599a4, 0x05db7678, 0x1f38f3ac, 0x0702e09b, 0x1ef178a4, 0x0827dc07,
-	0x1f6297d0, 0x063e2e0f, 0x1f38f3ac, 0x0702e09b, 0x1f0a7efc, 0x07c67e5f, 0x1ed740e7, 0x0888e931,
-	0x1fd88da4, 0x0322f4d8, 0x1fce15fd, 0x0386f0b9, 0x1fc26471, 0x03eac9cb, 0x1fb57972, 0x044e7c34,
-	0x1e9f4157, 0x094a0317, 0x1e426a4b, 0x0a68f121, 0x1ddb13b7, 0x0b844298, 0x1d696174, 0x0c9b9532,
-	0x1e9f4157, 0x094a0317, 0x1e6288ec, 0x0a09ae4a, 0x1e212105, 0x0ac7cd3b, 0x1ddb13b7, 0x0b844298,
-	0x1fa7557f, 0x04b2041c, 0x1f97f925, 0x05155dac, 0x1f8764fa, 0x05788511, 0x1f7599a4, 0x05db7678,
-	0x1ced7af4, 0x0dae8805, 0x1c678b35, 0x0ebcbbae, 0x1bd7c0ac, 0x0fc5d26e, 0x1b3e4d3f, 0x10c9704d,
-	0x1d906bcf, 0x0c3ef153, 0x1d4134d1, 0x0cf7bca2, 0x1ced7af4, 0x0dae8805, 0x1c954b21, 0x0e63374d,
-	0x1f6297d0, 0x063e2e0f, 0x1f4e603b, 0x06a0a809, 0x1f38f3ac, 0x0702e09b, 0x1f2252f7, 0x0764d3f9,
-	0x1a9b6629, 0x11c73b3a, 0x19ef43ef, 0x12bedb26, 0x193a224a, 0x13affa29, 0x187c4010, 0x149a449c,
-	0x1c38b2f2, 0x0f15ae9c, 0x1bd7c0ac, 0x0fc5d26e, 0x1b728345, 0x10738799, 0x1b090a58, 0x111eb354,
-	0x1f0a7efc, 0x07c67e5f, 0x1ef178a4, 0x0827dc07, 0x1ed740e7, 0x0888e931, 0x1ebbd8c9, 0x08e9a220,
-	0x17b5df22, 0x157d6935, 0x16e74455, 0x16591926, 0x1610b755, 0x172d0838, 0x15328293, 0x17f8ece3,
-	0x1a9b6629, 0x11c73b3a, 0x1a29a7a0, 0x126d054d, 0x19b3e048, 0x130ff7fd, 0x193a224a, 0x13affa29,
-	0x1e9f4157, 0x094a0317, 0x1e817bab, 0x09aa0861, 0x1e6288ec, 0x0a09ae4a, 0x1e426a4b, 0x0a68f121,
-	0x144cf325, 0x18bc806b, 0x136058b1, 0x19777ef5, 0x126d054d, 0x1a29a7a0, 0x11734d64, 0x1ad2bc9e,
-	0x18bc806b, 0x144cf325, 0x183b0e0c, 0x14e6cabc, 0x17b5df22, 0x157d6935, 0x172d0838, 0x1610b755,
-	0x1e212105, 0x0ac7cd3b, 0x1dfeae62, 0x0b263eef, 0x1ddb13b7, 0x0b844298, 0x1db65262, 0x0be1d499,
-	0x10738799, 0x1b728345, 0x0f6e0ca9, 0x1c08c426, 0x0e63374d, 0x1c954b21, 0x0d536416, 0x1d17e774,
-	0x16a09e66, 0x16a09e66, 0x1610b755, 0x172d0838, 0x157d6935, 0x17b5df22, 0x14e6cabc, 0x183b0e0c,
-	0x1d906bcf, 0x0c3ef153, 0x1d696174, 0x0c9b9532, 0x1d4134d1, 0x0cf7bca2, 0x1d17e774, 0x0d536416,
-	0x0c3ef153, 0x1d906bcf, 0x0b263eef, 0x1dfeae62, 0x0a09ae4a, 0x1e6288ec, 0x08e9a220, 0x1ebbd8c9,
-	0x144cf325, 0x18bc806b, 0x13affa29, 0x193a224a, 0x130ff7fd, 0x19b3e048, 0x126d054d, 0x1a29a7a0,
-	0x1ced7af4, 0x0dae8805, 0x1cc1f0f4, 0x0e0924ec, 0x1c954b21, 0x0e63374d, 0x1c678b35, 0x0ebcbbae,
-	0x07c67e5f, 0x1f0a7efc, 0x06a0a809, 0x1f4e603b, 0x05788511, 0x1f8764fa, 0x044e7c34, 0x1fb57972,
-	0x11c73b3a, 0x1a9b6629, 0x111eb354, 0x1b090a58, 0x10738799, 0x1b728345, 0x0fc5d26e, 0x1bd7c0ac,
-	0x1c38b2f2, 0x0f15ae9c, 0x1c08c426, 0x0f6e0ca9, 0x1bd7c0ac, 0x0fc5d26e, 0x1ba5aa67, 0x101cfc87,
-	0x0322f4d8, 0x1fd88da4, 0x01f656e8, 0x1ff09566, 0x00c90ab0, 0x1ffd8861, 0xff9b78b8, 0x1fff6217,
-	0x0f15ae9c, 0x1c38b2f2, 0x0e63374d, 0x1c954b21, 0x0dae8805, 0x1ced7af4, 0x0cf7bca2, 0x1d4134d1,
-	0x1b728345, 0x10738799, 0x1b3e4d3f, 0x10c9704d, 0x1b090a58, 0x111eb354, 0x1ad2bc9e, 0x11734d64,
-	0xfe6e09a1, 0x1ff621e3, 0xfd4125ff, 0x1fe1cafd, 0xfc153635, 0x1fc26471, 0xfaeaa254, 0x1f97f925,
-	0x0c3ef153, 0x1d906bcf, 0x0b844298, 0x1ddb13b7, 0x0ac7cd3b, 0x1e212105, 0x0a09ae4a, 0x1e6288ec,
-	0x1a9b6629, 0x11c73b3a, 0x1a63091b, 0x121a7999, 0x1a29a7a0, 0x126d054d, 0x19ef43ef, 0x12bedb26,
-	0xf9c1d1f1, 0x1f6297d0, 0xf89b2c07, 0x1f2252f7, 0xf77716cf, 0x1ed740e7, 0xf655f79f, 0x1e817bab,
-	0x094a0317, 0x1e9f4157, 0x0888e931, 0x1ed740e7, 0x07c67e5f, 0x1f0a7efc, 0x0702e09b, 0x1f38f3ac,
-	0x19b3e048, 0x130ff7fd, 0x19777ef5, 0x136058b1, 0x193a224a, 0x13affa29, 0x18fbcca4, 0x13fed953,
-	0xf53832c5, 0x1e212105, 0xf41e2b67, 0x1db65262, 0xf308435e, 0x1d4134d1, 0xf1f6db14, 0x1cc1f0f4,
-	0x063e2e0f, 0x1f6297d0, 0x05788511, 0x1f8764fa, 0x04b2041c, 0x1fa7557f, 0x03eac9cb, 0x1fc26471,
-	0x18bc806b, 0x144cf325, 0x187c4010, 0x149a449c, 0x183b0e0c, 0x14e6cabc, 0x17f8ece3, 0x15328293,
-	0xf0ea5164, 0x1c38b2f2, 0xefe30379, 0x1ba5aa67, 0xeee14cac, 0x1b090a58, 0xede58667, 0x1a63091b,
-	0x0322f4d8, 0x1fd88da4, 0x025aa412, 0x1fe9cdad, 0x0191f65f, 0x1ff621e3, 0x00c90ab0, 0x1ffd8861,
-	0x17b5df22, 0x157d6935, 0x1771e75f, 0x15c77bbe, 0x172d0838, 0x1610b755, 0x16e74455, 0x16591926,
-	0xecf00803, 0x19b3e048, 0xec0126ad, 0x18fbcca4, 0xeb193544, 0x183b0e0c, 0xea388442, 0x1771e75f,
-	0x00000000, 0x20000000, 0xff36f550, 0x1ffd8861, 0xfe6e09a1, 0x1ff621e3, 0xfda55bee, 0x1fe9cdad,
-	0x16a09e66, 0x16a09e66, 0x16591926, 0x16e74455, 0x1610b755, 0x172d0838, 0x15c77bbe, 0x1771e75f,
-	0xe95f619a, 0x16a09e66, 0xe88e18a1, 0x15c77bbe, 0xe7c4f1f4, 0x14e6cabc, 0xe704335c, 0x13fed953,
-	0xfcdd0b28, 0x1fd88da4, 0xfc153635, 0x1fc26471, 0xfb4dfbe4, 0x1fa7557f, 0xfa877aef, 0x1f8764fa,
-	0x157d6935, 0x17b5df22, 0x15328293, 0x17f8ece3, 0x14e6cabc, 0x183b0e0c, 0x149a449c, 0x187c4010,
-	0xe64c1fb8, 0x130ff7fd, 0xe59cf6e5, 0x121a7999, 0xe4f6f5a8, 0x111eb354, 0xe45a5599, 0x101cfc87,
-	0xf9c1d1f1, 0x1f6297d0, 0xf8fd1f65, 0x1f38f3ac, 0xf83981a1, 0x1f0a7efc, 0xf77716cf, 0x1ed740e7,
-	0x144cf325, 0x18bc806b, 0x13fed953, 0x18fbcca4, 0x13affa29, 0x193a224a, 0x136058b1, 0x19777ef5,
-	0xe3c74d0e, 0x0f15ae9c, 0xe33e0f0c, 0x0e0924ec, 0xe2becb2f, 0x0cf7bca2, 0xe249ad9e, 0x0be1d499,
-	0xf6b5fce9, 0x1e9f4157, 0xf5f651b6, 0x1e6288ec, 0xf53832c5, 0x1e212105, 0xf47bbd68, 0x1ddb13b7,
-	0x130ff7fd, 0x19b3e048, 0x12bedb26, 0x19ef43ef, 0x126d054d, 0x1a29a7a0, 0x121a7999, 0x1a63091b,
-	0xe1dedefb, 0x0ac7cd3b, 0xe17e8455, 0x09aa0861, 0xe128bf19, 0x0888e931, 0xe0ddad09, 0x0764d3f9,
-	0xf3c10ead, 0x1d906bcf, 0xf308435e, 0x1d4134d1, 0xf25177fb, 0x1ced7af4, 0xf19cc8b3, 0x1c954b21,
-	0x11c73b3a, 0x1a9b6629, 0x11734d64, 0x1ad2bc9e, 0x111eb354, 0x1b090a58, 0x10c9704d, 0x1b3e4d3f,
-	0xe09d6830, 0x063e2e0f, 0xe06806db, 0x05155dac, 0xe03d9b8f, 0x03eac9cb, 0xe01e3503, 0x02beda01,
-	0xf0ea5164, 0x1c38b2f2, 0xf03a2d92, 0x1bd7c0ac, 0xef8c7867, 0x1b728345, 0xeee14cac, 0x1b090a58,
-	0x10738799, 0x1b728345, 0x101cfc87, 0x1ba5aa67, 0x0fc5d26e, 0x1bd7c0ac, 0x0f6e0ca9, 0x1c08c426,
-	0xe009de1d, 0x0191f65f, 0xe0009de9, 0x00648748, 0xe002779f, 0xff36f550, 0xe00f6a9a, 0xfe09a918,
-	0xee38c4c6, 0x1a9b6629, 0xed92fab3, 0x1a29a7a0, 0xecf00803, 0x19b3e048, 0xec5005d7, 0x193a224a,
-	0x0f15ae9c, 0x1c38b2f2, 0x0ebcbbae, 0x1c678b35, 0x0e63374d, 0x1c954b21, 0x0e0924ec, 0x1cc1f0f4,
-	0xe027725c, 0xfcdd0b28, 0xe04a868e, 0xfbb183cc, 0xe0789b06, 0xfa877aef, 0xe0b19fc5, 0xf95f57f7,
-	0xebb30cdb, 0x18bc806b, 0xeb193544, 0x183b0e0c, 0xea8296cb, 0x17b5df22, 0xe9ef48ab, 0x172d0838,
-	0x0dae8805, 0x1ced7af4, 0x0d536416, 0x1d17e774, 0x0cf7bca2, 0x1d4134d1, 0x0c9b9532, 0x1d696174,
-	0xe0f58104, 0xf83981a1, 0xe1442737, 0xf7165de0, 0xe19d7714, 0xf5f651b6, 0xe201519e, 0xf4d9c111,
-	0xe95f619a, 0x16a09e66, 0xe8d2f7c8, 0x1610b755, 0xe84a20de, 0x157d6935, 0xe7c4f1f4, 0x14e6cabc,
-	0x0c3ef153, 0x1d906bcf, 0x0be1d499, 0x1db65262, 0x0b844298, 0x1ddb13b7, 0x0b263eef, 0x1dfeae62,
-	0xe26f9431, 0xf3c10ead, 0xe2e8188c, 0xf2ac9bea, 0xe36ab4df, 0xf19cc8b3, 0xe3f73bda, 0xf091f357,
-	0xe7437f95, 0x144cf325, 0xe6c5ddb6, 0x13affa29, 0xe64c1fb8, 0x130ff7fd, 0xe5d65860, 0x126d054d,
-	0x0ac7cd3b, 0x1e212105, 0x0a68f121, 0x1e426a4b, 0x0a09ae4a, 0x1e6288ec, 0x09aa0861, 0x1e817bab,
-	0xe48d7cbb, 0xef8c7867, 0xe52d4362, 0xee8cb29c, 0xe5d65860, 0xed92fab3, 0xe688810b, 0xec9fa74f,
-	0xe56499d7, 0x11c73b3a, 0xe4f6f5a8, 0x111eb354, 0xe48d7cbb, 0x10738799, 0xe4283f54, 0x0fc5d26e,
-	0x094a0317, 0x1e9f4157, 0x08e9a220, 0x1ebbd8c9, 0x0888e931, 0x1ed740e7, 0x0827dc07, 0x1ef178a4,
-	0xe7437f95, 0xebb30cdb, 0xe807131d, 0xeacd7d6d, 0xe8d2f7c8, 0xe9ef48ab, 0xe9a6e6da, 0xe918bbab,
-	0xe3c74d0e, 0x0f15ae9c, 0xe36ab4df, 0x0e63374d, 0xe312850c, 0x0dae8805, 0xe2becb2f, 0x0cf7bca2,
-	0x07c67e5f, 0x1f0a7efc, 0x0764d3f9, 0x1f2252f7, 0x0702e09b, 0x1f38f3ac, 0x06a0a809, 0x1f4e603b,
-	0xea8296cb, 0xe84a20de, 0xeb65bb64, 0xe783bff0, 0xec5005d7, 0xe6c5ddb6, 0xed4124da, 0xe610bc11,
-	0xe26f9431, 0x0c3ef153, 0xe224ec49, 0x0b844298, 0xe1dedefb, 0x0ac7cd3b, 0xe19d7714, 0x0a09ae4a,
-	0x063e2e0f, 0x1f6297d0, 0x05db7678, 0x1f7599a4, 0x05788511, 0x1f8764fa, 0x05155dac, 0x1f97f925,
-	0xee38c4c6, 0xe56499d7, 0xef368fb3, 0xe4c1b2c1, 0xf03a2d92, 0xe4283f54, 0xf1434452, 0xe39874cb,
-	0xe160bea9, 0x094a0317, 0xe128bf19, 0x0888e931, 0xe0f58104, 0x07c67e5f, 0xe0c70c54, 0x0702e09b,
-	0x04b2041c, 0x1fa7557f, 0x044e7c34, 0x1fb57972, 0x03eac9cb, 0x1fc26471, 0x0386f0b9, 0x1fce15fd,
-	0xf25177fb, 0xe312850c, 0xf3646ace, 0xe2969e8c, 0xf47bbd68, 0xe224ec49, 0xf5970edf, 0xe1bd95b5,
-	0xe09d6830, 0x063e2e0f, 0xe0789b06, 0x05788511, 0xe058aa81, 0x04b2041c, 0xe03d9b8f, 0x03eac9cb,
-	0x0322f4d8, 0x1fd88da4, 0x02beda01, 0x1fe1cafd, 0x025aa412, 0x1fe9cdad, 0x01f656e8, 0x1ff09566,
-	0xf6b5fce9, 0xe160bea9, 0xf7d823f9, 0xe10e875c, 0xf8fd1f65, 0xe0c70c54, 0xfa248988, 0xe08a665c,
-	0xe027725c, 0x0322f4d8, 0xe0163253, 0x025aa412, 0xe009de1d, 0x0191f65f, 0xe002779f, 0x00c90ab0,
-	0x0191f65f, 0x1ff621e3, 0x012d8657, 0x1ffa72f0, 0x00c90ab0, 0x1ffd8861, 0x00648748, 0x1fff6217,
-	0xfb4dfbe4, 0xe058aa81, 0xfc790f47, 0xe031ea03, 0xfda55bee, 0xe0163253, 0xfed279a9, 0xe0058d10
-};
-
-const int twidTab64[4*6 + 16*6] = {
-	0x20000000, 0x00000000, 0x16a09e66, 0x16a09e66, 0x00000000, 0x20000000, 0xe95f619a, 0x16a09e66,
-	0x20000000, 0x00000000, 0x1d906bcf, 0x0c3ef153, 0x16a09e66, 0x16a09e66, 0x0c3ef153, 0x1d906bcf,
-	0x20000000, 0x00000000, 0x0c3ef153, 0x1d906bcf, 0xe95f619a, 0x16a09e66, 0xe26f9431, 0xf3c10ead,
-
-	0x20000000, 0x00000000, 0x1f6297d0, 0x063e2e0f, 0x1d906bcf, 0x0c3ef153, 0x1a9b6629, 0x11c73b3a,
-	0x20000000, 0x00000000, 0x1fd88da4, 0x0322f4d8, 0x1f6297d0, 0x063e2e0f, 0x1e9f4157, 0x094a0317,
-	0x20000000, 0x00000000, 0x1e9f4157, 0x094a0317, 0x1a9b6629, 0x11c73b3a, 0x144cf325, 0x18bc806b,
-	0x16a09e66, 0x16a09e66, 0x11c73b3a, 0x1a9b6629, 0x0c3ef153, 0x1d906bcf, 0x063e2e0f, 0x1f6297d0,
-	0x1d906bcf, 0x0c3ef153, 0x1c38b2f2, 0x0f15ae9c, 0x1a9b6629, 0x11c73b3a, 0x18bc806b, 0x144cf325,
-	0x0c3ef153, 0x1d906bcf, 0x0322f4d8, 0x1fd88da4, 0xf9c1d1f1, 0x1f6297d0, 0xf0ea5164, 0x1c38b2f2,
-	0x00000000, 0x20000000, 0xf9c1d1f1, 0x1f6297d0, 0xf3c10ead, 0x1d906bcf, 0xee38c4c6, 0x1a9b6629,
-	0x16a09e66, 0x16a09e66, 0x144cf325, 0x18bc806b, 0x11c73b3a, 0x1a9b6629, 0x0f15ae9c, 0x1c38b2f2,
-	0xe95f619a, 0x16a09e66, 0xe3c74d0e, 0x0f15ae9c, 0xe09d6830, 0x063e2e0f, 0xe027725c, 0xfcdd0b28,
-	0xe95f619a, 0x16a09e66, 0xe56499d7, 0x11c73b3a, 0xe26f9431, 0x0c3ef153, 0xe09d6830, 0x063e2e0f,
-	0x0c3ef153, 0x1d906bcf, 0x094a0317, 0x1e9f4157, 0x063e2e0f, 0x1f6297d0, 0x0322f4d8, 0x1fd88da4,
-	0xe26f9431, 0xf3c10ead, 0xe7437f95, 0xebb30cdb, 0xee38c4c6, 0xe56499d7, 0xf6b5fce9, 0xe160bea9
-};
-
-#else
-
-/*
- *  Q30 for 128 and 1024
- *
- * for (i = 0; i < num/4; i++) {
- *   angle = (i + 0.125) * M_PI / num;
- *   x = cos(angle) * (1 << 30);
- *   x = sin(angle) * (1 << 30);
- *
- *   angle = (num/2 - 1 - i + 0.125) * M_PI / num;
- *   x = cos(angle) * (1 << 30);
- *   x = sin(angle) * (1 << 30);
- * }
- */
-const int cossintab[128 + 1024] = {
-	/* 128 */
-	0x3fffec43, 0x003243f1, 0x015fd4d2, 0x3ffc38d1, 0x3ff9c13a, 0x01c454f5, 0x02f1b755, 0x3feea776,
-	0x3fe9b8a9, 0x03562038, 0x0483259d, 0x3fd73a4a, 0x3fcfd50b, 0x04e767c5, 0x0613e1c5, 0x3fb5f4ea,
-	0x3fac1a5b, 0x0677edbb, 0x07a3adff, 0x3f8adc77, 0x3f7e8e1e, 0x08077457, 0x09324ca7, 0x3f55f796,
-	0x3f473759, 0x0995bdfd, 0x0abf8043, 0x3f174e70, 0x3f061e95, 0x0b228d42, 0x0c4b0b94, 0x3eceeaad,
-	0x3ebb4ddb, 0x0cada4f5, 0x0dd4b19a, 0x3e7cd778, 0x3e66d0b4, 0x0e36c82a, 0x0f5c35a3, 0x3e212179,
-	0x3e08b42a, 0x0fbdba40, 0x10e15b4e, 0x3dbbd6d4, 0x3da106bd, 0x11423ef0, 0x1263e699, 0x3d4d0728,
-	0x3d2fd86c, 0x12c41a4f, 0x13e39be9, 0x3cd4c38b, 0x3cb53aaa, 0x144310dd, 0x15604013, 0x3c531e88,
-	0x3c314060, 0x15bee78c, 0x16d99864, 0x3bc82c1f, 0x3ba3fde7, 0x173763c9, 0x184f6aab, 0x3b3401bb,
-	0x3b0d8909, 0x18ac4b87, 0x19c17d44, 0x3a96b636, 0x3a6df8f8, 0x1a1d6544, 0x1b2f971e, 0x39f061d2,
-	0x39c5664f, 0x1b8a7815, 0x1c997fc4, 0x39411e33, 0x3913eb0e, 0x1cf34baf, 0x1dfeff67, 0x38890663,
-	0x3859a292, 0x1e57a86d, 0x1f5fdee6, 0x37c836c2, 0x3796a996, 0x1fb7575c, 0x20bbe7d8, 0x36fecd0e,
-	0x36cb1e2a, 0x21122240, 0x2212e492, 0x362ce855, 0x35f71fb1, 0x2267d3a0, 0x2364a02e, 0x3552a8f4,
-	0x351acedd, 0x23b836ca, 0x24b0e699, 0x34703095, 0x34364da6, 0x250317df, 0x25f78497, 0x3385a222,
-	0x3349bf48, 0x264843d9, 0x273847c8, 0x329321c7, 0x32554840, 0x27878893, 0x2872feb6, 0x3198d4ea,
-	0x31590e3e, 0x28c0b4d2, 0x29a778db, 0x3096e223, 0x30553828, 0x29f3984c, 0x2ad586a3, 0x2f8d713a,
-	0x2f49ee0f, 0x2b2003ac, 0x2bfcf97c, 0x2e7cab1c, 0x2e37592c, 0x2c45c8a0, 0x2d1da3d5, 0x2d64b9da,
-	/* 1024 */
-	0x3fffffb1, 0x0006487f, 0x002bfb74, 0x3ffff0e3, 0x3fffe705, 0x00388c6e, 0x005e3f4c, 0x3fffba9b,
-	0x3fffa6de, 0x006ad03b, 0x009082ea, 0x3fff5cd8, 0x3fff3f3c, 0x009d13c5, 0x00c2c62f, 0x3ffed79b,
-	0x3ffeb021, 0x00cf56ef, 0x00f508fc, 0x3ffe2ae5, 0x3ffdf98c, 0x01019998, 0x01274b31, 0x3ffd56b5,
-	0x3ffd1b7e, 0x0133dba3, 0x01598cb1, 0x3ffc5b0c, 0x3ffc15f7, 0x01661cf0, 0x018bcd5b, 0x3ffb37ec,
-	0x3ffae8f9, 0x01985d60, 0x01be0d11, 0x3ff9ed53, 0x3ff99483, 0x01ca9cd4, 0x01f04bb4, 0x3ff87b44,
-	0x3ff81896, 0x01fcdb2e, 0x02228924, 0x3ff6e1bf, 0x3ff67534, 0x022f184d, 0x0254c544, 0x3ff520c5,
-	0x3ff4aa5d, 0x02615414, 0x0286fff3, 0x3ff33858, 0x3ff2b813, 0x02938e62, 0x02b93914, 0x3ff12878,
-	0x3ff09e56, 0x02c5c71a, 0x02eb7086, 0x3feef126, 0x3fee5d28, 0x02f7fe1c, 0x031da62b, 0x3fec9265,
-	0x3febf48b, 0x032a3349, 0x034fd9e5, 0x3fea0c35, 0x3fe96480, 0x035c6682, 0x03820b93, 0x3fe75e98,
-	0x3fe6ad08, 0x038e97a9, 0x03b43b17, 0x3fe48990, 0x3fe3ce26, 0x03c0c69e, 0x03e66852, 0x3fe18d1f,
-	0x3fe0c7da, 0x03f2f342, 0x04189326, 0x3fde6945, 0x3fdd9a27, 0x04251d77, 0x044abb73, 0x3fdb1e06,
-	0x3fda450f, 0x0457451d, 0x047ce11a, 0x3fd7ab64, 0x3fd6c894, 0x04896a16, 0x04af03fc, 0x3fd4115f,
-	0x3fd324b7, 0x04bb8c42, 0x04e123fa, 0x3fd04ffc, 0x3fcf597c, 0x04edab83, 0x051340f6, 0x3fcc673b,
-	0x3fcb66e4, 0x051fc7b9, 0x05455ad1, 0x3fc8571f, 0x3fc74cf3, 0x0551e0c7, 0x0577716b, 0x3fc41fac,
-	0x3fc30baa, 0x0583f68c, 0x05a984a6, 0x3fbfc0e3, 0x3fbea30c, 0x05b608eb, 0x05db9463, 0x3fbb3ac7,
-	0x3fba131b, 0x05e817c3, 0x060da083, 0x3fb68d5b, 0x3fb55bdc, 0x061a22f7, 0x063fa8e7, 0x3fb1b8a2,
-	0x3fb07d50, 0x064c2a67, 0x0671ad71, 0x3facbc9f, 0x3fab777b, 0x067e2df5, 0x06a3ae00, 0x3fa79954,
-	0x3fa64a5f, 0x06b02d81, 0x06d5aa77, 0x3fa24ec6, 0x3fa0f600, 0x06e228ee, 0x0707a2b7, 0x3f9cdcf7,
-	0x3f9b7a62, 0x0714201b, 0x073996a1, 0x3f9743eb, 0x3f95d787, 0x074612eb, 0x076b8616, 0x3f9183a5,
-	0x3f900d72, 0x0778013d, 0x079d70f7, 0x3f8b9c28, 0x3f8a1c29, 0x07a9eaf5, 0x07cf5726, 0x3f858d79,
-	0x3f8403ae, 0x07dbcff2, 0x08013883, 0x3f7f579b, 0x3f7dc405, 0x080db016, 0x083314f1, 0x3f78fa92,
-	0x3f775d31, 0x083f8b43, 0x0864ec4f, 0x3f727661, 0x3f70cf38, 0x08716159, 0x0896be80, 0x3f6bcb0e,
-	0x3f6a1a1c, 0x08a3323a, 0x08c88b65, 0x3f64f89b, 0x3f633de2, 0x08d4fdc6, 0x08fa52de, 0x3f5dff0e,
-	0x3f5c3a8f, 0x0906c3e0, 0x092c14ce, 0x3f56de6a, 0x3f551026, 0x09388469, 0x095dd116, 0x3f4f96b4,
-	0x3f4dbeac, 0x096a3f42, 0x098f8796, 0x3f4827f0, 0x3f464626, 0x099bf44c, 0x09c13831, 0x3f409223,
-	0x3f3ea697, 0x09cda368, 0x09f2e2c7, 0x3f38d552, 0x3f36e006, 0x09ff4c78, 0x0a24873a, 0x3f30f181,
-	0x3f2ef276, 0x0a30ef5e, 0x0a56256c, 0x3f28e6b6, 0x3f26ddec, 0x0a628bfa, 0x0a87bd3d, 0x3f20b4f5,
-	0x3f1ea26e, 0x0a94222f, 0x0ab94e8f, 0x3f185c43, 0x3f164001, 0x0ac5b1dc, 0x0aead944, 0x3f0fdca5,
-	0x3f0db6a9, 0x0af73ae5, 0x0b1c5d3d, 0x3f073621, 0x3f05066d, 0x0b28bd2a, 0x0b4dda5c, 0x3efe68bc,
-	0x3efc2f50, 0x0b5a388d, 0x0b7f5081, 0x3ef5747b, 0x3ef3315a, 0x0b8bacf0, 0x0bb0bf8f, 0x3eec5965,
-	0x3eea0c8e, 0x0bbd1a33, 0x0be22766, 0x3ee3177e, 0x3ee0c0f4, 0x0bee8038, 0x0c1387e9, 0x3ed9aecc,
-	0x3ed74e91, 0x0c1fdee1, 0x0c44e0f9, 0x3ed01f55, 0x3ecdb56a, 0x0c513610, 0x0c763278, 0x3ec66920,
-	0x3ec3f585, 0x0c8285a5, 0x0ca77c47, 0x3ebc8c31, 0x3eba0ee9, 0x0cb3cd84, 0x0cd8be47, 0x3eb2888f,
-	0x3eb0019c, 0x0ce50d8c, 0x0d09f85b, 0x3ea85e41, 0x3ea5cda3, 0x0d1645a0, 0x0d3b2a64, 0x3e9e0d4c,
-	0x3e9b7306, 0x0d4775a1, 0x0d6c5443, 0x3e9395b7, 0x3e90f1ca, 0x0d789d71, 0x0d9d75db, 0x3e88f788,
-	0x3e8649f5, 0x0da9bcf2, 0x0dce8f0d, 0x3e7e32c6, 0x3e7b7b90, 0x0ddad406, 0x0dff9fba, 0x3e734778,
-	0x3e70869f, 0x0e0be28e, 0x0e30a7c5, 0x3e6835a4, 0x3e656b2b, 0x0e3ce86b, 0x0e61a70f, 0x3e5cfd51,
-	0x3e5a2939, 0x0e6de580, 0x0e929d7a, 0x3e519e86, 0x3e4ec0d1, 0x0e9ed9af, 0x0ec38ae8, 0x3e46194a,
-	0x3e4331fa, 0x0ecfc4d9, 0x0ef46f3b, 0x3e3a6da4, 0x3e377cbb, 0x0f00a6df, 0x0f254a53, 0x3e2e9b9c,
-	0x3e2ba11b, 0x0f317fa5, 0x0f561c15, 0x3e22a338, 0x3e1f9f21, 0x0f624f0c, 0x0f86e460, 0x3e168480,
-	0x3e1376d5, 0x0f9314f5, 0x0fb7a317, 0x3e0a3f7b, 0x3e07283f, 0x0fc3d143, 0x0fe8581d, 0x3dfdd432,
-	0x3dfab365, 0x0ff483d7, 0x10190352, 0x3df142ab, 0x3dee1851, 0x10252c94, 0x1049a49a, 0x3de48aef,
-	0x3de15708, 0x1055cb5b, 0x107a3bd5, 0x3dd7ad05, 0x3dd46f94, 0x1086600e, 0x10aac8e6, 0x3dcaa8f5,
-	0x3dc761fc, 0x10b6ea90, 0x10db4baf, 0x3dbd7ec7, 0x3dba2e48, 0x10e76ac3, 0x110bc413, 0x3db02e84,
-	0x3dacd481, 0x1117e088, 0x113c31f3, 0x3da2b834, 0x3d9f54af, 0x11484bc2, 0x116c9531, 0x3d951bde,
-	0x3d91aed9, 0x1178ac53, 0x119cedaf, 0x3d87598c, 0x3d83e309, 0x11a9021d, 0x11cd3b50, 0x3d797145,
-	0x3d75f147, 0x11d94d02, 0x11fd7df6, 0x3d6b6313, 0x3d67d99b, 0x12098ce5, 0x122db583, 0x3d5d2efe,
-	0x3d599c0e, 0x1239c1a7, 0x125de1da, 0x3d4ed50f, 0x3d4b38aa, 0x1269eb2b, 0x128e02dc, 0x3d40554e,
-	0x3d3caf76, 0x129a0954, 0x12be186c, 0x3d31afc5, 0x3d2e007c, 0x12ca1c03, 0x12ee226c, 0x3d22e47c,
-	0x3d1f2bc5, 0x12fa231b, 0x131e20c0, 0x3d13f37e, 0x3d10315a, 0x132a1e7e, 0x134e1348, 0x3d04dcd2,
-	0x3d011145, 0x135a0e0e, 0x137df9e7, 0x3cf5a082, 0x3cf1cb8e, 0x1389f1af, 0x13add481, 0x3ce63e98,
-	0x3ce2603f, 0x13b9c943, 0x13dda2f7, 0x3cd6b71e, 0x3cd2cf62, 0x13e994ab, 0x140d652c, 0x3cc70a1c,
-	0x3cc318ff, 0x141953cb, 0x143d1b02, 0x3cb7379c, 0x3cb33d22, 0x14490685, 0x146cc45c, 0x3ca73fa9,
-	0x3ca33bd3, 0x1478acbc, 0x149c611d, 0x3c97224c, 0x3c93151d, 0x14a84652, 0x14cbf127, 0x3c86df8e,
-	0x3c82c909, 0x14d7d32a, 0x14fb745e, 0x3c76777b, 0x3c7257a2, 0x15075327, 0x152aeaa3, 0x3c65ea1c,
-	0x3c61c0f1, 0x1536c62b, 0x155a53d9, 0x3c55377b, 0x3c510501, 0x15662c18, 0x1589afe3, 0x3c445fa2,
-	0x3c4023dd, 0x159584d3, 0x15b8fea4, 0x3c33629d, 0x3c2f1d8e, 0x15c4d03e, 0x15e83fff, 0x3c224075,
-	0x3c1df21f, 0x15f40e3a, 0x161773d6, 0x3c10f935, 0x3c0ca19b, 0x16233eac, 0x16469a0d, 0x3bff8ce8,
-	0x3bfb2c0c, 0x16526176, 0x1675b286, 0x3bedfb99, 0x3be9917e, 0x1681767c, 0x16a4bd25, 0x3bdc4552,
-	0x3bd7d1fa, 0x16b07d9f, 0x16d3b9cc, 0x3bca6a1d, 0x3bc5ed8d, 0x16df76c3, 0x1702a85e, 0x3bb86a08,
-	0x3bb3e440, 0x170e61cc, 0x173188be, 0x3ba6451b, 0x3ba1b620, 0x173d3e9b, 0x17605ad0, 0x3b93fb63,
-	0x3b8f6337, 0x176c0d15, 0x178f1e76, 0x3b818ceb, 0x3b7ceb90, 0x179acd1c, 0x17bdd394, 0x3b6ef9be,
-	0x3b6a4f38, 0x17c97e93, 0x17ec7a0d, 0x3b5c41e8, 0x3b578e39, 0x17f8215e, 0x181b11c4, 0x3b496574,
-	0x3b44a8a0, 0x1826b561, 0x18499a9d, 0x3b36646e, 0x3b319e77, 0x18553a7d, 0x1878147a, 0x3b233ee1,
-	0x3b1e6fca, 0x1883b097, 0x18a67f3f, 0x3b0ff4d9, 0x3b0b1ca6, 0x18b21791, 0x18d4dad0, 0x3afc8663,
-	0x3af7a516, 0x18e06f50, 0x1903270f, 0x3ae8f38b, 0x3ae40926, 0x190eb7b7, 0x193163e1, 0x3ad53c5b,
-	0x3ad048e3, 0x193cf0a9, 0x195f9128, 0x3ac160e1, 0x3abc6458, 0x196b1a09, 0x198daec8, 0x3aad6129,
-	0x3aa85b92, 0x199933bb, 0x19bbbca6, 0x3a993d3e, 0x3a942e9d, 0x19c73da3, 0x19e9baa3, 0x3a84f52f,
-	0x3a7fdd86, 0x19f537a4, 0x1a17a8a5, 0x3a708906, 0x3a6b6859, 0x1a2321a2, 0x1a45868e, 0x3a5bf8d1,
-	0x3a56cf23, 0x1a50fb81, 0x1a735442, 0x3a47449c, 0x3a4211f0, 0x1a7ec524, 0x1aa111a6, 0x3a326c74,
-	0x3a2d30cd, 0x1aac7e6f, 0x1acebe9d, 0x3a1d7066, 0x3a182bc8, 0x1ada2746, 0x1afc5b0a, 0x3a08507f,
-	0x3a0302ed, 0x1b07bf8c, 0x1b29e6d2, 0x39f30ccc, 0x39edb649, 0x1b354727, 0x1b5761d8, 0x39dda55a,
-	0x39d845e9, 0x1b62bdf8, 0x1b84cc01, 0x39c81a36, 0x39c2b1da, 0x1b9023e5, 0x1bb22530, 0x39b26b6d,
-	0x39acfa2b, 0x1bbd78d2, 0x1bdf6d4a, 0x399c990d, 0x39971ee7, 0x1beabca1, 0x1c0ca432, 0x3986a324,
-	0x3981201e, 0x1c17ef39, 0x1c39c9cd, 0x397089bf, 0x396afddc, 0x1c45107c, 0x1c66ddfe, 0x395a4ceb,
-	0x3954b82e, 0x1c72204f, 0x1c93e0ab, 0x3943ecb6, 0x393e4f23, 0x1c9f1e96, 0x1cc0d1b6, 0x392d692f,
-	0x3927c2c9, 0x1ccc0b35, 0x1cedb106, 0x3916c262, 0x3911132d, 0x1cf8e611, 0x1d1a7e7d, 0x38fff85e,
-	0x38fa405e, 0x1d25af0d, 0x1d473a00, 0x38e90b31, 0x38e34a69, 0x1d52660f, 0x1d73e374, 0x38d1fae9,
-	0x38cc315d, 0x1d7f0afb, 0x1da07abc, 0x38bac795, 0x38b4f547, 0x1dab9db5, 0x1dccffbf, 0x38a37142,
-	0x389d9637, 0x1dd81e21, 0x1df9725f, 0x388bf7ff, 0x3886143b, 0x1e048c24, 0x1e25d282, 0x38745bdb,
-	0x386e6f60, 0x1e30e7a4, 0x1e52200c, 0x385c9ce3, 0x3856a7b6, 0x1e5d3084, 0x1e7e5ae2, 0x3844bb28,
-	0x383ebd4c, 0x1e8966a8, 0x1eaa82e9, 0x382cb6b7, 0x3826b030, 0x1eb589f7, 0x1ed69805, 0x38148f9f,
-	0x380e8071, 0x1ee19a54, 0x1f029a1c, 0x37fc45ef, 0x37f62e1d, 0x1f0d97a5, 0x1f2e8911, 0x37e3d9b7,
-	0x37ddb945, 0x1f3981ce, 0x1f5a64cb, 0x37cb4b04, 0x37c521f6, 0x1f6558b5, 0x1f862d2d, 0x37b299e7,
-	0x37ac6841, 0x1f911c3d, 0x1fb1e21d, 0x3799c66f, 0x37938c34, 0x1fbccc4d, 0x1fdd8381, 0x3780d0aa,
-	0x377a8ddf, 0x1fe868c8, 0x2009113c, 0x3767b8a9, 0x37616d51, 0x2013f196, 0x20348b35, 0x374e7e7b,
-	0x37482a9a, 0x203f6699, 0x205ff14f, 0x3735222f, 0x372ec5c9, 0x206ac7b8, 0x208b4372, 0x371ba3d4,
-	0x37153eee, 0x209614d9, 0x20b68181, 0x3702037c, 0x36fb9618, 0x20c14ddf, 0x20e1ab63, 0x36e84135,
-	0x36e1cb58, 0x20ec72b1, 0x210cc0fc, 0x36ce5d10, 0x36c7debd, 0x21178334, 0x2137c232, 0x36b4571b,
-	0x36add058, 0x21427f4d, 0x2162aeea, 0x369a2f69, 0x3693a038, 0x216d66e2, 0x218d870b, 0x367fe608,
-	0x36794e6e, 0x219839d8, 0x21b84a79, 0x36657b08, 0x365edb09, 0x21c2f815, 0x21e2f91a, 0x364aee7b,
-	0x3644461b, 0x21eda17f, 0x220d92d4, 0x36304070, 0x36298fb4, 0x221835fb, 0x2238178d, 0x361570f8,
-	0x360eb7e3, 0x2242b56f, 0x22628729, 0x35fa8023, 0x35f3beba, 0x226d1fc1, 0x228ce191, 0x35df6e03,
-	0x35d8a449, 0x229774d7, 0x22b726a8, 0x35c43aa7, 0x35bd68a1, 0x22c1b496, 0x22e15655, 0x35a8e621,
-	0x35a20bd3, 0x22ebdee5, 0x230b707e, 0x358d7081, 0x35868def, 0x2315f3a8, 0x23357509, 0x3571d9d9,
-	0x356aef08, 0x233ff2c8, 0x235f63dc, 0x35562239, 0x354f2f2c, 0x2369dc29, 0x23893cdd, 0x353a49b2,
-	0x35334e6f, 0x2393afb2, 0x23b2fff3, 0x351e5056, 0x35174ce0, 0x23bd6d48, 0x23dcad03, 0x35023636,
-	0x34fb2a92, 0x23e714d3, 0x240643f4, 0x34e5fb63, 0x34dee795, 0x2410a639, 0x242fc4ad, 0x34c99fef,
-	0x34c283fb, 0x243a215f, 0x24592f13, 0x34ad23eb, 0x34a5ffd5, 0x2463862c, 0x2482830d, 0x34908768,
-	0x34895b36, 0x248cd487, 0x24abc082, 0x3473ca79, 0x346c962f, 0x24b60c57, 0x24d4e757, 0x3456ed2f,
-	0x344fb0d1, 0x24df2d81, 0x24fdf775, 0x3439ef9c, 0x3432ab2e, 0x250837ed, 0x2526f0c1, 0x341cd1d2,
-	0x34158559, 0x25312b81, 0x254fd323, 0x33ff93e2, 0x33f83f62, 0x255a0823, 0x25789e80, 0x33e235df,
-	0x33dad95e, 0x2582cdbc, 0x25a152c0, 0x33c4b7db, 0x33bd535c, 0x25ab7c30, 0x25c9efca, 0x33a719e8,
-	0x339fad70, 0x25d41369, 0x25f27584, 0x33895c18, 0x3381e7ac, 0x25fc934b, 0x261ae3d6, 0x336b7e7e,
-	0x33640223, 0x2624fbbf, 0x26433aa7, 0x334d812d, 0x3345fce6, 0x264d4cac, 0x266b79dd, 0x332f6435,
-	0x3327d808, 0x267585f8, 0x2693a161, 0x331127ab, 0x3309939c, 0x269da78b, 0x26bbb119, 0x32f2cba1,
-	0x32eb2fb5, 0x26c5b14c, 0x26e3a8ec, 0x32d45029, 0x32ccac64, 0x26eda322, 0x270b88c2, 0x32b5b557,
-	0x32ae09be, 0x27157cf5, 0x27335082, 0x3296fb3d, 0x328f47d5, 0x273d3eac, 0x275b0014, 0x327821ee,
-	0x327066bc, 0x2764e82f, 0x27829760, 0x3259297d, 0x32516686, 0x278c7965, 0x27aa164c, 0x323a11fe,
-	0x32324746, 0x27b3f235, 0x27d17cc1, 0x321adb83, 0x3213090f, 0x27db5288, 0x27f8caa5, 0x31fb8620,
-	0x31f3abf5, 0x28029a45, 0x281fffe2, 0x31dc11e8, 0x31d4300b, 0x2829c954, 0x28471c5e, 0x31bc7eee,
-	0x31b49564, 0x2850df9d, 0x286e2002, 0x319ccd46, 0x3194dc14, 0x2877dd07, 0x28950ab6, 0x317cfd04,
-	0x3175042e, 0x289ec17a, 0x28bbdc61, 0x315d0e3b, 0x31550dc6, 0x28c58cdf, 0x28e294eb, 0x313d00ff,
-	0x3134f8f1, 0x28ec3f1e, 0x2909343e, 0x311cd564, 0x3114c5c0, 0x2912d81f, 0x292fba40, 0x30fc8b7d,
-	0x30f47449, 0x293957c9, 0x295626da, 0x30dc235e, 0x30d404a0, 0x295fbe06, 0x297c79f5, 0x30bb9d1c,
-	0x30b376d8, 0x29860abd, 0x29a2b378, 0x309af8ca, 0x3092cb05, 0x29ac3dd7, 0x29c8d34d, 0x307a367c,
-	0x3072013c, 0x29d2573c, 0x29eed95b, 0x30595648, 0x30511991, 0x29f856d5, 0x2a14c58b, 0x30385840,
-	0x30301418, 0x2a1e3c8a, 0x2a3a97c7, 0x30173c7a, 0x300ef0e5, 0x2a440844, 0x2a604ff5, 0x2ff6030a,
-	0x2fedb00d, 0x2a69b9ec, 0x2a85ee00, 0x2fd4ac04, 0x2fcc51a5, 0x2a8f516b, 0x2aab71d0, 0x2fb3377c,
-	0x2faad5c1, 0x2ab4cea9, 0x2ad0db4e, 0x2f91a589, 0x2f893c75, 0x2ada318e, 0x2af62a63, 0x2f6ff63d,
-	0x2f6785d7, 0x2aff7a05, 0x2b1b5ef8, 0x2f4e29af, 0x2f45b1fb, 0x2b24a7f6, 0x2b4078f5, 0x2f2c3ff2,
-	0x2f23c0f6, 0x2b49bb4a, 0x2b657844, 0x2f0a391d, 0x2f01b2de, 0x2b6eb3ea, 0x2b8a5cce, 0x2ee81543,
-	0x2edf87c6, 0x2b9391c0, 0x2baf267d, 0x2ec5d479, 0x2ebd3fc4, 0x2bb854b4, 0x2bd3d53a, 0x2ea376d6,
-	0x2e9adaee, 0x2bdcfcb0, 0x2bf868ed, 0x2e80fc6e, 0x2e785958, 0x2c01899e, 0x2c1ce181, 0x2e5e6556,
-	0x2e55bb17, 0x2c25fb66, 0x2c413edf, 0x2e3bb1a4, 0x2e330042, 0x2c4a51f3, 0x2c6580f1, 0x2e18e16d,
-	0x2e1028ed, 0x2c6e8d2e, 0x2c89a79f, 0x2df5f4c7, 0x2ded352f, 0x2c92ad01, 0x2cadb2d5, 0x2dd2ebc7,
-	0x2dca251c, 0x2cb6b155, 0x2cd1a27b, 0x2dafc683, 0x2da6f8ca, 0x2cda9a14, 0x2cf5767c, 0x2d8c8510,
-	0x2d83b04f, 0x2cfe6728, 0x2d192ec1, 0x2d692784, 0x2d604bc0, 0x2d22187a, 0x2d3ccb34, 0x2d45adf6
-};
-
-const int twidTab512[8*6 + 32*6 + 128*6] = {
-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3b20d79e, 0x187de2a6,
-	0x3ec52f9f, 0x0c7c5c1e, 0x3536cc52, 0x238e7673, 0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6,
-	0x187de2a6, 0x3b20d79e, 0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 0xf383a3e2, 0x3ec52f9f,
-	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xe7821d5a, 0x3b20d79e,
-	0x238e7673, 0x3536cc52, 0xc13ad061, 0x0c7c5c1e, 0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e,
-	0xc4df2862, 0xe7821d5a, 0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 0xdc71898d, 0xcac933ae,
-
-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3fb11b47, 0x0645e9af,
-	0x3fec43c6, 0x0323ecbe, 0x3f4eaafe, 0x09640837, 0x3ec52f9f, 0x0c7c5c1e, 0x3fb11b47, 0x0645e9af,
-	0x3d3e82ad, 0x1294062e, 0x3d3e82ad, 0x1294062e, 0x3f4eaafe, 0x09640837, 0x39daf5e8, 0x1b5d1009,
-	0x3b20d79e, 0x187de2a6, 0x3ec52f9f, 0x0c7c5c1e, 0x3536cc52, 0x238e7673, 0x387165e3, 0x1e2b5d38,
-	0x3e14fdf7, 0x0f8cfcbd, 0x2f6bbe44, 0x2afad269, 0x3536cc52, 0x238e7673, 0x3d3e82ad, 0x1294062e,
-	0x2899e64a, 0x317900d6, 0x317900d6, 0x2899e64a, 0x3c424209, 0x158f9a75, 0x20e70f32, 0x36e5068a,
-	0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x2899e64a, 0x317900d6,
-	0x39daf5e8, 0x1b5d1009, 0x0f8cfcbd, 0x3e14fdf7, 0x238e7673, 0x3536cc52, 0x387165e3, 0x1e2b5d38,
-	0x0645e9af, 0x3fb11b47, 0x1e2b5d38, 0x387165e3, 0x36e5068a, 0x20e70f32, 0xfcdc1342, 0x3fec43c6,
-	0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 0xf383a3e2, 0x3ec52f9f, 0x1294062e, 0x3d3e82ad,
-	0x3367c08f, 0x261feff9, 0xea70658b, 0x3c424209, 0x0c7c5c1e, 0x3ec52f9f, 0x317900d6, 0x2899e64a,
-	0xe1d4a2c8, 0x387165e3, 0x0645e9af, 0x3fb11b47, 0x2f6bbe44, 0x2afad269, 0xd9e01007, 0x3367c08f,
-	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xf9ba1651, 0x3fb11b47,
-	0x2afad269, 0x2f6bbe44, 0xcc983f71, 0x261feff9, 0xf383a3e2, 0x3ec52f9f, 0x2899e64a, 0x317900d6,
-	0xc78e9a1d, 0x1e2b5d38, 0xed6bf9d2, 0x3d3e82ad, 0x261feff9, 0x3367c08f, 0xc3bdbdf7, 0x158f9a75,
-	0xe7821d5a, 0x3b20d79e, 0x238e7673, 0x3536cc52, 0xc13ad061, 0x0c7c5c1e, 0xe1d4a2c8, 0x387165e3,
-	0x20e70f32, 0x36e5068a, 0xc013bc3a, 0x0323ecbe, 0xdc71898d, 0x3536cc52, 0x1e2b5d38, 0x387165e3,
-	0xc04ee4b9, 0xf9ba1651, 0xd76619b6, 0x317900d6, 0x1b5d1009, 0x39daf5e8, 0xc1eb0209, 0xf0730343,
-	0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 0xce86ff2a, 0x2899e64a,
-	0x158f9a75, 0x3c424209, 0xc91af976, 0xdf18f0ce, 0xcac933ae, 0x238e7673, 0x1294062e, 0x3d3e82ad,
-	0xce86ff2a, 0xd76619b6, 0xc78e9a1d, 0x1e2b5d38, 0x0f8cfcbd, 0x3e14fdf7, 0xd5052d97, 0xd09441bc,
-	0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 0xdc71898d, 0xcac933ae, 0xc2c17d53, 0x1294062e,
-	0x09640837, 0x3f4eaafe, 0xe4a2eff7, 0xc6250a18, 0xc13ad061, 0x0c7c5c1e, 0x0645e9af, 0x3fb11b47,
-	0xed6bf9d2, 0xc2c17d53, 0xc04ee4b9, 0x0645e9af, 0x0323ecbe, 0x3fec43c6, 0xf69bf7c9, 0xc0b15502,
-
-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3ffb10c1, 0x0192155f,
-	0x3ffec42d, 0x00c90e8f, 0x3ff4e5df, 0x025b0cae, 0x3fec43c6, 0x0323ecbe, 0x3ffb10c1, 0x0192155f,
-	0x3fd39b5a, 0x04b54824, 0x3fd39b5a, 0x04b54824, 0x3ff4e5df, 0x025b0cae, 0x3f9c2bfa, 0x070de171,
-	0x3fb11b47, 0x0645e9af, 0x3fec43c6, 0x0323ecbe, 0x3f4eaafe, 0x09640837, 0x3f84c8e1, 0x07d59395,
-	0x3fe12acb, 0x03ecadcf, 0x3eeb3347, 0x0bb6ecef, 0x3f4eaafe, 0x09640837, 0x3fd39b5a, 0x04b54824,
-	0x3e71e758, 0x0e05c135, 0x3f0ec9f4, 0x0af10a22, 0x3fc395f9, 0x057db402, 0x3de2f147, 0x104fb80e,
-	0x3ec52f9f, 0x0c7c5c1e, 0x3fb11b47, 0x0645e9af, 0x3d3e82ad, 0x1294062e, 0x3e71e758, 0x0e05c135,
-	0x3f9c2bfa, 0x070de171, 0x3c84d496, 0x14d1e242, 0x3e14fdf7, 0x0f8cfcbd, 0x3f84c8e1, 0x07d59395,
-	0x3bb6276d, 0x17088530, 0x3dae81ce, 0x1111d262, 0x3f6af2e3, 0x089cf867, 0x3ad2c2e7, 0x19372a63,
-	0x3d3e82ad, 0x1294062e, 0x3f4eaafe, 0x09640837, 0x39daf5e8, 0x1b5d1009, 0x3cc511d8, 0x14135c94,
-	0x3f2ff249, 0x0a2abb58, 0x38cf1669, 0x1d79775b, 0x3c424209, 0x158f9a75, 0x3f0ec9f4, 0x0af10a22,
-	0x37af8158, 0x1f8ba4db, 0x3bb6276d, 0x17088530, 0x3eeb3347, 0x0bb6ecef, 0x367c9a7d, 0x2192e09a,
-	0x3b20d79e, 0x187de2a6, 0x3ec52f9f, 0x0c7c5c1e, 0x3536cc52, 0x238e7673, 0x3a8269a2, 0x19ef7943,
-	0x3e9cc076, 0x0d415012, 0x33de87de, 0x257db64b, 0x39daf5e8, 0x1b5d1009, 0x3e71e758, 0x0e05c135,
-	0x32744493, 0x275ff452, 0x392a9642, 0x1cc66e99, 0x3e44a5ee, 0x0ec9a7f2, 0x30f8801f, 0x29348937,
-	0x387165e3, 0x1e2b5d38, 0x3e14fdf7, 0x0f8cfcbd, 0x2f6bbe44, 0x2afad269, 0x37af8158, 0x1f8ba4db,
-	0x3de2f147, 0x104fb80e, 0x2dce88a9, 0x2cb2324b, 0x36e5068a, 0x20e70f32, 0x3dae81ce, 0x1111d262,
-	0x2c216eaa, 0x2e5a106f, 0x361214b0, 0x223d66a8, 0x3d77b191, 0x11d3443f, 0x2a650525, 0x2ff1d9c6,
-	0x3536cc52, 0x238e7673, 0x3d3e82ad, 0x1294062e, 0x2899e64a, 0x317900d6, 0x34534f40, 0x24da0a99,
-	0x3d02f756, 0x135410c2, 0x26c0b162, 0x32eefde9, 0x3367c08f, 0x261feff9, 0x3cc511d8, 0x14135c94,
-	0x24da0a99, 0x34534f40, 0x32744493, 0x275ff452, 0x3c84d496, 0x14d1e242, 0x22e69ac7, 0x35a5793c,
-	0x317900d6, 0x2899e64a, 0x3c424209, 0x158f9a75, 0x20e70f32, 0x36e5068a, 0x30761c17, 0x29cd9577,
-	0x3bfd5cc4, 0x164c7ddd, 0x1edc1952, 0x3811884c, 0x2f6bbe44, 0x2afad269, 0x3bb6276d, 0x17088530,
-	0x1cc66e99, 0x392a9642, 0x2e5a106f, 0x2c216eaa, 0x3b6ca4c4, 0x17c3a931, 0x1aa6c82b, 0x3a2fcee8,
-	0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x2c216eaa, 0x2e5a106f,
-	0x3ad2c2e7, 0x19372a63, 0x164c7ddd, 0x3bfd5cc4, 0x2afad269, 0x2f6bbe44, 0x3a8269a2, 0x19ef7943,
-	0x14135c94, 0x3cc511d8, 0x29cd9577, 0x30761c17, 0x3a2fcee8, 0x1aa6c82b, 0x11d3443f, 0x3d77b191,
-	0x2899e64a, 0x317900d6, 0x39daf5e8, 0x1b5d1009, 0x0f8cfcbd, 0x3e14fdf7, 0x275ff452, 0x32744493,
-	0x3983e1e7, 0x1c1249d8, 0x0d415012, 0x3e9cc076, 0x261feff9, 0x3367c08f, 0x392a9642, 0x1cc66e99,
-	0x0af10a22, 0x3f0ec9f4, 0x24da0a99, 0x34534f40, 0x38cf1669, 0x1d79775b, 0x089cf867, 0x3f6af2e3,
-	0x238e7673, 0x3536cc52, 0x387165e3, 0x1e2b5d38, 0x0645e9af, 0x3fb11b47, 0x223d66a8, 0x361214b0,
-	0x3811884c, 0x1edc1952, 0x03ecadcf, 0x3fe12acb, 0x20e70f32, 0x36e5068a, 0x37af8158, 0x1f8ba4db,
-	0x0192155f, 0x3ffb10c1, 0x1f8ba4db, 0x37af8158, 0x374b54ce, 0x2039f90e, 0xff36f171, 0x3ffec42d,
-	0x1e2b5d38, 0x387165e3, 0x36e5068a, 0x20e70f32, 0xfcdc1342, 0x3fec43c6, 0x1cc66e99, 0x392a9642,
-	0x367c9a7d, 0x2192e09a, 0xfa824bfe, 0x3fc395f9, 0x1b5d1009, 0x39daf5e8, 0x361214b0, 0x223d66a8,
-	0xf82a6c6b, 0x3f84c8e1, 0x19ef7943, 0x3a8269a2, 0x35a5793c, 0x22e69ac7, 0xf5d544a8, 0x3f2ff249,
-	0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673, 0xf383a3e2, 0x3ec52f9f, 0x17088530, 0x3bb6276d,
-	0x34c61236, 0x2434f332, 0xf136580e, 0x3e44a5ee, 0x158f9a75, 0x3c424209, 0x34534f40, 0x24da0a99,
-	0xeeee2d9e, 0x3dae81ce, 0x14135c94, 0x3cc511d8, 0x33de87de, 0x257db64b, 0xecabef3e, 0x3d02f756,
-	0x1294062e, 0x3d3e82ad, 0x3367c08f, 0x261feff9, 0xea70658b, 0x3c424209, 0x1111d262, 0x3dae81ce,
-	0x32eefde9, 0x26c0b162, 0xe83c56cf, 0x3b6ca4c4, 0x0f8cfcbd, 0x3e14fdf7, 0x32744493, 0x275ff452,
-	0xe61086bd, 0x3a8269a2, 0x0e05c135, 0x3e71e758, 0x31f79947, 0x27fdb2a6, 0xe3edb628, 0x3983e1e7,
-	0x0c7c5c1e, 0x3ec52f9f, 0x317900d6, 0x2899e64a, 0xe1d4a2c8, 0x387165e3, 0x0af10a22, 0x3f0ec9f4,
-	0x30f8801f, 0x29348937, 0xdfc606f2, 0x374b54ce, 0x09640837, 0x3f4eaafe, 0x30761c17, 0x29cd9577,
-	0xddc29958, 0x361214b0, 0x07d59395, 0x3f84c8e1, 0x2ff1d9c6, 0x2a650525, 0xdbcb0cce, 0x34c61236,
-	0x0645e9af, 0x3fb11b47, 0x2f6bbe44, 0x2afad269, 0xd9e01007, 0x3367c08f, 0x04b54824, 0x3fd39b5a,
-	0x2ee3cebe, 0x2b8ef77c, 0xd8024d5a, 0x31f79947, 0x0323ecbe, 0x3fec43c6, 0x2e5a106f, 0x2c216eaa,
-	0xd6326a89, 0x30761c17, 0x0192155f, 0x3ffb10c1, 0x2dce88a9, 0x2cb2324b, 0xd4710884, 0x2ee3cebe,
-	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xfe6deaa1, 0x3ffb10c1,
-	0x2cb2324b, 0x2dce88a9, 0xd11c3142, 0x2b8ef77c, 0xfcdc1342, 0x3fec43c6, 0x2c216eaa, 0x2e5a106f,
-	0xcf89e3e9, 0x29cd9577, 0xfb4ab7dc, 0x3fd39b5a, 0x2b8ef77c, 0x2ee3cebe, 0xce0866b9, 0x27fdb2a6,
-	0xf9ba1651, 0x3fb11b47, 0x2afad269, 0x2f6bbe44, 0xcc983f71, 0x261feff9, 0xf82a6c6b, 0x3f84c8e1,
-	0x2a650525, 0x2ff1d9c6, 0xcb39edca, 0x2434f332, 0xf69bf7c9, 0x3f4eaafe, 0x29cd9577, 0x30761c17,
-	0xc9edeb50, 0x223d66a8, 0xf50ef5de, 0x3f0ec9f4, 0x29348937, 0x30f8801f, 0xc8b4ab32, 0x2039f90e,
-	0xf383a3e2, 0x3ec52f9f, 0x2899e64a, 0x317900d6, 0xc78e9a1d, 0x1e2b5d38, 0xf1fa3ecb, 0x3e71e758,
-	0x27fdb2a6, 0x31f79947, 0xc67c1e19, 0x1c1249d8, 0xf0730343, 0x3e14fdf7, 0x275ff452, 0x32744493,
-	0xc57d965e, 0x19ef7943, 0xeeee2d9e, 0x3dae81ce, 0x26c0b162, 0x32eefde9, 0xc4935b3c, 0x17c3a931,
-	0xed6bf9d2, 0x3d3e82ad, 0x261feff9, 0x3367c08f, 0xc3bdbdf7, 0x158f9a75, 0xebeca36c, 0x3cc511d8,
-	0x257db64b, 0x33de87de, 0xc2fd08aa, 0x135410c2, 0xea70658b, 0x3c424209, 0x24da0a99, 0x34534f40,
-	0xc2517e32, 0x1111d262, 0xe8f77ad0, 0x3bb6276d, 0x2434f332, 0x34c61236, 0xc1bb5a12, 0x0ec9a7f2,
-	0xe7821d5a, 0x3b20d79e, 0x238e7673, 0x3536cc52, 0xc13ad061, 0x0c7c5c1e, 0xe61086bd, 0x3a8269a2,
-	0x22e69ac7, 0x35a5793c, 0xc0d00db7, 0x0a2abb58, 0xe4a2eff7, 0x39daf5e8, 0x223d66a8, 0x361214b0,
-	0xc07b371f, 0x07d59395, 0xe3399167, 0x392a9642, 0x2192e09a, 0x367c9a7d, 0xc03c6a07, 0x057db402,
-	0xe1d4a2c8, 0x387165e3, 0x20e70f32, 0x36e5068a, 0xc013bc3a, 0x0323ecbe, 0xe0745b25, 0x37af8158,
-	0x2039f90e, 0x374b54ce, 0xc0013bd3, 0x00c90e8f, 0xdf18f0ce, 0x36e5068a, 0x1f8ba4db, 0x37af8158,
-	0xc004ef3f, 0xfe6deaa1, 0xddc29958, 0x361214b0, 0x1edc1952, 0x3811884c, 0xc01ed535, 0xfc135231,
-	0xdc71898d, 0x3536cc52, 0x1e2b5d38, 0x387165e3, 0xc04ee4b9, 0xf9ba1651, 0xdb25f567, 0x34534f40,
-	0x1d79775b, 0x38cf1669, 0xc0950d1d, 0xf7630799, 0xd9e01007, 0x3367c08f, 0x1cc66e99, 0x392a9642,
-	0xc0f1360c, 0xf50ef5de, 0xd8a00bae, 0x32744493, 0x1c1249d8, 0x3983e1e7, 0xc1633f8a, 0xf2beafee,
-	0xd76619b6, 0x317900d6, 0x1b5d1009, 0x39daf5e8, 0xc1eb0209, 0xf0730343, 0xd6326a89, 0x30761c17,
-	0x1aa6c82b, 0x3a2fcee8, 0xc2884e6f, 0xee2cbbc1, 0xd5052d97, 0x2f6bbe44, 0x19ef7943, 0x3a8269a2,
-	0xc33aee28, 0xebeca36c, 0xd3de9156, 0x2e5a106f, 0x19372a63, 0x3ad2c2e7, 0xc402a33c, 0xe9b38223,
-	0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 0xd1a5ef91, 0x2c216eaa,
-	0x17c3a931, 0x3b6ca4c4, 0xc5d03118, 0xe55937d5, 0xd09441bc, 0x2afad269, 0x17088530, 0x3bb6276d,
-	0xc6d569be, 0xe3399167, 0xcf89e3e9, 0x29cd9577, 0x164c7ddd, 0x3bfd5cc4, 0xc7ee77b4, 0xe123e6ae,
-	0xce86ff2a, 0x2899e64a, 0x158f9a75, 0x3c424209, 0xc91af976, 0xdf18f0ce, 0xcd8bbb6d, 0x275ff452,
-	0x14d1e242, 0x3c84d496, 0xca5a86c4, 0xdd196539, 0xcc983f71, 0x261feff9, 0x14135c94, 0x3cc511d8,
-	0xcbacb0c0, 0xdb25f567, 0xcbacb0c0, 0x24da0a99, 0x135410c2, 0x3d02f756, 0xcd110217, 0xd93f4e9e,
-	0xcac933ae, 0x238e7673, 0x1294062e, 0x3d3e82ad, 0xce86ff2a, 0xd76619b6, 0xc9edeb50, 0x223d66a8,
-	0x11d3443f, 0x3d77b191, 0xd00e263a, 0xd59afadb, 0xc91af976, 0x20e70f32, 0x1111d262, 0x3dae81ce,
-	0xd1a5ef91, 0xd3de9156, 0xc8507ea8, 0x1f8ba4db, 0x104fb80e, 0x3de2f147, 0xd34dcdb5, 0xd2317757,
-	0xc78e9a1d, 0x1e2b5d38, 0x0f8cfcbd, 0x3e14fdf7, 0xd5052d97, 0xd09441bc, 0xc6d569be, 0x1cc66e99,
-	0x0ec9a7f2, 0x3e44a5ee, 0xd6cb76c9, 0xcf077fe1, 0xc6250a18, 0x1b5d1009, 0x0e05c135, 0x3e71e758,
-	0xd8a00bae, 0xcd8bbb6d, 0xc57d965e, 0x19ef7943, 0x0d415012, 0x3e9cc076, 0xda8249b5, 0xcc217822,
-	0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f, 0xdc71898d, 0xcac933ae, 0xc449d893, 0x17088530,
-	0x0bb6ecef, 0x3eeb3347, 0xde6d1f66, 0xc9836583, 0xc3bdbdf7, 0x158f9a75, 0x0af10a22, 0x3f0ec9f4,
-	0xe0745b25, 0xc8507ea8, 0xc33aee28, 0x14135c94, 0x0a2abb58, 0x3f2ff249, 0xe28688a5, 0xc730e997,
-	0xc2c17d53, 0x1294062e, 0x09640837, 0x3f4eaafe, 0xe4a2eff7, 0xc6250a18, 0xc2517e32, 0x1111d262,
-	0x089cf867, 0x3f6af2e3, 0xe6c8d59d, 0xc52d3d19, 0xc1eb0209, 0x0f8cfcbd, 0x07d59395, 0x3f84c8e1,
-	0xe8f77ad0, 0xc449d893, 0xc18e18a8, 0x0e05c135, 0x070de171, 0x3f9c2bfa, 0xeb2e1dbe, 0xc37b2b6a,
-	0xc13ad061, 0x0c7c5c1e, 0x0645e9af, 0x3fb11b47, 0xed6bf9d2, 0xc2c17d53, 0xc0f1360c, 0x0af10a22,
-	0x057db402, 0x3fc395f9, 0xefb047f2, 0xc21d0eb9, 0xc0b15502, 0x09640837, 0x04b54824, 0x3fd39b5a,
-	0xf1fa3ecb, 0xc18e18a8, 0xc07b371f, 0x07d59395, 0x03ecadcf, 0x3fe12acb, 0xf4491311, 0xc114ccb9,
-	0xc04ee4b9, 0x0645e9af, 0x0323ecbe, 0x3fec43c6, 0xf69bf7c9, 0xc0b15502, 0xc02c64a6, 0x04b54824,
-	0x025b0cae, 0x3ff4e5df, 0xf8f21e8f, 0xc063d406, 0xc013bc3a, 0x0323ecbe, 0x0192155f, 0x3ffb10c1,
-	0xfb4ab7dc, 0xc02c64a6, 0xc004ef3f, 0x0192155f, 0x00c90e8f, 0x3ffec42d, 0xfda4f352, 0xc00b1a21
-};
-
-const int twidTab64[4*6 + 16*6] = {
-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x2d413ccc, 0x2d413ccc,
-	0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc,
-	0xd2bec334, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a,
-
-	0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x40000000, 0x00000000, 0x3ec52f9f, 0x0c7c5c1e,
-	0x3fb11b47, 0x0645e9af, 0x3d3e82ad, 0x1294062e, 0x3b20d79e, 0x187de2a6, 0x3ec52f9f, 0x0c7c5c1e,
-	0x3536cc52, 0x238e7673, 0x3536cc52, 0x238e7673, 0x3d3e82ad, 0x1294062e, 0x2899e64a, 0x317900d6,
-	0x2d413ccc, 0x2d413ccc, 0x3b20d79e, 0x187de2a6, 0x187de2a6, 0x3b20d79e, 0x238e7673, 0x3536cc52,
-	0x387165e3, 0x1e2b5d38, 0x0645e9af, 0x3fb11b47, 0x187de2a6, 0x3b20d79e, 0x3536cc52, 0x238e7673,
-	0xf383a3e2, 0x3ec52f9f, 0x0c7c5c1e, 0x3ec52f9f, 0x317900d6, 0x2899e64a, 0xe1d4a2c8, 0x387165e3,
-	0x00000000, 0x40000000, 0x2d413ccc, 0x2d413ccc, 0xd2bec334, 0x2d413ccc, 0xf383a3e2, 0x3ec52f9f,
-	0x2899e64a, 0x317900d6, 0xc78e9a1d, 0x1e2b5d38, 0xe7821d5a, 0x3b20d79e, 0x238e7673, 0x3536cc52,
-	0xc13ad061, 0x0c7c5c1e, 0xdc71898d, 0x3536cc52, 0x1e2b5d38, 0x387165e3, 0xc04ee4b9, 0xf9ba1651,
-	0xd2bec334, 0x2d413ccc, 0x187de2a6, 0x3b20d79e, 0xc4df2862, 0xe7821d5a, 0xcac933ae, 0x238e7673,
-	0x1294062e, 0x3d3e82ad, 0xce86ff2a, 0xd76619b6, 0xc4df2862, 0x187de2a6, 0x0c7c5c1e, 0x3ec52f9f,
-	0xdc71898d, 0xcac933ae, 0xc13ad061, 0x0c7c5c1e, 0x0645e9af, 0x3fb11b47, 0xed6bf9d2, 0xc2c17d53
-};
-#endif  //ARMV5E
-
-const int ShortWindowSine[FRAME_LEN_SHORT/2] ={
-	0x00c97fff, 0x025b7ffa, 0x03ed7ff1, 0x057f7fe2, 0x07117fce, 0x08a27fb5, 0x0a337f98, 0x0bc47f75,
-	0x0d547f4e, 0x0ee47f22, 0x10737ef0, 0x12017eba, 0x138f7e7f, 0x151c7e3f, 0x16a87dfb, 0x18337db1,
-	0x19be7d63, 0x1b477d0f, 0x1cd07cb7, 0x1e577c5a, 0x1fdd7bf9, 0x21627b92, 0x22e57b27, 0x24677ab7,
-	0x25e87a42, 0x276879c9, 0x28e5794a, 0x2a6278c8, 0x2bdc7840, 0x2d5577b4, 0x2ecc7723, 0x3042768e,
-	0x31b575f4, 0x33277556, 0x349774b3, 0x3604740b, 0x3770735f, 0x38d972af, 0x3a4071fa, 0x3ba57141,
-	0x3d087083, 0x3e686fc2, 0x3fc66efb, 0x41216e31, 0x427a6d62, 0x43d16c8f, 0x45246bb8, 0x46756add,
-	0x47c469fd, 0x490f691a, 0x4a586832, 0x4b9e6747, 0x4ce16657, 0x4e216564, 0x4f5e646c, 0x50986371,
-	0x51cf6272, 0x5303616f, 0x54336068, 0x55605f5e, 0x568a5e50, 0x57b15d3e, 0x58d45c29, 0x59f45b10
-};
-
-const int LongWindowKBD[FRAME_LEN_LONG/2]={
-	0x000a7fff, 0x000e7fff, 0x00127fff, 0x00157fff, 0x00197fff, 0x001c7fff, 0x00207fff, 0x00237fff,
-	0x00267fff, 0x002a7fff, 0x002d7fff, 0x00307fff, 0x00347fff, 0x00387fff, 0x003b7fff, 0x003f7fff,
-	0x00437fff, 0x00477fff, 0x004b7fff, 0x004f7fff, 0x00537fff, 0x00577fff, 0x005b7fff, 0x00607fff,
-	0x00647fff, 0x00697fff, 0x006d7fff, 0x00727fff, 0x00777fff, 0x007c7fff, 0x00817fff, 0x00867fff,
-	0x008b7fff, 0x00917fff, 0x00967fff, 0x009c7fff, 0x00a17fff, 0x00a77fff, 0x00ad7fff, 0x00b37fff,
-	0x00b97fff, 0x00bf7fff, 0x00c67fff, 0x00cc7fff, 0x00d37fff, 0x00da7fff, 0x00e07fff, 0x00e77fff,
-	0x00ee7fff, 0x00f57fff, 0x00fd7fff, 0x01047fff, 0x010c7fff, 0x01137fff, 0x011b7fff, 0x01237fff,
-	0x012b7fff, 0x01337fff, 0x013c7ffe, 0x01447ffe, 0x014d7ffe, 0x01567ffe, 0x015f7ffe, 0x01687ffe,
-	0x01717ffe, 0x017a7ffe, 0x01837ffe, 0x018d7ffe, 0x01977ffd, 0x01a17ffd, 0x01ab7ffd, 0x01b57ffd,
-	0x01bf7ffd, 0x01ca7ffd, 0x01d47ffd, 0x01df7ffc, 0x01ea7ffc, 0x01f57ffc, 0x02007ffc, 0x020c7ffc,
-	0x02177ffc, 0x02237ffb, 0x022f7ffb, 0x023b7ffb, 0x02477ffb, 0x02537ffb, 0x02607ffa, 0x026d7ffa,
-	0x027a7ffa, 0x02877ffa, 0x02947ff9, 0x02a17ff9, 0x02af7ff9, 0x02bc7ff9, 0x02ca7ff8, 0x02d87ff8,
-	0x02e77ff8, 0x02f57ff7, 0x03047ff7, 0x03127ff7, 0x03217ff6, 0x03317ff6, 0x03407ff5, 0x034f7ff5,
-	0x035f7ff5, 0x036f7ff4, 0x037f7ff4, 0x038f7ff3, 0x03a07ff3, 0x03b07ff2, 0x03c17ff2, 0x03d27ff1,
-	0x03e37ff1, 0x03f57ff0, 0x04067ff0, 0x04187fef, 0x042a7fef, 0x043c7fee, 0x044f7fed, 0x04617fed,
-	0x04747fec, 0x04877feb, 0x049a7feb, 0x04ae7fea, 0x04c17fe9, 0x04d57fe9, 0x04e97fe8, 0x04fd7fe7,
-	0x05127fe6, 0x05277fe5, 0x053b7fe5, 0x05507fe4, 0x05667fe3, 0x057b7fe2, 0x05917fe1, 0x05a77fe0,
-	0x05bd7fdf, 0x05d37fde, 0x05ea7fdd, 0x06017fdc, 0x06187fdb, 0x062f7fda, 0x06467fd9, 0x065e7fd7,
-	0x06767fd6, 0x068e7fd5, 0x06a67fd4, 0x06bf7fd2, 0x06d87fd1, 0x06f17fd0, 0x070a7fce, 0x07237fcd,
-	0x073d7fcc, 0x07577fca, 0x07717fc9, 0x078c7fc7, 0x07a67fc5, 0x07c17fc4, 0x07dc7fc2, 0x07f77fc0,
-	0x08137fbf, 0x082f7fbd, 0x084b7fbb, 0x08677fb9, 0x08847fb7, 0x08a07fb6, 0x08bd7fb4, 0x08da7fb2,
-	0x08f87faf, 0x09167fad, 0x09347fab, 0x09527fa9, 0x09707fa7, 0x098f7fa5, 0x09ae7fa2, 0x09cd7fa0,
-	0x09ec7f9d, 0x0a0c7f9b, 0x0a2c7f98, 0x0a4c7f96, 0x0a6c7f93, 0x0a8d7f91, 0x0aae7f8e, 0x0acf7f8b,
-	0x0af07f88, 0x0b127f85, 0x0b337f82, 0x0b557f7f, 0x0b787f7c, 0x0b9a7f79, 0x0bbd7f76, 0x0be07f73,
-	0x0c047f6f, 0x0c277f6c, 0x0c4b7f69, 0x0c6f7f65, 0x0c937f61, 0x0cb87f5e, 0x0cdd7f5a, 0x0d027f56,
-	0x0d277f53, 0x0d4d7f4f, 0x0d737f4b, 0x0d997f47, 0x0dbf7f43, 0x0de67f3e, 0x0e0c7f3a, 0x0e347f36,
-	0x0e5b7f31, 0x0e837f2d, 0x0eaa7f28, 0x0ed37f24, 0x0efb7f1f, 0x0f237f1a, 0x0f4c7f15, 0x0f757f10,
-	0x0f9f7f0b, 0x0fc87f06, 0x0ff27f01, 0x101c7efb, 0x10477ef6, 0x10717ef0, 0x109c7eeb, 0x10c87ee5,
-	0x10f37edf, 0x111f7eda, 0x114a7ed4, 0x11777ece, 0x11a37ec7, 0x11d07ec1, 0x11fd7ebb, 0x122a7eb4,
-	0x12577eae, 0x12857ea7, 0x12b37ea0, 0x12e17e9a, 0x130f7e93, 0x133e7e8c, 0x136d7e84, 0x139c7e7d,
-	0x13cc7e76, 0x13fb7e6e, 0x142b7e67, 0x145b7e5f, 0x148c7e57, 0x14bc7e4f, 0x14ed7e47, 0x151e7e3f,
-	0x15507e37, 0x15817e2e, 0x15b37e26, 0x15e57e1d, 0x16187e14, 0x164a7e0b, 0x167d7e02, 0x16b07df9,
-	0x16e47df0, 0x17177de6, 0x174b7ddd, 0x177f7dd3, 0x17b37dc9, 0x17e87dbf, 0x181d7db5, 0x18527dab,
-	0x18877da1, 0x18bc7d96, 0x18f27d8c, 0x19287d81, 0x195e7d76, 0x19957d6b, 0x19cb7d60, 0x1a027d54,
-	0x1a397d49, 0x1a717d3d, 0x1aa87d31, 0x1ae07d26, 0x1b187d19, 0x1b507d0d, 0x1b897d01, 0x1bc27cf4,
-	0x1bfb7ce8, 0x1c347cdb, 0x1c6d7cce, 0x1ca77cc1, 0x1ce17cb3, 0x1d1b7ca6, 0x1d557c98, 0x1d8f7c8a,
-	0x1dca7c7c, 0x1e057c6e, 0x1e407c60, 0x1e7b7c51, 0x1eb77c43, 0x1ef37c34, 0x1f2f7c25, 0x1f6b7c16,
-	0x1fa77c06, 0x1fe47bf7, 0x20217be7, 0x205e7bd7, 0x209b7bc7, 0x20d87bb7, 0x21167ba6, 0x21547b96,
-	0x21927b85, 0x21d07b74, 0x220e7b63, 0x224d7b52, 0x228c7b40, 0x22cb7b2e, 0x230a7b1c, 0x23497b0a,
-	0x23897af8, 0x23c87ae6, 0x24087ad3, 0x24487ac0, 0x24897aad, 0x24c97a9a, 0x250a7a86, 0x254b7a73,
-	0x258c7a5f, 0x25cd7a4b, 0x260e7a36, 0x26507a22, 0x26917a0d, 0x26d379f8, 0x271579e3, 0x275779ce,
-	0x279a79b8, 0x27dc79a3, 0x281f798d, 0x28627977, 0x28a57960, 0x28e8794a, 0x292b7933, 0x296f791c,
-	0x29b27905, 0x29f678ed, 0x2a3a78d6, 0x2a7e78be, 0x2ac278a6, 0x2b07788d, 0x2b4b7875, 0x2b90785c,
-	0x2bd47843, 0x2c19782a, 0x2c5e7810, 0x2ca477f7, 0x2ce977dd, 0x2d2e77c3, 0x2d7477a8, 0x2dba778e,
-	0x2dff7773, 0x2e457758, 0x2e8b773d, 0x2ed27721, 0x2f187706, 0x2f5e76ea, 0x2fa576cd, 0x2fec76b1,
-	0x30327694, 0x30797677, 0x30c0765a, 0x3107763d, 0x314e761f, 0x31967601, 0x31dd75e3, 0x322575c5,
-	0x326c75a6, 0x32b47588, 0x32fc7569, 0x33447549, 0x338c752a, 0x33d4750a, 0x341c74ea, 0x346474ca,
-	0x34ac74a9, 0x34f57488, 0x353d7467, 0x35857446, 0x35ce7424, 0x36177403, 0x365f73e1, 0x36a873be,
-	0x36f1739c, 0x373a7379, 0x37837356, 0x37cc7333, 0x3815730f, 0x385e72ec, 0x38a772c8, 0x38f172a3,
-	0x393a727f, 0x3983725a, 0x39cd7235, 0x3a167210, 0x3a6071ea, 0x3aa971c4, 0x3af3719e, 0x3b3c7178,
-	0x3b867151, 0x3bd0712b, 0x3c197104, 0x3c6370dc, 0x3cad70b5, 0x3cf7708d, 0x3d407065, 0x3d8a703c,
-	0x3dd47014, 0x3e1e6feb, 0x3e686fc2, 0x3eb16f98, 0x3efb6f6f, 0x3f456f45, 0x3f8f6f1b, 0x3fd96ef0,
-	0x40236ec6, 0x406d6e9b, 0x40b66e70, 0x41006e44, 0x414a6e19, 0x41946ded, 0x41de6dc1, 0x42286d94,
-	0x42716d68, 0x42bb6d3b, 0x43056d0d, 0x434f6ce0, 0x43986cb2, 0x43e26c84, 0x442c6c56, 0x44756c28,
-	0x44bf6bf9, 0x45086bca, 0x45526b9b, 0x459b6b6b, 0x45e56b3c, 0x462e6b0c, 0x46786adb, 0x46c16aab,
-	0x470a6a7a, 0x47536a49, 0x479c6a18, 0x47e569e7, 0x482e69b5, 0x48776983, 0x48c06951, 0x4909691e,
-	0x495268ec, 0x499b68b9, 0x49e36885, 0x4a2c6852, 0x4a74681e, 0x4abd67ea, 0x4b0567b6, 0x4b4d6782,
-	0x4b95674d, 0x4bde6718, 0x4c2666e3, 0x4c6d66ae, 0x4cb56678, 0x4cfd6642, 0x4d45660c, 0x4d8c65d6,
-	0x4dd4659f, 0x4e1b6568, 0x4e626531, 0x4ea964fa, 0x4ef064c3, 0x4f37648b, 0x4f7e6453, 0x4fc5641b,
-	0x500b63e2, 0x505263aa, 0x50986371, 0x50df6338, 0x512562fe, 0x516b62c5, 0x51b1628b, 0x51f66251,
-	0x523c6217, 0x528161dc, 0x52c761a2, 0x530c6167, 0x5351612c, 0x539660f1, 0x53db60b5, 0x54206079,
-	0x5464603d, 0x54a96001, 0x54ed5fc5, 0x55315f88, 0x55755f4b, 0x55b95f0e, 0x55fc5ed1, 0x56405e94,
-	0x56835e56, 0x56c75e18, 0x570a5dda, 0x574d5d9c, 0x578f5d5e, 0x57d25d1f, 0x58145ce0, 0x58565ca1,
-	0x58995c62, 0x58da5c23, 0x591c5be3, 0x595e5ba4, 0x599f5b64, 0x59e05b24, 0x5a215ae3, 0x5a625aa3
-};
-
-
-/*
-  form factor
-*/
-/* sqrt(((i+(1<<(FF_SQRT_BITS-2)+0.5)/2^31) */
-const Word32 formfac_sqrttable[96] = {
-  0x000407f8, 0x000417b9, 0x0004273f, 0x0004368c, 0x000445a1, 0x00045483, 0x00046332, 0x000471b0,
-  0x00048000, 0x00048e22, 0x00049c1a, 0x0004a9e7, 0x0004b78c, 0x0004c50a, 0x0004d263, 0x0004df96,
-  0x0004eca7, 0x0004f995, 0x00050662, 0x0005130e, 0x00051f9c, 0x00052c0a, 0x0005385b, 0x00054490,
-  0x000550a8, 0x00055ca5, 0x00056888, 0x00057450, 0x00058000, 0x00058b96, 0x00059715, 0x0005a27c,
-  0x0005adcc, 0x0005b906, 0x0005c42b, 0x0005cf39, 0x0005da33, 0x0005e519, 0x0005efea, 0x0005faa8,
-  0x00060552, 0x00060fea, 0x00061a70, 0x000624e3, 0x00062f45, 0x00063996, 0x000643d5, 0x00064e04,
-  0x00065823, 0x00066231, 0x00066c30, 0x0006761f, 0x00068000, 0x000689d1, 0x00069393, 0x00069d47,
-  0x0006a6ed, 0x0006b085, 0x0006ba10, 0x0006c38d, 0x0006ccfc, 0x0006d65f, 0x0006dfb5, 0x0006e8fe,
-  0x0006f23b, 0x0006fb6c, 0x00070490, 0x00070da9, 0x000716b6, 0x00071fb8, 0x000728ae, 0x00073199,
-  0x00073a79, 0x0007434e, 0x00074c19, 0x000754d9, 0x00075d8e, 0x0007663a, 0x00076edb, 0x00077772,
-  0x00078000, 0x00078883, 0x000790fd, 0x0007996e, 0x0007a1d5, 0x0007aa33, 0x0007b288, 0x0007bad4,
-  0x0007c318, 0x0007cb52, 0x0007d384, 0x0007dbad, 0x0007e3ce, 0x0007ebe6, 0x0007f3f6, 0x0007fbfe
-};
-
-
-
-/*!
-  \name    quantizer and inverse quantizer tables
-
-  \brief   these tables are used for the non
-           linear quantizer and inverse quantizer
-
-*/
-const Word32 mTab_3_4[512] = {
-	0x4c1bf829, 0x4c3880de, 0x4c550603, 0x4c71879c,
-	0x4c8e05aa, 0x4caa8030, 0x4cc6f72f, 0x4ce36aab,
-	0x4cffdaa4, 0x4d1c471d, 0x4d38b019, 0x4d55159a,
-	0x4d7177a1, 0x4d8dd631, 0x4daa314b, 0x4dc688f3,
-	0x4de2dd2a, 0x4dff2df2, 0x4e1b7b4d, 0x4e37c53d,
-	0x4e540bc5, 0x4e704ee6, 0x4e8c8ea3, 0x4ea8cafd,
-	0x4ec503f7, 0x4ee13992, 0x4efd6bd0, 0x4f199ab4,
-	0x4f35c640, 0x4f51ee75, 0x4f6e1356, 0x4f8a34e4,
-	0x4fa65321, 0x4fc26e10, 0x4fde85b2, 0x4ffa9a0a,
-	0x5016ab18, 0x5032b8e0, 0x504ec362, 0x506acaa1,
-	0x5086cea0, 0x50a2cf5e, 0x50becce0, 0x50dac725,
-	0x50f6be31, 0x5112b205, 0x512ea2a3, 0x514a900d,
-	0x51667a45, 0x5182614c, 0x519e4524, 0x51ba25cf,
-	0x51d60350, 0x51f1dda7, 0x520db4d6, 0x522988e0,
-	0x524559c6, 0x52612789, 0x527cf22d, 0x5298b9b1,
-	0x52b47e19, 0x52d03f65, 0x52ebfd98, 0x5307b8b4,
-	0x532370b9, 0x533f25aa, 0x535ad789, 0x53768656,
-	0x53923215, 0x53addac6, 0x53c9806b, 0x53e52306,
-	0x5400c298, 0x541c5f24, 0x5437f8ab, 0x54538f2e,
-	0x546f22af, 0x548ab330, 0x54a640b3, 0x54c1cb38,
-	0x54dd52c2, 0x54f8d753, 0x551458eb, 0x552fd78d,
-	0x554b5339, 0x5566cbf3, 0x558241bb, 0x559db492,
-	0x55b9247b, 0x55d49177, 0x55effb87, 0x560b62ad,
-	0x5626c6eb, 0x56422842, 0x565d86b4, 0x5678e242,
-	0x56943aee, 0x56af90b9, 0x56cae3a4, 0x56e633b2,
-	0x570180e4, 0x571ccb3b, 0x573812b8, 0x5753575e,
-	0x576e992e, 0x5789d829, 0x57a51450, 0x57c04da6,
-	0x57db842b, 0x57f6b7e1, 0x5811e8c9, 0x582d16e6,
-	0x58484238, 0x58636ac0, 0x587e9081, 0x5899b37c,
-	0x58b4d3b1, 0x58cff123, 0x58eb0bd3, 0x590623c2,
-	0x592138f2, 0x593c4b63, 0x59575b19, 0x59726812,
-	0x598d7253, 0x59a879da, 0x59c37eab, 0x59de80c6,
-	0x59f9802d, 0x5a147ce0, 0x5a2f76e2, 0x5a4a6e34,
-	0x5a6562d6, 0x5a8054cb, 0x5a9b4414, 0x5ab630b2,
-	0x5ad11aa6, 0x5aec01f1, 0x5b06e696, 0x5b21c895,
-	0x5b3ca7ef, 0x5b5784a6, 0x5b725ebc, 0x5b8d3631,
-	0x5ba80b06, 0x5bc2dd3e, 0x5bddacd9, 0x5bf879d8,
-	0x5c13443d, 0x5c2e0c09, 0x5c48d13e, 0x5c6393dc,
-	0x5c7e53e5, 0x5c99115a, 0x5cb3cc3c, 0x5cce848d,
-	0x5ce93a4e, 0x5d03ed80, 0x5d1e9e24, 0x5d394c3b,
-	0x5d53f7c7, 0x5d6ea0c9, 0x5d894742, 0x5da3eb33,
-	0x5dbe8c9e, 0x5dd92b84, 0x5df3c7e5, 0x5e0e61c3,
-	0x5e28f920, 0x5e438dfc, 0x5e5e2059, 0x5e78b037,
-	0x5e933d99, 0x5eadc87e, 0x5ec850e9, 0x5ee2d6da,
-	0x5efd5a53, 0x5f17db54, 0x5f3259e0, 0x5f4cd5f6,
-	0x5f674f99, 0x5f81c6c8, 0x5f9c3b87, 0x5fb6add4,
-	0x5fd11db3, 0x5feb8b23, 0x6005f626, 0x60205ebd,
-	0x603ac4e9, 0x605528ac, 0x606f8a05, 0x6089e8f7,
-	0x60a44583, 0x60be9fa9, 0x60d8f76b, 0x60f34cca,
-	0x610d9fc7, 0x6127f062, 0x61423e9e, 0x615c8a7a,
-	0x6176d3f9, 0x61911b1b, 0x61ab5fe1, 0x61c5a24d,
-	0x61dfe25f, 0x61fa2018, 0x62145b7a, 0x622e9485,
-	0x6248cb3b, 0x6262ff9d, 0x627d31ab, 0x62976167,
-	0x62b18ed1, 0x62cbb9eb, 0x62e5e2b6, 0x63000933,
-	0x631a2d62, 0x63344f45, 0x634e6edd, 0x63688c2b,
-	0x6382a730, 0x639cbfec, 0x63b6d661, 0x63d0ea90,
-	0x63eafc7a, 0x64050c1f, 0x641f1982, 0x643924a2,
-	0x64532d80, 0x646d341f, 0x6487387e, 0x64a13a9e,
-	0x64bb3a81, 0x64d53828, 0x64ef3393, 0x65092cc4,
-	0x652323bb, 0x653d1879, 0x65570b00, 0x6570fb50,
-	0x658ae96b, 0x65a4d550, 0x65bebf01, 0x65d8a680,
-	0x65f28bcc, 0x660c6ee8, 0x66264fd3, 0x66402e8f,
-	0x665a0b1c, 0x6673e57d, 0x668dbdb0, 0x66a793b8,
-	0x66c16795, 0x66db3949, 0x66f508d4, 0x670ed636,
-	0x6728a172, 0x67426a87, 0x675c3177, 0x6775f643,
-	0x678fb8eb, 0x67a97971, 0x67c337d5, 0x67dcf418,
-	0x67f6ae3b, 0x6810663f, 0x682a1c25, 0x6843cfed,
-	0x685d8199, 0x68773129, 0x6890de9f, 0x68aa89fa,
-	0x68c4333d, 0x68ddda67, 0x68f77f7a, 0x69112277,
-	0x692ac35e, 0x69446230, 0x695dfeee, 0x6977999a,
-	0x69913232, 0x69aac8ba, 0x69c45d31, 0x69ddef98,
-	0x69f77ff0, 0x6a110e3a, 0x6a2a9a77, 0x6a4424a8,
-	0x6a5daccc, 0x6a7732e6, 0x6a90b6f6, 0x6aaa38fd,
-	0x6ac3b8fb, 0x6add36f2, 0x6af6b2e2, 0x6b102ccd,
-	0x6b29a4b2, 0x6b431a92, 0x6b5c8e6f, 0x6b76004a,
-	0x6b8f7022, 0x6ba8ddf9, 0x6bc249d0, 0x6bdbb3a7,
-	0x6bf51b80, 0x6c0e815a, 0x6c27e537, 0x6c414718,
-	0x6c5aa6fd, 0x6c7404e7, 0x6c8d60d7, 0x6ca6bace,
-	0x6cc012cc, 0x6cd968d2, 0x6cf2bce1, 0x6d0c0ef9,
-	0x6d255f1d, 0x6d3ead4b, 0x6d57f985, 0x6d7143cc,
-	0x6d8a8c21, 0x6da3d283, 0x6dbd16f5, 0x6dd65976,
-	0x6def9a08, 0x6e08d8ab, 0x6e221560, 0x6e3b5027,
-	0x6e548902, 0x6e6dbff1, 0x6e86f4f5, 0x6ea0280e,
-	0x6eb9593e, 0x6ed28885, 0x6eebb5e3, 0x6f04e15a,
-	0x6f1e0aea, 0x6f373294, 0x6f505859, 0x6f697c39,
-	0x6f829e35, 0x6f9bbe4e, 0x6fb4dc85, 0x6fcdf8d9,
-	0x6fe7134d, 0x70002be0, 0x70194293, 0x70325767,
-	0x704b6a5d, 0x70647b76, 0x707d8ab1, 0x70969811,
-	0x70afa394, 0x70c8ad3d, 0x70e1b50c, 0x70fabb01,
-	0x7113bf1d, 0x712cc161, 0x7145c1ce, 0x715ec064,
-	0x7177bd24, 0x7190b80f, 0x71a9b124, 0x71c2a866,
-	0x71db9dd4, 0x71f49170, 0x720d8339, 0x72267331,
-	0x723f6159, 0x72584db0, 0x72713838, 0x728a20f1,
-	0x72a307db, 0x72bbecf9, 0x72d4d049, 0x72edb1ce,
-	0x73069187, 0x731f6f75, 0x73384b98, 0x735125f3,
-	0x7369fe84, 0x7382d54d, 0x739baa4e, 0x73b47d89,
-	0x73cd4efd, 0x73e61eab, 0x73feec94, 0x7417b8b8,
-	0x74308319, 0x74494bb6, 0x74621291, 0x747ad7aa,
-	0x74939b02, 0x74ac5c98, 0x74c51c6f, 0x74ddda86,
-	0x74f696de, 0x750f5178, 0x75280a54, 0x7540c174,
-	0x755976d7, 0x75722a7e, 0x758adc69, 0x75a38c9b,
-	0x75bc3b12, 0x75d4e7cf, 0x75ed92d4, 0x76063c21,
-	0x761ee3b6, 0x76378994, 0x76502dbc, 0x7668d02e,
-	0x768170eb, 0x769a0ff3, 0x76b2ad47, 0x76cb48e7,
-	0x76e3e2d5, 0x76fc7b10, 0x7715119a, 0x772da673,
-	0x7746399b, 0x775ecb13, 0x77775adc, 0x778fe8f6,
-	0x77a87561, 0x77c1001f, 0x77d98930, 0x77f21095,
-	0x780a964d, 0x78231a5b, 0x783b9cbd, 0x78541d75,
-	0x786c9c84, 0x788519e9, 0x789d95a6, 0x78b60fbb,
-	0x78ce8828, 0x78e6feef, 0x78ff740f, 0x7917e78a,
-	0x7930595f, 0x7948c990, 0x7961381d, 0x7979a506,
-	0x7992104c, 0x79aa79f0, 0x79c2e1f1, 0x79db4852,
-	0x79f3ad11, 0x7a0c1031, 0x7a2471b0, 0x7a3cd191,
-	0x7a552fd3, 0x7a6d8c76, 0x7a85e77d, 0x7a9e40e6,
-	0x7ab698b2, 0x7aceeee3, 0x7ae74378, 0x7aff9673,
-	0x7b17e7d2, 0x7b303799, 0x7b4885c5, 0x7b60d259,
-	0x7b791d55, 0x7b9166b9, 0x7ba9ae86, 0x7bc1f4bc,
-	0x7bda395c, 0x7bf27c66, 0x7c0abddb, 0x7c22fdbb,
-	0x7c3b3c07, 0x7c5378c0, 0x7c6bb3e5, 0x7c83ed78,
-	0x7c9c2579, 0x7cb45be9, 0x7ccc90c7, 0x7ce4c414,
-	0x7cfcf5d2, 0x7d152600, 0x7d2d549f, 0x7d4581b0,
-	0x7d5dad32, 0x7d75d727, 0x7d8dff8f, 0x7da6266a,
-	0x7dbe4bba, 0x7dd66f7d, 0x7dee91b6, 0x7e06b264,
-	0x7e1ed188, 0x7e36ef22, 0x7e4f0b34, 0x7e6725bd,
-	0x7e7f3ebd, 0x7e975636, 0x7eaf6c28, 0x7ec78093,
-	0x7edf9378, 0x7ef7a4d7, 0x7f0fb4b1, 0x7f27c307,
-	0x7f3fcfd8, 0x7f57db25, 0x7f6fe4ef, 0x7f87ed36,
-	0x7f9ff3fb, 0x7fb7f93e, 0x7fcffcff, 0x7fe7ff40
-};
-
-const Word32 mTab_4_3[512]={
-	0x32cbfd4a, 0x32eddd70, 0x330fc339, 0x3331aea3,
-	0x33539fac, 0x33759652, 0x33979294, 0x33b99470,
-	0x33db9be4, 0x33fda8ed, 0x341fbb8b, 0x3441d3bb,
-	0x3463f17c, 0x348614cc, 0x34a83da8, 0x34ca6c10,
-	0x34eca001, 0x350ed979, 0x35311877, 0x35535cfa,
-	0x3575a6fe, 0x3597f683, 0x35ba4b87, 0x35dca607,
-	0x35ff0603, 0x36216b78, 0x3643d665, 0x366646c7,
-	0x3688bc9e, 0x36ab37e8, 0x36cdb8a2, 0x36f03ecb,
-	0x3712ca62, 0x37355b64, 0x3757f1d1, 0x377a8da5,
-	0x379d2ee0, 0x37bfd580, 0x37e28184, 0x380532e8,
-	0x3827e9ad, 0x384aa5d0, 0x386d674f, 0x38902e2a,
-	0x38b2fa5d, 0x38d5cbe9, 0x38f8a2ca, 0x391b7eff,
-	0x393e6088, 0x39614761, 0x3984338a, 0x39a72501,
-	0x39ca1bc4, 0x39ed17d1, 0x3a101928, 0x3a331fc6,
-	0x3a562baa, 0x3a793cd2, 0x3a9c533d, 0x3abf6ee9,
-	0x3ae28fd5, 0x3b05b5ff, 0x3b28e165, 0x3b4c1206,
-	0x3b6f47e0, 0x3b9282f2, 0x3bb5c33a, 0x3bd908b7,
-	0x3bfc5368, 0x3c1fa349, 0x3c42f85b, 0x3c66529c,
-	0x3c89b209, 0x3cad16a2, 0x3cd08065, 0x3cf3ef51,
-	0x3d176364, 0x3d3adc9c, 0x3d5e5af8, 0x3d81de77,
-	0x3da56717, 0x3dc8f4d6, 0x3dec87b4, 0x3e101fae,
-	0x3e33bcc3, 0x3e575ef2, 0x3e7b063a, 0x3e9eb298,
-	0x3ec2640c, 0x3ee61a93, 0x3f09d62d, 0x3f2d96d8,
-	0x3f515c93, 0x3f75275b, 0x3f98f731, 0x3fbccc11,
-	0x3fe0a5fc, 0x400484ef, 0x402868ea, 0x404c51e9,
-	0x40703fee, 0x409432f5, 0x40b82afd, 0x40dc2806,
-	0x41002a0d, 0x41243111, 0x41483d12, 0x416c4e0d,
-	0x41906401, 0x41b47eed, 0x41d89ecf, 0x41fcc3a7,
-	0x4220ed72, 0x42451c30, 0x42694fde, 0x428d887d,
-	0x42b1c609, 0x42d60883, 0x42fa4fe8, 0x431e9c37,
-	0x4342ed70, 0x43674390, 0x438b9e96, 0x43affe82,
-	0x43d46351, 0x43f8cd03, 0x441d3b95, 0x4441af08,
-	0x44662758, 0x448aa487, 0x44af2690, 0x44d3ad75,
-	0x44f83933, 0x451cc9c8, 0x45415f35, 0x4565f977,
-	0x458a988d, 0x45af3c76, 0x45d3e531, 0x45f892bc,
-	0x461d4516, 0x4641fc3e, 0x4666b832, 0x468b78f2,
-	0x46b03e7c, 0x46d508cf, 0x46f9d7e9, 0x471eabca,
-	0x47438470, 0x476861d9, 0x478d4406, 0x47b22af3,
-	0x47d716a1, 0x47fc070e, 0x4820fc39, 0x4845f620,
-	0x486af4c3, 0x488ff820, 0x48b50035, 0x48da0d03,
-	0x48ff1e87, 0x492434c0, 0x49494fad, 0x496e6f4d,
-	0x4993939f, 0x49b8bca2, 0x49ddea54, 0x4a031cb4,
-	0x4a2853c1, 0x4a4d8f7a, 0x4a72cfde, 0x4a9814eb,
-	0x4abd5ea1, 0x4ae2acfd, 0x4b080000, 0x4b2d57a8,
-	0x4b52b3f3, 0x4b7814e1, 0x4b9d7a70, 0x4bc2e49f,
-	0x4be8536e, 0x4c0dc6db, 0x4c333ee4, 0x4c58bb89,
-	0x4c7e3cc9, 0x4ca3c2a2, 0x4cc94d14, 0x4ceedc1c,
-	0x4d146fbb, 0x4d3a07ef, 0x4d5fa4b6, 0x4d854611,
-	0x4daaebfd, 0x4dd09679, 0x4df64585, 0x4e1bf91f,
-	0x4e41b146, 0x4e676dfa, 0x4e8d2f38, 0x4eb2f501,
-	0x4ed8bf52, 0x4efe8e2b, 0x4f24618a, 0x4f4a3970,
-	0x4f7015d9, 0x4f95f6c6, 0x4fbbdc36, 0x4fe1c626,
-	0x5007b497, 0x502da787, 0x50539ef5, 0x50799ae1,
-	0x509f9b48, 0x50c5a02a, 0x50eba985, 0x5111b75a,
-	0x5137c9a6, 0x515de069, 0x5183fba2, 0x51aa1b4f,
-	0x51d03f70, 0x51f66803, 0x521c9508, 0x5242c67d,
-	0x5268fc62, 0x528f36b5, 0x52b57575, 0x52dbb8a2,
-	0x5302003a, 0x53284c3c, 0x534e9ca8, 0x5374f17c,
-	0x539b4ab7, 0x53c1a858, 0x53e80a5f, 0x540e70ca,
-	0x5434db98, 0x545b4ac8, 0x5481be5a, 0x54a8364b,
-	0x54ceb29c, 0x54f5334c, 0x551bb858, 0x554241c1,
-	0x5568cf85, 0x558f61a3, 0x55b5f81b, 0x55dc92eb,
-	0x56033212, 0x5629d590, 0x56507d63, 0x5677298a,
-	0x569dda05, 0x56c48ed3, 0x56eb47f2, 0x57120562,
-	0x5738c721, 0x575f8d2f, 0x5786578a, 0x57ad2633,
-	0x57d3f927, 0x57fad066, 0x5821abef, 0x58488bc0,
-	0x586f6fda, 0x5896583b, 0x58bd44e2, 0x58e435ce,
-	0x590b2aff, 0x59322473, 0x59592229, 0x59802420,
-	0x59a72a59, 0x59ce34d0, 0x59f54387, 0x5a1c567b,
-	0x5a436dac, 0x5a6a8919, 0x5a91a8c1, 0x5ab8cca3,
-	0x5adff4be, 0x5b072111, 0x5b2e519c, 0x5b55865e,
-	0x5b7cbf54, 0x5ba3fc80, 0x5bcb3ddf, 0x5bf28371,
-	0x5c19cd35, 0x5c411b2a, 0x5c686d4f, 0x5c8fc3a4,
-	0x5cb71e27, 0x5cde7cd7, 0x5d05dfb4, 0x5d2d46bd,
-	0x5d54b1f0, 0x5d7c214e, 0x5da394d4, 0x5dcb0c83,
-	0x5df28859, 0x5e1a0856, 0x5e418c78, 0x5e6914be,
-	0x5e90a129, 0x5eb831b7, 0x5edfc667, 0x5f075f38,
-	0x5f2efc29, 0x5f569d3a, 0x5f7e426a, 0x5fa5ebb7,
-	0x5fcd9921, 0x5ff54aa8, 0x601d004a, 0x6044ba06,
-	0x606c77dc, 0x609439ca, 0x60bbffd0, 0x60e3c9ee,
-	0x610b9821, 0x61336a6a, 0x615b40c8, 0x61831b39,
-	0x61aaf9bd, 0x61d2dc53, 0x61fac2fa, 0x6222adb2,
-	0x624a9c79, 0x62728f4f, 0x629a8633, 0x62c28123,
-	0x62ea8020, 0x63128329, 0x633a8a3c, 0x63629559,
-	0x638aa47f, 0x63b2b7ad, 0x63dacee2, 0x6402ea1e,
-	0x642b0960, 0x64532ca6, 0x647b53f1, 0x64a37f3f,
-	0x64cbae8f, 0x64f3e1e2, 0x651c1935, 0x65445488,
-	0x656c93db, 0x6594d72c, 0x65bd1e7b, 0x65e569c7,
-	0x660db90f, 0x66360c53, 0x665e6391, 0x6686bec9,
-	0x66af1dfa, 0x66d78123, 0x66ffe844, 0x6728535b,
-	0x6750c268, 0x6779356b, 0x67a1ac62, 0x67ca274c,
-	0x67f2a629, 0x681b28f9, 0x6843afb9, 0x686c3a6a,
-	0x6894c90b, 0x68bd5b9b, 0x68e5f219, 0x690e8c84,
-	0x69372add, 0x695fcd21, 0x69887350, 0x69b11d6a,
-	0x69d9cb6d, 0x6a027d5a, 0x6a2b332f, 0x6a53eceb,
-	0x6a7caa8d, 0x6aa56c16, 0x6ace3184, 0x6af6fad6,
-	0x6b1fc80c, 0x6b489925, 0x6b716e20, 0x6b9a46fd,
-	0x6bc323bb, 0x6bec0458, 0x6c14e8d5, 0x6c3dd130,
-	0x6c66bd69, 0x6c8fad80, 0x6cb8a172, 0x6ce19940,
-	0x6d0a94e9, 0x6d33946d, 0x6d5c97ca, 0x6d859eff,
-	0x6daeaa0d, 0x6dd7b8f1, 0x6e00cbad, 0x6e29e23e,
-	0x6e52fca4, 0x6e7c1adf, 0x6ea53cee, 0x6ece62cf,
-	0x6ef78c83, 0x6f20ba09, 0x6f49eb5f, 0x6f732085,
-	0x6f9c597b, 0x6fc59640, 0x6feed6d3, 0x70181b33,
-	0x70416360, 0x706aaf59, 0x7093ff1d, 0x70bd52ab,
-	0x70e6aa04, 0x71100525, 0x7139640f, 0x7162c6c1,
-	0x718c2d3a, 0x71b5977a, 0x71df057f, 0x72087749,
-	0x7231ecd8, 0x725b662a, 0x7284e33f, 0x72ae6417,
-	0x72d7e8b0, 0x7301710a, 0x732afd24, 0x73548cfe,
-	0x737e2097, 0x73a7b7ee, 0x73d15303, 0x73faf1d5,
-	0x74249462, 0x744e3aac, 0x7477e4b0, 0x74a1926e,
-	0x74cb43e6, 0x74f4f917, 0x751eb201, 0x75486ea1,
-	0x75722ef9, 0x759bf307, 0x75c5baca, 0x75ef8642,
-	0x7619556f, 0x7643284f, 0x766cfee2, 0x7696d928,
-	0x76c0b71f, 0x76ea98c7, 0x77147e20, 0x773e6728,
-	0x776853df, 0x77924445, 0x77bc3858, 0x77e63019,
-	0x78102b85, 0x783a2a9e, 0x78642d62, 0x788e33d1,
-	0x78b83de9, 0x78e24bab, 0x790c5d15, 0x79367228,
-	0x79608ae1, 0x798aa742, 0x79b4c748, 0x79deeaf4,
-	0x7a091245, 0x7a333d3a, 0x7a5d6bd2, 0x7a879e0e,
-	0x7ab1d3ec, 0x7adc0d6b, 0x7b064a8c, 0x7b308b4d,
-	0x7b5acfae, 0x7b8517ae, 0x7baf634c, 0x7bd9b289,
-	0x7c040563, 0x7c2e5bda, 0x7c58b5ec, 0x7c83139b,
-	0x7cad74e4, 0x7cd7d9c7, 0x7d024244, 0x7d2cae5a,
-	0x7d571e09, 0x7d81914f, 0x7dac082d, 0x7dd682a1,
-	0x7e0100ac, 0x7e2b824b, 0x7e560780, 0x7e809048,
-	0x7eab1ca5, 0x7ed5ac94, 0x7f004015, 0x7f2ad729,
-	0x7f5571cd, 0x7f801003, 0x7faab1c8, 0x7fd5571d
-};
-
-
-const Word32 invSBF[24] = {
-  0x3FFD34FC, 0x2D3F8000, 0x24F18C7E, 0x1FFE9A7E,
-  0x1C9DF10C, 0x1A1F851A, 0x182FE994, 0x169FC000,
-  0x15542AAA, 0x143C31C2, 0x134B1B6C, 0x127920BE,
-  0x11BF2FCC, 0x111A749E, 0x1085FC42, 0x0FFFA7BE,
-  0x0F855818, 0x0F14EE56, 0x0EAE6A78, 0x0E4EF886,
-  0x0DF69880, 0x0DA49568, 0x0D578542, 0x0D101D0C
-};
-
-const Word16 pow2tominusNover16[17] = {
-  0x7fff, 0x7a93, 0x7560, 0x7066,
-  0x6ba2, 0x6712, 0x62b4, 0x5e84,
-  0x5a82, 0x56ac, 0x52ff, 0x4f7b,
-  0x4c1c, 0x48e2, 0x45cb, 0x42d5,
-  0x4000
-};
-
-const Word16 sideInfoTabLong[MAX_SFB_LONG + 1] = {
-  9, 9, 9, 9, 9, 9, 9, 9, 9,
-  9, 9, 9, 9, 9, 9, 9, 9, 9,
-  9, 9, 9, 9, 9, 9, 9, 9, 9,
-  9, 9, 9, 9, 14, 14, 14, 14,
-  14, 14, 14, 14, 14, 14, 14,
-  14, 14, 14, 14, 14, 14, 14,
-  14, 14, 14
-};
-
-const Word16 sideInfoTabShort[MAX_SFB_SHORT + 1] = {
-  7, 7, 7, 7, 7, 7, 7, 10, 10,
-  10, 10, 10, 10, 10, 13, 13
-};
-
-const Word32 specExpMantTableComb_enc[4][14] =
-{
-  {0x40000000,  0x50a28be6,  0x6597fa95,  0x40000000,
-   0x50a28be6,  0x6597fa95,  0x40000000,  0x50a28be6,
-   0x6597fa95,  0x40000000,  0x50a28be6,  0x6597fa95,
-   0x40000000,  0x50a28be6},
-
-  {0x4c1bf829,  0x5fe4435e,  0x78d0df9c,  0x4c1bf829,
-   0x5fe4435e,  0x78d0df9c,  0x4c1bf829,  0x5fe4435e,
-   0x78d0df9c,  0x4c1bf829,  0x5fe4435e,  0x78d0df9c,
-   0x4c1bf829,  0x5fe4435e},
-
-  {0x5a82799a,  0x7208f81d,  0x47d66b0f,  0x5a82799a,
-   0x7208f81d,  0x47d66b0f,  0x5a82799a,  0x7208f81d,
-   0x47d66b0f,  0x5a82799a,  0x7208f81d,  0x47d66b0f,
-   0x5a82799a,  0x7208f81d},
-
-  {0x6ba27e65,  0x43ce3e4b,  0x556e0424,  0x6ba27e65,
-   0x43ce3e4b,  0x556e0424,  0x6ba27e65,  0x43ce3e4b,
-   0x556e0424,  0x6ba27e65,  0x43ce3e4b,  0x556e0424,
-   0x6ba27e65,  0x43ce3e4b}
-};
-
-const  UWord8 specExpTableComb_enc[4][14] =
-{
-  {1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 18},
-  {1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 18},
-  {1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14, 16, 17, 18},
-  {1, 3, 4, 5, 7, 8, 9, 11, 12, 13, 15, 16, 17, 19}
-};
-
-const Word16 quantBorders[4][4] = {
-  /* pow(1.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */
-  {0x0400, 0x0ee7, 0x1c86, 0x2c0d},
-  /* pow(2.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */
-  {0x04c2, 0x11b9, 0x21eb, 0x3463},
-  /* pow(3.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */
-  {0x05a8, 0x1514, 0x2856, 0x3e4c},
-  /* pow(4.0-0.4054, 4/3)/16 * pow(2, (0..3)/4) */
-  {0x06ba, 0x1911, 0x2ff8, 0x4a16},
-};
-
-const Word16 quantRecon[4][3] = {
-  {0x0800, 0x1429, 0x229d},
-  {0x0983, 0x17f9, 0x292a},
-  {0x0b50, 0x1c82, 0x30f4},
-  {0x0d74, 0x21e7, 0x3a37},
-};
-
-const int sampRateTab[NUM_SAMPLE_RATES] = {
-    96000, 88200, 64000, 48000, 44100, 32000,
-	24000, 22050, 16000, 12000, 11025,  8000
-};
-
-
-const int	rates[8] = {
-	160, 240, 320, 400, 480, 560, 640, 0
-};
-
-const int BandwithCoefTab[8][NUM_SAMPLE_RATES] = {
-	{ 7000,  7000,  4666,  3500,  3500,  2800,  2800,  2800,  2800,  2000,  2000,  2000},
-	{12000, 12000,  8000,  6000,  6000,  6000,  4000,  4000,  4000,  3000,  3000,  3000},
-	{18000, 18000, 12000,  9000,  9000,  9000,  7000,  7000,  7000,  5000,  5000,  5000},
-	{20000, 20000, 16000, 12000, 12000, 12000,  9000,  9000,  9000,  6000,  6000,  6000},
-	{20000, 20000, 18666, 14000, 14000, 14000, 10000, 10000, 10000,  7000,  7000,  7000},
-	{20000, 20000, 20000, 16000, 16000, 16000, 12000, 12000, 12000,  8000,  8000,  8000},
-	{20000, 20000, 20000, 20000, 20000, 20000, 15000, 15000, 15000, 10000, 10000, 10000},
-	{20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000}
-};
-
-
-/* total number of scale factor bands in one window */
-const UWord8 sfBandTotalShort[NUM_SAMPLE_RATES] = {
-    12, 12, 12, 14, 14, 14, 15, 15, 15, 15, 15, 15
-};
-
-const UWord8 sfBandTotalLong[NUM_SAMPLE_RATES] = {
-    41, 41, 47, 49, 49, 51, 47, 47, 43, 43, 43, 40
-};
-
-/* scale factor band tables */
-const int sfBandTabShortOffset[NUM_SAMPLE_RATES] = {0, 0, 0, 13, 13, 13, 28, 28, 44, 44, 44, 60};
-
-const short sfBandTabShort[76] = {
-	/* short block 64, 88, 96 kHz [13]  */
-	0,   4,   8,  12,  16,  20,  24,  32,  40,  48,  64,  92, 128,
-
-	/* short block 32, 44, 48 kHz [15]  */
-	0,   4,   8,  12,  16,  20,  28,  36,  44,  56,  68,  80,  96, 112, 128,
-
-	/* short block 22, 24 kHz [16]  */
-	0,   4,   8,  12,  16,  20,  24,  28,  36,  44,  52,  64,  76,  92, 108, 128,
-
-	/* short block 11, 12, 16 kHz [16] */
-	0,   4,   8,  12,  16,  20,  24,  28,  32,  40,  48,  60,  72,  88, 108, 128,
-
-	/* short block 8 kHz [16] */
-	0,   4,   8,  12,  16,  20,  24,  28,  36,  44,  52,  60,  72,  88, 108, 128
-};
-
-const int sfBandTabLongOffset[NUM_SAMPLE_RATES] = {0, 0, 42, 90, 90, 140, 192, 192, 240, 240, 240, 284};
-
-const short sfBandTabLong[325] = {
-	/* long block 88, 96 kHz [42]  */
-	  0,   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,
-
-	/* long block 64 kHz [48]  */
-	  0,   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,
-
-	/* long block 44, 48 kHz [50] */
-	  0,   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,
-
-	/* long block 32 kHz [52] */
-	  0,   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,
-
-	/* long block 22, 24 kHz [48] */
-	  0,   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,
-
-	/* long block 11, 12, 16 kHz [44] */
-	  0,   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,
-
-	/* long block 8 kHz [41]  */
-	  0,  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
-};
-
-/*
-  these tables are used only for counting and
-  are stored in packed format
-*/
-const UWord16 huff_ltab1_2[3][3][3][3]=
-{
-  {
-    {
-      {0x0b09,0x0907,0x0b09},
-      {0x0a08,0x0706,0x0a08},
-      {0x0b09,0x0908,0x0b09}
-    },
-    {
-      {0x0a08,0x0706,0x0a07},
-      {0x0706,0x0505,0x0706},
-      {0x0907,0x0706,0x0a08}
-    },
-    {
-      {0x0b09,0x0907,0x0b08},
-      {0x0908,0x0706,0x0908},
-      {0x0b09,0x0907,0x0b09}
-    }
-  },
-  {
-    {
-      {0x0908,0x0706,0x0907},
-      {0x0706,0x0505,0x0706},
-      {0x0907,0x0706,0x0908}
-    },
-    {
-      {0x0706,0x0505,0x0706},
-      {0x0505,0x0103,0x0505},
-      {0x0706,0x0505,0x0706}
-    },
-    {
-      {0x0908,0x0706,0x0907},
-      {0x0706,0x0505,0x0706},
-      {0x0908,0x0706,0x0908}
-    }
-  },
-  {
-    {
-      {0x0b09,0x0907,0x0b09},
-      {0x0908,0x0706,0x0908},
-      {0x0b08,0x0907,0x0b09}
-    },
-    {
-      {0x0a08,0x0706,0x0907},
-      {0x0706,0x0504,0x0706},
-      {0x0908,0x0706,0x0a07}
-    },
-    {
-      {0x0b09,0x0907,0x0b09},
-      {0x0a07,0x0706,0x0908},
-      {0x0b09,0x0907,0x0b09}
-    }
-  }
-};
-
-
-const UWord16 huff_ltab3_4[3][3][3][3]=
-{
-  {
-    {
-      {0x0104,0x0405,0x0808},
-      {0x0405,0x0504,0x0808},
-      {0x0909,0x0908,0x0a0b}
-    },
-    {
-      {0x0405,0x0605,0x0908},
-      {0x0605,0x0604,0x0908},
-      {0x0908,0x0907,0x0a0a}
-    },
-    {
-      {0x0909,0x0a08,0x0d0b},
-      {0x0908,0x0908,0x0b0a},
-      {0x0b0b,0x0a0a,0x0c0b}
-    }
-  },
-  {
-    {
-      {0x0404,0x0605,0x0a08},
-      {0x0604,0x0704,0x0a08},
-      {0x0a08,0x0a08,0x0c0a}
-    },
-    {
-      {0x0504,0x0704,0x0b08},
-      {0x0604,0x0704,0x0a07},
-      {0x0908,0x0907,0x0b09}
-    },
-    {
-      {0x0908,0x0a08,0x0d0a},
-      {0x0807,0x0907,0x0c09},
-      {0x0a0a,0x0b09,0x0c0a}
-    }
-  },
-  {
-    {
-      {0x0808,0x0a08,0x0f0b},
-      {0x0908,0x0b07,0x0f0a},
-      {0x0d0b,0x0e0a,0x100c}
-    },
-    {
-      {0x0808,0x0a07,0x0e0a},
-      {0x0907,0x0a07,0x0e09},
-      {0x0c0a,0x0c09,0x0f0b}
-    },
-    {
-      {0x0b0b,0x0c0a,0x100c},
-      {0x0a0a,0x0b09,0x0f0b},
-      {0x0c0b,0x0c0a,0x0f0b}
-    }
-  }
-};
-
-const UWord16 huff_ltab5_6[9][9]=
-{
-  {0x0d0b,0x0c0a,0x0b09,0x0b09,0x0a09,0x0b09,0x0b09,0x0c0a,0x0d0b},
-  {0x0c0a,0x0b09,0x0a08,0x0907,0x0807,0x0907,0x0a08,0x0b09,0x0c0a},
-  {0x0c09,0x0a08,0x0906,0x0806,0x0706,0x0806,0x0906,0x0a08,0x0b09},
-  {0x0b09,0x0907,0x0806,0x0504,0x0404,0x0504,0x0806,0x0907,0x0b09},
-  {0x0a09,0x0807,0x0706,0x0404,0x0104,0x0404,0x0706,0x0807,0x0b09},
-  {0x0b09,0x0907,0x0806,0x0504,0x0404,0x0504,0x0806,0x0907,0x0b09},
-  {0x0b09,0x0a08,0x0906,0x0806,0x0706,0x0806,0x0906,0x0a08,0x0b09},
-  {0x0c0a,0x0b09,0x0a08,0x0907,0x0807,0x0907,0x0a07,0x0b08,0x0c0a},
-  {0x0d0b,0x0c0a,0x0c09,0x0b09,0x0a09,0x0a09,0x0b09,0x0c0a,0x0d0b}
-};
-
-const UWord16 huff_ltab7_8[8][8]=
-{
-  {0x0105,0x0304,0x0605,0x0706,0x0807,0x0908,0x0a09,0x0b0a},
-  {0x0304,0x0403,0x0604,0x0705,0x0806,0x0807,0x0907,0x0908},
-  {0x0605,0x0604,0x0704,0x0805,0x0806,0x0907,0x0907,0x0a08},
-  {0x0706,0x0705,0x0805,0x0806,0x0906,0x0907,0x0a08,0x0a08},
-  {0x0807,0x0806,0x0906,0x0906,0x0a07,0x0a07,0x0a08,0x0b09},
-  {0x0908,0x0807,0x0906,0x0907,0x0a07,0x0a08,0x0b08,0x0b0a},
-  {0x0a09,0x0907,0x0907,0x0a08,0x0a08,0x0b08,0x0c09,0x0c09},
-  {0x0b0a,0x0a08,0x0a08,0x0a08,0x0b09,0x0b09,0x0c09,0x0c0a}
-};
-
-const UWord16 huff_ltab9_10[13][13]=
-{
-  {0x0106,0x0305,0x0606,0x0806,0x0907,0x0a08,0x0a09,0x0b0a,0x0b0a,0x0c0a,0x0c0b,0x0d0b,0x0d0c},
-  {0x0305,0x0404,0x0604,0x0705,0x0806,0x0807,0x0907,0x0a08,0x0a08,0x0a09,0x0b0a,0x0c0a,0x0c0b},
-  {0x0606,0x0604,0x0705,0x0805,0x0806,0x0906,0x0a07,0x0a08,0x0a08,0x0b09,0x0c09,0x0c0a,0x0c0a},
-  {0x0806,0x0705,0x0805,0x0905,0x0906,0x0a07,0x0a07,0x0b08,0x0b08,0x0b09,0x0c09,0x0c0a,0x0d0a},
-  {0x0907,0x0806,0x0906,0x0906,0x0a06,0x0a07,0x0b07,0x0b08,0x0b08,0x0c09,0x0c09,0x0c0a,0x0d0a},
-  {0x0a08,0x0907,0x0906,0x0a07,0x0b07,0x0b07,0x0b08,0x0c08,0x0b08,0x0c09,0x0c0a,0x0d0a,0x0d0b},
-  {0x0b09,0x0907,0x0a07,0x0b07,0x0b07,0x0b08,0x0c08,0x0c09,0x0c09,0x0c09,0x0d0a,0x0d0a,0x0d0b},
-  {0x0b09,0x0a08,0x0a08,0x0b08,0x0b08,0x0c08,0x0c09,0x0d09,0x0d09,0x0d0a,0x0d0a,0x0d0b,0x0d0b},
-  {0x0b09,0x0a08,0x0a08,0x0b08,0x0b08,0x0b08,0x0c09,0x0c09,0x0d0a,0x0d0a,0x0e0a,0x0d0b,0x0e0b},
-  {0x0b0a,0x0a09,0x0b09,0x0b09,0x0c09,0x0c09,0x0c09,0x0c0a,0x0d0a,0x0d0a,0x0e0b,0x0e0b,0x0e0c},
-  {0x0c0a,0x0b09,0x0b09,0x0c09,0x0c09,0x0c0a,0x0d0a,0x0d0a,0x0d0a,0x0e0b,0x0e0b,0x0e0b,0x0f0c},
-  {0x0c0b,0x0b0a,0x0c09,0x0c0a,0x0c0a,0x0d0a,0x0d0a,0x0d0a,0x0d0b,0x0e0b,0x0e0b,0x0f0b,0x0f0c},
-  {0x0d0b,0x0c0a,0x0c0a,0x0c0a,0x0d0a,0x0d0a,0x0d0a,0x0d0b,0x0e0b,0x0e0c,0x0e0c,0x0e0c,0x0f0c}
-};
-
-const UWord16 huff_ltab11[17][17]=
-{
-  {0x0004,0x0005,0x0006,0x0007,0x0008,0x0008,0x0009,0x000a,0x000a,0x000a,0x000b,0x000b,0x000c,0x000b,0x000c,0x000c,0x000a},
-  {0x0005,0x0004,0x0005,0x0006,0x0007,0x0007,0x0008,0x0008,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x000b,0x0008},
-  {0x0006,0x0005,0x0005,0x0006,0x0007,0x0007,0x0008,0x0008,0x0008,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x0008},
-  {0x0007,0x0006,0x0006,0x0006,0x0007,0x0007,0x0008,0x0008,0x0008,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x0008},
-  {0x0008,0x0007,0x0007,0x0007,0x0007,0x0008,0x0008,0x0008,0x0008,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x0008},
-  {0x0008,0x0007,0x0007,0x0007,0x0007,0x0008,0x0008,0x0008,0x0009,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x0008},
-  {0x0009,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x000a,0x0008},
-  {0x0009,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x0008},
-  {0x000a,0x0009,0x0008,0x0008,0x0009,0x0009,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000b,0x0008},
-  {0x000a,0x0009,0x0009,0x0009,0x0009,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000b,0x000b,0x0008},
-  {0x000b,0x0009,0x0009,0x0009,0x0009,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x000a,0x000b,0x000a,0x000b,0x000b,0x0008},
-  {0x000b,0x000a,0x0009,0x0009,0x000a,0x0009,0x000a,0x000a,0x000a,0x000a,0x000a,0x000b,0x000b,0x000b,0x000b,0x000b,0x0008},
-  {0x000b,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000b,0x000b,0x000b,0x000b,0x000b,0x0009},
-  {0x000b,0x000a,0x0009,0x0009,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000b,0x000b,0x000b,0x000b,0x000b,0x000b,0x0009},
-  {0x000b,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000b,0x000b,0x000b,0x000b,0x000b,0x000b,0x0009},
-  {0x000c,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000a,0x000b,0x000b,0x000b,0x000b,0x000b,0x000b,0x000c,0x000c,0x0009},
-  {0x0009,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0008,0x0009,0x0005}
-};
-
-const UWord16 huff_ltabscf[121]=
-{
-  0x0012,
-  0x0012,
-  0x0012,
-  0x0012,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0012,
-  0x0013,
-  0x0012,
-  0x0011,
-  0x0011,
-  0x0010,
-  0x0011,
-  0x0010,
-  0x0010,
-  0x0010,
-  0x0010,
-  0x000f,
-  0x000f,
-  0x000e,
-  0x000e,
-  0x000e,
-  0x000e,
-  0x000e,
-  0x000e,
-  0x000d,
-  0x000d,
-  0x000c,
-  0x000c,
-  0x000c,
-  0x000b,
-  0x000c,
-  0x000b,
-  0x000a,
-  0x000a,
-  0x000a,
-  0x0009,
-  0x0009,
-  0x0008,
-  0x0008,
-  0x0008,
-  0x0007,
-  0x0006,
-  0x0006,
-  0x0005,
-  0x0004,
-  0x0003,
-  0x0001,
-  0x0004,
-  0x0004,
-  0x0005,
-  0x0006,
-  0x0006,
-  0x0007,
-  0x0007,
-  0x0008,
-  0x0008,
-  0x0009,
-  0x0009,
-  0x000a,
-  0x000a,
-  0x000a,
-  0x000b,
-  0x000b,
-  0x000b,
-  0x000b,
-  0x000c,
-  0x000c,
-  0x000d,
-  0x000d,
-  0x000d,
-  0x000e,
-  0x000e,
-  0x0010,
-  0x000f,
-  0x0010,
-  0x000f,
-  0x0012,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013,
-  0x0013
-};
-
-
-const UWord16 huff_ctab1[3][3][3][3]=
-{
-  {
-    {
-      {0x07f8,0x01f1,0x07fd},
-      {0x03f5,0x0068,0x03f0},
-      {0x07f7,0x01ec,0x07f5}
-    },
-    {
-      {0x03f1,0x0072,0x03f4},
-      {0x0074,0x0011,0x0076},
-      {0x01eb,0x006c,0x03f6}
-    },
-    {
-      {0x07fc,0x01e1,0x07f1},
-      {0x01f0,0x0061,0x01f6},
-      {0x07f2,0x01ea,0x07fb}
-    }
-  },
-  {
-    {
-      {0x01f2,0x0069,0x01ed},
-      {0x0077,0x0017,0x006f},
-      {0x01e6,0x0064,0x01e5}
-    },
-    {
-      {0x0067,0x0015,0x0062},
-      {0x0012,0x0000,0x0014},
-      {0x0065,0x0016,0x006d}
-    },
-    {
-      {0x01e9,0x0063,0x01e4},
-      {0x006b,0x0013,0x0071},
-      {0x01e3,0x0070,0x01f3}
-    }
-  },
-  {
-    {
-      {0x07fe,0x01e7,0x07f3},
-      {0x01ef,0x0060,0x01ee},
-      {0x07f0,0x01e2,0x07fa}
-    },
-    {
-      {0x03f3,0x006a,0x01e8},
-      {0x0075,0x0010,0x0073},
-      {0x01f4,0x006e,0x03f7}
-    },
-    {
-      {0x07f6,0x01e0,0x07f9},
-      {0x03f2,0x0066,0x01f5},
-      {0x07ff,0x01f7,0x07f4}
-    }
-  }
-};
-
-const UWord16 huff_ctab2[3][3][3][3]=
-{
-  {
-    {
-      {0x01f3,0x006f,0x01fd},
-      {0x00eb,0x0023,0x00ea},
-      {0x01f7,0x00e8,0x01fa}
-    },
-    {
-      {0x00f2,0x002d,0x0070},
-      {0x0020,0x0006,0x002b},
-      {0x006e,0x0028,0x00e9}
-    },
-    {
-      {0x01f9,0x0066,0x00f8},
-      {0x00e7,0x001b,0x00f1},
-      {0x01f4,0x006b,0x01f5}
-    }
-  },
-  {
-    {
-      {0x00ec,0x002a,0x006c},
-      {0x002c,0x000a,0x0027},
-      {0x0067,0x001a,0x00f5}
-    },
-    {
-      {0x0024,0x0008,0x001f},
-      {0x0009,0x0000,0x0007},
-      {0x001d,0x000b,0x0030}
-    },
-    {
-      {0x00ef,0x001c,0x0064},
-      {0x001e,0x000c,0x0029},
-      {0x00f3,0x002f,0x00f0}
-    }
-  },
-  {
-    {
-      {0x01fc,0x0071,0x01f2},
-      {0x00f4,0x0021,0x00e6},
-      {0x00f7,0x0068,0x01f8}
-    },
-    {
-      {0x00ee,0x0022,0x0065},
-      {0x0031,0x0002,0x0026},
-      {0x00ed,0x0025,0x006a}
-    },
-    {
-      {0x01fb,0x0072,0x01fe},
-      {0x0069,0x002e,0x00f6},
-      {0x01ff,0x006d,0x01f6}
-    }
-  }
-};
-
-const UWord16 huff_ctab3[3][3][3][3]=
-{
-  {
-    {
-      {0x0000,0x0009,0x00ef},
-      {0x000b,0x0019,0x00f0},
-      {0x01eb,0x01e6,0x03f2}
-    },
-    {
-      {0x000a,0x0035,0x01ef},
-      {0x0034,0x0037,0x01e9},
-      {0x01ed,0x01e7,0x03f3}
-    },
-    {
-      {0x01ee,0x03ed,0x1ffa},
-      {0x01ec,0x01f2,0x07f9},
-      {0x07f8,0x03f8,0x0ff8}
-    }
-  },
-  {
-    {
-      {0x0008,0x0038,0x03f6},
-      {0x0036,0x0075,0x03f1},
-      {0x03eb,0x03ec,0x0ff4}
-    },
-    {
-      {0x0018,0x0076,0x07f4},
-      {0x0039,0x0074,0x03ef},
-      {0x01f3,0x01f4,0x07f6}
-    },
-    {
-      {0x01e8,0x03ea,0x1ffc},
-      {0x00f2,0x01f1,0x0ffb},
-      {0x03f5,0x07f3,0x0ffc}
-    }
-  },
-  {
-    {
-      {0x00ee,0x03f7,0x7ffe},
-      {0x01f0,0x07f5,0x7ffd},
-      {0x1ffb,0x3ffa,0xffff}
-    },
-    {
-      {0x00f1,0x03f0,0x3ffc},
-      {0x01ea,0x03ee,0x3ffb},
-      {0x0ff6,0x0ffa,0x7ffc}
-    },
-    {
-      {0x07f2,0x0ff5,0xfffe},
-      {0x03f4,0x07f7,0x7ffb},
-      {0x0ff7,0x0ff9,0x7ffa}
-    }
-  }
-};
-
-const UWord16 huff_ctab4[3][3][3][3]=
-{
-  {
-    {
-      {0x0007,0x0016,0x00f6},
-      {0x0018,0x0008,0x00ef},
-      {0x01ef,0x00f3,0x07f8}
-    },
-    {
-      {0x0019,0x0017,0x00ed},
-      {0x0015,0x0001,0x00e2},
-      {0x00f0,0x0070,0x03f0}
-    },
-    {
-      {0x01ee,0x00f1,0x07fa},
-      {0x00ee,0x00e4,0x03f2},
-      {0x07f6,0x03ef,0x07fd}
-    }
-  },
-  {
-    {
-      {0x0005,0x0014,0x00f2},
-      {0x0009,0x0004,0x00e5},
-      {0x00f4,0x00e8,0x03f4}
-    },
-    {
-      {0x0006,0x0002,0x00e7},
-      {0x0003,0x0000,0x006b},
-      {0x00e3,0x0069,0x01f3}
-    },
-    {
-      {0x00eb,0x00e6,0x03f6},
-      {0x006e,0x006a,0x01f4},
-      {0x03ec,0x01f0,0x03f9}
-    }
-  },
-  {
-    {
-      {0x00f5,0x00ec,0x07fb},
-      {0x00ea,0x006f,0x03f7},
-      {0x07f9,0x03f3,0x0fff}
-    },
-    {
-      {0x00e9,0x006d,0x03f8},
-      {0x006c,0x0068,0x01f5},
-      {0x03ee,0x01f2,0x07f4}
-    },
-    {
-      {0x07f7,0x03f1,0x0ffe},
-      {0x03ed,0x01f1,0x07f5},
-      {0x07fe,0x03f5,0x07fc}
-    }
-  }
-};
-const UWord16 huff_ctab5[9][9]=
-{
-  {0x1fff,0x0ff7,0x07f4,0x07e8,0x03f1,0x07ee,0x07f9,0x0ff8,0x1ffd},
-  {0x0ffd,0x07f1,0x03e8,0x01e8,0x00f0,0x01ec,0x03ee,0x07f2,0x0ffa},
-  {0x0ff4,0x03ef,0x01f2,0x00e8,0x0070,0x00ec,0x01f0,0x03ea,0x07f3},
-  {0x07eb,0x01eb,0x00ea,0x001a,0x0008,0x0019,0x00ee,0x01ef,0x07ed},
-  {0x03f0,0x00f2,0x0073,0x000b,0x0000,0x000a,0x0071,0x00f3,0x07e9},
-  {0x07ef,0x01ee,0x00ef,0x0018,0x0009,0x001b,0x00eb,0x01e9,0x07ec},
-  {0x07f6,0x03eb,0x01f3,0x00ed,0x0072,0x00e9,0x01f1,0x03ed,0x07f7},
-  {0x0ff6,0x07f0,0x03e9,0x01ed,0x00f1,0x01ea,0x03ec,0x07f8,0x0ff9},
-  {0x1ffc,0x0ffc,0x0ff5,0x07ea,0x03f3,0x03f2,0x07f5,0x0ffb,0x1ffe}
-};
-
-const UWord16 huff_ctab6[9][9]=
-{
-  {0x07fe,0x03fd,0x01f1,0x01eb,0x01f4,0x01ea,0x01f0,0x03fc,0x07fd},
-  {0x03f6,0x01e5,0x00ea,0x006c,0x0071,0x0068,0x00f0,0x01e6,0x03f7},
-  {0x01f3,0x00ef,0x0032,0x0027,0x0028,0x0026,0x0031,0x00eb,0x01f7},
-  {0x01e8,0x006f,0x002e,0x0008,0x0004,0x0006,0x0029,0x006b,0x01ee},
-  {0x01ef,0x0072,0x002d,0x0002,0x0000,0x0003,0x002f,0x0073,0x01fa},
-  {0x01e7,0x006e,0x002b,0x0007,0x0001,0x0005,0x002c,0x006d,0x01ec},
-  {0x01f9,0x00ee,0x0030,0x0024,0x002a,0x0025,0x0033,0x00ec,0x01f2},
-  {0x03f8,0x01e4,0x00ed,0x006a,0x0070,0x0069,0x0074,0x00f1,0x03fa},
-  {0x07ff,0x03f9,0x01f6,0x01ed,0x01f8,0x01e9,0x01f5,0x03fb,0x07fc}
-};
-
-const UWord16 huff_ctab7[8][8]=
-{
-  {0x0000,0x0005,0x0037,0x0074,0x00f2,0x01eb,0x03ed,0x07f7},
-  {0x0004,0x000c,0x0035,0x0071,0x00ec,0x00ee,0x01ee,0x01f5},
-  {0x0036,0x0034,0x0072,0x00ea,0x00f1,0x01e9,0x01f3,0x03f5},
-  {0x0073,0x0070,0x00eb,0x00f0,0x01f1,0x01f0,0x03ec,0x03fa},
-  {0x00f3,0x00ed,0x01e8,0x01ef,0x03ef,0x03f1,0x03f9,0x07fb},
-  {0x01ed,0x00ef,0x01ea,0x01f2,0x03f3,0x03f8,0x07f9,0x07fc},
-  {0x03ee,0x01ec,0x01f4,0x03f4,0x03f7,0x07f8,0x0ffd,0x0ffe},
-  {0x07f6,0x03f0,0x03f2,0x03f6,0x07fa,0x07fd,0x0ffc,0x0fff}
-};
-
-const UWord16 huff_ctab8[8][8]=
-{
-  {0x000e,0x0005,0x0010,0x0030,0x006f,0x00f1,0x01fa,0x03fe},
-  {0x0003,0x0000,0x0004,0x0012,0x002c,0x006a,0x0075,0x00f8},
-  {0x000f,0x0002,0x0006,0x0014,0x002e,0x0069,0x0072,0x00f5},
-  {0x002f,0x0011,0x0013,0x002a,0x0032,0x006c,0x00ec,0x00fa},
-  {0x0071,0x002b,0x002d,0x0031,0x006d,0x0070,0x00f2,0x01f9},
-  {0x00ef,0x0068,0x0033,0x006b,0x006e,0x00ee,0x00f9,0x03fc},
-  {0x01f8,0x0074,0x0073,0x00ed,0x00f0,0x00f6,0x01f6,0x01fd},
-  {0x03fd,0x00f3,0x00f4,0x00f7,0x01f7,0x01fb,0x01fc,0x03ff}
-};
-
-const UWord16 huff_ctab9[13][13]=
-{
-  {0x0000,0x0005,0x0037,0x00e7,0x01de,0x03ce,0x03d9,0x07c8,0x07cd,0x0fc8,0x0fdd,0x1fe4,0x1fec},
-  {0x0004,0x000c,0x0035,0x0072,0x00ea,0x00ed,0x01e2,0x03d1,0x03d3,0x03e0,0x07d8,0x0fcf,0x0fd5},
-  {0x0036,0x0034,0x0071,0x00e8,0x00ec,0x01e1,0x03cf,0x03dd,0x03db,0x07d0,0x0fc7,0x0fd4,0x0fe4},
-  {0x00e6,0x0070,0x00e9,0x01dd,0x01e3,0x03d2,0x03dc,0x07cc,0x07ca,0x07de,0x0fd8,0x0fea,0x1fdb},
-  {0x01df,0x00eb,0x01dc,0x01e6,0x03d5,0x03de,0x07cb,0x07dd,0x07dc,0x0fcd,0x0fe2,0x0fe7,0x1fe1},
-  {0x03d0,0x01e0,0x01e4,0x03d6,0x07c5,0x07d1,0x07db,0x0fd2,0x07e0,0x0fd9,0x0feb,0x1fe3,0x1fe9},
-  {0x07c4,0x01e5,0x03d7,0x07c6,0x07cf,0x07da,0x0fcb,0x0fda,0x0fe3,0x0fe9,0x1fe6,0x1ff3,0x1ff7},
-  {0x07d3,0x03d8,0x03e1,0x07d4,0x07d9,0x0fd3,0x0fde,0x1fdd,0x1fd9,0x1fe2,0x1fea,0x1ff1,0x1ff6},
-  {0x07d2,0x03d4,0x03da,0x07c7,0x07d7,0x07e2,0x0fce,0x0fdb,0x1fd8,0x1fee,0x3ff0,0x1ff4,0x3ff2},
-  {0x07e1,0x03df,0x07c9,0x07d6,0x0fca,0x0fd0,0x0fe5,0x0fe6,0x1feb,0x1fef,0x3ff3,0x3ff4,0x3ff5},
-  {0x0fe0,0x07ce,0x07d5,0x0fc6,0x0fd1,0x0fe1,0x1fe0,0x1fe8,0x1ff0,0x3ff1,0x3ff8,0x3ff6,0x7ffc},
-  {0x0fe8,0x07df,0x0fc9,0x0fd7,0x0fdc,0x1fdc,0x1fdf,0x1fed,0x1ff5,0x3ff9,0x3ffb,0x7ffd,0x7ffe},
-  {0x1fe7,0x0fcc,0x0fd6,0x0fdf,0x1fde,0x1fda,0x1fe5,0x1ff2,0x3ffa,0x3ff7,0x3ffc,0x3ffd,0x7fff}
-};
-
-const UWord16 huff_ctab10[13][13]=
-{
-  {0x0022,0x0008,0x001d,0x0026,0x005f,0x00d3,0x01cf,0x03d0,0x03d7,0x03ed,0x07f0,0x07f6,0x0ffd},
-  {0x0007,0x0000,0x0001,0x0009,0x0020,0x0054,0x0060,0x00d5,0x00dc,0x01d4,0x03cd,0x03de,0x07e7},
-  {0x001c,0x0002,0x0006,0x000c,0x001e,0x0028,0x005b,0x00cd,0x00d9,0x01ce,0x01dc,0x03d9,0x03f1},
-  {0x0025,0x000b,0x000a,0x000d,0x0024,0x0057,0x0061,0x00cc,0x00dd,0x01cc,0x01de,0x03d3,0x03e7},
-  {0x005d,0x0021,0x001f,0x0023,0x0027,0x0059,0x0064,0x00d8,0x00df,0x01d2,0x01e2,0x03dd,0x03ee},
-  {0x00d1,0x0055,0x0029,0x0056,0x0058,0x0062,0x00ce,0x00e0,0x00e2,0x01da,0x03d4,0x03e3,0x07eb},
-  {0x01c9,0x005e,0x005a,0x005c,0x0063,0x00ca,0x00da,0x01c7,0x01ca,0x01e0,0x03db,0x03e8,0x07ec},
-  {0x01e3,0x00d2,0x00cb,0x00d0,0x00d7,0x00db,0x01c6,0x01d5,0x01d8,0x03ca,0x03da,0x07ea,0x07f1},
-  {0x01e1,0x00d4,0x00cf,0x00d6,0x00de,0x00e1,0x01d0,0x01d6,0x03d1,0x03d5,0x03f2,0x07ee,0x07fb},
-  {0x03e9,0x01cd,0x01c8,0x01cb,0x01d1,0x01d7,0x01df,0x03cf,0x03e0,0x03ef,0x07e6,0x07f8,0x0ffa},
-  {0x03eb,0x01dd,0x01d3,0x01d9,0x01db,0x03d2,0x03cc,0x03dc,0x03ea,0x07ed,0x07f3,0x07f9,0x0ff9},
-  {0x07f2,0x03ce,0x01e4,0x03cb,0x03d8,0x03d6,0x03e2,0x03e5,0x07e8,0x07f4,0x07f5,0x07f7,0x0ffb},
-  {0x07fa,0x03ec,0x03df,0x03e1,0x03e4,0x03e6,0x03f0,0x07e9,0x07ef,0x0ff8,0x0ffe,0x0ffc,0x0fff}
-};
-
-const UWord16 huff_ctab11[17][17]=
-{
-  {0x0000,0x0006,0x0019,0x003d,0x009c,0x00c6,0x01a7,0x0390,0x03c2,0x03df,0x07e6,0x07f3,0x0ffb,0x07ec,0x0ffa,0x0ffe,0x038e},
-  {0x0005,0x0001,0x0008,0x0014,0x0037,0x0042,0x0092,0x00af,0x0191,0x01a5,0x01b5,0x039e,0x03c0,0x03a2,0x03cd,0x07d6,0x00ae},
-  {0x0017,0x0007,0x0009,0x0018,0x0039,0x0040,0x008e,0x00a3,0x00b8,0x0199,0x01ac,0x01c1,0x03b1,0x0396,0x03be,0x03ca,0x009d},
-  {0x003c,0x0015,0x0016,0x001a,0x003b,0x0044,0x0091,0x00a5,0x00be,0x0196,0x01ae,0x01b9,0x03a1,0x0391,0x03a5,0x03d5,0x0094},
-  {0x009a,0x0036,0x0038,0x003a,0x0041,0x008c,0x009b,0x00b0,0x00c3,0x019e,0x01ab,0x01bc,0x039f,0x038f,0x03a9,0x03cf,0x0093},
-  {0x00bf,0x003e,0x003f,0x0043,0x0045,0x009e,0x00a7,0x00b9,0x0194,0x01a2,0x01ba,0x01c3,0x03a6,0x03a7,0x03bb,0x03d4,0x009f},
-  {0x01a0,0x008f,0x008d,0x0090,0x0098,0x00a6,0x00b6,0x00c4,0x019f,0x01af,0x01bf,0x0399,0x03bf,0x03b4,0x03c9,0x03e7,0x00a8},
-  {0x01b6,0x00ab,0x00a4,0x00aa,0x00b2,0x00c2,0x00c5,0x0198,0x01a4,0x01b8,0x038c,0x03a4,0x03c4,0x03c6,0x03dd,0x03e8,0x00ad},
-  {0x03af,0x0192,0x00bd,0x00bc,0x018e,0x0197,0x019a,0x01a3,0x01b1,0x038d,0x0398,0x03b7,0x03d3,0x03d1,0x03db,0x07dd,0x00b4},
-  {0x03de,0x01a9,0x019b,0x019c,0x01a1,0x01aa,0x01ad,0x01b3,0x038b,0x03b2,0x03b8,0x03ce,0x03e1,0x03e0,0x07d2,0x07e5,0x00b7},
-  {0x07e3,0x01bb,0x01a8,0x01a6,0x01b0,0x01b2,0x01b7,0x039b,0x039a,0x03ba,0x03b5,0x03d6,0x07d7,0x03e4,0x07d8,0x07ea,0x00ba},
-  {0x07e8,0x03a0,0x01bd,0x01b4,0x038a,0x01c4,0x0392,0x03aa,0x03b0,0x03bc,0x03d7,0x07d4,0x07dc,0x07db,0x07d5,0x07f0,0x00c1},
-  {0x07fb,0x03c8,0x03a3,0x0395,0x039d,0x03ac,0x03ae,0x03c5,0x03d8,0x03e2,0x03e6,0x07e4,0x07e7,0x07e0,0x07e9,0x07f7,0x0190},
-  {0x07f2,0x0393,0x01be,0x01c0,0x0394,0x0397,0x03ad,0x03c3,0x03c1,0x03d2,0x07da,0x07d9,0x07df,0x07eb,0x07f4,0x07fa,0x0195},
-  {0x07f8,0x03bd,0x039c,0x03ab,0x03a8,0x03b3,0x03b9,0x03d0,0x03e3,0x03e5,0x07e2,0x07de,0x07ed,0x07f1,0x07f9,0x07fc,0x0193},
-  {0x0ffd,0x03dc,0x03b6,0x03c7,0x03cc,0x03cb,0x03d9,0x03da,0x07d3,0x07e1,0x07ee,0x07ef,0x07f5,0x07f6,0x0ffc,0x0fff,0x019d},
-  {0x01c2,0x00b5,0x00a1,0x0096,0x0097,0x0095,0x0099,0x00a0,0x00a2,0x00ac,0x00a9,0x00b1,0x00b3,0x00bb,0x00c0,0x018f,0x0004}
-};
-
-const UWord32 huff_ctabscf[121]=
-{
-  0x0003ffe8,
-  0x0003ffe6,
-  0x0003ffe7,
-  0x0003ffe5,
-  0x0007fff5,
-  0x0007fff1,
-  0x0007ffed,
-  0x0007fff6,
-  0x0007ffee,
-  0x0007ffef,
-  0x0007fff0,
-  0x0007fffc,
-  0x0007fffd,
-  0x0007ffff,
-  0x0007fffe,
-  0x0007fff7,
-  0x0007fff8,
-  0x0007fffb,
-  0x0007fff9,
-  0x0003ffe4,
-  0x0007fffa,
-  0x0003ffe3,
-  0x0001ffef,
-  0x0001fff0,
-  0x0000fff5,
-  0x0001ffee,
-  0x0000fff2,
-  0x0000fff3,
-  0x0000fff4,
-  0x0000fff1,
-  0x00007ff6,
-  0x00007ff7,
-  0x00003ff9,
-  0x00003ff5,
-  0x00003ff7,
-  0x00003ff3,
-  0x00003ff6,
-  0x00003ff2,
-  0x00001ff7,
-  0x00001ff5,
-  0x00000ff9,
-  0x00000ff7,
-  0x00000ff6,
-  0x000007f9,
-  0x00000ff4,
-  0x000007f8,
-  0x000003f9,
-  0x000003f7,
-  0x000003f5,
-  0x000001f8,
-  0x000001f7,
-  0x000000fa,
-  0x000000f8,
-  0x000000f6,
-  0x00000079,
-  0x0000003a,
-  0x00000038,
-  0x0000001a,
-  0x0000000b,
-  0x00000004,
-  0x00000000,
-  0x0000000a,
-  0x0000000c,
-  0x0000001b,
-  0x00000039,
-  0x0000003b,
-  0x00000078,
-  0x0000007a,
-  0x000000f7,
-  0x000000f9,
-  0x000001f6,
-  0x000001f9,
-  0x000003f4,
-  0x000003f6,
-  0x000003f8,
-  0x000007f5,
-  0x000007f4,
-  0x000007f6,
-  0x000007f7,
-  0x00000ff5,
-  0x00000ff8,
-  0x00001ff4,
-  0x00001ff6,
-  0x00001ff8,
-  0x00003ff8,
-  0x00003ff4,
-  0x0000fff0,
-  0x00007ff4,
-  0x0000fff6,
-  0x00007ff5,
-  0x0003ffe2,
-  0x0007ffd9,
-  0x0007ffda,
-  0x0007ffdb,
-  0x0007ffdc,
-  0x0007ffdd,
-  0x0007ffde,
-  0x0007ffd8,
-  0x0007ffd2,
-  0x0007ffd3,
-  0x0007ffd4,
-  0x0007ffd5,
-  0x0007ffd6,
-  0x0007fff2,
-  0x0007ffdf,
-  0x0007ffe7,
-  0x0007ffe8,
-  0x0007ffe9,
-  0x0007ffea,
-  0x0007ffeb,
-  0x0007ffe6,
-  0x0007ffe0,
-  0x0007ffe1,
-  0x0007ffe2,
-  0x0007ffe3,
-  0x0007ffe4,
-  0x0007ffe5,
-  0x0007ffd7,
-  0x0007ffec,
-  0x0007fff4,
-  0x0007fff3
-};
-
-const Word32 m_log2_table[INT_BITS] = {
-  0x00000000,0x4ae00d00,0x2934f080,0x15c01a3f,
-  0x0b31fb80,0x05aeb4e0,0x02dcf2d0,0x016fe50c,
-  0x00b84e23,0x005c3e10,0x002e24ca,0x001713d6,
-  0x000b8a47,0x0005c53b,0x0002e2a3,0x00017153,
-  0x0000b8aa,0x00005c55,0x00002e2b,0x00001715,
-  0x00000b8b,0x000005c5,0x000002e3,0x00000171,
-  0x000000b9,0x0000005c,0x0000002e,0x00000017,
-  0x0000000c,0x00000006,0x00000003,0x00000001
-};
-
-
-/*
-  3 bit resolution
-*/
-const Word32 tnsCoeff3[8] =
-{
-  0x81f1d1d4,
-  0x9126147c,
-  0xadb922f7,
-  0xd438af09,
-  0x00000000,
-  0x37898087,
-  0x64130dfa,
-  0x7cca6ffb,
-};
-
-const Word32 tnsCoeff3Borders[8] =
-{
-  0x80000000,  /* -4 */
-  0x87b826de,  /* -3 */
-  0x9df24153,  /* -2 */
-  0xbfffffe5,  /* -1 */
-  0xe9c5e578,  /*  0 */
-  0x1c7b90f0,  /*  1 */
-  0x4fce83aa,  /*  2 */
-  0x7352f2c4,  /*  3 */
-};
-
-
-/*
-  4 bit resolution
-*/
-
-const Word32 tnsCoeff4[16] =
-{
-  0x808bc84b,
-  0x84e2e57d,
-  0x8d6b49fb,
-  0x99da9207,
-  0xa9c45707,
-  0xbc9dde78,
-  0xd1c2d4fc,
-  0xe87ae539,
-  0x00000000,
-  0x1a9cd9c0,
-  0x340ff23b,
-  0x4b3c8bf7,
-  0x5f1f5e80,
-  0x6ed9eb84,
-  0x79bc3880,
-  0x7f4c7e89
-};
-
-const Word32 tnsCoeff4Borders[16]=
-{
-  0x80000000,  /* -8 */
-  0x822defef,  /* -7 */
-  0x88a4bfe5,  /* -6 */
-  0x932c159c,  /* -5 */
-  0xa16827c1,  /* -4 */
-  0xb2dcde26,  /* -3 */
-  0xc6f20b91,  /* -2 */
-  0xdcf89c64,  /* -1 */
-  0xf4308ce1,  /*  0 */
-  0x0d613054,  /*  1 */
-  0x278dde80,  /*  2 */
-  0x4000001b,  /*  3 */
-  0x55a6127c,  /*  4 */
-  0x678dde8f,  /*  5 */
-  0x74ef0ed8,  /*  6 */
-  0x7d33f0db   /*  7 */
-};
-
-
-const unsigned char bitrevTab[17 + 129] =
-{
-/* 64 */
-0x01, 0x08, 0x02, 0x04, 0x03, 0x0c, 0x05, 0x0a, 0x07, 0x0e, 0x0b, 0x0d, 0x00, 0x06, 0x09, 0x0f,
-0x00,
-
-/* 512 */
-0x01, 0x40, 0x02, 0x20, 0x03, 0x60, 0x04, 0x10, 0x05, 0x50, 0x06, 0x30, 0x07, 0x70, 0x09, 0x48,
-0x0a, 0x28, 0x0b, 0x68, 0x0c, 0x18, 0x0d, 0x58, 0x0e, 0x38, 0x0f, 0x78, 0x11, 0x44, 0x12, 0x24,
-0x13, 0x64, 0x15, 0x54, 0x16, 0x34, 0x17, 0x74, 0x19, 0x4c, 0x1a, 0x2c, 0x1b, 0x6c, 0x1d, 0x5c,
-0x1e, 0x3c, 0x1f, 0x7c, 0x21, 0x42, 0x23, 0x62, 0x25, 0x52, 0x26, 0x32, 0x27, 0x72, 0x29, 0x4a,
-0x2b, 0x6a, 0x2d, 0x5a, 0x2e, 0x3a, 0x2f, 0x7a, 0x31, 0x46, 0x33, 0x66, 0x35, 0x56, 0x37, 0x76,
-0x39, 0x4e, 0x3b, 0x6e, 0x3d, 0x5e, 0x3f, 0x7e, 0x43, 0x61, 0x45, 0x51, 0x47, 0x71, 0x4b, 0x69,
-0x4d, 0x59, 0x4f, 0x79, 0x53, 0x65, 0x57, 0x75, 0x5b, 0x6d, 0x5f, 0x7d, 0x67, 0x73, 0x6f, 0x7b,
-0x00, 0x08, 0x14, 0x1c, 0x22, 0x2a, 0x36, 0x3e, 0x41, 0x49, 0x55, 0x5d, 0x63, 0x6b, 0x77, 0x7f,
-0x00,
-};
diff --git a/media/libstagefright/codecs/aacenc/src/aacenc.c b/media/libstagefright/codecs/aacenc/src/aacenc.c
deleted file mode 100644
index df17787..0000000
--- a/media/libstagefright/codecs/aacenc/src/aacenc.c
+++ /dev/null
@@ -1,505 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		aacenc.c
-
-	Content:	aac encoder interface functions
-
-*******************************************************************************/
-
-#include "voAAC.h"
-#include "typedef.h"
-#include "aacenc_core.h"
-#include "aac_rom.h"
-#include "cmnMemory.h"
-#include "memalign.h"
-
-#define UNUSED(x) (void)(x)
-
-/**
-* Init the audio codec module and return codec handle
-* \param phCodec [OUT] Return the video codec handle
-* \param vType	[IN] The codec type if the module support multi codec.
-* \param pUserData	[IN] The init param. It is memory operator or alloced memory
-* \retval VO_ERR_NONE Succeeded.
-*/
-VO_U32 VO_API voAACEncInit(VO_HANDLE * phCodec,VO_AUDIO_CODINGTYPE vType, VO_CODEC_INIT_USERDATA *pUserData)
-{
-	AAC_ENCODER*hAacEnc;
-	int error;
-
-#ifdef USE_DEAULT_MEM
-	VO_MEM_OPERATOR voMemoprator;
-#endif
-	VO_MEM_OPERATOR *pMemOP;
-
-#ifdef USE_DEAULT_MEM
-	int interMem;
-        interMem = 0;
-#endif
-
-        UNUSED(vType);
-
-	error = 0;
-
-	/* init the memory operator */
-	if(pUserData == NULL || pUserData->memflag != VO_IMF_USERMEMOPERATOR || pUserData->memData == NULL )
-	{
-#ifdef USE_DEAULT_MEM
-		voMemoprator.Alloc = cmnMemAlloc;
-		voMemoprator.Copy = cmnMemCopy;
-		voMemoprator.Free = cmnMemFree;
-		voMemoprator.Set = cmnMemSet;
-		voMemoprator.Check = cmnMemCheck;
-
-		interMem = 1;
-
-		pMemOP = &voMemoprator;
-#else
-		*phCodec = NULL;
-		return VO_ERR_INVALID_ARG;
-#endif
-	}
-	else
-	{
-		pMemOP = (VO_MEM_OPERATOR *)pUserData->memData;
-	}
-
-	/* init the aac encoder handle */
-	hAacEnc = (AAC_ENCODER*)mem_malloc(pMemOP, sizeof(AAC_ENCODER), 32, VO_INDEX_ENC_AAC);
-	if(NULL == hAacEnc)
-	{
-		error = 1;
-	}
-
-	if(!error)
-	{
-		/* init the aac encoder intra memory */
-		hAacEnc->intbuf = (short *)mem_malloc(pMemOP, AACENC_BLOCKSIZE*MAX_CHANNELS*sizeof(short), 32, VO_INDEX_ENC_AAC);
-		if(NULL == hAacEnc->intbuf)
-		{
-			error = 1;
-		}
-	}
-
-	if (!error) {
-		/* init the aac encoder psychoacoustic */
-		error = (PsyNew(&hAacEnc->psyKernel, MAX_CHANNELS, pMemOP) ||
-			PsyOutNew(&hAacEnc->psyOut, pMemOP));
-	}
-
-	if (!error) {
-		/* init the aac encoder quantization elements */
-		error = QCOutNew(&hAacEnc->qcOut,MAX_CHANNELS, pMemOP);
-	}
-
-	if (!error) {
-		/* init the aac encoder quantization state */
-		error = QCNew(&hAacEnc->qcKernel, pMemOP);
-	}
-
-	/* uninit the aac encoder if error is nozero */
-	if(error)
-	{
-		AacEncClose(hAacEnc, pMemOP);
-		if(hAacEnc)
-		{
-			mem_free(pMemOP, hAacEnc, VO_INDEX_ENC_AAC);
-			hAacEnc = NULL;
-		}
-		*phCodec = NULL;
-		return VO_ERR_OUTOF_MEMORY;
-	}
-
-	/* init the aac encoder memory operator  */
-#ifdef USE_DEAULT_MEM
-	if(interMem)
-	{
-		hAacEnc->voMemoprator.Alloc = cmnMemAlloc;
-		hAacEnc->voMemoprator.Copy = cmnMemCopy;
-		hAacEnc->voMemoprator.Free = cmnMemFree;
-		hAacEnc->voMemoprator.Set = cmnMemSet;
-		hAacEnc->voMemoprator.Check = cmnMemCheck;
-
-		pMemOP = &hAacEnc->voMemoprator;
-	}
-#endif
-	/* init the aac encoder default parameter  */
-	if(hAacEnc->initOK == 0)
-	{
-		 AACENC_CONFIG config;
-		 config.adtsUsed = 1;
-		 config.bitRate = 128000;
-		 config.nChannelsIn = 2;
-		 config.nChannelsOut = 2;
-		 config.sampleRate = 44100;
-		 config.bandWidth = 20000;
-
-		 AacEncOpen(hAacEnc, config);
-	}
-
-	hAacEnc->voMemop = pMemOP;
-
-	*phCodec = hAacEnc;
-
-	return VO_ERR_NONE;
-}
-
-/**
-* Set input audio data.
-* \param hCodec [IN]] The Codec Handle which was created by Init function.
-* \param pInput [IN] The input buffer param.
-* \param pOutBuffer [OUT] The output buffer info.
-* \retval VO_ERR_NONE Succeeded.
-*/
-VO_U32 VO_API voAACEncSetInputData(VO_HANDLE hCodec, VO_CODECBUFFER * pInput)
-{
-	AAC_ENCODER *hAacEnc;
-	int  length;
-
-	if(NULL == hCodec || NULL == pInput || NULL == pInput->Buffer)
-	{
-		return VO_ERR_INVALID_ARG;
-	}
-
-	hAacEnc = (AAC_ENCODER *)hCodec;
-
-	/* init input pcm buffer and length*/
-	hAacEnc->inbuf = (short *)pInput->Buffer;
-	hAacEnc->inlen = pInput->Length / sizeof(short);
-	hAacEnc->uselength = 0;
-
-	hAacEnc->encbuf = hAacEnc->inbuf;
-	hAacEnc->enclen = hAacEnc->inlen;
-
-	/* rebuild intra pcm buffer and length*/
-	if(hAacEnc->intlen)
-	{
-		length = min(hAacEnc->config.nChannelsIn*AACENC_BLOCKSIZE - hAacEnc->intlen, hAacEnc->inlen);
-		hAacEnc->voMemop->Copy(VO_INDEX_ENC_AAC, hAacEnc->intbuf + hAacEnc->intlen,
-			hAacEnc->inbuf, length*sizeof(short));
-
-		hAacEnc->encbuf = hAacEnc->intbuf;
-		hAacEnc->enclen = hAacEnc->intlen + length;
-
-		hAacEnc->inbuf += length;
-		hAacEnc->inlen -= length;
-	}
-
-	return VO_ERR_NONE;
-}
-
-/**
-* Get the outut audio data
-* \param hCodec [IN]] The Codec Handle which was created by Init function.
-* \param pOutBuffer [OUT] The output audio data
-* \param pOutInfo [OUT] The dec module filled audio format and used the input size.
-*						 pOutInfo->InputUsed is total used the input size.
-* \retval  VO_ERR_NONE Succeeded.
-*			VO_ERR_INPUT_BUFFER_SMALL. The input was finished or the input data was not enought.
-*/
-VO_U32 VO_API voAACEncGetOutputData(VO_HANDLE hCodec, VO_CODECBUFFER * pOutput, VO_AUDIO_OUTPUTINFO * pOutInfo)
-{
-	AAC_ENCODER* hAacEnc = (AAC_ENCODER*)hCodec;
-	Word16 numAncDataBytes=0;
-	Word32  inbuflen;
-	int length;
-	if(NULL == hAacEnc)
-		return VO_ERR_INVALID_ARG;
-
-	 inbuflen = AACENC_BLOCKSIZE*hAacEnc->config.nChannelsIn;
-
-	 /* check the input pcm buffer and length*/
-	 if(NULL == hAacEnc->encbuf || hAacEnc->enclen < inbuflen)
-	 {
-		length = hAacEnc->enclen;
-		if(hAacEnc->intlen == 0)
-		{
-			hAacEnc->voMemop->Copy(VO_INDEX_ENC_AAC, hAacEnc->intbuf,
-				hAacEnc->encbuf, length*sizeof(short));
-			hAacEnc->uselength += length*sizeof(short);
-		}
-		else
-		{
-			hAacEnc->uselength += (length - hAacEnc->intlen)*sizeof(short);
-		}
-
-		hAacEnc->intlen = length;
-
-		pOutput->Length = 0;
-		if(pOutInfo)
-			pOutInfo->InputUsed = hAacEnc->uselength;
-		return VO_ERR_INPUT_BUFFER_SMALL;
-	 }
-
-	 /* check the output aac buffer and length*/
-	 if(NULL == pOutput || NULL == pOutput->Buffer || pOutput->Length < (6144/8)*hAacEnc->config.nChannelsOut/(sizeof(Word32)))
-		 return VO_ERR_OUTPUT_BUFFER_SMALL;
-
-	 /* aac encoder core function */
-	 AacEncEncode( hAacEnc,
-			(Word16*)hAacEnc->encbuf,
-			NULL,
-			&numAncDataBytes,
-			pOutput->Buffer,
-			&pOutput->Length);
-
-	 /* update the input pcm buffer and length*/
-	 if(hAacEnc->intlen)
-	 {
-		length = inbuflen - hAacEnc->intlen;
-		hAacEnc->encbuf = hAacEnc->inbuf;
-		hAacEnc->enclen = hAacEnc->inlen;
-		hAacEnc->uselength += length*sizeof(short);
-		hAacEnc->intlen = 0;
-	 }
-	 else
-	 {
-		 hAacEnc->encbuf = hAacEnc->encbuf + inbuflen;
-		 hAacEnc->enclen = hAacEnc->enclen - inbuflen;
-		 hAacEnc->uselength += inbuflen*sizeof(short);
-	 }
-
-	 /* update the output aac information */
-	if(pOutInfo)
-	{
-		pOutInfo->Format.Channels = hAacEnc->config.nChannelsOut;
-		pOutInfo->Format.SampleRate = hAacEnc->config.sampleRate;
-		pOutInfo->Format.SampleBits = 16;
-		pOutInfo->InputUsed = hAacEnc->uselength;
-	}
-
-	 return VO_ERR_NONE;
-}
-
-/**
-* Uninit the Codec.
-* \param hCodec [IN]] The Codec Handle which was created by Init function.
-* \retval VO_ERR_NONE Succeeded.
-*/
-VO_U32 VO_API voAACEncUninit(VO_HANDLE hCodec)
-{
-	AAC_ENCODER* hAacEnc = (AAC_ENCODER*)hCodec;
-
-	if(NULL != hAacEnc)
-	{
-		/* close the aac encoder */
-		AacEncClose(hAacEnc, hAacEnc->voMemop);
-
-		/* free the aac encoder handle*/
-		mem_free(hAacEnc->voMemop, hAacEnc, VO_INDEX_ENC_AAC);
-		hAacEnc = NULL;
-	}
-
-	return VO_ERR_NONE;
-}
-
-/**
-* Set the param for special target.
-* \param hCodec [IN]] The Codec Handle which was created by Init function.
-* \param uParamID [IN] The param ID.
-* \param pData [IN] The param value depend on the ID>
-* \retval VO_ERR_NONE Succeeded.
-*/
-VO_U32 VO_API voAACEncSetParam(VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData)
-{
-	AACENC_CONFIG config;
-	AACENC_PARAM* pAAC_param;
-	VO_AUDIO_FORMAT *pWAV_Format;
-	AAC_ENCODER* hAacEnc = (AAC_ENCODER*)hCodec;
-	int ret, i, bitrate, tmp;
-	int SampleRateIdx;
-
-	if(NULL == hAacEnc)
-		return VO_ERR_INVALID_ARG;
-
-	switch(uParamID)
-	{
-	case VO_PID_AAC_ENCPARAM:  /* init aac encoder parameter*/
-		AacInitDefaultConfig(&config);
-		if(pData == NULL)
-			return VO_ERR_INVALID_ARG;
-		pAAC_param = (AACENC_PARAM*)pData;
-		config.adtsUsed = pAAC_param->adtsUsed;
-		config.bitRate = pAAC_param->bitRate;
-		config.nChannelsIn = pAAC_param->nChannels;
-		config.nChannelsOut = pAAC_param->nChannels;
-		config.sampleRate = pAAC_param->sampleRate;
-
-		/* check the channel */
-		if(config.nChannelsIn< 1  || config.nChannelsIn > MAX_CHANNELS  ||
-             config.nChannelsOut < 1 || config.nChannelsOut > MAX_CHANNELS || config.nChannelsIn < config.nChannelsOut)
-			 return VO_ERR_AUDIO_UNSCHANNEL;
-
-		/* check the samplerate */
-		ret = -1;
-		for(i = 0; i < NUM_SAMPLE_RATES; i++)
-		{
-			if(config.sampleRate == sampRateTab[i])
-			{
-				ret = 0;
-				break;
-			}
-		}
-		if(ret < 0)
-			return VO_ERR_AUDIO_UNSSAMPLERATE;
-
-		SampleRateIdx = i;
-
-		tmp = 441;
-		if(config.sampleRate%8000 == 0)
-			tmp =480;
-		/* check the bitrate */
-		if(config.bitRate!=0 && ((config.bitRate/config.nChannelsOut < 4000) ||
-           (config.bitRate/config.nChannelsOut > 160000) ||
-		   (config.bitRate > config.sampleRate*6*config.nChannelsOut)))
-		{
-			config.bitRate = 640*config.sampleRate/tmp*config.nChannelsOut;
-
-			if(config.bitRate/config.nChannelsOut < 4000)
-				config.bitRate = 4000 * config.nChannelsOut;
-			else if(config.bitRate > config.sampleRate*6*config.nChannelsOut)
-				config.bitRate = config.sampleRate*6*config.nChannelsOut;
-			else if(config.bitRate/config.nChannelsOut > 160000)
-				config.bitRate = config.nChannelsOut*160000;
-		}
-
-		/* check the bandwidth */
-		bitrate = config.bitRate / config.nChannelsOut;
-		bitrate = bitrate * tmp / config.sampleRate;
-
-		for (i = 0; rates[i]; i++)
-		{
-			if (rates[i] >= bitrate)
-				break;
-		}
-
-		config.bandWidth = BandwithCoefTab[i][SampleRateIdx];
-
-		/* init aac encoder core */
-		ret = AacEncOpen(hAacEnc, config);
-		if(ret)
-			return VO_ERR_AUDIO_UNSFEATURE;
-		break;
-	case VO_PID_AUDIO_FORMAT:	/* init pcm channel and samplerate*/
-		AacInitDefaultConfig(&config);
-		if(pData == NULL)
-			return VO_ERR_INVALID_ARG;
-		pWAV_Format = (VO_AUDIO_FORMAT*)pData;
-		config.adtsUsed = 1;
-		config.nChannelsIn = pWAV_Format->Channels;
-		config.nChannelsOut = pWAV_Format->Channels;
-		config.sampleRate = pWAV_Format->SampleRate;
-
-		/* check the channel */
-		if(config.nChannelsIn< 1  || config.nChannelsIn > MAX_CHANNELS  ||
-             config.nChannelsOut < 1 || config.nChannelsOut > MAX_CHANNELS || config.nChannelsIn < config.nChannelsOut)
-			 return VO_ERR_AUDIO_UNSCHANNEL;
-
-		/* check the samplebits */
-		if(pWAV_Format->SampleBits != 16)
-		{
-			return VO_ERR_AUDIO_UNSFEATURE;
-		}
-
-		/* check the samplerate */
-		ret = -1;
-		for(i = 0; i < NUM_SAMPLE_RATES; i++)
-		{
-			if(config.sampleRate == sampRateTab[i])
-			{
-				ret = 0;
-				break;
-			}
-		}
-		if(ret < 0)
-			return VO_ERR_AUDIO_UNSSAMPLERATE;
-
-		SampleRateIdx = i;
-
-		/* update the bitrates */
-		tmp = 441;
-		if(config.sampleRate%8000 == 0)
-			tmp =480;
-
-		config.bitRate = 640*config.sampleRate/tmp*config.nChannelsOut;
-
-		if(config.bitRate/config.nChannelsOut < 4000)
-			config.bitRate = 4000 * config.nChannelsOut;
-		else if(config.bitRate > config.sampleRate*6*config.nChannelsOut)
-			config.bitRate = config.sampleRate*6*config.nChannelsOut;
-		else if(config.bitRate/config.nChannelsOut > 160000)
-			config.bitRate = config.nChannelsOut*160000;
-
-		/* check the bandwidth */
-		bitrate = config.bitRate / config.nChannelsOut;
-		bitrate = bitrate * tmp / config.sampleRate;
-
-		for (i = 0; rates[i]; i++)
-		{
-			if (rates[i] >= bitrate)
-				break;
-		}
-
-		config.bandWidth = BandwithCoefTab[i][SampleRateIdx];
-
-		/* init aac encoder core */
-		ret = AacEncOpen(hAacEnc, config);
-		if(ret)
-			return VO_ERR_AUDIO_UNSFEATURE;
-		break;
-	default:
-		return VO_ERR_WRONG_PARAM_ID;
-	}
-
-	return VO_ERR_NONE;
-}
-
-/**
-* Get the param for special target.
-* \param hCodec [IN]] The Codec Handle which was created by Init function.
-* \param uParamID [IN] The param ID.
-* \param pData [IN] The param value depend on the ID>
-* \retval VO_ERR_NONE Succeeded.
-*/
-VO_U32 VO_API voAACEncGetParam(VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData)
-{
-        UNUSED(hCodec);
-        UNUSED(uParamID);
-        UNUSED(pData);
-
-	return VO_ERR_NONE;
-}
-
-/**
- * Get audio codec API interface
- * \param pEncHandle [out] Return the AAC Encoder handle.
- * \retval VO_ERR_OK Succeeded.
- */
-VO_S32 VO_API voGetAACEncAPI(VO_AUDIO_CODECAPI * pDecHandle)
-{
-	if(pDecHandle == NULL)
-		return VO_ERR_INVALID_ARG;
-
-	pDecHandle->Init = voAACEncInit;
-	pDecHandle->SetInputData = voAACEncSetInputData;
-	pDecHandle->GetOutputData = voAACEncGetOutputData;
-	pDecHandle->SetParam = voAACEncSetParam;
-	pDecHandle->GetParam = voAACEncGetParam;
-	pDecHandle->Uninit = voAACEncUninit;
-
-	return VO_ERR_NONE;
-}
diff --git a/media/libstagefright/codecs/aacenc/src/aacenc_core.c b/media/libstagefright/codecs/aacenc/src/aacenc_core.c
deleted file mode 100644
index de452d4..0000000
--- a/media/libstagefright/codecs/aacenc/src/aacenc_core.c
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		aacenc_core.c
-
-	Content:	aac encoder core functions
-
-*******************************************************************************/
-
-#include "typedef.h"
-#include "aacenc_core.h"
-#include "bitenc.h"
-
-#include "psy_configuration.h"
-#include "psy_main.h"
-#include "qc_main.h"
-#include "psy_main.h"
-#include "channel_map.h"
-#include "aac_rom.h"
-
-/********************************************************************************
-*
-* function name: AacInitDefaultConfig
-* description:  gives reasonable default configuration
-*
-**********************************************************************************/
-void AacInitDefaultConfig(AACENC_CONFIG *config)
-{
-  /* default configurations */
-  config->adtsUsed        = 1;
-  config->nChannelsIn     = 2;
-  config->nChannelsOut    = 2;
-  config->bitRate         = 128000;
-  config->bandWidth       = 0;
-}
-
-/********************************************************************************
-*
-* function name: AacEncOpen
-* description:  allocate and initialize a new encoder instance
-* returns:      0 if success
-*
-**********************************************************************************/
-Word16  AacEncOpen(  AAC_ENCODER*      hAacEnc,        /* pointer to an encoder handle, initialized on return */
-                     const  AACENC_CONFIG     config   /* pre-initialized config struct */
-                     )
-{
-  Word32 error = 0;
-  Word16 profile = 1;
-
-  ELEMENT_INFO *elInfo = NULL;
-
-  if (hAacEnc==0) {
-    error=1;
-  }
-
-  if (!error) {
-    hAacEnc->config = config;
-  }
-
-  if (!error) {
-    error = InitElementInfo (config.nChannelsOut,
-                             &hAacEnc->elInfo);
-  }
-
-  if (!error) {
-    elInfo = &hAacEnc->elInfo;
-  }
-
-  if (!error) {
-    /* use or not tns tool for long and short block */
-	 Word16 tnsMask=3;
-
-	/* init encoder psychoacoustic */
-    error = psyMainInit(&hAacEnc->psyKernel,
-                        config.sampleRate,
-                        config.bitRate,
-                        elInfo->nChannelsInEl,
-                        tnsMask,
-                        hAacEnc->config.bandWidth);
-  }
-
- /* use or not adts header */
-  if(!error) {
-	  hAacEnc->qcOut.qcElement.adtsUsed = config.adtsUsed;
-  }
-
-  /* init encoder quantization */
-  if (!error) {
-    struct QC_INIT qcInit;
-
-    /*qcInit.channelMapping = &hAacEnc->channelMapping;*/
-    qcInit.elInfo = &hAacEnc->elInfo;
-
-    qcInit.maxBits = (Word16) (MAXBITS_COEF*elInfo->nChannelsInEl);
-    qcInit.bitRes = qcInit.maxBits;
-    qcInit.averageBits = (Word16) ((config.bitRate * FRAME_LEN_LONG) / config.sampleRate);
-
-    qcInit.padding.paddingRest = config.sampleRate;
-
-    qcInit.meanPe = (Word16) ((10 * FRAME_LEN_LONG * hAacEnc->config.bandWidth) /
-                                              (config.sampleRate>>1));
-
-    qcInit.maxBitFac = (Word16) ((100 * (MAXBITS_COEF-MINBITS_COEF)* elInfo->nChannelsInEl)/
-                                                 (qcInit.averageBits?qcInit.averageBits:1));
-
-    qcInit.bitrate = config.bitRate;
-
-    error = QCInit(&hAacEnc->qcKernel, &qcInit);
-  }
-
-  /* init bitstream encoder */
-  if (!error) {
-    hAacEnc->bseInit.nChannels   = elInfo->nChannelsInEl;
-    hAacEnc->bseInit.bitrate     = config.bitRate;
-    hAacEnc->bseInit.sampleRate  = config.sampleRate;
-    hAacEnc->bseInit.profile     = profile;
-  }
-
-  return error;
-}
-
-/********************************************************************************
-*
-* function name: AacEncEncode
-* description:  encode pcm to aac data core function
-* returns:      0 if success
-*
-**********************************************************************************/
-Word16 AacEncEncode(AAC_ENCODER *aacEnc,		/*!< an encoder handle */
-                    Word16 *timeSignal,         /*!< BLOCKSIZE*nChannels audio samples, interleaved */
-                    const UWord8 *ancBytes,     /*!< pointer to ancillary data bytes */
-                    Word16 *numAncBytes,		/*!< number of ancillary Data Bytes */
-                    UWord8 *outBytes,           /*!< pointer to output buffer (must be large MINBITS_COEF/8*MAX_CHANNELS bytes) */
-                    VO_U32 *numOutBytes         /*!< number of bytes in output buffer after processing */
-                    )
-{
-  ELEMENT_INFO *elInfo = &aacEnc->elInfo;
-  Word16 globUsedBits;
-  Word16 ancDataBytes, ancDataBytesLeft;
-
-  ancDataBytes = ancDataBytesLeft = *numAncBytes;
-
-  /* init output aac data buffer and length */
-  aacEnc->hBitStream = CreateBitBuffer(&aacEnc->bitStream, outBytes, *numOutBytes);
-
-  /* psychoacoustic process */
-  psyMain(aacEnc->config.nChannelsOut,
-          elInfo,
-          timeSignal,
-          &aacEnc->psyKernel.psyData[elInfo->ChannelIndex[0]],
-          &aacEnc->psyKernel.tnsData[elInfo->ChannelIndex[0]],
-          &aacEnc->psyKernel.psyConfLong,
-          &aacEnc->psyKernel.psyConfShort,
-          &aacEnc->psyOut.psyOutChannel[elInfo->ChannelIndex[0]],
-          &aacEnc->psyOut.psyOutElement,
-          aacEnc->psyKernel.pScratchTns,
-		  aacEnc->config.sampleRate);
-
-  /* adjust bitrate and frame length */
-  AdjustBitrate(&aacEnc->qcKernel,
-                aacEnc->config.bitRate,
-                aacEnc->config.sampleRate);
-
-  /* quantization and coding process */
-  QCMain(&aacEnc->qcKernel,
-         &aacEnc->qcKernel.elementBits,
-         &aacEnc->qcKernel.adjThr.adjThrStateElem,
-         &aacEnc->psyOut.psyOutChannel[elInfo->ChannelIndex[0]],
-         &aacEnc->psyOut.psyOutElement,
-         &aacEnc->qcOut.qcChannel[elInfo->ChannelIndex[0]],
-         &aacEnc->qcOut.qcElement,
-         elInfo->nChannelsInEl,
-		 min(ancDataBytesLeft,ancDataBytes));
-
-  ancDataBytesLeft = ancDataBytesLeft - ancDataBytes;
-
-  globUsedBits = FinalizeBitConsumption(&aacEnc->qcKernel,
-                         &aacEnc->qcOut);
-
-  /* write bitstream process */
-  WriteBitstream(aacEnc->hBitStream,
-                 *elInfo,
-                 &aacEnc->qcOut,
-                 &aacEnc->psyOut,
-                 &globUsedBits,
-                 ancBytes,
-				 aacEnc->psyKernel.sampleRateIdx);
-
-  updateBitres(&aacEnc->qcKernel,
-               &aacEnc->qcOut);
-
-  /* write out the bitstream */
-  *numOutBytes = GetBitsAvail(aacEnc->hBitStream) >> 3;
-
-  return 0;
-}
-
-
-/********************************************************************************
-*
-* function name:AacEncClose
-* description: deallocate an encoder instance
-*
-**********************************************************************************/
-void AacEncClose (AAC_ENCODER* hAacEnc, VO_MEM_OPERATOR *pMemOP)
-{
-  if (hAacEnc) {
-    QCDelete(&hAacEnc->qcKernel, pMemOP);
-
-    QCOutDelete(&hAacEnc->qcOut, pMemOP);
-
-    PsyDelete(&hAacEnc->psyKernel, pMemOP);
-
-    PsyOutDelete(&hAacEnc->psyOut, pMemOP);
-
-    DeleteBitBuffer(&hAacEnc->hBitStream);
-
-	if(hAacEnc->intbuf)
-	{
-		mem_free(pMemOP, hAacEnc->intbuf, VO_INDEX_ENC_AAC);
-		hAacEnc->intbuf = NULL;
-	}
-  }
-}
diff --git a/media/libstagefright/codecs/aacenc/src/adj_thr.c b/media/libstagefright/codecs/aacenc/src/adj_thr.c
deleted file mode 100644
index 8b8be0e..0000000
--- a/media/libstagefright/codecs/aacenc/src/adj_thr.c
+++ /dev/null
@@ -1,1228 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		adj_thr.c
-
-	Content:	Threshold compensation functions
-
-*******************************************************************************/
-
-/* Include system headers before local headers - the local headers
- * redefine __inline, which can mess up definitions in libc headers if
- * they happen to use __inline. */
-#include <string.h>
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "adj_thr_data.h"
-#include "adj_thr.h"
-#include "qc_data.h"
-#include "line_pe.h"
-
-
-#define  minSnrLimit    0x6666 /* 1 dB */
-#define  PEBITS_COEF	0x170a /* 0.18*(1 << 15)*/
-
-#define  HOLE_THR_LONG	0x2873	/* 0.316*(1 << 15) */
-#define  HOLE_THR_SHORT 0x4000  /* 0.5  *(1 << 15) */
-
-#define  MS_THRSPREAD_COEF 0x7333  /* 0.9 * (1 << 15) */
-
-#define	 MIN_SNR_COEF	   0x651f  /* 3.16* (1 << (15 - 2)) */
-
-/* values for avoid hole flag */
-enum _avoid_hole_state {
-  NO_AH              =0,
-  AH_INACTIVE        =1,
-  AH_ACTIVE          =2
-};
-
-/********************************************************************************
-*
-* function name:bits2pe
-* description: convert from bits to pe
-*			   pe = 1.18*desiredBits
-*
-**********************************************************************************/
-Word16 bits2pe(const Word16 bits) {
-  return (bits + ((PEBITS_COEF * bits) >> 15));
-}
-
-/********************************************************************************
-*
-* function name:calcThreshExp
-* description: loudness calculation (threshold to the power of redExp)
-*			   thr(n)^0.25
-*
-**********************************************************************************/
-static void calcThreshExp(Word32 thrExp[MAX_CHANNELS][MAX_GROUPED_SFB],
-                          PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-                          const Word16 nChannels)
-{
-  Word16 ch, sfb, sfbGrp;
-  Word32 *pthrExp = NULL, *psfbThre;
-  for (ch=0; ch<nChannels; ch++) {
-    PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-	 for(sfbGrp = 0; sfbGrp < psyOutChan->sfbCnt; sfbGrp+= psyOutChan->sfbPerGroup)
-	  pthrExp = &(thrExp[ch][sfbGrp]);
-	  psfbThre = psyOutChan->sfbThreshold + sfbGrp;
-	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-		*pthrExp = rsqrt(rsqrt(*psfbThre,INT_BITS),INT_BITS);
-		pthrExp++; psfbThre++;
-      }
-  }
-}
-
-/********************************************************************************
-*
-* function name:adaptMinSnr
-* description: reduce minSnr requirements for bands with relative low energies
-*
-**********************************************************************************/
-static void adaptMinSnr(PSY_OUT_CHANNEL     psyOutChannel[MAX_CHANNELS],
-                        Word16              logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                        MINSNR_ADAPT_PARAM *msaParam,
-                        const Word16        nChannels)
-{
-  Word16 ch, sfb, sfbOffs;
-  Word32 nSfb, avgEn;
-  Word16 log_avgEn = 0;
-  Word32 startRatio_x_avgEn = 0;
-
-
-  for (ch=0; ch<nChannels; ch++) {
-    PSY_OUT_CHANNEL* psyOutChan = &psyOutChannel[ch];
-
-    /* calc average energy per scalefactor band */
-    avgEn = 0;
-    nSfb = 0;
-    for (sfbOffs=0; sfbOffs<psyOutChan->sfbCnt; sfbOffs+=psyOutChan->sfbPerGroup) {
-      for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-        avgEn = L_add(avgEn, psyOutChan->sfbEnergy[sfbOffs+sfb]);
-        nSfb = nSfb + 1;
-      }
-    }
-
-    if (nSfb > 0) {
-	  avgEn = avgEn / nSfb;
-
-      log_avgEn = iLog4(avgEn);
-      startRatio_x_avgEn = fixmul(msaParam->startRatio, avgEn);
-    }
-
-
-    /* reduce minSnr requirement by minSnr^minSnrRed dependent on avgEn/sfbEn */
-    for (sfbOffs=0; sfbOffs<psyOutChan->sfbCnt; sfbOffs+=psyOutChan->sfbPerGroup) {
-      for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-        if (psyOutChan->sfbEnergy[sfbOffs+sfb] < startRatio_x_avgEn) {
-          Word16 dbRatio, minSnrRed;
-          Word32 snrRed;
-          Word16 newMinSnr;
-
-          dbRatio = log_avgEn - logSfbEnergy[ch][sfbOffs+sfb];
-          dbRatio = dbRatio + (dbRatio << 1);
-
-          minSnrRed = 110 - ((dbRatio + (dbRatio << 1)) >> 2);
-          minSnrRed = max(minSnrRed, 20); /* 110: (0.375(redOffs)+1)*80,
-                                               3: 0.00375(redRatioFac)*80
-                                               20: 0.25(maxRed) * 80 */
-
-          snrRed = minSnrRed * iLog4((psyOutChan->sfbMinSnr[sfbOffs+sfb] << 16));
-          /*
-             snrRedI si now scaled by 80 (minSnrRed) and 4 (ffr_iLog4)
-          */
-
-          newMinSnr = round16(pow2_xy(snrRed,80*4));
-
-          psyOutChan->sfbMinSnr[sfbOffs+sfb] = min(newMinSnr, minSnrLimit);
-        }
-      }
-    }
-  }
-
-}
-
-
-/********************************************************************************
-*
-* function name:initAvoidHoleFlag
-* description: determine bands where avoid hole is not necessary resp. possible
-*
-**********************************************************************************/
-static void initAvoidHoleFlag(Word16 ahFlag[MAX_CHANNELS][MAX_GROUPED_SFB],
-                              PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
-                              PSY_OUT_ELEMENT* psyOutElement,
-                              const Word16 nChannels,
-                              AH_PARAM *ahParam)
-{
-  Word16 ch, sfb, sfbGrp, shift;
-  Word32 threshold;
-  Word32* psfbSpreadEn;
-
-  for (ch=0; ch<nChannels; ch++) {
-    PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-
-    if (psyOutChan->windowSequence != SHORT_WINDOW) {
-      for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-         psfbSpreadEn = psyOutChan->sfbSpreadedEnergy + sfbGrp;
-		 for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-			*psfbSpreadEn = *psfbSpreadEn >> 1;  /* 0.5 */
-			++psfbSpreadEn;
-        }
-      }
-    }
-    else {
-      for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-		psfbSpreadEn = psyOutChan->sfbSpreadedEnergy + sfbGrp;
-        for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-          *psfbSpreadEn = (*psfbSpreadEn >> 1) + (*psfbSpreadEn >> 3);  /* 0.63 */
-		  ++psfbSpreadEn;
-        }
-      }
-    }
-  }
-
-  /* increase minSnr for local peaks, decrease it for valleys */
-  if (ahParam->modifyMinSnr) {
-    for(ch=0; ch<nChannels; ch++) {
-      PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-
-      if (psyOutChan->windowSequence != SHORT_WINDOW)
-        threshold = HOLE_THR_LONG;
-      else
-        threshold = HOLE_THR_SHORT;
-
-      for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-        Word16 *psfbMinSnr = psyOutChan->sfbMinSnr + sfbGrp;
-		for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-          Word32 sfbEn, sfbEnm1, sfbEnp1, avgEn;
-
-          if (sfb > 0)
-            sfbEnm1 = psyOutChan->sfbEnergy[sfbGrp+sfb-1];
-          else
-            sfbEnm1 = psyOutChan->sfbEnergy[sfbGrp];
-
-          if (sfb < (psyOutChan->maxSfbPerGroup-1))
-            sfbEnp1 = psyOutChan->sfbEnergy[sfbGrp+sfb+1];
-          else
-            sfbEnp1 = psyOutChan->sfbEnergy[sfbGrp+sfb];
-          avgEn = (sfbEnm1 + sfbEnp1) >> 1;
-          sfbEn = psyOutChan->sfbEnergy[sfbGrp+sfb];
-
-          if (sfbEn > avgEn && avgEn > 0) {
-            Word32 tmpMinSnr;
-            shift = norm_l(sfbEn);
-			tmpMinSnr = Div_32(L_mpy_ls(avgEn, minSnrLimit) << shift, sfbEn << shift );
-            tmpMinSnr = max(tmpMinSnr, HOLE_THR_LONG);
-            tmpMinSnr = max(tmpMinSnr, threshold);
-            *psfbMinSnr = min(*psfbMinSnr, tmpMinSnr);
-          }
-          /* valley ? */
-
-          if ((sfbEn < (avgEn >> 1)) && (sfbEn > 0)) {
-            Word32 tmpMinSnr;
-            Word32 minSnrEn = L_mpy_wx(avgEn, *psfbMinSnr);
-
-            if(minSnrEn < sfbEn) {
-			  shift = norm_l(sfbEn);
-              tmpMinSnr = Div_32( minSnrEn << shift, sfbEn<<shift);
-            }
-            else {
-              tmpMinSnr = MAX_16;
-            }
-            tmpMinSnr = min(minSnrLimit, tmpMinSnr);
-
-            *psfbMinSnr =
-              (min((tmpMinSnr >>  2), mult(*psfbMinSnr, MIN_SNR_COEF)) << 2);
-          }
-		  psfbMinSnr++;
-        }
-      }
-    }
-  }
-
-  /* stereo: adapt the minimum requirements sfbMinSnr of mid and
-     side channels */
-
-  if (nChannels == 2) {
-    PSY_OUT_CHANNEL *psyOutChanM = &psyOutChannel[0];
-    PSY_OUT_CHANNEL *psyOutChanS = &psyOutChannel[1];
-    for (sfb=0; sfb<psyOutChanM->sfbCnt; sfb++) {
-      if (psyOutElement->toolsInfo.msMask[sfb]) {
-        Word32 sfbEnM = psyOutChanM->sfbEnergy[sfb];
-        Word32 sfbEnS = psyOutChanS->sfbEnergy[sfb];
-        Word32 maxSfbEn = max(sfbEnM, sfbEnS);
-        Word32 maxThr = L_mpy_wx(maxSfbEn, psyOutChanM->sfbMinSnr[sfb]) >> 1;
-
-        if(maxThr >= sfbEnM) {
-          psyOutChanM->sfbMinSnr[sfb] = MAX_16;
-        }
-        else {
-          shift = norm_l(sfbEnM);
-		  psyOutChanM->sfbMinSnr[sfb] = min(max(psyOutChanM->sfbMinSnr[sfb],
-			  round16(Div_32(maxThr<<shift, sfbEnM << shift))), minSnrLimit);
-        }
-
-        if(maxThr >= sfbEnS) {
-          psyOutChanS->sfbMinSnr[sfb] = MAX_16;
-        }
-        else {
-		  shift = norm_l(sfbEnS);
-          psyOutChanS->sfbMinSnr[sfb] = min(max(psyOutChanS->sfbMinSnr[sfb],
-			  round16(Div_32(maxThr << shift, sfbEnS << shift))), minSnrLimit);
-        }
-
-
-        if (sfbEnM > psyOutChanM->sfbSpreadedEnergy[sfb])
-          psyOutChanS->sfbSpreadedEnergy[sfb] = L_mpy_ls(sfbEnS, MS_THRSPREAD_COEF);
-
-        if (sfbEnS > psyOutChanS->sfbSpreadedEnergy[sfb])
-          psyOutChanM->sfbSpreadedEnergy[sfb] = L_mpy_ls(sfbEnM, MS_THRSPREAD_COEF);
-      }
-    }
-  }
-
-
-  /* init ahFlag (0: no ah necessary, 1: ah possible, 2: ah active */
-  for(ch=0; ch<nChannels; ch++) {
-    PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-    for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-      Word16 *pahFlag = ahFlag[ch] + sfbGrp;
-	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-
-        if ((psyOutChan->sfbSpreadedEnergy[sfbGrp+sfb] > psyOutChan->sfbEnergy[sfbGrp+sfb]) ||
-            (psyOutChan->sfbEnergy[sfbGrp+sfb] <= psyOutChan->sfbThreshold[sfbGrp+sfb]) ||
-            (psyOutChan->sfbMinSnr[sfbGrp+sfb] == MAX_16)) {
-          *pahFlag++ = NO_AH;
-        }
-        else {
-          *pahFlag++ = AH_INACTIVE;
-        }
-      }
-      for (sfb=psyOutChan->maxSfbPerGroup; sfb<psyOutChan->sfbPerGroup; sfb++) {
-        *pahFlag++ = NO_AH;
-      }
-    }
-  }
-}
-
-/********************************************************************************
-*
-* function name:calcPeNoAH
-* description: sum the pe data only for bands where avoid hole is inactive
-*
-**********************************************************************************/
-static void calcPeNoAH(Word16          *pe,
-                       Word16          *constPart,
-                       Word16          *nActiveLines,
-                       PE_DATA         *peData,
-                       Word16           ahFlag[MAX_CHANNELS][MAX_GROUPED_SFB],
-                       PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
-                       const Word16     nChannels)
-{
-  Word16 ch, sfb, sfbGrp;
-  int ipe, iconstPart, inActiveLines;
-
-  ipe = 0;
-  iconstPart = 0;
-  inActiveLines = 0;
-  for(ch=0; ch<nChannels; ch++) {
-    PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-    PE_CHANNEL_DATA *peChanData = &peData->peChannelData[ch];
-    for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-      for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-
-        if (ahFlag[ch][sfbGrp+sfb] < AH_ACTIVE) {
-          ipe = ipe + peChanData->sfbPe[sfbGrp+sfb];
-          iconstPart = iconstPart + peChanData->sfbConstPart[sfbGrp+sfb];
-          inActiveLines = inActiveLines + peChanData->sfbNActiveLines[sfbGrp+sfb];
-        }
-      }
-    }
-  }
-
-  *pe = saturate(ipe);
-  *constPart = saturate(iconstPart);
-  *nActiveLines = saturate(inActiveLines);
-}
-
-/********************************************************************************
-*
-* function name:reduceThresholds
-* description: apply reduction formula
-*
-**********************************************************************************/
-static void reduceThresholds(PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
-                             Word16           ahFlag[MAX_CHANNELS][MAX_GROUPED_SFB],
-                             Word32           thrExp[MAX_CHANNELS][MAX_GROUPED_SFB],
-                             const Word16     nChannels,
-                             const Word32     redVal)
-{
-  Word32 sfbThrReduced;
-  Word32 *psfbEn, *psfbThr;
-  Word16 ch, sfb, sfbGrp;
-
-  for(ch=0; ch<nChannels; ch++) {
-    PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-    for(sfbGrp=0; sfbGrp<psyOutChan->sfbCnt; sfbGrp+=psyOutChan->sfbPerGroup) {
- 	  psfbEn  = psyOutChan->sfbEnergy + sfbGrp;
-      psfbThr = psyOutChan->sfbThreshold + sfbGrp;
-	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-
-        if (*psfbEn > *psfbThr) {
-          /* threshold reduction formula */
-          Word32 tmp = thrExp[ch][sfbGrp+sfb] + redVal;
-          tmp = fixmul(tmp, tmp);
-          sfbThrReduced = fixmul(tmp, tmp);
-          /* avoid holes */
-          tmp = L_mpy_ls(*psfbEn, psyOutChan->sfbMinSnr[sfbGrp+sfb]);
-
-          if ((sfbThrReduced > tmp) &&
-              (ahFlag[ch][sfbGrp+sfb] != NO_AH)){
-            sfbThrReduced = max(tmp, *psfbThr);
-            ahFlag[ch][sfbGrp+sfb] = AH_ACTIVE;
-          }
-		  *psfbThr = sfbThrReduced;
-        }
-
-		psfbEn++;  psfbThr++;
-      }
-    }
-  }
-}
-
-
-/********************************************************************************
-*
-* function name:correctThresh
-* description: if pe difference deltaPe between desired pe and real pe is small enough,
-*             the difference can be distributed among the scale factor bands.
-*
-**********************************************************************************/
-static void correctThresh(PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
-                          Word16           ahFlag[MAX_CHANNELS][MAX_GROUPED_SFB],
-                          PE_DATA          *peData,
-                          Word32           thrExp[MAX_CHANNELS][MAX_GROUPED_SFB],
-                          const Word32     redVal,
-                          const Word16     nChannels,
-                          const Word32     deltaPe)
-{
-  Word16 ch, sfb, sfbGrp,shift;
-  PSY_OUT_CHANNEL *psyOutChan;
-  PE_CHANNEL_DATA *peChanData;
-  Word32 deltaSfbPe;
-  Word32 normFactor;
-  Word32 *psfbPeFactors;
-  Word16 *psfbNActiveLines, *pahFlag;
-  Word32 sfbEn, sfbThr;
-  Word32 sfbThrReduced;
-
-  /* for each sfb calc relative factors for pe changes */
-  normFactor = 1;
-  for(ch=0; ch<nChannels; ch++) {
-    psyOutChan = &psyOutChannel[ch];
-    peChanData = &peData->peChannelData[ch];
-    for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-      psfbPeFactors = peData->sfbPeFactors[ch] + sfbGrp;
-	  psfbNActiveLines = peChanData->sfbNActiveLines + sfbGrp;
-	  pahFlag = ahFlag[ch] + sfbGrp;
-	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-        Word32 redThrExp = thrExp[ch][sfbGrp+sfb] + redVal;
-
-        if (((*pahFlag < AH_ACTIVE) || (deltaPe > 0)) && (redThrExp > 0) && (redThrExp >= *psfbNActiveLines)) {
-
-          *psfbPeFactors = (*psfbNActiveLines) * (0x7fffffff / redThrExp);
-          normFactor = L_add(normFactor, *psfbPeFactors);
-        }
-        else {
-          *psfbPeFactors = 0;
-        }
-		psfbPeFactors++;
-		pahFlag++; psfbNActiveLines++;
-      }
-    }
-  }
-
-
-  /* calculate new thresholds */
-  for(ch=0; ch<nChannels; ch++) {
-    psyOutChan = &psyOutChannel[ch];
-    peChanData = &peData->peChannelData[ch];
-    for(sfbGrp = 0;sfbGrp < psyOutChan->sfbCnt;sfbGrp+= psyOutChan->sfbPerGroup){
-      psfbPeFactors = peData->sfbPeFactors[ch] + sfbGrp;
-	  psfbNActiveLines = peChanData->sfbNActiveLines + sfbGrp;
-	  pahFlag = ahFlag[ch] + sfbGrp;
-	  for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-        /* pe difference for this sfb */
-        deltaSfbPe = *psfbPeFactors * deltaPe;
-
-		/* thr3(n) = thr2(n)*2^deltaSfbPe/b(n) */
-        if (*psfbNActiveLines > 0 && (normFactor* (*psfbNActiveLines)) != 0) {
-          /* new threshold */
-          Word32 thrFactor;
-          sfbEn  = psyOutChan->sfbEnergy[sfbGrp+sfb];
-          sfbThr = psyOutChan->sfbThreshold[sfbGrp+sfb];
-
-           if(deltaSfbPe >= 0){
-            /*
-              reduce threshold
-            */
-            thrFactor = pow2_xy(L_negate(deltaSfbPe), (normFactor* (*psfbNActiveLines)));
-
-            sfbThrReduced = L_mpy_ls(sfbThr, round16(thrFactor));
-          }
-          else {
-            /*
-              increase threshold
-            */
-            thrFactor = pow2_xy(deltaSfbPe, (normFactor * (*psfbNActiveLines)));
-
-
-            if(thrFactor > sfbThr) {
-              shift = norm_l(thrFactor);
-			  sfbThrReduced = Div_32( sfbThr << shift, thrFactor<<shift );
-            }
-            else {
-              sfbThrReduced = MAX_32;
-            }
-
-          }
-
-          /* avoid hole */
-          sfbEn = L_mpy_ls(sfbEn, psyOutChan->sfbMinSnr[sfbGrp+sfb]);
-
-          if ((sfbThrReduced > sfbEn) &&
-              (*pahFlag == AH_INACTIVE)) {
-            sfbThrReduced = max(sfbEn, sfbThr);
-            *pahFlag = AH_ACTIVE;
-          }
-
-          psyOutChan->sfbThreshold[sfbGrp+sfb] = sfbThrReduced;
-        }
-
-		pahFlag++; psfbNActiveLines++; psfbPeFactors++;
-      }
-    }
-  }
-}
-
-
-/********************************************************************************
-*
-* function name:reduceMinSnr
-* description: if the desired pe can not be reached, reduce pe by reducing minSnr
-*
-**********************************************************************************/
-static void reduceMinSnr(PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
-                         PE_DATA         *peData,
-                         Word16           ahFlag[MAX_CHANNELS][MAX_GROUPED_SFB],
-                         const Word16     nChannels,
-                         const Word16     desiredPe)
-{
-  Word16 ch, sfb, sfbSubWin;
-  Word16 deltaPe;
-
-  /* start at highest freq down to 0 */
-  sfbSubWin = psyOutChannel[0].maxSfbPerGroup;
-  while (peData->pe > desiredPe && sfbSubWin > 0) {
-
-    sfbSubWin = sfbSubWin - 1;
-    /* loop over all subwindows */
-    for (sfb=sfbSubWin; sfb<psyOutChannel[0].sfbCnt;
-        sfb+=psyOutChannel[0].sfbPerGroup) {
-      /* loop over all channels */
-		PE_CHANNEL_DATA* peChan = peData->peChannelData;
-		PSY_OUT_CHANNEL* psyOutCh = psyOutChannel;
-		for (ch=0; ch<nChannels; ch++) {
-        if (ahFlag[ch][sfb] != NO_AH &&
-            psyOutCh->sfbMinSnr[sfb] < minSnrLimit) {
-          psyOutCh->sfbMinSnr[sfb] = minSnrLimit;
-          psyOutCh->sfbThreshold[sfb] =
-            L_mpy_ls(psyOutCh->sfbEnergy[sfb], psyOutCh->sfbMinSnr[sfb]);
-
-          /* calc new pe */
-          deltaPe = ((peChan->sfbNLines4[sfb] + (peChan->sfbNLines4[sfb] >> 1)) >> 2) -
-              peChan->sfbPe[sfb];
-          peData->pe = peData->pe + deltaPe;
-          peChan->pe = peChan->pe + deltaPe;
-        }
-		peChan += 1; psyOutCh += 1;
-      }
-      /* stop if enough has been saved */
-
-      if (peData->pe <= desiredPe)
-        break;
-    }
-  }
-}
-
-/********************************************************************************
-*
-* function name:allowMoreHoles
-* description: if the desired pe can not be reached, some more scalefactor bands
-*              have to be quantized to zero
-*
-**********************************************************************************/
-static void allowMoreHoles(PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
-                           PSY_OUT_ELEMENT *psyOutElement,
-                           PE_DATA         *peData,
-                           Word16           ahFlag[MAX_CHANNELS][MAX_GROUPED_SFB],
-                           const AH_PARAM  *ahParam,
-                           const Word16     nChannels,
-                           const Word16     desiredPe)
-{
-  Word16 ch, sfb;
-  Word16 actPe, shift;
-
-  actPe = peData->pe;
-
-  /* for MS allow hole in the channel with less energy */
-
-  if (nChannels==2 &&
-      psyOutChannel[0].windowSequence==psyOutChannel[1].windowSequence) {
-    PSY_OUT_CHANNEL *psyOutChanL = &psyOutChannel[0];
-    PSY_OUT_CHANNEL *psyOutChanR = &psyOutChannel[1];
-    for (sfb=0; sfb<psyOutChanL->sfbCnt; sfb++) {
-      Word32 minEn;
-
-      if (psyOutElement->toolsInfo.msMask[sfb]) {
-        /* allow hole in side channel ? */
-        minEn = L_mpy_ls(psyOutChanL->sfbEnergy[sfb], (minSnrLimit * psyOutChanL->sfbMinSnr[sfb]) >> 16);
-
-        if (ahFlag[1][sfb] != NO_AH &&
-            minEn > psyOutChanR->sfbEnergy[sfb]) {
-          ahFlag[1][sfb] = NO_AH;
-          psyOutChanR->sfbThreshold[sfb] = L_add(psyOutChanR->sfbEnergy[sfb], psyOutChanR->sfbEnergy[sfb]);
-          actPe = actPe - peData->peChannelData[1].sfbPe[sfb];
-        }
-        /* allow hole in mid channel ? */
-        else {
-        minEn = L_mpy_ls(psyOutChanR->sfbEnergy[sfb], (minSnrLimit * psyOutChanR->sfbMinSnr[sfb]) >> 16);
-
-          if (ahFlag[0][sfb]!= NO_AH &&
-              minEn > psyOutChanL->sfbEnergy[sfb]) {
-            ahFlag[0][sfb] = NO_AH;
-            psyOutChanL->sfbThreshold[sfb] = L_add(psyOutChanL->sfbEnergy[sfb], psyOutChanL->sfbEnergy[sfb]);
-            actPe = actPe - peData->peChannelData[0].sfbPe[sfb];
-          }
-        }
-
-        if (actPe < desiredPe)
-          break;
-      }
-    }
-  }
-
-  /* subsequently erase bands */
-  if (actPe > desiredPe) {
-    Word16 startSfb[2];
-    Word32 avgEn, minEn;
-    Word16 ahCnt;
-    Word16 enIdx;
-    Word16 enDiff;
-    Word32 en[4];
-    Word16 minSfb, maxSfb;
-    Flag   done;
-
-    /* do not go below startSfb */
-    for (ch=0; ch<nChannels; ch++) {
-
-      if (psyOutChannel[ch].windowSequence != SHORT_WINDOW)
-        startSfb[ch] = ahParam->startSfbL;
-      else
-        startSfb[ch] = ahParam->startSfbS;
-    }
-
-    avgEn = 0;
-    minEn = MAX_32;
-    ahCnt = 0;
-    for (ch=0; ch<nChannels; ch++) {
-      PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-      for (sfb=startSfb[ch]; sfb<psyOutChan->sfbCnt; sfb++) {
-
-        if ((ahFlag[ch][sfb] != NO_AH) &&
-            (psyOutChan->sfbEnergy[sfb] > psyOutChan->sfbThreshold[sfb])) {
-          minEn = min(minEn, psyOutChan->sfbEnergy[sfb]);
-          avgEn = L_add(avgEn, psyOutChan->sfbEnergy[sfb]);
-          ahCnt++;
-        }
-      }
-    }
-
-    if(ahCnt) {
-      Word32 iahCnt;
-      shift = norm_l(ahCnt);
-	  iahCnt = Div_32( 1 << shift, ahCnt << shift );
-      avgEn = fixmul(avgEn, iahCnt);
-    }
-
-    enDiff = iLog4(avgEn) - iLog4(minEn);
-    /* calc some energy borders between minEn and avgEn */
-    for (enIdx=0; enIdx<4; enIdx++) {
-      Word32 enFac;
-      enFac = ((6-(enIdx << 1)) * enDiff);
-      en[enIdx] = fixmul(avgEn, pow2_xy(L_negate(enFac),7*4));
-    }
-
-    /* start with lowest energy border at highest sfb */
-    maxSfb = psyOutChannel[0].sfbCnt - 1;
-    minSfb = startSfb[0];
-
-    if (nChannels == 2) {
-      maxSfb = max(maxSfb, (psyOutChannel[1].sfbCnt - 1));
-      minSfb = min(minSfb, startSfb[1]);
-    }
-
-    sfb = maxSfb;
-    enIdx = 0;
-    done = 0;
-    while (!done) {
-
-      for (ch=0; ch<nChannels; ch++) {
-        PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-
-        if (sfb>=startSfb[ch] && sfb<psyOutChan->sfbCnt) {
-          /* sfb energy below border ? */
-
-          if (ahFlag[ch][sfb] != NO_AH && psyOutChan->sfbEnergy[sfb] < en[enIdx]){
-            /* allow hole */
-            ahFlag[ch][sfb] = NO_AH;
-            psyOutChan->sfbThreshold[sfb] = L_add(psyOutChan->sfbEnergy[sfb], psyOutChan->sfbEnergy[sfb]);
-            actPe = actPe - peData->peChannelData[ch].sfbPe[sfb];
-          }
-
-          if (actPe < desiredPe) {
-            done = 1;
-            break;
-          }
-        }
-      }
-      sfb = sfb - 1;
-
-      if (sfb < minSfb) {
-        /* restart with next energy border */
-        sfb = maxSfb;
-        enIdx = enIdx + 1;
-
-        if (enIdx - 4 >= 0)
-          done = 1;
-      }
-    }
-  }
-}
-
-/********************************************************************************
-*
-* function name:adaptThresholdsToPe
-* description: two guesses for the reduction value and one final correction of the
-*              thresholds
-*
-**********************************************************************************/
-static void adaptThresholdsToPe(PSY_OUT_CHANNEL     psyOutChannel[MAX_CHANNELS],
-                                PSY_OUT_ELEMENT    *psyOutElement,
-                                Word16              logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                                PE_DATA            *peData,
-                                const Word16        nChannels,
-                                const Word16        desiredPe,
-                                AH_PARAM           *ahParam,
-                                MINSNR_ADAPT_PARAM *msaParam)
-{
-  Word16 noRedPe, redPe, redPeNoAH;
-  Word16 constPart, constPartNoAH;
-  Word16 nActiveLines, nActiveLinesNoAH;
-  Word16 desiredPeNoAH;
-  Word32 redVal, avgThrExp;
-  Word32 iter;
-
-  calcThreshExp(peData->thrExp, psyOutChannel, nChannels);
-
-  adaptMinSnr(psyOutChannel, logSfbEnergy, msaParam, nChannels);
-
-  initAvoidHoleFlag(peData->ahFlag, psyOutChannel, psyOutElement, nChannels, ahParam);
-
-  noRedPe = peData->pe;
-  constPart = peData->constPart;
-  nActiveLines = peData->nActiveLines;
-
-  /* first guess of reduction value t^0.25 = 2^((a-pen)/4*b) */
-  avgThrExp = pow2_xy((constPart - noRedPe), (nActiveLines << 2));
-
-  /* r1 = 2^((a-per)/4*b) - t^0.25 */
-  redVal = pow2_xy((constPart - desiredPe), (nActiveLines << 2)) - avgThrExp;
-
-  /* reduce thresholds */
-  reduceThresholds(psyOutChannel, peData->ahFlag, peData->thrExp, nChannels, redVal);
-
-  /* pe after first guess */
-  calcSfbPe(peData, psyOutChannel, nChannels);
-  redPe = peData->pe;
-
-  iter = 0;
-  do {
-    /* pe for bands where avoid hole is inactive */
-    calcPeNoAH(&redPeNoAH, &constPartNoAH, &nActiveLinesNoAH,
-               peData, peData->ahFlag, psyOutChannel, nChannels);
-
-    desiredPeNoAH = desiredPe -(redPe - redPeNoAH);
-
-    if (desiredPeNoAH < 0) {
-      desiredPeNoAH = 0;
-    }
-
-    /* second guess */
-
-    if (nActiveLinesNoAH > 0) {
-
-		avgThrExp = pow2_xy((constPartNoAH - redPeNoAH), (nActiveLinesNoAH << 2));
-
-		redVal = (redVal + pow2_xy((constPartNoAH - desiredPeNoAH), (nActiveLinesNoAH << 2))) - avgThrExp;
-
-		/* reduce thresholds */
-		reduceThresholds(psyOutChannel, peData->ahFlag, peData->thrExp, nChannels, redVal);
-    }
-
-    calcSfbPe(peData, psyOutChannel, nChannels);
-    redPe = peData->pe;
-
-    iter = iter+1;
-
-  } while ((20 * abs_s(redPe - desiredPe) > desiredPe) && (iter < 2));
-
-
-  if ((100 * redPe < 115 * desiredPe)) {
-    correctThresh(psyOutChannel, peData->ahFlag, peData, peData->thrExp, redVal,
-                  nChannels, desiredPe - redPe);
-  }
-  else {
-    Word16 desiredPe105 = (105 * desiredPe) / 100;
-    reduceMinSnr(psyOutChannel, peData, peData->ahFlag,
-                 nChannels, desiredPe105);
-    allowMoreHoles(psyOutChannel, psyOutElement, peData, peData->ahFlag,
-                   ahParam, nChannels, desiredPe105);
-  }
-}
-
-
-/*****************************************************************************
-*
-* function name: calcBitSave
-* description:  Calculates percentage of bit save, see figure below
-* returns:
-* input:        parameters and bitres-fullness
-* output:       percentage of bit save
-*
-*****************************************************************************/
-static Word16 calcBitSave(Word16 fillLevel,
-                          const Word16 clipLow,
-                          const Word16 clipHigh,
-                          const Word16 minBitSave,
-                          const Word16 maxBitSave)
-{
-  Word16 bitsave = 0;
-
-  fillLevel = max(fillLevel, clipLow);
-  fillLevel = min(fillLevel, clipHigh);
-
-  if(clipHigh-clipLow)
-  bitsave = (maxBitSave - (((maxBitSave-minBitSave)*(fillLevel-clipLow))/
-                              (clipHigh-clipLow)));
-
-  return (bitsave);
-}
-
-
-
-/*****************************************************************************
-*
-* function name: calcBitSpend
-* description:  Calculates percentage of bit spend, see figure below
-* returns:
-* input:        parameters and bitres-fullness
-* output:       percentage of bit spend
-*
-*****************************************************************************/
-static Word16 calcBitSpend(Word16 fillLevel,
-                           const Word16 clipLow,
-                           const Word16 clipHigh,
-                           const Word16 minBitSpend,
-                           const Word16 maxBitSpend)
-{
-  Word16 bitspend = 1;
-
-  fillLevel = max(fillLevel, clipLow);
-  fillLevel = min(fillLevel, clipHigh);
-
-  if(clipHigh-clipLow)
-  bitspend = (minBitSpend + ((maxBitSpend - minBitSpend)*(fillLevel - clipLow) /
-                                (clipHigh-clipLow)));
-
-  return (bitspend);
-}
-
-
-/*****************************************************************************
-*
-* function name: adjustPeMinMax()
-* description:  adjusts peMin and peMax parameters over time
-* returns:
-* input:        current pe, peMin, peMax
-* output:       adjusted peMin/peMax
-*
-*****************************************************************************/
-static void adjustPeMinMax(const Word16 currPe,
-                           Word16      *peMin,
-                           Word16      *peMax)
-{
-  Word16 minFacHi, maxFacHi, minFacLo, maxFacLo;
-  Word16 diff;
-  Word16 minDiff = extract_l(currPe / 6);
-  minFacHi = 30;
-  maxFacHi = 100;
-  minFacLo = 14;
-  maxFacLo = 7;
-
-  diff = currPe - *peMax ;
-
-  if (diff > 0) {
-    *peMin = *peMin + ((diff * minFacHi) / 100);
-    *peMax = *peMax + ((diff * maxFacHi) / 100);
-  } else {
-    diff = *peMin - currPe;
-
-    if (diff > 0) {
-      *peMin = *peMin - ((diff * minFacLo) / 100);
-      *peMax = *peMax - ((diff * maxFacLo) / 100);
-    } else {
-      *peMin = *peMin + ((currPe - *peMin) * minFacHi / 100);
-      *peMax = *peMax - ((*peMax - currPe) * maxFacLo / 100);
-    }
-  }
-
-
-  if ((*peMax - *peMin) < minDiff) {
-    Word16 partLo, partHi;
-
-    partLo = max(0, (currPe - *peMin));
-    partHi = max(0, (*peMax - currPe));
-
-    *peMax = currPe + ((partHi * minDiff) / (partLo + partHi));
-    *peMin = currPe - ((partLo * minDiff) / (partLo + partHi));
-    *peMin = max(0, *peMin);
-  }
-}
-
-
-/*****************************************************************************
-*
-* function name: BitresCalcBitFac
-* description:  calculates factor of spending bits for one frame
-*                1.0 : take all frame dynpart bits
-*                >1.0 : take all frame dynpart bits + bitres
-*                <1.0 : put bits in bitreservoir
-*  returns:      BitFac*100
-*  input:        bitres-fullness, pe, blockType, parameter-settings
-*  output:
-*
-*****************************************************************************/
-static Word16 bitresCalcBitFac( const Word16   bitresBits,
-                                const Word16   maxBitresBits,
-                                const Word16   pe,
-                                const Word16   windowSequence,
-                                const Word16   avgBits,
-                                const Word16   maxBitFac,
-                                ADJ_THR_STATE *AdjThr,
-                                ATS_ELEMENT   *adjThrChan)
-{
-  BRES_PARAM *bresParam;
-  Word16 pex;
-  Word16 fillLevel;
-  Word16 bitSave, bitSpend, bitresFac;
-
-  fillLevel = extract_l((100* bitresBits) / maxBitresBits);
-
-  if (windowSequence != SHORT_WINDOW)
-    bresParam = &(AdjThr->bresParamLong);
-  else
-    bresParam = &(AdjThr->bresParamShort);
-
-  pex = max(pe, adjThrChan->peMin);
-  pex = min(pex,adjThrChan->peMax);
-
-  bitSave = calcBitSave(fillLevel,
-                        bresParam->clipSaveLow, bresParam->clipSaveHigh,
-                        bresParam->minBitSave, bresParam->maxBitSave);
-
-  bitSpend = calcBitSpend(fillLevel,
-                          bresParam->clipSpendLow, bresParam->clipSpendHigh,
-                          bresParam->minBitSpend, bresParam->maxBitSpend);
-
-  if(adjThrChan->peMax != adjThrChan->peMin)
-	bitresFac = (100 - bitSave) + extract_l(((bitSpend + bitSave) * (pex - adjThrChan->peMin)) /
-                    (adjThrChan->peMax - adjThrChan->peMin));
-  else
-	bitresFac = 0x7fff;
-
-  bitresFac = min(bitresFac,
-                    (100-30 + extract_l((100 * bitresBits) / avgBits)));
-
-  bitresFac = min(bitresFac, maxBitFac);
-
-  adjustPeMinMax(pe, &adjThrChan->peMin, &adjThrChan->peMax);
-
-  return bitresFac;
-}
-
-/*****************************************************************************
-*
-* function name: AdjThrInit
-* description:  init thresholds parameter
-*
-*****************************************************************************/
-void AdjThrInit(ADJ_THR_STATE *hAdjThr,
-                const Word32   meanPe,
-                Word32         chBitrate)
-{
-  ATS_ELEMENT* atsElem = &hAdjThr->adjThrStateElem;
-  MINSNR_ADAPT_PARAM *msaParam = &atsElem->minSnrAdaptParam;
-
-  /* common for all elements: */
-  /* parameters for bitres control */
-  hAdjThr->bresParamLong.clipSaveLow   =  20;
-  hAdjThr->bresParamLong.clipSaveHigh  =  95;
-  hAdjThr->bresParamLong.minBitSave    =  -5;
-  hAdjThr->bresParamLong.maxBitSave    =  30;
-  hAdjThr->bresParamLong.clipSpendLow  =  20;
-  hAdjThr->bresParamLong.clipSpendHigh =  95;
-  hAdjThr->bresParamLong.minBitSpend   = -10;
-  hAdjThr->bresParamLong.maxBitSpend   =  40;
-
-  hAdjThr->bresParamShort.clipSaveLow   =  20;
-  hAdjThr->bresParamShort.clipSaveHigh  =  75;
-  hAdjThr->bresParamShort.minBitSave    =   0;
-  hAdjThr->bresParamShort.maxBitSave    =  20;
-  hAdjThr->bresParamShort.clipSpendLow  =  20;
-  hAdjThr->bresParamShort.clipSpendHigh =  75;
-  hAdjThr->bresParamShort.minBitSpend   = -5;
-  hAdjThr->bresParamShort.maxBitSpend   =  50;
-
-  /* specific for each element: */
-
-  /* parameters for bitres control */
-  atsElem->peMin = extract_l(((80*meanPe) / 100));
-  atsElem->peMax = extract_l(((120*meanPe) / 100));
-
-  /* additional pe offset to correct pe2bits for low bitrates */
-  atsElem->peOffset = 0;
-  if (chBitrate < 32000) {
-    atsElem->peOffset = max(50, (100 - extract_l((100 * chBitrate) / 32000)));
-  }
-
-  /* avoid hole parameters */
-  if (chBitrate > 20000) {
-    atsElem->ahParam.modifyMinSnr = TRUE;
-    atsElem->ahParam.startSfbL = 15;
-    atsElem->ahParam.startSfbS = 3;
-  }
-  else {
-    atsElem->ahParam.modifyMinSnr = FALSE;
-    atsElem->ahParam.startSfbL = 0;
-    atsElem->ahParam.startSfbS = 0;
-  }
-
-  /* minSnr adaptation */
-  /* maximum reduction of minSnr goes down to minSnr^maxRed */
-  msaParam->maxRed = 0x20000000;     /* *0.25f */
-  /* start adaptation of minSnr for avgEn/sfbEn > startRatio */
-  msaParam->startRatio = 0x0ccccccd; /* 10 */
-  /* maximum minSnr reduction to minSnr^maxRed is reached for
-     avgEn/sfbEn >= maxRatio */
-  msaParam->maxRatio =  0x0020c49c; /* 1000 */
-  /* helper variables to interpolate minSnr reduction for
-     avgEn/sfbEn between startRatio and maxRatio */
-
-  msaParam->redRatioFac = 0xfb333333; /* -0.75/20 */
-
-  msaParam->redOffs = 0x30000000;  /* msaParam->redRatioFac * 10*log10(msaParam->startRatio) */
-
-
-  /* pe correction */
-  atsElem->peLast = 0;
-  atsElem->dynBitsLast = 0;
-  atsElem->peCorrectionFactor = 100; /* 1.0 */
-
-}
-
-/*****************************************************************************
-*
-* function name: calcPeCorrection
-* description:  calculates the desired perceptual entropy factor
-*				It is between 0.85 and 1.15
-*
-*****************************************************************************/
-static void calcPeCorrection(Word16 *correctionFac,
-                             const Word16 peAct,
-                             const Word16 peLast,
-                             const Word16 bitsLast)
-{
-  Word32 peAct100 = 100 * peAct;
-  Word32 peLast100 = 100 * peLast;
-  Word16 peBitsLast = bits2pe(bitsLast);
-
-  if ((bitsLast > 0) &&
-      (peAct100 < (150 * peLast)) &&  (peAct100 > (70 * peLast)) &&
-      ((120 * peBitsLast) > peLast100 ) && (( 65 * peBitsLast) < peLast100))
-    {
-      Word16 newFac = (100 * peLast) / peBitsLast;
-      /* dead zone */
-
-      if (newFac < 100) {
-        newFac = min(((110 * newFac) / 100), 100);
-        newFac = max(newFac, 85);
-      }
-      else {
-        newFac = max(((90 * newFac) / 100), 100);
-        newFac = min(newFac, 115);
-      }
-
-      if ((newFac > 100 && *correctionFac < 100) ||
-          (newFac < 100 && *correctionFac > 100)) {
-        *correctionFac = 100;
-      }
-      /* faster adaptation towards 1.0, slower in the other direction */
-
-      if ((*correctionFac < 100 && newFac < *correctionFac) ||
-          (*correctionFac > 100 && newFac > *correctionFac))
-        *correctionFac = (85 * *correctionFac + 15 * newFac) / 100;
-      else
-        *correctionFac = (70 * *correctionFac + 30 * newFac) / 100;
-      *correctionFac = min(*correctionFac, 115);
-      *correctionFac = max(*correctionFac, 85);
-    }
-  else {
-    *correctionFac = 100;
-  }
-}
-
-/********************************************************************************
-*
-* function name: AdjustThresholds
-* description:  Adjust thresholds to the desired bitrate
-*
-**********************************************************************************/
-void AdjustThresholds(ADJ_THR_STATE   *adjThrState,
-                      ATS_ELEMENT     *AdjThrStateElement,
-                      PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
-                      PSY_OUT_ELEMENT *psyOutElement,
-                      Word16          *chBitDistribution,
-                      Word16           logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                      Word16           sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
-                      QC_OUT_ELEMENT  *qcOE,
-					  ELEMENT_BITS	  *elBits,
-					  const Word16     nChannels,
-                      const Word16     maxBitFac)
-{
-  PE_DATA peData;
-  Word16 noRedPe, grantedPe, grantedPeCorr;
-  Word16 curWindowSequence;
-  Word16 bitFactor;
-  Word16 avgBits = (elBits->averageBits - (qcOE->staticBitsUsed + qcOE->ancBitsUsed));
-  Word16 bitresBits = elBits->bitResLevel;
-  Word16 maxBitresBits = elBits->maxBits;
-  Word16 sideInfoBits = (qcOE->staticBitsUsed + qcOE->ancBitsUsed);
-  Word16 ch;
-  memset(&peData, 0, sizeof(peData));
-
-  prepareSfbPe(&peData, psyOutChannel, logSfbEnergy, sfbNRelevantLines, nChannels, AdjThrStateElement->peOffset);
-
-  /* pe without reduction */
-  calcSfbPe(&peData, psyOutChannel, nChannels);
-  noRedPe = peData.pe;
-
-
-  curWindowSequence = LONG_WINDOW;
-
-  if (nChannels == 2) {
-
-    if ((psyOutChannel[0].windowSequence == SHORT_WINDOW) ||
-        (psyOutChannel[1].windowSequence == SHORT_WINDOW)) {
-      curWindowSequence = SHORT_WINDOW;
-    }
-  }
-  else {
-    curWindowSequence = psyOutChannel[0].windowSequence;
-  }
-
-
-  /* bit factor */
-  bitFactor = bitresCalcBitFac(bitresBits, maxBitresBits, noRedPe+5*sideInfoBits,
-                               curWindowSequence, avgBits, maxBitFac,
-                               adjThrState,
-                               AdjThrStateElement);
-
-  /* desired pe */
-  grantedPe = ((bitFactor * bits2pe(avgBits)) / 100);
-
-  /* correction of pe value */
-  calcPeCorrection(&(AdjThrStateElement->peCorrectionFactor),
-                   min(grantedPe, noRedPe),
-                   AdjThrStateElement->peLast,
-                   AdjThrStateElement->dynBitsLast);
-  grantedPeCorr = (grantedPe * AdjThrStateElement->peCorrectionFactor) / 100;
-
-
-  if (grantedPeCorr < noRedPe && noRedPe > peData.offset) {
-    /* calc threshold necessary for desired pe */
-    adaptThresholdsToPe(psyOutChannel,
-                        psyOutElement,
-                        logSfbEnergy,
-                        &peData,
-                        nChannels,
-                        grantedPeCorr,
-                        &AdjThrStateElement->ahParam,
-                        &AdjThrStateElement->minSnrAdaptParam);
-  }
-
-  /* calculate relative distribution */
-  for (ch=0; ch<nChannels; ch++) {
-    Word16 peOffsDiff = peData.pe - peData.offset;
-    chBitDistribution[ch] = 200;
-
-    if (peOffsDiff > 0) {
-      Word32 temp = 1000 - (nChannels * 200);
-      chBitDistribution[ch] = chBitDistribution[ch] +
-		  (temp * peData.peChannelData[ch].pe) / peOffsDiff;
-    }
-  }
-
-  /* store pe */
-  qcOE->pe = noRedPe;
-
-  /* update last pe */
-  AdjThrStateElement->peLast = grantedPe;
-}
-
-/********************************************************************************
-*
-* function name: AdjThrUpdate
-* description:  save dynBitsUsed for correction of bits2pe relation
-*
-**********************************************************************************/
-void AdjThrUpdate(ATS_ELEMENT *AdjThrStateElement,
-                  const Word16 dynBitsUsed)
-{
-  AdjThrStateElement->dynBitsLast = dynBitsUsed;
-}
-
-
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/AutoCorrelation_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/AutoCorrelation_v5.s
deleted file mode 100644
index e705197..0000000
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/AutoCorrelation_v5.s
+++ /dev/null
@@ -1,167 +0,0 @@
-@/*
-@ ** Copyright 2003-2010, VisualOn, Inc.
-@ **
-@ ** Licensed under the Apache License, Version 2.0 (the "License");
-@ ** you may not use this file except in compliance with the License.
-@ ** You may obtain a copy of the License at
-@ **
-@ **     http://www.apache.org/licenses/LICENSE-2.0
-@ **
-@ ** Unless required by applicable law or agreed to in writing, software
-@ ** distributed under the License is distributed on an "AS IS" BASIS,
-@ ** WITHOUT 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:		AutoCorrelation_v5.s
-@
-@	Content:	AutoCorrelation function armv5 assemble
-@
-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-
-
-	.section .text
-	.global	AutoCorrelation
-
-AutoCorrelation:
-	stmdb     sp!, {r4 - r11, lr}
-
-  sub     r13, r13, #20
-
-  mov     r5, r0
-  mov     r7, r1
-  mov     r9, r3
-  mov     r2, r2, lsl #16
-  mov     r0, #0
-  mov     r4, r2, asr #16
-  mov     r8, #0
-  cmp     r4, #0
-  ble     L136
-
-	cmp     r4, #8
-	mov		  r2, #0
-  blt     L133
-
-	sub     r12, r4, #8
-L132:
-  ldr     r6, [r5, r2]
-	add		  r2, r2, #4
-	smulbb  r3, r6, r6
-	ldr     r1, [r5, r2]
-	smultt	r10, r6, r6
-	mov		  r3, r3, asr #9
-	smulbb	r6, r1, r1
-	mov		  r10, r10, asr #9
-	qadd	  r0, r0, r3
-	smultt	r11, r1, r1
-	add     r2, r2, #4
-	qadd	  r0, r0, r10
-	mov		  r6, r6, asr #9
-	mov		  r11, r11, asr #9
-	ldr		  r1, [r5, r2]
-	qadd	  r0, r0, r6
-	smulbb	r10, r1, r1
-	smultt	r6, r1, r1
-	qadd	  r0, r0, r11
-	mov		  r10, r10, asr #9
-	mov		  r6, r6, asr #9
-	qadd	  r0, r0, r10
-	add     r2, r2, #4
-	add     r8, r8, #6
-
-	qadd	  r0, r0, r6
-	cmp     r8, r12
-  blt     L132
-L133:
-  ldrsh   r6, [r5, r2]
-  mul     r10, r6, r6
-	add     r2, r2, #2
-  mov     r1, r10, asr #9
-  qadd    r0, r0, r1
-L134:
-  add     r8, r8, #1
-  cmp     r8, r4
-  blt     L133
-L135:
-L136:
-  str     r0, [r7, #0]
-  cmp     r0, #0
-  beq     L1320
-L137:
-  mov     r2, r9, lsl #16
-	mov     r8, #1
-  mov     r2, r2, asr #16
-  cmp     r2, #1
-  ble     L1319
-L138:
-L139:
-  sub     r4, r4, #1
-  mov     r14, #0
-  mov     r3, #0
-  cmp     r4, #0
-  ble     L1317
-L1310:
-  cmp     r4, #6
-  addlt   r6, r5, r8, lsl #1
-  blt     L1314
-L1311:
-  add     r6, r5, r8, lsl #1
-  sub     r12, r4, #6
-  str     r8, [r13, #8]
-  str     r7, [r13, #4]
-L1312:
-  mov     r1, r3, lsl #1
-  ldrsh   r7, [r6, r1]
-  ldrsh   r10, [r5, r1]
-  add     r8, r1, r6
-	add     r9, r5, r1
-	mul     r7, r10, r7
-  ldrsh   r1, [r8, #2]
-	ldrsh   r10, [r8, #4]
-  add     r7, r14, r7, asr #9
-  ldrsh   r0, [r9, #2]
-  ldrsh   r11, [r9, #4]
-  mul     r1, r0, r1
-  ldrsh   r14, [r8, #6]
-  mul     r10, r11, r10
-	add     r7, r7, r1, asr #9
-  ldrsh   r8, [r8, #8]
-	add     r3, r3, #5
-	ldrsh   r11, [r9, #6]
-  ldrsh   r1, [r9, #8]
-  mul     r14, r11, r14
-  add     r7, r7, r10, asr #9
-  mul     r1, r1, r8
-  add     r14, r7, r14, asr #9
-	cmp     r3, r12
-  add     r14, r14, r1, asr #9
-  ble     L1312
-L1313:
-  ldr     r8, [r13, #8]
-  ldr     r7, [r13, #4]
-L1314:
-L1315:
-  mov     r12, r3, lsl #1
-  ldrsh   r9, [r6, r12]
-  ldrsh   r12, [r5, r12]
-  add     r3, r3, #1
-  cmp     r3, r4
-  mul     r12, r12, r9
-  add     r14, r14, r12, asr #9
-  blt     L1315
-L1316:
-L1317:
-  str     r14, [r7, +r8, lsl #2]
-  add     r8, r8, #1
-  cmp     r8, r2
-  blt     L139
-
-L1319:
-L1320:
-	add     r13, r13, #20
-	ldmia   sp!, {r4 - r11, pc}
-
-	@ENDP  @ |AutoCorrelation|
-	.end
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/CalcWindowEnergy_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/CalcWindowEnergy_v5.s
deleted file mode 100644
index b30e8cb..0000000
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/CalcWindowEnergy_v5.s
+++ /dev/null
@@ -1,112 +0,0 @@
-@/*
-@ ** Copyright 2003-2010, VisualOn, Inc.
-@ **
-@ ** Licensed under the Apache License, Version 2.0 (the "License");
-@ ** you may not use this file except in compliance with the License.
-@ ** You may obtain a copy of the License at
-@ **
-@ **     http://www.apache.org/licenses/LICENSE-2.0
-@ **
-@ ** Unless required by applicable law or agreed to in writing, software
-@ ** distributed under the License is distributed on an "AS IS" BASIS,
-@ ** WITHOUT 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:		CalcWindowEnergy_v5.s
-@
-@	Content:	CalcWindowEnergy function armv5 assemble
-@
-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-
-	.section .text
-
-	.global	CalcWindowEnergy
-
-CalcWindowEnergy:
-	stmdb   sp!, {r4 - r11, lr}
-	sub     r13, r13, #20
-
-  mov     r3, r3, lsl #16
-	ldr     r10, [r0, #168]                    @ states0 = blockSwitchingControl->iirStates[0];
-  mov     r3, r3, asr #16
-	ldr     r11, [r0, #172]                    @ states1 = blockSwitchingControl->iirStates[1];
-
-	mov     r2, r2, lsl #16
-	ldr     r12, hiPassCoeff                   @ Coeff0 = hiPassCoeff[0];
-  mov     r2, r2, asr #16
-	ldr     r14, hiPassCoeff + 4			         @ Coeff1 = hiPassCoeff[1];
-
-	mov			r8, #0							               @ w=0
-	mov			r5, #0							               @ wOffset = 0;
-
-BLOCK_BEGIN:
-	mov			r6, #0                             @ accuUE = 0;
-	mov			r7, #0								             @ accuFE = 0;
-	mov			r4, #0							               @ i=0
-
-	str			r8, [r13, #4]
-	str			r0, [r13, #8]
-	str			r3, [r13, #12]
-
-ENERGY_BEG:
-	mov     r9, r5, lsl #1
-	ldrsh   r9, [r1, r9]											@ tempUnfiltered = timeSignal[tidx];
-
-	add			r5, r5, r2												@ tidx = tidx + chIncrement;
-
-	smulwb	r3, r14, r9												@ accu1 = L_mpy_ls(Coeff1, tempUnfiltered);
-	smull		r0, r8, r12, r11									@ accu2 = fixmul( Coeff0, states1 );
-
-	mov			r3, r3, lsl #1
-	mov			r8, r8, lsl #1
-
-	sub			r0, r3, r10												@ accu3 = accu1 - states0;
-	sub			r8,	r0, r8												@ out = accu3 - accu2;
-
-	mov		  r10, r3														@ states0 = accu1;
-	mov		  r11, r8														@ states1 = out;
-
-	mul		  r3, r9, r9
-	mov     r8, r8, asr #16
-
-	add		  r4, r4, #1
-	add     r6, r6, r3, asr #7
-
-	mul		  r9, r8, r8
-	ldr		  r3, [r13, #12]
-
-	add		  r7, r7, r9, asr #7
-
-	cmp     r4, r3
-  blt     ENERGY_BEG
-
-	ldr		  r0, [r13, #8]
-	ldr		  r8, [r13, #4]
-
-ENERGY_END:
-	add		  r4, r0, r8, lsl #2
-
-	str     r6, [r4, #72]
-	add		  r8, r8, #1
-  str     r7, [r4, #136]
-
-	cmp		  r8, #8
-	blt		  BLOCK_BEGIN
-
-BLOCK_END:
-	str     r10, [r0, #168]
-  str     r11, [r0, #172]
-  mov     r0, #1
-
-  add     r13, r13, #20
-	ldmia   sp!, {r4 - r11, pc}
-
-hiPassCoeff:
-	.word 0xbec8b439
-	.word	0x609d4952
-
-	@ENDP
-	.end
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/PrePostMDCT_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/PrePostMDCT_v5.s
deleted file mode 100644
index da21d5f..0000000
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/PrePostMDCT_v5.s
+++ /dev/null
@@ -1,131 +0,0 @@
-@/*
-@ ** Copyright 2003-2010, VisualOn, Inc.
-@ **
-@ ** Licensed under the Apache License, Version 2.0 (the "License");
-@ ** you may not use this file except in compliance with the License.
-@ ** You may obtain a copy of the License at
-@ **
-@ **     http://www.apache.org/licenses/LICENSE-2.0
-@ **
-@ ** Unless required by applicable law or agreed to in writing, software
-@ ** distributed under the License is distributed on an "AS IS" BASIS,
-@ ** WITHOUT 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:		PrePostMDCT_v5.s
-@
-@	Content:	premdct and postmdct function armv5 assemble
-@
-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-
-	.section .text
-	.global	PreMDCT
-
-PreMDCT:
-	stmdb       sp!, {r4 - r11, lr}
-
-	add         r9, r0, r1, lsl #2
-	sub         r3, r9, #8
-
-	movs        r1, r1, asr #2
-	beq         PreMDCT_END
-
-PreMDCT_LOOP:
-	ldr					r8, [r2], #4
-	ldr					r9, [r2], #4
-
-	ldrd				r4, [r0]
-	ldrd				r6, [r3]
-
-	smull				r14, r11, r4, r8					@ MULHIGH(tr1, cosa)
-	smull    			r10, r12, r7, r8					@ MULHIGH(ti1, cosa)
-
-	smull				r14, r8, r7, r9						@ MULHIGH(ti1, sina)
-	smull				r7, r10, r4, r9						@ MULHIGH(tr1, sina)
-
-	add					r11, r11, r8						@ MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@
-	sub					r7, r12, r10						@ MULHIGH(ti1, cosa) - MULHIGH(tr1, sina)
-
-	ldr					r8, [r2], #4
-	ldr					r9, [r2], #4
-
-	smull				r14, r4, r6, r8						@ MULHIGH(tr2, cosa)
-	smull    			r10, r12, r5, r8					@ MULHIGH(ti2, cosa)
-
-	smull				r14, r8, r5, r9						@ MULHIGH(ti2, sina)
-	smull				r5, r10, r6, r9						@ MULHIGH(tr2, sina)
-
-	add					r8, r8, r4
-	sub					r9, r12, r10
-
-	mov					r6, r11
-
-	strd				r6, [r0]
-	strd				r8, [r3]
-
-	subs				r1, r1, #1
-	sub					r3, r3, #8
-	add 				r0, r0, #8
-	bne					PreMDCT_LOOP
-
-PreMDCT_END:
-	ldmia       sp!, {r4 - r11, pc}
-	@ENDP  @ |PreMDCT|
-
-	.section .text
-	.global	PostMDCT
-
-PostMDCT:
-	stmdb       sp!, {r4 - r11, lr}
-
-	add         r9, r0, r1, lsl #2
-	sub         r3, r9, #8
-
-	movs        r1, r1, asr #2
-	beq         PostMDCT_END
-
-PostMDCT_LOOP:
-	ldr					r8, [r2], #4
-	ldr					r9, [r2], #4
-
-	ldrd				r4, [r0]
-	ldrd				r6, [r3]
-
-	smull				r14, r11, r4, r8					@ MULHIGH(tr1, cosa)
-	smull    			r10, r12, r5, r8					@ MULHIGH(ti1, cosa)
-
-	smull				r14, r8, r5, r9						@ MULHIGH(ti1, sina)
-	smull				r5, r10, r4, r9						@ MULHIGH(tr1, sina)
-
-	add					r4, r11, r8							@ MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@
-	sub					r11, r10, r12						@ MULHIGH(ti1, cosa) - MULHIGH(tr1, sina)@
-
-	ldr					r8, [r2], #4						@
-	ldr					r9, [r2], #4
-
-	smull				r14, r5, r6, r8						@ MULHIGH(tr2, cosa)
-	smull    			r10, r12, r7, r8					@ MULHIGH(ti2, cosa)
-
-	smull				r14, r8, r7, r9						@ MULHIGH(ti2, sina)
-	smull				r7, r10, r6, r9						@ MULHIGH(tr2, sina)
-
-	add					r6, r8, r5							@ MULHIGH(cosb, tr2) + MULHIGH(sinb, ti2)@
-	sub					r5, r10, r12						@ MULHIGH(sinb, tr2) - MULHIGH(cosb, ti2)@
-
-	mov					r7, r11
-
-	strd				r4, [r0]
-	strd				r6, [r3]
-
-	subs				r1, r1, #1
-	sub					r3, r3, #8
-	add 				r0, r0, #8
-	bne					PostMDCT_LOOP
-
-PostMDCT_END:
-	ldmia       sp!, {r4 - r11, pc}
-	@ENDP  @ |PostMDCT|
-	.end
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/R4R8First_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/R4R8First_v5.s
deleted file mode 100644
index 4ca4f31..0000000
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/R4R8First_v5.s
+++ /dev/null
@@ -1,252 +0,0 @@
-@/*
-@ ** Copyright 2003-2010, VisualOn, Inc.
-@ **
-@ ** Licensed under the Apache License, Version 2.0 (the "License");
-@ ** you may not use this file except in compliance with the License.
-@ ** You may obtain a copy of the License at
-@ **
-@ **     http://www.apache.org/licenses/LICENSE-2.0
-@ **
-@ ** Unless required by applicable law or agreed to in writing, software
-@ ** distributed under the License is distributed on an "AS IS" BASIS,
-@ ** WITHOUT 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:		R4R8First_v5.s
-@
-@	Content:	Radix8First and Radix4First function armv5 assemble
-@
-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-
-	.section .text
-	.global	Radix4First
-
-Radix4First:
-	stmdb       sp!, {r4 - r11, lr}
-
-	movs				r10, r1
-	mov					r11, r0
-	beq					Radix4First_END
-
-Radix4First_LOOP:
-	ldrd				r0, [r11]
-	ldrd				r2, [r11, #8]
-	ldrd				r4, [r11, #16]
-	ldrd				r6, [r11, #24]
-
-	add					r8, r0, r2
-	add					r9, r1, r3
-
-	sub					r0, r0, r2
-	sub					r1, r1, r3
-
-	add					r2, r4, r6
-	add					r3, r5, r7
-
-	sub					r4, r4, r6
-	sub					r5, r5, r7
-
-	add					r6, r8, r2
-	add					r7, r9, r3
-
-	sub					r8, r8, r2
-	sub					r9, r9, r3
-
-	add					r2, r0, r5
-	sub					r3, r1, r4
-
-	sub					r0, r0, r5
-	add					r1, r1, r4
-
-	strd				r6, [r11]
-	strd				r2, [r11, #8]
-	strd				r8, [r11, #16]
-	strd				r0, [r11, #24]
-
-	subs				r10, r10, #1
-	add					r11, r11, #32
-	bne					Radix4First_LOOP
-
-Radix4First_END:
-	ldmia       sp!, {r4 - r11, pc}
-	@ENDP  @ |Radix4First|
-
-	.section .text
-	.global	Radix8First
-
-Radix8First:
-	stmdb       sp!, {r4 - r11, lr}
-	sub         sp, sp, #0x24
-
-	mov				  r12, r1
-	mov					r14, r0
-	cmp					r12, #0
-	beq					Radix8First_END
-
-Radix8First_LOOP:
-	ldrd				r0, [r14]
-	ldrd				r2, [r14, #8]
-	ldrd				r4, [r14, #16]
-	ldrd				r6, [r14, #24]
-
-	add					r8, r0, r2					@ r0 = buf[0] + buf[2]@
-	add					r9, r1, r3					@ i0 = buf[1] + buf[3]@
-
-	sub					r0, r0, r2					@ r1 = buf[0] - buf[2]@
-	sub					r1, r1, r3					@ i1 = buf[1] - buf[3]@
-
-	add					r2, r4, r6					@	r2 = buf[4] + buf[6]@
-	add					r3, r5, r7					@ i2 = buf[5] + buf[7]@
-
-	sub					r4, r4, r6					@	r3 = buf[4] - buf[6]@
-	sub					r5, r5, r7					@ i3 = buf[5] - buf[7]@
-
-	add					r6, r8, r2					@ r4 = (r0 + r2) >> 1@
-	add					r7, r9, r3					@ i4 = (i0 + i2) >> 1@
-
-	sub					r8, r8, r2					@	r5 = (r0 - r2) >> 1@
-	sub					r9, r9, r3					@ i5 = (i0 - i2) >> 1@
-
-	sub					r2, r0, r5					@ r6 = (r1 - i3) >> 1@
-	add					r3, r1, r4					@ i6 = (i1 + r3) >> 1@
-
-	add					r0, r0, r5					@ r7 = (r1 + i3) >> 1@
-	sub					r1, r1, r4					@ i7 = (i1 - r3) >> 1@
-
-	mov					r6, r6, asr #1			@
-	mov					r7, r7, asr #1			@
-
-	mov					r8, r8, asr #1
-	mov					r9, r9, asr #1
-
-	mov					r2, r2, asr #1
-	mov					r3, r3, asr #1
-
-	mov					r0, r0, asr #1
-	mov					r1, r1, asr #1
-
-	str					r6, [sp]
-	str					r7, [sp, #4]
-
-	str					r8, [sp, #8]
-	str					r9, [sp, #12]
-
-	str					r2, [sp, #16]
-	str					r3, [sp, #20]
-
-	str					r0, [sp, #24]
-	str					r1, [sp, #28]
-
-	ldrd				r2, [r14, #32]
-	ldrd				r4, [r14, #40]
-	ldrd				r6, [r14, #48]
-	ldrd				r8, [r14, #56]
-
-	add					r0, r2, r4					@ r0 = buf[ 8] + buf[10]@
-	add					r1, r3, r5					@ i0 = buf[ 9] + buf[11]@
-
-	sub					r2, r2, r4					@ r1 = buf[ 8] - buf[10]@
-	sub					r3, r3, r5					@ i1 = buf[ 9] - buf[11]@
-
-	add					r4, r6, r8					@ r2 = buf[12] + buf[14]@
-	add					r5, r7, r9					@ i2 = buf[13] + buf[15]@
-
-	sub					r6, r6, r8					@ r3 = buf[12] - buf[14]@
-	sub					r7, r7, r9					@	i3 = buf[13] - buf[15]@
-
-	add					r8, r0, r4					@ t0 = (r0 + r2)
-	add					r9, r1, r5					@ t1 = (i0 + i2)
-
-	sub					r0, r0, r4					@ t2 = (r0 - r2)
-	sub					r1, r1, r5					@ t3 = (i0 - i2)
-
-	mov					r8, r8, asr #1
-	ldr					r4, [sp]
-
-	mov					r9, r9, asr #1
-	ldr					r5, [sp, #4]
-
-	mov					r0, r0, asr #1
-	mov					r1, r1, asr #1
-
-	add					r10, r4, r8					@ buf[ 0] = r4 + t0@
-	add					r11, r5, r9					@ buf[ 1] = i4 + t1@
-
-	sub					r4,  r4, r8					@ buf[ 8] = r4 - t0@
-	sub					r5,  r5, r9					@	buf[ 9] = i4 - t1@
-
- 	strd				r10, [r14]
- 	strd				r4,  [r14, #32]
-
- 	ldr					r10, [sp, #8]
- 	ldr					r11, [sp, #12]
-
- 	add					r4, r10, r1					@ buf[ 4] = r5 + t3@
- 	sub					r5, r11, r0					@	buf[ 5] = i5 - t2@
-
- 	sub					r10, r10, r1				@ buf[12] = r5 - t3@
- 	add					r11, r11, r0				@ buf[13] = i5 + t2@
-
- 	strd				r4,  [r14, #16]
- 	strd				r10, [r14, #48]
-
- 	sub					r0, r2, r7					@ r0 = r1 - i3@
- 	add					r1, r3, r6					@ i0 = i1 + r3@
-
-  ldr					r11, DATATab
-
- 	add					r2, r2, r7					@ r2 = r1 + i3@
- 	sub					r3, r3, r6					@ i2 = i1 - r3@
-
-	sub					r4, r0, r1					@ r0 - i0
-	add					r5, r0, r1					@ r0 + i0
-
-	sub					r0, r2, r3					@ r2 - i2
-	add					r1, r2, r3					@ r2 + i2
-
-	smull				r8, r6, r4, r11
-	smull				r9, r7, r5, r11
-
-	ldr					r2, [sp, #16]
-	ldr					r3, [sp, #20]
-
-	smull				r8, r4, r0, r11
-	smull				r9, r5, r1, r11
-
-	ldr					r10, [sp, #24]
-	ldr					r11, [sp, #28]
-
-	sub					r8, r2, r6
-	sub					r9, r3, r7
-
-	add					r2, r2, r6
-	add					r3, r3, r7
-
-	add					r6, r10, r5
-	sub					r7, r11, r4
-
-	sub					r0, r10, r5
-	add					r1, r11, r4
-
-	strd				r6, [r14, #8]
-	strd				r8, [r14, #24]
-	strd				r0, [r14, #40]
-	strd				r2, [r14, #56]
-
-	subs				r12, r12, #1
-	add					r14, r14, #64
-
-	bne					Radix8First_LOOP
-
-Radix8First_END:
-	add         sp, sp, #0x24
-	ldmia       sp!, {r4 - r11, pc}
-
-DATATab:
-	.word       0x5a82799a
-
-	@ENDP  @ |Radix8First|
-	.end
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/Radix4FFT_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/Radix4FFT_v5.s
deleted file mode 100644
index b59b967..0000000
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/Radix4FFT_v5.s
+++ /dev/null
@@ -1,169 +0,0 @@
-@/*
-@ ** Copyright 2003-2010, VisualOn, Inc.
-@ **
-@ ** Licensed under the Apache License, Version 2.0 (the "License");
-@ ** you may not use this file except in compliance with the License.
-@ ** You may obtain a copy of the License at
-@ **
-@ **     http://www.apache.org/licenses/LICENSE-2.0
-@ **
-@ ** Unless required by applicable law or agreed to in writing, software
-@ ** distributed under the License is distributed on an "AS IS" BASIS,
-@ ** WITHOUT 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:		Radix4FFT_v5.s
-@
-@	Content:	Radix4FFT armv5 assemble
-@
-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-	.section .text
-	.global	Radix4FFT
-
-Radix4FFT:
-	stmdb     sp!, {r4 - r11, lr}
-	sub       sp, sp, #32
-
-	mov			r1, r1, asr #2
-	cmp     r1, #0
-	beq     Radix4FFT_END
-
-Radix4FFT_LOOP1:
-	mov     r14, r0          							@ xptr = buf@
-	mov		r10, r1 												@ i = num@
-	mov     r9, r2, lsl #3  							@ step = 2*bgn@
-	cmp     r10, #0
-	str		r0, [sp]
-	str		r1, [sp, #4]
-	str		r2, [sp, #8]
-	str		r3, [sp, #12]
-	beq     Radix4FFT_LOOP1_END
-
-Radix4FFT_LOOP2:
-	mov     r12, r3				        				@ csptr = twidTab@
-	mov		r11, r2												@ j = bgn
-	cmp     r11, #0
-	str		r10, [sp, #16]
-	beq     Radix4FFT_LOOP2_END
-
-Radix4FFT_LOOP3:
-	str			r11, [sp, #20]
-
-	ldrd		r0, [r14, #0]									@ r0 = xptr[0]@ r1 = xptr[1]@
-	add			r14, r14, r9 	 								@ xptr += step@
-
-	ldrd		r10,	[r14, #0]  					 			@ r2 = xptr[0]@ r3 = xptr[1]@
-	ldr			r8, [r12], #4									@ cosxsinx = csptr[0]@
-
-	smulwt	r4, r10, r8										@ L_mpy_wx(cosx, t0)
-	smulwt	r3, r11, r8										@ L_mpy_wx(cosx, t1)
-
-	smlawb	r2, r11, r8, r4								@ r2 = L_mpy_wx(cosx, t0) + L_mpy_wx(sinx, t1)@
-	smulwb	r5, r10, r8										@ L_mpy_wx(sinx, t0)
-
-	mov			r10, r0, asr #2								@ t0 = r0 >> 2@
-	mov			r11, r1, asr #2								@	t1 = r1 >> 2@
-
-	sub			r3, r3, r5										@ r3 = L_mpy_wx(cosx, t1) - L_mpy_wx(sinx, t0)@
-	add     r14, r14, r9 	 								@ xptr += step@
-
-	sub			r0, r10, r2										@ r0 = t0 - r2@
-	sub			r1, r11, r3									  @ r1 = t1 - r3@
-
-	add			r2, r10, r2										@ r2 = t0 + r2@
-	add			r3, r11, r3										@ r3 = t1 + r3@
-
-	str			r2, [sp, #24]
-	str			r3, [sp, #28]
-
-	ldrd		r10, [r14, #0]								@ r4 = xptr[0]@ r5 = xptr[1]@
-	ldr			r8, [r12], #4									@ cosxsinx = csptr[1]@
-
-	smulwt	r6, r10, r8										@ L_mpy_wx(cosx, t0)
-	smulwt	r5, r11, r8										@ L_mpy_wx(cosx, t1)
-
-	smlawb	r4, r11, r8, r6								@ r4 = L_mpy_wx(cosx, t0) + L_mpy_wx(sinx, t1)@
-	smulwb	r7, r10, r8										@ L_mpy_wx(sinx, t0)
-
-	add			r14, r14, r9									@ xptr += step@
-	sub			r5, r5, r7										@ r5 = L_mpy_wx(cosx, t1) - L_mpy_wx(sinx, t0)@
-
-	ldrd		r10, [r14]										@ r6 = xptr[0]@ r7 = xptr[1]@
-	ldr			r8, [r12], #4									@ cosxsinx = csptr[1]@
-
-	smulwt	r2, r10, r8										@ L_mpy_wx(cosx, t0)
-	smulwt	r7, r11, r8										@ L_mpy_wx(cosx, t1)
-
-	smlawb	r6, r11, r8, r2								@ r4 = L_mpy_wx(cosx, t0) + L_mpy_wx(sinx, t1)@
-	smulwb	r3, r10, r8										@ L_mpy_wx(sinx, t0)
-
-	mov			r10, r4												@ t0 = r4@
-	mov			r11, r5												@ t1 = r5@
-
-	sub			r7, r7, r3										@ r5 = L_mpy_wx(cosx, t1) - L_mpy_wx(sinx, t0)@
-
-
-	add			r4,  r10, r6									@	r4 = t0 + r6@
-	sub			r5, r7, r11										@ r5 = r7 - t1@
-
-	sub			r6, r10, r6										@ r6 = t0 - r6@
-	add			r7, r7, r11										@ r7 = r7 + t1@
-
-	ldr			r2, [sp, #24]
-	ldr			r3, [sp, #28]
-
-	add			r10, r0, r5										@ xptr[0] = r0 + r5@
-	add			r11, r1, r6										@ xptr[0] = r1 + r6
-
-	strd		r10, [r14]
-	sub			r14, r14, r9									@ xptr -= step@
-
-	sub			r10, r2, r4										@	xptr[0] = r2 - r4@
-	sub			r11, r3, r7										@ xptr[1] = r3 - r7@
-
-	strd		r10, [r14]
-	sub			r14, r14, r9									@ xptr -= step@
-
-	sub			r10, r0, r5										@ xptr[0] = r0 - r5@
-	sub			r11, r1, r6										@ xptr[0] = r1 - r6
-
-	strd		r10, [r14]
-	sub			r14, r14, r9									@ xptr -= step@
-
-	add			r10, r2, r4										@	xptr[0] = r2 - r4@
-	add			r11, r3, r7										@ xptr[1] = r3 - r7@
-
-	strd		r10, [r14]
-	add			r14, r14, #8									@ xptr += 2@
-
-	ldr			r11, [sp, #20]
-	subs		r11, r11, #1
-	bne			Radix4FFT_LOOP3
-
-Radix4FFT_LOOP2_END:
-	ldr			r10, [sp, #16]
-	ldr			r3, [sp, #12]
-	ldr			r2, [sp, #8]
-	rsb			r8, r9, r9, lsl #2
-	sub			r10, r10, #1
-	add			r14, r14, r8
-	cmp			r10, #0
-	bhi     Radix4FFT_LOOP2
-
-Radix4FFT_LOOP1_END:
-	ldr     r0, [sp]
-	ldr		r1, [sp, #4]
-	add     r3, r3, r8, asr #1
-	mov     r2, r2, lsl #2
-	movs    r1, r1, asr #2
-	bne     Radix4FFT_LOOP1
-
-Radix4FFT_END:
-	add     sp, sp, #32
-	ldmia   sp!, {r4 - r11, pc}
-
-	@ENDP  @ |Radix4FFT|
-	.end
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/band_nrg_v5.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/band_nrg_v5.s
deleted file mode 100644
index 4789f6d..0000000
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV5E/band_nrg_v5.s
+++ /dev/null
@@ -1,204 +0,0 @@
-@/*
-@ ** Copyright 2003-2010, VisualOn, Inc.
-@ **
-@ ** Licensed under the Apache License, Version 2.0 (the "License");
-@ ** you may not use this file except in compliance with the License.
-@ ** You may obtain a copy of the License at
-@ **
-@ **     http://www.apache.org/licenses/LICENSE-2.0
-@ **
-@ ** Unless required by applicable law or agreed to in writing, software
-@ ** distributed under the License is distributed on an "AS IS" BASIS,
-@ ** WITHOUT 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:		band_nrg_v5.s
-@
-@	Content:	CalcBandEnergy and CalcBandEnergyMS function armv5 assemble
-@
-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-
-	.section .text
-
-	.global	CalcBandEnergy
-
-CalcBandEnergy:
-	stmdb   sp!, {r4 - r11, lr}
-
-  mov     r2, r2, lsl #16
-	ldr     r12, [r13, #36]
-	mov			r9, #0
-  mov     r5, r2, asr #16
-	mov			r4, #0
-  cmp     r5, #0
-	ble     L212
-
-L22:
-  mov     r2, r4, lsl #1
-  ldrsh   r10, [r1, r2]
-  add     r11, r1, r2
-  ldrsh   r2, [r11, #2]
-	mov     r14, #0
-  cmp     r10, r2
-  bge     L28
-
-L23:
-	ldr     r11, [r0, +r10, lsl #2]
-  add     r10, r10, #1
-	ldr     r6, [r0, +r10, lsl #2]
-	smull   r11, r7, r11, r11
-	add     r10, r10, #1
-	smull	  r6, r8, r6, r6
-	ldr     r11, [r0, +r10, lsl #2]
-	qadd	  r14, r14, r7
-	add     r10, r10, #1
-	smull	  r11, r7, r11, r11
-	ldr     r6, [r0, +r10, lsl #2]
-	qadd	  r14, r14, r8
-	smull	  r6, r8, r6, r6
-  add     r10, r10, #1
-	qadd	  r14, r14, r7
-	cmp     r10, r2
-	qadd	  r14, r14, r8
-	blt     L23
-
-L28:
-	qadd	  r14, r14, r14
-	str     r14, [r3, +r4, lsl #2]
-	add     r4, r4, #1
-	qadd	  r9, r9, r14
-	cmp     r4, r5
-
-  blt     L22
-
-L212:
-	str     r9, [r12, #0]
-	ldmia   sp!, {r4 - r11, pc}
-
-	@ENDP  ; |CalcBandEnergy|
-
-	.global	CalcBandEnergyMS
-
-CalcBandEnergyMS:
-	stmdb   sp!, {r4 - r11, lr}
-	sub     r13, r13, #24
-
-	mov     r12, #0
-  mov     r3, r3, lsl #16
-  mov     r14, #0
-	mov     r3, r3, asr #16
-	cmp     r3, #0
-	mov		  r4, #0
-  ble     L315
-
-L32:
-	mov		  r5, r4, lsl #1
-	mov		  r6, #0
-	ldrsh   r10, [r2, r5]
-	add     r5, r2, r5
-	mov		  r7, #0
-	ldrsh	  r11, [r5, #2]
-	cmp     r10, r11
-  bge     L39
-
-	str		  r3, [r13, #4]
-	str		  r4, [r13, #8]
-	str		  r12, [r13, #12]
-	str		  r14, [r13, #16]
-
-L33:
-	ldr     r8, [r0, +r10, lsl #2]
-	ldr     r9, [r1, +r10, lsl #2]
-	mov		  r8, r8, asr #1
-	add		  r10, r10, #1
-	mov		  r9, r9, asr #1
-
-	ldr     r12, [r0, +r10, lsl #2]
-	add		  r5, r8, r9
-	ldr     r14, [r1, +r10, lsl #2]
-	sub		  r8, r8, r9
-
-	smull   r5, r3, r5, r5
-	mov		  r12, r12, asr #1
-	smull   r8, r4, r8, r8
-	mov		  r14, r14, asr #1
-
-	qadd	  r6, r6, r3
-	add		  r5, r12, r14
-	qadd	  r7, r7, r4
-	sub		  r8, r12, r14
-
-	smull   r5, r3, r5, r5
-	add		  r10, r10, #1
-	smull   r8, r4, r8, r8
-
-	qadd	  r6, r6, r3
-	qadd	  r7, r7, r4
-
-	ldr     r8, [r0, +r10, lsl #2]
-	ldr     r9, [r1, +r10, lsl #2]
-	mov		  r8, r8, asr #1
-	add		  r10, r10, #1
-	mov		  r9, r9, asr #1
-
-	ldr     r12, [r0, +r10, lsl #2]
-	add		  r5, r8, r9
-	ldr     r14, [r1, +r10, lsl #2]
-	sub		  r8, r8, r9
-
-	smull   r5, r3, r5, r5
-	mov		  r12, r12, asr #1
-	smull   r8, r4, r8, r8
-	mov		  r14, r14, asr #1
-
-	qadd	  r6, r6, r3
-	add		  r5, r12, r14
-	qadd	  r7, r7, r4
-	sub		  r8, r12, r14
-
-	smull   r5, r3, r5, r5
-	add		  r10, r10, #1
-	smull   r8, r4, r8, r8
-
-	qadd	  r6, r6, r3
-	qadd	  r7, r7, r4
-
-	cmp     r10, r11
-
-	blt		  L33
-
-	ldr		  r3, [r13, #4]
-	ldr		  r4, [r13, #8]
-	ldr		  r12, [r13, #12]
-	ldr		  r14, [r13, #16]
-L39:
-	qadd	  r6, r6, r6
-	qadd	  r7, r7, r7
-
-	ldr		  r8, [r13, #60]
-	ldr		  r9, [r13, #68]
-
-	qadd	  r12, r12, r6
-	qadd	  r14, r14, r7
-
-	str		  r6, [r8, +r4, lsl #2]
-	str     r7, [r9, +r4, lsl #2]
-
-	add		  r4, r4, #1
-	cmp		  r4, r3
-	blt     L32
-
-L315:
-	ldr		  r8, [r13, #64]
-	ldr		  r9, [r13, #72]
-	str		  r12, [r8, #0]
-	str		  r14, [r9, #0]
-
-	add     r13, r13, #24
-	ldmia   sp!, {r4 - r11, pc}
-	@ENDP  ; |CalcBandEnergyMS|
-
-	.end
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/PrePostMDCT_v7.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV7/PrePostMDCT_v7.s
deleted file mode 100644
index 7f6b881..0000000
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/PrePostMDCT_v7.s
+++ /dev/null
@@ -1,146 +0,0 @@
-@/*
-@ ** Copyright 2003-2010, VisualOn, Inc.
-@ **
-@ ** Licensed under the Apache License, Version 2.0 (the "License");
-@ ** you may not use this file except in compliance with the License.
-@ ** You may obtain a copy of the License at
-@ **
-@ **     http://www.apache.org/licenses/LICENSE-2.0
-@ **
-@ ** Unless required by applicable law or agreed to in writing, software
-@ ** distributed under the License is distributed on an "AS IS" BASIS,
-@ ** WITHOUT 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:		PrePostMDCT_v7.s
-@
-@	Content:	premdct and postmdct function armv7 assemble
-@
-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-
-	.section .text
-	.global	PreMDCT
-	.fnstart
-
-PreMDCT:
-	stmdb     sp!, {r4 - r11, lr}
-	.save	  {r4 - r11, lr}
-	fstmfdd   sp!, {d8 - d15}
-	.vsave	  {d8 - d15}
-
-	add         r9, r0, r1, lsl #2
-	sub         r3, r9, #32
-
-	movs        r1, r1, asr #2
-	beq         PreMDCT_END
-
-PreMDCT_LOOP:
-	VLD4.I32			{d0, d2, d4, d6}, [r2]!				@ cosa = *csptr++@ sina = *csptr++@
-	VLD4.I32			{d1, d3, d5, d7}, [r2]!				@ cosb = *csptr++@ sinb = *csptr++@
-	VLD2.I32			{d8, d9, d10, d11}, [r0]			@ tr1 = *(buf0 + 0)@ ti2 = *(buf0 + 1)@
-	VLD2.I32			{d13, d15}, [r3]!					@ tr2 = *(buf1 - 1)@ ti1 = *(buf1 + 0)@
-	VLD2.I32			{d12, d14}, [r3]!					@ tr2 = *(buf1 - 1)@ ti1 = *(buf1 + 0)@
-
-	VREV64.32			Q8, Q7
-	VREV64.32			Q9, Q6
-
-
-	VQDMULH.S32		Q10, Q0, Q4								@ MULHIGH(cosa, tr1)
-	VQDMULH.S32		Q11, Q1, Q8								@ MULHIGH(sina, ti1)
-	VQDMULH.S32		Q12, Q0, Q8								@ MULHIGH(cosa, ti1)
-	VQDMULH.S32		Q13, Q1, Q4								@ MULHIGH(sina, tr1)
-
-	VADD.S32			Q0, Q10, Q11						@ *buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@
-	VSUB.S32			Q1, Q12, Q13						@ *buf0++ = MULHIGH(cosa, ti1) - MULHIGH(sina, tr1)@
-
-	VST2.I32			{d0, d1, d2, d3}, [r0]!
-	sub						r3, r3, #32
-
-	VQDMULH.S32		Q10, Q2, Q9										@ MULHIGH(cosb, tr2)
-	VQDMULH.S32		Q11, Q3, Q5										@ MULHIGH(sinb, ti2)
-	VQDMULH.S32		Q12, Q2, Q5										@ MULHIGH(cosb, ti2)
-	VQDMULH.S32		Q13, Q3, Q9										@ MULHIGH(sinb, tr2)
-
-	VADD.S32			Q0, Q10, Q11									@ MULHIGH(cosa, tr2) + MULHIGH(sina, ti2)@
-	VSUB.S32			Q1, Q12, Q13									@ MULHIGH(cosa, ti2) - MULHIGH(sina, tr2)@
-
-	VREV64.32			Q3, Q1
-	VREV64.32			Q2, Q0
-
-	VST2.I32		{d5, d7}, [r3]!
-	VST2.I32		{d4, d6}, [r3]!
-
-	subs     		r1, r1, #4
-	sub		  		r3, r3, #64
-	bne       	PreMDCT_LOOP
-
-PreMDCT_END:
-	fldmfdd   sp!, {d8 - d15}
-	ldmia     sp!, {r4 - r11, pc}
-	@ENDP  @ |PreMDCT|
-	.fnend
-
-	.section .text
-	.global	PostMDCT
-	.fnstart
-
-PostMDCT:
-	stmdb     sp!, {r4 - r11, lr}
-	.save	  {r4 - r11, lr}
-	fstmfdd   sp!, {d8 - d15}
-	.vsave	  {d8 - d15}
-
-	add         r9, r0, r1, lsl #2
-	sub         r3, r9, #32
-
-	movs        r1, r1, asr #2
-	beq         PostMDCT_END
-
-PostMDCT_LOOP:
-	VLD4.I32			{d0, d2, d4, d6}, [r2]!				@ cosa = *csptr++@ sina = *csptr++@
-	VLD4.I32			{d1, d3, d5, d7}, [r2]!				@ cosb = *csptr++@ sinb = *csptr++@
-	VLD2.I32			{d8, d9, d10, d11}, [r0]			@ tr1 = *(zbuf1 + 0)@ ti1 = *(zbuf1 + 1)@
-	VLD2.I32			{d13, d15}, [r3]!							@ tr2 = *(zbuf2 - 1)@ ti2 = *(zbuf2 + 0)@
-	VLD2.I32			{d12, d14}, [r3]!							@ tr2 = *(zbuf2 - 1)@ ti2 = *(zbuf2 + 0)@
-
-	VREV64.32			Q8, Q6
-	VREV64.32			Q9, Q7
-
-	VQDMULH.S32		Q10, Q0, Q4										@ MULHIGH(cosa, tr1)
-	VQDMULH.S32		Q11, Q1, Q5										@ MULHIGH(sina, ti1)
-	VQDMULH.S32		Q12, Q0, Q5										@ MULHIGH(cosa, ti1)
-	VQDMULH.S32		Q13, Q1, Q4										@ MULHIGH(sina, tr1)
-
-	VADD.S32			Q0, Q10, Q11									@ *buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1)@
-	VSUB.S32			Q5, Q13, Q12									@ *buf1-- = MULHIGH(sina, tr1) - MULHIGH(cosa, ti1)@
-
-	VQDMULH.S32		Q10, Q2, Q8										@ MULHIGH(cosb, tr2)
-	VQDMULH.S32		Q11, Q3, Q9										@ MULHIGH(sinb, ti2)
-	VQDMULH.S32		Q12, Q2, Q9										@ MULHIGH(cosb, ti2)
-	VQDMULH.S32		Q13, Q3, Q8										@ MULHIGH(sinb, tr2)
-
-	VADD.S32			Q4, Q10, Q11									@ *buf1-- = MULHIGH(cosa, tr2) + MULHIGH(sina, ti2)@
-	VSUB.S32			Q1, Q13, Q12									@ *buf0++ = MULHIGH(sina, tr2) - MULHIGH(cosa, ti2)@
-
-	VREV64.32			Q2, Q4
-	VREV64.32			Q3, Q5
-
-	sub						r3, r3, #32
-	VST2.I32			{d0, d1, d2, d3}, [r0]!
-
-	VST2.I32			{d5, d7}, [r3]!
-	VST2.I32			{d4, d6}, [r3]!
-
-	subs     			r1, r1, #4
-	sub		  			r3, r3, #64
-	bne       	PostMDCT_LOOP
-
-PostMDCT_END:
-	fldmfdd   sp!, {d8 - d15}
-	ldmia     sp!, {r4 - r11, pc}
-
-	@ENDP  		@ |PostMDCT|
-	.fnend
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/R4R8First_v7.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV7/R4R8First_v7.s
deleted file mode 100644
index 03fa6a9..0000000
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/R4R8First_v7.s
+++ /dev/null
@@ -1,157 +0,0 @@
-@/*
-@ ** Copyright 2003-2010, VisualOn, Inc.
-@ **
-@ ** Licensed under the Apache License, Version 2.0 (the "License");
-@ ** you may not use this file except in compliance with the License.
-@ ** You may obtain a copy of the License at
-@ **
-@ **     http://www.apache.org/licenses/LICENSE-2.0
-@ **
-@ ** Unless required by applicable law or agreed to in writing, software
-@ ** distributed under the License is distributed on an "AS IS" BASIS,
-@ ** WITHOUT 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:		R4R8First_v7.s
-@
-@	Content:	Radix8First and Radix4First function armv7 assemble
-@
-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-
-	.section .text
-	.global	Radix8First
-	.fnstart
-
-Radix8First:
-	stmdb     		sp!, {r4 - r11, lr}
-	.save	  		{r4 - r11, lr}
-	fstmfdd   		sp!, {d8 - d15}
-	.vsave	  		{d8 - d15}
-
-	ldr       		r3, SQRT1_2
-	cmp       		r1, #0
-
-	VDUP.I32  		Q15, r3
-	beq       		Radix8First_END
-
-Radix8First_LOOP:
-	VLD1.I32			{d0, d1, d2, d3},	[r0]!
-	VLD1.I32			{d8, d9, d10, d11},	[r0]!
-
-	VADD.S32			d4, d0, d1		@ r0 = buf[0] + buf[2]@i0 = buf[1] + buf[3]@
-	VSUB.S32			d5, d0, d1		@ r1 = buf[0] - buf[2]@i1 = buf[1] - buf[3]@
-	VSUB.S32			d7, d2, d3		@ r2 = buf[4] - buf[6]@i2 = buf[5] - buf[7]@
-	VADD.S32			d6, d2, d3		@ r3 = buf[4] + buf[6]@i3 = buf[5] + buf[7]@
-	VREV64.I32			d7, d7
-
-	VADD.S32			Q0, Q2, Q3		@ r4 = (r0 + r2)@i4 = (i0 + i2)@i6 = (i1 + r3)@r7 = (r1 + i3)
-	VSUB.S32			Q1, Q2, Q3		@ r5 = (r0 - r2)@i5 = (i0 - i2)@r6 = (r1 - i3)@i7 = (i1 - r3)@
-
-	VREV64.I32			d3, d3
-
-	VADD.S32			d4, d8, d9		@ r0 = buf[ 8] + buf[10]@i0 = buf[ 9] + buf[11]@
-	VSUB.S32			d7, d10, d11	@ r1 = buf[12] - buf[14]@i1 = buf[13] - buf[15]@
-	VADD.S32			d6, d10, d11	@ r2 = buf[12] + buf[14]@i2 = buf[13] + buf[15]@
-	VREV64.I32			d7, d7
-	VSUB.S32			d5, d8, d9		@ r3 = buf[ 8] - buf[10]@i3 = buf[ 9] - buf[11]@
-
-	VTRN.32				d1, d3
-
-	VADD.S32			Q4, Q2, Q3		@ t0 = (r0 + r2) >> 1@t1 = (i0 + i2) >> 1@i0 = i1 + r3@r2 = r1 + i3@
-	VSUB.S32			Q5, Q2, Q3		@ t2 = (r0 - r2) >> 1@t3 = (i0 - i2) >> 1@r0 = r1 - i3@i2 = i1 - r3@
-
-	VREV64.I32			d3, d3
-
-	VSHR.S32			d8, d8, #1
-	VSHR.S32			Q0, Q0, #1
-	VREV64.I32			d10, d10
-	VTRN.32				d11, d9
-	VSHR.S32			Q1, Q1, #1
-	VSHR.S32			d10, d10, #1
-	VREV64.I32			d9, d9
-
-	sub       			r0, r0, #0x40
-
-	VADD.S32			d12, d0, d8
-	VSUB.S32			d16, d0, d8
-	VADD.S32			d14, d2, d10
-	VSUB.S32			d18, d2, d10
-
-	VSUB.S32			d4, d11, d9
-	VADD.S32			d5, d11, d9
-
-	VREV64.I32			d18, d18
-
-	VQDMULH.S32			Q3, Q2, Q15
-	VTRN.32				d14, d18
-	VTRN.32				d6, d7
-	VREV64.I32			d18, d18
-
-	VSUB.S32			d15, d3, d6
-	VREV64.I32			d7, d7
-	VADD.S32			d19, d3, d6
-	VADD.S32			d13, d1, d7
-	VSUB.S32			d17, d1, d7
-
-	VREV64.I32			d17, d17
-	VTRN.32				d13, d17
-	VREV64.I32			d17, d17
-
-	subs       			r1, r1, #1
-
-	VST1.I32			{d12, d13, d14, d15}, [r0]!
-	VST1.I32			{d16, d17, d18, d19}, [r0]!
-	bne       			Radix8First_LOOP
-
-Radix8First_END:
-	fldmfdd   sp!, {d8 - d15}
-	ldmia     sp!, {r4 - r11, pc}
-SQRT1_2:
-	.word      0x2d413ccd
-
-	@ENDP  @ |Radix8First|
-	.fnend
-
-	.section .text
-	.global	Radix4First
-	.fnstart
-
-Radix4First:
-	stmdb     	sp!, {r4 - r11, lr}
-	.save	  	{r4 - r11, lr}
-	fstmfdd   	sp!, {d8 - d15}
-	.vsave	  	{d8 - d15}
-
-	cmp       	r1, #0
-	beq       	Radix4First_END
-
-Radix4First_LOOP:
-	VLD1.I32			{d0, d1, d2, d3}, [r0]
-
-	VADD.S32			d4, d0, d1							@ r0 = buf[0] + buf[2]@ r1 = buf[1] + buf[3]@
-	VSUB.S32			d5, d0, d1							@ r2 = buf[0] - buf[2]@ r3 = buf[1] - buf[3]@
-	VSUB.S32			d7, d2, d3							@ r4 = buf[4] + buf[6]@ r5 = buf[5] + buf[7]@
-	VADD.S32			d6, d2, d3							@ r6 = buf[4] - buf[6]@ r7 = buf[5] - buf[7]@
-
-	VREV64.I32		d7, d7									@
-
-	VADD.S32			Q4, Q2, Q3
-	VSUB.S32			Q5, Q2, Q3
-
-	VREV64.I32		d11, d11
-	VTRN.32				d9, d11
-	subs       		r1, r1, #1
-	VREV64.I32		d11, d11
-	VST1.I32			{d8, d9, d10, d11}, [r0]!
-
-	bne       		Radix4First_LOOP
-
-Radix4First_END:
-	fldmfdd   		sp!, {d8 - d15}
-	ldmia    		sp!, {r4 - r11, pc}
-
-	@ENDP  @ |Radix4First|
-	.fnend
diff --git a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/Radix4FFT_v7.s b/media/libstagefright/codecs/aacenc/src/asm/ARMV7/Radix4FFT_v7.s
deleted file mode 100644
index 431bc30..0000000
--- a/media/libstagefright/codecs/aacenc/src/asm/ARMV7/Radix4FFT_v7.s
+++ /dev/null
@@ -1,148 +0,0 @@
-@/*
-@ ** Copyright 2003-2010, VisualOn, Inc.
-@ **
-@ ** Licensed under the Apache License, Version 2.0 (the "License");
-@ ** you may not use this file except in compliance with the License.
-@ ** You may obtain a copy of the License at
-@ **
-@ **     http://www.apache.org/licenses/LICENSE-2.0
-@ **
-@ ** Unless required by applicable law or agreed to in writing, software
-@ ** distributed under the License is distributed on an "AS IS" BASIS,
-@ ** WITHOUT 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:		Radix4FFT_v7.s
-@
-@	Content:	Radix4FFT armv7 assemble
-@
-@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-
-	.section .text
-	.global	Radix4FFT
-	.fnstart
-
-Radix4FFT:
-	stmdb    sp!, {r4 - r11, lr}
-	.save	 {r4 - r11, lr}
-	fstmfdd  sp!, {d8 - d15}
-	.vsave	 {d8 - d15}
-
-	mov			r1, r1, asr #2
-	cmp     	r1, #0
-	beq     	Radix4FFT_END
-
-Radix4FFT_LOOP1:
-	mov     	r5, r2, lsl #1
-	mov     	r8, r0
-	mov     	r7, r1
-	mov     	r5, r5, lsl #2
-	cmp     	r1, #0
-	rsbeq   	r12, r5, r5, lsl #2
-	beq     	Radix4FFT_LOOP1_END
-
-	rsb     	r12, r5, r5, lsl #2
-
-Radix4FFT_LOOP2:
-	mov     	r6, r3
-	mov     	r4, r2
-	cmp     	r2, #0
-	beq     	Radix4FFT_LOOP2_END
-
-Radix4FFT_LOOP3:
-	@r0 = xptr[0]@
-	@r1 = xptr[1]@
-	VLD2.I32			{D0, D1, D2, D3}, [r8]
-	VLD2.I32			{D28, D29, D30, D31}, [r6]!		@ cosx = csptr[0]@ sinx = csptr[1]@
-
-	add					r8, r8, r5										@ xptr += step@
-	VLD2.I32			{D4, D5, D6,D7}, [r8]					@ r2 = xptr[0]@ r3 = xptr[1]@
-
-	VQDMULH.S32		Q10, Q2, Q14									@ MULHIGH(cosx, t0)
-	VQDMULH.S32		Q11, Q3, Q15									@ MULHIGH(sinx, t1)
-	VQDMULH.S32		Q12, Q3, Q14									@ MULHIGH(cosx, t1)
-	VQDMULH.S32		Q13, Q2, Q15									@ MULHIGH(sinx, t0)
-
-	VADD.S32			Q2, Q10, Q11									@ MULHIGH(cosx, t0) + MULHIGH(sinx, t1)
-	VSUB.S32			Q3, Q12, Q13									@ MULHIGH(cosx, t1) - MULHIGH(sinx, t0)
-
-	add					r8, r8, r5										@ xptr += step@
-	VSHR.S32			Q10, Q0, #2										@ t0 = r0 >> 2@
-	VSHR.S32			Q11, Q1, #2										@ t1 = r1 >> 2@
-
-	VSUB.S32			Q0,	Q10, Q2										@ r0 = t0 - r2@
-	VSUB.S32			Q1,	Q11, Q3										@ r1 = t1 - r3@
-	VADD.S32			Q2, Q10, Q2										@ r2 = t0 + r2@
-	VADD.S32			Q3, Q11, Q3										@ r3 = t1 + r3@
-
-	VLD2.I32			{D8, D9, D10, D11}, [r8]
-	VLD2.I32			{D28, D29, D30, D31}, [r6]!
-	add						r8, r8, r5
-
-	VQDMULH.S32		Q10, Q4, Q14									@ MULHIGH(cosx, t0)
-	VQDMULH.S32		Q11, Q5, Q15									@ MULHIGH(sinx, t1)
-	VQDMULH.S32		Q12, Q5, Q14									@ MULHIGH(cosx, t1)
-	VQDMULH.S32		Q13, Q4, Q15									@ MULHIGH(sinx, t0)
-
-	VADD.S32			Q8, Q10, Q11									@ MULHIGH(cosx, t0) + MULHIGH(sinx, t1)
-	VSUB.S32			Q9, Q12, Q13									@ MULHIGH(cosx, t1) - MULHIGH(sinx, t0)
-
-	VLD2.I32		{D12, D13, D14, D15}, [r8]
-	VLD2.I32		{D28, D29, D30, D31}, [r6]!
-
-	VQDMULH.S32		Q10, Q6, Q14									@ MULHIGH(cosx, t0)
-	VQDMULH.S32		Q11, Q7, Q15									@ MULHIGH(sinx, t1)
-	VQDMULH.S32		Q12, Q7, Q14									@ MULHIGH(cosx, t1)
-	VQDMULH.S32		Q13, Q6, Q15									@ MULHIGH(sinx, t0)
-
-	VADD.S32			Q6, Q10, Q11									@ MULHIGH(cosx, t0) + MULHIGH(sinx, t1)
-	VSUB.S32			Q7, Q12, Q13									@ MULHIGH(cosx, t1) - MULHIGH(sinx, t0)
-
-	VADD.S32			Q4, Q8, Q6										@ r4 = t0 + r6@
-	VSUB.S32			Q5, Q7, Q9										@ r5 = r7 - t1@
-	VSUB.S32			Q6, Q8, Q6										@ r6 = t0 - r6@
-	VADD.S32			Q7, Q7, Q9										@ r7 = r7 + t1@
-
-	VADD.S32			Q8, Q0, Q5										@ xptr[0] = r0 + r5@
-	VADD.S32			Q9, Q1, Q6										@ xptr[1] = r1 + r6@
-	VST2.I32			{D16, D17, D18, D19}, [r8]
-
-	VSUB.S32			Q10, Q2, Q4										@ xptr[0] = r2 - r4@
-	sub					r8, r8, r5										@ xptr -= step@
-	VSUB.S32			Q11, Q3, Q7										@ xptr[1] = r3 - r7@
-	VST2.I32			{D20, D21, D22, D23}, [r8]
-
-	VSUB.S32			Q8, Q0, Q5										@ xptr[0] = r0 - r5@
-	sub					r8, r8, r5										@ xptr -= step@
-	VSUB.S32			Q9, Q1, Q6										@ xptr[1] = r1 - r6@
-	VST2.I32			{D16, D17, D18, D19}, [r8]
-
-	VADD.S32			Q10, Q2, Q4										@ xptr[0] = r2 + r4@
-	sub					r8, r8, r5										@ xptr -= step@
-	VADD.S32			Q11, Q3, Q7										@ xptr[1] = r3 + r7@
-	VST2.I32			{D20, D21, D22, D23}, [r8]!
-
-	subs    			r4, r4, #4
-	bne     			Radix4FFT_LOOP3
-
-Radix4FFT_LOOP2_END:
-	add     			r8, r8, r12
-	sub    				r7, r7, #1
-	cmp					r7, #0
-	bhi     			Radix4FFT_LOOP2
-
-Radix4FFT_LOOP1_END:
-	add     			r3, r12, r3
-	mov     			r2, r2, lsl #2
-	movs    			r1, r1, asr #2
-	bne     			Radix4FFT_LOOP1
-
-Radix4FFT_END:
-	fldmfdd   			sp!, {d8 - d15}
-	ldmia   			sp!, {r4 - r11, pc}
-
-	@ENDP  @ |Radix4FFT|
-	.fnend
diff --git a/media/libstagefright/codecs/aacenc/src/band_nrg.c b/media/libstagefright/codecs/aacenc/src/band_nrg.c
deleted file mode 100644
index e4034b8..0000000
--- a/media/libstagefright/codecs/aacenc/src/band_nrg.c
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		band_nrg.c
-
-	Content:	Band/Line energy calculations functions
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "band_nrg.h"
-
-#ifndef ARMV5E
-/********************************************************************************
-*
-* function name: CalcBandEnergy
-* description:   Calc sfb-bandwise mdct-energies for left and right channel
-*
-**********************************************************************************/
-void CalcBandEnergy(const Word32 *mdctSpectrum,
-                    const Word16 *bandOffset,
-                    const Word16  numBands,
-                    Word32       *bandEnergy,
-                    Word32       *bandEnergySum)
-{
-  Word32 i, j;
-  Word32 accuSum = 0;
-
-  for (i=0; i<numBands; i++) {
-    Word32 accu = 0;
-    for (j=bandOffset[i]; j<bandOffset[i+1]; j++)
-      accu = L_add(accu, MULHIGH(mdctSpectrum[j], mdctSpectrum[j]));
-
-	accu = L_add(accu, accu);
-    accuSum = L_add(accuSum, accu);
-    bandEnergy[i] = accu;
-  }
-  *bandEnergySum = accuSum;
-}
-
-/********************************************************************************
-*
-* function name: CalcBandEnergyMS
-* description:   Calc sfb-bandwise mdct-energies for left add or minus right channel
-*
-**********************************************************************************/
-void CalcBandEnergyMS(const Word32 *mdctSpectrumLeft,
-                      const Word32 *mdctSpectrumRight,
-                      const Word16 *bandOffset,
-                      const Word16  numBands,
-                      Word32       *bandEnergyMid,
-                      Word32       *bandEnergyMidSum,
-                      Word32       *bandEnergySide,
-                      Word32       *bandEnergySideSum)
-{
-
-  Word32 i, j;
-  Word32 accuMidSum = 0;
-  Word32 accuSideSum = 0;
-
-
-  for(i=0; i<numBands; i++) {
-    Word32 accuMid = 0;
-    Word32 accuSide = 0;
-    for (j=bandOffset[i]; j<bandOffset[i+1]; j++) {
-      Word32 specm, specs;
-      Word32 l, r;
-
-      l = mdctSpectrumLeft[j] >> 1;
-      r = mdctSpectrumRight[j] >> 1;
-      specm = l + r;
-      specs = l - r;
-      accuMid = L_add(accuMid, MULHIGH(specm, specm));
-      accuSide = L_add(accuSide, MULHIGH(specs, specs));
-    }
-
-	accuMid = L_add(accuMid, accuMid);
-	accuSide = L_add(accuSide, accuSide);
-	bandEnergyMid[i] = accuMid;
-    accuMidSum = L_add(accuMidSum, accuMid);
-    bandEnergySide[i] = accuSide;
-    accuSideSum = L_add(accuSideSum, accuSide);
-
-  }
-  *bandEnergyMidSum = accuMidSum;
-  *bandEnergySideSum = accuSideSum;
-}
-
-#endif
diff --git a/media/libstagefright/codecs/aacenc/src/bit_cnt.c b/media/libstagefright/codecs/aacenc/src/bit_cnt.c
deleted file mode 100644
index 65b035e..0000000
--- a/media/libstagefright/codecs/aacenc/src/bit_cnt.c
+++ /dev/null
@@ -1,885 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		bit_cnt.c
-
-	Content:	Huffman Bitcounter & coder functions
-
-*******************************************************************************/
-
-#include "bit_cnt.h"
-#include "aac_rom.h"
-
-#define HI_LTAB(a) ((a)>>8)
-#define LO_LTAB(a) ((a) & 0xff)
-
-#define EXPAND(a)  ((((Word32)((a)&0xff00)) << 8)|(Word32)((a)&0xff))
-
-
-/*****************************************************************************
-*
-* function name: count1_2_3_4_5_6_7_8_9_10_11
-* description:  counts tables 1-11
-* returns:
-* input:        quantized spectrum
-* output:       bitCount for tables 1-11
-*
-*****************************************************************************/
-
-static void count1_2_3_4_5_6_7_8_9_10_11(const Word16 *values,
-                                         const Word16  width,
-                                         Word16       *bitCount)
-{
-  Word32 t0,t1,t2,t3,i;
-  Word32 bc1_2,bc3_4,bc5_6,bc7_8,bc9_10;
-  Word16 bc11,sc;
-
-  bc1_2=0;
-  bc3_4=0;
-  bc5_6=0;
-  bc7_8=0;
-  bc9_10=0;
-  bc11=0;
-  sc=0;
-
-  for(i=0;i<width;i+=4){
-
-    t0= values[i+0];
-    t1= values[i+1];
-    t2= values[i+2];
-    t3= values[i+3];
-
-    /* 1,2 */
-
-    bc1_2 = bc1_2 + EXPAND(huff_ltab1_2[t0+1][t1+1][t2+1][t3+1]);
-
-    /* 5,6 */
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t0+4][t1+4]);
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t2+4][t3+4]);
-
-    t0=ABS(t0);
-    t1=ABS(t1);
-    t2=ABS(t2);
-    t3=ABS(t3);
-
-
-    bc3_4 = bc3_4 + EXPAND(huff_ltab3_4[t0][t1][t2][t3]);
-
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t2][t3]);
-
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t2][t3]);
-
-    bc11 = bc11 + huff_ltab11[t0][t1];
-    bc11 = bc11 + huff_ltab11[t2][t3];
-
-
-    sc = sc + (t0>0) + (t1>0) + (t2>0) + (t3>0);
-  }
-
-  bitCount[1]=extract_h(bc1_2);
-  bitCount[2]=extract_l(bc1_2);
-  bitCount[3]=extract_h(bc3_4) + sc;
-  bitCount[4]=extract_l(bc3_4) + sc;
-  bitCount[5]=extract_h(bc5_6);
-  bitCount[6]=extract_l(bc5_6);
-  bitCount[7]=extract_h(bc7_8) + sc;
-  bitCount[8]=extract_l(bc7_8) + sc;
-  bitCount[9]=extract_h(bc9_10) + sc;
-  bitCount[10]=extract_l(bc9_10) + sc;
-  bitCount[11]=bc11 + sc;
-}
-
-
-/*****************************************************************************
-*
-* function name: count3_4_5_6_7_8_9_10_11
-* description:  counts tables 3-11
-* returns:
-* input:        quantized spectrum
-* output:       bitCount for tables 3-11
-*
-*****************************************************************************/
-
-static void count3_4_5_6_7_8_9_10_11(const Word16 *values,
-                                     const Word16  width,
-                                     Word16       *bitCount)
-{
-  Word32 t0,t1,t2,t3, i;
-  Word32 bc3_4,bc5_6,bc7_8,bc9_10;
-  Word16 bc11,sc;
-
-  bc3_4=0;
-  bc5_6=0;
-  bc7_8=0;
-  bc9_10=0;
-  bc11=0;
-  sc=0;
-
-  for(i=0;i<width;i+=4){
-
-    t0= values[i+0];
-    t1= values[i+1];
-    t2= values[i+2];
-    t3= values[i+3];
-
-    /*
-      5,6
-    */
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t0+4][t1+4]);
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t2+4][t3+4]);
-
-    t0=ABS(t0);
-    t1=ABS(t1);
-    t2=ABS(t2);
-    t3=ABS(t3);
-
-
-    bc3_4 = bc3_4 + EXPAND(huff_ltab3_4[t0][t1][t2][t3]);
-
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t2][t3]);
-
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t2][t3]);
-
-    bc11 = bc11 + huff_ltab11[t0][t1];
-    bc11 = bc11 + huff_ltab11[t2][t3];
-
-
-    sc = sc + (t0>0) + (t1>0) + (t2>0) + (t3>0);
-  }
-
-  bitCount[1]=INVALID_BITCOUNT;
-  bitCount[2]=INVALID_BITCOUNT;
-  bitCount[3]=extract_h(bc3_4) + sc;
-  bitCount[4]=extract_l(bc3_4) + sc;
-  bitCount[5]=extract_h(bc5_6);
-  bitCount[6]=extract_l(bc5_6);
-  bitCount[7]=extract_h(bc7_8) + sc;
-  bitCount[8]=extract_l(bc7_8) + sc;
-  bitCount[9]=extract_h(bc9_10) + sc;
-  bitCount[10]=extract_l(bc9_10) + sc;
-  bitCount[11]=bc11 + sc;
-
-}
-
-
-
-/*****************************************************************************
-*
-* function name: count5_6_7_8_9_10_11
-* description:  counts tables 5-11
-* returns:
-* input:        quantized spectrum
-* output:       bitCount for tables 5-11
-*
-*****************************************************************************/
-static void count5_6_7_8_9_10_11(const Word16 *values,
-                                 const Word16  width,
-                                 Word16       *bitCount)
-{
-
-  Word32 t0,t1,i;
-  Word32 bc5_6,bc7_8,bc9_10;
-  Word16 bc11,sc;
-
-  bc5_6=0;
-  bc7_8=0;
-  bc9_10=0;
-  bc11=0;
-  sc=0;
-
-  for(i=0;i<width;i+=2){
-
-    t0 = values[i+0];
-    t1 = values[i+1];
-
-    bc5_6 = bc5_6 + EXPAND(huff_ltab5_6[t0+4][t1+4]);
-
-    t0=ABS(t0);
-    t1=ABS(t1);
-
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);
-    bc11 = bc11 + huff_ltab11[t0][t1];
-
-
-    sc = sc + (t0>0) + (t1>0);
-  }
-  bitCount[1]=INVALID_BITCOUNT;
-  bitCount[2]=INVALID_BITCOUNT;
-  bitCount[3]=INVALID_BITCOUNT;
-  bitCount[4]=INVALID_BITCOUNT;
-  bitCount[5]=extract_h(bc5_6);
-  bitCount[6]=extract_l(bc5_6);
-  bitCount[7]=extract_h(bc7_8) + sc;
-  bitCount[8]=extract_l(bc7_8) + sc;
-  bitCount[9]=extract_h(bc9_10) + sc;
-  bitCount[10]=extract_l(bc9_10) + sc;
-  bitCount[11]=bc11 + sc;
-
-}
-
-
-/*****************************************************************************
-*
-* function name: count7_8_9_10_11
-* description:  counts tables 7-11
-* returns:
-* input:        quantized spectrum
-* output:       bitCount for tables 7-11
-*
-*****************************************************************************/
-
-static void count7_8_9_10_11(const Word16 *values,
-                             const Word16  width,
-                             Word16       *bitCount)
-{
-  Word32 t0,t1, i;
-  Word32 bc7_8,bc9_10;
-  Word16 bc11,sc;
-
-  bc7_8=0;
-  bc9_10=0;
-  bc11=0;
-  sc=0;
-
-  for(i=0;i<width;i+=2){
-
-    t0=ABS(values[i+0]);
-    t1=ABS(values[i+1]);
-
-    bc7_8 = bc7_8 + EXPAND(huff_ltab7_8[t0][t1]);
-    bc9_10 = bc9_10 + EXPAND(huff_ltab9_10[t0][t1]);
-    bc11 = bc11 + huff_ltab11[t0][t1];
-
-
-    sc = sc + (t0>0) + (t1>0);
-  }
-  bitCount[1]=INVALID_BITCOUNT;
-  bitCount[2]=INVALID_BITCOUNT;
-  bitCount[3]=INVALID_BITCOUNT;
-  bitCount[4]=INVALID_BITCOUNT;
-  bitCount[5]=INVALID_BITCOUNT;
-  bitCount[6]=INVALID_BITCOUNT;
-  bitCount[7]=extract_h(bc7_8) + sc;
-  bitCount[8]=extract_l(bc7_8) + sc;
-  bitCount[9]=extract_h(bc9_10) + sc;
-  bitCount[10]=extract_l(bc9_10) + sc;
-  bitCount[11]=bc11 + sc;
-
-}
-
-/*****************************************************************************
-*
-* function name: count9_10_11
-* description:  counts tables 9-11
-* returns:
-* input:        quantized spectrum
-* output:       bitCount for tables 9-11
-*
-*****************************************************************************/
-static void count9_10_11(const Word16 *values,
-                         const Word16  width,
-                         Word16       *bitCount)
-{
-
-  Word32 t0,t1,i;
-  Word32 bc9_10;
-  Word16 bc11,sc;
-
-  bc9_10=0;
-  bc11=0;
-  sc=0;
-
-  for(i=0;i<width;i+=2){
-
-    t0=ABS(values[i+0]);
-    t1=ABS(values[i+1]);
-
-
-    bc9_10 += EXPAND(huff_ltab9_10[t0][t1]);
-    bc11 = bc11 + huff_ltab11[t0][t1];
-
-
-    sc = sc + (t0>0) + (t1>0);
-  }
-  bitCount[1]=INVALID_BITCOUNT;
-  bitCount[2]=INVALID_BITCOUNT;
-  bitCount[3]=INVALID_BITCOUNT;
-  bitCount[4]=INVALID_BITCOUNT;
-  bitCount[5]=INVALID_BITCOUNT;
-  bitCount[6]=INVALID_BITCOUNT;
-  bitCount[7]=INVALID_BITCOUNT;
-  bitCount[8]=INVALID_BITCOUNT;
-  bitCount[9]=extract_h(bc9_10) + sc;
-  bitCount[10]=extract_l(bc9_10) + sc;
-  bitCount[11]=bc11 + sc;
-
-}
-
-/*****************************************************************************
-*
-* function name: count11
-* description:  counts table 11
-* returns:
-* input:        quantized spectrum
-* output:       bitCount for table 11
-*
-*****************************************************************************/
- static void count11(const Word16 *values,
-                    const Word16  width,
-                    Word16        *bitCount)
-{
-  Word32 t0,t1,i;
-  Word16 bc11,sc;
-
-  bc11=0;
-  sc=0;
-  for(i=0;i<width;i+=2){
-    t0=ABS(values[i+0]);
-    t1=ABS(values[i+1]);
-    bc11 = bc11 + huff_ltab11[t0][t1];
-
-
-    sc = sc + (t0>0) + (t1>0);
-  }
-
-  bitCount[1]=INVALID_BITCOUNT;
-  bitCount[2]=INVALID_BITCOUNT;
-  bitCount[3]=INVALID_BITCOUNT;
-  bitCount[4]=INVALID_BITCOUNT;
-  bitCount[5]=INVALID_BITCOUNT;
-  bitCount[6]=INVALID_BITCOUNT;
-  bitCount[7]=INVALID_BITCOUNT;
-  bitCount[8]=INVALID_BITCOUNT;
-  bitCount[9]=INVALID_BITCOUNT;
-  bitCount[10]=INVALID_BITCOUNT;
-  bitCount[11]=bc11 + sc;
-}
-
-/*****************************************************************************
-*
-* function name: countEsc
-* description:  counts table 11 (with Esc)
-* returns:
-* input:        quantized spectrum
-* output:       bitCount for tables 11 (with Esc)
-*
-*****************************************************************************/
-
-static void countEsc(const Word16 *values,
-                     const Word16  width,
-                     Word16       *bitCount)
-{
-  Word32 t0,t1,t00,t01,i;
-  Word16 bc11,ec,sc;
-
-  bc11=0;
-  sc=0;
-  ec=0;
-  for(i=0;i<width;i+=2){
-    t0=ABS(values[i+0]);
-    t1=ABS(values[i+1]);
-
-
-    sc = sc + (t0>0) + (t1>0);
-
-    t00 = min(t0,16);
-    t01 = min(t1,16);
-    bc11 = bc11 + huff_ltab11[t00][t01];
-
-
-    if(t0 >= 16){
-      ec = ec + 5;
-      while(sub(t0=(t0 >> 1), 16) >= 0) {
-        ec = ec + 2;
-      }
-    }
-
-
-    if(t1 >= 16){
-      ec = ec + 5;
-      while(sub(t1=(t1 >> 1), 16) >= 0) {
-        ec = ec + 2;
-      }
-    }
-  }
-  bitCount[1]=INVALID_BITCOUNT;
-  bitCount[2]=INVALID_BITCOUNT;
-  bitCount[3]=INVALID_BITCOUNT;
-  bitCount[4]=INVALID_BITCOUNT;
-  bitCount[5]=INVALID_BITCOUNT;
-  bitCount[6]=INVALID_BITCOUNT;
-  bitCount[7]=INVALID_BITCOUNT;
-  bitCount[8]=INVALID_BITCOUNT;
-  bitCount[9]=INVALID_BITCOUNT;
-  bitCount[10]=INVALID_BITCOUNT;
-  bitCount[11]=bc11 + sc + ec;
-}
-
-
-typedef void (*COUNT_FUNCTION)(const Word16 *values,
-                               const Word16  width,
-                               Word16       *bitCount);
-
-static COUNT_FUNCTION countFuncTable[CODE_BOOK_ESC_LAV+1] =
-  {
-
-    count1_2_3_4_5_6_7_8_9_10_11,  /* 0  */
-    count1_2_3_4_5_6_7_8_9_10_11,  /* 1  */
-    count3_4_5_6_7_8_9_10_11,      /* 2  */
-    count5_6_7_8_9_10_11,          /* 3  */
-    count5_6_7_8_9_10_11,          /* 4  */
-    count7_8_9_10_11,              /* 5  */
-    count7_8_9_10_11,              /* 6  */
-    count7_8_9_10_11,              /* 7  */
-    count9_10_11,                  /* 8  */
-    count9_10_11,                  /* 9  */
-    count9_10_11,                  /* 10 */
-    count9_10_11,                  /* 11 */
-    count9_10_11,                  /* 12 */
-    count11,                       /* 13 */
-    count11,                       /* 14 */
-    count11,                       /* 15 */
-    countEsc                       /* 16 */
-  };
-
-/*****************************************************************************
-*
-* function name: bitCount
-* description:  count bits
-*
-*****************************************************************************/
-Word16 bitCount(const Word16 *values,
-                const Word16  width,
-                Word16        maxVal,
-                Word16       *bitCount)
-{
-  /*
-    check if we can use codebook 0
-  */
-
-  if(maxVal == 0)
-    bitCount[0] = 0;
-  else
-    bitCount[0] = INVALID_BITCOUNT;
-
-  maxVal = min(maxVal, CODE_BOOK_ESC_LAV);
-  countFuncTable[maxVal](values,width,bitCount);
-
-  return(0);
-}
-
-/*****************************************************************************
-*
-* function name: codeValues
-* description:  write huffum bits
-*
-*****************************************************************************/
-Word16 codeValues(Word16 *values, Word16 width, Word16 codeBook, HANDLE_BIT_BUF hBitstream)
-{
-
-  Word32 i, t0, t1, t2, t3, t00, t01;
-  UWord16 codeWord, codeLength;
-  Word16 sign, signLength;
-
-
-  switch (codeBook) {
-    case CODE_BOOK_ZERO_NO:
-      break;
-
-    case CODE_BOOK_1_NO:
-      for(i=0; i<width; i+=4) {
-        t0         = values[i+0];
-        t1         = values[i+1];
-        t2         = values[i+2];
-        t3         = values[i+3];
-        codeWord   = huff_ctab1[t0+1][t1+1][t2+1][t3+1];
-        codeLength = HI_LTAB(huff_ltab1_2[t0+1][t1+1][t2+1][t3+1]);
-        WriteBits(hBitstream, codeWord, codeLength);
-      }
-      break;
-
-    case CODE_BOOK_2_NO:
-      for(i=0; i<width; i+=4) {
-        t0         = values[i+0];
-        t1         = values[i+1];
-        t2         = values[i+2];
-        t3         = values[i+3];
-        codeWord   = huff_ctab2[t0+1][t1+1][t2+1][t3+1];
-        codeLength = LO_LTAB(huff_ltab1_2[t0+1][t1+1][t2+1][t3+1]);
-        WriteBits(hBitstream,codeWord,codeLength);
-      }
-      break;
-
-    case CODE_BOOK_3_NO:
-      for(i=0; i<width; i+=4) {
-        sign=0;
-        signLength=0;
-        t0 = values[i+0];
-
-        if(t0 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t0 < 0){
-            sign|=1;
-            t0=-t0;
-          }
-        }
-        t1 = values[i+1];
-
-        if(t1 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t1 < 0){
-            sign|=1;
-            t1=-t1;
-          }
-        }
-        t2 = values[i+2];
-
-        if(t2 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t2 < 0){
-            sign|=1;
-            t2=-t2;
-          }
-        }
-        t3 = values[i+3];
-        if(t3 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t3 < 0){
-            sign|=1;
-            t3=-t3;
-          }
-        }
-
-        codeWord   = huff_ctab3[t0][t1][t2][t3];
-        codeLength = HI_LTAB(huff_ltab3_4[t0][t1][t2][t3]);
-        WriteBits(hBitstream,codeWord,codeLength);
-        WriteBits(hBitstream,sign,signLength);
-      }
-      break;
-
-    case CODE_BOOK_4_NO:
-      for(i=0; i<width; i+=4) {
-        sign=0;
-        signLength=0;
-        t0 = values[i+0];
-
-        if(t0 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-          if(t0 < 0){
-            sign|=1;
-            t0=-t0;
-          }
-        }
-        t1 = values[i+1];
-
-        if(t1 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t1 < 0){
-            sign|=1;
-            t1=-t1;
-          }
-        }
-        t2 = values[i+2];
-
-        if(t2 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t2 < 0){
-            sign|=1;
-            t2=-t2;
-          }
-        }
-        t3 = values[i+3];
-
-        if(t3 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t3 < 0){
-            sign|=1;
-            t3=-t3;
-          }
-        }
-        codeWord   = huff_ctab4[t0][t1][t2][t3];
-        codeLength = LO_LTAB(huff_ltab3_4[t0][t1][t2][t3]);
-        WriteBits(hBitstream,codeWord,codeLength);
-        WriteBits(hBitstream,sign,signLength);
-      }
-      break;
-
-    case CODE_BOOK_5_NO:
-      for(i=0; i<width; i+=2) {
-        t0         = values[i+0];
-        t1         = values[i+1];
-        codeWord   = huff_ctab5[t0+4][t1+4];
-        codeLength = HI_LTAB(huff_ltab5_6[t0+4][t1+4]);
-        WriteBits(hBitstream,codeWord,codeLength);
-      }
-      break;
-
-    case CODE_BOOK_6_NO:
-      for(i=0; i<width; i+=2) {
-        t0         = values[i+0];
-        t1         = values[i+1];
-        codeWord   = huff_ctab6[t0+4][t1+4];
-        codeLength = LO_LTAB(huff_ltab5_6[t0+4][t1+4]);
-        WriteBits(hBitstream,codeWord,codeLength);
-      }
-      break;
-
-    case CODE_BOOK_7_NO:
-      for(i=0; i<width; i+=2){
-        sign=0;
-        signLength=0;
-        t0 = values[i+0];
-
-        if(t0 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t0 < 0){
-            sign|=1;
-            t0=-t0;
-          }
-        }
-
-        t1 = values[i+1];
-
-        if(t1 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t1 < 0){
-            sign|=1;
-            t1=-t1;
-          }
-        }
-        codeWord   = huff_ctab7[t0][t1];
-        codeLength = HI_LTAB(huff_ltab7_8[t0][t1]);
-        WriteBits(hBitstream,codeWord,codeLength);
-        WriteBits(hBitstream,sign,signLength);
-      }
-      break;
-
-    case CODE_BOOK_8_NO:
-      for(i=0; i<width; i+=2) {
-        sign=0;
-        signLength=0;
-        t0 = values[i+0];
-
-        if(t0 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t0 < 0){
-            sign|=1;
-            t0=-t0;
-          }
-        }
-
-        t1 = values[i+1];
-
-        if(t1 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t1 < 0){
-            sign|=1;
-            t1=-t1;
-          }
-        }
-        codeWord   = huff_ctab8[t0][t1];
-        codeLength = LO_LTAB(huff_ltab7_8[t0][t1]);
-        WriteBits(hBitstream,codeWord,codeLength);
-        WriteBits(hBitstream,sign,signLength);
-      }
-      break;
-
-    case CODE_BOOK_9_NO:
-      for(i=0; i<width; i+=2) {
-        sign=0;
-        signLength=0;
-        t0 = values[i+0];
-
-        if(t0 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t0 < 0){
-            sign|=1;
-            t0=-t0;
-          }
-        }
-
-        t1 = values[i+1];
-
-        if(t1 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t1 < 0){
-            sign|=1;
-            t1=-t1;
-          }
-        }
-        codeWord   = huff_ctab9[t0][t1];
-        codeLength = HI_LTAB(huff_ltab9_10[t0][t1]);
-        WriteBits(hBitstream,codeWord,codeLength);
-        WriteBits(hBitstream,sign,signLength);
-      }
-      break;
-
-    case CODE_BOOK_10_NO:
-      for(i=0; i<width; i+=2) {
-        sign=0;
-        signLength=0;
-        t0 = values[i+0];
-
-        if(t0 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t0 < 0){
-            sign|=1;
-            t0=-t0;
-          }
-        }
-
-        t1 = values[i+1];
-
-        if(t1 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t1 < 0){
-            sign|=1;
-            t1=-t1;
-          }
-        }
-        codeWord   = huff_ctab10[t0][t1];
-        codeLength = LO_LTAB(huff_ltab9_10[t0][t1]);
-        WriteBits(hBitstream,codeWord,codeLength);
-        WriteBits(hBitstream,sign,signLength);
-      }
-      break;
-
-    case CODE_BOOK_ESC_NO:
-      for(i=0; i<width; i+=2) {
-        sign=0;
-        signLength=0;
-        t0 = values[i+0];
-
-        if(t0 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t0 < 0){
-            sign|=1;
-            t0=-t0;
-          }
-        }
-
-        t1 = values[i+1];
-
-        if(t1 != 0){
-          signLength = signLength + 1;
-          sign = sign << 1;
-
-          if(t1 < 0){
-            sign|=1;
-            t1=-t1;
-          }
-        }
-        t00 = min(t0,16);
-        t01 = min(t1,16);
-
-        codeWord   = huff_ctab11[t00][t01];
-        codeLength = huff_ltab11[t00][t01];
-        WriteBits(hBitstream,codeWord,codeLength);
-        WriteBits(hBitstream,sign,signLength);
-
-        if(t0 >= 16){
-          Word16 n, p;
-          n=0;
-          p=t0;
-          while(sub(p=(p >> 1), 16) >= 0){
-
-            WriteBits(hBitstream,1,1);
-            n = n + 1;
-          }
-          WriteBits(hBitstream,0,1);
-          n = n + 4;
-          WriteBits(hBitstream,(t0 - (1 << n)),n);
-        }
-
-        if(t1 >= 16){
-          Word16 n, p;
-          n=0;
-          p=t1;
-          while(sub(p=(p >> 1), 16) >= 0){
-
-            WriteBits(hBitstream,1,1);
-            n = n + 1;
-          }
-          WriteBits(hBitstream,0,1);
-          n = n + 4;
-          WriteBits(hBitstream,(t1 - (1 << n)),n);
-        }
-      }
-      break;
-
-    default:
-      break;
-  }
-  return(0);
-}
-
-Word16 bitCountScalefactorDelta(Word16 delta)
-{
-  return(huff_ltabscf[delta+CODE_BOOK_SCF_LAV]);
-}
-
-Word16 codeScalefactorDelta(Word16 delta, HANDLE_BIT_BUF hBitstream)
-{
-  Word32 codeWord;
-  Word16 codeLength;
-
-
-  if(delta > CODE_BOOK_SCF_LAV || delta < -CODE_BOOK_SCF_LAV)
-    return(1);
-
-  codeWord   = huff_ctabscf[delta + CODE_BOOK_SCF_LAV];
-  codeLength = huff_ltabscf[delta + CODE_BOOK_SCF_LAV];
-  WriteBits(hBitstream,codeWord,codeLength);
-  return(0);
-}
diff --git a/media/libstagefright/codecs/aacenc/src/bitbuffer.c b/media/libstagefright/codecs/aacenc/src/bitbuffer.c
deleted file mode 100644
index 15eebd0..0000000
--- a/media/libstagefright/codecs/aacenc/src/bitbuffer.c
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		bitbuffer.c
-
-	Content:	Bit Buffer Management functions
-
-*******************************************************************************/
-
-#include "bitbuffer.h"
-
-/*****************************************************************************
-*
-* function name: CreateBitBuffer
-* description:  create and init Bit Buffer Management
-*
-*****************************************************************************/
-HANDLE_BIT_BUF CreateBitBuffer(HANDLE_BIT_BUF hBitBuf,
-                               UWord8 *pBitBufBase,
-                               Word16  bitBufSize)
-{
-  assert(bitBufSize*8 <= 32768);
-
-  hBitBuf->pBitBufBase = pBitBufBase;
-  hBitBuf->pBitBufEnd  = pBitBufBase + bitBufSize - 1;
-
-  hBitBuf->pWriteNext  = pBitBufBase;
-
-  hBitBuf->cache       = 0;
-
-  hBitBuf->wBitPos     = 0;
-  hBitBuf->cntBits     = 0;
-
-  hBitBuf->size        = (bitBufSize << 3);
-  hBitBuf->isValid     = 1;
-
-  return hBitBuf;
-}
-
-/*****************************************************************************
-*
-* function name: DeleteBitBuffer
-* description:  uninit Bit Buffer Management
-*
-*****************************************************************************/
-void DeleteBitBuffer(HANDLE_BIT_BUF *hBitBuf)
-{
-  if(*hBitBuf)
-	(*hBitBuf)->isValid = 0;
-  *hBitBuf = NULL;
-}
-
-/*****************************************************************************
-*
-* function name: ResetBitBuf
-* description:  reset Bit Buffer Management
-*
-*****************************************************************************/
-void ResetBitBuf(HANDLE_BIT_BUF hBitBuf,
-                 UWord8 *pBitBufBase,
-                 Word16  bitBufSize)
-{
-  hBitBuf->pBitBufBase = pBitBufBase;
-  hBitBuf->pBitBufEnd  = pBitBufBase + bitBufSize - 1;
-
-
-  hBitBuf->pWriteNext  = pBitBufBase;
-
-  hBitBuf->wBitPos     = 0;
-  hBitBuf->cntBits     = 0;
-
-  hBitBuf->cache	   = 0;
-}
-
-/*****************************************************************************
-*
-* function name: CopyBitBuf
-* description:  copy Bit Buffer Management
-*
-*****************************************************************************/
-void CopyBitBuf(HANDLE_BIT_BUF hBitBufSrc,
-                HANDLE_BIT_BUF hBitBufDst)
-{
-  *hBitBufDst = *hBitBufSrc;
-}
-
-/*****************************************************************************
-*
-* function name: GetBitsAvail
-* description:  get available bits
-*
-*****************************************************************************/
-Word16 GetBitsAvail(HANDLE_BIT_BUF hBitBuf)
-{
-  return hBitBuf->cntBits;
-}
-
-/*****************************************************************************
-*
-* function name: WriteBits
-* description:  write bits to the buffer
-*
-*****************************************************************************/
-Word16 WriteBits(HANDLE_BIT_BUF hBitBuf,
-                 UWord32 writeValue,
-                 Word16 noBitsToWrite)
-{
-  Word16 wBitPos;
-
-  assert(noBitsToWrite <= (Word16)sizeof(Word32)*8);
-
-  if(noBitsToWrite == 0)
-	  return noBitsToWrite;
-
-  hBitBuf->cntBits += noBitsToWrite;
-
-  wBitPos = hBitBuf->wBitPos;
-  wBitPos += noBitsToWrite;
-  writeValue &= ~(0xffffffff << noBitsToWrite); // Mask out everything except the lowest noBitsToWrite bits
-  writeValue <<= 32 - wBitPos;
-  writeValue |= hBitBuf->cache;
-
-  while (wBitPos >= 8)
-  {
-	  UWord8 tmp;
-	  tmp = (UWord8)((writeValue >> 24) & 0xFF);
-
-	  *hBitBuf->pWriteNext++ = tmp;
-	  writeValue <<= 8;
-	  wBitPos -= 8;
-  }
-
-  hBitBuf->wBitPos = wBitPos;
-  hBitBuf->cache = writeValue;
-
-  return noBitsToWrite;
-}
diff --git a/media/libstagefright/codecs/aacenc/src/bitenc.c b/media/libstagefright/codecs/aacenc/src/bitenc.c
deleted file mode 100644
index 9c81204..0000000
--- a/media/libstagefright/codecs/aacenc/src/bitenc.c
+++ /dev/null
@@ -1,693 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		bitenc.c
-
-	Content:	Bitstream encoder functions
-
-*******************************************************************************/
-
-#include "bitenc.h"
-#include "bit_cnt.h"
-#include "dyn_bits.h"
-#include "qc_data.h"
-#include "interface.h"
-
-#define UNUSED(x) (void)(x)
-
-static const  Word16 globalGainOffset = 100;
-static const  Word16 icsReservedBit   = 0;
-
-
-/*****************************************************************************
-*
-* function name: encodeSpectralData
-* description:  encode spectral data
-* returns:      spectral bits used
-*
-*****************************************************************************/
-static Word32 encodeSpectralData(Word16             *sfbOffset,
-                                 SECTION_DATA       *sectionData,
-                                 Word16             *quantSpectrum,
-                                 HANDLE_BIT_BUF      hBitStream)
-{
-  Word16 i,sfb;
-  Word16 dbgVal;
-  SECTION_INFO* psectioninfo;
-  dbgVal = GetBitsAvail(hBitStream);
-
-  for(i=0; i<sectionData->noOfSections; i++) {
-    psectioninfo = &(sectionData->sectionInfo[i]);
-	/*
-       huffencode spectral data for this section
-    */
-    for(sfb=psectioninfo->sfbStart;
-        sfb<psectioninfo->sfbStart+psectioninfo->sfbCnt;
-        sfb++) {
-      codeValues(quantSpectrum+sfbOffset[sfb],
-                 sfbOffset[sfb+1] - sfbOffset[sfb],
-                 psectioninfo->codeBook,
-                 hBitStream);
-    }
-  }
-
-  return(GetBitsAvail(hBitStream)-dbgVal);
-}
-
-/*****************************************************************************
-*
-* function name:encodeGlobalGain
-* description: encodes Global Gain (common scale factor)
-* returns:     none
-*
-*****************************************************************************/
-static void encodeGlobalGain(Word16 globalGain,
-                             Word16 logNorm,
-                             Word16 scalefac,
-                             HANDLE_BIT_BUF hBitStream)
-{
-  WriteBits(hBitStream, ((globalGain - scalefac) + globalGainOffset-(logNorm << 2)), 8);
-}
-
-
-/*****************************************************************************
-*
-* function name:encodeIcsInfo
-* description: encodes Ics Info
-* returns:     none
-*
-*****************************************************************************/
-
-static void encodeIcsInfo(Word16 blockType,
-                          Word16 windowShape,
-                          Word16 groupingMask,
-                          SECTION_DATA *sectionData,
-                          HANDLE_BIT_BUF  hBitStream)
-{
-  WriteBits(hBitStream,icsReservedBit,1);
-  WriteBits(hBitStream,blockType,2);
-  WriteBits(hBitStream,windowShape,1);
-
-
-  switch(blockType){
-    case LONG_WINDOW:
-    case START_WINDOW:
-    case STOP_WINDOW:
-      WriteBits(hBitStream,sectionData->maxSfbPerGroup,6);
-
-      /* No predictor data present */
-      WriteBits(hBitStream, 0, 1);
-      break;
-
-    case SHORT_WINDOW:
-      WriteBits(hBitStream,sectionData->maxSfbPerGroup,4);
-
-      /*
-      Write grouping bits
-      */
-      WriteBits(hBitStream,groupingMask,TRANS_FAC-1);
-      break;
-  }
-}
-
-/*****************************************************************************
-*
-* function name: encodeSectionData
-* description:  encode section data (common Huffman codebooks for adjacent
-*               SFB's)
-* returns:      none
-*
-*****************************************************************************/
-static Word32 encodeSectionData(SECTION_DATA *sectionData,
-                                HANDLE_BIT_BUF hBitStream)
-{
-  Word16 sectEscapeVal=0,sectLenBits=0;
-  Word16 sectLen;
-  Word16 i;
-  Word16 dbgVal=GetBitsAvail(hBitStream);
-
-
-
-  switch(sectionData->blockType)
-  {
-    case LONG_WINDOW:
-    case START_WINDOW:
-    case STOP_WINDOW:
-      sectEscapeVal = SECT_ESC_VAL_LONG;
-      sectLenBits   = SECT_BITS_LONG;
-      break;
-
-    case SHORT_WINDOW:
-      sectEscapeVal = SECT_ESC_VAL_SHORT;
-      sectLenBits   = SECT_BITS_SHORT;
-      break;
-  }
-
-  for(i=0;i<sectionData->noOfSections;i++) {
-    WriteBits(hBitStream,sectionData->sectionInfo[i].codeBook,4);
-    sectLen = sectionData->sectionInfo[i].sfbCnt;
-
-    while(sectLen >= sectEscapeVal) {
-
-      WriteBits(hBitStream,sectEscapeVal,sectLenBits);
-      sectLen = sectLen - sectEscapeVal;
-    }
-    WriteBits(hBitStream,sectLen,sectLenBits);
-  }
-  return(GetBitsAvail(hBitStream)-dbgVal);
-}
-
-/*****************************************************************************
-*
-* function name: encodeScaleFactorData
-* description:  encode DPCM coded scale factors
-* returns:      none
-*
-*****************************************************************************/
-static Word32 encodeScaleFactorData(UWord16        *maxValueInSfb,
-                                    SECTION_DATA   *sectionData,
-                                    Word16         *scalefac,
-                                    HANDLE_BIT_BUF  hBitStream)
-{
-  Word16 i,j,lastValScf,deltaScf;
-  Word16 dbgVal = GetBitsAvail(hBitStream);
-  SECTION_INFO* psectioninfo;
-
-  lastValScf=scalefac[sectionData->firstScf];
-
-  for(i=0;i<sectionData->noOfSections;i++){
-    psectioninfo = &(sectionData->sectionInfo[i]);
-    if (psectioninfo->codeBook != CODE_BOOK_ZERO_NO){
-      for (j=psectioninfo->sfbStart;
-           j<psectioninfo->sfbStart+psectioninfo->sfbCnt; j++){
-
-        if(maxValueInSfb[j] == 0) {
-          deltaScf = 0;
-        }
-        else {
-          deltaScf = lastValScf - scalefac[j];
-          lastValScf = scalefac[j];
-        }
-
-        if(codeScalefactorDelta(deltaScf,hBitStream)){
-          return(1);
-        }
-      }
-    }
-
-  }
-  return(GetBitsAvail(hBitStream)-dbgVal);
-}
-
-/*****************************************************************************
-*
-* function name:encodeMsInfo
-* description: encodes MS-Stereo Info
-* returns:     none
-*
-*****************************************************************************/
-static void encodeMSInfo(Word16          sfbCnt,
-                         Word16          grpSfb,
-                         Word16          maxSfb,
-                         Word16          msDigest,
-                         Word16         *jsFlags,
-                         HANDLE_BIT_BUF  hBitStream)
-{
-  Word16 sfb, sfbOff;
-
-
-  switch(msDigest)
-  {
-    case MS_NONE:
-      WriteBits(hBitStream,SI_MS_MASK_NONE,2);
-      break;
-
-    case MS_ALL:
-      WriteBits(hBitStream,SI_MS_MASK_ALL,2);
-      break;
-
-    case MS_SOME:
-      WriteBits(hBitStream,SI_MS_MASK_SOME,2);
-      for(sfbOff = 0; sfbOff < sfbCnt; sfbOff+=grpSfb) {
-        for(sfb=0; sfb<maxSfb; sfb++) {
-
-          if(jsFlags[sfbOff+sfb] & MS_ON) {
-            WriteBits(hBitStream,1,1);
-          }
-          else{
-            WriteBits(hBitStream,0,1);
-          }
-        }
-      }
-      break;
-  }
-
-}
-
-/*****************************************************************************
-*
-* function name: encodeTnsData
-* description:  encode TNS data (filter order, coeffs, ..)
-* returns:      none
-*
-*****************************************************************************/
-static void encodeTnsData(TNS_INFO tnsInfo,
-                          Word16 blockType,
-                          HANDLE_BIT_BUF hBitStream) {
-  Word16 i,k;
-  Flag tnsPresent;
-  Word16 numOfWindows;
-  Word16 coefBits;
-  Flag isShort;
-
-
-  if (blockType==2) {
-    isShort = 1;
-    numOfWindows = TRANS_FAC;
-  }
-  else {
-    isShort = 0;
-    numOfWindows = 1;
-  }
-
-  tnsPresent=0;
-  for (i=0; i<numOfWindows; i++) {
-
-    if (tnsInfo.tnsActive[i]) {
-      tnsPresent=1;
-    }
-  }
-
-  if (tnsPresent==0) {
-    WriteBits(hBitStream,0,1);
-  }
-  else{ /* there is data to be written*/
-    WriteBits(hBitStream,1,1); /*data_present */
-    for (i=0; i<numOfWindows; i++) {
-
-      WriteBits(hBitStream,tnsInfo.tnsActive[i],(isShort?1:2));
-
-      if (tnsInfo.tnsActive[i]) {
-
-        WriteBits(hBitStream,((tnsInfo.coefRes[i] - 4)==0?1:0),1);
-
-        WriteBits(hBitStream,tnsInfo.length[i],(isShort?4:6));
-
-        WriteBits(hBitStream,tnsInfo.order[i],(isShort?3:5));
-
-        if (tnsInfo.order[i]){
-          WriteBits(hBitStream, FILTER_DIRECTION, 1);
-
-          if(tnsInfo.coefRes[i] == 4) {
-            coefBits = 3;
-            for(k=0; k<tnsInfo.order[i]; k++) {
-
-              if (tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] > 3 ||
-                  tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] < -4) {
-                coefBits = 4;
-                break;
-              }
-            }
-          }
-          else {
-            coefBits = 2;
-            for(k=0; k<tnsInfo.order[i]; k++) {
-
-              if (tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] > 1 ||
-                  tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] < -2) {
-                coefBits = 3;
-                break;
-              }
-            }
-          }
-          WriteBits(hBitStream, tnsInfo.coefRes[i] - coefBits, 1); /*coef_compres*/
-          for (k=0; k<tnsInfo.order[i]; k++ ) {
-            static const Word16 rmask[] = {0,1,3,7,15};
-
-            WriteBits(hBitStream,tnsInfo.coef[i*TNS_MAX_ORDER_SHORT+k] & rmask[coefBits],coefBits);
-          }
-        }
-      }
-    }
-  }
-
-}
-
-/*****************************************************************************
-*
-* function name: encodeGainControlData
-* description:  unsupported
-* returns:      none
-*
-*****************************************************************************/
-static void encodeGainControlData(HANDLE_BIT_BUF hBitStream)
-{
-  WriteBits(hBitStream,0,1);
-}
-
-/*****************************************************************************
-*
-* function name: encodePulseData
-* description:  not supported yet (dummy)
-* returns:      none
-*
-*****************************************************************************/
-static void encodePulseData(HANDLE_BIT_BUF hBitStream)
-{
-  WriteBits(hBitStream,0,1);
-}
-
-
-/*****************************************************************************
-*
-* function name: WriteIndividualChannelStream
-* description:  management of write process of individual channel stream
-* returns:      none
-*
-*****************************************************************************/
-static void
-writeIndividualChannelStream(Flag   commonWindow,
-                             Word16 mdctScale,
-                             Word16 windowShape,
-                             Word16 groupingMask,
-                             Word16 *sfbOffset,
-                             Word16 scf[],
-                             UWord16 *maxValueInSfb,
-                             Word16 globalGain,
-                             Word16 quantSpec[],
-                             SECTION_DATA *sectionData,
-                             HANDLE_BIT_BUF hBitStream,
-                             TNS_INFO tnsInfo)
-{
-  Word16 logNorm;
-
-  logNorm = LOG_NORM_PCM - (mdctScale + 1);
-
-  encodeGlobalGain(globalGain, logNorm,scf[sectionData->firstScf], hBitStream);
-
-
-  if(!commonWindow) {
-    encodeIcsInfo(sectionData->blockType, windowShape, groupingMask, sectionData, hBitStream);
-  }
-
-  encodeSectionData(sectionData, hBitStream);
-
-  encodeScaleFactorData(maxValueInSfb,
-                        sectionData,
-                        scf,
-                        hBitStream);
-
-  encodePulseData(hBitStream);
-
-  encodeTnsData(tnsInfo, sectionData->blockType, hBitStream);
-
-  encodeGainControlData(hBitStream);
-
-  encodeSpectralData(sfbOffset,
-                     sectionData,
-                     quantSpec,
-                     hBitStream);
-
-}
-
-/*****************************************************************************
-*
-* function name: writeSingleChannelElement
-* description:  write single channel element to bitstream
-* returns:      none
-*
-*****************************************************************************/
-static Word16 writeSingleChannelElement(Word16 instanceTag,
-                                        Word16 *sfbOffset,
-                                        QC_OUT_CHANNEL* qcOutChannel,
-                                        HANDLE_BIT_BUF hBitStream,
-                                        TNS_INFO tnsInfo)
-{
-  WriteBits(hBitStream,ID_SCE,3);
-  WriteBits(hBitStream,instanceTag,4);
-  writeIndividualChannelStream(0,
-                               qcOutChannel->mdctScale,
-                               qcOutChannel->windowShape,
-                               qcOutChannel->groupingMask,
-                               sfbOffset,
-                               qcOutChannel->scf,
-                               qcOutChannel->maxValueInSfb,
-                               qcOutChannel->globalGain,
-                               qcOutChannel->quantSpec,
-                               &(qcOutChannel->sectionData),
-                               hBitStream,
-                               tnsInfo
-                               );
-  return(0);
-}
-
-
-
-/*****************************************************************************
-*
-* function name: writeChannelPairElement
-* description:
-* returns:      none
-*
-*****************************************************************************/
-static Word16 writeChannelPairElement(Word16 instanceTag,
-                                      Word16 msDigest,
-                                      Word16 msFlags[MAX_GROUPED_SFB],
-                                      Word16 *sfbOffset[2],
-                                      QC_OUT_CHANNEL qcOutChannel[2],
-                                      HANDLE_BIT_BUF hBitStream,
-                                      TNS_INFO tnsInfo[2])
-{
-  WriteBits(hBitStream,ID_CPE,3);
-  WriteBits(hBitStream,instanceTag,4);
-  WriteBits(hBitStream,1,1); /* common window */
-
-  encodeIcsInfo(qcOutChannel[0].sectionData.blockType,
-                qcOutChannel[0].windowShape,
-                qcOutChannel[0].groupingMask,
-                &(qcOutChannel[0].sectionData),
-                hBitStream);
-
-  encodeMSInfo(qcOutChannel[0].sectionData.sfbCnt,
-               qcOutChannel[0].sectionData.sfbPerGroup,
-               qcOutChannel[0].sectionData.maxSfbPerGroup,
-               msDigest,
-               msFlags,
-               hBitStream);
-
-  writeIndividualChannelStream(1,
-                               qcOutChannel[0].mdctScale,
-                               qcOutChannel[0].windowShape,
-                               qcOutChannel[0].groupingMask,
-                               sfbOffset[0],
-                               qcOutChannel[0].scf,
-                               qcOutChannel[0].maxValueInSfb,
-                               qcOutChannel[0].globalGain,
-                               qcOutChannel[0].quantSpec,
-                               &(qcOutChannel[0].sectionData),
-                               hBitStream,
-                               tnsInfo[0]);
-
-  writeIndividualChannelStream(1,
-                               qcOutChannel[1].mdctScale,
-                               qcOutChannel[1].windowShape,
-                               qcOutChannel[1].groupingMask,
-                               sfbOffset[1],
-                               qcOutChannel[1].scf,
-                               qcOutChannel[1].maxValueInSfb,
-                               qcOutChannel[1].globalGain,
-                               qcOutChannel[1].quantSpec,
-                               &(qcOutChannel[1].sectionData),
-                               hBitStream,
-                               tnsInfo[1]);
-
-  return(0);
-}
-
-
-
-/*****************************************************************************
-*
-* function name: writeFillElement
-* description:  write fill elements to bitstream
-* returns:      none
-*
-*****************************************************************************/
-static void writeFillElement( const UWord8 *ancBytes,
-                              Word16 totFillBits,
-                              HANDLE_BIT_BUF hBitStream)
-{
-  Word16 i;
-  Word16 cnt,esc_count;
-
-  /*
-    Write fill Element(s):
-    amount of a fill element can be 7+X*8 Bits, X element of [0..270]
-  */
-
-  while(totFillBits >= (3+4)) {
-    cnt = min(((totFillBits - (3+4)) >> 3), ((1<<4)-1));
-
-    WriteBits(hBitStream,ID_FIL,3);
-    WriteBits(hBitStream,cnt,4);
-
-    totFillBits = totFillBits - (3+4);
-
-
-    if (cnt == (1<<4)-1) {
-
-      esc_count = min( ((totFillBits >> 3) - ((1<<4)-1)), (1<<8)-1);
-      WriteBits(hBitStream,esc_count,8);
-      totFillBits = (totFillBits - 8);
-      cnt = cnt + (esc_count - 1);
-    }
-
-    for(i=0;i<cnt;i++) {
-
-      if(ancBytes)
-        WriteBits(hBitStream, *ancBytes++,8);
-      else
-        WriteBits(hBitStream,0,8);
-      totFillBits = totFillBits - 8;
-    }
-  }
-}
-
-/*****************************************************************************
-*
-* function name: WriteBitStream
-* description:  main function of write bitsteam process
-* returns:      0 if success
-*
-*****************************************************************************/
-Word16 WriteBitstream (HANDLE_BIT_BUF hBitStream,
-                       ELEMENT_INFO elInfo,
-                       QC_OUT *qcOut,
-                       PSY_OUT *psyOut,
-                       Word16 *globUsedBits,
-                       const UWord8 *ancBytes,
-					   Word16 sampindex
-                       ) /* returns error code */
-{
-  Word16 bitMarkUp;
-  Word16 elementUsedBits;
-  Word16 frameBits=0;
-
-  UNUSED(ancBytes);
-
-  /*   struct bitbuffer bsWriteCopy; */
-  bitMarkUp = GetBitsAvail(hBitStream);
-  if(qcOut->qcElement.adtsUsed)  /*  write adts header*/
-  {
-	  WriteBits(hBitStream, 0xFFF, 12); /* 12 bit Syncword */
-	  WriteBits(hBitStream, 1, 1); /* ID == 0 for MPEG4 AAC, 1 for MPEG2 AAC */
-	  WriteBits(hBitStream, 0, 2); /* layer == 0 */
-	  WriteBits(hBitStream, 1, 1); /* protection absent */
-	  WriteBits(hBitStream, 1, 2); /* profile */
-	  WriteBits(hBitStream, sampindex, 4); /* sampling rate */
-	  WriteBits(hBitStream, 0, 1); /* private bit */
-	  WriteBits(hBitStream, elInfo.nChannelsInEl, 3); /* ch. config (must be > 0) */
-								   /* simply using numChannels only works for
-									6 channels or less, else a channel
-									configuration should be written */
-	  WriteBits(hBitStream, 0, 1); /* original/copy */
-	  WriteBits(hBitStream, 0, 1); /* home */
-
-	  /* Variable ADTS header */
-	  WriteBits(hBitStream, 0, 1); /* copyr. id. bit */
-	  WriteBits(hBitStream, 0, 1); /* copyr. id. start */
-	  WriteBits(hBitStream, *globUsedBits >> 3, 13);
-	  WriteBits(hBitStream, 0x7FF, 11); /* buffer fullness (0x7FF for VBR) */
-	  WriteBits(hBitStream, 0, 2); /* raw data blocks (0+1=1) */
-  }
-
-  *globUsedBits=0;
-
-  {
-
-    Word16 *sfbOffset[2];
-    TNS_INFO tnsInfo[2];
-    elementUsedBits = 0;
-
-    switch (elInfo.elType) {
-
-      case ID_SCE:      /* single channel */
-        sfbOffset[0] = psyOut->psyOutChannel[elInfo.ChannelIndex[0]].sfbOffsets;
-        tnsInfo[0] = psyOut->psyOutChannel[elInfo.ChannelIndex[0]].tnsInfo;
-
-        writeSingleChannelElement(elInfo.instanceTag,
-                                  sfbOffset[0],
-                                  &qcOut->qcChannel[elInfo.ChannelIndex[0]],
-                                  hBitStream,
-                                  tnsInfo[0]);
-        break;
-
-      case ID_CPE:     /* channel pair */
-        {
-          Word16 msDigest;
-          Word16 *msFlags = psyOut->psyOutElement.toolsInfo.msMask;
-          msDigest = psyOut->psyOutElement.toolsInfo.msDigest;
-          sfbOffset[0] =
-            psyOut->psyOutChannel[elInfo.ChannelIndex[0]].sfbOffsets;
-          sfbOffset[1] =
-            psyOut->psyOutChannel[elInfo.ChannelIndex[1]].sfbOffsets;
-
-          tnsInfo[0]=
-            psyOut->psyOutChannel[elInfo.ChannelIndex[0]].tnsInfo;
-          tnsInfo[1]=
-            psyOut->psyOutChannel[elInfo.ChannelIndex[1]].tnsInfo;
-          writeChannelPairElement(elInfo.instanceTag,
-                                  msDigest,
-                                  msFlags,
-                                  sfbOffset,
-                                  &qcOut->qcChannel[elInfo.ChannelIndex[0]],
-                                  hBitStream,
-                                  tnsInfo);
-        }
-        break;
-
-      default:
-        return(1);
-
-      }   /* switch */
-
-    elementUsedBits = elementUsedBits - bitMarkUp;
-    bitMarkUp = GetBitsAvail(hBitStream);
-    frameBits = frameBits + elementUsedBits + bitMarkUp;
-
-  }
-
-  writeFillElement(NULL,
-                   qcOut->totFillBits,
-                   hBitStream);
-
-  WriteBits(hBitStream,ID_END,3);
-
-  /* byte alignement */
-  WriteBits(hBitStream,0, (8 - (hBitStream->cntBits & 7)) & 7);
-
-  *globUsedBits = *globUsedBits- bitMarkUp;
-  bitMarkUp = GetBitsAvail(hBitStream);
-  *globUsedBits = *globUsedBits + bitMarkUp;
-  frameBits = frameBits + *globUsedBits;
-
-
-  if (frameBits !=  (qcOut->totStaticBitsUsed+qcOut->totDynBitsUsed + qcOut->totAncBitsUsed +
-                     qcOut->totFillBits + qcOut->alignBits)) {
-    return(-1);
-  }
-  return(0);
-}
diff --git a/media/libstagefright/codecs/aacenc/src/block_switch.c b/media/libstagefright/codecs/aacenc/src/block_switch.c
deleted file mode 100644
index 11bc7e7..0000000
--- a/media/libstagefright/codecs/aacenc/src/block_switch.c
+++ /dev/null
@@ -1,404 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		block_switch.c
-
-	Content:	Block switching functions
-
-*******************************************************************************/
-
-#include "typedef.h"
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "psy_const.h"
-#include "block_switch.h"
-
-
-#define ENERGY_SHIFT (8 - 1)
-
-/**************** internal function prototypes ***********/
-static Word32
-SrchMaxWithIndex(const Word32 *in, Word16 *index, Word16 n);
-
-
-Word32
-CalcWindowEnergy(BLOCK_SWITCHING_CONTROL *blockSwitchingControl,
-                 Word16 *timeSignal,
-                 Word16 chIncrement,
-                 Word16 windowLen);
-
-
-
-/****************** Constants *****************************/
-
-
-/*
-  IIR high pass coeffs
-*/
-const Word32 hiPassCoeff[BLOCK_SWITCHING_IIR_LEN] = {
-  0xbec8b439, 0x609d4952  /* -0.5095f, 0.7548f */
-};
-
-static const Word32 accWindowNrgFac = 0x26666666;                   /* factor for accumulating filtered window energies 0.3 */
-static const Word32 oneMinusAccWindowNrgFac = 0x5999999a;			/* 0.7 */
-static const Word32 invAttackRatioHighBr = 0x0ccccccd;              /* inverted lower ratio limit for attacks 0.1*/
-static const Word32 invAttackRatioLowBr =  0x072b020c;              /* 0.056 */
-static const Word32 minAttackNrg = 0x00001e84;                      /* minimum energy for attacks 1e+6 */
-
-
-/****************** Routines ****************************/
-
-
-/*****************************************************************************
-*
-* function name: InitBlockSwitching
-* description:  init Block Switching parameter.
-* returns:      TRUE if success
-*
-**********************************************************************************/
-Word16 InitBlockSwitching(BLOCK_SWITCHING_CONTROL *blockSwitchingControl,
-                          const Word32 bitRate, const Word16 nChannels)
-{
-  /* select attackRatio */
-
-  if ((sub(nChannels,1)==0 && L_sub(bitRate, 24000) > 0) ||
-      (sub(nChannels,1)>0 && bitRate > (nChannels * 16000))) {
-    blockSwitchingControl->invAttackRatio = invAttackRatioHighBr;
-  }
-  else  {
-    blockSwitchingControl->invAttackRatio = invAttackRatioLowBr;
-  }
-
-  return(TRUE);
-}
-
-static Word16 suggestedGroupingTable[TRANS_FAC][MAX_NO_OF_GROUPS] = {
-  /* Attack in Window 0 */ {1,  3,  3,  1},
-  /* Attack in Window 1 */ {1,  1,  3,  3},
-  /* Attack in Window 2 */ {2,  1,  3,  2},
-  /* Attack in Window 3 */ {3,  1,  3,  1},
-  /* Attack in Window 4 */ {3,  1,  1,  3},
-  /* Attack in Window 5 */ {3,  2,  1,  2},
-  /* Attack in Window 6 */ {3,  3,  1,  1},
-  /* Attack in Window 7 */ {3,  3,  1,  1}
-};
-
-/*****************************************************************************
-*
-* function name: BlockSwitching
-* description:  detect this frame whether there is an attack
-* returns:      TRUE if success
-*
-**********************************************************************************/
-Word16 BlockSwitching(BLOCK_SWITCHING_CONTROL *blockSwitchingControl,
-                      Word16 *timeSignal,
-					  Word32 sampleRate,
-                      Word16 chIncrement)
-{
-  Word32 i, w;
-  Word32 enM1, enMax;
-
-  /* Reset grouping info */
-  for (i=0; i<TRANS_FAC; i++) {
-    blockSwitchingControl->groupLen[i] = 0;
-  }
-
-
-  /* Search for position and amplitude of attack in last frame (1 windows delay) */
-  blockSwitchingControl->maxWindowNrg = SrchMaxWithIndex( &blockSwitchingControl->windowNrg[0][BLOCK_SWITCH_WINDOWS-1],
-                                                          &blockSwitchingControl->attackIndex,
-                                                          BLOCK_SWITCH_WINDOWS);
-
-  blockSwitchingControl->attackIndex = blockSwitchingControl->lastAttackIndex;
-
-  /* Set grouping info */
-  blockSwitchingControl->noOfGroups = MAX_NO_OF_GROUPS;
-
-  for (i=0; i<MAX_NO_OF_GROUPS; i++) {
-    blockSwitchingControl->groupLen[i] = suggestedGroupingTable[blockSwitchingControl->attackIndex][i];
-  }
-
-  /* if the samplerate is less than 16000, it should be all the short block, avoid pre&post echo */
-  if(sampleRate >= 16000) {
-	  /* Save current window energy as last window energy */
-	  for (w=0; w<BLOCK_SWITCH_WINDOWS; w++) {
-		  blockSwitchingControl->windowNrg[0][w] = blockSwitchingControl->windowNrg[1][w];
-		  blockSwitchingControl->windowNrgF[0][w] = blockSwitchingControl->windowNrgF[1][w];
-	  }
-
-
-	  /* Calculate unfiltered and filtered energies in subwindows and combine to segments */
-	  CalcWindowEnergy(blockSwitchingControl, timeSignal, chIncrement, BLOCK_SWITCH_WINDOW_LEN);
-
-	  /* reset attack */
-	  blockSwitchingControl->attack = FALSE;
-
-	  enMax = 0;
-	  enM1 = blockSwitchingControl->windowNrgF[0][BLOCK_SWITCH_WINDOWS-1];
-
-	  for (w=0; w<BLOCK_SWITCH_WINDOWS; w++) {
-		  Word32 enM1_Tmp, accWindowNrg_Tmp, windowNrgF_Tmp;
-		  Word16 enM1_Shf, accWindowNrg_Shf, windowNrgF_Shf;
-
-		  accWindowNrg_Shf = norm_l(blockSwitchingControl->accWindowNrg);
-		  enM1_Shf = norm_l(enM1);
-		  windowNrgF_Shf = norm_l(blockSwitchingControl->windowNrgF[1][w]);
-
-		  accWindowNrg_Tmp = blockSwitchingControl->accWindowNrg << accWindowNrg_Shf;
-		  enM1_Tmp = enM1 << enM1_Shf;
-		  windowNrgF_Tmp = blockSwitchingControl->windowNrgF[1][w] << windowNrgF_Shf;
-
-		  /* a sliding average of the previous energies */
-		  blockSwitchingControl->accWindowNrg = (fixmul(oneMinusAccWindowNrgFac, accWindowNrg_Tmp) >> accWindowNrg_Shf) +
-			  (fixmul(accWindowNrgFac, enM1_Tmp) >> enM1_Shf);
-
-
-		  /* if the energy with the ratio is bigger than the average, and the attack and short block  */
-		  if ((fixmul(windowNrgF_Tmp, blockSwitchingControl->invAttackRatio) >> windowNrgF_Shf) >
-			  blockSwitchingControl->accWindowNrg ) {
-				  blockSwitchingControl->attack = TRUE;
-				  blockSwitchingControl->lastAttackIndex = w;
-		  }
-		  enM1 = blockSwitchingControl->windowNrgF[1][w];
-		  enMax = max(enMax, enM1);
-	  }
-
-	  if (enMax < minAttackNrg) {
-		  blockSwitchingControl->attack = FALSE;
-	  }
-  }
-  else
-  {
-	  blockSwitchingControl->attack = TRUE;
-  }
-
-  /* Check if attack spreads over frame border */
-  if ((!blockSwitchingControl->attack) && (blockSwitchingControl->lastattack)) {
-
-    if (blockSwitchingControl->attackIndex == TRANS_FAC-1) {
-      blockSwitchingControl->attack = TRUE;
-    }
-
-    blockSwitchingControl->lastattack = FALSE;
-  }
-  else {
-    blockSwitchingControl->lastattack = blockSwitchingControl->attack;
-  }
-
-  blockSwitchingControl->windowSequence =  blockSwitchingControl->nextwindowSequence;
-
-
-  if (blockSwitchingControl->attack) {
-    blockSwitchingControl->nextwindowSequence = SHORT_WINDOW;
-  }
-  else {
-    blockSwitchingControl->nextwindowSequence = LONG_WINDOW;
-  }
-
-  /* update short block group */
-  if (blockSwitchingControl->nextwindowSequence == SHORT_WINDOW) {
-
-    if (blockSwitchingControl->windowSequence== LONG_WINDOW) {
-      blockSwitchingControl->windowSequence = START_WINDOW;
-    }
-
-    if (blockSwitchingControl->windowSequence == STOP_WINDOW) {
-      blockSwitchingControl->windowSequence = SHORT_WINDOW;
-      blockSwitchingControl->noOfGroups = 3;
-      blockSwitchingControl->groupLen[0] = 3;
-      blockSwitchingControl->groupLen[1] = 3;
-      blockSwitchingControl->groupLen[2] = 2;
-    }
-  }
-
-  /* update block type */
-  if (blockSwitchingControl->nextwindowSequence == LONG_WINDOW) {
-
-    if (blockSwitchingControl->windowSequence == SHORT_WINDOW) {
-      blockSwitchingControl->nextwindowSequence = STOP_WINDOW;
-    }
-  }
-
-  return(TRUE);
-}
-
-
-/*****************************************************************************
-*
-* function name: SrchMaxWithIndex
-* description:  search for the biggest value in an array
-* returns:      the max value
-*
-**********************************************************************************/
-static Word32 SrchMaxWithIndex(const Word32 in[], Word16 *index, Word16 n)
-{
-  Word32 max;
-  Word32 i, idx;
-
-  /* Search maximum value in array and return index and value */
-  max = 0;
-  idx = 0;
-
-  for (i = 0; i < n; i++) {
-
-    if (in[i+1]  > max) {
-      max = in[i+1];
-      idx = i;
-    }
-  }
-  *index = idx;
-
-  return(max);
-}
-
-/*****************************************************************************
-*
-* function name: CalcWindowEnergy
-* description:  calculate the energy before iir-filter and after irr-filter
-* returns:      TRUE if success
-*
-**********************************************************************************/
-#ifndef ARMV5E
-Word32 CalcWindowEnergy(BLOCK_SWITCHING_CONTROL *blockSwitchingControl,
-                        Word16 *timeSignal,
-                        Word16 chIncrement,
-                        Word16 windowLen)
-{
-  Word32 w, i, tidx;
-  Word32 accuUE, accuFE;
-  Word32 tempUnfiltered;
-  Word32 tempFiltered;
-  Word32 states0, states1;
-  Word32 Coeff0, Coeff1;
-
-
-  states0 = blockSwitchingControl->iirStates[0];
-  states1 = blockSwitchingControl->iirStates[1];
-  Coeff0 = hiPassCoeff[0];
-  Coeff1 = hiPassCoeff[1];
-  tidx = 0;
-  for (w=0; w < BLOCK_SWITCH_WINDOWS; w++) {
-
-    accuUE = 0;
-    accuFE = 0;
-
-    for(i=0; i<windowLen; i++) {
-	  Word32 accu1, accu2, accu3;
-	  Word32 out;
-	  tempUnfiltered = timeSignal[tidx];
-      tidx = tidx + chIncrement;
-
-	  accu1 = L_mpy_ls(Coeff1, tempUnfiltered);
-	  accu2 = fixmul( Coeff0, states1 );
-	  accu3 = accu1 - states0;
-	  out = accu3 - accu2;
-
-	  states0 = accu1;
-	  states1 = out;
-
-      tempFiltered = extract_h(out);
-      accuUE += (tempUnfiltered * tempUnfiltered) >> ENERGY_SHIFT;
-      accuFE += (tempFiltered * tempFiltered) >> ENERGY_SHIFT;
-    }
-
-    blockSwitchingControl->windowNrg[1][w] = accuUE;
-    blockSwitchingControl->windowNrgF[1][w] = accuFE;
-
-  }
-
-  blockSwitchingControl->iirStates[0] = states0;
-  blockSwitchingControl->iirStates[1] = states1;
-
-  return(TRUE);
-}
-#endif
-
-static Word16 synchronizedBlockTypeTable[4][4] = {
-  /*                 LONG_WINDOW   START_WINDOW  SHORT_WINDOW  STOP_WINDOW */
-  /* LONG_WINDOW  */{LONG_WINDOW,  START_WINDOW, SHORT_WINDOW, STOP_WINDOW},
-  /* START_WINDOW */{START_WINDOW, START_WINDOW, SHORT_WINDOW, SHORT_WINDOW},
-  /* SHORT_WINDOW */{SHORT_WINDOW, SHORT_WINDOW, SHORT_WINDOW, SHORT_WINDOW},
-  /* STOP_WINDOW  */{STOP_WINDOW,  SHORT_WINDOW, SHORT_WINDOW, STOP_WINDOW}
-};
-
-
-/*****************************************************************************
-*
-* function name: SyncBlockSwitching
-* description:  update block type and group value
-* returns:      TRUE if success
-*
-**********************************************************************************/
-Word16 SyncBlockSwitching(BLOCK_SWITCHING_CONTROL *blockSwitchingControlLeft,
-                          BLOCK_SWITCHING_CONTROL *blockSwitchingControlRight,
-                          const Word16 nChannels)
-{
-  Word16 i;
-  Word16 patchType = LONG_WINDOW;
-
-
-  if (nChannels == 1) { /* Mono */
-    if (blockSwitchingControlLeft->windowSequence != SHORT_WINDOW) {
-      blockSwitchingControlLeft->noOfGroups = 1;
-      blockSwitchingControlLeft->groupLen[0] = 1;
-
-      for (i=1; i<TRANS_FAC; i++) {
-        blockSwitchingControlLeft->groupLen[i] = 0;
-      }
-    }
-  }
-  else { /* Stereo common Window */
-    patchType = synchronizedBlockTypeTable[patchType][blockSwitchingControlLeft->windowSequence];
-    patchType = synchronizedBlockTypeTable[patchType][blockSwitchingControlRight->windowSequence];
-
-    /* Set synchronized Blocktype */
-    blockSwitchingControlLeft->windowSequence = patchType;
-    blockSwitchingControlRight->windowSequence = patchType;
-
-    /* Synchronize grouping info */
-    if(patchType != SHORT_WINDOW) { /* Long Blocks */
-      /* Set grouping info */
-      blockSwitchingControlLeft->noOfGroups = 1;
-      blockSwitchingControlRight->noOfGroups = 1;
-      blockSwitchingControlLeft->groupLen[0] = 1;
-      blockSwitchingControlRight->groupLen[0] = 1;
-
-      for (i=1; i<TRANS_FAC; i++) {
-        blockSwitchingControlLeft->groupLen[i] = 0;
-        blockSwitchingControlRight->groupLen[i] = 0;
-      }
-    }
-    else {
-
-      if (blockSwitchingControlLeft->maxWindowNrg > blockSwitchingControlRight->maxWindowNrg) {
-        /* Left Channel wins */
-        blockSwitchingControlRight->noOfGroups = blockSwitchingControlLeft->noOfGroups;
-        for (i=0; i<TRANS_FAC; i++) {
-          blockSwitchingControlRight->groupLen[i] = blockSwitchingControlLeft->groupLen[i];
-        }
-      }
-      else {
-        /* Right Channel wins */
-        blockSwitchingControlLeft->noOfGroups = blockSwitchingControlRight->noOfGroups;
-        for (i=0; i<TRANS_FAC; i++) {
-          blockSwitchingControlLeft->groupLen[i] = blockSwitchingControlRight->groupLen[i];
-        }
-      }
-    }
-  } /*endif Mono or Stereo */
-
-  return(TRUE);
-}
diff --git a/media/libstagefright/codecs/aacenc/src/channel_map.c b/media/libstagefright/codecs/aacenc/src/channel_map.c
deleted file mode 100644
index f6552ed..0000000
--- a/media/libstagefright/codecs/aacenc/src/channel_map.c
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		channel_map.c
-
-	Content:	channel mapping functions
-
-*******************************************************************************/
-
-#include "channel_map.h"
-#include "bitenc.h"
-#include "psy_const.h"
-#include "qc_data.h"
-
-static const Word16 maxChannelBits = MAXBITS_COEF;
-
-static Word16 initElement(ELEMENT_INFO* elInfo, ELEMENT_TYPE elType)
-{
-  Word16 error=0;
-
-  elInfo->elType=elType;
-
-  switch(elInfo->elType) {
-
-    case ID_SCE:
-      elInfo->nChannelsInEl=1;
-
-      elInfo->ChannelIndex[0]=0;
-
-      elInfo->instanceTag=0;
-      break;
-
-    case ID_CPE:
-
-      elInfo->nChannelsInEl=2;
-
-      elInfo->ChannelIndex[0]=0;
-      elInfo->ChannelIndex[1]=1;
-
-      elInfo->instanceTag=0;
-      break;
-
-    default:
-      error=1;
-  }
-
-  return error;
-}
-
-
-Word16 InitElementInfo (Word16 nChannels, ELEMENT_INFO* elInfo)
-{
-  Word16 error;
-  error = 0;
-
-  switch(nChannels) {
-
-    case 1:
-      initElement(elInfo, ID_SCE);
-      break;
-
-    case 2:
-      initElement(elInfo, ID_CPE);
-      break;
-
-    default:
-      error=4;
-  }
-
-  return error;
-}
-
-
-Word16 InitElementBits(ELEMENT_BITS *elementBits,
-                       ELEMENT_INFO elInfo,
-                       Word32 bitrateTot,
-                       Word16 averageBitsTot,
-                       Word16 staticBitsTot)
-{
-  Word16 error;
-  error = 0;
-
-   switch(elInfo.nChannelsInEl) {
-    case 1:
-      elementBits->chBitrate = bitrateTot;
-      elementBits->averageBits = averageBitsTot - staticBitsTot;
-      elementBits->maxBits = maxChannelBits;
-
-      elementBits->maxBitResBits = maxChannelBits - averageBitsTot;
-      elementBits->maxBitResBits = elementBits->maxBitResBits - (elementBits->maxBitResBits & 7);
-      elementBits->bitResLevel = elementBits->maxBitResBits;
-      elementBits->relativeBits  = 0x4000; /* 1.0f/2 */
-      break;
-
-    case 2:
-      elementBits->chBitrate   = bitrateTot >> 1;
-      elementBits->averageBits = averageBitsTot - staticBitsTot;
-      elementBits->maxBits     = maxChannelBits << 1;
-
-      elementBits->maxBitResBits = (maxChannelBits << 1) - averageBitsTot;
-      elementBits->maxBitResBits = elementBits->maxBitResBits - (elementBits->maxBitResBits & 7);
-      elementBits->bitResLevel = elementBits->maxBitResBits;
-      elementBits->relativeBits = 0x4000; /* 1.0f/2 */
-      break;
-
-    default:
-      error = 1;
-  }
-  return error;
-}
diff --git a/media/libstagefright/codecs/aacenc/src/dyn_bits.c b/media/libstagefright/codecs/aacenc/src/dyn_bits.c
deleted file mode 100644
index e75b48f..0000000
--- a/media/libstagefright/codecs/aacenc/src/dyn_bits.c
+++ /dev/null
@@ -1,551 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		dyn_bits.c
-
-	Content:	Noiseless coder module functions
-
-*******************************************************************************/
-
-#define LOG_TAG "NoiselessCoder"
-
-#include "log/log.h"
-
-#include "aac_rom.h"
-#include "dyn_bits.h"
-#include "bit_cnt.h"
-#include "psy_const.h"
-
-/*****************************************************************************
-*
-* function name: buildBitLookUp
-* description:  count bits using all possible tables
-*
-*****************************************************************************/
-static void
-buildBitLookUp(const Word16 *quantSpectrum,
-               const Word16 maxSfb,
-               const Word16 *sfbOffset,
-               const UWord16 *sfbMax,
-               Word16 bitLookUp[MAX_SFB_LONG][CODE_BOOK_ESC_NDX + 1],
-               SECTION_INFO * sectionInfo)
-{
-  Word32 i;
-
-  for (i=0; i<maxSfb; i++) {
-    Word16 sfbWidth, maxVal;
-
-    sectionInfo[i].sfbCnt = 1;
-    sectionInfo[i].sfbStart = i;
-    sectionInfo[i].sectionBits = INVALID_BITCOUNT;
-    sectionInfo[i].codeBook = -1;
-    sfbWidth = sfbOffset[i + 1] - sfbOffset[i];
-    maxVal = sfbMax[i];
-    bitCount(quantSpectrum + sfbOffset[i], sfbWidth, maxVal, bitLookUp[i]);
-  }
-}
-
-
-/*****************************************************************************
-*
-* function name: findBestBook
-* description:  essential helper functions
-*
-*****************************************************************************/
-static Word16
-findBestBook(const Word16 *bc, Word16 *book)
-{
-  Word32 minBits, j;
-  minBits = INVALID_BITCOUNT;
-
-  for (j=0; j<=CODE_BOOK_ESC_NDX; j++) {
-
-    if (bc[j] < minBits) {
-      minBits = bc[j];
-      *book = j;
-    }
-  }
-  return extract_l(minBits);
-}
-
-static Word16
-findMinMergeBits(const Word16 *bc1, const Word16 *bc2)
-{
-  Word32 minBits, j, sum;
-  minBits = INVALID_BITCOUNT;
-
-  for (j=0; j<=CODE_BOOK_ESC_NDX; j++) {
-    sum = bc1[j] + bc2[j];
-    if (sum < minBits) {
-      minBits = sum;
-    }
-  }
-  return extract_l(minBits);
-}
-
-static void
-mergeBitLookUp(Word16 *bc1, const Word16 *bc2)
-{
-  Word32 j;
-
-  for (j=0; j<=CODE_BOOK_ESC_NDX; j++) {
-    bc1[j] = min(bc1[j] + bc2[j], INVALID_BITCOUNT);
-  }
-}
-
-static Word16
-findMaxMerge(const Word16 mergeGainLookUp[MAX_SFB_LONG],
-             const SECTION_INFO *sectionInfo,
-             const Word16 maxSfb, Word16 *maxNdx)
-{
-  Word32 i, maxMergeGain;
-  maxMergeGain = 0;
-
-  for (i=0; i+sectionInfo[i].sfbCnt < maxSfb; i += sectionInfo[i].sfbCnt) {
-
-    if (mergeGainLookUp[i] > maxMergeGain) {
-      maxMergeGain = mergeGainLookUp[i];
-      *maxNdx = i;
-    }
-  }
-  return extract_l(maxMergeGain);
-}
-
-
-
-static Word16
-CalcMergeGain(const SECTION_INFO *sectionInfo,
-              Word16 bitLookUp[MAX_SFB_LONG][CODE_BOOK_ESC_NDX + 1],
-              const Word16 *sideInfoTab,
-              const Word16 ndx1,
-              const Word16 ndx2)
-{
-  Word32 SplitBits;
-  Word32 MergeBits;
-  Word32 MergeGain;
-
-  /*
-    Bit amount for splitted sections
-  */
-  SplitBits = sectionInfo[ndx1].sectionBits + sectionInfo[ndx2].sectionBits;
-
-  MergeBits = sideInfoTab[sectionInfo[ndx1].sfbCnt + sectionInfo[ndx2].sfbCnt] +
-                  findMinMergeBits(bitLookUp[ndx1], bitLookUp[ndx2]);
-  MergeGain = (SplitBits - MergeBits);
-
-  return extract_l(MergeGain);
-}
-
-/*
-  sectioning Stage 0:find minimum codbooks
-*/
-
-static void
-gmStage0(SECTION_INFO * sectionInfo,
-         Word16 bitLookUp[MAX_SFB_LONG][CODE_BOOK_ESC_NDX + 1],
-         const Word16 maxSfb)
-{
-  Word32 i;
-
-  for (i=0; i<maxSfb; i++) {
-    /* Side-Info bits will be calculated in Stage 1!  */
-
-    if (sectionInfo[i].sectionBits == INVALID_BITCOUNT) {
-      sectionInfo[i].sectionBits = findBestBook(bitLookUp[i], &(sectionInfo[i].codeBook));
-    }
-  }
-}
-
-/*
-  sectioning Stage 1:merge all connected regions with the same code book and
-  calculate side info
-*/
-
-static void
-gmStage1(SECTION_INFO * sectionInfo,
-         Word16 bitLookUp[MAX_SFB_LONG][CODE_BOOK_ESC_NDX + 1],
-         const Word16 maxSfb,
-         const Word16 *sideInfoTab)
-{
-  SECTION_INFO * sectionInfo_s;
-  SECTION_INFO * sectionInfo_e;
-  Word32 mergeStart, mergeEnd;
-  mergeStart = 0;
-
-  do {
-
-    sectionInfo_s = sectionInfo + mergeStart;
-	for (mergeEnd=mergeStart+1; mergeEnd<maxSfb; mergeEnd++) {
-      sectionInfo_e = sectionInfo + mergeEnd;
-      if (sectionInfo_s->codeBook != sectionInfo_e->codeBook)
-        break;
-      sectionInfo_s->sfbCnt += 1;
-      sectionInfo_s->sectionBits += sectionInfo_e->sectionBits;
-
-      mergeBitLookUp(bitLookUp[mergeStart], bitLookUp[mergeEnd]);
-    }
-
-    sectionInfo_s->sectionBits += sideInfoTab[sectionInfo_s->sfbCnt];
-    sectionInfo[mergeEnd - 1].sfbStart = sectionInfo_s->sfbStart;      /* speed up prev search */
-
-    mergeStart = mergeEnd;
-
-
-  } while (mergeStart - maxSfb < 0);
-}
-
-/*
-  sectioning Stage 2:greedy merge algorithm, merge connected sections with
-  maximum bit gain until no more gain is possible
-*/
-static void
-gmStage2(SECTION_INFO *sectionInfo,
-         Word16 mergeGainLookUp[MAX_SFB_LONG],
-         Word16 bitLookUp[MAX_SFB_LONG][CODE_BOOK_ESC_NDX + 1],
-         const Word16 maxSfb,
-         const Word16 *sideInfoTab)
-{
-  Word16 i;
-
-  for (i=0; i+sectionInfo[i].sfbCnt<maxSfb; i+=sectionInfo[i].sfbCnt) {
-    mergeGainLookUp[i] = CalcMergeGain(sectionInfo,
-                                       bitLookUp,
-                                       sideInfoTab,
-                                       i,
-                                       (i + sectionInfo[i].sfbCnt));
-  }
-
-  while (TRUE) {
-    Word16 maxMergeGain, maxNdx = 0, maxNdxNext, maxNdxLast;
-
-    maxMergeGain = findMaxMerge(mergeGainLookUp, sectionInfo, maxSfb, &maxNdx);
-
-
-    if (maxMergeGain <= 0)
-      break;
-
-
-    maxNdxNext = maxNdx + sectionInfo[maxNdx].sfbCnt;
-
-    sectionInfo[maxNdx].sfbCnt = sectionInfo[maxNdx].sfbCnt + sectionInfo[maxNdxNext].sfbCnt;
-    sectionInfo[maxNdx].sectionBits = sectionInfo[maxNdx].sectionBits +
-                                          (sectionInfo[maxNdxNext].sectionBits - maxMergeGain);
-
-
-    mergeBitLookUp(bitLookUp[maxNdx], bitLookUp[maxNdxNext]);
-
-
-    if (maxNdx != 0) {
-      maxNdxLast = sectionInfo[maxNdx - 1].sfbStart;
-      mergeGainLookUp[maxNdxLast] = CalcMergeGain(sectionInfo,
-                                                  bitLookUp,
-                                                  sideInfoTab,
-                                                  maxNdxLast,
-                                                  maxNdx);
-    }
-    maxNdxNext = maxNdx + sectionInfo[maxNdx].sfbCnt;
-
-    sectionInfo[maxNdxNext - 1].sfbStart = sectionInfo[maxNdx].sfbStart;
-
-
-    if (maxNdxNext - maxSfb < 0) {
-      mergeGainLookUp[maxNdx] = CalcMergeGain(sectionInfo,
-                                              bitLookUp,
-                                              sideInfoTab,
-                                              maxNdx,
-                                              maxNdxNext);
-    }
-  }
-}
-
-/*
-  count bits used by the noiseless coder
-*/
-static void
-noiselessCounter(SECTION_DATA *sectionData,
-                 Word16 mergeGainLookUp[MAX_SFB_LONG],
-                 Word16 bitLookUp[MAX_SFB_LONG][CODE_BOOK_ESC_NDX + 1],
-                 const Word16 *quantSpectrum,
-                 const UWord16 *maxValueInSfb,
-                 const Word16 *sfbOffset,
-                 const Word32 blockType)
-{
-  Word32 grpNdx, i;
-  const Word16 *sideInfoTab = NULL;
-  SECTION_INFO *sectionInfo;
-
-  /*
-    use appropriate side info table
-  */
-  switch (blockType)
-  {
-    case LONG_WINDOW:
-    case START_WINDOW:
-    case STOP_WINDOW:
-      sideInfoTab = sideInfoTabLong;
-      break;
-    case SHORT_WINDOW:
-      sideInfoTab = sideInfoTabShort;
-      break;
-    default:
-      ALOGE("invalid blockType: %d", blockType);
-      return;
-  }
-
-
-  sectionData->noOfSections = 0;
-  sectionData->huffmanBits = 0;
-  sectionData->sideInfoBits = 0;
-
-
-  if (sectionData->maxSfbPerGroup == 0)
-    return;
-
-  /*
-    loop trough groups
-  */
-  for (grpNdx=0; grpNdx<sectionData->sfbCnt; grpNdx+=sectionData->sfbPerGroup) {
-
-    sectionInfo = sectionData->sectionInfo + sectionData->noOfSections;
-
-    buildBitLookUp(quantSpectrum,
-                   sectionData->maxSfbPerGroup,
-                   sfbOffset + grpNdx,
-                   maxValueInSfb + grpNdx,
-                   bitLookUp,
-                   sectionInfo);
-
-    /*
-       0.Stage
-    */
-    gmStage0(sectionInfo, bitLookUp, sectionData->maxSfbPerGroup);
-
-    /*
-       1.Stage
-    */
-    gmStage1(sectionInfo, bitLookUp, sectionData->maxSfbPerGroup, sideInfoTab);
-
-
-    /*
-       2.Stage
-    */
-    gmStage2(sectionInfo,
-             mergeGainLookUp,
-             bitLookUp,
-             sectionData->maxSfbPerGroup,
-             sideInfoTab);
-
-
-    /*
-       compress output, calculate total huff and side bits
-    */
-    for (i=0; i<sectionData->maxSfbPerGroup; i+=sectionInfo[i].sfbCnt) {
-      findBestBook(bitLookUp[i], &(sectionInfo[i].codeBook));
-      sectionInfo[i].sfbStart = sectionInfo[i].sfbStart + grpNdx;
-
-      sectionData->huffmanBits = (sectionData->huffmanBits +
-                                     (sectionInfo[i].sectionBits - sideInfoTab[sectionInfo[i].sfbCnt]));
-      sectionData->sideInfoBits = (sectionData->sideInfoBits + sideInfoTab[sectionInfo[i].sfbCnt]);
-      sectionData->sectionInfo[sectionData->noOfSections] = sectionInfo[i];
-      sectionData->noOfSections = sectionData->noOfSections + 1;
-    }
-  }
-}
-
-
-/*******************************************************************************
-*
-* functionname: scfCount
-* returns     : ---
-* description : count bits used by scalefactors.
-*
-********************************************************************************/
-static void scfCount(const Word16 *scalefacGain,
-                     const UWord16 *maxValueInSfb,
-                     SECTION_DATA * sectionData)
-
-{
-  SECTION_INFO *psectionInfo;
-  SECTION_INFO *psectionInfom;
-
-  /* counter */
-  Word32 i = 0; /* section counter */
-  Word32 j = 0; /* sfb counter */
-  Word32 k = 0; /* current section auxiliary counter */
-  Word32 m = 0; /* other section auxiliary counter */
-  Word32 n = 0; /* other sfb auxiliary counter */
-
-  /* further variables */
-  Word32 lastValScf     = 0;
-  Word32 deltaScf       = 0;
-  Flag found            = 0;
-  Word32 scfSkipCounter = 0;
-
-
-  sectionData->scalefacBits = 0;
-
-
-  if (scalefacGain == NULL) {
-    return;
-  }
-
-  lastValScf = 0;
-  sectionData->firstScf = 0;
-
-  psectionInfo = sectionData->sectionInfo;
-  for (i=0; i<sectionData->noOfSections; i++) {
-
-    if (psectionInfo->codeBook != CODE_BOOK_ZERO_NO) {
-      sectionData->firstScf = psectionInfo->sfbStart;
-      lastValScf = scalefacGain[sectionData->firstScf];
-      break;
-    }
-	psectionInfo += 1;
-  }
-
-  psectionInfo = sectionData->sectionInfo;
-  for (i=0; i<sectionData->noOfSections; i++, psectionInfo += 1) {
-
-    if (psectionInfo->codeBook != CODE_BOOK_ZERO_NO
-        && psectionInfo->codeBook != CODE_BOOK_PNS_NO) {
-      for (j = psectionInfo->sfbStart;
-           j < (psectionInfo->sfbStart + psectionInfo->sfbCnt); j++) {
-        /* check if we can repeat the last value to save bits */
-
-        if (maxValueInSfb[j] == 0) {
-          found = 0;
-
-          if (scfSkipCounter == 0) {
-            /* end of section */
-
-            if (j - ((psectionInfo->sfbStart + psectionInfo->sfbCnt) - 1) == 0) {
-              found = 0;
-            }
-            else {
-              for (k = j + 1; k < psectionInfo->sfbStart + psectionInfo->sfbCnt; k++) {
-
-                if (maxValueInSfb[k] != 0) {
-                  int tmp = L_abs(scalefacGain[k] - lastValScf);
-				  found = 1;
-
-                  if ( tmp < CODE_BOOK_SCF_LAV) {
-                    /* save bits */
-                    deltaScf = 0;
-                  }
-                  else {
-                    /* do not save bits */
-                    deltaScf = lastValScf - scalefacGain[j];
-                    lastValScf = scalefacGain[j];
-                    scfSkipCounter = 0;
-                  }
-                  break;
-                }
-                /* count scalefactor skip */
-                scfSkipCounter = scfSkipCounter + 1;
-              }
-            }
-
-			psectionInfom = psectionInfo + 1;
-            /* search for the next maxValueInSfb[] != 0 in all other sections */
-            for (m = i + 1; (m < sectionData->noOfSections) && (found == 0); m++) {
-
-              if ((psectionInfom->codeBook != CODE_BOOK_ZERO_NO) &&
-                  (psectionInfom->codeBook != CODE_BOOK_PNS_NO)) {
-                for (n = psectionInfom->sfbStart;
-                     n < (psectionInfom->sfbStart + psectionInfom->sfbCnt); n++) {
-
-                  if (maxValueInSfb[n] != 0) {
-                    found = 1;
-
-                    if ( (abs_s(scalefacGain[n] - lastValScf) < CODE_BOOK_SCF_LAV)) {
-                      deltaScf = 0;
-                    }
-                    else {
-                      deltaScf = (lastValScf - scalefacGain[j]);
-                      lastValScf = scalefacGain[j];
-                      scfSkipCounter = 0;
-                    }
-                    break;
-                  }
-                  /* count scalefactor skip */
-                  scfSkipCounter = scfSkipCounter + 1;
-                }
-              }
-
-			  psectionInfom += 1;
-            }
-
-            if (found == 0) {
-              deltaScf = 0;
-              scfSkipCounter = 0;
-            }
-          }
-          else {
-            deltaScf = 0;
-            scfSkipCounter = scfSkipCounter - 1;
-          }
-        }
-        else {
-          deltaScf = lastValScf - scalefacGain[j];
-          lastValScf = scalefacGain[j];
-        }
-        sectionData->scalefacBits += bitCountScalefactorDelta(deltaScf);
-      }
-    }
-  }
-}
-
-
-typedef Word16 (*lookUpTable)[CODE_BOOK_ESC_NDX + 1];
-
-
-Word16
-dynBitCount(const Word16  *quantSpectrum,
-            const UWord16 *maxValueInSfb,
-            const Word16  *scalefac,
-            const Word16   blockType,
-            const Word16   sfbCnt,
-            const Word16   maxSfbPerGroup,
-            const Word16   sfbPerGroup,
-            const Word16  *sfbOffset,
-            SECTION_DATA  *sectionData)
-{
-  sectionData->blockType      = blockType;
-  sectionData->sfbCnt         = sfbCnt;
-  sectionData->sfbPerGroup    = sfbPerGroup;
-  if(sfbPerGroup)
-	sectionData->noOfGroups   = sfbCnt/sfbPerGroup;
-  else
-	sectionData->noOfGroups   = 0x7fff;
-  sectionData->maxSfbPerGroup = maxSfbPerGroup;
-
-  noiselessCounter(sectionData,
-                   sectionData->mergeGainLookUp,
-                   (lookUpTable)sectionData->bitLookUp,
-                   quantSpectrum,
-                   maxValueInSfb,
-                   sfbOffset,
-                   blockType);
-
-  scfCount(scalefac,
-           maxValueInSfb,
-           sectionData);
-
-
-  return (sectionData->huffmanBits + sectionData->sideInfoBits +
-	      sectionData->scalefacBits);
-}
-
diff --git a/media/libstagefright/codecs/aacenc/src/grp_data.c b/media/libstagefright/codecs/aacenc/src/grp_data.c
deleted file mode 100644
index edfb95b..0000000
--- a/media/libstagefright/codecs/aacenc/src/grp_data.c
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		grp_data.c
-
-	Content:	Short block grouping function
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "psy_const.h"
-#include "interface.h"
-#include "grp_data.h"
-
-/*****************************************************************************
-*
-* function name: groupShortData
-* description:  group short data for next quantization and coding
-*
-**********************************************************************************/
-void
-groupShortData(Word32        *mdctSpectrum,
-               Word32        *tmpSpectrum,
-               SFB_THRESHOLD *sfbThreshold,
-               SFB_ENERGY    *sfbEnergy,
-               SFB_ENERGY    *sfbEnergyMS,
-               SFB_ENERGY    *sfbSpreadedEnergy,
-               const Word16   sfbCnt,
-               const Word16  *sfbOffset,
-               const Word16  *sfbMinSnr,
-               Word16        *groupedSfbOffset,
-               Word16        *maxSfbPerGroup,
-               Word16        *groupedSfbMinSnr,
-               const Word16   noOfGroups,
-               const Word16  *groupLen)
-{
-  Word32 i, j;
-  Word32 line;
-  Word32 sfb;
-  Word32 grp;
-  Word32 wnd;
-  Word32 offset;
-  Word32 highestSfb;
-
-  /* for short: regroup and  */
-  /* cumulate energies und thresholds group-wise . */
-
-  /* calculate sfbCnt */
-  highestSfb = 0;
-  for (wnd=0; wnd<TRANS_FAC; wnd++) {
-    for (sfb=sfbCnt - 1; sfb>=highestSfb; sfb--) {
-      for (line=(sfbOffset[sfb + 1] - 1); line>=sfbOffset[sfb]; line--) {
-
-        if (mdctSpectrum[wnd*FRAME_LEN_SHORT+line] != 0) break;
-      }
-
-      if (line >= sfbOffset[sfb]) break;
-    }
-    highestSfb = max(highestSfb, sfb);
-  }
-
-  if (highestSfb < 0) {
-    highestSfb = 0;
-  }
-  *maxSfbPerGroup = highestSfb + 1;
-
-  /* calculate sfbOffset */
-  i = 0;
-  offset = 0;
-  for (grp = 0; grp < noOfGroups; grp++) {
-    for (sfb = 0; sfb < sfbCnt; sfb++) {
-      groupedSfbOffset[i] = offset + sfbOffset[sfb] * groupLen[grp];
-      i += 1;
-    }
-    offset += groupLen[grp] * FRAME_LEN_SHORT;
-  }
-  groupedSfbOffset[i] = FRAME_LEN_LONG;
-
-  /* calculate minSnr */
-  i = 0;
-  offset = 0;
-  for (grp = 0; grp < noOfGroups; grp++) {
-    for (sfb = 0; sfb < sfbCnt; sfb++) {
-      groupedSfbMinSnr[i] = sfbMinSnr[sfb];
-      i += 1;
-    }
-    offset += groupLen[grp] * FRAME_LEN_SHORT;
-  }
-
-
-  /* sum up sfbThresholds */
-  wnd = 0;
-  i = 0;
-  for (grp = 0; grp < noOfGroups; grp++) {
-    for (sfb = 0; sfb < sfbCnt; sfb++) {
-      Word32 thresh = sfbThreshold->sfbShort[wnd][sfb];
-      for (j=1; j<groupLen[grp]; j++) {
-        thresh = L_add(thresh, sfbThreshold->sfbShort[wnd+j][sfb]);
-      }
-      sfbThreshold->sfbLong[i] = thresh;
-      i += 1;
-    }
-    wnd += groupLen[grp];
-  }
-
-  /* sum up sfbEnergies left/right */
-  wnd = 0;
-  i = 0;
-  for (grp = 0; grp < noOfGroups; grp++) {
-    for (sfb = 0; sfb < sfbCnt; sfb++) {
-      Word32 energy = sfbEnergy->sfbShort[wnd][sfb];
-      for (j=1; j<groupLen[grp]; j++) {
-        energy = L_add(energy, sfbEnergy->sfbShort[wnd+j][sfb]);
-      }
-      sfbEnergy->sfbLong[i] = energy;
-      i += 1;
-    }
-    wnd += groupLen[grp];
-  }
-
-  /* sum up sfbEnergies mid/side */
-  wnd = 0;
-  i = 0;
-  for (grp = 0; grp < noOfGroups; grp++) {
-    for (sfb = 0; sfb < sfbCnt; sfb++) {
-      Word32 energy = sfbEnergyMS->sfbShort[wnd][sfb];
-      for (j=1; j<groupLen[grp]; j++) {
-        energy = L_add(energy, sfbEnergyMS->sfbShort[wnd+j][sfb]);
-      }
-      sfbEnergyMS->sfbLong[i] = energy;
-      i += 1;
-    }
-    wnd += groupLen[grp];
-  }
-
-  /* sum up sfbSpreadedEnergies */
-  wnd = 0;
-  i = 0;
-  for (grp = 0; grp < noOfGroups; grp++) {
-    for (sfb = 0; sfb < sfbCnt; sfb++) {
-      Word32 energy = sfbSpreadedEnergy->sfbShort[wnd][sfb];
-      for (j=1; j<groupLen[grp]; j++) {
-        energy = L_add(energy, sfbSpreadedEnergy->sfbShort[wnd+j][sfb]);
-      }
-      sfbSpreadedEnergy->sfbLong[i] = energy;
-      i += 1;
-    }
-    wnd += groupLen[grp];
-  }
-
-  /* re-group spectrum */
-  wnd = 0;
-  i = 0;
-  for (grp = 0; grp < noOfGroups; grp++) {
-    for (sfb = 0; sfb < sfbCnt; sfb++) {
-      for (j = 0; j < groupLen[grp]; j++) {
-        Word16 lineOffset = FRAME_LEN_SHORT * (wnd + j);
-        for (line = lineOffset + sfbOffset[sfb]; line < lineOffset + sfbOffset[sfb+1]; line++) {
-          tmpSpectrum[i] = mdctSpectrum[line];
-          i = i + 1;
-        }
-      }
-    }
-    wnd += groupLen[grp];
-  }
-
-  for(i=0;i<FRAME_LEN_LONG;i+=4) {
-    mdctSpectrum[i] = tmpSpectrum[i];
-	mdctSpectrum[i+1] = tmpSpectrum[i+1];
-	mdctSpectrum[i+2] = tmpSpectrum[i+2];
-	mdctSpectrum[i+3] = tmpSpectrum[i+3];
-  }
-}
-
diff --git a/media/libstagefright/codecs/aacenc/src/interface.c b/media/libstagefright/codecs/aacenc/src/interface.c
deleted file mode 100644
index d0ad433..0000000
--- a/media/libstagefright/codecs/aacenc/src/interface.c
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		interface.c
-
-	Content:	Interface psychoaccoustic/quantizer functions
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "psy_const.h"
-#include "interface.h"
-
-/*****************************************************************************
-*
-* function name: BuildInterface
-* description:  update output parameter
-*
-**********************************************************************************/
-void BuildInterface(Word32                  *groupedMdctSpectrum,
-                    const Word16             mdctScale,
-                    SFB_THRESHOLD           *groupedSfbThreshold,
-                    SFB_ENERGY              *groupedSfbEnergy,
-                    SFB_ENERGY              *groupedSfbSpreadedEnergy,
-                    const SFB_ENERGY_SUM     sfbEnergySumLR,
-                    const SFB_ENERGY_SUM     sfbEnergySumMS,
-                    const Word16             windowSequence,
-                    const Word16             windowShape,
-                    const Word16             groupedSfbCnt,
-                    const Word16            *groupedSfbOffset,
-                    const Word16             maxSfbPerGroup,
-                    const Word16            *groupedSfbMinSnr,
-                    const Word16             noOfGroups,
-                    const Word16            *groupLen,
-                    PSY_OUT_CHANNEL         *psyOutCh)
-{
-  Word32 j;
-  Word32 grp;
-  Word32 mask;
-  Word16 *tmpV;
-
-  /*
-  copy values to psyOut
-  */
-  psyOutCh->maxSfbPerGroup    = maxSfbPerGroup;
-  psyOutCh->sfbCnt            = groupedSfbCnt;
-  if(noOfGroups)
-	psyOutCh->sfbPerGroup     = groupedSfbCnt/ noOfGroups;
-  else
-	psyOutCh->sfbPerGroup     = 0x7fff;
-  psyOutCh->windowSequence    = windowSequence;
-  psyOutCh->windowShape       = windowShape;
-  psyOutCh->mdctScale         = mdctScale;
-  psyOutCh->mdctSpectrum      = groupedMdctSpectrum;
-  psyOutCh->sfbEnergy         = groupedSfbEnergy->sfbLong;
-  psyOutCh->sfbThreshold      = groupedSfbThreshold->sfbLong;
-  psyOutCh->sfbSpreadedEnergy = groupedSfbSpreadedEnergy->sfbLong;
-
-  tmpV = psyOutCh->sfbOffsets;
-  for(j=0; j<groupedSfbCnt + 1; j++) {
-      *tmpV++ = groupedSfbOffset[j];
-  }
-
-  tmpV = psyOutCh->sfbMinSnr;
-  for(j=0;j<groupedSfbCnt; j++) {
-	  *tmpV++ =   groupedSfbMinSnr[j];
-  }
-
-  /* generate grouping mask */
-  mask = 0;
-  for (grp = 0; grp < noOfGroups; grp++) {
-    mask = mask << 1;
-    for (j=1; j<groupLen[grp]; j++) {
-      mask = mask << 1;
-      mask |= 1;
-    }
-  }
-  psyOutCh->groupingMask = mask;
-
-  if (windowSequence != SHORT_WINDOW) {
-    psyOutCh->sfbEnSumLR =  sfbEnergySumLR.sfbLong;
-    psyOutCh->sfbEnSumMS =  sfbEnergySumMS.sfbLong;
-  }
-  else {
-    Word32 i;
-    Word32 accuSumMS=0;
-    Word32 accuSumLR=0;
-    const Word32 *pSumMS = sfbEnergySumMS.sfbShort;
-    const Word32 *pSumLR = sfbEnergySumLR.sfbShort;
-
-    for (i=TRANS_FAC; i; i--) {
-      accuSumLR = L_add(accuSumLR, *pSumLR); pSumLR++;
-      accuSumMS = L_add(accuSumMS, *pSumMS); pSumMS++;
-    }
-    psyOutCh->sfbEnSumMS = accuSumMS;
-    psyOutCh->sfbEnSumLR = accuSumLR;
-  }
-}
diff --git a/media/libstagefright/codecs/aacenc/src/line_pe.c b/media/libstagefright/codecs/aacenc/src/line_pe.c
deleted file mode 100644
index 480dc28..0000000
--- a/media/libstagefright/codecs/aacenc/src/line_pe.c
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		line_pe.c
-
-	Content:	Perceptual entropie module functions
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "typedef.h"
-#include "line_pe.h"
-
-
-static const Word16  C1_I = 12;    /* log(8.0)/log(2) *4         */
-static const Word32  C2_I = 10830; /* log(2.5)/log(2) * 1024 * 4 * 2 */
-static const Word16  C3_I = 573;   /* (1-C2/C1) *1024            */
-
-
-/*****************************************************************************
-*
-* function name: prepareSfbPe
-* description:  constants that do not change during successive pe calculations
-*
-**********************************************************************************/
-void prepareSfbPe(PE_DATA *peData,
-                  PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],
-                  Word16 logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                  Word16 sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
-                  const Word16 nChannels,
-                  const Word16 peOffset)
-{
-  Word32 sfbGrp, sfb;
-  Word32 ch;
-
-  for(ch=0; ch<nChannels; ch++) {
-    PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-    PE_CHANNEL_DATA *peChanData=&peData->peChannelData[ch];
-    for(sfbGrp=0;sfbGrp<psyOutChan->sfbCnt; sfbGrp+=psyOutChan->sfbPerGroup){
-      for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-	    peChanData->sfbNLines4[sfbGrp+sfb] = sfbNRelevantLines[ch][sfbGrp+sfb];
-        sfbNRelevantLines[ch][sfbGrp+sfb] = sfbNRelevantLines[ch][sfbGrp+sfb] >> 2;
-	    peChanData->sfbLdEnergy[sfbGrp+sfb] = logSfbEnergy[ch][sfbGrp+sfb];
-      }
-    }
-  }
-  peData->offset = peOffset;
-}
-
-
-/*****************************************************************************
-*
-* function name: calcSfbPe
-* description:  constPart is sfbPe without the threshold part n*ld(thr) or n*C3*ld(thr)
-*
-**********************************************************************************/
-void calcSfbPe(PE_DATA *peData,
-               PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-               const Word16 nChannels)
-{
-  Word32 ch;
-  Word32 sfbGrp, sfb;
-  Word32 nLines4;
-  Word32 ldThr, ldRatio;
-  Word32 pe, constPart, nActiveLines;
-
-  peData->pe = peData->offset;
-  peData->constPart = 0;
-  peData->nActiveLines = 0;
-  for(ch=0; ch<nChannels; ch++) {
-    PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
-    PE_CHANNEL_DATA *peChanData = &peData->peChannelData[ch];
-    const Word32 *sfbEnergy = psyOutChan->sfbEnergy;
-    const Word32 *sfbThreshold = psyOutChan->sfbThreshold;
-
-    pe = 0;
-    constPart = 0;
-    nActiveLines = 0;
-
-    for(sfbGrp=0; sfbGrp<psyOutChan->sfbCnt; sfbGrp+=psyOutChan->sfbPerGroup) {
-      for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-        Word32 nrg = sfbEnergy[sfbGrp+sfb];
-        Word32 thres = sfbThreshold[sfbGrp+sfb];
-        Word32 sfbLDEn = peChanData->sfbLdEnergy[sfbGrp+sfb];
-
-        if (nrg > thres) {
-          ldThr = iLog4(thres);
-
-          ldRatio = sfbLDEn - ldThr;
-
-          nLines4 = peChanData->sfbNLines4[sfbGrp+sfb];
-
-          /* sfbPe = nl*log2(en/thr)*/
-		  if (ldRatio >= C1_I) {
-            peChanData->sfbPe[sfbGrp+sfb] = (nLines4*ldRatio + 8) >> 4;
-            peChanData->sfbConstPart[sfbGrp+sfb] = ((nLines4*sfbLDEn)) >> 4;
-          }
-          else {
-		  /* sfbPe = nl*(c2 + c3*log2(en/thr))*/
-            peChanData->sfbPe[sfbGrp+sfb] = extract_l((L_mpy_wx(
-                    (C2_I + C3_I * ldRatio * 2) << 4, nLines4) + 4) >> 3);
-            peChanData->sfbConstPart[sfbGrp+sfb] = extract_l(( L_mpy_wx(
-                    (C2_I + C3_I * sfbLDEn * 2) << 4, nLines4) + 4) >> 3);
-            nLines4 = (nLines4 * C3_I + (1024<<1)) >> 10;
-          }
-          peChanData->sfbNActiveLines[sfbGrp+sfb] = nLines4 >> 2;
-        }
-        else {
-          peChanData->sfbPe[sfbGrp+sfb] = 0;
-          peChanData->sfbConstPart[sfbGrp+sfb] = 0;
-          peChanData->sfbNActiveLines[sfbGrp+sfb] = 0;
-        }
-        pe = pe + peChanData->sfbPe[sfbGrp+sfb];
-        constPart = constPart + peChanData->sfbConstPart[sfbGrp+sfb];
-        nActiveLines = nActiveLines + peChanData->sfbNActiveLines[sfbGrp+sfb];
-      }
-    }
-
-	peChanData->pe = saturate(pe);
-    peChanData->constPart = saturate(constPart);
-    peChanData->nActiveLines = saturate(nActiveLines);
-
-
-	pe += peData->pe;
-	peData->pe = saturate(pe);
-    constPart += peData->constPart;
-	peData->constPart = saturate(constPart);
-    nActiveLines += peData->nActiveLines;
-	peData->nActiveLines = saturate(nActiveLines);
-  }
-}
diff --git a/media/libstagefright/codecs/aacenc/src/memalign.c b/media/libstagefright/codecs/aacenc/src/memalign.c
deleted file mode 100644
index bb266dc..0000000
--- a/media/libstagefright/codecs/aacenc/src/memalign.c
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		mem_align.c
-
-	Content:	Memory alloc alignments functions
-
-*******************************************************************************/
-
-
-#include	"memalign.h"
-#ifdef _MSC_VER
-#include	<stddef.h>
-#else
-#include	<stdint.h>
-#endif
-
-/*****************************************************************************
-*
-* function name: mem_malloc
-* description:  malloc the alignments memory
-* returns:      the point of the memory
-*
-**********************************************************************************/
-void *
-mem_malloc(VO_MEM_OPERATOR *pMemop, unsigned int size, unsigned char alignment, unsigned int CodecID)
-{
-	int ret;
-	unsigned char *mem_ptr;
-	VO_MEM_INFO MemInfo;
-
-	if (!alignment) {
-
-		MemInfo.Flag = 0;
-		MemInfo.Size = size + 1;
-		ret = pMemop->Alloc(CodecID, &MemInfo);
-		if(ret != 0)
-			return 0;
-		mem_ptr = (unsigned char *)MemInfo.VBuffer;
-
-		pMemop->Set(CodecID, mem_ptr, 0, size + 1);
-
-		*mem_ptr = (unsigned char)1;
-
-		return ((void *)(mem_ptr+1));
-	} else {
-		unsigned char *tmp;
-
-		MemInfo.Flag = 0;
-		MemInfo.Size = size + alignment;
-		ret = pMemop->Alloc(CodecID, &MemInfo);
-		if(ret != 0)
-			return 0;
-
-		tmp = (unsigned char *)MemInfo.VBuffer;
-
-		pMemop->Set(CodecID, tmp, 0, size + alignment);
-
-		mem_ptr =
-			(unsigned char *) ((intptr_t) (tmp + alignment - 1) &
-					(~((intptr_t) (alignment - 1))));
-
-		if (mem_ptr == tmp)
-			mem_ptr += alignment;
-
-		*(mem_ptr - 1) = (unsigned char) (mem_ptr - tmp);
-
-		return ((void *)mem_ptr);
-	}
-
-	return(0);
-}
-
-
-/*****************************************************************************
-*
-* function name: mem_free
-* description:  free the memory
-*
-*******************************************************************************/
-void
-mem_free(VO_MEM_OPERATOR *pMemop, void *mem_ptr, unsigned int CodecID)
-{
-
-	unsigned char *ptr;
-
-	if (mem_ptr == 0)
-		return;
-
-	ptr = mem_ptr;
-
-	ptr -= *(ptr - 1);
-
-	pMemop->Free(CodecID, ptr);
-}
-
-
-
diff --git a/media/libstagefright/codecs/aacenc/src/ms_stereo.c b/media/libstagefright/codecs/aacenc/src/ms_stereo.c
deleted file mode 100644
index ca028dc..0000000
--- a/media/libstagefright/codecs/aacenc/src/ms_stereo.c
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		ms_stereo.c
-
-	Content:	MS stereo processing function
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "psy_const.h"
-#include "ms_stereo.h"
-
-
-/********************************************************************************
-*
-* function name: MsStereoProcessing
-* description:  detect use ms stereo or not
-*				if ((min(thrLn, thrRn)*min(thrLn, thrRn))/(enMn*enSn))
-*				>= ((thrLn *thrRn)/(enLn*enRn)) then ms stereo
-*
-**********************************************************************************/
-void MsStereoProcessing(Word32       *sfbEnergyLeft,
-                        Word32       *sfbEnergyRight,
-                        const Word32 *sfbEnergyMid,
-                        const Word32 *sfbEnergySide,
-                        Word32       *mdctSpectrumLeft,
-                        Word32       *mdctSpectrumRight,
-                        Word32       *sfbThresholdLeft,
-                        Word32       *sfbThresholdRight,
-                        Word32       *sfbSpreadedEnLeft,
-                        Word32       *sfbSpreadedEnRight,
-                        Word16       *msDigest,
-                        Word16       *msMask,
-                        const Word16  sfbCnt,
-                        const Word16  sfbPerGroup,
-                        const Word16  maxSfbPerGroup,
-                        const Word16 *sfbOffset) {
-  Word32 sfb,sfboffs, j;
-  Word32 msMaskTrueSomewhere = 0;
-  Word32 msMaskFalseSomewhere = 0;
-
-  for (sfb=0; sfb<sfbCnt; sfb+=sfbPerGroup) {
-    for (sfboffs=0;sfboffs<maxSfbPerGroup;sfboffs++) {
-
-      Word32 temp;
-      Word32 pnlr,pnms;
-      Word32 minThreshold;
-      Word32 thrL, thrR, nrgL, nrgR;
-      Word32 idx, shift;
-
-      idx = sfb + sfboffs;
-
-      thrL = sfbThresholdLeft[idx];
-      thrR = sfbThresholdRight[idx];
-      nrgL = sfbEnergyLeft[idx];
-      nrgR = sfbEnergyRight[idx];
-
-      minThreshold = min(thrL, thrR);
-
-      nrgL = max(nrgL,thrL) + 1;
-      shift = norm_l(nrgL);
-	  nrgL = Div_32(thrL << shift, nrgL << shift);
-      nrgR = max(nrgR,thrR) + 1;
-      shift = norm_l(nrgR);
-	  nrgR = Div_32(thrR << shift, nrgR << shift);
-
-	  pnlr = fixmul(nrgL, nrgR);
-
-      nrgL = sfbEnergyMid[idx];
-      nrgR = sfbEnergySide[idx];
-
-      nrgL = max(nrgL,minThreshold) + 1;
-      shift = norm_l(nrgL);
-	  nrgL = Div_32(minThreshold << shift, nrgL << shift);
-
-      nrgR = max(nrgR,minThreshold) + 1;
-      shift = norm_l(nrgR);
-	  nrgR = Div_32(minThreshold << shift, nrgR << shift);
-
-      pnms = fixmul(nrgL, nrgR);
-
-      temp = pnms - pnlr;
-      if( temp > 0 ){
-
-        msMask[idx] = 1;
-        msMaskTrueSomewhere = 1;
-
-        for (j=sfbOffset[idx]; j<sfbOffset[idx+1]; j++) {
-          Word32 left, right;
-          left  = (mdctSpectrumLeft[j] >>  1);
-          right = (mdctSpectrumRight[j] >> 1);
-          mdctSpectrumLeft[j] =  left + right;
-          mdctSpectrumRight[j] =  left - right;
-        }
-
-        sfbThresholdLeft[idx] = minThreshold;
-        sfbThresholdRight[idx] = minThreshold;
-        sfbEnergyLeft[idx] = sfbEnergyMid[idx];
-        sfbEnergyRight[idx] = sfbEnergySide[idx];
-
-        sfbSpreadedEnRight[idx] = min(sfbSpreadedEnLeft[idx],sfbSpreadedEnRight[idx]) >> 1;
-        sfbSpreadedEnLeft[idx] = sfbSpreadedEnRight[idx];
-
-      }
-      else {
-        msMask[idx]  = 0;
-        msMaskFalseSomewhere = 1;
-      }
-    }
-    if ( msMaskTrueSomewhere ) {
-      if(msMaskFalseSomewhere ) {
-        *msDigest = SI_MS_MASK_SOME;
-      } else {
-        *msDigest = SI_MS_MASK_ALL;
-      }
-    } else {
-      *msDigest = SI_MS_MASK_NONE;
-    }
-  }
-
-}
diff --git a/media/libstagefright/codecs/aacenc/src/pre_echo_control.c b/media/libstagefright/codecs/aacenc/src/pre_echo_control.c
deleted file mode 100644
index 1406e11..0000000
--- a/media/libstagefright/codecs/aacenc/src/pre_echo_control.c
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		pre_echo_control.c
-
-	Content:	Pre echo control functions
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "oper_32b.h"
-
-#include "oper_32b.h"
-#include "pre_echo_control.h"
-
-
-/*****************************************************************************
-*
-* function name:InitPreEchoControl
-* description: init pre echo control parameter
-*
-*****************************************************************************/
-void InitPreEchoControl(Word32 *pbThresholdNm1,
-                        Word16  numPb,
-                        Word32 *pbThresholdQuiet)
-{
-  Word16 pb;
-
-  for(pb=0; pb<numPb; pb++) {
-    pbThresholdNm1[pb] = pbThresholdQuiet[pb];
-  }
-}
-
-/*****************************************************************************
-*
-* function name:PreEchoControl
-* description: update shreshold to avoid pre echo
-*			   thr(n) = max(rpmin*thrq(n), min(thrq(n), rpelev*thrq1(n)))
-*
-*
-*****************************************************************************/
-void PreEchoControl(Word32 *pbThresholdNm1,
-                    Word16  numPb,
-                    Word32  maxAllowedIncreaseFactor,
-                    Word16  minRemainingThresholdFactor,
-                    Word32 *pbThreshold,
-                    Word16  mdctScale,
-                    Word16  mdctScalenm1)
-{
-  Word32 i;
-  Word32 tmpThreshold1, tmpThreshold2;
-  Word32 scaling;
-
-  /* maxAllowedIncreaseFactor is hard coded to 2 */
-  (void)maxAllowedIncreaseFactor;
-
-  scaling = ((mdctScale - mdctScalenm1) << 1);
-
-  if ( scaling > 0 ) {
-    for(i = 0; i < numPb; i++) {
-      tmpThreshold1 = pbThresholdNm1[i] >> (scaling-1);
-      tmpThreshold2 = L_mpy_ls(pbThreshold[i], minRemainingThresholdFactor);
-
-      /* copy thresholds to internal memory */
-      pbThresholdNm1[i] = pbThreshold[i];
-
-
-      if(pbThreshold[i] > tmpThreshold1) {
-        pbThreshold[i] = tmpThreshold1;
-      }
-
-      if(tmpThreshold2 > pbThreshold[i]) {
-        pbThreshold[i] = tmpThreshold2;
-      }
-
-    }
-  }
-  else {
-    scaling = -scaling;
-    for(i = 0; i < numPb; i++) {
-
-      tmpThreshold1 = pbThresholdNm1[i] << 1;
-      tmpThreshold2 = L_mpy_ls(pbThreshold[i], minRemainingThresholdFactor);
-
-      /* copy thresholds to internal memory */
-      pbThresholdNm1[i] = pbThreshold[i];
-
-
-      if(((pbThreshold[i] >> scaling) > tmpThreshold1)) {
-        pbThreshold[i] = tmpThreshold1 << scaling;
-      }
-
-      if(tmpThreshold2 > pbThreshold[i]) {
-        pbThreshold[i] = tmpThreshold2;
-      }
-
-    }
-  }
-}
-
diff --git a/media/libstagefright/codecs/aacenc/src/psy_configuration.c b/media/libstagefright/codecs/aacenc/src/psy_configuration.c
deleted file mode 100644
index dd40f9b..0000000
--- a/media/libstagefright/codecs/aacenc/src/psy_configuration.c
+++ /dev/null
@@ -1,505 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		psy_configuration.c
-
-	Content:	Psychoaccoustic configuration functions
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "psy_configuration.h"
-#include "adj_thr.h"
-#include "aac_rom.h"
-
-
-
-#define BARC_SCALE	100 /* integer barc values are scaled with 100 */
-#define LOG2_1000	301 /* log2*1000 */
-#define PI2_1000	1571 /* pi/2*1000*/
-#define ATAN_COEF1	3560 /* 1000/0.280872f*/
-#define ATAN_COEF2	281 /* 1000*0.280872f*/
-
-
-typedef struct{
-  Word32 sampleRate;
-  const UWord8 *paramLong;
-  const UWord8 *paramShort;
-}SFB_INFO_TAB;
-
-static const Word16 ABS_LEV = 20;
-static const Word16 BARC_THR_QUIET[] = {15, 10,  7,  2,  0,  0,  0,  0,  0,  0,
-                                         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-                                         3,  5, 10, 20, 30};
-
-
-
-static const Word16 max_bark = 24; /* maximum bark-value */
-static const Word16 maskLow  = 30; /* in 1dB/bark */
-static const Word16 maskHigh = 15; /* in 1*dB/bark */
-static const Word16 c_ratio  = 0x0029; /* pow(10.0f, -(29.0f/10.0f)) */
-
-static const Word16 maskLowSprEnLong = 30;       /* in 1dB/bark */
-static const Word16 maskHighSprEnLong = 20;      /* in 1dB/bark */
-static const Word16 maskHighSprEnLongLowBr = 15; /* in 1dB/bark */
-static const Word16 maskLowSprEnShort = 20;      /* in 1dB/bark */
-static const Word16 maskHighSprEnShort = 15;     /* in 1dB/bark */
-static const Word16 c_minRemainingThresholdFactor = 0x0148;    /* 0.01 *(1 << 15)*/
-static const Word32 c_maxsnr = 0x66666666;		 /* upper limit is -1 dB */
-static const Word32 c_minsnr = 0x00624dd3;		 /* lower limit is -25 dB */
-
-static const Word32 c_maxClipEnergyLong = 0x77359400;  /* 2.0e9f*/
-static const Word32 c_maxClipEnergyShort = 0x01dcd650; /* 2.0e9f/(AACENC_TRANS_FAC*AACENC_TRANS_FAC)*/
-
-
-Word32 GetSRIndex(Word32 sampleRate)
-{
-    if (92017 <= sampleRate) return 0;
-    if (75132 <= sampleRate) return 1;
-    if (55426 <= sampleRate) return 2;
-    if (46009 <= sampleRate) return 3;
-    if (37566 <= sampleRate) return 4;
-    if (27713 <= sampleRate) return 5;
-    if (23004 <= sampleRate) return 6;
-    if (18783 <= sampleRate) return 7;
-    if (13856 <= sampleRate) return 8;
-    if (11502 <= sampleRate) return 9;
-    if (9391 <= sampleRate) return 10;
-
-    return 11;
-}
-
-
-/*********************************************************************************
-*
-* function name: atan_1000
-* description:  calculates 1000*atan(x/1000)
-*               based on atan approx for x > 0
-*				atan(x) = x/((float)1.0f+(float)0.280872f*x*x)  if x < 1
-*						= pi/2 - x/((float)0.280872f +x*x)	    if x >= 1
-* return:       1000*atan(x/1000)
-*
-**********************************************************************************/
-static Word16 atan_1000(Word32 val)
-{
-  Word32 y;
-
-
-  if(L_sub(val, 1000) < 0) {
-    y = extract_l(((1000 * val) / (1000 + ((val * val) / ATAN_COEF1))));
-  }
-  else {
-    y = PI2_1000 - ((1000 * val) / (ATAN_COEF2 + ((val * val) / 1000)));
-  }
-
-  return extract_l(y);
-}
-
-
-/*****************************************************************************
-*
-* function name: BarcLineValue
-* description:  Calculates barc value for one frequency line
-* returns:      barc value of line * BARC_SCALE
-* input:        number of lines in transform, index of line to check, Fs
-* output:
-*
-*****************************************************************************/
-static Word16 BarcLineValue(Word16 noOfLines, Word16 fftLine, Word32 samplingFreq)
-{
-  Word32 center_freq, temp, bvalFFTLine;
-
-  /* center frequency of fft line */
-  center_freq = (fftLine * samplingFreq) / (noOfLines << 1);
-  temp =  atan_1000((center_freq << 2) / (3*10));
-  bvalFFTLine =
-    (26600 * atan_1000((center_freq*76) / 100) + 7*temp*temp) / (2*1000*1000 / BARC_SCALE);
-
-  return saturate(bvalFFTLine);
-}
-
-/*****************************************************************************
-*
-* function name: initThrQuiet
-* description:  init thredhold in quiet
-*
-*****************************************************************************/
-static void initThrQuiet(Word16  numPb,
-                         const Word16 *pbOffset,
-                         Word16 *pbBarcVal,
-                         Word32 *pbThresholdQuiet) {
-  Word16 i;
-  Word16 barcThrQuiet;
-
-  for(i=0; i<numPb; i++) {
-    Word16 bv1, bv2;
-
-
-    if (i>0)
-      bv1 = (pbBarcVal[i] + pbBarcVal[i-1]) >> 1;
-    else
-      bv1 = pbBarcVal[i] >> 1;
-
-
-    if (i < (numPb - 1))
-      bv2 = (pbBarcVal[i] + pbBarcVal[i+1]) >> 1;
-    else {
-      bv2 = pbBarcVal[i];
-    }
-
-    bv1 = min((bv1 / BARC_SCALE), max_bark);
-    bv2 = min((bv2 / BARC_SCALE), max_bark);
-
-    barcThrQuiet = min(BARC_THR_QUIET[bv1], BARC_THR_QUIET[bv2]);
-
-
-    /*
-      we calculate
-      pow(10.0f,(float)(barcThrQuiet - ABS_LEV)*0.1)*(float)ABS_LOW*(pbOffset[i+1] - pbOffset[i]);
-    */
-
-    pbThresholdQuiet[i] = pow2_xy((((barcThrQuiet - ABS_LEV) * 100) +
-                          LOG2_1000*(14+2*LOG_NORM_PCM)), LOG2_1000) * (pbOffset[i+1] - pbOffset[i]);
-  }
-}
-
-
-/*****************************************************************************
-*
-* function name: initSpreading
-* description:  init energy spreading parameter
-*
-*****************************************************************************/
-static void initSpreading(Word16  numPb,
-                          Word16 *pbBarcValue,
-                          Word16 *pbMaskLoFactor,
-                          Word16 *pbMaskHiFactor,
-                          Word16 *pbMaskLoFactorSprEn,
-                          Word16 *pbMaskHiFactorSprEn,
-                          const Word32 bitrate,
-                          const Word16 blockType)
-{
-  Word16 i;
-  Word16 maskLowSprEn, maskHighSprEn;
-
-
-  if (sub(blockType, SHORT_WINDOW) != 0) {
-    maskLowSprEn = maskLowSprEnLong;
-
-    if (bitrate > 22000)
-      maskHighSprEn = maskHighSprEnLong;
-    else
-      maskHighSprEn = maskHighSprEnLongLowBr;
-  }
-  else {
-    maskLowSprEn = maskLowSprEnShort;
-    maskHighSprEn = maskHighSprEnShort;
-  }
-
-  for(i=0; i<numPb; i++) {
-
-    if (i > 0) {
-      Word32 dbVal;
-      Word16 dbark = pbBarcValue[i] - pbBarcValue[i-1];
-
-      /*
-        we calulate pow(10.0f, -0.1*dbVal/BARC_SCALE)
-      */
-      dbVal = (maskHigh * dbark);
-      pbMaskHiFactor[i] = round16(pow2_xy(L_negate(dbVal), (Word32)LOG2_1000));             /* 0.301 log10(2) */
-
-      dbVal = (maskLow * dbark);
-      pbMaskLoFactor[i-1] = round16(pow2_xy(L_negate(dbVal),(Word32)LOG2_1000));
-
-
-      dbVal = (maskHighSprEn * dbark);
-      pbMaskHiFactorSprEn[i] =  round16(pow2_xy(L_negate(dbVal),(Word32)LOG2_1000));
-      dbVal = (maskLowSprEn * dbark);
-      pbMaskLoFactorSprEn[i-1] = round16(pow2_xy(L_negate(dbVal),(Word32)LOG2_1000));
-    }
-    else {
-      pbMaskHiFactor[i] = 0;
-      pbMaskLoFactor[numPb-1] = 0;
-
-      pbMaskHiFactorSprEn[i] = 0;
-      pbMaskLoFactorSprEn[numPb-1] = 0;
-    }
-  }
-
-}
-
-
-/*****************************************************************************
-*
-* function name: initBarcValues
-* description:  init bark value
-*
-*****************************************************************************/
-static void initBarcValues(Word16  numPb,
-                           const Word16 *pbOffset,
-                           Word16  numLines,
-                           Word32  samplingFrequency,
-                           Word16 *pbBval)
-{
-  Word16 i;
-  Word16 pbBval0, pbBval1;
-
-  pbBval0 = 0;
-
-  for(i=0; i<numPb; i++){
-    pbBval1 = BarcLineValue(numLines, pbOffset[i+1], samplingFrequency);
-    pbBval[i] = (pbBval0 + pbBval1) >> 1;
-    pbBval0 = pbBval1;
-  }
-}
-
-
-/*****************************************************************************
-*
-* function name: initMinSnr
-* description:  calculate min snr parameter
-*				minSnr(n) = 1/(2^sfbPemin(n)/w(n) - 1.5)
-*
-*****************************************************************************/
-static void initMinSnr(const Word32  bitrate,
-                       const Word32  samplerate,
-                       const Word16  numLines,
-                       const Word16 *sfbOffset,
-                       const Word16 *pbBarcVal,
-                       const Word16  sfbActive,
-                       Word16       *sfbMinSnr)
-{
-  Word16 sfb;
-  Word16 barcWidth;
-  Word16 pePerWindow;
-  Word32 pePart;
-  Word32 snr;
-  Word16 pbVal0, pbVal1, shift;
-
-  /* relative number of active barks */
-
-
-  pePerWindow = bits2pe(extract_l((bitrate * numLines) / samplerate));
-
-  pbVal0 = 0;
-
-  for (sfb=0; sfb<sfbActive; sfb++) {
-
-    pbVal1 = (pbBarcVal[sfb] << 1) - pbVal0;
-    barcWidth = pbVal1 - pbVal0;
-    pbVal0 = pbVal1;
-
-    /* allow at least 2.4% of pe for each active barc */
-	pePart = ((pePerWindow * 24) * (max_bark * barcWidth)) /
-        (pbBarcVal[sfbActive-1] * (sfbOffset[sfb+1] - sfbOffset[sfb]));
-
-
-    pePart = min(pePart, 8400);
-    pePart = max(pePart, 1400);
-
-    /* minSnr(n) = 1/(2^sfbPemin(n)/w(n) - 1.5)*/
-	/* we add an offset of 2^16 to the pow functions */
-	/* 0xc000 = 1.5*(1 << 15)*/
-
-    snr = pow2_xy((pePart - 16*1000),1000) - 0x0000c000;
-
-    if(snr > 0x00008000)
-	{
-		shift = norm_l(snr);
-		snr = Div_32(0x00008000 << shift, snr << shift);
-	}
-	else
-	{
-		snr = 0x7fffffff;
-	}
-
-    /* upper limit is -1 dB */
-    snr = min(snr, c_maxsnr);
-    /* lower limit is -25 dB */
-    snr = max(snr, c_minsnr);
-    sfbMinSnr[sfb] = round16(snr);
-  }
-
-}
-
-/*****************************************************************************
-*
-* function name: InitPsyConfigurationLong
-* description:  init long block psychoacoustic configuration
-*
-*****************************************************************************/
-Word16 InitPsyConfigurationLong(Word32 bitrate,
-                                Word32 samplerate,
-                                Word16 bandwidth,
-                                PSY_CONFIGURATION_LONG *psyConf)
-{
-  Word32 samplerateindex;
-  Word16 sfbBarcVal[MAX_SFB_LONG];
-  Word16 sfb;
-
-  /*
-    init sfb table
-  */
-  samplerateindex = GetSRIndex(samplerate);
-  psyConf->sfbCnt = sfBandTotalLong[samplerateindex];
-  psyConf->sfbOffset = sfBandTabLong + sfBandTabLongOffset[samplerateindex];
-  psyConf->sampRateIdx = samplerateindex;
-
-  /*
-    calculate barc values for each pb
-  */
-  initBarcValues(psyConf->sfbCnt,
-                 psyConf->sfbOffset,
-                 psyConf->sfbOffset[psyConf->sfbCnt],
-                 samplerate,
-                 sfbBarcVal);
-
-  /*
-    init thresholds in quiet
-  */
-  initThrQuiet(psyConf->sfbCnt,
-               psyConf->sfbOffset,
-               sfbBarcVal,
-               psyConf->sfbThresholdQuiet);
-
-  /*
-    calculate spreading function
-  */
-  initSpreading(psyConf->sfbCnt,
-                sfbBarcVal,
-                psyConf->sfbMaskLowFactor,
-                psyConf->sfbMaskHighFactor,
-                psyConf->sfbMaskLowFactorSprEn,
-                psyConf->sfbMaskHighFactorSprEn,
-                bitrate,
-                LONG_WINDOW);
-
-  /*
-    init ratio
-  */
-  psyConf->ratio = c_ratio;
-
-  psyConf->maxAllowedIncreaseFactor = 2;
-  psyConf->minRemainingThresholdFactor = c_minRemainingThresholdFactor;    /* 0.01 *(1 << 15)*/
-
-  psyConf->clipEnergy = c_maxClipEnergyLong;
-  psyConf->lowpassLine = extract_l((bandwidth<<1) * FRAME_LEN_LONG / samplerate);
-
-  for (sfb = 0; sfb < psyConf->sfbCnt; sfb++) {
-    if (sub(psyConf->sfbOffset[sfb], psyConf->lowpassLine) >= 0)
-      break;
-  }
-  psyConf->sfbActive = sfb;
-
-  /*
-    calculate minSnr
-  */
-  initMinSnr(bitrate,
-             samplerate,
-             psyConf->sfbOffset[psyConf->sfbCnt],
-             psyConf->sfbOffset,
-             sfbBarcVal,
-             psyConf->sfbActive,
-             psyConf->sfbMinSnr);
-
-
-  return(0);
-}
-
-/*****************************************************************************
-*
-* function name: InitPsyConfigurationShort
-* description:  init short block psychoacoustic configuration
-*
-*****************************************************************************/
-Word16 InitPsyConfigurationShort(Word32 bitrate,
-                                 Word32 samplerate,
-                                 Word16 bandwidth,
-                                 PSY_CONFIGURATION_SHORT *psyConf)
-{
-  Word32 samplerateindex;
-  Word16 sfbBarcVal[MAX_SFB_SHORT];
-  Word16 sfb;
-  /*
-    init sfb table
-  */
-  samplerateindex = GetSRIndex(samplerate);
-  psyConf->sfbCnt = sfBandTotalShort[samplerateindex];
-  psyConf->sfbOffset = sfBandTabShort + sfBandTabShortOffset[samplerateindex];
-  psyConf->sampRateIdx = samplerateindex;
-  /*
-    calculate barc values for each pb
-  */
-  initBarcValues(psyConf->sfbCnt,
-                 psyConf->sfbOffset,
-                 psyConf->sfbOffset[psyConf->sfbCnt],
-                 samplerate,
-                 sfbBarcVal);
-
-  /*
-    init thresholds in quiet
-  */
-  initThrQuiet(psyConf->sfbCnt,
-               psyConf->sfbOffset,
-               sfbBarcVal,
-               psyConf->sfbThresholdQuiet);
-
-  /*
-    calculate spreading function
-  */
-  initSpreading(psyConf->sfbCnt,
-                sfbBarcVal,
-                psyConf->sfbMaskLowFactor,
-                psyConf->sfbMaskHighFactor,
-                psyConf->sfbMaskLowFactorSprEn,
-                psyConf->sfbMaskHighFactorSprEn,
-                bitrate,
-                SHORT_WINDOW);
-
-  /*
-    init ratio
-  */
-  psyConf->ratio = c_ratio;
-
-  psyConf->maxAllowedIncreaseFactor = 2;
-  psyConf->minRemainingThresholdFactor = c_minRemainingThresholdFactor;
-
-  psyConf->clipEnergy = c_maxClipEnergyShort;
-
-  psyConf->lowpassLine = extract_l(((bandwidth << 1) * FRAME_LEN_SHORT) / samplerate);
-
-  for (sfb = 0; sfb < psyConf->sfbCnt; sfb++) {
-
-    if (psyConf->sfbOffset[sfb] >= psyConf->lowpassLine)
-      break;
-  }
-  psyConf->sfbActive = sfb;
-
-  /*
-    calculate minSnr
-  */
-  initMinSnr(bitrate,
-             samplerate,
-             psyConf->sfbOffset[psyConf->sfbCnt],
-             psyConf->sfbOffset,
-             sfbBarcVal,
-             psyConf->sfbActive,
-             psyConf->sfbMinSnr);
-
-  return(0);
-}
-
diff --git a/media/libstagefright/codecs/aacenc/src/psy_main.c b/media/libstagefright/codecs/aacenc/src/psy_main.c
deleted file mode 100644
index 6f0679c..0000000
--- a/media/libstagefright/codecs/aacenc/src/psy_main.c
+++ /dev/null
@@ -1,815 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		psy_main.c
-
-	Content:	Psychoacoustic major functions
-
-*******************************************************************************/
-
-#include "typedef.h"
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "psy_const.h"
-#include "block_switch.h"
-#include "transform.h"
-#include "spreading.h"
-#include "pre_echo_control.h"
-#include "band_nrg.h"
-#include "psy_configuration.h"
-#include "psy_data.h"
-#include "ms_stereo.h"
-#include "interface.h"
-#include "psy_main.h"
-#include "grp_data.h"
-#include "tns_func.h"
-#include "memalign.h"
-
-#define UNUSED(x) (void)(x)
-
-/*                                    long       start       short       stop */
-static Word16 blockType2windowShape[] = {KBD_WINDOW,SINE_WINDOW,SINE_WINDOW,KBD_WINDOW};
-
-/*
-  forward definitions
-*/
-static Word16 advancePsychLong(PSY_DATA* psyData,
-                               TNS_DATA* tnsData,
-                               PSY_CONFIGURATION_LONG *hPsyConfLong,
-                               PSY_OUT_CHANNEL* psyOutChannel,
-                               Word32 *pScratchTns,
-                               const TNS_DATA *tnsData2,
-                               const Word16 ch);
-
-static Word16 advancePsychLongMS (PSY_DATA  psyData[MAX_CHANNELS],
-                                  const PSY_CONFIGURATION_LONG *hPsyConfLong);
-
-static Word16 advancePsychShort(PSY_DATA* psyData,
-                                TNS_DATA* tnsData,
-                                const PSY_CONFIGURATION_SHORT *hPsyConfShort,
-                                PSY_OUT_CHANNEL* psyOutChannel,
-                                Word32 *pScratchTns,
-                                const TNS_DATA *tnsData2,
-                                const Word16 ch);
-
-static Word16 advancePsychShortMS (PSY_DATA  psyData[MAX_CHANNELS],
-                                   const PSY_CONFIGURATION_SHORT *hPsyConfShort);
-
-
-/*****************************************************************************
-*
-* function name: PsyNew
-* description:  allocates memory for psychoacoustic
-* returns:      an error code
-* input:        pointer to a psych handle
-*
-*****************************************************************************/
-Word16 PsyNew(PSY_KERNEL *hPsy, Word32 nChan, VO_MEM_OPERATOR *pMemOP)
-{
-  Word16 i;
-  Word32 *mdctSpectrum;
-  Word32 *scratchTNS;
-  Word16 *mdctDelayBuffer;
-
-  mdctSpectrum = (Word32 *)mem_malloc(pMemOP, nChan * FRAME_LEN_LONG * sizeof(Word32), 32, VO_INDEX_ENC_AAC);
-  if(NULL == mdctSpectrum)
-	  return 1;
-
-  scratchTNS = (Word32 *)mem_malloc(pMemOP, nChan * FRAME_LEN_LONG * sizeof(Word32), 32, VO_INDEX_ENC_AAC);
-  if(NULL == scratchTNS)
-  {
-	  return 1;
-  }
-
-  mdctDelayBuffer = (Word16 *)mem_malloc(pMemOP, nChan * BLOCK_SWITCHING_OFFSET * sizeof(Word16), 32, VO_INDEX_ENC_AAC);
-  if(NULL == mdctDelayBuffer)
-  {
-	  return 1;
-  }
-
-  for (i=0; i<nChan; i++){
-    hPsy->psyData[i].mdctDelayBuffer = mdctDelayBuffer + i*BLOCK_SWITCHING_OFFSET;
-    hPsy->psyData[i].mdctSpectrum = mdctSpectrum + i*FRAME_LEN_LONG;
-  }
-
-  hPsy->pScratchTns = scratchTNS;
-
-  return 0;
-}
-
-
-/*****************************************************************************
-*
-* function name: PsyDelete
-* description:  allocates memory for psychoacoustic
-* returns:      an error code
-*
-*****************************************************************************/
-Word16 PsyDelete(PSY_KERNEL  *hPsy, VO_MEM_OPERATOR *pMemOP)
-{
-  Word32 nch;
-
-  if(hPsy)
-  {
-	if(hPsy->psyData[0].mdctDelayBuffer)
-		mem_free(pMemOP, hPsy->psyData[0].mdctDelayBuffer, VO_INDEX_ENC_AAC);
-
-    if(hPsy->psyData[0].mdctSpectrum)
-		mem_free(pMemOP, hPsy->psyData[0].mdctSpectrum, VO_INDEX_ENC_AAC);
-
-    for (nch=0; nch<MAX_CHANNELS; nch++){
-	  hPsy->psyData[nch].mdctDelayBuffer = NULL;
-	  hPsy->psyData[nch].mdctSpectrum = NULL;
-	}
-
-	if(hPsy->pScratchTns)
-	{
-		mem_free(pMemOP, hPsy->pScratchTns, VO_INDEX_ENC_AAC);
-		hPsy->pScratchTns = NULL;
-	}
-  }
-
-  return 0;
-}
-
-
-/*****************************************************************************
-*
-* function name: PsyOutNew
-* description:  allocates memory for psyOut struc
-* returns:      an error code
-* input:        pointer to a psych handle
-*
-*****************************************************************************/
-Word16 PsyOutNew(PSY_OUT *hPsyOut, VO_MEM_OPERATOR *pMemOP)
-{
-  pMemOP->Set(VO_INDEX_ENC_AAC, hPsyOut, 0, sizeof(PSY_OUT));
-  /*
-    alloc some more stuff, tbd
-  */
-  return 0;
-}
-
-/*****************************************************************************
-*
-* function name: PsyOutDelete
-* description:  allocates memory for psychoacoustic
-* returns:      an error code
-*
-*****************************************************************************/
-Word16 PsyOutDelete(PSY_OUT *hPsyOut, VO_MEM_OPERATOR *pMemOP)
-{
-  UNUSED(hPsyOut);
-  UNUSED(pMemOP);
-
-  return 0;
-}
-
-
-/*****************************************************************************
-*
-* function name: psyMainInit
-* description:  initializes psychoacoustic
-* returns:      an error code
-*
-*****************************************************************************/
-
-Word16 psyMainInit(PSY_KERNEL *hPsy,
-                   Word32 sampleRate,
-                   Word32 bitRate,
-                   Word16 channels,
-                   Word16 tnsMask,
-                   Word16 bandwidth)
-{
-  Word16 ch, err;
-  Word32 channelBitRate = bitRate/channels;
-
-  err = InitPsyConfigurationLong(channelBitRate,
-                                 sampleRate,
-                                 bandwidth,
-                                 &(hPsy->psyConfLong));
-
-  if (!err) {
-      hPsy->sampleRateIdx = hPsy->psyConfLong.sampRateIdx;
-	  err = InitTnsConfigurationLong(bitRate, sampleRate, channels,
-                                   &hPsy->psyConfLong.tnsConf, &hPsy->psyConfLong, tnsMask&2);
-  }
-
-  if (!err)
-    err = InitPsyConfigurationShort(channelBitRate,
-                                    sampleRate,
-                                    bandwidth,
-                                    &hPsy->psyConfShort);
-  if (!err) {
-    err = InitTnsConfigurationShort(bitRate, sampleRate, channels,
-                                    &hPsy->psyConfShort.tnsConf, &hPsy->psyConfShort, tnsMask&1);
-  }
-
-  if (!err)
-    for(ch=0;ch < channels;ch++){
-
-      InitBlockSwitching(&hPsy->psyData[ch].blockSwitchingControl,
-                         bitRate, channels);
-
-      InitPreEchoControl(hPsy->psyData[ch].sfbThresholdnm1,
-                         hPsy->psyConfLong.sfbCnt,
-                         hPsy->psyConfLong.sfbThresholdQuiet);
-      hPsy->psyData[ch].mdctScalenm1 = 0;
-    }
-
-	return(err);
-}
-
-/*****************************************************************************
-*
-* function name: psyMain
-* description:  psychoacoustic main function
-* returns:      an error code
-*
-*    This function assumes that enough input data is in the modulo buffer.
-*
-*****************************************************************************/
-
-Word16 psyMain(Word16                   nChannels,
-               ELEMENT_INFO            *elemInfo,
-               Word16                  *timeSignal,
-               PSY_DATA                 psyData[MAX_CHANNELS],
-               TNS_DATA                 tnsData[MAX_CHANNELS],
-               PSY_CONFIGURATION_LONG  *hPsyConfLong,
-               PSY_CONFIGURATION_SHORT *hPsyConfShort,
-               PSY_OUT_CHANNEL          psyOutChannel[MAX_CHANNELS],
-               PSY_OUT_ELEMENT         *psyOutElement,
-               Word32                  *pScratchTns,
-			   Word32				   sampleRate)
-{
-  Word16 maxSfbPerGroup[MAX_CHANNELS];
-  Word16 mdctScalingArray[MAX_CHANNELS];
-
-  Word16 ch;   /* counts through channels          */
-  Word16 sfb;  /* counts through scalefactor bands */
-  Word16 line; /* counts through lines             */
-  Word16 channels;
-  Word16 maxScale;
-
-  channels = elemInfo->nChannelsInEl;
-  maxScale = 0;
-
-  /* block switching */
-  for(ch = 0; ch < channels; ch++) {
-    BlockSwitching(&psyData[ch].blockSwitchingControl,
-                   timeSignal+elemInfo->ChannelIndex[ch],
-				   sampleRate,
-                   nChannels);
-  }
-
-  /* synch left and right block type */
-  SyncBlockSwitching(&psyData[0].blockSwitchingControl,
-                     &psyData[1].blockSwitchingControl,
-                     channels);
-
-  /* transform
-     and get maxScale (max mdctScaling) for all channels */
-  for(ch=0; ch<channels; ch++) {
-    Transform_Real(psyData[ch].mdctDelayBuffer,
-                   timeSignal+elemInfo->ChannelIndex[ch],
-                   nChannels,
-                   psyData[ch].mdctSpectrum,
-                   &(mdctScalingArray[ch]),
-                   psyData[ch].blockSwitchingControl.windowSequence);
-    maxScale = max(maxScale, mdctScalingArray[ch]);
-  }
-
-  /* common scaling for all channels */
-  for (ch=0; ch<channels; ch++) {
-    Word16 scaleDiff = maxScale - mdctScalingArray[ch];
-
-    if (scaleDiff > 0) {
-      Word32 *Spectrum = psyData[ch].mdctSpectrum;
-	  for(line=0; line<FRAME_LEN_LONG; line++) {
-        *Spectrum = (*Spectrum) >> scaleDiff;
-		Spectrum++;
-      }
-    }
-    psyData[ch].mdctScale = maxScale;
-  }
-
-  for (ch=0; ch<channels; ch++) {
-
-    if(psyData[ch].blockSwitchingControl.windowSequence != SHORT_WINDOW) {
-      /* update long block parameter */
-	  advancePsychLong(&psyData[ch],
-                       &tnsData[ch],
-                       hPsyConfLong,
-                       &psyOutChannel[ch],
-                       pScratchTns,
-                       &tnsData[1 - ch],
-                       ch);
-
-      /* determine maxSfb */
-      for (sfb=hPsyConfLong->sfbCnt-1; sfb>=0; sfb--) {
-        for (line=hPsyConfLong->sfbOffset[sfb+1] - 1; line>=hPsyConfLong->sfbOffset[sfb]; line--) {
-
-          if (psyData[ch].mdctSpectrum[line] != 0) break;
-        }
-        if (line >= hPsyConfLong->sfbOffset[sfb]) break;
-      }
-      maxSfbPerGroup[ch] = sfb + 1;
-
-      /* Calc bandwise energies for mid and side channel
-         Do it only if 2 channels exist */
-
-      if (ch == 1)
-        advancePsychLongMS(psyData, hPsyConfLong);
-    }
-    else {
-      advancePsychShort(&psyData[ch],
-                        &tnsData[ch],
-                        hPsyConfShort,
-                        &psyOutChannel[ch],
-                        pScratchTns,
-                        &tnsData[1 - ch],
-                        ch);
-
-      /* Calc bandwise energies for mid and side channel
-         Do it only if 2 channels exist */
-
-      if (ch == 1)
-        advancePsychShortMS (psyData, hPsyConfShort);
-    }
-  }
-
-  /* group short data */
-  for(ch=0; ch<channels; ch++) {
-
-    if (psyData[ch].blockSwitchingControl.windowSequence == SHORT_WINDOW) {
-      groupShortData(psyData[ch].mdctSpectrum,
-                     pScratchTns,
-                     &psyData[ch].sfbThreshold,
-                     &psyData[ch].sfbEnergy,
-                     &psyData[ch].sfbEnergyMS,
-                     &psyData[ch].sfbSpreadedEnergy,
-                     hPsyConfShort->sfbCnt,
-                     hPsyConfShort->sfbOffset,
-                     hPsyConfShort->sfbMinSnr,
-                     psyOutElement->groupedSfbOffset[ch],
-                     &maxSfbPerGroup[ch],
-                     psyOutElement->groupedSfbMinSnr[ch],
-                     psyData[ch].blockSwitchingControl.noOfGroups,
-                     psyData[ch].blockSwitchingControl.groupLen);
-    }
-  }
-
-
-#if (MAX_CHANNELS>1)
-  /*
-    stereo Processing
-  */
-  if (channels == 2) {
-    psyOutElement->toolsInfo.msDigest = MS_NONE;
-    maxSfbPerGroup[0] = maxSfbPerGroup[1] = max(maxSfbPerGroup[0], maxSfbPerGroup[1]);
-
-
-    if (psyData[0].blockSwitchingControl.windowSequence != SHORT_WINDOW)
-      MsStereoProcessing(psyData[0].sfbEnergy.sfbLong,
-                         psyData[1].sfbEnergy.sfbLong,
-                         psyData[0].sfbEnergyMS.sfbLong,
-                         psyData[1].sfbEnergyMS.sfbLong,
-                         psyData[0].mdctSpectrum,
-                         psyData[1].mdctSpectrum,
-                         psyData[0].sfbThreshold.sfbLong,
-                         psyData[1].sfbThreshold.sfbLong,
-                         psyData[0].sfbSpreadedEnergy.sfbLong,
-                         psyData[1].sfbSpreadedEnergy.sfbLong,
-                         (Word16*)&psyOutElement->toolsInfo.msDigest,
-                         (Word16*)psyOutElement->toolsInfo.msMask,
-                         hPsyConfLong->sfbCnt,
-                         hPsyConfLong->sfbCnt,
-                         maxSfbPerGroup[0],
-                         (const Word16*)hPsyConfLong->sfbOffset);
-      else
-        MsStereoProcessing(psyData[0].sfbEnergy.sfbLong,
-                           psyData[1].sfbEnergy.sfbLong,
-                           psyData[0].sfbEnergyMS.sfbLong,
-                           psyData[1].sfbEnergyMS.sfbLong,
-                           psyData[0].mdctSpectrum,
-                           psyData[1].mdctSpectrum,
-                           psyData[0].sfbThreshold.sfbLong,
-                           psyData[1].sfbThreshold.sfbLong,
-                           psyData[0].sfbSpreadedEnergy.sfbLong,
-                           psyData[1].sfbSpreadedEnergy.sfbLong,
-                           (Word16*)&psyOutElement->toolsInfo.msDigest,
-                           (Word16*)psyOutElement->toolsInfo.msMask,
-                           psyData[0].blockSwitchingControl.noOfGroups*hPsyConfShort->sfbCnt,
-                           hPsyConfShort->sfbCnt,
-                           maxSfbPerGroup[0],
-                           (const Word16*)psyOutElement->groupedSfbOffset[0]);
-  }
-
-#endif /* (MAX_CHANNELS>1) */
-
-  /*
-    build output
-  */
-  for(ch=0;ch<channels;ch++) {
-
-    if (psyData[ch].blockSwitchingControl.windowSequence != SHORT_WINDOW)
-      BuildInterface(psyData[ch].mdctSpectrum,
-                     psyData[ch].mdctScale,
-                     &psyData[ch].sfbThreshold,
-                     &psyData[ch].sfbEnergy,
-                     &psyData[ch].sfbSpreadedEnergy,
-                     psyData[ch].sfbEnergySum,
-                     psyData[ch].sfbEnergySumMS,
-                     psyData[ch].blockSwitchingControl.windowSequence,
-                     blockType2windowShape[psyData[ch].blockSwitchingControl.windowSequence],
-                     hPsyConfLong->sfbCnt,
-                     hPsyConfLong->sfbOffset,
-                     maxSfbPerGroup[ch],
-                     hPsyConfLong->sfbMinSnr,
-                     psyData[ch].blockSwitchingControl.noOfGroups,
-                     psyData[ch].blockSwitchingControl.groupLen,
-                     &psyOutChannel[ch]);
-    else
-      BuildInterface(psyData[ch].mdctSpectrum,
-                     psyData[ch].mdctScale,
-                     &psyData[ch].sfbThreshold,
-                     &psyData[ch].sfbEnergy,
-                     &psyData[ch].sfbSpreadedEnergy,
-                     psyData[ch].sfbEnergySum,
-                     psyData[ch].sfbEnergySumMS,
-                     SHORT_WINDOW,
-                     SINE_WINDOW,
-                     psyData[0].blockSwitchingControl.noOfGroups*hPsyConfShort->sfbCnt,
-                     psyOutElement->groupedSfbOffset[ch],
-                     maxSfbPerGroup[ch],
-                     psyOutElement->groupedSfbMinSnr[ch],
-                     psyData[ch].blockSwitchingControl.noOfGroups,
-                     psyData[ch].blockSwitchingControl.groupLen,
-                     &psyOutChannel[ch]);
-  }
-
-  return(0); /* no error */
-}
-
-/*****************************************************************************
-*
-* function name: advancePsychLong
-* description:  psychoacoustic for long blocks
-*
-*****************************************************************************/
-
-static Word16 advancePsychLong(PSY_DATA* psyData,
-                               TNS_DATA* tnsData,
-                               PSY_CONFIGURATION_LONG *hPsyConfLong,
-                               PSY_OUT_CHANNEL* psyOutChannel,
-                               Word32 *pScratchTns,
-                               const TNS_DATA* tnsData2,
-                               const Word16 ch)
-{
-  Word32 i;
-  Word32 normEnergyShift = (psyData->mdctScale + 1) << 1; /* in reference code, mdct spectrum must be multipied with 2, so +1 */
-  Word32 clipEnergy = hPsyConfLong->clipEnergy >> normEnergyShift;
-  Word32 *data0, *data1, tdata;
-
-  /* low pass */
-  data0 = psyData->mdctSpectrum + hPsyConfLong->lowpassLine;
-  for(i=hPsyConfLong->lowpassLine; i<FRAME_LEN_LONG; i++) {
-    *data0++ = 0;
-  }
-
-  /* Calc sfb-bandwise mdct-energies for left and right channel */
-  CalcBandEnergy( psyData->mdctSpectrum,
-                  hPsyConfLong->sfbOffset,
-                  hPsyConfLong->sfbActive,
-                  psyData->sfbEnergy.sfbLong,
-                  &psyData->sfbEnergySum.sfbLong);
-
-  /*
-    TNS detect
-  */
-  TnsDetect(tnsData,
-            hPsyConfLong->tnsConf,
-            pScratchTns,
-            (const Word16*)hPsyConfLong->sfbOffset,
-            psyData->mdctSpectrum,
-            0,
-            psyData->blockSwitchingControl.windowSequence,
-            psyData->sfbEnergy.sfbLong);
-
-  /*  TnsSync */
-  if (ch == 1) {
-    TnsSync(tnsData,
-            tnsData2,
-            hPsyConfLong->tnsConf,
-            0,
-            psyData->blockSwitchingControl.windowSequence);
-  }
-
-  /*  Tns Encoder */
-  TnsEncode(&psyOutChannel->tnsInfo,
-            tnsData,
-            hPsyConfLong->sfbCnt,
-            hPsyConfLong->tnsConf,
-            hPsyConfLong->lowpassLine,
-            psyData->mdctSpectrum,
-            0,
-            psyData->blockSwitchingControl.windowSequence);
-
-  /* first part of threshold calculation */
-  data0 = psyData->sfbEnergy.sfbLong;
-  data1 = psyData->sfbThreshold.sfbLong;
-  for (i=hPsyConfLong->sfbCnt; i; i--) {
-    tdata = L_mpy_ls(*data0++, hPsyConfLong->ratio);
-    *data1++ = min(tdata, clipEnergy);
-  }
-
-  /* Calc sfb-bandwise mdct-energies for left and right channel again */
-  if (tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive!=0) {
-    Word16 tnsStartBand = hPsyConfLong->tnsConf.tnsStartBand;
-    CalcBandEnergy( psyData->mdctSpectrum,
-                    hPsyConfLong->sfbOffset+tnsStartBand,
-                    hPsyConfLong->sfbActive - tnsStartBand,
-                    psyData->sfbEnergy.sfbLong+tnsStartBand,
-                    &psyData->sfbEnergySum.sfbLong);
-
-	data0 = psyData->sfbEnergy.sfbLong;
-	tdata = psyData->sfbEnergySum.sfbLong;
-	for (i=0; i<tnsStartBand; i++)
-      tdata += *data0++;
-
-	psyData->sfbEnergySum.sfbLong = tdata;
-  }
-
-
-  /* spreading energy */
-  SpreadingMax(hPsyConfLong->sfbCnt,
-               hPsyConfLong->sfbMaskLowFactor,
-               hPsyConfLong->sfbMaskHighFactor,
-               psyData->sfbThreshold.sfbLong);
-
-  /* threshold in quiet */
-  data0 = psyData->sfbThreshold.sfbLong;
-  data1 = hPsyConfLong->sfbThresholdQuiet;
-  for (i=hPsyConfLong->sfbCnt; i; i--)
-  {
-	  *data0 = max(*data0, (*data1 >> normEnergyShift));
-	  data0++; data1++;
-  }
-
-  /* preecho control */
-  if (psyData->blockSwitchingControl.windowSequence == STOP_WINDOW) {
-    data0 = psyData->sfbThresholdnm1;
-	for (i=hPsyConfLong->sfbCnt; i; i--) {
-      *data0++ = MAX_32;
-    }
-    psyData->mdctScalenm1 = 0;
-  }
-
-  PreEchoControl( psyData->sfbThresholdnm1,
-                  hPsyConfLong->sfbCnt,
-                  hPsyConfLong->maxAllowedIncreaseFactor,
-                  hPsyConfLong->minRemainingThresholdFactor,
-                  psyData->sfbThreshold.sfbLong,
-                  psyData->mdctScale,
-                  psyData->mdctScalenm1);
-  psyData->mdctScalenm1 = psyData->mdctScale;
-
-
-  if (psyData->blockSwitchingControl.windowSequence== START_WINDOW) {
-    data0 = psyData->sfbThresholdnm1;
-	for (i=hPsyConfLong->sfbCnt; i; i--) {
-      *data0++ = MAX_32;
-    }
-    psyData->mdctScalenm1 = 0;
-  }
-
-  /* apply tns mult table on cb thresholds */
-  ApplyTnsMultTableToRatios(hPsyConfLong->tnsConf.tnsRatioPatchLowestCb,
-                            hPsyConfLong->tnsConf.tnsStartBand,
-                            tnsData->dataRaw.tnsLong.subBlockInfo,
-                            psyData->sfbThreshold.sfbLong);
-
-
-  /* spreaded energy */
-  data0 = psyData->sfbSpreadedEnergy.sfbLong;
-  data1 = psyData->sfbEnergy.sfbLong;
-  for (i=hPsyConfLong->sfbCnt; i; i--) {
-    //psyData->sfbSpreadedEnergy.sfbLong[i] = psyData->sfbEnergy.sfbLong[i];
-	  *data0++ = *data1++;
-  }
-
-  /* spreading energy */
-  SpreadingMax(hPsyConfLong->sfbCnt,
-               hPsyConfLong->sfbMaskLowFactorSprEn,
-               hPsyConfLong->sfbMaskHighFactorSprEn,
-               psyData->sfbSpreadedEnergy.sfbLong);
-
-  return 0;
-}
-
-/*****************************************************************************
-*
-* function name: advancePsychLongMS
-* description:   update mdct-energies for left add or minus right channel
-*				for long block
-*
-*****************************************************************************/
-static Word16 advancePsychLongMS (PSY_DATA psyData[MAX_CHANNELS],
-                                  const PSY_CONFIGURATION_LONG *hPsyConfLong)
-{
-  CalcBandEnergyMS(psyData[0].mdctSpectrum,
-                   psyData[1].mdctSpectrum,
-                   hPsyConfLong->sfbOffset,
-                   hPsyConfLong->sfbActive,
-                   psyData[0].sfbEnergyMS.sfbLong,
-                   &psyData[0].sfbEnergySumMS.sfbLong,
-                   psyData[1].sfbEnergyMS.sfbLong,
-                   &psyData[1].sfbEnergySumMS.sfbLong);
-
-  return 0;
-}
-
-
-/*****************************************************************************
-*
-* function name: advancePsychShort
-* description:  psychoacoustic for short blocks
-*
-*****************************************************************************/
-
-static Word16 advancePsychShort(PSY_DATA* psyData,
-                                TNS_DATA* tnsData,
-                                const PSY_CONFIGURATION_SHORT *hPsyConfShort,
-                                PSY_OUT_CHANNEL* psyOutChannel,
-                                Word32 *pScratchTns,
-                                const TNS_DATA *tnsData2,
-                                const Word16 ch)
-{
-  Word32 w;
-  Word32 normEnergyShift = (psyData->mdctScale + 1) << 1; /* in reference code, mdct spectrum must be multipied with 2, so +1 */
-  Word32 clipEnergy = hPsyConfShort->clipEnergy >> normEnergyShift;
-  Word32 wOffset = 0;
-  Word32 *data0;
-  const Word32 *data1;
-
-  for(w = 0; w < TRANS_FAC; w++) {
-    Word32 i, tdata;
-
-    /* low pass */
-    data0 = psyData->mdctSpectrum + wOffset + hPsyConfShort->lowpassLine;
-	for(i=hPsyConfShort->lowpassLine; i<FRAME_LEN_SHORT; i++){
-      *data0++ = 0;
-    }
-
-    /* Calc sfb-bandwise mdct-energies for left and right channel */
-    CalcBandEnergy( psyData->mdctSpectrum+wOffset,
-                    hPsyConfShort->sfbOffset,
-                    hPsyConfShort->sfbActive,
-                    psyData->sfbEnergy.sfbShort[w],
-                    &psyData->sfbEnergySum.sfbShort[w]);
-    /*
-       TNS
-    */
-    TnsDetect(tnsData,
-              hPsyConfShort->tnsConf,
-              pScratchTns,
-              (const Word16*)hPsyConfShort->sfbOffset,
-              psyData->mdctSpectrum+wOffset,
-              w,
-              psyData->blockSwitchingControl.windowSequence,
-              psyData->sfbEnergy.sfbShort[w]);
-
-    /*  TnsSync */
-    if (ch == 1) {
-      TnsSync(tnsData,
-              tnsData2,
-              hPsyConfShort->tnsConf,
-              w,
-              psyData->blockSwitchingControl.windowSequence);
-    }
-
-    TnsEncode(&psyOutChannel->tnsInfo,
-              tnsData,
-              hPsyConfShort->sfbCnt,
-              hPsyConfShort->tnsConf,
-              hPsyConfShort->lowpassLine,
-              psyData->mdctSpectrum+wOffset,
-              w,
-              psyData->blockSwitchingControl.windowSequence);
-
-    /* first part of threshold calculation */
-    data0 = psyData->sfbThreshold.sfbShort[w];
-	data1 = psyData->sfbEnergy.sfbShort[w];
-	for (i=hPsyConfShort->sfbCnt; i; i--) {
-      tdata = L_mpy_ls(*data1++, hPsyConfShort->ratio);
-      *data0++ = min(tdata, clipEnergy);
-    }
-
-    /* Calc sfb-bandwise mdct-energies for left and right channel again */
-    if (tnsData->dataRaw.tnsShort.subBlockInfo[w].tnsActive != 0) {
-      Word16 tnsStartBand = hPsyConfShort->tnsConf.tnsStartBand;
-      CalcBandEnergy( psyData->mdctSpectrum+wOffset,
-                      hPsyConfShort->sfbOffset+tnsStartBand,
-                      (hPsyConfShort->sfbActive - tnsStartBand),
-                      psyData->sfbEnergy.sfbShort[w]+tnsStartBand,
-                      &psyData->sfbEnergySum.sfbShort[w]);
-
-      tdata = psyData->sfbEnergySum.sfbShort[w];
-	  data0 = psyData->sfbEnergy.sfbShort[w];
-	  for (i=tnsStartBand; i; i--)
-        tdata += *data0++;
-
-	  psyData->sfbEnergySum.sfbShort[w] = tdata;
-    }
-
-    /* spreading */
-    SpreadingMax(hPsyConfShort->sfbCnt,
-                 hPsyConfShort->sfbMaskLowFactor,
-                 hPsyConfShort->sfbMaskHighFactor,
-                 psyData->sfbThreshold.sfbShort[w]);
-
-
-    /* threshold in quiet */
-    data0 = psyData->sfbThreshold.sfbShort[w];
-	data1 = hPsyConfShort->sfbThresholdQuiet;
-	for (i=hPsyConfShort->sfbCnt; i; i--)
-    {
-		*data0 = max(*data0, (*data1 >> normEnergyShift));
-
-		data0++; data1++;
-	}
-
-
-    /* preecho */
-    PreEchoControl( psyData->sfbThresholdnm1,
-                    hPsyConfShort->sfbCnt,
-                    hPsyConfShort->maxAllowedIncreaseFactor,
-                    hPsyConfShort->minRemainingThresholdFactor,
-                    psyData->sfbThreshold.sfbShort[w],
-                    psyData->mdctScale,
-                    w==0 ? psyData->mdctScalenm1 : psyData->mdctScale);
-
-    /* apply tns mult table on cb thresholds */
-    ApplyTnsMultTableToRatios( hPsyConfShort->tnsConf.tnsRatioPatchLowestCb,
-                               hPsyConfShort->tnsConf.tnsStartBand,
-                               tnsData->dataRaw.tnsShort.subBlockInfo[w],
-                               psyData->sfbThreshold.sfbShort[w]);
-
-    /* spreaded energy */
-    data0 = psyData->sfbSpreadedEnergy.sfbShort[w];
-	data1 = psyData->sfbEnergy.sfbShort[w];
-	for (i=hPsyConfShort->sfbCnt; i; i--) {
-	  *data0++ = *data1++;
-    }
-    SpreadingMax(hPsyConfShort->sfbCnt,
-                 hPsyConfShort->sfbMaskLowFactorSprEn,
-                 hPsyConfShort->sfbMaskHighFactorSprEn,
-                 psyData->sfbSpreadedEnergy.sfbShort[w]);
-
-    wOffset += FRAME_LEN_SHORT;
-  } /* for TRANS_FAC */
-
-  psyData->mdctScalenm1 = psyData->mdctScale;
-
-  return 0;
-}
-
-/*****************************************************************************
-*
-* function name: advancePsychShortMS
-* description:   update mdct-energies for left add or minus right channel
-*				for short block
-*
-*****************************************************************************/
-static Word16 advancePsychShortMS (PSY_DATA psyData[MAX_CHANNELS],
-                                   const PSY_CONFIGURATION_SHORT *hPsyConfShort)
-{
-  Word32 w, wOffset;
-  wOffset = 0;
-  for(w=0; w<TRANS_FAC; w++) {
-    CalcBandEnergyMS(psyData[0].mdctSpectrum+wOffset,
-                     psyData[1].mdctSpectrum+wOffset,
-                     hPsyConfShort->sfbOffset,
-                     hPsyConfShort->sfbActive,
-                     psyData[0].sfbEnergyMS.sfbShort[w],
-                     &psyData[0].sfbEnergySumMS.sfbShort[w],
-                     psyData[1].sfbEnergyMS.sfbShort[w],
-                     &psyData[1].sfbEnergySumMS.sfbShort[w]);
-    wOffset += FRAME_LEN_SHORT;
-  }
-
-  return 0;
-}
diff --git a/media/libstagefright/codecs/aacenc/src/qc_main.c b/media/libstagefright/codecs/aacenc/src/qc_main.c
deleted file mode 100644
index e5d78aa..0000000
--- a/media/libstagefright/codecs/aacenc/src/qc_main.c
+++ /dev/null
@@ -1,578 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		qc_main.c
-
-	Content:	Quantizing & coding functions
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "qc_main.h"
-#include "quantize.h"
-#include "interface.h"
-#include "adj_thr.h"
-#include "sf_estim.h"
-#include "stat_bits.h"
-#include "bit_cnt.h"
-#include "dyn_bits.h"
-#include "channel_map.h"
-#include "memalign.h"
-
-#define UNUSED(x) (void)(x)
-
-typedef enum{
-  FRAME_LEN_BYTES_MODULO =  1,
-  FRAME_LEN_BYTES_INT    =  2
-}FRAME_LEN_RESULT_MODE;
-
-static const Word16 maxFillElemBits = 7 + 270*8;
-
-/* forward declarations */
-
-static Word16 calcMaxValueInSfb(Word16 sfbCnt,
-                                Word16 maxSfbPerGroup,
-                                Word16 sfbPerGroup,
-                                Word16 sfbOffset[MAX_GROUPED_SFB],
-                                Word16 quantSpectrum[FRAME_LEN_LONG],
-                                UWord16 maxValue[MAX_GROUPED_SFB]);
-
-
-/*****************************************************************************
-*
-* function name: calcFrameLen
-* description: estimate the frame length according the bitrates
-*
-*****************************************************************************/
-static Word16 calcFrameLen(Word32 bitRate,
-                           Word32 sampleRate,
-                           FRAME_LEN_RESULT_MODE mode)
-{
-
-  Word32 result;
-  Word32 quot;
-
-  result = (FRAME_LEN_LONG >> 3) * bitRate;
-  quot = result / sampleRate;
-
-
-  if (mode == FRAME_LEN_BYTES_MODULO) {
-    result -= quot * sampleRate;
-  }
-  else { /* FRAME_LEN_BYTES_INT */
-    result = quot;
-  }
-
-  return result;
-}
-
-/*****************************************************************************
-*
-*  function name:framePadding
-*  description: Calculates if padding is needed for actual frame
-*  returns: paddingOn or not
-*
-*****************************************************************************/
-static Word16 framePadding(Word32 bitRate,
-                           Word32 sampleRate,
-                           Word32 *paddingRest)
-{
-  Word16 paddingOn;
-  Word16 difference;
-
-  paddingOn = 0;
-
-  difference = calcFrameLen( bitRate,
-                             sampleRate,
-                             FRAME_LEN_BYTES_MODULO );
-  *paddingRest = *paddingRest - difference;
-
-
-  if (*paddingRest <= 0 ) {
-    paddingOn = 1;
-    *paddingRest = *paddingRest + sampleRate;
-  }
-
-  return paddingOn;
-}
-
-
-/*********************************************************************************
-*
-* function name: QCOutNew
-* description: init qcout parameter
-* returns:     0 if success
-*
-**********************************************************************************/
-
-Word16 QCOutNew(QC_OUT *hQC, Word16 nChannels, VO_MEM_OPERATOR *pMemOP)
-{
-  Word32 i;
-  Word16 *quantSpec;
-  Word16 *scf;
-  UWord16 *maxValueInSfb;
-
-  quantSpec = (Word16 *)mem_malloc(pMemOP, nChannels * FRAME_LEN_LONG * sizeof(Word16), 32, VO_INDEX_ENC_AAC);
-  if(NULL == quantSpec)
-	  return 1;
-  scf = (Word16 *)mem_malloc(pMemOP, nChannels * MAX_GROUPED_SFB * sizeof(Word16), 32, VO_INDEX_ENC_AAC);
-  if(NULL == scf)
-  {
-	  return 1;
-  }
-  maxValueInSfb = (UWord16 *)mem_malloc(pMemOP, nChannels * MAX_GROUPED_SFB * sizeof(UWord16), 32, VO_INDEX_ENC_AAC);
-  if(NULL == maxValueInSfb)
-  {
-	  return 1;
-  }
-
-  for (i=0; i<nChannels; i++) {
-    hQC->qcChannel[i].quantSpec = quantSpec + i*FRAME_LEN_LONG;
-
-    hQC->qcChannel[i].maxValueInSfb = maxValueInSfb + i*MAX_GROUPED_SFB;
-
-    hQC->qcChannel[i].scf = scf + i*MAX_GROUPED_SFB;
-  }
-
-  return 0;
-}
-
-
-/*********************************************************************************
-*
-* function name: QCOutDelete
-* description: unint qcout parameter
-* returns:      0 if success
-*
-**********************************************************************************/
-void QCOutDelete(QC_OUT* hQC, VO_MEM_OPERATOR *pMemOP)
-{
-   Word32 i;
-   if(hQC)
-   {
-      if(hQC->qcChannel[0].quantSpec)
-		 mem_free(pMemOP, hQC->qcChannel[0].quantSpec, VO_INDEX_ENC_AAC);
-
-      if(hQC->qcChannel[0].maxValueInSfb)
-		  mem_free(pMemOP, hQC->qcChannel[0].maxValueInSfb, VO_INDEX_ENC_AAC);
-
-	  if(hQC->qcChannel[0].scf)
-		  mem_free(pMemOP, hQC->qcChannel[0].scf, VO_INDEX_ENC_AAC);
-
-	  for (i=0; i<MAX_CHANNELS; i++) {
-		  hQC->qcChannel[i].quantSpec = NULL;
-
-		  hQC->qcChannel[i].maxValueInSfb = NULL;
-
-		  hQC->qcChannel[i].scf = NULL;
-	  }
-   }
-}
-
-/*********************************************************************************
-*
-* function name: QCNew
-* description: set QC to zero
-* returns:     0 if success
-*
-**********************************************************************************/
-Word16 QCNew(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP)
-{
-  pMemOP->Set(VO_INDEX_ENC_AAC, hQC,0,sizeof(QC_STATE));
-
-  return (0);
-}
-
-/*********************************************************************************
-*
-* function name: QCDelete
-* description: unint qcout parameter
-*
-**********************************************************************************/
-void QCDelete(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP)
-{
-  UNUSED(hQC);
-  UNUSED(pMemOP);
-}
-
-/*********************************************************************************
-*
-* function name: QCInit
-* description: init QD parameter
-* returns:     0 if success
-*
-**********************************************************************************/
-Word16 QCInit(QC_STATE *hQC,
-              struct QC_INIT *init)
-{
-  hQC->nChannels       = init->elInfo->nChannelsInEl;
-  hQC->maxBitsTot      = init->maxBits;
-  hQC->bitResTot       = sub(init->bitRes, init->averageBits);
-  hQC->averageBitsTot  = init->averageBits;
-  hQC->maxBitFac       = init->maxBitFac;
-
-  hQC->padding.paddingRest = init->padding.paddingRest;
-
-  hQC->globStatBits    = 3;                          /* for ID_END */
-
-  /* channel elements init */
-  InitElementBits(&hQC->elementBits,
-                  *init->elInfo,
-                  init->bitrate,
-                  init->averageBits,
-                  hQC->globStatBits);
-
-  /* threshold parameter init */
-  AdjThrInit(&hQC->adjThr,
-             init->meanPe,
-             hQC->elementBits.chBitrate);
-
-  return 0;
-}
-
-
-/*********************************************************************************
-*
-* function name: QCMain
-* description:  quantization and coding the spectrum
-* returns:      0 if success
-*
-**********************************************************************************/
-Word16 QCMain(QC_STATE* hQC,
-              ELEMENT_BITS* elBits,
-              ATS_ELEMENT* adjThrStateElement,
-              PSY_OUT_CHANNEL  psyOutChannel[MAX_CHANNELS],  /* may be modified in-place */
-              PSY_OUT_ELEMENT* psyOutElement,
-              QC_OUT_CHANNEL  qcOutChannel[MAX_CHANNELS],    /* out                      */
-              QC_OUT_ELEMENT* qcOutElement,
-              Word16 nChannels,
-			  Word16 ancillaryDataBytes)
-{
-  Word16 maxChDynBits[MAX_CHANNELS];
-  Word16 chBitDistribution[MAX_CHANNELS];
-  Word32 ch;
-
-  if (elBits->bitResLevel < 0) {
-    return -1;
-  }
-
-  if (elBits->bitResLevel > elBits->maxBitResBits) {
-    return -1;
-  }
-
-  qcOutElement->staticBitsUsed = countStaticBitdemand(psyOutChannel,
-                                                      psyOutElement,
-                                                      nChannels,
-													  qcOutElement->adtsUsed);
-
-
-  if (ancillaryDataBytes) {
-    qcOutElement->ancBitsUsed = 7 + (ancillaryDataBytes << 3);
-
-    if (ancillaryDataBytes >= 15)
-      qcOutElement->ancBitsUsed = qcOutElement->ancBitsUsed + 8;
-  }
-  else {
-    qcOutElement->ancBitsUsed = 0;
-  }
-
-  CalcFormFactor(hQC->logSfbFormFactor, hQC->sfbNRelevantLines, hQC->logSfbEnergy, psyOutChannel, nChannels);
-
-  /*adjust thresholds for the desired bitrate */
-  AdjustThresholds(&hQC->adjThr,
-                   adjThrStateElement,
-                   psyOutChannel,
-                   psyOutElement,
-                   chBitDistribution,
-                   hQC->logSfbEnergy,
-                   hQC->sfbNRelevantLines,
-                   qcOutElement,
-				   elBits,
-				   nChannels,
-				   hQC->maxBitFac);
-
-  /*estimate scale factors */
-  EstimateScaleFactors(psyOutChannel,
-                       qcOutChannel,
-                       hQC->logSfbEnergy,
-                       hQC->logSfbFormFactor,
-                       hQC->sfbNRelevantLines,
-                       nChannels);
-
-  /* condition to prevent empty bitreservoir */
-  for (ch = 0; ch < nChannels; ch++) {
-    Word32 maxDynBits;
-    maxDynBits = elBits->averageBits + elBits->bitResLevel - 7; /* -7 bec. of align bits */
-    maxDynBits = maxDynBits - qcOutElement->staticBitsUsed + qcOutElement->ancBitsUsed;
-    maxChDynBits[ch] = extract_l(chBitDistribution[ch] * maxDynBits / 1000);
-  }
-
-  qcOutElement->dynBitsUsed = 0;
-  for (ch = 0; ch < nChannels; ch++) {
-    Word32 chDynBits;
-    Flag   constraintsFulfilled;
-    Word32 iter;
-    iter = 0;
-    do {
-      constraintsFulfilled = 1;
-
-      QuantizeSpectrum(psyOutChannel[ch].sfbCnt,
-                       psyOutChannel[ch].maxSfbPerGroup,
-                       psyOutChannel[ch].sfbPerGroup,
-                       psyOutChannel[ch].sfbOffsets,
-                       psyOutChannel[ch].mdctSpectrum,
-                       qcOutChannel[ch].globalGain,
-                       qcOutChannel[ch].scf,
-                       qcOutChannel[ch].quantSpec);
-
-      if (calcMaxValueInSfb(psyOutChannel[ch].sfbCnt,
-                            psyOutChannel[ch].maxSfbPerGroup,
-                            psyOutChannel[ch].sfbPerGroup,
-                            psyOutChannel[ch].sfbOffsets,
-                            qcOutChannel[ch].quantSpec,
-                            qcOutChannel[ch].maxValueInSfb) > MAX_QUANT) {
-        constraintsFulfilled = 0;
-      }
-
-      chDynBits = dynBitCount(qcOutChannel[ch].quantSpec,
-                              qcOutChannel[ch].maxValueInSfb,
-                              qcOutChannel[ch].scf,
-                              psyOutChannel[ch].windowSequence,
-                              psyOutChannel[ch].sfbCnt,
-                              psyOutChannel[ch].maxSfbPerGroup,
-                              psyOutChannel[ch].sfbPerGroup,
-                              psyOutChannel[ch].sfbOffsets,
-                              &qcOutChannel[ch].sectionData);
-
-      if (chDynBits >= maxChDynBits[ch]) {
-        constraintsFulfilled = 0;
-      }
-
-      if (!constraintsFulfilled) {
-        qcOutChannel[ch].globalGain = qcOutChannel[ch].globalGain + 1;
-      }
-
-      iter = iter + 1;
-
-    } while(!constraintsFulfilled);
-
-    qcOutElement->dynBitsUsed = qcOutElement->dynBitsUsed + chDynBits;
-
-    qcOutChannel[ch].mdctScale    = psyOutChannel[ch].mdctScale;
-    qcOutChannel[ch].groupingMask = psyOutChannel[ch].groupingMask;
-    qcOutChannel[ch].windowShape  = psyOutChannel[ch].windowShape;
-  }
-
-  /* save dynBitsUsed for correction of bits2pe relation */
-  AdjThrUpdate(adjThrStateElement, qcOutElement->dynBitsUsed);
-
-  {
-    Word16 bitResSpace = elBits->maxBitResBits - elBits->bitResLevel;
-    Word16 deltaBitRes = elBits->averageBits -
-                        (qcOutElement->staticBitsUsed +
-                         qcOutElement->dynBitsUsed + qcOutElement->ancBitsUsed);
-
-    qcOutElement->fillBits = max(0, (deltaBitRes - bitResSpace));
-  }
-
-  return 0; /* OK */
-}
-
-
-/*********************************************************************************
-*
-* function name: calcMaxValueInSfb
-* description:  search the max Spectrum in one sfb
-*
-**********************************************************************************/
-static Word16 calcMaxValueInSfb(Word16 sfbCnt,
-                                Word16 maxSfbPerGroup,
-                                Word16 sfbPerGroup,
-                                Word16 sfbOffset[MAX_GROUPED_SFB],
-                                Word16 quantSpectrum[FRAME_LEN_LONG],
-                                UWord16 maxValue[MAX_GROUPED_SFB])
-{
-  Word16 sfbOffs, sfb;
-  Word16 maxValueAll;
-
-  maxValueAll = 0;
-
-  for(sfbOffs=0;sfbOffs<sfbCnt;sfbOffs+=sfbPerGroup) {
-    for (sfb = 0; sfb < maxSfbPerGroup; sfb++) {
-      Word16 line;
-      Word16 maxThisSfb;
-      maxThisSfb = 0;
-
-      for (line = sfbOffset[sfbOffs+sfb]; line < sfbOffset[sfbOffs+sfb+1]; line++) {
-        Word16 absVal;
-        absVal = abs_s(quantSpectrum[line]);
-        maxThisSfb = max(maxThisSfb, absVal);
-      }
-
-      maxValue[sfbOffs+sfb] = maxThisSfb;
-      maxValueAll = max(maxValueAll, maxThisSfb);
-    }
-  }
-  return maxValueAll;
-}
-
-
-/*********************************************************************************
-*
-* function name: updateBitres
-* description: update bitreservoir
-*
-**********************************************************************************/
-void updateBitres(QC_STATE* qcKernel,
-                  QC_OUT*   qcOut)
-
-{
-  ELEMENT_BITS *elBits;
-
-  qcKernel->bitResTot = 0;
-
-  elBits = &qcKernel->elementBits;
-
-
-  if (elBits->averageBits > 0) {
-    /* constant bitrate */
-    Word16 bitsUsed;
-    bitsUsed = (qcOut->qcElement.staticBitsUsed + qcOut->qcElement.dynBitsUsed) +
-                   (qcOut->qcElement.ancBitsUsed + qcOut->qcElement.fillBits);
-    elBits->bitResLevel = elBits->bitResLevel + (elBits->averageBits - bitsUsed);
-    qcKernel->bitResTot = qcKernel->bitResTot + elBits->bitResLevel;
-  }
-  else {
-    /* variable bitrate */
-    elBits->bitResLevel = elBits->maxBits;
-    qcKernel->bitResTot = qcKernel->maxBitsTot;
-  }
-}
-
-/*********************************************************************************
-*
-* function name: FinalizeBitConsumption
-* description: count bits used
-*
-**********************************************************************************/
-Word16 FinalizeBitConsumption(QC_STATE *qcKernel,
-                              QC_OUT* qcOut)
-{
-  Word32 nFullFillElem;
-  Word32 totFillBits;
-  Word16 diffBits;
-  Word16 bitsUsed;
-
-  totFillBits = 0;
-
-  qcOut->totStaticBitsUsed = qcKernel->globStatBits;
-  qcOut->totStaticBitsUsed += qcOut->qcElement.staticBitsUsed;
-  qcOut->totDynBitsUsed    = qcOut->qcElement.dynBitsUsed;
-  qcOut->totAncBitsUsed    = qcOut->qcElement.ancBitsUsed;
-  qcOut->totFillBits       = qcOut->qcElement.fillBits;
-
-  if (qcOut->qcElement.fillBits) {
-    totFillBits += qcOut->qcElement.fillBits;
-  }
-
-  nFullFillElem = (max((qcOut->totFillBits - 1), 0) / maxFillElemBits) * maxFillElemBits;
-
-  qcOut->totFillBits = qcOut->totFillBits - nFullFillElem;
-
-  /* check fill elements */
-
-  if (qcOut->totFillBits > 0) {
-    /* minimum Fillelement contains 7 (TAG + byte cnt) bits */
-    qcOut->totFillBits = max(7, qcOut->totFillBits);
-    /* fill element size equals n*8 + 7 */
-    qcOut->totFillBits = qcOut->totFillBits + ((8 - ((qcOut->totFillBits - 7) & 0x0007)) & 0x0007);
-  }
-
-  qcOut->totFillBits = qcOut->totFillBits + nFullFillElem;
-
-  /* now distribute extra fillbits and alignbits over channel elements */
-  qcOut->alignBits = 7 - ((qcOut->totDynBitsUsed + qcOut->totStaticBitsUsed +
-                           qcOut->totAncBitsUsed + qcOut->totFillBits - 1) & 0x0007);
-
-
-  if ( (qcOut->alignBits + qcOut->totFillBits - totFillBits == 8) &&
-       (qcOut->totFillBits > 8))
-    qcOut->totFillBits = qcOut->totFillBits - 8;
-
-
-  diffBits = qcOut->alignBits + qcOut->totFillBits - totFillBits;
-
-  if(diffBits>=0) {
-    qcOut->qcElement.fillBits += diffBits;
-  }
-
-  bitsUsed = qcOut->totDynBitsUsed + qcOut->totStaticBitsUsed + qcOut->totAncBitsUsed;
-  bitsUsed = bitsUsed + qcOut->totFillBits + qcOut->alignBits;
-
-  if (bitsUsed > qcKernel->maxBitsTot) {
-    return -1;
-  }
-  return bitsUsed;
-}
-
-
-/*********************************************************************************
-*
-* function name: AdjustBitrate
-* description:  adjusts framelength via padding on a frame to frame basis,
-*               to achieve a bitrate that demands a non byte aligned
-*               framelength
-* return:       errorcode
-*
-**********************************************************************************/
-Word16 AdjustBitrate(QC_STATE        *hQC,
-                     Word32           bitRate,    /* total bitrate */
-                     Word32           sampleRate) /* output sampling rate */
-{
-  Word16 paddingOn;
-  Word16 frameLen;
-  Word16 codeBits;
-  Word16 codeBitsLast;
-
-  /* Do we need a extra padding byte? */
-  paddingOn = framePadding(bitRate,
-                           sampleRate,
-                           &hQC->padding.paddingRest);
-
-  /* frame length */
-  frameLen = paddingOn + calcFrameLen(bitRate,
-                                      sampleRate,
-                                      FRAME_LEN_BYTES_INT);
-
-  frameLen = frameLen << 3;
-  codeBitsLast = hQC->averageBitsTot - hQC->globStatBits;
-  codeBits     = frameLen - hQC->globStatBits;
-
-  /* calculate bits for every channel element */
-  if (codeBits != codeBitsLast) {
-    Word16 totalBits = 0;
-
-    hQC->elementBits.averageBits = (hQC->elementBits.relativeBits * codeBits) >> 16; /* relativeBits was scaled down by 2 */
-    totalBits += hQC->elementBits.averageBits;
-
-    hQC->elementBits.averageBits = hQC->elementBits.averageBits + (codeBits - totalBits);
-  }
-
-  hQC->averageBitsTot = frameLen;
-
-  return 0;
-}
diff --git a/media/libstagefright/codecs/aacenc/src/quantize.c b/media/libstagefright/codecs/aacenc/src/quantize.c
deleted file mode 100644
index 0d0f550..0000000
--- a/media/libstagefright/codecs/aacenc/src/quantize.c
+++ /dev/null
@@ -1,445 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		quantize.c
-
-	Content:	quantization functions
-
-*******************************************************************************/
-
-#include "typedef.h"
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "quantize.h"
-#include "aac_rom.h"
-
-#define MANT_DIGITS 9
-#define MANT_SIZE   (1<<MANT_DIGITS)
-
-static const Word32 XROUND = 0x33e425af; /* final rounding constant (-0.0946f+ 0.5f) */
-
-
-/*****************************************************************************
-*
-* function name:pow34
-* description: calculate $x^{\frac{3}{4}}, for 0.5 < x < 1.0$.
-*
-*****************************************************************************/
-__inline Word32 pow34(Word32 x)
-{
-  /* index table using MANT_DIGITS bits, but mask out the sign bit and the MSB
-     which is always one */
-  return mTab_3_4[(x >> (INT_BITS-2-MANT_DIGITS)) & (MANT_SIZE-1)];
-}
-
-
-/*****************************************************************************
-*
-* function name:quantizeSingleLine
-* description: quantizes spectrum
-*              quaSpectrum = mdctSpectrum^3/4*2^(-(3/16)*gain)
-*
-*****************************************************************************/
-static Word16 quantizeSingleLine(const Word16 gain, const Word32 absSpectrum)
-{
-  Word32 e, minusFinalExp, finalShift;
-  Word32 x;
-  Word16 qua = 0;
-
-
-  if (absSpectrum) {
-    e = norm_l(absSpectrum);
-    x = pow34(absSpectrum << e);
-
-    /* calculate the final fractional exponent times 16 (was 3*(4*e + gain) + (INT_BITS-1)*16) */
-    minusFinalExp = (e << 2) + gain;
-    minusFinalExp = (minusFinalExp << 1) + minusFinalExp;
-    minusFinalExp = minusFinalExp + ((INT_BITS-1) << 4);
-
-    /* separate the exponent into a shift, and a multiply */
-    finalShift = minusFinalExp >> 4;
-
-    if (finalShift < INT_BITS) {
-      x = L_mpy_wx(x, pow2tominusNover16[minusFinalExp & 15]);
-
-      x += XROUND >> (INT_BITS - finalShift);
-
-      /* shift and quantize */
-	  finalShift--;
-
-	  if(finalShift >= 0)
-		  x >>= finalShift;
-	  else
-		  x <<= (-finalShift);
-
-	  qua = saturate(x);
-    }
-  }
-
-  return qua;
-}
-
-/*****************************************************************************
-*
-* function name:quantizeLines
-* description: quantizes spectrum lines
-*              quaSpectrum = mdctSpectrum^3/4*2^(-(3/16)*gain)
-*  input: global gain, number of lines to process, spectral data
-*  output: quantized spectrum
-*
-*****************************************************************************/
-static void quantizeLines(const Word16 gain,
-                          const Word16 noOfLines,
-                          const Word32 *mdctSpectrum,
-                          Word16 *quaSpectrum)
-{
-  Word32 line;
-  Word32 m = gain&3;
-  Word32 g = (gain >> 2) + 4;
-  Word32 mdctSpeL;
-  const Word16 *pquat;
-    /* gain&3 */
-
-  pquat = quantBorders[m];
-
-  g += 16;
-
-  if(g >= 0)
-  {
-	for (line=0; line<noOfLines; line++) {
-	  Word32 qua;
-	  qua = 0;
-
-	  mdctSpeL = mdctSpectrum[line];
-
-	  if (mdctSpeL) {
-		Word32 sa;
-		Word32 saShft;
-
-        sa = L_abs(mdctSpeL);
-        //saShft = L_shr(sa, 16 + g);
-	    saShft = sa >> g;
-
-        if (saShft > pquat[0]) {
-
-          if (saShft < pquat[1]) {
-
-            qua = mdctSpeL>0 ? 1 : -1;
-		  }
-          else {
-
-            if (saShft < pquat[2]) {
-
-              qua = mdctSpeL>0 ? 2 : -2;
-			}
-            else {
-
-              if (saShft < pquat[3]) {
-
-                qua = mdctSpeL>0 ? 3 : -3;
-			  }
-              else {
-                qua = quantizeSingleLine(gain, sa);
-                /* adjust the sign. Since 0 < qua < 1, this cannot overflow. */
-
-                if (mdctSpeL < 0)
-                  qua = -qua;
-			  }
-			}
-		  }
-		}
-	  }
-      quaSpectrum[line] = qua ;
-	}
-  }
-  else
-  {
-	for (line=0; line<noOfLines; line++) {
-	  Word32 qua;
-	  qua = 0;
-
-	  mdctSpeL = mdctSpectrum[line];
-
-	  if (mdctSpeL) {
-		Word32 sa;
-		Word32 saShft;
-
-        sa = L_abs(mdctSpeL);
-        saShft = sa << g;
-
-        if (saShft > pquat[0]) {
-
-          if (saShft < pquat[1]) {
-
-            qua = mdctSpeL>0 ? 1 : -1;
-		  }
-          else {
-
-            if (saShft < pquat[2]) {
-
-              qua = mdctSpeL>0 ? 2 : -2;
-			}
-            else {
-
-              if (saShft < pquat[3]) {
-
-                qua = mdctSpeL>0 ? 3 : -3;
-			  }
-              else {
-                qua = quantizeSingleLine(gain, sa);
-                /* adjust the sign. Since 0 < qua < 1, this cannot overflow. */
-
-                if (mdctSpeL < 0)
-                  qua = -qua;
-			  }
-			}
-		  }
-		}
-	  }
-      quaSpectrum[line] = qua ;
-	}
-  }
-
-}
-
-
-/*****************************************************************************
-*
-* function name:iquantizeLines
-* description: iquantizes spectrum lines without sign
-*              mdctSpectrum = iquaSpectrum^4/3 *2^(0.25*gain)
-* input: global gain, number of lines to process,quantized spectrum
-* output: spectral data
-*
-*****************************************************************************/
-static void iquantizeLines(const Word16 gain,
-                           const Word16 noOfLines,
-                           const Word16 *quantSpectrum,
-                           Word32 *mdctSpectrum)
-{
-  Word32   iquantizermod;
-  Word32   iquantizershift;
-  Word32   line;
-
-  iquantizermod = gain & 3;
-  iquantizershift = gain >> 2;
-
-  for (line=0; line<noOfLines; line++) {
-
-    if( quantSpectrum[line] != 0 ) {
-      Word32 accu;
-      Word32 ex;
-	  Word32 tabIndex;
-      Word32 specExp;
-      Word32 s,t;
-
-      accu = quantSpectrum[line];
-
-      ex = norm_l(accu);
-      accu = accu << ex;
-      specExp = INT_BITS-1 - ex;
-
-      tabIndex = (accu >> (INT_BITS-2-MANT_DIGITS)) & (~MANT_SIZE);
-
-      /* calculate "mantissa" ^4/3 */
-      s = mTab_4_3[tabIndex];
-
-      /* get approperiate exponent multiplier for specExp^3/4 combined with scfMod */
-      t = specExpMantTableComb_enc[iquantizermod][specExp];
-
-      /* multiply "mantissa" ^4/3 with exponent multiplier */
-      accu = MULHIGH(s, t);
-
-      /* get approperiate exponent shifter */
-      specExp = specExpTableComb_enc[iquantizermod][specExp];
-
-      specExp += iquantizershift + 1;
-	  if(specExp >= 0)
-		  mdctSpectrum[line] = accu << specExp;
-	  else
-		  mdctSpectrum[line] = accu >> (-specExp);
-    }
-    else {
-      mdctSpectrum[line] = 0;
-    }
-  }
-}
-
-/*****************************************************************************
-*
-* function name: QuantizeSpectrum
-* description: quantizes the entire spectrum
-* returns:
-* input: number of scalefactor bands to be quantized, ...
-* output: quantized spectrum
-*
-*****************************************************************************/
-void QuantizeSpectrum(Word16 sfbCnt,
-                      Word16 maxSfbPerGroup,
-                      Word16 sfbPerGroup,
-                      Word16 *sfbOffset,
-                      Word32 *mdctSpectrum,
-                      Word16 globalGain,
-                      Word16 *scalefactors,
-                      Word16 *quantizedSpectrum)
-{
-  Word32 sfbOffs, sfb;
-
-  for(sfbOffs=0;sfbOffs<sfbCnt;sfbOffs+=sfbPerGroup) {
-    Word32 sfbNext ;
-    for (sfb = 0; sfb < maxSfbPerGroup; sfb = sfbNext) {
-      Word16 scalefactor = scalefactors[sfbOffs+sfb];
-      /* coalesce sfbs with the same scalefactor */
-      for (sfbNext = sfb+1;
-           sfbNext < maxSfbPerGroup && scalefactor == scalefactors[sfbOffs+sfbNext];
-           sfbNext++) ;
-
-      quantizeLines(globalGain - scalefactor,
-                    sfbOffset[sfbOffs+sfbNext] - sfbOffset[sfbOffs+sfb],
-                    mdctSpectrum + sfbOffset[sfbOffs+sfb],
-                    quantizedSpectrum + sfbOffset[sfbOffs+sfb]);
-    }
-  }
-}
-
-
-/*****************************************************************************
-*
-* function name:calcSfbDist
-* description: quantizes and requantizes lines to calculate distortion
-* input:  number of lines to be quantized, ...
-* output: distortion
-*
-*****************************************************************************/
-Word32 calcSfbDist(const Word32 *spec,
-                   Word16  sfbWidth,
-                   Word16  gain)
-{
-  Word32 line;
-  Word32 dist;
-  Word32 m = gain&3;
-  Word32 g = (gain >> 2) + 4;
-  Word32 g2 = (g << 1) + 1;
-  const Word16 *pquat, *repquat;
-    /* gain&3 */
-
-  pquat = quantBorders[m];
-  repquat = quantRecon[m];
-
-  dist = 0;
-  g += 16;
-  if(g2 < 0 && g >= 0)
-  {
-	  g2 = -g2;
-	  for(line=0; line<sfbWidth; line++) {
-		  if (spec[line]) {
-			  Word32 diff;
-			  Word32 distSingle;
-			  Word32 sa;
-			  Word32 saShft;
-			  sa = L_abs(spec[line]);
-			  //saShft = round16(L_shr(sa, g));
-			  //saShft = L_shr(sa, 16+g);
-			  saShft = sa >> g;
-
-			  if (saShft < pquat[0]) {
-				  distSingle = (saShft * saShft) >> g2;
-			  }
-			  else {
-
-				  if (saShft < pquat[1]) {
-					  diff = saShft - repquat[0];
-					  distSingle = (diff * diff) >> g2;
-				  }
-				  else {
-
-					  if (saShft < pquat[2]) {
-						  diff = saShft - repquat[1];
-						  distSingle = (diff * diff) >> g2;
-					  }
-					  else {
-
-						  if (saShft < pquat[3]) {
-							  diff = saShft - repquat[2];
-							  distSingle = (diff * diff) >> g2;
-						  }
-						  else {
-							  Word16 qua = quantizeSingleLine(gain, sa);
-							  Word32 iqval, diff32;
-							  /* now that we have quantized x, re-quantize it. */
-							  iquantizeLines(gain, 1, &qua, &iqval);
-							  diff32 = sa - iqval;
-							  distSingle = fixmul(diff32, diff32);
-						  }
-					  }
-				  }
-			  }
-
-			  dist = L_add(dist, distSingle);
-		  }
-	  }
-  }
-  else
-  {
-	  for(line=0; line<sfbWidth; line++) {
-		  if (spec[line]) {
-			  Word32 diff;
-			  Word32 distSingle;
-			  Word32 sa;
-			  Word32 saShft;
-			  sa = L_abs(spec[line]);
-			  //saShft = round16(L_shr(sa, g));
-			  saShft = L_shr(sa, g);
-
-			  if (saShft < pquat[0]) {
-				  distSingle = L_shl((saShft * saShft), g2);
-			  }
-			  else {
-
-				  if (saShft < pquat[1]) {
-					  diff = saShft - repquat[0];
-					  distSingle = L_shl((diff * diff), g2);
-				  }
-				  else {
-
-					  if (saShft < pquat[2]) {
-						  diff = saShft - repquat[1];
-						  distSingle = L_shl((diff * diff), g2);
-					  }
-					  else {
-
-						  if (saShft < pquat[3]) {
-							  diff = saShft - repquat[2];
-							  distSingle = L_shl((diff * diff), g2);
-						  }
-						  else {
-							  Word16 qua = quantizeSingleLine(gain, sa);
-							  Word32 iqval, diff32;
-							  /* now that we have quantized x, re-quantize it. */
-							  iquantizeLines(gain, 1, &qua, &iqval);
-							  diff32 = sa - iqval;
-							  distSingle = fixmul(diff32, diff32);
-						  }
-					  }
-				  }
-			  }
-			  dist = L_add(dist, distSingle);
-		  }
-	  }
-  }
-
-  return dist;
-}
diff --git a/media/libstagefright/codecs/aacenc/src/sf_estim.c b/media/libstagefright/codecs/aacenc/src/sf_estim.c
deleted file mode 100644
index 78947e1..0000000
--- a/media/libstagefright/codecs/aacenc/src/sf_estim.c
+++ /dev/null
@@ -1,882 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		sf_estim.c
-
-	Content:	Scale factor estimation functions
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "sf_estim.h"
-#include "quantize.h"
-#include "bit_cnt.h"
-#include "aac_rom.h"
-
-static const Word16 MAX_SCF_DELTA = 60;
-
-/*!
-constants reference in comments
-
- C0 = 6.75f;
- C1 = -69.33295f;   -16/3*log(MAX_QUANT+0.5-logCon)/log(2)
- C2 = 4.0f;
- C3 = 2.66666666f;
-
-  PE_C1 = 3.0f;        log(8.0)/log(2)
-  PE_C2 = 1.3219281f;  log(2.5)/log(2)
-  PE_C3 = 0.5593573f;  1-C2/C1
-
-*/
-
-#define FF_SQRT_BITS                    7
-#define FF_SQRT_TABLE_SIZE              (1<<FF_SQRT_BITS - 1<<(FF_SQRT_BITS-2))
-#define COEF08_31		0x66666666		/* 0.8*(1 << 31) */
-#define PE_C1_8			24				/* PE_C1*8 */
-#define PE_C2_16		21				/* PE_C2*8/PE_C3 */
-#define PE_SCALE		0x059a			/* 0.7 * (1 << (15 - 1 - 3))*/
-
-#define SCALE_ESTIMATE_COEF	0x5555		/* (8.8585/(4*log2(10))) * (1 << 15)*/
-
-/*********************************************************************************
-*
-* function name: formfac_sqrt
-* description:  calculates sqrt(x)/256
-*
-**********************************************************************************/
-__inline Word32 formfac_sqrt(Word32 x)
-{
-	Word32 y;
-	Word32 preshift, postshift;
-
-
-	if (x==0) return 0;
-	preshift  = norm_l(x) - (INT_BITS-1-FF_SQRT_BITS);
-	postshift = preshift >> 1;
-	preshift  = postshift << 1;
-	postshift = postshift + 8;	  /* sqrt/256 */
-	if(preshift >= 0)
-		y = x << preshift;        /* now 1/4 <= y < 1 */
-	else
-		y = x >> (-preshift);
-	y = formfac_sqrttable[y-32];
-
-	if(postshift >= 0)
-		y = y >> postshift;
-	else
-		y = y << (-postshift);
-
-	return y;
-}
-
-
-/*********************************************************************************
-*
-* function name: CalcFormFactorChannel
-* description:  calculate the form factor one channel
-*				ffac(n) = sqrt(abs(X(k)) + sqrt(abs(X(k+1)) + ....
-*
-**********************************************************************************/
-static void
-CalcFormFactorChannel(Word16 *logSfbFormFactor,
-                      Word16 *sfbNRelevantLines,
-                      Word16 *logSfbEnergy,
-                      PSY_OUT_CHANNEL *psyOutChan)
-{
-	Word32 sfbw, sfbw1;
-	Word32 i, j;
-	Word32 sfbOffs, sfb;
-
-	sfbw = sfbw1 = 0;
-	for (sfbOffs=0; sfbOffs<psyOutChan->sfbCnt; sfbOffs+=psyOutChan->sfbPerGroup){
-		for (sfb=0; sfb<psyOutChan->maxSfbPerGroup; sfb++) {
-			i = sfbOffs+sfb;
-
-			if (psyOutChan->sfbEnergy[i] > psyOutChan->sfbThreshold[i]) {
-				Word32 accu, avgFormFactor,iSfbWidth;
-				Word32 *mdctSpec;
-				sfbw = psyOutChan->sfbOffsets[i+1] - psyOutChan->sfbOffsets[i];
-				iSfbWidth = invSBF[(sfbw >> 2) - 1];
-				mdctSpec = psyOutChan->mdctSpectrum + psyOutChan->sfbOffsets[i];
-				accu = 0;
-				/* calc sum of sqrt(spec) */
-				for (j=sfbw; j; j--) {
-					accu += formfac_sqrt(L_abs(*mdctSpec)); mdctSpec++;
-				}
-				logSfbFormFactor[i] = iLog4(accu);
-				logSfbEnergy[i] = iLog4(psyOutChan->sfbEnergy[i]);
-				avgFormFactor = fixmul(rsqrt(psyOutChan->sfbEnergy[i],INT_BITS), iSfbWidth);
-				avgFormFactor = rsqrt((Word32)avgFormFactor,INT_BITS) >> 10;
-				/* result is multiplied by 4 */
-				if(avgFormFactor)
-					sfbNRelevantLines[i] = accu / avgFormFactor;
-				else
-					sfbNRelevantLines[i] = 0x7fff;
-			}
-			else {
-				/* set number of lines to zero */
-				sfbNRelevantLines[i] = 0;
-			}
-		}
-	}
-}
-
-/*********************************************************************************
-*
-* function name: improveScf
-* description:  find better scalefactor with analysis by synthesis
-*
-**********************************************************************************/
-static Word16 improveScf(Word32 *spec,
-                         Word16  sfbWidth,
-                         Word32  thresh,
-                         Word16  scf,
-                         Word16  minScf,
-                         Word32 *dist,
-                         Word16 *minScfCalculated)
-{
-	Word32 cnt;
-	Word32 sfbDist;
-	Word32 scfBest;
-	Word32 thresh125 = L_add(thresh, (thresh >> 2));
-
-	scfBest = scf;
-
-	/* calc real distortion */
-	sfbDist = calcSfbDist(spec, sfbWidth, scf);
-	*minScfCalculated = scf;
-	if(!sfbDist)
-	  return scfBest;
-
-	if (sfbDist > thresh125) {
-		Word32 scfEstimated;
-		Word32 sfbDistBest;
-		scfEstimated = scf;
-		sfbDistBest = sfbDist;
-
-		cnt = 0;
-		while (sfbDist > thresh125 && (cnt < 3)) {
-
-			scf = scf + 1;
-			sfbDist = calcSfbDist(spec, sfbWidth, scf);
-
-			if (sfbDist < sfbDistBest) {
-				scfBest = scf;
-				sfbDistBest = sfbDist;
-			}
-			cnt = cnt + 1;
-		}
-		cnt = 0;
-		scf = scfEstimated;
-		sfbDist = sfbDistBest;
-		while ((sfbDist > thresh125) && (cnt < 1) && (scf > minScf)) {
-
-			scf = scf - 1;
-			sfbDist = calcSfbDist(spec, sfbWidth, scf);
-
-			if (sfbDist < sfbDistBest) {
-				scfBest = scf;
-				sfbDistBest = sfbDist;
-			}
-			*minScfCalculated = scf;
-			cnt = cnt + 1;
-		}
-		*dist = sfbDistBest;
-	}
-	else {
-		Word32 sfbDistBest;
-		Word32 sfbDistAllowed;
-		Word32 thresh08 = fixmul(COEF08_31, thresh);
-		sfbDistBest = sfbDist;
-
-		if (sfbDist < thresh08)
-			sfbDistAllowed = sfbDist;
-		else
-			sfbDistAllowed = thresh08;
-		for (cnt=0; cnt<3; cnt++) {
-			scf = scf + 1;
-			sfbDist = calcSfbDist(spec, sfbWidth, scf);
-
-			if (fixmul(COEF08_31,sfbDist) < sfbDistAllowed) {
-				*minScfCalculated = scfBest + 1;
-				scfBest = scf;
-				sfbDistBest = sfbDist;
-			}
-		}
-		*dist = sfbDistBest;
-	}
-
-	/* return best scalefactor */
-	return scfBest;
-}
-
-/*********************************************************************************
-*
-* function name: countSingleScfBits
-* description:  count single scf bits in huffum
-*
-**********************************************************************************/
-static Word16 countSingleScfBits(Word16 scf, Word16 scfLeft, Word16 scfRight)
-{
-	Word16 scfBits;
-
-	scfBits = bitCountScalefactorDelta(scfLeft - scf) +
-		bitCountScalefactorDelta(scf - scfRight);
-
-	return scfBits;
-}
-
-/*********************************************************************************
-*
-* function name: calcSingleSpecPe
-* description:  ldRatio = log2(en(n)) - 0,375*scfGain(n)
-*				nbits = 0.7*nLines*ldRation for ldRation >= c1
-*				nbits = 0.7*nLines*(c2 + c3*ldRatio) for ldRation < c1
-*
-**********************************************************************************/
-static Word16 calcSingleSpecPe(Word16 scf, Word16 sfbConstPePart, Word16 nLines)
-{
-	Word32 specPe;
-	Word32 ldRatio;
-	Word32 scf3;
-
-	ldRatio = sfbConstPePart << 3; /*  (sfbConstPePart -0.375*scf)*8 */
-	scf3 = scf + scf + scf;
-	ldRatio = ldRatio - scf3;
-
-	if (ldRatio < PE_C1_8) {
-		/* 21 : 2*8*PE_C2, 2*PE_C3 ~ 1*/
-		ldRatio = (ldRatio + PE_C2_16) >> 1;
-	}
-	specPe = nLines * ldRatio;
-	specPe = (specPe * PE_SCALE) >> 14;
-
-	return saturate(specPe);
-}
-
-
-/*********************************************************************************
-*
-* function name: countScfBitsDiff
-* description:  count different scf bits used
-*
-**********************************************************************************/
-static Word16 countScfBitsDiff(Word16 *scfOld, Word16 *scfNew,
-                               Word16 sfbCnt, Word16 startSfb, Word16 stopSfb)
-{
-	Word32 scfBitsDiff;
-	Word32 sfb, sfbLast;
-	Word32 sfbPrev, sfbNext;
-
-	scfBitsDiff = 0;
-	sfb = 0;
-
-	/* search for first relevant sfb */
-	sfbLast = startSfb;
-	while (sfbLast < stopSfb && scfOld[sfbLast] == VOAAC_SHRT_MIN) {
-
-		sfbLast = sfbLast + 1;
-	}
-	/* search for previous relevant sfb and count diff */
-	sfbPrev = startSfb - 1;
-	while ((sfbPrev>=0) && scfOld[sfbPrev] == VOAAC_SHRT_MIN) {
-
-		sfbPrev = sfbPrev - 1;
-	}
-
-	if (sfbPrev>=0) {
-		scfBitsDiff += bitCountScalefactorDelta(scfNew[sfbPrev] - scfNew[sfbLast]) -
-			bitCountScalefactorDelta(scfOld[sfbPrev] - scfOld[sfbLast]);
-	}
-	/* now loop through all sfbs and count diffs of relevant sfbs */
-	for (sfb=sfbLast+1; sfb<stopSfb; sfb++) {
-
-		if (scfOld[sfb] != VOAAC_SHRT_MIN) {
-			scfBitsDiff += bitCountScalefactorDelta(scfNew[sfbLast] - scfNew[sfb]) -
-				bitCountScalefactorDelta(scfOld[sfbLast] - scfOld[sfb]);
-			sfbLast = sfb;
-		}
-	}
-	/* search for next relevant sfb and count diff */
-	sfbNext = stopSfb;
-	while (sfbNext < sfbCnt && scfOld[sfbNext] == VOAAC_SHRT_MIN) {
-
-		sfbNext = sfbNext + 1;
-	}
-
-	if (sfbNext < sfbCnt)
-		scfBitsDiff += bitCountScalefactorDelta(scfNew[sfbLast] - scfNew[sfbNext]) -
-		bitCountScalefactorDelta(scfOld[sfbLast] - scfOld[sfbNext]);
-
-	return saturate(scfBitsDiff);
-}
-
-static Word16 calcSpecPeDiff(Word16 *scfOld,
-                             Word16 *scfNew,
-                             Word16 *sfbConstPePart,
-                             Word16 *logSfbEnergy,
-                             Word16 *logSfbFormFactor,
-                             Word16 *sfbNRelevantLines,
-                             Word16 startSfb,
-                             Word16 stopSfb)
-{
-	Word32 specPeDiff;
-	Word32 sfb;
-
-	specPeDiff = 0;
-
-	/* loop through all sfbs and count pe difference */
-	for (sfb=startSfb; sfb<stopSfb; sfb++) {
-
-
-		if (scfOld[sfb] != VOAAC_SHRT_MIN) {
-			Word32 ldRatioOld, ldRatioNew;
-			Word32 scf3;
-
-
-			if (sfbConstPePart[sfb] == MIN_16) {
-				sfbConstPePart[sfb] = ((logSfbEnergy[sfb] -
-					logSfbFormFactor[sfb]) + 11-8*4+3) >> 2;
-			}
-
-
-			ldRatioOld = sfbConstPePart[sfb] << 3;
-			scf3 = scfOld[sfb] + scfOld[sfb] + scfOld[sfb];
-			ldRatioOld = ldRatioOld - scf3;
-			ldRatioNew = sfbConstPePart[sfb] << 3;
-			scf3 = scfNew[sfb] + scfNew[sfb] + scfNew[sfb];
-			ldRatioNew = ldRatioNew - scf3;
-
-			if (ldRatioOld < PE_C1_8) {
-				/* 21 : 2*8*PE_C2, 2*PE_C3 ~ 1*/
-				ldRatioOld = (ldRatioOld + PE_C2_16) >> 1;
-			}
-
-			if (ldRatioNew < PE_C1_8) {
-				/* 21 : 2*8*PE_C2, 2*PE_C3 ~ 1*/
-				ldRatioNew = (ldRatioNew + PE_C2_16) >> 1;
-			}
-
-			specPeDiff +=  sfbNRelevantLines[sfb] * (ldRatioNew - ldRatioOld);
-		}
-	}
-
-	specPeDiff = (specPeDiff * PE_SCALE) >> 14;
-
-	return saturate(specPeDiff);
-}
-
-
-/*********************************************************************************
-*
-* function name: assimilateSingleScf
-* description:  searched for single scalefactor bands, where the number of bits gained
-*				by using a smaller scfgain(n) is greater than the estimated increased
-*				bit demand
-*
-**********************************************************************************/
-static void assimilateSingleScf(PSY_OUT_CHANNEL *psyOutChan,
-                                Word16 *scf,
-                                Word16 *minScf,
-                                Word32 *sfbDist,
-                                Word16 *sfbConstPePart,
-                                Word16 *logSfbEnergy,
-                                Word16 *logSfbFormFactor,
-                                Word16 *sfbNRelevantLines,
-                                Word16 *minScfCalculated,
-                                Flag    restartOnSuccess)
-{
-	Word16 sfbLast, sfbAct, sfbNext, scfAct, scfMin;
-	Word16 *scfLast, *scfNext;
-	Word32 sfbPeOld, sfbPeNew;
-	Word32 sfbDistNew;
-	Word32 j;
-	Flag   success;
-	Word16 deltaPe, deltaPeNew, deltaPeTmp;
-	Word16 *prevScfLast = psyOutChan->prevScfLast;
-	Word16 *prevScfNext = psyOutChan->prevScfNext;
-	Word16 *deltaPeLast = psyOutChan->deltaPeLast;
-	Flag   updateMinScfCalculated;
-
-	success = 0;
-	deltaPe = 0;
-
-	for(j=0;j<psyOutChan->sfbCnt;j++){
-		prevScfLast[j] = MAX_16;
-		prevScfNext[j] = MAX_16;
-		deltaPeLast[j] = MAX_16;
-	}
-
-	sfbLast = -1;
-	sfbAct = -1;
-	sfbNext = -1;
-	scfLast = 0;
-	scfNext = 0;
-	scfMin = MAX_16;
-	do {
-		/* search for new relevant sfb */
-		sfbNext = sfbNext + 1;
-		while (sfbNext < psyOutChan->sfbCnt && scf[sfbNext] == MIN_16) {
-
-			sfbNext = sfbNext + 1;
-		}
-
-		if ((sfbLast>=0) && (sfbAct>=0) && sfbNext < psyOutChan->sfbCnt) {
-			/* relevant scfs to the left and to the right */
-			scfAct  = scf[sfbAct];
-			scfLast = scf + sfbLast;
-			scfNext = scf + sfbNext;
-			scfMin  = min(*scfLast, *scfNext);
-		}
-		else {
-
-			if (sfbLast == -1 && (sfbAct>=0) && sfbNext < psyOutChan->sfbCnt) {
-				/* first relevant scf */
-				scfAct  = scf[sfbAct];
-				scfLast = &scfAct;
-				scfNext = scf + sfbNext;
-				scfMin  = *scfNext;
-			}
-			else {
-
-				if ((sfbLast>=0) && (sfbAct>=0) && sfbNext == psyOutChan->sfbCnt) {
-					/* last relevant scf */
-					scfAct  = scf[sfbAct];
-					scfLast = scf + sfbLast;
-					scfNext = &scfAct;
-					scfMin  = *scfLast;
-				}
-			}
-		}
-
-		if (sfbAct>=0)
-			scfMin = max(scfMin, minScf[sfbAct]);
-
-		if ((sfbAct >= 0) &&
-			(sfbLast>=0 || sfbNext < psyOutChan->sfbCnt) &&
-			scfAct > scfMin &&
-			(*scfLast != prevScfLast[sfbAct] ||
-			*scfNext != prevScfNext[sfbAct] ||
-			deltaPe < deltaPeLast[sfbAct])) {
-			success = 0;
-
-			/* estimate required bits for actual scf */
-			if (sfbConstPePart[sfbAct] == MIN_16) {
-				sfbConstPePart[sfbAct] = logSfbEnergy[sfbAct] -
-					logSfbFormFactor[sfbAct] + 11-8*4; /* 4*log2(6.75) - 32 */
-
-				if (sfbConstPePart[sfbAct] < 0)
-					sfbConstPePart[sfbAct] = sfbConstPePart[sfbAct] + 3;
-				sfbConstPePart[sfbAct] = sfbConstPePart[sfbAct] >> 2;
-			}
-
-			sfbPeOld = calcSingleSpecPe(scfAct, sfbConstPePart[sfbAct], sfbNRelevantLines[sfbAct]) +
-				countSingleScfBits(scfAct, *scfLast, *scfNext);
-			deltaPeNew = deltaPe;
-			updateMinScfCalculated = 1;
-			do {
-				scfAct = scfAct - 1;
-				/* check only if the same check was not done before */
-
-				if (scfAct < minScfCalculated[sfbAct]) {
-					sfbPeNew = calcSingleSpecPe(scfAct, sfbConstPePart[sfbAct], sfbNRelevantLines[sfbAct]) +
-						countSingleScfBits(scfAct, *scfLast, *scfNext);
-					/* use new scf if no increase in pe and
-					quantization error is smaller */
-					deltaPeTmp = deltaPe + sfbPeNew - sfbPeOld;
-
-					if (deltaPeTmp < 10) {
-						sfbDistNew = calcSfbDist(psyOutChan->mdctSpectrum+
-							psyOutChan->sfbOffsets[sfbAct],
-							(psyOutChan->sfbOffsets[sfbAct+1] - psyOutChan->sfbOffsets[sfbAct]),
-							scfAct);
-						if (sfbDistNew < sfbDist[sfbAct]) {
-							/* success, replace scf by new one */
-							scf[sfbAct] = scfAct;
-							sfbDist[sfbAct] = sfbDistNew;
-							deltaPeNew = deltaPeTmp;
-							success = 1;
-						}
-						/* mark as already checked */
-
-						if (updateMinScfCalculated) {
-							minScfCalculated[sfbAct] = scfAct;
-						}
-					}
-					else {
-						updateMinScfCalculated = 0;
-					}
-				}
-
-			} while (scfAct > scfMin);
-			deltaPe = deltaPeNew;
-			/* save parameters to avoid multiple computations of the same sfb */
-			prevScfLast[sfbAct] = *scfLast;
-			prevScfNext[sfbAct] = *scfNext;
-			deltaPeLast[sfbAct] = deltaPe;
-		}
-
-		if (success && restartOnSuccess) {
-			/* start again at first sfb */
-			sfbLast = -1;
-			sfbAct  = -1;
-			sfbNext = -1;
-			scfLast = 0;
-			scfNext = 0;
-			scfMin  = MAX_16;
-			success = 0;
-		}
-		else {
-			/* shift sfbs for next band */
-			sfbLast = sfbAct;
-			sfbAct  = sfbNext;
-		}
-
-  } while (sfbNext < psyOutChan->sfbCnt);
-}
-
-
-/*********************************************************************************
-*
-* function name: assimilateMultipleScf
-* description:  scalefactor difference reduction
-*
-**********************************************************************************/
-static void assimilateMultipleScf(PSY_OUT_CHANNEL *psyOutChan,
-                                  Word16 *scf,
-                                  Word16 *minScf,
-                                  Word32 *sfbDist,
-                                  Word16 *sfbConstPePart,
-                                  Word16 *logSfbEnergy,
-                                  Word16 *logSfbFormFactor,
-                                  Word16 *sfbNRelevantLines)
-{
-	Word32 sfb, startSfb, stopSfb, scfMin, scfMax, scfAct;
-	Flag   possibleRegionFound;
-	Word32 deltaScfBits;
-	Word32 deltaSpecPe;
-	Word32 deltaPe, deltaPeNew;
-	Word32 sfbCnt;
-	Word32 *sfbDistNew = psyOutChan->sfbDistNew;
-	Word16 *scfTmp = psyOutChan->prevScfLast;
-
-	deltaPe = 0;
-	sfbCnt = psyOutChan->sfbCnt;
-
-	/* calc min and max scalfactors */
-	scfMin = MAX_16;
-	scfMax = MIN_16;
-	for (sfb=0; sfb<sfbCnt; sfb++) {
-
-		if (scf[sfb] != MIN_16) {
-			scfMin = min(scfMin, scf[sfb]);
-			scfMax = max(scfMax, scf[sfb]);
-		}
-	}
-
-	if (scfMax !=  MIN_16) {
-
-		scfAct = scfMax;
-
-		do {
-			scfAct = scfAct - 1;
-			for (sfb=0; sfb<sfbCnt; sfb++) {
-				scfTmp[sfb] = scf[sfb];
-			}
-			stopSfb = 0;
-			do {
-				sfb = stopSfb;
-
-				while (sfb < sfbCnt && (scf[sfb] == MIN_16 || scf[sfb] <= scfAct)) {
-					sfb = sfb + 1;
-				}
-				startSfb = sfb;
-				sfb = sfb + 1;
-
-				while (sfb < sfbCnt && (scf[sfb] == MIN_16 || scf[sfb] > scfAct)) {
-					sfb = sfb + 1;
-				}
-				stopSfb = sfb;
-
-				possibleRegionFound = 0;
-
-				if (startSfb < sfbCnt) {
-					possibleRegionFound = 1;
-					for (sfb=startSfb; sfb<stopSfb; sfb++) {
-
-						if (scf[sfb]!=MIN_16) {
-
-							if (scfAct < minScf[sfb]) {
-								possibleRegionFound = 0;
-								break;
-							}
-						}
-					}
-				}
-
-
-				if (possibleRegionFound) { /* region found */
-
-					/* replace scfs in region by scfAct */
-					for (sfb=startSfb; sfb<stopSfb; sfb++) {
-
-						if (scfTmp[sfb]!=MIN_16)
-							scfTmp[sfb] = scfAct;
-					}
-
-					/* estimate change in bit demand for new scfs */
-					deltaScfBits = countScfBitsDiff(scf,scfTmp,sfbCnt,startSfb,stopSfb);
-					deltaSpecPe = calcSpecPeDiff(scf, scfTmp, sfbConstPePart,
-						logSfbEnergy, logSfbFormFactor, sfbNRelevantLines,
-						startSfb, stopSfb);
-					deltaPeNew = deltaPe + deltaScfBits + deltaSpecPe;
-
-
-					if (deltaPeNew < 10) {
-						Word32 distOldSum, distNewSum;
-
-						/* quantize and calc sum of new distortion */
-						distOldSum = 0;
-						distNewSum = 0;
-						for (sfb=startSfb; sfb<stopSfb; sfb++) {
-
-							if (scfTmp[sfb] != MIN_16) {
-								distOldSum = L_add(distOldSum, sfbDist[sfb]);
-
-								sfbDistNew[sfb] = calcSfbDist(psyOutChan->mdctSpectrum +
-									psyOutChan->sfbOffsets[sfb],
-									(psyOutChan->sfbOffsets[sfb+1] - psyOutChan->sfbOffsets[sfb]),
-									scfAct);
-
-
-								if (sfbDistNew[sfb] > psyOutChan->sfbThreshold[sfb]) {
-									distNewSum = distOldSum << 1;
-									break;
-								}
-								distNewSum = L_add(distNewSum, sfbDistNew[sfb]);
-							}
-						}
-
-						if (distNewSum < distOldSum) {
-							deltaPe = deltaPeNew;
-							for (sfb=startSfb; sfb<stopSfb; sfb++) {
-
-								if (scf[sfb]!=MIN_16) {
-									scf[sfb] = scfAct;
-									sfbDist[sfb] = sfbDistNew[sfb];
-								}
-							}
-						}
-					}
-				}
-			} while (stopSfb <= sfbCnt);
-		} while (scfAct > scfMin);
-	}
-}
-
-/*********************************************************************************
-*
-* function name: EstimateScaleFactorsChannel
-* description:  estimate scale factors for one channel
-*
-**********************************************************************************/
-static void
-EstimateScaleFactorsChannel(PSY_OUT_CHANNEL *psyOutChan,
-                            Word16          *scf,
-                            Word16          *globalGain,
-                            Word16          *logSfbEnergy,
-                            Word16          *logSfbFormFactor,
-                            Word16          *sfbNRelevantLines)
-{
-	Word32 i, j;
-	Word32 thresh, energy;
-	Word32 energyPart, thresholdPart;
-	Word32 scfInt, minScf, maxScf, maxAllowedScf, lastSf;
-	Word32 maxSpec;
-	Word32 *sfbDist = psyOutChan->sfbDist;
-	Word16 *minSfMaxQuant = psyOutChan->minSfMaxQuant;
-	Word16 *minScfCalculated = psyOutChan->minScfCalculated;
-
-
-	for (i=0; i<psyOutChan->sfbCnt; i++) {
-		Word32 sbfwith, sbfStart;
-		Word32 *mdctSpec;
-		thresh = psyOutChan->sfbThreshold[i];
-		energy = psyOutChan->sfbEnergy[i];
-
-		sbfStart = psyOutChan->sfbOffsets[i];
-		sbfwith = psyOutChan->sfbOffsets[i+1] - sbfStart;
-		mdctSpec = psyOutChan->mdctSpectrum+sbfStart;
-
-		maxSpec = 0;
-		/* maximum of spectrum */
-		for (j=sbfwith; j; j-- ) {
-			Word32 absSpec = L_abs(*mdctSpec); mdctSpec++;
-			maxSpec |= absSpec;
-		}
-
-		/* scfs without energy or with thresh>energy are marked with MIN_16 */
-		scf[i] = MIN_16;
-		minSfMaxQuant[i] = MIN_16;
-
-		if ((maxSpec > 0) && (energy > thresh)) {
-
-			energyPart = logSfbFormFactor[i];
-			thresholdPart = iLog4(thresh);
-			/* -20 = 4*log2(6.75) - 32 */
-			scfInt = ((thresholdPart - energyPart - 20) * SCALE_ESTIMATE_COEF) >> 15;
-
-			minSfMaxQuant[i] = iLog4(maxSpec) - 68; /* 68  -16/3*log(MAX_QUANT+0.5-logCon)/log(2) + 1 */
-
-
-			if (minSfMaxQuant[i] > scfInt) {
-				scfInt = minSfMaxQuant[i];
-			}
-
-			/* find better scalefactor with analysis by synthesis */
-			scfInt = improveScf(psyOutChan->mdctSpectrum+sbfStart,
-				sbfwith,
-				thresh, scfInt, minSfMaxQuant[i],
-				&sfbDist[i], &minScfCalculated[i]);
-
-			scf[i] = scfInt;
-		}
-	}
-
-
-	/* scalefactor differece reduction  */
-	{
-		Word16 sfbConstPePart[MAX_GROUPED_SFB];
-		for(i=0;i<psyOutChan->sfbCnt;i++) {
-			sfbConstPePart[i] = MIN_16;
-		}
-
-		assimilateSingleScf(psyOutChan, scf,
-			minSfMaxQuant, sfbDist, sfbConstPePart, logSfbEnergy,
-			logSfbFormFactor, sfbNRelevantLines, minScfCalculated, 1);
-
-		assimilateMultipleScf(psyOutChan, scf,
-			minSfMaxQuant, sfbDist, sfbConstPePart, logSfbEnergy,
-			logSfbFormFactor, sfbNRelevantLines);
-	}
-
-	/* get max scalefac for global gain */
-	maxScf = MIN_16;
-	minScf = MAX_16;
-	for (i=0; i<psyOutChan->sfbCnt; i++) {
-
-		if (maxScf < scf[i]) {
-			maxScf = scf[i];
-		}
-
-		if ((scf[i] != MIN_16) && (minScf > scf[i])) {
-			minScf = scf[i];
-		}
-	}
-	/* limit scf delta */
-	maxAllowedScf = minScf + MAX_SCF_DELTA;
-	for(i=0; i<psyOutChan->sfbCnt; i++) {
-
-		if ((scf[i] != MIN_16) && (maxAllowedScf < scf[i])) {
-			scf[i] = maxAllowedScf;
-		}
-	}
-	/* new maxScf if any scf has been limited */
-
-	if (maxAllowedScf < maxScf) {
-		maxScf = maxAllowedScf;
-	}
-
-	/* calc loop scalefactors */
-
-	if (maxScf > MIN_16) {
-		*globalGain = maxScf;
-		lastSf = 0;
-
-		for(i=0; i<psyOutChan->sfbCnt; i++) {
-
-			if (scf[i] == MIN_16) {
-				scf[i] = lastSf;
-				/* set band explicitely to zero */
-				for (j=psyOutChan->sfbOffsets[i]; j<psyOutChan->sfbOffsets[i+1]; j++) {
-					psyOutChan->mdctSpectrum[j] = 0;
-				}
-			}
-			else {
-				scf[i] = maxScf - scf[i];
-				lastSf = scf[i];
-			}
-		}
-	}
-	else{
-		*globalGain = 0;
-		/* set spectrum explicitely to zero */
-		for(i=0; i<psyOutChan->sfbCnt; i++) {
-			scf[i] = 0;
-			for (j=psyOutChan->sfbOffsets[i]; j<psyOutChan->sfbOffsets[i+1]; j++) {
-				psyOutChan->mdctSpectrum[j] = 0;
-			}
-		}
-	}
-}
-
-/*********************************************************************************
-*
-* function name: CalcFormFactor
-* description:  estimate Form factors for all channel
-*
-**********************************************************************************/
-void
-CalcFormFactor(Word16 logSfbFormFactor[MAX_CHANNELS][MAX_GROUPED_SFB],
-               Word16 sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
-               Word16 logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-               PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-               const Word16 nChannels)
-{
-	Word16 j;
-
-	for (j=0; j<nChannels; j++) {
-		CalcFormFactorChannel(logSfbFormFactor[j], sfbNRelevantLines[j], logSfbEnergy[j], &psyOutChannel[j]);
-	}
-}
-
-/*********************************************************************************
-*
-* function name: EstimateScaleFactors
-* description:  estimate scale factors for all channel
-*
-**********************************************************************************/
-void
-EstimateScaleFactors(PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-                     QC_OUT_CHANNEL  qcOutChannel[MAX_CHANNELS],
-                     Word16          logSfbEnergy[MAX_CHANNELS][MAX_GROUPED_SFB],
-                     Word16          logSfbFormFactor[MAX_CHANNELS][MAX_GROUPED_SFB],
-                     Word16          sfbNRelevantLines[MAX_CHANNELS][MAX_GROUPED_SFB],
-                     const Word16    nChannels)
-{
-	Word16 j;
-
-	for (j=0; j<nChannels; j++) {
-		EstimateScaleFactorsChannel(&psyOutChannel[j],
-			qcOutChannel[j].scf,
-			&(qcOutChannel[j].globalGain),
-			logSfbEnergy[j],
-			logSfbFormFactor[j],
-			sfbNRelevantLines[j]);
-	}
-}
-
diff --git a/media/libstagefright/codecs/aacenc/src/spreading.c b/media/libstagefright/codecs/aacenc/src/spreading.c
deleted file mode 100644
index aaf2fff..0000000
--- a/media/libstagefright/codecs/aacenc/src/spreading.c
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		spreading.c
-
-	Content:	Spreading of energy function
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "spreading.h"
-
-/*********************************************************************************
-*
-* function name: SpreadingMax
-* description:  spreading the energy
-*				 higher frequencies thr(n) = max(thr(n), sh(n)*thr(n-1))
-*				 lower frequencies  thr(n) = max(thr(n), sl(n)*thr(n+1))
-*
-**********************************************************************************/
-void SpreadingMax(const Word16 pbCnt,
-                  const Word16 *maskLowFactor,
-                  const Word16 *maskHighFactor,
-                  Word32       *pbSpreadedEnergy)
-{
-  Word32 i;
-
-  /* slope to higher frequencies */
-  for (i=1; i<pbCnt; i++) {
-    pbSpreadedEnergy[i] = max(pbSpreadedEnergy[i],
-                                L_mpy_ls(pbSpreadedEnergy[i-1], maskHighFactor[i]));
-  }
-  /* slope to lower frequencies */
-  for (i=pbCnt - 2; i>=0; i--) {
-    pbSpreadedEnergy[i] = max(pbSpreadedEnergy[i],
-                                L_mpy_ls(pbSpreadedEnergy[i+1], maskLowFactor[i]));
-  }
-}
diff --git a/media/libstagefright/codecs/aacenc/src/stat_bits.c b/media/libstagefright/codecs/aacenc/src/stat_bits.c
deleted file mode 100644
index c2bd8bd..0000000
--- a/media/libstagefright/codecs/aacenc/src/stat_bits.c
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		stat_bits.c
-
-	Content:	Static bit counter functions
-
-*******************************************************************************/
-
-#include "stat_bits.h"
-#include "bitenc.h"
-#include "tns.h"
-
-
-typedef enum {
-  SI_ID_BITS                =(3),
-  SI_FILL_COUNT_BITS        =(4),
-  SI_FILL_ESC_COUNT_BITS    =(8),
-  SI_FILL_EXTENTION_BITS    =(4),
-  SI_FILL_NIBBLE_BITS       =(4),
-  SI_SCE_BITS               =(4),
-  SI_CPE_BITS               =(5),
-  SI_CPE_MS_MASK_BITS       =(2) ,
-  SI_ICS_INFO_BITS_LONG     =(1+2+1+6+1),
-  SI_ICS_INFO_BITS_SHORT    =(1+2+1+4+7),
-  SI_ICS_BITS               =(8+1+1+1)
-} SI_BITS;
-
-
-/*********************************************************************************
-*
-* function name: countMsMaskBits
-* description:   count ms stereo bits demand
-*
-**********************************************************************************/
-static Word16 countMsMaskBits(Word16   sfbCnt,
-                              Word16   sfbPerGroup,
-                              Word16   maxSfbPerGroup,
-                              struct TOOLSINFO *toolsInfo)
-{
-  Word16 msBits, sfbOff, sfb;
-  msBits = 0;
-
-
-  switch(toolsInfo->msDigest) {
-    case MS_NONE:
-    case MS_ALL:
-      break;
-
-    case MS_SOME:
-      for(sfbOff=0; sfbOff<sfbCnt; sfbOff+=sfbPerGroup)
-        for(sfb=0; sfb<maxSfbPerGroup; sfb++)
-          msBits += 1;
-      break;
-  }
-  return(msBits);
-}
-
-/*********************************************************************************
-*
-* function name: tnsCount
-* description:   count tns bit demand  core function
-*
-**********************************************************************************/
-static Word16 tnsCount(TNS_INFO *tnsInfo, Word16 blockType)
-{
-
-  Word32 i, k;
-  Flag tnsPresent;
-  Word32 numOfWindows;
-  Word32 count;
-  Word32 coefBits;
-  Word16 *ptcoef;
-
-  count = 0;
-
-  if (blockType == 2)
-    numOfWindows = 8;
-  else
-    numOfWindows = 1;
-  tnsPresent = 0;
-
-  for (i=0; i<numOfWindows; i++) {
-
-    if (tnsInfo->tnsActive[i]!=0) {
-      tnsPresent = 1;
-    }
-  }
-
-  if (tnsPresent) {
-    /* there is data to be written*/
-    /*count += 1; */
-    for (i=0; i<numOfWindows; i++) {
-
-      if (blockType == 2)
-        count += 1;
-      else
-        count += 2;
-
-      if (tnsInfo->tnsActive[i]) {
-        count += 1;
-
-        if (blockType == 2) {
-          count += 4;
-          count += 3;
-        }
-        else {
-          count += 6;
-          count += 5;
-        }
-
-        if (tnsInfo->order[i]) {
-          count += 1; /*direction*/
-          count += 1; /*coef_compression */
-
-          if (tnsInfo->coefRes[i] == 4) {
-            ptcoef = tnsInfo->coef + i*TNS_MAX_ORDER_SHORT;
-			coefBits = 3;
-            for(k=0; k<tnsInfo->order[i]; k++) {
-
-              if ((ptcoef[k] > 3) || (ptcoef[k] < -4)) {
-                coefBits = 4;
-                break;
-              }
-            }
-          }
-          else {
-            coefBits = 2;
-            ptcoef = tnsInfo->coef + i*TNS_MAX_ORDER_SHORT;
-			for(k=0; k<tnsInfo->order[i]; k++) {
-
-              if ((ptcoef[k] > 1) || (ptcoef[k] < -2)) {
-                coefBits = 3;
-                break;
-              }
-            }
-          }
-          for (k=0; k<tnsInfo->order[i]; k++ ) {
-            count += coefBits;
-          }
-        }
-      }
-    }
-  }
-
-  return count;
-}
-
-/**********************************************************************************
-*
-* function name: countTnsBits
-* description:   count tns bit demand
-*
-**********************************************************************************/
-static Word16 countTnsBits(TNS_INFO *tnsInfo,Word16 blockType)
-{
-  return(tnsCount(tnsInfo, blockType));
-}
-
-/*********************************************************************************
-*
-* function name: countStaticBitdemand
-* description:   count static bit demand include tns
-*
-**********************************************************************************/
-Word16 countStaticBitdemand(PSY_OUT_CHANNEL psyOutChannel[MAX_CHANNELS],
-                            PSY_OUT_ELEMENT *psyOutElement,
-                            Word16 channels,
-							Word16 adtsUsed)
-{
-  Word32 statBits;
-  Word32 ch;
-
-  statBits = 0;
-
-  /* if adts used, add 56 bits */
-  if(adtsUsed) statBits += 56;
-
-
-  switch (channels) {
-    case 1:
-      statBits += SI_ID_BITS+SI_SCE_BITS+SI_ICS_BITS;
-      statBits += countTnsBits(&(psyOutChannel[0].tnsInfo),
-                               psyOutChannel[0].windowSequence);
-
-      switch(psyOutChannel[0].windowSequence){
-        case LONG_WINDOW:
-        case START_WINDOW:
-        case STOP_WINDOW:
-          statBits += SI_ICS_INFO_BITS_LONG;
-          break;
-        case SHORT_WINDOW:
-          statBits += SI_ICS_INFO_BITS_SHORT;
-          break;
-      }
-      break;
-    case 2:
-      statBits += SI_ID_BITS+SI_CPE_BITS+2*SI_ICS_BITS;
-
-      statBits += SI_CPE_MS_MASK_BITS;
-      statBits += countMsMaskBits(psyOutChannel[0].sfbCnt,
-								  psyOutChannel[0].sfbPerGroup,
-								  psyOutChannel[0].maxSfbPerGroup,
-								  &psyOutElement->toolsInfo);
-
-      switch (psyOutChannel[0].windowSequence) {
-        case LONG_WINDOW:
-        case START_WINDOW:
-        case STOP_WINDOW:
-          statBits += SI_ICS_INFO_BITS_LONG;
-          break;
-        case SHORT_WINDOW:
-          statBits += SI_ICS_INFO_BITS_SHORT;
-          break;
-      }
-      for(ch=0; ch<2; ch++)
-        statBits += countTnsBits(&(psyOutChannel[ch].tnsInfo),
-                                 psyOutChannel[ch].windowSequence);
-      break;
-  }
-
-  return statBits;
-}
-
diff --git a/media/libstagefright/codecs/aacenc/src/tns.c b/media/libstagefright/codecs/aacenc/src/tns.c
deleted file mode 100644
index 27c3971..0000000
--- a/media/libstagefright/codecs/aacenc/src/tns.c
+++ /dev/null
@@ -1,906 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		tns.c
-
-	Content:	Definition TNS tools functions
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "oper_32b.h"
-#include "assert.h"
-#include "aac_rom.h"
-#include "psy_const.h"
-#include "tns.h"
-#include "tns_param.h"
-#include "psy_configuration.h"
-#include "tns_func.h"
-
-#define UNUSED(x) (void)(x)
-
-#define TNS_MODIFY_BEGIN         2600  /* Hz */
-#define RATIO_PATCH_LOWER_BORDER 380   /* Hz */
-#define TNS_GAIN_THRESH			 141   /* 1.41*100 */
-#define NORM_COEF				 0x028f5c28
-
-static const Word32 TNS_PARCOR_THRESH = 0x0ccccccd; /* 0.1*(1 << 31) */
-/* Limit bands to > 2.0 kHz */
-static unsigned short tnsMinBandNumberLong[12] =
-{ 11, 12, 15, 16, 17, 20, 25, 26, 24, 28, 30, 31 };
-static unsigned short tnsMinBandNumberShort[12] =
-{ 2, 2, 2, 3, 3, 4, 6, 6, 8, 10, 10, 12 };
-
-/**************************************/
-/* Main/Low Profile TNS Parameters    */
-/**************************************/
-static unsigned short tnsMaxBandsLongMainLow[12] =
-{ 31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39 };
-
-static unsigned short tnsMaxBandsShortMainLow[12] =
-{ 9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14 };
-
-
-static void CalcWeightedSpectrum(const Word32 spectrum[],
-                                 Word16 weightedSpectrum[],
-                                 Word32* sfbEnergy,
-                                 const Word16* sfbOffset, Word16 lpcStartLine,
-                                 Word16 lpcStopLine, Word16 lpcStartBand,Word16 lpcStopBand,
-                                 Word32 *pWork32);
-
-
-
-void AutoCorrelation(const Word16 input[], Word32 corr[],
-                            Word16 samples, Word16 corrCoeff);
-static Word16 AutoToParcor(Word32 workBuffer[], Word32 reflCoeff[], Word16 numOfCoeff);
-
-static Word16 CalcTnsFilter(const Word16* signal, const Word32 window[], Word16 numOfLines,
-                                              Word16 tnsOrder, Word32 parcor[]);
-
-
-static void Parcor2Index(const Word32 parcor[], Word16 index[], Word16 order,
-                         Word16 bitsPerCoeff);
-
-static void Index2Parcor(const Word16 index[], Word32 parcor[], Word16 order,
-                         Word16 bitsPerCoeff);
-
-
-
-static void AnalysisFilterLattice(const Word32 signal[], Word16 numOfLines,
-                                  const Word32 parCoeff[], Word16 order,
-                                  Word32 output[]);
-
-
-/**
-*
-* function name: FreqToBandWithRounding
-* description:  Retrieve index of nearest band border
-* returnt:		index
-*
-*/
-static Word16 FreqToBandWithRounding(Word32 freq,                   /*!< frequency in Hertz */
-                                     Word32 fs,                     /*!< Sampling frequency in Hertz */
-                                     Word16 numOfBands,             /*!< total number of bands */
-                                     const Word16 *bandStartOffset) /*!< table of band borders */
-{
-  Word32 lineNumber, band;
-  Word32 temp, shift;
-
-  /*  assert(freq >= 0);  */
-  shift = norm_l(fs);
-  lineNumber = (extract_l(fixmul((bandStartOffset[numOfBands] << 2),Div_32(freq << shift,fs << shift))) + 1) >> 1;
-
-  /* freq > fs/2 */
-  temp = lineNumber - bandStartOffset[numOfBands] ;
-  if (temp >= 0)
-    return numOfBands;
-
-  /* find band the line number lies in */
-  for (band=0; band<numOfBands; band++) {
-    temp = bandStartOffset[band + 1] - lineNumber;
-    if (temp > 0) break;
-  }
-
-  temp = (lineNumber - bandStartOffset[band]);
-  temp = (temp - (bandStartOffset[band + 1] - lineNumber));
-  if ( temp > 0 )
-  {
-    band = band + 1;
-  }
-
-  return extract_l(band);
-}
-
-
-/**
-*
-* function name: InitTnsConfigurationLong
-* description:  Fill TNS_CONFIG structure with sensible content for long blocks
-* returns:		0 if success
-*
-*/
-Word16 InitTnsConfigurationLong(Word32 bitRate,          /*!< bitrate */
-                                Word32 sampleRate,          /*!< Sampling frequency */
-                                Word16 channels,            /*!< number of channels */
-                                TNS_CONFIG *tC,             /*!< TNS Config struct (modified) */
-                                PSY_CONFIGURATION_LONG *pC, /*!< psy config struct */
-                                Word16 active)              /*!< tns active flag */
-{
-
-  Word32 bitratePerChannel __unused;
-  tC->maxOrder     = TNS_MAX_ORDER;
-  tC->tnsStartFreq = 1275;
-  tC->coefRes      = 4;
-
-  /* to avoid integer division */
-  if ( sub(channels,2) == 0 ) {
-    bitratePerChannel = bitRate >> 1;
-  }
-  else {
-    bitratePerChannel = bitRate;
-  }
-
-  tC->tnsMaxSfb = tnsMaxBandsLongMainLow[pC->sampRateIdx];
-
-  tC->tnsActive = active;
-
-  /* now calc band and line borders */
-  tC->tnsStopBand = min(pC->sfbCnt, tC->tnsMaxSfb);
-  tC->tnsStopLine = pC->sfbOffset[tC->tnsStopBand];
-
-  tC->tnsStartBand = FreqToBandWithRounding(tC->tnsStartFreq, sampleRate,
-                                            pC->sfbCnt, (const Word16*)pC->sfbOffset);
-
-  tC->tnsModifyBeginCb = FreqToBandWithRounding(TNS_MODIFY_BEGIN,
-                                                sampleRate,
-                                                pC->sfbCnt,
-                                                (const Word16*)pC->sfbOffset);
-
-  tC->tnsRatioPatchLowestCb = FreqToBandWithRounding(RATIO_PATCH_LOWER_BORDER,
-                                                     sampleRate,
-                                                     pC->sfbCnt,
-                                                     (const Word16*)pC->sfbOffset);
-
-
-  tC->tnsStartLine = pC->sfbOffset[tC->tnsStartBand];
-
-  tC->lpcStopBand = tnsMaxBandsLongMainLow[pC->sampRateIdx];
-  tC->lpcStopBand = min(tC->lpcStopBand, pC->sfbActive);
-
-  tC->lpcStopLine = pC->sfbOffset[tC->lpcStopBand];
-
-  tC->lpcStartBand = tnsMinBandNumberLong[pC->sampRateIdx];
-
-  tC->lpcStartLine = pC->sfbOffset[tC->lpcStartBand];
-
-  tC->threshold = TNS_GAIN_THRESH;
-
-
-  return(0);
-}
-
-/**
-*
-* function name: InitTnsConfigurationShort
-* description:  Fill TNS_CONFIG structure with sensible content for short blocks
-* returns:		0 if success
-*
-*/
-Word16 InitTnsConfigurationShort(Word32 bitRate,              /*!< bitrate */
-                                 Word32 sampleRate,           /*!< Sampling frequency */
-                                 Word16 channels,             /*!< number of channels */
-                                 TNS_CONFIG *tC,              /*!< TNS Config struct (modified) */
-                                 PSY_CONFIGURATION_SHORT *pC, /*!< psy config struct */
-                                 Word16 active)               /*!< tns active flag */
-{
-  Word32 bitratePerChannel __unused;
-  tC->maxOrder     = TNS_MAX_ORDER_SHORT;
-  tC->tnsStartFreq = 2750;
-  tC->coefRes      = 3;
-
-  /* to avoid integer division */
-  if ( sub(channels,2) == 0 ) {
-    bitratePerChannel = L_shr(bitRate,1);
-  }
-  else {
-    bitratePerChannel = bitRate;
-  }
-
-  tC->tnsMaxSfb = tnsMaxBandsShortMainLow[pC->sampRateIdx];
-
-  tC->tnsActive = active;
-
-  /* now calc band and line borders */
-  tC->tnsStopBand = min(pC->sfbCnt, tC->tnsMaxSfb);
-  tC->tnsStopLine = pC->sfbOffset[tC->tnsStopBand];
-
-  tC->tnsStartBand=FreqToBandWithRounding(tC->tnsStartFreq, sampleRate,
-                                          pC->sfbCnt, (const Word16*)pC->sfbOffset);
-
-  tC->tnsModifyBeginCb = FreqToBandWithRounding(TNS_MODIFY_BEGIN,
-                                                sampleRate,
-                                                pC->sfbCnt,
-                                                (const Word16*)pC->sfbOffset);
-
-  tC->tnsRatioPatchLowestCb = FreqToBandWithRounding(RATIO_PATCH_LOWER_BORDER,
-                                                     sampleRate,
-                                                     pC->sfbCnt,
-                                                     (const Word16*)pC->sfbOffset);
-
-
-  tC->tnsStartLine = pC->sfbOffset[tC->tnsStartBand];
-
-  tC->lpcStopBand = tnsMaxBandsShortMainLow[pC->sampRateIdx];
-
-  tC->lpcStopBand = min(tC->lpcStopBand, pC->sfbActive);
-
-  tC->lpcStopLine = pC->sfbOffset[tC->lpcStopBand];
-
-  tC->lpcStartBand = tnsMinBandNumberShort[pC->sampRateIdx];
-
-  tC->lpcStartLine = pC->sfbOffset[tC->lpcStartBand];
-
-  tC->threshold = TNS_GAIN_THRESH;
-
-  return(0);
-}
-
-/**
-*
-* function name: TnsDetect
-* description:  Calculate TNS filter and decide on TNS usage
-* returns:		0 if success
-*
-*/
-Word32 TnsDetect(TNS_DATA* tnsData,        /*!< tns data structure (modified) */
-                 TNS_CONFIG tC,            /*!< tns config structure */
-                 Word32* pScratchTns,      /*!< pointer to scratch space */
-                 const Word16 sfbOffset[], /*!< scalefactor size and table */
-                 Word32* spectrum,         /*!< spectral data */
-                 Word16 subBlockNumber,    /*!< subblock num */
-                 Word16 blockType,         /*!< blocktype (long or short) */
-                 Word32 * sfbEnergy)       /*!< sfb-wise energy */
-{
-
-  Word32  predictionGain;
-  Word32  temp;
-  Word32* pWork32 = &pScratchTns[subBlockNumber >> 8];
-  Word16* pWeightedSpectrum = (Word16 *)&pScratchTns[subBlockNumber >> 8];
-
-
-  if (tC.tnsActive) {
-    CalcWeightedSpectrum(spectrum,
-                         pWeightedSpectrum,
-                         sfbEnergy,
-                         sfbOffset,
-                         tC.lpcStartLine,
-                         tC.lpcStopLine,
-                         tC.lpcStartBand,
-                         tC.lpcStopBand,
-                         pWork32);
-
-    temp = blockType - SHORT_WINDOW;
-    if ( temp != 0 ) {
-        predictionGain = CalcTnsFilter( &pWeightedSpectrum[tC.lpcStartLine],
-                                        tC.acfWindow,
-                                        tC.lpcStopLine - tC.lpcStartLine,
-                                        tC.maxOrder,
-                                        tnsData->dataRaw.tnsLong.subBlockInfo.parcor);
-
-
-        temp = predictionGain - tC.threshold;
-        if ( temp > 0 ) {
-          tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive = 1;
-        }
-        else {
-          tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive = 0;
-        }
-
-        tnsData->dataRaw.tnsLong.subBlockInfo.predictionGain = predictionGain;
-    }
-    else{
-
-        predictionGain = CalcTnsFilter( &pWeightedSpectrum[tC.lpcStartLine],
-                                        tC.acfWindow,
-                                        tC.lpcStopLine - tC.lpcStartLine,
-                                        tC.maxOrder,
-                                        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].parcor);
-
-        temp = predictionGain - tC.threshold;
-        if ( temp > 0 ) {
-          tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].tnsActive = 1;
-        }
-        else {
-          tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].tnsActive = 0;
-        }
-
-        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].predictionGain = predictionGain;
-    }
-
-  }
-  else{
-
-    temp = blockType - SHORT_WINDOW;
-    if ( temp != 0 ) {
-        tnsData->dataRaw.tnsLong.subBlockInfo.tnsActive = 0;
-        tnsData->dataRaw.tnsLong.subBlockInfo.predictionGain = 0;
-    }
-    else {
-        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].tnsActive = 0;
-        tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber].predictionGain = 0;
-    }
-  }
-
-  return(0);
-}
-
-
-/*****************************************************************************
-*
-* function name: TnsSync
-* description: update tns parameter
-*
-*****************************************************************************/
-void TnsSync(TNS_DATA *tnsDataDest,
-             const TNS_DATA *tnsDataSrc,
-             const TNS_CONFIG tC,
-             const Word16 subBlockNumber,
-             const Word16 blockType)
-{
-   TNS_SUBBLOCK_INFO *sbInfoDest;
-   const TNS_SUBBLOCK_INFO *sbInfoSrc;
-   Word32 i, temp;
-
-   temp =  blockType - SHORT_WINDOW;
-   if ( temp != 0 ) {
-      sbInfoDest = &tnsDataDest->dataRaw.tnsLong.subBlockInfo;
-      sbInfoSrc  = &tnsDataSrc->dataRaw.tnsLong.subBlockInfo;
-   }
-   else {
-      sbInfoDest = &tnsDataDest->dataRaw.tnsShort.subBlockInfo[subBlockNumber];
-      sbInfoSrc  = &tnsDataSrc->dataRaw.tnsShort.subBlockInfo[subBlockNumber];
-   }
-
-   if (100*abs_s(sbInfoDest->predictionGain - sbInfoSrc->predictionGain) <
-       (3 * sbInfoDest->predictionGain)) {
-      sbInfoDest->tnsActive = sbInfoSrc->tnsActive;
-      for ( i=0; i< tC.maxOrder; i++) {
-        sbInfoDest->parcor[i] = sbInfoSrc->parcor[i];
-      }
-   }
-}
-
-/*****************************************************************************
-*
-* function name: TnsEncode
-* description: do TNS filtering
-* returns:     0 if success
-*
-*****************************************************************************/
-Word16 TnsEncode(TNS_INFO* tnsInfo,     /*!< tns info structure (modified) */
-                 TNS_DATA* tnsData,     /*!< tns data structure (modified) */
-                 Word16 numOfSfb,       /*!< number of scale factor bands */
-                 TNS_CONFIG tC,         /*!< tns config structure */
-                 Word16 lowPassLine,    /*!< lowpass line */
-                 Word32* spectrum,      /*!< spectral data (modified) */
-                 Word16 subBlockNumber, /*!< subblock num */
-                 Word16 blockType)      /*!< blocktype (long or short) */
-{
-  Word32 i;
-  Word32 temp_s;
-  Word32 temp;
-  TNS_SUBBLOCK_INFO *psubBlockInfo;
-
-  temp_s = blockType - SHORT_WINDOW;
-  if ( temp_s != 0) {
-    psubBlockInfo = &tnsData->dataRaw.tnsLong.subBlockInfo;
-	if (psubBlockInfo->tnsActive == 0) {
-      tnsInfo->tnsActive[subBlockNumber] = 0;
-      return(0);
-    }
-    else {
-
-      Parcor2Index(psubBlockInfo->parcor,
-                   tnsInfo->coef,
-                   tC.maxOrder,
-                   tC.coefRes);
-
-      Index2Parcor(tnsInfo->coef,
-                   psubBlockInfo->parcor,
-                   tC.maxOrder,
-                   tC.coefRes);
-
-      for (i=tC.maxOrder - 1; i>=0; i--)  {
-        temp = psubBlockInfo->parcor[i] - TNS_PARCOR_THRESH;
-        if ( temp > 0 )
-          break;
-        temp = psubBlockInfo->parcor[i] + TNS_PARCOR_THRESH;
-        if ( temp < 0 )
-          break;
-      }
-      tnsInfo->order[subBlockNumber] = i + 1;
-
-
-      tnsInfo->tnsActive[subBlockNumber] = 1;
-      for (i=subBlockNumber+1; i<TRANS_FAC; i++) {
-        tnsInfo->tnsActive[i] = 0;
-      }
-      tnsInfo->coefRes[subBlockNumber] = tC.coefRes;
-      tnsInfo->length[subBlockNumber] = numOfSfb - tC.tnsStartBand;
-
-
-      AnalysisFilterLattice(&(spectrum[tC.tnsStartLine]),
-                            (min(tC.tnsStopLine,lowPassLine) - tC.tnsStartLine),
-                            psubBlockInfo->parcor,
-                            tnsInfo->order[subBlockNumber],
-                            &(spectrum[tC.tnsStartLine]));
-
-    }
-  }     /* if (blockType!=SHORT_WINDOW) */
-  else /*short block*/ {
-    psubBlockInfo = &tnsData->dataRaw.tnsShort.subBlockInfo[subBlockNumber];
-	if (psubBlockInfo->tnsActive == 0) {
-      tnsInfo->tnsActive[subBlockNumber] = 0;
-      return(0);
-    }
-    else {
-
-      Parcor2Index(psubBlockInfo->parcor,
-                   &tnsInfo->coef[subBlockNumber*TNS_MAX_ORDER_SHORT],
-                   tC.maxOrder,
-                   tC.coefRes);
-
-      Index2Parcor(&tnsInfo->coef[subBlockNumber*TNS_MAX_ORDER_SHORT],
-                   psubBlockInfo->parcor,
-                   tC.maxOrder,
-                   tC.coefRes);
-      for (i=(tC.maxOrder - 1); i>=0; i--)  {
-        temp = psubBlockInfo->parcor[i] - TNS_PARCOR_THRESH;
-         if ( temp > 0 )
-          break;
-
-        temp = psubBlockInfo->parcor[i] + TNS_PARCOR_THRESH;
-        if ( temp < 0 )
-          break;
-      }
-      tnsInfo->order[subBlockNumber] = i + 1;
-
-      tnsInfo->tnsActive[subBlockNumber] = 1;
-      tnsInfo->coefRes[subBlockNumber] = tC.coefRes;
-      tnsInfo->length[subBlockNumber] = numOfSfb - tC.tnsStartBand;
-
-
-      AnalysisFilterLattice(&(spectrum[tC.tnsStartLine]), (tC.tnsStopLine - tC.tnsStartLine),
-                 psubBlockInfo->parcor,
-                 tnsInfo->order[subBlockNumber],
-                 &(spectrum[tC.tnsStartLine]));
-
-    }
-  }
-
-  return(0);
-}
-
-
-/*****************************************************************************
-*
-* function name: CalcWeightedSpectrum
-* description: Calculate weighted spectrum for LPC calculation
-*
-*****************************************************************************/
-static void CalcWeightedSpectrum(const Word32  spectrum[],         /*!< input spectrum */
-                                 Word16        weightedSpectrum[],
-                                 Word32       *sfbEnergy,          /*!< sfb energies */
-                                 const Word16 *sfbOffset,
-                                 Word16        lpcStartLine,
-                                 Word16        lpcStopLine,
-                                 Word16        lpcStartBand,
-                                 Word16        lpcStopBand,
-                                 Word32       *pWork32)
-{
-    #define INT_BITS_SCAL 1<<(INT_BITS/2)
-
-    Word32 i, sfb, shift;
-    Word32 maxShift;
-    Word32 tmp_s, tmp2_s;
-    Word32 tmp, tmp2;
-    Word32 maxWS;
-    Word32 tnsSfbMean[MAX_SFB];    /* length [lpcStopBand-lpcStartBand] should be sufficient here */
-
-    maxWS = 0;
-
-    /* calc 1.0*2^-INT_BITS/2/sqrt(en) */
-    for( sfb = lpcStartBand; sfb < lpcStopBand; sfb++) {
-
-      tmp2 = sfbEnergy[sfb] - 2;
-      if( tmp2 > 0) {
-        tmp = rsqrt(sfbEnergy[sfb], INT_BITS);
-		if(tmp > INT_BITS_SCAL)
-		{
-			shift =  norm_l(tmp);
-			tmp = Div_32( INT_BITS_SCAL << shift, tmp << shift );
-		}
-		else
-		{
-			tmp = 0x7fffffff;
-		}
-      }
-      else {
-        tmp = 0x7fffffff;
-      }
-      tnsSfbMean[sfb] = tmp;
-    }
-
-    /* spread normalized values from sfbs to lines */
-    sfb = lpcStartBand;
-    tmp = tnsSfbMean[sfb];
-    for ( i=lpcStartLine; i<lpcStopLine; i++){
-      tmp_s = sfbOffset[sfb + 1] - i;
-      if ( tmp_s == 0 ) {
-        sfb = sfb + 1;
-        tmp2_s = sfb + 1 - lpcStopBand;
-        if (tmp2_s <= 0) {
-          tmp = tnsSfbMean[sfb];
-        }
-      }
-      pWork32[i] = tmp;
-    }
-    /*filter down*/
-    for (i=(lpcStopLine - 2); i>=lpcStartLine; i--){
-        pWork32[i] = (pWork32[i] + pWork32[i + 1]) >> 1;
-    }
-    /* filter up */
-    for (i=(lpcStartLine + 1); i<lpcStopLine; i++){
-       pWork32[i] = (pWork32[i] + pWork32[i - 1]) >> 1;
-    }
-
-    /* weight and normalize */
-    for (i=lpcStartLine; i<lpcStopLine; i++){
-      pWork32[i] = MULHIGH(pWork32[i], spectrum[i]);
-      maxWS |= L_abs(pWork32[i]);
-    }
-    maxShift = norm_l(maxWS);
-
-	maxShift = 16 - maxShift;
-    if(maxShift >= 0)
-	{
-		for (i=lpcStartLine; i<lpcStopLine; i++){
-			weightedSpectrum[i] = pWork32[i] >> maxShift;
-		}
-    }
-	else
-	{
-		maxShift = -maxShift;
-		for (i=lpcStartLine; i<lpcStopLine; i++){
-			weightedSpectrum[i] = saturate(pWork32[i] << maxShift);
-		}
-	}
-}
-
-
-
-
-/*****************************************************************************
-*
-* function name: CalcTnsFilter
-* description:  LPC calculation for one TNS filter
-* returns:      prediction gain
-* input:        signal spectrum, acf window, no. of spectral lines,
-*                max. TNS order, ptr. to reflection ocefficients
-* output:       reflection coefficients
-*(half) window size must be larger than tnsOrder !!*
-******************************************************************************/
-
-static Word16 CalcTnsFilter(const Word16 *signal,
-                            const Word32 window[],
-                            Word16 numOfLines,
-                            Word16 tnsOrder,
-                            Word32 parcor[])
-{
-  Word32 parcorWorkBuffer[2*TNS_MAX_ORDER+1];
-  Word32 predictionGain;
-  Word32 i;
-  Word32 tnsOrderPlus1 = tnsOrder + 1;
-
-  UNUSED(window);
-
-  assert(tnsOrder <= TNS_MAX_ORDER);      /* remove asserts later? (btg) */
-
-  for(i=0;i<tnsOrder;i++) {
-    parcor[i] = 0;
-  }
-
-  AutoCorrelation(signal, parcorWorkBuffer, numOfLines, tnsOrderPlus1);
-
-  /* early return if signal is very low: signal prediction off, with zero parcor coeffs */
-  if (parcorWorkBuffer[0] == 0)
-    return 0;
-
-  predictionGain = AutoToParcor(parcorWorkBuffer, parcor, tnsOrder);
-
-  return(predictionGain);
-}
-
-/*****************************************************************************
-*
-* function name: AutoCorrelation
-* description:  calc. autocorrelation (acf)
-* returns:      -
-* input:        input values, no. of input values, no. of acf values
-* output:       acf values
-*
-*****************************************************************************/
-#ifndef ARMV5E
-void AutoCorrelation(const Word16		 input[],
-                            Word32       corr[],
-                            Word16       samples,
-                            Word16       corrCoeff) {
-  Word32 i, j, isamples;
-  Word32 accu;
-  Word32 scf;
-
-  scf = 10 - 1;
-
-  isamples = samples;
-  /* calc first corrCoef:  R[0] = sum { t[i] * t[i] } ; i = 0..N-1 */
-  accu = 0;
-  for(j=0; j<isamples; j++) {
-    accu = L_add(accu, ((input[j] * input[j]) >> scf));
-  }
-  corr[0] = accu;
-
-  /* early termination if all corr coeffs are likely going to be zero */
-  if(corr[0] == 0) return ;
-
-  /* calc all other corrCoef:  R[j] = sum { t[i] * t[i+j] } ; i = 0..(N-j-1), j=1..p */
-  for(i=1; i<corrCoeff; i++) {
-    isamples = isamples - 1;
-    accu = 0;
-    for(j=0; j<isamples; j++) {
-      accu = L_add(accu, ((input[j] * input[j+i]) >> scf));
-    }
-    corr[i] = accu;
-  }
-}
-#endif
-
-/*****************************************************************************
-*
-* function name: AutoToParcor
-* description:  conversion autocorrelation to reflection coefficients
-* returns:      prediction gain
-* input:        <order+1> input values, no. of output values (=order),
-*               ptr. to workbuffer (required size: 2*order)
-* output:       <order> reflection coefficients
-*
-*****************************************************************************/
-static Word16 AutoToParcor(Word32 workBuffer[], Word32 reflCoeff[], Word16 numOfCoeff) {
-
-  Word32 i, j, shift;
-  Word32 *pWorkBuffer; /* temp pointer */
-  Word32 predictionGain = 0;
-  Word32 num, denom;
-  Word32 temp, workBuffer0;
-
-
-  num = workBuffer[0];
-  temp = workBuffer[numOfCoeff];
-
-  for(i=0; i<numOfCoeff-1; i++) {
-    workBuffer[i + numOfCoeff] = workBuffer[i + 1];
-  }
-  workBuffer[i + numOfCoeff] = temp;
-
-  for(i=0; i<numOfCoeff; i++) {
-    Word32 refc;
-
-
-    if (workBuffer[0] < L_abs(workBuffer[i + numOfCoeff])) {
-      return 0 ;
-    }
-	shift = norm_l(workBuffer[0]);
-	workBuffer0 = Div_32(1 << shift, workBuffer[0] << shift);
-    /* calculate refc = -workBuffer[numOfCoeff+i] / workBuffer[0]; -1 <= refc < 1 */
-	refc = L_negate(fixmul(workBuffer[numOfCoeff + i], workBuffer0));
-
-    reflCoeff[i] = refc;
-
-    pWorkBuffer = &(workBuffer[numOfCoeff]);
-
-    for(j=i; j<numOfCoeff; j++) {
-      Word32 accu1, accu2;
-      accu1 = L_add(pWorkBuffer[j], fixmul(refc, workBuffer[j - i]));
-      accu2 = L_add(workBuffer[j - i], fixmul(refc, pWorkBuffer[j]));
-      pWorkBuffer[j] = accu1;
-      workBuffer[j - i] = accu2;
-    }
-  }
-
-  denom = MULHIGH(workBuffer[0], NORM_COEF);
-
-  if (denom != 0) {
-    Word32 temp;
-	shift = norm_l(denom);
-	temp = Div_32(1 << shift, denom << shift);
-    predictionGain = fixmul(num, temp);
-  }
-
-  return extract_l(predictionGain);
-}
-
-
-
-static Word16 Search3(Word32 parcor)
-{
-  Word32 index = 0;
-  Word32 i;
-  Word32 temp;
-
-  for (i=0;i<8;i++) {
-    temp = L_sub( parcor, tnsCoeff3Borders[i]);
-    if (temp > 0)
-      index=i;
-  }
-  return extract_l(index - 4);
-}
-
-static Word16 Search4(Word32 parcor)
-{
-  Word32 index = 0;
-  Word32 i;
-  Word32 temp;
-
-
-  for (i=0;i<16;i++) {
-    temp = L_sub(parcor, tnsCoeff4Borders[i]);
-    if (temp > 0)
-      index=i;
-  }
-  return extract_l(index - 8);
-}
-
-
-
-/*****************************************************************************
-*
-* functionname: Parcor2Index
-* description:  quantization index for reflection coefficients
-*
-*****************************************************************************/
-static void Parcor2Index(const Word32 parcor[],   /*!< parcor coefficients */
-                         Word16 index[],          /*!< quantized coeff indices */
-                         Word16 order,            /*!< filter order */
-                         Word16 bitsPerCoeff) {   /*!< quantizer resolution */
-  Word32 i;
-  Word32 temp;
-
-  for(i=0; i<order; i++) {
-    temp = bitsPerCoeff - 3;
-    if (temp == 0) {
-      index[i] = Search3(parcor[i]);
-    }
-    else {
-      index[i] = Search4(parcor[i]);
-    }
-  }
-}
-
-/*****************************************************************************
-*
-* functionname: Index2Parcor
-* description:  Inverse quantization for reflection coefficients
-*
-*****************************************************************************/
-static void Index2Parcor(const Word16 index[],  /*!< quantized values */
-                         Word32 parcor[],       /*!< ptr. to reflection coefficients (output) */
-                         Word16 order,          /*!< no. of coefficients */
-                         Word16 bitsPerCoeff)   /*!< quantizer resolution */
-{
-  Word32 i;
-  Word32 temp;
-
-  for (i=0; i<order; i++) {
-    temp = bitsPerCoeff - 4;
-    if ( temp == 0 ) {
-        parcor[i] = tnsCoeff4[index[i] + 8];
-    }
-    else {
-        parcor[i] = tnsCoeff3[index[i] + 4];
-    }
-  }
-}
-
-/*****************************************************************************
-*
-* functionname: FIRLattice
-* description:  in place lattice filtering of spectral data
-* returns:		pointer to modified data
-*
-*****************************************************************************/
-static Word32 FIRLattice(Word16 order,           /*!< filter order */
-                         Word32 x,               /*!< spectral data */
-                         Word32 *state_par,      /*!< filter states */
-                         const Word32 *coef_par) /*!< filter coefficients */
-{
-   Word32 i;
-   Word32 accu,tmp,tmpSave;
-
-   x = x >> 1;
-   tmpSave = x;
-
-   for (i=0; i<(order - 1); i++) {
-
-     tmp = L_add(fixmul(coef_par[i], x), state_par[i]);
-     x   = L_add(fixmul(coef_par[i], state_par[i]), x);
-
-     state_par[i] = tmpSave;
-     tmpSave = tmp;
-  }
-
-  /* last stage: only need half operations */
-  accu = fixmul(state_par[order - 1], coef_par[(order - 1)]);
-  state_par[(order - 1)] = tmpSave;
-
-  x = L_add(accu, x);
-  x = L_add(x, x);
-
-  return x;
-}
-
-/*****************************************************************************
-*
-* functionname: AnalysisFilterLattice
-* description:  filters spectral lines with TNS filter
-*
-*****************************************************************************/
-static void AnalysisFilterLattice(const  Word32 signal[],  /*!< input spectrum */
-                                  Word16 numOfLines,       /*!< no. of lines */
-                                  const  Word32 parCoeff[],/*!< PARC coefficients */
-                                  Word16 order,            /*!< filter order */
-                                  Word32 output[])         /*!< filtered signal values */
-{
-
-  Word32 state_par[TNS_MAX_ORDER];
-  Word32 j;
-
-  for ( j=0; j<TNS_MAX_ORDER; j++ ) {
-    state_par[j] = 0;
-  }
-
-  for(j=0; j<numOfLines; j++) {
-    output[j] = FIRLattice(order,signal[j],state_par,parCoeff);
-  }
-}
-
-/*****************************************************************************
-*
-* functionname: ApplyTnsMultTableToRatios
-* description:  Change thresholds according to tns
-*
-*****************************************************************************/
-void ApplyTnsMultTableToRatios(Word16 startCb,
-                               Word16 stopCb,
-                               TNS_SUBBLOCK_INFO subInfo, /*!< TNS subblock info */
-                               Word32 *thresholds)        /*!< thresholds (modified) */
-{
-  Word32 i;
-  if (subInfo.tnsActive) {
-    for(i=startCb; i<stopCb; i++) {
-      /* thresholds[i] * 0.25 */
-      thresholds[i] = (thresholds[i] >> 2);
-    }
-  }
-}
diff --git a/media/libstagefright/codecs/aacenc/src/transform.c b/media/libstagefright/codecs/aacenc/src/transform.c
deleted file mode 100644
index 5de2b96..0000000
--- a/media/libstagefright/codecs/aacenc/src/transform.c
+++ /dev/null
@@ -1,677 +0,0 @@
-/*
- ** Copyright 2003-2010, VisualOn, Inc.
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- **     http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT 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:		transform.c
-
-	Content:	MDCT Transform functionss
-
-*******************************************************************************/
-
-#include "basic_op.h"
-#include "psy_const.h"
-#include "transform.h"
-#include "aac_rom.h"
-
-
-#define LS_TRANS ((FRAME_LEN_LONG-FRAME_LEN_SHORT)/2) /* 448 */
-#define SQRT1_2 0x5a82799a	/* sqrt(1/2) in Q31 */
-#define swap2(p0,p1) \
-	t = p0; t1 = *(&(p0)+1);	\
-	(p0) = p1; *(&(p0)+1) = *(&(p1)+1);	\
-	(p1) = t; *(&(p1)+1) = t1
-
-/*********************************************************************************
-*
-* function name: Shuffle
-* description:  Shuffle points prepared function for fft
-*
-**********************************************************************************/
-static void Shuffle(int *buf, int num, const unsigned char* bitTab)
-{
-    int *part0, *part1;
-	int i, j;
-	int t, t1;
-
-	part0 = buf;
-    part1 = buf + num;
-
-	while ((i = *bitTab++) != 0) {
-        j = *bitTab++;
-
-        swap2(part0[4*i+0], part0[4*j+0]);
-        swap2(part0[4*i+2], part1[4*j+0]);
-        swap2(part1[4*i+0], part0[4*j+2]);
-        swap2(part1[4*i+2], part1[4*j+2]);
-    }
-
-    do {
-        swap2(part0[4*i+2], part1[4*i+0]);
-    } while ((i = *bitTab++) != 0);
-}
-
-#if !defined(ARMV5E) && !defined(ARMV7Neon)
-
-/*****************************************************************************
-*
-* function name: Radix4First
-* description:  Radix 4 point prepared function for fft
-*
-**********************************************************************************/
-static void Radix4First(int *buf, int num)
-{
-    int r0, r1, r2, r3;
-	int r4, r5, r6, r7;
-
-	for (; num != 0; num--)
-	{
-		r0 = buf[0] + buf[2];
-		r1 = buf[1] + buf[3];
-		r2 = buf[0] - buf[2];
-		r3 = buf[1] - buf[3];
-		r4 = buf[4] + buf[6];
-		r5 = buf[5] + buf[7];
-		r6 = buf[4] - buf[6];
-		r7 = buf[5] - buf[7];
-
-		buf[0] = r0 + r4;
-		buf[1] = r1 + r5;
-		buf[4] = r0 - r4;
-		buf[5] = r1 - r5;
-		buf[2] = r2 + r7;
-		buf[3] = r3 - r6;
-		buf[6] = r2 - r7;
-		buf[7] = r3 + r6;
-
-		buf += 8;
-	}
-}
-
-/*****************************************************************************
-*
-* function name: Radix8First
-* description:  Radix 8 point prepared function for fft
-*
-**********************************************************************************/
-static void Radix8First(int *buf, int num)
-{
-   int r0, r1, r2, r3;
-   int i0, i1, i2, i3;
-   int r4, r5, r6, r7;
-   int i4, i5, i6, i7;
-   int t0, t1, t2, t3;
-
-	for ( ; num != 0; num--)
-	{
-		r0 = buf[0] + buf[2];
-		i0 = buf[1] + buf[3];
-		r1 = buf[0] - buf[2];
-		i1 = buf[1] - buf[3];
-		r2 = buf[4] + buf[6];
-		i2 = buf[5] + buf[7];
-		r3 = buf[4] - buf[6];
-		i3 = buf[5] - buf[7];
-
-		r4 = (r0 + r2) >> 1;
-		i4 = (i0 + i2) >> 1;
-		r5 = (r0 - r2) >> 1;
-		i5 = (i0 - i2) >> 1;
-		r6 = (r1 - i3) >> 1;
-		i6 = (i1 + r3) >> 1;
-		r7 = (r1 + i3) >> 1;
-		i7 = (i1 - r3) >> 1;
-
-		r0 = buf[ 8] + buf[10];
-		i0 = buf[ 9] + buf[11];
-		r1 = buf[ 8] - buf[10];
-		i1 = buf[ 9] - buf[11];
-		r2 = buf[12] + buf[14];
-		i2 = buf[13] + buf[15];
-		r3 = buf[12] - buf[14];
-		i3 = buf[13] - buf[15];
-
-		t0 = (r0 + r2) >> 1;
-		t1 = (i0 + i2) >> 1;
-		t2 = (r0 - r2) >> 1;
-		t3 = (i0 - i2) >> 1;
-
-		buf[ 0] = r4 + t0;
-		buf[ 1] = i4 + t1;
-		buf[ 8] = r4 - t0;
-		buf[ 9] = i4 - t1;
-		buf[ 4] = r5 + t3;
-		buf[ 5] = i5 - t2;
-		buf[12] = r5 - t3;
-		buf[13] = i5 + t2;
-
-		r0 = r1 - i3;
-		i0 = i1 + r3;
-		r2 = r1 + i3;
-		i2 = i1 - r3;
-
-		t0 = MULHIGH(SQRT1_2, r0 - i0);
-		t1 = MULHIGH(SQRT1_2, r0 + i0);
-		t2 = MULHIGH(SQRT1_2, r2 - i2);
-		t3 = MULHIGH(SQRT1_2, r2 + i2);
-
-		buf[ 6] = r6 - t0;
-		buf[ 7] = i6 - t1;
-		buf[14] = r6 + t0;
-		buf[15] = i6 + t1;
-		buf[ 2] = r7 + t3;
-		buf[ 3] = i7 - t2;
-		buf[10] = r7 - t3;
-		buf[11] = i7 + t2;
-
-		buf += 16;
-	}
-}
-
-/*****************************************************************************
-*
-* function name: Radix4FFT
-* description:  Radix 4 point fft core function
-*
-**********************************************************************************/
-static void Radix4FFT(int *buf, int num, int bgn, int *twidTab)
-{
-	int r0, r1, r2, r3;
-	int r4, r5, r6, r7;
-	int t0, t1;
-	int sinx, cosx;
-	int i, j, step;
-	int *xptr, *csptr;
-
-	for (num >>= 2; num != 0; num >>= 2)
-	{
-		step = 2*bgn;
-		xptr = buf;
-
-    	for (i = num; i != 0; i--)
-		{
-			csptr = twidTab;
-
-			for (j = bgn; j != 0; j--)
-			{
-				r0 = xptr[0];
-				r1 = xptr[1];
-				xptr += step;
-
-				t0 = xptr[0];
-				t1 = xptr[1];
-				cosx = csptr[0];
-				sinx = csptr[1];
-				r2 = MULHIGH(cosx, t0) + MULHIGH(sinx, t1);		/* cos*br + sin*bi */
-				r3 = MULHIGH(cosx, t1) - MULHIGH(sinx, t0);		/* cos*bi - sin*br */
-				xptr += step;
-
-				t0 = r0 >> 2;
-				t1 = r1 >> 2;
-				r0 = t0 - r2;
-				r1 = t1 - r3;
-				r2 = t0 + r2;
-				r3 = t1 + r3;
-
-				t0 = xptr[0];
-				t1 = xptr[1];
-				cosx = csptr[2];
-				sinx = csptr[3];
-				r4 = MULHIGH(cosx, t0) + MULHIGH(sinx, t1);		/* cos*cr + sin*ci */
-				r5 = MULHIGH(cosx, t1) - MULHIGH(sinx, t0);		/* cos*ci - sin*cr */
-				xptr += step;
-
-				t0 = xptr[0];
-				t1 = xptr[1];
-				cosx = csptr[4];
-				sinx = csptr[5];
-				r6 = MULHIGH(cosx, t0) + MULHIGH(sinx, t1);		/* cos*cr + sin*ci */
-				r7 = MULHIGH(cosx, t1) - MULHIGH(sinx, t0);		/* cos*ci - sin*cr */
-				csptr += 6;
-
-				t0 = r4;
-				t1 = r5;
-				r4 = t0 + r6;
-				r5 = r7 - t1;
-				r6 = t0 - r6;
-				r7 = r7 + t1;
-
-				xptr[0] = r0 + r5;
-				xptr[1] = r1 + r6;
-				xptr -= step;
-
-				xptr[0] = r2 - r4;
-				xptr[1] = r3 - r7;
-				xptr -= step;
-
-				xptr[0] = r0 - r5;
-				xptr[1] = r1 - r6;
-				xptr -= step;
-
-				xptr[0] = r2 + r4;
-				xptr[1] = r3 + r7;
-				xptr += 2;
-			}
-			xptr += 3*step;
-		}
-		twidTab += 3*step;
-		bgn <<= 2;
-	}
-}
-
-/*********************************************************************************
-*
-* function name: PreMDCT
-* description:  prepare MDCT process for next FFT compute
-*
-**********************************************************************************/
-static void PreMDCT(int *buf0, int num, const int *csptr)
-{
-	int i;
-	int tr1, ti1, tr2, ti2;
-	int cosa, sina, cosb, sinb;
-	int *buf1;
-
-	buf1 = buf0 + num - 1;
-
-	for(i = num >> 2; i != 0; i--)
-	{
-		cosa = *csptr++;
-		sina = *csptr++;
-		cosb = *csptr++;
-		sinb = *csptr++;
-
-		tr1 = *(buf0 + 0);
-		ti2 = *(buf0 + 1);
-		tr2 = *(buf1 - 1);
-		ti1 = *(buf1 + 0);
-
-		*buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1);
-		*buf0++ = MULHIGH(cosa, ti1) - MULHIGH(sina, tr1);
-
-		*buf1-- = MULHIGH(cosb, ti2) - MULHIGH(sinb, tr2);
-		*buf1-- = MULHIGH(cosb, tr2) + MULHIGH(sinb, ti2);
-	}
-}
-
-/*********************************************************************************
-*
-* function name: PostMDCT
-* description:   post MDCT process after next FFT for MDCT
-*
-**********************************************************************************/
-static void PostMDCT(int *buf0, int num, const int *csptr)
-{
-	int i;
-	int tr1, ti1, tr2, ti2;
-	int cosa, sina, cosb, sinb;
-	int *buf1;
-
-	buf1 = buf0 + num - 1;
-
-	for(i = num >> 2; i != 0; i--)
-	{
-		cosa = *csptr++;
-		sina = *csptr++;
-		cosb = *csptr++;
-		sinb = *csptr++;
-
-		tr1 = *(buf0 + 0);
-		ti1 = *(buf0 + 1);
-		ti2 = *(buf1 + 0);
-		tr2 = *(buf1 - 1);
-
-		*buf0++ = MULHIGH(cosa, tr1) + MULHIGH(sina, ti1);
-		*buf1-- = MULHIGH(sina, tr1) - MULHIGH(cosa, ti1);
-
-		*buf0++ = MULHIGH(sinb, tr2) - MULHIGH(cosb, ti2);
-		*buf1-- = MULHIGH(cosb, tr2) + MULHIGH(sinb, ti2);
-	}
-}
-#else
-void Radix4First(int *buf, int num);
-void Radix8First(int *buf, int num);
-void Radix4FFT(int *buf, int num, int bgn, int *twidTab);
-void PreMDCT(int *buf0, int num, const int *csptr);
-void PostMDCT(int *buf0, int num, const int *csptr);
-#endif
-
-
-/**********************************************************************************
-*
-* function name: Mdct_Long
-* description:  the long block mdct, include long_start block, end_long block
-*
-**********************************************************************************/
-void Mdct_Long(int *buf)
-{
-	PreMDCT(buf, 1024, cossintab + 128);
-
-	Shuffle(buf, 512, bitrevTab + 17);
-	Radix8First(buf, 512 >> 3);
-	Radix4FFT(buf, 512 >> 3, 8, (int *)twidTab512);
-
-	PostMDCT(buf, 1024, cossintab + 128);
-}
-
-
-/**********************************************************************************
-*
-* function name: Mdct_Short
-* description:  the short block mdct
-*
-**********************************************************************************/
-void Mdct_Short(int *buf)
-{
-	PreMDCT(buf, 128, cossintab);
-
-	Shuffle(buf, 64, bitrevTab);
-	Radix4First(buf, 64 >> 2);
-	Radix4FFT(buf, 64 >> 2, 4, (int *)twidTab64);
-
-	PostMDCT(buf, 128, cossintab);
-}
-
-
-/*****************************************************************************
-*
-* function name: shiftMdctDelayBuffer
-* description:    the mdct delay buffer has a size of 1600,
-*  so the calculation of LONG,STOP must be  spilt in two
-*  passes with 1024 samples and a mid shift,
-*  the SHORT transforms can be completed in the delay buffer,
-*  and afterwards a shift
-*
-**********************************************************************************/
-static void shiftMdctDelayBuffer(Word16 *mdctDelayBuffer, /*! start of mdct delay buffer */
-								 Word16 *timeSignal,      /*! pointer to new time signal samples, interleaved */
-								 Word16 chIncrement       /*! number of channels */
-								 )
-{
-	Word32 i;
-	Word16 *srBuf = mdctDelayBuffer;
-	Word16 *dsBuf = mdctDelayBuffer+FRAME_LEN_LONG;
-
-	for(i = 0; i < BLOCK_SWITCHING_OFFSET-FRAME_LEN_LONG; i+= 8)
-	{
-		*srBuf++ = *dsBuf++;	 *srBuf++ = *dsBuf++;
-		*srBuf++ = *dsBuf++;	 *srBuf++ = *dsBuf++;
-		*srBuf++ = *dsBuf++;	 *srBuf++ = *dsBuf++;
-		*srBuf++ = *dsBuf++;	 *srBuf++ = *dsBuf++;
-	}
-
-	srBuf = mdctDelayBuffer + BLOCK_SWITCHING_OFFSET-FRAME_LEN_LONG;
-	dsBuf = timeSignal;
-
-	for(i=0; i<FRAME_LEN_LONG; i+=8)
-	{
-		*srBuf++ = *dsBuf; dsBuf += chIncrement;
-		*srBuf++ = *dsBuf; dsBuf += chIncrement;
-		*srBuf++ = *dsBuf; dsBuf += chIncrement;
-		*srBuf++ = *dsBuf; dsBuf += chIncrement;
-		*srBuf++ = *dsBuf; dsBuf += chIncrement;
-		*srBuf++ = *dsBuf; dsBuf += chIncrement;
-		*srBuf++ = *dsBuf; dsBuf += chIncrement;
-		*srBuf++ = *dsBuf; dsBuf += chIncrement;
-	}
-}
-
-
-/*****************************************************************************
-*
-* function name: getScalefactorOfShortVectorStride
-* description:  Calculate max possible scale factor for input vector of shorts
-* returns:      Maximum scale factor
-*
-**********************************************************************************/
-static Word16 getScalefactorOfShortVectorStride(const Word16 *vector, /*!< Pointer to input vector */
-												Word16 len,           /*!< Length of input vector */
-												Word16 stride)        /*!< Stride of input vector */
-{
-	Word16 maxVal = 0;
-	Word16 absVal;
-	Word16 i;
-
-	for(i=0; i<len; i++){
-		absVal = abs_s(vector[i*stride]);
-		maxVal |= absVal;
-	}
-
-	return( maxVal ? norm_s(maxVal) : 15);
-}
-
-
-/*****************************************************************************
-*
-* function name: Transform_Real
-* description:  Calculate transform filter for input vector of shorts
-* returns:      TRUE if success
-*
-**********************************************************************************/
-void Transform_Real(Word16 *mdctDelayBuffer,
-                    Word16 *timeSignal,
-                    Word16 chIncrement,
-                    Word32 *realOut,
-                    Word16 *mdctScale,
-                    Word16 blockType
-                    )
-{
-	Word32 i,w;
-	Word32 timeSignalSample;
-	Word32 ws1,ws2;
-	Word16 *dctIn0, *dctIn1;
-	Word32 *outData0, *outData1;
-	Word32 *winPtr;
-
-	Word32 delayBufferSf,timeSignalSf,minSf;
-
-	switch(blockType){
-
-
-	case LONG_WINDOW:
-		/*
-		we access BLOCK_SWITCHING_OFFSET (1600 ) delay buffer samples + 448 new timeSignal samples
-		and get the biggest scale factor for next calculate more precise
-		*/
-		delayBufferSf = getScalefactorOfShortVectorStride(mdctDelayBuffer,BLOCK_SWITCHING_OFFSET,1);
-		timeSignalSf  = getScalefactorOfShortVectorStride(timeSignal,2*FRAME_LEN_LONG-BLOCK_SWITCHING_OFFSET,chIncrement);
-		minSf = min(delayBufferSf,timeSignalSf);
-		minSf = min(minSf,14);
-
-		dctIn0 = mdctDelayBuffer;
-		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
-		outData0 = realOut + FRAME_LEN_LONG/2;
-
-		/* add windows and pre add for mdct to last buffer*/
-		winPtr = (int *)LongWindowKBD;
-		for(i=0;i<FRAME_LEN_LONG/2;i++){
-			timeSignalSample = (*dctIn0++) << minSf;
-			ws1 = timeSignalSample * (*winPtr >> 16);
-			timeSignalSample = (*dctIn1--) << minSf;
-			ws2 = timeSignalSample * (*winPtr & 0xffff);
-			winPtr ++;
-			/* shift 2 to avoid overflow next */
-			*outData0++ = (ws1 >> 2) - (ws2 >> 2);
-		}
-
-		shiftMdctDelayBuffer(mdctDelayBuffer,timeSignal,chIncrement);
-
-		/* add windows and pre add for mdct to new buffer*/
-		dctIn0 = mdctDelayBuffer;
-		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
-		outData0 = realOut + FRAME_LEN_LONG/2 - 1;
-		winPtr = (int *)LongWindowKBD;
-		for(i=0;i<FRAME_LEN_LONG/2;i++){
-			timeSignalSample = (*dctIn0++) << minSf;
-			ws1 = timeSignalSample * (*winPtr & 0xffff);
-			timeSignalSample = (*dctIn1--) << minSf;
-			ws2 = timeSignalSample * (*winPtr >> 16);
-			winPtr++;
-			/* shift 2 to avoid overflow next */
-			*outData0-- = -((ws1 >> 2) + (ws2 >> 2));
-		}
-
-		Mdct_Long(realOut);
-		/* update scale factor */
-		minSf = 14 - minSf;
-		*mdctScale=minSf;
-		break;
-
-	case START_WINDOW:
-		/*
-		we access BLOCK_SWITCHING_OFFSET (1600 ) delay buffer samples + no timeSignal samples
-		and get the biggest scale factor for next calculate more precise
-		*/
-		minSf = getScalefactorOfShortVectorStride(mdctDelayBuffer,BLOCK_SWITCHING_OFFSET,1);
-		minSf = min(minSf,14);
-
-		dctIn0 = mdctDelayBuffer;
-		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
-		outData0 = realOut + FRAME_LEN_LONG/2;
-		winPtr = (int *)LongWindowKBD;
-
-		/* add windows and pre add for mdct to last buffer*/
-		for(i=0;i<FRAME_LEN_LONG/2;i++){
-			timeSignalSample = (*dctIn0++) << minSf;
-			ws1 = timeSignalSample * (*winPtr >> 16);
-			timeSignalSample = (*dctIn1--) << minSf;
-			ws2 = timeSignalSample * (*winPtr & 0xffff);
-			winPtr ++;
-			*outData0++ = (ws1 >> 2) - (ws2 >> 2);  /* shift 2 to avoid overflow next */
-		}
-
-		shiftMdctDelayBuffer(mdctDelayBuffer,timeSignal,chIncrement);
-
-		outData0 = realOut + FRAME_LEN_LONG/2 - 1;
-		for(i=0;i<LS_TRANS;i++){
-			*outData0-- = -mdctDelayBuffer[i] << (15 - 2 + minSf);
-		}
-
-		/* add windows and pre add for mdct to new buffer*/
-		dctIn0 = mdctDelayBuffer + LS_TRANS;
-		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1 - LS_TRANS;
-		outData0 = realOut + FRAME_LEN_LONG/2 - 1 -LS_TRANS;
-		winPtr = (int *)ShortWindowSine;
-		for(i=0;i<FRAME_LEN_SHORT/2;i++){
-			timeSignalSample= (*dctIn0++) << minSf;
-			ws1 = timeSignalSample * (*winPtr & 0xffff);
-			timeSignalSample= (*dctIn1--) << minSf;
-			ws2 = timeSignalSample * (*winPtr >> 16);
-			winPtr++;
-			*outData0-- =  -((ws1 >> 2) + (ws2 >> 2));  /* shift 2 to avoid overflow next */
-		}
-
-		Mdct_Long(realOut);
-		/* update scale factor */
-		minSf = 14 - minSf;
-		*mdctScale= minSf;
-		break;
-
-	case STOP_WINDOW:
-		/*
-		we access BLOCK_SWITCHING_OFFSET-LS_TRANS (1600-448 ) delay buffer samples + 448 new timeSignal samples
-		and get the biggest scale factor for next calculate more precise
-		*/
-		delayBufferSf = getScalefactorOfShortVectorStride(mdctDelayBuffer+LS_TRANS,BLOCK_SWITCHING_OFFSET-LS_TRANS,1);
-		timeSignalSf  = getScalefactorOfShortVectorStride(timeSignal,2*FRAME_LEN_LONG-BLOCK_SWITCHING_OFFSET,chIncrement);
-		minSf = min(delayBufferSf,timeSignalSf);
-		minSf = min(minSf,13);
-
-		outData0 = realOut + FRAME_LEN_LONG/2;
-		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
-		for(i=0;i<LS_TRANS;i++){
-			*outData0++ = -(*dctIn1--) << (15 - 2 + minSf);
-		}
-
-		/* add windows and pre add for mdct to last buffer*/
-		dctIn0 = mdctDelayBuffer + LS_TRANS;
-		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1 - LS_TRANS;
-		outData0 = realOut + FRAME_LEN_LONG/2 + LS_TRANS;
-		winPtr = (int *)ShortWindowSine;
-		for(i=0;i<FRAME_LEN_SHORT/2;i++){
-			timeSignalSample = (*dctIn0++) << minSf;
-			ws1 = timeSignalSample * (*winPtr >> 16);
-			timeSignalSample= (*dctIn1--) << minSf;
-			ws2 = timeSignalSample * (*winPtr & 0xffff);
-			winPtr++;
-			*outData0++ = (ws1 >> 2) - (ws2 >> 2);  /* shift 2 to avoid overflow next */
-		}
-
-		shiftMdctDelayBuffer(mdctDelayBuffer,timeSignal,chIncrement);
-
-		/* add windows and pre add for mdct to new buffer*/
-		dctIn0 = mdctDelayBuffer;
-		dctIn1 = mdctDelayBuffer + FRAME_LEN_LONG - 1;
-		outData0 = realOut + FRAME_LEN_LONG/2 - 1;
-		winPtr = (int *)LongWindowKBD;
-		for(i=0;i<FRAME_LEN_LONG/2;i++){
-			timeSignalSample= (*dctIn0++) << minSf;
-			ws1 = timeSignalSample *(*winPtr & 0xffff);
-			timeSignalSample= (*dctIn1--) << minSf;
-			ws2 = timeSignalSample * (*winPtr >> 16);
-			*outData0-- =  -((ws1 >> 2) + (ws2 >> 2));  /* shift 2 to avoid overflow next */
-			winPtr++;
-		}
-
-		Mdct_Long(realOut);
-		minSf = 14 - minSf;
-		*mdctScale= minSf; /* update scale factor */
-		break;
-
-	case SHORT_WINDOW:
-		/*
-		we access BLOCK_SWITCHING_OFFSET (1600 ) delay buffer samples + no new timeSignal samples
-		and get the biggest scale factor for next calculate more precise
-		*/
-		minSf = getScalefactorOfShortVectorStride(mdctDelayBuffer+TRANSFORM_OFFSET_SHORT,9*FRAME_LEN_SHORT,1);
-		minSf = min(minSf,10);
-
-
-		for(w=0;w<TRANS_FAC;w++){
-			dctIn0 = mdctDelayBuffer+w*FRAME_LEN_SHORT+TRANSFORM_OFFSET_SHORT;
-			dctIn1 = mdctDelayBuffer+w*FRAME_LEN_SHORT+TRANSFORM_OFFSET_SHORT + FRAME_LEN_SHORT-1;
-			outData0 = realOut + FRAME_LEN_SHORT/2;
-			outData1 = realOut + FRAME_LEN_SHORT/2 - 1;
-
-			winPtr = (int *)ShortWindowSine;
-			for(i=0;i<FRAME_LEN_SHORT/2;i++){
-				timeSignalSample= *dctIn0 << minSf;
-				ws1 = timeSignalSample * (*winPtr >> 16);
-				timeSignalSample= *dctIn1 << minSf;
-				ws2 = timeSignalSample * (*winPtr & 0xffff);
-				*outData0++ = (ws1 >> 2) - (ws2 >> 2);  /* shift 2 to avoid overflow next */
-
-				timeSignalSample= *(dctIn0 + FRAME_LEN_SHORT) << minSf;
-				ws1 = timeSignalSample * (*winPtr & 0xffff);
-				timeSignalSample= *(dctIn1 + FRAME_LEN_SHORT) << minSf;
-				ws2 = timeSignalSample * (*winPtr >> 16);
-				*outData1-- =  -((ws1 >> 2) + (ws2 >> 2));  /* shift 2 to avoid overflow next */
-
-				winPtr++;
-				dctIn0++;
-				dctIn1--;
-			}
-
-			Mdct_Short(realOut);
-			realOut += FRAME_LEN_SHORT;
-		}
-
-		minSf = 11 - minSf;
-		*mdctScale = minSf; /* update scale factor */
-
-		shiftMdctDelayBuffer(mdctDelayBuffer,timeSignal,chIncrement);
-		break;
-  }
-}
-
diff --git a/media/libstagefright/codecs/avcdec/Android.bp b/media/libstagefright/codecs/avcdec/Android.bp
index 1f43803..44c882c 100644
--- a/media/libstagefright/codecs/avcdec/Android.bp
+++ b/media/libstagefright/codecs/avcdec/Android.bp
@@ -36,3 +36,44 @@
     ldflags: ["-Wl,-Bsymbolic"],
     compile_multilib: "32",
 }
+
+cc_library_shared {
+    name: "libstagefright_soft_c2avcdec",
+
+    static_libs: [
+        "libavcdec",
+        "libstagefright_codec2_vndk",
+    ],
+    srcs: ["C2SoftAvcDec.cpp"],
+
+    include_dirs: [
+        "external/libavc/decoder",
+        "external/libavc/common",
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/av/media/libstagefright/codec2/vndk/include",
+    ],
+
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "android.hardware.graphics.mapper@2.0",
+        "libhidlbase",
+        "libion",
+        "liblog",
+        "libmedia",
+        "libstagefright_codec2",
+        "libstagefright_foundation",
+        "libutils",
+    ],
+
+    sanitize: {
+        misc_undefined: [
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+        diag: {
+            cfi: true,
+        },
+    },
+
+    ldflags: ["-Wl,-Bsymbolic"],
+}
diff --git a/media/libstagefright/codecs/avcdec/C2AvcConfig.h b/media/libstagefright/codecs/avcdec/C2AvcConfig.h
new file mode 100644
index 0000000..a7e0d95
--- /dev/null
+++ b/media/libstagefright/codecs/avcdec/C2AvcConfig.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2017 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 C2AVCCONFIG_H_
+#define C2AVCCONFIG_H_
+
+#include <C2Config.h>
+
+namespace android {
+
+enum : uint32_t {
+    kParamIndexAvcProfile = kParamIndexParamStart + 1,
+    kParamIndexAvcLevel,
+    kParamIndexBlockSize,
+    kParamIndexAlignment,
+    kParamIndexFramerate,
+    kParamIndexBlocksPerSecond,
+};
+
+enum C2AvcProfileIdc : uint32_t {
+    kAvcProfileUnknown  = 0,
+    kAvcProfileBaseline = 66,
+    kAvcProfileMain     = 77,
+    kAvcProfileExtended = 88,
+    kAvcProfileHigh     = 100,
+    kAvcProfileHigh10   = 110,
+    kAvcProfileHigh422  = 122,
+    kAvcProfileHigh444  = 144,
+};
+
+enum C2AvcLevelIdc : uint32_t {
+    kAvcLevelUnknown = 0,
+    kAvcLevel10      = 10,
+    kAvcLevel1b      = 9,
+    kAvcLevel11      = 11,
+    kAvcLevel12      = 12,
+    kAvcLevel13      = 13,
+    kAvcLevel20      = 20,
+    kAvcLevel21      = 21,
+    kAvcLevel22      = 22,
+    kAvcLevel30      = 30,
+    kAvcLevel31      = 31,
+    kAvcLevel32      = 32,
+    kAvcLevel40      = 40,
+    kAvcLevel41      = 41,
+    kAvcLevel42      = 42,
+    kAvcLevel50      = 50,
+    kAvcLevel51      = 51,
+    kAvcLevel52      = 52,
+};
+
+// profile for AVC video decoder [IN]
+typedef C2StreamParam<C2Info, C2SimpleValueStruct<C2AvcProfileIdc>, kParamIndexAvcProfile>
+    C2AvcProfileInfo;
+
+// level for AVC video decoder [IN]
+typedef C2StreamParam<C2Info, C2SimpleValueStruct<C2AvcLevelIdc>, kParamIndexAvcLevel>
+    C2AvcLevelInfo;
+
+// block size [OUT]
+typedef C2StreamParam<C2Info, C2VideoSizeStruct, kParamIndexBlockSize> C2BlockSizeInfo;
+
+// alignment [OUT]
+typedef C2StreamParam<C2Info, C2VideoSizeStruct, kParamIndexAlignment> C2AlignmentInfo;
+
+// frame rate [OUT, hint]
+typedef C2StreamParam<C2Info, C2Uint32Value, kParamIndexFramerate> C2FrameRateInfo;
+
+// blocks-per-second [OUT, hint]
+typedef C2StreamParam<C2Info, C2Uint32Value, kParamIndexBlocksPerSecond> C2BlocksPerSecondInfo;
+
+} // namespace android
+
+#endif  // C2AVCCONFIG_H_
diff --git a/media/libstagefright/codecs/avcdec/C2SoftAvcDec.cpp b/media/libstagefright/codecs/avcdec/C2SoftAvcDec.cpp
new file mode 100644
index 0000000..3aa8c38
--- /dev/null
+++ b/media/libstagefright/codecs/avcdec/C2SoftAvcDec.cpp
@@ -0,0 +1,1409 @@
+/*
+ * Copyright 2016 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 "C2SoftAvcDec"
+#include <utils/Log.h>
+
+#include <cmath>
+#include <thread>
+
+#include "ih264_typedefs.h"
+#include "iv.h"
+#include "ivd.h"
+#include "ih264d.h"
+#include "C2SoftAvcDec.h"
+
+#include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/MediaDefs.h>
+#include <utils/misc.h>
+
+#include "ih264d_defs.h"
+
+namespace {
+
+template <class T>
+inline int32_t floor32(T arg) {
+   return (int32_t) std::llround(std::floor(arg));
+}
+
+} // namespace
+
+namespace android {
+
+struct iv_obj_t : public ::iv_obj_t {};
+struct ivd_video_decode_ip_t : public ::ivd_video_decode_ip_t {};
+struct ivd_video_decode_op_t : public ::ivd_video_decode_op_t {};
+
+#define PRINT_TIME  ALOGV
+
+#define componentName                   "video_decoder.avc"
+// #define codingType                      OMX_VIDEO_CodingAVC
+#define CODEC_MIME_TYPE                 MEDIA_MIMETYPE_VIDEO_AVC
+
+/** Function and structure definitions to keep code similar for each codec */
+#define ivdec_api_function              ih264d_api_function
+#define ivdext_create_ip_t              ih264d_create_ip_t
+#define ivdext_create_op_t              ih264d_create_op_t
+#define ivdext_delete_ip_t              ih264d_delete_ip_t
+#define ivdext_delete_op_t              ih264d_delete_op_t
+#define ivdext_ctl_set_num_cores_ip_t   ih264d_ctl_set_num_cores_ip_t
+#define ivdext_ctl_set_num_cores_op_t   ih264d_ctl_set_num_cores_op_t
+
+#define IVDEXT_CMD_CTL_SET_NUM_CORES    \
+        (IVD_CONTROL_API_COMMAND_TYPE_T)IH264D_CMD_CTL_SET_NUM_CORES
+
+namespace {
+
+using SupportedValuesWithFields = C2SoftAvcDecIntf::SupportedValuesWithFields;
+
+uint32_t restoreIndex(const C2Param *param) {
+    return (param->forStream() ? (0x02000000 | ((param->stream() << 17) & 0x01FE0000)) : 0)
+            | param->type();
+}
+
+struct ValidateParam {
+    explicit ValidateParam(
+            const std::map<C2ParamField, SupportedValuesWithFields> &supportedValues)
+        : mSupportedValues(supportedValues) {}
+
+    template <class T, bool SIGNED = std::is_signed<T>::value, size_t SIZE = sizeof(T)>
+    struct Getter {
+        static T get(const C2Value::Primitive &) {
+            static_assert(!std::is_arithmetic<T>::value, "non-arithmetic type");
+            static_assert(!std::is_floating_point<T>::value || std::is_same<T, float>::value,
+                    "float is the only supported floating point type");
+            static_assert(sizeof(T) <= 8, "type exceeds 64-bit");
+        }
+    };
+
+    template <class T>
+    bool validateField(
+            const C2FieldSupportedValues &supportedValues, const T &value) {
+        switch (supportedValues.type) {
+        case C2FieldSupportedValues::RANGE:
+            {
+                // TODO: handle step, nom, denom
+                return Getter<T>::get(supportedValues.range.min) < value
+                        && value < Getter<T>::get(supportedValues.range.max);
+            }
+        case C2FieldSupportedValues::VALUES:
+            {
+                for (const auto &val : supportedValues.values) {
+                    if (Getter<T>::get(val) == value) {
+                        return true;
+                    }
+                }
+                return false;
+            }
+        case C2FieldSupportedValues::FLAGS:
+            // TODO
+            return false;
+        }
+        return false;
+    }
+
+protected:
+    const std::map<C2ParamField, SupportedValuesWithFields> &mSupportedValues;
+};
+
+template <>
+struct ValidateParam::Getter<float> {
+    static float get(const C2Value::Primitive &value) { return value.fp; }
+};
+template <class T>
+struct ValidateParam::Getter<T, true, 8u> {
+    static int64_t get(const C2Value::Primitive &value) { return value.i64; }
+};
+template <class T>
+struct ValidateParam::Getter<T, true, 4u> {
+    static int32_t get(const C2Value::Primitive &value) { return value.i32; }
+};
+template <class T>
+struct ValidateParam::Getter<T, false, 8u> {
+    static uint64_t get(const C2Value::Primitive &value) { return value.u64; }
+};
+template <class T>
+struct ValidateParam::Getter<T, false, 4u> {
+    static uint32_t get(const C2Value::Primitive &value) { return value.u32; }
+};
+
+template <class T>
+struct ValidateSimpleParam : public ValidateParam {
+    explicit ValidateSimpleParam(
+            const std::map<C2ParamField, SupportedValuesWithFields> &supportedValues)
+        : ValidateParam(supportedValues) {}
+
+    std::unique_ptr<C2SettingResult> operator() (C2Param *c2param) {
+        T* param = (T*)c2param;
+        C2ParamField field(param, &T::mValue);
+        const C2FieldSupportedValues &supportedValues = mSupportedValues.at(field).supported;
+        if (!validateField(supportedValues, param->mValue)) {
+            return std::unique_ptr<C2SettingResult>(
+                    new C2SettingResult {field, C2SettingResult::BAD_VALUE, nullptr, {}});
+        }
+        return nullptr;
+    }
+};
+
+template <class T>
+struct ValidateVideoSize : public ValidateParam {
+    explicit ValidateVideoSize(
+            const std::map<C2ParamField, SupportedValuesWithFields> &supportedValues)
+        : ValidateParam(supportedValues) {}
+
+    std::unique_ptr<C2SettingResult> operator() (C2Param *c2param) {
+        T* param = (T*)c2param;
+        C2ParamField field(param, &T::mWidth);
+        const C2FieldSupportedValues &supportedWidth = mSupportedValues.at(field).supported;
+        if (!validateField(supportedWidth, param->mWidth)) {
+            return std::unique_ptr<C2SettingResult>(
+                    new C2SettingResult {field, C2SettingResult::BAD_VALUE, nullptr, {}});
+        }
+        field = C2ParamField(param, &T::mHeight);
+        const C2FieldSupportedValues &supportedHeight = mSupportedValues.at(field).supported;
+        if (!validateField(supportedHeight, param->mHeight)) {
+            return std::unique_ptr<C2SettingResult>(
+                    new C2SettingResult {field, C2SettingResult::BAD_VALUE, nullptr, {}});
+        }
+        return nullptr;
+    }
+};
+
+template <class T>
+struct ValidateCString {
+    explicit ValidateCString(const char *expected) : mExpected(expected) {}
+
+    std::unique_ptr<C2SettingResult> operator() (C2Param *c2param) {
+        T* param = (T*)c2param;
+        if (strncmp(param->m.mValue, mExpected, param->flexCount()) != 0) {
+            return std::unique_ptr<C2SettingResult>(
+                    new C2SettingResult {C2ParamField(param, &T::m), C2SettingResult::BAD_VALUE, nullptr, {}});
+        }
+        return nullptr;
+    }
+
+private:
+    const char *mExpected;
+};
+
+class GraphicBuffer : public C2Buffer {
+public:
+    explicit GraphicBuffer(const std::shared_ptr<C2GraphicBlock> &block)
+        : C2Buffer({ block->share(C2Rect(block->width(), block->height()), ::android::C2Fence()) }) {}
+};
+
+}  // namespace
+
+#define CASE(member) \
+    case decltype(component->member)::baseIndex: \
+        return std::unique_ptr<C2StructDescriptor>(new C2StructDescriptor( \
+                static_cast<decltype(component->member) *>(nullptr)))
+
+class C2SoftAvcDecIntf::ParamReflector : public C2ParamReflector {
+public:
+    virtual std::unique_ptr<C2StructDescriptor> describe(C2Param::BaseIndex paramIndex) override {
+        constexpr C2SoftAvcDecIntf *component = nullptr;
+        switch (paramIndex.baseIndex()) {
+        CASE(mDomainInfo);
+        CASE(mInputStreamCount);
+        CASE(mInputStreamFormat);
+        // Output counterparts for the above would be redundant.
+        CASE(mVideoSize);
+        CASE(mMaxVideoSizeHint);
+
+        // port mime configs are stored as unique_ptr.
+        case C2PortMimeConfig::baseIndex:
+            return std::unique_ptr<C2StructDescriptor>(new C2StructDescriptor(
+                    static_cast<C2PortMimeConfig *>(nullptr)));
+        }
+        return nullptr;
+    }
+};
+#undef CASE
+
+// static const CodecProfileLevel kProfileLevels[] = {
+//     { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel52 },
+//     { OMX_VIDEO_AVCProfileMain,     OMX_VIDEO_AVCLevel52 },
+//     { OMX_VIDEO_AVCProfileHigh,     OMX_VIDEO_AVCLevel52 },
+// };
+C2SoftAvcDecIntf::C2SoftAvcDecIntf(const char *name, node_id id)
+    : mName(name),
+      mId(id),
+      mDomainInfo(C2DomainVideo),
+      mInputStreamCount(1u),
+      mOutputStreamCount(1u),
+      mInputStreamFormat(0u, C2FormatCompressed),
+      mOutputStreamFormat(0u, C2FormatVideo),
+      mProfile(0u, kAvcProfileUnknown),
+      mLevel(0u, kAvcLevelUnknown),
+      mBlockSize(0u),
+      mAlignment(0u),
+      mFrameRate(0u, 0),
+      mBlocksPerSecond(0u, 0),
+      mParamReflector(new ParamReflector) {
+
+    mInputPortMime = C2PortMimeConfig::input::alloc_unique(strlen(CODEC_MIME_TYPE) + 1);
+    strcpy(mInputPortMime->m.mValue, CODEC_MIME_TYPE);
+    mOutputPortMime = C2PortMimeConfig::output::alloc_unique(strlen(MEDIA_MIMETYPE_VIDEO_RAW) + 1);
+    strcpy(mOutputPortMime->m.mValue, MEDIA_MIMETYPE_VIDEO_RAW);
+
+    mVideoSize.mWidth = 320;
+    mVideoSize.mHeight = 240;
+    mBlockSize.mWidth = 16;
+    mBlockSize.mHeight = 16;
+    mAlignment.mWidth = 2;
+    mAlignment.mHeight = 2;
+
+    mMaxVideoSizeHint.mWidth = H264_MAX_FRAME_WIDTH;
+    mMaxVideoSizeHint.mHeight = H264_MAX_FRAME_HEIGHT;
+
+    auto insertParam = [&params = mParams] (C2Param *param) {
+        params[restoreIndex(param)] = param;
+    };
+
+    auto markReadOnly = [&supported = mSupportedValues] (auto *param) {
+        supported.emplace(
+                C2ParamField(param, &std::remove_pointer<decltype(param)>::type::mValue),
+                C2FieldSupportedValues(false /* flags */, {}));
+    };
+
+    auto markReadOnlyVideoSize = [&supported = mSupportedValues] (auto *param) {
+        supported.emplace(
+                C2ParamField(param, &std::remove_pointer<decltype(param)>::type::mWidth),
+                C2FieldSupportedValues(false /* flags */, {}));
+        supported.emplace(
+                C2ParamField(param, &std::remove_pointer<decltype(param)>::type::mHeight),
+                C2FieldSupportedValues(false /* flags */, {}));
+    };
+
+    insertParam(&mDomainInfo);
+    markReadOnly(&mDomainInfo);
+    mFieldVerifiers[restoreIndex(&mDomainInfo)] =
+            ValidateSimpleParam<decltype(mDomainInfo)>(mSupportedValues);
+
+    insertParam(mInputPortMime.get());
+    mFieldVerifiers[restoreIndex(mInputPortMime.get())] =
+            ValidateCString<std::remove_reference<decltype(*mInputPortMime)>::type>(CODEC_MIME_TYPE);
+
+    insertParam(&mInputStreamCount);
+    markReadOnly(&mInputStreamCount);
+    mFieldVerifiers[restoreIndex(&mInputStreamCount)] =
+            ValidateSimpleParam<decltype(mInputStreamCount)>(mSupportedValues);
+
+    insertParam(mOutputPortMime.get());
+    mFieldVerifiers[restoreIndex(mOutputPortMime.get())] =
+            ValidateCString<std::remove_reference<decltype(*mOutputPortMime)>::type>(MEDIA_MIMETYPE_VIDEO_RAW);
+
+    insertParam(&mOutputStreamCount);
+    markReadOnly(&mOutputStreamCount);
+    mFieldVerifiers[restoreIndex(&mOutputStreamCount)] =
+            ValidateSimpleParam<decltype(mOutputStreamCount)>(mSupportedValues);
+
+    insertParam(&mInputStreamFormat);
+    markReadOnly(&mInputStreamFormat);
+    mFieldVerifiers[restoreIndex(&mInputStreamFormat)] =
+            ValidateSimpleParam<decltype(mInputStreamFormat)>(mSupportedValues);
+
+    insertParam(&mOutputStreamFormat);
+    markReadOnly(&mOutputStreamFormat);
+    mFieldVerifiers[restoreIndex(&mOutputStreamFormat)] =
+            ValidateSimpleParam<decltype(mOutputStreamFormat)>(mSupportedValues);
+
+    insertParam(&mVideoSize);
+    markReadOnlyVideoSize(&mVideoSize);
+    mFieldVerifiers[restoreIndex(&mVideoSize)] =
+            ValidateVideoSize<decltype(mVideoSize)>(mSupportedValues);
+
+    insertParam(&mMaxVideoSizeHint);
+    mSupportedValues.emplace(
+            C2ParamField(&mMaxVideoSizeHint, &C2MaxVideoSizeHintPortSetting::mWidth),
+            C2FieldSupportedValues(H264_MIN_FRAME_WIDTH, H264_MAX_FRAME_WIDTH, mAlignment.mWidth));
+    mSupportedValues.emplace(
+            C2ParamField(&mMaxVideoSizeHint, &C2MaxVideoSizeHintPortSetting::mHeight),
+            C2FieldSupportedValues(H264_MIN_FRAME_HEIGHT, H264_MAX_FRAME_HEIGHT, mAlignment.mHeight));
+    mFieldVerifiers[restoreIndex(&mMaxVideoSizeHint)] =
+            ValidateVideoSize<decltype(mMaxVideoSizeHint)>(mSupportedValues);
+
+    insertParam(&mProfile);
+    mSupportedValues.emplace(
+            C2ParamField(&mProfile, &C2AvcProfileInfo::mValue),
+            C2FieldSupportedValues(false /* flags */, {
+                kAvcProfileUnknown,
+                kAvcProfileBaseline,
+                kAvcProfileMain,
+                kAvcProfileHigh,
+            }));
+    mFieldVerifiers[restoreIndex(&mProfile)] =
+            ValidateSimpleParam<decltype(mProfile)>(mSupportedValues);
+
+    insertParam(&mLevel);
+    mSupportedValues.emplace(
+            C2ParamField(&mLevel, &C2AvcLevelInfo::mValue),
+            C2FieldSupportedValues(false /* flags */, {
+                kAvcLevelUnknown,
+                kAvcLevel10,
+                kAvcLevel1b,
+                kAvcLevel11,
+                kAvcLevel12,
+                kAvcLevel13,
+                kAvcLevel20,
+                kAvcLevel21,
+                kAvcLevel22,
+                kAvcLevel30,
+                kAvcLevel31,
+                kAvcLevel32,
+                kAvcLevel40,
+                kAvcLevel41,
+                kAvcLevel42,
+                kAvcLevel50,
+                kAvcLevel51,
+                kAvcLevel52,
+            }));
+    mFieldVerifiers[restoreIndex(&mLevel)] =
+            ValidateSimpleParam<decltype(mLevel)>(mSupportedValues);
+
+    insertParam(&mBlockSize);
+    markReadOnlyVideoSize(&mBlockSize);
+    mFieldVerifiers[restoreIndex(&mBlockSize)] =
+            ValidateVideoSize<decltype(mBlockSize)>(mSupportedValues);
+
+    insertParam(&mAlignment);
+    markReadOnlyVideoSize(&mAlignment);
+    mFieldVerifiers[restoreIndex(&mAlignment)] =
+            ValidateVideoSize<decltype(mAlignment)>(mSupportedValues);
+
+    insertParam(&mFrameRate);
+    mSupportedValues.emplace(
+            C2ParamField(&mFrameRate, &C2FrameRateInfo::mValue),
+            C2FieldSupportedValues(0, 240));
+    mFieldVerifiers[restoreIndex(&mFrameRate)] =
+            ValidateSimpleParam<decltype(mFrameRate)>(mSupportedValues);
+
+    insertParam(&mBlocksPerSecond);
+    mSupportedValues.emplace(
+            C2ParamField(&mFrameRate, &C2BlocksPerSecondInfo::mValue),
+            C2FieldSupportedValues(0, 244800));
+    mFieldVerifiers[restoreIndex(&mBlocksPerSecond)] =
+            ValidateSimpleParam<decltype(mBlocksPerSecond)>(mSupportedValues);
+
+    mParamDescs.push_back(std::make_shared<C2ParamDescriptor>(
+            true, "_domain", &mDomainInfo));
+    mParamDescs.push_back(std::make_shared<C2ParamDescriptor>(
+            true, "_input_port_mime", mInputPortMime.get()));
+    mParamDescs.push_back(std::make_shared<C2ParamDescriptor>(
+            true, "_input_stream_count", &mInputStreamCount));
+    mParamDescs.push_back(std::make_shared<C2ParamDescriptor>(
+            true, "_output_port_mime", mOutputPortMime.get()));
+    mParamDescs.push_back(std::make_shared<C2ParamDescriptor>(
+            true, "_output_stream_count", &mOutputStreamCount));
+    mParamDescs.push_back(std::make_shared<C2ParamDescriptor>(
+            true, "_input_stream_format", &mInputStreamFormat));
+    mParamDescs.push_back(std::make_shared<C2ParamDescriptor>(
+            true, "_output_stream_format", &mOutputStreamFormat));
+    mParamDescs.push_back(std::make_shared<C2ParamDescriptor>(
+            false, "_video_size", &mVideoSize));
+    mParamDescs.push_back(std::make_shared<C2ParamDescriptor>(
+            false, "_max_video_size_hint", &mMaxVideoSizeHint));
+}
+
+C2String C2SoftAvcDecIntf::getName() const {
+    return mName;
+}
+
+node_id C2SoftAvcDecIntf::getId() const {
+    return mId;
+}
+
+status_t C2SoftAvcDecIntf::query_nb(
+        const std::vector<C2Param* const> & stackParams,
+        const std::vector<C2Param::Index> & heapParamIndices,
+        std::vector<std::unique_ptr<C2Param>>* const heapParams) const {
+    for (C2Param* const param : stackParams) {
+        if (!*param) {
+            continue;
+        }
+
+        uint32_t index = restoreIndex(param);
+        if (!mParams.count(index)) {
+            continue;
+        }
+
+        C2Param *myParam = mParams.find(index)->second;
+        if (myParam->size() != param->size()) {
+            param->invalidate();
+            continue;
+        }
+
+        param->updateFrom(*myParam);
+    }
+
+    for (const C2Param::Index index : heapParamIndices) {
+        if (mParams.count(index)) {
+            C2Param *myParam = mParams.find(index)->second;
+            heapParams->emplace_back(C2Param::Copy(*myParam));
+        }
+    }
+
+    return C2_OK;
+}
+
+status_t C2SoftAvcDecIntf::config_nb(
+        const std::vector<C2Param* const> &params,
+        std::vector<std::unique_ptr<C2SettingResult>>* const failures) {
+    status_t err = C2_OK;
+    for (C2Param *param : params) {
+        uint32_t index = restoreIndex(param);
+        if (mParams.count(index) == 0) {
+            // We can't create C2SettingResult with no field, so just skipping in this case.
+            err = C2_BAD_INDEX;
+            continue;
+        }
+        C2Param *myParam = mParams.find(index)->second;
+        std::unique_ptr<C2SettingResult> result;
+        if (!(result = mFieldVerifiers[index](param))) {
+            myParam->updateFrom(*param);
+            updateSupportedValues();
+        } else {
+            failures->push_back(std::move(result));
+            err = C2_BAD_VALUE;
+        }
+    }
+    return err;
+}
+
+status_t C2SoftAvcDecIntf::commit_sm(
+        const std::vector<C2Param* const> &params,
+        std::vector<std::unique_ptr<C2SettingResult>>* const failures) {
+    // TODO
+    return config_nb(params, failures);
+}
+
+status_t C2SoftAvcDecIntf::createTunnel_sm(node_id targetComponent) {
+    // Tunneling is not supported
+    (void) targetComponent;
+    return C2_UNSUPPORTED;
+}
+
+status_t C2SoftAvcDecIntf::releaseTunnel_sm(node_id targetComponent) {
+    // Tunneling is not supported
+    (void) targetComponent;
+    return C2_UNSUPPORTED;
+}
+
+std::shared_ptr<C2ParamReflector> C2SoftAvcDecIntf::getParamReflector() const {
+    return mParamReflector;
+}
+
+status_t C2SoftAvcDecIntf::getSupportedParams(
+        std::vector<std::shared_ptr<C2ParamDescriptor>> * const params) const {
+    params->insert(params->begin(), mParamDescs.begin(), mParamDescs.end());
+    return C2_OK;
+}
+
+status_t C2SoftAvcDecIntf::getSupportedValues(
+        const std::vector<const C2ParamField> &fields,
+        std::vector<C2FieldSupportedValues>* const values) const {
+    for (const auto &field : fields) {
+        if (mSupportedValues.count(field) == 0) {
+            return BAD_VALUE;
+        }
+        values->push_back(mSupportedValues.at(field).supported);
+    }
+    return C2_OK;
+}
+
+void C2SoftAvcDecIntf::updateSupportedValues() {
+    int32_t maxWidth = H264_MAX_FRAME_WIDTH;
+    int32_t maxHeight = H264_MAX_FRAME_HEIGHT;
+    // cf: Rec. ITU-T H.264 A.3
+    int maxFrameRate = 172;
+    std::vector<C2ParamField> fields;
+    if (mLevel.mValue != kAvcLevelUnknown) {
+        // cf: Rec. ITU-T H.264 Table A-1
+        constexpr int MaxFS[] = {
+        //  0       1       2       3       4       5       6       7       8       9
+            0,      0,      0,      0,      0,      0,      0,      0,      0,      99,
+            99,     396,    396,    396,    0,      0,      0,      0,      0,      0,
+            396,    792,    1620,   0,      0,      0,      0,      0,      0,      0,
+            1620,   3600,   5120,   0,      0,      0,      0,      0,      0,      0,
+            8192,   8192,   8704,   0,      0,      0,      0,      0,      0,      0,
+            22080,  36864,  36864,
+        };
+        constexpr int MaxMBPS[] = {
+        //  0       1       2       3       4       5       6       7       8       9
+            0,      0,      0,      0,      0,      0,      0,      0,      0,      1485,
+            1485,   3000,   6000,   11880,  0,      0,      0,      0,      0,      0,
+            11880,  19800,  20250,  0,      0,      0,      0,      0,      0,      0,
+            40500,  108000, 216000, 0,      0,      0,      0,      0,      0,      0,
+            245760, 245760, 522240, 0,      0,      0,      0,      0,      0,      0,
+            589824, 983040, 2073600,
+        };
+
+        // cf: Rec. ITU-T H.264 A.3.1
+        maxWidth = std::min(maxWidth, floor32(std::sqrt(MaxFS[mLevel.mValue] * 8)) * MB_SIZE);
+        maxHeight = std::min(maxHeight, floor32(std::sqrt(MaxFS[mLevel.mValue] * 8)) * MB_SIZE);
+        int32_t MBs = ((mVideoSize.mWidth + 15) / 16) * ((mVideoSize.mHeight + 15) / 16);
+        maxFrameRate = std::min(maxFrameRate, MaxMBPS[mLevel.mValue] / MBs);
+        fields.push_back(C2ParamField(&mLevel, &C2AvcLevelInfo::mValue));
+    }
+
+    SupportedValuesWithFields &maxWidthVals = mSupportedValues.at(
+            C2ParamField(&mMaxVideoSizeHint, &C2MaxVideoSizeHintPortSetting::mWidth));
+    maxWidthVals.supported.range.max = maxWidth;
+    maxWidthVals.restrictingFields.clear();
+    maxWidthVals.restrictingFields.insert(fields.begin(), fields.end());
+
+    SupportedValuesWithFields &maxHeightVals = mSupportedValues.at(
+            C2ParamField(&mMaxVideoSizeHint, &C2MaxVideoSizeHintPortSetting::mHeight));
+    maxHeightVals.supported.range.max = maxHeight;
+    maxHeightVals.restrictingFields.clear();
+    maxHeightVals.restrictingFields.insert(fields.begin(), fields.end());
+
+    SupportedValuesWithFields &frameRate = mSupportedValues.at(
+            C2ParamField(&mFrameRate, &C2FrameRateInfo::mValue));
+    frameRate.supported.range.max = maxFrameRate;
+    frameRate.restrictingFields.clear();
+    frameRate.restrictingFields.insert(fields.begin(), fields.end());
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+class C2SoftAvcDec::QueueProcessThread {
+public:
+    QueueProcessThread() : mExitRequested(false), mRunning(false) {}
+
+    ~QueueProcessThread() {
+        if (mThread && mThread->joinable()) {
+            mExitRequested = true;
+            mThread->join();
+        }
+    }
+
+    void start(std::weak_ptr<C2SoftAvcDec> component) {
+        mThread.reset(new std::thread([this, component] () {
+            mRunning = true;
+            while (auto comp = component.lock()) {
+                if (mExitRequested) break;
+                comp->processQueue();
+            }
+            mRunning = false;
+        }));
+    }
+
+    void requestExit() {
+        mExitRequested = true;
+    }
+
+    bool isRunning() {
+        return mRunning;
+    }
+
+private:
+    std::atomic_bool mExitRequested;
+    std::atomic_bool mRunning;
+    std::unique_ptr<std::thread> mThread;
+};
+
+C2SoftAvcDec::C2SoftAvcDec(
+        const char *name,
+        node_id id,
+        const std::shared_ptr<C2ComponentListener> &listener)
+    : mIntf(std::make_shared<C2SoftAvcDecIntf>(name, id)),
+      mListener(listener),
+      mThread(new QueueProcessThread),
+      mCodecCtx(NULL),
+      mFlushOutBuffer(NULL),
+      mIvColorFormat(IV_YUV_420P),
+      mChangingResolution(false),
+      mSignalledError(false),
+      mWidth(320),
+      mHeight(240),
+      mInputOffset(0) {
+    GETTIME(&mTimeStart, NULL);
+
+    // If input dump is enabled, then open create an empty file
+    GENERATE_FILE_NAMES();
+    CREATE_DUMP_FILE(mInFile);
+}
+
+C2SoftAvcDec::~C2SoftAvcDec() {
+    CHECK_EQ(deInitDecoder(), (status_t)OK);
+}
+
+status_t C2SoftAvcDec::queue_nb(
+        std::list<std::unique_ptr<C2Work>>* const items) {
+    if (!mThread->isRunning()) {
+        return C2_CORRUPTED;
+    }
+    std::unique_lock<std::mutex> lock(mQueueLock);
+    while (!items->empty()) {
+        // TODO: examine item and update width/height?
+        mQueue.emplace_back(std::move(items->front()));
+        items->pop_front();
+    }
+    mQueueCond.notify_all();
+    return C2_OK;
+}
+
+status_t C2SoftAvcDec::announce_nb(const std::vector<C2WorkOutline> &items) {
+    // Tunneling is not supported
+    (void) items;
+    return C2_UNSUPPORTED;
+}
+
+status_t C2SoftAvcDec::flush_sm(
+        bool flushThrough, std::list<std::unique_ptr<C2Work>>* const flushedWork) {
+    // Tunneling is not supported
+    (void) flushThrough;
+
+    if (!mThread->isRunning()) {
+        return C2_CORRUPTED;
+    }
+    {
+        std::unique_lock<std::mutex> lock(mQueueLock);
+        while (!mQueue.empty()) {
+            flushedWork->emplace_back(std::move(mQueue.front()));
+            mQueue.pop_front();
+        }
+        mQueueCond.notify_all();
+    }
+    {
+        std::unique_lock<std::mutex> lock(mPendingLock);
+        for (auto &elem : mPendingWork) {
+            flushedWork->emplace_back(std::move(elem.second));
+        }
+        mPendingWork.clear();
+    }
+    return C2_OK;
+}
+
+status_t C2SoftAvcDec::drain_nb(bool drainThrough) {
+    // Tunneling is not supported
+    (void) drainThrough;
+
+    if (!mThread->isRunning()) {
+        return C2_CORRUPTED;
+    }
+    std::unique_lock<std::mutex> lock(mQueueLock);
+    if (!mQueue.empty()) {
+        C2BufferPack &lastInput = mQueue.back()->input;
+        lastInput.flags = (flags_t)(lastInput.flags | BUFFERFLAG_END_OF_STREAM);
+        mQueueCond.notify_all();
+    }
+    return C2_OK;
+}
+
+status_t C2SoftAvcDec::start() {
+    if (!mThread->isRunning()) {
+        mThread->start(shared_from_this());
+    }
+    return C2_OK;
+}
+
+status_t C2SoftAvcDec::stop() {
+    ALOGV("stop");
+    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
+    std::chrono::system_clock::time_point deadline = now + std::chrono::milliseconds(500);
+
+    mThread->requestExit();
+    while (mThread->isRunning() && (now = std::chrono::system_clock::now()) < deadline) {
+        std::this_thread::yield();
+        std::unique_lock<std::mutex> lock(mQueueLock);
+        mQueueCond.notify_all();
+    }
+    if (mThread->isRunning()) {
+        return C2_TIMED_OUT;
+    }
+
+    mSignalledError = false;
+    resetDecoder();
+    resetPlugin();
+
+    return C2_OK;
+}
+
+void C2SoftAvcDec::reset() {
+    if (mThread->isRunning()) {
+        stop();
+    }
+    // TODO
+}
+
+void C2SoftAvcDec::release() {
+    if (mThread->isRunning()) {
+        stop();
+    }
+    // TODO
+}
+
+std::shared_ptr<C2ComponentInterface> C2SoftAvcDec::intf() {
+    return mIntf;
+}
+
+void C2SoftAvcDec::processQueue() {
+    if (mIsInFlush) {
+        setFlushMode();
+
+        /* Allocate a picture buffer to flushed data */
+        uint32_t displayStride = mWidth;
+        uint32_t displayHeight = mHeight;
+
+        uint32_t bufferSize = displayStride * displayHeight * 3 / 2;
+        mFlushOutBuffer = (uint8_t *)memalign(128, bufferSize);
+        if (NULL == mFlushOutBuffer) {
+            ALOGE("Could not allocate flushOutputBuffer of size %u", bufferSize);
+            return;
+        }
+
+        while (true) {
+            ivd_video_decode_ip_t s_dec_ip;
+            ivd_video_decode_op_t s_dec_op;
+            IV_API_CALL_STATUS_T status;
+            size_t sizeY, sizeUV;
+
+            setDecodeArgs(&s_dec_ip, &s_dec_op, NULL, NULL, 0, 0u);
+
+            status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op);
+            if (0 == s_dec_op.u4_output_present) {
+                resetPlugin();
+                break;
+            }
+        }
+
+        if (mFlushOutBuffer) {
+            free(mFlushOutBuffer);
+            mFlushOutBuffer = NULL;
+        }
+        mIsInFlush = false;
+    }
+
+    std::unique_ptr<C2Work> work;
+    {
+        std::unique_lock<std::mutex> lock(mQueueLock);
+        if (mQueue.empty()) {
+            mQueueCond.wait(lock);
+        }
+        if (mQueue.empty()) {
+            ALOGV("empty queue");
+            return;
+        }
+        work.swap(mQueue.front());
+        mQueue.pop_front();
+    }
+
+    // Process the work
+    process(work);
+
+    std::vector<std::unique_ptr<C2Work>> done;
+    {
+        std::unique_lock<std::mutex> lock(mPendingLock);
+        uint32_t index = work->input.ordinal.frame_index;
+        mPendingWork[index].swap(work);
+
+        if (work) {
+            work->result = C2_CORRUPTED;
+            done.emplace_back(std::move(work));
+        }
+    }
+
+    if (!done.empty()) {
+        mListener->onWorkDone(shared_from_this(), std::move(done));
+    }
+}
+
+
+static void *ivd_aligned_malloc(void *ctxt, WORD32 alignment, WORD32 size) {
+    UNUSED(ctxt);
+    return memalign(alignment, size);
+}
+
+static void ivd_aligned_free(void *ctxt, void *buf) {
+    UNUSED(ctxt);
+    free(buf);
+    return;
+}
+
+static size_t GetCPUCoreCount() {
+    long cpuCoreCount = 1;
+#if defined(_SC_NPROCESSORS_ONLN)
+    cpuCoreCount = sysconf(_SC_NPROCESSORS_ONLN);
+#else
+    // _SC_NPROC_ONLN must be defined...
+    cpuCoreCount = sysconf(_SC_NPROC_ONLN);
+#endif
+    CHECK(cpuCoreCount >= 1);
+    ALOGV("Number of CPU cores: %ld", cpuCoreCount);
+    return (size_t)cpuCoreCount;
+}
+
+void C2SoftAvcDec::logVersion() {
+    ivd_ctl_getversioninfo_ip_t s_ctl_ip;
+    ivd_ctl_getversioninfo_op_t s_ctl_op;
+    UWORD8 au1_buf[512];
+    IV_API_CALL_STATUS_T status;
+
+    s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
+    s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_GETVERSION;
+    s_ctl_ip.u4_size = sizeof(ivd_ctl_getversioninfo_ip_t);
+    s_ctl_op.u4_size = sizeof(ivd_ctl_getversioninfo_op_t);
+    s_ctl_ip.pv_version_buffer = au1_buf;
+    s_ctl_ip.u4_version_buffer_size = sizeof(au1_buf);
+
+    status =
+        ivdec_api_function(mCodecCtx, (void *)&s_ctl_ip, (void *)&s_ctl_op);
+
+    if (status != IV_SUCCESS) {
+        ALOGE("Error in getting version number: 0x%x",
+                s_ctl_op.u4_error_code);
+    } else {
+        ALOGV("Ittiam decoder version number: %s",
+                (char *)s_ctl_ip.pv_version_buffer);
+    }
+    return;
+}
+
+status_t C2SoftAvcDec::setParams(size_t stride) {
+    ivd_ctl_set_config_ip_t s_ctl_ip;
+    ivd_ctl_set_config_op_t s_ctl_op;
+    IV_API_CALL_STATUS_T status;
+    s_ctl_ip.u4_disp_wd = (UWORD32)stride;
+    s_ctl_ip.e_frm_skip_mode = IVD_SKIP_NONE;
+
+    s_ctl_ip.e_frm_out_mode = IVD_DISPLAY_FRAME_OUT;
+    s_ctl_ip.e_vid_dec_mode = IVD_DECODE_FRAME;
+    s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
+    s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_SETPARAMS;
+    s_ctl_ip.u4_size = sizeof(ivd_ctl_set_config_ip_t);
+    s_ctl_op.u4_size = sizeof(ivd_ctl_set_config_op_t);
+
+    ALOGV("Set the run-time (dynamic) parameters stride = %zu", stride);
+    status = ivdec_api_function(mCodecCtx, (void *)&s_ctl_ip, (void *)&s_ctl_op);
+
+    if (status != IV_SUCCESS) {
+        ALOGE("Error in setting the run-time parameters: 0x%x",
+                s_ctl_op.u4_error_code);
+
+        return UNKNOWN_ERROR;
+    }
+    return OK;
+}
+
+status_t C2SoftAvcDec::resetPlugin() {
+    mReceivedEOS = false;
+    mInputOffset = 0;
+
+    /* Initialize both start and end times */
+    gettimeofday(&mTimeStart, NULL);
+    gettimeofday(&mTimeEnd, NULL);
+
+    return OK;
+}
+
+status_t C2SoftAvcDec::resetDecoder() {
+    ivd_ctl_reset_ip_t s_ctl_ip;
+    ivd_ctl_reset_op_t s_ctl_op;
+    IV_API_CALL_STATUS_T status;
+
+    s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
+    s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_RESET;
+    s_ctl_ip.u4_size = sizeof(ivd_ctl_reset_ip_t);
+    s_ctl_op.u4_size = sizeof(ivd_ctl_reset_op_t);
+
+    status = ivdec_api_function(mCodecCtx, (void *)&s_ctl_ip, (void *)&s_ctl_op);
+    if (IV_SUCCESS != status) {
+        ALOGE("Error in reset: 0x%x", s_ctl_op.u4_error_code);
+        return UNKNOWN_ERROR;
+    }
+    mSignalledError = false;
+
+    /* Set number of cores/threads to be used by the codec */
+    setNumCores();
+
+    mStride = 0;
+    return OK;
+}
+
+status_t C2SoftAvcDec::setNumCores() {
+    ivdext_ctl_set_num_cores_ip_t s_set_cores_ip;
+    ivdext_ctl_set_num_cores_op_t s_set_cores_op;
+    IV_API_CALL_STATUS_T status;
+    s_set_cores_ip.e_cmd = IVD_CMD_VIDEO_CTL;
+    s_set_cores_ip.e_sub_cmd = IVDEXT_CMD_CTL_SET_NUM_CORES;
+    s_set_cores_ip.u4_num_cores = MIN(mNumCores, CODEC_MAX_NUM_CORES);
+    s_set_cores_ip.u4_size = sizeof(ivdext_ctl_set_num_cores_ip_t);
+    s_set_cores_op.u4_size = sizeof(ivdext_ctl_set_num_cores_op_t);
+    status = ivdec_api_function(
+            mCodecCtx, (void *)&s_set_cores_ip, (void *)&s_set_cores_op);
+    if (IV_SUCCESS != status) {
+        ALOGE("Error in setting number of cores: 0x%x",
+                s_set_cores_op.u4_error_code);
+        return UNKNOWN_ERROR;
+    }
+    return OK;
+}
+
+status_t C2SoftAvcDec::setFlushMode() {
+    IV_API_CALL_STATUS_T status;
+    ivd_ctl_flush_ip_t s_video_flush_ip;
+    ivd_ctl_flush_op_t s_video_flush_op;
+
+    s_video_flush_ip.e_cmd = IVD_CMD_VIDEO_CTL;
+    s_video_flush_ip.e_sub_cmd = IVD_CMD_CTL_FLUSH;
+    s_video_flush_ip.u4_size = sizeof(ivd_ctl_flush_ip_t);
+    s_video_flush_op.u4_size = sizeof(ivd_ctl_flush_op_t);
+
+    /* Set the decoder in Flush mode, subsequent decode() calls will flush */
+    status = ivdec_api_function(
+            mCodecCtx, (void *)&s_video_flush_ip, (void *)&s_video_flush_op);
+
+    if (status != IV_SUCCESS) {
+        ALOGE("Error in setting the decoder in flush mode: (%d) 0x%x", status,
+                s_video_flush_op.u4_error_code);
+        return UNKNOWN_ERROR;
+    }
+
+    return OK;
+}
+
+status_t C2SoftAvcDec::initDecoder() {
+    IV_API_CALL_STATUS_T status;
+
+    mNumCores = GetCPUCoreCount();
+    mCodecCtx = NULL;
+
+    mStride = mWidth;
+
+    /* Initialize the decoder */
+    {
+        ivdext_create_ip_t s_create_ip;
+        ivdext_create_op_t s_create_op;
+
+        void *dec_fxns = (void *)ivdec_api_function;
+
+        s_create_ip.s_ivd_create_ip_t.u4_size = sizeof(ivdext_create_ip_t);
+        s_create_ip.s_ivd_create_ip_t.e_cmd = IVD_CMD_CREATE;
+        s_create_ip.s_ivd_create_ip_t.u4_share_disp_buf = 0;
+        s_create_op.s_ivd_create_op_t.u4_size = sizeof(ivdext_create_op_t);
+        s_create_ip.s_ivd_create_ip_t.e_output_format = (IV_COLOR_FORMAT_T)mIvColorFormat;
+        s_create_ip.s_ivd_create_ip_t.pf_aligned_alloc = ivd_aligned_malloc;
+        s_create_ip.s_ivd_create_ip_t.pf_aligned_free = ivd_aligned_free;
+        s_create_ip.s_ivd_create_ip_t.pv_mem_ctxt = NULL;
+
+        status = ivdec_api_function(mCodecCtx, (void *)&s_create_ip, (void *)&s_create_op);
+
+        mCodecCtx = (iv_obj_t*)s_create_op.s_ivd_create_op_t.pv_handle;
+        mCodecCtx->pv_fxns = dec_fxns;
+        mCodecCtx->u4_size = sizeof(iv_obj_t);
+
+        if (status != IV_SUCCESS) {
+            ALOGE("Error in create: 0x%x",
+                    s_create_op.s_ivd_create_op_t.u4_error_code);
+            deInitDecoder();
+            mCodecCtx = NULL;
+            return UNKNOWN_ERROR;
+        }
+    }
+
+    /* Reset the plugin state */
+    resetPlugin();
+
+    /* Set the run time (dynamic) parameters */
+    setParams(mStride);
+
+    /* Set number of cores/threads to be used by the codec */
+    setNumCores();
+
+    /* Get codec version */
+    logVersion();
+
+    mFlushNeeded = false;
+    return OK;
+}
+
+status_t C2SoftAvcDec::deInitDecoder() {
+    size_t i;
+    IV_API_CALL_STATUS_T status;
+
+    if (mCodecCtx) {
+        ivdext_delete_ip_t s_delete_ip;
+        ivdext_delete_op_t s_delete_op;
+
+        s_delete_ip.s_ivd_delete_ip_t.u4_size = sizeof(ivdext_delete_ip_t);
+        s_delete_ip.s_ivd_delete_ip_t.e_cmd = IVD_CMD_DELETE;
+
+        s_delete_op.s_ivd_delete_op_t.u4_size = sizeof(ivdext_delete_op_t);
+
+        status = ivdec_api_function(mCodecCtx, (void *)&s_delete_ip, (void *)&s_delete_op);
+        if (status != IV_SUCCESS) {
+            ALOGE("Error in delete: 0x%x",
+                    s_delete_op.s_ivd_delete_op_t.u4_error_code);
+            return UNKNOWN_ERROR;
+        }
+    }
+
+
+    mChangingResolution = false;
+
+    return OK;
+}
+
+bool C2SoftAvcDec::getVUIParams() {
+    IV_API_CALL_STATUS_T status;
+    ih264d_ctl_get_vui_params_ip_t s_ctl_get_vui_params_ip;
+    ih264d_ctl_get_vui_params_op_t s_ctl_get_vui_params_op;
+
+    s_ctl_get_vui_params_ip.e_cmd = IVD_CMD_VIDEO_CTL;
+    s_ctl_get_vui_params_ip.e_sub_cmd =
+        (IVD_CONTROL_API_COMMAND_TYPE_T)IH264D_CMD_CTL_GET_VUI_PARAMS;
+
+    s_ctl_get_vui_params_ip.u4_size =
+        sizeof(ih264d_ctl_get_vui_params_ip_t);
+
+    s_ctl_get_vui_params_op.u4_size = sizeof(ih264d_ctl_get_vui_params_op_t);
+
+    status = ivdec_api_function(
+            (iv_obj_t *)mCodecCtx, (void *)&s_ctl_get_vui_params_ip,
+            (void *)&s_ctl_get_vui_params_op);
+
+    if (status != IV_SUCCESS) {
+        ALOGW("Error in getting VUI params: 0x%x",
+                s_ctl_get_vui_params_op.u4_error_code);
+        return false;
+    }
+
+    int32_t primaries = s_ctl_get_vui_params_op.u1_colour_primaries;
+    int32_t transfer = s_ctl_get_vui_params_op.u1_tfr_chars;
+    int32_t coeffs = s_ctl_get_vui_params_op.u1_matrix_coeffs;
+    bool fullRange = s_ctl_get_vui_params_op.u1_video_full_range_flag;
+
+    ColorAspects colorAspects;
+    ColorUtils::convertIsoColorAspectsToCodecAspects(
+            primaries, transfer, coeffs, fullRange, colorAspects);
+
+    // Update color aspects if necessary.
+    if (colorAspectsDiffer(colorAspects, mBitstreamColorAspects)) {
+        mBitstreamColorAspects = colorAspects;
+        status_t err = handleColorAspectsChange();
+        CHECK(err == OK);
+    }
+    return true;
+}
+
+bool C2SoftAvcDec::setDecodeArgs(
+        ivd_video_decode_ip_t *ps_dec_ip,
+        ivd_video_decode_op_t *ps_dec_op,
+        C2ReadView *inBuffer,
+        C2GraphicView *outBuffer,
+        uint32_t workIndex,
+        size_t inOffset) {
+    size_t width = mWidth;
+    size_t height = mHeight;
+    size_t sizeY = width * height;
+    size_t sizeUV;
+
+    ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
+    ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
+
+    ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
+
+    /* When in flush and after EOS with zero byte input,
+     * inBuffer is set to zero. Hence check for non-null */
+    if (inBuffer) {
+        ps_dec_ip->u4_ts = workIndex;
+        ps_dec_ip->pv_stream_buffer = const_cast<uint8_t *>(inBuffer->data()) + inOffset;
+        ps_dec_ip->u4_num_Bytes = inBuffer->capacity() - inOffset;
+    } else {
+        ps_dec_ip->u4_ts = 0;
+        ps_dec_ip->pv_stream_buffer = NULL;
+        ps_dec_ip->u4_num_Bytes = 0;
+    }
+
+    sizeUV = sizeY / 4;
+    ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
+    ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
+    ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
+
+    if (outBuffer) {
+        if (outBuffer->width() < width ||
+                outBuffer->height() < height) {
+            ALOGE("Output buffer too small: provided (%dx%d) required (%zux%zu)",
+                  outBuffer->width(), outBuffer->height(), width, height);
+            return false;
+        }
+        ps_dec_ip->s_out_buffer.pu1_bufs[0] = outBuffer->data()[0];
+        ps_dec_ip->s_out_buffer.pu1_bufs[1] = outBuffer->data()[1];
+        ps_dec_ip->s_out_buffer.pu1_bufs[2] = outBuffer->data()[2];
+    } else {
+        // mFlushOutBuffer always has the right size.
+        ps_dec_ip->s_out_buffer.pu1_bufs[0] = mFlushOutBuffer;
+        ps_dec_ip->s_out_buffer.pu1_bufs[1] = mFlushOutBuffer + sizeY;
+        ps_dec_ip->s_out_buffer.pu1_bufs[2] = mFlushOutBuffer + sizeY + sizeUV;
+    }
+
+    ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
+    return true;
+}
+
+void C2SoftAvcDec::process(std::unique_ptr<C2Work> &work) {
+    if (mSignalledError) {
+        return;
+    }
+
+    if (NULL == mCodecCtx) {
+        if (OK != initDecoder()) {
+            ALOGE("Failed to initialize decoder");
+            // TODO: notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL);
+            mSignalledError = true;
+            return;
+        }
+    }
+    if (mWidth != mStride) {
+        /* Set the run-time (dynamic) parameters */
+        mStride = mWidth;
+        setParams(mStride);
+    }
+
+    const C2ConstLinearBlock &buffer =
+            work->input.buffers[0]->data().linearBlocks().front();
+    if (buffer.capacity() == 0) {
+        // TODO: result?
+
+        std::vector<std::unique_ptr<C2Work>> done;
+        done.emplace_back(std::move(work));
+        mListener->onWorkDone(shared_from_this(), std::move(done));
+        if (!(work->input.flags & BUFFERFLAG_END_OF_STREAM)) {
+            return;
+        }
+
+        mReceivedEOS = true;
+        // TODO: flush
+    } else if (work->input.flags & BUFFERFLAG_END_OF_STREAM) {
+        mReceivedEOS = true;
+    }
+
+    C2ReadView input = work->input.buffers[0]->data().linearBlocks().front().map().get();
+    uint32_t workIndex = work->input.ordinal.frame_index & 0xFFFFFFFF;
+
+    // TODO: populate --- assume display order?
+    if (!mAllocatedBlock) {
+        // TODO: error handling
+        // TODO: format & usage
+        uint32_t format = HAL_PIXEL_FORMAT_YV12;
+        C2MemoryUsage usage = { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite };
+        (void) work->worklets.front()->allocators[0]->allocateGraphicBlock(
+                mWidth, mHeight, format, usage, &mAllocatedBlock);
+        ALOGE("provided (%dx%d) required (%dx%d)", mAllocatedBlock->width(), mAllocatedBlock->height(), mWidth, mHeight);
+    }
+    C2GraphicView output = mAllocatedBlock->map().get();
+    ALOGE("mapped err = %d", output.error());
+
+    size_t inOffset = 0u;
+    while (inOffset < input.capacity()) {
+        ivd_video_decode_ip_t s_dec_ip;
+        ivd_video_decode_op_t s_dec_op;
+        WORD32 timeDelay, timeTaken;
+        size_t sizeY, sizeUV;
+
+        if (!setDecodeArgs(&s_dec_ip, &s_dec_op, &input, &output, workIndex, inOffset)) {
+            ALOGE("Decoder arg setup failed");
+            // TODO: notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
+            mSignalledError = true;
+            return;
+        }
+        ALOGE("Decoder arg setup succeeded");
+        // If input dump is enabled, then write to file
+        DUMP_TO_FILE(mInFile, s_dec_ip.pv_stream_buffer, s_dec_ip.u4_num_Bytes, mInputOffset);
+
+        GETTIME(&mTimeStart, NULL);
+        /* Compute time elapsed between end of previous decode()
+         * to start of current decode() */
+        TIME_DIFF(mTimeEnd, mTimeStart, timeDelay);
+
+        IV_API_CALL_STATUS_T status;
+        status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op);
+
+        bool unsupportedResolution =
+            (IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED == (s_dec_op.u4_error_code & 0xFF));
+
+        /* Check for unsupported dimensions */
+        if (unsupportedResolution) {
+            ALOGE("Unsupported resolution : %dx%d", mWidth, mHeight);
+            // TODO: notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL);
+            mSignalledError = true;
+            return;
+        }
+
+        bool allocationFailed = (IVD_MEM_ALLOC_FAILED == (s_dec_op.u4_error_code & 0xFF));
+        if (allocationFailed) {
+            ALOGE("Allocation failure in decoder");
+            // TODO: notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL);
+            mSignalledError = true;
+            return;
+        }
+
+        bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF));
+
+        getVUIParams();
+
+        GETTIME(&mTimeEnd, NULL);
+        /* Compute time taken for decode() */
+        TIME_DIFF(mTimeStart, mTimeEnd, timeTaken);
+
+        PRINT_TIME("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay,
+               s_dec_op.u4_num_bytes_consumed);
+        ALOGI("bytes total=%u", input.capacity());
+        if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) {
+            mFlushNeeded = true;
+        }
+
+        if (1 != s_dec_op.u4_frame_decoded_flag) {
+            /* If the input did not contain picture data, then ignore
+             * the associated timestamp */
+            //mTimeStampsValid[workIndex] = false;
+        }
+
+        // If the decoder is in the changing resolution mode and there is no output present,
+        // that means the switching is done and it's ready to reset the decoder and the plugin.
+        if (mChangingResolution && !s_dec_op.u4_output_present) {
+            ALOGV("changing resolution");
+            mChangingResolution = false;
+            resetDecoder();
+            resetPlugin();
+            mStride = mWidth;
+            setParams(mStride);
+            return;
+        }
+
+        if (resChanged) {
+            ALOGV("res changed");
+            mChangingResolution = true;
+            if (mFlushNeeded) {
+                setFlushMode();
+            }
+            return;
+        }
+
+        // Combine the resolution change and coloraspects change in one PortSettingChange event
+        // if necessary.
+        if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) {
+            uint32_t width = s_dec_op.u4_pic_wd;
+            uint32_t height = s_dec_op.u4_pic_ht;
+            ALOGV("width = %u height = %u", width, height);
+            if (width != mWidth || height != mHeight) {
+                mAllocatedBlock.reset();
+                mWidth = width;
+                mHeight = height;
+            }
+        } else if (mUpdateColorAspects) {
+            //notify(OMX_EventPortSettingsChanged, kOutputPortIndex,
+            //    kDescribeColorAspectsIndex, NULL);
+            ALOGV("update color aspect");
+            mUpdateColorAspects = false;
+            return;
+        }
+
+        if (s_dec_op.u4_output_present) {
+            ALOGV("output_present");
+            // TODO: outHeader->nFilledLen = (mWidth * mHeight * 3) / 2;
+            std::vector<std::unique_ptr<C2Work>> done;
+            done.push_back(std::move(mPendingWork[s_dec_op.u4_ts]));
+            done[0]->worklets.front()->output.buffers.clear();
+            done[0]->worklets.front()->output.buffers.emplace_back(
+                    std::make_shared<GraphicBuffer>(std::move(mAllocatedBlock)));
+            done[0]->worklets.front()->output.ordinal = done[0]->input.ordinal;
+            mListener->onWorkDone(shared_from_this(), std::move(done));
+        } else if (mIsInFlush) {
+            ALOGV("flush");
+            /* If in flush mode and no output is returned by the codec,
+             * then come out of flush mode */
+            mIsInFlush = false;
+
+            /* If EOS was recieved on input port and there is no output
+             * from the codec, then signal EOS on output port */
+            if (mReceivedEOS) {
+                // TODO
+                // outHeader->nFilledLen = 0;
+                // outHeader->nFlags |= OMX_BUFFERFLAG_EOS;
+
+                // outInfo->mOwnedByUs = false;
+                // outQueue.erase(outQueue.begin());
+                // outInfo = NULL;
+                // notifyFillBufferDone(outHeader);
+                // outHeader = NULL;
+                resetPlugin();
+            }
+        }
+        inOffset += s_dec_op.u4_num_bytes_consumed;
+    }
+    /* If input EOS is seen and decoder is not in flush mode,
+     * set the decoder in flush mode.
+     * There can be a case where EOS is sent along with last picture data
+     * In that case, only after decoding that input data, decoder has to be
+     * put in flush. This case is handled here  */
+
+    if (mReceivedEOS && !mIsInFlush) {
+        setFlushMode();
+    }
+}
+
+bool C2SoftAvcDec::colorAspectsDiffer(
+        const ColorAspects &a, const ColorAspects &b) {
+    if (a.mRange != b.mRange
+        || a.mPrimaries != b.mPrimaries
+        || a.mTransfer != b.mTransfer
+        || a.mMatrixCoeffs != b.mMatrixCoeffs) {
+        return true;
+    }
+    return false;
+}
+
+void C2SoftAvcDec::updateFinalColorAspects(
+        const ColorAspects &otherAspects, const ColorAspects &preferredAspects) {
+    Mutex::Autolock autoLock(mColorAspectsLock);
+    ColorAspects newAspects;
+    newAspects.mRange = preferredAspects.mRange != ColorAspects::RangeUnspecified ?
+        preferredAspects.mRange : otherAspects.mRange;
+    newAspects.mPrimaries = preferredAspects.mPrimaries != ColorAspects::PrimariesUnspecified ?
+        preferredAspects.mPrimaries : otherAspects.mPrimaries;
+    newAspects.mTransfer = preferredAspects.mTransfer != ColorAspects::TransferUnspecified ?
+        preferredAspects.mTransfer : otherAspects.mTransfer;
+    newAspects.mMatrixCoeffs = preferredAspects.mMatrixCoeffs != ColorAspects::MatrixUnspecified ?
+        preferredAspects.mMatrixCoeffs : otherAspects.mMatrixCoeffs;
+
+    // Check to see if need update mFinalColorAspects.
+    if (colorAspectsDiffer(mFinalColorAspects, newAspects)) {
+        mFinalColorAspects = newAspects;
+        mUpdateColorAspects = true;
+    }
+}
+
+status_t C2SoftAvcDec::handleColorAspectsChange() {
+//    int perference = getColorAspectPreference();
+//    ALOGD("Color Aspects preference: %d ", perference);
+//
+//     if (perference == kPreferBitstream) {
+//         updateFinalColorAspects(mDefaultColorAspects, mBitstreamColorAspects);
+//     } else if (perference == kPreferContainer) {
+//         updateFinalColorAspects(mBitstreamColorAspects, mDefaultColorAspects);
+//     } else {
+//         return OMX_ErrorUnsupportedSetting;
+//     }
+    updateFinalColorAspects(mDefaultColorAspects, mBitstreamColorAspects);
+    return C2_OK;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/codecs/avcdec/C2SoftAvcDec.h b/media/libstagefright/codecs/avcdec/C2SoftAvcDec.h
new file mode 100644
index 0000000..6a83d1d
--- /dev/null
+++ b/media/libstagefright/codecs/avcdec/C2SoftAvcDec.h
@@ -0,0 +1,312 @@
+/*
+ * Copyright 2016 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 C2_SOFT_H264_DEC_H_
+
+#define C2_SOFT_H264_DEC_H_
+
+#include <condition_variable>
+#include <map>
+#include <memory>
+#include <mutex>
+#include <set>
+#include <unordered_map>
+
+#include <util/C2ParamUtils.h>
+
+#include <C2Component.h>
+#include <C2Param.h>
+
+#include "C2AvcConfig.h"
+
+#include <media/stagefright/foundation/ABase.h>
+#include <media/stagefright/foundation/ColorUtils.h>
+
+#include <sys/time.h>
+
+namespace android {
+
+struct iv_obj_t;
+struct ivd_video_decode_ip_t;
+struct ivd_video_decode_op_t;
+
+/** Number of entries in the time-stamp array */
+#define MAX_PENDING_WORKS 64
+
+/** Maximum number of cores supported by the codec */
+#define CODEC_MAX_NUM_CORES 4
+
+#define CODEC_MAX_WIDTH     1920
+
+#define CODEC_MAX_HEIGHT    1088
+
+/** Input buffer size */
+#define INPUT_BUF_SIZE (1024 * 1024)
+
+#define MIN(a, b) ((a) < (b)) ? (a) : (b)
+
+/** Used to remove warnings about unused parameters */
+#define UNUSED(x) ((void)(x))
+
+/** Get time */
+#define GETTIME(a, b) gettimeofday(a, b);
+
+/** Compute difference between start and end */
+#define TIME_DIFF(start, end, diff) \
+    diff = (((end).tv_sec - (start).tv_sec) * 1000000) + \
+            ((end).tv_usec - (start).tv_usec);
+
+
+class C2SoftAvcDecIntf : public C2ComponentInterface {
+public:
+    struct SupportedValuesWithFields {
+        C2FieldSupportedValues supported;
+        std::set<C2ParamField> restrictingFields;
+
+        SupportedValuesWithFields(const C2FieldSupportedValues &supported) : supported(supported) {}
+    };
+
+    C2SoftAvcDecIntf(const char *name, node_id id);
+    virtual ~C2SoftAvcDecIntf() = default;
+
+    // From C2ComponentInterface
+    virtual C2String getName() const override;
+    virtual node_id getId() const override;
+    virtual status_t query_nb(
+            const std::vector<C2Param* const> &stackParams,
+            const std::vector<C2Param::Index> &heapParamIndices,
+            std::vector<std::unique_ptr<C2Param>>* const heapParams) const override;
+    virtual status_t config_nb(
+            const std::vector<C2Param* const> &params,
+            std::vector<std::unique_ptr<C2SettingResult>>* const failures) override;
+    virtual status_t commit_sm(
+            const std::vector<C2Param* const> &params,
+            std::vector<std::unique_ptr<C2SettingResult>>* const failures) override;
+    virtual status_t createTunnel_sm(node_id targetComponent) override;
+    virtual status_t releaseTunnel_sm(node_id targetComponent) override;
+    virtual std::shared_ptr<C2ParamReflector> getParamReflector() const override;
+    virtual status_t getSupportedParams(
+            std::vector<std::shared_ptr<C2ParamDescriptor>> * const params) const override;
+    virtual status_t getSupportedValues(
+            const std::vector<const C2ParamField> &fields,
+            std::vector<C2FieldSupportedValues>* const values) const override;
+
+private:
+    class ParamReflector;
+
+    const C2String mName;
+    const node_id mId;
+
+    C2ComponentDomainInfo mDomainInfo;
+    // TODO: config desc
+    std::unique_ptr<C2PortMimeConfig::input> mInputPortMime;
+    C2PortStreamCountConfig::input mInputStreamCount;
+    std::unique_ptr<C2PortMimeConfig::output> mOutputPortMime;
+    C2PortStreamCountConfig::output mOutputStreamCount;
+    // TODO: C2StreamMimeConfig mInputStreamMime;
+    // TODO: C2StreamMimeConfig mOutputStreamMime;
+    C2StreamFormatConfig::input mInputStreamFormat;
+    C2StreamFormatConfig::output mOutputStreamFormat;
+    C2VideoSizeStreamInfo::output mVideoSize;
+    C2MaxVideoSizeHintPortSetting::input mMaxVideoSizeHint;
+    C2AvcProfileInfo::input mProfile;
+    C2AvcLevelInfo::input mLevel;
+    C2BlockSizeInfo::output mBlockSize;
+    C2AlignmentInfo::output mAlignment;
+    C2FrameRateInfo::output mFrameRate;
+    C2BlocksPerSecondInfo::output mBlocksPerSecond;
+
+    std::shared_ptr<C2ParamReflector> mParamReflector;
+
+    std::unordered_map<uint32_t, C2Param *> mParams;
+    // C2ParamField is LessThanComparable
+    std::map<C2ParamField, SupportedValuesWithFields> mSupportedValues;
+    std::unordered_map<
+            uint32_t, std::function<std::unique_ptr<C2SettingResult>(C2Param *)>> mFieldVerifiers;
+    std::vector<std::shared_ptr<C2ParamDescriptor>> mParamDescs;
+
+    void updateSupportedValues();
+};
+
+class C2SoftAvcDec
+    : public C2Component,
+      public std::enable_shared_from_this<C2SoftAvcDec> {
+public:
+    C2SoftAvcDec(
+            const char *name, node_id id, const std::shared_ptr<C2ComponentListener> &listener);
+    virtual ~C2SoftAvcDec();
+
+    // From C2Component
+    virtual status_t queue_nb(std::list<std::unique_ptr<C2Work>>* const items) override;
+    virtual status_t announce_nb(const std::vector<C2WorkOutline> &items) override;
+    virtual status_t flush_sm(
+            bool flushThrough, std::list<std::unique_ptr<C2Work>>* const flushedWork) override;
+    virtual status_t drain_nb(bool drainThrough) override;
+    virtual status_t start() override;
+    virtual status_t stop() override;
+    virtual void reset() override;
+    virtual void release() override;
+    virtual std::shared_ptr<C2ComponentInterface> intf() override;
+
+private:
+    class QueueProcessThread;
+
+    Mutex mColorAspectsLock;
+    // color aspects passed from the framework.
+    ColorAspects mDefaultColorAspects;
+    // color aspects parsed from the bitstream.
+    ColorAspects mBitstreamColorAspects;
+    // final color aspects after combining the above two aspects.
+    ColorAspects mFinalColorAspects;
+    bool mUpdateColorAspects;
+
+    bool colorAspectsDiffer(const ColorAspects &a, const ColorAspects &b);
+
+    // This functions takes two color aspects and updates the mFinalColorAspects
+    // based on |preferredAspects|.
+    void updateFinalColorAspects(
+            const ColorAspects &otherAspects, const ColorAspects &preferredAspects);
+
+    // This function will update the mFinalColorAspects based on codec preference.
+    status_t handleColorAspectsChange();
+
+    // Number of input and output buffers
+    enum {
+        kNumBuffers = 8
+    };
+
+    using IndexType = decltype(C2WorkOrdinalStruct().frame_index);
+
+    const std::shared_ptr<C2SoftAvcDecIntf> mIntf;
+    const std::shared_ptr<C2ComponentListener> mListener;
+
+    std::mutex mQueueLock;
+    std::condition_variable mQueueCond;
+    std::list<std::unique_ptr<C2Work>> mQueue;
+
+    std::mutex mPendingLock;
+    std::unordered_map<IndexType, std::unique_ptr<C2Work>> mPendingWork;
+
+    std::unique_ptr<QueueProcessThread> mThread;
+
+    std::shared_ptr<C2GraphicBlock> mAllocatedBlock;
+
+    iv_obj_t *mCodecCtx;         // Codec context
+
+    size_t mNumCores;            // Number of cores to be uesd by the codec
+
+    struct timeval mTimeStart;   // Time at the start of decode()
+    struct timeval mTimeEnd;     // Time at the end of decode()
+
+    // Internal buffer to be used to flush out the buffers from decoder
+    uint8_t *mFlushOutBuffer;
+
+#ifdef FILE_DUMP_ENABLE
+    char mInFile[200];
+#endif /* FILE_DUMP_ENABLE */
+
+    int mIvColorFormat;        // Ittiam Color format
+
+    bool mIsInFlush;        // codec is flush mode
+    bool mReceivedEOS;      // EOS is receieved on input port
+
+    // The input stream has changed to a different resolution, which is still supported by the
+    // codec. So the codec is switching to decode the new resolution.
+    bool mChangingResolution;
+    bool mFlushNeeded;
+    bool mSignalledError;
+    int32_t mWidth;
+    int32_t mHeight;
+    int32_t mStride;
+    size_t mInputOffset;
+
+    void processQueue();
+    void process(std::unique_ptr<C2Work> &work);
+
+    status_t initDecoder();
+    status_t deInitDecoder();
+    status_t setFlushMode();
+    status_t setParams(size_t stride);
+    void logVersion();
+    status_t setNumCores();
+    status_t resetDecoder();
+    status_t resetPlugin();
+
+    bool setDecodeArgs(
+            ivd_video_decode_ip_t *ps_dec_ip,
+            ivd_video_decode_op_t *ps_dec_op,
+            C2ReadView *inBuffer,
+            C2GraphicView *outBuffer,
+            uint32_t timeStampIx,
+            size_t inOffset);
+
+    bool getVUIParams();
+
+    DISALLOW_EVIL_CONSTRUCTORS(C2SoftAvcDec);
+};
+
+#ifdef FILE_DUMP_ENABLE
+
+#define INPUT_DUMP_PATH     "/sdcard/media/avcd_input"
+#define INPUT_DUMP_EXT      "h264"
+
+#define GENERATE_FILE_NAMES() {                         \
+    GETTIME(&mTimeStart, NULL);                         \
+    strcpy(mInFile, "");                                \
+    sprintf(mInFile, "%s_%ld.%ld.%s", INPUT_DUMP_PATH,  \
+            mTimeStart.tv_sec, mTimeStart.tv_usec,      \
+            INPUT_DUMP_EXT);                            \
+}
+
+#define CREATE_DUMP_FILE(m_filename) {                  \
+    FILE *fp = fopen(m_filename, "wb");                 \
+    if (fp != NULL) {                                   \
+        fclose(fp);                                     \
+    } else {                                            \
+        ALOGD("Could not open file %s", m_filename);    \
+    }                                                   \
+}
+#define DUMP_TO_FILE(m_filename, m_buf, m_size, m_offset)\
+{                                                       \
+    FILE *fp = fopen(m_filename, "ab");                 \
+    if (fp != NULL && m_buf != NULL && m_offset == 0) { \
+        int i;                                          \
+        i = fwrite(m_buf, 1, m_size, fp);               \
+        ALOGD("fwrite ret %d to write %d", i, m_size);  \
+        if (i != (int) m_size) {                        \
+            ALOGD("Error in fwrite, returned %d", i);   \
+            perror("Error in write to file");           \
+        }                                               \
+    } else if (fp == NULL) {                            \
+        ALOGD("Could not write to file %s", m_filename);\
+    }                                                   \
+    if (fp) {                                           \
+        fclose(fp);                                     \
+    }                                                   \
+}
+#else /* FILE_DUMP_ENABLE */
+#define INPUT_DUMP_PATH
+#define INPUT_DUMP_EXT
+#define OUTPUT_DUMP_PATH
+#define OUTPUT_DUMP_EXT
+#define GENERATE_FILE_NAMES()
+#define CREATE_DUMP_FILE(m_filename)
+#define DUMP_TO_FILE(m_filename, m_buf, m_size, m_offset)
+#endif /* FILE_DUMP_ENABLE */
+
+} // namespace android
+
+#endif  // C2_SOFT_H264_DEC_H_
diff --git a/media/libstagefright/codecs/cmds/Android.bp b/media/libstagefright/codecs/cmds/Android.bp
new file mode 100644
index 0000000..e44e53c
--- /dev/null
+++ b/media/libstagefright/codecs/cmds/Android.bp
@@ -0,0 +1,50 @@
+cc_binary {
+    name: "codec2",
+
+    srcs: [
+        "codec2.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/av/media/libstagefright/codec2/vndk/include",
+    ],
+
+    shared_libs: [
+        "android.hardware.graphics.allocator@2.0",
+        "android.hardware.graphics.mapper@2.0",
+        "libbinder",
+        "libcutils",
+        "libgui",
+        "libhidlbase",
+        "libion",
+        "liblog",
+        "libstagefright",
+        "libstagefright_codec2",
+        "libstagefright_foundation",
+        "libstagefright_soft_c2avcdec",
+        "libui",
+        "libutils",
+    ],
+
+    static_libs: [
+        "libstagefright_codec2_vndk",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-std=c++14",
+    ],
+
+//    sanitize: {
+//        cfi: true,
+//        misc_undefined: [
+//            "unsigned-integer-overflow",
+//            "signed-integer-overflow",
+//        ],
+//        diag: {
+//            cfi: true,
+//        },
+//    },
+}
diff --git a/media/libstagefright/codecs/cmds/codec2.cpp b/media/libstagefright/codecs/cmds/codec2.cpp
new file mode 100644
index 0000000..ad4da9b
--- /dev/null
+++ b/media/libstagefright/codecs/cmds/codec2.cpp
@@ -0,0 +1,464 @@
+/*
+ * Copyright (C) 2017 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 <inttypes.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <thread>
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "codec2"
+#include <media/stagefright/foundation/ADebug.h>
+
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+#include <media/ICrypto.h>
+#include <media/IMediaHTTPService.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/ALooper.h>
+#include <media/stagefright/foundation/AMessage.h>
+#include <media/stagefright/foundation/AUtils.h>
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/Utils.h>
+
+#include <gui/GLConsumer.h>
+#include <gui/IProducerListener.h>
+#include <gui/Surface.h>
+#include <gui/SurfaceComposerClient.h>
+
+#include <util/C2ParamUtils.h>
+#include <C2Buffer.h>
+#include <C2BufferPriv.h>
+#include <C2Component.h>
+#include <C2Work.h>
+
+#include "../avcdec/C2SoftAvcDec.h"
+
+using namespace android;
+using namespace std::chrono_literals;
+
+namespace {
+
+class LinearBuffer : public C2Buffer {
+public:
+    explicit LinearBuffer(const std::shared_ptr<C2LinearBlock> &block)
+        : C2Buffer({ block->share(block->offset(), block->size(), ::android::C2Fence()) }) {}
+};
+
+class Listener;
+
+class SimplePlayer {
+public:
+    SimplePlayer();
+    ~SimplePlayer();
+
+    void onWorkDone(std::weak_ptr<C2Component> component,
+                    std::vector<std::unique_ptr<C2Work>> workItems);
+    void onTripped(std::weak_ptr<C2Component> component,
+                   std::vector<std::shared_ptr<C2SettingResult>> settingResult);
+    void onError(std::weak_ptr<C2Component> component, uint32_t errorCode);
+
+    void play(const sp<IMediaSource> &source);
+
+private:
+    typedef std::unique_lock<std::mutex> ULock;
+
+    std::shared_ptr<Listener> mListener;
+    std::shared_ptr<C2Component> mComponent;
+
+    sp<IProducerListener> mProducerListener;
+
+    std::shared_ptr<C2Allocator> mAllocIon;
+    std::shared_ptr<C2Allocator> mAllocGralloc;
+    std::shared_ptr<C2BlockAllocator> mLinearAlloc;
+    std::shared_ptr<C2BlockAllocator> mGraphicAlloc;
+
+    std::mutex mQueueLock;
+    std::condition_variable mQueueCondition;
+    std::list<std::unique_ptr<C2Work>> mWorkQueue;
+
+    std::mutex mProcessedLock;
+    std::condition_variable mProcessedCondition;
+    std::list<std::unique_ptr<C2Work>> mProcessedWork;
+
+    sp<Surface> mSurface;
+    sp<SurfaceComposerClient> mComposerClient;
+    sp<SurfaceControl> mControl;
+};
+
+class Listener : public C2ComponentListener {
+public:
+    explicit Listener(SimplePlayer *thiz) : mThis(thiz) {}
+    virtual ~Listener() = default;
+
+    virtual void onWorkDone(std::weak_ptr<C2Component> component,
+                            std::vector<std::unique_ptr<C2Work>> workItems) override {
+        mThis->onWorkDone(component, std::move(workItems));
+    }
+
+    virtual void onTripped(std::weak_ptr<C2Component> component,
+                           std::vector<std::shared_ptr<C2SettingResult>> settingResult) override {
+        mThis->onTripped(component, settingResult);
+    }
+
+    virtual void onError(std::weak_ptr<C2Component> component,
+                         uint32_t errorCode) override {
+        mThis->onError(component, errorCode);
+    }
+
+private:
+    SimplePlayer * const mThis;
+};
+
+
+SimplePlayer::SimplePlayer()
+    : mListener(new Listener(this)),
+      mProducerListener(new DummyProducerListener),
+      mAllocIon(new C2AllocatorIon),
+      mAllocGralloc(new C2AllocatorGralloc),
+      mLinearAlloc(new C2DefaultBlockAllocator(mAllocIon)),
+      mGraphicAlloc(new C2DefaultGraphicBlockAllocator(mAllocGralloc)),
+      mComposerClient(new SurfaceComposerClient) {
+    CHECK_EQ(mComposerClient->initCheck(), (status_t)OK);
+
+    mControl = mComposerClient->createSurface(
+            String8("A Surface"),
+            1280,
+            800,
+            HAL_PIXEL_FORMAT_YV12);
+            //PIXEL_FORMAT_RGB_565);
+
+    CHECK(mControl != NULL);
+    CHECK(mControl->isValid());
+
+    SurfaceComposerClient::openGlobalTransaction();
+    CHECK_EQ(mControl->setLayer(INT_MAX), (status_t)OK);
+    CHECK_EQ(mControl->show(), (status_t)OK);
+    SurfaceComposerClient::closeGlobalTransaction();
+
+    mSurface = mControl->getSurface();
+    CHECK(mSurface != NULL);
+    mSurface->connect(NATIVE_WINDOW_API_CPU, mProducerListener);
+}
+
+SimplePlayer::~SimplePlayer() {
+    mComposerClient->dispose();
+}
+
+void SimplePlayer::onWorkDone(
+        std::weak_ptr<C2Component> component, std::vector<std::unique_ptr<C2Work>> workItems) {
+    (void) component;
+    ULock l(mProcessedLock);
+    for (auto & item : workItems) {
+        mProcessedWork.push_back(std::move(item));
+    }
+    mProcessedCondition.notify_all();
+}
+
+void SimplePlayer::onTripped(
+        std::weak_ptr<C2Component> component,
+        std::vector<std::shared_ptr<C2SettingResult>> settingResult) {
+    (void) component;
+    (void) settingResult;
+    // TODO
+}
+
+void SimplePlayer::onError(std::weak_ptr<C2Component> component, uint32_t errorCode) {
+    (void) component;
+    (void) errorCode;
+    // TODO
+}
+
+void SimplePlayer::play(const sp<IMediaSource> &source) {
+    sp<AMessage> format;
+    (void) convertMetaDataToMessage(source->getFormat(), &format);
+
+    sp<ABuffer> csd0, csd1;
+    format->findBuffer("csd-0", &csd0);
+    format->findBuffer("csd-1", &csd1);
+
+    status_t err = source->start();
+
+    if (err != OK) {
+        fprintf(stderr, "source returned error %d (0x%08x)\n", err, err);
+        return;
+    }
+
+    std::shared_ptr<C2Component> component(std::make_shared<C2SoftAvcDec>("avc", 0, mListener));
+    component->start();
+
+    for (int i = 0; i < 8; ++i) {
+        mWorkQueue.emplace_back(new C2Work);
+    }
+
+    std::atomic_bool running(true);
+    std::thread surfaceThread([this, &running]() {
+        const sp<IGraphicBufferProducer> &igbp = mSurface->getIGraphicBufferProducer();
+        while (running) {
+            std::unique_ptr<C2Work> work;
+            {
+                ULock l(mProcessedLock);
+                if (mProcessedWork.empty()) {
+                    mProcessedCondition.wait_for(l, 100ms);
+                    if (mProcessedWork.empty()) {
+                        continue;
+                    }
+                }
+                work.swap(mProcessedWork.front());
+                mProcessedWork.pop_front();
+            }
+            int slot;
+            sp<Fence> fence;
+            const std::shared_ptr<C2Buffer> &output = work->worklets.front()->output.buffers[0];
+            const C2ConstGraphicBlock &block = output->data().graphicBlocks().front();
+            sp<GraphicBuffer> buffer(new GraphicBuffer(
+                    block.handle(),
+                    GraphicBuffer::CLONE_HANDLE,
+                    block.width(),
+                    block.height(),
+                    HAL_PIXEL_FORMAT_YV12,
+                    1,
+                    (uint64_t)GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
+                    block.width()));
+
+            status_t err = igbp->attachBuffer(&slot, buffer);
+
+            IGraphicBufferProducer::QueueBufferInput qbi(
+                    work->worklets.front()->output.ordinal.timestamp * 1000ll,
+                    false,
+                    HAL_DATASPACE_UNKNOWN,
+                    Rect(block.width(), block.height()),
+                    NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW,
+                    0,
+                    Fence::NO_FENCE,
+                    0);
+            IGraphicBufferProducer::QueueBufferOutput qbo;
+            err = igbp->queueBuffer(slot, qbi, &qbo);
+
+            work->input.buffers.clear();
+            work->worklets.clear();
+
+            ULock l(mQueueLock);
+            mWorkQueue.push_back(std::move(work));
+            mQueueCondition.notify_all();
+        }
+    });
+
+    long numFrames = 0;
+    mLinearAlloc.reset(new C2DefaultBlockAllocator(mAllocIon));
+
+    for (;;) {
+        size_t size = 0u;
+        void *data = nullptr;
+        int64_t timestamp = 0u;
+        MediaBuffer *buffer = nullptr;
+        sp<ABuffer> csd;
+        if (csd0 != nullptr) {
+            csd = csd0;
+            csd0 = nullptr;
+        } else if (csd1 != nullptr) {
+            csd = csd1;
+            csd1 = nullptr;
+        } else {
+            status_t err = source->read(&buffer);
+            if (err != OK) {
+                CHECK(buffer == NULL);
+
+                if (err == INFO_FORMAT_CHANGED) {
+                    continue;
+                }
+
+                break;
+            }
+            sp<MetaData> meta = buffer->meta_data();
+            CHECK(meta->findInt64(kKeyTime, &timestamp));
+
+            size = buffer->size();
+            data = buffer->data();
+        }
+
+        if (csd != nullptr) {
+            size = csd->size();
+            data = csd->data();
+        }
+
+        // Prepare C2Work
+
+        std::unique_ptr<C2Work> work;
+        while (!work) {
+            ULock l(mQueueLock);
+            if (!mWorkQueue.empty()) {
+                work.swap(mWorkQueue.front());
+                mWorkQueue.pop_front();
+            } else {
+                mQueueCondition.wait_for(l, 100ms);
+            }
+        }
+        work->input.flags = (flags_t)0;
+        work->input.ordinal.timestamp = timestamp;
+        work->input.ordinal.frame_index = numFrames;
+
+        std::shared_ptr<C2LinearBlock> block;
+        mLinearAlloc->allocateLinearBlock(
+                size,
+                { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                &block);
+        C2WriteView view = block->map().get();
+        if (view.error() != C2_OK) {
+            fprintf(stderr, "C2LinearBlock::map() failed : %d", view.error());
+            break;
+        }
+        memcpy(view.base(), data, size);
+
+        work->input.buffers.clear();
+        work->input.buffers.emplace_back(new LinearBuffer(block));
+        work->worklets.clear();
+        work->worklets.emplace_back(new C2Worklet);
+        work->worklets.front()->allocators.emplace_back(mGraphicAlloc);
+
+        std::list<std::unique_ptr<C2Work>> items;
+        items.push_back(std::move(work));
+
+        // DO THE DECODING
+        component->queue_nb(&items);
+
+        if (buffer) {
+            buffer->release();
+            buffer = NULL;
+        }
+
+        ++numFrames;
+    }
+    source->stop();
+    component->release();
+
+    running.store(false);
+    surfaceThread.join();
+    printf("\n");
+}
+
+}  // namespace
+
+static void usage(const char *me) {
+    fprintf(stderr, "usage: %s [options] [input_filename]\n", me);
+    fprintf(stderr, "       -h(elp)\n");
+}
+
+int main(int argc, char **argv) {
+    android::ProcessState::self()->startThreadPool();
+
+    int res;
+    while ((res = getopt(argc, argv, "h")) >= 0) {
+        switch (res) {
+            case 'h':
+            default:
+            {
+                usage(argv[0]);
+                exit(1);
+                break;
+            }
+        }
+    }
+
+    argc -= optind;
+    argv += optind;
+
+    if (argc < 1) {
+        fprintf(stderr, "No input file specified\n");
+        return 1;
+    }
+
+    status_t err = OK;
+    SimplePlayer player;
+
+    for (int k = 0; k < argc && err == OK; ++k) {
+        const char *filename = argv[k];
+
+        sp<DataSource> dataSource =
+            DataSource::CreateFromURI(NULL /* httpService */, filename);
+
+        if (strncasecmp(filename, "sine:", 5) && dataSource == NULL) {
+            fprintf(stderr, "Unable to create data source.\n");
+            return 1;
+        }
+
+        Vector<sp<IMediaSource> > mediaSources;
+        sp<IMediaSource> mediaSource;
+
+        sp<IMediaExtractor> extractor = MediaExtractor::Create(dataSource);
+
+        if (extractor == NULL) {
+            fprintf(stderr, "could not create extractor.\n");
+            return -1;
+        }
+
+        sp<MetaData> meta = extractor->getMetaData();
+
+        if (meta != NULL) {
+            const char *mime;
+            if (!meta->findCString(kKeyMIMEType, &mime)) {
+                fprintf(stderr, "extractor did not provide MIME type.\n");
+                return -1;
+            }
+        }
+
+        size_t numTracks = extractor->countTracks();
+
+        size_t i;
+        for (i = 0; i < numTracks; ++i) {
+            meta = extractor->getTrackMetaData(
+                    i, MediaExtractor::kIncludeExtensiveMetaData);
+
+            if (meta == NULL) {
+                break;
+            }
+            const char *mime;
+            meta->findCString(kKeyMIMEType, &mime);
+
+            // TODO: allowing AVC only for the time being
+            if (!strncasecmp(mime, "video/avc", 9)) {
+                break;
+            }
+
+            meta = NULL;
+        }
+
+        if (meta == NULL) {
+            fprintf(stderr, "No AVC track found.\n");
+            return -1;
+        }
+
+        mediaSource = extractor->getTrack(i);
+        if (mediaSource == nullptr) {
+            fprintf(stderr, "skip NULL track %zu, total tracks %zu.\n", i, numTracks);
+            return -1;
+        }
+
+        player.play(mediaSource);
+    }
+
+    return 0;
+}
diff --git a/media/libstagefright/codecs/tests/Android.mk b/media/libstagefright/codecs/tests/Android.mk
new file mode 100644
index 0000000..dcb86ba
--- /dev/null
+++ b/media/libstagefright/codecs/tests/Android.mk
@@ -0,0 +1,40 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+	C2SoftAvcDec_test.cpp \
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE := c2_google_component_test
+
+LOCAL_SHARED_LIBRARIES := \
+	libcutils \
+	libmedia \
+	libstagefright_codec2 \
+	libstagefright_soft_c2avcdec \
+	liblog \
+
+LOCAL_C_INCLUDES := \
+	frameworks/av/media/libstagefright/codec2/include \
+	frameworks/av/media/libstagefright/codec2/vndk/include \
+	frameworks/av/media/libstagefright/codecs/avcdec \
+
+LOCAL_CFLAGS += -Werror -Wall -std=c++14
+LOCAL_CLANG := true
+
+include $(BUILD_NATIVE_TEST)
diff --git a/media/libstagefright/codecs/tests/C2SoftAvcDec_test.cpp b/media/libstagefright/codecs/tests/C2SoftAvcDec_test.cpp
new file mode 100644
index 0000000..e59c03e
--- /dev/null
+++ b/media/libstagefright/codecs/tests/C2SoftAvcDec_test.cpp
@@ -0,0 +1,185 @@
+/*
+ * Copyright 2017 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 "C2SoftAvcDec_test"
+#include <utils/Log.h>
+
+#include <gtest/gtest.h>
+
+#include <media/MediaDefs.h>
+
+#include "C2SoftAvcDec.h"
+
+namespace android {
+
+namespace {
+
+template <class T>
+std::unique_ptr<T> alloc_unique_cstr(const char *cstr) {
+    std::unique_ptr<T> ptr = T::alloc_unique(strlen(cstr) + 1);
+    strcpy(ptr->m.mValue, cstr);
+    return ptr;
+}
+
+}  // namespace
+
+
+class C2SoftAvcDecTest : public ::testing::Test {
+public:
+    C2SoftAvcDecTest() : mIntf(new C2SoftAvcDecIntf("dummy", 0u)) {}
+    ~C2SoftAvcDecTest() = default;
+
+    template <typename T>
+    void testReadOnlyParam(const T *expected, const T *invalid);
+
+    template <typename T>
+    void testReadOnlyParamOnStack(const T *expected, const T *invalid);
+
+    template <typename T>
+    void testReadOnlyParamOnHeap(const T *expected, const T *invalid);
+
+    template <typename T>
+    void testReadOnlyFlexParam(
+            const std::unique_ptr<T> &expected, const std::unique_ptr<T> &invalid);
+
+protected:
+    std::shared_ptr<C2SoftAvcDecIntf> mIntf;
+};
+
+template <typename T>
+void C2SoftAvcDecTest::testReadOnlyParam(const T *expected, const T *invalid) {
+    testReadOnlyParamOnStack(expected, invalid);
+    testReadOnlyParamOnHeap(expected, invalid);
+}
+
+template <typename T>
+void C2SoftAvcDecTest::testReadOnlyParamOnStack(const T *expected, const T *invalid) {
+    T param;
+    ASSERT_EQ(C2_OK, mIntf->query_nb({&param}, {}, nullptr));
+    ASSERT_EQ(*expected, param);
+
+    std::vector<C2Param * const> params{ (C2Param * const)invalid };
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+    ASSERT_EQ(C2_BAD_VALUE, mIntf->config_nb(params, &failures));
+
+    // The param must not change after failed config.
+    ASSERT_EQ(C2_OK, mIntf->query_nb({&param}, {}, nullptr));
+    ASSERT_EQ(*expected, param);
+}
+
+template <typename T>
+void C2SoftAvcDecTest::testReadOnlyParamOnHeap(const T *expected, const T *invalid) {
+    std::vector<std::unique_ptr<C2Param>> heapParams;
+
+    uint32_t index = expected->type();
+    if (expected->forStream()) {
+        index |= ((expected->stream() << 17) & 0x01FE0000) | 0x02000000;
+    }
+
+    ASSERT_EQ(C2_OK, mIntf->query_nb({}, {index}, &heapParams));
+    ASSERT_EQ(1u, heapParams.size());
+    ASSERT_EQ(*expected, *heapParams[0]);
+
+    std::vector<C2Param * const> params{ (C2Param * const)invalid };
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+    ASSERT_EQ(C2_BAD_VALUE, mIntf->config_nb(params, &failures));
+
+    // The param must not change after failed config.
+    heapParams.clear();
+    ASSERT_EQ(C2_OK, mIntf->query_nb({}, {index}, &heapParams));
+    ASSERT_EQ(1u, heapParams.size());
+    ASSERT_EQ(*expected, *heapParams[0]);
+}
+
+template <typename T>
+void C2SoftAvcDecTest::testReadOnlyFlexParam(
+        const std::unique_ptr<T> &expected, const std::unique_ptr<T> &invalid) {
+    std::vector<std::unique_ptr<C2Param>> heapParams;
+
+    uint32_t index = expected->type();
+    if (expected->forStream()) {
+        index |= ((expected->stream() << 17) & 0x01FE0000) | 0x02000000;
+    }
+
+    ASSERT_EQ(C2_OK, mIntf->query_nb({}, {index}, &heapParams));
+    ASSERT_EQ(1u, heapParams.size());
+    ASSERT_EQ(*expected, *heapParams[0]);
+
+    std::vector<C2Param * const> params{ invalid.get() };
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+    ASSERT_EQ(C2_BAD_VALUE, mIntf->config_nb(params, &failures));
+
+    // The param must not change after failed config.
+    heapParams.clear();
+    ASSERT_EQ(C2_OK, mIntf->query_nb({}, {index}, &heapParams));
+    ASSERT_EQ(1u, heapParams.size());
+    ASSERT_EQ(*expected, *heapParams[0]);
+}
+
+
+TEST_F(C2SoftAvcDecTest, TestNameAndId) {
+    EXPECT_STREQ("dummy", mIntf->getName().c_str());
+    EXPECT_EQ(0u, mIntf->getId());
+}
+
+TEST_F(C2SoftAvcDecTest, TestDomainInfo) {
+    C2ComponentDomainInfo expected(C2DomainVideo);
+    C2ComponentDomainInfo invalid(C2DomainAudio);
+    testReadOnlyParam(&expected, &invalid);
+}
+
+TEST_F(C2SoftAvcDecTest, TestInputStreamCount) {
+    C2PortStreamCountConfig::input expected(1);
+    C2PortStreamCountConfig::input invalid(100);
+    testReadOnlyParam(&expected, &invalid);
+}
+
+TEST_F(C2SoftAvcDecTest, TestOutputStreamCount) {
+    C2PortStreamCountConfig::output expected(1);
+    C2PortStreamCountConfig::output invalid(100);
+    testReadOnlyParam(&expected, &invalid);
+}
+
+TEST_F(C2SoftAvcDecTest, TestInputPortMime) {
+    std::unique_ptr<C2PortMimeConfig::input> expected(
+            alloc_unique_cstr<C2PortMimeConfig::input>(MEDIA_MIMETYPE_VIDEO_AVC));
+    std::unique_ptr<C2PortMimeConfig::input> invalid(
+            alloc_unique_cstr<C2PortMimeConfig::input>(MEDIA_MIMETYPE_VIDEO_RAW));
+    testReadOnlyFlexParam(expected, invalid);
+}
+
+TEST_F(C2SoftAvcDecTest, TestOutputPortMime) {
+    std::unique_ptr<C2PortMimeConfig::output> expected(
+            alloc_unique_cstr<C2PortMimeConfig::output>(MEDIA_MIMETYPE_VIDEO_RAW));
+    std::unique_ptr<C2PortMimeConfig::output> invalid(
+            alloc_unique_cstr<C2PortMimeConfig::output>(MEDIA_MIMETYPE_VIDEO_AVC));
+    testReadOnlyFlexParam(expected, invalid);
+}
+
+TEST_F(C2SoftAvcDecTest, TestInputStreamFormat) {
+    C2StreamFormatConfig::input expected(0u, C2FormatCompressed);
+    C2StreamFormatConfig::input invalid(0u, C2FormatVideo);
+    testReadOnlyParam(&expected, &invalid);
+}
+
+TEST_F(C2SoftAvcDecTest, TestOutputStreamFormat) {
+    C2StreamFormatConfig::output expected(0u, C2FormatVideo);
+    C2StreamFormatConfig::output invalid(0u, C2FormatCompressed);
+    testReadOnlyParam(&expected, &invalid);
+}
+
+} // namespace android
diff --git a/media/libstagefright/flac/dec/Android.bp b/media/libstagefright/flac/dec/Android.bp
index 1b9fe0f..bbbd8c0 100644
--- a/media/libstagefright/flac/dec/Android.bp
+++ b/media/libstagefright/flac/dec/Android.bp
@@ -30,7 +30,6 @@
     static_libs: ["libFLAC"],
 
     shared_libs: [
-        "libcutils",
         "liblog",
         "libstagefright_foundation",
         "libutils",
diff --git a/media/libstagefright/foundation/Android.bp b/media/libstagefright/foundation/Android.bp
index 221af1d..459ada1 100644
--- a/media/libstagefright/foundation/Android.bp
+++ b/media/libstagefright/foundation/Android.bp
@@ -13,6 +13,8 @@
     include_dirs: [
         "frameworks/av/include",
         "frameworks/native/include",
+        "frameworks/native/libs/arect/include",
+        "frameworks/native/libs/nativebase/include",
     ],
 
     local_include_dirs: [
@@ -30,7 +32,6 @@
 
     export_shared_lib_headers: [
         "libbinder",
-        "libui",
     ],
 
     cflags: [
@@ -42,7 +43,6 @@
     shared_libs: [
         "libbinder",
         "libutils",
-        "libui",
         "libcutils",
         "liblog",
         "libpowermanager",
diff --git a/media/libstagefright/http/Android.bp b/media/libstagefright/http/Android.bp
index 5d90b0a..2e49fc4 100644
--- a/media/libstagefright/http/Android.bp
+++ b/media/libstagefright/http/Android.bp
@@ -12,7 +12,6 @@
     shared_libs: [
         "liblog",
         "libutils",
-        "libbinder",
         "libandroid_runtime",
         "libmedia",
     ],
diff --git a/media/libstagefright/httplive/Android.bp b/media/libstagefright/httplive/Android.bp
index e415334..b10585e 100644
--- a/media/libstagefright/httplive/Android.bp
+++ b/media/libstagefright/httplive/Android.bp
@@ -39,5 +39,14 @@
         "libstagefright",
         "libstagefright_foundation",
         "libutils",
+        "libhidlbase",
+        "android.hardware.cas@1.0",
+        "android.hardware.cas.native@1.0",
     ],
+
+    static_libs: [
+        "libstagefright_id3",
+        "libstagefright_mpeg2support",
+    ],
+
 }
diff --git a/media/libstagefright/include/AACEncoder.h b/media/libstagefright/include/AACEncoder.h
deleted file mode 100644
index 462e905..0000000
--- a/media/libstagefright/include/AACEncoder.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2010 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_ENCODER_H
-#define AAC_ENCODER_H
-
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-
-struct VO_AUDIO_CODECAPI;
-struct VO_MEM_OPERATOR;
-
-namespace android {
-
-class MediaBufferGroup;
-
-class AACEncoder: public BnMediaSource {
-    public:
-        AACEncoder(const sp<IMediaSource> &source, const sp<MetaData> &meta);
-
-        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 ~AACEncoder();
-
-    private:
-        sp<IMediaSource>   mSource;
-        sp<MetaData>      mMeta;
-        bool              mStarted;
-        MediaBufferGroup *mBufferGroup;
-        MediaBuffer      *mInputBuffer;
-        status_t          mInitCheck;
-        int32_t           mSampleRate;
-        int32_t           mChannels;
-        int32_t           mBitRate;
-        int32_t           mFrameCount;
-
-        int64_t           mAnchorTimeUs;
-        int64_t           mNumInputSamples;
-
-        enum {
-            kNumSamplesPerFrame = 1024,
-        };
-
-        int16_t           *mInputFrame;
-
-        uint8_t           mAudioSpecificConfigData[2]; // auido specific data
-        void             *mEncoderHandle;
-        VO_AUDIO_CODECAPI *mApiHandle;
-        VO_MEM_OPERATOR  *mMemOperator;
-
-        status_t setAudioSpecificConfigData();
-        status_t initCheck();
-
-        AACEncoder& operator=(const AACEncoder &rhs);
-        AACEncoder(const AACEncoder& copy);
-
-};
-
-}
-
-#endif  //#ifndef AAC_ENCODER_H
-
diff --git a/media/libstagefright/include/media/stagefright/AACWriter.h b/media/libstagefright/include/media/stagefright/AACWriter.h
index a1f63d7..aa60a19 100644
--- a/media/libstagefright/include/media/stagefright/AACWriter.h
+++ b/media/libstagefright/include/media/stagefright/AACWriter.h
@@ -31,7 +31,7 @@
 
     status_t initCheck() const;
 
-    virtual status_t addSource(const sp<IMediaSource> &source);
+    virtual status_t addSource(const sp<MediaSource> &source);
     virtual bool reachedEOS();
     virtual status_t start(MetaData *params = NULL);
     virtual status_t stop() { return reset(); }
@@ -48,7 +48,7 @@
 
     int   mFd;
     status_t mInitCheck;
-    sp<IMediaSource> mSource;
+    sp<MediaSource> mSource;
     bool mStarted;
     volatile bool mPaused;
     volatile bool mResumed;
diff --git a/media/libstagefright/include/media/stagefright/AMRWriter.h b/media/libstagefright/include/media/stagefright/AMRWriter.h
index fbbdf2e..7d2c879 100644
--- a/media/libstagefright/include/media/stagefright/AMRWriter.h
+++ b/media/libstagefright/include/media/stagefright/AMRWriter.h
@@ -20,7 +20,6 @@
 
 #include <stdio.h>
 
-#include <media/IMediaSource.h>
 #include <media/stagefright/MediaWriter.h>
 #include <utils/threads.h>
 
@@ -33,7 +32,7 @@
 
     status_t initCheck() const;
 
-    virtual status_t addSource(const sp<IMediaSource> &source);
+    virtual status_t addSource(const sp<MediaSource> &source);
     virtual bool reachedEOS();
     virtual status_t start(MetaData *params = NULL);
     virtual status_t stop() { return reset(); }
@@ -45,7 +44,7 @@
 private:
     int   mFd;
     status_t mInitCheck;
-    sp<IMediaSource> mSource;
+    sp<MediaSource> mSource;
     bool mStarted;
     volatile bool mPaused;
     volatile bool mResumed;
diff --git a/media/libstagefright/include/media/stagefright/AudioPlayer.h b/media/libstagefright/include/media/stagefright/AudioPlayer.h
index f7499b6..581ead9 100644
--- a/media/libstagefright/include/media/stagefright/AudioPlayer.h
+++ b/media/libstagefright/include/media/stagefright/AudioPlayer.h
@@ -18,9 +18,9 @@
 
 #define AUDIO_PLAYER_H_
 
-#include <media/IMediaSource.h>
 #include <media/MediaPlayerInterface.h>
 #include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaSource.h>
 #include <utils/threads.h>
 
 namespace android {
@@ -50,7 +50,7 @@
     virtual ~AudioPlayer();
 
     // Caller retains ownership of "source".
-    void setSource(const sp<IMediaSource> &source);
+    void setSource(const sp<MediaSource> &source);
 
     status_t start(bool sourceAlreadyStarted = false);
 
@@ -66,7 +66,7 @@
     status_t getPlaybackRate(AudioPlaybackRate *rate /* nonnull */);
 
 private:
-    sp<IMediaSource> mSource;
+    sp<MediaSource> mSource;
     sp<AudioTrack> mAudioTrack;
 
     MediaBuffer *mInputBuffer;
diff --git a/media/libstagefright/include/media/stagefright/CallbackMediaSource.h b/media/libstagefright/include/media/stagefright/CallbackMediaSource.h
new file mode 100644
index 0000000..17fca4e
--- /dev/null
+++ b/media/libstagefright/include/media/stagefright/CallbackMediaSource.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2017, 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 CALLBACK_MEDIA_SOURCE_H_
+#define CALLBACK_MEDIA_SOURCE_H_
+
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/foundation/ABase.h>
+
+namespace android {
+
+// A stagefright MediaSource that wraps a binder IMediaSource.
+class CallbackMediaSource : public MediaSource {
+public:
+    explicit CallbackMediaSource(const sp<IMediaSource> &source);
+    virtual ~CallbackMediaSource();
+    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);
+    virtual status_t pause();
+    virtual status_t setBuffers(const Vector<MediaBuffer *> &buffers);
+
+private:
+    sp<IMediaSource> mSource;
+
+    DISALLOW_EVIL_CONSTRUCTORS(CallbackMediaSource);
+};
+
+}  // namespace android
+
+#endif  // CALLBACK_MEDIA_SOURCE_H_
diff --git a/media/libstagefright/include/media/stagefright/MPEG2TSWriter.h b/media/libstagefright/include/media/stagefright/MPEG2TSWriter.h
index 4516fb6..3d7960b 100644
--- a/media/libstagefright/include/media/stagefright/MPEG2TSWriter.h
+++ b/media/libstagefright/include/media/stagefright/MPEG2TSWriter.h
@@ -34,7 +34,7 @@
             void *cookie,
             ssize_t (*write)(void *cookie, const void *data, size_t size));
 
-    virtual status_t addSource(const sp<IMediaSource> &source);
+    virtual status_t addSource(const sp<MediaSource> &source);
     virtual status_t start(MetaData *param = NULL);
     virtual status_t stop() { return reset(); }
     virtual status_t pause();
diff --git a/media/libstagefright/include/media/stagefright/MPEG4Writer.h b/media/libstagefright/include/media/stagefright/MPEG4Writer.h
index 1c7b4a6..eba3b32 100644
--- a/media/libstagefright/include/media/stagefright/MPEG4Writer.h
+++ b/media/libstagefright/include/media/stagefright/MPEG4Writer.h
@@ -20,7 +20,6 @@
 
 #include <stdio.h>
 
-#include <media/IMediaSource.h>
 #include <media/stagefright/MediaWriter.h>
 #include <utils/List.h>
 #include <utils/threads.h>
@@ -40,7 +39,7 @@
     // Limitations
     // No more than one video and/or one audio source can be added, but
     // multiple metadata sources can be added.
-    virtual status_t addSource(const sp<IMediaSource> &source);
+    virtual status_t addSource(const sp<MediaSource> &source);
 
     // Returns INVALID_OPERATION if there is no source or track.
     virtual status_t start(MetaData *param = NULL);
diff --git a/media/libstagefright/include/media/stagefright/MediaClock.h b/media/libstagefright/include/media/stagefright/MediaClock.h
index dd1a809..7511913 100644
--- a/media/libstagefright/include/media/stagefright/MediaClock.h
+++ b/media/libstagefright/include/media/stagefright/MediaClock.h
@@ -18,7 +18,8 @@
 
 #define MEDIA_CLOCK_H_
 
-#include <media/stagefright/foundation/ABase.h>
+#include <list>
+#include <media/stagefright/foundation/AHandler.h>
 #include <utils/Mutex.h>
 #include <utils/RefBase.h>
 
@@ -26,8 +27,14 @@
 
 struct AMessage;
 
-struct MediaClock : public RefBase {
+struct MediaClock : public AHandler {
+    enum {
+        TIMER_REASON_REACHED = 0,
+        TIMER_REASON_RESET = 1,
+    };
+
     MediaClock();
+    void init();
 
     void setStartingTimeMedia(int64_t startingTimeMediaUs);
 
@@ -54,15 +61,38 @@
     // The result is saved in |outRealUs|.
     status_t getRealTimeFor(int64_t targetMediaUs, int64_t *outRealUs) const;
 
+    // request to set up a timer. The target time is |mediaTimeUs|, adjusted by
+    // system time of |adjustRealUs|. In other words, the wake up time is
+    // mediaTimeUs + (adjustRealUs / playbackRate)
+    void addTimer(const sp<AMessage> &notify, int64_t mediaTimeUs, int64_t adjustRealUs = 0);
+
+    void reset();
+
 protected:
     virtual ~MediaClock();
 
+    virtual void onMessageReceived(const sp<AMessage> &msg);
+
 private:
+    enum {
+        kWhatTimeIsUp = 'tIsU',
+    };
+
+    struct Timer {
+        Timer(const sp<AMessage> &notify, int64_t mediaTimeUs, int64_t adjustRealUs);
+        const sp<AMessage> mNotify;
+        int64_t mMediaTimeUs;
+        int64_t mAdjustRealUs;
+    };
+
     status_t getMediaTime_l(
             int64_t realUs,
             int64_t *outMediaUs,
             bool allowPastMaxTime) const;
 
+    void processTimers_l();
+
+    sp<ALooper> mLooper;
     mutable Mutex mLock;
 
     int64_t mAnchorTimeMediaUs;
@@ -72,6 +102,9 @@
 
     float mPlaybackRate;
 
+    int32_t mGeneration;
+    std::list<Timer> mTimers;
+
     DISALLOW_EVIL_CONSTRUCTORS(MediaClock);
 };
 
diff --git a/media/libstagefright/include/media/stagefright/MediaExtractor.h b/media/libstagefright/include/media/stagefright/MediaExtractor.h
index 6ec7eaf..441c6d7 100644
--- a/media/libstagefright/include/media/stagefright/MediaExtractor.h
+++ b/media/libstagefright/include/media/stagefright/MediaExtractor.h
@@ -18,16 +18,18 @@
 
 #define MEDIA_EXTRACTOR_H_
 
+#include <stdio.h>
+
 #include <media/IMediaExtractor.h>
-#include <media/IMediaSource.h>
 #include <media/MediaAnalyticsItem.h>
 
 namespace android {
+
 class DataSource;
 struct MediaSource;
 class MetaData;
 
-class MediaExtractor : public BnMediaExtractor {
+class MediaExtractor : public RefBase {
 public:
     static sp<IMediaExtractor> Create(
             const sp<DataSource> &source, const char *mime = NULL);
@@ -35,7 +37,7 @@
             const sp<DataSource> &source, const char *mime = NULL);
 
     virtual size_t countTracks() = 0;
-    virtual sp<IMediaSource> getTrack(size_t index) = 0;
+    virtual sp<MediaSource> getTrack(size_t index) = 0;
 
     enum GetTrackMetaDataFlags {
         kIncludeExtensiveMetaData = 1
@@ -60,19 +62,59 @@
     // CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD | CAN_SEEK | CAN_PAUSE
     virtual uint32_t flags() const;
 
+    // Creates an IMediaExtractor wrapper to this MediaExtractor.
+    virtual sp<IMediaExtractor> asIMediaExtractor();
+
     // for DRM
     virtual char* getDrmTrackInfo(size_t /*trackID*/, int * /*len*/) {
         return NULL;
     }
     virtual void setUID(uid_t /*uid*/) {
     }
-    virtual status_t setMediaCas(const HInterfaceToken &/*casToken*/) override {
+    virtual status_t setMediaCas(const HInterfaceToken &/*casToken*/) {
         return INVALID_OPERATION;
     }
 
     virtual const char * name() { return "<unspecified>"; }
 
     virtual void release() {}
+    typedef MediaExtractor* (*CreatorFunc)(
+            const sp<DataSource> &source, const sp<AMessage> &meta);
+
+    // The sniffer can optionally fill in "meta" with an AMessage containing
+    // a dictionary of values that helps the corresponding extractor initialize
+    // its state without duplicating effort already exerted by the sniffer.
+    typedef CreatorFunc (*SnifferFunc)(
+            const sp<DataSource> &source, String8 *mimeType,
+            float *confidence, sp<AMessage> *meta);
+
+    typedef struct {
+        const uint8_t b[16];
+    } uuid_t;
+
+    typedef struct {
+        // version number of this structure
+        const uint32_t def_version;
+
+        // A unique identifier for this extractor.
+        // See below for a convenience macro to create this from a string.
+        uuid_t extractor_uuid;
+
+        // Version number of this extractor. When two extractors with the same
+        // uuid are encountered, the one with the largest version number will
+        // be used.
+        const uint32_t extractor_version;
+
+        // a human readable name
+        const char *extractor_name;
+
+        // the sniffer function
+        const SnifferFunc sniff;
+    } ExtractorDef;
+
+    static const uint32_t EXTRACTORDEF_VERSION = 1;
+
+    typedef ExtractorDef (*GetExtractorDef)();
 
 protected:
     MediaExtractor();
@@ -84,20 +126,13 @@
 
 private:
 
-    typedef bool (*SnifferFunc)(
-            const sp<DataSource> &source, String8 *mimeType,
-            float *confidence, sp<AMessage> *meta);
-
     static Mutex gSnifferMutex;
-    static List<SnifferFunc> gSniffers;
+    static List<ExtractorDef> gSniffers;
     static bool gSniffersRegistered;
 
-    // The sniffer can optionally fill in "meta" with an AMessage containing
-    // a dictionary of values that helps the corresponding extractor initialize
-    // its state without duplicating effort already exerted by the sniffer.
-    static void RegisterSniffer_l(SnifferFunc func);
+    static void RegisterSniffer_l(const ExtractorDef &def);
 
-    static bool sniff(const sp<DataSource> &source,
+    static CreatorFunc sniff(const sp<DataSource> &source,
             String8 *mimeType, float *confidence, sp<AMessage> *meta);
 
     static void RegisterDefaultSniffers();
@@ -106,6 +141,68 @@
     MediaExtractor &operator=(const MediaExtractor &);
 };
 
+// purposely not defined anywhere so that this will fail to link if
+// expressions below are not evaluated at compile time
+int invalid_uuid_string(const char *);
+
+template <typename T, size_t N>
+constexpr uint8_t _digitAt_(const T (&s)[N], const size_t n) {
+    return s[n] >= '0' && s[n] <= '9' ? s[n] - '0'
+            : s[n] >= 'a' && s[n] <= 'f' ? s[n] - 'a' + 10
+                    : s[n] >= 'A' && s[n] <= 'F' ? s[n] - 'A' + 10
+                            : invalid_uuid_string("uuid: bad digits");
+}
+
+template <typename T, size_t N>
+constexpr uint8_t _hexByteAt_(const T (&s)[N], size_t n) {
+    return (_digitAt_(s, n) << 4) + _digitAt_(s, n + 1);
+}
+
+constexpr bool _assertIsDash_(char c) {
+    return c == '-' ? true : invalid_uuid_string("Wrong format");
+}
+
+template <size_t N>
+constexpr MediaExtractor::uuid_t constUUID(const char (&s) [N]) {
+    static_assert(N == 37, "uuid: wrong length");
+    return
+            _assertIsDash_(s[8]),
+            _assertIsDash_(s[13]),
+            _assertIsDash_(s[18]),
+            _assertIsDash_(s[23]),
+            MediaExtractor::uuid_t {{
+                _hexByteAt_(s, 0),
+                _hexByteAt_(s, 2),
+                _hexByteAt_(s, 4),
+                _hexByteAt_(s, 6),
+                _hexByteAt_(s, 9),
+                _hexByteAt_(s, 11),
+                _hexByteAt_(s, 14),
+                _hexByteAt_(s, 16),
+                _hexByteAt_(s, 19),
+                _hexByteAt_(s, 21),
+                _hexByteAt_(s, 24),
+                _hexByteAt_(s, 26),
+                _hexByteAt_(s, 28),
+                _hexByteAt_(s, 30),
+                _hexByteAt_(s, 32),
+                _hexByteAt_(s, 34),
+            }};
+}
+// Convenience macro to create a uuid_t from a string literal, which should
+// be formatted as "12345678-1234-1234-1234-123456789abc", as generated by
+// e.g. https://www.uuidgenerator.net/ or the 'uuidgen' linux command.
+// Hex digits may be upper or lower case.
+//
+// The macro call is otherwise equivalent to specifying the structure directly
+// (e.g. UUID("7d613858-5837-4a38-84c5-332d1cddee27") is the same as
+//       {{0x7d, 0x61, 0x38, 0x58, 0x58, 0x37, 0x4a, 0x38,
+//         0x84, 0xc5, 0x33, 0x2d, 0x1c, 0xdd, 0xee, 0x27}})
+
+#define UUID(str) []{ constexpr MediaExtractor::uuid_t uuid = constUUID(str); return uuid; }()
+
+
+
 }  // namespace android
 
 #endif  // MEDIA_EXTRACTOR_H_
diff --git a/media/libstagefright/include/media/stagefright/MediaSource.h b/media/libstagefright/include/media/stagefright/MediaSource.h
index 14adb05..7e30e30 100644
--- a/media/libstagefright/include/media/stagefright/MediaSource.h
+++ b/media/libstagefright/include/media/stagefright/MediaSource.h
@@ -22,6 +22,7 @@
 
 #include <media/IMediaSource.h>
 #include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/MetaData.h>
 #include <utils/RefBase.h>
 #include <utils/Vector.h>
 
@@ -29,8 +30,18 @@
 
 class MediaBuffer;
 class MetaData;
+class IMediaSource;
 
-struct MediaSource : public BnMediaSource {
+struct MediaSource : public virtual RefBase {
+    // TODO: Move ReadOptions implementation from IMediaSource to MediaSource
+    // once this class moves to a separate extractor lib on which both libmedia
+    // and libstagefright rely. For now, alias is added to avoid circular
+    // dependency.
+    using ReadOptions = IMediaSource::ReadOptions;
+
+    // Creates a MediaSource which wraps the given IMediaSource object.
+    static sp<MediaSource> CreateFromIMediaSource(const sp<IMediaSource> &source);
+
     MediaSource();
 
     // To be called before any other methods on this object, except
@@ -92,6 +103,9 @@
         return ERROR_UNSUPPORTED;
     }
 
+    // Creates an IMediaSource wrapper to this MediaSource.
+    virtual sp<IMediaSource> asIMediaSource();
+
 protected:
     virtual ~MediaSource();
 
diff --git a/media/libstagefright/include/media/stagefright/MediaWriter.h b/media/libstagefright/include/media/stagefright/MediaWriter.h
index cd4af4d..80c5358 100644
--- a/media/libstagefright/include/media/stagefright/MediaWriter.h
+++ b/media/libstagefright/include/media/stagefright/MediaWriter.h
@@ -20,7 +20,7 @@
 
 #include <utils/RefBase.h>
 #include <media/IMediaRecorderClient.h>
-#include <media/IMediaSource.h>
+#include <media/stagefright/MediaSource.h>
 
 namespace android {
 
@@ -32,7 +32,7 @@
           mMaxFileDurationLimitUs(0) {
     }
 
-    virtual status_t addSource(const sp<IMediaSource> &source) = 0;
+    virtual status_t addSource(const sp<MediaSource> &source) = 0;
     virtual bool reachedEOS() = 0;
     virtual status_t start(MetaData *params = NULL) = 0;
     virtual status_t stop() = 0;
diff --git a/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h b/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h
new file mode 100644
index 0000000..96611d1
--- /dev/null
+++ b/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2017, 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 REMOTE_MEDIA_EXTRACTOR_H_
+#define REMOTE_MEDIA_EXTRACTOR_H_
+
+#include <media/IMediaExtractor.h>
+#include <media/stagefright/MediaExtractor.h>
+
+namespace android {
+
+// IMediaExtractor wrapper to the MediaExtractor.
+class RemoteMediaExtractor : public BnMediaExtractor {
+public:
+    static sp<IMediaExtractor> wrap(const sp<MediaExtractor> &extractor);
+
+    virtual ~RemoteMediaExtractor();
+    virtual size_t countTracks();
+    virtual sp<IMediaSource> getTrack(size_t index);
+    virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags = 0);
+    virtual sp<MetaData> getMetaData();
+    virtual status_t getMetrics(Parcel *reply);
+    virtual uint32_t flags() const;
+    virtual char* getDrmTrackInfo(size_t trackID, int * len);
+    virtual void setUID(uid_t uid);
+    virtual status_t setMediaCas(const HInterfaceToken &casToken);
+    virtual const char * name();
+    virtual void release();
+
+private:
+    sp<MediaExtractor> mExtractor;
+
+    explicit RemoteMediaExtractor(const sp<MediaExtractor> &extractor);
+
+    DISALLOW_EVIL_CONSTRUCTORS(RemoteMediaExtractor);
+};
+
+}  // namespace android
+
+#endif  // REMOTE_MEDIA_EXTRACTOR_H_
diff --git a/media/libstagefright/include/media/stagefright/RemoteMediaSource.h b/media/libstagefright/include/media/stagefright/RemoteMediaSource.h
new file mode 100644
index 0000000..2731114
--- /dev/null
+++ b/media/libstagefright/include/media/stagefright/RemoteMediaSource.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2017, 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 REMOTE_MEDIA_SOURCE_H_
+#define REMOTE_MEDIA_SOURCE_H_
+
+#include <media/IMediaSource.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/foundation/ABase.h>
+
+namespace android {
+
+// IMediaSrouce wrapper to the MediaSource.
+class RemoteMediaSource : public BnMediaSource {
+public:
+    static sp<IMediaSource> wrap(const sp<MediaSource> &source);
+    virtual ~RemoteMediaSource();
+    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);
+    virtual status_t pause();
+    virtual status_t setBuffers(const Vector<MediaBuffer *> &buffers);
+    virtual status_t setStopTimeUs(int64_t stopTimeUs);
+
+private:
+    sp<MediaSource> mSource;
+
+    explicit RemoteMediaSource(const sp<MediaSource> &source);
+
+    DISALLOW_EVIL_CONSTRUCTORS(RemoteMediaSource);
+};
+
+}  // namespace android
+
+#endif  // REMOTE_MEDIA_SOURCE_H_
diff --git a/media/libstagefright/include/media/stagefright/SimpleDecodingSource.h b/media/libstagefright/include/media/stagefright/SimpleDecodingSource.h
index a000fde..b8d141a 100644
--- a/media/libstagefright/include/media/stagefright/SimpleDecodingSource.h
+++ b/media/libstagefright/include/media/stagefright/SimpleDecodingSource.h
@@ -45,12 +45,12 @@
     // does not support secure input or pausing.
     // if |desiredCodec| is given, use this specific codec.
     static sp<SimpleDecodingSource> Create(
-            const sp<IMediaSource> &source, uint32_t flags,
+            const sp<MediaSource> &source, uint32_t flags,
             const sp<ANativeWindow> &nativeWindow,
             const char *desiredCodec = NULL);
 
     static sp<SimpleDecodingSource> Create(
-            const sp<IMediaSource> &source, uint32_t flags = 0);
+            const sp<MediaSource> &source, uint32_t flags = 0);
 
     virtual ~SimpleDecodingSource();
 
@@ -73,11 +73,11 @@
 private:
     // Construct this using a codec, source and looper.
     SimpleDecodingSource(
-            const sp<MediaCodec> &codec, const sp<IMediaSource> &source, const sp<ALooper> &looper,
+            const sp<MediaCodec> &codec, const sp<MediaSource> &source, const sp<ALooper> &looper,
             bool usingSurface, bool isVorbis, const sp<AMessage> &format);
 
     sp<MediaCodec> mCodec;
-    sp<IMediaSource> mSource;
+    sp<MediaSource> mSource;
     sp<ALooper> mLooper;
     bool mUsingSurface;
     bool mIsVorbis;
diff --git a/media/libstagefright/mpeg2ts/Android.bp b/media/libstagefright/mpeg2ts/Android.bp
index 21259c4..7654eb3 100644
--- a/media/libstagefright/mpeg2ts/Android.bp
+++ b/media/libstagefright/mpeg2ts/Android.bp
@@ -1,5 +1,5 @@
 cc_library_static {
-    name: "libstagefright_mpeg2ts",
+    name: "libstagefright_mpeg2support",
 
     srcs: [
         "AnotherPacketSource.cpp",
@@ -7,8 +7,6 @@
         "CasManager.cpp",
         "ESQueue.cpp",
         "HlsSampleDecryptor.cpp",
-        "MPEG2PSExtractor.cpp",
-        "MPEG2TSExtractor.cpp",
     ],
 
     include_dirs: [
diff --git a/media/libstagefright/omx/Android.bp b/media/libstagefright/omx/Android.bp
index d4cdf69..0d6c696 100644
--- a/media/libstagefright/omx/Android.bp
+++ b/media/libstagefright/omx/Android.bp
@@ -57,16 +57,12 @@
         "libhidlmemory",
         "libhidltransport",
         "libnativewindow", // TODO(b/62923479): use header library
-        "android.hidl.memory@1.0",
-        "android.hidl.token@1.0-utils",
-        "android.hardware.media@1.0",
+        "libvndksupport",
         "android.hardware.media.omx@1.0",
-        "android.hardware.graphics.common@1.0",
         "android.hardware.graphics.bufferqueue@1.0",
     ],
 
     export_shared_lib_headers: [
-        "android.hidl.memory@1.0",
         "libmedia_omx",
         "libstagefright_foundation",
         "libstagefright_xmlparser",
diff --git a/media/libstagefright/omx/OMXMaster.cpp b/media/libstagefright/omx/OMXMaster.cpp
index fd97fdc..0967b5f 100644
--- a/media/libstagefright/omx/OMXMaster.cpp
+++ b/media/libstagefright/omx/OMXMaster.cpp
@@ -22,6 +22,8 @@
 #include <media/stagefright/omx/SoftOMXPlugin.h>
 #include <media/stagefright/foundation/ADebug.h>
 
+#include <vndksupport/linker.h>
+
 #include <dlfcn.h>
 #include <fcntl.h>
 
@@ -67,7 +69,7 @@
 }
 
 void OMXMaster::addPlugin(const char *libname) {
-    mVendorLibHandle = dlopen(libname, RTLD_NOW);
+    mVendorLibHandle = android_load_sphal_library(libname, RTLD_NOW);
 
     if (mVendorLibHandle == NULL) {
         return;
diff --git a/media/libstagefright/omx/tests/OMXHarness.cpp b/media/libstagefright/omx/tests/OMXHarness.cpp
index 3266439..4b624f2 100644
--- a/media/libstagefright/omx/tests/OMXHarness.cpp
+++ b/media/libstagefright/omx/tests/OMXHarness.cpp
@@ -543,7 +543,7 @@
     return NULL;
 }
 
-static sp<IMediaSource> CreateSourceForMime(const char *mime) {
+static sp<MediaSource> CreateSourceForMime(const char *mime) {
     const char *url = GetURLForMime(mime);
 
     if (url == NULL) {
@@ -564,7 +564,7 @@
         CHECK(meta->findCString(kKeyMIMEType, &trackMime));
 
         if (!strcasecmp(mime, trackMime)) {
-            return extractor->getTrack(i);
+            return MediaSource::CreateFromIMediaSource(extractor->getTrack(i));
         }
     }
 
@@ -610,7 +610,7 @@
         return OK;
     }
 
-    sp<IMediaSource> source = CreateSourceForMime(mime);
+    sp<MediaSource> source = CreateSourceForMime(mime);
 
     if (source == NULL) {
         printf("  * Unable to open test content for type '%s', "
@@ -620,14 +620,14 @@
         return OK;
     }
 
-    sp<IMediaSource> seekSource = CreateSourceForMime(mime);
+    sp<MediaSource> seekSource = CreateSourceForMime(mime);
     if (source == NULL || seekSource == NULL) {
         return UNKNOWN_ERROR;
     }
 
     CHECK_EQ(seekSource->start(), (status_t)OK);
 
-    sp<IMediaSource> codec = SimpleDecodingSource::Create(
+    sp<MediaSource> codec = SimpleDecodingSource::Create(
             source, 0 /* flags */, NULL /* nativeWindow */, componentName);
 
     CHECK(codec != NULL);
diff --git a/media/libstagefright/rtsp/ARTPWriter.cpp b/media/libstagefright/rtsp/ARTPWriter.cpp
index 1f6b6f7..56c4aa6 100644
--- a/media/libstagefright/rtsp/ARTPWriter.cpp
+++ b/media/libstagefright/rtsp/ARTPWriter.cpp
@@ -104,7 +104,7 @@
     mFd = -1;
 }
 
-status_t ARTPWriter::addSource(const sp<IMediaSource> &source) {
+status_t ARTPWriter::addSource(const sp<MediaSource> &source) {
     mSource = source;
     return OK;
 }
diff --git a/media/libstagefright/rtsp/ARTPWriter.h b/media/libstagefright/rtsp/ARTPWriter.h
index 3c7042e..92a64f2 100644
--- a/media/libstagefright/rtsp/ARTPWriter.h
+++ b/media/libstagefright/rtsp/ARTPWriter.h
@@ -37,7 +37,7 @@
 struct ARTPWriter : public MediaWriter {
     explicit ARTPWriter(int fd);
 
-    virtual status_t addSource(const sp<IMediaSource> &source);
+    virtual status_t addSource(const sp<MediaSource> &source);
     virtual bool reachedEOS();
     virtual status_t start(MetaData *params);
     virtual status_t stop();
@@ -72,7 +72,7 @@
     int mRTCPFd;
 #endif
 
-    sp<IMediaSource> mSource;
+    sp<MediaSource> mSource;
     sp<ALooper> mLooper;
     sp<AHandlerReflector<ARTPWriter> > mReflector;
 
diff --git a/media/libstagefright/webm/WebmFrameThread.cpp b/media/libstagefright/webm/WebmFrameThread.cpp
index 71bfbc9..420890b 100644
--- a/media/libstagefright/webm/WebmFrameThread.cpp
+++ b/media/libstagefright/webm/WebmFrameThread.cpp
@@ -252,7 +252,7 @@
 }
 
 WebmFrameMediaSourceThread::WebmFrameMediaSourceThread(
-        const sp<IMediaSource>& source,
+        const sp<MediaSource>& source,
         int type,
         LinkedBlockingQueue<const sp<WebmFrame> >& sink,
         uint64_t timeCodeScale,
diff --git a/media/libstagefright/webm/WebmFrameThread.h b/media/libstagefright/webm/WebmFrameThread.h
index 528984f..d65d9b7 100644
--- a/media/libstagefright/webm/WebmFrameThread.h
+++ b/media/libstagefright/webm/WebmFrameThread.h
@@ -123,7 +123,7 @@
 class WebmFrameMediaSourceThread: public WebmFrameSourceThread {
 public:
     WebmFrameMediaSourceThread(
-            const sp<IMediaSource>& source,
+            const sp<MediaSource>& source,
             int type,
             LinkedBlockingQueue<const sp<WebmFrame> >& sink,
             uint64_t timeCodeScale,
@@ -142,7 +142,7 @@
     }
 
 private:
-    const sp<IMediaSource> mSource;
+    const sp<MediaSource> mSource;
     const uint64_t mTimeCodeScale;
     uint64_t mStartTimeUs;
 
diff --git a/media/libstagefright/webm/WebmWriter.cpp b/media/libstagefright/webm/WebmWriter.cpp
index d6c6930..4d73eb8 100644
--- a/media/libstagefright/webm/WebmWriter.cpp
+++ b/media/libstagefright/webm/WebmWriter.cpp
@@ -360,7 +360,7 @@
     return err;
 }
 
-status_t WebmWriter::addSource(const sp<IMediaSource> &source) {
+status_t WebmWriter::addSource(const sp<MediaSource> &source) {
     Mutex::Autolock l(mLock);
     if (mStarted) {
         ALOGE("Attempt to add source AFTER recording is started");
diff --git a/media/libstagefright/webm/WebmWriter.h b/media/libstagefright/webm/WebmWriter.h
index 9f3b19f..ed5bc4c 100644
--- a/media/libstagefright/webm/WebmWriter.h
+++ b/media/libstagefright/webm/WebmWriter.h
@@ -40,7 +40,7 @@
     ~WebmWriter() { reset(); }
 
 
-    virtual status_t addSource(const sp<IMediaSource> &source);
+    virtual status_t addSource(const sp<MediaSource> &source);
     virtual status_t start(MetaData *param = NULL);
     virtual status_t stop();
     virtual status_t pause();
@@ -85,7 +85,7 @@
         const char *mName;
         sp<WebmElement> (*mMakeTrack)(const sp<MetaData>&);
 
-        sp<IMediaSource> mSource;
+        sp<MediaSource> mSource;
         sp<WebmElement> mTrackEntry;
         sp<WebmFrameSourceThread> mThread;
         LinkedBlockingQueue<const sp<WebmFrame> > mSink;
diff --git a/media/libstagefright/wifi-display/Android.bp b/media/libstagefright/wifi-display/Android.bp
deleted file mode 100644
index fb08c5b..0000000
--- a/media/libstagefright/wifi-display/Android.bp
+++ /dev/null
@@ -1,51 +0,0 @@
-cc_library_shared {
-    name: "libstagefright_wfd",
-
-    srcs: [
-        "MediaSender.cpp",
-        "Parameters.cpp",
-        "rtp/RTPSender.cpp",
-        "source/Converter.cpp",
-        "source/MediaPuller.cpp",
-        "source/PlaybackSession.cpp",
-        "source/RepeaterSource.cpp",
-        "source/TSPacketizer.cpp",
-        "source/WifiDisplaySource.cpp",
-        "VideoFormats.cpp",
-    ],
-
-    include_dirs: [
-        "frameworks/av/media/libstagefright",
-        "frameworks/native/include/media/openmax",
-        "frameworks/native/include/media/hardware",
-        "frameworks/av/media/libstagefright/mpeg2ts",
-    ],
-
-    shared_libs: [
-        "libbinder",
-        "libcutils",
-        "liblog",
-        "libmedia",
-        "libstagefright",
-        "libstagefright_foundation",
-        "libui",
-        "libgui",
-        "libutils",
-    ],
-
-    cflags: [
-        "-Wno-multichar",
-        "-Werror",
-        "-Wall",
-    ],
-
-    sanitize: {
-        misc_undefined: [
-            "signed-integer-overflow",
-        ],
-        cfi: true,
-        diag: {
-            cfi: true,
-        },
-    },
-}
diff --git a/media/libstagefright/wifi-display/MediaSender.cpp b/media/libstagefright/wifi-display/MediaSender.cpp
deleted file mode 100644
index cc412f5..0000000
--- a/media/libstagefright/wifi-display/MediaSender.cpp
+++ /dev/null
@@ -1,519 +0,0 @@
-/*
- * Copyright 2013, 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 "MediaSender"
-#include <utils/Log.h>
-
-#include "MediaSender.h"
-
-#include "rtp/RTPSender.h"
-#include "source/TSPacketizer.h"
-
-#include "include/avc_utils.h"
-
-#include <media/IHDCP.h>
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/foundation/ANetworkSession.h>
-#include <ui/GraphicBuffer.h>
-
-namespace android {
-
-MediaSender::MediaSender(
-        const sp<ANetworkSession> &netSession,
-        const sp<AMessage> &notify)
-    : mNetSession(netSession),
-      mNotify(notify),
-      mMode(MODE_UNDEFINED),
-      mGeneration(0),
-      mPrevTimeUs(-1ll),
-      mInitDoneCount(0),
-      mLogFile(NULL) {
-    // mLogFile = fopen("/data/misc/log.ts", "wb");
-}
-
-MediaSender::~MediaSender() {
-    if (mLogFile != NULL) {
-        fclose(mLogFile);
-        mLogFile = NULL;
-    }
-}
-
-status_t MediaSender::setHDCP(const sp<IHDCP> &hdcp) {
-    if (mMode != MODE_UNDEFINED) {
-        return INVALID_OPERATION;
-    }
-
-    mHDCP = hdcp;
-
-    return OK;
-}
-
-ssize_t MediaSender::addTrack(const sp<AMessage> &format, uint32_t flags) {
-    if (mMode != MODE_UNDEFINED) {
-        return INVALID_OPERATION;
-    }
-
-    TrackInfo info;
-    info.mFormat = format;
-    info.mFlags = flags;
-    info.mPacketizerTrackIndex = -1;
-
-    AString mime;
-    CHECK(format->findString("mime", &mime));
-    info.mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
-
-    size_t index = mTrackInfos.size();
-    mTrackInfos.push_back(info);
-
-    return index;
-}
-
-status_t MediaSender::initAsync(
-        ssize_t trackIndex,
-        const char *remoteHost,
-        int32_t remoteRTPPort,
-        RTPSender::TransportMode rtpMode,
-        int32_t remoteRTCPPort,
-        RTPSender::TransportMode rtcpMode,
-        int32_t *localRTPPort) {
-    if (trackIndex < 0) {
-        if (mMode != MODE_UNDEFINED) {
-            return INVALID_OPERATION;
-        }
-
-        uint32_t flags = 0;
-        if (mHDCP != NULL) {
-            // XXX Determine proper HDCP version.
-            flags |= TSPacketizer::EMIT_HDCP20_DESCRIPTOR;
-        }
-        mTSPacketizer = new TSPacketizer(flags);
-
-        status_t err = OK;
-        for (size_t i = 0; i < mTrackInfos.size(); ++i) {
-            TrackInfo *info = &mTrackInfos.editItemAt(i);
-
-            ssize_t packetizerTrackIndex =
-                mTSPacketizer->addTrack(info->mFormat);
-
-            if (packetizerTrackIndex < 0) {
-                err = packetizerTrackIndex;
-                break;
-            }
-
-            info->mPacketizerTrackIndex = packetizerTrackIndex;
-        }
-
-        if (err == OK) {
-            sp<AMessage> notify = new AMessage(kWhatSenderNotify, this);
-            notify->setInt32("generation", mGeneration);
-            mTSSender = new RTPSender(mNetSession, notify);
-            looper()->registerHandler(mTSSender);
-
-            err = mTSSender->initAsync(
-                    remoteHost,
-                    remoteRTPPort,
-                    rtpMode,
-                    remoteRTCPPort,
-                    rtcpMode,
-                    localRTPPort);
-
-            if (err != OK) {
-                looper()->unregisterHandler(mTSSender->id());
-                mTSSender.clear();
-            }
-        }
-
-        if (err != OK) {
-            for (size_t i = 0; i < mTrackInfos.size(); ++i) {
-                TrackInfo *info = &mTrackInfos.editItemAt(i);
-                info->mPacketizerTrackIndex = -1;
-            }
-
-            mTSPacketizer.clear();
-            return err;
-        }
-
-        mMode = MODE_TRANSPORT_STREAM;
-        mInitDoneCount = 1;
-
-        return OK;
-    }
-
-    if (mMode == MODE_TRANSPORT_STREAM) {
-        return INVALID_OPERATION;
-    }
-
-    if ((size_t)trackIndex >= mTrackInfos.size()) {
-        return -ERANGE;
-    }
-
-    TrackInfo *info = &mTrackInfos.editItemAt(trackIndex);
-
-    if (info->mSender != NULL) {
-        return INVALID_OPERATION;
-    }
-
-    sp<AMessage> notify = new AMessage(kWhatSenderNotify, this);
-    notify->setInt32("generation", mGeneration);
-    notify->setSize("trackIndex", trackIndex);
-
-    info->mSender = new RTPSender(mNetSession, notify);
-    looper()->registerHandler(info->mSender);
-
-    status_t err = info->mSender->initAsync(
-            remoteHost,
-            remoteRTPPort,
-            rtpMode,
-            remoteRTCPPort,
-            rtcpMode,
-            localRTPPort);
-
-    if (err != OK) {
-        looper()->unregisterHandler(info->mSender->id());
-        info->mSender.clear();
-
-        return err;
-    }
-
-    if (mMode == MODE_UNDEFINED) {
-        mInitDoneCount = mTrackInfos.size();
-    }
-
-    mMode = MODE_ELEMENTARY_STREAMS;
-
-    return OK;
-}
-
-status_t MediaSender::queueAccessUnit(
-        size_t trackIndex, const sp<ABuffer> &accessUnit) {
-    if (mMode == MODE_UNDEFINED) {
-        return INVALID_OPERATION;
-    }
-
-    if (trackIndex >= mTrackInfos.size()) {
-        return -ERANGE;
-    }
-
-    if (mMode == MODE_TRANSPORT_STREAM) {
-        TrackInfo *info = &mTrackInfos.editItemAt(trackIndex);
-        info->mAccessUnits.push_back(accessUnit);
-
-        mTSPacketizer->extractCSDIfNecessary(info->mPacketizerTrackIndex);
-
-        for (;;) {
-            ssize_t minTrackIndex = -1;
-            int64_t minTimeUs = -1ll;
-
-            for (size_t i = 0; i < mTrackInfos.size(); ++i) {
-                const TrackInfo &info = mTrackInfos.itemAt(i);
-
-                if (info.mAccessUnits.empty()) {
-                    minTrackIndex = -1;
-                    minTimeUs = -1ll;
-                    break;
-                }
-
-                int64_t timeUs;
-                const sp<ABuffer> &accessUnit = *info.mAccessUnits.begin();
-                CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
-
-                if (minTrackIndex < 0 || timeUs < minTimeUs) {
-                    minTrackIndex = i;
-                    minTimeUs = timeUs;
-                }
-            }
-
-            if (minTrackIndex < 0) {
-                return OK;
-            }
-
-            TrackInfo *info = &mTrackInfos.editItemAt(minTrackIndex);
-            sp<ABuffer> accessUnit = *info->mAccessUnits.begin();
-            info->mAccessUnits.erase(info->mAccessUnits.begin());
-
-            sp<ABuffer> tsPackets;
-            status_t err = packetizeAccessUnit(
-                    minTrackIndex, accessUnit, &tsPackets);
-
-            if (err == OK) {
-                if (mLogFile != NULL) {
-                    fwrite(tsPackets->data(), 1, tsPackets->size(), mLogFile);
-                }
-
-                int64_t timeUs;
-                CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
-                tsPackets->meta()->setInt64("timeUs", timeUs);
-
-                err = mTSSender->queueBuffer(
-                        tsPackets,
-                        33 /* packetType */,
-                        RTPSender::PACKETIZATION_TRANSPORT_STREAM);
-            }
-
-            if (err != OK) {
-                return err;
-            }
-        }
-    }
-
-    TrackInfo *info = &mTrackInfos.editItemAt(trackIndex);
-
-    return info->mSender->queueBuffer(
-            accessUnit,
-            info->mIsAudio ? 96 : 97 /* packetType */,
-            info->mIsAudio
-                ? RTPSender::PACKETIZATION_AAC : RTPSender::PACKETIZATION_H264);
-}
-
-void MediaSender::onMessageReceived(const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatSenderNotify:
-        {
-            int32_t generation;
-            CHECK(msg->findInt32("generation", &generation));
-            if (generation != mGeneration) {
-                break;
-            }
-
-            onSenderNotify(msg);
-            break;
-        }
-
-        default:
-            TRESPASS();
-    }
-}
-
-void MediaSender::onSenderNotify(const sp<AMessage> &msg) {
-    int32_t what;
-    CHECK(msg->findInt32("what", &what));
-
-    switch (what) {
-        case RTPSender::kWhatInitDone:
-        {
-            --mInitDoneCount;
-
-            int32_t err;
-            CHECK(msg->findInt32("err", &err));
-
-            if (err != OK) {
-                notifyInitDone(err);
-                ++mGeneration;
-                break;
-            }
-
-            if (mInitDoneCount == 0) {
-                notifyInitDone(OK);
-            }
-            break;
-        }
-
-        case RTPSender::kWhatError:
-        {
-            int32_t err;
-            CHECK(msg->findInt32("err", &err));
-
-            notifyError(err);
-            break;
-        }
-
-        case kWhatNetworkStall:
-        {
-            size_t numBytesQueued;
-            CHECK(msg->findSize("numBytesQueued", &numBytesQueued));
-
-            notifyNetworkStall(numBytesQueued);
-            break;
-        }
-
-        case kWhatInformSender:
-        {
-            int64_t avgLatencyUs;
-            CHECK(msg->findInt64("avgLatencyUs", &avgLatencyUs));
-
-            int64_t maxLatencyUs;
-            CHECK(msg->findInt64("maxLatencyUs", &maxLatencyUs));
-
-            sp<AMessage> notify = mNotify->dup();
-            notify->setInt32("what", kWhatInformSender);
-            notify->setInt64("avgLatencyUs", avgLatencyUs);
-            notify->setInt64("maxLatencyUs", maxLatencyUs);
-            notify->post();
-            break;
-        }
-
-        default:
-            TRESPASS();
-    }
-}
-
-void MediaSender::notifyInitDone(status_t err) {
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("what", kWhatInitDone);
-    notify->setInt32("err", err);
-    notify->post();
-}
-
-void MediaSender::notifyError(status_t err) {
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("what", kWhatError);
-    notify->setInt32("err", err);
-    notify->post();
-}
-
-void MediaSender::notifyNetworkStall(size_t numBytesQueued) {
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("what", kWhatNetworkStall);
-    notify->setSize("numBytesQueued", numBytesQueued);
-    notify->post();
-}
-
-status_t MediaSender::packetizeAccessUnit(
-        size_t trackIndex,
-        sp<ABuffer> accessUnit,
-        sp<ABuffer> *tsPackets) {
-    const TrackInfo &info = mTrackInfos.itemAt(trackIndex);
-
-    uint32_t flags = 0;
-
-    bool isHDCPEncrypted = false;
-    uint64_t inputCTR;
-    uint8_t HDCP_private_data[16];
-
-    bool manuallyPrependSPSPPS =
-        !info.mIsAudio
-        && (info.mFlags & FLAG_MANUALLY_PREPEND_SPS_PPS)
-        && IsIDR(accessUnit);
-
-    if (mHDCP != NULL && !info.mIsAudio) {
-        isHDCPEncrypted = true;
-
-        if (manuallyPrependSPSPPS) {
-            accessUnit = mTSPacketizer->prependCSD(
-                    info.mPacketizerTrackIndex, accessUnit);
-        }
-
-        status_t err;
-        native_handle_t* handle;
-        if (accessUnit->meta()->findPointer("handle", (void**)&handle)
-                && handle != NULL) {
-            int32_t rangeLength, rangeOffset;
-            sp<AMessage> notify;
-            CHECK(accessUnit->meta()->findInt32("rangeOffset", &rangeOffset));
-            CHECK(accessUnit->meta()->findInt32("rangeLength", &rangeLength));
-            CHECK(accessUnit->meta()->findMessage("notify", &notify)
-                    && notify != NULL);
-            CHECK_GE((int32_t)accessUnit->size(), rangeLength);
-
-            sp<GraphicBuffer> grbuf(new GraphicBuffer(
-                    rangeOffset + rangeLength /* width */, 1 /* height */,
-                    HAL_PIXEL_FORMAT_Y8, 1 /* layerCount */,
-                    GRALLOC_USAGE_HW_VIDEO_ENCODER,
-                    rangeOffset + rangeLength /* stride */, handle,
-                    false /* keepOwnership */));
-
-            err = mHDCP->encryptNative(
-                    grbuf, rangeOffset, rangeLength,
-                    trackIndex  /* streamCTR */,
-                    &inputCTR,
-                    accessUnit->data());
-            notify->post();
-        } else {
-            err = mHDCP->encrypt(
-                    accessUnit->data(), accessUnit->size(),
-                    trackIndex  /* streamCTR */,
-                    &inputCTR,
-                    accessUnit->data());
-        }
-
-        if (err != OK) {
-            ALOGE("Failed to HDCP-encrypt media data (err %d)",
-                  err);
-
-            return err;
-        }
-
-        HDCP_private_data[0] = 0x00;
-
-        HDCP_private_data[1] =
-            (((trackIndex >> 30) & 3) << 1) | 1;
-
-        HDCP_private_data[2] = (trackIndex >> 22) & 0xff;
-
-        HDCP_private_data[3] =
-            (((trackIndex >> 15) & 0x7f) << 1) | 1;
-
-        HDCP_private_data[4] = (trackIndex >> 7) & 0xff;
-
-        HDCP_private_data[5] =
-            ((trackIndex & 0x7f) << 1) | 1;
-
-        HDCP_private_data[6] = 0x00;
-
-        HDCP_private_data[7] =
-            (((inputCTR >> 60) & 0x0f) << 1) | 1;
-
-        HDCP_private_data[8] = (inputCTR >> 52) & 0xff;
-
-        HDCP_private_data[9] =
-            (((inputCTR >> 45) & 0x7f) << 1) | 1;
-
-        HDCP_private_data[10] = (inputCTR >> 37) & 0xff;
-
-        HDCP_private_data[11] =
-            (((inputCTR >> 30) & 0x7f) << 1) | 1;
-
-        HDCP_private_data[12] = (inputCTR >> 22) & 0xff;
-
-        HDCP_private_data[13] =
-            (((inputCTR >> 15) & 0x7f) << 1) | 1;
-
-        HDCP_private_data[14] = (inputCTR >> 7) & 0xff;
-
-        HDCP_private_data[15] =
-            ((inputCTR & 0x7f) << 1) | 1;
-
-        flags |= TSPacketizer::IS_ENCRYPTED;
-    } else if (manuallyPrependSPSPPS) {
-        flags |= TSPacketizer::PREPEND_SPS_PPS_TO_IDR_FRAMES;
-    }
-
-    int64_t timeUs = ALooper::GetNowUs();
-    if (mPrevTimeUs < 0ll || mPrevTimeUs + 100000ll <= timeUs) {
-        flags |= TSPacketizer::EMIT_PCR;
-        flags |= TSPacketizer::EMIT_PAT_AND_PMT;
-
-        mPrevTimeUs = timeUs;
-    }
-
-    mTSPacketizer->packetize(
-            info.mPacketizerTrackIndex,
-            accessUnit,
-            tsPackets,
-            flags,
-            !isHDCPEncrypted ? NULL : HDCP_private_data,
-            !isHDCPEncrypted ? 0 : sizeof(HDCP_private_data),
-            info.mIsAudio ? 2 : 0 /* numStuffingBytes */);
-
-    return OK;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/wifi-display/MediaSender.h b/media/libstagefright/wifi-display/MediaSender.h
deleted file mode 100644
index 04538ea..0000000
--- a/media/libstagefright/wifi-display/MediaSender.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright 2013, 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_SENDER_H_
-
-#define MEDIA_SENDER_H_
-
-#include "rtp/RTPSender.h"
-
-#include <media/stagefright/foundation/ABase.h>
-#include <media/stagefright/foundation/AHandler.h>
-#include <utils/Errors.h>
-#include <utils/Vector.h>
-
-namespace android {
-
-struct ABuffer;
-struct ANetworkSession;
-struct AMessage;
-struct IHDCP;
-struct TSPacketizer;
-
-// This class facilitates sending of data from one or more media tracks
-// through one or more RTP channels, either providing a 1:1 mapping from
-// track to RTP channel or muxing all tracks into a single RTP channel and
-// using transport stream encapsulation.
-// Optionally the (video) data is encrypted using the provided hdcp object.
-struct MediaSender : public AHandler {
-    enum {
-        kWhatInitDone,
-        kWhatError,
-        kWhatNetworkStall,
-        kWhatInformSender,
-    };
-
-    MediaSender(
-            const sp<ANetworkSession> &netSession,
-            const sp<AMessage> &notify);
-
-    status_t setHDCP(const sp<IHDCP> &hdcp);
-
-    enum FlagBits {
-        FLAG_MANUALLY_PREPEND_SPS_PPS = 1,
-    };
-    ssize_t addTrack(const sp<AMessage> &format, uint32_t flags);
-
-    // If trackIndex == -1, initialize for transport stream muxing.
-    status_t initAsync(
-            ssize_t trackIndex,
-            const char *remoteHost,
-            int32_t remoteRTPPort,
-            RTPSender::TransportMode rtpMode,
-            int32_t remoteRTCPPort,
-            RTPSender::TransportMode rtcpMode,
-            int32_t *localRTPPort);
-
-    status_t queueAccessUnit(
-            size_t trackIndex, const sp<ABuffer> &accessUnit);
-
-protected:
-    virtual void onMessageReceived(const sp<AMessage> &msg);
-    virtual ~MediaSender();
-
-private:
-    enum {
-        kWhatSenderNotify,
-    };
-
-    enum Mode {
-        MODE_UNDEFINED,
-        MODE_TRANSPORT_STREAM,
-        MODE_ELEMENTARY_STREAMS,
-    };
-
-    struct TrackInfo {
-        sp<AMessage> mFormat;
-        uint32_t mFlags;
-        sp<RTPSender> mSender;
-        List<sp<ABuffer> > mAccessUnits;
-        ssize_t mPacketizerTrackIndex;
-        bool mIsAudio;
-    };
-
-    sp<ANetworkSession> mNetSession;
-    sp<AMessage> mNotify;
-
-    sp<IHDCP> mHDCP;
-
-    Mode mMode;
-    int32_t mGeneration;
-
-    Vector<TrackInfo> mTrackInfos;
-
-    sp<TSPacketizer> mTSPacketizer;
-    sp<RTPSender> mTSSender;
-    int64_t mPrevTimeUs;
-
-    size_t mInitDoneCount;
-
-    FILE *mLogFile;
-
-    void onSenderNotify(const sp<AMessage> &msg);
-
-    void notifyInitDone(status_t err);
-    void notifyError(status_t err);
-    void notifyNetworkStall(size_t numBytesQueued);
-
-    status_t packetizeAccessUnit(
-            size_t trackIndex,
-            sp<ABuffer> accessUnit,
-            sp<ABuffer> *tsPackets);
-
-    DISALLOW_EVIL_CONSTRUCTORS(MediaSender);
-};
-
-}  // namespace android
-
-#endif  // MEDIA_SENDER_H_
-
diff --git a/media/libstagefright/wifi-display/Parameters.cpp b/media/libstagefright/wifi-display/Parameters.cpp
deleted file mode 100644
index d2a61ea..0000000
--- a/media/libstagefright/wifi-display/Parameters.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright 2012, 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 "Parameters.h"
-
-#include <media/stagefright/MediaErrors.h>
-
-namespace android {
-
-// static
-sp<Parameters> Parameters::Parse(const char *data, size_t size) {
-    sp<Parameters> params = new Parameters;
-    status_t err = params->parse(data, size);
-
-    if (err != OK) {
-        return NULL;
-    }
-
-    return params;
-}
-
-Parameters::Parameters() {}
-
-Parameters::~Parameters() {}
-
-status_t Parameters::parse(const char *data, size_t size) {
-    size_t i = 0;
-    while (i < size) {
-        size_t nameStart = i;
-        while (i < size && data[i] != ':') {
-            ++i;
-        }
-
-        if (i == size || i == nameStart) {
-            return ERROR_MALFORMED;
-        }
-
-        AString name(&data[nameStart], i - nameStart);
-        name.trim();
-        name.tolower();
-
-        ++i;
-
-        size_t valueStart = i;
-
-        while (i + 1 < size && (data[i] != '\r' || data[i + 1] != '\n')) {
-            ++i;
-        }
-
-        AString value(&data[valueStart], i - valueStart);
-        value.trim();
-
-        mDict.add(name, value);
-
-        while (i + 1 < size && data[i] == '\r' && data[i + 1] == '\n') {
-            i += 2;
-        }
-    }
-
-    return OK;
-}
-
-bool Parameters::findParameter(const char *name, AString *value) const {
-    AString key = name;
-    key.tolower();
-
-    ssize_t index = mDict.indexOfKey(key);
-
-    if (index < 0) {
-        value->clear();
-
-        return false;
-    }
-
-    *value = mDict.valueAt(index);
-    return true;
-}
-
-}  // namespace android
diff --git a/media/libstagefright/wifi-display/Parameters.h b/media/libstagefright/wifi-display/Parameters.h
deleted file mode 100644
index a5e787e..0000000
--- a/media/libstagefright/wifi-display/Parameters.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2012, 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/foundation/ABase.h>
-#include <media/stagefright/foundation/AString.h>
-#include <utils/KeyedVector.h>
-#include <utils/RefBase.h>
-
-namespace android {
-
-struct Parameters : public RefBase {
-    static sp<Parameters> Parse(const char *data, size_t size);
-
-    bool findParameter(const char *name, AString *value) const;
-
-protected:
-    virtual ~Parameters();
-
-private:
-    KeyedVector<AString, AString> mDict;
-
-    Parameters();
-    status_t parse(const char *data, size_t size);
-
-    DISALLOW_EVIL_CONSTRUCTORS(Parameters);
-};
-
-}  // namespace android
diff --git a/media/libstagefright/wifi-display/VideoFormats.cpp b/media/libstagefright/wifi-display/VideoFormats.cpp
deleted file mode 100644
index dbc511c..0000000
--- a/media/libstagefright/wifi-display/VideoFormats.cpp
+++ /dev/null
@@ -1,550 +0,0 @@
-/*
- * Copyright 2013, 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 "VideoFormats"
-#include <utils/Log.h>
-
-#include "VideoFormats.h"
-
-#include <media/stagefright/foundation/ADebug.h>
-
-namespace android {
-
-// static
-const VideoFormats::config_t VideoFormats::mResolutionTable[][32] = {
-    {
-        // CEA Resolutions
-        { 640, 480, 60, false, 0, 0},
-        { 720, 480, 60, false, 0, 0},
-        { 720, 480, 60, true, 0, 0},
-        { 720, 576, 50, false, 0, 0},
-        { 720, 576, 50, true, 0, 0},
-        { 1280, 720, 30, false, 0, 0},
-        { 1280, 720, 60, false, 0, 0},
-        { 1920, 1080, 30, false, 0, 0},
-        { 1920, 1080, 60, false, 0, 0},
-        { 1920, 1080, 60, true, 0, 0},
-        { 1280, 720, 25, false, 0, 0},
-        { 1280, 720, 50, false, 0, 0},
-        { 1920, 1080, 25, false, 0, 0},
-        { 1920, 1080, 50, false, 0, 0},
-        { 1920, 1080, 50, true, 0, 0},
-        { 1280, 720, 24, false, 0, 0},
-        { 1920, 1080, 24, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-    },
-    {
-        // VESA Resolutions
-        { 800, 600, 30, false, 0, 0},
-        { 800, 600, 60, false, 0, 0},
-        { 1024, 768, 30, false, 0, 0},
-        { 1024, 768, 60, false, 0, 0},
-        { 1152, 864, 30, false, 0, 0},
-        { 1152, 864, 60, false, 0, 0},
-        { 1280, 768, 30, false, 0, 0},
-        { 1280, 768, 60, false, 0, 0},
-        { 1280, 800, 30, false, 0, 0},
-        { 1280, 800, 60, false, 0, 0},
-        { 1360, 768, 30, false, 0, 0},
-        { 1360, 768, 60, false, 0, 0},
-        { 1366, 768, 30, false, 0, 0},
-        { 1366, 768, 60, false, 0, 0},
-        { 1280, 1024, 30, false, 0, 0},
-        { 1280, 1024, 60, false, 0, 0},
-        { 1400, 1050, 30, false, 0, 0},
-        { 1400, 1050, 60, false, 0, 0},
-        { 1440, 900, 30, false, 0, 0},
-        { 1440, 900, 60, false, 0, 0},
-        { 1600, 900, 30, false, 0, 0},
-        { 1600, 900, 60, false, 0, 0},
-        { 1600, 1200, 30, false, 0, 0},
-        { 1600, 1200, 60, false, 0, 0},
-        { 1680, 1024, 30, false, 0, 0},
-        { 1680, 1024, 60, false, 0, 0},
-        { 1680, 1050, 30, false, 0, 0},
-        { 1680, 1050, 60, false, 0, 0},
-        { 1920, 1200, 30, false, 0, 0},
-        { 1920, 1200, 60, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-    },
-    {
-        // HH Resolutions
-        { 800, 480, 30, false, 0, 0},
-        { 800, 480, 60, false, 0, 0},
-        { 854, 480, 30, false, 0, 0},
-        { 854, 480, 60, false, 0, 0},
-        { 864, 480, 30, false, 0, 0},
-        { 864, 480, 60, false, 0, 0},
-        { 640, 360, 30, false, 0, 0},
-        { 640, 360, 60, false, 0, 0},
-        { 960, 540, 30, false, 0, 0},
-        { 960, 540, 60, false, 0, 0},
-        { 848, 480, 30, false, 0, 0},
-        { 848, 480, 60, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-        { 0, 0, 0, false, 0, 0},
-    }
-};
-
-VideoFormats::VideoFormats() {
-    memcpy(mConfigs, mResolutionTable, sizeof(mConfigs));
-
-    for (size_t i = 0; i < kNumResolutionTypes; ++i) {
-        mResolutionEnabled[i] = 0;
-    }
-
-    setNativeResolution(RESOLUTION_CEA, 0);  // default to 640x480 p60
-}
-
-void VideoFormats::setNativeResolution(ResolutionType type, size_t index) {
-    CHECK_LT(type, kNumResolutionTypes);
-    CHECK(GetConfiguration(type, index, NULL, NULL, NULL, NULL));
-
-    mNativeType = type;
-    mNativeIndex = index;
-
-    setResolutionEnabled(type, index);
-}
-
-void VideoFormats::getNativeResolution(
-        ResolutionType *type, size_t *index) const {
-    *type = mNativeType;
-    *index = mNativeIndex;
-}
-
-void VideoFormats::disableAll() {
-    for (size_t i = 0; i < kNumResolutionTypes; ++i) {
-        mResolutionEnabled[i] = 0;
-        for (size_t j = 0; j < 32; j++) {
-            mConfigs[i][j].profile = mConfigs[i][j].level = 0;
-        }
-    }
-}
-
-void VideoFormats::enableAll() {
-    for (size_t i = 0; i < kNumResolutionTypes; ++i) {
-        mResolutionEnabled[i] = 0xffffffff;
-        for (size_t j = 0; j < 32; j++) {
-            mConfigs[i][j].profile = (1ul << PROFILE_CBP);
-            mConfigs[i][j].level = (1ul << LEVEL_31);
-        }
-    }
-}
-
-void VideoFormats::enableResolutionUpto(
-        ResolutionType type, size_t index,
-        ProfileType profile, LevelType level) {
-    size_t width, height, fps, score;
-    bool interlaced;
-    if (!GetConfiguration(type, index, &width, &height,
-            &fps, &interlaced)) {
-        ALOGE("Maximum resolution not found!");
-        return;
-    }
-    score = width * height * fps * (!interlaced + 1);
-    for (size_t i = 0; i < kNumResolutionTypes; ++i) {
-        for (size_t j = 0; j < 32; j++) {
-            if (GetConfiguration((ResolutionType)i, j,
-                    &width, &height, &fps, &interlaced)
-                    && score >= width * height * fps * (!interlaced + 1)) {
-                setResolutionEnabled((ResolutionType)i, j);
-                setProfileLevel((ResolutionType)i, j, profile, level);
-            }
-        }
-    }
-}
-
-void VideoFormats::setResolutionEnabled(
-        ResolutionType type, size_t index, bool enabled) {
-    CHECK_LT(type, kNumResolutionTypes);
-    CHECK(GetConfiguration(type, index, NULL, NULL, NULL, NULL));
-
-    if (enabled) {
-        mResolutionEnabled[type] |= (1ul << index);
-        mConfigs[type][index].profile = (1ul << PROFILE_CBP);
-        mConfigs[type][index].level = (1ul << LEVEL_31);
-    } else {
-        mResolutionEnabled[type] &= ~(1ul << index);
-        mConfigs[type][index].profile = 0;
-        mConfigs[type][index].level = 0;
-    }
-}
-
-void VideoFormats::setProfileLevel(
-        ResolutionType type, size_t index,
-        ProfileType profile, LevelType level) {
-    CHECK_LT(type, kNumResolutionTypes);
-    CHECK(GetConfiguration(type, index, NULL, NULL, NULL, NULL));
-
-    mConfigs[type][index].profile = (1ul << profile);
-    mConfigs[type][index].level = (1ul << level);
-}
-
-void VideoFormats::getProfileLevel(
-        ResolutionType type, size_t index,
-        ProfileType *profile, LevelType *level) const{
-    CHECK_LT(type, kNumResolutionTypes);
-    CHECK(GetConfiguration(type, index, NULL, NULL, NULL, NULL));
-
-    int i, bestProfile = -1, bestLevel = -1;
-
-    for (i = 0; i < kNumProfileTypes; ++i) {
-        if (mConfigs[type][index].profile & (1ul << i)) {
-            bestProfile = i;
-        }
-    }
-
-    for (i = 0; i < kNumLevelTypes; ++i) {
-        if (mConfigs[type][index].level & (1ul << i)) {
-            bestLevel = i;
-        }
-    }
-
-    if (bestProfile == -1 || bestLevel == -1) {
-        ALOGE("Profile or level not set for resolution type %d, index %zu",
-                type, index);
-        bestProfile = PROFILE_CBP;
-        bestLevel = LEVEL_31;
-    }
-
-    *profile = (ProfileType) bestProfile;
-    *level = (LevelType) bestLevel;
-}
-
-bool VideoFormats::isResolutionEnabled(
-        ResolutionType type, size_t index) const {
-    CHECK_LT(type, kNumResolutionTypes);
-    CHECK(GetConfiguration(type, index, NULL, NULL, NULL, NULL));
-
-    return mResolutionEnabled[type] & (1ul << index);
-}
-
-// static
-bool VideoFormats::GetConfiguration(
-        ResolutionType type,
-        size_t index,
-        size_t *width, size_t *height, size_t *framesPerSecond,
-        bool *interlaced) {
-    CHECK_LT(type, kNumResolutionTypes);
-
-    if (index >= 32) {
-        return false;
-    }
-
-    const config_t *config = &mResolutionTable[type][index];
-
-    if (config->width == 0) {
-        return false;
-    }
-
-    if (width) {
-        *width = config->width;
-    }
-
-    if (height) {
-        *height = config->height;
-    }
-
-    if (framesPerSecond) {
-        *framesPerSecond = config->framesPerSecond;
-    }
-
-    if (interlaced) {
-        *interlaced = config->interlaced;
-    }
-
-    return true;
-}
-
-bool VideoFormats::parseH264Codec(const char *spec) {
-    unsigned profile, level, res[3];
-
-    if (sscanf(
-            spec,
-            "%02x %02x %08X %08X %08X",
-            &profile,
-            &level,
-            &res[0],
-            &res[1],
-            &res[2]) != 5) {
-        return false;
-    }
-
-    for (size_t i = 0; i < kNumResolutionTypes; ++i) {
-        for (size_t j = 0; j < 32; ++j) {
-            if (res[i] & (1ul << j)){
-                mResolutionEnabled[i] |= (1ul << j);
-                if (profile > mConfigs[i][j].profile) {
-                    // prefer higher profile (even if level is lower)
-                    mConfigs[i][j].profile = profile;
-                    mConfigs[i][j].level = level;
-                } else if (profile == mConfigs[i][j].profile &&
-                           level > mConfigs[i][j].level) {
-                    mConfigs[i][j].level = level;
-                }
-            }
-        }
-    }
-
-    return true;
-}
-
-// static
-bool VideoFormats::GetProfileLevel(
-        ProfileType profile, LevelType level, unsigned *profileIdc,
-        unsigned *levelIdc, unsigned *constraintSet) {
-    CHECK_LT(profile, kNumProfileTypes);
-    CHECK_LT(level, kNumLevelTypes);
-
-    static const unsigned kProfileIDC[kNumProfileTypes] = {
-        66,     // PROFILE_CBP
-        100,    // PROFILE_CHP
-    };
-
-    static const unsigned kLevelIDC[kNumLevelTypes] = {
-        31,     // LEVEL_31
-        32,     // LEVEL_32
-        40,     // LEVEL_40
-        41,     // LEVEL_41
-        42,     // LEVEL_42
-    };
-
-    static const unsigned kConstraintSet[kNumProfileTypes] = {
-        0xc0,   // PROFILE_CBP
-        0x0c,   // PROFILE_CHP
-    };
-
-    if (profileIdc) {
-        *profileIdc = kProfileIDC[profile];
-    }
-
-    if (levelIdc) {
-        *levelIdc = kLevelIDC[level];
-    }
-
-    if (constraintSet) {
-        *constraintSet = kConstraintSet[profile];
-    }
-
-    return true;
-}
-
-bool VideoFormats::parseFormatSpec(const char *spec) {
-    CHECK_EQ(kNumResolutionTypes, 3);
-
-    disableAll();
-
-    unsigned native, dummy;
-    size_t size = strlen(spec);
-    size_t offset = 0;
-
-    if (sscanf(spec, "%02x %02x ", &native, &dummy) != 2) {
-        return false;
-    }
-
-    offset += 6; // skip native and preferred-display-mode-supported
-    CHECK_LE(offset + 58, size);
-    while (offset < size) {
-        parseH264Codec(spec + offset);
-        offset += 60; // skip H.264-codec + ", "
-    }
-
-    mNativeIndex = native >> 3;
-    mNativeType = (ResolutionType)(native & 7);
-
-    bool success;
-    if (mNativeType >= kNumResolutionTypes) {
-        success = false;
-    } else {
-        success = GetConfiguration(
-                mNativeType, mNativeIndex, NULL, NULL, NULL, NULL);
-    }
-
-    if (!success) {
-        ALOGW("sink advertised an illegal native resolution, fortunately "
-              "this value is ignored for the time being...");
-    }
-
-    return true;
-}
-
-AString VideoFormats::getFormatSpec(bool forM4Message) const {
-    CHECK_EQ(kNumResolutionTypes, 3);
-
-    // wfd_video_formats:
-    // 1 byte "native"
-    // 1 byte "preferred-display-mode-supported" 0 or 1
-    // one or more avc codec structures
-    //   1 byte profile
-    //   1 byte level
-    //   4 byte CEA mask
-    //   4 byte VESA mask
-    //   4 byte HH mask
-    //   1 byte latency
-    //   2 byte min-slice-slice
-    //   2 byte slice-enc-params
-    //   1 byte framerate-control-support
-    //   max-hres (none or 2 byte)
-    //   max-vres (none or 2 byte)
-
-    return AStringPrintf(
-            "%02x 00 %02x %02x %08x %08x %08x 00 0000 0000 00 none none",
-            forM4Message ? 0x00 : ((mNativeIndex << 3) | mNativeType),
-            mConfigs[mNativeType][mNativeIndex].profile,
-            mConfigs[mNativeType][mNativeIndex].level,
-            mResolutionEnabled[0],
-            mResolutionEnabled[1],
-            mResolutionEnabled[2]);
-}
-
-// static
-bool VideoFormats::PickBestFormat(
-        const VideoFormats &sinkSupported,
-        const VideoFormats &sourceSupported,
-        ResolutionType *chosenType,
-        size_t *chosenIndex,
-        ProfileType *chosenProfile,
-        LevelType *chosenLevel) {
-#if 0
-    // Support for the native format is a great idea, the spec includes
-    // these features, but nobody supports it and the tests don't validate it.
-
-    ResolutionType nativeType;
-    size_t nativeIndex;
-    sinkSupported.getNativeResolution(&nativeType, &nativeIndex);
-    if (sinkSupported.isResolutionEnabled(nativeType, nativeIndex)) {
-        if (sourceSupported.isResolutionEnabled(nativeType, nativeIndex)) {
-            ALOGI("Choosing sink's native resolution");
-            *chosenType = nativeType;
-            *chosenIndex = nativeIndex;
-            return true;
-        }
-    } else {
-        ALOGW("Sink advertised native resolution that it doesn't "
-              "actually support... ignoring");
-    }
-
-    sourceSupported.getNativeResolution(&nativeType, &nativeIndex);
-    if (sourceSupported.isResolutionEnabled(nativeType, nativeIndex)) {
-        if (sinkSupported.isResolutionEnabled(nativeType, nativeIndex)) {
-            ALOGI("Choosing source's native resolution");
-            *chosenType = nativeType;
-            *chosenIndex = nativeIndex;
-            return true;
-        }
-    } else {
-        ALOGW("Source advertised native resolution that it doesn't "
-              "actually support... ignoring");
-    }
-#endif
-
-    bool first = true;
-    uint32_t bestScore = 0;
-    size_t bestType = 0;
-    size_t bestIndex = 0;
-    for (size_t i = 0; i < kNumResolutionTypes; ++i) {
-        for (size_t j = 0; j < 32; ++j) {
-            size_t width, height, framesPerSecond;
-            bool interlaced;
-            if (!GetConfiguration(
-                        (ResolutionType)i,
-                        j,
-                        &width, &height, &framesPerSecond, &interlaced)) {
-                break;
-            }
-
-            if (!sinkSupported.isResolutionEnabled((ResolutionType)i, j)
-                    || !sourceSupported.isResolutionEnabled(
-                        (ResolutionType)i, j)) {
-                continue;
-            }
-
-            ALOGV("type %zu, index %zu, %zu x %zu %c%zu supported",
-                  i, j, width, height, interlaced ? 'i' : 'p', framesPerSecond);
-
-            uint32_t score = width * height * framesPerSecond;
-            if (!interlaced) {
-                score *= 2;
-            }
-
-            if (first || score > bestScore) {
-                bestScore = score;
-                bestType = i;
-                bestIndex = j;
-
-                first = false;
-            }
-        }
-    }
-
-    if (first) {
-        return false;
-    }
-
-    *chosenType = (ResolutionType)bestType;
-    *chosenIndex = bestIndex;
-
-    // Pick the best profile/level supported by both sink and source.
-    ProfileType srcProfile, sinkProfile;
-    LevelType srcLevel, sinkLevel;
-    sourceSupported.getProfileLevel(
-                        (ResolutionType)bestType, bestIndex,
-                        &srcProfile, &srcLevel);
-    sinkSupported.getProfileLevel(
-                        (ResolutionType)bestType, bestIndex,
-                        &sinkProfile, &sinkLevel);
-    *chosenProfile = srcProfile < sinkProfile ? srcProfile : sinkProfile;
-    *chosenLevel = srcLevel < sinkLevel ? srcLevel : sinkLevel;
-
-    return true;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/wifi-display/VideoFormats.h b/media/libstagefright/wifi-display/VideoFormats.h
deleted file mode 100644
index fd38fd1..0000000
--- a/media/libstagefright/wifi-display/VideoFormats.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright 2013, 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 VIDEO_FORMATS_H_
-
-#define VIDEO_FORMATS_H_
-
-#include <media/stagefright/foundation/ABase.h>
-
-#include <stdint.h>
-
-namespace android {
-
-struct AString;
-
-// This class encapsulates that video resolution capabilities of a wfd source
-// or sink as outlined in the wfd specs. Currently three sets of resolutions
-// are specified, each of which supports up to 32 resolutions.
-// In addition to its capabilities each sink/source also publishes its
-// "native" resolution, presumably one that is preferred among all others
-// because it wouldn't require any scaling and directly corresponds to the
-// display capabilities/pixels.
-struct VideoFormats {
-    VideoFormats();
-
-    struct config_t {
-        size_t width, height, framesPerSecond;
-        bool interlaced;
-        unsigned char profile, level;
-    };
-
-    enum ProfileType {
-        PROFILE_CBP = 0,
-        PROFILE_CHP,
-        kNumProfileTypes,
-    };
-
-    enum LevelType {
-        LEVEL_31 = 0,
-        LEVEL_32,
-        LEVEL_40,
-        LEVEL_41,
-        LEVEL_42,
-        kNumLevelTypes,
-    };
-
-    enum ResolutionType {
-        RESOLUTION_CEA,
-        RESOLUTION_VESA,
-        RESOLUTION_HH,
-        kNumResolutionTypes,
-    };
-
-    void setNativeResolution(ResolutionType type, size_t index);
-    void getNativeResolution(ResolutionType *type, size_t *index) const;
-
-    void disableAll();
-    void enableAll();
-    void enableResolutionUpto(
-            ResolutionType type, size_t index,
-            ProfileType profile, LevelType level);
-
-    void setResolutionEnabled(
-            ResolutionType type, size_t index, bool enabled = true);
-
-    bool isResolutionEnabled(ResolutionType type, size_t index) const;
-
-    void setProfileLevel(
-            ResolutionType type, size_t index,
-            ProfileType profile, LevelType level);
-
-    void getProfileLevel(
-            ResolutionType type, size_t index,
-            ProfileType *profile, LevelType *level) const;
-
-    static bool GetConfiguration(
-            ResolutionType type, size_t index,
-            size_t *width, size_t *height, size_t *framesPerSecond,
-            bool *interlaced);
-
-    static bool GetProfileLevel(
-            ProfileType profile, LevelType level,
-            unsigned *profileIdc, unsigned *levelIdc,
-            unsigned *constraintSet);
-
-    bool parseFormatSpec(const char *spec);
-    AString getFormatSpec(bool forM4Message = false) const;
-
-    static bool PickBestFormat(
-            const VideoFormats &sinkSupported,
-            const VideoFormats &sourceSupported,
-            ResolutionType *chosenType,
-            size_t *chosenIndex,
-            ProfileType *chosenProfile,
-            LevelType *chosenLevel);
-
-private:
-    bool parseH264Codec(const char *spec);
-    ResolutionType mNativeType;
-    size_t mNativeIndex;
-
-    uint32_t mResolutionEnabled[kNumResolutionTypes];
-    static const config_t mResolutionTable[kNumResolutionTypes][32];
-    config_t mConfigs[kNumResolutionTypes][32];
-
-    DISALLOW_EVIL_CONSTRUCTORS(VideoFormats);
-};
-
-}  // namespace android
-
-#endif  // VIDEO_FORMATS_H_
-
diff --git a/media/libstagefright/wifi-display/rtp/RTPBase.h b/media/libstagefright/wifi-display/rtp/RTPBase.h
deleted file mode 100644
index 194f1ee..0000000
--- a/media/libstagefright/wifi-display/rtp/RTPBase.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2013, 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 RTP_BASE_H_
-
-#define RTP_BASE_H_
-
-namespace android {
-
-struct RTPBase {
-    enum PacketizationMode {
-        PACKETIZATION_TRANSPORT_STREAM,
-        PACKETIZATION_H264,
-        PACKETIZATION_AAC,
-        PACKETIZATION_NONE,
-    };
-
-    enum TransportMode {
-        TRANSPORT_UNDEFINED,
-        TRANSPORT_NONE,
-        TRANSPORT_UDP,
-        TRANSPORT_TCP,
-        TRANSPORT_TCP_INTERLEAVED,
-    };
-
-    // Really UDP _payload_ size
-    const unsigned int kMaxUDPPacketSize = 1472;   // 1472 good, 1473 bad on Android@Home
-
-    static int32_t PickRandomRTPPort();
-};
-
-}  // namespace android
-
-#endif  // RTP_BASE_H_
-
-
diff --git a/media/libstagefright/wifi-display/rtp/RTPSender.cpp b/media/libstagefright/wifi-display/rtp/RTPSender.cpp
deleted file mode 100644
index ca9fdd2..0000000
--- a/media/libstagefright/wifi-display/rtp/RTPSender.cpp
+++ /dev/null
@@ -1,808 +0,0 @@
-/*
- * Copyright 2013, 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 "RTPSender"
-#include <utils/Log.h>
-
-#include "RTPSender.h"
-
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/foundation/ANetworkSession.h>
-#include <media/stagefright/foundation/hexdump.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/Utils.h>
-
-#include "include/avc_utils.h"
-
-namespace android {
-
-RTPSender::RTPSender(
-        const sp<ANetworkSession> &netSession,
-        const sp<AMessage> &notify)
-    : mNetSession(netSession),
-      mNotify(notify),
-      mRTPMode(TRANSPORT_UNDEFINED),
-      mRTCPMode(TRANSPORT_UNDEFINED),
-      mRTPSessionID(0),
-      mRTCPSessionID(0),
-      mRTPConnected(false),
-      mRTCPConnected(false),
-      mLastNTPTime(0),
-      mLastRTPTime(0),
-      mNumRTPSent(0),
-      mNumRTPOctetsSent(0),
-      mNumSRsSent(0),
-      mRTPSeqNo(0),
-      mHistorySize(0) {
-}
-
-RTPSender::~RTPSender() {
-    if (mRTCPSessionID != 0) {
-        mNetSession->destroySession(mRTCPSessionID);
-        mRTCPSessionID = 0;
-    }
-
-    if (mRTPSessionID != 0) {
-        mNetSession->destroySession(mRTPSessionID);
-        mRTPSessionID = 0;
-    }
-}
-
-// static
-int32_t RTPBase::PickRandomRTPPort() {
-    // Pick an even integer in range [1024, 65534)
-
-    static const size_t kRange = (65534 - 1024) / 2;
-
-    return (int32_t)(((float)(kRange + 1) * rand()) / RAND_MAX) * 2 + 1024;
-}
-
-status_t RTPSender::initAsync(
-        const char *remoteHost,
-        int32_t remoteRTPPort,
-        TransportMode rtpMode,
-        int32_t remoteRTCPPort,
-        TransportMode rtcpMode,
-        int32_t *outLocalRTPPort) {
-    if (mRTPMode != TRANSPORT_UNDEFINED
-            || rtpMode == TRANSPORT_UNDEFINED
-            || rtpMode == TRANSPORT_NONE
-            || rtcpMode == TRANSPORT_UNDEFINED) {
-        return INVALID_OPERATION;
-    }
-
-    CHECK_NE(rtpMode, TRANSPORT_TCP_INTERLEAVED);
-    CHECK_NE(rtcpMode, TRANSPORT_TCP_INTERLEAVED);
-
-    if ((rtcpMode == TRANSPORT_NONE && remoteRTCPPort >= 0)
-            || (rtcpMode != TRANSPORT_NONE && remoteRTCPPort < 0)) {
-        return INVALID_OPERATION;
-    }
-
-    sp<AMessage> rtpNotify = new AMessage(kWhatRTPNotify, this);
-
-    sp<AMessage> rtcpNotify;
-    if (remoteRTCPPort >= 0) {
-        rtcpNotify = new AMessage(kWhatRTCPNotify, this);
-    }
-
-    CHECK_EQ(mRTPSessionID, 0);
-    CHECK_EQ(mRTCPSessionID, 0);
-
-    int32_t localRTPPort;
-
-    for (;;) {
-        localRTPPort = PickRandomRTPPort();
-
-        status_t err;
-        if (rtpMode == TRANSPORT_UDP) {
-            err = mNetSession->createUDPSession(
-                    localRTPPort,
-                    remoteHost,
-                    remoteRTPPort,
-                    rtpNotify,
-                    &mRTPSessionID);
-        } else {
-            CHECK_EQ(rtpMode, TRANSPORT_TCP);
-            err = mNetSession->createTCPDatagramSession(
-                    localRTPPort,
-                    remoteHost,
-                    remoteRTPPort,
-                    rtpNotify,
-                    &mRTPSessionID);
-        }
-
-        if (err != OK) {
-            continue;
-        }
-
-        if (remoteRTCPPort < 0) {
-            break;
-        }
-
-        if (rtcpMode == TRANSPORT_UDP) {
-            err = mNetSession->createUDPSession(
-                    localRTPPort + 1,
-                    remoteHost,
-                    remoteRTCPPort,
-                    rtcpNotify,
-                    &mRTCPSessionID);
-        } else {
-            CHECK_EQ(rtcpMode, TRANSPORT_TCP);
-            err = mNetSession->createTCPDatagramSession(
-                    localRTPPort + 1,
-                    remoteHost,
-                    remoteRTCPPort,
-                    rtcpNotify,
-                    &mRTCPSessionID);
-        }
-
-        if (err == OK) {
-            break;
-        }
-
-        mNetSession->destroySession(mRTPSessionID);
-        mRTPSessionID = 0;
-    }
-
-    if (rtpMode == TRANSPORT_UDP) {
-        mRTPConnected = true;
-    }
-
-    if (rtcpMode == TRANSPORT_UDP) {
-        mRTCPConnected = true;
-    }
-
-    mRTPMode = rtpMode;
-    mRTCPMode = rtcpMode;
-    *outLocalRTPPort = localRTPPort;
-
-    if (mRTPMode == TRANSPORT_UDP
-            && (mRTCPMode == TRANSPORT_UDP || mRTCPMode == TRANSPORT_NONE)) {
-        notifyInitDone(OK);
-    }
-
-    return OK;
-}
-
-status_t RTPSender::queueBuffer(
-        const sp<ABuffer> &buffer, uint8_t packetType, PacketizationMode mode) {
-    status_t err;
-
-    switch (mode) {
-        case PACKETIZATION_NONE:
-            err = queueRawPacket(buffer, packetType);
-            break;
-
-        case PACKETIZATION_TRANSPORT_STREAM:
-            err = queueTSPackets(buffer, packetType);
-            break;
-
-        case PACKETIZATION_H264:
-            err  = queueAVCBuffer(buffer, packetType);
-            break;
-
-        default:
-            TRESPASS();
-    }
-
-    return err;
-}
-
-status_t RTPSender::queueRawPacket(
-        const sp<ABuffer> &packet, uint8_t packetType) {
-    CHECK_LE(packet->size(), kMaxUDPPacketSize - 12);
-
-    int64_t timeUs;
-    CHECK(packet->meta()->findInt64("timeUs", &timeUs));
-
-    sp<ABuffer> udpPacket = new ABuffer(12 + packet->size());
-
-    udpPacket->setInt32Data(mRTPSeqNo);
-
-    uint8_t *rtp = udpPacket->data();
-    rtp[0] = 0x80;
-    rtp[1] = packetType;
-
-    rtp[2] = (mRTPSeqNo >> 8) & 0xff;
-    rtp[3] = mRTPSeqNo & 0xff;
-    ++mRTPSeqNo;
-
-    uint32_t rtpTime = (timeUs * 9) / 100ll;
-
-    rtp[4] = rtpTime >> 24;
-    rtp[5] = (rtpTime >> 16) & 0xff;
-    rtp[6] = (rtpTime >> 8) & 0xff;
-    rtp[7] = rtpTime & 0xff;
-
-    rtp[8] = kSourceID >> 24;
-    rtp[9] = (kSourceID >> 16) & 0xff;
-    rtp[10] = (kSourceID >> 8) & 0xff;
-    rtp[11] = kSourceID & 0xff;
-
-    memcpy(&rtp[12], packet->data(), packet->size());
-
-    return sendRTPPacket(
-            udpPacket,
-            true /* storeInHistory */,
-            true /* timeValid */,
-            ALooper::GetNowUs());
-}
-
-status_t RTPSender::queueTSPackets(
-        const sp<ABuffer> &tsPackets, uint8_t packetType) {
-    CHECK_EQ(0u, tsPackets->size() % 188);
-
-    int64_t timeUs;
-    CHECK(tsPackets->meta()->findInt64("timeUs", &timeUs));
-
-    size_t srcOffset = 0;
-    while (srcOffset < tsPackets->size()) {
-        sp<ABuffer> udpPacket =
-            new ABuffer(12 + kMaxNumTSPacketsPerRTPPacket * 188);
-
-        udpPacket->setInt32Data(mRTPSeqNo);
-
-        uint8_t *rtp = udpPacket->data();
-        rtp[0] = 0x80;
-        rtp[1] = packetType;
-
-        rtp[2] = (mRTPSeqNo >> 8) & 0xff;
-        rtp[3] = mRTPSeqNo & 0xff;
-        ++mRTPSeqNo;
-
-        int64_t nowUs = ALooper::GetNowUs();
-        uint32_t rtpTime = (nowUs * 9) / 100ll;
-
-        rtp[4] = rtpTime >> 24;
-        rtp[5] = (rtpTime >> 16) & 0xff;
-        rtp[6] = (rtpTime >> 8) & 0xff;
-        rtp[7] = rtpTime & 0xff;
-
-        rtp[8] = kSourceID >> 24;
-        rtp[9] = (kSourceID >> 16) & 0xff;
-        rtp[10] = (kSourceID >> 8) & 0xff;
-        rtp[11] = kSourceID & 0xff;
-
-        size_t numTSPackets = (tsPackets->size() - srcOffset) / 188;
-        if (numTSPackets > kMaxNumTSPacketsPerRTPPacket) {
-            numTSPackets = kMaxNumTSPacketsPerRTPPacket;
-        }
-
-        memcpy(&rtp[12], tsPackets->data() + srcOffset, numTSPackets * 188);
-
-        udpPacket->setRange(0, 12 + numTSPackets * 188);
-
-        srcOffset += numTSPackets * 188;
-        bool isLastPacket = (srcOffset == tsPackets->size());
-
-        status_t err = sendRTPPacket(
-                udpPacket,
-                true /* storeInHistory */,
-                isLastPacket /* timeValid */,
-                timeUs);
-
-        if (err != OK) {
-            return err;
-        }
-    }
-
-    return OK;
-}
-
-status_t RTPSender::queueAVCBuffer(
-        const sp<ABuffer> &accessUnit, uint8_t packetType) {
-    int64_t timeUs;
-    CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
-
-    uint32_t rtpTime = (timeUs * 9 / 100ll);
-
-    List<sp<ABuffer> > packets;
-
-    sp<ABuffer> out = new ABuffer(kMaxUDPPacketSize);
-    size_t outBytesUsed = 12;  // Placeholder for RTP header.
-
-    const uint8_t *data = accessUnit->data();
-    size_t size = accessUnit->size();
-    const uint8_t *nalStart;
-    size_t nalSize;
-    while (getNextNALUnit(
-                &data, &size, &nalStart, &nalSize,
-                true /* startCodeFollows */) == OK) {
-        size_t bytesNeeded = nalSize + 2;
-        if (outBytesUsed == 12) {
-            ++bytesNeeded;
-        }
-
-        if (outBytesUsed + bytesNeeded > out->capacity()) {
-            bool emitSingleNALPacket = false;
-
-            if (outBytesUsed == 12
-                    && outBytesUsed + nalSize <= out->capacity()) {
-                // We haven't emitted anything into the current packet yet and
-                // this NAL unit fits into a single-NAL-unit-packet while
-                // it wouldn't have fit as part of a STAP-A packet.
-
-                memcpy(out->data() + outBytesUsed, nalStart, nalSize);
-                outBytesUsed += nalSize;
-
-                emitSingleNALPacket = true;
-            }
-
-            if (outBytesUsed > 12) {
-                out->setRange(0, outBytesUsed);
-                packets.push_back(out);
-                out = new ABuffer(kMaxUDPPacketSize);
-                outBytesUsed = 12;  // Placeholder for RTP header
-            }
-
-            if (emitSingleNALPacket) {
-                continue;
-            }
-        }
-
-        if (outBytesUsed + bytesNeeded <= out->capacity()) {
-            uint8_t *dst = out->data() + outBytesUsed;
-
-            if (outBytesUsed == 12) {
-                *dst++ = 24;  // STAP-A header
-            }
-
-            *dst++ = (nalSize >> 8) & 0xff;
-            *dst++ = nalSize & 0xff;
-            memcpy(dst, nalStart, nalSize);
-
-            outBytesUsed += bytesNeeded;
-            continue;
-        }
-
-        // This single NAL unit does not fit into a single RTP packet,
-        // we need to emit an FU-A.
-
-        CHECK_EQ(outBytesUsed, 12u);
-
-        uint8_t nalType = nalStart[0] & 0x1f;
-        uint8_t nri = (nalStart[0] >> 5) & 3;
-
-        size_t srcOffset = 1;
-        while (srcOffset < nalSize) {
-            size_t copy = out->capacity() - outBytesUsed - 2;
-            if (copy > nalSize - srcOffset) {
-                copy = nalSize - srcOffset;
-            }
-
-            uint8_t *dst = out->data() + outBytesUsed;
-            dst[0] = (nri << 5) | 28;
-
-            dst[1] = nalType;
-
-            if (srcOffset == 1) {
-                dst[1] |= 0x80;
-            }
-
-            if (srcOffset + copy == nalSize) {
-                dst[1] |= 0x40;
-            }
-
-            memcpy(&dst[2], nalStart + srcOffset, copy);
-            srcOffset += copy;
-
-            out->setRange(0, outBytesUsed + copy + 2);
-
-            packets.push_back(out);
-            out = new ABuffer(kMaxUDPPacketSize);
-            outBytesUsed = 12;  // Placeholder for RTP header
-        }
-    }
-
-    if (outBytesUsed > 12) {
-        out->setRange(0, outBytesUsed);
-        packets.push_back(out);
-    }
-
-    while (!packets.empty()) {
-        sp<ABuffer> out = *packets.begin();
-        packets.erase(packets.begin());
-
-        out->setInt32Data(mRTPSeqNo);
-
-        bool last = packets.empty();
-
-        uint8_t *dst = out->data();
-
-        dst[0] = 0x80;
-
-        dst[1] = packetType;
-        if (last) {
-            dst[1] |= 1 << 7;  // M-bit
-        }
-
-        dst[2] = (mRTPSeqNo >> 8) & 0xff;
-        dst[3] = mRTPSeqNo & 0xff;
-        ++mRTPSeqNo;
-
-        dst[4] = rtpTime >> 24;
-        dst[5] = (rtpTime >> 16) & 0xff;
-        dst[6] = (rtpTime >> 8) & 0xff;
-        dst[7] = rtpTime & 0xff;
-        dst[8] = kSourceID >> 24;
-        dst[9] = (kSourceID >> 16) & 0xff;
-        dst[10] = (kSourceID >> 8) & 0xff;
-        dst[11] = kSourceID & 0xff;
-
-        status_t err = sendRTPPacket(out, true /* storeInHistory */);
-
-        if (err != OK) {
-            return err;
-        }
-    }
-
-    return OK;
-}
-
-status_t RTPSender::sendRTPPacket(
-        const sp<ABuffer> &buffer, bool storeInHistory,
-        bool timeValid, int64_t timeUs) {
-    CHECK(mRTPConnected);
-
-    status_t err = mNetSession->sendRequest(
-            mRTPSessionID, buffer->data(), buffer->size(),
-            timeValid, timeUs);
-
-    if (err != OK) {
-        return err;
-    }
-
-    mLastNTPTime = GetNowNTP();
-    mLastRTPTime = U32_AT(buffer->data() + 4);
-
-    ++mNumRTPSent;
-    mNumRTPOctetsSent += buffer->size() - 12;
-
-    if (storeInHistory) {
-        if (mHistorySize == kMaxHistorySize) {
-            mHistory.erase(mHistory.begin());
-        } else {
-            ++mHistorySize;
-        }
-        mHistory.push_back(buffer);
-    }
-
-    return OK;
-}
-
-// static
-uint64_t RTPSender::GetNowNTP() {
-    struct timeval tv;
-    gettimeofday(&tv, NULL /* timezone */);
-
-    uint64_t nowUs = tv.tv_sec * 1000000ll + tv.tv_usec;
-
-    nowUs += ((70ll * 365 + 17) * 24) * 60 * 60 * 1000000ll;
-
-    uint64_t hi = nowUs / 1000000ll;
-    uint64_t lo = ((1ll << 32) * (nowUs % 1000000ll)) / 1000000ll;
-
-    return (hi << 32) | lo;
-}
-
-void RTPSender::onMessageReceived(const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatRTPNotify:
-        case kWhatRTCPNotify:
-            onNetNotify(msg->what() == kWhatRTPNotify, msg);
-            break;
-
-        default:
-            TRESPASS();
-    }
-}
-
-void RTPSender::onNetNotify(bool isRTP, const sp<AMessage> &msg) {
-    int32_t reason;
-    CHECK(msg->findInt32("reason", &reason));
-
-    switch (reason) {
-        case ANetworkSession::kWhatError:
-        {
-            int32_t sessionID;
-            CHECK(msg->findInt32("sessionID", &sessionID));
-
-            int32_t err;
-            CHECK(msg->findInt32("err", &err));
-
-            int32_t errorOccuredDuringSend;
-            CHECK(msg->findInt32("send", &errorOccuredDuringSend));
-
-            AString detail;
-            CHECK(msg->findString("detail", &detail));
-
-            ALOGE("An error occurred during %s in session %d "
-                  "(%d, '%s' (%s)).",
-                  errorOccuredDuringSend ? "send" : "receive",
-                  sessionID,
-                  err,
-                  detail.c_str(),
-                  strerror(-err));
-
-            mNetSession->destroySession(sessionID);
-
-            if (sessionID == mRTPSessionID) {
-                mRTPSessionID = 0;
-            } else if (sessionID == mRTCPSessionID) {
-                mRTCPSessionID = 0;
-            }
-
-            if (!mRTPConnected
-                    || (mRTPMode != TRANSPORT_NONE && !mRTCPConnected)) {
-                // We haven't completed initialization, attach the error
-                // to the notification instead.
-                notifyInitDone(err);
-                break;
-            }
-
-            notifyError(err);
-            break;
-        }
-
-        case ANetworkSession::kWhatDatagram:
-        {
-            sp<ABuffer> data;
-            CHECK(msg->findBuffer("data", &data));
-
-            if (isRTP) {
-                ALOGW("Huh? Received data on RTP connection...");
-            } else {
-                onRTCPData(data);
-            }
-            break;
-        }
-
-        case ANetworkSession::kWhatConnected:
-        {
-            int32_t sessionID;
-            CHECK(msg->findInt32("sessionID", &sessionID));
-
-            if  (isRTP) {
-                CHECK_EQ(mRTPMode, TRANSPORT_TCP);
-                CHECK_EQ(sessionID, mRTPSessionID);
-                mRTPConnected = true;
-            } else {
-                CHECK_EQ(mRTCPMode, TRANSPORT_TCP);
-                CHECK_EQ(sessionID, mRTCPSessionID);
-                mRTCPConnected = true;
-            }
-
-            if (mRTPConnected
-                    && (mRTCPMode == TRANSPORT_NONE || mRTCPConnected)) {
-                notifyInitDone(OK);
-            }
-            break;
-        }
-
-        case ANetworkSession::kWhatNetworkStall:
-        {
-            size_t numBytesQueued;
-            CHECK(msg->findSize("numBytesQueued", &numBytesQueued));
-
-            notifyNetworkStall(numBytesQueued);
-            break;
-        }
-
-        default:
-            TRESPASS();
-    }
-}
-
-status_t RTPSender::onRTCPData(const sp<ABuffer> &buffer) {
-    const uint8_t *data = buffer->data();
-    size_t size = buffer->size();
-
-    while (size > 0) {
-        if (size < 8) {
-            // Too short to be a valid RTCP header
-            return ERROR_MALFORMED;
-        }
-
-        if ((data[0] >> 6) != 2) {
-            // Unsupported version.
-            return ERROR_UNSUPPORTED;
-        }
-
-        if (data[0] & 0x20) {
-            // Padding present.
-
-            size_t paddingLength = data[size - 1];
-
-            if (paddingLength + 12 > size) {
-                // If we removed this much padding we'd end up with something
-                // that's too short to be a valid RTP header.
-                return ERROR_MALFORMED;
-            }
-
-            size -= paddingLength;
-        }
-
-        size_t headerLength = 4 * (data[2] << 8 | data[3]) + 4;
-
-        if (size < headerLength) {
-            // Only received a partial packet?
-            return ERROR_MALFORMED;
-        }
-
-        switch (data[1]) {
-            case 200:
-            case 201:  // RR
-                parseReceiverReport(data, headerLength);
-                break;
-
-            case 202:  // SDES
-            case 203:
-                break;
-
-            case 204:  // APP
-                parseAPP(data, headerLength);
-                break;
-
-            case 205:  // TSFB (transport layer specific feedback)
-                parseTSFB(data, headerLength);
-                break;
-
-            case 206:  // PSFB (payload specific feedback)
-                // hexdump(data, headerLength);
-                break;
-
-            default:
-            {
-                ALOGW("Unknown RTCP packet type %u of size %zu",
-                        (unsigned)data[1], headerLength);
-                break;
-            }
-        }
-
-        data += headerLength;
-        size -= headerLength;
-    }
-
-    return OK;
-}
-
-status_t RTPSender::parseReceiverReport(
-        const uint8_t *data, size_t /* size */) {
-    float fractionLost = data[12] / 256.0f;
-
-    ALOGI("lost %.2f %% of packets during report interval.",
-          100.0f * fractionLost);
-
-    return OK;
-}
-
-status_t RTPSender::parseTSFB(const uint8_t *data, size_t size) {
-    if ((data[0] & 0x1f) != 1) {
-        return ERROR_UNSUPPORTED;  // We only support NACK for now.
-    }
-
-    uint32_t srcId = U32_AT(&data[8]);
-    if (srcId != kSourceID) {
-        return ERROR_MALFORMED;
-    }
-
-    for (size_t i = 12; i < size; i += 4) {
-        uint16_t seqNo = U16_AT(&data[i]);
-        uint16_t blp = U16_AT(&data[i + 2]);
-
-        List<sp<ABuffer> >::iterator it = mHistory.begin();
-        bool foundSeqNo = false;
-        while (it != mHistory.end()) {
-            const sp<ABuffer> &buffer = *it;
-
-            uint16_t bufferSeqNo = buffer->int32Data() & 0xffff;
-
-            bool retransmit = false;
-            if (bufferSeqNo == seqNo) {
-                retransmit = true;
-            } else if (blp != 0) {
-                for (size_t i = 0; i < 16; ++i) {
-                    if ((blp & (1 << i))
-                        && (bufferSeqNo == ((seqNo + i + 1) & 0xffff))) {
-                        blp &= ~(1 << i);
-                        retransmit = true;
-                    }
-                }
-            }
-
-            if (retransmit) {
-                ALOGV("retransmitting seqNo %d", bufferSeqNo);
-
-                CHECK_EQ((status_t)OK,
-                         sendRTPPacket(buffer, false /* storeInHistory */));
-
-                if (bufferSeqNo == seqNo) {
-                    foundSeqNo = true;
-                }
-
-                if (foundSeqNo && blp == 0) {
-                    break;
-                }
-            }
-
-            ++it;
-        }
-
-        if (!foundSeqNo || blp != 0) {
-            ALOGI("Some sequence numbers were no longer available for "
-                  "retransmission (seqNo = %d, foundSeqNo = %d, blp = 0x%04x)",
-                  seqNo, foundSeqNo, blp);
-
-            if (!mHistory.empty()) {
-                int32_t earliest = (*mHistory.begin())->int32Data() & 0xffff;
-                int32_t latest = (*--mHistory.end())->int32Data() & 0xffff;
-
-                ALOGI("have seq numbers from %d - %d", earliest, latest);
-            }
-        }
-    }
-
-    return OK;
-}
-
-status_t RTPSender::parseAPP(const uint8_t *data, size_t size) {
-    static const size_t late_offset = 8;
-    static const char late_string[] = "late";
-    static const size_t avgLatencyUs_offset = late_offset + sizeof(late_string) - 1;
-    static const size_t maxLatencyUs_offset = avgLatencyUs_offset + sizeof(int64_t);
-
-    if ((size >= (maxLatencyUs_offset + sizeof(int64_t)))
-            && !memcmp(late_string, &data[late_offset], sizeof(late_string) - 1)) {
-        int64_t avgLatencyUs = (int64_t)U64_AT(&data[avgLatencyUs_offset]);
-        int64_t maxLatencyUs = (int64_t)U64_AT(&data[maxLatencyUs_offset]);
-
-        sp<AMessage> notify = mNotify->dup();
-        notify->setInt32("what", kWhatInformSender);
-        notify->setInt64("avgLatencyUs", avgLatencyUs);
-        notify->setInt64("maxLatencyUs", maxLatencyUs);
-        notify->post();
-    }
-
-    return OK;
-}
-
-void RTPSender::notifyInitDone(status_t err) {
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("what", kWhatInitDone);
-    notify->setInt32("err", err);
-    notify->post();
-}
-
-void RTPSender::notifyError(status_t err) {
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("what", kWhatError);
-    notify->setInt32("err", err);
-    notify->post();
-}
-
-void RTPSender::notifyNetworkStall(size_t numBytesQueued) {
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("what", kWhatNetworkStall);
-    notify->setSize("numBytesQueued", numBytesQueued);
-    notify->post();
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/wifi-display/rtp/RTPSender.h b/media/libstagefright/wifi-display/rtp/RTPSender.h
deleted file mode 100644
index bedfd01..0000000
--- a/media/libstagefright/wifi-display/rtp/RTPSender.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright 2013, 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 RTP_SENDER_H_
-
-#define RTP_SENDER_H_
-
-#include "RTPBase.h"
-
-#include <media/stagefright/foundation/AHandler.h>
-
-namespace android {
-
-struct ABuffer;
-struct ANetworkSession;
-
-// An object of this class facilitates sending of media data over an RTP
-// channel. The channel is established over a UDP or TCP connection depending
-// on which "TransportMode" was chosen. In addition different RTP packetization
-// schemes are supported such as "Transport Stream Packets over RTP",
-// or "AVC/H.264 encapsulation as specified in RFC 3984 (non-interleaved mode)"
-struct RTPSender : public RTPBase, public AHandler {
-    enum {
-        kWhatInitDone,
-        kWhatError,
-        kWhatNetworkStall,
-        kWhatInformSender,
-    };
-    RTPSender(
-            const sp<ANetworkSession> &netSession,
-            const sp<AMessage> &notify);
-
-    status_t initAsync(
-              const char *remoteHost,
-              int32_t remoteRTPPort,
-              TransportMode rtpMode,
-              int32_t remoteRTCPPort,
-              TransportMode rtcpMode,
-              int32_t *outLocalRTPPort);
-
-    status_t queueBuffer(
-            const sp<ABuffer> &buffer,
-            uint8_t packetType,
-            PacketizationMode mode);
-
-protected:
-    virtual ~RTPSender();
-    virtual void onMessageReceived(const sp<AMessage> &msg);
-
-private:
-    enum {
-        kWhatRTPNotify,
-        kWhatRTCPNotify,
-    };
-
-    const unsigned int kMaxNumTSPacketsPerRTPPacket = (kMaxUDPPacketSize - 12) / 188;
-    const unsigned int kMaxHistorySize              = 1024;
-    const unsigned int kSourceID                    = 0xdeadbeef;
-
-    sp<ANetworkSession> mNetSession;
-    sp<AMessage> mNotify;
-    TransportMode mRTPMode;
-    TransportMode mRTCPMode;
-    int32_t mRTPSessionID;
-    int32_t mRTCPSessionID;
-    bool mRTPConnected;
-    bool mRTCPConnected;
-
-    uint64_t mLastNTPTime;
-    uint32_t mLastRTPTime;
-    uint32_t mNumRTPSent;
-    uint32_t mNumRTPOctetsSent;
-    uint32_t mNumSRsSent;
-
-    uint32_t mRTPSeqNo;
-
-    List<sp<ABuffer> > mHistory;
-    size_t mHistorySize;
-
-    static uint64_t GetNowNTP();
-
-    status_t queueRawPacket(const sp<ABuffer> &tsPackets, uint8_t packetType);
-    status_t queueTSPackets(const sp<ABuffer> &tsPackets, uint8_t packetType);
-    status_t queueAVCBuffer(const sp<ABuffer> &accessUnit, uint8_t packetType);
-
-    status_t sendRTPPacket(
-            const sp<ABuffer> &packet, bool storeInHistory,
-            bool timeValid = false, int64_t timeUs = -1ll);
-
-    void onNetNotify(bool isRTP, const sp<AMessage> &msg);
-
-    status_t onRTCPData(const sp<ABuffer> &data);
-    status_t parseReceiverReport(const uint8_t *data, size_t size);
-    status_t parseTSFB(const uint8_t *data, size_t size);
-    status_t parseAPP(const uint8_t *data, size_t size);
-
-    void notifyInitDone(status_t err);
-    void notifyError(status_t err);
-    void notifyNetworkStall(size_t numBytesQueued);
-
-    DISALLOW_EVIL_CONSTRUCTORS(RTPSender);
-};
-
-}  // namespace android
-
-#endif  // RTP_SENDER_H_
diff --git a/media/libstagefright/wifi-display/source/Converter.cpp b/media/libstagefright/wifi-display/source/Converter.cpp
deleted file mode 100644
index 273af18..0000000
--- a/media/libstagefright/wifi-display/source/Converter.cpp
+++ /dev/null
@@ -1,821 +0,0 @@
-/*
- * Copyright 2012, 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 "Converter"
-#include <utils/Log.h>
-
-#include "Converter.h"
-
-#include "MediaPuller.h"
-#include "include/avc_utils.h"
-
-#include <cutils/properties.h>
-#include <gui/Surface.h>
-#include <media/ICrypto.h>
-#include <media/MediaCodecBuffer.h>
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MediaCodec.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaErrors.h>
-
-#include <arpa/inet.h>
-
-#include <OMX_Video.h>
-
-namespace android {
-
-Converter::Converter(
-        const sp<AMessage> &notify,
-        const sp<ALooper> &codecLooper,
-        const sp<AMessage> &outputFormat,
-        uint32_t flags)
-    : mNotify(notify),
-      mCodecLooper(codecLooper),
-      mOutputFormat(outputFormat),
-      mFlags(flags),
-      mIsVideo(false),
-      mIsH264(false),
-      mIsPCMAudio(false),
-      mNeedToManuallyPrependSPSPPS(false),
-      mDoMoreWorkPending(false)
-#if ENABLE_SILENCE_DETECTION
-      ,mFirstSilentFrameUs(-1ll)
-      ,mInSilentMode(false)
-#endif
-      ,mPrevVideoBitrate(-1)
-      ,mNumFramesToDrop(0)
-      ,mEncodingSuspended(false)
-    {
-    AString mime;
-    CHECK(mOutputFormat->findString("mime", &mime));
-
-    if (!strncasecmp("video/", mime.c_str(), 6)) {
-        mIsVideo = true;
-
-        mIsH264 = !strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC);
-    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mime.c_str())) {
-        mIsPCMAudio = true;
-    }
-}
-
-void Converter::releaseEncoder() {
-    if (mEncoder == NULL) {
-        return;
-    }
-
-    mEncoder->release();
-    mEncoder.clear();
-
-    mInputBufferQueue.clear();
-    mEncoderInputBuffers.clear();
-    mEncoderOutputBuffers.clear();
-}
-
-Converter::~Converter() {
-    CHECK(mEncoder == NULL);
-}
-
-void Converter::shutdownAsync() {
-    ALOGV("shutdown");
-    (new AMessage(kWhatShutdown, this))->post();
-}
-
-status_t Converter::init() {
-    status_t err = initEncoder();
-
-    if (err != OK) {
-        releaseEncoder();
-    }
-
-    return err;
-}
-
-sp<IGraphicBufferProducer> Converter::getGraphicBufferProducer() {
-    CHECK(mFlags & FLAG_USE_SURFACE_INPUT);
-    return mGraphicBufferProducer;
-}
-
-size_t Converter::getInputBufferCount() const {
-    return mEncoderInputBuffers.size();
-}
-
-sp<AMessage> Converter::getOutputFormat() const {
-    return mOutputFormat;
-}
-
-bool Converter::needToManuallyPrependSPSPPS() const {
-    return mNeedToManuallyPrependSPSPPS;
-}
-
-// static
-int32_t Converter::GetInt32Property(
-        const char *propName, int32_t defaultValue) {
-    char val[PROPERTY_VALUE_MAX];
-    if (property_get(propName, val, NULL)) {
-        char *end;
-        unsigned long x = strtoul(val, &end, 10);
-
-        if (*end == '\0' && end > val && x > 0) {
-            return x;
-        }
-    }
-
-    return defaultValue;
-}
-
-status_t Converter::initEncoder() {
-    AString outputMIME;
-    CHECK(mOutputFormat->findString("mime", &outputMIME));
-
-    bool isAudio = !strncasecmp(outputMIME.c_str(), "audio/", 6);
-
-    if (!mIsPCMAudio) {
-        mEncoder = MediaCodec::CreateByType(
-                mCodecLooper, outputMIME.c_str(), true /* encoder */);
-
-        if (mEncoder == NULL) {
-            return ERROR_UNSUPPORTED;
-        }
-    }
-
-    if (mIsPCMAudio) {
-        return OK;
-    }
-
-    int32_t audioBitrate = GetInt32Property("media.wfd.audio-bitrate", 128000);
-    int32_t videoBitrate = GetInt32Property("media.wfd.video-bitrate", 5000000);
-    mPrevVideoBitrate = videoBitrate;
-
-    ALOGI("using audio bitrate of %d bps, video bitrate of %d bps",
-          audioBitrate, videoBitrate);
-
-    if (isAudio) {
-        mOutputFormat->setInt32("bitrate", audioBitrate);
-    } else {
-        mOutputFormat->setInt32("bitrate", videoBitrate);
-        mOutputFormat->setInt32("bitrate-mode", OMX_Video_ControlRateConstant);
-        mOutputFormat->setInt32("frame-rate", 30);
-        mOutputFormat->setInt32("i-frame-interval", 15);  // Iframes every 15 secs
-
-        // Configure encoder to use intra macroblock refresh mode
-        mOutputFormat->setInt32("intra-refresh-mode", OMX_VIDEO_IntraRefreshCyclic);
-
-        int width, height, mbs;
-        if (!mOutputFormat->findInt32("width", &width)
-                || !mOutputFormat->findInt32("height", &height)) {
-            return ERROR_UNSUPPORTED;
-        }
-
-        // Update macroblocks in a cyclic fashion with 10% of all MBs within
-        // frame gets updated at one time. It takes about 10 frames to
-        // completely update a whole video frame. If the frame rate is 30,
-        // it takes about 333 ms in the best case (if next frame is not an IDR)
-        // to recover from a lost/corrupted packet.
-        mbs = (((width + 15) / 16) * ((height + 15) / 16) * 10) / 100;
-        mOutputFormat->setInt32("intra-refresh-CIR-mbs", mbs);
-    }
-
-    ALOGV("output format is '%s'", mOutputFormat->debugString(0).c_str());
-
-    mNeedToManuallyPrependSPSPPS = false;
-
-    status_t err = NO_INIT;
-
-    if (!isAudio) {
-        sp<AMessage> tmp = mOutputFormat->dup();
-        tmp->setInt32("prepend-sps-pps-to-idr-frames", 1);
-
-        err = mEncoder->configure(
-                tmp,
-                NULL /* nativeWindow */,
-                NULL /* crypto */,
-                MediaCodec::CONFIGURE_FLAG_ENCODE);
-
-        if (err == OK) {
-            // Encoder supported prepending SPS/PPS, we don't need to emulate
-            // it.
-            mOutputFormat = tmp;
-        } else {
-            mNeedToManuallyPrependSPSPPS = true;
-
-            ALOGI("We going to manually prepend SPS and PPS to IDR frames.");
-        }
-    }
-
-    if (err != OK) {
-        // We'll get here for audio or if we failed to configure the encoder
-        // to automatically prepend SPS/PPS in the case of video.
-
-        err = mEncoder->configure(
-                    mOutputFormat,
-                    NULL /* nativeWindow */,
-                    NULL /* crypto */,
-                    MediaCodec::CONFIGURE_FLAG_ENCODE);
-    }
-
-    if (err != OK) {
-        return err;
-    }
-
-    if (mFlags & FLAG_USE_SURFACE_INPUT) {
-        CHECK(mIsVideo);
-
-        err = mEncoder->createInputSurface(&mGraphicBufferProducer);
-
-        if (err != OK) {
-            return err;
-        }
-    }
-
-    err = mEncoder->start();
-
-    if (err != OK) {
-        return err;
-    }
-
-    err = mEncoder->getInputBuffers(&mEncoderInputBuffers);
-
-    if (err != OK) {
-        return err;
-    }
-
-    err = mEncoder->getOutputBuffers(&mEncoderOutputBuffers);
-
-    if (err != OK) {
-        return err;
-    }
-
-    if (mFlags & FLAG_USE_SURFACE_INPUT) {
-        scheduleDoMoreWork();
-    }
-
-    return OK;
-}
-
-void Converter::notifyError(status_t err) {
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("what", kWhatError);
-    notify->setInt32("err", err);
-    notify->post();
-}
-
-// static
-bool Converter::IsSilence(const sp<ABuffer> &accessUnit) {
-    const uint8_t *ptr = accessUnit->data();
-    const uint8_t *end = ptr + accessUnit->size();
-    while (ptr < end) {
-        if (*ptr != 0) {
-            return false;
-        }
-        ++ptr;
-    }
-
-    return true;
-}
-
-void Converter::onMessageReceived(const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatMediaPullerNotify:
-        {
-            int32_t what;
-            CHECK(msg->findInt32("what", &what));
-
-            if (!mIsPCMAudio && mEncoder == NULL) {
-                ALOGV("got msg '%s' after encoder shutdown.",
-                      msg->debugString().c_str());
-
-                if (what == MediaPuller::kWhatAccessUnit) {
-                    sp<ABuffer> accessUnit;
-                    CHECK(msg->findBuffer("accessUnit", &accessUnit));
-
-                    accessUnit->setMediaBufferBase(NULL);
-                }
-                break;
-            }
-
-            if (what == MediaPuller::kWhatEOS) {
-                mInputBufferQueue.push_back(NULL);
-
-                feedEncoderInputBuffers();
-
-                scheduleDoMoreWork();
-            } else {
-                CHECK_EQ(what, MediaPuller::kWhatAccessUnit);
-
-                sp<ABuffer> accessUnit;
-                CHECK(msg->findBuffer("accessUnit", &accessUnit));
-
-                if (mNumFramesToDrop > 0 || mEncodingSuspended) {
-                    if (mNumFramesToDrop > 0) {
-                        --mNumFramesToDrop;
-                        ALOGI("dropping frame.");
-                    }
-
-                    accessUnit->setMediaBufferBase(NULL);
-                    break;
-                }
-
-#if 0
-                MediaBuffer *mbuf =
-                    (MediaBuffer *)(accessUnit->getMediaBufferBase());
-                if (mbuf != NULL) {
-                    ALOGI("queueing mbuf %p", mbuf);
-                    mbuf->release();
-                }
-#endif
-
-#if ENABLE_SILENCE_DETECTION
-                if (!mIsVideo) {
-                    if (IsSilence(accessUnit)) {
-                        if (mInSilentMode) {
-                            break;
-                        }
-
-                        int64_t nowUs = ALooper::GetNowUs();
-
-                        if (mFirstSilentFrameUs < 0ll) {
-                            mFirstSilentFrameUs = nowUs;
-                        } else if (nowUs >= mFirstSilentFrameUs + 10000000ll) {
-                            mInSilentMode = true;
-                            ALOGI("audio in silent mode now.");
-                            break;
-                        }
-                    } else {
-                        if (mInSilentMode) {
-                            ALOGI("audio no longer in silent mode.");
-                        }
-                        mInSilentMode = false;
-                        mFirstSilentFrameUs = -1ll;
-                    }
-                }
-#endif
-
-                mInputBufferQueue.push_back(accessUnit);
-
-                feedEncoderInputBuffers();
-
-                scheduleDoMoreWork();
-            }
-            break;
-        }
-
-        case kWhatEncoderActivity:
-        {
-#if 0
-            int64_t whenUs;
-            if (msg->findInt64("whenUs", &whenUs)) {
-                int64_t nowUs = ALooper::GetNowUs();
-                ALOGI("[%s] kWhatEncoderActivity after %lld us",
-                      mIsVideo ? "video" : "audio", nowUs - whenUs);
-            }
-#endif
-
-            mDoMoreWorkPending = false;
-
-            if (mEncoder == NULL) {
-                break;
-            }
-
-            status_t err = doMoreWork();
-
-            if (err != OK) {
-                notifyError(err);
-            } else {
-                scheduleDoMoreWork();
-            }
-            break;
-        }
-
-        case kWhatRequestIDRFrame:
-        {
-            if (mEncoder == NULL) {
-                break;
-            }
-
-            if (mIsVideo) {
-                ALOGV("requesting IDR frame");
-                mEncoder->requestIDRFrame();
-            }
-            break;
-        }
-
-        case kWhatShutdown:
-        {
-            ALOGI("shutting down %s encoder", mIsVideo ? "video" : "audio");
-
-            releaseEncoder();
-
-            AString mime;
-            CHECK(mOutputFormat->findString("mime", &mime));
-            ALOGI("encoder (%s) shut down.", mime.c_str());
-
-            sp<AMessage> notify = mNotify->dup();
-            notify->setInt32("what", kWhatShutdownCompleted);
-            notify->post();
-            break;
-        }
-
-        case kWhatDropAFrame:
-        {
-            ++mNumFramesToDrop;
-            break;
-        }
-
-        case kWhatReleaseOutputBuffer:
-        {
-            if (mEncoder != NULL) {
-                size_t bufferIndex;
-                CHECK(msg->findInt32("bufferIndex", (int32_t*)&bufferIndex));
-                CHECK(bufferIndex < mEncoderOutputBuffers.size());
-                mEncoder->releaseOutputBuffer(bufferIndex);
-            }
-            break;
-        }
-
-        case kWhatSuspendEncoding:
-        {
-            int32_t suspend;
-            CHECK(msg->findInt32("suspend", &suspend));
-
-            mEncodingSuspended = suspend;
-
-            if (mFlags & FLAG_USE_SURFACE_INPUT) {
-                sp<AMessage> params = new AMessage;
-                params->setInt32("drop-input-frames",suspend);
-                mEncoder->setParameters(params);
-            }
-            break;
-        }
-
-        default:
-            TRESPASS();
-    }
-}
-
-void Converter::scheduleDoMoreWork() {
-    if (mIsPCMAudio) {
-        // There's no encoder involved in this case.
-        return;
-    }
-
-    if (mDoMoreWorkPending) {
-        return;
-    }
-
-    mDoMoreWorkPending = true;
-
-#if 1
-    if (mEncoderActivityNotify == NULL) {
-        mEncoderActivityNotify = new AMessage(kWhatEncoderActivity, this);
-    }
-    mEncoder->requestActivityNotification(mEncoderActivityNotify->dup());
-#else
-    sp<AMessage> notify = new AMessage(kWhatEncoderActivity, this);
-    notify->setInt64("whenUs", ALooper::GetNowUs());
-    mEncoder->requestActivityNotification(notify);
-#endif
-}
-
-status_t Converter::feedRawAudioInputBuffers() {
-    // Split incoming PCM audio into buffers of 6 AUs of 80 audio frames each
-    // and add a 4 byte header according to the wifi display specs.
-
-    while (!mInputBufferQueue.empty()) {
-        sp<ABuffer> buffer = *mInputBufferQueue.begin();
-        mInputBufferQueue.erase(mInputBufferQueue.begin());
-
-        int16_t *ptr = (int16_t *)buffer->data();
-        int16_t *stop = (int16_t *)(buffer->data() + buffer->size());
-        while (ptr < stop) {
-            *ptr = htons(*ptr);
-            ++ptr;
-        }
-
-        static const size_t kFrameSize = 2 * sizeof(int16_t);  // stereo
-        static const size_t kFramesPerAU = 80;
-        static const size_t kNumAUsPerPESPacket = 6;
-
-        if (mPartialAudioAU != NULL) {
-            size_t bytesMissingForFullAU =
-                kNumAUsPerPESPacket * kFramesPerAU * kFrameSize
-                - mPartialAudioAU->size() + 4;
-
-            size_t copy = buffer->size();
-            if(copy > bytesMissingForFullAU) {
-                copy = bytesMissingForFullAU;
-            }
-
-            memcpy(mPartialAudioAU->data() + mPartialAudioAU->size(),
-                   buffer->data(),
-                   copy);
-
-            mPartialAudioAU->setRange(0, mPartialAudioAU->size() + copy);
-
-            buffer->setRange(buffer->offset() + copy, buffer->size() - copy);
-
-            int64_t timeUs;
-            CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
-
-            int64_t copyUs = (int64_t)((copy / kFrameSize) * 1E6 / 48000.0);
-            timeUs += copyUs;
-            buffer->meta()->setInt64("timeUs", timeUs);
-
-            if (bytesMissingForFullAU == copy) {
-                sp<AMessage> notify = mNotify->dup();
-                notify->setInt32("what", kWhatAccessUnit);
-                notify->setBuffer("accessUnit", mPartialAudioAU);
-                notify->post();
-
-                mPartialAudioAU.clear();
-            }
-        }
-
-        while (buffer->size() > 0) {
-            sp<ABuffer> partialAudioAU =
-                new ABuffer(
-                        4
-                        + kNumAUsPerPESPacket * kFrameSize * kFramesPerAU);
-
-            uint8_t *ptr = partialAudioAU->data();
-            ptr[0] = 0xa0;  // 10100000b
-            ptr[1] = kNumAUsPerPESPacket;
-            ptr[2] = 0;  // reserved, audio _emphasis_flag = 0
-
-            static const unsigned kQuantizationWordLength = 0;  // 16-bit
-            static const unsigned kAudioSamplingFrequency = 2;  // 48Khz
-            static const unsigned kNumberOfAudioChannels = 1;  // stereo
-
-            ptr[3] = (kQuantizationWordLength << 6)
-                    | (kAudioSamplingFrequency << 3)
-                    | kNumberOfAudioChannels;
-
-            size_t copy = buffer->size();
-            if (copy > partialAudioAU->size() - 4) {
-                copy = partialAudioAU->size() - 4;
-            }
-
-            memcpy(&ptr[4], buffer->data(), copy);
-
-            partialAudioAU->setRange(0, 4 + copy);
-            buffer->setRange(buffer->offset() + copy, buffer->size() - copy);
-
-            int64_t timeUs;
-            CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
-
-            partialAudioAU->meta()->setInt64("timeUs", timeUs);
-
-            int64_t copyUs = (int64_t)((copy / kFrameSize) * 1E6 / 48000.0);
-            timeUs += copyUs;
-            buffer->meta()->setInt64("timeUs", timeUs);
-
-            if (copy == partialAudioAU->capacity() - 4) {
-                sp<AMessage> notify = mNotify->dup();
-                notify->setInt32("what", kWhatAccessUnit);
-                notify->setBuffer("accessUnit", partialAudioAU);
-                notify->post();
-
-                partialAudioAU.clear();
-                continue;
-            }
-
-            mPartialAudioAU = partialAudioAU;
-        }
-    }
-
-    return OK;
-}
-
-status_t Converter::feedEncoderInputBuffers() {
-    if (mIsPCMAudio) {
-        return feedRawAudioInputBuffers();
-    }
-
-    while (!mInputBufferQueue.empty()
-            && !mAvailEncoderInputIndices.empty()) {
-        sp<ABuffer> buffer = *mInputBufferQueue.begin();
-        mInputBufferQueue.erase(mInputBufferQueue.begin());
-
-        size_t bufferIndex = *mAvailEncoderInputIndices.begin();
-        mAvailEncoderInputIndices.erase(mAvailEncoderInputIndices.begin());
-
-        int64_t timeUs = 0ll;
-        uint32_t flags = 0;
-
-        if (buffer != NULL) {
-            CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
-
-            memcpy(mEncoderInputBuffers.itemAt(bufferIndex)->data(),
-                   buffer->data(),
-                   buffer->size());
-
-            MediaBuffer *mediaBuffer =
-                (MediaBuffer *)(buffer->getMediaBufferBase());
-            if (mediaBuffer != NULL) {
-                mEncoderInputBuffers.itemAt(bufferIndex)->setMediaBufferBase(
-                        mediaBuffer);
-
-                buffer->setMediaBufferBase(NULL);
-            }
-        } else {
-            flags = MediaCodec::BUFFER_FLAG_EOS;
-        }
-
-        status_t err = mEncoder->queueInputBuffer(
-                bufferIndex, 0, (buffer == NULL) ? 0 : buffer->size(),
-                timeUs, flags);
-
-        if (err != OK) {
-            return err;
-        }
-    }
-
-    return OK;
-}
-
-sp<ABuffer> Converter::prependCSD(const sp<ABuffer> &accessUnit) const {
-    CHECK(mCSD0 != NULL);
-
-    sp<ABuffer> dup = new ABuffer(accessUnit->size() + mCSD0->size());
-    memcpy(dup->data(), mCSD0->data(), mCSD0->size());
-    memcpy(dup->data() + mCSD0->size(), accessUnit->data(), accessUnit->size());
-
-    int64_t timeUs;
-    CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
-
-    dup->meta()->setInt64("timeUs", timeUs);
-
-    return dup;
-}
-
-status_t Converter::doMoreWork() {
-    status_t err;
-
-    if (!(mFlags & FLAG_USE_SURFACE_INPUT)) {
-        for (;;) {
-            size_t bufferIndex;
-            err = mEncoder->dequeueInputBuffer(&bufferIndex);
-
-            if (err != OK) {
-                break;
-            }
-
-            mAvailEncoderInputIndices.push_back(bufferIndex);
-        }
-
-        feedEncoderInputBuffers();
-    }
-
-    for (;;) {
-        size_t bufferIndex;
-        size_t offset;
-        size_t size;
-        int64_t timeUs;
-        uint32_t flags;
-        native_handle_t* handle = NULL;
-        err = mEncoder->dequeueOutputBuffer(
-                &bufferIndex, &offset, &size, &timeUs, &flags);
-
-        if (err != OK) {
-            if (err == INFO_FORMAT_CHANGED) {
-                continue;
-            } else if (err == INFO_OUTPUT_BUFFERS_CHANGED) {
-                mEncoder->getOutputBuffers(&mEncoderOutputBuffers);
-                continue;
-            }
-
-            if (err == -EAGAIN) {
-                err = OK;
-            }
-            break;
-        }
-
-        if (flags & MediaCodec::BUFFER_FLAG_EOS) {
-            sp<AMessage> notify = mNotify->dup();
-            notify->setInt32("what", kWhatEOS);
-            notify->post();
-        } else {
-#if 0
-            if (mIsVideo) {
-                int32_t videoBitrate = GetInt32Property(
-                        "media.wfd.video-bitrate", 5000000);
-
-                setVideoBitrate(videoBitrate);
-            }
-#endif
-
-            sp<ABuffer> buffer;
-            sp<MediaCodecBuffer> outbuf = mEncoderOutputBuffers.itemAt(bufferIndex);
-
-            if (outbuf->meta()->findPointer("handle", (void**)&handle) &&
-                    handle != NULL) {
-                int32_t rangeLength, rangeOffset;
-                CHECK(outbuf->meta()->findInt32("rangeOffset", &rangeOffset));
-                CHECK(outbuf->meta()->findInt32("rangeLength", &rangeLength));
-                outbuf->meta()->setPointer("handle", NULL);
-
-                // MediaSender will post the following message when HDCP
-                // is done, to release the output buffer back to encoder.
-                sp<AMessage> notify(new AMessage(kWhatReleaseOutputBuffer, this));
-                notify->setInt32("bufferIndex", bufferIndex);
-
-                buffer = new ABuffer(
-                        rangeLength > (int32_t)size ? rangeLength : size);
-                buffer->meta()->setPointer("handle", handle);
-                buffer->meta()->setInt32("rangeOffset", rangeOffset);
-                buffer->meta()->setInt32("rangeLength", rangeLength);
-                buffer->meta()->setMessage("notify", notify);
-            } else {
-                buffer = new ABuffer(size);
-            }
-
-            buffer->meta()->setInt64("timeUs", timeUs);
-
-            ALOGV("[%s] time %lld us (%.2f secs)",
-                    mIsVideo ? "video" : "audio", (long long)timeUs, timeUs / 1E6);
-
-            memcpy(buffer->data(), outbuf->base() + offset, size);
-
-            if (flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) {
-                if (!handle) {
-                    if (mIsH264) {
-                        mCSD0 = buffer;
-                    }
-                    mOutputFormat->setBuffer("csd-0", buffer);
-                }
-            } else {
-                if (mNeedToManuallyPrependSPSPPS
-                        && mIsH264
-                        && (mFlags & FLAG_PREPEND_CSD_IF_NECESSARY)
-                        && IsIDR(buffer)) {
-                    buffer = prependCSD(buffer);
-                }
-
-                sp<AMessage> notify = mNotify->dup();
-                notify->setInt32("what", kWhatAccessUnit);
-                notify->setBuffer("accessUnit", buffer);
-                notify->post();
-            }
-        }
-
-        if (!handle) {
-            mEncoder->releaseOutputBuffer(bufferIndex);
-        }
-
-        if (flags & MediaCodec::BUFFER_FLAG_EOS) {
-            break;
-        }
-    }
-
-    return err;
-}
-
-void Converter::requestIDRFrame() {
-    (new AMessage(kWhatRequestIDRFrame, this))->post();
-}
-
-void Converter::dropAFrame() {
-    // Unsupported in surface input mode.
-    CHECK(!(mFlags & FLAG_USE_SURFACE_INPUT));
-
-    (new AMessage(kWhatDropAFrame, this))->post();
-}
-
-void Converter::suspendEncoding(bool suspend) {
-    sp<AMessage> msg = new AMessage(kWhatSuspendEncoding, this);
-    msg->setInt32("suspend", suspend);
-    msg->post();
-}
-
-int32_t Converter::getVideoBitrate() const {
-    return mPrevVideoBitrate;
-}
-
-void Converter::setVideoBitrate(int32_t bitRate) {
-    if (mIsVideo && mEncoder != NULL && bitRate != mPrevVideoBitrate) {
-        sp<AMessage> params = new AMessage;
-        params->setInt32("video-bitrate", bitRate);
-
-        mEncoder->setParameters(params);
-
-        mPrevVideoBitrate = bitRate;
-    }
-}
-
-}  // namespace android
diff --git a/media/libstagefright/wifi-display/source/Converter.h b/media/libstagefright/wifi-display/source/Converter.h
deleted file mode 100644
index ad95ab5..0000000
--- a/media/libstagefright/wifi-display/source/Converter.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright 2012, 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 CONVERTER_H_
-
-#define CONVERTER_H_
-
-#include <media/stagefright/foundation/AHandler.h>
-
-namespace android {
-
-struct ABuffer;
-class IGraphicBufferProducer;
-struct MediaCodec;
-class MediaCodecBuffer;
-
-#define ENABLE_SILENCE_DETECTION        0
-
-// Utility class that receives media access units and converts them into
-// media access unit of a different format.
-// Right now this'll convert raw video into H.264 and raw audio into AAC.
-struct Converter : public AHandler {
-    enum {
-        kWhatAccessUnit,
-        kWhatEOS,
-        kWhatError,
-        kWhatShutdownCompleted,
-    };
-
-    enum FlagBits {
-        FLAG_USE_SURFACE_INPUT          = 1,
-        FLAG_PREPEND_CSD_IF_NECESSARY   = 2,
-    };
-    Converter(const sp<AMessage> &notify,
-              const sp<ALooper> &codecLooper,
-              const sp<AMessage> &outputFormat,
-              uint32_t flags = 0);
-
-    status_t init();
-
-    sp<IGraphicBufferProducer> getGraphicBufferProducer();
-
-    size_t getInputBufferCount() const;
-
-    sp<AMessage> getOutputFormat() const;
-    bool needToManuallyPrependSPSPPS() const;
-
-    void feedAccessUnit(const sp<ABuffer> &accessUnit);
-    void signalEOS();
-
-    void requestIDRFrame();
-
-    void dropAFrame();
-    void suspendEncoding(bool suspend);
-
-    void shutdownAsync();
-
-    int32_t getVideoBitrate() const;
-    void setVideoBitrate(int32_t bitrate);
-
-    static int32_t GetInt32Property(const char *propName, int32_t defaultValue);
-
-    enum {
-        // MUST not conflict with private enums below.
-        kWhatMediaPullerNotify = 'pulN',
-    };
-
-protected:
-    virtual ~Converter();
-    virtual void onMessageReceived(const sp<AMessage> &msg);
-
-private:
-    enum {
-        kWhatDoMoreWork,
-        kWhatRequestIDRFrame,
-        kWhatSuspendEncoding,
-        kWhatShutdown,
-        kWhatEncoderActivity,
-        kWhatDropAFrame,
-        kWhatReleaseOutputBuffer,
-    };
-
-    sp<AMessage> mNotify;
-    sp<ALooper> mCodecLooper;
-    sp<AMessage> mOutputFormat;
-    uint32_t mFlags;
-    bool mIsVideo;
-    bool mIsH264;
-    bool mIsPCMAudio;
-    bool mNeedToManuallyPrependSPSPPS;
-
-    sp<MediaCodec> mEncoder;
-    sp<AMessage> mEncoderActivityNotify;
-
-    sp<IGraphicBufferProducer> mGraphicBufferProducer;
-
-    Vector<sp<MediaCodecBuffer> > mEncoderInputBuffers;
-    Vector<sp<MediaCodecBuffer> > mEncoderOutputBuffers;
-
-    List<size_t> mAvailEncoderInputIndices;
-
-    List<sp<ABuffer> > mInputBufferQueue;
-
-    sp<ABuffer> mCSD0;
-
-    bool mDoMoreWorkPending;
-
-#if ENABLE_SILENCE_DETECTION
-    int64_t mFirstSilentFrameUs;
-    bool mInSilentMode;
-#endif
-
-    sp<ABuffer> mPartialAudioAU;
-
-    int32_t mPrevVideoBitrate;
-
-    int32_t mNumFramesToDrop;
-    bool mEncodingSuspended;
-
-    status_t initEncoder();
-    void releaseEncoder();
-
-    status_t feedEncoderInputBuffers();
-
-    void scheduleDoMoreWork();
-    status_t doMoreWork();
-
-    void notifyError(status_t err);
-
-    // Packetizes raw PCM audio data available in mInputBufferQueue
-    // into a format suitable for transport stream inclusion and
-    // notifies the observer.
-    status_t feedRawAudioInputBuffers();
-
-    static bool IsSilence(const sp<ABuffer> &accessUnit);
-
-    sp<ABuffer> prependCSD(const sp<ABuffer> &accessUnit) const;
-
-    DISALLOW_EVIL_CONSTRUCTORS(Converter);
-};
-
-}  // namespace android
-
-#endif  // CONVERTER_H_
diff --git a/media/libstagefright/wifi-display/source/MediaPuller.cpp b/media/libstagefright/wifi-display/source/MediaPuller.cpp
deleted file mode 100644
index ce07a4e..0000000
--- a/media/libstagefright/wifi-display/source/MediaPuller.cpp
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright 2012, 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 "MediaPuller"
-#include <utils/Log.h>
-
-#include "MediaPuller.h"
-
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-
-namespace android {
-
-MediaPuller::MediaPuller(
-        const sp<MediaSource> &source, const sp<AMessage> &notify)
-    : mSource(source),
-      mNotify(notify),
-      mPullGeneration(0),
-      mIsAudio(false),
-      mPaused(false) {
-    sp<MetaData> meta = source->getFormat();
-    const char *mime;
-    CHECK(meta->findCString(kKeyMIMEType, &mime));
-
-    mIsAudio = !strncasecmp(mime, "audio/", 6);
-}
-
-MediaPuller::~MediaPuller() {
-}
-
-status_t MediaPuller::postSynchronouslyAndReturnError(
-        const sp<AMessage> &msg) {
-    sp<AMessage> response;
-    status_t err = msg->postAndAwaitResponse(&response);
-
-    if (err != OK) {
-        return err;
-    }
-
-    if (!response->findInt32("err", &err)) {
-        err = OK;
-    }
-
-    return err;
-}
-
-status_t MediaPuller::start() {
-    return postSynchronouslyAndReturnError(new AMessage(kWhatStart, this));
-}
-
-void MediaPuller::stopAsync(const sp<AMessage> &notify) {
-    sp<AMessage> msg = new AMessage(kWhatStop, this);
-    msg->setMessage("notify", notify);
-    msg->post();
-}
-
-void MediaPuller::pause() {
-    (new AMessage(kWhatPause, this))->post();
-}
-
-void MediaPuller::resume() {
-    (new AMessage(kWhatResume, this))->post();
-}
-
-void MediaPuller::onMessageReceived(const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatStart:
-        {
-            status_t err;
-            if (mIsAudio) {
-                // This atrocity causes AudioSource to deliver absolute
-                // systemTime() based timestamps (off by 1 us).
-                sp<MetaData> params = new MetaData;
-                params->setInt64(kKeyTime, 1ll);
-                err = mSource->start(params.get());
-            } else {
-                err = mSource->start();
-                if (err != OK) {
-                    ALOGE("source failed to start w/ err %d", err);
-                }
-            }
-
-            if (err == OK) {
-                schedulePull();
-            }
-
-            sp<AMessage> response = new AMessage;
-            response->setInt32("err", err);
-
-            sp<AReplyToken> replyID;
-            CHECK(msg->senderAwaitsResponse(&replyID));
-            response->postReply(replyID);
-            break;
-        }
-
-        case kWhatStop:
-        {
-            sp<MetaData> meta = mSource->getFormat();
-            const char *tmp;
-            CHECK(meta->findCString(kKeyMIMEType, &tmp));
-            AString mime = tmp;
-
-            ALOGI("MediaPuller(%s) stopping.", mime.c_str());
-            mSource->stop();
-            ALOGI("MediaPuller(%s) stopped.", mime.c_str());
-            ++mPullGeneration;
-
-            sp<AMessage> notify;
-            CHECK(msg->findMessage("notify", &notify));
-            notify->post();
-            break;
-        }
-
-        case kWhatPull:
-        {
-            int32_t generation;
-            CHECK(msg->findInt32("generation", &generation));
-
-            if (generation != mPullGeneration) {
-                break;
-            }
-
-            MediaBuffer *mbuf;
-            status_t err = mSource->read(&mbuf);
-
-            if (mPaused) {
-                if (err == OK) {
-                    mbuf->release();
-                    mbuf = NULL;
-                }
-
-                schedulePull();
-                break;
-            }
-
-            if (err != OK) {
-                if (err == ERROR_END_OF_STREAM) {
-                    ALOGI("stream ended.");
-                } else {
-                    ALOGE("error %d reading stream.", err);
-                }
-
-                sp<AMessage> notify = mNotify->dup();
-                notify->setInt32("what", kWhatEOS);
-                notify->post();
-            } else {
-                int64_t timeUs;
-                CHECK(mbuf->meta_data()->findInt64(kKeyTime, &timeUs));
-
-                sp<ABuffer> accessUnit = new ABuffer(mbuf->range_length());
-
-                memcpy(accessUnit->data(),
-                       (const uint8_t *)mbuf->data() + mbuf->range_offset(),
-                       mbuf->range_length());
-
-                accessUnit->meta()->setInt64("timeUs", timeUs);
-
-                if (mIsAudio) {
-                    mbuf->release();
-                    mbuf = NULL;
-                } else {
-                    // video encoder will release MediaBuffer when done
-                    // with underlying data.
-                    accessUnit->setMediaBufferBase(mbuf);
-                }
-
-                sp<AMessage> notify = mNotify->dup();
-
-                notify->setInt32("what", kWhatAccessUnit);
-                notify->setBuffer("accessUnit", accessUnit);
-                notify->post();
-
-                if (mbuf != NULL) {
-                    ALOGV("posted mbuf %p", mbuf);
-                }
-
-                schedulePull();
-            }
-            break;
-        }
-
-        case kWhatPause:
-        {
-            mPaused = true;
-            break;
-        }
-
-        case kWhatResume:
-        {
-            mPaused = false;
-            break;
-        }
-
-        default:
-            TRESPASS();
-    }
-}
-
-void MediaPuller::schedulePull() {
-    sp<AMessage> msg = new AMessage(kWhatPull, this);
-    msg->setInt32("generation", mPullGeneration);
-    msg->post();
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/wifi-display/source/MediaPuller.h b/media/libstagefright/wifi-display/source/MediaPuller.h
deleted file mode 100644
index 1291bb3..0000000
--- a/media/libstagefright/wifi-display/source/MediaPuller.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2012, 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_PULLER_H_
-
-#define MEDIA_PULLER_H_
-
-#include <media/stagefright/foundation/AHandler.h>
-
-namespace android {
-
-struct MediaSource;
-
-struct MediaPuller : public AHandler {
-    enum {
-        kWhatEOS,
-        kWhatAccessUnit
-    };
-
-    MediaPuller(const sp<MediaSource> &source, const sp<AMessage> &notify);
-
-    status_t start();
-    void stopAsync(const sp<AMessage> &notify);
-
-    void pause();
-    void resume();
-
-protected:
-    virtual void onMessageReceived(const sp<AMessage> &msg);
-    virtual ~MediaPuller();
-
-private:
-    enum {
-        kWhatStart,
-        kWhatStop,
-        kWhatPull,
-        kWhatPause,
-        kWhatResume,
-    };
-
-    sp<MediaSource> mSource;
-    sp<AMessage> mNotify;
-    int32_t mPullGeneration;
-    bool mIsAudio;
-    bool mPaused;
-
-    status_t postSynchronouslyAndReturnError(const sp<AMessage> &msg);
-    void schedulePull();
-
-    DISALLOW_EVIL_CONSTRUCTORS(MediaPuller);
-};
-
-}  // namespace android
-
-#endif  // MEDIA_PULLER_H_
diff --git a/media/libstagefright/wifi-display/source/PlaybackSession.cpp b/media/libstagefright/wifi-display/source/PlaybackSession.cpp
deleted file mode 100644
index f1ecca0..0000000
--- a/media/libstagefright/wifi-display/source/PlaybackSession.cpp
+++ /dev/null
@@ -1,1112 +0,0 @@
-/*
- * Copyright 2012, 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 "PlaybackSession"
-#include <utils/Log.h>
-
-#include "PlaybackSession.h"
-
-#include "Converter.h"
-#include "MediaPuller.h"
-#include "RepeaterSource.h"
-#include "include/avc_utils.h"
-#include "WifiDisplaySource.h"
-
-#include <binder/IServiceManager.h>
-#include <cutils/properties.h>
-#include <media/IHDCP.h>
-#include <media/IMediaHTTPService.h>
-#include <media/stagefright/foundation/ABitReader.h>
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/foundation/hexdump.h>
-#include <media/stagefright/AudioSource.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-#include <media/stagefright/NuMediaExtractor.h>
-#include <media/stagefright/SurfaceMediaSource.h>
-#include <media/stagefright/Utils.h>
-
-#include <OMX_IVCommon.h>
-
-namespace android {
-
-struct WifiDisplaySource::PlaybackSession::Track : public AHandler {
-    enum {
-        kWhatStopped,
-    };
-
-    Track(const sp<AMessage> &notify,
-          const sp<ALooper> &pullLooper,
-          const sp<ALooper> &codecLooper,
-          const sp<MediaPuller> &mediaPuller,
-          const sp<Converter> &converter);
-
-    Track(const sp<AMessage> &notify, const sp<AMessage> &format);
-
-    void setRepeaterSource(const sp<RepeaterSource> &source);
-
-    sp<AMessage> getFormat();
-    bool isAudio() const;
-
-    const sp<Converter> &converter() const;
-    const sp<RepeaterSource> &repeaterSource() const;
-
-    ssize_t mediaSenderTrackIndex() const;
-    void setMediaSenderTrackIndex(size_t index);
-
-    status_t start();
-    void stopAsync();
-
-    void pause();
-    void resume();
-
-    void queueAccessUnit(const sp<ABuffer> &accessUnit);
-    sp<ABuffer> dequeueAccessUnit();
-
-    bool hasOutputBuffer(int64_t *timeUs) const;
-    void queueOutputBuffer(const sp<ABuffer> &accessUnit);
-    sp<ABuffer> dequeueOutputBuffer();
-
-#if SUSPEND_VIDEO_IF_IDLE
-    bool isSuspended() const;
-#endif
-
-    size_t countQueuedOutputBuffers() const {
-        return mQueuedOutputBuffers.size();
-    }
-
-    void requestIDRFrame();
-
-protected:
-    virtual void onMessageReceived(const sp<AMessage> &msg);
-    virtual ~Track();
-
-private:
-    enum {
-        kWhatMediaPullerStopped,
-    };
-
-    sp<AMessage> mNotify;
-    sp<ALooper> mPullLooper;
-    sp<ALooper> mCodecLooper;
-    sp<MediaPuller> mMediaPuller;
-    sp<Converter> mConverter;
-    sp<AMessage> mFormat;
-    bool mStarted;
-    ssize_t mMediaSenderTrackIndex;
-    bool mIsAudio;
-    List<sp<ABuffer> > mQueuedAccessUnits;
-    sp<RepeaterSource> mRepeaterSource;
-    List<sp<ABuffer> > mQueuedOutputBuffers;
-    int64_t mLastOutputBufferQueuedTimeUs;
-
-    static bool IsAudioFormat(const sp<AMessage> &format);
-
-    DISALLOW_EVIL_CONSTRUCTORS(Track);
-};
-
-WifiDisplaySource::PlaybackSession::Track::Track(
-        const sp<AMessage> &notify,
-        const sp<ALooper> &pullLooper,
-        const sp<ALooper> &codecLooper,
-        const sp<MediaPuller> &mediaPuller,
-        const sp<Converter> &converter)
-    : mNotify(notify),
-      mPullLooper(pullLooper),
-      mCodecLooper(codecLooper),
-      mMediaPuller(mediaPuller),
-      mConverter(converter),
-      mStarted(false),
-      mIsAudio(IsAudioFormat(mConverter->getOutputFormat())),
-      mLastOutputBufferQueuedTimeUs(-1ll) {
-}
-
-WifiDisplaySource::PlaybackSession::Track::Track(
-        const sp<AMessage> &notify, const sp<AMessage> &format)
-    : mNotify(notify),
-      mFormat(format),
-      mStarted(false),
-      mIsAudio(IsAudioFormat(format)),
-      mLastOutputBufferQueuedTimeUs(-1ll) {
-}
-
-WifiDisplaySource::PlaybackSession::Track::~Track() {
-    CHECK(!mStarted);
-}
-
-// static
-bool WifiDisplaySource::PlaybackSession::Track::IsAudioFormat(
-        const sp<AMessage> &format) {
-    AString mime;
-    CHECK(format->findString("mime", &mime));
-
-    return !strncasecmp(mime.c_str(), "audio/", 6);
-}
-
-sp<AMessage> WifiDisplaySource::PlaybackSession::Track::getFormat() {
-    return mFormat != NULL ? mFormat : mConverter->getOutputFormat();
-}
-
-bool WifiDisplaySource::PlaybackSession::Track::isAudio() const {
-    return mIsAudio;
-}
-
-const sp<Converter> &WifiDisplaySource::PlaybackSession::Track::converter() const {
-    return mConverter;
-}
-
-const sp<RepeaterSource> &
-WifiDisplaySource::PlaybackSession::Track::repeaterSource() const {
-    return mRepeaterSource;
-}
-
-ssize_t WifiDisplaySource::PlaybackSession::Track::mediaSenderTrackIndex() const {
-    CHECK_GE(mMediaSenderTrackIndex, 0);
-    return mMediaSenderTrackIndex;
-}
-
-void WifiDisplaySource::PlaybackSession::Track::setMediaSenderTrackIndex(
-        size_t index) {
-    mMediaSenderTrackIndex = index;
-}
-
-status_t WifiDisplaySource::PlaybackSession::Track::start() {
-    ALOGV("Track::start isAudio=%d", mIsAudio);
-
-    CHECK(!mStarted);
-
-    status_t err = OK;
-
-    if (mMediaPuller != NULL) {
-        err = mMediaPuller->start();
-    }
-
-    if (err == OK) {
-        mStarted = true;
-    }
-
-    return err;
-}
-
-void WifiDisplaySource::PlaybackSession::Track::stopAsync() {
-    ALOGV("Track::stopAsync isAudio=%d", mIsAudio);
-
-    if (mConverter != NULL) {
-        mConverter->shutdownAsync();
-    }
-
-    sp<AMessage> msg = new AMessage(kWhatMediaPullerStopped, this);
-
-    if (mStarted && mMediaPuller != NULL) {
-        if (mRepeaterSource != NULL) {
-            // Let's unblock MediaPuller's MediaSource::read().
-            mRepeaterSource->wakeUp();
-        }
-
-        mMediaPuller->stopAsync(msg);
-    } else {
-        mStarted = false;
-        msg->post();
-    }
-}
-
-void WifiDisplaySource::PlaybackSession::Track::pause() {
-    mMediaPuller->pause();
-}
-
-void WifiDisplaySource::PlaybackSession::Track::resume() {
-    mMediaPuller->resume();
-}
-
-void WifiDisplaySource::PlaybackSession::Track::onMessageReceived(
-        const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatMediaPullerStopped:
-        {
-            mConverter.clear();
-
-            mStarted = false;
-
-            sp<AMessage> notify = mNotify->dup();
-            notify->setInt32("what", kWhatStopped);
-            notify->post();
-
-            ALOGI("kWhatStopped %s posted", mIsAudio ? "audio" : "video");
-            break;
-        }
-
-        default:
-            TRESPASS();
-    }
-}
-
-void WifiDisplaySource::PlaybackSession::Track::queueAccessUnit(
-        const sp<ABuffer> &accessUnit) {
-    mQueuedAccessUnits.push_back(accessUnit);
-}
-
-sp<ABuffer> WifiDisplaySource::PlaybackSession::Track::dequeueAccessUnit() {
-    if (mQueuedAccessUnits.empty()) {
-        return NULL;
-    }
-
-    sp<ABuffer> accessUnit = *mQueuedAccessUnits.begin();
-    CHECK(accessUnit != NULL);
-
-    mQueuedAccessUnits.erase(mQueuedAccessUnits.begin());
-
-    return accessUnit;
-}
-
-void WifiDisplaySource::PlaybackSession::Track::setRepeaterSource(
-        const sp<RepeaterSource> &source) {
-    mRepeaterSource = source;
-}
-
-void WifiDisplaySource::PlaybackSession::Track::requestIDRFrame() {
-    if (mIsAudio) {
-        return;
-    }
-
-    if (mRepeaterSource != NULL) {
-        mRepeaterSource->wakeUp();
-    }
-
-    mConverter->requestIDRFrame();
-}
-
-bool WifiDisplaySource::PlaybackSession::Track::hasOutputBuffer(
-        int64_t *timeUs) const {
-    *timeUs = 0ll;
-
-    if (mQueuedOutputBuffers.empty()) {
-        return false;
-    }
-
-    const sp<ABuffer> &outputBuffer = *mQueuedOutputBuffers.begin();
-
-    CHECK(outputBuffer->meta()->findInt64("timeUs", timeUs));
-
-    return true;
-}
-
-void WifiDisplaySource::PlaybackSession::Track::queueOutputBuffer(
-        const sp<ABuffer> &accessUnit) {
-    mQueuedOutputBuffers.push_back(accessUnit);
-    mLastOutputBufferQueuedTimeUs = ALooper::GetNowUs();
-}
-
-sp<ABuffer> WifiDisplaySource::PlaybackSession::Track::dequeueOutputBuffer() {
-    CHECK(!mQueuedOutputBuffers.empty());
-
-    sp<ABuffer> outputBuffer = *mQueuedOutputBuffers.begin();
-    mQueuedOutputBuffers.erase(mQueuedOutputBuffers.begin());
-
-    return outputBuffer;
-}
-
-#if SUSPEND_VIDEO_IF_IDLE
-bool WifiDisplaySource::PlaybackSession::Track::isSuspended() const {
-    if (!mQueuedOutputBuffers.empty()) {
-        return false;
-    }
-
-    if (mLastOutputBufferQueuedTimeUs < 0ll) {
-        // We've never seen an output buffer queued, but tracks start
-        // out live, not suspended.
-        return false;
-    }
-
-    // If we've not seen new output data for 60ms or more, we consider
-    // this track suspended for the time being.
-    return (ALooper::GetNowUs() - mLastOutputBufferQueuedTimeUs) > 60000ll;
-}
-#endif
-
-////////////////////////////////////////////////////////////////////////////////
-
-WifiDisplaySource::PlaybackSession::PlaybackSession(
-        const String16 &opPackageName,
-        const sp<ANetworkSession> &netSession,
-        const sp<AMessage> &notify,
-        const in_addr &interfaceAddr,
-        const sp<IHDCP> &hdcp,
-        const char *path)
-    : mOpPackageName(opPackageName),
-      mNetSession(netSession),
-      mNotify(notify),
-      mInterfaceAddr(interfaceAddr),
-      mHDCP(hdcp),
-      mLocalRTPPort(-1),
-      mWeAreDead(false),
-      mPaused(false),
-      mLastLifesignUs(),
-      mVideoTrackIndex(-1),
-      mPrevTimeUs(-1ll),
-      mPullExtractorPending(false),
-      mPullExtractorGeneration(0),
-      mFirstSampleTimeRealUs(-1ll),
-      mFirstSampleTimeUs(-1ll) {
-    if (path != NULL) {
-        mMediaPath.setTo(path);
-    }
-}
-
-status_t WifiDisplaySource::PlaybackSession::init(
-        const char *clientIP,
-        int32_t clientRtp,
-        RTPSender::TransportMode rtpMode,
-        int32_t clientRtcp,
-        RTPSender::TransportMode rtcpMode,
-        bool enableAudio,
-        bool usePCMAudio,
-        bool enableVideo,
-        VideoFormats::ResolutionType videoResolutionType,
-        size_t videoResolutionIndex,
-        VideoFormats::ProfileType videoProfileType,
-        VideoFormats::LevelType videoLevelType) {
-    sp<AMessage> notify = new AMessage(kWhatMediaSenderNotify, this);
-    mMediaSender = new MediaSender(mNetSession, notify);
-    looper()->registerHandler(mMediaSender);
-
-    mMediaSender->setHDCP(mHDCP);
-
-    status_t err = setupPacketizer(
-            enableAudio,
-            usePCMAudio,
-            enableVideo,
-            videoResolutionType,
-            videoResolutionIndex,
-            videoProfileType,
-            videoLevelType);
-
-    if (err == OK) {
-        err = mMediaSender->initAsync(
-                -1 /* trackIndex */,
-                clientIP,
-                clientRtp,
-                rtpMode,
-                clientRtcp,
-                rtcpMode,
-                &mLocalRTPPort);
-    }
-
-    if (err != OK) {
-        mLocalRTPPort = -1;
-
-        looper()->unregisterHandler(mMediaSender->id());
-        mMediaSender.clear();
-
-        return err;
-    }
-
-    updateLiveness();
-
-    return OK;
-}
-
-WifiDisplaySource::PlaybackSession::~PlaybackSession() {
-}
-
-int32_t WifiDisplaySource::PlaybackSession::getRTPPort() const {
-    return mLocalRTPPort;
-}
-
-int64_t WifiDisplaySource::PlaybackSession::getLastLifesignUs() const {
-    return mLastLifesignUs;
-}
-
-void WifiDisplaySource::PlaybackSession::updateLiveness() {
-    mLastLifesignUs = ALooper::GetNowUs();
-}
-
-status_t WifiDisplaySource::PlaybackSession::play() {
-    updateLiveness();
-
-    (new AMessage(kWhatResume, this))->post();
-
-    return OK;
-}
-
-status_t WifiDisplaySource::PlaybackSession::onMediaSenderInitialized() {
-    for (size_t i = 0; i < mTracks.size(); ++i) {
-        CHECK_EQ((status_t)OK, mTracks.editValueAt(i)->start());
-    }
-
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("what", kWhatSessionEstablished);
-    notify->post();
-
-    return OK;
-}
-
-status_t WifiDisplaySource::PlaybackSession::pause() {
-    updateLiveness();
-
-    (new AMessage(kWhatPause, this))->post();
-
-    return OK;
-}
-
-void WifiDisplaySource::PlaybackSession::destroyAsync() {
-    ALOGI("destroyAsync");
-
-    for (size_t i = 0; i < mTracks.size(); ++i) {
-        mTracks.valueAt(i)->stopAsync();
-    }
-}
-
-void WifiDisplaySource::PlaybackSession::onMessageReceived(
-        const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatConverterNotify:
-        {
-            if (mWeAreDead) {
-                ALOGV("dropping msg '%s' because we're dead",
-                      msg->debugString().c_str());
-
-                break;
-            }
-
-            int32_t what;
-            CHECK(msg->findInt32("what", &what));
-
-            size_t trackIndex;
-            CHECK(msg->findSize("trackIndex", &trackIndex));
-
-            if (what == Converter::kWhatAccessUnit) {
-                sp<ABuffer> accessUnit;
-                CHECK(msg->findBuffer("accessUnit", &accessUnit));
-
-                const sp<Track> &track = mTracks.valueFor(trackIndex);
-
-                status_t err = mMediaSender->queueAccessUnit(
-                        track->mediaSenderTrackIndex(),
-                        accessUnit);
-
-                if (err != OK) {
-                    notifySessionDead();
-                }
-                break;
-            } else if (what == Converter::kWhatEOS) {
-                CHECK_EQ(what, Converter::kWhatEOS);
-
-                ALOGI("output EOS on track %zu", trackIndex);
-
-                ssize_t index = mTracks.indexOfKey(trackIndex);
-                CHECK_GE(index, 0);
-
-                const sp<Converter> &converter =
-                    mTracks.valueAt(index)->converter();
-                looper()->unregisterHandler(converter->id());
-
-                mTracks.removeItemsAt(index);
-
-                if (mTracks.isEmpty()) {
-                    ALOGI("Reached EOS");
-                }
-            } else if (what != Converter::kWhatShutdownCompleted) {
-                CHECK_EQ(what, Converter::kWhatError);
-
-                status_t err;
-                CHECK(msg->findInt32("err", &err));
-
-                ALOGE("converter signaled error %d", err);
-
-                notifySessionDead();
-            }
-            break;
-        }
-
-        case kWhatMediaSenderNotify:
-        {
-            int32_t what;
-            CHECK(msg->findInt32("what", &what));
-
-            if (what == MediaSender::kWhatInitDone) {
-                status_t err;
-                CHECK(msg->findInt32("err", &err));
-
-                if (err == OK) {
-                    onMediaSenderInitialized();
-                } else {
-                    notifySessionDead();
-                }
-            } else if (what == MediaSender::kWhatError) {
-                notifySessionDead();
-            } else if (what == MediaSender::kWhatNetworkStall) {
-                size_t numBytesQueued;
-                CHECK(msg->findSize("numBytesQueued", &numBytesQueued));
-
-                if (mVideoTrackIndex >= 0) {
-                    const sp<Track> &videoTrack =
-                        mTracks.valueFor(mVideoTrackIndex);
-
-                    sp<Converter> converter = videoTrack->converter();
-                    if (converter != NULL) {
-                        converter->dropAFrame();
-                    }
-                }
-            } else if (what == MediaSender::kWhatInformSender) {
-                onSinkFeedback(msg);
-            } else {
-                TRESPASS();
-            }
-            break;
-        }
-
-        case kWhatTrackNotify:
-        {
-            int32_t what;
-            CHECK(msg->findInt32("what", &what));
-
-            size_t trackIndex;
-            CHECK(msg->findSize("trackIndex", &trackIndex));
-
-            if (what == Track::kWhatStopped) {
-                ALOGI("Track %zu stopped", trackIndex);
-
-                sp<Track> track = mTracks.valueFor(trackIndex);
-                looper()->unregisterHandler(track->id());
-                mTracks.removeItem(trackIndex);
-                track.clear();
-
-                if (!mTracks.isEmpty()) {
-                    ALOGI("not all tracks are stopped yet");
-                    break;
-                }
-
-                looper()->unregisterHandler(mMediaSender->id());
-                mMediaSender.clear();
-
-                sp<AMessage> notify = mNotify->dup();
-                notify->setInt32("what", kWhatSessionDestroyed);
-                notify->post();
-            }
-            break;
-        }
-
-        case kWhatPause:
-        {
-            if (mExtractor != NULL) {
-                ++mPullExtractorGeneration;
-                mFirstSampleTimeRealUs = -1ll;
-                mFirstSampleTimeUs = -1ll;
-            }
-
-            if (mPaused) {
-                break;
-            }
-
-            for (size_t i = 0; i < mTracks.size(); ++i) {
-                mTracks.editValueAt(i)->pause();
-            }
-
-            mPaused = true;
-            break;
-        }
-
-        case kWhatResume:
-        {
-            if (mExtractor != NULL) {
-                schedulePullExtractor();
-            }
-
-            if (!mPaused) {
-                break;
-            }
-
-            for (size_t i = 0; i < mTracks.size(); ++i) {
-                mTracks.editValueAt(i)->resume();
-            }
-
-            mPaused = false;
-            break;
-        }
-
-        case kWhatPullExtractorSample:
-        {
-            int32_t generation;
-            CHECK(msg->findInt32("generation", &generation));
-
-            if (generation != mPullExtractorGeneration) {
-                break;
-            }
-
-            mPullExtractorPending = false;
-
-            onPullExtractor();
-            break;
-        }
-
-        default:
-            TRESPASS();
-    }
-}
-
-void WifiDisplaySource::PlaybackSession::onSinkFeedback(const sp<AMessage> &msg) {
-    int64_t avgLatencyUs;
-    CHECK(msg->findInt64("avgLatencyUs", &avgLatencyUs));
-
-    int64_t maxLatencyUs;
-    CHECK(msg->findInt64("maxLatencyUs", &maxLatencyUs));
-
-    ALOGI("sink reports avg. latency of %lld ms (max %lld ms)",
-          avgLatencyUs / 1000ll,
-          maxLatencyUs / 1000ll);
-
-    if (mVideoTrackIndex >= 0) {
-        const sp<Track> &videoTrack = mTracks.valueFor(mVideoTrackIndex);
-        sp<Converter> converter = videoTrack->converter();
-
-        if (converter != NULL) {
-            int32_t videoBitrate =
-                Converter::GetInt32Property("media.wfd.video-bitrate", -1);
-
-            char val[PROPERTY_VALUE_MAX];
-            if (videoBitrate < 0
-                    && property_get("media.wfd.video-bitrate", val, NULL)
-                    && !strcasecmp("adaptive", val)) {
-                videoBitrate = converter->getVideoBitrate();
-
-                if (avgLatencyUs > 300000ll) {
-                    videoBitrate *= 0.6;
-                } else if (avgLatencyUs < 100000ll) {
-                    videoBitrate *= 1.1;
-                }
-            }
-
-            if (videoBitrate > 0) {
-                if (videoBitrate < 500000) {
-                    videoBitrate = 500000;
-                } else if (videoBitrate > 10000000) {
-                    videoBitrate = 10000000;
-                }
-
-                if (videoBitrate != converter->getVideoBitrate()) {
-                    ALOGI("setting video bitrate to %d bps", videoBitrate);
-
-                    converter->setVideoBitrate(videoBitrate);
-                }
-            }
-        }
-
-        sp<RepeaterSource> repeaterSource = videoTrack->repeaterSource();
-        if (repeaterSource != NULL) {
-            double rateHz =
-                Converter::GetInt32Property(
-                        "media.wfd.video-framerate", -1);
-
-            char val[PROPERTY_VALUE_MAX];
-            if (rateHz < 0.0
-                    && property_get("media.wfd.video-framerate", val, NULL)
-                    && !strcasecmp("adaptive", val)) {
-                 rateHz = repeaterSource->getFrameRate();
-
-                if (avgLatencyUs > 300000ll) {
-                    rateHz *= 0.9;
-                } else if (avgLatencyUs < 200000ll) {
-                    rateHz *= 1.1;
-                }
-            }
-
-            if (rateHz > 0) {
-                if (rateHz < 5.0) {
-                    rateHz = 5.0;
-                } else if (rateHz > 30.0) {
-                    rateHz = 30.0;
-                }
-
-                if (rateHz != repeaterSource->getFrameRate()) {
-                    ALOGI("setting frame rate to %.2f Hz", rateHz);
-
-                    repeaterSource->setFrameRate(rateHz);
-                }
-            }
-        }
-    }
-}
-
-status_t WifiDisplaySource::PlaybackSession::setupMediaPacketizer(
-        bool enableAudio, bool enableVideo) {
-    mExtractor = new NuMediaExtractor;
-
-    status_t err = mExtractor->setDataSource(
-            NULL /* httpService */, mMediaPath.c_str());
-
-    if (err != OK) {
-        return err;
-    }
-
-    size_t n = mExtractor->countTracks();
-    bool haveAudio = false;
-    bool haveVideo = false;
-    for (size_t i = 0; i < n; ++i) {
-        sp<AMessage> format;
-        err = mExtractor->getTrackFormat(i, &format);
-
-        if (err != OK) {
-            continue;
-        }
-
-        AString mime;
-        CHECK(format->findString("mime", &mime));
-
-        bool isAudio = !strncasecmp(mime.c_str(), "audio/", 6);
-        bool isVideo = !strncasecmp(mime.c_str(), "video/", 6);
-
-        if (isAudio && enableAudio && !haveAudio) {
-            haveAudio = true;
-        } else if (isVideo && enableVideo && !haveVideo) {
-            haveVideo = true;
-        } else {
-            continue;
-        }
-
-        err = mExtractor->selectTrack(i);
-
-        size_t trackIndex = mTracks.size();
-
-        sp<AMessage> notify = new AMessage(kWhatTrackNotify, this);
-        notify->setSize("trackIndex", trackIndex);
-
-        sp<Track> track = new Track(notify, format);
-        looper()->registerHandler(track);
-
-        mTracks.add(trackIndex, track);
-
-        mExtractorTrackToInternalTrack.add(i, trackIndex);
-
-        if (isVideo) {
-            mVideoTrackIndex = trackIndex;
-        }
-
-        uint32_t flags = MediaSender::FLAG_MANUALLY_PREPEND_SPS_PPS;
-
-        ssize_t mediaSenderTrackIndex =
-            mMediaSender->addTrack(format, flags);
-        CHECK_GE(mediaSenderTrackIndex, 0);
-
-        track->setMediaSenderTrackIndex(mediaSenderTrackIndex);
-
-        if ((haveAudio || !enableAudio) && (haveVideo || !enableVideo)) {
-            break;
-        }
-    }
-
-    return OK;
-}
-
-void WifiDisplaySource::PlaybackSession::schedulePullExtractor() {
-    if (mPullExtractorPending) {
-        return;
-    }
-
-    int64_t delayUs = 1000000; // default delay is 1 sec
-    int64_t sampleTimeUs;
-    status_t err = mExtractor->getSampleTime(&sampleTimeUs);
-
-    if (err == OK) {
-        int64_t nowUs = ALooper::GetNowUs();
-
-        if (mFirstSampleTimeRealUs < 0ll) {
-            mFirstSampleTimeRealUs = nowUs;
-            mFirstSampleTimeUs = sampleTimeUs;
-        }
-
-        int64_t whenUs = sampleTimeUs - mFirstSampleTimeUs + mFirstSampleTimeRealUs;
-        delayUs = whenUs - nowUs;
-    } else {
-        ALOGW("could not get sample time (%d)", err);
-    }
-
-    sp<AMessage> msg = new AMessage(kWhatPullExtractorSample, this);
-    msg->setInt32("generation", mPullExtractorGeneration);
-    msg->post(delayUs);
-
-    mPullExtractorPending = true;
-}
-
-void WifiDisplaySource::PlaybackSession::onPullExtractor() {
-    sp<ABuffer> accessUnit = new ABuffer(1024 * 1024);
-    status_t err = mExtractor->readSampleData(accessUnit);
-    if (err != OK) {
-        // EOS.
-        return;
-    }
-
-    int64_t timeUs;
-    CHECK_EQ((status_t)OK, mExtractor->getSampleTime(&timeUs));
-
-    accessUnit->meta()->setInt64(
-            "timeUs", mFirstSampleTimeRealUs + timeUs - mFirstSampleTimeUs);
-
-    size_t trackIndex;
-    CHECK_EQ((status_t)OK, mExtractor->getSampleTrackIndex(&trackIndex));
-
-    sp<AMessage> msg = new AMessage(kWhatConverterNotify, this);
-
-    msg->setSize(
-            "trackIndex", mExtractorTrackToInternalTrack.valueFor(trackIndex));
-
-    msg->setInt32("what", Converter::kWhatAccessUnit);
-    msg->setBuffer("accessUnit", accessUnit);
-    msg->post();
-
-    mExtractor->advance();
-
-    schedulePullExtractor();
-}
-
-status_t WifiDisplaySource::PlaybackSession::setupPacketizer(
-        bool enableAudio,
-        bool usePCMAudio,
-        bool enableVideo,
-        VideoFormats::ResolutionType videoResolutionType,
-        size_t videoResolutionIndex,
-        VideoFormats::ProfileType videoProfileType,
-        VideoFormats::LevelType videoLevelType) {
-    CHECK(enableAudio || enableVideo);
-
-    if (!mMediaPath.empty()) {
-        return setupMediaPacketizer(enableAudio, enableVideo);
-    }
-
-    if (enableVideo) {
-        status_t err = addVideoSource(
-                videoResolutionType, videoResolutionIndex, videoProfileType,
-                videoLevelType);
-
-        if (err != OK) {
-            return err;
-        }
-    }
-
-    if (!enableAudio) {
-        return OK;
-    }
-
-    return addAudioSource(usePCMAudio);
-}
-
-status_t WifiDisplaySource::PlaybackSession::addSource(
-        bool isVideo, const sp<MediaSource> &source, bool isRepeaterSource,
-        bool usePCMAudio, unsigned profileIdc, unsigned levelIdc,
-        unsigned constraintSet, size_t *numInputBuffers) {
-    CHECK(!usePCMAudio || !isVideo);
-    CHECK(!isRepeaterSource || isVideo);
-    CHECK(!profileIdc || isVideo);
-    CHECK(!levelIdc || isVideo);
-    CHECK(!constraintSet || isVideo);
-
-    sp<ALooper> pullLooper = new ALooper;
-    pullLooper->setName("pull_looper");
-
-    pullLooper->start(
-            false /* runOnCallingThread */,
-            false /* canCallJava */,
-            PRIORITY_AUDIO);
-
-    sp<ALooper> codecLooper = new ALooper;
-    codecLooper->setName("codec_looper");
-
-    codecLooper->start(
-            false /* runOnCallingThread */,
-            false /* canCallJava */,
-            PRIORITY_AUDIO);
-
-    size_t trackIndex;
-
-    sp<AMessage> notify;
-
-    trackIndex = mTracks.size();
-
-    sp<AMessage> format;
-    status_t err = convertMetaDataToMessage(source->getFormat(), &format);
-    CHECK_EQ(err, (status_t)OK);
-
-    if (isVideo) {
-        format->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
-        format->setInt32(
-                "android._input-metadata-buffer-type", kMetadataBufferTypeANWBuffer);
-        format->setInt32("android._store-metadata-in-buffers-output", (mHDCP != NULL)
-                && (mHDCP->getCaps() & HDCPModule::HDCP_CAPS_ENCRYPT_NATIVE));
-        format->setInt32(
-                "color-format", OMX_COLOR_FormatAndroidOpaque);
-        format->setInt32("profile-idc", profileIdc);
-        format->setInt32("level-idc", levelIdc);
-        format->setInt32("constraint-set", constraintSet);
-    } else {
-        if (usePCMAudio) {
-            format->setInt32("pcm-encoding", kAudioEncodingPcm16bit);
-            format->setString("mime", MEDIA_MIMETYPE_AUDIO_RAW);
-        } else {
-            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
-        }
-    }
-
-    notify = new AMessage(kWhatConverterNotify, this);
-    notify->setSize("trackIndex", trackIndex);
-
-    sp<Converter> converter = new Converter(notify, codecLooper, format);
-
-    looper()->registerHandler(converter);
-
-    err = converter->init();
-    if (err != OK) {
-        ALOGE("%s converter returned err %d", isVideo ? "video" : "audio", err);
-
-        looper()->unregisterHandler(converter->id());
-        return err;
-    }
-
-    notify = new AMessage(Converter::kWhatMediaPullerNotify, converter);
-    notify->setSize("trackIndex", trackIndex);
-
-    sp<MediaPuller> puller = new MediaPuller(source, notify);
-    pullLooper->registerHandler(puller);
-
-    if (numInputBuffers != NULL) {
-        *numInputBuffers = converter->getInputBufferCount();
-    }
-
-    notify = new AMessage(kWhatTrackNotify, this);
-    notify->setSize("trackIndex", trackIndex);
-
-    sp<Track> track = new Track(
-            notify, pullLooper, codecLooper, puller, converter);
-
-    if (isRepeaterSource) {
-        track->setRepeaterSource(static_cast<RepeaterSource *>(source.get()));
-    }
-
-    looper()->registerHandler(track);
-
-    mTracks.add(trackIndex, track);
-
-    if (isVideo) {
-        mVideoTrackIndex = trackIndex;
-    }
-
-    uint32_t flags = 0;
-    if (converter->needToManuallyPrependSPSPPS()) {
-        flags |= MediaSender::FLAG_MANUALLY_PREPEND_SPS_PPS;
-    }
-
-    ssize_t mediaSenderTrackIndex =
-        mMediaSender->addTrack(converter->getOutputFormat(), flags);
-    CHECK_GE(mediaSenderTrackIndex, 0);
-
-    track->setMediaSenderTrackIndex(mediaSenderTrackIndex);
-
-    return OK;
-}
-
-status_t WifiDisplaySource::PlaybackSession::addVideoSource(
-        VideoFormats::ResolutionType videoResolutionType,
-        size_t videoResolutionIndex,
-        VideoFormats::ProfileType videoProfileType,
-        VideoFormats::LevelType videoLevelType) {
-    size_t width, height, framesPerSecond;
-    bool interlaced;
-    CHECK(VideoFormats::GetConfiguration(
-                videoResolutionType,
-                videoResolutionIndex,
-                &width,
-                &height,
-                &framesPerSecond,
-                &interlaced));
-
-    unsigned profileIdc, levelIdc, constraintSet;
-    CHECK(VideoFormats::GetProfileLevel(
-                videoProfileType,
-                videoLevelType,
-                &profileIdc,
-                &levelIdc,
-                &constraintSet));
-
-    sp<SurfaceMediaSource> source = new SurfaceMediaSource(width, height);
-
-    source->setUseAbsoluteTimestamps();
-
-    sp<RepeaterSource> videoSource =
-        new RepeaterSource(source, framesPerSecond);
-
-    size_t numInputBuffers;
-    status_t err = addSource(
-            true /* isVideo */, videoSource, true /* isRepeaterSource */,
-            false /* usePCMAudio */, profileIdc, levelIdc, constraintSet,
-            &numInputBuffers);
-
-    if (err != OK) {
-        return err;
-    }
-
-    err = source->setMaxAcquiredBufferCount(numInputBuffers);
-    CHECK_EQ(err, (status_t)OK);
-
-    mProducer = source->getProducer();
-
-    return OK;
-}
-
-status_t WifiDisplaySource::PlaybackSession::addAudioSource(bool usePCMAudio) {
-    sp<AudioSource> audioSource = new AudioSource(
-            AUDIO_SOURCE_REMOTE_SUBMIX,
-            mOpPackageName,
-            48000 /* sampleRate */,
-            2 /* channelCount */);
-
-    if (audioSource->initCheck() == OK) {
-        return addSource(
-                false /* isVideo */, audioSource, false /* isRepeaterSource */,
-                usePCMAudio, 0 /* profileIdc */, 0 /* levelIdc */,
-                0 /* constraintSet */, NULL /* numInputBuffers */);
-    }
-
-    ALOGW("Unable to instantiate audio source");
-
-    return OK;
-}
-
-sp<IGraphicBufferProducer> WifiDisplaySource::PlaybackSession::getSurfaceTexture() {
-    return mProducer;
-}
-
-void WifiDisplaySource::PlaybackSession::requestIDRFrame() {
-    for (size_t i = 0; i < mTracks.size(); ++i) {
-        const sp<Track> &track = mTracks.valueAt(i);
-
-        track->requestIDRFrame();
-    }
-}
-
-void WifiDisplaySource::PlaybackSession::notifySessionDead() {
-    // Inform WifiDisplaySource of our premature death (wish).
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("what", kWhatSessionDead);
-    notify->post();
-
-    mWeAreDead = true;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/wifi-display/source/PlaybackSession.h b/media/libstagefright/wifi-display/source/PlaybackSession.h
deleted file mode 100644
index f6673df..0000000
--- a/media/libstagefright/wifi-display/source/PlaybackSession.h
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright 2012, 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 PLAYBACK_SESSION_H_
-
-#define PLAYBACK_SESSION_H_
-
-#include "MediaSender.h"
-#include "VideoFormats.h"
-#include "WifiDisplaySource.h"
-
-#include <utils/String16.h>
-
-namespace android {
-
-struct ABuffer;
-struct IHDCP;
-class IGraphicBufferProducer;
-struct MediaPuller;
-struct MediaSource;
-struct MediaSender;
-struct NuMediaExtractor;
-
-// Encapsulates the state of an RTP/RTCP session in the context of wifi
-// display.
-struct WifiDisplaySource::PlaybackSession : public AHandler {
-    PlaybackSession(
-            const String16 &opPackageName,
-            const sp<ANetworkSession> &netSession,
-            const sp<AMessage> &notify,
-            const struct in_addr &interfaceAddr,
-            const sp<IHDCP> &hdcp,
-            const char *path = NULL);
-
-    status_t init(
-            const char *clientIP,
-            int32_t clientRtp,
-            RTPSender::TransportMode rtpMode,
-            int32_t clientRtcp,
-            RTPSender::TransportMode rtcpMode,
-            bool enableAudio,
-            bool usePCMAudio,
-            bool enableVideo,
-            VideoFormats::ResolutionType videoResolutionType,
-            size_t videoResolutionIndex,
-            VideoFormats::ProfileType videoProfileType,
-            VideoFormats::LevelType videoLevelType);
-
-    void destroyAsync();
-
-    int32_t getRTPPort() const;
-
-    int64_t getLastLifesignUs() const;
-    void updateLiveness();
-
-    status_t play();
-    status_t finishPlay();
-    status_t pause();
-
-    sp<IGraphicBufferProducer> getSurfaceTexture();
-
-    void requestIDRFrame();
-
-    enum {
-        kWhatSessionDead,
-        kWhatBinaryData,
-        kWhatSessionEstablished,
-        kWhatSessionDestroyed,
-    };
-
-protected:
-    virtual void onMessageReceived(const sp<AMessage> &msg);
-    virtual ~PlaybackSession();
-
-private:
-    struct Track;
-
-    enum {
-        kWhatMediaPullerNotify,
-        kWhatConverterNotify,
-        kWhatTrackNotify,
-        kWhatUpdateSurface,
-        kWhatPause,
-        kWhatResume,
-        kWhatMediaSenderNotify,
-        kWhatPullExtractorSample,
-    };
-
-    String16 mOpPackageName;
-
-    sp<ANetworkSession> mNetSession;
-    sp<AMessage> mNotify;
-    in_addr mInterfaceAddr;
-    sp<IHDCP> mHDCP;
-    AString mMediaPath;
-
-    sp<MediaSender> mMediaSender;
-    int32_t mLocalRTPPort;
-
-    bool mWeAreDead;
-    bool mPaused;
-
-    int64_t mLastLifesignUs;
-
-    sp<IGraphicBufferProducer> mProducer;
-
-    KeyedVector<size_t, sp<Track> > mTracks;
-    ssize_t mVideoTrackIndex;
-
-    int64_t mPrevTimeUs;
-
-    sp<NuMediaExtractor> mExtractor;
-    KeyedVector<size_t, size_t> mExtractorTrackToInternalTrack;
-    bool mPullExtractorPending;
-    int32_t mPullExtractorGeneration;
-    int64_t mFirstSampleTimeRealUs;
-    int64_t mFirstSampleTimeUs;
-
-    status_t setupMediaPacketizer(bool enableAudio, bool enableVideo);
-
-    status_t setupPacketizer(
-            bool enableAudio,
-            bool usePCMAudio,
-            bool enableVideo,
-            VideoFormats::ResolutionType videoResolutionType,
-            size_t videoResolutionIndex,
-            VideoFormats::ProfileType videoProfileType,
-            VideoFormats::LevelType videoLevelType);
-
-    status_t addSource(
-            bool isVideo,
-            const sp<MediaSource> &source,
-            bool isRepeaterSource,
-            bool usePCMAudio,
-            unsigned profileIdc,
-            unsigned levelIdc,
-            unsigned contraintSet,
-            size_t *numInputBuffers);
-
-    status_t addVideoSource(
-            VideoFormats::ResolutionType videoResolutionType,
-            size_t videoResolutionIndex,
-            VideoFormats::ProfileType videoProfileType,
-            VideoFormats::LevelType videoLevelType);
-
-    status_t addAudioSource(bool usePCMAudio);
-
-    status_t onMediaSenderInitialized();
-
-    void notifySessionDead();
-
-    void schedulePullExtractor();
-    void onPullExtractor();
-
-    void onSinkFeedback(const sp<AMessage> &msg);
-
-    DISALLOW_EVIL_CONSTRUCTORS(PlaybackSession);
-};
-
-}  // namespace android
-
-#endif  // PLAYBACK_SESSION_H_
-
diff --git a/media/libstagefright/wifi-display/source/RepeaterSource.cpp b/media/libstagefright/wifi-display/source/RepeaterSource.cpp
deleted file mode 100644
index af6b663..0000000
--- a/media/libstagefright/wifi-display/source/RepeaterSource.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-//#define LOG_NDEBUG 0
-#define LOG_TAG "RepeaterSource"
-#include <utils/Log.h>
-
-#include "RepeaterSource.h"
-
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/ALooper.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MetaData.h>
-
-namespace android {
-
-RepeaterSource::RepeaterSource(const sp<MediaSource> &source, double rateHz)
-    : mStarted(false),
-      mSource(source),
-      mRateHz(rateHz),
-      mBuffer(NULL),
-      mResult(OK),
-      mLastBufferUpdateUs(-1ll),
-      mStartTimeUs(-1ll),
-      mFrameCount(0) {
-}
-
-RepeaterSource::~RepeaterSource() {
-    CHECK(!mStarted);
-}
-
-double RepeaterSource::getFrameRate() const {
-    return mRateHz;
-}
-
-void RepeaterSource::setFrameRate(double rateHz) {
-    Mutex::Autolock autoLock(mLock);
-
-    if (rateHz == mRateHz) {
-        return;
-    }
-
-    if (mStartTimeUs >= 0ll) {
-        int64_t nextTimeUs = mStartTimeUs + (mFrameCount * 1000000ll) / mRateHz;
-        mStartTimeUs = nextTimeUs;
-        mFrameCount = 0;
-    }
-    mRateHz = rateHz;
-}
-
-status_t RepeaterSource::start(MetaData *params) {
-    CHECK(!mStarted);
-
-    status_t err = mSource->start(params);
-
-    if (err != OK) {
-        return err;
-    }
-
-    mBuffer = NULL;
-    mResult = OK;
-    mStartTimeUs = -1ll;
-    mFrameCount = 0;
-
-    mLooper = new ALooper;
-    mLooper->setName("repeater_looper");
-    mLooper->start();
-
-    mReflector = new AHandlerReflector<RepeaterSource>(this);
-    mLooper->registerHandler(mReflector);
-
-    postRead();
-
-    mStarted = true;
-
-    return OK;
-}
-
-status_t RepeaterSource::stop() {
-    CHECK(mStarted);
-
-    ALOGV("stopping");
-
-    status_t err = mSource->stop();
-
-    if (mLooper != NULL) {
-        mLooper->stop();
-        mLooper.clear();
-
-        mReflector.clear();
-    }
-
-    if (mBuffer != NULL) {
-        ALOGV("releasing mbuf %p", mBuffer);
-        mBuffer->release();
-        mBuffer = NULL;
-    }
-
-
-    ALOGV("stopped");
-
-    mStarted = false;
-
-    return err;
-}
-
-sp<MetaData> RepeaterSource::getFormat() {
-    return mSource->getFormat();
-}
-
-status_t RepeaterSource::read(
-        MediaBuffer **buffer, const ReadOptions *options) {
-    int64_t seekTimeUs;
-    ReadOptions::SeekMode seekMode;
-    CHECK(options == NULL || !options->getSeekTo(&seekTimeUs, &seekMode));
-
-    for (;;) {
-        int64_t bufferTimeUs = -1ll;
-
-        if (mStartTimeUs < 0ll) {
-            Mutex::Autolock autoLock(mLock);
-            while ((mLastBufferUpdateUs < 0ll || mBuffer == NULL)
-                    && mResult == OK) {
-                mCondition.wait(mLock);
-            }
-
-            ALOGV("now resuming.");
-            mStartTimeUs = ALooper::GetNowUs();
-            bufferTimeUs = mStartTimeUs;
-        } else {
-            bufferTimeUs = mStartTimeUs + (mFrameCount * 1000000ll) / mRateHz;
-
-            int64_t nowUs = ALooper::GetNowUs();
-            int64_t delayUs = bufferTimeUs - nowUs;
-
-            if (delayUs > 0ll) {
-                usleep(delayUs);
-            }
-        }
-
-        bool stale = false;
-
-        {
-            Mutex::Autolock autoLock(mLock);
-            if (mResult != OK) {
-                CHECK(mBuffer == NULL);
-                return mResult;
-            }
-
-#if SUSPEND_VIDEO_IF_IDLE
-            int64_t nowUs = ALooper::GetNowUs();
-            if (nowUs - mLastBufferUpdateUs > 1000000ll) {
-                mLastBufferUpdateUs = -1ll;
-                stale = true;
-            } else
-#endif
-            {
-                mBuffer->add_ref();
-                *buffer = mBuffer;
-                (*buffer)->meta_data()->setInt64(kKeyTime, bufferTimeUs);
-                ++mFrameCount;
-            }
-        }
-
-        if (!stale) {
-            break;
-        }
-
-        mStartTimeUs = -1ll;
-        mFrameCount = 0;
-        ALOGV("now dormant");
-    }
-
-    return OK;
-}
-
-void RepeaterSource::postRead() {
-    (new AMessage(kWhatRead, mReflector))->post();
-}
-
-void RepeaterSource::onMessageReceived(const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatRead:
-        {
-            MediaBuffer *buffer;
-            status_t err = mSource->read(&buffer);
-
-            ALOGV("read mbuf %p", buffer);
-
-            Mutex::Autolock autoLock(mLock);
-            if (mBuffer != NULL) {
-                mBuffer->release();
-                mBuffer = NULL;
-            }
-            mBuffer = buffer;
-            mResult = err;
-            mLastBufferUpdateUs = ALooper::GetNowUs();
-
-            mCondition.broadcast();
-
-            if (err == OK) {
-                postRead();
-            }
-            break;
-        }
-
-        default:
-            TRESPASS();
-    }
-}
-
-void RepeaterSource::wakeUp() {
-    ALOGV("wakeUp");
-    Mutex::Autolock autoLock(mLock);
-    if (mLastBufferUpdateUs < 0ll && mBuffer != NULL) {
-        mLastBufferUpdateUs = ALooper::GetNowUs();
-        mCondition.broadcast();
-    }
-}
-
-}  // namespace android
diff --git a/media/libstagefright/wifi-display/source/RepeaterSource.h b/media/libstagefright/wifi-display/source/RepeaterSource.h
deleted file mode 100644
index 8d414fd..0000000
--- a/media/libstagefright/wifi-display/source/RepeaterSource.h
+++ /dev/null
@@ -1,67 +0,0 @@
-#ifndef REPEATER_SOURCE_H_
-
-#define REPEATER_SOURCE_H_
-
-#include <media/stagefright/foundation/ABase.h>
-#include <media/stagefright/foundation/AHandlerReflector.h>
-#include <media/stagefright/MediaSource.h>
-
-#define SUSPEND_VIDEO_IF_IDLE   0
-
-namespace android {
-
-// This MediaSource delivers frames at a constant rate by repeating buffers
-// if necessary.
-struct RepeaterSource : public MediaSource {
-    RepeaterSource(const sp<MediaSource> &source, double rateHz);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-    void onMessageReceived(const sp<AMessage> &msg);
-
-    // If RepeaterSource is currently dormant, because SurfaceFlinger didn't
-    // send updates in a while, this is its wakeup call.
-    void wakeUp();
-
-    double getFrameRate() const;
-    void setFrameRate(double rateHz);
-
-protected:
-    virtual ~RepeaterSource();
-
-private:
-    enum {
-        kWhatRead,
-    };
-
-    Mutex mLock;
-    Condition mCondition;
-
-    bool mStarted;
-
-    sp<MediaSource> mSource;
-    double mRateHz;
-
-    sp<ALooper> mLooper;
-    sp<AHandlerReflector<RepeaterSource> > mReflector;
-
-    MediaBuffer *mBuffer;
-    status_t mResult;
-    int64_t mLastBufferUpdateUs;
-
-    int64_t mStartTimeUs;
-    int32_t mFrameCount;
-
-    void postRead();
-
-    DISALLOW_EVIL_CONSTRUCTORS(RepeaterSource);
-};
-
-}  // namespace android
-
-#endif // REPEATER_SOURCE_H_
diff --git a/media/libstagefright/wifi-display/source/TSPacketizer.cpp b/media/libstagefright/wifi-display/source/TSPacketizer.cpp
deleted file mode 100644
index 865ba94..0000000
--- a/media/libstagefright/wifi-display/source/TSPacketizer.cpp
+++ /dev/null
@@ -1,1055 +0,0 @@
-/*
- * Copyright 2012, 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 "TSPacketizer"
-#include <utils/Log.h>
-
-#include "TSPacketizer.h"
-#include "include/avc_utils.h"
-
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/foundation/hexdump.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaErrors.h>
-
-#include <arpa/inet.h>
-
-namespace android {
-
-struct TSPacketizer::Track : public RefBase {
-    Track(const sp<AMessage> &format,
-          unsigned PID, unsigned streamType, unsigned streamID);
-
-    unsigned PID() const;
-    unsigned streamType() const;
-    unsigned streamID() const;
-
-    // Returns the previous value.
-    unsigned incrementContinuityCounter();
-
-    bool isAudio() const;
-    bool isVideo() const;
-
-    bool isH264() const;
-    bool isAAC() const;
-    bool lacksADTSHeader() const;
-    bool isPCMAudio() const;
-
-    sp<ABuffer> prependCSD(const sp<ABuffer> &accessUnit) const;
-    sp<ABuffer> prependADTSHeader(const sp<ABuffer> &accessUnit) const;
-
-    size_t countDescriptors() const;
-    sp<ABuffer> descriptorAt(size_t index) const;
-
-    void finalize();
-    void extractCSDIfNecessary();
-
-protected:
-    virtual ~Track();
-
-private:
-    sp<AMessage> mFormat;
-
-    unsigned mPID;
-    unsigned mStreamType;
-    unsigned mStreamID;
-    unsigned mContinuityCounter;
-
-    AString mMIME;
-    Vector<sp<ABuffer> > mCSD;
-
-    Vector<sp<ABuffer> > mDescriptors;
-
-    bool mAudioLacksATDSHeaders;
-    bool mFinalized;
-    bool mExtractedCSD;
-
-    DISALLOW_EVIL_CONSTRUCTORS(Track);
-};
-
-TSPacketizer::Track::Track(
-        const sp<AMessage> &format,
-        unsigned PID, unsigned streamType, unsigned streamID)
-    : mFormat(format),
-      mPID(PID),
-      mStreamType(streamType),
-      mStreamID(streamID),
-      mContinuityCounter(0),
-      mAudioLacksATDSHeaders(false),
-      mFinalized(false),
-      mExtractedCSD(false) {
-    CHECK(format->findString("mime", &mMIME));
-}
-
-void TSPacketizer::Track::extractCSDIfNecessary() {
-    if (mExtractedCSD) {
-        return;
-    }
-
-    if (!strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)
-            || !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
-        for (size_t i = 0;; ++i) {
-            sp<ABuffer> csd;
-            if (!mFormat->findBuffer(AStringPrintf("csd-%d", i).c_str(), &csd)) {
-                break;
-            }
-
-            mCSD.push(csd);
-        }
-
-        if (!strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
-            int32_t isADTS;
-            if (!mFormat->findInt32("is-adts", &isADTS) || isADTS == 0) {
-                mAudioLacksATDSHeaders = true;
-            }
-        }
-    }
-
-    mExtractedCSD = true;
-}
-
-TSPacketizer::Track::~Track() {
-}
-
-unsigned TSPacketizer::Track::PID() const {
-    return mPID;
-}
-
-unsigned TSPacketizer::Track::streamType() const {
-    return mStreamType;
-}
-
-unsigned TSPacketizer::Track::streamID() const {
-    return mStreamID;
-}
-
-unsigned TSPacketizer::Track::incrementContinuityCounter() {
-    unsigned prevCounter = mContinuityCounter;
-
-    if (++mContinuityCounter == 16) {
-        mContinuityCounter = 0;
-    }
-
-    return prevCounter;
-}
-
-bool TSPacketizer::Track::isAudio() const {
-    return !strncasecmp("audio/", mMIME.c_str(), 6);
-}
-
-bool TSPacketizer::Track::isVideo() const {
-    return !strncasecmp("video/", mMIME.c_str(), 6);
-}
-
-bool TSPacketizer::Track::isH264() const {
-    return !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_VIDEO_AVC);
-}
-
-bool TSPacketizer::Track::isAAC() const {
-    return !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_AAC);
-}
-
-bool TSPacketizer::Track::isPCMAudio() const {
-    return !strcasecmp(mMIME.c_str(), MEDIA_MIMETYPE_AUDIO_RAW);
-}
-
-bool TSPacketizer::Track::lacksADTSHeader() const {
-    return mAudioLacksATDSHeaders;
-}
-
-sp<ABuffer> TSPacketizer::Track::prependCSD(
-        const sp<ABuffer> &accessUnit) const {
-    size_t size = 0;
-    for (size_t i = 0; i < mCSD.size(); ++i) {
-        size += mCSD.itemAt(i)->size();
-    }
-
-    sp<ABuffer> dup = new ABuffer(accessUnit->size() + size);
-    size_t offset = 0;
-    for (size_t i = 0; i < mCSD.size(); ++i) {
-        const sp<ABuffer> &csd = mCSD.itemAt(i);
-
-        memcpy(dup->data() + offset, csd->data(), csd->size());
-        offset += csd->size();
-    }
-
-    memcpy(dup->data() + offset, accessUnit->data(), accessUnit->size());
-
-    return dup;
-}
-
-sp<ABuffer> TSPacketizer::Track::prependADTSHeader(
-        const sp<ABuffer> &accessUnit) const {
-    CHECK_EQ(mCSD.size(), 1u);
-
-    const uint8_t *codec_specific_data = mCSD.itemAt(0)->data();
-
-    const uint32_t aac_frame_length = accessUnit->size() + 7;
-
-    sp<ABuffer> dup = new ABuffer(aac_frame_length);
-
-    unsigned profile = (codec_specific_data[0] >> 3) - 1;
-
-    unsigned sampling_freq_index =
-        ((codec_specific_data[0] & 7) << 1)
-        | (codec_specific_data[1] >> 7);
-
-    unsigned channel_configuration =
-        (codec_specific_data[1] >> 3) & 0x0f;
-
-    uint8_t *ptr = dup->data();
-
-    *ptr++ = 0xff;
-    *ptr++ = 0xf9;  // b11111001, ID=1(MPEG-2), layer=0, protection_absent=1
-
-    *ptr++ =
-        profile << 6
-        | sampling_freq_index << 2
-        | ((channel_configuration >> 2) & 1);  // private_bit=0
-
-    // original_copy=0, home=0, copyright_id_bit=0, copyright_id_start=0
-    *ptr++ =
-        (channel_configuration & 3) << 6
-        | aac_frame_length >> 11;
-    *ptr++ = (aac_frame_length >> 3) & 0xff;
-    *ptr++ = (aac_frame_length & 7) << 5;
-
-    // adts_buffer_fullness=0, number_of_raw_data_blocks_in_frame=0
-    *ptr++ = 0;
-
-    memcpy(ptr, accessUnit->data(), accessUnit->size());
-
-    return dup;
-}
-
-size_t TSPacketizer::Track::countDescriptors() const {
-    return mDescriptors.size();
-}
-
-sp<ABuffer> TSPacketizer::Track::descriptorAt(size_t index) const {
-    CHECK_LT(index, mDescriptors.size());
-    return mDescriptors.itemAt(index);
-}
-
-void TSPacketizer::Track::finalize() {
-    if (mFinalized) {
-        return;
-    }
-
-    if (isH264()) {
-        {
-            // AVC video descriptor (40)
-
-            sp<ABuffer> descriptor = new ABuffer(6);
-            uint8_t *data = descriptor->data();
-            data[0] = 40;  // descriptor_tag
-            data[1] = 4;  // descriptor_length
-
-            if (mCSD.size() > 0) {
-                CHECK_GE(mCSD.size(), 1u);
-                const sp<ABuffer> &sps = mCSD.itemAt(0);
-                CHECK(!memcmp("\x00\x00\x00\x01", sps->data(), 4));
-                CHECK_GE(sps->size(), 7u);
-                // profile_idc, constraint_set*, level_idc
-                memcpy(&data[2], sps->data() + 4, 3);
-            } else {
-                int32_t profileIdc, levelIdc, constraintSet;
-                CHECK(mFormat->findInt32("profile-idc", &profileIdc));
-                CHECK(mFormat->findInt32("level-idc", &levelIdc));
-                CHECK(mFormat->findInt32("constraint-set", &constraintSet));
-                CHECK_GE(profileIdc, 0);
-                CHECK_GE(levelIdc, 0);
-                data[2] = profileIdc;    // profile_idc
-                data[3] = constraintSet; // constraint_set*
-                data[4] = levelIdc;      // level_idc
-            }
-
-            // AVC_still_present=0, AVC_24_hour_picture_flag=0, reserved
-            data[5] = 0x3f;
-
-            mDescriptors.push_back(descriptor);
-        }
-
-        {
-            // AVC timing and HRD descriptor (42)
-
-            sp<ABuffer> descriptor = new ABuffer(4);
-            uint8_t *data = descriptor->data();
-            data[0] = 42;  // descriptor_tag
-            data[1] = 2;  // descriptor_length
-
-            // hrd_management_valid_flag = 0
-            // reserved = 111111b
-            // picture_and_timing_info_present = 0
-
-            data[2] = 0x7e;
-
-            // fixed_frame_rate_flag = 0
-            // temporal_poc_flag = 0
-            // picture_to_display_conversion_flag = 0
-            // reserved = 11111b
-            data[3] = 0x1f;
-
-            mDescriptors.push_back(descriptor);
-        }
-    } else if (isPCMAudio()) {
-        // LPCM audio stream descriptor (0x83)
-
-        int32_t channelCount;
-        CHECK(mFormat->findInt32("channel-count", &channelCount));
-        CHECK_EQ(channelCount, 2);
-
-        int32_t sampleRate;
-        CHECK(mFormat->findInt32("sample-rate", &sampleRate));
-        CHECK(sampleRate == 44100 || sampleRate == 48000);
-
-        sp<ABuffer> descriptor = new ABuffer(4);
-        uint8_t *data = descriptor->data();
-        data[0] = 0x83;  // descriptor_tag
-        data[1] = 2;  // descriptor_length
-
-        unsigned sampling_frequency = (sampleRate == 44100) ? 1 : 2;
-
-        data[2] = (sampling_frequency << 5)
-                    | (3 /* reserved */ << 1)
-                    | 0 /* emphasis_flag */;
-
-        data[3] =
-            (1 /* number_of_channels = stereo */ << 5)
-            | 0xf /* reserved */;
-
-        mDescriptors.push_back(descriptor);
-    }
-
-    mFinalized = true;
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-TSPacketizer::TSPacketizer(uint32_t flags)
-    : mFlags(flags),
-      mPATContinuityCounter(0),
-      mPMTContinuityCounter(0) {
-    initCrcTable();
-
-    if (flags & (EMIT_HDCP20_DESCRIPTOR | EMIT_HDCP21_DESCRIPTOR)) {
-        int32_t hdcpVersion;
-        if (flags & EMIT_HDCP20_DESCRIPTOR) {
-            CHECK(!(flags & EMIT_HDCP21_DESCRIPTOR));
-            hdcpVersion = 0x20;
-        } else {
-            CHECK(!(flags & EMIT_HDCP20_DESCRIPTOR));
-
-            // HDCP2.0 _and_ HDCP 2.1 specs say to set the version
-            // inside the HDCP descriptor to 0x20!!!
-            hdcpVersion = 0x20;
-        }
-
-        // HDCP descriptor
-        sp<ABuffer> descriptor = new ABuffer(7);
-        uint8_t *data = descriptor->data();
-        data[0] = 0x05;  // descriptor_tag
-        data[1] = 5;  // descriptor_length
-        data[2] = 'H';
-        data[3] = 'D';
-        data[4] = 'C';
-        data[5] = 'P';
-        data[6] = hdcpVersion;
-
-        mProgramInfoDescriptors.push_back(descriptor);
-    }
-}
-
-TSPacketizer::~TSPacketizer() {
-}
-
-ssize_t TSPacketizer::addTrack(const sp<AMessage> &format) {
-    AString mime;
-    CHECK(format->findString("mime", &mime));
-
-    unsigned PIDStart;
-    bool isVideo = !strncasecmp("video/", mime.c_str(), 6);
-    bool isAudio = !strncasecmp("audio/", mime.c_str(), 6);
-
-    if (isVideo) {
-        PIDStart = 0x1011;
-    } else if (isAudio) {
-        PIDStart = 0x1100;
-    } else {
-        return ERROR_UNSUPPORTED;
-    }
-
-    unsigned streamType;
-    unsigned streamIDStart;
-    unsigned streamIDStop;
-
-    if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)) {
-        streamType = 0x1b;
-        streamIDStart = 0xe0;
-        streamIDStop = 0xef;
-    } else if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
-        streamType = 0x0f;
-        streamIDStart = 0xc0;
-        streamIDStop = 0xdf;
-    } else if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_RAW)) {
-        streamType = 0x83;
-        streamIDStart = 0xbd;
-        streamIDStop = 0xbd;
-    } else {
-        return ERROR_UNSUPPORTED;
-    }
-
-    size_t numTracksOfThisType = 0;
-    unsigned PID = PIDStart;
-
-    for (size_t i = 0; i < mTracks.size(); ++i) {
-        const sp<Track> &track = mTracks.itemAt(i);
-
-        if (track->streamType() == streamType) {
-            ++numTracksOfThisType;
-        }
-
-        if ((isAudio && track->isAudio()) || (isVideo && track->isVideo())) {
-            ++PID;
-        }
-    }
-
-    unsigned streamID = streamIDStart + numTracksOfThisType;
-    if (streamID > streamIDStop) {
-        return -ERANGE;
-    }
-
-    sp<Track> track = new Track(format, PID, streamType, streamID);
-    return mTracks.add(track);
-}
-
-status_t TSPacketizer::extractCSDIfNecessary(size_t trackIndex) {
-    if (trackIndex >= mTracks.size()) {
-        return -ERANGE;
-    }
-
-    const sp<Track> &track = mTracks.itemAt(trackIndex);
-    track->extractCSDIfNecessary();
-
-    return OK;
-}
-
-status_t TSPacketizer::packetize(
-        size_t trackIndex,
-        const sp<ABuffer> &_accessUnit,
-        sp<ABuffer> *packets,
-        uint32_t flags,
-        const uint8_t *PES_private_data, size_t PES_private_data_len,
-        size_t numStuffingBytes) {
-    sp<ABuffer> accessUnit = _accessUnit;
-
-    int64_t timeUs;
-    CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
-
-    packets->clear();
-
-    if (trackIndex >= mTracks.size()) {
-        return -ERANGE;
-    }
-
-    const sp<Track> &track = mTracks.itemAt(trackIndex);
-
-    if (track->isH264() && (flags & PREPEND_SPS_PPS_TO_IDR_FRAMES)
-            && IsIDR(accessUnit)) {
-        // prepend codec specific data, i.e. SPS and PPS.
-        accessUnit = track->prependCSD(accessUnit);
-    } else if (track->isAAC() && track->lacksADTSHeader()) {
-        CHECK(!(flags & IS_ENCRYPTED));
-        accessUnit = track->prependADTSHeader(accessUnit);
-    }
-
-    // 0x47
-    // transport_error_indicator = b0
-    // payload_unit_start_indicator = b1
-    // transport_priority = b0
-    // PID
-    // transport_scrambling_control = b00
-    // adaptation_field_control = b??
-    // continuity_counter = b????
-    // -- payload follows
-    // packet_startcode_prefix = 0x000001
-    // stream_id
-    // PES_packet_length = 0x????
-    // reserved = b10
-    // PES_scrambling_control = b00
-    // PES_priority = b0
-    // data_alignment_indicator = b1
-    // copyright = b0
-    // original_or_copy = b0
-    // PTS_DTS_flags = b10  (PTS only)
-    // ESCR_flag = b0
-    // ES_rate_flag = b0
-    // DSM_trick_mode_flag = b0
-    // additional_copy_info_flag = b0
-    // PES_CRC_flag = b0
-    // PES_extension_flag = b0
-    // PES_header_data_length = 0x05
-    // reserved = b0010 (PTS)
-    // PTS[32..30] = b???
-    // reserved = b1
-    // PTS[29..15] = b??? ???? ???? ???? (15 bits)
-    // reserved = b1
-    // PTS[14..0] = b??? ???? ???? ???? (15 bits)
-    // reserved = b1
-    // the first fragment of "buffer" follows
-
-    // Each transport packet (except for the last one contributing to the PES
-    // payload) must contain a multiple of 16 bytes of payload per HDCP spec.
-    bool alignPayload =
-        (mFlags & (EMIT_HDCP20_DESCRIPTOR | EMIT_HDCP21_DESCRIPTOR));
-
-    /*
-       a) The very first PES transport stream packet contains
-
-       4 bytes of TS header
-       ... padding
-       14 bytes of static PES header
-       PES_private_data_len + 1 bytes (only if PES_private_data_len > 0)
-       numStuffingBytes bytes
-
-       followed by the payload
-
-       b) Subsequent PES transport stream packets contain
-
-       4 bytes of TS header
-       ... padding
-
-       followed by the payload
-    */
-
-    size_t PES_packet_length = accessUnit->size() + 8 + numStuffingBytes;
-    if (PES_private_data_len > 0) {
-        PES_packet_length += PES_private_data_len + 1;
-    }
-
-    size_t numTSPackets = 1;
-
-    {
-        // Make sure the PES header fits into a single TS packet:
-        size_t PES_header_size = 14 + numStuffingBytes;
-        if (PES_private_data_len > 0) {
-            PES_header_size += PES_private_data_len + 1;
-        }
-
-        CHECK_LE(PES_header_size, 188u - 4u);
-
-        size_t sizeAvailableForPayload = 188 - 4 - PES_header_size;
-        size_t numBytesOfPayload = accessUnit->size();
-
-        if (numBytesOfPayload > sizeAvailableForPayload) {
-            numBytesOfPayload = sizeAvailableForPayload;
-
-            if (alignPayload && numBytesOfPayload > 16) {
-                numBytesOfPayload -= (numBytesOfPayload % 16);
-            }
-        }
-
-        size_t numPaddingBytes = sizeAvailableForPayload - numBytesOfPayload;
-        ALOGV("packet 1 contains %zd padding bytes and %zd bytes of payload",
-              numPaddingBytes, numBytesOfPayload);
-
-        size_t numBytesOfPayloadRemaining = accessUnit->size() - numBytesOfPayload;
-
-#if 0
-        // The following hopefully illustrates the logic that led to the
-        // more efficient computation in the #else block...
-
-        while (numBytesOfPayloadRemaining > 0) {
-            size_t sizeAvailableForPayload = 188 - 4;
-
-            size_t numBytesOfPayload = numBytesOfPayloadRemaining;
-
-            if (numBytesOfPayload > sizeAvailableForPayload) {
-                numBytesOfPayload = sizeAvailableForPayload;
-
-                if (alignPayload && numBytesOfPayload > 16) {
-                    numBytesOfPayload -= (numBytesOfPayload % 16);
-                }
-            }
-
-            size_t numPaddingBytes = sizeAvailableForPayload - numBytesOfPayload;
-            ALOGI("packet %zd contains %zd padding bytes and %zd bytes of payload",
-                    numTSPackets + 1, numPaddingBytes, numBytesOfPayload);
-
-            numBytesOfPayloadRemaining -= numBytesOfPayload;
-            ++numTSPackets;
-        }
-#else
-        // This is how many bytes of payload each subsequent TS packet
-        // can contain at most.
-        sizeAvailableForPayload = 188 - 4;
-        size_t sizeAvailableForAlignedPayload = sizeAvailableForPayload;
-        if (alignPayload) {
-            // We're only going to use a subset of the available space
-            // since we need to make each fragment a multiple of 16 in size.
-            sizeAvailableForAlignedPayload -=
-                (sizeAvailableForAlignedPayload % 16);
-        }
-
-        size_t numFullTSPackets =
-            numBytesOfPayloadRemaining / sizeAvailableForAlignedPayload;
-
-        numTSPackets += numFullTSPackets;
-
-        numBytesOfPayloadRemaining -=
-            numFullTSPackets * sizeAvailableForAlignedPayload;
-
-        // numBytesOfPayloadRemaining < sizeAvailableForAlignedPayload
-        if (numFullTSPackets == 0 && numBytesOfPayloadRemaining > 0) {
-            // There wasn't enough payload left to form a full aligned payload,
-            // the last packet doesn't have to be aligned.
-            ++numTSPackets;
-        } else if (numFullTSPackets > 0
-                && numBytesOfPayloadRemaining
-                    + sizeAvailableForAlignedPayload > sizeAvailableForPayload) {
-            // The last packet emitted had a full aligned payload and together
-            // with the bytes remaining does exceed the unaligned payload
-            // size, so we need another packet.
-            ++numTSPackets;
-        }
-#endif
-    }
-
-    if (flags & EMIT_PAT_AND_PMT) {
-        numTSPackets += 2;
-    }
-
-    if (flags & EMIT_PCR) {
-        ++numTSPackets;
-    }
-
-    sp<ABuffer> buffer = new ABuffer(numTSPackets * 188);
-    uint8_t *packetDataStart = buffer->data();
-
-    if (flags & EMIT_PAT_AND_PMT) {
-        // Program Association Table (PAT):
-        // 0x47
-        // transport_error_indicator = b0
-        // payload_unit_start_indicator = b1
-        // transport_priority = b0
-        // PID = b0000000000000 (13 bits)
-        // transport_scrambling_control = b00
-        // adaptation_field_control = b01 (no adaptation field, payload only)
-        // continuity_counter = b????
-        // skip = 0x00
-        // --- payload follows
-        // table_id = 0x00
-        // section_syntax_indicator = b1
-        // must_be_zero = b0
-        // reserved = b11
-        // section_length = 0x00d
-        // transport_stream_id = 0x0000
-        // reserved = b11
-        // version_number = b00001
-        // current_next_indicator = b1
-        // section_number = 0x00
-        // last_section_number = 0x00
-        //   one program follows:
-        //   program_number = 0x0001
-        //   reserved = b111
-        //   program_map_PID = kPID_PMT (13 bits!)
-        // CRC = 0x????????
-
-        if (++mPATContinuityCounter == 16) {
-            mPATContinuityCounter = 0;
-        }
-
-        uint8_t *ptr = packetDataStart;
-        *ptr++ = 0x47;
-        *ptr++ = 0x40;
-        *ptr++ = 0x00;
-        *ptr++ = 0x10 | mPATContinuityCounter;
-        *ptr++ = 0x00;
-
-        uint8_t *crcDataStart = ptr;
-        *ptr++ = 0x00;
-        *ptr++ = 0xb0;
-        *ptr++ = 0x0d;
-        *ptr++ = 0x00;
-        *ptr++ = 0x00;
-        *ptr++ = 0xc3;
-        *ptr++ = 0x00;
-        *ptr++ = 0x00;
-        *ptr++ = 0x00;
-        *ptr++ = 0x01;
-        *ptr++ = 0xe0 | (kPID_PMT >> 8);
-        *ptr++ = kPID_PMT & 0xff;
-
-        CHECK_EQ(ptr - crcDataStart, 12);
-        uint32_t crc = htonl(crc32(crcDataStart, ptr - crcDataStart));
-        memcpy(ptr, &crc, 4);
-        ptr += 4;
-
-        size_t sizeLeft = packetDataStart + 188 - ptr;
-        memset(ptr, 0xff, sizeLeft);
-
-        packetDataStart += 188;
-
-        // Program Map (PMT):
-        // 0x47
-        // transport_error_indicator = b0
-        // payload_unit_start_indicator = b1
-        // transport_priority = b0
-        // PID = kPID_PMT (13 bits)
-        // transport_scrambling_control = b00
-        // adaptation_field_control = b01 (no adaptation field, payload only)
-        // continuity_counter = b????
-        // skip = 0x00
-        // -- payload follows
-        // table_id = 0x02
-        // section_syntax_indicator = b1
-        // must_be_zero = b0
-        // reserved = b11
-        // section_length = 0x???
-        // program_number = 0x0001
-        // reserved = b11
-        // version_number = b00001
-        // current_next_indicator = b1
-        // section_number = 0x00
-        // last_section_number = 0x00
-        // reserved = b111
-        // PCR_PID = kPCR_PID (13 bits)
-        // reserved = b1111
-        // program_info_length = 0x???
-        //   program_info_descriptors follow
-        // one or more elementary stream descriptions follow:
-        //   stream_type = 0x??
-        //   reserved = b111
-        //   elementary_PID = b? ???? ???? ???? (13 bits)
-        //   reserved = b1111
-        //   ES_info_length = 0x000
-        // CRC = 0x????????
-
-        if (++mPMTContinuityCounter == 16) {
-            mPMTContinuityCounter = 0;
-        }
-
-        ptr = packetDataStart;
-        *ptr++ = 0x47;
-        *ptr++ = 0x40 | (kPID_PMT >> 8);
-        *ptr++ = kPID_PMT & 0xff;
-        *ptr++ = 0x10 | mPMTContinuityCounter;
-        *ptr++ = 0x00;
-
-        crcDataStart = ptr;
-        *ptr++ = 0x02;
-
-        *ptr++ = 0x00;  // section_length to be filled in below.
-        *ptr++ = 0x00;
-
-        *ptr++ = 0x00;
-        *ptr++ = 0x01;
-        *ptr++ = 0xc3;
-        *ptr++ = 0x00;
-        *ptr++ = 0x00;
-        *ptr++ = 0xe0 | (kPID_PCR >> 8);
-        *ptr++ = kPID_PCR & 0xff;
-
-        size_t program_info_length = 0;
-        for (size_t i = 0; i < mProgramInfoDescriptors.size(); ++i) {
-            program_info_length += mProgramInfoDescriptors.itemAt(i)->size();
-        }
-
-        CHECK_LT(program_info_length, 0x400u);
-        *ptr++ = 0xf0 | (program_info_length >> 8);
-        *ptr++ = (program_info_length & 0xff);
-
-        for (size_t i = 0; i < mProgramInfoDescriptors.size(); ++i) {
-            const sp<ABuffer> &desc = mProgramInfoDescriptors.itemAt(i);
-            memcpy(ptr, desc->data(), desc->size());
-            ptr += desc->size();
-        }
-
-        for (size_t i = 0; i < mTracks.size(); ++i) {
-            const sp<Track> &track = mTracks.itemAt(i);
-
-            // Make sure all the decriptors have been added.
-            track->finalize();
-
-            *ptr++ = track->streamType();
-            *ptr++ = 0xe0 | (track->PID() >> 8);
-            *ptr++ = track->PID() & 0xff;
-
-            size_t ES_info_length = 0;
-            for (size_t i = 0; i < track->countDescriptors(); ++i) {
-                ES_info_length += track->descriptorAt(i)->size();
-            }
-            CHECK_LE(ES_info_length, 0xfffu);
-
-            *ptr++ = 0xf0 | (ES_info_length >> 8);
-            *ptr++ = (ES_info_length & 0xff);
-
-            for (size_t i = 0; i < track->countDescriptors(); ++i) {
-                const sp<ABuffer> &descriptor = track->descriptorAt(i);
-                memcpy(ptr, descriptor->data(), descriptor->size());
-                ptr += descriptor->size();
-            }
-        }
-
-        size_t section_length = ptr - (crcDataStart + 3) + 4 /* CRC */;
-
-        crcDataStart[1] = 0xb0 | (section_length >> 8);
-        crcDataStart[2] = section_length & 0xff;
-
-        crc = htonl(crc32(crcDataStart, ptr - crcDataStart));
-        memcpy(ptr, &crc, 4);
-        ptr += 4;
-
-        sizeLeft = packetDataStart + 188 - ptr;
-        memset(ptr, 0xff, sizeLeft);
-
-        packetDataStart += 188;
-    }
-
-    if (flags & EMIT_PCR) {
-        // PCR stream
-        // 0x47
-        // transport_error_indicator = b0
-        // payload_unit_start_indicator = b1
-        // transport_priority = b0
-        // PID = kPCR_PID (13 bits)
-        // transport_scrambling_control = b00
-        // adaptation_field_control = b10 (adaptation field only, no payload)
-        // continuity_counter = b0000 (does not increment)
-        // adaptation_field_length = 183
-        // discontinuity_indicator = b0
-        // random_access_indicator = b0
-        // elementary_stream_priority_indicator = b0
-        // PCR_flag = b1
-        // OPCR_flag = b0
-        // splicing_point_flag = b0
-        // transport_private_data_flag = b0
-        // adaptation_field_extension_flag = b0
-        // program_clock_reference_base = b?????????????????????????????????
-        // reserved = b111111
-        // program_clock_reference_extension = b?????????
-
-        int64_t nowUs = ALooper::GetNowUs();
-
-        uint64_t PCR = nowUs * 27;  // PCR based on a 27MHz clock
-        uint64_t PCR_base = PCR / 300;
-        uint32_t PCR_ext = PCR % 300;
-
-        uint8_t *ptr = packetDataStart;
-        *ptr++ = 0x47;
-        *ptr++ = 0x40 | (kPID_PCR >> 8);
-        *ptr++ = kPID_PCR & 0xff;
-        *ptr++ = 0x20;
-        *ptr++ = 0xb7;  // adaptation_field_length
-        *ptr++ = 0x10;
-        *ptr++ = (PCR_base >> 25) & 0xff;
-        *ptr++ = (PCR_base >> 17) & 0xff;
-        *ptr++ = (PCR_base >> 9) & 0xff;
-        *ptr++ = ((PCR_base & 1) << 7) | 0x7e | ((PCR_ext >> 8) & 1);
-        *ptr++ = (PCR_ext & 0xff);
-
-        size_t sizeLeft = packetDataStart + 188 - ptr;
-        memset(ptr, 0xff, sizeLeft);
-
-        packetDataStart += 188;
-    }
-
-    uint64_t PTS = (timeUs * 9ll) / 100ll;
-
-    if (PES_packet_length >= 65536) {
-        // This really should only happen for video.
-        CHECK(track->isVideo());
-
-        // It's valid to set this to 0 for video according to the specs.
-        PES_packet_length = 0;
-    }
-
-    size_t sizeAvailableForPayload = 188 - 4 - 14 - numStuffingBytes;
-    if (PES_private_data_len > 0) {
-        sizeAvailableForPayload -= PES_private_data_len + 1;
-    }
-
-    size_t copy = accessUnit->size();
-
-    if (copy > sizeAvailableForPayload) {
-        copy = sizeAvailableForPayload;
-
-        if (alignPayload && copy > 16) {
-            copy -= (copy % 16);
-        }
-    }
-
-    size_t numPaddingBytes = sizeAvailableForPayload - copy;
-
-    uint8_t *ptr = packetDataStart;
-    *ptr++ = 0x47;
-    *ptr++ = 0x40 | (track->PID() >> 8);
-    *ptr++ = track->PID() & 0xff;
-
-    *ptr++ = (numPaddingBytes > 0 ? 0x30 : 0x10)
-                | track->incrementContinuityCounter();
-
-    if (numPaddingBytes > 0) {
-        *ptr++ = numPaddingBytes - 1;
-        if (numPaddingBytes >= 2) {
-            *ptr++ = 0x00;
-            memset(ptr, 0xff, numPaddingBytes - 2);
-            ptr += numPaddingBytes - 2;
-        }
-    }
-
-    *ptr++ = 0x00;
-    *ptr++ = 0x00;
-    *ptr++ = 0x01;
-    *ptr++ = track->streamID();
-    *ptr++ = PES_packet_length >> 8;
-    *ptr++ = PES_packet_length & 0xff;
-    *ptr++ = 0x84;
-    *ptr++ = (PES_private_data_len > 0) ? 0x81 : 0x80;
-
-    size_t headerLength = 0x05 + numStuffingBytes;
-    if (PES_private_data_len > 0) {
-        headerLength += 1 + PES_private_data_len;
-    }
-
-    *ptr++ = headerLength;
-
-    *ptr++ = 0x20 | (((PTS >> 30) & 7) << 1) | 1;
-    *ptr++ = (PTS >> 22) & 0xff;
-    *ptr++ = (((PTS >> 15) & 0x7f) << 1) | 1;
-    *ptr++ = (PTS >> 7) & 0xff;
-    *ptr++ = ((PTS & 0x7f) << 1) | 1;
-
-    if (PES_private_data_len > 0) {
-        *ptr++ = 0x8e;  // PES_private_data_flag, reserved.
-        memcpy(ptr, PES_private_data, PES_private_data_len);
-        ptr += PES_private_data_len;
-    }
-
-    for (size_t i = 0; i < numStuffingBytes; ++i) {
-        *ptr++ = 0xff;
-    }
-
-    memcpy(ptr, accessUnit->data(), copy);
-    ptr += copy;
-
-    CHECK_EQ(ptr, packetDataStart + 188);
-    packetDataStart += 188;
-
-    size_t offset = copy;
-    while (offset < accessUnit->size()) {
-        // for subsequent fragments of "buffer":
-        // 0x47
-        // transport_error_indicator = b0
-        // payload_unit_start_indicator = b0
-        // transport_priority = b0
-        // PID = b0 0001 1110 ???? (13 bits) [0x1e0 + 1 + sourceIndex]
-        // transport_scrambling_control = b00
-        // adaptation_field_control = b??
-        // continuity_counter = b????
-        // the fragment of "buffer" follows.
-
-        size_t sizeAvailableForPayload = 188 - 4;
-
-        size_t copy = accessUnit->size() - offset;
-
-        if (copy > sizeAvailableForPayload) {
-            copy = sizeAvailableForPayload;
-
-            if (alignPayload && copy > 16) {
-                copy -= (copy % 16);
-            }
-        }
-
-        size_t numPaddingBytes = sizeAvailableForPayload - copy;
-
-        uint8_t *ptr = packetDataStart;
-        *ptr++ = 0x47;
-        *ptr++ = 0x00 | (track->PID() >> 8);
-        *ptr++ = track->PID() & 0xff;
-
-        *ptr++ = (numPaddingBytes > 0 ? 0x30 : 0x10)
-                    | track->incrementContinuityCounter();
-
-        if (numPaddingBytes > 0) {
-            *ptr++ = numPaddingBytes - 1;
-            if (numPaddingBytes >= 2) {
-                *ptr++ = 0x00;
-                memset(ptr, 0xff, numPaddingBytes - 2);
-                ptr += numPaddingBytes - 2;
-            }
-        }
-
-        memcpy(ptr, accessUnit->data() + offset, copy);
-        ptr += copy;
-        CHECK_EQ(ptr, packetDataStart + 188);
-
-        offset += copy;
-        packetDataStart += 188;
-    }
-
-    CHECK(packetDataStart == buffer->data() + buffer->capacity());
-
-    *packets = buffer;
-
-    return OK;
-}
-
-void TSPacketizer::initCrcTable() {
-    uint32_t poly = 0x04C11DB7;
-
-    for (int i = 0; i < 256; i++) {
-        uint32_t crc = i << 24;
-        for (int j = 0; j < 8; j++) {
-            crc = (crc << 1) ^ ((crc & 0x80000000) ? (poly) : 0);
-        }
-        mCrcTable[i] = crc;
-    }
-}
-
-uint32_t TSPacketizer::crc32(const uint8_t *start, size_t size) const {
-    uint32_t crc = 0xFFFFFFFF;
-    const uint8_t *p;
-
-    for (p = start; p < start + size; ++p) {
-        crc = (crc << 8) ^ mCrcTable[((crc >> 24) ^ *p) & 0xFF];
-    }
-
-    return crc;
-}
-
-sp<ABuffer> TSPacketizer::prependCSD(
-        size_t trackIndex, const sp<ABuffer> &accessUnit) const {
-    CHECK_LT(trackIndex, mTracks.size());
-
-    const sp<Track> &track = mTracks.itemAt(trackIndex);
-    CHECK(track->isH264() && IsIDR(accessUnit));
-
-    int64_t timeUs;
-    CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
-
-    sp<ABuffer> accessUnit2 = track->prependCSD(accessUnit);
-
-    accessUnit2->meta()->setInt64("timeUs", timeUs);
-
-    return accessUnit2;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/wifi-display/source/TSPacketizer.h b/media/libstagefright/wifi-display/source/TSPacketizer.h
deleted file mode 100644
index 0dcb179..0000000
--- a/media/libstagefright/wifi-display/source/TSPacketizer.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright 2012, 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 TS_PACKETIZER_H_
-
-#define TS_PACKETIZER_H_
-
-#include <media/stagefright/foundation/ABase.h>
-#include <utils/Errors.h>
-#include <utils/RefBase.h>
-#include <utils/Vector.h>
-
-namespace android {
-
-struct ABuffer;
-struct AMessage;
-
-// Forms the packets of a transport stream given access units.
-// Emits metadata tables (PAT and PMT) and timestamp stream (PCR) based
-// on flags.
-struct TSPacketizer : public RefBase {
-    enum {
-        EMIT_HDCP20_DESCRIPTOR = 1,
-        EMIT_HDCP21_DESCRIPTOR = 2,
-    };
-    explicit TSPacketizer(uint32_t flags);
-
-    // Returns trackIndex or error.
-    ssize_t addTrack(const sp<AMessage> &format);
-
-    enum {
-        EMIT_PAT_AND_PMT                = 1,
-        EMIT_PCR                        = 2,
-        IS_ENCRYPTED                    = 4,
-        PREPEND_SPS_PPS_TO_IDR_FRAMES   = 8,
-    };
-    status_t packetize(
-            size_t trackIndex, const sp<ABuffer> &accessUnit,
-            sp<ABuffer> *packets,
-            uint32_t flags,
-            const uint8_t *PES_private_data, size_t PES_private_data_len,
-            size_t numStuffingBytes = 0);
-
-    status_t extractCSDIfNecessary(size_t trackIndex);
-
-    // XXX to be removed once encoder config option takes care of this for
-    // encrypted mode.
-    sp<ABuffer> prependCSD(
-            size_t trackIndex, const sp<ABuffer> &accessUnit) const;
-
-protected:
-    virtual ~TSPacketizer();
-
-private:
-    enum {
-        kPID_PMT = 0x100,
-        kPID_PCR = 0x1000,
-    };
-
-    struct Track;
-
-    uint32_t mFlags;
-    Vector<sp<Track> > mTracks;
-
-    Vector<sp<ABuffer> > mProgramInfoDescriptors;
-
-    unsigned mPATContinuityCounter;
-    unsigned mPMTContinuityCounter;
-
-    uint32_t mCrcTable[256];
-
-    void initCrcTable();
-    uint32_t crc32(const uint8_t *start, size_t size) const;
-
-    DISALLOW_EVIL_CONSTRUCTORS(TSPacketizer);
-};
-
-}  // namespace android
-
-#endif  // TS_PACKETIZER_H_
-
diff --git a/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp b/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp
deleted file mode 100644
index 4695e5d..0000000
--- a/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp
+++ /dev/null
@@ -1,1737 +0,0 @@
-/*
- * Copyright 2012, 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 "WifiDisplaySource"
-#include <utils/Log.h>
-
-#include "WifiDisplaySource.h"
-#include "PlaybackSession.h"
-#include "Parameters.h"
-#include "rtp/RTPSender.h"
-
-#include <binder/IServiceManager.h>
-#include <gui/IGraphicBufferProducer.h>
-#include <media/IHDCP.h>
-#include <media/IMediaPlayerService.h>
-#include <media/IRemoteDisplayClient.h>
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/foundation/ParsedMessage.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/Utils.h>
-
-#include <arpa/inet.h>
-#include <cutils/properties.h>
-
-#include <ctype.h>
-
-namespace android {
-
-// static
-const int64_t WifiDisplaySource::kReaperIntervalUs;
-const int64_t WifiDisplaySource::kTeardownTriggerTimeouSecs;
-const int64_t WifiDisplaySource::kPlaybackSessionTimeoutSecs;
-const int64_t WifiDisplaySource::kPlaybackSessionTimeoutUs;
-const AString WifiDisplaySource::sUserAgent = MakeUserAgent();
-
-WifiDisplaySource::WifiDisplaySource(
-        const String16 &opPackageName,
-        const sp<ANetworkSession> &netSession,
-        const sp<IRemoteDisplayClient> &client,
-        const char *path)
-    : mOpPackageName(opPackageName),
-      mState(INITIALIZED),
-      mNetSession(netSession),
-      mClient(client),
-      mSessionID(0),
-      mStopReplyID(NULL),
-      mChosenRTPPort(-1),
-      mUsingPCMAudio(false),
-      mClientSessionID(0),
-      mReaperPending(false),
-      mNextCSeq(1),
-      mUsingHDCP(false),
-      mIsHDCP2_0(false),
-      mHDCPPort(0),
-      mHDCPInitializationComplete(false),
-      mSetupTriggerDeferred(false),
-      mPlaybackSessionEstablished(false) {
-    if (path != NULL) {
-        mMediaPath.setTo(path);
-    }
-
-    mSupportedSourceVideoFormats.disableAll();
-
-    mSupportedSourceVideoFormats.setNativeResolution(
-            VideoFormats::RESOLUTION_CEA, 5);  // 1280x720 p30
-
-    // Enable all resolutions up to 1280x720p30
-    mSupportedSourceVideoFormats.enableResolutionUpto(
-            VideoFormats::RESOLUTION_CEA, 5,
-            VideoFormats::PROFILE_CHP,  // Constrained High Profile
-            VideoFormats::LEVEL_32);    // Level 3.2
-}
-
-WifiDisplaySource::~WifiDisplaySource() {
-}
-
-static status_t PostAndAwaitResponse(
-        const sp<AMessage> &msg, sp<AMessage> *response) {
-    status_t err = msg->postAndAwaitResponse(response);
-
-    if (err != OK) {
-        return err;
-    }
-
-    if (response == NULL || !(*response)->findInt32("err", &err)) {
-        err = OK;
-    }
-
-    return err;
-}
-
-status_t WifiDisplaySource::start(const char *iface) {
-    CHECK_EQ(mState, INITIALIZED);
-
-    sp<AMessage> msg = new AMessage(kWhatStart, this);
-    msg->setString("iface", iface);
-
-    sp<AMessage> response;
-    return PostAndAwaitResponse(msg, &response);
-}
-
-status_t WifiDisplaySource::stop() {
-    sp<AMessage> msg = new AMessage(kWhatStop, this);
-
-    sp<AMessage> response;
-    return PostAndAwaitResponse(msg, &response);
-}
-
-status_t WifiDisplaySource::pause() {
-    sp<AMessage> msg = new AMessage(kWhatPause, this);
-
-    sp<AMessage> response;
-    return PostAndAwaitResponse(msg, &response);
-}
-
-status_t WifiDisplaySource::resume() {
-    sp<AMessage> msg = new AMessage(kWhatResume, this);
-
-    sp<AMessage> response;
-    return PostAndAwaitResponse(msg, &response);
-}
-
-void WifiDisplaySource::onMessageReceived(const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatStart:
-        {
-            sp<AReplyToken> replyID;
-            CHECK(msg->senderAwaitsResponse(&replyID));
-
-            AString iface;
-            CHECK(msg->findString("iface", &iface));
-
-            status_t err = OK;
-
-            ssize_t colonPos = iface.find(":");
-
-            unsigned long port;
-
-            if (colonPos >= 0) {
-                const char *s = iface.c_str() + colonPos + 1;
-
-                char *end;
-                port = strtoul(s, &end, 10);
-
-                if (end == s || *end != '\0' || port > 65535) {
-                    err = -EINVAL;
-                } else {
-                    iface.erase(colonPos, iface.size() - colonPos);
-                }
-            } else {
-                port = kWifiDisplayDefaultPort;
-            }
-
-            if (err == OK) {
-                if (inet_aton(iface.c_str(), &mInterfaceAddr) != 0) {
-                    sp<AMessage> notify = new AMessage(kWhatRTSPNotify, this);
-
-                    err = mNetSession->createRTSPServer(
-                            mInterfaceAddr, port, notify, &mSessionID);
-                } else {
-                    err = -EINVAL;
-                }
-            }
-
-            mState = AWAITING_CLIENT_CONNECTION;
-
-            sp<AMessage> response = new AMessage;
-            response->setInt32("err", err);
-            response->postReply(replyID);
-            break;
-        }
-
-        case kWhatRTSPNotify:
-        {
-            int32_t reason;
-            CHECK(msg->findInt32("reason", &reason));
-
-            switch (reason) {
-                case ANetworkSession::kWhatError:
-                {
-                    int32_t sessionID;
-                    CHECK(msg->findInt32("sessionID", &sessionID));
-
-                    int32_t err;
-                    CHECK(msg->findInt32("err", &err));
-
-                    AString detail;
-                    CHECK(msg->findString("detail", &detail));
-
-                    ALOGE("An error occurred in session %d (%d, '%s/%s').",
-                          sessionID,
-                          err,
-                          detail.c_str(),
-                          strerror(-err));
-
-                    mNetSession->destroySession(sessionID);
-
-                    if (sessionID == mClientSessionID) {
-                        mClientSessionID = 0;
-
-                        mClient->onDisplayError(
-                                IRemoteDisplayClient::kDisplayErrorUnknown);
-                    }
-                    break;
-                }
-
-                case ANetworkSession::kWhatClientConnected:
-                {
-                    int32_t sessionID;
-                    CHECK(msg->findInt32("sessionID", &sessionID));
-
-                    if (mClientSessionID > 0) {
-                        ALOGW("A client tried to connect, but we already "
-                              "have one.");
-
-                        mNetSession->destroySession(sessionID);
-                        break;
-                    }
-
-                    CHECK_EQ(mState, AWAITING_CLIENT_CONNECTION);
-
-                    CHECK(msg->findString("client-ip", &mClientInfo.mRemoteIP));
-                    CHECK(msg->findString("server-ip", &mClientInfo.mLocalIP));
-
-                    if (mClientInfo.mRemoteIP == mClientInfo.mLocalIP) {
-                        // Disallow connections from the local interface
-                        // for security reasons.
-                        mNetSession->destroySession(sessionID);
-                        break;
-                    }
-
-                    CHECK(msg->findInt32(
-                                "server-port", &mClientInfo.mLocalPort));
-                    mClientInfo.mPlaybackSessionID = -1;
-
-                    mClientSessionID = sessionID;
-
-                    ALOGI("We now have a client (%d) connected.", sessionID);
-
-                    mState = AWAITING_CLIENT_SETUP;
-
-                    status_t err = sendM1(sessionID);
-                    CHECK_EQ(err, (status_t)OK);
-                    break;
-                }
-
-                case ANetworkSession::kWhatData:
-                {
-                    status_t err = onReceiveClientData(msg);
-
-                    if (err != OK) {
-                        mClient->onDisplayError(
-                                IRemoteDisplayClient::kDisplayErrorUnknown);
-                    }
-
-#if 0
-                    // testing only.
-                    char val[PROPERTY_VALUE_MAX];
-                    if (property_get("media.wfd.trigger", val, NULL)) {
-                        if (!strcasecmp(val, "pause") && mState == PLAYING) {
-                            mState = PLAYING_TO_PAUSED;
-                            sendTrigger(mClientSessionID, TRIGGER_PAUSE);
-                        } else if (!strcasecmp(val, "play")
-                                    && mState == PAUSED) {
-                            mState = PAUSED_TO_PLAYING;
-                            sendTrigger(mClientSessionID, TRIGGER_PLAY);
-                        }
-                    }
-#endif
-                    break;
-                }
-
-                case ANetworkSession::kWhatNetworkStall:
-                {
-                    break;
-                }
-
-                default:
-                    TRESPASS();
-            }
-            break;
-        }
-
-        case kWhatStop:
-        {
-            CHECK(msg->senderAwaitsResponse(&mStopReplyID));
-
-            CHECK_LT(mState, AWAITING_CLIENT_TEARDOWN);
-
-            if (mState >= AWAITING_CLIENT_PLAY) {
-                // We have a session, i.e. a previous SETUP succeeded.
-
-                status_t err = sendTrigger(
-                        mClientSessionID, TRIGGER_TEARDOWN);
-
-                if (err == OK) {
-                    mState = AWAITING_CLIENT_TEARDOWN;
-
-                    (new AMessage(kWhatTeardownTriggerTimedOut, this))->post(
-                            kTeardownTriggerTimeouSecs * 1000000ll);
-
-                    break;
-                }
-
-                // fall through.
-            }
-
-            finishStop();
-            break;
-        }
-
-        case kWhatPause:
-        {
-            sp<AReplyToken> replyID;
-            CHECK(msg->senderAwaitsResponse(&replyID));
-
-            status_t err = OK;
-
-            if (mState != PLAYING) {
-                err = INVALID_OPERATION;
-            } else {
-                mState = PLAYING_TO_PAUSED;
-                sendTrigger(mClientSessionID, TRIGGER_PAUSE);
-            }
-
-            sp<AMessage> response = new AMessage;
-            response->setInt32("err", err);
-            response->postReply(replyID);
-            break;
-        }
-
-        case kWhatResume:
-        {
-            sp<AReplyToken> replyID;
-            CHECK(msg->senderAwaitsResponse(&replyID));
-
-            status_t err = OK;
-
-            if (mState != PAUSED) {
-                err = INVALID_OPERATION;
-            } else {
-                mState = PAUSED_TO_PLAYING;
-                sendTrigger(mClientSessionID, TRIGGER_PLAY);
-            }
-
-            sp<AMessage> response = new AMessage;
-            response->setInt32("err", err);
-            response->postReply(replyID);
-            break;
-        }
-
-        case kWhatReapDeadClients:
-        {
-            mReaperPending = false;
-
-            if (mClientSessionID == 0
-                    || mClientInfo.mPlaybackSession == NULL) {
-                break;
-            }
-
-            if (mClientInfo.mPlaybackSession->getLastLifesignUs()
-                    + kPlaybackSessionTimeoutUs < ALooper::GetNowUs()) {
-                ALOGI("playback session timed out, reaping.");
-
-                mNetSession->destroySession(mClientSessionID);
-                mClientSessionID = 0;
-
-                mClient->onDisplayError(
-                        IRemoteDisplayClient::kDisplayErrorUnknown);
-            } else {
-                scheduleReaper();
-            }
-            break;
-        }
-
-        case kWhatPlaybackSessionNotify:
-        {
-            int32_t playbackSessionID;
-            CHECK(msg->findInt32("playbackSessionID", &playbackSessionID));
-
-            int32_t what;
-            CHECK(msg->findInt32("what", &what));
-
-            if (what == PlaybackSession::kWhatSessionDead) {
-                ALOGI("playback session wants to quit.");
-
-                mClient->onDisplayError(
-                        IRemoteDisplayClient::kDisplayErrorUnknown);
-            } else if (what == PlaybackSession::kWhatSessionEstablished) {
-                mPlaybackSessionEstablished = true;
-
-                if (mClient != NULL) {
-                    if (!mSinkSupportsVideo) {
-                        mClient->onDisplayConnected(
-                                NULL,  // SurfaceTexture
-                                0, // width,
-                                0, // height,
-                                mUsingHDCP
-                                    ? IRemoteDisplayClient::kDisplayFlagSecure
-                                    : 0,
-                                0);
-                    } else {
-                        size_t width, height;
-
-                        CHECK(VideoFormats::GetConfiguration(
-                                    mChosenVideoResolutionType,
-                                    mChosenVideoResolutionIndex,
-                                    &width,
-                                    &height,
-                                    NULL /* framesPerSecond */,
-                                    NULL /* interlaced */));
-
-                        mClient->onDisplayConnected(
-                                mClientInfo.mPlaybackSession
-                                    ->getSurfaceTexture(),
-                                width,
-                                height,
-                                mUsingHDCP
-                                    ? IRemoteDisplayClient::kDisplayFlagSecure
-                                    : 0,
-                                playbackSessionID);
-                    }
-                }
-
-                finishPlay();
-
-                if (mState == ABOUT_TO_PLAY) {
-                    mState = PLAYING;
-                }
-            } else if (what == PlaybackSession::kWhatSessionDestroyed) {
-                disconnectClient2();
-            } else {
-                CHECK_EQ(what, PlaybackSession::kWhatBinaryData);
-
-                int32_t channel;
-                CHECK(msg->findInt32("channel", &channel));
-
-                sp<ABuffer> data;
-                CHECK(msg->findBuffer("data", &data));
-
-                CHECK_LE(channel, 0xff);
-                CHECK_LE(data->size(), 0xffffu);
-
-                int32_t sessionID;
-                CHECK(msg->findInt32("sessionID", &sessionID));
-
-                char header[4];
-                header[0] = '$';
-                header[1] = channel;
-                header[2] = data->size() >> 8;
-                header[3] = data->size() & 0xff;
-
-                mNetSession->sendRequest(
-                        sessionID, header, sizeof(header));
-
-                mNetSession->sendRequest(
-                        sessionID, data->data(), data->size());
-            }
-            break;
-        }
-
-        case kWhatKeepAlive:
-        {
-            int32_t sessionID;
-            CHECK(msg->findInt32("sessionID", &sessionID));
-
-            if (mClientSessionID != sessionID) {
-                // Obsolete event, client is already gone.
-                break;
-            }
-
-            sendM16(sessionID);
-            break;
-        }
-
-        case kWhatTeardownTriggerTimedOut:
-        {
-            if (mState == AWAITING_CLIENT_TEARDOWN) {
-                ALOGI("TEARDOWN trigger timed out, forcing disconnection.");
-
-                CHECK(mStopReplyID != NULL);
-                finishStop();
-                break;
-            }
-            break;
-        }
-
-        case kWhatHDCPNotify:
-        {
-            int32_t msgCode, ext1, ext2;
-            CHECK(msg->findInt32("msg", &msgCode));
-            CHECK(msg->findInt32("ext1", &ext1));
-            CHECK(msg->findInt32("ext2", &ext2));
-
-            ALOGI("Saw HDCP notification code %d, ext1 %d, ext2 %d",
-                    msgCode, ext1, ext2);
-
-            switch (msgCode) {
-                case HDCPModule::HDCP_INITIALIZATION_COMPLETE:
-                {
-                    mHDCPInitializationComplete = true;
-
-                    if (mSetupTriggerDeferred) {
-                        mSetupTriggerDeferred = false;
-
-                        sendTrigger(mClientSessionID, TRIGGER_SETUP);
-                    }
-                    break;
-                }
-
-                case HDCPModule::HDCP_SHUTDOWN_COMPLETE:
-                case HDCPModule::HDCP_SHUTDOWN_FAILED:
-                {
-                    // Ugly hack to make sure that the call to
-                    // HDCPObserver::notify is completely handled before
-                    // we clear the HDCP instance and unload the shared
-                    // library :(
-                    (new AMessage(kWhatFinishStop2, this))->post(300000ll);
-                    break;
-                }
-
-                default:
-                {
-                    ALOGE("HDCP failure, shutting down.");
-
-                    mClient->onDisplayError(
-                            IRemoteDisplayClient::kDisplayErrorUnknown);
-                    break;
-                }
-            }
-            break;
-        }
-
-        case kWhatFinishStop2:
-        {
-            finishStop2();
-            break;
-        }
-
-        default:
-            TRESPASS();
-    }
-}
-
-void WifiDisplaySource::registerResponseHandler(
-        int32_t sessionID, int32_t cseq, HandleRTSPResponseFunc func) {
-    ResponseID id;
-    id.mSessionID = sessionID;
-    id.mCSeq = cseq;
-    mResponseHandlers.add(id, func);
-}
-
-status_t WifiDisplaySource::sendM1(int32_t sessionID) {
-    AString request = "OPTIONS * RTSP/1.0\r\n";
-    AppendCommonResponse(&request, mNextCSeq);
-
-    request.append(
-            "Require: org.wfa.wfd1.0\r\n"
-            "\r\n");
-
-    status_t err =
-        mNetSession->sendRequest(sessionID, request.c_str(), request.size());
-
-    if (err != OK) {
-        return err;
-    }
-
-    registerResponseHandler(
-            sessionID, mNextCSeq, &WifiDisplaySource::onReceiveM1Response);
-
-    ++mNextCSeq;
-
-    return OK;
-}
-
-status_t WifiDisplaySource::sendM3(int32_t sessionID) {
-    AString body =
-        "wfd_content_protection\r\n"
-        "wfd_video_formats\r\n"
-        "wfd_audio_codecs\r\n"
-        "wfd_client_rtp_ports\r\n";
-
-    AString request = "GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\n";
-    AppendCommonResponse(&request, mNextCSeq);
-
-    request.append("Content-Type: text/parameters\r\n");
-    request.append(AStringPrintf("Content-Length: %d\r\n", body.size()));
-    request.append("\r\n");
-    request.append(body);
-
-    status_t err =
-        mNetSession->sendRequest(sessionID, request.c_str(), request.size());
-
-    if (err != OK) {
-        return err;
-    }
-
-    registerResponseHandler(
-            sessionID, mNextCSeq, &WifiDisplaySource::onReceiveM3Response);
-
-    ++mNextCSeq;
-
-    return OK;
-}
-
-status_t WifiDisplaySource::sendM4(int32_t sessionID) {
-    CHECK_EQ(sessionID, mClientSessionID);
-
-    AString body;
-
-    if (mSinkSupportsVideo) {
-        body.append("wfd_video_formats: ");
-
-        VideoFormats chosenVideoFormat;
-        chosenVideoFormat.disableAll();
-        chosenVideoFormat.setNativeResolution(
-                mChosenVideoResolutionType, mChosenVideoResolutionIndex);
-        chosenVideoFormat.setProfileLevel(
-                mChosenVideoResolutionType, mChosenVideoResolutionIndex,
-                mChosenVideoProfile, mChosenVideoLevel);
-
-        body.append(chosenVideoFormat.getFormatSpec(true /* forM4Message */));
-        body.append("\r\n");
-    }
-
-    if (mSinkSupportsAudio) {
-        body.append(
-                AStringPrintf("wfd_audio_codecs: %s\r\n",
-                             (mUsingPCMAudio
-                                ? "LPCM 00000002 00" // 2 ch PCM 48kHz
-                                : "AAC 00000001 00")));  // 2 ch AAC 48kHz
-    }
-
-    body.append(
-            AStringPrintf(
-                "wfd_presentation_URL: rtsp://%s/wfd1.0/streamid=0 none\r\n",
-                mClientInfo.mLocalIP.c_str()));
-
-    body.append(
-            AStringPrintf(
-                "wfd_client_rtp_ports: %s\r\n", mWfdClientRtpPorts.c_str()));
-
-    AString request = "SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\n";
-    AppendCommonResponse(&request, mNextCSeq);
-
-    request.append("Content-Type: text/parameters\r\n");
-    request.append(AStringPrintf("Content-Length: %d\r\n", body.size()));
-    request.append("\r\n");
-    request.append(body);
-
-    status_t err =
-        mNetSession->sendRequest(sessionID, request.c_str(), request.size());
-
-    if (err != OK) {
-        return err;
-    }
-
-    registerResponseHandler(
-            sessionID, mNextCSeq, &WifiDisplaySource::onReceiveM4Response);
-
-    ++mNextCSeq;
-
-    return OK;
-}
-
-status_t WifiDisplaySource::sendTrigger(
-        int32_t sessionID, TriggerType triggerType) {
-    AString body = "wfd_trigger_method: ";
-    switch (triggerType) {
-        case TRIGGER_SETUP:
-            body.append("SETUP");
-            break;
-        case TRIGGER_TEARDOWN:
-            ALOGI("Sending TEARDOWN trigger.");
-            body.append("TEARDOWN");
-            break;
-        case TRIGGER_PAUSE:
-            body.append("PAUSE");
-            break;
-        case TRIGGER_PLAY:
-            body.append("PLAY");
-            break;
-        default:
-            TRESPASS();
-    }
-
-    body.append("\r\n");
-
-    AString request = "SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\n";
-    AppendCommonResponse(&request, mNextCSeq);
-
-    request.append("Content-Type: text/parameters\r\n");
-    request.append(AStringPrintf("Content-Length: %d\r\n", body.size()));
-    request.append("\r\n");
-    request.append(body);
-
-    status_t err =
-        mNetSession->sendRequest(sessionID, request.c_str(), request.size());
-
-    if (err != OK) {
-        return err;
-    }
-
-    registerResponseHandler(
-            sessionID, mNextCSeq, &WifiDisplaySource::onReceiveM5Response);
-
-    ++mNextCSeq;
-
-    return OK;
-}
-
-status_t WifiDisplaySource::sendM16(int32_t sessionID) {
-    AString request = "GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\n";
-    AppendCommonResponse(&request, mNextCSeq);
-
-    CHECK_EQ(sessionID, mClientSessionID);
-    request.append(
-            AStringPrintf("Session: %d\r\n", mClientInfo.mPlaybackSessionID));
-    request.append("\r\n");  // Empty body
-
-    status_t err =
-        mNetSession->sendRequest(sessionID, request.c_str(), request.size());
-
-    if (err != OK) {
-        return err;
-    }
-
-    registerResponseHandler(
-            sessionID, mNextCSeq, &WifiDisplaySource::onReceiveM16Response);
-
-    ++mNextCSeq;
-
-    scheduleKeepAlive(sessionID);
-
-    return OK;
-}
-
-status_t WifiDisplaySource::onReceiveM1Response(
-        int32_t /* sessionID */, const sp<ParsedMessage> &msg) {
-    int32_t statusCode;
-    if (!msg->getStatusCode(&statusCode)) {
-        return ERROR_MALFORMED;
-    }
-
-    if (statusCode != 200) {
-        return ERROR_UNSUPPORTED;
-    }
-
-    return OK;
-}
-
-// sink_audio_list := ("LPCM"|"AAC"|"AC3" HEXDIGIT*8 HEXDIGIT*2)
-//                       (", " sink_audio_list)*
-static void GetAudioModes(const char *s, const char *prefix, uint32_t *modes) {
-    *modes = 0;
-
-    size_t prefixLen = strlen(prefix);
-
-    while (*s != '0') {
-        if (!strncmp(s, prefix, prefixLen) && s[prefixLen] == ' ') {
-            unsigned latency;
-            if (sscanf(&s[prefixLen + 1], "%08x %02x", modes, &latency) != 2) {
-                *modes = 0;
-            }
-
-            return;
-        }
-
-        const char *commaPos = strchr(s, ',');
-        if (commaPos != NULL) {
-            s = commaPos + 1;
-
-            while (isspace(*s)) {
-                ++s;
-            }
-        } else {
-            break;
-        }
-    }
-}
-
-status_t WifiDisplaySource::onReceiveM3Response(
-        int32_t sessionID, const sp<ParsedMessage> &msg) {
-    int32_t statusCode;
-    if (!msg->getStatusCode(&statusCode)) {
-        return ERROR_MALFORMED;
-    }
-
-    if (statusCode != 200) {
-        return ERROR_UNSUPPORTED;
-    }
-
-    sp<Parameters> params =
-        Parameters::Parse(msg->getContent(), strlen(msg->getContent()));
-
-    if (params == NULL) {
-        return ERROR_MALFORMED;
-    }
-
-    AString value;
-    if (!params->findParameter("wfd_client_rtp_ports", &value)) {
-        ALOGE("Sink doesn't report its choice of wfd_client_rtp_ports.");
-        return ERROR_MALFORMED;
-    }
-
-    unsigned port0 = 0, port1 = 0;
-    if (sscanf(value.c_str(),
-               "RTP/AVP/UDP;unicast %u %u mode=play",
-               &port0,
-               &port1) == 2
-        || sscanf(value.c_str(),
-               "RTP/AVP/TCP;unicast %u %u mode=play",
-               &port0,
-               &port1) == 2) {
-            if (port0 == 0 || port0 > 65535 || port1 != 0) {
-                ALOGE("Sink chose its wfd_client_rtp_ports poorly (%s)",
-                      value.c_str());
-
-                return ERROR_MALFORMED;
-            }
-    } else if (strcmp(value.c_str(), "RTP/AVP/TCP;interleaved mode=play")) {
-        ALOGE("Unsupported value for wfd_client_rtp_ports (%s)",
-              value.c_str());
-
-        return ERROR_UNSUPPORTED;
-    }
-
-    mWfdClientRtpPorts = value;
-    mChosenRTPPort = port0;
-
-    if (!params->findParameter("wfd_video_formats", &value)) {
-        ALOGE("Sink doesn't report its choice of wfd_video_formats.");
-        return ERROR_MALFORMED;
-    }
-
-    mSinkSupportsVideo = false;
-
-    if  (!(value == "none")) {
-        mSinkSupportsVideo = true;
-        if (!mSupportedSinkVideoFormats.parseFormatSpec(value.c_str())) {
-            ALOGE("Failed to parse sink provided wfd_video_formats (%s)",
-                  value.c_str());
-
-            return ERROR_MALFORMED;
-        }
-
-        if (!VideoFormats::PickBestFormat(
-                    mSupportedSinkVideoFormats,
-                    mSupportedSourceVideoFormats,
-                    &mChosenVideoResolutionType,
-                    &mChosenVideoResolutionIndex,
-                    &mChosenVideoProfile,
-                    &mChosenVideoLevel)) {
-            ALOGE("Sink and source share no commonly supported video "
-                  "formats.");
-
-            return ERROR_UNSUPPORTED;
-        }
-
-        size_t width, height, framesPerSecond;
-        bool interlaced;
-        CHECK(VideoFormats::GetConfiguration(
-                    mChosenVideoResolutionType,
-                    mChosenVideoResolutionIndex,
-                    &width,
-                    &height,
-                    &framesPerSecond,
-                    &interlaced));
-
-        ALOGI("Picked video resolution %zu x %zu %c%zu",
-              width, height, interlaced ? 'i' : 'p', framesPerSecond);
-
-        ALOGI("Picked AVC profile %d, level %d",
-              mChosenVideoProfile, mChosenVideoLevel);
-    } else {
-        ALOGI("Sink doesn't support video at all.");
-    }
-
-    if (!params->findParameter("wfd_audio_codecs", &value)) {
-        ALOGE("Sink doesn't report its choice of wfd_audio_codecs.");
-        return ERROR_MALFORMED;
-    }
-
-    mSinkSupportsAudio = false;
-
-    if  (!(value == "none")) {
-        mSinkSupportsAudio = true;
-
-        uint32_t modes;
-        GetAudioModes(value.c_str(), "AAC", &modes);
-
-        bool supportsAAC = (modes & 1) != 0;  // AAC 2ch 48kHz
-
-        GetAudioModes(value.c_str(), "LPCM", &modes);
-
-        bool supportsPCM = (modes & 2) != 0;  // LPCM 2ch 48kHz
-
-        if (supportsPCM
-                && property_get_bool("media.wfd.use-pcm-audio", false)) {
-            ALOGI("Using PCM audio.");
-            mUsingPCMAudio = true;
-        } else if (supportsAAC) {
-            ALOGI("Using AAC audio.");
-            mUsingPCMAudio = false;
-        } else if (supportsPCM) {
-            ALOGI("Using PCM audio.");
-            mUsingPCMAudio = true;
-        } else {
-            ALOGI("Sink doesn't support an audio format we do.");
-            return ERROR_UNSUPPORTED;
-        }
-    } else {
-        ALOGI("Sink doesn't support audio at all.");
-    }
-
-    if (!mSinkSupportsVideo && !mSinkSupportsAudio) {
-        ALOGE("Sink supports neither video nor audio...");
-        return ERROR_UNSUPPORTED;
-    }
-
-    mUsingHDCP = false;
-    if (!params->findParameter("wfd_content_protection", &value)) {
-        ALOGI("Sink doesn't appear to support content protection.");
-    } else if (value == "none") {
-        ALOGI("Sink does not support content protection.");
-    } else {
-        mUsingHDCP = true;
-
-        bool isHDCP2_0 = false;
-        if (value.startsWith("HDCP2.0 ")) {
-            isHDCP2_0 = true;
-        } else if (!value.startsWith("HDCP2.1 ")) {
-            ALOGE("malformed wfd_content_protection: '%s'", value.c_str());
-
-            return ERROR_MALFORMED;
-        }
-
-        int32_t hdcpPort;
-        if (!ParsedMessage::GetInt32Attribute(
-                    value.c_str() + 8, "port", &hdcpPort)
-                || hdcpPort < 1 || hdcpPort > 65535) {
-            return ERROR_MALFORMED;
-        }
-
-        mIsHDCP2_0 = isHDCP2_0;
-        mHDCPPort = hdcpPort;
-
-        status_t err = makeHDCP();
-        if (err != OK) {
-            ALOGE("Unable to instantiate HDCP component. "
-                  "Not using HDCP after all.");
-
-            mUsingHDCP = false;
-        }
-    }
-
-    return sendM4(sessionID);
-}
-
-status_t WifiDisplaySource::onReceiveM4Response(
-        int32_t sessionID, const sp<ParsedMessage> &msg) {
-    int32_t statusCode;
-    if (!msg->getStatusCode(&statusCode)) {
-        return ERROR_MALFORMED;
-    }
-
-    if (statusCode != 200) {
-        return ERROR_UNSUPPORTED;
-    }
-
-    if (mUsingHDCP && !mHDCPInitializationComplete) {
-        ALOGI("Deferring SETUP trigger until HDCP initialization completes.");
-
-        mSetupTriggerDeferred = true;
-        return OK;
-    }
-
-    return sendTrigger(sessionID, TRIGGER_SETUP);
-}
-
-status_t WifiDisplaySource::onReceiveM5Response(
-        int32_t /* sessionID */, const sp<ParsedMessage> &msg) {
-    int32_t statusCode;
-    if (!msg->getStatusCode(&statusCode)) {
-        return ERROR_MALFORMED;
-    }
-
-    if (statusCode != 200) {
-        return ERROR_UNSUPPORTED;
-    }
-
-    return OK;
-}
-
-status_t WifiDisplaySource::onReceiveM16Response(
-        int32_t sessionID, const sp<ParsedMessage> & /* msg */) {
-    // If only the response was required to include a "Session:" header...
-
-    CHECK_EQ(sessionID, mClientSessionID);
-
-    if (mClientInfo.mPlaybackSession != NULL) {
-        mClientInfo.mPlaybackSession->updateLiveness();
-    }
-
-    return OK;
-}
-
-void WifiDisplaySource::scheduleReaper() {
-    if (mReaperPending) {
-        return;
-    }
-
-    mReaperPending = true;
-    (new AMessage(kWhatReapDeadClients, this))->post(kReaperIntervalUs);
-}
-
-void WifiDisplaySource::scheduleKeepAlive(int32_t sessionID) {
-    // We need to send updates at least 5 secs before the timeout is set to
-    // expire, make sure the timeout is greater than 5 secs to begin with.
-    CHECK_GT(kPlaybackSessionTimeoutUs, 5000000ll);
-
-    sp<AMessage> msg = new AMessage(kWhatKeepAlive, this);
-    msg->setInt32("sessionID", sessionID);
-    msg->post(kPlaybackSessionTimeoutUs - 5000000ll);
-}
-
-status_t WifiDisplaySource::onReceiveClientData(const sp<AMessage> &msg) {
-    int32_t sessionID;
-    CHECK(msg->findInt32("sessionID", &sessionID));
-
-    sp<RefBase> obj;
-    CHECK(msg->findObject("data", &obj));
-
-    sp<ParsedMessage> data =
-        static_cast<ParsedMessage *>(obj.get());
-
-    ALOGV("session %d received '%s'",
-          sessionID, data->debugString().c_str());
-
-    AString method;
-    AString uri;
-    data->getRequestField(0, &method);
-
-    int32_t cseq;
-    if (!data->findInt32("cseq", &cseq)) {
-        sendErrorResponse(sessionID, "400 Bad Request", -1 /* cseq */);
-        return ERROR_MALFORMED;
-    }
-
-    if (method.startsWith("RTSP/")) {
-        // This is a response.
-
-        ResponseID id;
-        id.mSessionID = sessionID;
-        id.mCSeq = cseq;
-
-        ssize_t index = mResponseHandlers.indexOfKey(id);
-
-        if (index < 0) {
-            ALOGW("Received unsolicited server response, cseq %d", cseq);
-            return ERROR_MALFORMED;
-        }
-
-        HandleRTSPResponseFunc func = mResponseHandlers.valueAt(index);
-        mResponseHandlers.removeItemsAt(index);
-
-        status_t err = (this->*func)(sessionID, data);
-
-        if (err != OK) {
-            ALOGW("Response handler for session %d, cseq %d returned "
-                  "err %d (%s)",
-                  sessionID, cseq, err, strerror(-err));
-
-            return err;
-        }
-
-        return OK;
-    }
-
-    AString version;
-    data->getRequestField(2, &version);
-    if (!(version == AString("RTSP/1.0"))) {
-        sendErrorResponse(sessionID, "505 RTSP Version not supported", cseq);
-        return ERROR_UNSUPPORTED;
-    }
-
-    status_t err;
-    if (method == "OPTIONS") {
-        err = onOptionsRequest(sessionID, cseq, data);
-    } else if (method == "SETUP") {
-        err = onSetupRequest(sessionID, cseq, data);
-    } else if (method == "PLAY") {
-        err = onPlayRequest(sessionID, cseq, data);
-    } else if (method == "PAUSE") {
-        err = onPauseRequest(sessionID, cseq, data);
-    } else if (method == "TEARDOWN") {
-        err = onTeardownRequest(sessionID, cseq, data);
-    } else if (method == "GET_PARAMETER") {
-        err = onGetParameterRequest(sessionID, cseq, data);
-    } else if (method == "SET_PARAMETER") {
-        err = onSetParameterRequest(sessionID, cseq, data);
-    } else {
-        sendErrorResponse(sessionID, "405 Method Not Allowed", cseq);
-
-        err = ERROR_UNSUPPORTED;
-    }
-
-    return err;
-}
-
-status_t WifiDisplaySource::onOptionsRequest(
-        int32_t sessionID,
-        int32_t cseq,
-        const sp<ParsedMessage> &data) {
-    int32_t playbackSessionID;
-    sp<PlaybackSession> playbackSession =
-        findPlaybackSession(data, &playbackSessionID);
-
-    if (playbackSession != NULL) {
-        playbackSession->updateLiveness();
-    }
-
-    AString response = "RTSP/1.0 200 OK\r\n";
-    AppendCommonResponse(&response, cseq);
-
-    response.append(
-            "Public: org.wfa.wfd1.0, SETUP, TEARDOWN, PLAY, PAUSE, "
-            "GET_PARAMETER, SET_PARAMETER\r\n");
-
-    response.append("\r\n");
-
-    status_t err = mNetSession->sendRequest(sessionID, response.c_str());
-
-    if (err == OK) {
-        err = sendM3(sessionID);
-    }
-
-    return err;
-}
-
-status_t WifiDisplaySource::onSetupRequest(
-        int32_t sessionID,
-        int32_t cseq,
-        const sp<ParsedMessage> &data) {
-    CHECK_EQ(sessionID, mClientSessionID);
-    if (mClientInfo.mPlaybackSessionID != -1) {
-        // We only support a single playback session per client.
-        // This is due to the reversed keep-alive design in the wfd specs...
-        sendErrorResponse(sessionID, "400 Bad Request", cseq);
-        return ERROR_MALFORMED;
-    }
-
-    AString transport;
-    if (!data->findString("transport", &transport)) {
-        sendErrorResponse(sessionID, "400 Bad Request", cseq);
-        return ERROR_MALFORMED;
-    }
-
-    RTPSender::TransportMode rtpMode = RTPSender::TRANSPORT_UDP;
-
-    int clientRtp, clientRtcp;
-    if (transport.startsWith("RTP/AVP/TCP;")) {
-        AString interleaved;
-        if (ParsedMessage::GetAttribute(
-                    transport.c_str(), "interleaved", &interleaved)
-                && sscanf(interleaved.c_str(), "%d-%d",
-                          &clientRtp, &clientRtcp) == 2) {
-            rtpMode = RTPSender::TRANSPORT_TCP_INTERLEAVED;
-        } else {
-            bool badRequest = false;
-
-            AString clientPort;
-            if (!ParsedMessage::GetAttribute(
-                        transport.c_str(), "client_port", &clientPort)) {
-                badRequest = true;
-            } else if (sscanf(clientPort.c_str(), "%d-%d",
-                              &clientRtp, &clientRtcp) == 2) {
-            } else if (sscanf(clientPort.c_str(), "%d", &clientRtp) == 1) {
-                // No RTCP.
-                clientRtcp = -1;
-            } else {
-                badRequest = true;
-            }
-
-            if (badRequest) {
-                sendErrorResponse(sessionID, "400 Bad Request", cseq);
-                return ERROR_MALFORMED;
-            }
-
-            rtpMode = RTPSender::TRANSPORT_TCP;
-        }
-    } else if (transport.startsWith("RTP/AVP;unicast;")
-            || transport.startsWith("RTP/AVP/UDP;unicast;")) {
-        bool badRequest = false;
-
-        AString clientPort;
-        if (!ParsedMessage::GetAttribute(
-                    transport.c_str(), "client_port", &clientPort)) {
-            badRequest = true;
-        } else if (sscanf(clientPort.c_str(), "%d-%d",
-                          &clientRtp, &clientRtcp) == 2) {
-        } else if (sscanf(clientPort.c_str(), "%d", &clientRtp) == 1) {
-            // No RTCP.
-            clientRtcp = -1;
-        } else {
-            badRequest = true;
-        }
-
-        if (badRequest) {
-            sendErrorResponse(sessionID, "400 Bad Request", cseq);
-            return ERROR_MALFORMED;
-        }
-#if 1
-    // The older LG dongles doesn't specify client_port=xxx apparently.
-    } else if (transport == "RTP/AVP/UDP;unicast") {
-        clientRtp = 19000;
-        clientRtcp = -1;
-#endif
-    } else {
-        sendErrorResponse(sessionID, "461 Unsupported Transport", cseq);
-        return ERROR_UNSUPPORTED;
-    }
-
-    int32_t playbackSessionID = makeUniquePlaybackSessionID();
-
-    sp<AMessage> notify = new AMessage(kWhatPlaybackSessionNotify, this);
-    notify->setInt32("playbackSessionID", playbackSessionID);
-    notify->setInt32("sessionID", sessionID);
-
-    sp<PlaybackSession> playbackSession =
-        new PlaybackSession(
-                mOpPackageName, mNetSession, notify, mInterfaceAddr, mHDCP, mMediaPath.c_str());
-
-    looper()->registerHandler(playbackSession);
-
-    AString uri;
-    data->getRequestField(1, &uri);
-
-    if (strncasecmp("rtsp://", uri.c_str(), 7)) {
-        sendErrorResponse(sessionID, "400 Bad Request", cseq);
-        return ERROR_MALFORMED;
-    }
-
-    if (!(uri.startsWith("rtsp://") && uri.endsWith("/wfd1.0/streamid=0"))) {
-        sendErrorResponse(sessionID, "404 Not found", cseq);
-        return ERROR_MALFORMED;
-    }
-
-    RTPSender::TransportMode rtcpMode = RTPSender::TRANSPORT_UDP;
-    if (clientRtcp < 0) {
-        rtcpMode = RTPSender::TRANSPORT_NONE;
-    }
-
-    status_t err = playbackSession->init(
-            mClientInfo.mRemoteIP.c_str(),
-            clientRtp,
-            rtpMode,
-            clientRtcp,
-            rtcpMode,
-            mSinkSupportsAudio,
-            mUsingPCMAudio,
-            mSinkSupportsVideo,
-            mChosenVideoResolutionType,
-            mChosenVideoResolutionIndex,
-            mChosenVideoProfile,
-            mChosenVideoLevel);
-
-    if (err != OK) {
-        looper()->unregisterHandler(playbackSession->id());
-        playbackSession.clear();
-    }
-
-    switch (err) {
-        case OK:
-            break;
-        case -ENOENT:
-            sendErrorResponse(sessionID, "404 Not Found", cseq);
-            return err;
-        default:
-            sendErrorResponse(sessionID, "403 Forbidden", cseq);
-            return err;
-    }
-
-    mClientInfo.mPlaybackSessionID = playbackSessionID;
-    mClientInfo.mPlaybackSession = playbackSession;
-
-    AString response = "RTSP/1.0 200 OK\r\n";
-    AppendCommonResponse(&response, cseq, playbackSessionID);
-
-    if (rtpMode == RTPSender::TRANSPORT_TCP_INTERLEAVED) {
-        response.append(
-                AStringPrintf(
-                    "Transport: RTP/AVP/TCP;interleaved=%d-%d;",
-                    clientRtp, clientRtcp));
-    } else {
-        int32_t serverRtp = playbackSession->getRTPPort();
-
-        AString transportString = "UDP";
-        if (rtpMode == RTPSender::TRANSPORT_TCP) {
-            transportString = "TCP";
-        }
-
-        if (clientRtcp >= 0) {
-            response.append(
-                    AStringPrintf(
-                        "Transport: RTP/AVP/%s;unicast;client_port=%d-%d;"
-                        "server_port=%d-%d\r\n",
-                        transportString.c_str(),
-                        clientRtp, clientRtcp, serverRtp, serverRtp + 1));
-        } else {
-            response.append(
-                    AStringPrintf(
-                        "Transport: RTP/AVP/%s;unicast;client_port=%d;"
-                        "server_port=%d\r\n",
-                        transportString.c_str(),
-                        clientRtp, serverRtp));
-        }
-    }
-
-    response.append("\r\n");
-
-    err = mNetSession->sendRequest(sessionID, response.c_str());
-
-    if (err != OK) {
-        return err;
-    }
-
-    mState = AWAITING_CLIENT_PLAY;
-
-    scheduleReaper();
-    scheduleKeepAlive(sessionID);
-
-    return OK;
-}
-
-status_t WifiDisplaySource::onPlayRequest(
-        int32_t sessionID,
-        int32_t cseq,
-        const sp<ParsedMessage> &data) {
-    int32_t playbackSessionID;
-    sp<PlaybackSession> playbackSession =
-        findPlaybackSession(data, &playbackSessionID);
-
-    if (playbackSession == NULL) {
-        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
-        return ERROR_MALFORMED;
-    }
-
-    if (mState != AWAITING_CLIENT_PLAY
-     && mState != PAUSED_TO_PLAYING
-     && mState != PAUSED) {
-        ALOGW("Received PLAY request but we're in state %d", mState);
-
-        sendErrorResponse(
-                sessionID, "455 Method Not Valid in This State", cseq);
-
-        return INVALID_OPERATION;
-    }
-
-    ALOGI("Received PLAY request.");
-    if (mPlaybackSessionEstablished) {
-        finishPlay();
-    } else {
-        ALOGI("deferring PLAY request until session established.");
-    }
-
-    AString response = "RTSP/1.0 200 OK\r\n";
-    AppendCommonResponse(&response, cseq, playbackSessionID);
-    response.append("Range: npt=now-\r\n");
-    response.append("\r\n");
-
-    status_t err = mNetSession->sendRequest(sessionID, response.c_str());
-
-    if (err != OK) {
-        return err;
-    }
-
-    if (mState == PAUSED_TO_PLAYING || mPlaybackSessionEstablished) {
-        mState = PLAYING;
-        return OK;
-    }
-
-    CHECK_EQ(mState, AWAITING_CLIENT_PLAY);
-    mState = ABOUT_TO_PLAY;
-
-    return OK;
-}
-
-void WifiDisplaySource::finishPlay() {
-    const sp<PlaybackSession> &playbackSession =
-        mClientInfo.mPlaybackSession;
-
-    status_t err = playbackSession->play();
-    CHECK_EQ(err, (status_t)OK);
-}
-
-status_t WifiDisplaySource::onPauseRequest(
-        int32_t sessionID,
-        int32_t cseq,
-        const sp<ParsedMessage> &data) {
-    int32_t playbackSessionID;
-    sp<PlaybackSession> playbackSession =
-        findPlaybackSession(data, &playbackSessionID);
-
-    if (playbackSession == NULL) {
-        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
-        return ERROR_MALFORMED;
-    }
-
-    ALOGI("Received PAUSE request.");
-
-    if (mState != PLAYING_TO_PAUSED && mState != PLAYING) {
-        return INVALID_OPERATION;
-    }
-
-    status_t err = playbackSession->pause();
-    CHECK_EQ(err, (status_t)OK);
-
-    AString response = "RTSP/1.0 200 OK\r\n";
-    AppendCommonResponse(&response, cseq, playbackSessionID);
-    response.append("\r\n");
-
-    err = mNetSession->sendRequest(sessionID, response.c_str());
-
-    if (err != OK) {
-        return err;
-    }
-
-    mState = PAUSED;
-
-    return err;
-}
-
-status_t WifiDisplaySource::onTeardownRequest(
-        int32_t sessionID,
-        int32_t cseq,
-        const sp<ParsedMessage> &data) {
-    ALOGI("Received TEARDOWN request.");
-
-    int32_t playbackSessionID;
-    sp<PlaybackSession> playbackSession =
-        findPlaybackSession(data, &playbackSessionID);
-
-    if (playbackSession == NULL) {
-        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
-        return ERROR_MALFORMED;
-    }
-
-    AString response = "RTSP/1.0 200 OK\r\n";
-    AppendCommonResponse(&response, cseq, playbackSessionID);
-    response.append("Connection: close\r\n");
-    response.append("\r\n");
-
-    mNetSession->sendRequest(sessionID, response.c_str());
-
-    if (mState == AWAITING_CLIENT_TEARDOWN) {
-        CHECK(mStopReplyID != NULL);
-        finishStop();
-    } else {
-        mClient->onDisplayError(IRemoteDisplayClient::kDisplayErrorUnknown);
-    }
-
-    return OK;
-}
-
-void WifiDisplaySource::finishStop() {
-    ALOGV("finishStop");
-
-    mState = STOPPING;
-
-    disconnectClientAsync();
-}
-
-void WifiDisplaySource::finishStopAfterDisconnectingClient() {
-    ALOGV("finishStopAfterDisconnectingClient");
-
-    if (mHDCP != NULL) {
-        ALOGI("Initiating HDCP shutdown.");
-        mHDCP->shutdownAsync();
-        return;
-    }
-
-    finishStop2();
-}
-
-void WifiDisplaySource::finishStop2() {
-    ALOGV("finishStop2");
-
-    if (mHDCP != NULL) {
-        mHDCP->setObserver(NULL);
-        mHDCPObserver.clear();
-        mHDCP.clear();
-    }
-
-    if (mSessionID != 0) {
-        mNetSession->destroySession(mSessionID);
-        mSessionID = 0;
-    }
-
-    ALOGI("We're stopped.");
-    mState = STOPPED;
-
-    status_t err = OK;
-
-    sp<AMessage> response = new AMessage;
-    response->setInt32("err", err);
-    response->postReply(mStopReplyID);
-}
-
-status_t WifiDisplaySource::onGetParameterRequest(
-        int32_t sessionID,
-        int32_t cseq,
-        const sp<ParsedMessage> &data) {
-    int32_t playbackSessionID;
-    sp<PlaybackSession> playbackSession =
-        findPlaybackSession(data, &playbackSessionID);
-
-    if (playbackSession == NULL) {
-        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
-        return ERROR_MALFORMED;
-    }
-
-    playbackSession->updateLiveness();
-
-    AString response = "RTSP/1.0 200 OK\r\n";
-    AppendCommonResponse(&response, cseq, playbackSessionID);
-    response.append("\r\n");
-
-    status_t err = mNetSession->sendRequest(sessionID, response.c_str());
-    return err;
-}
-
-status_t WifiDisplaySource::onSetParameterRequest(
-        int32_t sessionID,
-        int32_t cseq,
-        const sp<ParsedMessage> &data) {
-    int32_t playbackSessionID;
-    sp<PlaybackSession> playbackSession =
-        findPlaybackSession(data, &playbackSessionID);
-
-    if (playbackSession == NULL) {
-        sendErrorResponse(sessionID, "454 Session Not Found", cseq);
-        return ERROR_MALFORMED;
-    }
-
-    if (strstr(data->getContent(), "wfd_idr_request\r\n")) {
-        playbackSession->requestIDRFrame();
-    }
-
-    playbackSession->updateLiveness();
-
-    AString response = "RTSP/1.0 200 OK\r\n";
-    AppendCommonResponse(&response, cseq, playbackSessionID);
-    response.append("\r\n");
-
-    status_t err = mNetSession->sendRequest(sessionID, response.c_str());
-    return err;
-}
-
-// static
-void WifiDisplaySource::AppendCommonResponse(
-        AString *response, int32_t cseq, int32_t playbackSessionID) {
-    time_t now = time(NULL);
-    struct tm *now2 = gmtime(&now);
-    char buf[128];
-    strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S %z", now2);
-
-    response->append("Date: ");
-    response->append(buf);
-    response->append("\r\n");
-
-    response->append(AStringPrintf("Server: %s\r\n", sUserAgent.c_str()));
-
-    if (cseq >= 0) {
-        response->append(AStringPrintf("CSeq: %d\r\n", cseq));
-    }
-
-    if (playbackSessionID >= 0ll) {
-        response->append(
-                AStringPrintf(
-                    "Session: %d;timeout=%lld\r\n",
-                    playbackSessionID, kPlaybackSessionTimeoutSecs));
-    }
-}
-
-void WifiDisplaySource::sendErrorResponse(
-        int32_t sessionID,
-        const char *errorDetail,
-        int32_t cseq) {
-    AString response;
-    response.append("RTSP/1.0 ");
-    response.append(errorDetail);
-    response.append("\r\n");
-
-    AppendCommonResponse(&response, cseq);
-
-    response.append("\r\n");
-
-    mNetSession->sendRequest(sessionID, response.c_str());
-}
-
-int32_t WifiDisplaySource::makeUniquePlaybackSessionID() const {
-    return rand();
-}
-
-sp<WifiDisplaySource::PlaybackSession> WifiDisplaySource::findPlaybackSession(
-        const sp<ParsedMessage> &data, int32_t *playbackSessionID) const {
-    if (!data->findInt32("session", playbackSessionID)) {
-        // XXX the older dongles do not always include a "Session:" header.
-        *playbackSessionID = mClientInfo.mPlaybackSessionID;
-        return mClientInfo.mPlaybackSession;
-    }
-
-    if (*playbackSessionID != mClientInfo.mPlaybackSessionID) {
-        return NULL;
-    }
-
-    return mClientInfo.mPlaybackSession;
-}
-
-void WifiDisplaySource::disconnectClientAsync() {
-    ALOGV("disconnectClient");
-
-    if (mClientInfo.mPlaybackSession == NULL) {
-        disconnectClient2();
-        return;
-    }
-
-    if (mClientInfo.mPlaybackSession != NULL) {
-        ALOGV("Destroying PlaybackSession");
-        mClientInfo.mPlaybackSession->destroyAsync();
-    }
-}
-
-void WifiDisplaySource::disconnectClient2() {
-    ALOGV("disconnectClient2");
-
-    if (mClientInfo.mPlaybackSession != NULL) {
-        looper()->unregisterHandler(mClientInfo.mPlaybackSession->id());
-        mClientInfo.mPlaybackSession.clear();
-    }
-
-    if (mClientSessionID != 0) {
-        mNetSession->destroySession(mClientSessionID);
-        mClientSessionID = 0;
-    }
-
-    mClient->onDisplayDisconnected();
-
-    finishStopAfterDisconnectingClient();
-}
-
-struct WifiDisplaySource::HDCPObserver : public BnHDCPObserver {
-    explicit HDCPObserver(const sp<AMessage> &notify);
-
-    virtual void notify(
-            int msg, int ext1, int ext2, const Parcel *obj);
-
-private:
-    sp<AMessage> mNotify;
-
-    DISALLOW_EVIL_CONSTRUCTORS(HDCPObserver);
-};
-
-WifiDisplaySource::HDCPObserver::HDCPObserver(
-        const sp<AMessage> &notify)
-    : mNotify(notify) {
-}
-
-void WifiDisplaySource::HDCPObserver::notify(
-        int msg, int ext1, int ext2, const Parcel * /* obj */) {
-    sp<AMessage> notify = mNotify->dup();
-    notify->setInt32("msg", msg);
-    notify->setInt32("ext1", ext1);
-    notify->setInt32("ext2", ext2);
-    notify->post();
-}
-
-status_t WifiDisplaySource::makeHDCP() {
-    sp<IServiceManager> sm = defaultServiceManager();
-    sp<IBinder> binder = sm->getService(String16("media.player"));
-
-    sp<IMediaPlayerService> service =
-        interface_cast<IMediaPlayerService>(binder);
-
-    CHECK(service != NULL);
-
-    mHDCP = service->makeHDCP(true /* createEncryptionModule */);
-
-    if (mHDCP == NULL) {
-        return ERROR_UNSUPPORTED;
-    }
-
-    sp<AMessage> notify = new AMessage(kWhatHDCPNotify, this);
-    mHDCPObserver = new HDCPObserver(notify);
-
-    status_t err = mHDCP->setObserver(mHDCPObserver);
-
-    if (err != OK) {
-        ALOGE("Failed to set HDCP observer.");
-
-        mHDCPObserver.clear();
-        mHDCP.clear();
-
-        return err;
-    }
-
-    ALOGI("Initiating HDCP negotiation w/ host %s:%d",
-            mClientInfo.mRemoteIP.c_str(), mHDCPPort);
-
-    err = mHDCP->initAsync(mClientInfo.mRemoteIP.c_str(), mHDCPPort);
-
-    if (err != OK) {
-        return err;
-    }
-
-    return OK;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/wifi-display/source/WifiDisplaySource.h b/media/libstagefright/wifi-display/source/WifiDisplaySource.h
deleted file mode 100644
index c25a675..0000000
--- a/media/libstagefright/wifi-display/source/WifiDisplaySource.h
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Copyright 2012, 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 WIFI_DISPLAY_SOURCE_H_
-
-#define WIFI_DISPLAY_SOURCE_H_
-
-#include "VideoFormats.h"
-
-#include <media/stagefright/foundation/AHandler.h>
-#include <media/stagefright/foundation/ANetworkSession.h>
-
-#include <netinet/in.h>
-
-#include <utils/String16.h>
-
-namespace android {
-
-struct AReplyToken;
-struct IHDCP;
-class IRemoteDisplayClient;
-struct ParsedMessage;
-
-// Represents the RTSP server acting as a wifi display source.
-// Manages incoming connections, sets up Playback sessions as necessary.
-struct WifiDisplaySource : public AHandler {
-    static const unsigned kWifiDisplayDefaultPort = 7236;
-
-    WifiDisplaySource(
-            const String16 &opPackageName,
-            const sp<ANetworkSession> &netSession,
-            const sp<IRemoteDisplayClient> &client,
-            const char *path = NULL);
-
-    status_t start(const char *iface);
-    status_t stop();
-
-    status_t pause();
-    status_t resume();
-
-protected:
-    virtual ~WifiDisplaySource();
-    virtual void onMessageReceived(const sp<AMessage> &msg);
-
-private:
-    struct PlaybackSession;
-    struct HDCPObserver;
-
-    enum State {
-        INITIALIZED,
-        AWAITING_CLIENT_CONNECTION,
-        AWAITING_CLIENT_SETUP,
-        AWAITING_CLIENT_PLAY,
-        ABOUT_TO_PLAY,
-        PLAYING,
-        PLAYING_TO_PAUSED,
-        PAUSED,
-        PAUSED_TO_PLAYING,
-        AWAITING_CLIENT_TEARDOWN,
-        STOPPING,
-        STOPPED,
-    };
-
-    enum {
-        kWhatStart,
-        kWhatRTSPNotify,
-        kWhatStop,
-        kWhatPause,
-        kWhatResume,
-        kWhatReapDeadClients,
-        kWhatPlaybackSessionNotify,
-        kWhatKeepAlive,
-        kWhatHDCPNotify,
-        kWhatFinishStop2,
-        kWhatTeardownTriggerTimedOut,
-    };
-
-    struct ResponseID {
-        int32_t mSessionID;
-        int32_t mCSeq;
-
-        bool operator<(const ResponseID &other) const {
-            return mSessionID < other.mSessionID
-                || (mSessionID == other.mSessionID
-                        && mCSeq < other.mCSeq);
-        }
-    };
-
-    typedef status_t (WifiDisplaySource::*HandleRTSPResponseFunc)(
-            int32_t sessionID, const sp<ParsedMessage> &msg);
-
-    static const int64_t kReaperIntervalUs = 1000000ll;
-
-    // We request that the dongle send us a "TEARDOWN" in order to
-    // perform an orderly shutdown. We're willing to wait up to 2 secs
-    // for this message to arrive, after that we'll force a disconnect
-    // instead.
-    static const int64_t kTeardownTriggerTimeouSecs = 2;
-
-    static const int64_t kPlaybackSessionTimeoutSecs = 30;
-
-    static const int64_t kPlaybackSessionTimeoutUs =
-        kPlaybackSessionTimeoutSecs * 1000000ll;
-
-    static const AString sUserAgent;
-
-    String16 mOpPackageName;
-
-    State mState;
-    VideoFormats mSupportedSourceVideoFormats;
-    sp<ANetworkSession> mNetSession;
-    sp<IRemoteDisplayClient> mClient;
-    AString mMediaPath;
-    struct in_addr mInterfaceAddr;
-    int32_t mSessionID;
-
-    sp<AReplyToken> mStopReplyID;
-
-    AString mWfdClientRtpPorts;
-    int32_t mChosenRTPPort;  // extracted from "wfd_client_rtp_ports"
-
-    bool mSinkSupportsVideo;
-    VideoFormats mSupportedSinkVideoFormats;
-
-    VideoFormats::ResolutionType mChosenVideoResolutionType;
-    size_t mChosenVideoResolutionIndex;
-    VideoFormats::ProfileType mChosenVideoProfile;
-    VideoFormats::LevelType mChosenVideoLevel;
-
-    bool mSinkSupportsAudio;
-
-    bool mUsingPCMAudio;
-    int32_t mClientSessionID;
-
-    struct ClientInfo {
-        AString mRemoteIP;
-        AString mLocalIP;
-        int32_t mLocalPort;
-        int32_t mPlaybackSessionID;
-        sp<PlaybackSession> mPlaybackSession;
-    };
-    ClientInfo mClientInfo;
-
-    bool mReaperPending;
-
-    int32_t mNextCSeq;
-
-    KeyedVector<ResponseID, HandleRTSPResponseFunc> mResponseHandlers;
-
-    // HDCP specific section >>>>
-    bool mUsingHDCP;
-    bool mIsHDCP2_0;
-    int32_t mHDCPPort;
-    sp<IHDCP> mHDCP;
-    sp<HDCPObserver> mHDCPObserver;
-
-    bool mHDCPInitializationComplete;
-    bool mSetupTriggerDeferred;
-
-    bool mPlaybackSessionEstablished;
-
-    status_t makeHDCP();
-    // <<<< HDCP specific section
-
-    status_t sendM1(int32_t sessionID);
-    status_t sendM3(int32_t sessionID);
-    status_t sendM4(int32_t sessionID);
-
-    enum TriggerType {
-        TRIGGER_SETUP,
-        TRIGGER_TEARDOWN,
-        TRIGGER_PAUSE,
-        TRIGGER_PLAY,
-    };
-
-    // M5
-    status_t sendTrigger(int32_t sessionID, TriggerType triggerType);
-
-    status_t sendM16(int32_t sessionID);
-
-    status_t onReceiveM1Response(
-            int32_t sessionID, const sp<ParsedMessage> &msg);
-
-    status_t onReceiveM3Response(
-            int32_t sessionID, const sp<ParsedMessage> &msg);
-
-    status_t onReceiveM4Response(
-            int32_t sessionID, const sp<ParsedMessage> &msg);
-
-    status_t onReceiveM5Response(
-            int32_t sessionID, const sp<ParsedMessage> &msg);
-
-    status_t onReceiveM16Response(
-            int32_t sessionID, const sp<ParsedMessage> &msg);
-
-    void registerResponseHandler(
-            int32_t sessionID, int32_t cseq, HandleRTSPResponseFunc func);
-
-    status_t onReceiveClientData(const sp<AMessage> &msg);
-
-    status_t onOptionsRequest(
-            int32_t sessionID,
-            int32_t cseq,
-            const sp<ParsedMessage> &data);
-
-    status_t onSetupRequest(
-            int32_t sessionID,
-            int32_t cseq,
-            const sp<ParsedMessage> &data);
-
-    status_t onPlayRequest(
-            int32_t sessionID,
-            int32_t cseq,
-            const sp<ParsedMessage> &data);
-
-    status_t onPauseRequest(
-            int32_t sessionID,
-            int32_t cseq,
-            const sp<ParsedMessage> &data);
-
-    status_t onTeardownRequest(
-            int32_t sessionID,
-            int32_t cseq,
-            const sp<ParsedMessage> &data);
-
-    status_t onGetParameterRequest(
-            int32_t sessionID,
-            int32_t cseq,
-            const sp<ParsedMessage> &data);
-
-    status_t onSetParameterRequest(
-            int32_t sessionID,
-            int32_t cseq,
-            const sp<ParsedMessage> &data);
-
-    void sendErrorResponse(
-            int32_t sessionID,
-            const char *errorDetail,
-            int32_t cseq);
-
-    static void AppendCommonResponse(
-            AString *response, int32_t cseq, int32_t playbackSessionID = -1ll);
-
-    void scheduleReaper();
-    void scheduleKeepAlive(int32_t sessionID);
-
-    int32_t makeUniquePlaybackSessionID() const;
-
-    sp<PlaybackSession> findPlaybackSession(
-            const sp<ParsedMessage> &data, int32_t *playbackSessionID) const;
-
-    void finishStop();
-    void disconnectClientAsync();
-    void disconnectClient2();
-    void finishStopAfterDisconnectingClient();
-    void finishStop2();
-
-    void finishPlay();
-
-    DISALLOW_EVIL_CONSTRUCTORS(WifiDisplaySource);
-};
-
-}  // namespace android
-
-#endif  // WIFI_DISPLAY_SOURCE_H_
diff --git a/media/libstagefright/xmlparser/Android.bp b/media/libstagefright/xmlparser/Android.bp
index 3507284..a4fa342 100644
--- a/media/libstagefright/xmlparser/Android.bp
+++ b/media/libstagefright/xmlparser/Android.bp
@@ -15,10 +15,7 @@
 
     shared_libs: [
         "libexpat",
-        "libutils",
         "liblog",
-        "libcutils",
-        "libstagefright_foundation",
         "libstagefright_omx_utils",
     ],
 
diff --git a/media/mtp/MtpFfsHandle.cpp b/media/mtp/MtpFfsHandle.cpp
index 89b20e5..965985d 100644
--- a/media/mtp/MtpFfsHandle.cpp
+++ b/media/mtp/MtpFfsHandle.cpp
@@ -94,8 +94,11 @@
     __le32 fs_count;
     __le32 hs_count;
     __le32 ss_count;
+    __le32 os_count;
     struct func_desc fs_descs, hs_descs;
     struct ss_func_desc ss_descs;
+    struct usb_os_desc_header os_header;
+    struct usb_ext_compat_desc os_desc;
 } __attribute__((packed));
 
 const struct usb_interface_descriptor mtp_interface_desc = {
@@ -261,6 +264,31 @@
     },
 };
 
+struct usb_os_desc_header mtp_os_desc_header = {
+    .interface = htole32(1),
+    .dwLength = htole32(sizeof(usb_os_desc_header) + sizeof(usb_ext_compat_desc)),
+    .bcdVersion = htole16(1),
+    .wIndex = htole16(4),
+    .bCount = htole16(1),
+    .Reserved = htole16(0),
+};
+
+struct usb_ext_compat_desc mtp_os_desc_compat = {
+    .bFirstInterfaceNumber = 0,
+    .Reserved1 = htole32(1),
+    .CompatibleID = { 'M', 'T', 'P' },
+    .SubCompatibleID = {0},
+    .Reserved2 = {0},
+};
+
+struct usb_ext_compat_desc ptp_os_desc_compat = {
+    .bFirstInterfaceNumber = 0,
+    .Reserved1 = htole32(1),
+    .CompatibleID = { 'P', 'T', 'P' },
+    .SubCompatibleID = {0},
+    .Reserved2 = {0},
+};
+
 struct mtp_device_status {
     uint16_t  wLength;
     uint16_t  wCode;
@@ -336,13 +364,16 @@
     v2_descriptor.header.magic = htole32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2);
     v2_descriptor.header.length = htole32(sizeof(v2_descriptor));
     v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC |
-                                 FUNCTIONFS_HAS_SS_DESC;
+                                 FUNCTIONFS_HAS_SS_DESC | FUNCTIONFS_HAS_MS_OS_DESC;
     v2_descriptor.fs_count = 4;
     v2_descriptor.hs_count = 4;
     v2_descriptor.ss_count = 7;
+    v2_descriptor.os_count = 1;
     v2_descriptor.fs_descs = mPtp ? ptp_fs_descriptors : mtp_fs_descriptors;
     v2_descriptor.hs_descs = mPtp ? ptp_hs_descriptors : mtp_hs_descriptors;
     v2_descriptor.ss_descs = mPtp ? ptp_ss_descriptors : mtp_ss_descriptors;
+    v2_descriptor.os_header = mtp_os_desc_header;
+    v2_descriptor.os_desc = mPtp ? ptp_os_desc_compat : mtp_os_desc_compat;
 
     if (mControl < 0) { // might have already done this before
         mControl.reset(TEMP_FAILURE_RETRY(open(FFS_MTP_EP0, O_RDWR)));
diff --git a/media/ndk/Android.bp b/media/ndk/Android.bp
index 0d48de1..116f156 100644
--- a/media/ndk/Android.bp
+++ b/media/ndk/Android.bp
@@ -69,7 +69,6 @@
         "libmedia",
         "libmedia_jni",
         "libmediadrm",
-        "libskia",
         "libstagefright",
         "libstagefright_foundation",
         "liblog",
diff --git a/media/ndk/OWNERS b/media/ndk/OWNERS
new file mode 100644
index 0000000..43e4bb3
--- /dev/null
+++ b/media/ndk/OWNERS
@@ -0,0 +1 @@
+marcone@google.com
diff --git a/media/utils/OWNERS b/media/utils/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/media/utils/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/services/OWNERS b/services/OWNERS
index d500dce..d5d00da 100644
--- a/services/OWNERS
+++ b/services/OWNERS
@@ -1,4 +1,4 @@
 elaurent@google.com
 etalvala@google.com
-gkasten@android.com
+gkasten@google.com
 hunga@google.com
diff --git a/services/audioflinger/Android.mk b/services/audioflinger/Android.mk
index d0454d4..7419e64 100644
--- a/services/audioflinger/Android.mk
+++ b/services/audioflinger/Android.mk
@@ -51,6 +51,7 @@
     libmedialogservice \
     libmediautils \
     libnbaio \
+    libnblog \
     libpowermanager \
     libserviceutility \
     libmediautils \
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 39f04fb..79e540a 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -1566,7 +1566,7 @@
 
 // ----------------------------------------------------------------------------
 
-sp<IAudioRecord> AudioFlinger::openRecord(
+sp<media::IAudioRecord> AudioFlinger::openRecord(
         audio_io_handle_t input,
         uint32_t sampleRate,
         audio_format_t format,
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index 63898a0..dff94d2 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -33,7 +33,6 @@
 #include <media/IAudioFlinger.h>
 #include <media/IAudioFlingerClient.h>
 #include <media/IAudioTrack.h>
-#include <media/IAudioRecord.h>
 #include <media/AudioSystem.h>
 #include <media/AudioTrack.h>
 #include <media/MmapStreamInterface.h>
@@ -72,10 +71,12 @@
 
 #include <powermanager/IPowerManager.h>
 
-#include <media/nbaio/NBLog.h>
+#include <media/nblog/NBLog.h>
 #include <private/media/AudioEffectShared.h>
 #include <private/media/AudioTrackShared.h>
 
+#include "android/media/BnAudioRecord.h"
+
 namespace android {
 
 class AudioMixer;
@@ -129,7 +130,7 @@
                                 status_t *status /*non-NULL*/,
                                 audio_port_handle_t portId);
 
-    virtual sp<IAudioRecord> openRecord(
+    virtual sp<media::IAudioRecord> openRecord(
                                 audio_io_handle_t input,
                                 uint32_t sampleRate,
                                 audio_format_t format,
@@ -556,10 +557,10 @@
         virtual void        pause();
         virtual status_t    attachAuxEffect(int effectId);
         virtual status_t    setParameters(const String8& keyValuePairs);
-        virtual VolumeShaper::Status applyVolumeShaper(
-                const sp<VolumeShaper::Configuration>& configuration,
-                const sp<VolumeShaper::Operation>& operation) override;
-        virtual sp<VolumeShaper::State> getVolumeShaperState(int id) override;
+        virtual media::VolumeShaper::Status applyVolumeShaper(
+                const sp<media::VolumeShaper::Configuration>& configuration,
+                const sp<media::VolumeShaper::Operation>& operation) override;
+        virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
         virtual status_t    getTimestamp(AudioTimestamp& timestamp);
         virtual void        signal(); // signal playback thread for a change in control block
 
@@ -571,15 +572,13 @@
     };
 
     // server side of the client's IAudioRecord
-    class RecordHandle : public android::BnAudioRecord {
+    class RecordHandle : public android::media::BnAudioRecord {
     public:
         explicit RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
         virtual             ~RecordHandle();
-        virtual status_t    start(int /*AudioSystem::sync_event_t*/ event,
-                audio_session_t triggerSession);
-        virtual void        stop();
-        virtual status_t onTransact(
-            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
+        virtual binder::Status    start(int /*AudioSystem::sync_event_t*/ event,
+                int /*audio_session_t*/ triggerSession);
+        virtual binder::Status   stop();
     private:
         const sp<RecordThread::RecordTrack> mRecordTrack;
 
diff --git a/services/audioflinger/FastMixer.cpp b/services/audioflinger/FastMixer.cpp
index c10fa05..ace586c 100644
--- a/services/audioflinger/FastMixer.cpp
+++ b/services/audioflinger/FastMixer.cpp
@@ -138,8 +138,6 @@
 
 void FastMixer::onStateChange()
 {
-    // log that audio was turned on/off
-    LOG_AUDIO_STATE();
     const FastMixerState * const current = (const FastMixerState *) mCurrent;
     const FastMixerState * const previous = (const FastMixerState *) mPrevious;
     FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
@@ -336,7 +334,13 @@
 
 void FastMixer::onWork()
 {
-    LOG_HIST_TS();
+    // TODO: pass an ID parameter to indicate which time series we want to write to in NBLog.cpp
+    // Or: pass both of these into a single call with a boolean
+    if (mIsWarm) {
+        LOG_HIST_TS();
+    } else {
+        LOG_AUDIO_STATE();
+    }
     const FastMixerState * const current = (const FastMixerState *) mCurrent;
     FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
     const FastMixerState::Command command = mCommand;
diff --git a/services/audioflinger/FastMixerState.h b/services/audioflinger/FastMixerState.h
index 5a55c7a..2be1e91 100644
--- a/services/audioflinger/FastMixerState.h
+++ b/services/audioflinger/FastMixerState.h
@@ -21,7 +21,7 @@
 #include <system/audio.h>
 #include <media/ExtendedAudioBufferProvider.h>
 #include <media/nbaio/NBAIO.h>
-#include <media/nbaio/NBLog.h>
+#include <media/nblog/NBLog.h>
 #include "FastThreadState.h"
 
 namespace android {
diff --git a/services/audioflinger/FastThreadState.h b/services/audioflinger/FastThreadState.h
index f18f846..54c0dc6 100644
--- a/services/audioflinger/FastThreadState.h
+++ b/services/audioflinger/FastThreadState.h
@@ -19,7 +19,7 @@
 
 #include "Configuration.h"
 #include <stdint.h>
-#include <media/nbaio/NBLog.h>
+#include <media/nblog/NBLog.h>
 
 namespace android {
 
diff --git a/services/audioflinger/OWNERS b/services/audioflinger/OWNERS
index 703e4d2..d02d9e0 100644
--- a/services/audioflinger/OWNERS
+++ b/services/audioflinger/OWNERS
@@ -1,3 +1,4 @@
 hunga@google.com
 jmtrivi@google.com
 mnaganov@google.com
+gkasten@google.com
diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h
index 1c1a989..946d88f 100644
--- a/services/audioflinger/PlaybackTracks.h
+++ b/services/audioflinger/PlaybackTracks.h
@@ -82,11 +82,11 @@
     virtual bool        isFastTrack() const { return (mFlags & AUDIO_OUTPUT_FLAG_FAST) != 0; }
 
 // implement volume handling.
-   VolumeShaper::Status applyVolumeShaper(
-                                const sp<VolumeShaper::Configuration>& configuration,
-                                const sp<VolumeShaper::Operation>& operation);
-sp<VolumeShaper::State> getVolumeShaperState(int id);
-    sp<VolumeHandler>   getVolumeHandler() { return mVolumeHandler; }
+    media::VolumeShaper::Status applyVolumeShaper(
+                                const sp<media::VolumeShaper::Configuration>& configuration,
+                                const sp<media::VolumeShaper::Operation>& operation);
+    sp<media::VolumeShaper::State> getVolumeShaperState(int id);
+    sp<media::VolumeHandler>   getVolumeHandler() { return mVolumeHandler; }
 
 protected:
     // for numerous
@@ -163,7 +163,7 @@
 
     ExtendedTimestamp  mSinkTimestamp;
 
-    sp<VolumeHandler>  mVolumeHandler; // handles multiple VolumeShaper configs and operations
+    sp<media::VolumeHandler>  mVolumeHandler; // handles multiple VolumeShaper configs and operations
 
 private:
     // The following fields are only for fast tracks, and should be in a subclass
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index e202ca4..1e88ab2 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -2638,6 +2638,7 @@
 // shared by MIXER and DIRECT, overridden by DUPLICATING
 ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
 {
+    LOG_HIST_TS();
     mInWrite = true;
     ssize_t bytesWritten;
     const size_t offset = mCurrentWriteLength - mBytesRemaining;
@@ -3116,6 +3117,10 @@
 
                     threadLoop_standby();
 
+                    // This is where we go into standby
+                    if (!mStandby) {
+                        LOG_AUDIO_STATE();
+                    }
                     mStandby = true;
                 }
 
@@ -5449,7 +5454,7 @@
         mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
         mOffloadUnderrunPosition(~0LL)
 {
-    //FIXME: mStandby should be set to true by ThreadBase constructor
+    //FIXME: mStandby should be set to true by ThreadBase constructo
     mStandby = true;
     mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
 }
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index dd2b89b..b685e1b 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -485,6 +485,7 @@
                 // Updated by updateSuspendedSessions_l() only.
                 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
                                         mSuspendedSessions;
+                // TODO: add comment and adjust size as needed
                 static const size_t     kLogSize = 4 * 1024;
                 sp<NBLog::Writer>       mNBLogWriter;
                 bool                    mSystemReady;
@@ -984,6 +985,7 @@
     sp<NBAIO_Source>        mTeeSource;
 #endif
     uint32_t                mScreenState;   // cached copy of gScreenState
+    // TODO: add comment and adjust size as needed
     static const size_t     kFastMixerLogSize = 8 * 1024;
     sp<NBLog::Writer>       mFastMixerNBLogWriter;
 
@@ -1456,6 +1458,7 @@
             // If a fast capture is present, the Pipe as IMemory, otherwise clear
             sp<IMemory>                         mPipeMemory;
 
+            // TODO: add comment and adjust size as needed
             static const size_t                 kFastCaptureLogSize = 4 * 1024;
             sp<NBLog::Writer>                   mFastCaptureNBLogWriter;
 
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index 0f25153..50c0e23 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -52,6 +52,7 @@
 
 namespace android {
 
+using media::VolumeShaper;
 // ----------------------------------------------------------------------------
 //      TrackBase
 // ----------------------------------------------------------------------------
@@ -399,7 +400,7 @@
     mAuxEffectId(0), mHasVolumeController(false),
     mPresentationCompleteFrames(0),
     mFrameMap(16 /* sink-frame-to-track-frame map memory */),
-    mVolumeHandler(new VolumeHandler(sampleRate)),
+    mVolumeHandler(new media::VolumeHandler(sampleRate)),
     // mSinkTimestamp
     mFastIndex(-1),
     mCachedVolume(1.0),
@@ -1561,14 +1562,16 @@
     mRecordTrack->destroy();
 }
 
-status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
-        audio_session_t triggerSession) {
+binder::Status AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
+        int /*audio_session_t*/ triggerSession) {
     ALOGV("RecordHandle::start()");
-    return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
+    return binder::Status::fromStatusT(
+        mRecordTrack->start((AudioSystem::sync_event_t)event, (audio_session_t) triggerSession));
 }
 
-void AudioFlinger::RecordHandle::stop() {
+binder::Status AudioFlinger::RecordHandle::stop() {
     stop_nonvirtual();
+    return binder::Status::ok();
 }
 
 void AudioFlinger::RecordHandle::stop_nonvirtual() {
@@ -1576,12 +1579,6 @@
     mRecordTrack->stop();
 }
 
-status_t AudioFlinger::RecordHandle::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    return BnAudioRecord::onTransact(code, data, reply, flags);
-}
-
 // ----------------------------------------------------------------------------
 
 // RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
diff --git a/services/audioflinger/TypedLogger.h b/services/audioflinger/TypedLogger.h
index 909af09..cae74b1 100644
--- a/services/audioflinger/TypedLogger.h
+++ b/services/audioflinger/TypedLogger.h
@@ -18,7 +18,9 @@
 #ifndef ANDROID_TYPED_LOGGER_H
 #define ANDROID_TYPED_LOGGER_H
 
-#include <media/nbaio/NBLog.h>
+// This is the client API for the typed logger.
+
+#include <media/nblog/NBLog.h>
 #include <algorithm>
 
 /*
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
index 8593444..4d3c3b5 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
@@ -46,17 +46,17 @@
     for (int i = 0; i < NUM_STRATEGIES; i++) {
         mStrategyMutedByDevice[i] = false;
     }
-    if (port != NULL) {
-        port->pickAudioProfile(mSamplingRate, mChannelMask, mFormat);
-        if (port->mGains.size() > 0) {
-            port->mGains[0]->getDefaultConfig(&mGain);
+    if (mPort.get() != nullptr) {
+        mPort->pickAudioProfile(mSamplingRate, mChannelMask, mFormat);
+        if (mPort->mGains.size() > 0) {
+            mPort->mGains[0]->getDefaultConfig(&mGain);
         }
     }
 }
 
 audio_module_handle_t AudioOutputDescriptor::getModuleHandle() const
 {
-    return mPort->getModuleHandle();
+    return mPort.get() != nullptr ? mPort->getModuleHandle() : AUDIO_MODULE_HANDLE_NONE;
 }
 
 audio_port_handle_t AudioOutputDescriptor::getId() const
@@ -175,9 +175,9 @@
     dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
 }
 
-void AudioOutputDescriptor::toAudioPort(
-                                                    struct audio_port *port) const
+void AudioOutputDescriptor::toAudioPort(struct audio_port *port) const
 {
+    // Should not be called for duplicated ports, see SwAudioOutputDescriptor::toAudioPortConfig.
     mPort->toAudioPort(port);
     port->id = mId;
     port->ext.mix.hw_module = getModuleHandle();
diff --git a/services/audiopolicy/config/audio_policy_configuration.xml b/services/audiopolicy/config/audio_policy_configuration.xml
index 7af2f81..73efe8e 100644
--- a/services/audiopolicy/config/audio_policy_configuration.xml
+++ b/services/audiopolicy/config/audio_policy_configuration.xml
@@ -163,37 +163,16 @@
                        sources="primary output,deep_buffer,compressed_offload,BT SCO Headset Mic,Telephony Rx"/>
                 <route type="mix" sink="Wired Headphones"
                        sources="primary output,deep_buffer,compressed_offload,BT SCO Headset Mic,Telephony Rx"/>
-                <route type="mix" sink="Telephony Tx"
-                       sources="voice_tx"/>
                 <route type="mix" sink="primary input"
                        sources="Built-In Mic,Built-In Back Mic,Wired Headset Mic,BT SCO Headset Mic"/>
                 <route type="mix" sink="Telephony Tx"
-                       sources="Built-In Mic,Built-In Back Mic,Wired Headset Mic,BT SCO Headset Mic"/>
+                       sources="Built-In Mic,Built-In Back Mic,Wired Headset Mic,BT SCO Headset Mic, voice_tx"/>
                 <route type="mix" sink="voice_rx"
                        sources="Telephony Rx"/>
             </routes>
 
         </module>
 
-        <!-- HDMI Audio HAL -->
-        <module description="HDMI Audio HAL" name="hdmi" version="2.0">
-            <mixPorts>
-                <mixPort name="hdmi output" role="source">
-                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT" samplingRates="48000"/>
-                </mixPort>
-            </mixPorts>
-            <devicePorts>
-                <devicePort tagName="HDMI Out" type="AUDIO_DEVICE_OUT_AUX_DIGITAL" role="sink">
-                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
-                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
-                </devicePort>
-            </devicePorts>
-            <routes>
-                <route type="mix" sink="HDMI Out"
-                       sources="hdmi output"/>
-            </routes>
-        </module>
-
         <!-- A2dp Audio HAL -->
         <xi:include href="a2dp_audio_policy_configuration.xml"/>
 
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index bdfaf2f..906e05a 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -874,48 +874,6 @@
     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
     status_t status;
 
-#ifdef AUDIO_POLICY_TEST
-    if (mCurOutput != 0) {
-        ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
-                mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
-
-        if (mTestOutputs[mCurOutput] == 0) {
-            ALOGV("getOutput() opening test output");
-            sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
-                                                                               mpClientInterface);
-            outputDesc->mDevice = mTestDevice;
-            outputDesc->mLatency = mTestLatencyMs;
-            outputDesc->mFlags =
-                    (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
-            outputDesc->mRefCount[stream] = 0;
-            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
-            config.sample_rate = mTestSamplingRate;
-            config.channel_mask = mTestChannels;
-            config.format = mTestFormat;
-            if (offloadInfo != NULL) {
-                config.offload_info = *offloadInfo;
-            }
-            status = mpClientInterface->openOutput(0,
-                                                  &mTestOutputs[mCurOutput],
-                                                  &config,
-                                                  &outputDesc->mDevice,
-                                                  String8(""),
-                                                  &outputDesc->mLatency,
-                                                  outputDesc->mFlags);
-            if (status == NO_ERROR) {
-                outputDesc->mSamplingRate = config.sample_rate;
-                outputDesc->mFormat = config.format;
-                outputDesc->mChannelMask = config.channel_mask;
-                AudioParameter outputCmd = AudioParameter();
-                outputCmd.addInt(String8("set_id"),mCurOutput);
-                mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
-                addOutput(mTestOutputs[mCurOutput], outputDesc);
-            }
-        }
-        return mTestOutputs[mCurOutput];
-    }
-#endif //AUDIO_POLICY_TEST
-
     // open a direct output if required by specified parameters
     //force direct flag if offload flag is set: offloading implies a direct output stream
     // and all common behaviors are driven by checking only the direct flag
@@ -1094,7 +1052,7 @@
         flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
         output = selectOutput(outputs, flags, format);
     }
-    ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
+    ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d, "
             "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
 
     return output;
@@ -1454,19 +1412,6 @@
         return;
     }
 
-#ifdef AUDIO_POLICY_TEST
-    int testIndex = testOutputIndex(output);
-    if (testIndex != 0) {
-        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
-        if (outputDesc->isActive()) {
-            mpClientInterface->closeOutput(output);
-            removeOutput(output);
-            mTestOutputs[testIndex] = 0;
-        }
-        return;
-    }
-#endif //AUDIO_POLICY_TEST
-
     // Routing
     mOutputRoutes.removeRoute(session);
 
@@ -1685,7 +1630,7 @@
         } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
             profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
         } else { // fail
-            ALOGW("getInputForDevice() could not find profile for device 0x%X,"
+            ALOGW("getInputForDevice() could not find profile for device 0x%X, "
                   "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
                     device, samplingRate, format, channelMask, flags);
             return input;
@@ -3581,9 +3526,6 @@
 
 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
     :
-#ifdef AUDIO_POLICY_TEST
-    Thread(false),
-#endif //AUDIO_POLICY_TEST
     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
     mA2dpSuspended(false),
     mAudioPortGeneration(1),
@@ -3824,37 +3766,10 @@
     ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
 
     updateDevicesAndOutputs();
-
-#ifdef AUDIO_POLICY_TEST
-    if (mPrimaryOutput != 0) {
-        AudioParameter outputCmd = AudioParameter();
-        outputCmd.addInt(String8("set_id"), 0);
-        mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
-
-        mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
-        mTestSamplingRate = 44100;
-        mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
-        mTestChannels =  AUDIO_CHANNEL_OUT_STEREO;
-        mTestLatencyMs = 0;
-        mCurOutput = 0;
-        mDirectOutput = false;
-        for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
-            mTestOutputs[i] = 0;
-        }
-
-        const size_t SIZE = 256;
-        char buffer[SIZE];
-        snprintf(buffer, SIZE, "AudioPolicyManagerTest");
-        run(buffer, ANDROID_PRIORITY_AUDIO);
-    }
-#endif //AUDIO_POLICY_TEST
 }
 
 AudioPolicyManager::~AudioPolicyManager()
 {
-#ifdef AUDIO_POLICY_TEST
-    exit();
-#endif //AUDIO_POLICY_TEST
    for (size_t i = 0; i < mOutputs.size(); i++) {
         mpClientInterface->closeOutput(mOutputs.keyAt(i));
    }
@@ -3873,164 +3788,6 @@
     return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
 }
 
-#ifdef AUDIO_POLICY_TEST
-bool AudioPolicyManager::threadLoop()
-{
-    ALOGV("entering threadLoop()");
-    while (!exitPending())
-    {
-        String8 command;
-        int valueInt;
-        String8 value;
-
-        Mutex::Autolock _l(mLock);
-        mWaitWorkCV.waitRelative(mLock, milliseconds(50));
-
-        command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
-        AudioParameter param = AudioParameter(command);
-
-        if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
-            valueInt != 0) {
-            ALOGV("Test command %s received", command.string());
-            String8 target;
-            if (param.get(String8("target"), target) != NO_ERROR) {
-                target = "Manager";
-            }
-            if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_output"));
-                mCurOutput = valueInt;
-            }
-            if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_direct"));
-                if (value == "false") {
-                    mDirectOutput = false;
-                } else if (value == "true") {
-                    mDirectOutput = true;
-                }
-            }
-            if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_input"));
-                mTestInput = valueInt;
-            }
-
-            if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_format"));
-                int format = AUDIO_FORMAT_INVALID;
-                if (value == "PCM 16 bits") {
-                    format = AUDIO_FORMAT_PCM_16_BIT;
-                } else if (value == "PCM 8 bits") {
-                    format = AUDIO_FORMAT_PCM_8_BIT;
-                } else if (value == "Compressed MP3") {
-                    format = AUDIO_FORMAT_MP3;
-                }
-                if (format != AUDIO_FORMAT_INVALID) {
-                    if (target == "Manager") {
-                        mTestFormat = format;
-                    } else if (mTestOutputs[mCurOutput] != 0) {
-                        AudioParameter outputParam = AudioParameter();
-                        outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
-                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
-                    }
-                }
-            }
-            if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_channels"));
-                int channels = 0;
-
-                if (value == "Channels Stereo") {
-                    channels =  AUDIO_CHANNEL_OUT_STEREO;
-                } else if (value == "Channels Mono") {
-                    channels =  AUDIO_CHANNEL_OUT_MONO;
-                }
-                if (channels != 0) {
-                    if (target == "Manager") {
-                        mTestChannels = channels;
-                    } else if (mTestOutputs[mCurOutput] != 0) {
-                        AudioParameter outputParam = AudioParameter();
-                        outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
-                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
-                    }
-                }
-            }
-            if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_sampleRate"));
-                if (valueInt >= 0 && valueInt <= 96000) {
-                    int samplingRate = valueInt;
-                    if (target == "Manager") {
-                        mTestSamplingRate = samplingRate;
-                    } else if (mTestOutputs[mCurOutput] != 0) {
-                        AudioParameter outputParam = AudioParameter();
-                        outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
-                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
-                    }
-                }
-            }
-
-            if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_reopen"));
-
-                mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
-
-                audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
-
-                removeOutput(mPrimaryOutput->mIoHandle);
-                sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
-                                                                               mpClientInterface);
-                outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
-                audio_config_t config = AUDIO_CONFIG_INITIALIZER;
-                config.sample_rate = outputDesc->mSamplingRate;
-                config.channel_mask = outputDesc->mChannelMask;
-                config.format = outputDesc->mFormat;
-                audio_io_handle_t handle;
-                status_t status = mpClientInterface->openOutput(moduleHandle,
-                                                                &handle,
-                                                                &config,
-                                                                &outputDesc->mDevice,
-                                                                String8(""),
-                                                                &outputDesc->mLatency,
-                                                                outputDesc->mFlags);
-                if (status != NO_ERROR) {
-                    ALOGE("Failed to reopen hardware output stream, "
-                        "samplingRate: %d, format %d, channels %d",
-                        outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
-                } else {
-                    outputDesc->mSamplingRate = config.sample_rate;
-                    outputDesc->mChannelMask = config.channel_mask;
-                    outputDesc->mFormat = config.format;
-                    mPrimaryOutput = outputDesc;
-                    AudioParameter outputCmd = AudioParameter();
-                    outputCmd.addInt(String8("set_id"), 0);
-                    mpClientInterface->setParameters(handle, outputCmd.toString());
-                    addOutput(handle, outputDesc);
-                }
-            }
-
-
-            mpClientInterface->setParameters(0, String8("test_cmd_policy="));
-        }
-    }
-    return false;
-}
-
-void AudioPolicyManager::exit()
-{
-    {
-        AutoMutex _l(mLock);
-        requestExit();
-        mWaitWorkCV.signal();
-    }
-    requestExitAndWait();
-}
-
-int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
-{
-    for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
-        if (output == mTestOutputs[i]) return i;
-    }
-    return 0;
-}
-#endif //AUDIO_POLICY_TEST
-
 // ---
 
 void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h
index 82c4c35..7ba0669 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.h
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h
@@ -76,10 +76,6 @@
 // ----------------------------------------------------------------------------
 
 class AudioPolicyManager : public AudioPolicyInterface, public AudioPolicyManagerObserver
-
-#ifdef AUDIO_POLICY_TEST
-    , public Thread
-#endif //AUDIO_POLICY_TEST
 {
 
 public:
@@ -419,11 +415,6 @@
         {
             return mEffects.getMaxEffectsMemory();
         }
-#ifdef AUDIO_POLICY_TEST
-        virtual     bool        threadLoop();
-                    void        exit();
-        int testOutputIndex(audio_io_handle_t output);
-#endif //AUDIO_POLICY_TEST
 
         SortedVector<audio_io_handle_t> getOutputsForDevice(audio_devices_t device,
                                                             const SwAudioOutputCollection& openOutputs);
@@ -574,22 +565,6 @@
         AudioPolicyMixCollection mPolicyMixes; // list of registered mixes
         audio_io_handle_t mMusicEffectOutput;     // output selected for music effects
 
-
-#ifdef AUDIO_POLICY_TEST
-        Mutex   mLock;
-        Condition mWaitWorkCV;
-
-        int             mCurOutput;
-        bool            mDirectOutput;
-        audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
-        int             mTestInput;
-        uint32_t        mTestDevice;
-        uint32_t        mTestSamplingRate;
-        uint32_t        mTestFormat;
-        uint32_t        mTestChannels;
-        uint32_t        mTestLatencyMs;
-#endif //AUDIO_POLICY_TEST
-
         uint32_t nextAudioPortGeneration();
 
         // Audio Policy Engine Interface.
diff --git a/services/camera/libcameraservice/api1/client2/JpegProcessor.cpp b/services/camera/libcameraservice/api1/client2/JpegProcessor.cpp
old mode 100644
new mode 100755
index d8b7af2..d1bbdaf
--- a/services/camera/libcameraservice/api1/client2/JpegProcessor.cpp
+++ b/services/camera/libcameraservice/api1/client2/JpegProcessor.cpp
@@ -395,7 +395,7 @@
     }
 
     // Read JFIF segment markers, skip over segment data
-    size = 0;
+    size = MARKER_LENGTH; //jump SOI;
     while (size <= maxSize - MARKER_LENGTH) {
         segment_t *segment = (segment_t*)(jpegBuffer + size);
         uint8_t type = checkJpegMarker(segment->marker);
diff --git a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
index c03e8a2..f985382 100644
--- a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
+++ b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
@@ -193,7 +193,7 @@
          */
         SurfaceMap surfaceMap;
         Vector<int32_t> outputStreamIds;
-        for (sp<Surface> surface : request.mSurfaceList) {
+        for (const sp<Surface>& surface : request.mSurfaceList) {
             if (surface == 0) continue;
 
             sp<IGraphicBufferProducer> gbp = surface->getIGraphicBufferProducer();
diff --git a/services/camera/libcameraservice/device3/Camera3OutputStream.cpp b/services/camera/libcameraservice/device3/Camera3OutputStream.cpp
index dcaefe3..0a02a32 100644
--- a/services/camera/libcameraservice/device3/Camera3OutputStream.cpp
+++ b/services/camera/libcameraservice/device3/Camera3OutputStream.cpp
@@ -728,7 +728,7 @@
         const std::vector<sp<GraphicBuffer>>& removedBuffers) {
     sp<Camera3StreamBufferFreedListener> callback = mBufferFreedListener.promote();
     if (callback != nullptr) {
-        for (auto gb : removedBuffers) {
+        for (const auto& gb : removedBuffers) {
             callback->onBufferFreed(mId, gb->handle);
         }
     }
diff --git a/services/camera/libcameraservice/device3/Camera3SharedOutputStream.cpp b/services/camera/libcameraservice/device3/Camera3SharedOutputStream.cpp
index 5051711..fb7472b 100644
--- a/services/camera/libcameraservice/device3/Camera3SharedOutputStream.cpp
+++ b/services/camera/libcameraservice/device3/Camera3SharedOutputStream.cpp
@@ -200,7 +200,7 @@
         // Called before shared buffer queue is constructed.
         *usage = getPresetConsumerUsage();
 
-        for (auto surface : mSurfaces) {
+        for (const auto& surface : mSurfaces) {
             if (surface != nullptr) {
                 res = getEndpointUsageForSurface(&u, surface);
                 *usage |= u;
diff --git a/services/mediaanalytics/OWNERS b/services/mediaanalytics/OWNERS
new file mode 100644
index 0000000..9af258b
--- /dev/null
+++ b/services/mediaanalytics/OWNERS
@@ -0,0 +1 @@
+essick@google.com
diff --git a/services/mediacodec/android.hardware.media.omx@1.0-service.rc b/services/mediacodec/android.hardware.media.omx@1.0-service.rc
index ec51d65..3ef9a85 100644
--- a/services/mediacodec/android.hardware.media.omx@1.0-service.rc
+++ b/services/mediacodec/android.hardware.media.omx@1.0-service.rc
@@ -1,4 +1,4 @@
-service mediacodec /vendor/bin/hw/android.hardware.media.omx@1.0-service
+service vendor.media.omx /vendor/bin/hw/android.hardware.media.omx@1.0-service
     class main
     user mediacodec
     group camera drmrpc mediadrm
diff --git a/services/mediaextractor/Android.mk b/services/mediaextractor/Android.mk
index 1ebb7ff..2f7b7f7 100644
--- a/services/mediaextractor/Android.mk
+++ b/services/mediaextractor/Android.mk
@@ -14,6 +14,20 @@
 LOCAL_REQUIRED_MODULES_arm := mediaextractor.policy
 LOCAL_REQUIRED_MODULES_arm64 := mediaextractor.policy
 LOCAL_REQUIRED_MODULES_x86 := mediaextractor.policy
+
+# extractor libraries
+LOCAL_REQUIRED_MODULES := \
+    libaacextractor \
+    libamrextractor \
+    libflacextractor \
+    libmidiextractor \
+    libmkvextractor \
+    libmp3extractor \
+    libmp4extractor \
+    libmpeg2extractor \
+    liboggextractor \
+    libwavextractor \
+
 LOCAL_SRC_FILES := main_extractorservice.cpp
 LOCAL_SHARED_LIBRARIES := libmedia libmediaextractorservice libbinder libutils \
     liblog libbase libicuuc libavservices_minijail
diff --git a/services/mediaextractor/MediaExtractorService.cpp b/services/mediaextractor/MediaExtractorService.cpp
index 08cbef6..50a4191 100644
--- a/services/mediaextractor/MediaExtractorService.cpp
+++ b/services/mediaextractor/MediaExtractorService.cpp
@@ -33,17 +33,18 @@
 
     sp<DataSource> localSource = DataSource::CreateFromIDataSource(remoteSource);
 
-    sp<IMediaExtractor> ret = MediaExtractor::CreateFromService(localSource, mime);
+    sp<MediaExtractor> extractor = MediaExtractor::CreateFromService(localSource, mime);
 
     ALOGV("extractor service created %p (%s)",
-            ret.get(),
-            ret == NULL ? "" : ret->name());
+            extractor.get(),
+            extractor == nullptr ? "" : extractor->name());
 
-    if (ret != NULL) {
+    if (extractor != nullptr) {
+        sp<IMediaExtractor> ret = extractor->asIMediaExtractor();
         registerMediaExtractor(ret, localSource, mime);
+        return ret;
     }
-
-    return ret;
+    return nullptr;
 }
 
 sp<IDataSource> MediaExtractorService::makeIDataSource(int fd, int64_t offset, int64_t length)
diff --git a/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy b/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy
index d1278a9..438a332 100644
--- a/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy
+++ b/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy
@@ -33,6 +33,12 @@
 # for FileSource
 readlinkat: 1
 
+# for dynamically loading extractors
+getdents64: 1
+readlinkat: 1
+pread64: 1
+mremap: 1
+
 # for attaching to debuggerd on process crash
 tgkill: 1
 rt_sigprocmask: 1
diff --git a/services/mediaextractor/seccomp_policy/mediaextractor-x86.policy b/services/mediaextractor/seccomp_policy/mediaextractor-x86.policy
index 3b37f92..ede108e 100644
--- a/services/mediaextractor/seccomp_policy/mediaextractor-x86.policy
+++ b/services/mediaextractor/seccomp_policy/mediaextractor-x86.policy
@@ -39,6 +39,12 @@
 nanosleep: 1
 getrandom: 1
 
+# for dynamically loading extractors
+getdents64: 1
+readlinkat: 1
+pread64: 1
+mremap: 1
+
 # for FileSource
 readlinkat: 1
 _llseek: 1
diff --git a/services/medialog/Android.mk b/services/medialog/Android.mk
index 423b186..4f2630e 100644
--- a/services/medialog/Android.mk
+++ b/services/medialog/Android.mk
@@ -4,7 +4,7 @@
 
 LOCAL_SRC_FILES := MediaLogService.cpp IMediaLogService.cpp
 
-LOCAL_SHARED_LIBRARIES := libbinder libutils liblog libnbaio libaudioutils
+LOCAL_SHARED_LIBRARIES := libbinder libutils liblog libnbaio libnblog libaudioutils
 
 LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
 
diff --git a/services/medialog/MediaLogService.cpp b/services/medialog/MediaLogService.cpp
index a5512e1..1be5544 100644
--- a/services/medialog/MediaLogService.cpp
+++ b/services/medialog/MediaLogService.cpp
@@ -20,19 +20,25 @@
 #include <sys/mman.h>
 #include <utils/Log.h>
 #include <binder/PermissionCache.h>
-#include <media/nbaio/NBLog.h>
+#include <media/nblog/NBLog.h>
 #include <private/android_filesystem_config.h>
 #include "MediaLogService.h"
 
 namespace android {
 
- static const char kDeadlockedString[] = "MediaLogService may be deadlocked\n";
+static const char kDeadlockedString[] = "MediaLogService may be deadlocked\n";
+
+// mMerger, mMergeReader, and mMergeThread all point to the same location in memory
+// mMergerShared. This is the local memory FIFO containing data merged from all
+// individual thread FIFOs in shared memory. mMergeThread is used to periodically
+// call NBLog::Merger::merge() to collect the data and write it to the FIFO, and call
+// NBLog::MergeReader::getAndProcessSnapshot to process the merged data.
 MediaLogService::MediaLogService() :
     BnMediaLogService(),
     mMergerShared((NBLog::Shared*) malloc(NBLog::Timeline::sharedSize(kMergeBufferSize))),
     mMerger(mMergerShared, kMergeBufferSize),
     mMergeReader(mMergerShared, kMergeBufferSize, mMerger),
-    mMergeThread(new NBLog::MergeThread(mMerger))
+    mMergeThread(new NBLog::MergeThread(mMerger, mMergeReader))
 {
     mMergeThread->run("MergeThread");
 }
@@ -123,15 +129,10 @@
                 } else {
                     ALOGI("%s:", namedReader.name());
                 }
-                // TODO This code is for testing, remove it when done
-                // namedReader.reader()->dump(fd, 0 /*indent*/);
             }
-
             mLock.unlock();
         }
     }
-
-    // FIXME request merge to make sure log is up to date
     mMergeReader.dump(fd);
     return NO_ERROR;
 }
diff --git a/services/medialog/MediaLogService.h b/services/medialog/MediaLogService.h
index 39d9cc0..c945d1f 100644
--- a/services/medialog/MediaLogService.h
+++ b/services/medialog/MediaLogService.h
@@ -19,7 +19,7 @@
 
 #include <binder/BinderService.h>
 #include <media/IMediaLogService.h>
-#include <media/nbaio/NBLog.h>
+#include <media/nblog/NBLog.h>
 
 namespace android {
 
diff --git a/services/medialog/OWNERS b/services/medialog/OWNERS
index fb8b8ee..21723ba 100644
--- a/services/medialog/OWNERS
+++ b/services/medialog/OWNERS
@@ -1,3 +1,3 @@
 elaurent@google.com
-gkasten@android.com
+gkasten@google.com
 hunga@google.com
diff --git a/services/minijail/OWNERS b/services/minijail/OWNERS
new file mode 100644
index 0000000..19f4f9f
--- /dev/null
+++ b/services/minijail/OWNERS
@@ -0,0 +1,2 @@
+jorgelo@google.com
+marcone@google.com
diff --git a/services/oboeservice/AAudioClientTracker.cpp b/services/oboeservice/AAudioClientTracker.cpp
index 75392bd..a3d5ea1 100644
--- a/services/oboeservice/AAudioClientTracker.cpp
+++ b/services/oboeservice/AAudioClientTracker.cpp
@@ -172,12 +172,12 @@
 
         {
             std::lock_guard<std::mutex> lock(mLock);
-            for (auto serviceStream : mStreams) {
+            for (const auto& serviceStream : mStreams) {
                 streamsToClose.insert(serviceStream);
             }
         }
 
-        for (auto serviceStream : streamsToClose) {
+        for (const auto& serviceStream : streamsToClose) {
             aaudio_handle_t handle = serviceStream->getHandle();
             ALOGW("AAudioClientTracker::binderDied() close abandoned stream 0x%08X\n", handle);
             aaudioService->closeStream(handle);
@@ -200,7 +200,7 @@
     }
 
     result << "  client: pid = " << mProcessId << " has " << mStreams.size() << " streams\n";
-    for (auto serviceStream : mStreams) {
+    for (const auto& serviceStream : mStreams) {
         result << "     stream: 0x" << std::hex << serviceStream->getHandle() << std::dec << "\n";
     }
 
diff --git a/tools/OWNERS b/tools/OWNERS
index 6dcb035..f9cb567 100644
--- a/tools/OWNERS
+++ b/tools/OWNERS
@@ -1 +1 @@
-gkasten@android.com
+gkasten@google.com
diff --git a/tools/resampler_tools/OWNERS b/tools/resampler_tools/OWNERS
new file mode 100644
index 0000000..b4a6798
--- /dev/null
+++ b/tools/resampler_tools/OWNERS
@@ -0,0 +1 @@
+hunga@google.com