Merge "Using requested video scaling mode in NuPlayer"
diff --git a/camera/CameraUtils.cpp b/camera/CameraUtils.cpp
index 04244ac..5cd2717 100644
--- a/camera/CameraUtils.cpp
+++ b/camera/CameraUtils.cpp
@@ -44,7 +44,7 @@
     }
 
     camera_metadata_ro_entry_t entryFacing = staticInfo.find(ANDROID_LENS_FACING);
-    if (entry.count == 0) {
+    if (entryFacing.count == 0) {
         ALOGE("%s: Can't find android.lens.facing in static metadata!", __FUNCTION__);
         return INVALID_OPERATION;
     }
diff --git a/camera/ICamera.cpp b/camera/ICamera.cpp
index 9943be6..93f8342 100644
--- a/camera/ICamera.cpp
+++ b/camera/ICamera.cpp
@@ -54,7 +54,7 @@
 class BpCamera: public BpInterface<ICamera>
 {
 public:
-    BpCamera(const sp<IBinder>& impl)
+    explicit BpCamera(const sp<IBinder>& impl)
         : BpInterface<ICamera>(impl)
     {
     }
diff --git a/camera/ICameraClient.cpp b/camera/ICameraClient.cpp
index 179a341..bda122d 100644
--- a/camera/ICameraClient.cpp
+++ b/camera/ICameraClient.cpp
@@ -33,7 +33,7 @@
 class BpCameraClient: public BpInterface<ICameraClient>
 {
 public:
-    BpCameraClient(const sp<IBinder>& impl)
+    explicit BpCameraClient(const sp<IBinder>& impl)
         : BpInterface<ICameraClient>(impl)
     {
     }
diff --git a/camera/ICameraRecordingProxy.cpp b/camera/ICameraRecordingProxy.cpp
index 3dc0ffb..1562601 100644
--- a/camera/ICameraRecordingProxy.cpp
+++ b/camera/ICameraRecordingProxy.cpp
@@ -35,7 +35,7 @@
 class BpCameraRecordingProxy: public BpInterface<ICameraRecordingProxy>
 {
 public:
-    BpCameraRecordingProxy(const sp<IBinder>& impl)
+    explicit BpCameraRecordingProxy(const sp<IBinder>& impl)
         : BpInterface<ICameraRecordingProxy>(impl)
     {
     }
diff --git a/camera/ICameraRecordingProxyListener.cpp b/camera/ICameraRecordingProxyListener.cpp
index cf848fc..8139736 100644
--- a/camera/ICameraRecordingProxyListener.cpp
+++ b/camera/ICameraRecordingProxyListener.cpp
@@ -30,7 +30,7 @@
 class BpCameraRecordingProxyListener: public BpInterface<ICameraRecordingProxyListener>
 {
 public:
-    BpCameraRecordingProxyListener(const sp<IBinder>& impl)
+    explicit BpCameraRecordingProxyListener(const sp<IBinder>& impl)
         : BpInterface<ICameraRecordingProxyListener>(impl)
     {
     }
diff --git a/camera/ICameraService.cpp b/camera/ICameraService.cpp
index b359f57..f52fc64 100644
--- a/camera/ICameraService.cpp
+++ b/camera/ICameraService.cpp
@@ -89,7 +89,7 @@
 class BpCameraService: public BpInterface<ICameraService>
 {
 public:
-    BpCameraService(const sp<IBinder>& impl)
+    explicit BpCameraService(const sp<IBinder>& impl)
         : BpInterface<ICameraService>(impl)
     {
     }
diff --git a/camera/ICameraServiceListener.cpp b/camera/ICameraServiceListener.cpp
index 0010325..0bbff7e 100644
--- a/camera/ICameraServiceListener.cpp
+++ b/camera/ICameraServiceListener.cpp
@@ -37,7 +37,7 @@
 {
 
 public:
-    BpCameraServiceListener(const sp<IBinder>& impl)
+    explicit BpCameraServiceListener(const sp<IBinder>& impl)
         : BpInterface<ICameraServiceListener>(impl)
     {
     }
diff --git a/camera/ICameraServiceProxy.cpp b/camera/ICameraServiceProxy.cpp
index 06a5afb..a9d0836 100644
--- a/camera/ICameraServiceProxy.cpp
+++ b/camera/ICameraServiceProxy.cpp
@@ -26,14 +26,25 @@
 
 class BpCameraServiceProxy: public BpInterface<ICameraServiceProxy> {
 public:
-    BpCameraServiceProxy(const sp<IBinder>& impl) : BpInterface<ICameraServiceProxy>(impl) {}
+    explicit BpCameraServiceProxy(const sp<IBinder>& impl)
+        : BpInterface<ICameraServiceProxy>(impl) {}
 
     virtual void pingForUserUpdate() {
-        Parcel data, reply;
+        Parcel data;
         data.writeInterfaceToken(ICameraServiceProxy::getInterfaceDescriptor());
-        remote()->transact(BnCameraServiceProxy::PING_FOR_USER_UPDATE, data, &reply,
+        remote()->transact(BnCameraServiceProxy::PING_FOR_USER_UPDATE, data, nullptr,
                 IBinder::FLAG_ONEWAY);
     }
+
+    virtual void notifyCameraState(String16 cameraId, CameraState newCameraState) {
+        Parcel data;
+        data.writeInterfaceToken(ICameraServiceProxy::getInterfaceDescriptor());
+        data.writeString16(cameraId);
+        data.writeInt32(newCameraState);
+        remote()->transact(BnCameraServiceProxy::NOTIFY_CAMERA_STATE, data, nullptr,
+                IBinder::FLAG_ONEWAY);
+    }
+
 };
 
 
@@ -47,9 +58,16 @@
             pingForUserUpdate();
             return NO_ERROR;
         } break;
+        case NOTIFY_CAMERA_STATE: {
+            CHECK_INTERFACE(ICameraServiceProxy, data, reply);
+            String16 cameraId = data.readString16();
+            CameraState newCameraState =
+                static_cast<CameraState>(data.readInt32());
+            notifyCameraState(cameraId, newCameraState);
+            return NO_ERROR;
+        } break;
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
 }
 }; // namespace android
-
diff --git a/camera/camera2/ICameraDeviceCallbacks.cpp b/camera/camera2/ICameraDeviceCallbacks.cpp
index f599879..d694a45 100644
--- a/camera/camera2/ICameraDeviceCallbacks.cpp
+++ b/camera/camera2/ICameraDeviceCallbacks.cpp
@@ -43,7 +43,7 @@
 class BpCameraDeviceCallbacks: public BpInterface<ICameraDeviceCallbacks>
 {
 public:
-    BpCameraDeviceCallbacks(const sp<IBinder>& impl)
+    explicit BpCameraDeviceCallbacks(const sp<IBinder>& impl)
         : BpInterface<ICameraDeviceCallbacks>(impl)
     {
     }
diff --git a/camera/camera2/ICameraDeviceUser.cpp b/camera/camera2/ICameraDeviceUser.cpp
index d2dc200..1aca242 100644
--- a/camera/camera2/ICameraDeviceUser.cpp
+++ b/camera/camera2/ICameraDeviceUser.cpp
@@ -49,7 +49,8 @@
     WAIT_UNTIL_IDLE,
     FLUSH,
     PREPARE,
-    TEAR_DOWN
+    TEAR_DOWN,
+    PREPARE2
 };
 
 namespace {
@@ -68,7 +69,7 @@
 class BpCameraDeviceUser : public BpInterface<ICameraDeviceUser>
 {
 public:
-    BpCameraDeviceUser(const sp<IBinder>& impl)
+    explicit BpCameraDeviceUser(const sp<IBinder>& impl)
         : BpInterface<ICameraDeviceUser>(impl)
     {
     }
@@ -366,6 +367,21 @@
         return reply.readInt32();
     }
 
+    virtual status_t prepare2(int maxCount, int streamId)
+    {
+        ALOGV("prepare2");
+        Parcel data, reply;
+
+        data.writeInterfaceToken(ICameraDeviceUser::getInterfaceDescriptor());
+        data.writeInt32(maxCount);
+        data.writeInt32(streamId);
+
+        remote()->transact(PREPARE2, data, &reply);
+
+        reply.readExceptionCode();
+        return reply.readInt32();
+    }
+
     virtual status_t tearDown(int streamId)
     {
         ALOGV("tearDown");
@@ -592,7 +608,14 @@
             reply->writeInt32(tearDown(streamId));
             return NO_ERROR;
         } break;
-
+        case PREPARE2: {
+            CHECK_INTERFACE(ICameraDeviceUser, data, reply);
+            int maxCount = data.readInt32();
+            int streamId = data.readInt32();
+            reply->writeNoException();
+            reply->writeInt32(prepare2(maxCount, streamId));
+            return NO_ERROR;
+        } break;
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/camera/tests/Android.mk b/camera/tests/Android.mk
index 3777d94..de18df85 100644
--- a/camera/tests/Android.mk
+++ b/camera/tests/Android.mk
@@ -21,6 +21,7 @@
 	CameraBinderTests.cpp
 
 LOCAL_SHARED_LIBRARIES := \
+	liblog \
 	libutils \
 	libcutils \
 	libcamera_metadata \
diff --git a/cmds/stagefright/Android.mk b/cmds/stagefright/Android.mk
index 20c0094..b79abce 100644
--- a/cmds/stagefright/Android.mk
+++ b/cmds/stagefright/Android.mk
@@ -9,7 +9,7 @@
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright libmedia libutils libbinder libstagefright_foundation \
-        libjpeg libgui libcutils liblog
+	libjpeg libgui libcutils liblog
 
 LOCAL_C_INCLUDES:= \
 	frameworks/av/media/libstagefright \
@@ -31,8 +31,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:=         \
-        SineSource.cpp    \
-        record.cpp
+	SineSource.cpp    \
+	record.cpp
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libstagefright_foundation
@@ -55,8 +55,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:=         \
-        SineSource.cpp    \
-        recordvideo.cpp
+	SineSource.cpp    \
+	recordvideo.cpp
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libstagefright_foundation
@@ -80,8 +80,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:=         \
-        SineSource.cpp    \
-        audioloop.cpp
+	SineSource.cpp    \
+	audioloop.cpp
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libstagefright_foundation
@@ -108,7 +108,7 @@
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libgui \
-        libstagefright_foundation libmedia libcutils
+	libstagefright_foundation libmedia libcutils
 
 LOCAL_C_INCLUDES:= \
 	frameworks/av/media/libstagefright \
@@ -128,11 +128,11 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:=         \
-        sf2.cpp    \
+	sf2.cpp    \
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libstagefright_foundation \
-        libmedia libgui libcutils libui
+	libmedia libgui libcutils libui
 
 LOCAL_C_INCLUDES:= \
 	frameworks/av/media/libstagefright \
@@ -152,12 +152,12 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:=               \
-        codec.cpp               \
-        SimplePlayer.cpp        \
+	codec.cpp               \
+	SimplePlayer.cpp        \
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libstagefright_foundation \
-        libmedia libgui libcutils libui
+	libmedia libgui libcutils libui
 
 LOCAL_C_INCLUDES:= \
 	frameworks/av/media/libstagefright \
@@ -220,11 +220,11 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:=               \
-        muxer.cpp            \
+	muxer.cpp            \
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libstagefright_foundation \
-        libmedia libgui libcutils libui libc
+	libmedia libgui libcutils libui libc
 
 LOCAL_C_INCLUDES:= \
 	frameworks/av/media/libstagefright \
diff --git a/cmds/stagefright/audioloop.cpp b/cmds/stagefright/audioloop.cpp
index 6e9e6ec..67017eb 100644
--- a/cmds/stagefright/audioloop.cpp
+++ b/cmds/stagefright/audioloop.cpp
@@ -23,13 +23,14 @@
 #include <binder/ProcessState.h>
 #include <media/mediarecorder.h>
 #include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/foundation/AMessage.h>
 #include <media/stagefright/AMRWriter.h>
 #include <media/stagefright/AudioPlayer.h>
 #include <media/stagefright/AudioSource.h>
+#include <media/stagefright/MediaCodecSource.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaData.h>
-#include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
+#include <media/stagefright/SimpleDecodingSource.h>
 #include "SineSource.h"
 
 using namespace android;
@@ -79,8 +80,6 @@
     const int32_t kBitRate = outputWBAMR ? 16000 : 8000;
 
     android::ProcessState::self()->startThreadPool();
-    OMXClient client;
-    CHECK_EQ(client.connect(), (status_t)OK);
     sp<MediaSource> source;
 
     if (useMic) {
@@ -95,24 +94,25 @@
         source = new SineSource(kSampleRate, channels);
     }
 
-    sp<MetaData> meta = new MetaData;
-    meta->setCString(
-            kKeyMIMEType,
+    sp<AMessage> meta = new AMessage;
+    meta->setString(
+            "mime",
             outputWBAMR ? MEDIA_MIMETYPE_AUDIO_AMR_WB
                     : MEDIA_MIMETYPE_AUDIO_AMR_NB);
 
-    meta->setInt32(kKeyChannelCount, channels);
-    meta->setInt32(kKeySampleRate, kSampleRate);
-    meta->setInt32(kKeyBitRate, kBitRate);
+    meta->setInt32("channel-count", channels);
+    meta->setInt32("sample-rate", kSampleRate);
+    meta->setInt32("bitrate", kBitRate);
     int32_t maxInputSize;
     if (source->getFormat()->findInt32(kKeyMaxInputSize, &maxInputSize)) {
-        meta->setInt32(kKeyMaxInputSize, maxInputSize);
+        meta->setInt32("max-input-size", maxInputSize);
     }
 
-    sp<MediaSource> encoder = OMXCodec::Create(
-            client.interface(),
-            meta, true /* createEncoder */,
-            source);
+    sp<ALooper> looper = new ALooper;
+    looper->setName("audioloop");
+    looper->start();
+
+    sp<MediaSource> encoder = MediaCodecSource::Create(looper, meta, source);
 
     if (fileOut != NULL) {
         // target file specified, write encoded AMR output
@@ -128,17 +128,15 @@
         writer->stop();
     } else {
         // otherwise decode to speaker
-        sp<MediaSource> decoder = OMXCodec::Create(
-                client.interface(),
-                meta, false /* createEncoder */,
-                encoder);
+        sp<MediaSource> decoder = SimpleDecodingSource::Create(encoder);
 
         if (playToSpeaker) {
             AudioPlayer *player = new AudioPlayer(NULL);
             player->setSource(decoder);
             player->start();
             sleep(duration);
-            source->stop(); // must stop source otherwise delete player will hang
+
+            decoder.clear(); // must clear |decoder| otherwise delete player will hang.
             delete player; // there is no player->stop()...
         } else {
             CHECK_EQ(decoder->start(), (status_t)OK);
diff --git a/cmds/stagefright/record.cpp b/cmds/stagefright/record.cpp
index 594c933..fbea7e9 100644
--- a/cmds/stagefright/record.cpp
+++ b/cmds/stagefright/record.cpp
@@ -18,16 +18,18 @@
 
 #include <binder/ProcessState.h>
 #include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/foundation/ALooper.h>
+#include <media/stagefright/foundation/AMessage.h>
 #include <media/stagefright/AudioPlayer.h>
 #include <media/stagefright/CameraSource.h>
 #include <media/stagefright/FileSource.h>
 #include <media/stagefright/MediaBufferGroup.h>
 #include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MediaCodecSource.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/MediaExtractor.h>
 #include <media/stagefright/MPEG4Writer.h>
-#include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
+#include <media/stagefright/SimpleDecodingSource.h>
 #include <media/MediaPlayerInterface.h>
 
 using namespace android;
@@ -182,9 +184,6 @@
         fprintf(stderr, "input color format must be 0 (YUV420SP) or 1 (YUV420P)\n");
         return 1;
     }
-    OMXClient client;
-    CHECK_EQ(client.connect(), (status_t)OK);
-
     status_t err = OK;
 
 #if 0
@@ -197,8 +196,7 @@
 
     sp<MetaData> meta = source->getFormat();
 
-    sp<MediaSource> decoder = OMXCodec::Create(
-            client.interface(), meta, false /* createEncoder */, source);
+    sp<MediaSource> decoder = SimpleDecodingSource::Create(source);
 
     int width, height;
     bool success = meta->findInt32(kKeyWidth, &width);
@@ -210,22 +208,21 @@
     sp<MediaSource> decoder = new DummySource(width, height, colorFormat);
 #endif
 
-    sp<MetaData> enc_meta = new MetaData;
-    // enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
-    // enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
-    enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
-    enc_meta->setInt32(kKeyWidth, width);
-    enc_meta->setInt32(kKeyHeight, height);
-    enc_meta->setInt32(kKeySampleRate, kFramerate);
-    enc_meta->setInt32(kKeyBitRate, kVideoBitRate);
-    enc_meta->setInt32(kKeyStride, width);
-    enc_meta->setInt32(kKeySliceHeight, height);
-    enc_meta->setInt32(kKeyIFramesInterval, kIFramesIntervalSec);
-    enc_meta->setInt32(kKeyColorFormat, colorFormat);
+    sp<AMessage> enc_meta = new AMessage;
+    // enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_H263);
+    // enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_MPEG4);
+    enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
+    enc_meta->setInt32("width", width);
+    enc_meta->setInt32("height", height);
+    enc_meta->setInt32("sample-rate", kFramerate);
+    enc_meta->setInt32("bit-rate", kVideoBitRate);
+    // enc_meta->setInt32("stride", width);
+    // enc_meta->setInt32("slice-height", height);
+    enc_meta->setInt32("i-frame-interval", kIFramesIntervalSec);
+    enc_meta->setInt32("color-format", colorFormat);
 
     sp<MediaSource> encoder =
-        OMXCodec::Create(
-                client.interface(), enc_meta, true /* createEncoder */, decoder);
+        MediaCodecSource::Create(looper, format, decoder);
 
 #if 1
     sp<MPEG4Writer> writer = new MPEG4Writer("/sdcard/output.mp4");
@@ -260,7 +257,6 @@
 #endif
 
     printf("$\n");
-    client.disconnect();
 #endif
 
 #if 0
@@ -299,9 +295,6 @@
 int main(int /* argc */, char ** /* argv */) {
     android::ProcessState::self()->startThreadPool();
 
-    OMXClient client;
-    CHECK_EQ(client.connect(), (status_t)OK);
-
     const int32_t kSampleRate = 22050;
     const int32_t kNumChannels = 2;
     sp<MediaSource> audioSource = new SineSource(kSampleRate, kNumChannels);
@@ -317,16 +310,20 @@
     player->stop();
 #endif
 
-    sp<MetaData> encMeta = new MetaData;
-    encMeta->setCString(kKeyMIMEType,
+    sp<AMessage> encMeta = new AMessage;
+    encMeta->setString("mime",
             0 ? MEDIA_MIMETYPE_AUDIO_AMR_WB : MEDIA_MIMETYPE_AUDIO_AAC);
-    encMeta->setInt32(kKeySampleRate, kSampleRate);
-    encMeta->setInt32(kKeyChannelCount, kNumChannels);
-    encMeta->setInt32(kKeyMaxInputSize, 8192);
-    encMeta->setInt32(kKeyBitRate, kAudioBitRate);
+    encMeta->setInt32("sample-rate", kSampleRate);
+    encMeta->setInt32("channel-count", kNumChannels);
+    encMeta->setInt32("max-input-size", 8192);
+    encMeta->setInt32("bitrate", kAudioBitRate);
+
+    sp<ALooper> looper = new ALooper;
+    looper->setName("record");
+    looper->start();
 
     sp<MediaSource> encoder =
-        OMXCodec::Create(client.interface(), encMeta, true, audioSource);
+        MediaCodecSource::Create(looper, encMeta, audioSource);
 
     encoder->start();
 
@@ -348,8 +345,6 @@
 
     encoder->stop();
 
-    client.disconnect();
-
     return 0;
 }
 #endif
diff --git a/cmds/stagefright/recordvideo.cpp b/cmds/stagefright/recordvideo.cpp
index 2ad40bd..af39d46 100644
--- a/cmds/stagefright/recordvideo.cpp
+++ b/cmds/stagefright/recordvideo.cpp
@@ -23,15 +23,18 @@
 
 #include <binder/ProcessState.h>
 #include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/foundation/ALooper.h>
+#include <media/stagefright/foundation/AMessage.h>
 #include <media/stagefright/AudioPlayer.h>
 #include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaCodecSource.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/MPEG4Writer.h>
-#include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
 #include <media/MediaPlayerInterface.h>
 
+#include <OMX_Video.h>
+
 using namespace android;
 
 // Print usage showing how to use this utility to record videos
@@ -265,44 +268,45 @@
         }
     }
 
-    OMXClient client;
-    CHECK_EQ(client.connect(), (status_t)OK);
-
     status_t err = OK;
     sp<MediaSource> source =
         new DummySource(width, height, nFrames, frameRateFps, colorFormat);
 
-    sp<MetaData> enc_meta = new MetaData;
+    sp<AMessage> enc_meta = new AMessage;
     switch (codec) {
         case 1:
-            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
+            enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_MPEG4);
             break;
         case 2:
-            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
+            enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_H263);
             break;
         default:
-            enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
+            enc_meta->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
             break;
     }
-    enc_meta->setInt32(kKeyWidth, width);
-    enc_meta->setInt32(kKeyHeight, height);
-    enc_meta->setInt32(kKeyFrameRate, frameRateFps);
-    enc_meta->setInt32(kKeyBitRate, bitRateBps);
-    enc_meta->setInt32(kKeyStride, width);
-    enc_meta->setInt32(kKeySliceHeight, height);
-    enc_meta->setInt32(kKeyIFramesInterval, iFramesIntervalSeconds);
-    enc_meta->setInt32(kKeyColorFormat, colorFormat);
+    enc_meta->setInt32("width", width);
+    enc_meta->setInt32("height", height);
+    enc_meta->setInt32("frame-rate", frameRateFps);
+    enc_meta->setInt32("bitrate", bitRateBps);
+    enc_meta->setInt32("stride", width);
+    enc_meta->setInt32("slice-height", height);
+    enc_meta->setInt32("i-frame-interval", iFramesIntervalSeconds);
+    enc_meta->setInt32("color-format", colorFormat);
     if (level != -1) {
-        enc_meta->setInt32(kKeyVideoLevel, level);
+        enc_meta->setInt32("level", level);
     }
     if (profile != -1) {
-        enc_meta->setInt32(kKeyVideoProfile, profile);
+        enc_meta->setInt32("profile", profile);
     }
 
+    sp<ALooper> looper = new ALooper;
+    looper->setName("recordvideo");
+    looper->start();
+
     sp<MediaSource> encoder =
-        OMXCodec::Create(
-                client.interface(), enc_meta, true /* createEncoder */, source,
-                0, preferSoftwareCodec ? OMXCodec::kPreferSoftwareCodecs : 0);
+        MediaCodecSource::Create(
+                looper, enc_meta, source, NULL /* consumer */,
+                preferSoftwareCodec ? MediaCodecSource::FLAG_PREFER_SOFTWARE_CODEC : 0);
 
     int fd = open(fileName, O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
     if (fd < 0) {
@@ -321,7 +325,6 @@
     int64_t end = systemTime();
 
     fprintf(stderr, "$\n");
-    client.disconnect();
 
     if (err != OK && err != ERROR_END_OF_STREAM) {
         fprintf(stderr, "record failed: %d\n", err);
diff --git a/cmds/stagefright/stagefright.cpp b/cmds/stagefright/stagefright.cpp
index a9c6eda..66df9d0 100644
--- a/cmds/stagefright/stagefright.cpp
+++ b/cmds/stagefright/stagefright.cpp
@@ -31,20 +31,26 @@
 
 #include <binder/IServiceManager.h>
 #include <binder/ProcessState.h>
+#include <media/ICrypto.h>
 #include <media/IMediaHTTPService.h>
 #include <media/IMediaPlayerService.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 "include/NuCachedSource2.h"
 #include <media/stagefright/AudioPlayer.h>
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/JPEGSource.h>
+#include <media/stagefright/MediaCodec.h>
+#include <media/stagefright/MediaCodecList.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/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
+#include <media/stagefright/SimpleDecodingSource.h>
+#include <media/stagefright/Utils.h>
 #include <media/mediametadataretriever.h>
 
 #include <media/stagefright/foundation/hexdump.h>
@@ -163,7 +169,7 @@
     out = NULL;
 }
 
-static void playSource(OMXClient *client, sp<MediaSource> &source) {
+static void playSource(sp<MediaSource> &source) {
     sp<MetaData> meta = source->getFormat();
 
     const char *mime;
@@ -175,20 +181,14 @@
     } else {
         int flags = 0;
         if (gPreferSoftwareCodec) {
-            flags |= OMXCodec::kPreferSoftwareCodecs;
+            flags |= MediaCodecList::kPreferSoftwareCodecs;
         }
         if (gForceToUseHardwareCodec) {
             CHECK(!gPreferSoftwareCodec);
-            flags |= OMXCodec::kHardwareCodecsOnly;
+            flags |= MediaCodecList::kHardwareCodecsOnly;
         }
-        rawSource = OMXCodec::Create(
-            client->interface(), meta, false /* createEncoder */, source,
-            NULL /* matchComponentName */,
-            flags,
-            gSurface);
-
+        rawSource = SimpleDecodingSource::Create(source, flags, gSurface);
         if (rawSource == NULL) {
-            fprintf(stderr, "Failed to instantiate decoder for '%s'.\n", mime);
             return;
         }
         displayAVCProfileLevelIfPossible(meta);
@@ -397,7 +397,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct DetectSyncSource : public MediaSource {
-    DetectSyncSource(const sp<MediaSource> &source);
+    explicit DetectSyncSource(const sp<MediaSource> &source);
 
     virtual status_t start(MetaData *params = NULL);
     virtual status_t stop();
@@ -618,7 +618,7 @@
     fprintf(stderr, "       -D(ump) output_filename (decoded PCM data to a file)\n");
 }
 
-static void dumpCodecProfiles(const sp<IOMX>& omx, bool queryDecoders) {
+static void dumpCodecProfiles(bool queryDecoders) {
     const char *kMimeTypes[] = {
         MEDIA_MIMETYPE_VIDEO_AVC, MEDIA_MIMETYPE_VIDEO_MPEG4,
         MEDIA_MIMETYPE_VIDEO_H263, MEDIA_MIMETYPE_AUDIO_AAC,
@@ -631,30 +631,36 @@
     const char *codecType = queryDecoders? "decoder" : "encoder";
     printf("%s profiles:\n", codecType);
 
+    sp<IMediaCodecList> list = MediaCodecList::getInstance();
+    size_t numCodecs = list->countCodecs();
+
     for (size_t k = 0; k < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]); ++k) {
         printf("type '%s':\n", kMimeTypes[k]);
 
-        Vector<CodecCapabilities> results;
-        // will retrieve hardware and software codecs
-        CHECK_EQ(QueryCodecs(omx, kMimeTypes[k],
-                             queryDecoders,
-                             &results), (status_t)OK);
-
-        for (size_t i = 0; i < results.size(); ++i) {
+        for (size_t index = 0; index < numCodecs; ++index) {
+            sp<MediaCodecInfo> info = list->getCodecInfo(index);
+            if (info == NULL || info->isEncoder() != !queryDecoders) {
+                continue;
+            }
+            sp<MediaCodecInfo::Capabilities> caps = info->getCapabilitiesFor(kMimeTypes[k]);
+            if (caps == NULL) {
+                continue;
+            }
             printf("  %s '%s' supports ",
-                       codecType, results[i].mComponentName.string());
+                       codecType, info->getCodecName());
 
-            if (results[i].mProfileLevels.size() == 0) {
-                    printf("NOTHING.\n");
-                    continue;
+            Vector<MediaCodecInfo::ProfileLevel> profileLevels;
+            caps->getSupportedProfileLevels(&profileLevels);
+            if (profileLevels.size() == 0) {
+                printf("NOTHING.\n");
+                continue;
             }
 
-            for (size_t j = 0; j < results[i].mProfileLevels.size(); ++j) {
-                const CodecProfileLevel &profileLevel =
-                     results[i].mProfileLevels[j];
+            for (size_t j = 0; j < profileLevels.size(); ++j) {
+                const MediaCodecInfo::ProfileLevel &profileLevel = profileLevels[j];
 
-                printf("%s%" PRIu32 "/%" PRIu32, j > 0 ? ", " : "",
-                    profileLevel.mProfile, profileLevel.mLevel);
+                printf("%s%u/%u", j > 0 ? ", " : "",
+                        profileLevel.mProfile, profileLevel.mLevel);
             }
 
             printf("\n");
@@ -881,17 +887,8 @@
     }
 
     if (dumpProfiles) {
-        sp<IServiceManager> sm = defaultServiceManager();
-        sp<IBinder> binder = sm->getService(String16("media.player"));
-        sp<IMediaPlayerService> service =
-            interface_cast<IMediaPlayerService>(binder);
-
-        CHECK(service.get() != NULL);
-
-        sp<IOMX> omx = service->getOMX();
-        CHECK(omx.get() != NULL);
-        dumpCodecProfiles(omx, true /* queryDecoders */);
-        dumpCodecProfiles(omx, false /* queryDecoders */);
+        dumpCodecProfiles(true /* queryDecoders */);
+        dumpCodecProfiles(false /* queryDecoders */);
     }
 
     if (listComponents) {
@@ -954,16 +951,11 @@
                     false /* isControlledByApp */);
             gSurface = new Surface(producer);
         }
-
-        CHECK_EQ((status_t)OK,
-                 native_window_api_connect(
-                     gSurface.get(), NATIVE_WINDOW_API_MEDIA));
     }
 
     DataSource::RegisterDefaultSniffers();
 
-    OMXClient client;
-    status_t err = client.connect();
+    status_t err = OK;
 
     for (int k = 0; k < argc && err == OK; ++k) {
         bool syncInfoPresent = true;
@@ -1097,31 +1089,16 @@
         } else if (dumpStream) {
             dumpSource(mediaSource, dumpStreamFilename);
         } else if (dumpPCMStream) {
-            OMXClient client;
-            CHECK_EQ(client.connect(), (status_t)OK);
-
-            sp<MediaSource> decSource =
-                OMXCodec::Create(
-                        client.interface(),
-                        mediaSource->getFormat(),
-                        false,
-                        mediaSource,
-                        0,
-                        0);
-
+            sp<MediaSource> decSource = SimpleDecodingSource::Create(mediaSource);
             dumpSource(decSource, dumpStreamFilename);
         } else if (seekTest) {
             performSeekTest(mediaSource);
         } else {
-            playSource(&client, mediaSource);
+            playSource(mediaSource);
         }
     }
 
     if ((useSurfaceAlloc || useSurfaceTexAlloc) && !audioOnly) {
-        CHECK_EQ((status_t)OK,
-                 native_window_api_disconnect(
-                     gSurface.get(), NATIVE_WINDOW_API_MEDIA));
-
         gSurface.clear();
 
         if (useSurfaceAlloc) {
@@ -1129,7 +1106,5 @@
         }
     }
 
-    client.disconnect();
-
     return 0;
 }
diff --git a/cmds/stagefright/stream.cpp b/cmds/stagefright/stream.cpp
index 1a40e53..66bd69d 100644
--- a/cmds/stagefright/stream.cpp
+++ b/cmds/stagefright/stream.cpp
@@ -45,7 +45,7 @@
 
 struct MyStreamSource : public BnStreamSource {
     // Object assumes ownership of fd.
-    MyStreamSource(int fd);
+    explicit MyStreamSource(int fd);
 
     virtual void setListener(const sp<IStreamListener> &listener);
     virtual void setBuffers(const Vector<sp<IMemory> > &buffers);
@@ -125,7 +125,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct MyConvertingStreamSource : public BnStreamSource {
-    MyConvertingStreamSource(const char *filename);
+    explicit MyConvertingStreamSource(const char *filename);
 
     virtual void setListener(const sp<IStreamListener> &listener);
     virtual void setBuffers(const Vector<sp<IMemory> > &buffers);
diff --git a/drm/common/Android.mk b/drm/common/Android.mk
index db67534..ca3d2cd 100644
--- a/drm/common/Android.mk
+++ b/drm/common/Android.mk
@@ -31,6 +31,8 @@
     DrmInfoEvent.cpp \
     ReadWriteUtils.cpp
 
+LOCAL_STATIC_LIBRARIES := libbinder
+
 LOCAL_C_INCLUDES := \
     $(TOP)/frameworks/av/include \
     $(TOP)/frameworks/av/drm/libdrmframework/include \
diff --git a/drm/common/IDrmManagerService.cpp b/drm/common/IDrmManagerService.cpp
index b90da1b..1614e26 100644
--- a/drm/common/IDrmManagerService.cpp
+++ b/drm/common/IDrmManagerService.cpp
@@ -33,7 +33,7 @@
 
 #include "IDrmManagerService.h"
 
-#define INVALID_BUFFER_LENGTH -1
+#define INVALID_BUFFER_LENGTH (-1)
 #define MAX_BINDER_TRANSACTION_SIZE ((1*1024*1024)-(4096*2))
 
 using namespace android;
@@ -742,9 +742,11 @@
     const status_t status = reply.readInt32();
     ALOGV("Return value of decrypt() is %d", status);
 
-    const int size = reply.readInt32();
-    (*decBuffer)->length = size;
-    reply.read((void *)(*decBuffer)->data, size);
+    if (status == NO_ERROR) {
+        const int size = reply.readInt32();
+        (*decBuffer)->length = size;
+        reply.read((void *)(*decBuffer)->data, size);
+    }
 
     return status;
 }
@@ -1470,9 +1472,11 @@
 
         reply->writeInt32(status);
 
-        const int size = decBuffer->length;
-        reply->writeInt32(size);
-        reply->write(decBuffer->data, size);
+        if (status == NO_ERROR) {
+            const int size = decBuffer->length;
+            reply->writeInt32(size);
+            reply->write(decBuffer->data, size);
+        }
 
         clearDecryptHandle(&handle);
         delete encBuffer; encBuffer = NULL;
diff --git a/drm/common/ReadWriteUtils.cpp b/drm/common/ReadWriteUtils.cpp
index d696f16..16b5b34 100644
--- a/drm/common/ReadWriteUtils.cpp
+++ b/drm/common/ReadWriteUtils.cpp
@@ -30,7 +30,7 @@
 
 using namespace android;
 
-#define FAILURE -1
+#define FAILURE (-1)
 
 String8 ReadWriteUtils::readBytes(const String8& filePath) {
     FILE* file = NULL;
diff --git a/drm/drmserver/DrmManager.cpp b/drm/drmserver/DrmManager.cpp
index d8aeb0c..18b9a3b 100644
--- a/drm/drmserver/DrmManager.cpp
+++ b/drm/drmserver/DrmManager.cpp
@@ -33,7 +33,7 @@
 #include "DrmManager.h"
 #include "ReadWriteUtils.h"
 
-#define DECRYPT_FILE_ERROR -1
+#define DECRYPT_FILE_ERROR (-1)
 
 using namespace android;
 
@@ -370,7 +370,7 @@
 }
 
 status_t DrmManager::getAllSupportInfo(
-                    int uniqueId, int* length, DrmSupportInfo** drmSupportInfoArray) {
+                    int /*uniqueId*/, int* length, DrmSupportInfo** drmSupportInfoArray) {
     Mutex::Autolock _l(mLock);
     Vector<String8> plugInPathList = mPlugInManager.getPlugInIdList();
     int size = plugInPathList.size();
diff --git a/drm/drmserver/drmserver.rc b/drm/drmserver/drmserver.rc
index c6b8226..42f5fc8 100644
--- a/drm/drmserver/drmserver.rc
+++ b/drm/drmserver/drmserver.rc
@@ -1,4 +1,4 @@
 service drm /system/bin/drmserver
     class main
     user drm
-    group drm system inet drmrpc
+    group drm system inet drmrpc readproc
diff --git a/drm/drmserver/main_drmserver.cpp b/drm/drmserver/main_drmserver.cpp
index 434d561..b9ad7d1 100644
--- a/drm/drmserver/main_drmserver.cpp
+++ b/drm/drmserver/main_drmserver.cpp
@@ -26,7 +26,7 @@
 
 using namespace android;
 
-int main(int argc, char** argv)
+int main(int, char**)
 {
     sp<ProcessState> proc(ProcessState::self());
     sp<IServiceManager> sm = defaultServiceManager();
diff --git a/drm/libdrmframework/DrmManagerClientImpl.cpp b/drm/libdrmframework/DrmManagerClientImpl.cpp
index 9457bb6..2296d93 100644
--- a/drm/libdrmframework/DrmManagerClientImpl.cpp
+++ b/drm/libdrmframework/DrmManagerClientImpl.cpp
@@ -28,7 +28,7 @@
 
 using namespace android;
 
-#define INVALID_VALUE -1
+#define INVALID_VALUE (-1)
 
 Mutex DrmManagerClientImpl::sMutex;
 sp<IDrmManagerService> DrmManagerClientImpl::sDrmManagerService;
@@ -350,7 +350,7 @@
     }
 }
 
-void DrmManagerClientImpl::DeathNotifier::binderDied(const wp<IBinder>& who) {
+void DrmManagerClientImpl::DeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
     Mutex::Autolock lock(sMutex);
     DrmManagerClientImpl::sDrmManagerService.clear();
     ALOGW("DrmManager server died!");
diff --git a/drm/libdrmframework/NoOpDrmManagerClientImpl.cpp b/drm/libdrmframework/NoOpDrmManagerClientImpl.cpp
index dab583d..cbecc43 100644
--- a/drm/libdrmframework/NoOpDrmManagerClientImpl.cpp
+++ b/drm/libdrmframework/NoOpDrmManagerClientImpl.cpp
@@ -18,134 +18,160 @@
 
 namespace android {
 
-void NoOpDrmManagerClientImpl::remove(int uniqueId) {
+void NoOpDrmManagerClientImpl::remove(int /* uniqueId */) {
 }
 
-void NoOpDrmManagerClientImpl::addClient(int uniqueId) {
+void NoOpDrmManagerClientImpl::addClient(int /* uniqueId */) {
 }
 
-void NoOpDrmManagerClientImpl::removeClient(int uniqueId) {
+void NoOpDrmManagerClientImpl::removeClient(int /* uniqueId */) {
 }
 
 status_t NoOpDrmManagerClientImpl::setOnInfoListener(
-            int uniqueId, const sp<DrmManagerClient::OnInfoListener>& infoListener) {
+            int /* uniqueId */,
+            const sp<DrmManagerClient::OnInfoListener>& /* infoListener */) {
     return UNKNOWN_ERROR;
 }
 
-DrmConstraints* NoOpDrmManagerClientImpl::getConstraints(int uniqueId, const String8* path, const int action) {
+DrmConstraints* NoOpDrmManagerClientImpl::getConstraints(int /* uniqueId */,
+            const String8* /* path */, const int /* action */) {
     return NULL;
 }
 
-DrmMetadata* NoOpDrmManagerClientImpl::getMetadata(int uniqueId, const String8* path) {
+DrmMetadata* NoOpDrmManagerClientImpl::getMetadata(int /* uniqueId */,
+            const String8* /* path */) {
     return NULL;
 }
 
-bool NoOpDrmManagerClientImpl::canHandle(int uniqueId, const String8& path, const String8& mimeType) {
+bool NoOpDrmManagerClientImpl::canHandle(int /* uniqueId */,
+            const String8& /* path */, const String8& /* mimeType */) {
     return false;
 }
 
-DrmInfoStatus* NoOpDrmManagerClientImpl::processDrmInfo(int uniqueId, const DrmInfo* drmInfo) {
+DrmInfoStatus* NoOpDrmManagerClientImpl::processDrmInfo(int /* uniqueId */,
+            const DrmInfo* /* drmInfo */) {
     return NULL;
 }
 
-DrmInfo* NoOpDrmManagerClientImpl::acquireDrmInfo(int uniqueId, const DrmInfoRequest* drmInfoRequest) {
+DrmInfo* NoOpDrmManagerClientImpl::acquireDrmInfo(int /* uniqueId */,
+            const DrmInfoRequest* /* drmInfoRequest */) {
     return NULL;
 }
 
-status_t NoOpDrmManagerClientImpl::saveRights(int uniqueId, const DrmRights& drmRights,
-            const String8& rightsPath, const String8& contentPath) {
+status_t NoOpDrmManagerClientImpl::saveRights(int /* uniqueId */,
+            const DrmRights& /* drmRights */, const String8& /* rightsPath */,
+            const String8& /* contentPath */) {
     return UNKNOWN_ERROR;
 }
 
-String8 NoOpDrmManagerClientImpl::getOriginalMimeType(int uniqueId, const String8& path, int fd) {
+String8 NoOpDrmManagerClientImpl::getOriginalMimeType(int /* uniqueId */,
+            const String8& /* path */, int /* fd */) {
     return String8();
 }
 
-int NoOpDrmManagerClientImpl::getDrmObjectType(int uniqueId, const String8& path, const String8& mimeType) {
+int NoOpDrmManagerClientImpl::getDrmObjectType(int /* uniqueId */,
+            const String8& /* path */, const String8& /* mimeType */) {
     return -1;
 }
 
-int NoOpDrmManagerClientImpl::checkRightsStatus(int uniqueId, const String8& path, int action) {
+int NoOpDrmManagerClientImpl::checkRightsStatus(int /* uniqueId */,
+            const String8& /* path */, int /* action */) {
     return -1;
 }
 
-status_t NoOpDrmManagerClientImpl::consumeRights(int uniqueId, sp<DecryptHandle> &decryptHandle, int action, bool reserve) {
+status_t NoOpDrmManagerClientImpl::consumeRights(int /* uniqueId */,
+            sp<DecryptHandle>& /* decryptHandle */, int /* action */,
+            bool /* reserve */) {
     return UNKNOWN_ERROR;
 }
 
 status_t NoOpDrmManagerClientImpl::setPlaybackStatus(
-            int uniqueId, sp<DecryptHandle> &decryptHandle, int playbackStatus, int64_t position) {
+            int /* uniqueId */, sp<DecryptHandle>& /* decryptHandle */,
+            int /* playbackStatus */, int64_t /* position */) {
     return UNKNOWN_ERROR;
 }
 
-bool NoOpDrmManagerClientImpl::validateAction(
-        int uniqueId, const String8& path, int action, const ActionDescription& description) {
+bool NoOpDrmManagerClientImpl::validateAction(int /* uniqueId */,
+            const String8& /* path */, int /* action */,
+            const ActionDescription& /* description */) {
     return false;
 }
 
-status_t NoOpDrmManagerClientImpl::removeRights(int uniqueId, const String8& path) {
+status_t NoOpDrmManagerClientImpl::removeRights(int /* uniqueId */,
+            const String8& /* path */) {
     return UNKNOWN_ERROR;
 }
 
-status_t NoOpDrmManagerClientImpl::removeAllRights(int uniqueId) {
+status_t NoOpDrmManagerClientImpl::removeAllRights(int /* uniqueId */) {
     return UNKNOWN_ERROR;
 }
 
-int NoOpDrmManagerClientImpl::openConvertSession(int uniqueId, const String8& mimeType) {
+int NoOpDrmManagerClientImpl::openConvertSession(int /* uniqueId */,
+            const String8& /* mimeType */) {
     return -1;
 }
 
-DrmConvertedStatus* NoOpDrmManagerClientImpl::convertData(int uniqueId, int convertId, const DrmBuffer* inputData) {
+DrmConvertedStatus* NoOpDrmManagerClientImpl::convertData(int /* uniqueId */,
+            int /* convertId */, const DrmBuffer* /* inputData */) {
     return NULL;
 }
 
-DrmConvertedStatus* NoOpDrmManagerClientImpl::closeConvertSession(int uniqueId, int convertId) {
+DrmConvertedStatus* NoOpDrmManagerClientImpl::closeConvertSession(
+            int /* uniqueId */, int /* convertId */) {
     return NULL;
 }
 
-status_t NoOpDrmManagerClientImpl::getAllSupportInfo(int uniqueId, int* length, DrmSupportInfo** drmSupportInfoArray) {
+status_t NoOpDrmManagerClientImpl::getAllSupportInfo(int /* uniqueId */,
+            int* /* length */, DrmSupportInfo** /* drmSupportInfoArray */) {
     return UNKNOWN_ERROR;
 }
 
 sp<DecryptHandle> NoOpDrmManagerClientImpl::openDecryptSession(
-            int uniqueId, int fd, off64_t offset, off64_t length, const char* mime) {
+            int /* uniqueId */, int /* fd */, off64_t /* offset */,
+            off64_t /* length */, const char* /* mime */) {
     return NULL;
 }
 
 sp<DecryptHandle> NoOpDrmManagerClientImpl::openDecryptSession(
-            int uniqueId, const char* uri, const char* mime) {
+            int /* uniqueId */, const char* /* uri */, const char* /* mime */) {
     return NULL;
 }
 
-sp<DecryptHandle> NoOpDrmManagerClientImpl::openDecryptSession(int uniqueId, const DrmBuffer& buf,
-            const String8& mimeType) {
+sp<DecryptHandle> NoOpDrmManagerClientImpl::openDecryptSession(int /* uniqueId */,
+            const DrmBuffer& /* buf */, const String8& /* mimeType */) {
     return NULL;
 }
 
-status_t NoOpDrmManagerClientImpl::closeDecryptSession(int uniqueId, sp<DecryptHandle> &decryptHandle) {
+status_t NoOpDrmManagerClientImpl::closeDecryptSession(int /* uniqueId */,
+            sp<DecryptHandle>& /* decryptHandle */) {
     return UNKNOWN_ERROR;
 }
 
-status_t NoOpDrmManagerClientImpl::initializeDecryptUnit(int uniqueId, sp<DecryptHandle> &decryptHandle,
-            int decryptUnitId, const DrmBuffer* headerInfo) {
+status_t NoOpDrmManagerClientImpl::initializeDecryptUnit(int /* uniqueId */,
+            sp<DecryptHandle>& /* decryptHandle */, int /* decryptUnitId */,
+            const DrmBuffer* /* headerInfo */) {
     return UNKNOWN_ERROR;
 }
 
-status_t NoOpDrmManagerClientImpl::decrypt(int uniqueId, sp<DecryptHandle> &decryptHandle, int decryptUnitId,
-            const DrmBuffer* encBuffer, DrmBuffer** decBuffer, DrmBuffer* IV) {
+status_t NoOpDrmManagerClientImpl::decrypt(int /* uniqueId */,
+            sp<DecryptHandle>& /* decryptHandle */, int /* decryptUnitId */,
+            const DrmBuffer* /* encBuffer */, DrmBuffer** /* decBuffer */,
+            DrmBuffer* /* IV */) {
     return UNKNOWN_ERROR;
 }
 
-status_t NoOpDrmManagerClientImpl::finalizeDecryptUnit(int uniqueId, sp<DecryptHandle> &decryptHandle, int decryptUnitId) {
+status_t NoOpDrmManagerClientImpl::finalizeDecryptUnit(int /* uniqueId */,
+            sp<DecryptHandle>& /* decryptHandle */, int /* decryptUnitId */) {
     return UNKNOWN_ERROR;
 }
 
-ssize_t NoOpDrmManagerClientImpl::pread(int uniqueId, sp<DecryptHandle> &decryptHandle,
-            void* buffer, ssize_t numBytes, off64_t offset) {
+ssize_t NoOpDrmManagerClientImpl::pread(int /* uniqueId */,
+            sp<DecryptHandle>& /* decryptHandle */,
+            void* /* buffer */, ssize_t /* numBytes */, off64_t /* offset */) {
     return -1;
 }
 
-status_t NoOpDrmManagerClientImpl::notify(const DrmInfoEvent& event) {
+status_t NoOpDrmManagerClientImpl::notify(const DrmInfoEvent& /* event */) {
     return UNKNOWN_ERROR;
 }
 
diff --git a/drm/libdrmframework/plugins/common/include/DrmEngineBase.h b/drm/libdrmframework/plugins/common/include/DrmEngineBase.h
index fa51c13..c55eda2 100644
--- a/drm/libdrmframework/plugins/common/include/DrmEngineBase.h
+++ b/drm/libdrmframework/plugins/common/include/DrmEngineBase.h
@@ -398,9 +398,9 @@
      *     DRM_ERROR_CANNOT_HANDLE for failure and DRM_NO_ERROR for success
      */
     virtual status_t onOpenDecryptSession(
-            int uniqueId, DecryptHandle* decryptHandle,
-            int fd, off64_t offset, off64_t length,
-            const char* mime) {
+            int /*uniqueId*/, DecryptHandle* /*decryptHandle*/,
+            int /*fd*/, off64_t /*offset*/, off64_t /*length*/,
+            const char* /*mime*/) {
 
         return DRM_ERROR_CANNOT_HANDLE;
     }
@@ -430,8 +430,8 @@
      *     DRM_ERROR_CANNOT_HANDLE for failure and DRM_NO_ERROR for success
      */
     virtual status_t onOpenDecryptSession(
-            int uniqueId, DecryptHandle* decryptHandle,
-            const char* uri, const char* mime) {
+            int /*uniqueId*/, DecryptHandle* /*decryptHandle*/,
+            const char* /*uri*/, const char* /*mime*/) {
 
         return DRM_ERROR_CANNOT_HANDLE;
     }
@@ -446,8 +446,8 @@
      * @return
      *     DRM_ERROR_CANNOT_HANDLE for failure and DRM_NO_ERROR for success
      */
-    virtual status_t onOpenDecryptSession(int uniqueId, DecryptHandle* decryptHandle,
-            const DrmBuffer& buf, const String8& mimeType) {
+    virtual status_t onOpenDecryptSession(int /*uniqueId*/, DecryptHandle* /*decryptHandle*/,
+            const DrmBuffer& /*buf*/, const String8& /*mimeType*/) {
         return DRM_ERROR_CANNOT_HANDLE;
     }
 
diff --git a/drm/libdrmframework/plugins/common/util/src/MimeTypeUtil.cpp b/drm/libdrmframework/plugins/common/util/src/MimeTypeUtil.cpp
index 576ed15..3b1566f 100644
--- a/drm/libdrmframework/plugins/common/util/src/MimeTypeUtil.cpp
+++ b/drm/libdrmframework/plugins/common/util/src/MimeTypeUtil.cpp
@@ -115,7 +115,7 @@
  * replacement mimetype otherwise the original mimetype
  * is returned.
  *
- * If the mimetype is of unsupported group i.e. application/*
+ * If the mimetype is of unsupported group i.e. application/...
  * then "unsupported/drm.mimetype" will be returned.
  *
  * @param mimeType - mimetype in lower case to convert.
diff --git a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/src/FwdLockEngine.cpp b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/src/FwdLockEngine.cpp
index f400732..efbd547 100644
--- a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/src/FwdLockEngine.cpp
+++ b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/src/FwdLockEngine.cpp
@@ -119,7 +119,7 @@
     return drmConstraints;
 }
 
-DrmMetadata* FwdLockEngine::onGetMetadata(int uniqueId, const String8* path) {
+DrmMetadata* FwdLockEngine::onGetMetadata(int /*uniqueId*/, const String8* path) {
     DrmMetadata* drmMetadata = NULL;
 
     LOG_VERBOSE("FwdLockEngine::onGetMetadata");
@@ -132,7 +132,7 @@
     return drmMetadata;
 }
 
-android::status_t FwdLockEngine::onInitialize(int uniqueId) {
+android::status_t FwdLockEngine::onInitialize(int /*uniqueId*/) {
     LOG_VERBOSE("FwdLockEngine::onInitialize");
 
     if (FwdLockGlue_InitializeKeyEncryption()) {
@@ -146,14 +146,14 @@
 }
 
 android::status_t
-FwdLockEngine::onSetOnInfoListener(int uniqueId, const IDrmEngine::OnInfoListener* infoListener) {
+FwdLockEngine::onSetOnInfoListener(int /*uniqueId*/, const IDrmEngine::OnInfoListener* /*infoListener*/) {
     // Not used
     LOG_VERBOSE("FwdLockEngine::onSetOnInfoListener");
 
     return DRM_NO_ERROR;
 }
 
-android::status_t FwdLockEngine::onTerminate(int uniqueId) {
+android::status_t FwdLockEngine::onTerminate(int /*uniqueId*/) {
     LOG_VERBOSE("FwdLockEngine::onTerminate");
 
     return DRM_NO_ERROR;
@@ -207,7 +207,7 @@
     return false;
 }
 
-DrmSupportInfo* FwdLockEngine::onGetSupportInfo(int uniqueId) {
+DrmSupportInfo* FwdLockEngine::onGetSupportInfo(int /*uniqueId*/) {
     DrmSupportInfo* pSupportInfo = new DrmSupportInfo();
 
     LOG_VERBOSE("FwdLockEngine::onGetSupportInfo");
@@ -222,14 +222,14 @@
     return pSupportInfo;
 }
 
-bool FwdLockEngine::onCanHandle(int uniqueId, const String8& path) {
+bool FwdLockEngine::onCanHandle(int /*uniqueId*/, const String8& path) {
     bool result = false;
 
     String8 extString = path.getPathExtension();
     return IsFileSuffixSupported(extString);
 }
 
-DrmInfoStatus* FwdLockEngine::onProcessDrmInfo(int uniqueId, const DrmInfo* drmInfo) {
+DrmInfoStatus* FwdLockEngine::onProcessDrmInfo(int /*uniqueId*/, const DrmInfo* /*drmInfo*/) {
     DrmInfoStatus *drmInfoStatus = NULL;
 
     // Nothing to process
@@ -242,16 +242,16 @@
 }
 
 status_t FwdLockEngine::onSaveRights(
-            int uniqueId,
-            const DrmRights& drmRights,
-            const String8& rightsPath,
-            const String8& contentPath) {
+            int /*uniqueId*/,
+            const DrmRights& /*drmRights*/,
+            const String8& /*rightsPath*/,
+            const String8& /*contentPath*/) {
     // No rights to save. Return
     LOG_VERBOSE("FwdLockEngine::onSaveRights");
     return DRM_ERROR_UNKNOWN;
 }
 
-DrmInfo* FwdLockEngine::onAcquireDrmInfo(int uniqueId, const DrmInfoRequest* drmInfoRequest) {
+DrmInfo* FwdLockEngine::onAcquireDrmInfo(int /*uniqueId*/, const DrmInfoRequest* /*drmInfoRequest*/) {
     DrmInfo* drmInfo = NULL;
 
     // Nothing to be done for Forward Lock file
@@ -290,10 +290,10 @@
     return result;
 }
 
-status_t FwdLockEngine::onConsumeRights(int uniqueId,
-                                        DecryptHandle* decryptHandle,
-                                        int action,
-                                        bool reserve) {
+status_t FwdLockEngine::onConsumeRights(int /*uniqueId*/,
+                                        DecryptHandle* /*decryptHandle*/,
+                                        int /*action*/,
+                                        bool /*reserve*/) {
     // No rights consumption
     LOG_VERBOSE("FwdLockEngine::onConsumeRights");
     return DRM_NO_ERROR;
@@ -302,14 +302,14 @@
 bool FwdLockEngine::onValidateAction(int uniqueId,
                                      const String8& path,
                                      int action,
-                                     const ActionDescription& description) {
+                                     const ActionDescription& /*description*/) {
     LOG_VERBOSE("FwdLockEngine::onValidateAction");
 
     // For the forwardlock engine checkRights and ValidateAction are the same.
     return (onCheckRightsStatus(uniqueId, path, action) == RightsStatus::RIGHTS_VALID);
 }
 
-String8 FwdLockEngine::onGetOriginalMimeType(int uniqueId, const String8& path, int fd) {
+String8 FwdLockEngine::onGetOriginalMimeType(int /*uniqueId*/, const String8& /*path*/, int fd) {
     LOG_VERBOSE("FwdLockEngine::onGetOriginalMimeType");
     String8 mimeString = String8("");
     int fileDesc = dup(fd);
@@ -354,31 +354,31 @@
     return DrmObjectType::UNKNOWN;
 }
 
-status_t FwdLockEngine::onRemoveRights(int uniqueId, const String8& path) {
+status_t FwdLockEngine::onRemoveRights(int /*uniqueId*/, const String8& /*path*/) {
     // No Rights to remove
     LOG_VERBOSE("FwdLockEngine::onRemoveRights");
     return DRM_NO_ERROR;
 }
 
-status_t FwdLockEngine::onRemoveAllRights(int uniqueId) {
+status_t FwdLockEngine::onRemoveAllRights(int /*uniqueId*/) {
     // No rights to remove
     LOG_VERBOSE("FwdLockEngine::onRemoveAllRights");
     return DRM_NO_ERROR;
 }
 
 #ifdef USE_64BIT_DRM_API
-status_t FwdLockEngine::onSetPlaybackStatus(int uniqueId, DecryptHandle* decryptHandle,
-                                            int playbackStatus, int64_t position) {
+status_t FwdLockEngine::onSetPlaybackStatus(int /*uniqueId*/, DecryptHandle* /*decryptHandle*/,
+                                            int /*playbackStatus*/, int64_t /*position*/) {
 #else
-status_t FwdLockEngine::onSetPlaybackStatus(int uniqueId, DecryptHandle* decryptHandle,
-                                            int playbackStatus, int position) {
+status_t FwdLockEngine::onSetPlaybackStatus(int /*uniqueId*/, DecryptHandle* /*decryptHandle*/,
+                                            int /*playbackStatus*/, int /*position*/) {
 #endif
     // Not used
     LOG_VERBOSE("FwdLockEngine::onSetPlaybackStatus");
     return DRM_NO_ERROR;
 }
 
-status_t FwdLockEngine::onOpenConvertSession(int uniqueId,
+status_t FwdLockEngine::onOpenConvertSession(int /*uniqueId*/,
                                          int convertId) {
     status_t result = DRM_ERROR_UNKNOWN;
     LOG_VERBOSE("FwdLockEngine::onOpenConvertSession");
@@ -396,7 +396,7 @@
     return result;
 }
 
-DrmConvertedStatus* FwdLockEngine::onConvertData(int uniqueId,
+DrmConvertedStatus* FwdLockEngine::onConvertData(int /*uniqueId*/,
                                                  int convertId,
                                                  const DrmBuffer* inputData) {
     FwdLockConv_Status_t retStatus = FwdLockConv_Status_InvalidArgument;
@@ -432,7 +432,7 @@
     return new DrmConvertedStatus(getConvertedStatus(retStatus), convResult, offset);
 }
 
-DrmConvertedStatus* FwdLockEngine::onCloseConvertSession(int uniqueId,
+DrmConvertedStatus* FwdLockEngine::onCloseConvertSession(int /*uniqueId*/,
                                                          int convertId) {
     FwdLockConv_Status_t retStatus = FwdLockConv_Status_InvalidArgument;
     DrmBuffer *convResult = new DrmBuffer(NULL, 0);
@@ -464,17 +464,17 @@
 }
 
 #ifdef USE_64BIT_DRM_API
-status_t FwdLockEngine::onOpenDecryptSession(int uniqueId,
+status_t FwdLockEngine::onOpenDecryptSession(int /*uniqueId*/,
                                              DecryptHandle* decryptHandle,
                                              int fd,
                                              off64_t offset,
-                                             off64_t length) {
+                                             off64_t /*length*/) {
 #else
-status_t FwdLockEngine::onOpenDecryptSession(int uniqueId,
+status_t FwdLockEngine::onOpenDecryptSession(int /*uniqueId*/,
                                              DecryptHandle* decryptHandle,
                                              int fd,
                                              int offset,
-                                             int length) {
+                                             int /*length*/) {
 #endif
     status_t result = DRM_ERROR_CANNOT_HANDLE;
     int fileDesc = -1;
@@ -552,7 +552,7 @@
     return result;
 }
 
-status_t FwdLockEngine::onCloseDecryptSession(int uniqueId,
+status_t FwdLockEngine::onCloseDecryptSession(int /*uniqueId*/,
                                               DecryptHandle* decryptHandle) {
     status_t result = DRM_ERROR_UNKNOWN;
     LOG_VERBOSE("FwdLockEngine::onCloseDecryptSession");
@@ -584,37 +584,39 @@
     return result;
 }
 
-status_t FwdLockEngine::onInitializeDecryptUnit(int uniqueId,
-                                                DecryptHandle* decryptHandle,
-                                                int decryptUnitId,
-                                                const DrmBuffer* headerInfo) {
+status_t FwdLockEngine::onInitializeDecryptUnit(int /*uniqueId*/,
+                                                DecryptHandle* /*decryptHandle*/,
+                                                int /*decryptUnitId*/,
+                                                const DrmBuffer* /*headerInfo*/) {
     ALOGE("FwdLockEngine::onInitializeDecryptUnit is not supported for this DRM scheme");
     return DRM_ERROR_UNKNOWN;
 }
 
-status_t FwdLockEngine::onDecrypt(int uniqueId, DecryptHandle* decryptHandle, int decryptUnitId,
-            const DrmBuffer* encBuffer, DrmBuffer** decBuffer, DrmBuffer* IV) {
+status_t FwdLockEngine::onDecrypt(int /*uniqueId*/,
+            DecryptHandle* /*decryptHandle*/, int /*decryptUnitId*/,
+            const DrmBuffer* /*encBuffer*/, DrmBuffer** /*decBuffer*/,
+            DrmBuffer* /*IV*/) {
     ALOGE("FwdLockEngine::onDecrypt is not supported for this DRM scheme");
     return DRM_ERROR_UNKNOWN;
 }
 
-status_t FwdLockEngine::onDecrypt(int uniqueId,
-                                  DecryptHandle* decryptHandle,
-                                  int decryptUnitId,
-                                  const DrmBuffer* encBuffer,
-                                  DrmBuffer** decBuffer) {
+status_t FwdLockEngine::onDecrypt(int /*uniqueId*/,
+                                  DecryptHandle* /*decryptHandle*/,
+                                  int /*decryptUnitId*/,
+                                  const DrmBuffer* /*encBuffer*/,
+                                  DrmBuffer** /*decBuffer*/) {
     ALOGE("FwdLockEngine::onDecrypt is not supported for this DRM scheme");
     return DRM_ERROR_UNKNOWN;
 }
 
-status_t FwdLockEngine::onFinalizeDecryptUnit(int uniqueId,
-                                              DecryptHandle* decryptHandle,
-                                              int decryptUnitId) {
+status_t FwdLockEngine::onFinalizeDecryptUnit(int /*uniqueId*/,
+                                              DecryptHandle* /*decryptHandle*/,
+                                              int /*decryptUnitId*/) {
     ALOGE("FwdLockEngine::onFinalizeDecryptUnit is not supported for this DRM scheme");
     return DRM_ERROR_UNKNOWN;
 }
 
-ssize_t FwdLockEngine::onRead(int uniqueId,
+ssize_t FwdLockEngine::onRead(int /*uniqueId*/,
                               DecryptHandle* decryptHandle,
                               void* buffer,
                               int numBytes) {
@@ -640,10 +642,10 @@
 }
 
 #ifdef USE_64BIT_DRM_API
-off64_t FwdLockEngine::onLseek(int uniqueId, DecryptHandle* decryptHandle,
+off64_t FwdLockEngine::onLseek(int /*uniqueId*/, DecryptHandle* decryptHandle,
                                off64_t offset, int whence) {
 #else
-off_t FwdLockEngine::onLseek(int uniqueId, DecryptHandle* decryptHandle,
+off_t FwdLockEngine::onLseek(int /*uniqueId*/, DecryptHandle* decryptHandle,
                              off_t offset, int whence) {
 #endif
     off_t offval = -1;
diff --git a/drm/libdrmframework/plugins/passthru/src/DrmPassthruPlugIn.cpp b/drm/libdrmframework/plugins/passthru/src/DrmPassthruPlugIn.cpp
index 084e323..7f5b0ec 100644
--- a/drm/libdrmframework/plugins/passthru/src/DrmPassthruPlugIn.cpp
+++ b/drm/libdrmframework/plugins/passthru/src/DrmPassthruPlugIn.cpp
@@ -52,12 +52,12 @@
 
 }
 
-DrmMetadata* DrmPassthruPlugIn::onGetMetadata(int uniqueId, const String8* path) {
+DrmMetadata* DrmPassthruPlugIn::onGetMetadata(int /*uniqueId*/, const String8* /*path*/) {
     return NULL;
 }
 
 DrmConstraints* DrmPassthruPlugIn::onGetConstraints(
-        int uniqueId, const String8* path, int action) {
+        int uniqueId, const String8* /*path*/, int /*action*/) {
     ALOGV("DrmPassthruPlugIn::onGetConstraints From Path: %d", uniqueId);
     DrmConstraints* drmConstraints = new DrmConstraints();
 
@@ -108,7 +108,7 @@
 }
 
 status_t DrmPassthruPlugIn::onSetOnInfoListener(
-            int uniqueId, const IDrmEngine::OnInfoListener* infoListener) {
+            int uniqueId, const IDrmEngine::OnInfoListener* /*infoListener*/) {
     ALOGV("DrmPassthruPlugIn::onSetOnInfoListener : %d", uniqueId);
     return DRM_NO_ERROR;
 }
@@ -135,8 +135,8 @@
     return drmSupportInfo;
 }
 
-status_t DrmPassthruPlugIn::onSaveRights(int uniqueId, const DrmRights& drmRights,
-            const String8& rightsPath, const String8& contentPath) {
+status_t DrmPassthruPlugIn::onSaveRights(int uniqueId, const DrmRights& /*drmRights*/,
+            const String8& /*rightsPath*/, const String8& /*contentPath*/) {
     ALOGV("DrmPassthruPlugIn::onSaveRights : %d", uniqueId);
     return DRM_NO_ERROR;
 }
@@ -157,49 +157,50 @@
     return drmInfo;
 }
 
-bool DrmPassthruPlugIn::onCanHandle(int uniqueId, const String8& path) {
+bool DrmPassthruPlugIn::onCanHandle(int /*uniqueId*/, const String8& path) {
     ALOGV("DrmPassthruPlugIn::canHandle: %s ", path.string());
     String8 extension = path.getPathExtension();
     extension.toLower();
     return (String8(".passthru") == extension);
 }
 
-String8 DrmPassthruPlugIn::onGetOriginalMimeType(int uniqueId, const String8& path, int fd) {
+String8 DrmPassthruPlugIn::onGetOriginalMimeType(int uniqueId,
+            const String8& /*path*/, int /*fd*/) {
     ALOGV("DrmPassthruPlugIn::onGetOriginalMimeType() : %d", uniqueId);
     return String8("video/passthru");
 }
 
 int DrmPassthruPlugIn::onGetDrmObjectType(
-            int uniqueId, const String8& path, const String8& mimeType) {
+            int uniqueId, const String8& /*path*/, const String8& /*mimeType*/) {
     ALOGV("DrmPassthruPlugIn::onGetDrmObjectType() : %d", uniqueId);
     return DrmObjectType::UNKNOWN;
 }
 
-int DrmPassthruPlugIn::onCheckRightsStatus(int uniqueId, const String8& path, int action) {
+int DrmPassthruPlugIn::onCheckRightsStatus(int uniqueId, const String8& /*path*/, int /*action*/) {
     ALOGV("DrmPassthruPlugIn::onCheckRightsStatus() : %d", uniqueId);
     int rightsStatus = RightsStatus::RIGHTS_VALID;
     return rightsStatus;
 }
 
-status_t DrmPassthruPlugIn::onConsumeRights(int uniqueId, DecryptHandle* decryptHandle,
-            int action, bool reserve) {
+status_t DrmPassthruPlugIn::onConsumeRights(int uniqueId,
+            DecryptHandle* /*decryptHandle*/, int /*action*/, bool /*reserve*/) {
     ALOGV("DrmPassthruPlugIn::onConsumeRights() : %d", uniqueId);
     return DRM_NO_ERROR;
 }
 
-status_t DrmPassthruPlugIn::onSetPlaybackStatus(int uniqueId, DecryptHandle* decryptHandle,
-            int playbackStatus, int64_t position) {
+status_t DrmPassthruPlugIn::onSetPlaybackStatus(int uniqueId,
+            DecryptHandle* /*decryptHandle*/, int /*playbackStatus*/, int64_t /*position*/) {
     ALOGV("DrmPassthruPlugIn::onSetPlaybackStatus() : %d", uniqueId);
     return DRM_NO_ERROR;
 }
 
-bool DrmPassthruPlugIn::onValidateAction(int uniqueId, const String8& path,
-            int action, const ActionDescription& description) {
+bool DrmPassthruPlugIn::onValidateAction(int uniqueId,
+            const String8& /*path*/, int /*action*/, const ActionDescription& /*description*/) {
     ALOGV("DrmPassthruPlugIn::onValidateAction() : %d", uniqueId);
     return true;
 }
 
-status_t DrmPassthruPlugIn::onRemoveRights(int uniqueId, const String8& path) {
+status_t DrmPassthruPlugIn::onRemoveRights(int uniqueId, const String8& /*path*/) {
     ALOGV("DrmPassthruPlugIn::onRemoveRights() : %d", uniqueId);
     return DRM_NO_ERROR;
 }
@@ -209,13 +210,13 @@
     return DRM_NO_ERROR;
 }
 
-status_t DrmPassthruPlugIn::onOpenConvertSession(int uniqueId, int convertId) {
+status_t DrmPassthruPlugIn::onOpenConvertSession(int uniqueId, int /*convertId*/) {
     ALOGV("DrmPassthruPlugIn::onOpenConvertSession() : %d", uniqueId);
     return DRM_NO_ERROR;
 }
 
 DrmConvertedStatus* DrmPassthruPlugIn::onConvertData(
-            int uniqueId, int convertId, const DrmBuffer* inputData) {
+            int uniqueId, int /*convertId*/, const DrmBuffer* inputData) {
     ALOGV("DrmPassthruPlugIn::onConvertData() : %d", uniqueId);
     DrmBuffer* convertedData = NULL;
 
@@ -229,13 +230,13 @@
     return new DrmConvertedStatus(DrmConvertedStatus::STATUS_OK, convertedData, 0 /*offset*/);
 }
 
-DrmConvertedStatus* DrmPassthruPlugIn::onCloseConvertSession(int uniqueId, int convertId) {
+DrmConvertedStatus* DrmPassthruPlugIn::onCloseConvertSession(int uniqueId, int /*convertId*/) {
     ALOGV("DrmPassthruPlugIn::onCloseConvertSession() : %d", uniqueId);
     return new DrmConvertedStatus(DrmConvertedStatus::STATUS_OK, NULL, 0 /*offset*/);
 }
 
 status_t DrmPassthruPlugIn::onOpenDecryptSession(
-            int uniqueId, DecryptHandle* decryptHandle, int fd, off64_t offset, off64_t length) {
+            int uniqueId, DecryptHandle* decryptHandle, int /*fd*/, off64_t /*offset*/, off64_t /*length*/) {
     ALOGV("DrmPassthruPlugIn::onOpenDecryptSession() : %d", uniqueId);
 
 #ifdef ENABLE_PASSTHRU_DECRYPTION
@@ -250,7 +251,7 @@
 }
 
 status_t DrmPassthruPlugIn::onOpenDecryptSession(
-            int uniqueId, DecryptHandle* decryptHandle, const char* uri) {
+            int /*uniqueId*/, DecryptHandle* /*decryptHandle*/, const char* /*uri*/) {
     return DRM_ERROR_CANNOT_HANDLE;
 }
 
@@ -265,14 +266,14 @@
     return DRM_NO_ERROR;
 }
 
-status_t DrmPassthruPlugIn::onInitializeDecryptUnit(int uniqueId, DecryptHandle* decryptHandle,
-            int decryptUnitId, const DrmBuffer* headerInfo) {
+status_t DrmPassthruPlugIn::onInitializeDecryptUnit(int uniqueId, DecryptHandle* /*decryptHandle*/,
+            int /*decryptUnitId*/, const DrmBuffer* /*headerInfo*/) {
     ALOGV("DrmPassthruPlugIn::onInitializeDecryptUnit() : %d", uniqueId);
     return DRM_NO_ERROR;
 }
 
-status_t DrmPassthruPlugIn::onDecrypt(int uniqueId, DecryptHandle* decryptHandle,
-            int decryptUnitId, const DrmBuffer* encBuffer, DrmBuffer** decBuffer, DrmBuffer* IV) {
+status_t DrmPassthruPlugIn::onDecrypt(int uniqueId, DecryptHandle* /*decryptHandle*/,
+            int /*decryptUnitId*/, const DrmBuffer* encBuffer, DrmBuffer** decBuffer, DrmBuffer* /*IV*/) {
     ALOGV("DrmPassthruPlugIn::onDecrypt() : %d", uniqueId);
     /**
      * As a workaround implementation passthru would copy the given
@@ -293,13 +294,13 @@
 }
 
 status_t DrmPassthruPlugIn::onFinalizeDecryptUnit(
-            int uniqueId, DecryptHandle* decryptHandle, int decryptUnitId) {
+            int uniqueId, DecryptHandle* /*decryptHandle*/, int /*decryptUnitId*/) {
     ALOGV("DrmPassthruPlugIn::onFinalizeDecryptUnit() : %d", uniqueId);
     return DRM_NO_ERROR;
 }
 
-ssize_t DrmPassthruPlugIn::onPread(int uniqueId, DecryptHandle* decryptHandle,
-            void* buffer, ssize_t numBytes, off64_t offset) {
+ssize_t DrmPassthruPlugIn::onPread(int uniqueId, DecryptHandle* /*decryptHandle*/,
+            void* /*buffer*/, ssize_t /*numBytes*/, off64_t /*offset*/) {
     ALOGV("DrmPassthruPlugIn::onPread() : %d", uniqueId);
     return 0;
 }
diff --git a/include/camera/ICameraServiceProxy.h b/include/camera/ICameraServiceProxy.h
index 12a555f..2613c01 100644
--- a/include/camera/ICameraServiceProxy.h
+++ b/include/camera/ICameraServiceProxy.h
@@ -23,15 +23,30 @@
 
 namespace android {
 
+/**
+ * Interface from native camera service to managed-side camera service proxy.
+ *
+ * Keep in sync with frameworks/base/core/java/android/hardware/ICameraServiceProxy.aidl
+ *
+ */
 class ICameraServiceProxy : public IInterface {
 public:
     enum {
         PING_FOR_USER_UPDATE = IBinder::FIRST_CALL_TRANSACTION,
+        NOTIFY_CAMERA_STATE
+    };
+
+    enum CameraState {
+        CAMERA_STATE_OPEN,
+        CAMERA_STATE_ACTIVE,
+        CAMERA_STATE_IDLE,
+        CAMERA_STATE_CLOSED
     };
 
     DECLARE_META_INTERFACE(CameraServiceProxy);
 
     virtual void pingForUserUpdate() = 0;
+    virtual void notifyCameraState(String16 cameraId, CameraState newCameraState) = 0;
 };
 
 class BnCameraServiceProxy: public BnInterface<ICameraServiceProxy>
@@ -48,5 +63,3 @@
 }; // namespace android
 
 #endif // ANDROID_HARDWARE_ICAMERASERVICEPROXY_H
-
-
diff --git a/include/camera/camera2/ICameraDeviceUser.h b/include/camera/camera2/ICameraDeviceUser.h
index a7bf8ab..4d8eb53 100644
--- a/include/camera/camera2/ICameraDeviceUser.h
+++ b/include/camera/camera2/ICameraDeviceUser.h
@@ -140,6 +140,11 @@
     virtual status_t        prepare(int streamId) = 0;
 
     /**
+     * Preallocate up to maxCount buffers for a given output stream asynchronously.
+     */
+    virtual status_t        prepare2(int maxCount, int streamId) = 0;
+
+    /**
      * Free all unused buffers for a given output stream.
      */
     virtual status_t        tearDown(int streamId) = 0;
diff --git a/include/drm/drm_framework_common.h b/include/drm/drm_framework_common.h
index 637409c..0750406 100644
--- a/include/drm/drm_framework_common.h
+++ b/include/drm/drm_framework_common.h
@@ -23,7 +23,7 @@
 #include <utils/String8.h>
 #include <utils/Errors.h>
 
-#define INVALID_VALUE -1
+#define INVALID_VALUE (-1)
 
 namespace android {
 
diff --git a/include/media/AudioPolicy.h b/include/media/AudioPolicy.h
index feed402..098c8be 100644
--- a/include/media/AudioPolicy.h
+++ b/include/media/AudioPolicy.h
@@ -34,7 +34,7 @@
 #define RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET \
     (RULE_EXCLUSION_MASK|RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET)
 
-#define MIX_TYPE_INVALID -1
+#define MIX_TYPE_INVALID (-1)
 #define MIX_TYPE_PLAYERS 0
 #define MIX_TYPE_RECORDERS 1
 
@@ -43,7 +43,7 @@
 // keep in sync with AudioSystem.java
 #define DYNAMIC_POLICY_EVENT_MIX_STATE_UPDATE 0
 
-#define MIX_STATE_DISABLED -1
+#define MIX_STATE_DISABLED (-1)
 #define MIX_STATE_IDLE 0
 #define MIX_STATE_MIXING 1
 
diff --git a/include/media/AudioSystem.h b/include/media/AudioSystem.h
index 06116a5..26a0bb2 100644
--- a/include/media/AudioSystem.h
+++ b/include/media/AudioSystem.h
@@ -399,6 +399,7 @@
         uint32_t                            mInSamplingRate;
         audio_format_t                      mInFormat;
         audio_channel_mask_t                mInChannelMask;
+        sp<AudioIoDescriptor> getIoDescriptor_l(audio_io_handle_t ioHandle);
     };
 
     class AudioPolicyServiceClient: public IBinder::DeathRecipient,
diff --git a/include/media/IOMX.h b/include/media/IOMX.h
index 3d29e4a..27ad694 100644
--- a/include/media/IOMX.h
+++ b/include/media/IOMX.h
@@ -249,6 +249,12 @@
     virtual status_t onTransact(
             uint32_t code, const Parcel &data, Parcel *reply,
             uint32_t flags = 0);
+
+protected:
+    // check if the codec is secure.
+    virtual bool isSecure(IOMX::node_id node) {
+        return false;
+    }
 };
 
 class BnOMXObserver : public BnInterface<IOMXObserver> {
diff --git a/include/media/MediaCodecInfo.h b/include/media/MediaCodecInfo.h
index 4067b47..ac5b075 100644
--- a/include/media/MediaCodecInfo.h
+++ b/include/media/MediaCodecInfo.h
@@ -33,7 +33,6 @@
 
 struct AMessage;
 class Parcel;
-struct CodecCapabilities;
 
 typedef KeyedVector<AString, AString> CodecSettings;
 
@@ -44,12 +43,19 @@
     };
 
     struct Capabilities : public RefBase {
+        enum {
+            // decoder flags
+            kFlagSupportsAdaptivePlayback = 1 << 0,
+            kFlagSupportsSecurePlayback = 1 << 1,
+            kFlagSupportsTunneledPlayback = 1 << 2,
+        };
+
         void getSupportedProfileLevels(Vector<ProfileLevel> *profileLevels) const;
         void getSupportedColorFormats(Vector<uint32_t> *colorFormats) const;
         uint32_t getFlags() const;
         const sp<AMessage> getDetails() const;
 
-    private:
+    protected:
         Vector<ProfileLevel> mProfileLevels;
         Vector<uint32_t> mColorFormats;
         uint32_t mFlags;
@@ -57,6 +63,7 @@
 
         Capabilities();
 
+    private:
         // read object from parcel even if object creation fails
         static sp<Capabilities> FromParcel(const Parcel &parcel);
         status_t writeToParcel(Parcel *parcel) const;
@@ -66,6 +73,14 @@
         friend class MediaCodecInfo;
     };
 
+    // Use a subclass to allow setting fields on construction without allowing
+    // to do the same throughout the framework.
+    struct CapabilitiesBuilder : public Capabilities {
+        void addProfileLevel(uint32_t profile, uint32_t level);
+        void addColorFormat(uint32_t format);
+        void addFlags(uint32_t flags);
+    };
+
     bool isEncoder() const;
     bool hasQuirk(const char *name) const;
     void getSupportedMimes(Vector<AString> *mimes) const;
@@ -107,7 +122,8 @@
     void addQuirk(const char *name);
     status_t addMime(const char *mime);
     status_t updateMime(const char *mime);
-    status_t initializeCapabilities(const CodecCapabilities &caps);
+
+    status_t initializeCapabilities(const sp<Capabilities> &caps);
     void addDetail(const AString &key, const AString &value);
     void addFeature(const AString &key, int32_t value);
     void addFeature(const AString &key, const char *value);
diff --git a/include/media/stagefright/ACodec.h b/include/media/stagefright/ACodec.h
index 8b5b862..69b4045 100644
--- a/include/media/stagefright/ACodec.h
+++ b/include/media/stagefright/ACodec.h
@@ -50,6 +50,10 @@
     virtual void initiateStart();
     virtual void initiateShutdown(bool keepComponentAllocated = false);
 
+    virtual status_t queryCapabilities(
+            const AString &name, const AString &mime, bool isEncoder,
+            sp<MediaCodecInfo::Capabilities> *caps);
+
     virtual status_t setSurface(const sp<Surface> &surface);
 
     virtual void signalFlush();
@@ -91,6 +95,14 @@
             int width, int height, int rate, int bitrate,
             OMX_VIDEO_AVCPROFILETYPE profile = OMX_VIDEO_AVCProfileBaseline);
 
+    // Quirk still supported, even though deprecated
+    enum Quirks {
+        kRequiresAllocateBufferOnInputPorts   = 1,
+        kRequiresAllocateBufferOnOutputPorts  = 2,
+    };
+
+    static status_t getOMXChannelMapping(size_t numChannels, OMX_AUDIO_CHANNELTYPE map[]);
+
 protected:
     virtual ~ACodec();
 
@@ -212,6 +224,7 @@
     sp<IdleToLoadedState> mIdleToLoadedState;
     sp<FlushingState> mFlushingState;
     sp<SkipCutBuffer> mSkipCutBuffer;
+    int32_t mSampleRate;
 
     AString mComponentName;
     uint32_t mFlags;
@@ -301,6 +314,10 @@
             ssize_t *index = NULL);
 
     status_t setComponentRole(bool isEncoder, const char *mime);
+    static const char *getComponentRole(bool isEncoder, const char *mime);
+    static status_t setComponentRole(
+            const sp<IOMX> &omx, IOMX::node_id node, const char *role);
+
     status_t configureCodec(const char *mime, const sp<AMessage> &msg);
 
     status_t configureTunneledVideoPlayback(int32_t audioHwSync,
diff --git a/include/media/stagefright/AudioPlayer.h b/include/media/stagefright/AudioPlayer.h
index e0cd965..86ce50d 100644
--- a/include/media/stagefright/AudioPlayer.h
+++ b/include/media/stagefright/AudioPlayer.h
@@ -20,7 +20,6 @@
 
 #include <media/MediaPlayerInterface.h>
 #include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/TimeSource.h>
 #include <utils/threads.h>
 
 namespace android {
@@ -30,7 +29,7 @@
 struct AwesomePlayer;
 class MediaSource;
 
-class AudioPlayer : public TimeSource {
+class AudioPlayer {
 public:
     enum {
         REACHED_EOS,
@@ -46,29 +45,18 @@
     };
 
     AudioPlayer(const sp<MediaPlayerBase::AudioSink> &audioSink,
-                uint32_t flags = 0,
-                AwesomePlayer *audioObserver = NULL);
+                uint32_t flags = 0);
 
     virtual ~AudioPlayer();
 
     // Caller retains ownership of "source".
     void setSource(const sp<MediaSource> &source);
 
-    // Return time in us.
-    virtual int64_t getRealTimeUs();
-
     status_t start(bool sourceAlreadyStarted = false);
 
     void pause(bool playPendingSamples = false);
     status_t resume();
 
-    // Returns the timestamp of the last buffer played (in us).
-    int64_t getMediaTimeUs();
-
-    // Returns true iff a mapping is established, i.e. the AudioPlayer
-    // has played at least one frame of audio.
-    bool getMediaTimeMapping(int64_t *realtime_us, int64_t *mediatime_us);
-
     status_t seekTo(int64_t time_us);
 
     bool isSeeking();
@@ -77,10 +65,7 @@
     status_t setPlaybackRate(const AudioPlaybackRate &rate);
     status_t getPlaybackRate(AudioPlaybackRate *rate /* nonnull */);
 
-    void notifyAudioEOS();
-
 private:
-    friend class VideoEditorAudioPlayer;
     sp<MediaSource> mSource;
     sp<AudioTrack> mAudioTrack;
 
@@ -109,8 +94,6 @@
     MediaBuffer *mFirstBuffer;
 
     sp<MediaPlayerBase::AudioSink> mAudioSink;
-    AwesomePlayer *mObserver;
-    int64_t mPinnedTimeUs;
 
     bool mPlaying;
     int64_t mStartPosUs;
@@ -126,11 +109,8 @@
 
     size_t fillBuffer(void *data, size_t size);
 
-    int64_t getRealTimeUsLocked() const;
-
     void reset();
 
-    uint32_t getNumFramesPendingPlayout() const;
     int64_t getOutputPlayPositionUs_l();
 
     bool allowDeepBuffering() const { return (mCreateFlags & ALLOW_DEEP_BUFFERING) != 0; }
diff --git a/include/media/stagefright/ClockEstimator.h b/include/media/stagefright/ClockEstimator.h
deleted file mode 100644
index 1455b7f..0000000
--- a/include/media/stagefright/ClockEstimator.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
-**
-** Copyright 2014, 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 CLOCK_ESTIMATOR_H_
-
-#define CLOCK_ESTIMATOR_H_
-
-#include "foundation/ABase.h"
-#include <utils/RefBase.h>
-#include <utils/Vector.h>
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-struct ClockEstimator : RefBase {
-    virtual double estimate(double x, double y) = 0;
-    virtual void reset() = 0;
-};
-
-struct WindowedLinearFitEstimator : ClockEstimator {
-    struct LinearFit {
-        /**
-         * Fit y = a * x + b, where each input has a weight
-         */
-        double mX;  // sum(w_i * x_i)
-        double mXX; // sum(w_i * x_i^2)
-        double mY;  // sum(w_i * y_i)
-        double mYY; // sum(w_i * y_i^2)
-        double mXY; // sum(w_i * x_i * y_i)
-        double mW;  // sum(w_i)
-
-        LinearFit();
-        void reset();
-        void combine(const LinearFit &lf);
-        void add(double x, double y, double w);
-        void scale(double w);
-        double interpolate(double x);
-        double size() const;
-
-        DISALLOW_EVIL_CONSTRUCTORS(LinearFit);
-    };
-
-    /**
-     * Estimator for f(x) = y' where input y' is noisy, but
-     * theoretically linear:
-     *
-     *      y' =~ y = a * x + b
-     *
-     * It uses linear fit regression over a tapering rolling window
-     * to get an estimate for y (from the current and past inputs
-     * (x, y')).
-     *
-     *     ____________
-     *    /|          |\
-     *   / |          | \
-     *  /  |          |  \   <--- new data (x, y')
-     * /   |   main   |   \
-     * <--><----------><-->
-     * tail            head
-     *
-     * weight is 1 under the main window, tapers exponentially by
-     * the factors given in the head and the tail.
-     *
-     * Assuming that x and y' are monotonic, that x is somewhat
-     * evenly sampled, and that a =~ 1, the estimated y is also
-     * going to be monotonic.
-     */
-    WindowedLinearFitEstimator(
-            size_t headLength = 5, double headFactor = 0.5,
-            size_t mainLength = 0, double tailFactor = 0.99);
-
-    virtual void reset();
-
-    // add a new sample (x -> y') and return an estimated value for the true y
-    virtual double estimate(double x, double y);
-
-private:
-    Vector<double> mXHistory; // circular buffer
-    Vector<double> mYHistory; // circular buffer
-    LinearFit mHead;
-    LinearFit mMain;
-    LinearFit mTail;
-    double mHeadFactorInv;
-    double mTailFactor;
-    double mFirstWeight;
-    size_t mHistoryLength;
-    size_t mHeadLength;
-    size_t mNumSamples;
-    size_t mSampleIx;
-
-    DISALLOW_EVIL_CONSTRUCTORS(WindowedLinearFitEstimator);
-};
-
-}; // namespace android
-
-#endif
diff --git a/include/media/stagefright/CodecBase.h b/include/media/stagefright/CodecBase.h
index bb36052..1a2bcdb 100644
--- a/include/media/stagefright/CodecBase.h
+++ b/include/media/stagefright/CodecBase.h
@@ -21,6 +21,7 @@
 #include <stdint.h>
 #include <media/IOMX.h>
 
+#include <media/MediaCodecInfo.h>
 #include <media/stagefright/foundation/AHandler.h>
 
 namespace android {
@@ -59,6 +60,10 @@
     // require an explicit message handler
     virtual void onMessageReceived(const sp<AMessage> &msg) = 0;
 
+    virtual status_t queryCapabilities(
+            const AString &name, const AString &mime, bool isEncoder,
+            sp<MediaCodecInfo::Capabilities> *caps /* nonnull */) { return INVALID_OPERATION; }
+
     virtual status_t setSurface(const sp<Surface> &surface) { return INVALID_OPERATION; }
 
     virtual void signalFlush() = 0;
diff --git a/include/media/stagefright/FileSource.h b/include/media/stagefright/FileSource.h
index a981d1c..266168b 100644
--- a/include/media/stagefright/FileSource.h
+++ b/include/media/stagefright/FileSource.h
@@ -56,7 +56,7 @@
     sp<DecryptHandle> mDecryptHandle;
     DrmManagerClient *mDrmManagerClient;
     int64_t mDrmBufOffset;
-    size_t mDrmBufSize;
+    ssize_t mDrmBufSize;
     unsigned char *mDrmBuf;
 
     ssize_t readAtDRM(off64_t offset, void *data, size_t size);
diff --git a/include/media/stagefright/MediaCodec.h b/include/media/stagefright/MediaCodec.h
index c10963d..c187e4b 100644
--- a/include/media/stagefright/MediaCodec.h
+++ b/include/media/stagefright/MediaCodec.h
@@ -20,6 +20,7 @@
 
 #include <gui/IGraphicBufferProducer.h>
 #include <media/hardware/CryptoAPI.h>
+#include <media/MediaCodecInfo.h>
 #include <media/MediaResource.h>
 #include <media/stagefright/foundation/AHandler.h>
 #include <media/stagefright/FrameRenderTracker.h>
@@ -64,15 +65,20 @@
     static const pid_t kNoPid = -1;
 
     static sp<MediaCodec> CreateByType(
-            const sp<ALooper> &looper, const char *mime, bool encoder, status_t *err = NULL,
+            const sp<ALooper> &looper, const AString &mime, bool encoder, status_t *err = NULL,
             pid_t pid = kNoPid);
 
     static sp<MediaCodec> CreateByComponentName(
-            const sp<ALooper> &looper, const char *name, status_t *err = NULL,
+            const sp<ALooper> &looper, const AString &name, status_t *err = NULL,
             pid_t pid = kNoPid);
 
     static sp<PersistentSurface> CreatePersistentInputSurface();
 
+    // utility method to query capabilities
+    static status_t QueryCapabilities(
+            const AString &name, const AString &mime, bool isEncoder,
+            sp<MediaCodecInfo::Capabilities> *caps /* nonnull */);
+
     status_t configure(
             const sp<AMessage> &format,
             const sp<Surface> &nativeWindow,
@@ -176,7 +182,7 @@
 
 private:
     // used by ResourceManagerClient
-    status_t reclaim();
+    status_t reclaim(bool force = false);
     friend struct ResourceManagerClient;
 
 private:
@@ -339,6 +345,8 @@
 
     MediaCodec(const sp<ALooper> &looper, pid_t pid);
 
+    static sp<CodecBase> GetCodecBase(const AString &name, bool nameIsType = false);
+
     static status_t PostAndAwaitResponse(
             const sp<AMessage> &msg, sp<AMessage> *response);
 
@@ -385,6 +393,9 @@
     uint64_t getGraphicBufferSize();
     void addResource(const String8 &type, const String8 &subtype, uint64_t value);
 
+    bool hasPendingBuffer(int portIndex);
+    bool hasPendingBuffer();
+
     /* called to get the last codec error when the sticky flag is set.
      * if no such codec error is found, returns UNKNOWN_ERROR.
      */
diff --git a/include/media/stagefright/MediaCodecList.h b/include/media/stagefright/MediaCodecList.h
index 3aaa032..44dbde0 100644
--- a/include/media/stagefright/MediaCodecList.h
+++ b/include/media/stagefright/MediaCodecList.h
@@ -47,6 +47,10 @@
     virtual size_t countCodecs() const;
 
     virtual sp<MediaCodecInfo> getCodecInfo(size_t index) const {
+        if (index >= mCodecInfos.size()) {
+            ALOGE("b/24445127");
+            return NULL;
+        }
         return mCodecInfos.itemAt(index);
     }
 
@@ -61,6 +65,22 @@
     // only to be used by MediaPlayerService
     void parseTopLevelXMLFile(const char *path, bool ignore_errors = false);
 
+    enum Flags {
+        kPreferSoftwareCodecs   = 1,
+        kHardwareCodecsOnly     = 2,
+    };
+
+    static void findMatchingCodecs(
+            const char *mime,
+            bool createEncoder,
+            uint32_t flags,
+            Vector<AString> *matching);
+
+    static uint32_t getQuirksFor(const char *mComponentName);
+
+    static bool isSoftwareCodec(const AString &componentName);
+
+
 private:
     class BinderDeathObserver : public IBinder::DeathRecipient {
         void binderDied(const wp<IBinder> &the_late_who __unused);
diff --git a/include/media/stagefright/MediaCodecSource.h b/include/media/stagefright/MediaCodecSource.h
index 71f58a9..d8c70fe 100644
--- a/include/media/stagefright/MediaCodecSource.h
+++ b/include/media/stagefright/MediaCodecSource.h
@@ -19,16 +19,18 @@
 
 #include <media/stagefright/foundation/ABase.h>
 #include <media/stagefright/foundation/AHandlerReflector.h>
+#include <media/stagefright/foundation/Mutexed.h>
 #include <media/stagefright/MediaSource.h>
 
+#include <gui/IGraphicBufferConsumer.h>
+
 namespace android {
 
 struct ALooper;
-class AMessage;
+struct AMessage;
 struct AReplyToken;
 class IGraphicBufferProducer;
-class IGraphicBufferConsumer;
-class MediaCodec;
+struct MediaCodec;
 class MetaData;
 
 struct MediaCodecSource : public MediaSource,
@@ -36,6 +38,7 @@
     enum FlagBits {
         FLAG_USE_SURFACE_INPUT      = 1,
         FLAG_USE_METADATA_INPUT     = 2,
+        FLAG_PREFER_SOFTWARE_CODEC  = 4,  // used for testing only
     };
 
     static sp<MediaCodecSource> Create(
@@ -75,6 +78,7 @@
         kWhatStart,
         kWhatStop,
         kWhatPause,
+        kWhatStopStalled,
     };
 
     MediaCodecSource(
@@ -122,12 +126,16 @@
     int64_t mFirstSampleTimeUs;
     List<int64_t> mDriftTimeQueue;
 
-    // following variables are protected by mOutputBufferLock
-    Mutex mOutputBufferLock;
-    Condition mOutputBufferCond;
-    List<MediaBuffer*> mOutputBufferQueue;
-    bool mEncoderReachedEOS;
-    status_t mErrorCode;
+    struct Output {
+        Output();
+        List<MediaBuffer*> mBufferQueue;
+        bool mEncoderReachedEOS;
+        status_t mErrorCode;
+        Condition mCond;
+    };
+    Mutexed<Output> mOutput;
+
+    int32_t mGeneration;
 
     DISALLOW_EVIL_CONSTRUCTORS(MediaCodecSource);
 };
diff --git a/include/media/stagefright/MediaSource.h b/include/media/stagefright/MediaSource.h
index a653db9..ed0d578 100644
--- a/include/media/stagefright/MediaSource.h
+++ b/include/media/stagefright/MediaSource.h
@@ -99,8 +99,9 @@
     };
 
     // Causes this source to suspend pulling data from its upstream source
-    // until a subsequent read-with-seek. Currently only supported by
-    // OMXCodec.
+    // until a subsequent read-with-seek. This is currently not supported
+    // as such by any source. E.g. MediaCodecSource does not susped its
+    // upstream source, and instead discard upstream data while paused.
     virtual status_t pause() {
         return ERROR_UNSUPPORTED;
     }
diff --git a/include/media/stagefright/OMXCodec.h b/include/media/stagefright/OMXCodec.h
deleted file mode 100644
index 7fabcb3..0000000
--- a/include/media/stagefright/OMXCodec.h
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef OMX_CODEC_H_
-
-#define OMX_CODEC_H_
-
-#include <android/native_window.h>
-#include <media/IOMX.h>
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MediaSource.h>
-#include <utils/threads.h>
-
-#include <OMX_Audio.h>
-
-namespace android {
-
-struct MediaCodecInfo;
-class MemoryDealer;
-struct OMXCodecObserver;
-struct CodecProfileLevel;
-class SkipCutBuffer;
-
-struct OMXCodec : public MediaSource,
-                  public MediaBufferObserver {
-    enum CreationFlags {
-        kPreferSoftwareCodecs    = 1,
-        kIgnoreCodecSpecificData = 2,
-
-        // The client wants to access the output buffer's video
-        // data for example for thumbnail extraction.
-        kClientNeedsFramebuffer  = 4,
-
-        // Request for software or hardware codecs. If request
-        // can not be fullfilled, Create() returns NULL.
-        kSoftwareCodecsOnly      = 8,
-        kHardwareCodecsOnly      = 16,
-
-        // Store meta data in video buffers
-        kStoreMetaDataInVideoBuffers = 32,
-
-        // Only submit one input buffer at one time.
-        kOnlySubmitOneInputBufferAtOneTime = 64,
-
-        // Enable GRALLOC_USAGE_PROTECTED for output buffers from native window
-        kEnableGrallocUsageProtected = 128,
-
-        // Secure decoding mode
-        kUseSecureInputBuffers = 256,
-    };
-    static sp<MediaSource> Create(
-            const sp<IOMX> &omx,
-            const sp<MetaData> &meta, bool createEncoder,
-            const sp<MediaSource> &source,
-            const char *matchComponentName = NULL,
-            uint32_t flags = 0,
-            const sp<ANativeWindow> &nativeWindow = NULL);
-
-    static void setComponentRole(
-            const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder,
-            const char *mime);
-
-    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();
-
-    // from MediaBufferObserver
-    virtual void signalBufferReturned(MediaBuffer *buffer);
-
-    enum Quirks {
-        kNeedsFlushBeforeDisable              = 1,
-        kWantsNALFragments                    = 2,
-        kRequiresLoadedToIdleAfterAllocation  = 4,
-        kRequiresAllocateBufferOnInputPorts   = 8,
-        kRequiresFlushCompleteEmulation       = 16,
-        kRequiresAllocateBufferOnOutputPorts  = 32,
-        kRequiresFlushBeforeShutdown          = 64,
-        kDefersOutputBufferAllocation         = 128,
-        kDecoderLiesAboutNumberOfChannels     = 256,
-        kInputBufferSizesAreBogus             = 512,
-        kSupportsMultipleFramesPerInputBuffer = 1024,
-        kRequiresLargerEncoderOutputBuffer    = 2048,
-        kOutputBuffersAreUnreadable           = 4096,
-    };
-
-    struct CodecNameAndQuirks {
-        String8 mName;
-        uint32_t mQuirks;
-    };
-
-    // for use by ACodec
-    static void findMatchingCodecs(
-            const char *mime,
-            bool createEncoder, const char *matchComponentName,
-            uint32_t flags,
-            Vector<CodecNameAndQuirks> *matchingCodecNamesAndQuirks);
-
-    static uint32_t getComponentQuirks(
-            const sp<MediaCodecInfo> &list);
-
-    static bool findCodecQuirks(const char *componentName, uint32_t *quirks);
-
-protected:
-    virtual ~OMXCodec();
-
-private:
-
-    // Make sure mLock is accessible to OMXCodecObserver
-    friend class OMXCodecObserver;
-
-    // Call this with mLock hold
-    void on_message(const omx_message &msg);
-
-    enum State {
-        DEAD,
-        LOADED,
-        LOADED_TO_IDLE,
-        IDLE_TO_EXECUTING,
-        EXECUTING,
-        EXECUTING_TO_IDLE,
-        IDLE_TO_LOADED,
-        RECONFIGURING,
-        ERROR
-    };
-
-    enum {
-        kPortIndexInput  = 0,
-        kPortIndexOutput = 1
-    };
-
-    enum PortStatus {
-        ENABLED,
-        DISABLING,
-        DISABLED,
-        ENABLING,
-        SHUTTING_DOWN,
-    };
-
-    enum BufferStatus {
-        OWNED_BY_US,
-        OWNED_BY_COMPONENT,
-        OWNED_BY_NATIVE_WINDOW,
-        OWNED_BY_CLIENT,
-    };
-
-    struct BufferInfo {
-        IOMX::buffer_id mBuffer;
-        BufferStatus mStatus;
-        sp<IMemory> mMem;
-        size_t mSize;
-        void *mData;
-        MediaBuffer *mMediaBuffer;
-    };
-
-    struct CodecSpecificData {
-        size_t mSize;
-        uint8_t mData[1];
-    };
-
-    sp<IOMX> mOMX;
-    bool mOMXLivesLocally;
-    IOMX::node_id mNode;
-    uint32_t mQuirks;
-
-    // Flags specified in the creation of the codec.
-    uint32_t mFlags;
-
-    bool mIsEncoder;
-    bool mIsVideo;
-    char *mMIME;
-    char *mComponentName;
-    sp<MetaData> mOutputFormat;
-    sp<MediaSource> mSource;
-    Vector<CodecSpecificData *> mCodecSpecificData;
-    size_t mCodecSpecificDataIndex;
-
-    sp<MemoryDealer> mDealer[2];
-
-    State mState;
-    Vector<BufferInfo> mPortBuffers[2];
-    PortStatus mPortStatus[2];
-    bool mInitialBufferSubmit;
-    bool mSignalledEOS;
-    status_t mFinalStatus;
-    bool mNoMoreOutputData;
-    bool mOutputPortSettingsHaveChanged;
-    int64_t mSeekTimeUs;
-    ReadOptions::SeekMode mSeekMode;
-    int64_t mTargetTimeUs;
-    bool mOutputPortSettingsChangedPending;
-    sp<SkipCutBuffer> mSkipCutBuffer;
-
-    MediaBuffer *mLeftOverBuffer;
-
-    Mutex mLock;
-    Condition mAsyncCompletion;
-
-    bool mPaused;
-
-    sp<ANativeWindow> mNativeWindow;
-
-    // The index in each of the mPortBuffers arrays of the buffer that will be
-    // submitted to OMX next.  This only applies when using buffers from a
-    // native window.
-    size_t mNextNativeBufferIndex[2];
-
-    // A list of indices into mPortStatus[kPortIndexOutput] filled with data.
-    List<size_t> mFilledBuffers;
-    Condition mBufferFilled;
-
-    // Used to record the decoding time for an output picture from
-    // a video encoder.
-    List<int64_t> mDecodingTimeList;
-
-    OMXCodec(const sp<IOMX> &omx, IOMX::node_id node,
-             uint32_t quirks, uint32_t flags,
-             bool isEncoder, const char *mime, const char *componentName,
-             const sp<MediaSource> &source,
-             const sp<ANativeWindow> &nativeWindow);
-
-    void addCodecSpecificData(const void *data, size_t size);
-    void clearCodecSpecificData();
-
-    void setComponentRole();
-
-    void setAMRFormat(bool isWAMR, int32_t bitRate);
-
-    status_t setAACFormat(
-            int32_t numChannels, int32_t sampleRate, int32_t bitRate,
-            int32_t aacProfile, bool isADTS);
-
-    status_t setAC3Format(int32_t numChannels, int32_t sampleRate);
-
-    void setG711Format(int32_t sampleRate, int32_t numChannels);
-
-    status_t setVideoPortFormatType(
-            OMX_U32 portIndex,
-            OMX_VIDEO_CODINGTYPE compressionFormat,
-            OMX_COLOR_FORMATTYPE colorFormat);
-
-    void setVideoInputFormat(
-            const char *mime, const sp<MetaData>& meta);
-
-    status_t setupBitRate(int32_t bitRate);
-    status_t setupErrorCorrectionParameters();
-    status_t setupH263EncoderParameters(const sp<MetaData>& meta);
-    status_t setupMPEG4EncoderParameters(const sp<MetaData>& meta);
-    status_t setupAVCEncoderParameters(const sp<MetaData>& meta);
-    status_t findTargetColorFormat(
-            const sp<MetaData>& meta, OMX_COLOR_FORMATTYPE *colorFormat);
-
-    status_t isColorFormatSupported(
-            OMX_COLOR_FORMATTYPE colorFormat, int portIndex);
-
-    // If profile/level is set in the meta data, its value in the meta
-    // data will be used; otherwise, the default value will be used.
-    status_t getVideoProfileLevel(const sp<MetaData>& meta,
-            const CodecProfileLevel& defaultProfileLevel,
-            CodecProfileLevel& profileLevel);
-
-    status_t setVideoOutputFormat(
-            const char *mime, const sp<MetaData>& meta);
-
-    void setImageOutputFormat(
-            OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height);
-
-    void setJPEGInputFormat(
-            OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize);
-
-    void setMinBufferSize(OMX_U32 portIndex, OMX_U32 size);
-
-    void setRawAudioFormat(
-            OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels);
-
-    status_t allocateBuffers();
-    status_t allocateBuffersOnPort(OMX_U32 portIndex);
-    status_t allocateOutputBuffersFromNativeWindow();
-
-    status_t queueBufferToNativeWindow(BufferInfo *info);
-    status_t cancelBufferToNativeWindow(BufferInfo *info);
-    BufferInfo* dequeueBufferFromNativeWindow();
-
-    status_t freeBuffersOnPort(
-            OMX_U32 portIndex, bool onlyThoseWeOwn = false);
-
-    status_t freeBuffer(OMX_U32 portIndex, size_t bufIndex);
-
-    bool drainInputBuffer(IOMX::buffer_id buffer);
-    void fillOutputBuffer(IOMX::buffer_id buffer);
-    bool drainInputBuffer(BufferInfo *info);
-    void fillOutputBuffer(BufferInfo *info);
-
-    void drainInputBuffers();
-    void fillOutputBuffers();
-
-    bool drainAnyInputBuffer();
-    BufferInfo *findInputBufferByDataPointer(void *ptr);
-    BufferInfo *findEmptyInputBuffer();
-
-    // Returns true iff a flush was initiated and a completion event is
-    // upcoming, false otherwise (A flush was not necessary as we own all
-    // the buffers on that port).
-    // This method will ONLY ever return false for a component with quirk
-    // "kRequiresFlushCompleteEmulation".
-    bool flushPortAsync(OMX_U32 portIndex);
-
-    void disablePortAsync(OMX_U32 portIndex);
-    status_t enablePortAsync(OMX_U32 portIndex);
-
-    static size_t countBuffersWeOwn(const Vector<BufferInfo> &buffers);
-    static bool isIntermediateState(State state);
-
-    void onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2);
-    void onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data);
-    void onStateChange(OMX_STATETYPE newState);
-    void onPortSettingsChanged(OMX_U32 portIndex);
-
-    void setState(State newState);
-
-    status_t init();
-    void initOutputFormat(const sp<MetaData> &inputFormat);
-    status_t initNativeWindow();
-
-    void initNativeWindowCrop();
-
-    void dumpPortStatus(OMX_U32 portIndex);
-
-    status_t configureCodec(const sp<MetaData> &meta);
-
-    status_t waitForBufferFilled_l();
-
-    int64_t getDecodingTimeUs();
-
-    status_t parseHEVCCodecSpecificData(
-            const void *data, size_t size,
-            unsigned *profile, unsigned *level);
-    status_t parseAVCCodecSpecificData(
-            const void *data, size_t size,
-            unsigned *profile, unsigned *level);
-
-    status_t stopOmxComponent_l();
-
-    OMXCodec(const OMXCodec &);
-    OMXCodec &operator=(const OMXCodec &);
-};
-
-struct CodecCapabilities {
-    enum {
-        kFlagSupportsAdaptivePlayback = 1 << 0,
-    };
-
-    String8 mComponentName;
-    Vector<CodecProfileLevel> mProfileLevels;
-    Vector<OMX_U32> mColorFormats;
-    uint32_t mFlags;
-};
-
-// Return a vector of componentNames with supported profile/level pairs
-// supporting the given mime type, if queryDecoders==true, returns components
-// that decode content of the given type, otherwise returns components
-// that encode content of the given type.
-// profile and level indications only make sense for h.263, mpeg4 and avc
-// video.
-// If hwCodecOnly==true, only returns hardware-based components, software and
-// hardware otherwise.
-// The profile/level values correspond to
-// OMX_VIDEO_H263PROFILETYPE, OMX_VIDEO_MPEG4PROFILETYPE,
-// OMX_VIDEO_AVCPROFILETYPE, OMX_VIDEO_H263LEVELTYPE, OMX_VIDEO_MPEG4LEVELTYPE
-// and OMX_VIDEO_AVCLEVELTYPE respectively.
-
-status_t QueryCodecs(
-        const sp<IOMX> &omx,
-        const char *mimeType, bool queryDecoders, bool hwCodecOnly,
-        Vector<CodecCapabilities> *results);
-
-status_t QueryCodecs(
-        const sp<IOMX> &omx,
-        const char *mimeType, bool queryDecoders,
-        Vector<CodecCapabilities> *results);
-
-status_t QueryCodec(
-        const sp<IOMX> &omx,
-        const char *componentName, const char *mime,
-        bool isEncoder,
-        CodecCapabilities *caps);
-
-status_t getOMXChannelMapping(size_t numChannels, OMX_AUDIO_CHANNELTYPE map[]);
-
-}  // namespace android
-
-#endif  // OMX_CODEC_H_
diff --git a/include/media/stagefright/SimpleDecodingSource.h b/include/media/stagefright/SimpleDecodingSource.h
new file mode 100644
index 0000000..07e1f79
--- /dev/null
+++ b/include/media/stagefright/SimpleDecodingSource.h
@@ -0,0 +1,108 @@
+/*
+ * 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 SIMPLE_DECODING_SOURCE_H_
+#define SIMPLE_DECODING_SOURCE_H_
+
+#include <system/window.h>
+
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/foundation/AString.h>
+#include <media/stagefright/foundation/Mutexed.h>
+
+#include <utils/Condition.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+
+struct ALooper;
+struct AMessage;
+class MediaBuffer;
+struct MediaCodec;
+class MetaData;
+
+class SimpleDecodingSource : public MediaSource {
+public:
+    // Creates a MediaSource that uses MediaCodec to decode a compressed input |source|.
+    // The selected codec can be influenced using |flags|. This source only supports the
+    // kPreferGoogleCodec and kNonGoogleCodecsOnly |flags| - MediaCodecList.
+    // You can pass in a target |nativeWindow| to render video directly onto a surface. In this
+    // case the source will return empty buffers.
+    // This source cannot be restarted (hence the name "Simple"), all reads are blocking, and
+    // does not support secure input or pausing.
+    // if |desiredCodec| is given, use this specific codec.
+    static sp<SimpleDecodingSource> Create(
+            const sp<MediaSource> &source, uint32_t flags = 0,
+            const sp<ANativeWindow> &nativeWindow = NULL,
+            const char *desiredCodec = NULL);
+
+    virtual ~SimpleDecodingSource();
+
+    // starts this source (and it's underlying source). |params| is ignored.
+    virtual status_t start(MetaData *params = NULL);
+
+    // stops this source (and it's underlying source).
+    virtual status_t stop();
+
+    // returns the output format of this source.
+    virtual sp<MetaData> getFormat();
+
+    // reads from the source. This call always blocks.
+    virtual status_t read(MediaBuffer **buffer, const ReadOptions *options);
+
+    // unsupported methods
+    virtual status_t pause() { return INVALID_OPERATION; }
+    virtual status_t setBuffers(const Vector<MediaBuffer *> &) { return INVALID_OPERATION; }
+
+private:
+    // Construct this using a codec, source and looper.
+    SimpleDecodingSource(
+            const sp<MediaCodec> &codec, const sp<MediaSource> &source, const sp<ALooper> &looper,
+            bool usingSurface, const sp<AMessage> &format);
+
+    sp<MediaCodec> mCodec;
+    sp<MediaSource> mSource;
+    sp<ALooper> mLooper;
+    bool mUsingSurface;
+    enum State {
+        INIT,
+        STARTED,
+        STOPPING,
+        STOPPED,
+        ERROR,
+    };
+    AString mComponentName;
+
+    struct ProtectedState {
+        ProtectedState(const sp<AMessage> &format);
+        bool mReading;
+        Condition mReadCondition;
+
+        sp<AMessage> mFormat;
+        State mState;
+        bool mQueuedInputEOS;
+        bool mGotOutputEOS;
+    };
+    Mutexed<ProtectedState> mProtectedState;
+
+    // do the actual reading
+    status_t doRead(
+            Mutexed<ProtectedState>::Locked &me, MediaBuffer **buffer, const ReadOptions *options);
+};
+
+} // namespace android
+
+#endif
diff --git a/include/media/stagefright/TimeSource.h b/include/media/stagefright/TimeSource.h
deleted file mode 100644
index 8f11e14..0000000
--- a/include/media/stagefright/TimeSource.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef TIME_SOURCE_H_
-
-#define TIME_SOURCE_H_
-
-#include <stdint.h>
-
-namespace android {
-
-class TimeSource {
-public:
-    TimeSource() {}
-    virtual ~TimeSource() {}
-
-    virtual int64_t getRealTimeUs() = 0;
-
-private:
-    TimeSource(const TimeSource &);
-    TimeSource &operator=(const TimeSource &);
-};
-
-class SystemTimeSource : public TimeSource {
-public:
-    SystemTimeSource();
-
-    virtual int64_t getRealTimeUs();
-
-private:
-    int64_t mStartTimeUs;
-};
-
-}  // namespace android
-
-#endif  // TIME_SOURCE_H_
diff --git a/include/media/stagefright/Utils.h b/include/media/stagefright/Utils.h
index 5e9d7d4..ca74dc2 100644
--- a/include/media/stagefright/Utils.h
+++ b/include/media/stagefright/Utils.h
@@ -28,7 +28,7 @@
 namespace android {
 
 #define FOURCC(c1, c2, c3, c4) \
-    (c1 << 24 | c2 << 16 | c3 << 8 | c4)
+    ((c1) << 24 | (c2) << 16 | (c3) << 8 | (c4))
 
 uint16_t U16_AT(const uint8_t *ptr);
 uint32_t U32_AT(const uint8_t *ptr);
diff --git a/include/media/stagefright/foundation/ABase.h b/include/media/stagefright/foundation/ABase.h
index ef1e010..76a787e 100644
--- a/include/media/stagefright/foundation/ABase.h
+++ b/include/media/stagefright/foundation/ABase.h
@@ -24,7 +24,7 @@
 
 #define DISALLOW_EVIL_CONSTRUCTORS(name) \
     name(const name &); \
-    name &operator=(const name &)
+    name &operator=(const name &) /* NOLINT */
 
 /* Returns true if the size parameter is safe for new array allocation (32-bit)
  *
diff --git a/include/media/stagefright/foundation/ABuffer.h b/include/media/stagefright/foundation/ABuffer.h
index 6294ee7..dc9c778 100644
--- a/include/media/stagefright/foundation/ABuffer.h
+++ b/include/media/stagefright/foundation/ABuffer.h
@@ -33,8 +33,6 @@
     ABuffer(size_t capacity);
     ABuffer(void *data, size_t capacity);
 
-    void setFarewellMessage(const sp<AMessage> msg);
-
     uint8_t *base() { return (uint8_t *)mData; }
     uint8_t *data() { return (uint8_t *)mData + mRangeOffset; }
     size_t capacity() const { return mCapacity; }
@@ -58,7 +56,6 @@
     virtual ~ABuffer();
 
 private:
-    sp<AMessage> mFarewell;
     sp<AMessage> mMeta;
 
     MediaBufferBase *mMediaBufferBase;
diff --git a/include/media/stagefright/foundation/AUtils.h b/include/media/stagefright/foundation/AUtils.h
index 47444c1..255a0f4 100644
--- a/include/media/stagefright/foundation/AUtils.h
+++ b/include/media/stagefright/foundation/AUtils.h
@@ -68,6 +68,7 @@
 
 // needle is in range [hayStart, hayStart + haySize)
 template<class T, class U>
+__attribute__((no_sanitize("integer")))
 inline static bool isInRange(const T &hayStart, const U &haySize, const T &needle) {
     ENSURE_UNSIGNED_TYPE<U>();
     return (T)(hayStart + haySize) >= hayStart && needle >= hayStart && (U)(needle - hayStart) < haySize;
@@ -75,6 +76,7 @@
 
 // [needleStart, needleStart + needleSize) is in range [hayStart, hayStart + haySize)
 template<class T, class U>
+__attribute__((no_sanitize("integer")))
 inline static bool isInRange(
         const T &hayStart, const U &haySize, const T &needleStart, const U &needleSize) {
     ENSURE_UNSIGNED_TYPE<U>();
diff --git a/include/media/stagefright/foundation/Mutexed.h b/include/media/stagefright/foundation/Mutexed.h
new file mode 100644
index 0000000..d4fd905
--- /dev/null
+++ b/include/media/stagefright/foundation/Mutexed.h
@@ -0,0 +1,195 @@
+/*
+ * 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 STAGEFRIGHT_FOUNDATION_MUTEXED_H_
+#define STAGEFRIGHT_FOUNDATION_MUTEXED_H_
+
+#include <utils/Mutex.h>
+#include <utils/Condition.h>
+
+namespace android {
+
+/*
+ * Wrapper class to programmatically protect a structure using a mutex.
+ *
+ * Mutexed<> objects contain a built-in mutex. Protection is enforced because the structure can
+ * only be accessed by locking the mutex first.
+ *
+ * Usage:
+ *
+ * struct DataToProtect {
+ *   State(int var1) : mVar1(var1), mVar2(0) { }
+ *   int mVar1;
+ *   int mVar2;
+ *   Condition mCondition1;
+ * };
+ *
+ * Mutexed<DataToProtect> mProtectedData;
+ *
+ * // members are inaccessible via mProtectedData directly
+ *
+ * void someFunction() {
+ *   Mutexed<DataToProtect>::Locked data(mProtectedData); // access the protected data
+ *
+ *   // the mutex is locked here, so accessing the data is safe
+ *
+ *   if (data->mVar1 < 5) {
+ *     ++data->mVar2;
+ *   }
+ *
+ *   // if you need to temporarily unlock the mutex, you can use unlock/relock mutex locally
+ *   // using the accessor object.
+ *
+ *   data.unlock();
+ *
+ *   // data is inaccessible here
+ *
+ *   doSomeLongOperation();
+ *
+ *   data.lock();
+ *
+ *   // data is now accessible again. Note: it may have changed since unlock().
+ *
+ *   // you can use the integral mutex to wait for a condition
+ *
+ *   data.waitForCondition(data->mCondition1);
+ *
+ *   helper(&data);
+ * }
+ *
+ * void trigger() {
+ *   Mutexed<DataToProtect>::Locked data(mProtectedData);
+ *   data->mCondition1.signal();
+ * }
+ *
+ * void helper(const Mutexed<DataToProtect>::Locked &data) {
+ *   data->mVar1 = 3;
+ * }
+ *
+ */
+
+template<typename T>
+class Mutexed {
+public:
+    /*
+     * Accessor-guard of the mutex-protected structure. This can be dereferenced to
+     * access the structure (using -> or * operators).
+     *
+     * Upon creation, the mutex is locked. You can use lock()/unlock() methods to
+     * temporarily lock/unlock the mutex. Using any references to the underlying
+     * structure or its members defeats the protection of this class, so don't do
+     * it.
+     *
+     * Note: The accessor-guard itself is not thread-safe. E.g. you should not call
+     * unlock() or lock() from different threads; they must be called from the thread
+     * that locked the original wrapper.
+     *
+     * Also note: Recursive locking/unlocking is not supported by the accessor. This
+     * is as intended, as it allows lenient locking/unlocking via multiple code paths.
+     */
+    class Locked {
+    public:
+        inline Locked(Mutexed<T> &mParent);
+        inline ~Locked();
+
+        // dereference the protected structure. This returns nullptr if the
+        // mutex is not locked by this accessor-guard.
+        inline T* operator->() const { return mLocked ? &mTreasure : nullptr; }
+        inline T& operator*()  const { return mLocked ?  mTreasure : *(T*)nullptr; }
+
+        // Wait on the condition variable using lock. Must be locked.
+        inline status_t waitForCondition(Condition &cond) { return cond.wait(mLock); }
+
+        // same with relative timeout
+        inline status_t waitForConditionRelative(Condition &cond, nsecs_t reltime) {
+            return cond.waitRelative(mLock, reltime);
+        }
+
+        // unlocks the integral mutex. No-op if the mutex was already unlocked.
+        inline void unlock();
+
+        // locks the integral mutex. No-op if the mutex was already locked.
+        inline void lock();
+
+    private:
+        Mutex &mLock;
+        T &mTreasure;
+        bool mLocked;
+
+        // disable copy constructors
+        Locked(const Locked&) = delete;
+        void operator=(const Locked&) = delete;
+    };
+
+    // Wrap all constructors of the underlying structure
+    template<typename ...Args>
+    Mutexed(Args... args) : mTreasure(args...) { }
+
+    ~Mutexed() { }
+
+    // Lock the mutex, and create an accessor-guard (a Locked object) to access the underlying
+    // structure. This returns an object that dereferences to the wrapped structure when the mutex
+    // is locked by it, or otherwise to "null".
+    inline Locked&& lock() {
+        // use rvalue as Locked has no copy constructor
+        return std::move(Locked(*this));
+    }
+
+private:
+    friend class Locked;
+    Mutex mLock;
+    T mTreasure;
+
+    // disable copy constructors
+    Mutexed(const Mutexed<T>&) = delete;
+    void operator=(const Mutexed<T>&) = delete;
+};
+
+template<typename T>
+inline Mutexed<T>::Locked::Locked(Mutexed<T> &mParent)
+    : mLock(mParent.mLock),
+      mTreasure(mParent.mTreasure),
+      mLocked(true) {
+    mLock.lock();
+
+}
+
+template<typename T>
+inline Mutexed<T>::Locked::~Locked() {
+    if (mLocked) {
+        mLock.unlock();
+    }
+}
+
+template<typename T>
+inline void Mutexed<T>::Locked::unlock() {
+    if (mLocked) {
+        mLocked = false;
+        mLock.unlock();
+    }
+}
+
+template<typename T>
+inline void Mutexed<T>::Locked::lock() {
+    if (!mLocked) {
+        mLock.lock();
+        mLocked = true;
+    }
+}
+
+} // namespace android
+
+#endif
diff --git a/include/media/stagefright/timedtext/TimedTextDriver.h b/include/media/stagefright/timedtext/TimedTextDriver.h
deleted file mode 100644
index 6f7c693..0000000
--- a/include/media/stagefright/timedtext/TimedTextDriver.h
+++ /dev/null
@@ -1,104 +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 TIMED_TEXT_DRIVER_H_
-#define TIMED_TEXT_DRIVER_H_
-
-#include <media/stagefright/foundation/ABase.h> // for DISALLOW_* macro
-#include <utils/Errors.h> // for status_t
-#include <utils/RefBase.h>
-#include <utils/threads.h>
-
-namespace android {
-
-struct ALooper;
-struct IMediaHTTPService;
-class MediaPlayerBase;
-class MediaSource;
-class Parcel;
-class TimedTextPlayer;
-class TimedTextSource;
-class DataSource;
-
-class TimedTextDriver {
-public:
-    TimedTextDriver(
-            const wp<MediaPlayerBase> &listener,
-            const sp<IMediaHTTPService> &httpService);
-
-    ~TimedTextDriver();
-
-    status_t start();
-    status_t pause();
-    status_t selectTrack(size_t index);
-    status_t unselectTrack(size_t index);
-
-    status_t seekToAsync(int64_t timeUs);
-
-    status_t addInBandTextSource(
-            size_t trackIndex, const sp<MediaSource>& source);
-
-    status_t addOutOfBandTextSource(
-            size_t trackIndex, const char *uri, const char *mimeType);
-
-    // Caller owns the file desriptor and caller is responsible for closing it.
-    status_t addOutOfBandTextSource(
-            size_t trackIndex, int fd, off64_t offset,
-            off64_t length, const char *mimeType);
-
-    void getExternalTrackInfo(Parcel *parcel);
-    size_t countExternalTracks() const;
-
-private:
-    Mutex mLock;
-
-    enum State {
-        UNINITIALIZED,
-        PREPARED,
-        PLAYING,
-        PAUSED,
-    };
-
-    enum TextSourceType {
-        TEXT_SOURCE_TYPE_IN_BAND = 0,
-        TEXT_SOURCE_TYPE_OUT_OF_BAND,
-    };
-
-    sp<ALooper> mLooper;
-    sp<TimedTextPlayer> mPlayer;
-    wp<MediaPlayerBase> mListener;
-    sp<IMediaHTTPService> mHTTPService;
-
-    // Variables to be guarded by mLock.
-    State mState;
-    size_t mCurrentTrackIndex;
-    KeyedVector<size_t, sp<TimedTextSource> > mTextSourceVector;
-    Vector<TextSourceType> mTextSourceTypeVector;
-
-    // -- End of variables to be guarded by mLock
-
-    status_t selectTrack_l(size_t index);
-
-    status_t createOutOfBandTextSource(
-            size_t trackIndex, const char* mimeType,
-            const sp<DataSource>& dataSource);
-
-    DISALLOW_EVIL_CONSTRUCTORS(TimedTextDriver);
-};
-
-}  // namespace android
-
-#endif  // TIMED_TEXT_DRIVER_H_
diff --git a/media/common_time/ICommonClock.cpp b/media/common_time/ICommonClock.cpp
index 19b7d6e..f1f1fca 100644
--- a/media/common_time/ICommonClock.cpp
+++ b/media/common_time/ICommonClock.cpp
@@ -48,7 +48,7 @@
 class BpCommonClock : public BpInterface<ICommonClock>
 {
   public:
-    BpCommonClock(const sp<IBinder>& impl)
+    explicit BpCommonClock(const sp<IBinder>& impl)
         : BpInterface<ICommonClock>(impl) {}
 
     virtual status_t isCommonTimeValid(bool* valid, uint32_t* timelineID) {
@@ -401,7 +401,7 @@
 class BpCommonClockListener : public BpInterface<ICommonClockListener>
 {
   public:
-    BpCommonClockListener(const sp<IBinder>& impl)
+    explicit BpCommonClockListener(const sp<IBinder>& impl)
         : BpInterface<ICommonClockListener>(impl) {}
 
     virtual void onTimelineChanged(uint64_t timelineID) {
diff --git a/media/common_time/ICommonTimeConfig.cpp b/media/common_time/ICommonTimeConfig.cpp
index 67167b0..e587b39 100644
--- a/media/common_time/ICommonTimeConfig.cpp
+++ b/media/common_time/ICommonTimeConfig.cpp
@@ -50,7 +50,7 @@
 class BpCommonTimeConfig : public BpInterface<ICommonTimeConfig>
 {
   public:
-    BpCommonTimeConfig(const sp<IBinder>& impl)
+    explicit BpCommonTimeConfig(const sp<IBinder>& impl)
         : BpInterface<ICommonTimeConfig>(impl) {}
 
     virtual status_t getMasterElectionPriority(uint8_t *priority) {
diff --git a/media/common_time/cc_helper.cpp b/media/common_time/cc_helper.cpp
index 8d8556c..6a7de74 100644
--- a/media/common_time/cc_helper.cpp
+++ b/media/common_time/cc_helper.cpp
@@ -80,7 +80,7 @@
     }
 }
 
-void CCHelper::CommonClockListener::onTimelineChanged(uint64_t timelineID) {
+void CCHelper::CommonClockListener::onTimelineChanged(uint64_t /*timelineID*/) {
     // do nothing; listener is only really used as a token so the server can
     // find out when clients die.
 }
diff --git a/media/img_utils/include/img_utils/DngUtils.h b/media/img_utils/include/img_utils/DngUtils.h
index 3dcedc5..1d8df9c 100644
--- a/media/img_utils/include/img_utils/DngUtils.h
+++ b/media/img_utils/include/img_utils/DngUtils.h
@@ -138,6 +138,34 @@
                                             double opticalCenterY,
                                             const double* kCoeffs);
 
+
+        /**
+         * Add FixBadPixelsList opcode for the given metadata parameters.
+         *
+         * Returns OK on success, or a negative error code.
+         */
+        virtual status_t addBadPixelListForMetadata(const uint32_t* hotPixels,
+                                                    uint32_t xyPairCount,
+                                                    uint32_t colorFilterArrangement);
+
+        /**
+         * Add FixBadPixelsList opcode.
+         *
+         * bayerPhase - 0=top-left of image is red, 1=top-left of image is green pixel in red row,
+         *              2=top-left of image is green pixel in blue row, 3=top-left of image is
+         *              blue.
+         * badPointCount - number of (x,y) pairs of bad pixels are given in badPointRowColPairs.
+         * badRectCount - number of (top, left, bottom, right) tuples are given in
+         *              badRectTopLeftBottomRightTuples
+         *
+         * Returns OK on success, or a negative error code.
+         */
+        virtual status_t addBadPixelList(uint32_t bayerPhase,
+                                         uint32_t badPointCount,
+                                         uint32_t badRectCount,
+                                         const uint32_t* badPointRowColPairs,
+                                         const uint32_t* badRectTopLeftBottomRightTuples);
+
         // TODO: Add other Opcode methods
     protected:
         static const uint32_t FLAG_OPTIONAL = 0x1u;
@@ -146,6 +174,7 @@
         // Opcode IDs
         enum {
             WARP_RECTILINEAR_ID = 1,
+            FIX_BAD_PIXELS_LIST = 5,
             GAIN_MAP_ID = 9,
         };
 
@@ -161,6 +190,8 @@
         ByteArrayOutput mOpList;
         EndianOutput mEndianOut;
 
+        status_t addOpcodePreamble(uint32_t opcodeId);
+
 };
 
 } /*namespace img_utils*/
diff --git a/media/img_utils/include/img_utils/TiffHelpers.h b/media/img_utils/include/img_utils/TiffHelpers.h
index 0969e4d..3e5f863 100644
--- a/media/img_utils/include/img_utils/TiffHelpers.h
+++ b/media/img_utils/include/img_utils/TiffHelpers.h
@@ -25,7 +25,7 @@
 const uint8_t ZERO_WORD[] = {0, 0, 0, 0};
 
 #define BAIL_ON_FAIL(x, flag) \
-    if ((flag = (x)) != OK) return flag;
+    if (((flag) = (x)) != OK) return flag;
 
 #define BYTES_TILL_WORD(index) \
     ((TIFF_WORD_SIZE - ((index) % TIFF_WORD_SIZE)) % TIFF_WORD_SIZE)
diff --git a/media/img_utils/src/Android.mk b/media/img_utils/src/Android.mk
index 4074849..c1f64ca 100644
--- a/media/img_utils/src/Android.mk
+++ b/media/img_utils/src/Android.mk
@@ -34,6 +34,7 @@
   StripSource.cpp \
 
 LOCAL_SHARED_LIBRARIES := \
+  liblog \
   libexpat \
   libutils \
   libcutils \
diff --git a/media/img_utils/src/DngUtils.cpp b/media/img_utils/src/DngUtils.cpp
index b213403..9473dce 100644
--- a/media/img_utils/src/DngUtils.cpp
+++ b/media/img_utils/src/DngUtils.cpp
@@ -224,13 +224,7 @@
                                        uint32_t mapPlanes,
                                        const float* mapGains) {
 
-    uint32_t opcodeId = GAIN_MAP_ID;
-
-    status_t err = mEndianOut.write(&opcodeId, 0, 1);
-    if (err != OK) return err;
-
-    uint8_t version[] = {1, 3, 0, 0};
-    err = mEndianOut.write(version, 0, NELEMS(version));
+    status_t err = addOpcodePreamble(GAIN_MAP_ID);
     if (err != OK) return err;
 
     // Allow this opcode to be skipped if not supported
@@ -334,13 +328,7 @@
                                                double opticalCenterY,
                                                const double* kCoeffs) {
 
-    uint32_t opcodeId = WARP_RECTILINEAR_ID;
-
-    status_t err = mEndianOut.write(&opcodeId, 0, 1);
-    if (err != OK) return err;
-
-    uint8_t version[] = {1, 3, 0, 0};
-    err = mEndianOut.write(version, 0, NELEMS(version));
+    status_t err = addOpcodePreamble(WARP_RECTILINEAR_ID);
     if (err != OK) return err;
 
     // Allow this opcode to be skipped if not supported
@@ -373,5 +361,74 @@
     return OK;
 }
 
+status_t OpcodeListBuilder::addBadPixelListForMetadata(const uint32_t* hotPixels,
+                                                       uint32_t xyPairCount,
+                                                       uint32_t colorFilterArrangement) {
+    if (colorFilterArrangement > 3) {
+        ALOGE("%s:  Unknown color filter arrangement %" PRIu32, __FUNCTION__,
+                colorFilterArrangement);
+        return BAD_VALUE;
+    }
+
+    return addBadPixelList(colorFilterArrangement, xyPairCount, 0, hotPixels, nullptr);
+}
+
+status_t OpcodeListBuilder::addBadPixelList(uint32_t bayerPhase,
+                                            uint32_t badPointCount,
+                                            uint32_t badRectCount,
+                                            const uint32_t* badPointRowColPairs,
+                                            const uint32_t* badRectTopLeftBottomRightTuples) {
+
+    status_t err = addOpcodePreamble(FIX_BAD_PIXELS_LIST);
+    if (err != OK) return err;
+
+    // Allow this opcode to be skipped if not supported
+    uint32_t flags = FLAG_OPTIONAL;
+
+    err = mEndianOut.write(&flags, 0, 1);
+    if (err != OK) return err;
+
+    const uint32_t NUM_NON_VARLEN_FIELDS = 3;
+    const uint32_t SIZE_OF_POINT = 2;
+    const uint32_t SIZE_OF_RECT = 4;
+
+    uint32_t totalSize =  (NUM_NON_VARLEN_FIELDS  + badPointCount * SIZE_OF_POINT +
+            badRectCount * SIZE_OF_RECT) * sizeof(uint32_t);
+    err = mEndianOut.write(&totalSize, 0, 1);
+    if (err != OK) return err;
+
+    err = mEndianOut.write(&bayerPhase, 0, 1);
+    if (err != OK) return err;
+
+    err = mEndianOut.write(&badPointCount, 0, 1);
+    if (err != OK) return err;
+
+    err = mEndianOut.write(&badRectCount, 0, 1);
+    if (err != OK) return err;
+
+    if (badPointCount > 0) {
+        err = mEndianOut.write(badPointRowColPairs, 0, SIZE_OF_POINT * badPointCount);
+        if (err != OK) return err;
+    }
+
+    if (badRectCount > 0) {
+        err = mEndianOut.write(badRectTopLeftBottomRightTuples, 0, SIZE_OF_RECT * badRectCount);
+        if (err != OK) return err;
+    }
+
+    mCount++;
+    return OK;
+}
+
+status_t OpcodeListBuilder::addOpcodePreamble(uint32_t opcodeId) {
+    status_t err = mEndianOut.write(&opcodeId, 0, 1);
+    if (err != OK) return err;
+
+    uint8_t version[] = {1, 3, 0, 0};
+    err = mEndianOut.write(version, 0, NELEMS(version));
+    if (err != OK) return err;
+    return OK;
+}
+
 } /*namespace img_utils*/
 } /*namespace android*/
diff --git a/media/img_utils/src/TiffWriter.cpp b/media/img_utils/src/TiffWriter.cpp
index a6f9218..564474f 100644
--- a/media/img_utils/src/TiffWriter.cpp
+++ b/media/img_utils/src/TiffWriter.cpp
@@ -40,7 +40,7 @@
 }
 
 #define ARRAY_SIZE(array) \
-    (sizeof(array) / sizeof(array[0]))
+    (sizeof(array) / sizeof((array)[0]))
 
 KeyedVector<uint16_t, const TagDefinition_t*> TiffWriter::sTagMaps[] = {
     buildTagMap(TIFF_EP_TAG_DEFINITIONS, ARRAY_SIZE(TIFF_EP_TAG_DEFINITIONS)),
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h b/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
index 94a7869..b1ebadf 100644
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
@@ -36,190 +36,190 @@
 
  /* Coefficients for centre frequency 55Hz */
 #define HPF_Fs8000_Fc55_A0                         1029556328         /* Floating point value 0.958849 */
-#define HPF_Fs8000_Fc55_A1                        -2059112655         /* Floating point value -1.917698 */
+#define HPF_Fs8000_Fc55_A1                       (-2059112655)        /* Floating point value -1.917698 */
 #define HPF_Fs8000_Fc55_A2                         1029556328         /* Floating point value 0.958849 */
-#define HPF_Fs8000_Fc55_B1                        -2081986375         /* Floating point value -1.939001 */
+#define HPF_Fs8000_Fc55_B1                       (-2081986375)        /* Floating point value -1.939001 */
 #define HPF_Fs8000_Fc55_B2                         1010183914         /* Floating point value 0.940807 */
 #define HPF_Fs11025_Fc55_A0                        1038210831         /* Floating point value 0.966909 */
-#define HPF_Fs11025_Fc55_A1                       -2076421662         /* Floating point value -1.933818 */
+#define HPF_Fs11025_Fc55_A1                      (-2076421662)        /* Floating point value -1.933818 */
 #define HPF_Fs11025_Fc55_A2                        1038210831         /* Floating point value 0.966909 */
-#define HPF_Fs11025_Fc55_B1                       -2099950710         /* Floating point value -1.955732 */
+#define HPF_Fs11025_Fc55_B1                      (-2099950710)        /* Floating point value -1.955732 */
 #define HPF_Fs11025_Fc55_B2                        1027238450         /* Floating point value 0.956690 */
 #define HPF_Fs12000_Fc55_A0                        1040079943         /* Floating point value 0.968650 */
-#define HPF_Fs12000_Fc55_A1                       -2080159885         /* Floating point value -1.937300 */
+#define HPF_Fs12000_Fc55_A1                      (-2080159885)        /* Floating point value -1.937300 */
 #define HPF_Fs12000_Fc55_A2                        1040079943         /* Floating point value 0.968650 */
-#define HPF_Fs12000_Fc55_B1                       -2103811702         /* Floating point value -1.959327 */
+#define HPF_Fs12000_Fc55_B1                      (-2103811702)        /* Floating point value -1.959327 */
 #define HPF_Fs12000_Fc55_B2                        1030940477         /* Floating point value 0.960138 */
 #define HPF_Fs16000_Fc55_A0                        1045381988         /* Floating point value 0.973588 */
-#define HPF_Fs16000_Fc55_A1                       -2090763976         /* Floating point value -1.947176 */
+#define HPF_Fs16000_Fc55_A1                      (-2090763976)        /* Floating point value -1.947176 */
 #define HPF_Fs16000_Fc55_A2                        1045381988         /* Floating point value 0.973588 */
-#define HPF_Fs16000_Fc55_B1                       -2114727793         /* Floating point value -1.969494 */
+#define HPF_Fs16000_Fc55_B1                      (-2114727793)        /* Floating point value -1.969494 */
 #define HPF_Fs16000_Fc55_B2                        1041478147         /* Floating point value 0.969952 */
 #define HPF_Fs22050_Fc55_A0                        1049766523         /* Floating point value 0.977671 */
-#define HPF_Fs22050_Fc55_A1                       -2099533046         /* Floating point value -1.955343 */
+#define HPF_Fs22050_Fc55_A1                      (-2099533046)        /* Floating point value -1.955343 */
 #define HPF_Fs22050_Fc55_A2                        1049766523         /* Floating point value 0.977671 */
-#define HPF_Fs22050_Fc55_B1                       -2123714381         /* Floating point value -1.977863 */
+#define HPF_Fs22050_Fc55_B1                      (-2123714381)        /* Floating point value -1.977863 */
 #define HPF_Fs22050_Fc55_B2                        1050232780         /* Floating point value 0.978105 */
 #define HPF_Fs24000_Fc55_A0                        1050711051         /* Floating point value 0.978551 */
-#define HPF_Fs24000_Fc55_A1                       -2101422103         /* Floating point value -1.957102 */
+#define HPF_Fs24000_Fc55_A1                      (-2101422103)        /* Floating point value -1.957102 */
 #define HPF_Fs24000_Fc55_A2                        1050711051         /* Floating point value 0.978551 */
-#define HPF_Fs24000_Fc55_B1                       -2125645498         /* Floating point value -1.979662 */
+#define HPF_Fs24000_Fc55_B1                      (-2125645498)        /* Floating point value -1.979662 */
 #define HPF_Fs24000_Fc55_B2                        1052123526         /* Floating point value 0.979866 */
 #define HPF_Fs32000_Fc55_A0                        1053385759         /* Floating point value 0.981042 */
-#define HPF_Fs32000_Fc55_A1                       -2106771519         /* Floating point value -1.962084 */
+#define HPF_Fs32000_Fc55_A1                      (-2106771519)        /* Floating point value -1.962084 */
 #define HPF_Fs32000_Fc55_A2                        1053385759         /* Floating point value 0.981042 */
-#define HPF_Fs32000_Fc55_B1                       -2131104794         /* Floating point value -1.984746 */
+#define HPF_Fs32000_Fc55_B1                      (-2131104794)        /* Floating point value -1.984746 */
 #define HPF_Fs32000_Fc55_B2                        1057486949         /* Floating point value 0.984861 */
 #define HPF_Fs44100_Fc55_A0                        1055592498         /* Floating point value 0.983097 */
-#define HPF_Fs44100_Fc55_A1                       -2111184995         /* Floating point value -1.966194 */
+#define HPF_Fs44100_Fc55_A1                      (-2111184995)        /* Floating point value -1.966194 */
 #define HPF_Fs44100_Fc55_A2                        1055592498         /* Floating point value 0.983097 */
-#define HPF_Fs44100_Fc55_B1                       -2135598658         /* Floating point value -1.988931 */
+#define HPF_Fs44100_Fc55_B1                      (-2135598658)        /* Floating point value -1.988931 */
 #define HPF_Fs44100_Fc55_B2                        1061922249         /* Floating point value 0.988992 */
 #define HPF_Fs48000_Fc55_A0                        1056067276         /* Floating point value 0.983539 */
-#define HPF_Fs48000_Fc55_A1                       -2112134551         /* Floating point value -1.967079 */
+#define HPF_Fs48000_Fc55_A1                      (-2112134551)        /* Floating point value -1.967079 */
 #define HPF_Fs48000_Fc55_A2                        1056067276         /* Floating point value 0.983539 */
-#define HPF_Fs48000_Fc55_B1                       -2136564296         /* Floating point value -1.989831 */
+#define HPF_Fs48000_Fc55_B1                      (-2136564296)        /* Floating point value -1.989831 */
 #define HPF_Fs48000_Fc55_B2                        1062877714         /* Floating point value 0.989882 */
 
  /* Coefficients for centre frequency 66Hz */
 #define HPF_Fs8000_Fc66_A0                         1023293271         /* Floating point value 0.953016 */
-#define HPF_Fs8000_Fc66_A1                        -2046586542         /* Floating point value -1.906032 */
+#define HPF_Fs8000_Fc66_A1                       (-2046586542)        /* Floating point value -1.906032 */
 #define HPF_Fs8000_Fc66_A2                         1023293271         /* Floating point value 0.953016 */
-#define HPF_Fs8000_Fc66_B1                        -2068896860         /* Floating point value -1.926810 */
+#define HPF_Fs8000_Fc66_B1                       (-2068896860)        /* Floating point value -1.926810 */
 #define HPF_Fs8000_Fc66_B2                          997931110         /* Floating point value 0.929396 */
 #define HPF_Fs11025_Fc66_A0                        1033624228         /* Floating point value 0.962638 */
-#define HPF_Fs11025_Fc66_A1                       -2067248455         /* Floating point value -1.925275 */
+#define HPF_Fs11025_Fc66_A1                      (-2067248455)        /* Floating point value -1.925275 */
 #define HPF_Fs11025_Fc66_A2                        1033624228         /* Floating point value 0.962638 */
-#define HPF_Fs11025_Fc66_B1                       -2090448000         /* Floating point value -1.946881 */
+#define HPF_Fs11025_Fc66_B1                      (-2090448000)        /* Floating point value -1.946881 */
 #define HPF_Fs11025_Fc66_B2                        1018182305         /* Floating point value 0.948256 */
 #define HPF_Fs12000_Fc66_A0                        1035857662         /* Floating point value 0.964718 */
-#define HPF_Fs12000_Fc66_A1                       -2071715325         /* Floating point value -1.929435 */
+#define HPF_Fs12000_Fc66_A1                      (-2071715325)        /* Floating point value -1.929435 */
 #define HPF_Fs12000_Fc66_A2                        1035857662         /* Floating point value 0.964718 */
-#define HPF_Fs12000_Fc66_B1                       -2095080333         /* Floating point value -1.951196 */
+#define HPF_Fs12000_Fc66_B1                      (-2095080333)        /* Floating point value -1.951196 */
 #define HPF_Fs12000_Fc66_B2                        1022587158         /* Floating point value 0.952359 */
 #define HPF_Fs16000_Fc66_A0                        1042197528         /* Floating point value 0.970622 */
-#define HPF_Fs16000_Fc66_A1                       -2084395056         /* Floating point value -1.941244 */
+#define HPF_Fs16000_Fc66_A1                      (-2084395056)        /* Floating point value -1.941244 */
 #define HPF_Fs16000_Fc66_A2                        1042197528         /* Floating point value 0.970622 */
-#define HPF_Fs16000_Fc66_B1                       -2108177912         /* Floating point value -1.963394 */
+#define HPF_Fs16000_Fc66_B1                      (-2108177912)        /* Floating point value -1.963394 */
 #define HPF_Fs16000_Fc66_B2                        1035142690         /* Floating point value 0.964052 */
 #define HPF_Fs22050_Fc66_A0                        1047445145         /* Floating point value 0.975509 */
-#define HPF_Fs22050_Fc66_A1                       -2094890289         /* Floating point value -1.951019 */
+#define HPF_Fs22050_Fc66_A1                      (-2094890289)        /* Floating point value -1.951019 */
 #define HPF_Fs22050_Fc66_A2                        1047445145         /* Floating point value 0.975509 */
-#define HPF_Fs22050_Fc66_B1                       -2118961025         /* Floating point value -1.973436 */
+#define HPF_Fs22050_Fc66_B1                      (-2118961025)        /* Floating point value -1.973436 */
 #define HPF_Fs22050_Fc66_B2                        1045593102         /* Floating point value 0.973784 */
 #define HPF_Fs24000_Fc66_A0                        1048576175         /* Floating point value 0.976563 */
-#define HPF_Fs24000_Fc66_A1                       -2097152349         /* Floating point value -1.953125 */
+#define HPF_Fs24000_Fc66_A1                      (-2097152349)        /* Floating point value -1.953125 */
 #define HPF_Fs24000_Fc66_A2                        1048576175         /* Floating point value 0.976563 */
-#define HPF_Fs24000_Fc66_B1                       -2121278255         /* Floating point value -1.975594 */
+#define HPF_Fs24000_Fc66_B1                      (-2121278255)        /* Floating point value -1.975594 */
 #define HPF_Fs24000_Fc66_B2                        1047852379         /* Floating point value 0.975889 */
 #define HPF_Fs32000_Fc66_A0                        1051780119         /* Floating point value 0.979547 */
-#define HPF_Fs32000_Fc66_A1                       -2103560237         /* Floating point value -1.959093 */
+#define HPF_Fs32000_Fc66_A1                      (-2103560237)        /* Floating point value -1.959093 */
 #define HPF_Fs32000_Fc66_A2                        1051780119         /* Floating point value 0.979547 */
-#define HPF_Fs32000_Fc66_B1                       -2127829187         /* Floating point value -1.981695 */
+#define HPF_Fs32000_Fc66_B1                      (-2127829187)        /* Floating point value -1.981695 */
 #define HPF_Fs32000_Fc66_B2                        1054265623         /* Floating point value 0.981861 */
 #define HPF_Fs44100_Fc66_A0                        1054424722         /* Floating point value 0.982010 */
-#define HPF_Fs44100_Fc66_A1                       -2108849444         /* Floating point value -1.964019 */
+#define HPF_Fs44100_Fc66_A1                      (-2108849444)        /* Floating point value -1.964019 */
 #define HPF_Fs44100_Fc66_A2                        1054424722         /* Floating point value 0.982010 */
-#define HPF_Fs44100_Fc66_B1                       -2133221723         /* Floating point value -1.986718 */
+#define HPF_Fs44100_Fc66_B1                      (-2133221723)        /* Floating point value -1.986718 */
 #define HPF_Fs44100_Fc66_B2                        1059573993         /* Floating point value 0.986805 */
 #define HPF_Fs48000_Fc66_A0                        1054993851         /* Floating point value 0.982540 */
-#define HPF_Fs48000_Fc66_A1                       -2109987702         /* Floating point value -1.965079 */
+#define HPF_Fs48000_Fc66_A1                      (-2109987702)        /* Floating point value -1.965079 */
 #define HPF_Fs48000_Fc66_A2                        1054993851         /* Floating point value 0.982540 */
-#define HPF_Fs48000_Fc66_B1                       -2134380475         /* Floating point value -1.987797 */
+#define HPF_Fs48000_Fc66_B1                      (-2134380475)        /* Floating point value -1.987797 */
 #define HPF_Fs48000_Fc66_B2                        1060718118         /* Floating point value 0.987871 */
 
  /* Coefficients for centre frequency 78Hz */
 #define HPF_Fs8000_Fc78_A0                         1016504203         /* Floating point value 0.946693 */
-#define HPF_Fs8000_Fc78_A1                        -2033008405         /* Floating point value -1.893387 */
+#define HPF_Fs8000_Fc78_A1                       (-2033008405)        /* Floating point value -1.893387 */
 #define HPF_Fs8000_Fc78_A2                         1016504203         /* Floating point value 0.946693 */
-#define HPF_Fs8000_Fc78_B1                        -2054623390         /* Floating point value -1.913517 */
+#define HPF_Fs8000_Fc78_B1                       (-2054623390)        /* Floating point value -1.913517 */
 #define HPF_Fs8000_Fc78_B2                          984733853         /* Floating point value 0.917105 */
 #define HPF_Fs11025_Fc78_A0                        1028643741         /* Floating point value 0.957999 */
-#define HPF_Fs11025_Fc78_A1                       -2057287482         /* Floating point value -1.915998 */
+#define HPF_Fs11025_Fc78_A1                      (-2057287482)        /* Floating point value -1.915998 */
 #define HPF_Fs11025_Fc78_A2                        1028643741         /* Floating point value 0.957999 */
-#define HPF_Fs11025_Fc78_B1                       -2080083769         /* Floating point value -1.937229 */
+#define HPF_Fs11025_Fc78_B1                      (-2080083769)        /* Floating point value -1.937229 */
 #define HPF_Fs11025_Fc78_B2                        1008393904         /* Floating point value 0.939140 */
 #define HPF_Fs12000_Fc78_A0                        1031271067         /* Floating point value 0.960446 */
-#define HPF_Fs12000_Fc78_A1                       -2062542133         /* Floating point value -1.920892 */
+#define HPF_Fs12000_Fc78_A1                      (-2062542133)        /* Floating point value -1.920892 */
 #define HPF_Fs12000_Fc78_A2                        1031271067         /* Floating point value 0.960446 */
-#define HPF_Fs12000_Fc78_B1                       -2085557048         /* Floating point value -1.942326 */
+#define HPF_Fs12000_Fc78_B1                      (-2085557048)        /* Floating point value -1.942326 */
 #define HPF_Fs12000_Fc78_B2                        1013551620         /* Floating point value 0.943944 */
 #define HPF_Fs16000_Fc78_A0                        1038734628         /* Floating point value 0.967397 */
-#define HPF_Fs16000_Fc78_A1                       -2077469256         /* Floating point value -1.934794 */
+#define HPF_Fs16000_Fc78_A1                      (-2077469256)        /* Floating point value -1.934794 */
 #define HPF_Fs16000_Fc78_A2                        1038734628         /* Floating point value 0.967397 */
-#define HPF_Fs16000_Fc78_B1                       -2101033380         /* Floating point value -1.956740 */
+#define HPF_Fs16000_Fc78_B1                      (-2101033380)        /* Floating point value -1.956740 */
 #define HPF_Fs16000_Fc78_B2                        1028275228         /* Floating point value 0.957656 */
 #define HPF_Fs22050_Fc78_A0                        1044918584         /* Floating point value 0.973156 */
-#define HPF_Fs22050_Fc78_A1                       -2089837169         /* Floating point value -1.946313 */
+#define HPF_Fs22050_Fc78_A1                      (-2089837169)        /* Floating point value -1.946313 */
 #define HPF_Fs22050_Fc78_A2                        1044918584         /* Floating point value 0.973156 */
-#define HPF_Fs22050_Fc78_B1                       -2113775854         /* Floating point value -1.968607 */
+#define HPF_Fs22050_Fc78_B1                      (-2113775854)        /* Floating point value -1.968607 */
 #define HPF_Fs22050_Fc78_B2                        1040555007         /* Floating point value 0.969092 */
 #define HPF_Fs24000_Fc78_A0                        1046252164         /* Floating point value 0.974398 */
-#define HPF_Fs24000_Fc78_A1                       -2092504328         /* Floating point value -1.948797 */
+#define HPF_Fs24000_Fc78_A1                      (-2092504328)        /* Floating point value -1.948797 */
 #define HPF_Fs24000_Fc78_A2                        1046252164         /* Floating point value 0.974398 */
-#define HPF_Fs24000_Fc78_B1                       -2116514229         /* Floating point value -1.971157 */
+#define HPF_Fs24000_Fc78_B1                      (-2116514229)        /* Floating point value -1.971157 */
 #define HPF_Fs24000_Fc78_B2                        1043212719         /* Floating point value 0.971568 */
 #define HPF_Fs32000_Fc78_A0                        1050031301         /* Floating point value 0.977918 */
-#define HPF_Fs32000_Fc78_A1                       -2100062603         /* Floating point value -1.955836 */
+#define HPF_Fs32000_Fc78_A1                      (-2100062603)        /* Floating point value -1.955836 */
 #define HPF_Fs32000_Fc78_A2                        1050031301         /* Floating point value 0.977918 */
-#define HPF_Fs32000_Fc78_B1                       -2124255900         /* Floating point value -1.978367 */
+#define HPF_Fs32000_Fc78_B1                      (-2124255900)        /* Floating point value -1.978367 */
 #define HPF_Fs32000_Fc78_B2                        1050762639         /* Floating point value 0.978599 */
 #define HPF_Fs44100_Fc78_A0                        1053152258         /* Floating point value 0.980824 */
-#define HPF_Fs44100_Fc78_A1                       -2106304516         /* Floating point value -1.961649 */
+#define HPF_Fs44100_Fc78_A1                      (-2106304516)        /* Floating point value -1.961649 */
 #define HPF_Fs44100_Fc78_A2                        1053152258         /* Floating point value 0.980824 */
-#define HPF_Fs44100_Fc78_B1                       -2130628742         /* Floating point value -1.984303 */
+#define HPF_Fs44100_Fc78_B1                      (-2130628742)        /* Floating point value -1.984303 */
 #define HPF_Fs44100_Fc78_B2                        1057018180         /* Floating point value 0.984425 */
 #define HPF_Fs48000_Fc78_A0                        1053824087         /* Floating point value 0.981450 */
-#define HPF_Fs48000_Fc78_A1                       -2107648173         /* Floating point value -1.962900 */
+#define HPF_Fs48000_Fc78_A1                      (-2107648173)        /* Floating point value -1.962900 */
 #define HPF_Fs48000_Fc78_A2                        1053824087         /* Floating point value 0.981450 */
-#define HPF_Fs48000_Fc78_B1                       -2131998154         /* Floating point value -1.985578 */
+#define HPF_Fs48000_Fc78_B1                      (-2131998154)        /* Floating point value -1.985578 */
 #define HPF_Fs48000_Fc78_B2                        1058367200         /* Floating point value 0.985681 */
 
  /* Coefficients for centre frequency 90Hz */
 #define HPF_Fs8000_Fc90_A0                         1009760053         /* Floating point value 0.940412 */
-#define HPF_Fs8000_Fc90_A1                        -2019520105         /* Floating point value -1.880825 */
+#define HPF_Fs8000_Fc90_A1                       (-2019520105)        /* Floating point value -1.880825 */
 #define HPF_Fs8000_Fc90_A2                         1009760053         /* Floating point value 0.940412 */
-#define HPF_Fs8000_Fc90_B1                        -2040357139         /* Floating point value -1.900231 */
+#define HPF_Fs8000_Fc90_B1                       (-2040357139)        /* Floating point value -1.900231 */
 #define HPF_Fs8000_Fc90_B2                          971711129         /* Floating point value 0.904977 */
 #define HPF_Fs11025_Fc90_A0                        1023687217         /* Floating point value 0.953383 */
-#define HPF_Fs11025_Fc90_A1                       -2047374434         /* Floating point value -1.906766 */
+#define HPF_Fs11025_Fc90_A1                      (-2047374434)        /* Floating point value -1.906766 */
 #define HPF_Fs11025_Fc90_A2                        1023687217         /* Floating point value 0.953383 */
-#define HPF_Fs11025_Fc90_B1                       -2069722397         /* Floating point value -1.927579 */
+#define HPF_Fs11025_Fc90_B1                      (-2069722397)        /* Floating point value -1.927579 */
 #define HPF_Fs11025_Fc90_B2                         998699604         /* Floating point value 0.930111 */
 #define HPF_Fs12000_Fc90_A0                        1026704754         /* Floating point value 0.956193 */
-#define HPF_Fs12000_Fc90_A1                       -2053409508         /* Floating point value -1.912387 */
+#define HPF_Fs12000_Fc90_A1                      (-2053409508)        /* Floating point value -1.912387 */
 #define HPF_Fs12000_Fc90_A2                        1026704754         /* Floating point value 0.956193 */
-#define HPF_Fs12000_Fc90_B1                       -2076035996         /* Floating point value -1.933459 */
+#define HPF_Fs12000_Fc90_B1                      (-2076035996)        /* Floating point value -1.933459 */
 #define HPF_Fs12000_Fc90_B2                        1004595918         /* Floating point value 0.935603 */
 #define HPF_Fs16000_Fc90_A0                        1035283225         /* Floating point value 0.964183 */
-#define HPF_Fs16000_Fc90_A1                       -2070566451         /* Floating point value -1.928365 */
+#define HPF_Fs16000_Fc90_A1                      (-2070566451)        /* Floating point value -1.928365 */
 #define HPF_Fs16000_Fc90_A2                        1035283225         /* Floating point value 0.964183 */
-#define HPF_Fs16000_Fc90_B1                       -2093889811         /* Floating point value -1.950087 */
+#define HPF_Fs16000_Fc90_B1                      (-2093889811)        /* Floating point value -1.950087 */
 #define HPF_Fs16000_Fc90_B2                        1021453326         /* Floating point value 0.951303 */
 #define HPF_Fs22050_Fc90_A0                        1042398116         /* Floating point value 0.970809 */
-#define HPF_Fs22050_Fc90_A1                       -2084796232         /* Floating point value -1.941618 */
+#define HPF_Fs22050_Fc90_A1                      (-2084796232)        /* Floating point value -1.941618 */
 #define HPF_Fs22050_Fc90_A2                        1042398116         /* Floating point value 0.970809 */
-#define HPF_Fs22050_Fc90_B1                       -2108591057         /* Floating point value -1.963778 */
+#define HPF_Fs22050_Fc90_B1                      (-2108591057)        /* Floating point value -1.963778 */
 #define HPF_Fs22050_Fc90_B2                        1035541188         /* Floating point value 0.964423 */
 #define HPF_Fs24000_Fc90_A0                        1043933302         /* Floating point value 0.972239 */
-#define HPF_Fs24000_Fc90_A1                       -2087866604         /* Floating point value -1.944477 */
+#define HPF_Fs24000_Fc90_A1                      (-2087866604)        /* Floating point value -1.944477 */
 #define HPF_Fs24000_Fc90_A2                        1043933302         /* Floating point value 0.972239 */
-#define HPF_Fs24000_Fc90_B1                       -2111750495         /* Floating point value -1.966721 */
+#define HPF_Fs24000_Fc90_B1                      (-2111750495)        /* Floating point value -1.966721 */
 #define HPF_Fs24000_Fc90_B2                        1038593601         /* Floating point value 0.967266 */
 #define HPF_Fs32000_Fc90_A0                        1048285391         /* Floating point value 0.976292 */
-#define HPF_Fs32000_Fc90_A1                       -2096570783         /* Floating point value -1.952584 */
+#define HPF_Fs32000_Fc90_A1                      (-2096570783)        /* Floating point value -1.952584 */
 #define HPF_Fs32000_Fc90_A2                        1048285391         /* Floating point value 0.976292 */
-#define HPF_Fs32000_Fc90_B1                       -2120682737         /* Floating point value -1.975040 */
+#define HPF_Fs32000_Fc90_B1                      (-2120682737)        /* Floating point value -1.975040 */
 #define HPF_Fs32000_Fc90_B2                        1047271295         /* Floating point value 0.975347 */
 #define HPF_Fs44100_Fc90_A0                        1051881330         /* Floating point value 0.979641 */
-#define HPF_Fs44100_Fc90_A1                       -2103762660         /* Floating point value -1.959282 */
+#define HPF_Fs44100_Fc90_A1                      (-2103762660)        /* Floating point value -1.959282 */
 #define HPF_Fs44100_Fc90_A2                        1051881330         /* Floating point value 0.979641 */
-#define HPF_Fs44100_Fc90_B1                       -2128035809         /* Floating point value -1.981888 */
+#define HPF_Fs44100_Fc90_B1                      (-2128035809)        /* Floating point value -1.981888 */
 #define HPF_Fs44100_Fc90_B2                        1054468533         /* Floating point value 0.982050 */
 #define HPF_Fs48000_Fc90_A0                        1052655619         /* Floating point value 0.980362 */
-#define HPF_Fs48000_Fc90_A1                       -2105311238         /* Floating point value -1.960724 */
+#define HPF_Fs48000_Fc90_A1                      (-2105311238)        /* Floating point value -1.960724 */
 #define HPF_Fs48000_Fc90_A2                        1052655619         /* Floating point value 0.980362 */
-#define HPF_Fs48000_Fc90_B1                       -2129615871         /* Floating point value -1.983359 */
+#define HPF_Fs48000_Fc90_B1                      (-2129615871)        /* Floating point value -1.983359 */
 #define HPF_Fs48000_Fc90_B2                        1056021492         /* Floating point value 0.983497 */
 
 
@@ -232,189 +232,189 @@
  /* Coefficients for centre frequency 55Hz */
 #define BPF_Fs8000_Fc55_A0                            9875247         /* Floating point value 0.009197 */
 #define BPF_Fs8000_Fc55_A1                                  0         /* Floating point value 0.000000 */
-#define BPF_Fs8000_Fc55_A2                           -9875247         /* Floating point value -0.009197 */
-#define BPF_Fs8000_Fc55_B1                        -2125519830         /* Floating point value -1.979545 */
+#define BPF_Fs8000_Fc55_A2                          (-9875247)        /* Floating point value -0.009197 */
+#define BPF_Fs8000_Fc55_B1                       (-2125519830)        /* Floating point value -1.979545 */
 #define BPF_Fs8000_Fc55_B2                         1053762629         /* Floating point value 0.981393 */
 #define BPF_Fs11025_Fc55_A0                           7183952         /* Floating point value 0.006691 */
 #define BPF_Fs11025_Fc55_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs11025_Fc55_A2                          -7183952         /* Floating point value -0.006691 */
-#define BPF_Fs11025_Fc55_B1                       -2131901658         /* Floating point value -1.985488 */
+#define BPF_Fs11025_Fc55_A2                         (-7183952)        /* Floating point value -0.006691 */
+#define BPF_Fs11025_Fc55_B1                      (-2131901658)        /* Floating point value -1.985488 */
 #define BPF_Fs11025_Fc55_B2                        1059207548         /* Floating point value 0.986464 */
 #define BPF_Fs12000_Fc55_A0                           6603871         /* Floating point value 0.006150 */
 #define BPF_Fs12000_Fc55_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs12000_Fc55_A2                          -6603871         /* Floating point value -0.006150 */
-#define BPF_Fs12000_Fc55_B1                       -2133238092         /* Floating point value -1.986733 */
+#define BPF_Fs12000_Fc55_A2                         (-6603871)        /* Floating point value -0.006150 */
+#define BPF_Fs12000_Fc55_B1                      (-2133238092)        /* Floating point value -1.986733 */
 #define BPF_Fs12000_Fc55_B2                        1060381143         /* Floating point value 0.987557 */
 #define BPF_Fs16000_Fc55_A0                           4960591         /* Floating point value 0.004620 */
 #define BPF_Fs16000_Fc55_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs16000_Fc55_A2                          -4960591         /* Floating point value -0.004620 */
-#define BPF_Fs16000_Fc55_B1                       -2136949052         /* Floating point value -1.990189 */
+#define BPF_Fs16000_Fc55_A2                         (-4960591)        /* Floating point value -0.004620 */
+#define BPF_Fs16000_Fc55_B1                      (-2136949052)        /* Floating point value -1.990189 */
 #define BPF_Fs16000_Fc55_B2                        1063705760         /* Floating point value 0.990653 */
 #define BPF_Fs22050_Fc55_A0                           3604131         /* Floating point value 0.003357 */
 #define BPF_Fs22050_Fc55_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs22050_Fc55_A2                          -3604131         /* Floating point value -0.003357 */
-#define BPF_Fs22050_Fc55_B1                       -2139929085         /* Floating point value -1.992964 */
+#define BPF_Fs22050_Fc55_A2                         (-3604131)        /* Floating point value -0.003357 */
+#define BPF_Fs22050_Fc55_B1                      (-2139929085)        /* Floating point value -1.992964 */
 #define BPF_Fs22050_Fc55_B2                        1066450095         /* Floating point value 0.993209 */
 #define BPF_Fs24000_Fc55_A0                           3312207         /* Floating point value 0.003085 */
 #define BPF_Fs24000_Fc55_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs24000_Fc55_A2                          -3312207         /* Floating point value -0.003085 */
-#define BPF_Fs24000_Fc55_B1                       -2140560606         /* Floating point value -1.993552 */
+#define BPF_Fs24000_Fc55_A2                         (-3312207)        /* Floating point value -0.003085 */
+#define BPF_Fs24000_Fc55_B1                      (-2140560606)        /* Floating point value -1.993552 */
 #define BPF_Fs24000_Fc55_B2                        1067040703         /* Floating point value 0.993759 */
 #define BPF_Fs32000_Fc55_A0                           2486091         /* Floating point value 0.002315 */
 #define BPF_Fs32000_Fc55_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs32000_Fc55_A2                          -2486091         /* Floating point value -0.002315 */
-#define BPF_Fs32000_Fc55_B1                       -2142328962         /* Floating point value -1.995199 */
+#define BPF_Fs32000_Fc55_A2                         (-2486091)        /* Floating point value -0.002315 */
+#define BPF_Fs32000_Fc55_B1                      (-2142328962)        /* Floating point value -1.995199 */
 #define BPF_Fs32000_Fc55_B2                        1068712067         /* Floating point value 0.995316 */
 #define BPF_Fs44100_Fc55_A0                           1805125         /* Floating point value 0.001681 */
 #define BPF_Fs44100_Fc55_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs44100_Fc55_A2                          -1805125         /* Floating point value -0.001681 */
-#define BPF_Fs44100_Fc55_B1                       -2143765772         /* Floating point value -1.996537 */
+#define BPF_Fs44100_Fc55_A2                         (-1805125)        /* Floating point value -0.001681 */
+#define BPF_Fs44100_Fc55_B1                      (-2143765772)        /* Floating point value -1.996537 */
 #define BPF_Fs44100_Fc55_B2                        1070089770         /* Floating point value 0.996599 */
 #define BPF_Fs48000_Fc55_A0                           1658687         /* Floating point value 0.001545 */
 #define BPF_Fs48000_Fc55_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs48000_Fc55_A2                          -1658687         /* Floating point value -0.001545 */
-#define BPF_Fs48000_Fc55_B1                       -2144072292         /* Floating point value -1.996823 */
+#define BPF_Fs48000_Fc55_A2                         (-1658687)        /* Floating point value -0.001545 */
+#define BPF_Fs48000_Fc55_B1                      (-2144072292)        /* Floating point value -1.996823 */
 #define BPF_Fs48000_Fc55_B2                        1070386036         /* Floating point value 0.996875 */
 
  /* Coefficients for centre frequency 66Hz */
 #define BPF_Fs8000_Fc66_A0                           13580189         /* Floating point value 0.012648 */
 #define BPF_Fs8000_Fc66_A1                                  0         /* Floating point value 0.000000 */
-#define BPF_Fs8000_Fc66_A2                          -13580189         /* Floating point value -0.012648 */
-#define BPF_Fs8000_Fc66_B1                        -2117161175         /* Floating point value -1.971760 */
+#define BPF_Fs8000_Fc66_A2                         (-13580189)        /* Floating point value -0.012648 */
+#define BPF_Fs8000_Fc66_B1                       (-2117161175)        /* Floating point value -1.971760 */
 #define BPF_Fs8000_Fc66_B2                         1046266945         /* Floating point value 0.974412 */
 #define BPF_Fs11025_Fc66_A0                           9888559         /* Floating point value 0.009209 */
 #define BPF_Fs11025_Fc66_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs11025_Fc66_A2                          -9888559         /* Floating point value -0.009209 */
-#define BPF_Fs11025_Fc66_B1                       -2125972738         /* Floating point value -1.979966 */
+#define BPF_Fs11025_Fc66_A2                         (-9888559)        /* Floating point value -0.009209 */
+#define BPF_Fs11025_Fc66_B1                      (-2125972738)        /* Floating point value -1.979966 */
 #define BPF_Fs11025_Fc66_B2                        1053735698         /* Floating point value 0.981368 */
 #define BPF_Fs12000_Fc66_A0                           9091954         /* Floating point value 0.008468 */
 #define BPF_Fs12000_Fc66_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs12000_Fc66_A2                          -9091954         /* Floating point value -0.008468 */
-#define BPF_Fs12000_Fc66_B1                       -2127818004         /* Floating point value -1.981685 */
+#define BPF_Fs12000_Fc66_A2                         (-9091954)        /* Floating point value -0.008468 */
+#define BPF_Fs12000_Fc66_B1                      (-2127818004)        /* Floating point value -1.981685 */
 #define BPF_Fs12000_Fc66_B2                        1055347356         /* Floating point value 0.982869 */
 #define BPF_Fs16000_Fc66_A0                           6833525         /* Floating point value 0.006364 */
 #define BPF_Fs16000_Fc66_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs16000_Fc66_A2                          -6833525         /* Floating point value -0.006364 */
-#define BPF_Fs16000_Fc66_B1                       -2132941739         /* Floating point value -1.986457 */
+#define BPF_Fs16000_Fc66_A2                         (-6833525)        /* Floating point value -0.006364 */
+#define BPF_Fs16000_Fc66_B1                      (-2132941739)        /* Floating point value -1.986457 */
 #define BPF_Fs16000_Fc66_B2                        1059916517         /* Floating point value 0.987124 */
 #define BPF_Fs22050_Fc66_A0                           4967309         /* Floating point value 0.004626 */
 #define BPF_Fs22050_Fc66_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs22050_Fc66_A2                          -4967309         /* Floating point value -0.004626 */
-#define BPF_Fs22050_Fc66_B1                       -2137056003         /* Floating point value -1.990288 */
+#define BPF_Fs22050_Fc66_A2                         (-4967309)        /* Floating point value -0.004626 */
+#define BPF_Fs22050_Fc66_B1                      (-2137056003)        /* Floating point value -1.990288 */
 #define BPF_Fs22050_Fc66_B2                        1063692170         /* Floating point value 0.990641 */
 #define BPF_Fs24000_Fc66_A0                           4565445         /* Floating point value 0.004252 */
 #define BPF_Fs24000_Fc66_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs24000_Fc66_A2                          -4565445         /* Floating point value -0.004252 */
-#define BPF_Fs24000_Fc66_B1                       -2137927842         /* Floating point value -1.991100 */
+#define BPF_Fs24000_Fc66_A2                         (-4565445)        /* Floating point value -0.004252 */
+#define BPF_Fs24000_Fc66_B1                      (-2137927842)        /* Floating point value -1.991100 */
 #define BPF_Fs24000_Fc66_B2                        1064505202         /* Floating point value 0.991398 */
 #define BPF_Fs32000_Fc66_A0                           3427761         /* Floating point value 0.003192 */
 #define BPF_Fs32000_Fc66_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs32000_Fc66_A2                          -3427761         /* Floating point value -0.003192 */
-#define BPF_Fs32000_Fc66_B1                       -2140369007         /* Floating point value -1.993374 */
+#define BPF_Fs32000_Fc66_A2                         (-3427761)        /* Floating point value -0.003192 */
+#define BPF_Fs32000_Fc66_B1                      (-2140369007)        /* Floating point value -1.993374 */
 #define BPF_Fs32000_Fc66_B2                        1066806920         /* Floating point value 0.993541 */
 #define BPF_Fs44100_Fc66_A0                           2489466         /* Floating point value 0.002318 */
 #define BPF_Fs44100_Fc66_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs44100_Fc66_A2                          -2489466         /* Floating point value -0.002318 */
-#define BPF_Fs44100_Fc66_B1                       -2142352342         /* Floating point value -1.995221 */
+#define BPF_Fs44100_Fc66_A2                         (-2489466)        /* Floating point value -0.002318 */
+#define BPF_Fs44100_Fc66_B1                      (-2142352342)        /* Floating point value -1.995221 */
 #define BPF_Fs44100_Fc66_B2                        1068705240         /* Floating point value 0.995309 */
 #define BPF_Fs48000_Fc66_A0                           2287632         /* Floating point value 0.002131 */
 #define BPF_Fs48000_Fc66_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs48000_Fc66_A2                          -2287632         /* Floating point value -0.002131 */
-#define BPF_Fs48000_Fc66_B1                       -2142775436         /* Floating point value -1.995615 */
+#define BPF_Fs48000_Fc66_A2                         (-2287632)        /* Floating point value -0.002131 */
+#define BPF_Fs48000_Fc66_B1                      (-2142775436)        /* Floating point value -1.995615 */
 #define BPF_Fs48000_Fc66_B2                        1069113581         /* Floating point value 0.995690 */
 
  /* Coefficients for centre frequency 78Hz */
 #define BPF_Fs8000_Fc78_A0                           19941180         /* Floating point value 0.018572 */
 #define BPF_Fs8000_Fc78_A1                                  0         /* Floating point value 0.000000 */
-#define BPF_Fs8000_Fc78_A2                          -19941180         /* Floating point value -0.018572 */
-#define BPF_Fs8000_Fc78_B1                        -2103186749         /* Floating point value -1.958745 */
+#define BPF_Fs8000_Fc78_A2                         (-19941180)        /* Floating point value -0.018572 */
+#define BPF_Fs8000_Fc78_B1                       (-2103186749)        /* Floating point value -1.958745 */
 #define BPF_Fs8000_Fc78_B2                         1033397648         /* Floating point value 0.962427 */
 #define BPF_Fs11025_Fc78_A0                          14543934         /* Floating point value 0.013545 */
 #define BPF_Fs11025_Fc78_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs11025_Fc78_A2                         -14543934         /* Floating point value -0.013545 */
-#define BPF_Fs11025_Fc78_B1                       -2115966638         /* Floating point value -1.970647 */
+#define BPF_Fs11025_Fc78_A2                        (-14543934)        /* Floating point value -0.013545 */
+#define BPF_Fs11025_Fc78_B1                      (-2115966638)        /* Floating point value -1.970647 */
 #define BPF_Fs11025_Fc78_B2                        1044317135         /* Floating point value 0.972596 */
 #define BPF_Fs12000_Fc78_A0                          13376999         /* Floating point value 0.012458 */
 #define BPF_Fs12000_Fc78_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs12000_Fc78_A2                         -13376999         /* Floating point value -0.012458 */
-#define BPF_Fs12000_Fc78_B1                       -2118651708         /* Floating point value -1.973148 */
+#define BPF_Fs12000_Fc78_A2                        (-13376999)        /* Floating point value -0.012458 */
+#define BPF_Fs12000_Fc78_B1                      (-2118651708)        /* Floating point value -1.973148 */
 #define BPF_Fs12000_Fc78_B2                        1046678029         /* Floating point value 0.974795 */
 #define BPF_Fs16000_Fc78_A0                          10064222         /* Floating point value 0.009373 */
 #define BPF_Fs16000_Fc78_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs16000_Fc78_A2                         -10064222         /* Floating point value -0.009373 */
-#define BPF_Fs16000_Fc78_B1                       -2126124342         /* Floating point value -1.980108 */
+#define BPF_Fs16000_Fc78_A2                        (-10064222)        /* Floating point value -0.009373 */
+#define BPF_Fs16000_Fc78_B1                      (-2126124342)        /* Floating point value -1.980108 */
 #define BPF_Fs16000_Fc78_B2                        1053380304         /* Floating point value 0.981037 */
 #define BPF_Fs22050_Fc78_A0                           7321780         /* Floating point value 0.006819 */
 #define BPF_Fs22050_Fc78_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs22050_Fc78_A2                          -7321780         /* Floating point value -0.006819 */
-#define BPF_Fs22050_Fc78_B1                       -2132143771         /* Floating point value -1.985714 */
+#define BPF_Fs22050_Fc78_A2                         (-7321780)        /* Floating point value -0.006819 */
+#define BPF_Fs22050_Fc78_B1                      (-2132143771)        /* Floating point value -1.985714 */
 #define BPF_Fs22050_Fc78_B2                        1058928700         /* Floating point value 0.986204 */
 #define BPF_Fs24000_Fc78_A0                           6730640         /* Floating point value 0.006268 */
 #define BPF_Fs24000_Fc78_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs24000_Fc78_A2                          -6730640         /* Floating point value -0.006268 */
-#define BPF_Fs24000_Fc78_B1                       -2133421607         /* Floating point value -1.986904 */
+#define BPF_Fs24000_Fc78_A2                         (-6730640)        /* Floating point value -0.006268 */
+#define BPF_Fs24000_Fc78_B1                      (-2133421607)        /* Floating point value -1.986904 */
 #define BPF_Fs24000_Fc78_B2                        1060124669         /* Floating point value 0.987318 */
 #define BPF_Fs32000_Fc78_A0                           5055965         /* Floating point value 0.004709 */
 #define BPF_Fs32000_Fc78_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs32000_Fc78_A2                          -5055965         /* Floating point value -0.004709 */
-#define BPF_Fs32000_Fc78_B1                       -2137003977         /* Floating point value -1.990240 */
+#define BPF_Fs32000_Fc78_A2                         (-5055965)        /* Floating point value -0.004709 */
+#define BPF_Fs32000_Fc78_B1                      (-2137003977)        /* Floating point value -1.990240 */
 #define BPF_Fs32000_Fc78_B2                        1063512802         /* Floating point value 0.990473 */
 #define BPF_Fs44100_Fc78_A0                           3673516         /* Floating point value 0.003421 */
 #define BPF_Fs44100_Fc78_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs44100_Fc78_A2                          -3673516         /* Floating point value -0.003421 */
-#define BPF_Fs44100_Fc78_B1                       -2139919394         /* Floating point value -1.992955 */
+#define BPF_Fs44100_Fc78_A2                         (-3673516)        /* Floating point value -0.003421 */
+#define BPF_Fs44100_Fc78_B1                      (-2139919394)        /* Floating point value -1.992955 */
 #define BPF_Fs44100_Fc78_B2                        1066309718         /* Floating point value 0.993078 */
 #define BPF_Fs48000_Fc78_A0                           3375990         /* Floating point value 0.003144 */
 #define BPF_Fs48000_Fc78_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs48000_Fc78_A2                          -3375990         /* Floating point value -0.003144 */
-#define BPF_Fs48000_Fc78_B1                       -2140541906         /* Floating point value -1.993535 */
+#define BPF_Fs48000_Fc78_A2                         (-3375990)        /* Floating point value -0.003144 */
+#define BPF_Fs48000_Fc78_B1                      (-2140541906)        /* Floating point value -1.993535 */
 #define BPF_Fs48000_Fc78_B2                        1066911660         /* Floating point value 0.993639 */
 
  /* Coefficients for centre frequency 90Hz */
 #define BPF_Fs8000_Fc90_A0                           24438548         /* Floating point value 0.022760 */
 #define BPF_Fs8000_Fc90_A1                                  0         /* Floating point value 0.000000 */
-#define BPF_Fs8000_Fc90_A2                          -24438548         /* Floating point value -0.022760 */
-#define BPF_Fs8000_Fc90_B1                        -2092801347         /* Floating point value -1.949073 */
+#define BPF_Fs8000_Fc90_A2                         (-24438548)        /* Floating point value -0.022760 */
+#define BPF_Fs8000_Fc90_B1                       (-2092801347)        /* Floating point value -1.949073 */
 #define BPF_Fs8000_Fc90_B2                         1024298757         /* Floating point value 0.953953 */
 #define BPF_Fs11025_Fc90_A0                          17844385         /* Floating point value 0.016619 */
 #define BPF_Fs11025_Fc90_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs11025_Fc90_A2                         -17844385         /* Floating point value -0.016619 */
-#define BPF_Fs11025_Fc90_B1                       -2108604921         /* Floating point value -1.963791 */
+#define BPF_Fs11025_Fc90_A2                        (-17844385)        /* Floating point value -0.016619 */
+#define BPF_Fs11025_Fc90_B1                      (-2108604921)        /* Floating point value -1.963791 */
 #define BPF_Fs11025_Fc90_B2                        1037639797         /* Floating point value 0.966377 */
 #define BPF_Fs12000_Fc90_A0                          16416707         /* Floating point value 0.015289 */
 #define BPF_Fs12000_Fc90_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs12000_Fc90_A2                         -16416707         /* Floating point value -0.015289 */
-#define BPF_Fs12000_Fc90_B1                       -2111922936         /* Floating point value -1.966882 */
+#define BPF_Fs12000_Fc90_A2                        (-16416707)        /* Floating point value -0.015289 */
+#define BPF_Fs12000_Fc90_B1                      (-2111922936)        /* Floating point value -1.966882 */
 #define BPF_Fs12000_Fc90_B2                        1040528216         /* Floating point value 0.969067 */
 #define BPF_Fs16000_Fc90_A0                          12359883         /* Floating point value 0.011511 */
 #define BPF_Fs16000_Fc90_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs16000_Fc90_A2                         -12359883         /* Floating point value -0.011511 */
-#define BPF_Fs16000_Fc90_B1                       -2121152162         /* Floating point value -1.975477 */
+#define BPF_Fs16000_Fc90_A2                        (-12359883)        /* Floating point value -0.011511 */
+#define BPF_Fs16000_Fc90_B1                      (-2121152162)        /* Floating point value -1.975477 */
 #define BPF_Fs16000_Fc90_B2                        1048735817         /* Floating point value 0.976711 */
 #define BPF_Fs22050_Fc90_A0                           8997173         /* Floating point value 0.008379 */
 #define BPF_Fs22050_Fc90_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs22050_Fc90_A2                          -8997173         /* Floating point value -0.008379 */
-#define BPF_Fs22050_Fc90_B1                       -2128580762         /* Floating point value -1.982395 */
+#define BPF_Fs22050_Fc90_A2                         (-8997173)        /* Floating point value -0.008379 */
+#define BPF_Fs22050_Fc90_B1                      (-2128580762)        /* Floating point value -1.982395 */
 #define BPF_Fs22050_Fc90_B2                        1055539113         /* Floating point value 0.983047 */
 #define BPF_Fs24000_Fc90_A0                           8271818         /* Floating point value 0.007704 */
 #define BPF_Fs24000_Fc90_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs24000_Fc90_A2                          -8271818         /* Floating point value -0.007704 */
-#define BPF_Fs24000_Fc90_B1                       -2130157013         /* Floating point value -1.983863 */
+#define BPF_Fs24000_Fc90_A2                         (-8271818)        /* Floating point value -0.007704 */
+#define BPF_Fs24000_Fc90_B1                      (-2130157013)        /* Floating point value -1.983863 */
 #define BPF_Fs24000_Fc90_B2                        1057006621         /* Floating point value 0.984414 */
 #define BPF_Fs32000_Fc90_A0                           6215918         /* Floating point value 0.005789 */
 #define BPF_Fs32000_Fc90_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs32000_Fc90_A2                          -6215918         /* Floating point value -0.005789 */
-#define BPF_Fs32000_Fc90_B1                       -2134574521         /* Floating point value -1.987977 */
+#define BPF_Fs32000_Fc90_A2                         (-6215918)        /* Floating point value -0.005789 */
+#define BPF_Fs32000_Fc90_B1                      (-2134574521)        /* Floating point value -1.987977 */
 #define BPF_Fs32000_Fc90_B2                        1061166033         /* Floating point value 0.988288 */
 #define BPF_Fs44100_Fc90_A0                           4517651         /* Floating point value 0.004207 */
 #define BPF_Fs44100_Fc90_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs44100_Fc90_A2                          -4517651         /* Floating point value -0.004207 */
-#define BPF_Fs44100_Fc90_B1                       -2138167926         /* Floating point value -1.991324 */
+#define BPF_Fs44100_Fc90_A2                         (-4517651)        /* Floating point value -0.004207 */
+#define BPF_Fs44100_Fc90_B1                      (-2138167926)        /* Floating point value -1.991324 */
 #define BPF_Fs44100_Fc90_B2                        1064601898         /* Floating point value 0.991488 */
 #define BPF_Fs48000_Fc90_A0                           4152024         /* Floating point value 0.003867 */
 #define BPF_Fs48000_Fc90_A1                                 0         /* Floating point value 0.000000 */
-#define BPF_Fs48000_Fc90_A2                          -4152024         /* Floating point value -0.003867 */
-#define BPF_Fs48000_Fc90_B1                       -2138935002         /* Floating point value -1.992038 */
+#define BPF_Fs48000_Fc90_A2                         (-4152024)        /* Floating point value -0.003867 */
+#define BPF_Fs48000_Fc90_B1                      (-2138935002)        /* Floating point value -1.992038 */
 #define BPF_Fs48000_Fc90_B2                        1065341620         /* Floating point value 0.992177 */
 
 
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h b/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
index f578db9..2712b2c 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
@@ -74,63 +74,63 @@
 #define HPF_Fs22050_Gain6_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain6_Shift                             1         /* Shift value */
                                                                     /* Gain =  7.000000 dB */
-#define HPF_Fs22050_Gain7_A0                             -164         /* Floating point value -0.005002 */
+#define HPF_Fs22050_Gain7_A0                            (-164)        /* Floating point value -0.005002 */
 #define HPF_Fs22050_Gain7_A1                            11311         /* Floating point value 0.345199 */
 #define HPF_Fs22050_Gain7_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain7_B1                            12125         /* Floating point value 0.370033 */
 #define HPF_Fs22050_Gain7_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain7_Shift                             2         /* Shift value */
                                                                     /* Gain =  8.000000 dB */
-#define HPF_Fs22050_Gain8_A0                             -864         /* Floating point value -0.026368 */
+#define HPF_Fs22050_Gain8_A0                            (-864)        /* Floating point value -0.026368 */
 #define HPF_Fs22050_Gain8_A1                            12012         /* Floating point value 0.366565 */
 #define HPF_Fs22050_Gain8_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain8_B1                            12125         /* Floating point value 0.370033 */
 #define HPF_Fs22050_Gain8_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain8_Shift                             2         /* Shift value */
                                                                     /* Gain =  9.000000 dB */
-#define HPF_Fs22050_Gain9_A0                            -1650         /* Floating point value -0.050340 */
+#define HPF_Fs22050_Gain9_A0                           (-1650)        /* Floating point value -0.050340 */
 #define HPF_Fs22050_Gain9_A1                            12797         /* Floating point value 0.390537 */
 #define HPF_Fs22050_Gain9_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain9_B1                            12125         /* Floating point value 0.370033 */
 #define HPF_Fs22050_Gain9_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain9_Shift                             2         /* Shift value */
                                                                     /* Gain =  10.000000 dB */
-#define HPF_Fs22050_Gain10_A0                           -2531         /* Floating point value -0.077238 */
+#define HPF_Fs22050_Gain10_A0                          (-2531)        /* Floating point value -0.077238 */
 #define HPF_Fs22050_Gain10_A1                           13679         /* Floating point value 0.417435 */
 #define HPF_Fs22050_Gain10_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain10_B1                           12125         /* Floating point value 0.370033 */
 #define HPF_Fs22050_Gain10_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain10_Shift                            2         /* Shift value */
                                                                     /* Gain =  11.000000 dB */
-#define HPF_Fs22050_Gain11_A0                           -3520         /* Floating point value -0.107417 */
+#define HPF_Fs22050_Gain11_A0                          (-3520)        /* Floating point value -0.107417 */
 #define HPF_Fs22050_Gain11_A1                           14667         /* Floating point value 0.447615 */
 #define HPF_Fs22050_Gain11_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain11_B1                           12125         /* Floating point value 0.370033 */
 #define HPF_Fs22050_Gain11_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain11_Shift                            2         /* Shift value */
                                                                     /* Gain =  12.000000 dB */
-#define HPF_Fs22050_Gain12_A0                           -4629         /* Floating point value -0.141279 */
+#define HPF_Fs22050_Gain12_A0                          (-4629)        /* Floating point value -0.141279 */
 #define HPF_Fs22050_Gain12_A1                           15777         /* Floating point value 0.481477 */
 #define HPF_Fs22050_Gain12_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain12_B1                           12125         /* Floating point value 0.370033 */
 #define HPF_Fs22050_Gain12_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain12_Shift                            2         /* Shift value */
                                                                     /* Gain =  13.000000 dB */
-#define HPF_Fs22050_Gain13_A0                           -2944         /* Floating point value -0.089849 */
+#define HPF_Fs22050_Gain13_A0                          (-2944)        /* Floating point value -0.089849 */
 #define HPF_Fs22050_Gain13_A1                            8531         /* Floating point value 0.260352 */
 #define HPF_Fs22050_Gain13_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain13_B1                           12125         /* Floating point value 0.370033 */
 #define HPF_Fs22050_Gain13_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain13_Shift                            3         /* Shift value */
                                                                     /* Gain =  14.000000 dB */
-#define HPF_Fs22050_Gain14_A0                           -3644         /* Floating point value -0.111215 */
+#define HPF_Fs22050_Gain14_A0                          (-3644)        /* Floating point value -0.111215 */
 #define HPF_Fs22050_Gain14_A1                            9231         /* Floating point value 0.281718 */
 #define HPF_Fs22050_Gain14_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain14_B1                           12125         /* Floating point value 0.370033 */
 #define HPF_Fs22050_Gain14_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain14_Shift                            3         /* Shift value */
                                                                     /* Gain =  15.000000 dB */
-#define HPF_Fs22050_Gain15_A0                           -4430         /* Floating point value -0.135187 */
+#define HPF_Fs22050_Gain15_A0                          (-4430)        /* Floating point value -0.135187 */
 #define HPF_Fs22050_Gain15_A1                           10017         /* Floating point value 0.305690 */
 #define HPF_Fs22050_Gain15_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs22050_Gain15_B1                           12125         /* Floating point value 0.370033 */
@@ -168,77 +168,77 @@
 #define HPF_Fs24000_Gain4_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain4_Shift                             1         /* Shift value */
                                                                     /* Gain =  5.000000 dB */
-#define HPF_Fs24000_Gain5_A0                             -275         /* Floating point value -0.008383 */
+#define HPF_Fs24000_Gain5_A0                            (-275)        /* Floating point value -0.008383 */
 #define HPF_Fs24000_Gain5_A1                            20860         /* Floating point value 0.636589 */
 #define HPF_Fs24000_Gain5_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain5_B1                             8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain5_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain5_Shift                             1         /* Shift value */
                                                                     /* Gain =  6.000000 dB */
-#define HPF_Fs24000_Gain6_A0                            -1564         /* Floating point value -0.047733 */
+#define HPF_Fs24000_Gain6_A0                           (-1564)        /* Floating point value -0.047733 */
 #define HPF_Fs24000_Gain6_A1                            22149         /* Floating point value 0.675938 */
 #define HPF_Fs24000_Gain6_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain6_B1                             8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain6_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain6_Shift                             1         /* Shift value */
                                                                     /* Gain =  7.000000 dB */
-#define HPF_Fs24000_Gain7_A0                            -1509         /* Floating point value -0.046051 */
+#define HPF_Fs24000_Gain7_A0                           (-1509)        /* Floating point value -0.046051 */
 #define HPF_Fs24000_Gain7_A1                            11826         /* Floating point value 0.360899 */
 #define HPF_Fs24000_Gain7_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain7_B1                             8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain7_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain7_Shift                             2         /* Shift value */
                                                                     /* Gain =  8.000000 dB */
-#define HPF_Fs24000_Gain8_A0                            -2323         /* Floating point value -0.070878 */
+#define HPF_Fs24000_Gain8_A0                           (-2323)        /* Floating point value -0.070878 */
 #define HPF_Fs24000_Gain8_A1                            12640         /* Floating point value 0.385727 */
 #define HPF_Fs24000_Gain8_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain8_B1                             8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain8_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain8_Shift                             2         /* Shift value */
                                                                     /* Gain =  9.000000 dB */
-#define HPF_Fs24000_Gain9_A0                            -3235         /* Floating point value -0.098736 */
+#define HPF_Fs24000_Gain9_A0                           (-3235)        /* Floating point value -0.098736 */
 #define HPF_Fs24000_Gain9_A1                            13552         /* Floating point value 0.413584 */
 #define HPF_Fs24000_Gain9_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain9_B1                             8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain9_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain9_Shift                             2         /* Shift value */
                                                                     /* Gain =  10.000000 dB */
-#define HPF_Fs24000_Gain10_A0                           -4260         /* Floating point value -0.129992 */
+#define HPF_Fs24000_Gain10_A0                          (-4260)        /* Floating point value -0.129992 */
 #define HPF_Fs24000_Gain10_A1                           14577         /* Floating point value 0.444841 */
 #define HPF_Fs24000_Gain10_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain10_B1                            8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain10_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain10_Shift                            2         /* Shift value */
                                                                     /* Gain =  11.000000 dB */
-#define HPF_Fs24000_Gain11_A0                           -5409         /* Floating point value -0.165062 */
+#define HPF_Fs24000_Gain11_A0                          (-5409)        /* Floating point value -0.165062 */
 #define HPF_Fs24000_Gain11_A1                           15726         /* Floating point value 0.479911 */
 #define HPF_Fs24000_Gain11_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain11_B1                            8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain11_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain11_Shift                            2         /* Shift value */
                                                                     /* Gain =  12.000000 dB */
-#define HPF_Fs24000_Gain12_A0                           -6698         /* Floating point value -0.204411 */
+#define HPF_Fs24000_Gain12_A0                          (-6698)        /* Floating point value -0.204411 */
 #define HPF_Fs24000_Gain12_A1                           17015         /* Floating point value 0.519260 */
 #define HPF_Fs24000_Gain12_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain12_B1                            8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain12_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain12_Shift                            2         /* Shift value */
                                                                     /* Gain =  13.000000 dB */
-#define HPF_Fs24000_Gain13_A0                           -4082         /* Floating point value -0.124576 */
+#define HPF_Fs24000_Gain13_A0                          (-4082)        /* Floating point value -0.124576 */
 #define HPF_Fs24000_Gain13_A1                            9253         /* Floating point value 0.282374 */
 #define HPF_Fs24000_Gain13_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain13_B1                            8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain13_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain13_Shift                            3         /* Shift value */
                                                                     /* Gain =  14.000000 dB */
-#define HPF_Fs24000_Gain14_A0                           -4896         /* Floating point value -0.149404 */
+#define HPF_Fs24000_Gain14_A0                          (-4896)        /* Floating point value -0.149404 */
 #define HPF_Fs24000_Gain14_A1                           10066         /* Floating point value 0.307202 */
 #define HPF_Fs24000_Gain14_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain14_B1                            8780         /* Floating point value 0.267949 */
 #define HPF_Fs24000_Gain14_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain14_Shift                            3         /* Shift value */
                                                                     /* Gain =  15.000000 dB */
-#define HPF_Fs24000_Gain15_A0                           -5808         /* Floating point value -0.177261 */
+#define HPF_Fs24000_Gain15_A0                          (-5808)        /* Floating point value -0.177261 */
 #define HPF_Fs24000_Gain15_A1                           10979         /* Floating point value 0.335059 */
 #define HPF_Fs24000_Gain15_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs24000_Gain15_B1                            8780         /* Floating point value 0.267949 */
@@ -249,105 +249,105 @@
 /* Coefficients for sample rate 32000Hz */
                                                                     /* Gain =  1.000000 dB */
 #define HPF_Fs32000_Gain1_A0                            17225         /* Floating point value 0.525677 */
-#define HPF_Fs32000_Gain1_A1                             -990         /* Floating point value -0.030227 */
+#define HPF_Fs32000_Gain1_A1                            (-990)        /* Floating point value -0.030227 */
 #define HPF_Fs32000_Gain1_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain1_B1                                0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain1_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain1_Shift                             1         /* Shift value */
                                                                     /* Gain =  2.000000 dB */
 #define HPF_Fs32000_Gain2_A0                            18337         /* Floating point value 0.559593 */
-#define HPF_Fs32000_Gain2_A1                            -2102         /* Floating point value -0.064142 */
+#define HPF_Fs32000_Gain2_A1                           (-2102)        /* Floating point value -0.064142 */
 #define HPF_Fs32000_Gain2_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain2_B1                                0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain2_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain2_Shift                             1         /* Shift value */
                                                                     /* Gain =  3.000000 dB */
 #define HPF_Fs32000_Gain3_A0                            19584         /* Floating point value 0.597646 */
-#define HPF_Fs32000_Gain3_A1                            -3349         /* Floating point value -0.102196 */
+#define HPF_Fs32000_Gain3_A1                           (-3349)        /* Floating point value -0.102196 */
 #define HPF_Fs32000_Gain3_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain3_B1                                0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain3_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain3_Shift                             1         /* Shift value */
                                                                     /* Gain =  4.000000 dB */
 #define HPF_Fs32000_Gain4_A0                            20983         /* Floating point value 0.640343 */
-#define HPF_Fs32000_Gain4_A1                            -4748         /* Floating point value -0.144893 */
+#define HPF_Fs32000_Gain4_A1                           (-4748)        /* Floating point value -0.144893 */
 #define HPF_Fs32000_Gain4_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain4_B1                                0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain4_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain4_Shift                             1         /* Shift value */
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs32000_Gain5_A0                            22553         /* Floating point value 0.688250 */
-#define HPF_Fs32000_Gain5_A1                            -6318         /* Floating point value -0.192799 */
+#define HPF_Fs32000_Gain5_A1                           (-6318)        /* Floating point value -0.192799 */
 #define HPF_Fs32000_Gain5_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain5_B1                                0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain5_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain5_Shift                             1         /* Shift value */
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs32000_Gain6_A0                            24314         /* Floating point value 0.742002 */
-#define HPF_Fs32000_Gain6_A1                            -8079         /* Floating point value -0.246551 */
+#define HPF_Fs32000_Gain6_A1                           (-8079)        /* Floating point value -0.246551 */
 #define HPF_Fs32000_Gain6_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain6_B1                                0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain6_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain6_Shift                             1         /* Shift value */
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs32000_Gain7_A0                            13176         /* Floating point value 0.402109 */
-#define HPF_Fs32000_Gain7_A1                            -5040         /* Floating point value -0.153795 */
+#define HPF_Fs32000_Gain7_A1                           (-5040)        /* Floating point value -0.153795 */
 #define HPF_Fs32000_Gain7_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain7_B1                                0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain7_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain7_Shift                             2         /* Shift value */
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs32000_Gain8_A0                            14288         /* Floating point value 0.436024 */
-#define HPF_Fs32000_Gain8_A1                            -6151         /* Floating point value -0.187711 */
+#define HPF_Fs32000_Gain8_A1                           (-6151)        /* Floating point value -0.187711 */
 #define HPF_Fs32000_Gain8_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain8_B1                                0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain8_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain8_Shift                             2         /* Shift value */
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs32000_Gain9_A0                            15535         /* Floating point value 0.474078 */
-#define HPF_Fs32000_Gain9_A1                            -7398         /* Floating point value -0.225764 */
+#define HPF_Fs32000_Gain9_A1                           (-7398)        /* Floating point value -0.225764 */
 #define HPF_Fs32000_Gain9_A2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain9_B1                                0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain9_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain9_Shift                             2         /* Shift value */
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs32000_Gain10_A0                           16934         /* Floating point value 0.516774 */
-#define HPF_Fs32000_Gain10_A1                           -8797         /* Floating point value -0.268461 */
+#define HPF_Fs32000_Gain10_A1                          (-8797)        /* Floating point value -0.268461 */
 #define HPF_Fs32000_Gain10_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain10_B1                               0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain10_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain10_Shift                            2         /* Shift value */
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs32000_Gain11_A0                           18503         /* Floating point value 0.564681 */
-#define HPF_Fs32000_Gain11_A1                          -10367         /* Floating point value -0.316368 */
+#define HPF_Fs32000_Gain11_A1                         (-10367)        /* Floating point value -0.316368 */
 #define HPF_Fs32000_Gain11_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain11_B1                               0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain11_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain11_Shift                            2         /* Shift value */
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs32000_Gain12_A0                           20265         /* Floating point value 0.618433 */
-#define HPF_Fs32000_Gain12_A1                          -12128         /* Floating point value -0.370120 */
+#define HPF_Fs32000_Gain12_A1                         (-12128)        /* Floating point value -0.370120 */
 #define HPF_Fs32000_Gain12_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain12_B1                               0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain12_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain12_Shift                            2         /* Shift value */
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs32000_Gain13_A0                           11147         /* Floating point value 0.340178 */
-#define HPF_Fs32000_Gain13_A1                           -7069         /* Floating point value -0.215726 */
+#define HPF_Fs32000_Gain13_A1                          (-7069)        /* Floating point value -0.215726 */
 #define HPF_Fs32000_Gain13_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain13_B1                               0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain13_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain13_Shift                            3         /* Shift value */
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs32000_Gain14_A0                           12258         /* Floating point value 0.374093 */
-#define HPF_Fs32000_Gain14_A1                           -8180         /* Floating point value -0.249642 */
+#define HPF_Fs32000_Gain14_A1                          (-8180)        /* Floating point value -0.249642 */
 #define HPF_Fs32000_Gain14_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain14_B1                               0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain14_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain14_Shift                            3         /* Shift value */
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs32000_Gain15_A0                           13505         /* Floating point value 0.412147 */
-#define HPF_Fs32000_Gain15_A1                           -9427         /* Floating point value -0.287695 */
+#define HPF_Fs32000_Gain15_A1                          (-9427)        /* Floating point value -0.287695 */
 #define HPF_Fs32000_Gain15_A2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs32000_Gain15_B1                               0         /* Floating point value -0.000000 */
 #define HPF_Fs32000_Gain15_B2                               0         /* Floating point value 0.000000 */
@@ -357,107 +357,107 @@
 /* Coefficients for sample rate 44100Hz */
                                                                     /* Gain =  1.000000 dB */
 #define HPF_Fs44100_Gain1_A0                            17442         /* Floating point value 0.532294 */
-#define HPF_Fs44100_Gain1_A1                            -4761         /* Floating point value -0.145294 */
+#define HPF_Fs44100_Gain1_A1                           (-4761)        /* Floating point value -0.145294 */
 #define HPF_Fs44100_Gain1_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain1_B1                            -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain1_B1                           (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain1_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain1_Shift                             1         /* Shift value */
                                                                     /* Gain =  2.000000 dB */
 #define HPF_Fs44100_Gain2_A0                            18797         /* Floating point value 0.573633 */
-#define HPF_Fs44100_Gain2_A1                            -6116         /* Floating point value -0.186634 */
+#define HPF_Fs44100_Gain2_A1                           (-6116)        /* Floating point value -0.186634 */
 #define HPF_Fs44100_Gain2_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain2_B1                            -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain2_B1                           (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain2_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain2_Shift                             1         /* Shift value */
                                                                     /* Gain =  3.000000 dB */
 #define HPF_Fs44100_Gain3_A0                            20317         /* Floating point value 0.620016 */
-#define HPF_Fs44100_Gain3_A1                            -7635         /* Floating point value -0.233017 */
+#define HPF_Fs44100_Gain3_A1                           (-7635)        /* Floating point value -0.233017 */
 #define HPF_Fs44100_Gain3_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain3_B1                            -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain3_B1                           (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain3_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain3_Shift                             1         /* Shift value */
                                                                     /* Gain =  4.000000 dB */
 #define HPF_Fs44100_Gain4_A0                            22022         /* Floating point value 0.672059 */
-#define HPF_Fs44100_Gain4_A1                            -9341         /* Floating point value -0.285060 */
+#define HPF_Fs44100_Gain4_A1                           (-9341)        /* Floating point value -0.285060 */
 #define HPF_Fs44100_Gain4_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain4_B1                            -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain4_B1                           (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain4_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain4_Shift                             1         /* Shift value */
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs44100_Gain5_A0                            23935         /* Floating point value 0.730452 */
-#define HPF_Fs44100_Gain5_A1                           -11254         /* Floating point value -0.343453 */
+#define HPF_Fs44100_Gain5_A1                          (-11254)        /* Floating point value -0.343453 */
 #define HPF_Fs44100_Gain5_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain5_B1                            -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain5_B1                           (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain5_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain5_Shift                             1         /* Shift value */
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs44100_Gain6_A0                            26082         /* Floating point value 0.795970 */
-#define HPF_Fs44100_Gain6_A1                           -13401         /* Floating point value -0.408971 */
+#define HPF_Fs44100_Gain6_A1                          (-13401)        /* Floating point value -0.408971 */
 #define HPF_Fs44100_Gain6_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain6_B1                            -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain6_B1                           (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain6_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain6_Shift                             1         /* Shift value */
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs44100_Gain7_A0                            14279         /* Floating point value 0.435774 */
-#define HPF_Fs44100_Gain7_A1                            -7924         /* Floating point value -0.241815 */
+#define HPF_Fs44100_Gain7_A1                           (-7924)        /* Floating point value -0.241815 */
 #define HPF_Fs44100_Gain7_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain7_B1                            -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain7_B1                           (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain7_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain7_Shift                             2         /* Shift value */
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs44100_Gain8_A0                            15634         /* Floating point value 0.477113 */
-#define HPF_Fs44100_Gain8_A1                            -9278         /* Floating point value -0.283154 */
+#define HPF_Fs44100_Gain8_A1                           (-9278)        /* Floating point value -0.283154 */
 #define HPF_Fs44100_Gain8_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain8_B1                            -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain8_B1                           (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain8_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain8_Shift                             2         /* Shift value */
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs44100_Gain9_A0                            17154         /* Floating point value 0.523496 */
-#define HPF_Fs44100_Gain9_A1                           -10798         /* Floating point value -0.329537 */
+#define HPF_Fs44100_Gain9_A1                          (-10798)        /* Floating point value -0.329537 */
 #define HPF_Fs44100_Gain9_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain9_B1                            -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain9_B1                           (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain9_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain9_Shift                             2         /* Shift value */
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs44100_Gain10_A0                           18859         /* Floating point value 0.575539 */
-#define HPF_Fs44100_Gain10_A1                          -12504         /* Floating point value -0.381580 */
+#define HPF_Fs44100_Gain10_A1                         (-12504)        /* Floating point value -0.381580 */
 #define HPF_Fs44100_Gain10_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain10_B1                           -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain10_B1                          (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain10_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain10_Shift                            2         /* Shift value */
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs44100_Gain11_A0                           20773         /* Floating point value 0.633932 */
-#define HPF_Fs44100_Gain11_A1                          -14417         /* Floating point value -0.439973 */
+#define HPF_Fs44100_Gain11_A1                         (-14417)        /* Floating point value -0.439973 */
 #define HPF_Fs44100_Gain11_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain11_B1                           -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain11_B1                          (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain11_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain11_Shift                            2         /* Shift value */
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs44100_Gain12_A0                           22920         /* Floating point value 0.699450 */
-#define HPF_Fs44100_Gain12_A1                          -16564         /* Floating point value -0.505491 */
+#define HPF_Fs44100_Gain12_A1                         (-16564)        /* Floating point value -0.505491 */
 #define HPF_Fs44100_Gain12_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain12_B1                           -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain12_B1                          (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain12_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain12_Shift                            2         /* Shift value */
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs44100_Gain13_A0                           12694         /* Floating point value 0.387399 */
-#define HPF_Fs44100_Gain13_A1                           -9509         /* Floating point value -0.290189 */
+#define HPF_Fs44100_Gain13_A1                          (-9509)        /* Floating point value -0.290189 */
 #define HPF_Fs44100_Gain13_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain13_B1                           -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain13_B1                          (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain13_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain13_Shift                            3         /* Shift value */
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs44100_Gain14_A0                           14049         /* Floating point value 0.428738 */
-#define HPF_Fs44100_Gain14_A1                          -10864         /* Floating point value -0.331528 */
+#define HPF_Fs44100_Gain14_A1                         (-10864)        /* Floating point value -0.331528 */
 #define HPF_Fs44100_Gain14_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain14_B1                           -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain14_B1                          (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain14_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain14_Shift                            3         /* Shift value */
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs44100_Gain15_A0                           15569         /* Floating point value 0.475121 */
-#define HPF_Fs44100_Gain15_A1                          -12383         /* Floating point value -0.377912 */
+#define HPF_Fs44100_Gain15_A1                         (-12383)        /* Floating point value -0.377912 */
 #define HPF_Fs44100_Gain15_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs44100_Gain15_B1                           -7173         /* Floating point value -0.218894 */
+#define HPF_Fs44100_Gain15_B1                          (-7173)        /* Floating point value -0.218894 */
 #define HPF_Fs44100_Gain15_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs44100_Gain15_Shift                            3         /* Shift value */
 
@@ -465,107 +465,107 @@
 /* Coefficients for sample rate 48000Hz */
                                                                     /* Gain =  1.000000 dB */
 #define HPF_Fs48000_Gain1_A0                            17491         /* Floating point value 0.533777 */
-#define HPF_Fs48000_Gain1_A1                            -5606         /* Floating point value -0.171082 */
+#define HPF_Fs48000_Gain1_A1                           (-5606)        /* Floating point value -0.171082 */
 #define HPF_Fs48000_Gain1_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain1_B1                            -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain1_B1                           (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain1_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain1_Shift                             1         /* Shift value */
                                                                     /* Gain =  2.000000 dB */
 #define HPF_Fs48000_Gain2_A0                            18900         /* Floating point value 0.576779 */
-#define HPF_Fs48000_Gain2_A1                            -7015         /* Floating point value -0.214085 */
+#define HPF_Fs48000_Gain2_A1                           (-7015)        /* Floating point value -0.214085 */
 #define HPF_Fs48000_Gain2_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain2_B1                            -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain2_B1                           (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain2_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain2_Shift                             1         /* Shift value */
                                                                     /* Gain =  3.000000 dB */
 #define HPF_Fs48000_Gain3_A0                            20481         /* Floating point value 0.625029 */
-#define HPF_Fs48000_Gain3_A1                            -8596         /* Floating point value -0.262335 */
+#define HPF_Fs48000_Gain3_A1                           (-8596)        /* Floating point value -0.262335 */
 #define HPF_Fs48000_Gain3_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain3_B1                            -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain3_B1                           (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain3_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain3_Shift                             1         /* Shift value */
                                                                     /* Gain =  4.000000 dB */
 #define HPF_Fs48000_Gain4_A0                            22255         /* Floating point value 0.679167 */
-#define HPF_Fs48000_Gain4_A1                           -10370         /* Floating point value -0.316472 */
+#define HPF_Fs48000_Gain4_A1                          (-10370)        /* Floating point value -0.316472 */
 #define HPF_Fs48000_Gain4_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain4_B1                            -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain4_B1                           (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain4_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain4_Shift                             1         /* Shift value */
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs48000_Gain5_A0                            24245         /* Floating point value 0.739910 */
-#define HPF_Fs48000_Gain5_A1                           -12361         /* Floating point value -0.377215 */
+#define HPF_Fs48000_Gain5_A1                          (-12361)        /* Floating point value -0.377215 */
 #define HPF_Fs48000_Gain5_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain5_B1                            -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain5_B1                           (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain5_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain5_Shift                             1         /* Shift value */
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs48000_Gain6_A0                            26479         /* Floating point value 0.808065 */
-#define HPF_Fs48000_Gain6_A1                           -14594         /* Floating point value -0.445370 */
+#define HPF_Fs48000_Gain6_A1                          (-14594)        /* Floating point value -0.445370 */
 #define HPF_Fs48000_Gain6_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain6_B1                            -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain6_B1                           (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain6_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain6_Shift                             1         /* Shift value */
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs48000_Gain7_A0                            14527         /* Floating point value 0.443318 */
-#define HPF_Fs48000_Gain7_A1                            -8570         /* Floating point value -0.261540 */
+#define HPF_Fs48000_Gain7_A1                           (-8570)        /* Floating point value -0.261540 */
 #define HPF_Fs48000_Gain7_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain7_B1                            -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain7_B1                           (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain7_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain7_Shift                             2         /* Shift value */
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs48000_Gain8_A0                            15936         /* Floating point value 0.486321 */
-#define HPF_Fs48000_Gain8_A1                            -9979         /* Floating point value -0.304543 */
+#define HPF_Fs48000_Gain8_A1                           (-9979)        /* Floating point value -0.304543 */
 #define HPF_Fs48000_Gain8_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain8_B1                            -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain8_B1                           (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain8_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain8_Shift                             2         /* Shift value */
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs48000_Gain9_A0                            17517         /* Floating point value 0.534571 */
-#define HPF_Fs48000_Gain9_A1                           -11560         /* Floating point value -0.352793 */
+#define HPF_Fs48000_Gain9_A1                          (-11560)        /* Floating point value -0.352793 */
 #define HPF_Fs48000_Gain9_A2                                0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain9_B1                            -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain9_B1                           (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain9_B2                                0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain9_Shift                             2         /* Shift value */
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs48000_Gain10_A0                           19291         /* Floating point value 0.588708 */
-#define HPF_Fs48000_Gain10_A1                          -13334         /* Floating point value -0.406930 */
+#define HPF_Fs48000_Gain10_A1                         (-13334)        /* Floating point value -0.406930 */
 #define HPF_Fs48000_Gain10_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain10_B1                           -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain10_B1                          (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain10_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain10_Shift                            2         /* Shift value */
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs48000_Gain11_A0                           21281         /* Floating point value 0.649452 */
-#define HPF_Fs48000_Gain11_A1                          -15325         /* Floating point value -0.467674 */
+#define HPF_Fs48000_Gain11_A1                         (-15325)        /* Floating point value -0.467674 */
 #define HPF_Fs48000_Gain11_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain11_B1                           -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain11_B1                          (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain11_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain11_Shift                            2         /* Shift value */
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs48000_Gain12_A0                           23515         /* Floating point value 0.717607 */
-#define HPF_Fs48000_Gain12_A1                          -17558         /* Floating point value -0.535829 */
+#define HPF_Fs48000_Gain12_A1                         (-17558)        /* Floating point value -0.535829 */
 #define HPF_Fs48000_Gain12_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain12_B1                           -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain12_B1                          (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain12_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain12_Shift                            2         /* Shift value */
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs48000_Gain13_A0                           13041         /* Floating point value 0.397982 */
-#define HPF_Fs48000_Gain13_A1                          -10056         /* Floating point value -0.306877 */
+#define HPF_Fs48000_Gain13_A1                         (-10056)        /* Floating point value -0.306877 */
 #define HPF_Fs48000_Gain13_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain13_B1                           -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain13_B1                          (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain13_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain13_Shift                            3         /* Shift value */
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs48000_Gain14_A0                           14450         /* Floating point value 0.440984 */
-#define HPF_Fs48000_Gain14_A1                          -11465         /* Floating point value -0.349880 */
+#define HPF_Fs48000_Gain14_A1                         (-11465)        /* Floating point value -0.349880 */
 #define HPF_Fs48000_Gain14_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain14_B1                           -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain14_B1                          (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain14_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain14_Shift                            3         /* Shift value */
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs48000_Gain15_A0                           16031         /* Floating point value 0.489234 */
-#define HPF_Fs48000_Gain15_A1                          -13046         /* Floating point value -0.398130 */
+#define HPF_Fs48000_Gain15_A1                         (-13046)        /* Floating point value -0.398130 */
 #define HPF_Fs48000_Gain15_A2                               0         /* Floating point value 0.000000 */
-#define HPF_Fs48000_Gain15_B1                           -8780         /* Floating point value -0.267949 */
+#define HPF_Fs48000_Gain15_B1                          (-8780)        /* Floating point value -0.267949 */
 #define HPF_Fs48000_Gain15_B2                               0         /* Floating point value 0.000000 */
 #define HPF_Fs48000_Gain15_Shift                            3         /* Shift value */
 
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Private.h b/media/libeffects/lvm/lib/Bundle/src/LVM_Private.h
index 2d1cf42..2e85f77 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Private.h
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Private.h
@@ -81,7 +81,7 @@
 #define LVM_TE_MIN_EFFECTLEVEL          0         /*TE Minimum EffectLevel*/
 #define LVM_TE_MAX_EFFECTLEVEL          15        /*TE Maximum Effect level*/
 
-#define LVM_VC_MIN_EFFECTLEVEL          -96       /*VC Minimum EffectLevel*/
+#define LVM_VC_MIN_EFFECTLEVEL          (-96)     /*VC Minimum EffectLevel*/
 #define LVM_VC_MAX_EFFECTLEVEL          0         /*VC Maximum Effect level*/
 
 #define LVM_BE_MIN_EFFECTLEVEL          0         /*BE Minimum EffectLevel*/
@@ -89,7 +89,7 @@
 
 #define LVM_EQNB_MIN_BAND_FREQ          20        /*EQNB Minimum Band Frequency*/
 #define LVM_EQNB_MAX_BAND_FREQ          24000     /*EQNB Maximum Band Frequency*/
-#define LVM_EQNB_MIN_BAND_GAIN          -15       /*EQNB Minimum Band Frequency*/
+#define LVM_EQNB_MIN_BAND_GAIN          (-15)     /*EQNB Minimum Band Frequency*/
 #define LVM_EQNB_MAX_BAND_GAIN          15        /*EQNB Maximum Band Frequency*/
 #define LVM_EQNB_MIN_QFACTOR            25        /*EQNB Minimum Q Factor*/
 #define LVM_EQNB_MAX_QFACTOR            1200      /*EQNB Maximum Q Factor*/
@@ -103,7 +103,7 @@
 
 #define LVM_VC_MIXER_TIME              100       /*VC mixer time*/
 #define LVM_VC_BALANCE_MAX             96        /*VC balance max value*/
-#define LVM_VC_BALANCE_MIN             -96       /*VC balance min value*/
+#define LVM_VC_BALANCE_MIN             (-96)     /*VC balance min value*/
 
 /* Algorithm masks */
 #define LVM_CS_MASK                     1
diff --git a/media/libeffects/lvm/lib/Common/lib/LVM_Types.h b/media/libeffects/lvm/lib/Common/lib/LVM_Types.h
index 0c6fb25..68c55f7 100644
--- a/media/libeffects/lvm/lib/Common/lib/LVM_Types.h
+++ b/media/libeffects/lvm/lib/Common/lib/LVM_Types.h
@@ -73,10 +73,10 @@
 #define LVM_MEM_EXTERNAL        8                   /* External (slow) access memory */
 
 /* Platform specific */
-#define LVM_PERSISTENT          LVM_MEM_PARTITION0+LVM_MEM_PERSISTENT+LVM_MEM_INTERNAL
-#define LVM_PERSISTENT_DATA     LVM_MEM_PARTITION1+LVM_MEM_PERSISTENT+LVM_MEM_INTERNAL
-#define LVM_PERSISTENT_COEF     LVM_MEM_PARTITION2+LVM_MEM_PERSISTENT+LVM_MEM_INTERNAL
-#define LVM_SCRATCH             LVM_MEM_PARTITION3+LVM_MEM_SCRATCH+LVM_MEM_INTERNAL
+#define LVM_PERSISTENT          (LVM_MEM_PARTITION0+LVM_MEM_PERSISTENT+LVM_MEM_INTERNAL)
+#define LVM_PERSISTENT_DATA     (LVM_MEM_PARTITION1+LVM_MEM_PERSISTENT+LVM_MEM_INTERNAL)
+#define LVM_PERSISTENT_COEF     (LVM_MEM_PARTITION2+LVM_MEM_PERSISTENT+LVM_MEM_INTERNAL)
+#define LVM_SCRATCH             (LVM_MEM_PARTITION3+LVM_MEM_SCRATCH+LVM_MEM_INTERNAL)
 
 /****************************************************************************************/
 /*                                                                                      */
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
index 87d7145..95212f2 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
@@ -27,21 +27,21 @@
 /************************************************************************************/
 
 #define LVEQNB_GAINSHIFT                                   11         /* As a power of 2 */
-#define LVEQNB_Gain_Neg15_dB                            -1684         /* Floating point value -0.822172 */
-#define LVEQNB_Gain_Neg14_dB                            -1639         /* Floating point value -0.800474 */
-#define LVEQNB_Gain_Neg13_dB                            -1590         /* Floating point value -0.776128 */
-#define LVEQNB_Gain_Neg12_dB                            -1534         /* Floating point value -0.748811 */
-#define LVEQNB_Gain_Neg11_dB                            -1471         /* Floating point value -0.718162 */
-#define LVEQNB_Gain_Neg10_dB                            -1400         /* Floating point value -0.683772 */
-#define LVEQNB_Gain_Neg9_dB                             -1321         /* Floating point value -0.645187 */
-#define LVEQNB_Gain_Neg8_dB                             -1233         /* Floating point value -0.601893 */
-#define LVEQNB_Gain_Neg7_dB                             -1133         /* Floating point value -0.553316 */
-#define LVEQNB_Gain_Neg6_dB                             -1022         /* Floating point value -0.498813 */
-#define LVEQNB_Gain_Neg5_dB                              -896         /* Floating point value -0.437659 */
-#define LVEQNB_Gain_Neg4_dB                              -756         /* Floating point value -0.369043 */
-#define LVEQNB_Gain_Neg3_dB                              -598         /* Floating point value -0.292054 */
-#define LVEQNB_Gain_Neg2_dB                              -421         /* Floating point value -0.205672 */
-#define LVEQNB_Gain_Neg1_dB                              -223         /* Floating point value -0.108749 */
+#define LVEQNB_Gain_Neg15_dB                           (-1684)        /* Floating point value -0.822172 */
+#define LVEQNB_Gain_Neg14_dB                           (-1639)        /* Floating point value -0.800474 */
+#define LVEQNB_Gain_Neg13_dB                           (-1590)        /* Floating point value -0.776128 */
+#define LVEQNB_Gain_Neg12_dB                           (-1534)        /* Floating point value -0.748811 */
+#define LVEQNB_Gain_Neg11_dB                           (-1471)        /* Floating point value -0.718162 */
+#define LVEQNB_Gain_Neg10_dB                           (-1400)        /* Floating point value -0.683772 */
+#define LVEQNB_Gain_Neg9_dB                            (-1321)        /* Floating point value -0.645187 */
+#define LVEQNB_Gain_Neg8_dB                            (-1233)        /* Floating point value -0.601893 */
+#define LVEQNB_Gain_Neg7_dB                            (-1133)        /* Floating point value -0.553316 */
+#define LVEQNB_Gain_Neg6_dB                            (-1022)        /* Floating point value -0.498813 */
+#define LVEQNB_Gain_Neg5_dB                             (-896)        /* Floating point value -0.437659 */
+#define LVEQNB_Gain_Neg4_dB                             (-756)        /* Floating point value -0.369043 */
+#define LVEQNB_Gain_Neg3_dB                             (-598)        /* Floating point value -0.292054 */
+#define LVEQNB_Gain_Neg2_dB                             (-421)        /* Floating point value -0.205672 */
+#define LVEQNB_Gain_Neg1_dB                             (-223)        /* Floating point value -0.108749 */
 #define LVEQNB_Gain_0_dB                                    0         /* Floating point value 0.000000 */
 #define LVEQNB_Gain_1_dB                                  250         /* Floating point value 0.122018 */
 #define LVEQNB_Gain_2_dB                                  530         /* Floating point value 0.258925 */
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Private.h b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Private.h
index 1d8bedd..03522fb 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Private.h
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Private.h
@@ -52,7 +52,7 @@
 #define LVPSA_NBANDSMIN                  1      /* Minimum number of frequency band                                 */
 #define LVPSA_NBANDSMAX                  30     /* Maximum number of frequency band                                 */
 #define LVPSA_MAXCENTERFREQ              20000  /* Maximum possible center frequency                                */
-#define LVPSA_MINPOSTGAIN                -15    /* Minimum possible post gain                                       */
+#define LVPSA_MINPOSTGAIN              (-15)    /* Minimum possible post gain                                       */
 #define LVPSA_MAXPOSTGAIN                15     /* Maximum possible post gain                                       */
 #define LVPSA_MINQFACTOR                 25     /* Minimum possible Q factor                                        */
 #define LVPSA_MAXQFACTOR                 1200   /* Maximum possible Q factor                                        */
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 1d55281..3e640cb 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 @@
 
 /* Stereo Enhancer coefficients for 8000 Hz sample rate, scaled with 0.161258 */
 #define CS_MIDDLE_8000_A0                          7462         /* Floating point value 0.227720 */
-#define CS_MIDDLE_8000_A1                         -7049         /* Floating point value -0.215125 */
+#define CS_MIDDLE_8000_A1                        (-7049)        /* Floating point value -0.215125 */
 #define CS_MIDDLE_8000_A2                             0         /* Floating point value 0.000000 */
-#define CS_MIDDLE_8000_B1                        -30209         /* Floating point value -0.921899 */
+#define CS_MIDDLE_8000_B1                       (-30209)        /* Floating point value -0.921899 */
 #define CS_MIDDLE_8000_B2                             0         /* Floating point value 0.000000 */
 #define CS_MIDDLE_8000_SCALE                         15
 #define CS_SIDE_8000_A0                           20036         /* Floating point value 0.611441 */
-#define CS_SIDE_8000_A1                          -12463         /* Floating point value -0.380344 */
-#define CS_SIDE_8000_A2                           -7573         /* Floating point value -0.231097 */
-#define CS_SIDE_8000_B1                          -20397         /* Floating point value -0.622470 */
-#define CS_SIDE_8000_B2                           -4285         /* Floating point value -0.130759 */
+#define CS_SIDE_8000_A1                         (-12463)        /* Floating point value -0.380344 */
+#define CS_SIDE_8000_A2                          (-7573)        /* Floating point value -0.231097 */
+#define CS_SIDE_8000_B1                         (-20397)        /* Floating point value -0.622470 */
+#define CS_SIDE_8000_B2                          (-4285)        /* Floating point value -0.130759 */
 #define CS_SIDE_8000_SCALE                           15
 
 /* Stereo Enhancer coefficients for 11025Hz sample rate, scaled with 0.162943 */
 #define CS_MIDDLE_11025_A0                         7564         /* Floating point value 0.230838 */
-#define CS_MIDDLE_11025_A1                        -7260         /* Floating point value -0.221559 */
+#define CS_MIDDLE_11025_A1                       (-7260)        /* Floating point value -0.221559 */
 #define CS_MIDDLE_11025_A2                            0         /* Floating point value 0.000000 */
-#define CS_MIDDLE_11025_B1                       -30902         /* Floating point value -0.943056 */
+#define CS_MIDDLE_11025_B1                      (-30902)        /* Floating point value -0.943056 */
 #define CS_MIDDLE_11025_B2                            0         /* Floating point value 0.000000 */
 #define CS_MIDDLE_11025_SCALE                        15
 #define CS_SIDE_11025_A0                          18264         /* Floating point value 0.557372 */
-#define CS_SIDE_11025_A1                         -12828         /* Floating point value -0.391490 */
-#define CS_SIDE_11025_A2                          -5436         /* Floating point value -0.165881 */
-#define CS_SIDE_11025_B1                         -28856         /* Floating point value -0.880608 */
+#define CS_SIDE_11025_A1                        (-12828)        /* Floating point value -0.391490 */
+#define CS_SIDE_11025_A2                         (-5436)        /* Floating point value -0.165881 */
+#define CS_SIDE_11025_B1                        (-28856)        /* Floating point value -0.880608 */
 #define CS_SIDE_11025_B2                           1062         /* Floating point value 0.032397 */
 #define CS_SIDE_11025_SCALE                          15
 
 /* Stereo Enhancer coefficients for 12000Hz sample rate, scaled with 0.162191 */
 #define CS_MIDDLE_12000_A0                         7534         /* Floating point value 0.229932 */
-#define CS_MIDDLE_12000_A1                        -7256         /* Floating point value -0.221436 */
+#define CS_MIDDLE_12000_A1                       (-7256)        /* Floating point value -0.221436 */
 #define CS_MIDDLE_12000_A2                            0         /* Floating point value 0.000000 */
-#define CS_MIDDLE_12000_B1                       -31051         /* Floating point value -0.947616 */
+#define CS_MIDDLE_12000_B1                      (-31051)        /* Floating point value -0.947616 */
 #define CS_MIDDLE_12000_B2                            0         /* Floating point value 0.000000 */
 #define CS_MIDDLE_12000_SCALE                        15
 #define CS_SIDE_12000_A0                          18298         /* Floating point value 0.558398 */
-#define CS_SIDE_12000_A1                         -12852         /* Floating point value -0.392211 */
-#define CS_SIDE_12000_A2                          -5446         /* Floating point value -0.166187 */
-#define CS_SIDE_12000_B1                         -29247         /* Floating point value -0.892550 */
+#define CS_SIDE_12000_A1                        (-12852)        /* Floating point value -0.392211 */
+#define CS_SIDE_12000_A2                         (-5446)        /* Floating point value -0.166187 */
+#define CS_SIDE_12000_B1                        (-29247)        /* Floating point value -0.892550 */
 #define CS_SIDE_12000_B2                           1077         /* Floating point value 0.032856 */
 #define CS_SIDE_12000_SCALE                          15
 
 /* Stereo Enhancer coefficients for 16000Hz sample rate, scaled with 0.162371 */
 #define CS_MIDDLE_16000_A0                         7558         /* Floating point value 0.230638 */
-#define CS_MIDDLE_16000_A1                        -7348         /* Floating point value -0.224232 */
+#define CS_MIDDLE_16000_A1                       (-7348)        /* Floating point value -0.224232 */
 #define CS_MIDDLE_16000_A2                            0         /* Floating point value 0.000000 */
-#define CS_MIDDLE_16000_B1                       -31475         /* Floating point value -0.960550 */
+#define CS_MIDDLE_16000_B1                      (-31475)        /* Floating point value -0.960550 */
 #define CS_MIDDLE_16000_B2                            0         /* Floating point value 0.000000 */
 #define CS_MIDDLE_16000_SCALE                        15
 #define CS_SIDE_16000_A0                           8187         /* Floating point value 0.499695 */
-#define CS_SIDE_16000_A1                          -5825         /* Floating point value -0.355543 */
-#define CS_SIDE_16000_A2                          -2362         /* Floating point value -0.144152 */
-#define CS_SIDE_16000_B1                         -17216         /* Floating point value -1.050788 */
+#define CS_SIDE_16000_A1                         (-5825)        /* Floating point value -0.355543 */
+#define CS_SIDE_16000_A2                         (-2362)        /* Floating point value -0.144152 */
+#define CS_SIDE_16000_B1                        (-17216)        /* Floating point value -1.050788 */
 #define CS_SIDE_16000_B2                           2361         /* Floating point value 0.144104 */
 #define CS_SIDE_16000_SCALE                          14
 
 /* Stereo Enhancer coefficients for 22050Hz sample rate, scaled with 0.160781 */
 #define CS_MIDDLE_22050_A0                         7496         /* Floating point value 0.228749 */
-#define CS_MIDDLE_22050_A1                        -7344         /* Floating point value -0.224128 */
+#define CS_MIDDLE_22050_A1                       (-7344)        /* Floating point value -0.224128 */
 #define CS_MIDDLE_22050_A2                            0         /* Floating point value 0.000000 */
-#define CS_MIDDLE_22050_B1                       -31826         /* Floating point value -0.971262 */
+#define CS_MIDDLE_22050_B1                      (-31826)        /* Floating point value -0.971262 */
 #define CS_MIDDLE_22050_B2                            0         /* Floating point value 0.000000 */
 #define CS_MIDDLE_22050_SCALE                        15
 #define CS_SIDE_22050_A0                           7211         /* Floating point value 0.440112 */
-#define CS_SIDE_22050_A1                          -4278         /* Floating point value -0.261096 */
-#define CS_SIDE_22050_A2                          -2933         /* Floating point value -0.179016 */
-#define CS_SIDE_22050_B1                         -18297         /* Floating point value -1.116786 */
+#define CS_SIDE_22050_A1                         (-4278)        /* Floating point value -0.261096 */
+#define CS_SIDE_22050_A2                         (-2933)        /* Floating point value -0.179016 */
+#define CS_SIDE_22050_B1                        (-18297)        /* Floating point value -1.116786 */
 #define CS_SIDE_22050_B2                           2990         /* Floating point value 0.182507 */
 #define CS_SIDE_22050_SCALE                          14
 
 /* Stereo Enhancer coefficients for 24000Hz sample rate, scaled with 0.161882 */
 #define CS_MIDDLE_24000_A0                         7550         /* Floating point value 0.230395 */
-#define CS_MIDDLE_24000_A1                        -7409         /* Floating point value -0.226117 */
+#define CS_MIDDLE_24000_A1                       (-7409)        /* Floating point value -0.226117 */
 #define CS_MIDDLE_24000_A2                            0         /* Floating point value 0.000000 */
-#define CS_MIDDLE_24000_B1                       -31902         /* Floating point value -0.973573 */
+#define CS_MIDDLE_24000_B1                      (-31902)        /* Floating point value -0.973573 */
 #define CS_MIDDLE_24000_B2                            0         /* Floating point value 0.000000 */
 #define CS_MIDDLE_24000_SCALE                        15
 #define CS_SIDE_24000_A0                           6796         /* Floating point value 0.414770 */
-#define CS_SIDE_24000_A1                          -4705         /* Floating point value -0.287182 */
-#define CS_SIDE_24000_A2                          -2090         /* Floating point value -0.127588 */
-#define CS_SIDE_24000_B1                         -20147         /* Floating point value -1.229648 */
+#define CS_SIDE_24000_A1                         (-4705)        /* Floating point value -0.287182 */
+#define CS_SIDE_24000_A2                         (-2090)        /* Floating point value -0.127588 */
+#define CS_SIDE_24000_B1                        (-20147)        /* Floating point value -1.229648 */
 #define CS_SIDE_24000_B2                           4623         /* Floating point value 0.282177 */
 #define CS_SIDE_24000_SCALE                          14
 
 /* Stereo Enhancer coefficients for 32000Hz sample rate, scaled with 0.160322 */
 #define CS_MIDDLE_32000_A0                         7484         /* Floating point value 0.228400 */
-#define CS_MIDDLE_32000_A1                        -7380         /* Floating point value -0.225214 */
+#define CS_MIDDLE_32000_A1                       (-7380)        /* Floating point value -0.225214 */
 #define CS_MIDDLE_32000_A2                            0         /* Floating point value 0.000000 */
-#define CS_MIDDLE_32000_B1                       -32117         /* Floating point value -0.980126 */
+#define CS_MIDDLE_32000_B1                      (-32117)        /* Floating point value -0.980126 */
 #define CS_MIDDLE_32000_B2                            0         /* Floating point value 0.000000 */
 #define CS_MIDDLE_32000_SCALE                        15
 #define CS_SIDE_32000_A0                           5973         /* Floating point value 0.364579 */
-#define CS_SIDE_32000_A1                          -3397         /* Floating point value -0.207355 */
-#define CS_SIDE_32000_A2                          -2576         /* Floating point value -0.157224 */
-#define CS_SIDE_32000_B1                         -20877         /* Floating point value -1.274231 */
+#define CS_SIDE_32000_A1                         (-3397)        /* Floating point value -0.207355 */
+#define CS_SIDE_32000_A2                         (-2576)        /* Floating point value -0.157224 */
+#define CS_SIDE_32000_B1                        (-20877)        /* Floating point value -1.274231 */
 #define CS_SIDE_32000_B2                           5120         /* Floating point value 0.312495 */
 #define CS_SIDE_32000_SCALE                          14
 
 /* Stereo Enhancer coefficients for 44100Hz sample rate, scaled with 0.163834 */
 #define CS_MIDDLE_44100_A0                         7654         /* Floating point value 0.233593 */
-#define CS_MIDDLE_44100_A1                        -7577         /* Floating point value -0.231225 */
+#define CS_MIDDLE_44100_A1                       (-7577)        /* Floating point value -0.231225 */
 #define CS_MIDDLE_44100_A2                            0         /* Floating point value 0.000000 */
-#define CS_MIDDLE_44100_B1                       -32294         /* Floating point value -0.985545 */
+#define CS_MIDDLE_44100_B1                      (-32294)        /* Floating point value -0.985545 */
 #define CS_MIDDLE_44100_B2                            0         /* Floating point value 0.000000 */
 #define CS_MIDDLE_44100_SCALE                        15
 #define CS_SIDE_44100_A0                           4662         /* Floating point value 0.284573 */
-#define CS_SIDE_44100_A1                          -4242         /* Floating point value -0.258910 */
-#define CS_SIDE_44100_A2                           -420         /* Floating point value -0.025662 */
-#define CS_SIDE_44100_B1                         -25760         /* Floating point value -1.572248 */
+#define CS_SIDE_44100_A1                         (-4242)        /* Floating point value -0.258910 */
+#define CS_SIDE_44100_A2                          (-420)        /* Floating point value -0.025662 */
+#define CS_SIDE_44100_B1                        (-25760)        /* Floating point value -1.572248 */
 #define CS_SIDE_44100_B2                           9640         /* Floating point value 0.588399 */
 #define CS_SIDE_44100_SCALE                          14
 
 /* Stereo Enhancer coefficients for 48000Hz sample rate, scaled with 0.164402 */
 #define CS_MIDDLE_48000_A0                         7682         /* Floating point value 0.234445 */
-#define CS_MIDDLE_48000_A1                        -7611         /* Floating point value -0.232261 */
+#define CS_MIDDLE_48000_A1                       (-7611)        /* Floating point value -0.232261 */
 #define CS_MIDDLE_48000_A2                            0         /* Floating point value 0.000000 */
-#define CS_MIDDLE_48000_B1                       -32333         /* Floating point value -0.986713 */
+#define CS_MIDDLE_48000_B1                      (-32333)        /* Floating point value -0.986713 */
 #define CS_MIDDLE_48000_B2                            0         /* Floating point value 0.000000 */
 #define CS_MIDDLE_48000_SCALE                        15
 #define CS_SIDE_48000_A0                           4466         /* Floating point value 0.272606 */
-#define CS_SIDE_48000_A1                          -4374         /* Floating point value -0.266952 */
-#define CS_SIDE_48000_A2                            -93         /* Floating point value -0.005654 */
-#define CS_SIDE_48000_B1                         -26495         /* Floating point value -1.617141 */
+#define CS_SIDE_48000_A1                         (-4374)        /* Floating point value -0.266952 */
+#define CS_SIDE_48000_A2                           (-93)        /* Floating point value -0.005654 */
+#define CS_SIDE_48000_B1                        (-26495)        /* Floating point value -1.617141 */
 #define CS_SIDE_48000_B2                          10329         /* Floating point value 0.630405 */
 #define CS_SIDE_48000_SCALE                          14
 
@@ -171,73 +171,73 @@
 
 /* Reverb coefficients for 8000 Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_8000_A0                         21865         /* Floating point value 0.667271 */
-#define CS_REVERB_8000_A1                        -21865         /* Floating point value -0.667271 */
+#define CS_REVERB_8000_A1                       (-21865)        /* Floating point value -0.667271 */
 #define CS_REVERB_8000_A2                             0         /* Floating point value 0.000000 */
-#define CS_REVERB_8000_B1                        -21895         /* Floating point value -0.668179 */
+#define CS_REVERB_8000_B1                       (-21895)        /* Floating point value -0.668179 */
 #define CS_REVERB_8000_B2                             0         /* Floating point value 0.000000 */
 #define CS_REVERB_8000_SCALE                         15
 
 /* Reverb coefficients for 11025Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_11025_A0                        22926         /* Floating point value 0.699638 */
-#define CS_REVERB_11025_A1                       -22926         /* Floating point value -0.699638 */
+#define CS_REVERB_11025_A1                      (-22926)        /* Floating point value -0.699638 */
 #define CS_REVERB_11025_A2                            0         /* Floating point value 0.000000 */
-#define CS_REVERB_11025_B1                       -24546         /* Floating point value -0.749096 */
+#define CS_REVERB_11025_B1                      (-24546)        /* Floating point value -0.749096 */
 #define CS_REVERB_11025_B2                            0         /* Floating point value 0.000000 */
 #define CS_REVERB_11025_SCALE                        15
 
 /* Reverb coefficients for 12000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_12000_A0                        23165         /* Floating point value 0.706931 */
-#define CS_REVERB_12000_A1                       -23165         /* Floating point value -0.706931 */
+#define CS_REVERB_12000_A1                      (-23165)        /* Floating point value -0.706931 */
 #define CS_REVERB_12000_A2                            0         /* Floating point value 0.000000 */
-#define CS_REVERB_12000_B1                       -25144         /* Floating point value -0.767327 */
+#define CS_REVERB_12000_B1                      (-25144)        /* Floating point value -0.767327 */
 #define CS_REVERB_12000_B2                            0         /* Floating point value 0.000000 */
 #define CS_REVERB_12000_SCALE                        15
 
 /* Reverb coefficients for 16000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_16000_A0                        23864         /* Floating point value 0.728272 */
-#define CS_REVERB_16000_A1                       -23864         /* Floating point value -0.728272 */
+#define CS_REVERB_16000_A1                      (-23864)        /* Floating point value -0.728272 */
 #define CS_REVERB_16000_A2                            0         /* Floating point value 0.000000 */
-#define CS_REVERB_16000_B1                       -26892         /* Floating point value -0.820679 */
+#define CS_REVERB_16000_B1                      (-26892)        /* Floating point value -0.820679 */
 #define CS_REVERB_16000_B2                            0         /* Floating point value 0.000000 */
 #define CS_REVERB_16000_SCALE                        15
 
 /* Reverb coefficients for 22050Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_22050_A0                        16921         /* Floating point value 0.516396 */
 #define CS_REVERB_22050_A1                            0         /* Floating point value 0.000000 */
-#define CS_REVERB_22050_A2                       -16921         /* Floating point value -0.516396 */
-#define CS_REVERB_22050_B1                       -16991         /* Floating point value -0.518512 */
-#define CS_REVERB_22050_B2                        -9535         /* Floating point value -0.290990 */
+#define CS_REVERB_22050_A2                      (-16921)        /* Floating point value -0.516396 */
+#define CS_REVERB_22050_B1                      (-16991)        /* Floating point value -0.518512 */
+#define CS_REVERB_22050_B2                       (-9535)        /* Floating point value -0.290990 */
 #define CS_REVERB_22050_SCALE                        15
 
 /* Reverb coefficients for 24000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_24000_A0                        15714         /* Floating point value 0.479565 */
 #define CS_REVERB_24000_A1                            0         /* Floating point value 0.000000 */
-#define CS_REVERB_24000_A2                       -15714         /* Floating point value -0.479565 */
-#define CS_REVERB_24000_B1                       -20898         /* Floating point value -0.637745 */
-#define CS_REVERB_24000_B2                        -6518         /* Floating point value -0.198912 */
+#define CS_REVERB_24000_A2                      (-15714)        /* Floating point value -0.479565 */
+#define CS_REVERB_24000_B1                      (-20898)        /* Floating point value -0.637745 */
+#define CS_REVERB_24000_B2                       (-6518)        /* Floating point value -0.198912 */
 #define CS_REVERB_24000_SCALE                        15
 
 /* Reverb coefficients for 32000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_32000_A0                        12463         /* Floating point value 0.380349 */
 #define CS_REVERB_32000_A1                            0         /* Floating point value 0.000000 */
-#define CS_REVERB_32000_A2                       -12463         /* Floating point value -0.380349 */
-#define CS_REVERB_32000_B1                       -31158         /* Floating point value -0.950873 */
+#define CS_REVERB_32000_A2                      (-12463)        /* Floating point value -0.380349 */
+#define CS_REVERB_32000_B1                      (-31158)        /* Floating point value -0.950873 */
 #define CS_REVERB_32000_B2                         1610         /* Floating point value 0.049127 */
 #define CS_REVERB_32000_SCALE                        15
 
 /* Reverb coefficients for 44100Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_44100_A0                         4872         /* Floating point value 0.297389 */
 #define CS_REVERB_44100_A1                            0         /* Floating point value 0.000000 */
-#define CS_REVERB_44100_A2                        -4872         /* Floating point value -0.297389 */
-#define CS_REVERB_44100_B1                       -19668         /* Floating point value -1.200423 */
+#define CS_REVERB_44100_A2                       (-4872)        /* Floating point value -0.297389 */
+#define CS_REVERB_44100_B1                      (-19668)        /* Floating point value -1.200423 */
 #define CS_REVERB_44100_B2                         4203         /* Floating point value 0.256529 */
 #define CS_REVERB_44100_SCALE                        14
 
 /* Reverb coefficients for 48000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_48000_A0                         4566         /* Floating point value 0.278661 */
 #define CS_REVERB_48000_A1                            0         /* Floating point value 0.000000 */
-#define CS_REVERB_48000_A2                        -4566         /* Floating point value -0.278661 */
-#define CS_REVERB_48000_B1                       -20562         /* Floating point value -1.254993 */
+#define CS_REVERB_48000_A2                       (-4566)        /* Floating point value -0.278661 */
+#define CS_REVERB_48000_B1                      (-20562)        /* Floating point value -1.254993 */
 #define CS_REVERB_48000_B2                         4970         /* Floating point value 0.303347 */
 #define CS_REVERB_48000_SCALE                        14
 
@@ -257,128 +257,128 @@
 
 /* Equaliser coefficients for 8000 Hz sample rate, CS scaled with 1.038497 and CSEX scaled with 0.775480 */
 #define CS_EQUALISER_8000_A0                      20698         /* Floating point value 1.263312 */
-#define CS_EQUALISER_8000_A1                      -9859         /* Floating point value -0.601748 */
-#define CS_EQUALISER_8000_A2                      -4599         /* Floating point value -0.280681 */
-#define CS_EQUALISER_8000_B1                      -7797         /* Floating point value -0.475865 */
-#define CS_EQUALISER_8000_B2                      -6687         /* Floating point value -0.408154 */
+#define CS_EQUALISER_8000_A1                     (-9859)        /* Floating point value -0.601748 */
+#define CS_EQUALISER_8000_A2                     (-4599)        /* Floating point value -0.280681 */
+#define CS_EQUALISER_8000_B1                     (-7797)        /* Floating point value -0.475865 */
+#define CS_EQUALISER_8000_B2                     (-6687)        /* Floating point value -0.408154 */
 #define CS_EQUALISER_8000_SCALE                      14
 #define CSEX_EQUALISER_8000_A0                    30912         /* Floating point value 0.943357 */
-#define CSEX_EQUALISER_8000_A1                   -14724         /* Floating point value -0.449345 */
-#define CSEX_EQUALISER_8000_A2                    -6868         /* Floating point value -0.209594 */
-#define CSEX_EQUALISER_8000_B1                   -15593         /* Floating point value -0.475865 */
-#define CSEX_EQUALISER_8000_B2                   -13374         /* Floating point value -0.408154 */
+#define CSEX_EQUALISER_8000_A1                  (-14724)        /* Floating point value -0.449345 */
+#define CSEX_EQUALISER_8000_A2                   (-6868)        /* Floating point value -0.209594 */
+#define CSEX_EQUALISER_8000_B1                  (-15593)        /* Floating point value -0.475865 */
+#define CSEX_EQUALISER_8000_B2                  (-13374)        /* Floating point value -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                     18041         /* Floating point value 1.101145 */
 #define CS_EQUALISER_11025_A1                      2278         /* Floating point value 0.139020 */
-#define CS_EQUALISER_11025_A2                    -14163         /* Floating point value -0.864423 */
+#define CS_EQUALISER_11025_A2                   (-14163)        /* Floating point value -0.864423 */
 #define CS_EQUALISER_11025_B1                       402         /* Floating point value 0.024541 */
-#define CS_EQUALISER_11025_B2                    -14892         /* Floating point value -0.908930 */
+#define CS_EQUALISER_11025_B2                   (-14892)        /* Floating point value -0.908930 */
 #define CS_EQUALISER_11025_SCALE                     14
 #define CSEX_EQUALISER_11025_A0                   31983         /* Floating point value 0.976058 */
-#define CSEX_EQUALISER_11025_A1                  -22784         /* Floating point value -0.695326 */
-#define CSEX_EQUALISER_11025_A2                   -2976         /* Floating point value -0.090809 */
-#define CSEX_EQUALISER_11025_B1                  -20008         /* Floating point value -0.610594 */
-#define CSEX_EQUALISER_11025_B2                  -10196         /* Floating point value -0.311149 */
+#define CSEX_EQUALISER_11025_A1                 (-22784)        /* Floating point value -0.695326 */
+#define CSEX_EQUALISER_11025_A2                  (-2976)        /* Floating point value -0.090809 */
+#define CSEX_EQUALISER_11025_B1                 (-20008)        /* Floating point value -0.610594 */
+#define CSEX_EQUALISER_11025_B2                 (-10196)        /* Floating point value -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                     20917         /* Floating point value 1.276661 */
-#define CS_EQUALISER_12000_A1                    -16671         /* Floating point value -1.017519 */
-#define CS_EQUALISER_12000_A2                      -723         /* Floating point value -0.044128 */
-#define CS_EQUALISER_12000_B1                    -11954         /* Floating point value -0.729616 */
-#define CS_EQUALISER_12000_B2                     -3351         /* Floating point value -0.204532 */
+#define CS_EQUALISER_12000_A1                   (-16671)        /* Floating point value -1.017519 */
+#define CS_EQUALISER_12000_A2                     (-723)        /* Floating point value -0.044128 */
+#define CS_EQUALISER_12000_B1                   (-11954)        /* Floating point value -0.729616 */
+#define CS_EQUALISER_12000_B2                    (-3351)        /* Floating point value -0.204532 */
 #define CS_EQUALISER_12000_SCALE                     14
 #define CSEX_EQUALISER_12000_A0                   16500         /* Floating point value 1.007095 */
-#define CSEX_EQUALISER_12000_A1                  -14285         /* Floating point value -0.871912 */
+#define CSEX_EQUALISER_12000_A1                 (-14285)        /* Floating point value -0.871912 */
 #define CSEX_EQUALISER_12000_A2                     381         /* Floating point value 0.023232 */
-#define CSEX_EQUALISER_12000_B1                  -12220         /* Floating point value -0.745857 */
-#define CSEX_EQUALISER_12000_B2                   -3099         /* Floating point value -0.189171 */
+#define CSEX_EQUALISER_12000_B1                 (-12220)        /* Floating point value -0.745857 */
+#define CSEX_EQUALISER_12000_B2                  (-3099)        /* Floating point value -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                     20998         /* Floating point value 1.281629 */
-#define CS_EQUALISER_16000_A1                    -17627         /* Floating point value -1.075872 */
-#define CS_EQUALISER_16000_A2                      -678         /* Floating point value -0.041365 */
-#define CS_EQUALISER_16000_B1                    -11882         /* Floating point value -0.725239 */
-#define CS_EQUALISER_16000_B2                     -3676         /* Floating point value -0.224358 */
+#define CS_EQUALISER_16000_A1                   (-17627)        /* Floating point value -1.075872 */
+#define CS_EQUALISER_16000_A2                     (-678)        /* Floating point value -0.041365 */
+#define CS_EQUALISER_16000_B1                   (-11882)        /* Floating point value -0.725239 */
+#define CS_EQUALISER_16000_B2                    (-3676)        /* Floating point value -0.224358 */
 #define CS_EQUALISER_16000_SCALE                     14
 #define CSEX_EQUALISER_16000_A0                   17713         /* Floating point value 1.081091 */
-#define CSEX_EQUALISER_16000_A1                  -14208         /* Floating point value -0.867183 */
-#define CSEX_EQUALISER_16000_A2                   -1151         /* Floating point value -0.070247 */
-#define CSEX_EQUALISER_16000_B1                   -8440         /* Floating point value -0.515121 */
-#define CSEX_EQUALISER_16000_B2                   -6978         /* Floating point value -0.425893 */
+#define CSEX_EQUALISER_16000_A1                 (-14208)        /* Floating point value -0.867183 */
+#define CSEX_EQUALISER_16000_A2                  (-1151)        /* Floating point value -0.070247 */
+#define CSEX_EQUALISER_16000_B1                  (-8440)        /* Floating point value -0.515121 */
+#define CSEX_EQUALISER_16000_B2                  (-6978)        /* Floating point value -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                     22751         /* Floating point value 1.388605 */
-#define CS_EQUALISER_22050_A1                    -21394         /* Floating point value -1.305799 */
+#define CS_EQUALISER_22050_A1                   (-21394)        /* Floating point value -1.305799 */
 #define CS_EQUALISER_22050_A2                       654         /* Floating point value 0.039922 */
-#define CS_EQUALISER_22050_B1                    -11788         /* Floating point value -0.719494 */
-#define CS_EQUALISER_22050_B2                     -3985         /* Floating point value -0.243245 */
+#define CS_EQUALISER_22050_B1                   (-11788)        /* Floating point value -0.719494 */
+#define CS_EQUALISER_22050_B2                    (-3985)        /* Floating point value -0.243245 */
 #define CS_EQUALISER_22050_SCALE                     14
 #define CSEX_EQUALISER_22050_A0                   20855         /* Floating point value 1.272910 */
-#define CSEX_EQUALISER_22050_A1                  -21971         /* Floating point value -1.341014 */
+#define CSEX_EQUALISER_22050_A1                 (-21971)        /* Floating point value -1.341014 */
 #define CSEX_EQUALISER_22050_A2                    2744         /* Floating point value 0.167462 */
-#define CSEX_EQUALISER_22050_B1                  -10063         /* Floating point value -0.614219 */
-#define CSEX_EQUALISER_22050_B2                   -5659         /* Floating point value -0.345384 */
+#define CSEX_EQUALISER_22050_B1                 (-10063)        /* Floating point value -0.614219 */
+#define CSEX_EQUALISER_22050_B2                  (-5659)        /* Floating point value -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                     23099         /* Floating point value 1.409832 */
-#define CS_EQUALISER_24000_A1                    -23863         /* Floating point value -1.456506 */
+#define CS_EQUALISER_24000_A1                   (-23863)        /* Floating point value -1.456506 */
 #define CS_EQUALISER_24000_A2                      2481         /* Floating point value 0.151410 */
-#define CS_EQUALISER_24000_B1                    -13176         /* Floating point value -0.804201 */
-#define CS_EQUALISER_24000_B2                     -2683         /* Floating point value -0.163783 */
+#define CS_EQUALISER_24000_B1                   (-13176)        /* Floating point value -0.804201 */
+#define CS_EQUALISER_24000_B2                    (-2683)        /* Floating point value -0.163783 */
 #define CS_EQUALISER_24000_SCALE                     14
 #define CSEX_EQUALISER_24000_A0                   21286         /* Floating point value 1.299198 */
-#define CSEX_EQUALISER_24000_A1                  -23797         /* Floating point value -1.452447 */
+#define CSEX_EQUALISER_24000_A1                 (-23797)        /* Floating point value -1.452447 */
 #define CSEX_EQUALISER_24000_A2                    3940         /* Floating point value 0.240489 */
-#define CSEX_EQUALISER_24000_B1                  -10966         /* Floating point value -0.669303 */
-#define CSEX_EQUALISER_24000_B2                   -4833         /* Floating point value -0.294984 */
+#define CSEX_EQUALISER_24000_B1                 (-10966)        /* Floating point value -0.669303 */
+#define CSEX_EQUALISER_24000_B2                  (-4833)        /* Floating point value -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                     25575         /* Floating point value 1.560988 */
-#define CS_EQUALISER_32000_A1                    -30765         /* Floating point value -1.877724 */
+#define CS_EQUALISER_32000_A1                   (-30765)        /* Floating point value -1.877724 */
 #define CS_EQUALISER_32000_A2                      6386         /* Floating point value 0.389741 */
-#define CS_EQUALISER_32000_B1                    -14867         /* Floating point value -0.907410 */
-#define CS_EQUALISER_32000_B2                     -1155         /* Floating point value -0.070489 */
+#define CS_EQUALISER_32000_B1                   (-14867)        /* Floating point value -0.907410 */
+#define CS_EQUALISER_32000_B2                    (-1155)        /* Floating point value -0.070489 */
 #define CS_EQUALISER_32000_SCALE                     14
 #define CSEX_EQUALISER_32000_A0                   14623         /* Floating point value 1.785049 */
-#define CSEX_EQUALISER_32000_A1                  -18297         /* Floating point value -2.233497 */
+#define CSEX_EQUALISER_32000_A1                 (-18297)        /* Floating point value -2.233497 */
 #define CSEX_EQUALISER_32000_A2                    4313         /* Floating point value 0.526431 */
-#define CSEX_EQUALISER_32000_B1                   -3653         /* Floating point value -0.445939 */
-#define CSEX_EQUALISER_32000_B2                   -4280         /* Floating point value -0.522446 */
+#define CSEX_EQUALISER_32000_B1                  (-3653)        /* Floating point value -0.445939 */
+#define CSEX_EQUALISER_32000_B2                  (-4280)        /* Floating point value -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                     13304         /* Floating point value 1.623993 */
-#define CS_EQUALISER_44100_A1                    -18602         /* Floating point value -2.270743 */
+#define CS_EQUALISER_44100_A1                   (-18602)        /* Floating point value -2.270743 */
 #define CS_EQUALISER_44100_A2                      5643         /* Floating point value 0.688829 */
-#define CS_EQUALISER_44100_B1                     -9152         /* Floating point value -1.117190 */
+#define CS_EQUALISER_44100_B1                    (-9152)        /* Floating point value -1.117190 */
 #define CS_EQUALISER_44100_B2                      1067         /* Floating point value 0.130208 */
 #define CS_EQUALISER_44100_SCALE                     13
 #define CSEX_EQUALISER_44100_A0                   16616         /* Floating point value 2.028315 */
-#define CSEX_EQUALISER_44100_A1                  -23613         /* Floating point value -2.882459 */
+#define CSEX_EQUALISER_44100_A1                 (-23613)        /* Floating point value -2.882459 */
 #define CSEX_EQUALISER_44100_A2                    7410         /* Floating point value 0.904535 */
-#define CSEX_EQUALISER_44100_B1                   -4860         /* Floating point value -0.593308 */
-#define CSEX_EQUALISER_44100_B2                   -3161         /* Floating point value -0.385816 */
+#define CSEX_EQUALISER_44100_B1                  (-4860)        /* Floating point value -0.593308 */
+#define CSEX_EQUALISER_44100_B2                  (-3161)        /* Floating point value -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                     13445         /* Floating point value 1.641177 */
-#define CS_EQUALISER_48000_A1                    -19372         /* Floating point value -2.364687 */
+#define CS_EQUALISER_48000_A1                   (-19372)        /* Floating point value -2.364687 */
 #define CS_EQUALISER_48000_A2                      6225         /* Floating point value 0.759910 */
-#define CS_EQUALISER_48000_B1                     -9558         /* Floating point value -1.166774 */
+#define CS_EQUALISER_48000_B1                    (-9558)        /* Floating point value -1.166774 */
 #define CS_EQUALISER_48000_B2                      1459         /* Floating point value 0.178074 */
 #define CS_EQUALISER_48000_SCALE                     13
 #define CSEX_EQUALISER_48000_A0                   17200         /* Floating point value 2.099655 */
-#define CSEX_EQUALISER_48000_A1                  -25110         /* Floating point value -3.065220 */
+#define CSEX_EQUALISER_48000_A1                 (-25110)        /* Floating point value -3.065220 */
 #define CSEX_EQUALISER_48000_A2                    8277         /* Floating point value 1.010417 */
-#define CSEX_EQUALISER_48000_B1                   -5194         /* Floating point value -0.634021 */
-#define CSEX_EQUALISER_48000_B2                   -2845         /* Floating point value -0.347332 */
+#define CSEX_EQUALISER_48000_B1                  (-5194)        /* Floating point value -0.634021 */
+#define CSEX_EQUALISER_48000_B2                  (-2845)        /* Floating point value -0.347332 */
 #define CSEX_EQUALISER_48000_SCALE                   13
 
 
diff --git a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
index af904a6..f6a61d8 100644
--- a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
+++ b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
@@ -16,7 +16,7 @@
  */
 
 #define LOG_TAG "Bundle"
-#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
+#define ARRAY_SIZE(array) (sizeof (array) / sizeof (array)[0])
 //#define LOG_NDEBUG 0
 
 #include <assert.h>
@@ -34,19 +34,19 @@
 extern "C" const struct effect_interface_s gLvmEffectInterface;
 
 #define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc){\
-        if (LvmStatus == LVM_NULLADDRESS){\
+        if ((LvmStatus) == LVM_NULLADDRESS){\
             ALOGV("\tLVM_ERROR : Parameter error - "\
                     "null pointer returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
         }\
-        if (LvmStatus == LVM_ALIGNMENTERROR){\
+        if ((LvmStatus) == LVM_ALIGNMENTERROR){\
             ALOGV("\tLVM_ERROR : Parameter error - "\
                     "bad alignment returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
         }\
-        if (LvmStatus == LVM_INVALIDNUMSAMPLES){\
+        if ((LvmStatus) == LVM_INVALIDNUMSAMPLES){\
             ALOGV("\tLVM_ERROR : Parameter error - "\
                     "bad number of samples returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
         }\
-        if (LvmStatus == LVM_OUTOFRANGE){\
+        if ((LvmStatus) == LVM_OUTOFRANGE){\
             ALOGV("\tLVM_ERROR : Parameter error - "\
                     "out of range returned by %s in %s\n", callingFunc, calledFunc);\
         }\
@@ -3091,7 +3091,10 @@
             //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_GET_PARAM start");
 
             effect_param_t *p = (effect_param_t *)pCmdData;
-
+            if (SIZE_MAX - sizeof(effect_param_t) < (size_t)p->psize) {
+                android_errorWriteLog(0x534e4554, "26347509");
+                return -EINVAL;
+            }
             if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
                     cmdSize < (sizeof(effect_param_t) + p->psize) ||
                     pReplyData == NULL || replySize == NULL ||
diff --git a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
index a48a4e3..f7dcdda 100644
--- a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
+++ b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
@@ -16,7 +16,7 @@
  */
 
 #define LOG_TAG "Reverb"
-#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
+#define ARRAY_SIZE(array) (sizeof (array) / sizeof (array)[0])
 //#define LOG_NDEBUG 0
 
 #include <assert.h>
@@ -34,15 +34,15 @@
 extern "C" const struct effect_interface_s gReverbInterface;
 
 #define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc){\
-        if (LvmStatus == LVREV_NULLADDRESS){\
+        if ((LvmStatus) == LVREV_NULLADDRESS){\
             ALOGV("\tLVREV_ERROR : Parameter error - "\
                     "null pointer returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
         }\
-        if (LvmStatus == LVREV_INVALIDNUMSAMPLES){\
+        if ((LvmStatus) == LVREV_INVALIDNUMSAMPLES){\
             ALOGV("\tLVREV_ERROR : Parameter error - "\
                     "bad number of samples returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
         }\
-        if (LvmStatus == LVREV_OUTOFRANGE){\
+        if ((LvmStatus) == LVREV_OUTOFRANGE){\
             ALOGV("\tLVREV_ERROR : Parameter error - "\
                     "out of range returned by %s in %s\n", callingFunc, calledFunc);\
         }\
@@ -1956,7 +1956,10 @@
             //ALOGV("\tReverb_command cmdCode Case: "
             //        "EFFECT_CMD_GET_PARAM start");
             effect_param_t *p = (effect_param_t *)pCmdData;
-
+            if (SIZE_MAX - sizeof(effect_param_t) < (size_t)p->psize) {
+                android_errorWriteLog(0x534e4554, "26347509");
+                return -EINVAL;
+            }
             if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
                     cmdSize < (sizeof(effect_param_t) + p->psize) ||
                     pReplyData == NULL || replySize == NULL ||
diff --git a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h
index 7c15b18..8165f5a 100644
--- a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h
+++ b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h
@@ -30,7 +30,7 @@
 #define LVREV_MAX_REVERB_LEVEL  2000
 #define LVREV_MAX_FRAME_SIZE    2560
 #define LVREV_CUP_LOAD_ARM9E    470    // Expressed in 0.1 MIPS
-#define LVREV_MEM_USAGE         71+(LVREV_MAX_FRAME_SIZE>>7)     // Expressed in kB
+#define LVREV_MEM_USAGE         (71+(LVREV_MAX_FRAME_SIZE>>7))     // Expressed in kB
 //#define LVM_PCM
 
 typedef struct _LPFPair_t
diff --git a/media/libeffects/preprocessing/Android.mk b/media/libeffects/preprocessing/Android.mk
index 0022fd9..4e4b094 100644
--- a/media/libeffects/preprocessing/Android.mk
+++ b/media/libeffects/preprocessing/Android.mk
@@ -11,9 +11,9 @@
     PreProcessing.cpp
 
 LOCAL_C_INCLUDES += \
-    external/webrtc/src \
-    external/webrtc/src/modules/interface \
-    external/webrtc/src/modules/audio_processing/include \
+    external/webrtc \
+    external/webrtc/webrtc/modules/include \
+    external/webrtc/webrtc/modules/audio_processing/include \
     $(call include-path-for, audio-effects)
 
 LOCAL_C_INCLUDES += $(call include-path-for, speex)
@@ -25,6 +25,10 @@
     liblog
 
 LOCAL_SHARED_LIBRARIES += libdl
+
+LOCAL_CFLAGS += \
+    -DWEBRTC_POSIX
+
 LOCAL_CFLAGS += -fvisibility=hidden
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libeffects/preprocessing/PreProcessing.cpp b/media/libeffects/preprocessing/PreProcessing.cpp
index 7ed107a..0b4ab3d 100644
--- a/media/libeffects/preprocessing/PreProcessing.cpp
+++ b/media/libeffects/preprocessing/PreProcessing.cpp
@@ -89,6 +89,7 @@
     preproc_session_t *session;     // session the effect is on
     const preproc_ops_t *ops;       // effect ops table
     preproc_fx_handle_t engine;     // handle on webRTC engine
+    uint32_t type;                  // subtype of effect
 #ifdef DUAL_MIC_TEST
     bool aux_channels_on;           // support auxiliary channels
     size_t cur_channel_config;      // current auciliary channel configuration
@@ -559,6 +560,21 @@
     ALOGV("NsInit");
     webrtc::NoiseSuppression *ns = static_cast<webrtc::NoiseSuppression *>(effect->engine);
     ns->set_level(kNsDefaultLevel);
+    webrtc::Config config;
+    std::vector<webrtc::Point> geometry;
+    // TODO(aluebs): Make the geometry settable.
+    geometry.push_back(webrtc::Point(-0.03f, 0.f, 0.f));
+    geometry.push_back(webrtc::Point(-0.01f, 0.f, 0.f));
+    geometry.push_back(webrtc::Point(0.01f, 0.f, 0.f));
+    geometry.push_back(webrtc::Point(0.03f, 0.f, 0.f));
+    // The geometry needs to be set with Beamforming enabled.
+    config.Set<webrtc::Beamforming>(
+            new webrtc::Beamforming(true, geometry));
+    effect->session->apm->SetExtraOptions(config);
+    config.Set<webrtc::Beamforming>(
+            new webrtc::Beamforming(false, geometry));
+    effect->session->apm->SetExtraOptions(config);
+    effect->type = NS_TYPE_SINGLE_CHANNEL;
     return 0;
 }
 
@@ -584,11 +600,35 @@
     return status;
 }
 
-int NsSetParameter (preproc_effect_t *effect __unused,
-                    void *pParam __unused,
-                    void *pValue __unused)
+int NsSetParameter (preproc_effect_t *effect, void *pParam, void *pValue)
 {
     int status = 0;
+    webrtc::NoiseSuppression *ns = static_cast<webrtc::NoiseSuppression *>(effect->engine);
+    uint32_t param = *(uint32_t *)pParam;
+    uint32_t value = *(uint32_t *)pValue;
+    switch(param) {
+        case NS_PARAM_LEVEL:
+            ns->set_level((webrtc::NoiseSuppression::Level)value);
+            ALOGV("NsSetParameter() level %d", value);
+            break;
+        case NS_PARAM_TYPE:
+        {
+            webrtc::Config config;
+            std::vector<webrtc::Point> geometry;
+            bool is_beamforming_enabled =
+                    value == NS_TYPE_MULTI_CHANNEL && ns->is_enabled();
+            config.Set<webrtc::Beamforming>(
+                    new webrtc::Beamforming(is_beamforming_enabled, geometry));
+            effect->session->apm->SetExtraOptions(config);
+            effect->type = value;
+            ALOGV("NsSetParameter() type %d", value);
+            break;
+        }
+        default:
+            ALOGW("NsSetParameter() unknown param %08x value %08x", param, value);
+            status = -EINVAL;
+    }
+
     return status;
 }
 
@@ -597,6 +637,12 @@
     webrtc::NoiseSuppression *ns = static_cast<webrtc::NoiseSuppression *>(effect->engine);
     ALOGV("NsEnable ns %p", ns);
     ns->Enable(true);
+    if (effect->type == NS_TYPE_MULTI_CHANNEL) {
+        webrtc::Config config;
+        std::vector<webrtc::Point> geometry;
+        config.Set<webrtc::Beamforming>(new webrtc::Beamforming(true, geometry));
+        effect->session->apm->SetExtraOptions(config);
+    }
 }
 
 void NsDisable(preproc_effect_t *effect)
@@ -604,6 +650,10 @@
     ALOGV("NsDisable");
     webrtc::NoiseSuppression *ns = static_cast<webrtc::NoiseSuppression *>(effect->engine);
     ns->Enable(false);
+    webrtc::Config config;
+    std::vector<webrtc::Point> geometry;
+    config.Set<webrtc::Beamforming>(new webrtc::Beamforming(false, geometry));
+    effect->session->apm->SetExtraOptions(config);
 }
 
 static const preproc_ops_t sNsOps = {
@@ -777,14 +827,17 @@
     ALOGV("Session_CreateEffect procId %d, createdMsk %08x", procId, session->createdMsk);
 
     if (session->createdMsk == 0) {
-        session->apm = webrtc::AudioProcessing::Create(session->io);
+        session->apm = webrtc::AudioProcessing::Create();
         if (session->apm == NULL) {
             ALOGW("Session_CreateEffect could not get apm engine");
             goto error;
         }
-        session->apm->set_sample_rate_hz(kPreprocDefaultSr);
-        session->apm->set_num_channels(kPreProcDefaultCnl, kPreProcDefaultCnl);
-        session->apm->set_num_reverse_channels(kPreProcDefaultCnl);
+        const webrtc::ProcessingConfig processing_config = {
+            {{kPreprocDefaultSr, kPreProcDefaultCnl},
+             {kPreprocDefaultSr, kPreProcDefaultCnl},
+             {kPreprocDefaultSr, kPreProcDefaultCnl},
+             {kPreprocDefaultSr, kPreProcDefaultCnl}}};
+        session->apm->Initialize(processing_config);
         session->procFrame = new webrtc::AudioFrame();
         if (session->procFrame == NULL) {
             ALOGW("Session_CreateEffect could not allocate audio frame");
@@ -834,7 +887,7 @@
         session->revFrame = NULL;
         delete session->procFrame;
         session->procFrame = NULL;
-        webrtc::AudioProcessing::Destroy(session->apm);
+        delete session->apm;
         session->apm = NULL;
     }
     return status;
@@ -846,7 +899,7 @@
     ALOGW_IF(Effect_Release(fx) != 0, " Effect_Release() failed for proc ID %d", fx->procId);
     session->createdMsk &= ~(1<<fx->procId);
     if (session->createdMsk == 0) {
-        webrtc::AudioProcessing::Destroy(session->apm);
+        delete session->apm;
         session->apm = NULL;
         delete session->procFrame;
         session->procFrame = NULL;
@@ -881,8 +934,8 @@
 int Session_SetConfig(preproc_session_t *session, effect_config_t *config)
 {
     uint32_t sr;
-    uint32_t inCnl = audio_channel_count_from_out_mask(config->inputCfg.channels);
-    uint32_t outCnl = audio_channel_count_from_out_mask(config->outputCfg.channels);
+    uint32_t inCnl = audio_channel_count_from_in_mask(config->inputCfg.channels);
+    uint32_t outCnl = audio_channel_count_from_in_mask(config->outputCfg.channels);
 
     if (config->inputCfg.samplingRate != config->outputCfg.samplingRate ||
         config->inputCfg.format != config->outputCfg.format ||
@@ -894,17 +947,6 @@
          config->inputCfg.samplingRate, config->inputCfg.channels);
     int status;
 
-    // if at least one process is enabled, do not accept configuration changes
-    if (session->enabledMsk) {
-        if (session->samplingRate != config->inputCfg.samplingRate ||
-                session->inChannelCount != inCnl ||
-                session->outChannelCount != outCnl) {
-            return -ENOSYS;
-        } else {
-            return 0;
-        }
-    }
-
     // AEC implementation is limited to 16kHz
     if (config->inputCfg.samplingRate >= 32000 && !(session->createdMsk & (1 << PREPROC_AEC))) {
         session->apmSamplingRate = 32000;
@@ -914,15 +956,13 @@
     } else if (config->inputCfg.samplingRate >= 8000) {
         session->apmSamplingRate = 8000;
     }
-    status = session->apm->set_sample_rate_hz(session->apmSamplingRate);
-    if (status < 0) {
-        return -EINVAL;
-    }
-    status = session->apm->set_num_channels(inCnl, outCnl);
-    if (status < 0) {
-        return -EINVAL;
-    }
-    status = session->apm->set_num_reverse_channels(inCnl);
+
+    const webrtc::ProcessingConfig processing_config = {
+      {{static_cast<int>(session->apmSamplingRate), inCnl},
+       {static_cast<int>(session->apmSamplingRate), outCnl},
+       {static_cast<int>(session->apmSamplingRate), inCnl},
+       {static_cast<int>(session->apmSamplingRate), inCnl}}};
+    status = session->apm->Initialize(processing_config);
     if (status < 0) {
         return -EINVAL;
     }
@@ -1038,7 +1078,12 @@
         return -EINVAL;
     }
     uint32_t inCnl = audio_channel_count_from_out_mask(config->inputCfg.channels);
-    int status = session->apm->set_num_reverse_channels(inCnl);
+    const webrtc::ProcessingConfig processing_config = {
+       {{static_cast<int>(session->apmSamplingRate), session->inChannelCount},
+        {static_cast<int>(session->apmSamplingRate), session->outChannelCount},
+        {static_cast<int>(session->apmSamplingRate), inCnl},
+        {static_cast<int>(session->apmSamplingRate), inCnl}}};
+    int status = session->apm->Initialize(processing_config);
     if (status < 0) {
         return -EINVAL;
     }
@@ -1280,8 +1325,7 @@
             }
             session->framesIn = 0;
         }
-        session->procFrame->samples_per_channel_ =
-                session->apmFrameCount * session->inChannelCount;
+        session->procFrame->samples_per_channel_ = session->apmFrameCount;
 
         effect->session->apm->ProcessStream(session->procFrame);
 
@@ -1792,8 +1836,7 @@
             }
             session->framesRev = 0;
         }
-        session->revFrame->samples_per_channel_ =
-                session->apmFrameCount * session->inChannelCount;
+        session->revFrame->samples_per_channel_ = session->apmFrameCount;
         effect->session->apm->AnalyzeReverseStream(session->revFrame);
         return 0;
     } else {
diff --git a/media/libmedia/Android.mk b/media/libmedia/Android.mk
index be88aa0..6aa804f 100644
--- a/media/libmedia/Android.mk
+++ b/media/libmedia/Android.mk
@@ -74,6 +74,8 @@
         libcamera_client libstagefright_foundation \
         libgui libdl libaudioutils libnbaio
 
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libbinder
+
 LOCAL_WHOLE_STATIC_LIBRARIES := libmedia_helper
 
 LOCAL_MODULE:= libmedia
diff --git a/media/libmedia/AudioSystem.cpp b/media/libmedia/AudioSystem.cpp
index 3bfb09a..9d645f0 100644
--- a/media/libmedia/AudioSystem.cpp
+++ b/media/libmedia/AudioSystem.cpp
@@ -476,7 +476,7 @@
         switch (event) {
         case AUDIO_OUTPUT_OPENED:
         case AUDIO_INPUT_OPENED: {
-            sp<AudioIoDescriptor> oldDesc = getIoDescriptor(ioDesc->mIoHandle);
+            sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
             if (oldDesc == 0) {
                 mIoDescriptors.add(ioDesc->mIoHandle, ioDesc);
             } else {
@@ -498,7 +498,7 @@
             } break;
         case AUDIO_OUTPUT_CLOSED:
         case AUDIO_INPUT_CLOSED: {
-            if (getIoDescriptor(ioDesc->mIoHandle) == 0) {
+            if (getIoDescriptor_l(ioDesc->mIoHandle) == 0) {
                 ALOGW("ioConfigChanged() closing unknown %s %d",
                       event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->mIoHandle);
                 break;
@@ -512,7 +512,7 @@
 
         case AUDIO_OUTPUT_CONFIG_CHANGED:
         case AUDIO_INPUT_CONFIG_CHANGED: {
-            sp<AudioIoDescriptor> oldDesc = getIoDescriptor(ioDesc->mIoHandle);
+            sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
             if (oldDesc == 0) {
                 ALOGW("ioConfigChanged() modifying unknown output! %d", ioDesc->mIoHandle);
                 break;
@@ -575,7 +575,7 @@
     return NO_ERROR;
 }
 
-sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor(audio_io_handle_t ioHandle)
+sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor_l(audio_io_handle_t ioHandle)
 {
     sp<AudioIoDescriptor> desc;
     ssize_t index = mIoDescriptors.indexOfKey(ioHandle);
@@ -585,6 +585,12 @@
     return desc;
 }
 
+sp<AudioIoDescriptor> AudioSystem::AudioFlingerClient::getIoDescriptor(audio_io_handle_t ioHandle)
+{
+    Mutex::Autolock _l(mLock);
+    return getIoDescriptor_l(ioHandle);
+}
+
 status_t AudioSystem::AudioFlingerClient::addAudioDeviceCallback(
         const sp<AudioDeviceCallback>& callback, audio_io_handle_t audioIo)
 {
diff --git a/media/libmedia/AudioTrack.cpp b/media/libmedia/AudioTrack.cpp
index b049895..b999623 100644
--- a/media/libmedia/AudioTrack.cpp
+++ b/media/libmedia/AudioTrack.cpp
@@ -523,6 +523,15 @@
         mTimestampStartupGlitchReported = false;
         mRetrogradeMotionReported = false;
 
+        // If previousState == STATE_STOPPED, we reactivate markers (mMarkerPosition != 0)
+        // as the position is reset to 0. This is legacy behavior. This is not done
+        // in stop() to avoid a race condition where the last marker event is issued twice.
+        // Note: the if is technically unnecessary because previousState == STATE_FLUSHED
+        // is only for streaming tracks, and mMarkerReached is already set to false.
+        if (previousState == STATE_STOPPED) {
+            mMarkerReached = false;
+        }
+
         // For offloaded tracks, we don't know if the hardware counters are really zero here,
         // since the flush is asynchronous and stop may not fully drain.
         // We save the time when the track is started to later verify whether
@@ -592,9 +601,9 @@
 
     mProxy->interrupt();
     mAudioTrack->stop();
-    // the playback head position will reset to 0, so if a marker is set, we need
-    // to activate it again
-    mMarkerReached = false;
+
+    // Note: legacy handling - stop does not clear playback marker
+    // and periodic update counter, but flush does for streaming tracks.
 
     if (mSharedBuffer != 0) {
         // clear buffer position and loop count.
@@ -822,13 +831,13 @@
     }
 
     // Check resampler ratios are within bounds
-    if (effectiveRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
+    if ((uint64_t)effectiveRate > (uint64_t)mSampleRate * (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
         ALOGV("setPlaybackRate(%f, %f) failed. Resample rate exceeds max accepted value",
                 playbackRate.mSpeed, playbackRate.mPitch);
         return BAD_VALUE;
     }
 
-    if (effectiveRate * AUDIO_RESAMPLER_UP_RATIO_MAX < mSampleRate) {
+    if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
         ALOGV("setPlaybackRate(%f, %f) failed. Resample rate below min accepted value",
                         playbackRate.mSpeed, playbackRate.mPitch);
         return BAD_VALUE;
@@ -1843,7 +1852,11 @@
         case NO_ERROR:
         case DEAD_OBJECT:
         case TIMED_OUT:
-            mCbf(EVENT_STREAM_END, mUserData, NULL);
+            if (status != DEAD_OBJECT) {
+                // for DEAD_OBJECT, we do not send a EVENT_STREAM_END after stop();
+                // instead, the application should handle the EVENT_NEW_IAUDIOTRACK.
+                mCbf(EVENT_STREAM_END, mUserData, NULL);
+            }
             {
                 AutoMutex lock(mLock);
                 // The previously assigned value of waitStreamEnd is no longer valid,
@@ -1967,7 +1980,8 @@
         if (err != NO_ERROR) {
             if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
                     (isOffloaded() && (err == DEAD_OBJECT))) {
-                return 0;
+                // FIXME bug 25195759
+                return 1000000;
             }
             ALOGE("Error %d obtaining an audio buffer, giving up.", err);
             return NS_NEVER;
@@ -2183,6 +2197,7 @@
     return mAudioTrack->setParameters(keyValuePairs);
 }
 
+__attribute__((no_sanitize("integer")))
 status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
 {
     AutoMutex lock(mLock);
@@ -2317,7 +2332,7 @@
     // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
     if (status == NO_ERROR) {
         if (previousTimestampValid) {
-#define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * 1000000000 + time.tv_nsec)
+#define TIME_TO_NANOS(time) ((uint64_t)(time).tv_sec * 1000000000 + (time).tv_nsec)
             const uint64_t previousTimeNanos = TIME_TO_NANOS(mPreviousTimestamp.mTime);
             const uint64_t currentTimeNanos = TIME_TO_NANOS(timestamp.mTime);
 #undef TIME_TO_NANOS
diff --git a/media/libmedia/AudioTrackShared.cpp b/media/libmedia/AudioTrackShared.cpp
index 5e45c85..9d5d996 100644
--- a/media/libmedia/AudioTrackShared.cpp
+++ b/media/libmedia/AudioTrackShared.cpp
@@ -240,6 +240,7 @@
             errno = 0;
             (void) syscall(__NR_futex, &cblk->mFutex,
                     mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
+            status_t error = errno; // clock_gettime can affect errno
             // update total elapsed time spent waiting
             if (measure) {
                 struct timespec after;
@@ -257,7 +258,7 @@
                 before = after;
                 beforeIsValid = true;
             }
-            switch (errno) {
+            switch (error) {
             case 0:            // normal wakeup by server, or by binderDied()
             case EWOULDBLOCK:  // benign race condition with server
             case EINTR:        // wait was interrupted by signal or other spurious wakeup
@@ -265,7 +266,7 @@
                 // FIXME these error/non-0 status are being dropped
                 break;
             default:
-                status = errno;
+                status = error;
                 ALOGE("%s unexpected error %s", __func__, strerror(status));
                 goto end;
             }
@@ -933,7 +934,7 @@
     return (ssize_t) mState.mPosition;
 }
 
-status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush __unused)
+status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
 {
     if (mIsShutdown) {
         buffer->mFrameCount = 0;
@@ -971,7 +972,9 @@
     // it is always larger or equal to avail.
     LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
     buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
-    mUnreleased = avail;
+    if (!ackFlush) {
+        mUnreleased = avail;
+    }
     return NO_ERROR;
 }
 
diff --git a/media/libmedia/IAudioFlinger.cpp b/media/libmedia/IAudioFlinger.cpp
index a3f014b..632e6d5 100644
--- a/media/libmedia/IAudioFlinger.cpp
+++ b/media/libmedia/IAudioFlinger.cpp
@@ -89,7 +89,7 @@
 class BpAudioFlinger : public BpInterface<IAudioFlinger>
 {
 public:
-    BpAudioFlinger(const sp<IBinder>& impl)
+    explicit BpAudioFlinger(const sp<IBinder>& impl)
         : BpInterface<IAudioFlinger>(impl)
     {
     }
@@ -937,7 +937,7 @@
             pid_t tid = (pid_t) data.readInt32();
             int sessionId = data.readInt32();
             int clientUid = data.readInt32();
-            status_t status;
+            status_t status = NO_ERROR;
             sp<IAudioTrack> track;
             if ((haveSharedBuffer && (buffer == 0)) ||
                     ((buffer != 0) && (buffer->pointer() == NULL))) {
@@ -972,7 +972,7 @@
             size_t notificationFrames = data.readInt64();
             sp<IMemory> cblk;
             sp<IMemory> buffers;
-            status_t status;
+            status_t status = NO_ERROR;
             sp<IAudioRecord> record = openRecord(input,
                     sampleRate, format, channelMask, opPackageName, &frameCount, &flags, tid,
                     clientUid, &sessionId, &notificationFrames, cblk, buffers, &status);
@@ -1104,13 +1104,15 @@
         case OPEN_OUTPUT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             audio_module_handle_t module = (audio_module_handle_t)data.readInt32();
-            audio_config_t config;
-            data.read(&config, sizeof(audio_config_t));
+            audio_config_t config = {};
+            if (data.read(&config, sizeof(audio_config_t)) != NO_ERROR) {
+                ALOGE("b/23905951");
+            }
             audio_devices_t devices = (audio_devices_t)data.readInt32();
             String8 address(data.readString8());
             audio_output_flags_t flags = (audio_output_flags_t) data.readInt32();
-            uint32_t latencyMs;
-            audio_io_handle_t output;
+            uint32_t latencyMs = 0;
+            audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
             status_t status = openOutput(module, &output, &config,
                                          &devices, address, &latencyMs, flags);
             ALOGV("OPEN_OUTPUT output, %d", output);
@@ -1149,8 +1151,10 @@
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             audio_module_handle_t module = (audio_module_handle_t)data.readInt32();
             audio_io_handle_t input = (audio_io_handle_t)data.readInt32();
-            audio_config_t config;
-            data.read(&config, sizeof(audio_config_t));
+            audio_config_t config = {};
+            if (data.read(&config, sizeof(audio_config_t)) != NO_ERROR) {
+                ALOGE("b/23905951");
+            }
             audio_devices_t device = (audio_devices_t)data.readInt32();
             String8 address(data.readString8());
             audio_source_t source = (audio_source_t)data.readInt32();
@@ -1186,8 +1190,8 @@
         case GET_RENDER_POSITION: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             audio_io_handle_t output = (audio_io_handle_t) data.readInt32();
-            uint32_t halFrames;
-            uint32_t dspFrames;
+            uint32_t halFrames = 0;
+            uint32_t dspFrames = 0;
             status_t status = getRenderPosition(&halFrames, &dspFrames, output);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
@@ -1223,7 +1227,7 @@
         } break;
         case QUERY_NUM_EFFECTS: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            uint32_t numEffects;
+            uint32_t numEffects = 0;
             status_t status = queryNumberEffects(&numEffects);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
@@ -1233,7 +1237,7 @@
         }
         case QUERY_EFFECT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            effect_descriptor_t desc;
+            effect_descriptor_t desc = {};
             status_t status = queryEffect(data.readInt32(), &desc);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
@@ -1245,7 +1249,7 @@
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             effect_uuid_t uuid;
             data.read(&uuid, sizeof(effect_uuid_t));
-            effect_descriptor_t desc;
+            effect_descriptor_t desc = {};
             status_t status = getEffectDescriptor(&uuid, &desc);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
@@ -1255,16 +1259,18 @@
         }
         case CREATE_EFFECT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            effect_descriptor_t desc;
-            data.read(&desc, sizeof(effect_descriptor_t));
+            effect_descriptor_t desc = {};
+            if (data.read(&desc, sizeof(effect_descriptor_t)) != NO_ERROR) {
+                ALOGE("b/23905951");
+            }
             sp<IEffectClient> client = interface_cast<IEffectClient>(data.readStrongBinder());
             int32_t priority = data.readInt32();
             audio_io_handle_t output = (audio_io_handle_t) data.readInt32();
             int sessionId = data.readInt32();
             const String16 opPackageName = data.readString16();
-            status_t status;
-            int id;
-            int enabled;
+            status_t status = NO_ERROR;
+            int id = 0;
+            int enabled = 0;
 
             sp<IEffect> effect = createEffect(&desc, client, priority, output, sessionId,
                     opPackageName, &status, &id, &enabled);
@@ -1333,8 +1339,10 @@
         } break;
         case GET_AUDIO_PORT: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            struct audio_port port;
-            data.read(&port, sizeof(struct audio_port));
+            struct audio_port port = {};
+            if (data.read(&port, sizeof(struct audio_port)) != NO_ERROR) {
+                ALOGE("b/23905951");
+            }
             status_t status = getAudioPort(&port);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
@@ -1346,8 +1354,10 @@
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             struct audio_patch patch;
             data.read(&patch, sizeof(struct audio_patch));
-            audio_patch_handle_t handle;
-            data.read(&handle, sizeof(audio_patch_handle_t));
+            audio_patch_handle_t handle = {};
+            if (data.read(&handle, sizeof(audio_patch_handle_t)) != NO_ERROR) {
+                ALOGE("b/23905951");
+            }
             status_t status = createAudioPatch(&patch, &handle);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
diff --git a/media/libmedia/IAudioFlingerClient.cpp b/media/libmedia/IAudioFlingerClient.cpp
index 3429d36..343db41 100644
--- a/media/libmedia/IAudioFlingerClient.cpp
+++ b/media/libmedia/IAudioFlingerClient.cpp
@@ -34,7 +34,7 @@
 class BpAudioFlingerClient : public BpInterface<IAudioFlingerClient>
 {
 public:
-    BpAudioFlingerClient(const sp<IBinder>& impl)
+    explicit BpAudioFlingerClient(const sp<IBinder>& impl)
         : BpInterface<IAudioFlingerClient>(impl)
     {
     }
diff --git a/media/libmedia/IAudioPolicyService.cpp b/media/libmedia/IAudioPolicyService.cpp
index 3348441..c993a5c 100644
--- a/media/libmedia/IAudioPolicyService.cpp
+++ b/media/libmedia/IAudioPolicyService.cpp
@@ -81,7 +81,7 @@
 class BpAudioPolicyService : public BpInterface<IAudioPolicyService>
 {
 public:
-    BpAudioPolicyService(const sp<IBinder>& impl)
+    explicit BpAudioPolicyService(const sp<IBinder>& impl)
         : BpInterface<IAudioPolicyService>(impl)
     {
     }
@@ -877,7 +877,7 @@
             if (hasOffloadInfo) {
                 data.read(&offloadInfo, sizeof(audio_offload_info_t));
             }
-            audio_io_handle_t output;
+            audio_io_handle_t output = 0;
             status_t status = getOutputForAttr(hasAttributes ? &attr : NULL,
                     &output, session, &stream, uid,
                     samplingRate, format, channelMask,
@@ -932,7 +932,7 @@
             audio_channel_mask_t channelMask = data.readInt32();
             audio_input_flags_t flags = (audio_input_flags_t) data.readInt32();
             audio_port_handle_t selectedDeviceId = (audio_port_handle_t) data.readInt32();
-            audio_io_handle_t input;
+            audio_io_handle_t input = {};
             status_t status = getInputForAttr(&attr, &input, session, uid,
                                               samplingRate, format, channelMask,
                                               flags, selectedDeviceId);
@@ -994,7 +994,7 @@
             audio_stream_type_t stream =
                     static_cast <audio_stream_type_t>(data.readInt32());
             audio_devices_t device = static_cast <audio_devices_t>(data.readInt32());
-            int index;
+            int index = 0;
             status_t status = getStreamVolumeIndex(stream, &index, device);
             reply->writeInt32(index);
             reply->writeInt32(static_cast <uint32_t>(status));
@@ -1148,8 +1148,10 @@
 
         case GET_AUDIO_PORT: {
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            struct audio_port port;
-            data.read(&port, sizeof(struct audio_port));
+            struct audio_port port = {};
+            if (data.read(&port, sizeof(struct audio_port)) != NO_ERROR) {
+                ALOGE("b/23912202");
+            }
             status_t status = getAudioPort(&port);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
@@ -1162,8 +1164,10 @@
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             struct audio_patch patch;
             data.read(&patch, sizeof(struct audio_patch));
-            audio_patch_handle_t handle;
-            data.read(&handle, sizeof(audio_patch_handle_t));
+            audio_patch_handle_t handle = {};
+            if (data.read(&handle, sizeof(audio_patch_handle_t)) != NO_ERROR) {
+                ALOGE("b/23912202");
+            }
             status_t status = createAudioPatch(&patch, &handle);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
@@ -1238,9 +1242,9 @@
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             sp<IAudioPolicyServiceClient> client = interface_cast<IAudioPolicyServiceClient>(
                     data.readStrongBinder());
-            audio_session_t session;
-            audio_io_handle_t ioHandle;
-            audio_devices_t device;
+            audio_session_t session = {};
+            audio_io_handle_t ioHandle = {};
+            audio_devices_t device = {};
             status_t status = acquireSoundTriggerSession(&session, &ioHandle, &device);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
@@ -1292,7 +1296,7 @@
             data.read(&source, sizeof(struct audio_port_config));
             audio_attributes_t attributes;
             data.read(&attributes, sizeof(audio_attributes_t));
-            audio_io_handle_t handle;
+            audio_io_handle_t handle = {};
             status_t status = startAudioSource(&source, &attributes, &handle);
             reply->writeInt32(status);
             reply->writeInt32(handle);
diff --git a/media/libmedia/IAudioPolicyServiceClient.cpp b/media/libmedia/IAudioPolicyServiceClient.cpp
index 65cc7d6..c015d24 100644
--- a/media/libmedia/IAudioPolicyServiceClient.cpp
+++ b/media/libmedia/IAudioPolicyServiceClient.cpp
@@ -36,7 +36,7 @@
 class BpAudioPolicyServiceClient : public BpInterface<IAudioPolicyServiceClient>
 {
 public:
-    BpAudioPolicyServiceClient(const sp<IBinder>& impl)
+    explicit BpAudioPolicyServiceClient(const sp<IBinder>& impl)
         : BpInterface<IAudioPolicyServiceClient>(impl)
     {
     }
diff --git a/media/libmedia/IAudioRecord.cpp b/media/libmedia/IAudioRecord.cpp
index 9d80753..958bfc6 100644
--- a/media/libmedia/IAudioRecord.cpp
+++ b/media/libmedia/IAudioRecord.cpp
@@ -37,7 +37,7 @@
 class BpAudioRecord : public BpInterface<IAudioRecord>
 {
 public:
-    BpAudioRecord(const sp<IBinder>& impl)
+    explicit BpAudioRecord(const sp<IBinder>& impl)
         : BpInterface<IAudioRecord>(impl)
     {
     }
diff --git a/media/libmedia/IAudioTrack.cpp b/media/libmedia/IAudioTrack.cpp
index 651cb61..6c901ce 100644
--- a/media/libmedia/IAudioTrack.cpp
+++ b/media/libmedia/IAudioTrack.cpp
@@ -47,7 +47,7 @@
 class BpAudioTrack : public BpInterface<IAudioTrack>
 {
 public:
-    BpAudioTrack(const sp<IBinder>& impl)
+    explicit BpAudioTrack(const sp<IBinder>& impl)
         : BpInterface<IAudioTrack>(impl)
     {
     }
diff --git a/media/libmedia/ICrypto.cpp b/media/libmedia/ICrypto.cpp
index 947294f..29a0823 100644
--- a/media/libmedia/ICrypto.cpp
+++ b/media/libmedia/ICrypto.cpp
@@ -39,7 +39,7 @@
 };
 
 struct BpCrypto : public BpInterface<ICrypto> {
-    BpCrypto(const sp<IBinder> &impl)
+    explicit BpCrypto(const sp<IBinder> &impl)
         : BpInterface<ICrypto>(impl) {
     }
 
@@ -297,13 +297,33 @@
             if (secure) {
                 secureBufferId = reinterpret_cast<void *>(static_cast<uintptr_t>(data.readInt64()));
             } else {
-                dstPtr = malloc(totalSize);
+                dstPtr = calloc(1, totalSize);
             }
 
             AString errorDetailMsg;
             ssize_t result;
 
-            if (offset + totalSize > sharedBuffer->size()) {
+            size_t sumSubsampleSizes = 0;
+            bool overflow = false;
+            for (int32_t i = 0; i < numSubSamples; ++i) {
+                CryptoPlugin::SubSample &ss = subSamples[i];
+                if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfEncryptedData) {
+                    sumSubsampleSizes += ss.mNumBytesOfEncryptedData;
+                } else {
+                    overflow = true;
+                }
+                if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfClearData) {
+                    sumSubsampleSizes += ss.mNumBytesOfClearData;
+                } else {
+                    overflow = true;
+                }
+            }
+
+            if (overflow || sumSubsampleSizes != totalSize) {
+                result = -EINVAL;
+            } else if (totalSize > sharedBuffer->size()) {
+                result = -EINVAL;
+            } else if ((size_t)offset > sharedBuffer->size() - totalSize) {
                 result = -EINVAL;
             } else {
                 result = decrypt(
diff --git a/media/libmedia/IDataSource.cpp b/media/libmedia/IDataSource.cpp
index 76d1d68..0be53c9 100644
--- a/media/libmedia/IDataSource.cpp
+++ b/media/libmedia/IDataSource.cpp
@@ -35,7 +35,8 @@
 };
 
 struct BpDataSource : public BpInterface<IDataSource> {
-    BpDataSource(const sp<IBinder>& impl) : BpInterface<IDataSource>(impl) {}
+    explicit BpDataSource(const sp<IBinder>& impl)
+        : BpInterface<IDataSource>(impl) {}
 
     virtual sp<IMemory> getIMemory() {
         Parcel data, reply;
diff --git a/media/libmedia/IDrm.cpp b/media/libmedia/IDrm.cpp
index b1ad0c5..284e99a 100644
--- a/media/libmedia/IDrm.cpp
+++ b/media/libmedia/IDrm.cpp
@@ -60,7 +60,7 @@
 };
 
 struct BpDrm : public BpInterface<IDrm> {
-    BpDrm(const sp<IBinder> &impl)
+    explicit BpDrm(const sp<IBinder> &impl)
         : BpInterface<IDrm>(impl) {
     }
 
diff --git a/media/libmedia/IDrmClient.cpp b/media/libmedia/IDrmClient.cpp
index 490c6ed..444201f 100644
--- a/media/libmedia/IDrmClient.cpp
+++ b/media/libmedia/IDrmClient.cpp
@@ -35,7 +35,7 @@
 class BpDrmClient: public BpInterface<IDrmClient>
 {
 public:
-    BpDrmClient(const sp<IBinder>& impl)
+    explicit BpDrmClient(const sp<IBinder>& impl)
         : BpInterface<IDrmClient>(impl)
     {
     }
diff --git a/media/libmedia/IEffect.cpp b/media/libmedia/IEffect.cpp
index eb4b098..115ca75 100644
--- a/media/libmedia/IEffect.cpp
+++ b/media/libmedia/IEffect.cpp
@@ -36,7 +36,7 @@
 class BpEffect: public BpInterface<IEffect>
 {
 public:
-    BpEffect(const sp<IBinder>& impl)
+    explicit BpEffect(const sp<IBinder>& impl)
         : BpInterface<IEffect>(impl)
     {
     }
@@ -85,13 +85,15 @@
         data.writeInt32(size);
 
         status_t status = remote()->transact(COMMAND, data, &reply);
+        if (status == NO_ERROR) {
+            status = reply.readInt32();
+        }
         if (status != NO_ERROR) {
             if (pReplySize != NULL)
                 *pReplySize = 0;
             return status;
         }
 
-        status = reply.readInt32();
         size = reply.readInt32();
         if (size != 0 && pReplyData != NULL && pReplySize != NULL) {
             reply.read(pReplyData, size);
@@ -154,23 +156,34 @@
             uint32_t cmdSize = data.readInt32();
             char *cmd = NULL;
             if (cmdSize) {
-                cmd = (char *)malloc(cmdSize);
+                cmd = (char *)calloc(cmdSize, 1);
+                if (cmd == NULL) {
+                    reply->writeInt32(NO_MEMORY);
+                    return NO_ERROR;
+                }
                 data.read(cmd, cmdSize);
             }
             uint32_t replySize = data.readInt32();
             uint32_t replySz = replySize;
             char *resp = NULL;
             if (replySize) {
-                resp = (char *)malloc(replySize);
+                resp = (char *)calloc(replySize, 1);
+                if (resp == NULL) {
+                    free(cmd);
+                    reply->writeInt32(NO_MEMORY);
+                    return NO_ERROR;
+                }
             }
             status_t status = command(cmdCode, cmdSize, cmd, &replySz, resp);
             reply->writeInt32(status);
-            if (replySz < replySize) {
-                replySize = replySz;
-            }
-            reply->writeInt32(replySize);
-            if (replySize) {
-                reply->write(resp, replySize);
+            if (status == NO_ERROR) {
+                if (replySz < replySize) {
+                    replySize = replySz;
+                }
+                reply->writeInt32(replySize);
+                if (replySize) {
+                    reply->write(resp, replySize);
+                }
             }
             if (cmd) {
                 free(cmd);
diff --git a/media/libmedia/IEffectClient.cpp b/media/libmedia/IEffectClient.cpp
index 1322e72..3f2c67d 100644
--- a/media/libmedia/IEffectClient.cpp
+++ b/media/libmedia/IEffectClient.cpp
@@ -33,7 +33,7 @@
 class BpEffectClient: public BpInterface<IEffectClient>
 {
 public:
-    BpEffectClient(const sp<IBinder>& impl)
+    explicit BpEffectClient(const sp<IBinder>& impl)
         : BpInterface<IEffectClient>(impl)
     {
     }
diff --git a/media/libmedia/IHDCP.cpp b/media/libmedia/IHDCP.cpp
index f3a8902..21e35f6 100644
--- a/media/libmedia/IHDCP.cpp
+++ b/media/libmedia/IHDCP.cpp
@@ -37,7 +37,7 @@
 };
 
 struct BpHDCPObserver : public BpInterface<IHDCPObserver> {
-    BpHDCPObserver(const sp<IBinder> &impl)
+    explicit BpHDCPObserver(const sp<IBinder> &impl)
         : BpInterface<IHDCPObserver>(impl) {
     }
 
@@ -58,7 +58,7 @@
 IMPLEMENT_META_INTERFACE(HDCPObserver, "android.hardware.IHDCPObserver");
 
 struct BpHDCP : public BpInterface<IHDCP> {
-    BpHDCP(const sp<IBinder> &impl)
+    explicit BpHDCP(const sp<IBinder> &impl)
         : BpInterface<IHDCP>(impl) {
     }
 
diff --git a/media/libmedia/IMediaCodecList.cpp b/media/libmedia/IMediaCodecList.cpp
index e2df104..9fca9c7 100644
--- a/media/libmedia/IMediaCodecList.cpp
+++ b/media/libmedia/IMediaCodecList.cpp
@@ -38,7 +38,7 @@
 class BpMediaCodecList: public BpInterface<IMediaCodecList>
 {
 public:
-    BpMediaCodecList(const sp<IBinder>& impl)
+    explicit BpMediaCodecList(const sp<IBinder>& impl)
         : BpInterface<IMediaCodecList>(impl)
     {
     }
diff --git a/media/libmedia/IMediaHTTPConnection.cpp b/media/libmedia/IMediaHTTPConnection.cpp
index 0dda0be9..e4b717b 100644
--- a/media/libmedia/IMediaHTTPConnection.cpp
+++ b/media/libmedia/IMediaHTTPConnection.cpp
@@ -38,7 +38,7 @@
 };
 
 struct BpMediaHTTPConnection : public BpInterface<IMediaHTTPConnection> {
-    BpMediaHTTPConnection(const sp<IBinder> &impl)
+    explicit BpMediaHTTPConnection(const sp<IBinder> &impl)
         : BpInterface<IMediaHTTPConnection>(impl) {
     }
 
diff --git a/media/libmedia/IMediaHTTPService.cpp b/media/libmedia/IMediaHTTPService.cpp
index 0c16a2b..062a07a 100644
--- a/media/libmedia/IMediaHTTPService.cpp
+++ b/media/libmedia/IMediaHTTPService.cpp
@@ -30,7 +30,7 @@
 };
 
 struct BpMediaHTTPService : public BpInterface<IMediaHTTPService> {
-    BpMediaHTTPService(const sp<IBinder> &impl)
+    explicit BpMediaHTTPService(const sp<IBinder> &impl)
         : BpInterface<IMediaHTTPService>(impl) {
     }
 
diff --git a/media/libmedia/IMediaLogService.cpp b/media/libmedia/IMediaLogService.cpp
index 1536337..bc445ff 100644
--- a/media/libmedia/IMediaLogService.cpp
+++ b/media/libmedia/IMediaLogService.cpp
@@ -34,7 +34,7 @@
 class BpMediaLogService : public BpInterface<IMediaLogService>
 {
 public:
-    BpMediaLogService(const sp<IBinder>& impl)
+    explicit BpMediaLogService(const sp<IBinder>& impl)
         : BpInterface<IMediaLogService>(impl)
     {
     }
diff --git a/media/libmedia/IMediaMetadataRetriever.cpp b/media/libmedia/IMediaMetadataRetriever.cpp
index dbf524e..3c4dce9 100644
--- a/media/libmedia/IMediaMetadataRetriever.cpp
+++ b/media/libmedia/IMediaMetadataRetriever.cpp
@@ -75,7 +75,7 @@
 class BpMediaMetadataRetriever: public BpInterface<IMediaMetadataRetriever>
 {
 public:
-    BpMediaMetadataRetriever(const sp<IBinder>& impl)
+    explicit BpMediaMetadataRetriever(const sp<IBinder>& impl)
         : BpInterface<IMediaMetadataRetriever>(impl)
     {
     }
diff --git a/media/libmedia/IMediaPlayer.cpp b/media/libmedia/IMediaPlayer.cpp
index bde35f2..77ca96d 100644
--- a/media/libmedia/IMediaPlayer.cpp
+++ b/media/libmedia/IMediaPlayer.cpp
@@ -72,7 +72,7 @@
 class BpMediaPlayer: public BpInterface<IMediaPlayer>
 {
 public:
-    BpMediaPlayer(const sp<IBinder>& impl)
+    explicit BpMediaPlayer(const sp<IBinder>& impl)
         : BpInterface<IMediaPlayer>(impl)
     {
     }
@@ -566,7 +566,7 @@
         } break;
         case GET_CURRENT_POSITION: {
             CHECK_INTERFACE(IMediaPlayer, data, reply);
-            int msec;
+            int msec = 0;
             status_t ret = getCurrentPosition(&msec);
             reply->writeInt32(msec);
             reply->writeInt32(ret);
@@ -574,7 +574,7 @@
         } break;
         case GET_DURATION: {
             CHECK_INTERFACE(IMediaPlayer, data, reply);
-            int msec;
+            int msec = 0;
             status_t ret = getDuration(&msec);
             reply->writeInt32(msec);
             reply->writeInt32(ret);
@@ -653,6 +653,7 @@
             CHECK_INTERFACE(IMediaPlayer, data, reply);
 
             struct sockaddr_in endpoint;
+            memset(&endpoint, 0, sizeof(endpoint));
             int amt = data.readInt32();
             if (amt == sizeof(endpoint)) {
                 data.read(&endpoint, sizeof(struct sockaddr_in));
@@ -667,6 +668,7 @@
             CHECK_INTERFACE(IMediaPlayer, data, reply);
 
             struct sockaddr_in endpoint;
+            memset(&endpoint, 0, sizeof(endpoint));
             status_t res = getRetransmitEndpoint(&endpoint);
 
             reply->writeInt32(res);
diff --git a/media/libmedia/IMediaPlayerClient.cpp b/media/libmedia/IMediaPlayerClient.cpp
index d608386..bbf8475 100644
--- a/media/libmedia/IMediaPlayerClient.cpp
+++ b/media/libmedia/IMediaPlayerClient.cpp
@@ -30,7 +30,7 @@
 class BpMediaPlayerClient: public BpInterface<IMediaPlayerClient>
 {
 public:
-    BpMediaPlayerClient(const sp<IBinder>& impl)
+    explicit BpMediaPlayerClient(const sp<IBinder>& impl)
         : BpInterface<IMediaPlayerClient>(impl)
     {
     }
diff --git a/media/libmedia/IMediaPlayerService.cpp b/media/libmedia/IMediaPlayerService.cpp
index 05f8670..6fe916d 100644
--- a/media/libmedia/IMediaPlayerService.cpp
+++ b/media/libmedia/IMediaPlayerService.cpp
@@ -54,7 +54,7 @@
 class BpMediaPlayerService: public BpInterface<IMediaPlayerService>
 {
 public:
-    BpMediaPlayerService(const sp<IBinder>& impl)
+    explicit BpMediaPlayerService(const sp<IBinder>& impl)
         : BpInterface<IMediaPlayerService>(impl)
     {
     }
diff --git a/media/libmedia/IMediaRecorder.cpp b/media/libmedia/IMediaRecorder.cpp
index ee3b584..3fc2541 100644
--- a/media/libmedia/IMediaRecorder.cpp
+++ b/media/libmedia/IMediaRecorder.cpp
@@ -60,7 +60,7 @@
 class BpMediaRecorder: public BpInterface<IMediaRecorder>
 {
 public:
-    BpMediaRecorder(const sp<IBinder>& impl)
+    explicit BpMediaRecorder(const sp<IBinder>& impl)
     : BpInterface<IMediaRecorder>(impl)
     {
     }
diff --git a/media/libmedia/IMediaRecorderClient.cpp b/media/libmedia/IMediaRecorderClient.cpp
index 6795d23..a76f934 100644
--- a/media/libmedia/IMediaRecorderClient.cpp
+++ b/media/libmedia/IMediaRecorderClient.cpp
@@ -30,7 +30,7 @@
 class BpMediaRecorderClient: public BpInterface<IMediaRecorderClient>
 {
 public:
-    BpMediaRecorderClient(const sp<IBinder>& impl)
+    explicit BpMediaRecorderClient(const sp<IBinder>& impl)
         : BpInterface<IMediaRecorderClient>(impl)
     {
     }
diff --git a/media/libmedia/IOMX.cpp b/media/libmedia/IOMX.cpp
index 16da65e..af29a44 100644
--- a/media/libmedia/IOMX.cpp
+++ b/media/libmedia/IOMX.cpp
@@ -61,7 +61,7 @@
 
 class BpOMX : public BpInterface<IOMX> {
 public:
-    BpOMX(const sp<IBinder> &impl)
+    explicit BpOMX(const sp<IBinder> &impl)
         : BpInterface<IOMX>(impl) {
     }
 
@@ -592,7 +592,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 #define CHECK_OMX_INTERFACE(interface, data, reply) \
-        do { if (!data.enforceInterface(interface::getInterfaceDescriptor())) { \
+        do { if (!(data).enforceInterface(interface::getInterfaceDescriptor())) { \
             ALOGW("Call incorrectly routed to " #interface); \
             return PERMISSION_DENIED; \
         } } while (0)
@@ -963,6 +963,12 @@
 
             node_id node = (node_id)data.readInt32();
             OMX_U32 port_index = data.readInt32();
+            if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) {
+                ALOGE("b/24310423");
+                reply->writeInt32(INVALID_OPERATION);
+                return NO_ERROR;
+            }
+
             size_t size = data.readInt64();
 
             buffer_id buffer;
@@ -1073,7 +1079,7 @@
 
 class BpOMXObserver : public BpInterface<IOMXObserver> {
 public:
-    BpOMXObserver(const sp<IBinder> &impl)
+    explicit BpOMXObserver(const sp<IBinder> &impl)
         : BpInterface<IOMXObserver>(impl) {
     }
 
diff --git a/media/libmedia/IRemoteDisplay.cpp b/media/libmedia/IRemoteDisplay.cpp
index 869d11a..85c7bd6 100644
--- a/media/libmedia/IRemoteDisplay.cpp
+++ b/media/libmedia/IRemoteDisplay.cpp
@@ -30,7 +30,7 @@
 class BpRemoteDisplay: public BpInterface<IRemoteDisplay>
 {
 public:
-    BpRemoteDisplay(const sp<IBinder>& impl)
+    explicit BpRemoteDisplay(const sp<IBinder>& impl)
         : BpInterface<IRemoteDisplay>(impl)
     {
     }
diff --git a/media/libmedia/IRemoteDisplayClient.cpp b/media/libmedia/IRemoteDisplayClient.cpp
index bedeb6c..ca67665 100644
--- a/media/libmedia/IRemoteDisplayClient.cpp
+++ b/media/libmedia/IRemoteDisplayClient.cpp
@@ -32,7 +32,7 @@
 class BpRemoteDisplayClient: public BpInterface<IRemoteDisplayClient>
 {
 public:
-    BpRemoteDisplayClient(const sp<IBinder>& impl)
+    explicit BpRemoteDisplayClient(const sp<IBinder>& impl)
         : BpInterface<IRemoteDisplayClient>(impl)
     {
     }
diff --git a/media/libmedia/IResourceManagerClient.cpp b/media/libmedia/IResourceManagerClient.cpp
index b3f56e8..1fea479 100644
--- a/media/libmedia/IResourceManagerClient.cpp
+++ b/media/libmedia/IResourceManagerClient.cpp
@@ -31,7 +31,7 @@
 class BpResourceManagerClient: public BpInterface<IResourceManagerClient>
 {
 public:
-    BpResourceManagerClient(const sp<IBinder> &impl)
+    explicit BpResourceManagerClient(const sp<IBinder> &impl)
         : BpInterface<IResourceManagerClient>(impl)
     {
     }
diff --git a/media/libmedia/IResourceManagerService.cpp b/media/libmedia/IResourceManagerService.cpp
index 4598686..c4cded0 100644
--- a/media/libmedia/IResourceManagerService.cpp
+++ b/media/libmedia/IResourceManagerService.cpp
@@ -58,7 +58,7 @@
 class BpResourceManagerService : public BpInterface<IResourceManagerService>
 {
 public:
-    BpResourceManagerService(const sp<IBinder> &impl)
+    explicit BpResourceManagerService(const sp<IBinder> &impl)
         : BpInterface<IResourceManagerService>(impl)
     {
     }
diff --git a/media/libmedia/IStreamSource.cpp b/media/libmedia/IStreamSource.cpp
index 840e453..8ec521c 100644
--- a/media/libmedia/IStreamSource.cpp
+++ b/media/libmedia/IStreamSource.cpp
@@ -51,7 +51,7 @@
 };
 
 struct BpStreamSource : public BpInterface<IStreamSource> {
-    BpStreamSource(const sp<IBinder> &impl)
+    explicit BpStreamSource(const sp<IBinder> &impl)
         : BpInterface<IStreamSource>(impl) {
     }
 
@@ -141,7 +141,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct BpStreamListener : public BpInterface<IStreamListener> {
-    BpStreamListener(const sp<IBinder> &impl)
+    explicit BpStreamListener(const sp<IBinder> &impl)
         : BpInterface<IStreamListener>(impl) {
     }
 
diff --git a/media/libmedia/MediaCodecInfo.cpp b/media/libmedia/MediaCodecInfo.cpp
index 8d3fa7b..06abd8d 100644
--- a/media/libmedia/MediaCodecInfo.cpp
+++ b/media/libmedia/MediaCodecInfo.cpp
@@ -26,8 +26,6 @@
 #include <media/stagefright/foundation/AMessage.h>
 #include <binder/Parcel.h>
 
-#include <media/stagefright/OMXCodec.h>
-
 namespace android {
 
 void MediaCodecInfo::Capabilities::getSupportedProfileLevels(
@@ -101,6 +99,21 @@
     return OK;
 }
 
+void MediaCodecInfo::CapabilitiesBuilder::addProfileLevel(uint32_t profile, uint32_t level) {
+    ProfileLevel profileLevel;
+    profileLevel.mProfile = profile;
+    profileLevel.mLevel = level;
+    mProfileLevels.push_back(profileLevel);
+}
+
+void MediaCodecInfo::CapabilitiesBuilder::addColorFormat(uint32_t format) {
+    mColorFormats.push(format);
+}
+
+void MediaCodecInfo::CapabilitiesBuilder::addFlags(uint32_t flags) {
+    mFlags |= flags;
+}
+
 bool MediaCodecInfo::isEncoder() const {
     return mIsEncoder;
 }
@@ -225,26 +238,15 @@
     }
 }
 
-status_t MediaCodecInfo::initializeCapabilities(const CodecCapabilities &caps) {
-    mCurrentCaps->mProfileLevels.clear();
+status_t MediaCodecInfo::initializeCapabilities(const sp<Capabilities> &caps) {
+    // TRICKY: copy data to mCurrentCaps as it is a reference to
+    // an element of the capabilites map.
     mCurrentCaps->mColorFormats.clear();
-
-    for (size_t i = 0; i < caps.mProfileLevels.size(); ++i) {
-        const CodecProfileLevel &src = caps.mProfileLevels.itemAt(i);
-
-        ProfileLevel profileLevel;
-        profileLevel.mProfile = src.mProfile;
-        profileLevel.mLevel = src.mLevel;
-        mCurrentCaps->mProfileLevels.push_back(profileLevel);
-    }
-
-    for (size_t i = 0; i < caps.mColorFormats.size(); ++i) {
-        mCurrentCaps->mColorFormats.push_back(caps.mColorFormats.itemAt(i));
-    }
-
-    mCurrentCaps->mFlags = caps.mFlags;
-    mCurrentCaps->mDetails = new AMessage;
-
+    mCurrentCaps->mColorFormats.appendVector(caps->mColorFormats);
+    mCurrentCaps->mProfileLevels.clear();
+    mCurrentCaps->mProfileLevels.appendVector(caps->mProfileLevels);
+    mCurrentCaps->mFlags = caps->mFlags;
+    mCurrentCaps->mDetails = caps->mDetails;
     return OK;
 }
 
diff --git a/media/libmedia/ToneGenerator.cpp b/media/libmedia/ToneGenerator.cpp
index 9f4b4de..752c9a4 100644
--- a/media/libmedia/ToneGenerator.cpp
+++ b/media/libmedia/ToneGenerator.cpp
@@ -814,10 +814,10 @@
 
     char value[PROPERTY_VALUE_MAX];
     property_get("gsm.operator.iso-country", value, "");
-    if (strcmp(value,"us") == 0 ||
-        strcmp(value,"ca") == 0) {
+    if (strstr(value, "us") != NULL ||
+        strstr(value, "ca") != NULL) {
         mRegion = ANSI;
-    } else if (strcmp(value,"jp") == 0) {
+    } else if (strstr(value, "jp") != NULL) {
         mRegion = JAPAN;
     } else {
         mRegion = CEPT;
diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp
index 502ab2d..faf2339 100644
--- a/media/libmedia/mediaplayer.cpp
+++ b/media/libmedia/mediaplayer.cpp
@@ -922,6 +922,7 @@
 }
 
 status_t MediaPlayer::setNextMediaPlayer(const sp<MediaPlayer>& next) {
+    Mutex::Autolock _l(mLock);
     if (mPlayer == NULL) {
         return NO_INIT;
     }
diff --git a/media/libmediaplayerservice/Android.mk b/media/libmediaplayerservice/Android.mk
index 4d1b587..677fbf4 100644
--- a/media/libmediaplayerservice/Android.mk
+++ b/media/libmediaplayerservice/Android.mk
@@ -18,7 +18,6 @@
     MetadataRetrieverClient.cpp \
     RemoteDisplay.cpp           \
     SharedLibrary.cpp           \
-    StagefrightPlayer.cpp       \
     StagefrightRecorder.cpp     \
     TestPlayerStub.cpp          \
 
@@ -45,6 +44,9 @@
 LOCAL_STATIC_LIBRARIES :=       \
     libstagefright_nuplayer     \
     libstagefright_rtsp         \
+    libstagefright_timedtext    \
+
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libmedia
 
 LOCAL_C_INCLUDES :=                                                 \
     $(TOP)/frameworks/av/media/libstagefright/include               \
diff --git a/media/libmediaplayerservice/MediaPlayerFactory.cpp b/media/libmediaplayerservice/MediaPlayerFactory.cpp
index d5d12f7..605c710 100644
--- a/media/libmediaplayerservice/MediaPlayerFactory.cpp
+++ b/media/libmediaplayerservice/MediaPlayerFactory.cpp
@@ -31,7 +31,6 @@
 #include "MediaPlayerFactory.h"
 
 #include "TestPlayerStub.h"
-#include "StagefrightPlayer.h"
 #include "nuplayer/NuPlayerDriver.h"
 
 namespace android {
@@ -64,12 +63,6 @@
 }
 
 static player_type getDefaultPlayerType() {
-    char value[PROPERTY_VALUE_MAX];
-    if (property_get("media.stagefright.use-awesome", value, NULL)
-            && (!strcmp("1", value) || !strcasecmp("true", value))) {
-        return STAGEFRIGHT_PLAYER;
-    }
-
     return NU_PLAYER;
 }
 
@@ -176,63 +169,6 @@
  *                                                                           *
  *****************************************************************************/
 
-class StagefrightPlayerFactory :
-    public MediaPlayerFactory::IFactory {
-  public:
-    virtual float scoreFactory(const sp<IMediaPlayer>& /*client*/,
-                               int fd,
-                               int64_t offset,
-                               int64_t length,
-                               float /*curScore*/) {
-        if (legacyDrm()) {
-            sp<DataSource> source = new FileSource(dup(fd), offset, length);
-            String8 mimeType;
-            float confidence;
-            if (SniffWVM(source, &mimeType, &confidence, NULL /* format */)) {
-                return 1.0;
-            }
-        }
-
-        if (getDefaultPlayerType() == STAGEFRIGHT_PLAYER) {
-            char buf[20];
-            lseek(fd, offset, SEEK_SET);
-            read(fd, buf, sizeof(buf));
-            lseek(fd, offset, SEEK_SET);
-
-            uint32_t ident = *((uint32_t*)buf);
-
-            // Ogg vorbis?
-            if (ident == 0x5367674f) // 'OggS'
-                return 1.0;
-        }
-
-        return 0.0;
-    }
-
-    virtual float scoreFactory(const sp<IMediaPlayer>& /*client*/,
-                               const char* url,
-                               float /*curScore*/) {
-        if (legacyDrm() && !strncasecmp("widevine://", url, 11)) {
-            return 1.0;
-        }
-        return 0.0;
-    }
-
-    virtual sp<MediaPlayerBase> createPlayer(pid_t /* pid */) {
-        ALOGV(" create StagefrightPlayer");
-        return new StagefrightPlayer();
-    }
-  private:
-    bool legacyDrm() {
-        char value[PROPERTY_VALUE_MAX];
-        if (property_get("persist.sys.media.legacy-drm", value, NULL)
-                && (!strcmp("1", value) || !strcasecmp("true", value))) {
-            return true;
-        }
-        return false;
-    }
-};
-
 class NuPlayerFactory : public MediaPlayerFactory::IFactory {
   public:
     virtual float scoreFactory(const sp<IMediaPlayer>& /*client*/,
@@ -310,7 +246,6 @@
     if (sInitComplete)
         return;
 
-    registerFactory_l(new StagefrightPlayerFactory(), STAGEFRIGHT_PLAYER);
     registerFactory_l(new NuPlayerFactory(), NU_PLAYER);
     registerFactory_l(new TestPlayerFactory(), TEST_PLAYER);
 
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index 05a65a3..4ec2ac4 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -57,7 +57,7 @@
 #include <media/MemoryLeakTrackUtil.h>
 #include <media/stagefright/MediaCodecList.h>
 #include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/AudioPlayer.h>
+#include <media/stagefright/Utils.h>
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/ALooperRoster.h>
 #include <mediautils/BatteryNotifier.h>
@@ -73,7 +73,6 @@
 #include "MediaPlayerFactory.h"
 
 #include "TestPlayerStub.h"
-#include "StagefrightPlayer.h"
 #include "nuplayer/NuPlayerDriver.h"
 
 #include <OMX.h>
@@ -1730,7 +1729,7 @@
     t->setVolume(mLeftVolume, mRightVolume);
 
     mSampleRateHz = sampleRate;
-    mFlags = t->getFlags(); // we suggest the flags above, but new AudioTrack() may not grant it.
+    mFlags = flags;
     mMsecsPerFrame = 1E3f / (mPlaybackRate.mSpeed * sampleRate);
     mFrameSize = t->frameSize();
     uint32_t pos;
@@ -1742,7 +1741,7 @@
     status_t res = NO_ERROR;
     // Note some output devices may give us a direct track even though we don't specify it.
     // Example: Line application b/17459982.
-    if ((mFlags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
+    if ((t->getFlags() & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) {
         res = t->setPlaybackRate(mPlaybackRate);
         if (res == NO_ERROR) {
             t->setAuxEffectSendLevel(mSendLevel);
@@ -1890,8 +1889,13 @@
 void MediaPlayerService::AudioOutput::close()
 {
     ALOGV("close");
-    Mutex::Autolock lock(mLock);
-    close_l();
+    sp<AudioTrack> track;
+    {
+        Mutex::Autolock lock(mLock);
+        track = mTrack;
+        close_l(); // clears mTrack
+    }
+    // destruction of the track occurs outside of mutex.
 }
 
 void MediaPlayerService::AudioOutput::setVolume(float left, float right)
diff --git a/media/libmediaplayerservice/StagefrightPlayer.cpp b/media/libmediaplayerservice/StagefrightPlayer.cpp
deleted file mode 100644
index 8fc4b29..0000000
--- a/media/libmediaplayerservice/StagefrightPlayer.cpp
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "StagefrightPlayer"
-#include <utils/Log.h>
-
-#include "StagefrightPlayer.h"
-
-#include "AwesomePlayer.h"
-
-#include <media/Metadata.h>
-#include <media/stagefright/MediaExtractor.h>
-
-namespace android {
-
-StagefrightPlayer::StagefrightPlayer()
-    : mPlayer(new AwesomePlayer) {
-    ALOGV("StagefrightPlayer");
-
-    mPlayer->setListener(this);
-}
-
-StagefrightPlayer::~StagefrightPlayer() {
-    ALOGV("~StagefrightPlayer");
-    reset();
-
-    delete mPlayer;
-    mPlayer = NULL;
-}
-
-status_t StagefrightPlayer::initCheck() {
-    ALOGV("initCheck");
-    return OK;
-}
-
-status_t StagefrightPlayer::setUID(uid_t uid) {
-    mPlayer->setUID(uid);
-
-    return OK;
-}
-
-status_t StagefrightPlayer::setDataSource(
-        const sp<IMediaHTTPService> &httpService,
-        const char *url,
-        const KeyedVector<String8, String8> *headers) {
-    return mPlayer->setDataSource(httpService, url, headers);
-}
-
-// Warning: The filedescriptor passed into this method will only be valid until
-// the method returns, if you want to keep it, dup it!
-status_t StagefrightPlayer::setDataSource(int fd, int64_t offset, int64_t length) {
-    ALOGV("setDataSource(%d, %lld, %lld)", fd, offset, length);
-    return mPlayer->setDataSource(fd, offset, length);
-}
-
-status_t StagefrightPlayer::setDataSource(const sp<IStreamSource> &source) {
-    return mPlayer->setDataSource(source);
-}
-
-status_t StagefrightPlayer::setVideoSurfaceTexture(
-        const sp<IGraphicBufferProducer> &bufferProducer) {
-    ALOGV("setVideoSurfaceTexture");
-
-    return mPlayer->setSurfaceTexture(bufferProducer);
-}
-
-status_t StagefrightPlayer::prepare() {
-    return mPlayer->prepare();
-}
-
-status_t StagefrightPlayer::prepareAsync() {
-    return mPlayer->prepareAsync();
-}
-
-status_t StagefrightPlayer::start() {
-    ALOGV("start");
-
-    return mPlayer->play();
-}
-
-status_t StagefrightPlayer::stop() {
-    ALOGV("stop");
-
-    return pause();  // what's the difference?
-}
-
-status_t StagefrightPlayer::pause() {
-    ALOGV("pause");
-
-    return mPlayer->pause();
-}
-
-bool StagefrightPlayer::isPlaying() {
-    ALOGV("isPlaying");
-    return mPlayer->isPlaying();
-}
-
-status_t StagefrightPlayer::seekTo(int msec) {
-    ALOGV("seekTo %.2f secs", msec / 1E3);
-
-    status_t err = mPlayer->seekTo((int64_t)msec * 1000);
-
-    return err;
-}
-
-status_t StagefrightPlayer::getCurrentPosition(int *msec) {
-    ALOGV("getCurrentPosition");
-
-    int64_t positionUs;
-    status_t err = mPlayer->getPosition(&positionUs);
-
-    if (err != OK) {
-        return err;
-    }
-
-    *msec = (positionUs + 500) / 1000;
-
-    return OK;
-}
-
-status_t StagefrightPlayer::getDuration(int *msec) {
-    ALOGV("getDuration");
-
-    int64_t durationUs;
-    status_t err = mPlayer->getDuration(&durationUs);
-
-    if (err != OK) {
-        *msec = 0;
-        return OK;
-    }
-
-    *msec = (durationUs + 500) / 1000;
-
-    return OK;
-}
-
-status_t StagefrightPlayer::reset() {
-    ALOGV("reset");
-
-    mPlayer->reset();
-
-    return OK;
-}
-
-status_t StagefrightPlayer::setLooping(int loop) {
-    ALOGV("setLooping");
-
-    return mPlayer->setLooping(loop);
-}
-
-player_type StagefrightPlayer::playerType() {
-    ALOGV("playerType");
-    return STAGEFRIGHT_PLAYER;
-}
-
-status_t StagefrightPlayer::invoke(const Parcel &request, Parcel *reply) {
-    ALOGV("invoke()");
-    return mPlayer->invoke(request, reply);
-}
-
-void StagefrightPlayer::setAudioSink(const sp<AudioSink> &audioSink) {
-    MediaPlayerInterface::setAudioSink(audioSink);
-
-    mPlayer->setAudioSink(audioSink);
-}
-
-status_t StagefrightPlayer::setParameter(int key, const Parcel &request) {
-    ALOGV("setParameter(key=%d)", key);
-    return mPlayer->setParameter(key, request);
-}
-
-status_t StagefrightPlayer::getParameter(int key, Parcel *reply) {
-    ALOGV("getParameter");
-    return mPlayer->getParameter(key, reply);
-}
-
-status_t StagefrightPlayer::setPlaybackSettings(const AudioPlaybackRate &rate) {
-    return mPlayer->setPlaybackSettings(rate);
-}
-
-status_t StagefrightPlayer::getPlaybackSettings(AudioPlaybackRate *rate /* nonnull */) {
-    return mPlayer->getPlaybackSettings(rate);
-}
-
-status_t StagefrightPlayer::getMetadata(
-        const media::Metadata::Filter& /* ids */, Parcel *records) {
-    using media::Metadata;
-
-    uint32_t flags = mPlayer->flags();
-
-    Metadata metadata(records);
-
-    metadata.appendBool(
-            Metadata::kPauseAvailable,
-            flags & MediaExtractor::CAN_PAUSE);
-
-    metadata.appendBool(
-            Metadata::kSeekBackwardAvailable,
-            flags & MediaExtractor::CAN_SEEK_BACKWARD);
-
-    metadata.appendBool(
-            Metadata::kSeekForwardAvailable,
-            flags & MediaExtractor::CAN_SEEK_FORWARD);
-
-    metadata.appendBool(
-            Metadata::kSeekAvailable,
-            flags & MediaExtractor::CAN_SEEK);
-
-    return OK;
-}
-
-status_t StagefrightPlayer::dump(int fd, const Vector<String16> &args) const {
-    return mPlayer->dump(fd, args);
-}
-
-}  // namespace android
diff --git a/media/libmediaplayerservice/StagefrightPlayer.h b/media/libmediaplayerservice/StagefrightPlayer.h
deleted file mode 100644
index 96013df..0000000
--- a/media/libmediaplayerservice/StagefrightPlayer.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
-**
-** Copyright 2009, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#ifndef ANDROID_STAGEFRIGHTPLAYER_H
-#define ANDROID_STAGEFRIGHTPLAYER_H
-
-#include <media/MediaPlayerInterface.h>
-
-namespace android {
-
-struct AwesomePlayer;
-
-class StagefrightPlayer : public MediaPlayerInterface {
-public:
-    StagefrightPlayer();
-    virtual ~StagefrightPlayer();
-
-    virtual status_t initCheck();
-
-    virtual status_t setUID(uid_t uid);
-
-    virtual status_t setDataSource(
-            const sp<IMediaHTTPService> &httpService,
-            const char *url,
-            const KeyedVector<String8, String8> *headers);
-
-    virtual status_t setDataSource(int fd, int64_t offset, int64_t length);
-
-    virtual status_t setDataSource(const sp<IStreamSource> &source);
-
-    virtual status_t setVideoSurfaceTexture(
-            const sp<IGraphicBufferProducer> &bufferProducer);
-    virtual status_t prepare();
-    virtual status_t prepareAsync();
-    virtual status_t start();
-    virtual status_t stop();
-    virtual status_t pause();
-    virtual bool isPlaying();
-    virtual status_t seekTo(int msec);
-    virtual status_t getCurrentPosition(int *msec);
-    virtual status_t getDuration(int *msec);
-    virtual status_t reset();
-    virtual status_t setLooping(int loop);
-    virtual player_type playerType();
-    virtual status_t invoke(const Parcel &request, Parcel *reply);
-    virtual void setAudioSink(const sp<AudioSink> &audioSink);
-    virtual status_t setParameter(int key, const Parcel &request);
-    virtual status_t getParameter(int key, Parcel *reply);
-    virtual status_t setPlaybackSettings(const AudioPlaybackRate &rate);
-    virtual status_t getPlaybackSettings(AudioPlaybackRate *rate /* nonnull */);
-
-    virtual status_t getMetadata(
-            const media::Metadata::Filter& ids, Parcel *records);
-
-    virtual status_t dump(int fd, const Vector<String16> &args) const;
-
-private:
-    AwesomePlayer *mPlayer;
-
-    StagefrightPlayer(const StagefrightPlayer &);
-    StagefrightPlayer &operator=(const StagefrightPlayer &);
-};
-
-}  // namespace android
-
-#endif  // ANDROID_STAGEFRIGHTPLAYER_H
diff --git a/media/libmediaplayerservice/StagefrightRecorder.cpp b/media/libmediaplayerservice/StagefrightRecorder.cpp
index 36fe800..3b13f2a 100644
--- a/media/libmediaplayerservice/StagefrightRecorder.cpp
+++ b/media/libmediaplayerservice/StagefrightRecorder.cpp
@@ -41,8 +41,6 @@
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/MediaCodecSource.h>
-#include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
 #include <media/MediaProfiles.h>
 #include <camera/ICamera.h>
 #include <camera/CameraParameters.h>
@@ -1213,18 +1211,6 @@
 }
 
 status_t StagefrightRecorder::checkVideoEncoderCapabilities() {
-    /* hardware codecs must support camera source meta data mode */
-    Vector<CodecCapabilities> codecs;
-    OMXClient client;
-    CHECK_EQ(client.connect(), (status_t)OK);
-    QueryCodecs(
-            client.interface(),
-            (mVideoEncoder == VIDEO_ENCODER_H263 ? MEDIA_MIMETYPE_VIDEO_H263 :
-             mVideoEncoder == VIDEO_ENCODER_MPEG_4_SP ? MEDIA_MIMETYPE_VIDEO_MPEG4 :
-             mVideoEncoder == VIDEO_ENCODER_VP8 ? MEDIA_MIMETYPE_VIDEO_VP8 :
-             mVideoEncoder == VIDEO_ENCODER_H264 ? MEDIA_MIMETYPE_VIDEO_AVC : ""),
-            false /* decoder */, true /* hwCodec */, &codecs);
-
     if (!mCaptureFpsEnable) {
         // Dont clip for time lapse capture as encoder will have enough
         // time to encode because of slow capture rate of time lapse.
diff --git a/media/libmediaplayerservice/nuplayer/Android.mk b/media/libmediaplayerservice/nuplayer/Android.mk
index cd20837..3ea2159 100644
--- a/media/libmediaplayerservice/nuplayer/Android.mk
+++ b/media/libmediaplayerservice/nuplayer/Android.mk
@@ -34,6 +34,8 @@
 
 LOCAL_CLANG := true
 
+LOCAL_SHARED_LIBRARIES := libmedia
+
 LOCAL_MODULE:= libstagefright_nuplayer
 
 LOCAL_MODULE_TAGS := eng
diff --git a/media/libmediaplayerservice/nuplayer/GenericSource.cpp b/media/libmediaplayerservice/nuplayer/GenericSource.cpp
index 7dc9be7..45da218 100644
--- a/media/libmediaplayerservice/nuplayer/GenericSource.cpp
+++ b/media/libmediaplayerservice/nuplayer/GenericSource.cpp
@@ -467,9 +467,19 @@
 
 void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) {
     if (err != OK) {
-        mDataSource.clear();
-        mCachedSource.clear();
-        mHttpSource.clear();
+        {
+            sp<DataSource> dataSource = mDataSource;
+            sp<NuCachedSource2> cachedSource = mCachedSource;
+            sp<DataSource> httpSource = mHttpSource;
+            {
+                Mutex::Autolock _l(mDisconnectLock);
+                mDataSource.clear();
+                mDecryptHandle = NULL;
+                mDrmManagerClient = NULL;
+                mCachedSource.clear();
+                mHttpSource.clear();
+            }
+        }
         mBitrate = -1;
 
         cancelPollBuffering();
@@ -522,13 +532,20 @@
 }
 
 void NuPlayer::GenericSource::disconnect() {
-    if (mDataSource != NULL) {
+    sp<DataSource> dataSource, httpSource;
+    {
+        Mutex::Autolock _l(mDisconnectLock);
+        dataSource = mDataSource;
+        httpSource = mHttpSource;
+    }
+
+    if (dataSource != NULL) {
         // disconnect data source
-        if (mDataSource->flags() & DataSource::kIsCachingDataSource) {
-            static_cast<NuCachedSource2 *>(mDataSource.get())->disconnect();
+        if (dataSource->flags() & DataSource::kIsCachingDataSource) {
+            static_cast<NuCachedSource2 *>(dataSource.get())->disconnect();
         }
-    } else if (mHttpSource != NULL) {
-        static_cast<HTTPBase *>(mHttpSource.get())->disconnect();
+    } else if (httpSource != NULL) {
+        static_cast<HTTPBase *>(httpSource.get())->disconnect();
     }
 }
 
diff --git a/media/libmediaplayerservice/nuplayer/GenericSource.h b/media/libmediaplayerservice/nuplayer/GenericSource.h
index dc85d2d..ac980ef 100644
--- a/media/libmediaplayerservice/nuplayer/GenericSource.h
+++ b/media/libmediaplayerservice/nuplayer/GenericSource.h
@@ -153,6 +153,7 @@
     int32_t mPrevBufferPercentage;
 
     mutable Mutex mReadBufferLock;
+    mutable Mutex mDisconnectLock;
 
     sp<ALooper> mLooper;
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index 6ef2b3a..6b540c1 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -69,7 +69,7 @@
 };
 
 struct NuPlayer::SeekAction : public Action {
-    SeekAction(int64_t seekTimeUs)
+    explicit SeekAction(int64_t seekTimeUs)
         : mSeekTimeUs(seekTimeUs) {
     }
 
@@ -84,7 +84,7 @@
 };
 
 struct NuPlayer::ResumeDecoderAction : public Action {
-    ResumeDecoderAction(bool needNotify)
+    explicit ResumeDecoderAction(bool needNotify)
         : mNeedNotify(needNotify) {
     }
 
@@ -99,7 +99,7 @@
 };
 
 struct NuPlayer::SetSurfaceAction : public Action {
-    SetSurfaceAction(const sp<Surface> &surface)
+    explicit SetSurfaceAction(const sp<Surface> &surface)
         : mSurface(surface) {
     }
 
@@ -131,7 +131,7 @@
 };
 
 struct NuPlayer::PostMessageAction : public Action {
-    PostMessageAction(const sp<AMessage> &msg)
+    explicit PostMessageAction(const sp<AMessage> &msg)
         : mMessage(msg) {
     }
 
@@ -150,7 +150,7 @@
 struct NuPlayer::SimpleAction : public Action {
     typedef void (NuPlayer::*ActionFunc)();
 
-    SimpleAction(ActionFunc func)
+    explicit SimpleAction(ActionFunc func)
         : mFunc(func) {
     }
 
@@ -188,6 +188,7 @@
       mPlaybackSettings(AUDIO_PLAYBACK_RATE_DEFAULT),
       mVideoFpsHint(-1.f),
       mStarted(false),
+      mResetting(false),
       mSourceStarted(false),
       mPaused(false),
       mPausedByClient(false),
@@ -1076,6 +1077,12 @@
                 int32_t audio;
                 CHECK(msg->findInt32("audio", &audio));
 
+                if (audio) {
+                    mAudioEOS = false;
+                } else {
+                    mVideoEOS = false;
+                }
+
                 ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
                 if (audio && (mFlushingAudio == NONE || mFlushingAudio == FLUSHED
                         || mFlushingAudio == SHUT_DOWN)) {
@@ -1093,6 +1100,7 @@
                 int32_t reason;
                 CHECK(msg->findInt32("reason", &reason));
                 ALOGV("Tear down audio with reason %d.", reason);
+                mAudioDecoder->pause();
                 mAudioDecoder.clear();
                 ++mAudioDecoderGeneration;
                 bool needsToCreateAudioDecoder = true;
@@ -1140,6 +1148,8 @@
         {
             ALOGV("kWhatReset");
 
+            mResetting = true;
+
             mDeferredActions.push_back(
                     new FlushDecoderAction(
                         FLUSH_CMD_SHUTDOWN /* audio */,
@@ -1222,7 +1232,8 @@
 }
 
 void NuPlayer::onResume() {
-    if (!mPaused) {
+    if (!mPaused || mResetting) {
+        ALOGD_IF(mResetting, "resetting, onResume discarded");
         return;
     }
     mPaused = false;
@@ -1489,7 +1500,9 @@
 }
 
 status_t NuPlayer::instantiateDecoder(bool audio, sp<DecoderBase> *decoder) {
-    if (*decoder != NULL) {
+    // The audio decoder could be cleared by tear down. If still in shut down
+    // process, no need to create a new audio decoder.
+    if (*decoder != NULL || (audio && mFlushingAudio == SHUT_DOWN)) {
         return OK;
     }
 
@@ -1676,8 +1689,10 @@
     // Make sure we don't continue to scan sources until we finish flushing.
     ++mScanSourcesGeneration;
     if (mScanSourcesPending) {
-        mDeferredActions.push_back(
-                new SimpleAction(&NuPlayer::performScanSources));
+        if (!needShutdown) {
+            mDeferredActions.push_back(
+                    new SimpleAction(&NuPlayer::performScanSources));
+        }
         mScanSourcesPending = false;
     }
 
@@ -1923,6 +1938,7 @@
     }
 
     mStarted = false;
+    mResetting = false;
     mSourceStarted = false;
 }
 
@@ -2183,7 +2199,7 @@
             int posMs;
             int64_t timeUs, posUs;
             driver->getCurrentPosition(&posMs);
-            posUs = posMs * 1000;
+            posUs = (int64_t) posMs * 1000ll;
             CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
 
             if (posUs < timeUs) {
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.h b/media/libmediaplayerservice/nuplayer/NuPlayer.h
index c9f0bbd..4cec1a1 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.h
@@ -197,6 +197,7 @@
     AVSyncSettings mSyncSettings;
     float mVideoFpsHint;
     bool mStarted;
+    bool mResetting;
     bool mSourceStarted;
 
     // Actual pause state, either as requested by client or due to buffering.
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerCCDecoder.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerCCDecoder.cpp
index ac3c6b6..2c07f28 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerCCDecoder.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerCCDecoder.cpp
@@ -235,6 +235,12 @@
             payload_size += last_byte;
         } while (last_byte == 0xFF);
 
+        if (payload_size > SIZE_MAX / 8
+                || !br.atLeastNumBitsLeft(payload_size * 8)) {
+            ALOGV("Malformed SEI payload");
+            break;
+        }
+
         // sei_payload()
         if (payload_type == 4) {
             bool isCC = false;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
index 3646828..ce87f87 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
@@ -69,7 +69,6 @@
       mIsSecure(false),
       mFormatChangePending(false),
       mTimeChangePending(false),
-      mPaused(true),
       mResumePending(false),
       mComponentName("decoder") {
     mCodecLooper = new ALooper;
@@ -635,8 +634,11 @@
             flags = AUDIO_OUTPUT_FLAG_NONE;
         }
 
-        mRenderer->openAudioSink(
+        status_t err = mRenderer->openAudioSink(
                 format, false /* offloadOnly */, hasVideo, flags, NULL /* isOffloaed */);
+        if (err != OK) {
+            handleError(err);
+        }
     }
 }
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.h b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.h
index eeb4af4..ae08b4b 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.h
@@ -91,7 +91,6 @@
     bool mFormatChangePending;
     bool mTimeChangePending;
 
-    bool mPaused;
     bool mResumePending;
     AString mComponentName;
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDecoderBase.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDecoderBase.cpp
index 7e76842..04bb61c 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDecoderBase.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDecoderBase.cpp
@@ -31,6 +31,7 @@
 NuPlayer::DecoderBase::DecoderBase(const sp<AMessage> &notify)
     :  mNotify(notify),
        mBufferGeneration(0),
+       mPaused(false),
        mStats(new AMessage),
        mRequestInputBuffersPending(false) {
     // Every decoder has its own looper because MediaCodec operations
@@ -83,6 +84,13 @@
     msg->post();
 }
 
+void NuPlayer::DecoderBase::pause() {
+    sp<AMessage> msg = new AMessage(kWhatPause, this);
+
+    sp<AMessage> response;
+    PostAndAwaitResponse(msg, &response);
+}
+
 status_t NuPlayer::DecoderBase::getInputBuffers(Vector<sp<ABuffer> > *buffers) const {
     sp<AMessage> msg = new AMessage(kWhatGetInputBuffers, this);
     msg->setPointer("buffers", buffers);
@@ -146,6 +154,17 @@
             break;
         }
 
+        case kWhatPause:
+        {
+            sp<AReplyToken> replyID;
+            CHECK(msg->senderAwaitsResponse(&replyID));
+
+            mPaused = true;
+
+            (new AMessage)->postReply(replyID);
+            break;
+        }
+
         case kWhatGetInputBuffers:
         {
             sp<AReplyToken> replyID;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDecoderBase.h b/media/libmediaplayerservice/nuplayer/NuPlayerDecoderBase.h
index b0dc01d..a334ec5 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDecoderBase.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDecoderBase.h
@@ -36,6 +36,9 @@
     void init();
     void setParameters(const sp<AMessage> &params);
 
+    // Synchronous call to ensure decoder will not request or send out data.
+    void pause();
+
     void setRenderer(const sp<Renderer> &renderer);
     virtual status_t setVideoSurface(const sp<Surface> &) { return INVALID_OPERATION; }
 
@@ -78,6 +81,7 @@
 
     sp<AMessage> mNotify;
     int32_t mBufferGeneration;
+    bool mPaused;
     sp<AMessage> mStats;
 
 private:
@@ -85,6 +89,7 @@
         kWhatConfigure           = 'conf',
         kWhatSetParameters       = 'setP',
         kWhatSetRenderer         = 'setR',
+        kWhatPause               = 'paus',
         kWhatGetInputBuffers     = 'gInB',
         kWhatRequestInputBuffers = 'reqB',
         kWhatFlush               = 'flus',
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDecoderPassThrough.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDecoderPassThrough.cpp
index 30146c4..514ec1a 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDecoderPassThrough.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDecoderPassThrough.cpp
@@ -47,7 +47,6 @@
       mSource(source),
       mRenderer(renderer),
       mSkipRenderingUntilMediaTimeUs(-1ll),
-      mPaused(false),
       mReachedEOS(true),
       mPendingAudioErr(OK),
       mPendingBuffersToDrain(0),
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDecoderPassThrough.h b/media/libmediaplayerservice/nuplayer/NuPlayerDecoderPassThrough.h
index db33e87..5850efa 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDecoderPassThrough.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDecoderPassThrough.h
@@ -52,7 +52,6 @@
     sp<Source> mSource;
     sp<Renderer> mRenderer;
     int64_t mSkipRenderingUntilMediaTimeUs;
-    bool mPaused;
 
     bool    mReachedEOS;
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
index 6419be0..f288c36 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
@@ -362,9 +362,9 @@
 }
 
 status_t NuPlayerDriver::setPlaybackSettings(const AudioPlaybackRate &rate) {
-    Mutex::Autolock autoLock(mLock);
     status_t err = mPlayer->setPlaybackSettings(rate);
     if (err == OK) {
+        Mutex::Autolock autoLock(mLock);
         if (rate.mSpeed == 0.f && mState == STATE_RUNNING) {
             mState = STATE_PAUSED;
             // try to update position
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
index 04a46f4..c6a7805 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
@@ -106,10 +106,12 @@
       mNotifyCompleteVideo(false),
       mSyncQueues(false),
       mPaused(false),
+      mPauseDrainAudioAllowedUs(0),
       mVideoSampleReceived(false),
       mVideoRenderingStarted(false),
       mVideoRenderingStartGeneration(0),
       mAudioRenderingStartGeneration(0),
+      mRenderingDataDelivered(false),
       mAudioOffloadPauseTimeoutGeneration(0),
       mAudioTornDown(false),
       mCurrentOffloadInfo(AUDIO_INFO_INITIALIZER),
@@ -630,6 +632,14 @@
         return;
     }
 
+    // FIXME: if paused, wait until AudioTrack stop() is complete before delivering data.
+    if (mPaused) {
+        const int64_t diffUs = mPauseDrainAudioAllowedUs - ALooper::GetNowUs();
+        if (diffUs > delayUs) {
+            delayUs = diffUs;
+        }
+    }
+
     mDrainAudioQueuePending = true;
     sp<AMessage> msg = new AMessage(kWhatDrainAudioQueue, this);
     msg->setInt32("drainGeneration", mAudioDrainGeneration);
@@ -639,11 +649,16 @@
 void NuPlayer::Renderer::prepareForMediaRenderingStart_l() {
     mAudioRenderingStartGeneration = mAudioDrainGeneration;
     mVideoRenderingStartGeneration = mVideoDrainGeneration;
+    mRenderingDataDelivered = false;
 }
 
 void NuPlayer::Renderer::notifyIfMediaRenderingStarted_l() {
     if (mVideoRenderingStartGeneration == mVideoDrainGeneration &&
         mAudioRenderingStartGeneration == mAudioDrainGeneration) {
+        mRenderingDataDelivered = true;
+        if (mPaused) {
+            return;
+        }
         mVideoRenderingStartGeneration = -1;
         mAudioRenderingStartGeneration = -1;
 
@@ -798,6 +813,10 @@
 }
 
 bool NuPlayer::Renderer::onDrainAudioQueue() {
+    // do not drain audio during teardown as queued buffers may be invalid.
+    if (mAudioTornDown) {
+        return false;
+    }
     // TODO: This call to getPosition checks if AudioTrack has been created
     // in AudioSink before draining audio. If AudioTrack doesn't exist, then
     // CHECKs on getPosition will fail.
@@ -877,6 +896,8 @@
                 ALOGV("AudioSink write would block when writing %zu bytes", copy);
             } else {
                 ALOGE("AudioSink write error(%zd) when writing %zu bytes", written, copy);
+                // This can only happen when AudioSink was opened with doNotReconnect flag set to
+                // true, in which case the NuPlayer will handle the reconnect.
                 notifyAudioTearDown();
             }
             break;
@@ -895,6 +916,13 @@
 
         {
             Mutex::Autolock autoLock(mLock);
+            int64_t maxTimeMedia;
+            maxTimeMedia =
+                mAnchorTimeMediaUs +
+                        (int64_t)(max((long long)mNumFramesWritten - mAnchorNumFramesWritten, 0LL)
+                                * 1000LL * mAudioSink->msecsPerFrame());
+            mMediaClock->updateMaxTimeMedia(maxTimeMedia);
+
             notifyIfMediaRenderingStarted_l();
         }
 
@@ -921,15 +949,6 @@
             break;
         }
     }
-    int64_t maxTimeMedia;
-    {
-        Mutex::Autolock autoLock(mLock);
-        maxTimeMedia =
-            mAnchorTimeMediaUs +
-                    (int64_t)(max((long long)mNumFramesWritten - mAnchorNumFramesWritten, 0LL)
-                            * 1000LL * mAudioSink->msecsPerFrame());
-    }
-    mMediaClock->updateMaxTimeMedia(maxTimeMedia);
 
     // calculate whether we need to reschedule another write.
     bool reschedule = !mAudioQueue.empty()
@@ -943,6 +962,10 @@
 int64_t NuPlayer::Renderer::getDurationUsIfPlayedAtSampleRate(uint32_t numFrames) {
     int32_t sampleRate = offloadingAudio() ?
             mCurrentOffloadInfo.sample_rate : mCurrentPcmInfo.mSampleRate;
+    if (sampleRate == 0) {
+        ALOGE("sampleRate is 0 in %s mode", offloadingAudio() ? "offload" : "non-offload");
+        return 0;
+    }
     // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
     return (int64_t)((int32_t)numFrames * 1000000LL / sampleRate);
 }
@@ -1019,6 +1042,9 @@
                 mMediaClock->updateAnchor(mediaTimeUs, nowUs, mediaTimeUs);
                 mAnchorTimeMediaUs = mediaTimeUs;
                 realTimeUs = nowUs;
+            } else if (!mVideoSampleReceived) {
+                // Always render the first video frame.
+                realTimeUs = nowUs;
             } else {
                 realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
             }
@@ -1079,7 +1105,7 @@
         return;
     }
 
-    int64_t nowUs = -1;
+    int64_t nowUs = ALooper::GetNowUs();
     int64_t realTimeUs;
     if (mFlags & FLAG_REAL_TIME) {
         CHECK(entry->mBuffer->meta()->findInt64("timeUs", &realTimeUs));
@@ -1087,16 +1113,12 @@
         int64_t mediaTimeUs;
         CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
 
-        nowUs = ALooper::GetNowUs();
         realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
     }
 
     bool tooLate = false;
 
     if (!mPaused) {
-        if (nowUs == -1) {
-            nowUs = ALooper::GetNowUs();
-        }
         setVideoLateByUs(nowUs - realTimeUs);
         tooLate = (mVideoLateByUs > 40000);
 
@@ -1120,6 +1142,12 @@
         }
     }
 
+    // Always render the first video frame while keeping stats on A/V sync.
+    if (!mVideoSampleReceived) {
+        realTimeUs = nowUs;
+        tooLate = false;
+    }
+
     entry->mNotifyConsumed->setInt64("timestampNs", realTimeUs * 1000ll);
     entry->mNotifyConsumed->setInt32("render", !tooLate);
     entry->mNotifyConsumed->post();
@@ -1338,8 +1366,16 @@
             mAudioSink->flush();
             // Call stop() to signal to the AudioSink to completely fill the
             // internal buffer before resuming playback.
+            // FIXME: this is ignored after flush().
             mAudioSink->stop();
-            if (!mPaused) {
+            if (mPaused) {
+                // Race condition: if renderer is paused and audio sink is stopped,
+                // we need to make sure that the audio track buffer fully drains
+                // before delivering data.
+                // FIXME: remove this if we can detect if stop() is complete.
+                const int delayUs = 2 * 50 * 1000; // (2 full mixer thread cycles at 50ms)
+                mPauseDrainAudioAllowedUs = ALooper::GetNowUs() + delayUs;
+            } else {
                 mAudioSink->start();
             }
             mNumFramesWritten = 0;
@@ -1471,6 +1507,7 @@
         cancelAudioOffloadPauseTimeout();
         status_t err = mAudioSink->start();
         if (err != OK) {
+            ALOGE("cannot start AudioSink err %d", err);
             notifyAudioTearDown();
         }
     }
@@ -1478,7 +1515,10 @@
     {
         Mutex::Autolock autoLock(mLock);
         mPaused = false;
-
+        // rendering started message may have been delayed if we were paused.
+        if (mRenderingDataDelivered) {
+            notifyIfMediaRenderingStarted_l();
+        }
         // configure audiosink as we did not do it when pausing
         if (mAudioSink != NULL && mAudioSink->ready()) {
             mAudioSink->setPlaybackRate(mPlaybackSettings);
@@ -1764,6 +1804,12 @@
         const uint32_t frameCount =
                 (unsigned long long)sampleRate * getAudioSinkPcmMsSetting() / 1000;
 
+        // The doNotReconnect means AudioSink will signal back and let NuPlayer to re-construct
+        // AudioSink. We don't want this when there's video because it will cause a video seek to
+        // the previous I frame. But we do want this when there's only audio because it will give
+        // NuPlayer a chance to switch from non-offload mode to offload mode.
+        // So we only set doNotReconnect when there's no video.
+        const bool doNotReconnect = !hasVideo;
         status_t err = mAudioSink->open(
                     sampleRate,
                     numChannels,
@@ -1774,13 +1820,14 @@
                     mUseAudioCallback ? this : NULL,
                     (audio_output_flags_t)pcmFlags,
                     NULL,
-                    true /* doNotReconnect */,
+                    doNotReconnect,
                     frameCount);
         if (err == OK) {
             err = mAudioSink->setPlaybackRate(mPlaybackSettings);
         }
         if (err != OK) {
             ALOGW("openAudioSink: non offloaded open failed status: %d", err);
+            mAudioSink->close();
             mCurrentPcmInfo = AUDIO_PCMINFO_INITIALIZER;
             return err;
         }
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
index 3e65649..9479c31 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
@@ -170,11 +170,13 @@
 
     // modified on only renderer's thread.
     bool mPaused;
+    int64_t mPauseDrainAudioAllowedUs; // time when we can drain/deliver audio in pause mode.
 
     bool mVideoSampleReceived;
     bool mVideoRenderingStarted;
     int32_t mVideoRenderingStartGeneration;
     int32_t mAudioRenderingStartGeneration;
+    bool mRenderingDataDelivered;
 
     int64_t mLastPositionUpdateUs;
 
diff --git a/media/libmediaplayerservice/nuplayer/RTSPSource.cpp b/media/libmediaplayerservice/nuplayer/RTSPSource.cpp
index 58ff113..af0351e 100644
--- a/media/libmediaplayerservice/nuplayer/RTSPSource.cpp
+++ b/media/libmediaplayerservice/nuplayer/RTSPSource.cpp
@@ -134,7 +134,9 @@
             return;
         }
     }
-    mHandler->pause();
+    if (mHandler != NULL) {
+        mHandler->pause();
+    }
 }
 
 void NuPlayer::RTSPSource::resume() {
diff --git a/media/libmediaplayerservice/nuplayer/StreamingSource.cpp b/media/libmediaplayerservice/nuplayer/StreamingSource.cpp
index 0246b59..d4c88de 100644
--- a/media/libmediaplayerservice/nuplayer/StreamingSource.cpp
+++ b/media/libmediaplayerservice/nuplayer/StreamingSource.cpp
@@ -32,6 +32,8 @@
 
 namespace android {
 
+const int32_t kNumListenerQueuePackets = 80;
+
 NuPlayer::StreamingSource::StreamingSource(
         const sp<AMessage> &notify,
         const sp<IStreamSource> &source)
@@ -84,7 +86,7 @@
 }
 
 void NuPlayer::StreamingSource::onReadBuffer() {
-    for (int32_t i = 0; i < 50; ++i) {
+    for (int32_t i = 0; i < kNumListenerQueuePackets; ++i) {
         char buffer[188];
         sp<AMessage> extra;
         ssize_t n = mStreamListener->read(buffer, sizeof(buffer), &extra);
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index 0b81b80..069325f 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -41,7 +41,6 @@
 #include <media/stagefright/MediaCodecList.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
 #include <media/stagefright/PersistentSurface.h>
 #include <media/stagefright/SurfaceUtils.h>
 #include <media/hardware/HardwareAPI.h>
@@ -56,6 +55,10 @@
 
 namespace android {
 
+enum {
+    kMaxIndicesToCheck = 32, // used when enumerating supported formats and profiles
+};
+
 // OMX errors are directly mapped into status_t range if
 // there is no corresponding MediaError status code.
 // Use the statusFromOMXError(int32_t omxError) function.
@@ -213,7 +216,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::BaseState : public AState {
-    BaseState(ACodec *codec, const sp<AState> &parentState = NULL);
+    explicit BaseState(ACodec *codec, const sp<AState> &parentState = NULL);
 
 protected:
     enum PortMode {
@@ -264,7 +267,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::DeathNotifier : public IBinder::DeathRecipient {
-    DeathNotifier(const sp<AMessage> &notify)
+    explicit DeathNotifier(const sp<AMessage> &notify)
         : mNotify(notify) {
     }
 
@@ -282,7 +285,7 @@
 };
 
 struct ACodec::UninitializedState : public ACodec::BaseState {
-    UninitializedState(ACodec *codec);
+    explicit UninitializedState(ACodec *codec);
 
 protected:
     virtual bool onMessageReceived(const sp<AMessage> &msg);
@@ -300,7 +303,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::LoadedState : public ACodec::BaseState {
-    LoadedState(ACodec *codec);
+    explicit LoadedState(ACodec *codec);
 
 protected:
     virtual bool onMessageReceived(const sp<AMessage> &msg);
@@ -323,7 +326,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::LoadedToIdleState : public ACodec::BaseState {
-    LoadedToIdleState(ACodec *codec);
+    explicit LoadedToIdleState(ACodec *codec);
 
 protected:
     virtual bool onMessageReceived(const sp<AMessage> &msg);
@@ -339,7 +342,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::IdleToExecutingState : public ACodec::BaseState {
-    IdleToExecutingState(ACodec *codec);
+    explicit IdleToExecutingState(ACodec *codec);
 
 protected:
     virtual bool onMessageReceived(const sp<AMessage> &msg);
@@ -353,7 +356,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::ExecutingState : public ACodec::BaseState {
-    ExecutingState(ACodec *codec);
+    explicit ExecutingState(ACodec *codec);
 
     void submitRegularOutputBuffers();
     void submitOutputMetaBuffers();
@@ -383,7 +386,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::OutputPortSettingsChangedState : public ACodec::BaseState {
-    OutputPortSettingsChangedState(ACodec *codec);
+    explicit OutputPortSettingsChangedState(ACodec *codec);
 
 protected:
     virtual PortMode getPortMode(OMX_U32 portIndex);
@@ -400,7 +403,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::ExecutingToIdleState : public ACodec::BaseState {
-    ExecutingToIdleState(ACodec *codec);
+    explicit ExecutingToIdleState(ACodec *codec);
 
 protected:
     virtual bool onMessageReceived(const sp<AMessage> &msg);
@@ -422,7 +425,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::IdleToLoadedState : public ACodec::BaseState {
-    IdleToLoadedState(ACodec *codec);
+    explicit IdleToLoadedState(ACodec *codec);
 
 protected:
     virtual bool onMessageReceived(const sp<AMessage> &msg);
@@ -437,7 +440,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct ACodec::FlushingState : public ACodec::BaseState {
-    FlushingState(ACodec *codec);
+    explicit FlushingState(ACodec *codec);
 
 protected:
     virtual bool onMessageReceived(const sp<AMessage> &msg);
@@ -491,7 +494,8 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 ACodec::ACodec()
-    : mQuirks(0),
+    : mSampleRate(0),
+      mQuirks(0),
       mNode(0),
       mNativeWindowUsageBits(0),
       mSentFormat(false),
@@ -824,8 +828,8 @@
 
                 uint32_t requiresAllocateBufferBit =
                     (portIndex == kPortIndexInput)
-                        ? OMXCodec::kRequiresAllocateBufferOnInputPorts
-                        : OMXCodec::kRequiresAllocateBufferOnOutputPorts;
+                        ? kRequiresAllocateBufferOnInputPorts
+                        : kRequiresAllocateBufferOnOutputPorts;
 
                 if ((portIndex == kPortIndexInput && (mFlags & kFlagIsSecure))
                         || (portIndex == kPortIndexOutput && usingMetadataOnEncoderOutput())) {
@@ -1525,6 +1529,21 @@
 
 status_t ACodec::setComponentRole(
         bool isEncoder, const char *mime) {
+    const char *role = getComponentRole(isEncoder, mime);
+    if (role == NULL) {
+        return BAD_VALUE;
+    }
+    status_t err = setComponentRole(mOMX, mNode, role);
+    if (err != OK) {
+        ALOGW("[%s] Failed to set standard component role '%s'.",
+             mComponentName.c_str(), role);
+    }
+    return err;
+}
+
+//static
+const char *ACodec::getComponentRole(
+        bool isEncoder, const char *mime) {
     struct MimeToRole {
         const char *mime;
         const char *decoderRole;
@@ -1589,35 +1608,27 @@
     }
 
     if (i == kNumMimeToRole) {
-        return ERROR_UNSUPPORTED;
+        return NULL;
     }
 
-    const char *role =
-        isEncoder ? kMimeToRole[i].encoderRole
+    return isEncoder ? kMimeToRole[i].encoderRole
                   : kMimeToRole[i].decoderRole;
+}
 
-    if (role != NULL) {
-        OMX_PARAM_COMPONENTROLETYPE roleParams;
-        InitOMXParams(&roleParams);
+//static
+status_t ACodec::setComponentRole(
+        const sp<IOMX> &omx, IOMX::node_id node, const char *role) {
+    OMX_PARAM_COMPONENTROLETYPE roleParams;
+    InitOMXParams(&roleParams);
 
-        strncpy((char *)roleParams.cRole,
-                role, OMX_MAX_STRINGNAME_SIZE - 1);
+    strncpy((char *)roleParams.cRole,
+            role, OMX_MAX_STRINGNAME_SIZE - 1);
 
-        roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
+    roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
 
-        status_t err = mOMX->setParameter(
-                mNode, OMX_IndexParamStandardComponentRole,
-                &roleParams, sizeof(roleParams));
-
-        if (err != OK) {
-            ALOGW("[%s] Failed to set standard component role '%s'.",
-                 mComponentName.c_str(), role);
-
-            return err;
-        }
-    }
-
-    return OK;
+    return omx->setParameter(
+            node, OMX_IndexParamStandardComponentRole,
+            &roleParams, sizeof(roleParams));
 }
 
 status_t ACodec::configureCodec(
@@ -2272,9 +2283,8 @@
     InitOMXParams(&format);
 
     format.nPortIndex = portIndex;
-    for (OMX_U32 index = 0;; ++index) {
+    for (OMX_U32 index = 0; index <= kMaxIndicesToCheck; ++index) {
         format.nIndex = index;
-
         status_t err = mOMX->getParameter(
                 mNode, OMX_IndexParamAudioPortFormat,
                 &format, sizeof(format));
@@ -2286,6 +2296,13 @@
         if (format.eEncoding == desiredFormat) {
             break;
         }
+
+        if (index == kMaxIndicesToCheck) {
+            ALOGW("[%s] stopping checking formats after %u: %s(%x)",
+                    mComponentName.c_str(), index,
+                    asString(format.eEncoding), format.eEncoding);
+            return ERROR_UNSUPPORTED;
+        }
     }
 
     return mOMX->setParameter(
@@ -2436,6 +2453,7 @@
     } else {
         ALOGW("did not set AudioAndroidAacPresentation due to error %d when setting AudioAac", res);
     }
+    mSampleRate = sampleRate;
     return res;
 }
 
@@ -2705,8 +2723,7 @@
     format.nIndex = 0;
     bool found = false;
 
-    OMX_U32 index = 0;
-    for (;;) {
+    for (OMX_U32 index = 0; index <= kMaxIndicesToCheck; ++index) {
         format.nIndex = index;
         status_t err = mOMX->getParameter(
                 mNode, OMX_IndexParamVideoPortFormat,
@@ -2751,7 +2768,12 @@
             break;
         }
 
-        ++index;
+        if (index == kMaxIndicesToCheck) {
+            ALOGW("[%s] stopping checking formats after %u: %s(%x)/%s(%x)",
+                    mComponentName.c_str(), index,
+                    asString(format.eCompressionFormat), format.eCompressionFormat,
+                    asString(format.eColorFormat), format.eColorFormat);
+        }
     }
 
     if (!found) {
@@ -3624,7 +3646,8 @@
     InitOMXParams(&params);
     params.nPortIndex = kPortIndexOutput;
 
-    for (params.nProfileIndex = 0;; ++params.nProfileIndex) {
+    for (OMX_U32 index = 0; index <= kMaxIndicesToCheck; ++index) {
+        params.nProfileIndex = index;
         status_t err = mOMX->getParameter(
                 mNode,
                 OMX_IndexParamVideoProfileLevelQuerySupported,
@@ -3641,7 +3664,14 @@
         if (profile == supportedProfile && level <= supportedLevel) {
             return OK;
         }
+
+        if (index == kMaxIndicesToCheck) {
+            ALOGW("[%s] stopping checking profiles after %u: %x/%x",
+                    mComponentName.c_str(), index,
+                    params.eProfile, params.eLevel);
+        }
     }
+    return ERROR_UNSUPPORTED;
 }
 
 status_t ACodec::configureBitrate(
@@ -3840,7 +3870,7 @@
         fmt != OMX_COLOR_FormatYUV420PackedPlanar &&
         fmt != OMX_COLOR_FormatYUV420SemiPlanar &&
         fmt != OMX_COLOR_FormatYUV420PackedSemiPlanar &&
-        fmt != HAL_PIXEL_FORMAT_YV12) {
+        fmt != (OMX_COLOR_FORMATTYPE)HAL_PIXEL_FORMAT_YV12) {
         ALOGW("do not know color format 0x%x = %d", fmt, fmt);
         return false;
     }
@@ -4436,8 +4466,14 @@
         reply->setRect("crop", left, top, right + 1, bottom + 1);
     } else if (mime == MEDIA_MIMETYPE_AUDIO_RAW &&
                (mEncoderDelay || mEncoderPadding)) {
-        int32_t channelCount;
+        int32_t channelCount, sampleRate;
         CHECK(notify->findInt32("channel-count", &channelCount));
+        CHECK(mOutputFormat->findInt32("sample-rate", &sampleRate));
+        if (mSampleRate != 0 && sampleRate != 0) {
+            mEncoderDelay = mEncoderDelay * sampleRate / mSampleRate;
+            mEncoderPadding = mEncoderPadding * sampleRate / mSampleRate;
+            mSampleRate = sampleRate;
+        }
         if (mSkipCutBuffer != NULL) {
             size_t prevbufsize = mSkipCutBuffer->size();
             if (prevbufsize != 0) {
@@ -5465,7 +5501,7 @@
         mDeathNotifier.clear();
     }
 
-    Vector<OMXCodec::CodecNameAndQuirks> matchingCodecs;
+    Vector<AString> matchingCodecs;
 
     AString mime;
 
@@ -5473,13 +5509,9 @@
     uint32_t quirks = 0;
     int32_t encoder = false;
     if (msg->findString("componentName", &componentName)) {
-        ssize_t index = matchingCodecs.add();
-        OMXCodec::CodecNameAndQuirks *entry = &matchingCodecs.editItemAt(index);
-        entry->mName = String8(componentName.c_str());
-
-        if (!OMXCodec::findCodecQuirks(
-                    componentName.c_str(), &entry->mQuirks)) {
-            entry->mQuirks = 0;
+        sp<IMediaCodecList> list = MediaCodecList::getInstance();
+        if (list != NULL && list->findCodecByName(componentName.c_str()) >= 0) {
+            matchingCodecs.add(componentName);
         }
     } else {
         CHECK(msg->findString("mime", &mime));
@@ -5488,11 +5520,10 @@
             encoder = false;
         }
 
-        OMXCodec::findMatchingCodecs(
+        MediaCodecList::findMatchingCodecs(
                 mime.c_str(),
                 encoder, // createEncoder
-                NULL,  // matchComponentName
-                0,     // flags
+                0,       // flags
                 &matchingCodecs);
     }
 
@@ -5502,8 +5533,8 @@
     status_t err = NAME_NOT_FOUND;
     for (size_t matchIndex = 0; matchIndex < matchingCodecs.size();
             ++matchIndex) {
-        componentName = matchingCodecs.itemAt(matchIndex).mName.string();
-        quirks = matchingCodecs.itemAt(matchIndex).mQuirks;
+        componentName = matchingCodecs[matchIndex];
+        quirks = MediaCodecList::getQuirksFor(componentName.c_str());
 
         pid_t tid = gettid();
         int prevPriority = androidGetThreadPriority(tid);
@@ -6863,4 +6894,190 @@
     }
 }
 
+status_t ACodec::queryCapabilities(
+        const AString &name, const AString &mime, bool isEncoder,
+        sp<MediaCodecInfo::Capabilities> *caps) {
+    (*caps).clear();
+    const char *role = getComponentRole(isEncoder, mime.c_str());
+    if (role == NULL) {
+        return BAD_VALUE;
+    }
+
+    OMXClient client;
+    status_t err = client.connect();
+    if (err != OK) {
+        return err;
+    }
+
+    sp<IOMX> omx = client.interface();
+    sp<CodecObserver> observer = new CodecObserver;
+    IOMX::node_id node = 0;
+
+    err = omx->allocateNode(name.c_str(), observer, &node);
+    if (err != OK) {
+        client.disconnect();
+        return err;
+    }
+
+    err = setComponentRole(omx, node, role);
+    if (err != OK) {
+        omx->freeNode(node);
+        client.disconnect();
+        return err;
+    }
+
+    sp<MediaCodecInfo::CapabilitiesBuilder> builder = new MediaCodecInfo::CapabilitiesBuilder();
+    bool isVideo = mime.startsWithIgnoreCase("video/");
+
+    if (isVideo) {
+        OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
+        InitOMXParams(&param);
+        param.nPortIndex = isEncoder ? kPortIndexOutput : kPortIndexInput;
+
+        for (OMX_U32 index = 0; index <= kMaxIndicesToCheck; ++index) {
+            param.nProfileIndex = index;
+            status_t err = omx->getParameter(
+                    node, OMX_IndexParamVideoProfileLevelQuerySupported,
+                    &param, sizeof(param));
+            if (err != OK) {
+                break;
+            }
+            builder->addProfileLevel(param.eProfile, param.eLevel);
+
+            if (index == kMaxIndicesToCheck) {
+                ALOGW("[%s] stopping checking profiles after %u: %x/%x",
+                        name.c_str(), index,
+                        param.eProfile, param.eLevel);
+            }
+        }
+
+        // Color format query
+        // return colors in the order reported by the OMX component
+        // prefix "flexible" standard ones with the flexible equivalent
+        OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
+        InitOMXParams(&portFormat);
+        portFormat.nPortIndex = isEncoder ? kPortIndexInput : kPortIndexOutput;
+        Vector<uint32_t> supportedColors; // shadow copy to check for duplicates
+        for (OMX_U32 index = 0; index <= kMaxIndicesToCheck; ++index) {
+            portFormat.nIndex = index;
+            status_t err = omx->getParameter(
+                    node, OMX_IndexParamVideoPortFormat,
+                    &portFormat, sizeof(portFormat));
+            if (err != OK) {
+                break;
+            }
+
+            OMX_U32 flexibleEquivalent;
+            if (isFlexibleColorFormat(
+                    omx, node, portFormat.eColorFormat, false /* usingNativeWindow */,
+                    &flexibleEquivalent)) {
+                bool marked = false;
+                for (size_t i = 0; i < supportedColors.size(); ++i) {
+                    if (supportedColors[i] == flexibleEquivalent) {
+                        marked = true;
+                        break;
+                    }
+                }
+                if (!marked) {
+                    supportedColors.push(flexibleEquivalent);
+                    builder->addColorFormat(flexibleEquivalent);
+                }
+            }
+            supportedColors.push(portFormat.eColorFormat);
+            builder->addColorFormat(portFormat.eColorFormat);
+
+            if (index == kMaxIndicesToCheck) {
+                ALOGW("[%s] stopping checking formats after %u: %s(%x)",
+                        name.c_str(), index,
+                        asString(portFormat.eColorFormat), portFormat.eColorFormat);
+            }
+        }
+    }
+
+    if (isVideo && !isEncoder) {
+        native_handle_t *sidebandHandle = NULL;
+        if (omx->configureVideoTunnelMode(
+                node, kPortIndexOutput, OMX_TRUE, 0, &sidebandHandle) == OK) {
+            // tunneled playback includes adaptive playback
+            builder->addFlags(MediaCodecInfo::Capabilities::kFlagSupportsAdaptivePlayback
+                    | MediaCodecInfo::Capabilities::kFlagSupportsTunneledPlayback);
+        } else if (omx->storeMetaDataInBuffers(
+                node, kPortIndexOutput, OMX_TRUE) == OK ||
+            omx->prepareForAdaptivePlayback(
+                node, kPortIndexOutput, OMX_TRUE,
+                1280 /* width */, 720 /* height */) == OK) {
+            builder->addFlags(MediaCodecInfo::Capabilities::kFlagSupportsAdaptivePlayback);
+        }
+    }
+
+    *caps = builder;
+    omx->freeNode(node);
+    client.disconnect();
+    return OK;
+}
+
+// These are supposed be equivalent to the logic in
+// "audio_channel_out_mask_from_count".
+//static
+status_t ACodec::getOMXChannelMapping(size_t numChannels, OMX_AUDIO_CHANNELTYPE map[]) {
+    switch (numChannels) {
+        case 1:
+            map[0] = OMX_AUDIO_ChannelCF;
+            break;
+        case 2:
+            map[0] = OMX_AUDIO_ChannelLF;
+            map[1] = OMX_AUDIO_ChannelRF;
+            break;
+        case 3:
+            map[0] = OMX_AUDIO_ChannelLF;
+            map[1] = OMX_AUDIO_ChannelRF;
+            map[2] = OMX_AUDIO_ChannelCF;
+            break;
+        case 4:
+            map[0] = OMX_AUDIO_ChannelLF;
+            map[1] = OMX_AUDIO_ChannelRF;
+            map[2] = OMX_AUDIO_ChannelLR;
+            map[3] = OMX_AUDIO_ChannelRR;
+            break;
+        case 5:
+            map[0] = OMX_AUDIO_ChannelLF;
+            map[1] = OMX_AUDIO_ChannelRF;
+            map[2] = OMX_AUDIO_ChannelCF;
+            map[3] = OMX_AUDIO_ChannelLR;
+            map[4] = OMX_AUDIO_ChannelRR;
+            break;
+        case 6:
+            map[0] = OMX_AUDIO_ChannelLF;
+            map[1] = OMX_AUDIO_ChannelRF;
+            map[2] = OMX_AUDIO_ChannelCF;
+            map[3] = OMX_AUDIO_ChannelLFE;
+            map[4] = OMX_AUDIO_ChannelLR;
+            map[5] = OMX_AUDIO_ChannelRR;
+            break;
+        case 7:
+            map[0] = OMX_AUDIO_ChannelLF;
+            map[1] = OMX_AUDIO_ChannelRF;
+            map[2] = OMX_AUDIO_ChannelCF;
+            map[3] = OMX_AUDIO_ChannelLFE;
+            map[4] = OMX_AUDIO_ChannelLR;
+            map[5] = OMX_AUDIO_ChannelRR;
+            map[6] = OMX_AUDIO_ChannelCS;
+            break;
+        case 8:
+            map[0] = OMX_AUDIO_ChannelLF;
+            map[1] = OMX_AUDIO_ChannelRF;
+            map[2] = OMX_AUDIO_ChannelCF;
+            map[3] = OMX_AUDIO_ChannelLFE;
+            map[4] = OMX_AUDIO_ChannelLR;
+            map[5] = OMX_AUDIO_ChannelRR;
+            map[6] = OMX_AUDIO_ChannelLS;
+            map[7] = OMX_AUDIO_ChannelRS;
+            break;
+        default:
+            return -EINVAL;
+    }
+
+    return OK;
+}
+
 }  // namespace android
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index 1c44285..9d0dbe9 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -1,7 +1,6 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
-include frameworks/av/media/libstagefright/codecs/common/Config.mk
 
 LOCAL_SRC_FILES:=                         \
         ACodec.cpp                        \
@@ -11,11 +10,9 @@
         AMRWriter.cpp                     \
         AudioPlayer.cpp                   \
         AudioSource.cpp                   \
-        AwesomePlayer.cpp                 \
         CallbackDataSource.cpp            \
         CameraSource.cpp                  \
         CameraSourceTimeLapse.cpp         \
-        ClockEstimator.cpp                \
         CodecBase.cpp                     \
         DataSource.cpp                    \
         DataURISource.cpp                 \
@@ -49,19 +46,17 @@
         NuCachedSource2.cpp               \
         NuMediaExtractor.cpp              \
         OMXClient.cpp                     \
-        OMXCodec.cpp                      \
         OggExtractor.cpp                  \
         ProcessInfo.cpp                   \
         SampleIterator.cpp                \
         SampleTable.cpp                   \
+        SimpleDecodingSource.cpp          \
         SkipCutBuffer.cpp                 \
         StagefrightMediaScanner.cpp       \
         StagefrightMetadataRetriever.cpp  \
         SurfaceMediaSource.cpp            \
         SurfaceUtils.cpp                  \
         ThrottledSource.cpp               \
-        TimeSource.cpp                    \
-        TimedEventQueue.cpp               \
         Utils.cpp                         \
         VBRISeeker.cpp                    \
         VideoFrameScheduler.cpp           \
@@ -127,6 +122,8 @@
         libdl \
         libRScpp \
 
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libmedia
+
 LOCAL_CFLAGS += -Wno-multichar -Werror -Wno-error=deprecated-declarations -Wall
 
 # enable experiments only in userdebug and eng builds
diff --git a/media/libstagefright/AudioPlayer.cpp b/media/libstagefright/AudioPlayer.cpp
index dd9d393..68cac74 100644
--- a/media/libstagefright/AudioPlayer.cpp
+++ b/media/libstagefright/AudioPlayer.cpp
@@ -33,14 +33,11 @@
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/Utils.h>
 
-#include "include/AwesomePlayer.h"
-
 namespace android {
 
 AudioPlayer::AudioPlayer(
         const sp<MediaPlayerBase::AudioSink> &audioSink,
-        uint32_t flags,
-        AwesomePlayer *observer)
+        uint32_t flags)
     : mInputBuffer(NULL),
       mSampleRate(0),
       mLatencyUs(0),
@@ -58,8 +55,6 @@
       mFirstBufferResult(OK),
       mFirstBuffer(NULL),
       mAudioSink(audioSink),
-      mObserver(observer),
-      mPinnedTimeUs(-1ll),
       mPlaying(false),
       mStartPosUs(0),
       mCreateFlags(flags) {
@@ -256,7 +251,6 @@
 
     mStarted = true;
     mPlaying = true;
-    mPinnedTimeUs = -1ll;
 
     return OK;
 }
@@ -279,8 +273,6 @@
         } else {
             mAudioTrack->pause();
         }
-
-        mPinnedTimeUs = ALooper::GetNowUs();
     }
 
     mPlaying = false;
@@ -386,11 +378,6 @@
     static_cast<AudioPlayer *>(user)->AudioCallback(event, info);
 }
 
-bool AudioPlayer::isSeeking() {
-    Mutex::Autolock autoLock(mLock);
-    return mSeeking;
-}
-
 bool AudioPlayer::reachedEOS(status_t *finalStatus) {
     *finalStatus = OK;
 
@@ -399,15 +386,6 @@
     return mReachedEOS;
 }
 
-void AudioPlayer::notifyAudioEOS() {
-    ALOGV("AudioPlayer@0x%p notifyAudioEOS", this);
-
-    if (mObserver != NULL) {
-        mObserver->postAudioEOS(0);
-        ALOGV("Notified observer of EOS!");
-    }
-}
-
 status_t AudioPlayer::setPlaybackRate(const AudioPlaybackRate &rate) {
     if (mAudioSink.get() != NULL) {
         return mAudioSink->setPlaybackRate(rate);
@@ -443,12 +421,10 @@
     case MediaPlayerBase::AudioSink::CB_EVENT_STREAM_END:
         ALOGV("AudioSinkCallback: stream end");
         me->mReachedEOS = true;
-        me->notifyAudioEOS();
         break;
 
     case MediaPlayerBase::AudioSink::CB_EVENT_TEAR_DOWN:
         ALOGV("AudioSinkCallback: Tear down event");
-        me->mObserver->postAudioTearDown();
         break;
     }
 
@@ -467,31 +443,10 @@
 
     case AudioTrack::EVENT_STREAM_END:
         mReachedEOS = true;
-        notifyAudioEOS();
         break;
     }
 }
 
-uint32_t AudioPlayer::getNumFramesPendingPlayout() const {
-    uint32_t numFramesPlayedOut;
-    status_t err;
-
-    if (mAudioSink != NULL) {
-        err = mAudioSink->getPosition(&numFramesPlayedOut);
-    } else {
-        err = mAudioTrack->getPosition(&numFramesPlayedOut);
-    }
-
-    if (err != OK || mNumFramesPlayed < numFramesPlayedOut) {
-        return 0;
-    }
-
-    // mNumFramesPlayed is the number of frames submitted
-    // to the audio sink for playback, but not all of them
-    // may have played out by now.
-    return mNumFramesPlayed - numFramesPlayedOut;
-}
-
 size_t AudioPlayer::fillBuffer(void *data, size_t size) {
     if (mNumFramesPlayed == 0) {
         ALOGV("AudioCallback");
@@ -501,10 +456,6 @@
         return 0;
     }
 
-    bool postSeekComplete = false;
-    bool postEOS = false;
-    int64_t postEOSDelayUs = 0;
-
     size_t size_done = 0;
     size_t size_remaining = size;
     while (size_remaining > 0) {
@@ -532,9 +483,6 @@
                 }
 
                 mSeeking = false;
-                if (mObserver) {
-                    postSeekComplete = true;
-                }
             }
         }
 
@@ -567,42 +515,6 @@
                             mAudioTrack->stop();
                         }
                     } else {
-                        if (mObserver) {
-                            // We don't want to post EOS right away but only
-                            // after all frames have actually been played out.
-
-                            // These are the number of frames submitted to the
-                            // AudioTrack that you haven't heard yet.
-                            uint32_t numFramesPendingPlayout =
-                                getNumFramesPendingPlayout();
-
-                            // These are the number of frames we're going to
-                            // submit to the AudioTrack by returning from this
-                            // callback.
-                            uint32_t numAdditionalFrames = size_done / mFrameSize;
-
-                            numFramesPendingPlayout += numAdditionalFrames;
-
-                            int64_t timeToCompletionUs =
-                                (1000000ll * numFramesPendingPlayout) / mSampleRate;
-
-                            ALOGV("total number of frames played: %" PRId64 " (%lld us)",
-                                    (mNumFramesPlayed + numAdditionalFrames),
-                                    1000000ll * (mNumFramesPlayed + numAdditionalFrames)
-                                        / mSampleRate);
-
-                            ALOGV("%d frames left to play, %" PRId64 " us (%.2f secs)",
-                                 numFramesPendingPlayout,
-                                 timeToCompletionUs, timeToCompletionUs / 1E6);
-
-                            postEOS = true;
-                            if (mAudioSink->needsTrailingPadding()) {
-                                postEOSDelayUs = timeToCompletionUs + mLatencyUs;
-                            } else {
-                                postEOSDelayUs = 0;
-                            }
-                        }
-
                         mReachedEOS = true;
                     }
                 }
@@ -626,12 +538,6 @@
             // might not be able to get the exact seek time requested.
             if (refreshSeekTime) {
                 if (useOffload()) {
-                    if (postSeekComplete) {
-                        ALOGV("fillBuffer is going to post SEEK_COMPLETE");
-                        mObserver->postAudioSeekComplete();
-                        postSeekComplete = false;
-                    }
-
                     mStartPosUs = mPositionTimeMediaUs;
                     ALOGV("adjust seek time to: %.2f", mStartPosUs/ 1E6);
                 }
@@ -690,58 +596,11 @@
         Mutex::Autolock autoLock(mLock);
         mNumFramesPlayed += size_done / mFrameSize;
         mNumFramesPlayedSysTimeUs = ALooper::GetNowUs();
-
-        if (mReachedEOS) {
-            mPinnedTimeUs = mNumFramesPlayedSysTimeUs;
-        } else {
-            mPinnedTimeUs = -1ll;
-        }
-    }
-
-    if (postEOS) {
-        mObserver->postAudioEOS(postEOSDelayUs);
-    }
-
-    if (postSeekComplete) {
-        mObserver->postAudioSeekComplete();
     }
 
     return size_done;
 }
 
-int64_t AudioPlayer::getRealTimeUs() {
-    Mutex::Autolock autoLock(mLock);
-    if (useOffload()) {
-        if (mSeeking) {
-            return mSeekTimeUs;
-        }
-        mPositionTimeRealUs = getOutputPlayPositionUs_l();
-        return mPositionTimeRealUs;
-    }
-
-    return getRealTimeUsLocked();
-}
-
-int64_t AudioPlayer::getRealTimeUsLocked() const {
-    CHECK(mStarted);
-    CHECK_NE(mSampleRate, 0);
-    int64_t result = -mLatencyUs + (mNumFramesPlayed * 1000000) / mSampleRate;
-
-    // Compensate for large audio buffers, updates of mNumFramesPlayed
-    // are less frequent, therefore to get a "smoother" notion of time we
-    // compensate using system time.
-    int64_t diffUs;
-    if (mPinnedTimeUs >= 0ll) {
-        diffUs = mPinnedTimeUs;
-    } else {
-        diffUs = ALooper::GetNowUs();
-    }
-
-    diffUs -= mNumFramesPlayedSysTimeUs;
-
-    return result + diffUs;
-}
-
 int64_t AudioPlayer::getOutputPlayPositionUs_l()
 {
     uint32_t playedSamples = 0;
@@ -770,54 +629,6 @@
     return renderedDuration;
 }
 
-int64_t AudioPlayer::getMediaTimeUs() {
-    Mutex::Autolock autoLock(mLock);
-
-    if (useOffload()) {
-        if (mSeeking) {
-            return mSeekTimeUs;
-        }
-        if (mReachedEOS) {
-            int64_t durationUs;
-            mSource->getFormat()->findInt64(kKeyDuration, &durationUs);
-            return durationUs;
-        }
-        mPositionTimeRealUs = getOutputPlayPositionUs_l();
-        ALOGV("getMediaTimeUs getOutputPlayPositionUs_l() mPositionTimeRealUs %" PRId64,
-              mPositionTimeRealUs);
-        return mPositionTimeRealUs;
-    }
-
-
-    if (mPositionTimeMediaUs < 0 || mPositionTimeRealUs < 0) {
-        // mSeekTimeUs is either seek time while seeking or 0 if playback did not start.
-        return mSeekTimeUs;
-    }
-
-    int64_t realTimeOffset = getRealTimeUsLocked() - mPositionTimeRealUs;
-    if (realTimeOffset < 0) {
-        realTimeOffset = 0;
-    }
-
-    return mPositionTimeMediaUs + realTimeOffset;
-}
-
-bool AudioPlayer::getMediaTimeMapping(
-        int64_t *realtime_us, int64_t *mediatime_us) {
-    Mutex::Autolock autoLock(mLock);
-
-    if (useOffload()) {
-        mPositionTimeRealUs = getOutputPlayPositionUs_l();
-        *realtime_us = mPositionTimeRealUs;
-        *mediatime_us = mPositionTimeRealUs;
-    } else {
-        *realtime_us = mPositionTimeRealUs;
-        *mediatime_us = mPositionTimeMediaUs;
-    }
-
-    return mPositionTimeRealUs != -1 && mPositionTimeMediaUs != -1;
-}
-
 status_t AudioPlayer::seekTo(int64_t time_us) {
     Mutex::Autolock autoLock(mLock);
 
diff --git a/media/libstagefright/AudioSource.cpp b/media/libstagefright/AudioSource.cpp
index 3505844..6e4a1dd 100644
--- a/media/libstagefright/AudioSource.cpp
+++ b/media/libstagefright/AudioSource.cpp
@@ -290,6 +290,10 @@
 
 status_t AudioSource::dataCallback(const AudioRecord::Buffer& audioBuffer) {
     int64_t timeUs = systemTime() / 1000ll;
+    // Estimate the real sampling time of the 1st sample in this buffer
+    // from AudioRecord's latency. (Apply this adjustment first so that
+    // the start time logic is not affected.)
+    timeUs -= mRecord->latency() * 1000LL;
 
     ALOGV("dataCallbackTimestamp: %" PRId64 " us", timeUs);
     Mutex::Autolock autoLock(mLock);
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
deleted file mode 100644
index b451021..0000000
--- a/media/libstagefright/AwesomePlayer.cpp
+++ /dev/null
@@ -1,3048 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#undef DEBUG_HDCP
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "AwesomePlayer"
-#define ATRACE_TAG ATRACE_TAG_VIDEO
-
-#include <inttypes.h>
-
-#include <utils/Log.h>
-#include <utils/Trace.h>
-
-#include <dlfcn.h>
-
-#include "include/AwesomePlayer.h"
-#include "include/DRMExtractor.h"
-#include "include/SoftwareRenderer.h"
-#include "include/NuCachedSource2.h"
-#include "include/ThrottledSource.h"
-#include "include/MPEG2TSExtractor.h"
-#include "include/WVMExtractor.h"
-
-#include <binder/IPCThreadState.h>
-#include <binder/IServiceManager.h>
-#include <media/IMediaHTTPConnection.h>
-#include <media/IMediaHTTPService.h>
-#include <media/IMediaPlayerService.h>
-#include <media/stagefright/foundation/hexdump.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/timedtext/TimedTextDriver.h>
-#include <media/stagefright/AudioPlayer.h>
-#include <media/stagefright/ClockEstimator.h>
-#include <media/stagefright/DataSource.h>
-#include <media/stagefright/FileSource.h>
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaExtractor.h>
-#include <media/stagefright/MediaHTTP.h>
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-#include <media/stagefright/OMXCodec.h>
-#include <media/stagefright/Utils.h>
-
-#include <gui/IGraphicBufferProducer.h>
-#include <gui/Surface.h>
-
-#include <media/stagefright/foundation/AMessage.h>
-
-#include <cutils/properties.h>
-
-#define USE_SURFACE_ALLOC 1
-#define FRAME_DROP_FREQ 0
-
-namespace android {
-
-static int64_t kLowWaterMarkUs = 2000000ll;  // 2secs
-static int64_t kHighWaterMarkUs = 5000000ll;  // 5secs
-static const size_t kLowWaterMarkBytes = 40000;
-static const size_t kHighWaterMarkBytes = 200000;
-
-// maximum time in paused state when offloading audio decompression. When elapsed, the AudioPlayer
-// is destroyed to allow the audio DSP to power down.
-static int64_t kOffloadPauseMaxUs = 10000000ll;
-
-
-struct AwesomeEvent : public TimedEventQueue::Event {
-    AwesomeEvent(
-            AwesomePlayer *player,
-            void (AwesomePlayer::*method)())
-        : mPlayer(player),
-          mMethod(method) {
-    }
-
-protected:
-    virtual ~AwesomeEvent() {}
-
-    virtual void fire(TimedEventQueue * /* queue */, int64_t /* now_us */) {
-        (mPlayer->*mMethod)();
-    }
-
-private:
-    AwesomePlayer *mPlayer;
-    void (AwesomePlayer::*mMethod)();
-
-    AwesomeEvent(const AwesomeEvent &);
-    AwesomeEvent &operator=(const AwesomeEvent &);
-};
-
-struct AwesomeLocalRenderer : public AwesomeRenderer {
-    AwesomeLocalRenderer(
-            const sp<ANativeWindow> &nativeWindow, const sp<AMessage> &format)
-        : mFormat(format),
-          mTarget(new SoftwareRenderer(nativeWindow)) {
-    }
-
-    virtual void render(MediaBuffer *buffer) {
-        int64_t timeUs;
-        CHECK(buffer->meta_data()->findInt64(kKeyTime, &timeUs));
-
-        render((const uint8_t *)buffer->data() + buffer->range_offset(),
-               buffer->range_length(), timeUs, timeUs * 1000);
-    }
-
-    void render(const void *data, size_t size, int64_t mediaTimeUs, nsecs_t renderTimeNs) {
-        (void)mTarget->render(data, size, mediaTimeUs, renderTimeNs, NULL, mFormat);
-    }
-
-protected:
-    virtual ~AwesomeLocalRenderer() {
-        delete mTarget;
-        mTarget = NULL;
-    }
-
-private:
-    sp<AMessage> mFormat;
-    SoftwareRenderer *mTarget;
-
-    AwesomeLocalRenderer(const AwesomeLocalRenderer &);
-    AwesomeLocalRenderer &operator=(const AwesomeLocalRenderer &);;
-};
-
-struct AwesomeNativeWindowRenderer : public AwesomeRenderer {
-    AwesomeNativeWindowRenderer(
-            const sp<ANativeWindow> &nativeWindow,
-            int32_t rotationDegrees)
-        : mNativeWindow(nativeWindow) {
-        applyRotation(rotationDegrees);
-    }
-
-    virtual void render(MediaBuffer *buffer) {
-        ATRACE_CALL();
-        int64_t timeUs;
-        CHECK(buffer->meta_data()->findInt64(kKeyTime, &timeUs));
-        native_window_set_buffers_timestamp(mNativeWindow.get(), timeUs * 1000);
-        status_t err = mNativeWindow->queueBuffer(
-                mNativeWindow.get(), buffer->graphicBuffer().get(), -1);
-        if (err != 0) {
-            ALOGE("queueBuffer failed with error %s (%d)", strerror(-err),
-                    -err);
-            return;
-        }
-
-        sp<MetaData> metaData = buffer->meta_data();
-        metaData->setInt32(kKeyRendered, 1);
-    }
-
-protected:
-    virtual ~AwesomeNativeWindowRenderer() {}
-
-private:
-    sp<ANativeWindow> mNativeWindow;
-
-    void applyRotation(int32_t rotationDegrees) {
-        uint32_t transform;
-        switch (rotationDegrees) {
-            case 0: transform = 0; break;
-            case 90: transform = HAL_TRANSFORM_ROT_90; break;
-            case 180: transform = HAL_TRANSFORM_ROT_180; break;
-            case 270: transform = HAL_TRANSFORM_ROT_270; break;
-            default: transform = 0; break;
-        }
-
-        if (transform) {
-            CHECK_EQ(0, native_window_set_buffers_transform(
-                        mNativeWindow.get(), transform));
-        }
-    }
-
-    AwesomeNativeWindowRenderer(const AwesomeNativeWindowRenderer &);
-    AwesomeNativeWindowRenderer &operator=(
-            const AwesomeNativeWindowRenderer &);
-};
-
-// To collect the decoder usage
-void addBatteryData(uint32_t params) {
-    sp<IBinder> binder =
-        defaultServiceManager()->getService(String16("media.player"));
-    sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
-    CHECK(service.get() != NULL);
-
-    service->addBatteryData(params);
-}
-
-////////////////////////////////////////////////////////////////////////////////
-AwesomePlayer::AwesomePlayer()
-    : mQueueStarted(false),
-      mUIDValid(false),
-      mTimeSource(NULL),
-      mVideoRenderingStarted(false),
-      mVideoRendererIsPreview(false),
-      mMediaRenderingStartGeneration(0),
-      mStartGeneration(0),
-      mAudioPlayer(NULL),
-      mDisplayWidth(0),
-      mDisplayHeight(0),
-      mVideoScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW),
-      mFlags(0),
-      mExtractorFlags(0),
-      mVideoBuffer(NULL),
-      mDecryptHandle(NULL),
-      mLastVideoTimeUs(-1),
-      mTextDriver(NULL),
-      mOffloadAudio(false),
-      mAudioTearDown(false) {
-    CHECK_EQ(mClient.connect(), (status_t)OK);
-
-    DataSource::RegisterDefaultSniffers();
-
-    mVideoEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoEvent);
-    mVideoEventPending = false;
-    mStreamDoneEvent = new AwesomeEvent(this, &AwesomePlayer::onStreamDone);
-    mStreamDoneEventPending = false;
-    mBufferingEvent = new AwesomeEvent(this, &AwesomePlayer::onBufferingUpdate);
-    mBufferingEventPending = false;
-    mVideoLagEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoLagUpdate);
-    mVideoLagEventPending = false;
-
-    mCheckAudioStatusEvent = new AwesomeEvent(
-            this, &AwesomePlayer::onCheckAudioStatus);
-
-    mAudioStatusEventPending = false;
-
-    mAudioTearDownEvent = new AwesomeEvent(this,
-                              &AwesomePlayer::onAudioTearDownEvent);
-    mAudioTearDownEventPending = false;
-
-    mClockEstimator = new WindowedLinearFitEstimator();
-
-    mPlaybackSettings = AUDIO_PLAYBACK_RATE_DEFAULT;
-
-    reset();
-}
-
-AwesomePlayer::~AwesomePlayer() {
-    if (mQueueStarted) {
-        mQueue.stop();
-    }
-
-    reset();
-
-    mClient.disconnect();
-}
-
-void AwesomePlayer::cancelPlayerEvents(bool keepNotifications) {
-    mQueue.cancelEvent(mVideoEvent->eventID());
-    mVideoEventPending = false;
-    mQueue.cancelEvent(mVideoLagEvent->eventID());
-    mVideoLagEventPending = false;
-
-    if (mOffloadAudio) {
-        mQueue.cancelEvent(mAudioTearDownEvent->eventID());
-        mAudioTearDownEventPending = false;
-    }
-
-    if (!keepNotifications) {
-        mQueue.cancelEvent(mStreamDoneEvent->eventID());
-        mStreamDoneEventPending = false;
-        mQueue.cancelEvent(mCheckAudioStatusEvent->eventID());
-        mAudioStatusEventPending = false;
-
-        mQueue.cancelEvent(mBufferingEvent->eventID());
-        mBufferingEventPending = false;
-        mAudioTearDown = false;
-    }
-}
-
-void AwesomePlayer::setListener(const wp<MediaPlayerBase> &listener) {
-    Mutex::Autolock autoLock(mLock);
-    mListener = listener;
-}
-
-void AwesomePlayer::setUID(uid_t uid) {
-    ALOGV("AwesomePlayer running on behalf of uid %d", uid);
-
-    mUID = uid;
-    mUIDValid = true;
-}
-
-status_t AwesomePlayer::setDataSource(
-        const sp<IMediaHTTPService> &httpService,
-        const char *uri,
-        const KeyedVector<String8, String8> *headers) {
-    Mutex::Autolock autoLock(mLock);
-    return setDataSource_l(httpService, uri, headers);
-}
-
-status_t AwesomePlayer::setDataSource_l(
-        const sp<IMediaHTTPService> &httpService,
-        const char *uri,
-        const KeyedVector<String8, String8> *headers) {
-    reset_l();
-
-    mHTTPService = httpService;
-    mUri = uri;
-
-    if (headers) {
-        mUriHeaders = *headers;
-
-        ssize_t index = mUriHeaders.indexOfKey(String8("x-hide-urls-from-log"));
-        if (index >= 0) {
-            // Browser is in "incognito" mode, suppress logging URLs.
-
-            // This isn't something that should be passed to the server.
-            mUriHeaders.removeItemsAt(index);
-
-            modifyFlags(INCOGNITO, SET);
-        }
-    }
-
-    ALOGI("setDataSource_l(%s)", uriDebugString(mUri, mFlags & INCOGNITO).c_str());
-
-    // The actual work will be done during preparation in the call to
-    // ::finishSetDataSource_l to avoid blocking the calling thread in
-    // setDataSource for any significant time.
-
-    {
-        Mutex::Autolock autoLock(mStatsLock);
-        mStats.mFd = -1;
-        mStats.mURI = mUri;
-    }
-
-    return OK;
-}
-
-status_t AwesomePlayer::setDataSource(
-        int fd, int64_t offset, int64_t length) {
-    Mutex::Autolock autoLock(mLock);
-
-    reset_l();
-
-    fd = dup(fd);
-    sp<DataSource> dataSource = new FileSource(fd, offset, length);
-
-    status_t err = dataSource->initCheck();
-
-    if (err != OK) {
-        return err;
-    }
-
-    mFileSource = dataSource;
-
-    {
-        Mutex::Autolock autoLock(mStatsLock);
-        mStats.mFd = fd;
-        mStats.mURI = String8();
-    }
-
-    return setDataSource_l(dataSource);
-}
-
-status_t AwesomePlayer::setDataSource(const sp<IStreamSource> &source __unused) {
-    return INVALID_OPERATION;
-}
-
-status_t AwesomePlayer::setDataSource_l(
-        const sp<DataSource> &dataSource) {
-    sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
-
-    if (extractor == NULL) {
-        return UNKNOWN_ERROR;
-    }
-
-    if (extractor->getDrmFlag()) {
-        checkDrmStatus(dataSource);
-    }
-
-    return setDataSource_l(extractor);
-}
-
-void AwesomePlayer::checkDrmStatus(const sp<DataSource>& dataSource) {
-    dataSource->getDrmInfo(mDecryptHandle, &mDrmManagerClient);
-    if (mDecryptHandle != NULL) {
-        CHECK(mDrmManagerClient);
-        if (RightsStatus::RIGHTS_VALID != mDecryptHandle->status) {
-            notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
-        }
-    }
-}
-
-status_t AwesomePlayer::setDataSource_l(const sp<MediaExtractor> &extractor) {
-    // Attempt to approximate overall stream bitrate by summing all
-    // tracks' individual bitrates, if not all of them advertise bitrate,
-    // we have to fail.
-
-    int64_t totalBitRate = 0;
-
-    mExtractor = extractor;
-    for (size_t i = 0; i < extractor->countTracks(); ++i) {
-        sp<MetaData> meta = extractor->getTrackMetaData(i);
-
-        int32_t bitrate;
-        if (!meta->findInt32(kKeyBitRate, &bitrate)) {
-            const char *mime;
-            CHECK(meta->findCString(kKeyMIMEType, &mime));
-            ALOGV("track of type '%s' does not publish bitrate", mime);
-
-            totalBitRate = -1;
-            break;
-        }
-
-        totalBitRate += bitrate;
-    }
-    sp<MetaData> fileMeta = mExtractor->getMetaData();
-    if (fileMeta != NULL) {
-        int64_t duration;
-        if (fileMeta->findInt64(kKeyDuration, &duration)) {
-            mDurationUs = duration;
-        }
-    }
-
-    mBitrate = totalBitRate;
-
-    ALOGV("mBitrate = %lld bits/sec", (long long)mBitrate);
-
-    {
-        Mutex::Autolock autoLock(mStatsLock);
-        mStats.mBitrate = mBitrate;
-        mStats.mTracks.clear();
-        mStats.mAudioTrackIndex = -1;
-        mStats.mVideoTrackIndex = -1;
-    }
-
-    bool haveAudio = false;
-    bool haveVideo = false;
-    for (size_t i = 0; i < extractor->countTracks(); ++i) {
-        sp<MetaData> meta = extractor->getTrackMetaData(i);
-
-        const char *_mime;
-        CHECK(meta->findCString(kKeyMIMEType, &_mime));
-
-        String8 mime = String8(_mime);
-
-        if (!haveVideo && !strncasecmp(mime.string(), "video/", 6)) {
-            setVideoSource(extractor->getTrack(i));
-            haveVideo = true;
-
-            // Set the presentation/display size
-            int32_t displayWidth, displayHeight;
-            bool success = meta->findInt32(kKeyDisplayWidth, &displayWidth);
-            if (success) {
-                success = meta->findInt32(kKeyDisplayHeight, &displayHeight);
-            }
-            if (success) {
-                mDisplayWidth = displayWidth;
-                mDisplayHeight = displayHeight;
-            }
-
-            {
-                Mutex::Autolock autoLock(mStatsLock);
-                mStats.mVideoTrackIndex = mStats.mTracks.size();
-                mStats.mTracks.push();
-                TrackStat *stat =
-                    &mStats.mTracks.editItemAt(mStats.mVideoTrackIndex);
-                stat->mMIME = mime.string();
-            }
-        } else if (!haveAudio && !strncasecmp(mime.string(), "audio/", 6)) {
-            setAudioSource(extractor->getTrack(i));
-            haveAudio = true;
-            mActiveAudioTrackIndex = i;
-
-            {
-                Mutex::Autolock autoLock(mStatsLock);
-                mStats.mAudioTrackIndex = mStats.mTracks.size();
-                mStats.mTracks.push();
-                TrackStat *stat =
-                    &mStats.mTracks.editItemAt(mStats.mAudioTrackIndex);
-                stat->mMIME = mime.string();
-            }
-
-            if (!strcasecmp(mime.string(), MEDIA_MIMETYPE_AUDIO_VORBIS)) {
-                // Only do this for vorbis audio, none of the other audio
-                // formats even support this ringtone specific hack and
-                // retrieving the metadata on some extractors may turn out
-                // to be very expensive.
-                sp<MetaData> fileMeta = extractor->getMetaData();
-                int32_t loop;
-                if (fileMeta != NULL
-                        && fileMeta->findInt32(kKeyAutoLoop, &loop) && loop != 0) {
-                    modifyFlags(AUTO_LOOPING, SET);
-                }
-            }
-        } else if (!strcasecmp(mime.string(), MEDIA_MIMETYPE_TEXT_3GPP)) {
-            addTextSource_l(i, extractor->getTrack(i));
-        }
-    }
-
-    if (!haveAudio && !haveVideo) {
-        if (mWVMExtractor != NULL) {
-            return mWVMExtractor->getError();
-        } else {
-            return UNKNOWN_ERROR;
-        }
-    }
-
-    mExtractorFlags = extractor->flags();
-
-    return OK;
-}
-
-void AwesomePlayer::reset() {
-    Mutex::Autolock autoLock(mLock);
-    reset_l();
-}
-
-void AwesomePlayer::reset_l() {
-    mVideoRenderingStarted = false;
-    mActiveAudioTrackIndex = -1;
-    mDisplayWidth = 0;
-    mDisplayHeight = 0;
-
-    notifyListener_l(MEDIA_STOPPED);
-
-    if (mDecryptHandle != NULL) {
-            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
-                    Playback::STOP, 0);
-            mDecryptHandle = NULL;
-            mDrmManagerClient = NULL;
-    }
-
-    if (mFlags & PLAYING) {
-        uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder;
-        if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) {
-            params |= IMediaPlayerService::kBatteryDataTrackAudio;
-        }
-        if (mVideoSource != NULL) {
-            params |= IMediaPlayerService::kBatteryDataTrackVideo;
-        }
-        addBatteryData(params);
-    }
-
-    if (mFlags & PREPARING) {
-        modifyFlags(PREPARE_CANCELLED, SET);
-        if (mConnectingDataSource != NULL) {
-            ALOGI("interrupting the connection process");
-            mConnectingDataSource->disconnect();
-        }
-
-        if (mFlags & PREPARING_CONNECTED) {
-            // We are basically done preparing, we're just buffering
-            // enough data to start playback, we can safely interrupt that.
-            finishAsyncPrepare_l();
-        }
-    }
-
-    while (mFlags & PREPARING) {
-        mPreparedCondition.wait(mLock);
-    }
-
-    cancelPlayerEvents();
-
-    mWVMExtractor.clear();
-    mCachedSource.clear();
-    mAudioTrack.clear();
-    mVideoTrack.clear();
-    mExtractor.clear();
-
-    // Shutdown audio first, so that the response to the reset request
-    // appears to happen instantaneously as far as the user is concerned
-    // If we did this later, audio would continue playing while we
-    // shutdown the video-related resources and the player appear to
-    // not be as responsive to a reset request.
-    if ((mAudioPlayer == NULL || !(mFlags & AUDIOPLAYER_STARTED))
-            && mAudioSource != NULL) {
-        // If we had an audio player, it would have effectively
-        // taken possession of the audio source and stopped it when
-        // _it_ is stopped. Otherwise this is still our responsibility.
-        mAudioSource->stop();
-    }
-    mAudioSource.clear();
-    mOmxSource.clear();
-
-    mTimeSource = NULL;
-
-    delete mAudioPlayer;
-    mAudioPlayer = NULL;
-
-    if (mTextDriver != NULL) {
-        delete mTextDriver;
-        mTextDriver = NULL;
-    }
-
-    mVideoRenderer.clear();
-
-    if (mVideoSource != NULL) {
-        shutdownVideoDecoder_l();
-    }
-
-    mDurationUs = -1;
-    modifyFlags(0, ASSIGN);
-    mExtractorFlags = 0;
-    mTimeSourceDeltaUs = 0;
-    mVideoTimeUs = 0;
-
-    mSeeking = NO_SEEK;
-    mSeekNotificationSent = true;
-    mSeekTimeUs = 0;
-
-    mHTTPService.clear();
-    mUri.setTo("");
-    mUriHeaders.clear();
-
-    mFileSource.clear();
-
-    mBitrate = -1;
-    mLastVideoTimeUs = -1;
-
-    {
-        Mutex::Autolock autoLock(mStatsLock);
-        mStats.mFd = -1;
-        mStats.mURI = String8();
-        mStats.mBitrate = -1;
-        mStats.mAudioTrackIndex = -1;
-        mStats.mVideoTrackIndex = -1;
-        mStats.mNumVideoFramesDecoded = 0;
-        mStats.mNumVideoFramesDropped = 0;
-        mStats.mVideoWidth = -1;
-        mStats.mVideoHeight = -1;
-        mStats.mFlags = 0;
-        mStats.mTracks.clear();
-    }
-
-    mWatchForAudioSeekComplete = false;
-    mWatchForAudioEOS = false;
-
-    mMediaRenderingStartGeneration = 0;
-    mStartGeneration = 0;
-}
-
-void AwesomePlayer::notifyListener_l(int msg, int ext1, int ext2) {
-    if ((mListener != NULL) && !mAudioTearDown) {
-        sp<MediaPlayerBase> listener = mListener.promote();
-
-        if (listener != NULL) {
-            listener->sendEvent(msg, ext1, ext2);
-        }
-    }
-}
-
-bool AwesomePlayer::getBitrate(int64_t *bitrate) {
-    off64_t size;
-    if (mDurationUs > 0 && mCachedSource != NULL
-            && mCachedSource->getSize(&size) == OK) {
-        *bitrate = size * 8000000ll / mDurationUs;  // in bits/sec
-        return true;
-    }
-
-    if (mBitrate >= 0) {
-        *bitrate = mBitrate;
-        return true;
-    }
-
-    *bitrate = 0;
-
-    return false;
-}
-
-// Returns true iff cached duration is available/applicable.
-bool AwesomePlayer::getCachedDuration_l(int64_t *durationUs, bool *eos) {
-    int64_t bitrate;
-
-    if (mCachedSource != NULL && getBitrate(&bitrate) && (bitrate > 0)) {
-        status_t finalStatus;
-        size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus);
-        *durationUs = cachedDataRemaining * 8000000ll / bitrate;
-        *eos = (finalStatus != OK);
-        return true;
-    } else if (mWVMExtractor != NULL) {
-        status_t finalStatus;
-        *durationUs = mWVMExtractor->getCachedDurationUs(&finalStatus);
-        *eos = (finalStatus != OK);
-        return true;
-    }
-
-    return false;
-}
-
-void AwesomePlayer::ensureCacheIsFetching_l() {
-    if (mCachedSource != NULL) {
-        mCachedSource->resumeFetchingIfNecessary();
-    }
-}
-
-void AwesomePlayer::onVideoLagUpdate() {
-    Mutex::Autolock autoLock(mLock);
-    if (!mVideoLagEventPending) {
-        return;
-    }
-    mVideoLagEventPending = false;
-
-    int64_t audioTimeUs = mAudioPlayer->getMediaTimeUs();
-    int64_t videoLateByUs = audioTimeUs - mVideoTimeUs;
-
-    if (!(mFlags & VIDEO_AT_EOS) && videoLateByUs > 300000ll) {
-        ALOGV("video late by %lld ms.", videoLateByUs / 1000ll);
-
-        notifyListener_l(
-                MEDIA_INFO,
-                MEDIA_INFO_VIDEO_TRACK_LAGGING,
-                videoLateByUs / 1000ll);
-    }
-
-    postVideoLagEvent_l();
-}
-
-void AwesomePlayer::onBufferingUpdate() {
-    Mutex::Autolock autoLock(mLock);
-    if (!mBufferingEventPending) {
-        return;
-    }
-    mBufferingEventPending = false;
-
-    if (mCachedSource != NULL) {
-        status_t finalStatus;
-        size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus);
-        bool eos = (finalStatus != OK);
-
-        if (eos) {
-            if (finalStatus == ERROR_END_OF_STREAM) {
-                notifyListener_l(MEDIA_BUFFERING_UPDATE, 100);
-            }
-            if (mFlags & PREPARING) {
-                ALOGV("cache has reached EOS, prepare is done.");
-                finishAsyncPrepare_l();
-            }
-        } else {
-            bool eos2;
-            int64_t cachedDurationUs;
-            if (getCachedDuration_l(&cachedDurationUs, &eos2) && mDurationUs > 0) {
-                int percentage = 100.0 * (double)cachedDurationUs / mDurationUs;
-                if (percentage > 100) {
-                    percentage = 100;
-                }
-
-                notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage);
-            } else {
-                // We don't know the bitrate/duration of the stream, use absolute size
-                // limits to maintain the cache.
-
-                if ((mFlags & PLAYING) && !eos
-                        && (cachedDataRemaining < kLowWaterMarkBytes)) {
-                    ALOGI("cache is running low (< %zu) , pausing.",
-                         kLowWaterMarkBytes);
-                    modifyFlags(CACHE_UNDERRUN, SET);
-                    pause_l();
-                    ensureCacheIsFetching_l();
-                    sendCacheStats();
-                    notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START);
-                } else if (eos || cachedDataRemaining > kHighWaterMarkBytes) {
-                    if (mFlags & CACHE_UNDERRUN) {
-                        ALOGI("cache has filled up (> %zu), resuming.",
-                             kHighWaterMarkBytes);
-                        modifyFlags(CACHE_UNDERRUN, CLEAR);
-                        play_l();
-                    } else if (mFlags & PREPARING) {
-                        ALOGV("cache has filled up (> %zu), prepare is done",
-                             kHighWaterMarkBytes);
-                        finishAsyncPrepare_l();
-                    }
-                }
-            }
-        }
-    } else if (mWVMExtractor != NULL) {
-        status_t finalStatus;
-
-        int64_t cachedDurationUs
-            = mWVMExtractor->getCachedDurationUs(&finalStatus);
-
-        bool eos = (finalStatus != OK);
-
-        if (eos) {
-            if (finalStatus == ERROR_END_OF_STREAM) {
-                notifyListener_l(MEDIA_BUFFERING_UPDATE, 100);
-            }
-            if (mFlags & PREPARING) {
-                ALOGV("cache has reached EOS, prepare is done.");
-                finishAsyncPrepare_l();
-            }
-        } else {
-            int percentage = 100.0 * (double)cachedDurationUs / mDurationUs;
-            if (percentage > 100) {
-                percentage = 100;
-            }
-
-            notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage);
-        }
-    }
-
-    int64_t cachedDurationUs;
-    bool eos;
-    if (getCachedDuration_l(&cachedDurationUs, &eos)) {
-        ALOGV("cachedDurationUs = %.2f secs, eos=%d",
-             cachedDurationUs / 1E6, eos);
-
-        if ((mFlags & PLAYING) && !eos
-                && (cachedDurationUs < kLowWaterMarkUs)) {
-            modifyFlags(CACHE_UNDERRUN, SET);
-            ALOGI("cache is running low (%.2f secs) , pausing.",
-                  cachedDurationUs / 1E6);
-            pause_l();
-            ensureCacheIsFetching_l();
-            sendCacheStats();
-            notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START);
-        } else if (eos || cachedDurationUs > kHighWaterMarkUs) {
-            if (mFlags & CACHE_UNDERRUN) {
-                modifyFlags(CACHE_UNDERRUN, CLEAR);
-                ALOGI("cache has filled up (%.2f secs), resuming.",
-                      cachedDurationUs / 1E6);
-                play_l();
-            } else if (mFlags & PREPARING) {
-                ALOGV("cache has filled up (%.2f secs), prepare is done",
-                     cachedDurationUs / 1E6);
-                finishAsyncPrepare_l();
-            }
-        }
-    }
-
-    if (mFlags & (PLAYING | PREPARING | CACHE_UNDERRUN)) {
-        postBufferingEvent_l();
-    }
-}
-
-void AwesomePlayer::sendCacheStats() {
-    sp<MediaPlayerBase> listener = mListener.promote();
-    if (listener != NULL) {
-        int32_t kbps = 0;
-        status_t err = UNKNOWN_ERROR;
-        if (mCachedSource != NULL) {
-            err = mCachedSource->getEstimatedBandwidthKbps(&kbps);
-        } else if (mWVMExtractor != NULL) {
-            err = mWVMExtractor->getEstimatedBandwidthKbps(&kbps);
-        }
-        if (err == OK) {
-            listener->sendEvent(
-                MEDIA_INFO, MEDIA_INFO_NETWORK_BANDWIDTH, kbps);
-        }
-    }
-}
-
-void AwesomePlayer::onStreamDone() {
-    // Posted whenever any stream finishes playing.
-    ATRACE_CALL();
-
-    Mutex::Autolock autoLock(mLock);
-    if (!mStreamDoneEventPending) {
-        return;
-    }
-    mStreamDoneEventPending = false;
-
-    if (mStreamDoneStatus != ERROR_END_OF_STREAM) {
-        ALOGV("MEDIA_ERROR %d", mStreamDoneStatus);
-
-        notifyListener_l(
-                MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, mStreamDoneStatus);
-
-        pause_l(true /* at eos */);
-
-        modifyFlags(AT_EOS, SET);
-        return;
-    }
-
-    const bool allDone =
-        (mVideoSource == NULL || (mFlags & VIDEO_AT_EOS))
-            && (mAudioSource == NULL || (mFlags & AUDIO_AT_EOS));
-
-    if (!allDone) {
-        return;
-    }
-
-    if (mFlags & AUTO_LOOPING) {
-        audio_stream_type_t streamType = AUDIO_STREAM_MUSIC;
-        if (mAudioSink != NULL) {
-            streamType = mAudioSink->getAudioStreamType();
-        }
-        if (streamType == AUDIO_STREAM_NOTIFICATION) {
-            ALOGW("disabling auto-loop for notification");
-            modifyFlags(AUTO_LOOPING, CLEAR);
-        }
-    }
-    if ((mFlags & LOOPING)
-            || (mFlags & AUTO_LOOPING)) {
-
-        seekTo_l(0);
-
-        if (mVideoSource != NULL) {
-            postVideoEvent_l();
-        }
-    } else {
-        ALOGV("MEDIA_PLAYBACK_COMPLETE");
-        notifyListener_l(MEDIA_PLAYBACK_COMPLETE);
-
-        pause_l(true /* at eos */);
-
-        // If audio hasn't completed MEDIA_SEEK_COMPLETE yet,
-        // notify MEDIA_SEEK_COMPLETE to observer immediately for state persistence.
-        if (mWatchForAudioSeekComplete) {
-            notifyListener_l(MEDIA_SEEK_COMPLETE);
-            mWatchForAudioSeekComplete = false;
-        }
-
-        modifyFlags(AT_EOS, SET);
-    }
-}
-
-status_t AwesomePlayer::play() {
-    ATRACE_CALL();
-
-    Mutex::Autolock autoLock(mLock);
-
-    modifyFlags(CACHE_UNDERRUN, CLEAR);
-
-    return play_l();
-}
-
-status_t AwesomePlayer::play_l() {
-    modifyFlags(SEEK_PREVIEW, CLEAR);
-
-    if (mFlags & PLAYING) {
-        return OK;
-    }
-
-    mMediaRenderingStartGeneration = ++mStartGeneration;
-
-    if (!(mFlags & PREPARED)) {
-        status_t err = prepare_l();
-
-        if (err != OK) {
-            return err;
-        }
-    }
-
-    modifyFlags(PLAYING, SET);
-    modifyFlags(FIRST_FRAME, SET);
-
-    if (mDecryptHandle != NULL) {
-        int64_t position;
-        getPosition(&position);
-        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
-                Playback::START, position / 1000);
-    }
-
-    if (mAudioSource != NULL) {
-        if (mAudioPlayer == NULL) {
-            createAudioPlayer_l();
-        }
-
-        CHECK(!(mFlags & AUDIO_RUNNING));
-
-        if (mVideoSource == NULL) {
-
-            // We don't want to post an error notification at this point,
-            // the error returned from MediaPlayer::start() will suffice.
-
-            status_t err = startAudioPlayer_l(
-                    false /* sendErrorNotification */);
-
-            if ((err != OK) && mOffloadAudio) {
-                ALOGI("play_l() cannot create offload output, fallback to sw decode");
-                int64_t curTimeUs;
-                getPosition(&curTimeUs);
-
-                delete mAudioPlayer;
-                mAudioPlayer = NULL;
-                // if the player was started it will take care of stopping the source when destroyed
-                if (!(mFlags & AUDIOPLAYER_STARTED)) {
-                    mAudioSource->stop();
-                }
-                modifyFlags((AUDIO_RUNNING | AUDIOPLAYER_STARTED), CLEAR);
-                mOffloadAudio = false;
-                mAudioSource = mOmxSource;
-                if (mAudioSource != NULL) {
-                    err = mAudioSource->start();
-
-                    if (err != OK) {
-                        mAudioSource.clear();
-                    } else {
-                        mSeekNotificationSent = true;
-                        if (mExtractorFlags & MediaExtractor::CAN_SEEK) {
-                            seekTo_l(curTimeUs);
-                        }
-                        createAudioPlayer_l();
-                        err = startAudioPlayer_l(false);
-                    }
-                }
-            }
-
-            if (err != OK) {
-                delete mAudioPlayer;
-                mAudioPlayer = NULL;
-
-                modifyFlags((PLAYING | FIRST_FRAME), CLEAR);
-
-                if (mDecryptHandle != NULL) {
-                    mDrmManagerClient->setPlaybackStatus(
-                            mDecryptHandle, Playback::STOP, 0);
-                }
-
-                return err;
-            }
-        }
-
-        if (mAudioPlayer != NULL) {
-            mAudioPlayer->setPlaybackRate(mPlaybackSettings);
-        }
-    }
-
-    if (mTimeSource == NULL && mAudioPlayer == NULL) {
-        mTimeSource = &mSystemTimeSource;
-    }
-
-    if (mVideoSource != NULL) {
-        // Kick off video playback
-        postVideoEvent_l();
-
-        if (mAudioSource != NULL && mVideoSource != NULL) {
-            postVideoLagEvent_l();
-        }
-    }
-
-    if (mFlags & AT_EOS) {
-        // Legacy behaviour, if a stream finishes playing and then
-        // is started again, we play from the start...
-        seekTo_l(0);
-    }
-
-    uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted
-        | IMediaPlayerService::kBatteryDataTrackDecoder;
-    if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) {
-        params |= IMediaPlayerService::kBatteryDataTrackAudio;
-    }
-    if (mVideoSource != NULL) {
-        params |= IMediaPlayerService::kBatteryDataTrackVideo;
-    }
-    addBatteryData(params);
-
-    if (isStreamingHTTP()) {
-        postBufferingEvent_l();
-    }
-
-    return OK;
-}
-
-void AwesomePlayer::createAudioPlayer_l()
-{
-    uint32_t flags = 0;
-    int64_t cachedDurationUs;
-    bool eos;
-
-    if (mOffloadAudio) {
-        flags |= AudioPlayer::USE_OFFLOAD;
-    } else if (mVideoSource == NULL
-            && (mDurationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US ||
-            (getCachedDuration_l(&cachedDurationUs, &eos) &&
-            cachedDurationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US))) {
-        flags |= AudioPlayer::ALLOW_DEEP_BUFFERING;
-    }
-    if (isStreamingHTTP()) {
-        flags |= AudioPlayer::IS_STREAMING;
-    }
-    if (mVideoSource != NULL) {
-        flags |= AudioPlayer::HAS_VIDEO;
-    }
-
-    mAudioPlayer = new AudioPlayer(mAudioSink, flags, this);
-    mAudioPlayer->setSource(mAudioSource);
-
-    mTimeSource = mAudioPlayer;
-
-    // If there was a seek request before we ever started,
-    // honor the request now.
-    // Make sure to do this before starting the audio player
-    // to avoid a race condition.
-    seekAudioIfNecessary_l();
-}
-
-void AwesomePlayer::notifyIfMediaStarted_l() {
-    if (mMediaRenderingStartGeneration == mStartGeneration) {
-        mMediaRenderingStartGeneration = -1;
-        notifyListener_l(MEDIA_STARTED);
-    }
-}
-
-status_t AwesomePlayer::startAudioPlayer_l(bool sendErrorNotification) {
-    CHECK(!(mFlags & AUDIO_RUNNING));
-    status_t err = OK;
-
-    if (mAudioSource == NULL || mAudioPlayer == NULL) {
-        return OK;
-    }
-
-    if (mOffloadAudio) {
-        mQueue.cancelEvent(mAudioTearDownEvent->eventID());
-        mAudioTearDownEventPending = false;
-    }
-
-    if (!(mFlags & AUDIOPLAYER_STARTED)) {
-        bool wasSeeking = mAudioPlayer->isSeeking();
-
-        // We've already started the MediaSource in order to enable
-        // the prefetcher to read its data.
-        err = mAudioPlayer->start(
-                true /* sourceAlreadyStarted */);
-
-        if (err != OK) {
-            if (sendErrorNotification) {
-                notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
-            }
-
-            return err;
-        }
-
-        modifyFlags(AUDIOPLAYER_STARTED, SET);
-
-        if (wasSeeking) {
-            CHECK(!mAudioPlayer->isSeeking());
-
-            // We will have finished the seek while starting the audio player.
-            postAudioSeekComplete();
-        } else {
-            notifyIfMediaStarted_l();
-        }
-    } else {
-        err = mAudioPlayer->resume();
-    }
-
-    if (err == OK) {
-        err = mAudioPlayer->setPlaybackRate(mPlaybackSettings);
-    }
-
-    if (err == OK) {
-        modifyFlags(AUDIO_RUNNING, SET);
-
-        mWatchForAudioEOS = true;
-    }
-
-    return err;
-}
-
-void AwesomePlayer::notifyVideoSize_l() {
-    ATRACE_CALL();
-    sp<MetaData> meta = mVideoSource->getFormat();
-
-    int32_t cropLeft, cropTop, cropRight, cropBottom;
-    if (!meta->findRect(
-                kKeyCropRect, &cropLeft, &cropTop, &cropRight, &cropBottom)) {
-        int32_t width, height;
-        CHECK(meta->findInt32(kKeyWidth, &width));
-        CHECK(meta->findInt32(kKeyHeight, &height));
-
-        cropLeft = cropTop = 0;
-        cropRight = width - 1;
-        cropBottom = height - 1;
-
-        ALOGV("got dimensions only %d x %d", width, height);
-    } else {
-        ALOGV("got crop rect %d, %d, %d, %d",
-             cropLeft, cropTop, cropRight, cropBottom);
-    }
-
-    int32_t displayWidth;
-    if (meta->findInt32(kKeyDisplayWidth, &displayWidth)) {
-        ALOGV("Display width changed (%d=>%d)", mDisplayWidth, displayWidth);
-        mDisplayWidth = displayWidth;
-    }
-    int32_t displayHeight;
-    if (meta->findInt32(kKeyDisplayHeight, &displayHeight)) {
-        ALOGV("Display height changed (%d=>%d)", mDisplayHeight, displayHeight);
-        mDisplayHeight = displayHeight;
-    }
-
-    int32_t usableWidth = cropRight - cropLeft + 1;
-    int32_t usableHeight = cropBottom - cropTop + 1;
-    if (mDisplayWidth != 0) {
-        usableWidth = mDisplayWidth;
-    }
-    if (mDisplayHeight != 0) {
-        usableHeight = mDisplayHeight;
-    }
-
-    {
-        Mutex::Autolock autoLock(mStatsLock);
-        mStats.mVideoWidth = usableWidth;
-        mStats.mVideoHeight = usableHeight;
-    }
-
-    int32_t rotationDegrees;
-    if (!mVideoTrack->getFormat()->findInt32(
-                kKeyRotation, &rotationDegrees)) {
-        rotationDegrees = 0;
-    }
-
-    if (rotationDegrees == 90 || rotationDegrees == 270) {
-        notifyListener_l(
-                MEDIA_SET_VIDEO_SIZE, usableHeight, usableWidth);
-    } else {
-        notifyListener_l(
-                MEDIA_SET_VIDEO_SIZE, usableWidth, usableHeight);
-    }
-}
-
-void AwesomePlayer::initRenderer_l() {
-    ATRACE_CALL();
-
-    if (mNativeWindow == NULL) {
-        return;
-    }
-
-    sp<MetaData> meta = mVideoSource->getFormat();
-
-    int32_t format;
-    const char *component;
-    int32_t decodedWidth, decodedHeight;
-    CHECK(meta->findInt32(kKeyColorFormat, &format));
-    CHECK(meta->findCString(kKeyDecoderComponent, &component));
-    CHECK(meta->findInt32(kKeyWidth, &decodedWidth));
-    CHECK(meta->findInt32(kKeyHeight, &decodedHeight));
-
-    int32_t rotationDegrees;
-    if (!mVideoTrack->getFormat()->findInt32(
-                kKeyRotation, &rotationDegrees)) {
-        rotationDegrees = 0;
-    }
-
-    mVideoRenderer.clear();
-
-    // Must ensure that mVideoRenderer's destructor is actually executed
-    // before creating a new one.
-    IPCThreadState::self()->flushCommands();
-
-    // Even if set scaling mode fails, we will continue anyway
-    setVideoScalingMode_l(mVideoScalingMode);
-    if (USE_SURFACE_ALLOC
-            && !strncmp(component, "OMX.", 4)
-            && strncmp(component, "OMX.google.", 11)) {
-        // Hardware decoders avoid the CPU color conversion by decoding
-        // directly to ANativeBuffers, so we must use a renderer that
-        // just pushes those buffers to the ANativeWindow.
-        mVideoRenderer =
-            new AwesomeNativeWindowRenderer(mNativeWindow, rotationDegrees);
-    } else {
-        // Other decoders are instantiated locally and as a consequence
-        // allocate their buffers in local address space.  This renderer
-        // then performs a color conversion and copy to get the data
-        // into the ANativeBuffer.
-        sp<AMessage> format;
-        convertMetaDataToMessage(meta, &format);
-        mVideoRenderer = new AwesomeLocalRenderer(mNativeWindow, format);
-    }
-}
-
-status_t AwesomePlayer::pause() {
-    ATRACE_CALL();
-
-    Mutex::Autolock autoLock(mLock);
-
-    modifyFlags(CACHE_UNDERRUN, CLEAR);
-
-    return pause_l();
-}
-
-status_t AwesomePlayer::pause_l(bool at_eos) {
-    if (!(mFlags & PLAYING)) {
-        if (mAudioTearDown && mAudioTearDownWasPlaying) {
-            ALOGV("pause_l() during teardown and finishSetDataSource_l() mFlags %x" , mFlags);
-            mAudioTearDownWasPlaying = false;
-            notifyListener_l(MEDIA_PAUSED);
-            mMediaRenderingStartGeneration = ++mStartGeneration;
-        }
-        return OK;
-    }
-
-    notifyListener_l(MEDIA_PAUSED);
-    mMediaRenderingStartGeneration = ++mStartGeneration;
-
-    cancelPlayerEvents(true /* keepNotifications */);
-
-    if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) {
-        // If we played the audio stream to completion we
-        // want to make sure that all samples remaining in the audio
-        // track's queue are played out.
-        mAudioPlayer->pause(at_eos /* playPendingSamples */);
-        // send us a reminder to tear down the AudioPlayer if paused for too long.
-        if (mOffloadAudio) {
-            postAudioTearDownEvent(kOffloadPauseMaxUs);
-        }
-        modifyFlags(AUDIO_RUNNING, CLEAR);
-    }
-
-    if (mFlags & TEXTPLAYER_INITIALIZED) {
-        mTextDriver->pause();
-        modifyFlags(TEXT_RUNNING, CLEAR);
-    }
-
-    modifyFlags(PLAYING, CLEAR);
-
-    if (mDecryptHandle != NULL) {
-        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
-                Playback::PAUSE, 0);
-    }
-
-    uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder;
-    if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) {
-        params |= IMediaPlayerService::kBatteryDataTrackAudio;
-    }
-    if (mVideoSource != NULL) {
-        params |= IMediaPlayerService::kBatteryDataTrackVideo;
-    }
-
-    addBatteryData(params);
-
-    return OK;
-}
-
-bool AwesomePlayer::isPlaying() const {
-    return (mFlags & PLAYING) || (mFlags & CACHE_UNDERRUN);
-}
-
-status_t AwesomePlayer::setSurfaceTexture(const sp<IGraphicBufferProducer> &bufferProducer) {
-    Mutex::Autolock autoLock(mLock);
-
-    status_t err;
-    if (bufferProducer != NULL) {
-        err = setNativeWindow_l(new Surface(bufferProducer));
-    } else {
-        err = setNativeWindow_l(NULL);
-    }
-
-    return err;
-}
-
-void AwesomePlayer::shutdownVideoDecoder_l() {
-    if (mVideoBuffer) {
-        mVideoBuffer->release();
-        mVideoBuffer = NULL;
-    }
-
-    mVideoSource->stop();
-
-    // The following hack is necessary to ensure that the OMX
-    // component is completely released by the time we may try
-    // to instantiate it again.
-    wp<MediaSource> tmp = mVideoSource;
-    mVideoSource.clear();
-    while (tmp.promote() != NULL) {
-        usleep(1000);
-    }
-    IPCThreadState::self()->flushCommands();
-    ALOGV("video decoder shutdown completed");
-}
-
-status_t AwesomePlayer::setNativeWindow_l(const sp<ANativeWindow> &native) {
-    mNativeWindow = native;
-
-    if (mVideoSource == NULL) {
-        return OK;
-    }
-
-    ALOGV("attempting to reconfigure to use new surface");
-
-    bool wasPlaying = (mFlags & PLAYING) != 0;
-
-    pause_l();
-    mVideoRenderer.clear();
-
-    shutdownVideoDecoder_l();
-
-    status_t err = initVideoDecoder();
-
-    if (err != OK) {
-        ALOGE("failed to reinstantiate video decoder after surface change.");
-        return err;
-    }
-
-    if (mLastVideoTimeUs >= 0) {
-        mSeeking = SEEK;
-        mSeekTimeUs = mLastVideoTimeUs;
-        modifyFlags((AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS), CLEAR);
-    }
-
-    if (wasPlaying) {
-        play_l();
-    }
-
-    return OK;
-}
-
-void AwesomePlayer::setAudioSink(
-        const sp<MediaPlayerBase::AudioSink> &audioSink) {
-    Mutex::Autolock autoLock(mLock);
-
-    mAudioSink = audioSink;
-}
-
-status_t AwesomePlayer::setLooping(bool shouldLoop) {
-    Mutex::Autolock autoLock(mLock);
-
-    modifyFlags(LOOPING, CLEAR);
-
-    if (shouldLoop) {
-        modifyFlags(LOOPING, SET);
-    }
-
-    return OK;
-}
-
-status_t AwesomePlayer::getDuration(int64_t *durationUs) {
-    Mutex::Autolock autoLock(mMiscStateLock);
-
-    if (mDurationUs < 0) {
-        return UNKNOWN_ERROR;
-    }
-
-    *durationUs = mDurationUs;
-
-    return OK;
-}
-
-status_t AwesomePlayer::getPosition(int64_t *positionUs) {
-    if (mSeeking != NO_SEEK) {
-        *positionUs = mSeekTimeUs;
-    } else if (mVideoSource != NULL
-            && (mAudioPlayer == NULL || !(mFlags & VIDEO_AT_EOS))) {
-        Mutex::Autolock autoLock(mMiscStateLock);
-        *positionUs = mVideoTimeUs;
-    } else if (mAudioPlayer != NULL) {
-        *positionUs = mAudioPlayer->getMediaTimeUs();
-    } else {
-        *positionUs = 0;
-    }
-    return OK;
-}
-
-status_t AwesomePlayer::seekTo(int64_t timeUs) {
-    ATRACE_CALL();
-
-    if (mExtractorFlags & MediaExtractor::CAN_SEEK) {
-        Mutex::Autolock autoLock(mLock);
-        return seekTo_l(timeUs);
-    }
-
-    return OK;
-}
-
-status_t AwesomePlayer::seekTo_l(int64_t timeUs) {
-    if (mFlags & CACHE_UNDERRUN) {
-        modifyFlags(CACHE_UNDERRUN, CLEAR);
-        play_l();
-    }
-
-    if ((mFlags & PLAYING) && mVideoSource != NULL && (mFlags & VIDEO_AT_EOS)) {
-        // Video playback completed before, there's no pending
-        // video event right now. In order for this new seek
-        // to be honored, we need to post one.
-
-        postVideoEvent_l();
-    }
-
-    mSeeking = SEEK;
-    mSeekNotificationSent = false;
-    mSeekTimeUs = timeUs;
-    modifyFlags((AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS), CLEAR);
-
-    if (mFlags & PLAYING) {
-        notifyListener_l(MEDIA_PAUSED);
-        mMediaRenderingStartGeneration = ++mStartGeneration;
-    }
-
-    seekAudioIfNecessary_l();
-
-    if (mFlags & TEXTPLAYER_INITIALIZED) {
-        mTextDriver->seekToAsync(mSeekTimeUs);
-    }
-
-    if (!(mFlags & PLAYING)) {
-        ALOGV("seeking while paused, sending SEEK_COMPLETE notification"
-             " immediately.");
-
-        notifyListener_l(MEDIA_SEEK_COMPLETE);
-        mSeekNotificationSent = true;
-
-        if ((mFlags & PREPARED) && mVideoSource != NULL) {
-            modifyFlags(SEEK_PREVIEW, SET);
-            postVideoEvent_l();
-        }
-    }
-
-    return OK;
-}
-
-void AwesomePlayer::seekAudioIfNecessary_l() {
-    if (mSeeking != NO_SEEK && mVideoSource == NULL && mAudioPlayer != NULL) {
-        mAudioPlayer->seekTo(mSeekTimeUs);
-
-        mWatchForAudioSeekComplete = true;
-        mWatchForAudioEOS = true;
-
-        if (mDecryptHandle != NULL) {
-            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
-                    Playback::PAUSE, 0);
-            mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
-                    Playback::START, mSeekTimeUs / 1000);
-        }
-    }
-}
-
-void AwesomePlayer::setAudioSource(sp<MediaSource> source) {
-    CHECK(source != NULL);
-
-    mAudioTrack = source;
-}
-
-void AwesomePlayer::addTextSource_l(size_t trackIndex, const sp<MediaSource>& source) {
-    CHECK(source != NULL);
-
-    if (mTextDriver == NULL) {
-        mTextDriver = new TimedTextDriver(mListener, mHTTPService);
-    }
-
-    mTextDriver->addInBandTextSource(trackIndex, source);
-}
-
-status_t AwesomePlayer::initAudioDecoder() {
-    ATRACE_CALL();
-
-    sp<MetaData> meta = mAudioTrack->getFormat();
-
-    const char *mime;
-    CHECK(meta->findCString(kKeyMIMEType, &mime));
-    // Check whether there is a hardware codec for this stream
-    // This doesn't guarantee that the hardware has a free stream
-    // but it avoids us attempting to open (and re-open) an offload
-    // stream to hardware that doesn't have the necessary codec
-    audio_stream_type_t streamType = AUDIO_STREAM_MUSIC;
-    if (mAudioSink != NULL) {
-        streamType = mAudioSink->getAudioStreamType();
-    }
-
-    mOffloadAudio = canOffloadStream(meta, (mVideoSource != NULL),
-                                     isStreamingHTTP(), streamType);
-
-    if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) {
-        ALOGV("createAudioPlayer: bypass OMX (raw)");
-        mAudioSource = mAudioTrack;
-    } else {
-        // If offloading we still create a OMX decoder as a fall-back
-        // but we don't start it
-        mOmxSource = OMXCodec::Create(
-                mClient.interface(), mAudioTrack->getFormat(),
-                false, // createEncoder
-                mAudioTrack);
-
-        if (mOffloadAudio) {
-            ALOGV("createAudioPlayer: bypass OMX (offload)");
-            mAudioSource = mAudioTrack;
-        } else {
-            mAudioSource = mOmxSource;
-        }
-    }
-
-    if (mAudioSource != NULL) {
-        int64_t durationUs;
-        if (mAudioTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
-            Mutex::Autolock autoLock(mMiscStateLock);
-            if (mDurationUs < 0 || durationUs > mDurationUs) {
-                mDurationUs = durationUs;
-            }
-        }
-
-        status_t err = mAudioSource->start();
-
-        if (err != OK) {
-            mAudioSource.clear();
-            mOmxSource.clear();
-            return err;
-        }
-    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_QCELP)) {
-        // For legacy reasons we're simply going to ignore the absence
-        // of an audio decoder for QCELP instead of aborting playback
-        // altogether.
-        return OK;
-    }
-
-    if (mAudioSource != NULL) {
-        Mutex::Autolock autoLock(mStatsLock);
-        TrackStat *stat = &mStats.mTracks.editItemAt(mStats.mAudioTrackIndex);
-        const char *component;
-        if (!mAudioSource->getFormat()
-                ->findCString(kKeyDecoderComponent, &component)) {
-            component = "none";
-        }
-
-        stat->mDecoderName = component;
-    }
-
-    return mAudioSource != NULL ? OK : UNKNOWN_ERROR;
-}
-
-void AwesomePlayer::setVideoSource(sp<MediaSource> source) {
-    CHECK(source != NULL);
-
-    mVideoTrack = source;
-}
-
-status_t AwesomePlayer::initVideoDecoder(uint32_t flags) {
-    ATRACE_CALL();
-
-    // Either the application or the DRM system can independently say
-    // that there must be a hardware-protected path to an external video sink.
-    // For now we always require a hardware-protected path to external video sink
-    // if content is DRMed, but eventually this could be optional per DRM agent.
-    // When the application wants protection, then
-    //   (USE_SURFACE_ALLOC && (mSurface != 0) &&
-    //   (mSurface->getFlags() & ISurfaceComposer::eProtectedByApp))
-    // will be true, but that part is already handled by SurfaceFlinger.
-
-#ifdef DEBUG_HDCP
-    // For debugging, we allow a system property to control the protected usage.
-    // In case of uninitialized or unexpected property, we default to "DRM only".
-    bool setProtectionBit = false;
-    char value[PROPERTY_VALUE_MAX];
-    if (property_get("persist.sys.hdcp_checking", value, NULL)) {
-        if (!strcmp(value, "never")) {
-            // nop
-        } else if (!strcmp(value, "always")) {
-            setProtectionBit = true;
-        } else if (!strcmp(value, "drm-only")) {
-            if (mDecryptHandle != NULL) {
-                setProtectionBit = true;
-            }
-        // property value is empty, or unexpected value
-        } else {
-            if (mDecryptHandle != NULL) {
-                setProtectionBit = true;
-            }
-        }
-    // can' read property value
-    } else {
-        if (mDecryptHandle != NULL) {
-            setProtectionBit = true;
-        }
-    }
-    // note that usage bit is already cleared, so no need to clear it in the "else" case
-    if (setProtectionBit) {
-        flags |= OMXCodec::kEnableGrallocUsageProtected;
-    }
-#else
-    if (mDecryptHandle != NULL) {
-        flags |= OMXCodec::kEnableGrallocUsageProtected;
-    }
-#endif
-    ALOGV("initVideoDecoder flags=0x%x", flags);
-    mVideoSource = OMXCodec::Create(
-            mClient.interface(), mVideoTrack->getFormat(),
-            false, // createEncoder
-            mVideoTrack,
-            NULL, flags, USE_SURFACE_ALLOC ? mNativeWindow : NULL);
-
-    if (mVideoSource != NULL) {
-        int64_t durationUs;
-        if (mVideoTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) {
-            Mutex::Autolock autoLock(mMiscStateLock);
-            if (mDurationUs < 0 || durationUs > mDurationUs) {
-                mDurationUs = durationUs;
-            }
-        }
-
-        status_t err = mVideoSource->start();
-
-        if (err != OK) {
-            ALOGE("failed to start video source");
-            mVideoSource.clear();
-            return err;
-        }
-    }
-
-    if (mVideoSource != NULL) {
-        const char *componentName;
-        CHECK(mVideoSource->getFormat()
-                ->findCString(kKeyDecoderComponent, &componentName));
-
-        {
-            Mutex::Autolock autoLock(mStatsLock);
-            TrackStat *stat = &mStats.mTracks.editItemAt(mStats.mVideoTrackIndex);
-
-            stat->mDecoderName = componentName;
-        }
-
-        static const char *kPrefix = "OMX.Nvidia.";
-        static const char *kSuffix = ".decode";
-        static const size_t kSuffixLength = strlen(kSuffix);
-
-        size_t componentNameLength = strlen(componentName);
-
-        if (!strncmp(componentName, kPrefix, strlen(kPrefix))
-                && componentNameLength >= kSuffixLength
-                && !strcmp(&componentName[
-                    componentNameLength - kSuffixLength], kSuffix)) {
-            modifyFlags(SLOW_DECODER_HACK, SET);
-        }
-    }
-
-    return mVideoSource != NULL ? OK : UNKNOWN_ERROR;
-}
-
-void AwesomePlayer::finishSeekIfNecessary(int64_t videoTimeUs) {
-    ATRACE_CALL();
-
-    if (mSeeking == SEEK_VIDEO_ONLY) {
-        mSeeking = NO_SEEK;
-        return;
-    }
-
-    if (mSeeking == NO_SEEK || (mFlags & SEEK_PREVIEW)) {
-        return;
-    }
-
-    // If we paused, then seeked, then resumed, it is possible that we have
-    // signaled SEEK_COMPLETE at a copmletely different media time than where
-    // we are now resuming.  Signal new position to media time provider.
-    // Cannot signal another SEEK_COMPLETE, as existing clients may not expect
-    // multiple SEEK_COMPLETE responses to a single seek() request.
-    if (mSeekNotificationSent && llabs((long long)(mSeekTimeUs - videoTimeUs)) > 10000) {
-        // notify if we are resuming more than 10ms away from desired seek time
-        notifyListener_l(MEDIA_SKIPPED);
-    }
-
-    if (mAudioPlayer != NULL) {
-        ALOGV("seeking audio to %" PRId64 " us (%.2f secs).", videoTimeUs, videoTimeUs / 1E6);
-
-        // If we don't have a video time, seek audio to the originally
-        // requested seek time instead.
-
-        mAudioPlayer->seekTo(videoTimeUs < 0 ? mSeekTimeUs : videoTimeUs);
-        mWatchForAudioSeekComplete = true;
-        mWatchForAudioEOS = true;
-    } else if (!mSeekNotificationSent) {
-        // If we're playing video only, report seek complete now,
-        // otherwise audio player will notify us later.
-        notifyListener_l(MEDIA_SEEK_COMPLETE);
-        mSeekNotificationSent = true;
-    }
-
-    modifyFlags(FIRST_FRAME, SET);
-    mSeeking = NO_SEEK;
-
-    if (mDecryptHandle != NULL) {
-        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
-                Playback::PAUSE, 0);
-        mDrmManagerClient->setPlaybackStatus(mDecryptHandle,
-                Playback::START, videoTimeUs / 1000);
-    }
-}
-
-void AwesomePlayer::onVideoEvent() {
-    ATRACE_CALL();
-    Mutex::Autolock autoLock(mLock);
-    if (!mVideoEventPending) {
-        // The event has been cancelled in reset_l() but had already
-        // been scheduled for execution at that time.
-        return;
-    }
-    mVideoEventPending = false;
-
-    if (mSeeking != NO_SEEK) {
-        if (mVideoBuffer) {
-            mVideoBuffer->release();
-            mVideoBuffer = NULL;
-        }
-
-        if (mSeeking == SEEK && isStreamingHTTP() && mAudioSource != NULL
-                && !(mFlags & SEEK_PREVIEW)) {
-            // We're going to seek the video source first, followed by
-            // the audio source.
-            // In order to avoid jumps in the DataSource offset caused by
-            // the audio codec prefetching data from the old locations
-            // while the video codec is already reading data from the new
-            // locations, we'll "pause" the audio source, causing it to
-            // stop reading input data until a subsequent seek.
-
-            if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) {
-                mAudioPlayer->pause();
-
-                modifyFlags(AUDIO_RUNNING, CLEAR);
-            }
-            mAudioSource->pause();
-        }
-    }
-
-    if (!mVideoBuffer) {
-        MediaSource::ReadOptions options;
-        if (mSeeking != NO_SEEK) {
-            ALOGV("seeking to %" PRId64 " us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6);
-
-            options.setSeekTo(
-                    mSeekTimeUs,
-                    mSeeking == SEEK_VIDEO_ONLY
-                        ? MediaSource::ReadOptions::SEEK_NEXT_SYNC
-                        : MediaSource::ReadOptions::SEEK_CLOSEST_SYNC);
-        }
-        for (;;) {
-            status_t err = mVideoSource->read(&mVideoBuffer, &options);
-            options.clearSeekTo();
-
-            if (err != OK) {
-                CHECK(mVideoBuffer == NULL);
-
-                if (err == INFO_FORMAT_CHANGED) {
-                    ALOGV("VideoSource signalled format change.");
-
-                    notifyVideoSize_l();
-
-                    if (mVideoRenderer != NULL) {
-                        mVideoRendererIsPreview = false;
-                        initRenderer_l();
-                    }
-                    continue;
-                }
-
-                // So video playback is complete, but we may still have
-                // a seek request pending that needs to be applied
-                // to the audio track.
-                if (mSeeking != NO_SEEK) {
-                    ALOGV("video stream ended while seeking!");
-                }
-                finishSeekIfNecessary(-1);
-
-                if (mAudioPlayer != NULL
-                        && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) {
-                    startAudioPlayer_l();
-                }
-
-                modifyFlags(VIDEO_AT_EOS, SET);
-                postStreamDoneEvent_l(err);
-                return;
-            }
-
-            if (mVideoBuffer->range_length() == 0) {
-                // Some decoders, notably the PV AVC software decoder
-                // return spurious empty buffers that we just want to ignore.
-
-                mVideoBuffer->release();
-                mVideoBuffer = NULL;
-                continue;
-            }
-
-            break;
-        }
-
-        {
-            Mutex::Autolock autoLock(mStatsLock);
-            ++mStats.mNumVideoFramesDecoded;
-        }
-    }
-
-    int64_t timeUs;
-    CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs));
-
-    mLastVideoTimeUs = timeUs;
-
-    if (mSeeking == SEEK_VIDEO_ONLY) {
-        if (mSeekTimeUs > timeUs) {
-            ALOGI("XXX mSeekTimeUs = %" PRId64 " us, timeUs = %" PRId64 " us",
-                 mSeekTimeUs, timeUs);
-        }
-    }
-
-    {
-        Mutex::Autolock autoLock(mMiscStateLock);
-        mVideoTimeUs = timeUs;
-    }
-
-    SeekType wasSeeking = mSeeking;
-    finishSeekIfNecessary(timeUs);
-
-    if (mAudioPlayer != NULL && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) {
-        status_t err = startAudioPlayer_l();
-        if (err != OK) {
-            ALOGE("Starting the audio player failed w/ err %d", err);
-            return;
-        }
-    }
-
-    if ((mFlags & TEXTPLAYER_INITIALIZED)
-            && !(mFlags & (TEXT_RUNNING | SEEK_PREVIEW))) {
-        mTextDriver->start();
-        modifyFlags(TEXT_RUNNING, SET);
-    }
-
-    TimeSource *ts =
-        ((mFlags & AUDIO_AT_EOS) || !(mFlags & AUDIOPLAYER_STARTED))
-            ? &mSystemTimeSource : mTimeSource;
-    int64_t systemTimeUs = mSystemTimeSource.getRealTimeUs();
-    int64_t looperTimeUs = ALooper::GetNowUs();
-
-    if (mFlags & FIRST_FRAME) {
-        modifyFlags(FIRST_FRAME, CLEAR);
-        mSinceLastDropped = 0;
-        mClockEstimator->reset();
-        mTimeSourceDeltaUs = estimateRealTimeUs(ts, systemTimeUs) - timeUs;
-    }
-
-    int64_t realTimeUs, mediaTimeUs;
-    if (!(mFlags & AUDIO_AT_EOS) && mAudioPlayer != NULL
-        && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) {
-        ALOGV("updating TSdelta (%" PRId64 " => %" PRId64 " change %" PRId64 ")",
-              mTimeSourceDeltaUs, realTimeUs - mediaTimeUs,
-              mTimeSourceDeltaUs - (realTimeUs - mediaTimeUs));
-        ATRACE_INT("TS delta change (ms)", (mTimeSourceDeltaUs - (realTimeUs - mediaTimeUs)) / 1E3);
-        mTimeSourceDeltaUs = realTimeUs - mediaTimeUs;
-    }
-
-    if (wasSeeking == SEEK_VIDEO_ONLY) {
-        int64_t nowUs = estimateRealTimeUs(ts, systemTimeUs) - mTimeSourceDeltaUs;
-
-        int64_t latenessUs = nowUs - timeUs;
-
-        ATRACE_INT("Video Lateness (ms)", latenessUs / 1E3);
-
-        if (latenessUs > 0) {
-            ALOGI("after SEEK_VIDEO_ONLY we're late by %.2f secs", latenessUs / 1E6);
-        }
-    }
-
-    int64_t latenessUs = 0;
-    if (wasSeeking == NO_SEEK) {
-        // Let's display the first frame after seeking right away.
-
-        int64_t nowUs = estimateRealTimeUs(ts, systemTimeUs) - mTimeSourceDeltaUs;
-
-        latenessUs = nowUs - timeUs;
-
-        ATRACE_INT("Video Lateness (ms)", latenessUs / 1E3);
-
-        if (latenessUs > 500000ll
-                && mAudioPlayer != NULL
-                && mAudioPlayer->getMediaTimeMapping(
-                    &realTimeUs, &mediaTimeUs)) {
-            if (mWVMExtractor == NULL) {
-                ALOGI("we're much too late (%.2f secs), video skipping ahead",
-                     latenessUs / 1E6);
-
-                mVideoBuffer->release();
-                mVideoBuffer = NULL;
-
-                mSeeking = SEEK_VIDEO_ONLY;
-                mSeekTimeUs = mediaTimeUs;
-
-                postVideoEvent_l();
-                return;
-            } else {
-                // The widevine extractor doesn't deal well with seeking
-                // audio and video independently. We'll just have to wait
-                // until the decoder catches up, which won't be long at all.
-                ALOGI("we're very late (%.2f secs)", latenessUs / 1E6);
-            }
-        }
-
-        if (latenessUs > 40000) {
-            // We're more than 40ms late.
-            ALOGV("we're late by %" PRId64 " us (%.2f secs)",
-                 latenessUs, latenessUs / 1E6);
-
-            if (!(mFlags & SLOW_DECODER_HACK)
-                    || mSinceLastDropped > FRAME_DROP_FREQ)
-            {
-                ALOGV("we're late by %" PRId64 " us (%.2f secs) dropping "
-                     "one after %d frames",
-                     latenessUs, latenessUs / 1E6, mSinceLastDropped);
-
-                mSinceLastDropped = 0;
-                mVideoBuffer->release();
-                mVideoBuffer = NULL;
-
-                {
-                    Mutex::Autolock autoLock(mStatsLock);
-                    ++mStats.mNumVideoFramesDropped;
-                }
-
-                postVideoEvent_l(0);
-                return;
-            }
-        }
-
-        if (latenessUs < -30000) {
-            // We're more than 30ms early, schedule at most 20 ms before time due
-            postVideoEvent_l(latenessUs < -60000 ? 30000 : -latenessUs - 20000);
-            return;
-        }
-    }
-
-    if ((mNativeWindow != NULL)
-            && (mVideoRendererIsPreview || mVideoRenderer == NULL)) {
-        mVideoRendererIsPreview = false;
-
-        initRenderer_l();
-    }
-
-    if (mVideoRenderer != NULL) {
-        mSinceLastDropped++;
-        mVideoBuffer->meta_data()->setInt64(kKeyTime, looperTimeUs - latenessUs);
-
-        mVideoRenderer->render(mVideoBuffer);
-        if (!mVideoRenderingStarted) {
-            mVideoRenderingStarted = true;
-            notifyListener_l(MEDIA_INFO, MEDIA_INFO_RENDERING_START);
-        }
-
-        if (mFlags & PLAYING) {
-            notifyIfMediaStarted_l();
-        }
-    }
-
-    mVideoBuffer->release();
-    mVideoBuffer = NULL;
-
-    if (wasSeeking != NO_SEEK && (mFlags & SEEK_PREVIEW)) {
-        modifyFlags(SEEK_PREVIEW, CLEAR);
-        return;
-    }
-
-    /* get next frame time */
-    if (wasSeeking == NO_SEEK) {
-        MediaSource::ReadOptions options;
-        for (;;) {
-            status_t err = mVideoSource->read(&mVideoBuffer, &options);
-            if (err != OK) {
-                // deal with any errors next time
-                CHECK(mVideoBuffer == NULL);
-                postVideoEvent_l(0);
-                return;
-            }
-
-            if (mVideoBuffer->range_length() != 0) {
-                break;
-            }
-
-            // Some decoders, notably the PV AVC software decoder
-            // return spurious empty buffers that we just want to ignore.
-
-            mVideoBuffer->release();
-            mVideoBuffer = NULL;
-        }
-
-        {
-            Mutex::Autolock autoLock(mStatsLock);
-            ++mStats.mNumVideoFramesDecoded;
-        }
-
-        int64_t nextTimeUs;
-        CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &nextTimeUs));
-        systemTimeUs = mSystemTimeSource.getRealTimeUs();
-        int64_t delayUs = nextTimeUs - estimateRealTimeUs(ts, systemTimeUs) + mTimeSourceDeltaUs;
-        ATRACE_INT("Frame delta (ms)", (nextTimeUs - timeUs) / 1E3);
-        ALOGV("next frame in %" PRId64, delayUs);
-        // try to schedule 30ms before time due
-        postVideoEvent_l(delayUs > 60000 ? 30000 : (delayUs < 30000 ? 0 : delayUs - 30000));
-        return;
-    }
-
-    postVideoEvent_l();
-}
-
-int64_t AwesomePlayer::estimateRealTimeUs(TimeSource *ts, int64_t systemTimeUs) {
-    if (ts == &mSystemTimeSource) {
-        return systemTimeUs;
-    } else {
-        return (int64_t)mClockEstimator->estimate(systemTimeUs, ts->getRealTimeUs());
-    }
-}
-
-void AwesomePlayer::postVideoEvent_l(int64_t delayUs) {
-    ATRACE_CALL();
-
-    if (mVideoEventPending) {
-        return;
-    }
-
-    mVideoEventPending = true;
-    mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs);
-}
-
-void AwesomePlayer::postStreamDoneEvent_l(status_t status) {
-    if (mStreamDoneEventPending) {
-        return;
-    }
-    mStreamDoneEventPending = true;
-
-    mStreamDoneStatus = status;
-    mQueue.postEvent(mStreamDoneEvent);
-}
-
-void AwesomePlayer::postBufferingEvent_l() {
-    if (mBufferingEventPending) {
-        return;
-    }
-    mBufferingEventPending = true;
-    mQueue.postEventWithDelay(mBufferingEvent, 1000000ll);
-}
-
-void AwesomePlayer::postVideoLagEvent_l() {
-    if (mVideoLagEventPending) {
-        return;
-    }
-    mVideoLagEventPending = true;
-    mQueue.postEventWithDelay(mVideoLagEvent, 1000000ll);
-}
-
-void AwesomePlayer::postCheckAudioStatusEvent(int64_t delayUs) {
-    Mutex::Autolock autoLock(mAudioLock);
-    if (mAudioStatusEventPending) {
-        return;
-    }
-    mAudioStatusEventPending = true;
-    // Do not honor delay when looping in order to limit audio gap
-    if (mFlags & (LOOPING | AUTO_LOOPING)) {
-        delayUs = 0;
-    }
-    mQueue.postEventWithDelay(mCheckAudioStatusEvent, delayUs);
-}
-
-void AwesomePlayer::postAudioTearDownEvent(int64_t delayUs) {
-    Mutex::Autolock autoLock(mAudioLock);
-    if (mAudioTearDownEventPending) {
-        return;
-    }
-    mAudioTearDownEventPending = true;
-    mQueue.postEventWithDelay(mAudioTearDownEvent, delayUs);
-}
-
-void AwesomePlayer::onCheckAudioStatus() {
-    {
-        Mutex::Autolock autoLock(mAudioLock);
-        if (!mAudioStatusEventPending) {
-            // Event was dispatched and while we were blocking on the mutex,
-            // has already been cancelled.
-            return;
-        }
-
-        mAudioStatusEventPending = false;
-    }
-
-    Mutex::Autolock autoLock(mLock);
-
-    if (mWatchForAudioSeekComplete && !mAudioPlayer->isSeeking()) {
-        mWatchForAudioSeekComplete = false;
-
-        if (!mSeekNotificationSent) {
-            notifyListener_l(MEDIA_SEEK_COMPLETE);
-            mSeekNotificationSent = true;
-        }
-
-        if (mVideoSource == NULL) {
-            // For video the mSeeking flag is always reset in finishSeekIfNecessary
-            mSeeking = NO_SEEK;
-        }
-
-        notifyIfMediaStarted_l();
-    }
-
-    status_t finalStatus;
-    if (mWatchForAudioEOS && mAudioPlayer->reachedEOS(&finalStatus)) {
-        mWatchForAudioEOS = false;
-        modifyFlags(AUDIO_AT_EOS, SET);
-        modifyFlags(FIRST_FRAME, SET);
-        postStreamDoneEvent_l(finalStatus);
-    }
-}
-
-status_t AwesomePlayer::prepare() {
-    ATRACE_CALL();
-    Mutex::Autolock autoLock(mLock);
-    return prepare_l();
-}
-
-status_t AwesomePlayer::prepare_l() {
-    if (mFlags & PREPARED) {
-        return OK;
-    }
-
-    if (mFlags & PREPARING) {
-        return UNKNOWN_ERROR;
-    }
-
-    mIsAsyncPrepare = false;
-    status_t err = prepareAsync_l();
-
-    if (err != OK) {
-        return err;
-    }
-
-    while (mFlags & PREPARING) {
-        mPreparedCondition.wait(mLock);
-    }
-
-    return mPrepareResult;
-}
-
-status_t AwesomePlayer::prepareAsync() {
-    ATRACE_CALL();
-    Mutex::Autolock autoLock(mLock);
-
-    if (mFlags & PREPARING) {
-        return UNKNOWN_ERROR;  // async prepare already pending
-    }
-
-    mIsAsyncPrepare = true;
-    return prepareAsync_l();
-}
-
-status_t AwesomePlayer::prepareAsync_l() {
-    if (mFlags & PREPARING) {
-        return UNKNOWN_ERROR;  // async prepare already pending
-    }
-
-    if (!mQueueStarted) {
-        mQueue.start();
-        mQueueStarted = true;
-    }
-
-    modifyFlags(PREPARING, SET);
-    mAsyncPrepareEvent = new AwesomeEvent(
-            this, &AwesomePlayer::onPrepareAsyncEvent);
-
-    mQueue.postEvent(mAsyncPrepareEvent);
-
-    return OK;
-}
-
-status_t AwesomePlayer::finishSetDataSource_l() {
-    ATRACE_CALL();
-    sp<DataSource> dataSource;
-
-    bool isWidevineStreaming = false;
-    if (!strncasecmp("widevine://", mUri.string(), 11)) {
-        isWidevineStreaming = true;
-
-        String8 newURI = String8("http://");
-        newURI.append(mUri.string() + 11);
-
-        mUri = newURI;
-    }
-
-    AString sniffedMIME;
-
-    if (!strncasecmp("http://", mUri.string(), 7)
-            || !strncasecmp("https://", mUri.string(), 8)
-            || isWidevineStreaming) {
-        if (mHTTPService == NULL) {
-            ALOGE("Attempt to play media from http URI without HTTP service.");
-            return UNKNOWN_ERROR;
-        }
-
-        sp<IMediaHTTPConnection> conn = mHTTPService->makeHTTPConnection();
-        mConnectingDataSource = new MediaHTTP(conn);
-
-        String8 cacheConfig;
-        bool disconnectAtHighwatermark;
-        NuCachedSource2::RemoveCacheSpecificHeaders(
-                &mUriHeaders, &cacheConfig, &disconnectAtHighwatermark);
-
-        mLock.unlock();
-        status_t err = mConnectingDataSource->connect(mUri, &mUriHeaders);
-        // force connection at this point, to avoid a race condition between getMIMEType and the
-        // caching datasource constructed below, which could result in multiple requests to the
-        // server, and/or failed connections.
-        String8 contentType = mConnectingDataSource->getMIMEType();
-        mLock.lock();
-
-        if (err != OK) {
-            mConnectingDataSource.clear();
-
-            ALOGI("mConnectingDataSource->connect() returned %d", err);
-            return err;
-        }
-
-        if (!isWidevineStreaming) {
-            // The widevine extractor does its own caching.
-
-#if 0
-            mCachedSource = new NuCachedSource2(
-                    new ThrottledSource(
-                        mConnectingDataSource, 50 * 1024 /* bytes/sec */));
-#else
-            mCachedSource = new NuCachedSource2(
-                    mConnectingDataSource,
-                    cacheConfig.isEmpty() ? NULL : cacheConfig.string(),
-                    disconnectAtHighwatermark);
-#endif
-
-            dataSource = mCachedSource;
-        } else {
-            dataSource = mConnectingDataSource;
-        }
-
-        mConnectingDataSource.clear();
-
-        if (strncasecmp(contentType.string(), "audio/", 6)) {
-            // We're not doing this for streams that appear to be audio-only
-            // streams to ensure that even low bandwidth streams start
-            // playing back fairly instantly.
-
-            // We're going to prefill the cache before trying to instantiate
-            // the extractor below, as the latter is an operation that otherwise
-            // could block on the datasource for a significant amount of time.
-            // During that time we'd be unable to abort the preparation phase
-            // without this prefill.
-            if (mCachedSource != NULL) {
-                // We're going to prefill the cache before trying to instantiate
-                // the extractor below, as the latter is an operation that otherwise
-                // could block on the datasource for a significant amount of time.
-                // During that time we'd be unable to abort the preparation phase
-                // without this prefill.
-
-                mLock.unlock();
-
-                // Initially make sure we have at least 192 KB for the sniff
-                // to complete without blocking.
-                static const size_t kMinBytesForSniffing = 192 * 1024;
-
-                off64_t metaDataSize = -1ll;
-                for (;;) {
-                    status_t finalStatus;
-                    size_t cachedDataRemaining =
-                        mCachedSource->approxDataRemaining(&finalStatus);
-
-                    if (finalStatus != OK
-                            || (metaDataSize >= 0
-                                && (off64_t)cachedDataRemaining >= metaDataSize)
-                            || (mFlags & PREPARE_CANCELLED)) {
-                        break;
-                    }
-
-                    ALOGV("now cached %zu bytes of data", cachedDataRemaining);
-
-                    if (metaDataSize < 0
-                            && cachedDataRemaining >= kMinBytesForSniffing) {
-                        String8 tmp;
-                        float confidence;
-                        sp<AMessage> meta;
-                        if (!dataSource->sniff(&tmp, &confidence, &meta)) {
-                            mLock.lock();
-                            return UNKNOWN_ERROR;
-                        }
-
-                        // We successfully identified the file's extractor to
-                        // be, remember this mime type so we don't have to
-                        // sniff it again when we call MediaExtractor::Create()
-                        // below.
-                        sniffedMIME = tmp.string();
-
-                        if (meta == NULL
-                                || !meta->findInt64("meta-data-size",
-                                     reinterpret_cast<int64_t*>(&metaDataSize))) {
-                            metaDataSize = kHighWaterMarkBytes;
-                        }
-
-                        CHECK_GE(metaDataSize, 0ll);
-                        ALOGV("metaDataSize = %lld bytes", (long long)metaDataSize);
-                    }
-
-                    usleep(200000);
-                }
-
-                mLock.lock();
-            }
-
-            if (mFlags & PREPARE_CANCELLED) {
-                ALOGI("Prepare cancelled while waiting for initial cache fill.");
-                return UNKNOWN_ERROR;
-            }
-        }
-    } else {
-        dataSource = DataSource::CreateFromURI(
-                mHTTPService, mUri.string(), &mUriHeaders);
-    }
-
-    if (dataSource == NULL) {
-        return UNKNOWN_ERROR;
-    }
-
-    sp<MediaExtractor> extractor;
-
-    if (isWidevineStreaming) {
-        String8 mimeType;
-        float confidence;
-        sp<AMessage> dummy;
-        bool success;
-
-        // SniffWVM is potentially blocking since it may require network access.
-        // Do not call it with mLock held.
-        mLock.unlock();
-        success = SniffWVM(dataSource, &mimeType, &confidence, &dummy);
-        mLock.lock();
-
-        if (!success
-                || strcasecmp(
-                    mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM)) {
-            return ERROR_UNSUPPORTED;
-        }
-
-        mWVMExtractor = new WVMExtractor(dataSource);
-        mWVMExtractor->setAdaptiveStreamingMode(true);
-        if (mUIDValid)
-            mWVMExtractor->setUID(mUID);
-        extractor = mWVMExtractor;
-    } else {
-        extractor = MediaExtractor::Create(
-                dataSource, sniffedMIME.empty() ? NULL : sniffedMIME.c_str());
-
-        if (extractor == NULL) {
-            return UNKNOWN_ERROR;
-        }
-    }
-
-    if (extractor->getDrmFlag()) {
-        checkDrmStatus(dataSource);
-    }
-
-    status_t err = setDataSource_l(extractor);
-
-    if (err != OK) {
-        mWVMExtractor.clear();
-
-        return err;
-    }
-
-    return OK;
-}
-
-void AwesomePlayer::abortPrepare(status_t err) {
-    CHECK(err != OK);
-
-    if (mIsAsyncPrepare) {
-        notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
-    }
-
-    mPrepareResult = err;
-    modifyFlags((PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED), CLEAR);
-    mAsyncPrepareEvent = NULL;
-    mPreparedCondition.broadcast();
-    mAudioTearDown = false;
-}
-
-// static
-bool AwesomePlayer::ContinuePreparation(void *cookie) {
-    AwesomePlayer *me = static_cast<AwesomePlayer *>(cookie);
-
-    return (me->mFlags & PREPARE_CANCELLED) == 0;
-}
-
-void AwesomePlayer::onPrepareAsyncEvent() {
-    Mutex::Autolock autoLock(mLock);
-    beginPrepareAsync_l();
-}
-
-void AwesomePlayer::beginPrepareAsync_l() {
-    if (mFlags & PREPARE_CANCELLED) {
-        ALOGI("prepare was cancelled before doing anything");
-        abortPrepare(UNKNOWN_ERROR);
-        return;
-    }
-
-    if (mUri.size() > 0) {
-        status_t err = finishSetDataSource_l();
-
-        if (err != OK) {
-            abortPrepare(err);
-            return;
-        }
-    }
-
-    if (mVideoTrack != NULL && mVideoSource == NULL) {
-        status_t err = initVideoDecoder();
-
-        if (err != OK) {
-            abortPrepare(err);
-            return;
-        }
-    }
-
-    if (mAudioTrack != NULL && mAudioSource == NULL) {
-        status_t err = initAudioDecoder();
-
-        if (err != OK) {
-            abortPrepare(err);
-            return;
-        }
-    }
-
-    modifyFlags(PREPARING_CONNECTED, SET);
-
-    if (isStreamingHTTP()) {
-        postBufferingEvent_l();
-    } else {
-        finishAsyncPrepare_l();
-    }
-}
-
-void AwesomePlayer::finishAsyncPrepare_l() {
-    if (mIsAsyncPrepare) {
-        if (mVideoSource == NULL) {
-            notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0);
-        } else {
-            notifyVideoSize_l();
-        }
-
-        notifyListener_l(MEDIA_PREPARED);
-    }
-
-    mPrepareResult = OK;
-    modifyFlags((PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED), CLEAR);
-    modifyFlags(PREPARED, SET);
-    mAsyncPrepareEvent = NULL;
-    mPreparedCondition.broadcast();
-
-    if (mAudioTearDown) {
-        if (mPrepareResult == OK) {
-            if (mExtractorFlags & MediaExtractor::CAN_SEEK) {
-                seekTo_l(mAudioTearDownPosition);
-            }
-
-            if (mAudioTearDownWasPlaying) {
-                modifyFlags(CACHE_UNDERRUN, CLEAR);
-                play_l();
-            }
-        }
-        mAudioTearDown = false;
-    }
-}
-
-uint32_t AwesomePlayer::flags() const {
-    return mExtractorFlags;
-}
-
-void AwesomePlayer::postAudioEOS(int64_t delayUs) {
-    postCheckAudioStatusEvent(delayUs);
-}
-
-void AwesomePlayer::postAudioSeekComplete() {
-    postCheckAudioStatusEvent(0);
-}
-
-void AwesomePlayer::postAudioTearDown() {
-    postAudioTearDownEvent(0);
-}
-
-status_t AwesomePlayer::setParameter(int key, const Parcel &request) {
-    switch (key) {
-        case KEY_PARAMETER_CACHE_STAT_COLLECT_FREQ_MS:
-        {
-            return setCacheStatCollectFreq(request);
-        }
-        default:
-        {
-            return ERROR_UNSUPPORTED;
-        }
-    }
-}
-
-status_t AwesomePlayer::setCacheStatCollectFreq(const Parcel &request) {
-    if (mCachedSource != NULL) {
-        int32_t freqMs = request.readInt32();
-        ALOGD("Request to keep cache stats in the past %d ms",
-            freqMs);
-        return mCachedSource->setCacheStatCollectFreq(freqMs);
-    }
-    return ERROR_UNSUPPORTED;
-}
-
-status_t AwesomePlayer::getParameter(int key, Parcel *reply) {
-    switch (key) {
-    case KEY_PARAMETER_AUDIO_CHANNEL_COUNT:
-        {
-            int32_t channelCount;
-            if (mAudioTrack == 0 ||
-                    !mAudioTrack->getFormat()->findInt32(kKeyChannelCount, &channelCount)) {
-                channelCount = 0;
-            }
-            reply->writeInt32(channelCount);
-        }
-        return OK;
-    default:
-        {
-            return ERROR_UNSUPPORTED;
-        }
-    }
-}
-
-status_t AwesomePlayer::setPlaybackSettings(const AudioPlaybackRate &rate) {
-    Mutex::Autolock autoLock(mLock);
-    // cursory sanity check for non-audio and paused cases
-    if ((rate.mSpeed != 0.f && rate.mSpeed < AUDIO_TIMESTRETCH_SPEED_MIN)
-        || rate.mSpeed > AUDIO_TIMESTRETCH_SPEED_MAX
-        || rate.mPitch < AUDIO_TIMESTRETCH_SPEED_MIN
-        || rate.mPitch > AUDIO_TIMESTRETCH_SPEED_MAX) {
-        return BAD_VALUE;
-    }
-
-    status_t err = OK;
-    if (rate.mSpeed == 0.f) {
-        if (mFlags & PLAYING) {
-            modifyFlags(CACHE_UNDERRUN, CLEAR); // same as pause
-            err = pause_l();
-        }
-        if (err == OK) {
-            // save settings (using old speed) in case player is resumed
-            AudioPlaybackRate newRate = rate;
-            newRate.mSpeed = mPlaybackSettings.mSpeed;
-            mPlaybackSettings = newRate;
-        }
-        return err;
-    }
-    if (mAudioPlayer != NULL) {
-        err = mAudioPlayer->setPlaybackRate(rate);
-    }
-    if (err == OK) {
-        mPlaybackSettings = rate;
-        if (!(mFlags & PLAYING)) {
-            play_l();
-        }
-    }
-    return err;
-}
-
-status_t AwesomePlayer::getPlaybackSettings(AudioPlaybackRate *rate /* nonnull */) {
-    if (mAudioPlayer != NULL) {
-        status_t err = mAudioPlayer->getPlaybackRate(rate);
-        if (err == OK) {
-            mPlaybackSettings = *rate;
-            Mutex::Autolock autoLock(mLock);
-            if (!(mFlags & PLAYING)) {
-                rate->mSpeed = 0.f;
-            }
-        }
-        return err;
-    }
-    *rate = mPlaybackSettings;
-    return OK;
-}
-
-status_t AwesomePlayer::getTrackInfo(Parcel *reply) const {
-    Mutex::Autolock autoLock(mLock);
-    size_t trackCount = mExtractor->countTracks();
-    if (mTextDriver != NULL) {
-        trackCount += mTextDriver->countExternalTracks();
-    }
-
-    reply->writeInt32(trackCount);
-    for (size_t i = 0; i < mExtractor->countTracks(); ++i) {
-        sp<MetaData> meta = mExtractor->getTrackMetaData(i);
-
-        const char *_mime;
-        CHECK(meta->findCString(kKeyMIMEType, &_mime));
-
-        String8 mime = String8(_mime);
-
-        reply->writeInt32(2); // 2 fields
-
-        if (!strncasecmp(mime.string(), "video/", 6)) {
-            reply->writeInt32(MEDIA_TRACK_TYPE_VIDEO);
-        } else if (!strncasecmp(mime.string(), "audio/", 6)) {
-            reply->writeInt32(MEDIA_TRACK_TYPE_AUDIO);
-        } else if (!strcasecmp(mime.string(), MEDIA_MIMETYPE_TEXT_3GPP)) {
-            reply->writeInt32(MEDIA_TRACK_TYPE_TIMEDTEXT);
-        } else {
-            reply->writeInt32(MEDIA_TRACK_TYPE_UNKNOWN);
-        }
-
-        const char *lang;
-        if (!meta->findCString(kKeyMediaLanguage, &lang)) {
-            lang = "und";
-        }
-        reply->writeString16(String16(lang));
-    }
-
-    if (mTextDriver != NULL) {
-        mTextDriver->getExternalTrackInfo(reply);
-    }
-    return OK;
-}
-
-status_t AwesomePlayer::selectAudioTrack_l(
-        const sp<MediaSource>& source, size_t trackIndex) {
-
-    ALOGI("selectAudioTrack_l: trackIndex=%zu, mFlags=0x%x", trackIndex, mFlags);
-
-    {
-        Mutex::Autolock autoLock(mStatsLock);
-        if ((ssize_t)trackIndex == mActiveAudioTrackIndex) {
-            ALOGI("Track %zu is active. Does nothing.", trackIndex);
-            return OK;
-        }
-        //mStats.mFlags = mFlags;
-    }
-
-    if (mSeeking != NO_SEEK) {
-        ALOGE("Selecting a track while seeking is not supported");
-        return ERROR_UNSUPPORTED;
-    }
-
-    if ((mFlags & PREPARED) == 0) {
-        ALOGE("Data source has not finished preparation");
-        return ERROR_UNSUPPORTED;
-    }
-
-    CHECK(source != NULL);
-    bool wasPlaying = (mFlags & PLAYING) != 0;
-
-    pause_l();
-
-    int64_t curTimeUs;
-    CHECK_EQ(getPosition(&curTimeUs), (status_t)OK);
-
-    if ((mAudioPlayer == NULL || !(mFlags & AUDIOPLAYER_STARTED))
-            && mAudioSource != NULL) {
-        // If we had an audio player, it would have effectively
-        // taken possession of the audio source and stopped it when
-        // _it_ is stopped. Otherwise this is still our responsibility.
-        mAudioSource->stop();
-    }
-    mAudioSource.clear();
-    mOmxSource.clear();
-
-    mTimeSource = NULL;
-
-    delete mAudioPlayer;
-    mAudioPlayer = NULL;
-
-    modifyFlags(AUDIOPLAYER_STARTED, CLEAR);
-
-    setAudioSource(source);
-
-    modifyFlags(AUDIO_AT_EOS, CLEAR);
-    modifyFlags(AT_EOS, CLEAR);
-
-    status_t err;
-    if ((err = initAudioDecoder()) != OK) {
-        ALOGE("Failed to init audio decoder: 0x%x", err);
-        return err;
-    }
-
-    mSeekNotificationSent = true;
-    seekTo_l(curTimeUs);
-
-    if (wasPlaying) {
-        play_l();
-    }
-
-    mActiveAudioTrackIndex = trackIndex;
-
-    return OK;
-}
-
-status_t AwesomePlayer::selectTrack(size_t trackIndex, bool select) {
-    ATRACE_CALL();
-    ALOGV("selectTrack: trackIndex = %zu and select=%d", trackIndex, select);
-    Mutex::Autolock autoLock(mLock);
-    size_t trackCount = mExtractor->countTracks();
-    if (mTextDriver != NULL) {
-        trackCount += mTextDriver->countExternalTracks();
-    }
-    if (trackIndex >= trackCount) {
-        ALOGE("Track index (%zu) is out of range [0, %zu)", trackIndex, trackCount);
-        return ERROR_OUT_OF_RANGE;
-    }
-
-    bool isAudioTrack = false;
-    if (trackIndex < mExtractor->countTracks()) {
-        sp<MetaData> meta = mExtractor->getTrackMetaData(trackIndex);
-        const char *mime;
-        CHECK(meta->findCString(kKeyMIMEType, &mime));
-        isAudioTrack = !strncasecmp(mime, "audio/", 6);
-
-        if (!isAudioTrack && strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) != 0) {
-            ALOGE("Track %zu is not either audio or timed text", trackIndex);
-            return ERROR_UNSUPPORTED;
-        }
-    }
-
-    if (isAudioTrack) {
-        if (!select) {
-            ALOGE("Deselect an audio track (%zu) is not supported", trackIndex);
-            return ERROR_UNSUPPORTED;
-        }
-        return selectAudioTrack_l(mExtractor->getTrack(trackIndex), trackIndex);
-    }
-
-    // Timed text track handling
-    if (mTextDriver == NULL) {
-        return INVALID_OPERATION;
-    }
-
-    status_t err = OK;
-    if (select) {
-        err = mTextDriver->selectTrack(trackIndex);
-        if (err == OK) {
-            modifyFlags(TEXTPLAYER_INITIALIZED, SET);
-            if (mFlags & PLAYING && !(mFlags & TEXT_RUNNING)) {
-                mTextDriver->start();
-                modifyFlags(TEXT_RUNNING, SET);
-            }
-        }
-    } else {
-        err = mTextDriver->unselectTrack(trackIndex);
-        if (err == OK) {
-            modifyFlags(TEXTPLAYER_INITIALIZED, CLEAR);
-            modifyFlags(TEXT_RUNNING, CLEAR);
-        }
-    }
-    return err;
-}
-
-size_t AwesomePlayer::countTracks() const {
-    return mExtractor->countTracks() + mTextDriver->countExternalTracks();
-}
-
-status_t AwesomePlayer::setVideoScalingMode(int32_t mode) {
-    Mutex::Autolock lock(mLock);
-    return setVideoScalingMode_l(mode);
-}
-
-status_t AwesomePlayer::setVideoScalingMode_l(int32_t mode) {
-    mVideoScalingMode = mode;
-    if (mNativeWindow != NULL) {
-        status_t err = native_window_set_scaling_mode(
-                mNativeWindow.get(), mVideoScalingMode);
-        if (err != OK) {
-            ALOGW("Failed to set scaling mode: %d", err);
-        }
-        return err;
-    }
-    return OK;
-}
-
-status_t AwesomePlayer::invoke(const Parcel &request, Parcel *reply) {
-    ATRACE_CALL();
-    if (NULL == reply) {
-        return android::BAD_VALUE;
-    }
-    int32_t methodId;
-    status_t ret = request.readInt32(&methodId);
-    if (ret != android::OK) {
-        return ret;
-    }
-    switch(methodId) {
-        case INVOKE_ID_SET_VIDEO_SCALING_MODE:
-        {
-            int mode = request.readInt32();
-            return setVideoScalingMode(mode);
-        }
-
-        case INVOKE_ID_GET_TRACK_INFO:
-        {
-            return getTrackInfo(reply);
-        }
-        case INVOKE_ID_ADD_EXTERNAL_SOURCE:
-        {
-            Mutex::Autolock autoLock(mLock);
-            if (mTextDriver == NULL) {
-                mTextDriver = new TimedTextDriver(mListener, mHTTPService);
-            }
-            // String values written in Parcel are UTF-16 values.
-            String8 uri(request.readString16());
-            String8 mimeType(request.readString16());
-            size_t nTracks = countTracks();
-            return mTextDriver->addOutOfBandTextSource(nTracks, uri, mimeType);
-        }
-        case INVOKE_ID_ADD_EXTERNAL_SOURCE_FD:
-        {
-            Mutex::Autolock autoLock(mLock);
-            if (mTextDriver == NULL) {
-                mTextDriver = new TimedTextDriver(mListener, mHTTPService);
-            }
-            int fd         = request.readFileDescriptor();
-            off64_t offset = request.readInt64();
-            off64_t length  = request.readInt64();
-            String8 mimeType(request.readString16());
-            size_t nTracks = countTracks();
-            return mTextDriver->addOutOfBandTextSource(
-                    nTracks, fd, offset, length, mimeType);
-        }
-        case INVOKE_ID_SELECT_TRACK:
-        {
-            int trackIndex = request.readInt32();
-            return selectTrack(trackIndex, true /* select */);
-        }
-        case INVOKE_ID_UNSELECT_TRACK:
-        {
-            int trackIndex = request.readInt32();
-            return selectTrack(trackIndex, false /* select */);
-        }
-        default:
-        {
-            return ERROR_UNSUPPORTED;
-        }
-    }
-    // It will not reach here.
-    return OK;
-}
-
-bool AwesomePlayer::isStreamingHTTP() const {
-    return mCachedSource != NULL || mWVMExtractor != NULL;
-}
-
-status_t AwesomePlayer::dump(
-        int fd, const Vector<String16> & /* args */) const {
-    Mutex::Autolock autoLock(mStatsLock);
-
-    FILE *out = fdopen(dup(fd), "w");
-
-    fprintf(out, " AwesomePlayer\n");
-    if (mStats.mFd < 0) {
-        fprintf(out, "  URI(%s)", uriDebugString(mUri, mFlags & INCOGNITO).c_str());
-    } else {
-        fprintf(out, "  fd(%d)", mStats.mFd);
-    }
-
-    fprintf(out, ", flags(0x%08x)", mStats.mFlags);
-
-    if (mStats.mBitrate >= 0) {
-        fprintf(out, ", bitrate(%" PRId64 " bps)", mStats.mBitrate);
-    }
-
-    fprintf(out, "\n");
-
-    for (size_t i = 0; i < mStats.mTracks.size(); ++i) {
-        const TrackStat &stat = mStats.mTracks.itemAt(i);
-
-        fprintf(out, "  Track %zu\n", i + 1);
-        fprintf(out, "   MIME(%s)", stat.mMIME.string());
-
-        if (!stat.mDecoderName.isEmpty()) {
-            fprintf(out, ", decoder(%s)", stat.mDecoderName.string());
-        }
-
-        fprintf(out, "\n");
-
-        if ((ssize_t)i == mStats.mVideoTrackIndex) {
-            fprintf(out,
-                    "   videoDimensions(%d x %d), "
-                    "numVideoFramesDecoded(%" PRId64 "), "
-                    "numVideoFramesDropped(%" PRId64 ")\n",
-                    mStats.mVideoWidth,
-                    mStats.mVideoHeight,
-                    mStats.mNumVideoFramesDecoded,
-                    mStats.mNumVideoFramesDropped);
-        }
-    }
-
-    fclose(out);
-    out = NULL;
-
-    return OK;
-}
-
-void AwesomePlayer::modifyFlags(unsigned value, FlagMode mode) {
-    switch (mode) {
-        case SET:
-            mFlags |= value;
-            break;
-        case CLEAR:
-            if ((value & CACHE_UNDERRUN) && (mFlags & CACHE_UNDERRUN)) {
-                notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END);
-            }
-            mFlags &= ~value;
-            break;
-        case ASSIGN:
-            mFlags = value;
-            break;
-        default:
-            TRESPASS();
-    }
-
-    {
-        Mutex::Autolock autoLock(mStatsLock);
-        mStats.mFlags = mFlags;
-    }
-}
-
-void AwesomePlayer::onAudioTearDownEvent() {
-
-    Mutex::Autolock autoLock(mLock);
-    if (!mAudioTearDownEventPending) {
-        return;
-    }
-    mAudioTearDownEventPending = false;
-
-    ALOGV("onAudioTearDownEvent");
-
-    // stream info is cleared by reset_l() so copy what we need
-    mAudioTearDownWasPlaying = (mFlags & PLAYING);
-    KeyedVector<String8, String8> uriHeaders(mUriHeaders);
-    sp<DataSource> fileSource(mFileSource);
-
-    mStatsLock.lock();
-    String8 uri(mStats.mURI);
-    mStatsLock.unlock();
-
-    // get current position so we can start recreated stream from here
-    getPosition(&mAudioTearDownPosition);
-
-    sp<IMediaHTTPService> savedHTTPService = mHTTPService;
-
-    bool wasLooping = mFlags & LOOPING;
-    // Reset and recreate
-    reset_l();
-
-    status_t err;
-
-    if (fileSource != NULL) {
-        mFileSource = fileSource;
-        err = setDataSource_l(fileSource);
-    } else {
-        err = setDataSource_l(savedHTTPService, uri, &uriHeaders);
-    }
-
-    mFlags |= PREPARING;
-    if ( err != OK ) {
-        // This will force beingPrepareAsync_l() to notify
-        // a MEDIA_ERROR to the client and abort the prepare
-        mFlags |= PREPARE_CANCELLED;
-    }
-    if (wasLooping) {
-        mFlags |= LOOPING;
-    }
-
-    mAudioTearDown = true;
-    mIsAsyncPrepare = true;
-
-    // Call prepare for the host decoding
-    beginPrepareAsync_l();
-}
-
-}  // namespace android
diff --git a/media/libstagefright/CameraSource.cpp b/media/libstagefright/CameraSource.cpp
index 66280da..ec0cfb7 100644
--- a/media/libstagefright/CameraSource.cpp
+++ b/media/libstagefright/CameraSource.cpp
@@ -44,7 +44,7 @@
 static const int64_t CAMERA_SOURCE_TIMEOUT_NS = 3000000000LL;
 
 struct CameraSourceListener : public CameraListener {
-    CameraSourceListener(const sp<CameraSource> &source);
+    explicit CameraSourceListener(const sp<CameraSource> &source);
 
     virtual void notify(int32_t msgType, int32_t ext1, int32_t ext2);
     virtual void postData(int32_t msgType, const sp<IMemory> &dataPtr,
diff --git a/media/libstagefright/ClockEstimator.cpp b/media/libstagefright/ClockEstimator.cpp
deleted file mode 100644
index 34d1e42..0000000
--- a/media/libstagefright/ClockEstimator.cpp
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
-**
-** Copyright 2014, 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 "ClockEstimator"
-#include <utils/Log.h>
-
-#include <math.h>
-#include <media/stagefright/ClockEstimator.h>
-
-#include <media/stagefright/foundation/ADebug.h>
-
-namespace android {
-
-WindowedLinearFitEstimator::WindowedLinearFitEstimator(
-        size_t headLength, double headFactor, size_t mainLength, double tailFactor)
-    : mHeadFactorInv(1. / headFactor),
-      mTailFactor(tailFactor),
-      mHistoryLength(mainLength + headLength),
-      mHeadLength(headLength) {
-    reset();
-    mXHistory.resize(mHistoryLength);
-    mYHistory.resize(mHistoryLength);
-    mFirstWeight = pow(headFactor, mHeadLength);
-}
-
-WindowedLinearFitEstimator::LinearFit::LinearFit() {
-    reset();
-}
-
-void WindowedLinearFitEstimator::LinearFit::reset() {
-    mX = mXX = mY = mYY = mXY = mW = 0.;
-}
-
-double WindowedLinearFitEstimator::LinearFit::size() const {
-    double s = mW * mW + mX * mX + mY * mY + mXX * mXX + mXY * mXY + mYY * mYY;
-    if (s > 1e72) {
-        // 1e72 corresponds to clock monotonic time of about 8 years
-        ALOGW("estimator is overflowing: w=%g x=%g y=%g xx=%g xy=%g yy=%g",
-              mW, mX, mY, mXX, mXY, mYY);
-    }
-    return s;
-}
-
-void WindowedLinearFitEstimator::LinearFit::add(double x, double y, double w) {
-    mW += w;
-    mX += w * x;
-    mY += w * y;
-    mXX += w * x * x;
-    mXY += w * x * y;
-    mYY += w * y * y;
-}
-
-void WindowedLinearFitEstimator::LinearFit::combine(const LinearFit &lf) {
-    mW += lf.mW;
-    mX += lf.mX;
-    mY += lf.mY;
-    mXX += lf.mXX;
-    mXY += lf.mXY;
-    mYY += lf.mYY;
-}
-
-void WindowedLinearFitEstimator::LinearFit::scale(double w) {
-    mW *= w;
-    mX *= w;
-    mY *= w;
-    mXX *= w;
-    mXY *= w;
-    mYY *= w;
-}
-
-double WindowedLinearFitEstimator::LinearFit::interpolate(double x) {
-    double div = mW * mXX - mX * mX;
-    if (fabs(div) < 1e-5 * mW * mW) {
-        // this only should happen on the first value
-        return x;
-        // assuming a = 1, we could also return x + (mY - mX) / mW;
-    }
-    double a_div = (mW * mXY - mX * mY);
-    double b_div = (mXX * mY - mX * mXY);
-    ALOGV("a=%.4g b=%.4g in=%g out=%g",
-            a_div / div, b_div / div, x, (a_div * x + b_div) / div);
-    return (a_div * x + b_div) / div;
-}
-
-double WindowedLinearFitEstimator::estimate(double x, double y) {
-    /*
-     * TODO: We could update the head by adding the new sample to it
-     * and amplifying it, but this approach can lead to unbounded
-     * error. Instead, we recalculate the head at each step, which
-     * is computationally more expensive. We could balance the two
-     * methods by recalculating just before the error becomes
-     * significant.
-     */
-    const bool update_head = false;
-    if (update_head) {
-        // add new sample to the head
-        mHead.scale(mHeadFactorInv); // amplify head
-        mHead.add(x, y, mFirstWeight);
-    }
-
-    /*
-     * TRICKY: place elements into the circular buffer at decreasing
-     * indices, so that we can access past elements by addition
-     * (thereby avoiding potentially negative indices.)
-     */
-    if (mNumSamples >= mHeadLength) {
-        // move last head sample from head to the main window
-        size_t lastHeadIx = (mSampleIx + mHeadLength) % mHistoryLength;
-        if (update_head) {
-            mHead.add(mXHistory[lastHeadIx], mYHistory[lastHeadIx], -1.); // remove
-        }
-        mMain.add(mXHistory[lastHeadIx], mYHistory[lastHeadIx], 1.);
-        if (mNumSamples >= mHistoryLength) {
-            // move last main sample from main window to tail
-            mMain.add(mXHistory[mSampleIx], mYHistory[mSampleIx], -1.); // remove
-            mTail.add(mXHistory[mSampleIx], mYHistory[mSampleIx], 1.);
-            mTail.scale(mTailFactor); // attenuate tail
-        }
-    }
-
-    mXHistory.editItemAt(mSampleIx) = x;
-    mYHistory.editItemAt(mSampleIx) = y;
-    if (mNumSamples < mHistoryLength) {
-        ++mNumSamples;
-    }
-
-    // recalculate head unless we were using the update method
-    if (!update_head) {
-        mHead.reset();
-        double w = mFirstWeight;
-        for (size_t headIx = 0; headIx < mHeadLength && headIx < mNumSamples; ++headIx) {
-            size_t ix = (mSampleIx + headIx) % mHistoryLength;
-            mHead.add(mXHistory[ix], mYHistory[ix], w);
-            w *= mHeadFactorInv;
-        }
-    }
-
-    if (mSampleIx > 0) {
-        --mSampleIx;
-    } else {
-        mSampleIx = mHistoryLength - 1;
-    }
-
-    // return estimation result
-    LinearFit total;
-    total.combine(mHead);
-    total.combine(mMain);
-    total.combine(mTail);
-    return total.interpolate(x);
-}
-
-void WindowedLinearFitEstimator::reset() {
-    mHead.reset();
-    mMain.reset();
-    mTail.reset();
-    mNumSamples = 0;
-    mSampleIx = mHistoryLength - 1;
-}
-
-}; // namespace android
-
-
diff --git a/media/libstagefright/DataSource.cpp b/media/libstagefright/DataSource.cpp
index 75ef288..5020c6c 100644
--- a/media/libstagefright/DataSource.cpp
+++ b/media/libstagefright/DataSource.cpp
@@ -246,7 +246,7 @@
                 *contentType = httpSource->getMIMEType();
             }
 
-            source = new NuCachedSource2(
+            source = NuCachedSource2::Create(
                     httpSource,
                     cacheConfig.isEmpty() ? NULL : cacheConfig.string(),
                     disconnectAtHighwatermark);
diff --git a/media/libstagefright/DataURISource.cpp b/media/libstagefright/DataURISource.cpp
index 2a61c3a..3dc345f 100644
--- a/media/libstagefright/DataURISource.cpp
+++ b/media/libstagefright/DataURISource.cpp
@@ -28,7 +28,7 @@
         return NULL;
     }
 
-    char *commaPos = strrchr(uri, ',');
+    const char *commaPos = strrchr(uri, ',');
 
     if (commaPos == NULL) {
         return NULL;
diff --git a/media/libstagefright/FLACExtractor.cpp b/media/libstagefright/FLACExtractor.cpp
index 89a91f7..43f16a8 100644
--- a/media/libstagefright/FLACExtractor.cpp
+++ b/media/libstagefright/FLACExtractor.cpp
@@ -73,7 +73,7 @@
 class FLACParser : public RefBase {
 
 public:
-    FLACParser(
+    explicit FLACParser(
         const sp<DataSource> &dataSource,
         // If metadata pointers aren't provided, we don't fill them
         const sp<MetaData> &fileMetadata = 0,
diff --git a/media/libstagefright/FileSource.cpp b/media/libstagefright/FileSource.cpp
index 565f156..37053ec 100644
--- a/media/libstagefright/FileSource.cpp
+++ b/media/libstagefright/FileSource.cpp
@@ -166,7 +166,7 @@
     }
 
     if (mDrmBuf != NULL && mDrmBufSize > 0 && (offset + mOffset) >= mDrmBufOffset
-            && (offset + mOffset + size) <= (mDrmBufOffset + mDrmBufSize)) {
+            && (offset + mOffset + size) <= static_cast<size_t>(mDrmBufOffset + mDrmBufSize)) {
         /* Use buffered data */
         memcpy(data, (void*)(mDrmBuf+(offset+mOffset-mDrmBufOffset)), size);
         return size;
@@ -177,7 +177,7 @@
                 DRM_CACHE_SIZE, offset + mOffset);
         if (mDrmBufSize > 0) {
             int64_t dataRead = 0;
-            dataRead = size > mDrmBufSize ? mDrmBufSize : size;
+            dataRead = size > static_cast<size_t>(mDrmBufSize) ? mDrmBufSize : size;
             memcpy(data, (void*)mDrmBuf, dataRead);
             return dataRead;
         } else {
diff --git a/media/libstagefright/MPEG2TSWriter.cpp b/media/libstagefright/MPEG2TSWriter.cpp
index ef07aa0..8f30a8a 100644
--- a/media/libstagefright/MPEG2TSWriter.cpp
+++ b/media/libstagefright/MPEG2TSWriter.cpp
@@ -35,7 +35,7 @@
 namespace android {
 
 struct MPEG2TSWriter::SourceInfo : public AHandler {
-    SourceInfo(const sp<MediaSource> &source);
+    explicit SourceInfo(const sp<MediaSource> &source);
 
     void start(const sp<AMessage> &notify);
     void stop();
diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/libstagefright/MPEG4Extractor.cpp
index c0f4e6c..a53ab81 100755
--- a/media/libstagefright/MPEG4Extractor.cpp
+++ b/media/libstagefright/MPEG4Extractor.cpp
@@ -172,7 +172,7 @@
 // Each MPEG4DataSource caches the sampletable metadata for a single track.
 
 struct MPEG4DataSource : public DataSource {
-    MPEG4DataSource(const sp<DataSource> &source);
+    explicit MPEG4DataSource(const sp<DataSource> &source);
 
     virtual status_t initCheck() const;
     virtual ssize_t readAt(off64_t offset, void *data, size_t size);
@@ -1022,7 +1022,7 @@
                     int64_t delay = (media_time  * samplerate + 500000) / 1000000;
                     mLastTrack->meta->setInt32(kKeyEncoderDelay, delay);
 
-                    int64_t paddingus = duration - (segment_duration + media_time);
+                    int64_t paddingus = duration - (int64_t)(segment_duration + media_time);
                     if (paddingus < 0) {
                         // track duration from media header (which is what kKeyDuration is) might
                         // be slightly shorter than the segment duration, which would make the
@@ -1952,15 +1952,14 @@
                 return ERROR_IO;
             }
 
-            if (mLastTrack == NULL)
-                return ERROR_MALFORMED;
-
             uint32_t type = ntohl(buffer);
             // For the 3GPP file format, the handler-type within the 'hdlr' box
             // shall be 'text'. We also want to support 'sbtl' handler type
             // for a practical reason as various MPEG4 containers use it.
             if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) {
-                mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP);
+                if (mLastTrack != NULL) {
+                    mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP);
+                }
             }
 
             break;
@@ -2565,6 +2564,12 @@
                     mLastCommentName.setTo((const char *)buffer + 4);
                     break;
                 case FOURCC('d', 'a', 't', 'a'):
+                    if (size < 8) {
+                        delete[] buffer;
+                        buffer = NULL;
+                        ALOGE("b/24346430");
+                        return ERROR_MALFORMED;
+                    }
                     mLastCommentData.setTo((const char *)buffer + 8);
                     break;
             }
@@ -4145,7 +4150,10 @@
             (const uint8_t *)mBuffer->data() + mBuffer->range_offset();
 
         size_t nal_size = parseNALSize(src);
-        if (mBuffer->range_length() < mNALLengthSize + nal_size) {
+        if (mNALLengthSize > SIZE_MAX - nal_size) {
+            ALOGE("b/24441553, b/24445122");
+        }
+        if (mBuffer->range_length() - mNALLengthSize < nal_size) {
             ALOGE("incomplete NAL unit.");
 
             mBuffer->release();
@@ -4432,7 +4440,11 @@
             (const uint8_t *)mBuffer->data() + mBuffer->range_offset();
 
         size_t nal_size = parseNALSize(src);
-        if (mBuffer->range_length() < mNALLengthSize + nal_size) {
+        if (mNALLengthSize > SIZE_MAX - nal_size) {
+            ALOGE("b/24441553, b/24445122");
+        }
+
+        if (mBuffer->range_length() - mNALLengthSize < nal_size) {
             ALOGE("incomplete NAL unit.");
 
             mBuffer->release();
@@ -4533,7 +4545,15 @@
                     continue;
                 }
 
-                CHECK(dstOffset + 4 <= mBuffer->size());
+                if (dstOffset > SIZE_MAX - 4 ||
+                        dstOffset + 4 > SIZE_MAX - nalLength ||
+                        dstOffset + 4 + nalLength > mBuffer->size()) {
+                    ALOGE("b/26365349 : %zu %zu", dstOffset, mBuffer->size());
+                    android_errorWriteLog(0x534e4554, "26365349");
+                    mBuffer->release();
+                    mBuffer = NULL;
+                    return ERROR_MALFORMED;
+                }
 
                 dstData[dstOffset++] = 0;
                 dstData[dstOffset++] = 0;
diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp
index 78d4fb1..8c25a7f 100644
--- a/media/libstagefright/MPEG4Writer.cpp
+++ b/media/libstagefright/MPEG4Writer.cpp
@@ -594,7 +594,7 @@
     if (mMaxFileDurationLimitUs != 0) {
         if (bitRate > 0) {
             int64_t size2 =
-                ((mMaxFileDurationLimitUs * bitRate * 6) / 1000 / 8000000);
+                ((mMaxFileDurationLimitUs / 1000) * bitRate * 6) / 8000000;
             if (mMaxFileSizeLimitBytes != 0 && mIsFileSizeLimitExplicitlyRequested) {
                 // When both file size and duration limits are set,
                 // we use the smaller limit of the two.
diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp
index cd59709..2760233 100644
--- a/media/libstagefright/MediaCodec.cpp
+++ b/media/libstagefright/MediaCodec.cpp
@@ -44,7 +44,6 @@
 #include <media/stagefright/MediaFilter.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
 #include <media/stagefright/PersistentSurface.h>
 #include <media/stagefright/SurfaceUtils.h>
 #include <mediautils/BatteryNotifier.h>
@@ -63,9 +62,10 @@
 }
 
 static const int kMaxRetry = 2;
+static const int kMaxReclaimWaitTimeInUs = 500000;  // 0.5s
 
 struct ResourceManagerClient : public BnResourceManagerClient {
-    ResourceManagerClient(MediaCodec* codec) : mMediaCodec(codec) {}
+    explicit ResourceManagerClient(MediaCodec* codec) : mMediaCodec(codec) {}
 
     virtual bool reclaimResource() {
         sp<MediaCodec> codec = mMediaCodec.promote();
@@ -74,6 +74,12 @@
             return true;
         }
         status_t err = codec->reclaim();
+        if (err == WOULD_BLOCK) {
+            ALOGD("Wait for the client to release codec.");
+            usleep(kMaxReclaimWaitTimeInUs);
+            ALOGD("Try to reclaim again.");
+            err = codec->reclaim(true /* force */);
+        }
         if (err != OK) {
             ALOGW("ResourceManagerClient failed to release codec with err %d", err);
         }
@@ -164,7 +170,7 @@
 
 // static
 sp<MediaCodec> MediaCodec::CreateByType(
-        const sp<ALooper> &looper, const char *mime, bool encoder, status_t *err, pid_t pid) {
+        const sp<ALooper> &looper, const AString &mime, bool encoder, status_t *err, pid_t pid) {
     sp<MediaCodec> codec = new MediaCodec(looper, pid);
 
     const status_t ret = codec->init(mime, true /* nameIsType */, encoder);
@@ -176,7 +182,7 @@
 
 // static
 sp<MediaCodec> MediaCodec::CreateByComponentName(
-        const sp<ALooper> &looper, const char *name, status_t *err, pid_t pid) {
+        const sp<ALooper> &looper, const AString &name, status_t *err, pid_t pid) {
     sp<MediaCodec> codec = new MediaCodec(looper, pid);
 
     const status_t ret = codec->init(name, false /* nameIsType */, false /* encoder */);
@@ -187,6 +193,22 @@
 }
 
 // static
+status_t MediaCodec::QueryCapabilities(
+        const AString &name, const AString &mime, bool isEncoder,
+        sp<MediaCodecInfo::Capabilities> *caps /* nonnull */) {
+    // TRICKY: this method is used by MediaCodecList/Info during its
+    // initialization. As such, we cannot create a MediaCodec instance
+    // because that requires an initialized MediaCodecList.
+
+    sp<CodecBase> codec = GetCodecBase(name);
+    if (codec == NULL) {
+        return NAME_NOT_FOUND;
+    }
+
+    return codec->queryCapabilities(name, mime, isEncoder, caps);
+}
+
+// static
 sp<PersistentSurface> MediaCodec::CreatePersistentInputSurface() {
     OMXClient client;
     CHECK_EQ(client.connect(), (status_t)OK);
@@ -292,6 +314,18 @@
     response->postReply(replyID);
 }
 
+//static
+sp<CodecBase> MediaCodec::GetCodecBase(const AString &name, bool nameIsType) {
+    // at this time only ACodec specifies a mime type.
+    if (nameIsType || name.startsWithIgnoreCase("omx.")) {
+        return new ACodec;
+    } else if (name.startsWithIgnoreCase("android.filter.")) {
+        return new MediaFilter;
+    } else {
+        return NULL;
+    }
+}
+
 status_t MediaCodec::init(const AString &name, bool nameIsType, bool encoder) {
     mResourceManagerService->init();
 
@@ -305,12 +339,8 @@
     // we need to invest in an extra looper to free the main event
     // queue.
 
-    if (nameIsType || !strncasecmp(name.c_str(), "omx.", 4)) {
-        mCodec = new ACodec;
-    } else if (!nameIsType
-            && !strncasecmp(name.c_str(), "android.filter.", 15)) {
-        mCodec = new MediaFilter;
-    } else {
+    mCodec = GetCodecBase(name, nameIsType);
+    if (mCodec == NULL) {
         return NAME_NOT_FOUND;
     }
 
@@ -571,12 +601,34 @@
     return PostAndAwaitResponse(msg, &response);
 }
 
-status_t MediaCodec::reclaim() {
+bool MediaCodec::hasPendingBuffer(int portIndex) {
+    const Vector<BufferInfo> &buffers = mPortBuffers[portIndex];
+    for (size_t i = 0; i < buffers.size(); ++i) {
+        const BufferInfo &info = buffers.itemAt(i);
+        if (info.mOwnedByClient) {
+            return true;
+        }
+    }
+    return false;
+}
+
+bool MediaCodec::hasPendingBuffer() {
+    return hasPendingBuffer(kPortIndexInput) || hasPendingBuffer(kPortIndexOutput);
+}
+
+status_t MediaCodec::reclaim(bool force) {
+    ALOGD("MediaCodec::reclaim(%p) %s", this, mInitName.c_str());
     sp<AMessage> msg = new AMessage(kWhatRelease, this);
     msg->setInt32("reclaimed", 1);
+    msg->setInt32("force", force ? 1 : 0);
 
     sp<AMessage> response;
-    return PostAndAwaitResponse(msg, &response);
+    status_t ret = PostAndAwaitResponse(msg, &response);
+    if (ret == -ENOENT) {
+        ALOGD("MediaCodec looper is gone, skip reclaim");
+        ret = OK;
+    }
+    return ret;
 }
 
 status_t MediaCodec::release() {
@@ -1154,8 +1206,10 @@
                         resourceType = String8(kResourceNonSecureCodec);
                     }
 
-                    const char *subtype = mIsVideo ? kResourceVideoCodec : kResourceAudioCodec;
-                    addResource(resourceType, String8(subtype), 1);
+                    if (mIsVideo) {
+                        // audio codec is currently ignored.
+                        addResource(resourceType, String8(kResourceVideoCodec), 1);
+                    }
 
                     (new AMessage)->postReply(mReplyID);
                     break;
@@ -1784,6 +1838,23 @@
             msg->findInt32("reclaimed", &reclaimed);
             if (reclaimed) {
                 mReleasedByResourceManager = true;
+
+                int32_t force = 0;
+                msg->findInt32("force", &force);
+                if (!force && hasPendingBuffer()) {
+                    ALOGW("Can't reclaim codec right now due to pending buffers.");
+
+                    // return WOULD_BLOCK to ask resource manager to retry later.
+                    sp<AMessage> response = new AMessage;
+                    response->setInt32("err", WOULD_BLOCK);
+                    response->postReply(replyID);
+
+                    // notify the async client
+                    if (mFlags & kFlagIsAsync) {
+                        onError(DEAD_OBJECT, ACTION_CODE_FATAL);
+                    }
+                    break;
+                }
             }
 
             if (!((mFlags & kFlagIsComponentAllocated) && targetState == UNINITIALIZED) // See 1
diff --git a/media/libstagefright/MediaCodecList.cpp b/media/libstagefright/MediaCodecList.cpp
index c657195..08bb45d 100644
--- a/media/libstagefright/MediaCodecList.cpp
+++ b/media/libstagefright/MediaCodecList.cpp
@@ -30,10 +30,11 @@
 
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/AMessage.h>
+#include <media/stagefright/ACodec.h>
+#include <media/stagefright/MediaCodec.h>
 #include <media/stagefright/MediaCodecList.h>
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
 
 #include <sys/stat.h>
 #include <utils/threads.h>
@@ -181,7 +182,7 @@
 
 void MediaCodecList::parseTopLevelXMLFile(const char *codecs_xml, bool ignore_errors) {
     // get href_base
-    char *href_base_end = strrchr(codecs_xml, '/');
+    const char *href_base_end = strrchr(codecs_xml, '/');
     if (href_base_end != NULL) {
         mHrefBase = AString(codecs_xml, href_base_end - codecs_xml + 1);
     }
@@ -751,15 +752,19 @@
     ALOGV("initializeCapabilities %s:%s",
             mCurrentInfo->mName.c_str(), type);
 
-    CodecCapabilities caps;
-    status_t err = QueryCodec(
-            mOMX,
-            mCurrentInfo->mName.c_str(),
+    sp<MediaCodecInfo::Capabilities> caps;
+    status_t err = MediaCodec::QueryCapabilities(
+            mCurrentInfo->mName,
             type,
             mCurrentInfo->mIsEncoder,
             &caps);
     if (err != OK) {
         return err;
+    } else if (caps == NULL) {
+        ALOGE("MediaCodec::QueryCapabilities returned OK but no capabilities for '%s':'%s':'%s'",
+                mCurrentInfo->mName.c_str(), type,
+                mCurrentInfo->mIsEncoder ? "encoder" : "decoder");
+        return UNKNOWN_ERROR;
     }
 
     return mCurrentInfo->initializeCapabilities(caps);
@@ -1115,4 +1120,85 @@
     return mGlobalSettings;
 }
 
+//static
+bool MediaCodecList::isSoftwareCodec(const AString &componentName) {
+    return componentName.startsWithIgnoreCase("OMX.google.")
+        || !componentName.startsWithIgnoreCase("OMX.");
+}
+
+static int compareSoftwareCodecsFirst(const AString *name1, const AString *name2) {
+    // sort order 1: software codecs are first (lower)
+    bool isSoftwareCodec1 = MediaCodecList::isSoftwareCodec(*name1);
+    bool isSoftwareCodec2 = MediaCodecList::isSoftwareCodec(*name2);
+    if (isSoftwareCodec1 != isSoftwareCodec2) {
+        return isSoftwareCodec2 - isSoftwareCodec1;
+    }
+
+    // sort order 2: OMX codecs are first (lower)
+    bool isOMX1 = name1->startsWithIgnoreCase("OMX.");
+    bool isOMX2 = name2->startsWithIgnoreCase("OMX.");
+    return isOMX2 - isOMX1;
+}
+
+//static
+void MediaCodecList::findMatchingCodecs(
+        const char *mime, bool encoder, uint32_t flags, Vector<AString> *matches) {
+    matches->clear();
+
+    const sp<IMediaCodecList> list = getInstance();
+    if (list == NULL) {
+        return;
+    }
+
+    size_t index = 0;
+    for (;;) {
+        ssize_t matchIndex =
+            list->findCodecByType(mime, encoder, index);
+
+        if (matchIndex < 0) {
+            break;
+        }
+
+        index = matchIndex + 1;
+
+        const sp<MediaCodecInfo> info = list->getCodecInfo(matchIndex);
+        CHECK(info != NULL);
+        AString componentName = info->getCodecName();
+
+        if (!((flags & kHardwareCodecsOnly) && !isSoftwareCodec(componentName))) {
+            matches->push(componentName);
+            ALOGV("matching '%s'", componentName.c_str());
+        }
+    }
+
+    if (flags & kPreferSoftwareCodecs) {
+        matches->sort(compareSoftwareCodecsFirst);
+    }
+}
+
+// static
+uint32_t MediaCodecList::getQuirksFor(const char *componentName) {
+    const sp<IMediaCodecList> list = getInstance();
+    if (list == NULL) {
+        return 0;
+    }
+
+    ssize_t ix = list->findCodecByName(componentName);
+    if (ix < 0) {
+        return 0;
+    }
+
+    const sp<MediaCodecInfo> info = list->getCodecInfo(ix);
+
+    uint32_t quirks = 0;
+    if (info->hasQuirk("requires-allocate-on-input-ports")) {
+        quirks |= ACodec::kRequiresAllocateBufferOnInputPorts;
+    }
+    if (info->hasQuirk("requires-allocate-on-output-ports")) {
+        quirks |= ACodec::kRequiresAllocateBufferOnOutputPorts;
+    }
+
+    return quirks;
+}
+
 }  // namespace android
diff --git a/media/libstagefright/MediaCodecSource.cpp b/media/libstagefright/MediaCodecSource.cpp
index 7f9f824..57a966e 100644
--- a/media/libstagefright/MediaCodecSource.cpp
+++ b/media/libstagefright/MediaCodecSource.cpp
@@ -30,6 +30,7 @@
 #include <media/stagefright/foundation/AMessage.h>
 #include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MediaCodec.h>
+#include <media/stagefright/MediaCodecList.h>
 #include <media/stagefright/MediaCodecSource.h>
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/MediaSource.h>
@@ -42,15 +43,19 @@
 const int kDefaultSwVideoEncoderFormat = HAL_PIXEL_FORMAT_YCbCr_420_888;
 const int kDefaultSwVideoEncoderDataSpace = HAL_DATASPACE_BT709;
 
+const int kStopTimeoutUs = 300000; // allow 1 sec for shutting down encoder
+
 struct MediaCodecSource::Puller : public AHandler {
-    Puller(const sp<MediaSource> &source);
+    explicit Puller(const sp<MediaSource> &source);
 
     status_t start(const sp<MetaData> &meta, const sp<AMessage> &notify);
     void stop();
-
+    void stopSource();
     void pause();
     void resume();
 
+    bool readBuffer(MediaBuffer **buffer);
+
 protected:
     virtual void onMessageReceived(const sp<AMessage> &msg);
     virtual ~Puller();
@@ -60,17 +65,31 @@
         kWhatStart = 'msta',
         kWhatStop,
         kWhatPull,
-        kWhatPause,
-        kWhatResume,
     };
 
     sp<MediaSource> mSource;
     sp<AMessage> mNotify;
     sp<ALooper> mLooper;
-    int32_t mPullGeneration;
     bool mIsAudio;
-    bool mPaused;
-    bool mReachedEOS;
+
+    struct Queue {
+        Queue()
+            : mReadPendingSince(0),
+              mPaused(false),
+              mPulling(false) { }
+        int64_t mReadPendingSince;
+        bool mPaused;
+        bool mPulling;
+        Vector<MediaBuffer *> mReadBuffers;
+
+        void flush();
+        // if queue is empty, return false and set *|buffer| to NULL . Otherwise, pop
+        // buffer from front of the queue, place it into *|buffer| and return true. 
+        bool readBuffer(MediaBuffer **buffer);
+        // add a buffer to the back of the queue 
+        void pushBuffer(MediaBuffer *mbuf);
+    };
+    Mutexed<Queue> mQueue;
 
     status_t postSynchronouslyAndReturnError(const sp<AMessage> &msg);
     void schedulePull();
@@ -82,10 +101,8 @@
 MediaCodecSource::Puller::Puller(const sp<MediaSource> &source)
     : mSource(source),
       mLooper(new ALooper()),
-      mPullGeneration(0),
-      mIsAudio(false),
-      mPaused(false),
-      mReachedEOS(false) {
+      mIsAudio(false)
+{
     sp<MetaData> meta = source->getFormat();
     const char *mime;
     CHECK(meta->findCString(kKeyMIMEType, &mime));
@@ -100,6 +117,33 @@
     mLooper->stop();
 }
 
+void MediaCodecSource::Puller::Queue::pushBuffer(MediaBuffer *mbuf) {
+    mReadBuffers.push_back(mbuf);
+}
+
+bool MediaCodecSource::Puller::Queue::readBuffer(MediaBuffer **mbuf) {
+    if (mReadBuffers.empty()) {
+        *mbuf = NULL;
+        return false;
+    }
+    *mbuf = *mReadBuffers.begin();
+    mReadBuffers.erase(mReadBuffers.begin());
+    return true;
+}
+
+void MediaCodecSource::Puller::Queue::flush() {
+    MediaBuffer *mbuf;
+    while (readBuffer(&mbuf)) {
+        // there are no null buffers in the queue
+        mbuf->release();
+    }
+}
+
+bool MediaCodecSource::Puller::readBuffer(MediaBuffer **mbuf) {
+    Mutexed<Queue>::Locked queue(mQueue);
+    return queue->readBuffer(mbuf);
+}
+
 status_t MediaCodecSource::Puller::postSynchronouslyAndReturnError(
         const sp<AMessage> &msg) {
     sp<AMessage> response;
@@ -116,8 +160,7 @@
     return err;
 }
 
-status_t MediaCodecSource::Puller::start(const sp<MetaData> &meta,
-        const sp<AMessage> &notify) {
+status_t MediaCodecSource::Puller::start(const sp<MetaData> &meta, const sp<AMessage> &notify) {
     ALOGV("puller (%s) start", mIsAudio ? "audio" : "video");
     mLooper->start(
             false /* runOnCallingThread */,
@@ -132,41 +175,46 @@
 }
 
 void MediaCodecSource::Puller::stop() {
-    // Stop source from caller's thread instead of puller's looper.
-    // mSource->stop() is thread-safe, doing it outside the puller's
-    // looper allows us to at least stop if source gets stuck.
-    // If source gets stuck in read(), the looper would never
-    // be able to process the stop(), which could lead to ANR.
+    bool interrupt = false;
+    {
+        // mark stopping before actually reaching kWhatStop on the looper, so the pulling will
+        // stop.
+        Mutexed<Queue>::Locked queue(mQueue);
+        queue->mPulling = false;
+        interrupt = queue->mReadPendingSince && (queue->mReadPendingSince < ALooper::GetNowUs() - 1000000);
+        queue->flush(); // flush any unprocessed pulled buffers
+    }
 
-    ALOGV("source (%s) stopping", mIsAudio ? "audio" : "video");
-    mSource->stop();
-    ALOGV("source (%s) stopped", mIsAudio ? "audio" : "video");
+    if (interrupt) {
+        // call source->stop if read has been pending for over a second
+        // TODO: we should really call this if kWhatStop has not returned for more than a second.
+        mSource->stop();
+    }
+}
 
+void MediaCodecSource::Puller::stopSource() {
     (new AMessage(kWhatStop, this))->post();
 }
 
 void MediaCodecSource::Puller::pause() {
-    (new AMessage(kWhatPause, this))->post();
+    Mutexed<Queue>::Locked queue(mQueue);
+    queue->mPaused = true;
 }
 
 void MediaCodecSource::Puller::resume() {
-    (new AMessage(kWhatResume, this))->post();
+    Mutexed<Queue>::Locked queue(mQueue);
+    queue->mPaused = false;
 }
 
 void MediaCodecSource::Puller::schedulePull() {
-    sp<AMessage> msg = new AMessage(kWhatPull, this);
-    msg->setInt32("generation", mPullGeneration);
-    msg->post();
+    (new AMessage(kWhatPull, this))->post();
 }
 
 void MediaCodecSource::Puller::handleEOS() {
-    if (!mReachedEOS) {
-        ALOGV("puller (%s) posting EOS", mIsAudio ? "audio" : "video");
-        mReachedEOS = true;
-        sp<AMessage> notify = mNotify->dup();
-        notify->setPointer("accessUnit", NULL);
-        notify->post();
-    }
+    ALOGV("puller (%s) posting EOS", mIsAudio ? "audio" : "video");
+    sp<AMessage> msg = mNotify->dup();
+    msg->setInt32("eos", 1);
+    msg->post();
 }
 
 void MediaCodecSource::Puller::onMessageReceived(const sp<AMessage> &msg) {
@@ -176,7 +224,10 @@
             sp<RefBase> obj;
             CHECK(msg->findObject("meta", &obj));
 
-            mReachedEOS = false;
+            {
+                Mutexed<Queue>::Locked queue(mQueue);
+                queue->mPulling = true;
+            }
 
             status_t err = mSource->start(static_cast<MetaData *>(obj.get()));
 
@@ -195,61 +246,52 @@
 
         case kWhatStop:
         {
-            ++mPullGeneration;
-
-            handleEOS();
+            mSource->stop();
             break;
         }
 
         case kWhatPull:
         {
-            int32_t generation;
-            CHECK(msg->findInt32("generation", &generation));
-
-            if (generation != mPullGeneration) {
+            Mutexed<Queue>::Locked queue(mQueue);
+            queue->mReadPendingSince = ALooper::GetNowUs();
+            if (!queue->mPulling) {
+                handleEOS();
                 break;
             }
 
-            MediaBuffer *mbuf;
+            queue.unlock();
+            MediaBuffer *mbuf = NULL;
             status_t err = mSource->read(&mbuf);
+            queue.lock();
 
-            if (mPaused) {
-                if (err == OK) {
+            queue->mReadPendingSince = 0;
+            // if we need to discard buffer
+            if (!queue->mPulling || queue->mPaused || err != OK) {
+                if (mbuf != NULL) {
                     mbuf->release();
                     mbuf = NULL;
                 }
-
-                msg->post();
-                break;
-            }
-
-            if (err != OK) {
-                if (err == ERROR_END_OF_STREAM) {
+                if (queue->mPulling && err == OK) {
+                    msg->post(); // if simply paused, keep pulling source
+                } else if (err == ERROR_END_OF_STREAM) {
                     ALOGV("stream ended, mbuf %p", mbuf);
-                } else {
+                } else if (err != OK) {
                     ALOGE("error %d reading stream.", err);
                 }
-                handleEOS();
-            } else {
-                sp<AMessage> notify = mNotify->dup();
-
-                notify->setPointer("accessUnit", mbuf);
-                notify->post();
-
-                msg->post();
             }
-            break;
-        }
 
-        case kWhatPause:
-        {
-            mPaused = true;
-            break;
-        }
+            if (mbuf != NULL) {
+                queue->pushBuffer(mbuf);
+            }
 
-        case kWhatResume:
-        {
-            mPaused = false;
+            queue.unlock();
+
+            if (mbuf != NULL) {
+                mNotify->post();
+                msg->post();
+            } else {
+                handleEOS();
+            }
             break;
         }
 
@@ -258,6 +300,11 @@
     }
 }
 
+MediaCodecSource::Output::Output()
+    : mEncoderReachedEOS(false),
+      mErrorCode(OK) {
+}
+
 // static
 sp<MediaCodecSource> MediaCodecSource::Create(
         const sp<ALooper> &looper,
@@ -282,21 +329,7 @@
 
 status_t MediaCodecSource::stop() {
     sp<AMessage> msg = new AMessage(kWhatStop, mReflector);
-    status_t err = postSynchronouslyAndReturnError(msg);
-
-    // mPuller->stop() needs to be done outside MediaCodecSource's looper,
-    // as it contains a synchronous call to stop the underlying MediaSource,
-    // which often waits for all outstanding MediaBuffers to return, but
-    // MediaBuffers are only returned when MediaCodecSource looper gets
-    // to process them.
-
-    if (mPuller != NULL) {
-        ALOGI("puller (%s) stopping", mIsVideo ? "video" : "audio");
-        mPuller->stop();
-        ALOGI("puller (%s) stopped", mIsVideo ? "video" : "audio");
-    }
-
-    return err;
+    return postSynchronouslyAndReturnError(msg);
 }
 
 status_t MediaCodecSource::pause() {
@@ -311,18 +344,18 @@
 
 status_t MediaCodecSource::read(
         MediaBuffer** buffer, const ReadOptions* /* options */) {
-    Mutex::Autolock autolock(mOutputBufferLock);
+    Mutexed<Output>::Locked output(mOutput);
 
     *buffer = NULL;
-    while (mOutputBufferQueue.size() == 0 && !mEncoderReachedEOS) {
-        mOutputBufferCond.wait(mOutputBufferLock);
+    while (output->mBufferQueue.size() == 0 && !output->mEncoderReachedEOS) {
+        output.waitForCondition(output->mCond);
     }
-    if (!mEncoderReachedEOS) {
-        *buffer = *mOutputBufferQueue.begin();
-        mOutputBufferQueue.erase(mOutputBufferQueue.begin());
+    if (!output->mEncoderReachedEOS) {
+        *buffer = *output->mBufferQueue.begin();
+        output->mBufferQueue.erase(output->mBufferQueue.begin());
         return OK;
     }
-    return mErrorCode;
+    return output->mErrorCode;
 }
 
 void MediaCodecSource::signalBufferReturned(MediaBuffer *buffer) {
@@ -349,8 +382,7 @@
       mEncoderDataSpace(0),
       mGraphicBufferConsumer(consumer),
       mFirstSampleTimeUs(-1ll),
-      mEncoderReachedEOS(false),
-      mErrorCode(OK) {
+      mGeneration(0) {
     CHECK(mLooper != NULL);
 
     AString mime;
@@ -401,24 +433,39 @@
     AString outputMIME;
     CHECK(mOutputFormat->findString("mime", &outputMIME));
 
-    mEncoder = MediaCodec::CreateByType(
-            mCodecLooper, outputMIME.c_str(), true /* encoder */);
+    Vector<AString> matchingCodecs;
+    MediaCodecList::findMatchingCodecs(
+            outputMIME.c_str(), true /* encoder */,
+            ((mFlags & FLAG_PREFER_SOFTWARE_CODEC) ? MediaCodecList::kPreferSoftwareCodecs : 0),
+            &matchingCodecs);
 
-    if (mEncoder == NULL) {
-        return NO_INIT;
+    status_t err = NO_INIT;
+    for (size_t ix = 0; ix < matchingCodecs.size(); ++ix) {
+        mEncoder = MediaCodec::CreateByComponentName(
+                mCodecLooper, matchingCodecs[ix]);
+
+        if (mEncoder == NULL) {
+            continue;
+        }
+
+        ALOGV("output format is '%s'", mOutputFormat->debugString(0).c_str());
+
+        mEncoderActivityNotify = new AMessage(kWhatEncoderActivity, mReflector);
+        mEncoder->setCallback(mEncoderActivityNotify);
+
+        err = mEncoder->configure(
+                    mOutputFormat,
+                    NULL /* nativeWindow */,
+                    NULL /* crypto */,
+                    MediaCodec::CONFIGURE_FLAG_ENCODE);
+
+        if (err == OK) {
+            break;
+        }
+        mEncoder->release();
+        mEncoder = NULL;
     }
 
-    ALOGV("output format is '%s'", mOutputFormat->debugString(0).c_str());
-
-    mEncoderActivityNotify = new AMessage(kWhatEncoderActivity, mReflector);
-    mEncoder->setCallback(mEncoderActivityNotify);
-
-    status_t err = mEncoder->configure(
-                mOutputFormat,
-                NULL /* nativeWindow */,
-                NULL /* crypto */,
-                MediaCodec::CONFIGURE_FLAG_ENCODE);
-
     if (err != OK) {
         return err;
     }
@@ -462,8 +509,11 @@
         return err;
     }
 
-    mEncoderReachedEOS = false;
-    mErrorCode = OK;
+    {
+        Mutexed<Output>::Locked output(mOutput);
+        output->mEncoderReachedEOS = false;
+        output->mErrorCode = OK;
+    }
 
     return OK;
 }
@@ -475,14 +525,6 @@
 
     mEncoder->release();
     mEncoder.clear();
-
-    while (!mInputBufferQueue.empty()) {
-        MediaBuffer *mbuf = *mInputBufferQueue.begin();
-        mInputBufferQueue.erase(mInputBufferQueue.begin());
-        if (mbuf != NULL) {
-            mbuf->release();
-        }
-    }
 }
 
 status_t MediaCodecSource::postSynchronouslyAndReturnError(
@@ -502,25 +544,32 @@
 }
 
 void MediaCodecSource::signalEOS(status_t err) {
-    if (!mEncoderReachedEOS) {
-        ALOGV("encoder (%s) reached EOS", mIsVideo ? "video" : "audio");
-        {
-            Mutex::Autolock autoLock(mOutputBufferLock);
+    bool reachedEOS = false;
+    {
+        Mutexed<Output>::Locked output(mOutput);
+        reachedEOS = output->mEncoderReachedEOS;
+        if (!reachedEOS) {
+            ALOGV("encoder (%s) reached EOS", mIsVideo ? "video" : "audio");
             // release all unread media buffers
-            for (List<MediaBuffer*>::iterator it = mOutputBufferQueue.begin();
-                    it != mOutputBufferQueue.end(); it++) {
+            for (List<MediaBuffer*>::iterator it = output->mBufferQueue.begin();
+                    it != output->mBufferQueue.end(); it++) {
                 (*it)->release();
             }
-            mOutputBufferQueue.clear();
-            mEncoderReachedEOS = true;
-            mErrorCode = err;
-            mOutputBufferCond.signal();
-        }
+            output->mBufferQueue.clear();
+            output->mEncoderReachedEOS = true;
+            output->mErrorCode = err;
+            output->mCond.signal();
 
-        releaseEncoder();
+            reachedEOS = true;
+            output.unlock();
+            releaseEncoder();
+        }
     }
-    if (mStopping && mEncoderReachedEOS) {
+
+    if (mStopping && reachedEOS) {
         ALOGI("encoder (%s) stopped", mIsVideo ? "video" : "audio");
+        mPuller->stopSource();
+        ALOGV("source (%s) stopped", mIsVideo ? "video" : "audio");
         // posting reply to everyone that's waiting
         List<sp<AReplyToken>>::iterator it;
         for (it = mStopReplyIDQueue.begin();
@@ -529,6 +578,7 @@
         }
         mStopReplyIDQueue.clear();
         mStopping = false;
+        ++mGeneration;
     }
 }
 
@@ -554,11 +604,8 @@
 }
 
 status_t MediaCodecSource::feedEncoderInputBuffers() {
-    while (!mInputBufferQueue.empty()
-            && !mAvailEncoderInputIndices.empty()) {
-        MediaBuffer* mbuf = *mInputBufferQueue.begin();
-        mInputBufferQueue.erase(mInputBufferQueue.begin());
-
+    MediaBuffer* mbuf = NULL;
+    while (!mAvailEncoderInputIndices.empty() && mPuller->readBuffer(&mbuf)) {
         size_t bufferIndex = *mAvailEncoderInputIndices.begin();
         mAvailEncoderInputIndices.erase(mAvailEncoderInputIndices.begin());
 
@@ -676,30 +723,19 @@
     switch (msg->what()) {
     case kWhatPullerNotify:
     {
-        MediaBuffer *mbuf;
-        CHECK(msg->findPointer("accessUnit", (void**)&mbuf));
-
-        if (mbuf == NULL) {
-            ALOGV("puller (%s) reached EOS",
-                    mIsVideo ? "video" : "audio");
+        int32_t eos = 0;
+        if (msg->findInt32("eos", &eos) && eos) {
+            ALOGV("puller (%s) reached EOS", mIsVideo ? "video" : "audio");
             signalEOS();
-        }
-
-        if (mEncoder == NULL) {
-            ALOGV("got msg '%s' after encoder shutdown.",
-                  msg->debugString().c_str());
-
-            if (mbuf != NULL) {
-                mbuf->release();
-            }
-
             break;
         }
 
-        mInputBufferQueue.push_back(mbuf);
+        if (mEncoder == NULL) {
+            ALOGV("got msg '%s' after encoder shutdown.", msg->debugString().c_str());
+            break;
+        }
 
         feedEncoderInputBuffers();
-
         break;
     }
     case kWhatEncoderActivity:
@@ -788,9 +824,9 @@
             mbuf->add_ref();
 
             {
-                Mutex::Autolock autoLock(mOutputBufferLock);
-                mOutputBufferQueue.push_back(mbuf);
-                mOutputBufferCond.signal();
+                Mutexed<Output>::Locked output(mOutput);
+                output->mBufferQueue.push_back(mbuf);
+                output->mCond.signal();
             }
 
             mEncoder->releaseOutputBuffer(index);
@@ -824,7 +860,7 @@
         sp<AReplyToken> replyID;
         CHECK(msg->senderAwaitsResponse(&replyID));
 
-        if (mEncoderReachedEOS) {
+        if (mOutput.lock()->mEncoderReachedEOS) {
             // if we already reached EOS, reply and return now
             ALOGI("encoder (%s) already stopped",
                     mIsVideo ? "video" : "audio");
@@ -842,17 +878,41 @@
         mStopping = true;
 
         // if using surface, signal source EOS and wait for EOS to come back.
-        // otherwise, release encoder and post EOS if haven't done already
+        // otherwise, stop puller (which also clears the input buffer queue)
+        // and wait for the EOS message. We cannot call source->stop() because
+        // the encoder may still be processing input buffers.
         if (mFlags & FLAG_USE_SURFACE_INPUT) {
             mEncoder->signalEndOfInputStream();
         } else {
-            signalEOS();
+            mPuller->stop();
         }
+
+        // complete stop even if encoder/puller stalled
+        sp<AMessage> timeoutMsg = new AMessage(kWhatStopStalled, mReflector);
+        timeoutMsg->setInt32("generation", mGeneration);
+        timeoutMsg->post(kStopTimeoutUs);
         break;
     }
+
+    case kWhatStopStalled:
+    {
+        int32_t generation;
+        CHECK(msg->findInt32("generation", &generation));
+        if (generation != mGeneration) {
+             break;
+        }
+
+        if (!(mFlags & FLAG_USE_SURFACE_INPUT)) {
+            ALOGV("source (%s) stopping", mIsVideo ? "video" : "audio");
+            mPuller->stopSource();
+            ALOGV("source (%s) stopped", mIsVideo ? "video" : "audio");
+        }
+        signalEOS();
+    }
+
     case kWhatPause:
     {
-        if (mFlags && FLAG_USE_SURFACE_INPUT) {
+        if (mFlags & FLAG_USE_SURFACE_INPUT) {
             suspend();
         } else {
             CHECK(mPuller != NULL);
diff --git a/media/libstagefright/NuCachedSource2.cpp b/media/libstagefright/NuCachedSource2.cpp
index f82636b..4b0bdda 100644
--- a/media/libstagefright/NuCachedSource2.cpp
+++ b/media/libstagefright/NuCachedSource2.cpp
@@ -31,7 +31,7 @@
 namespace android {
 
 struct PageCache {
-    PageCache(size_t pageSize);
+    explicit PageCache(size_t pageSize);
     ~PageCache();
 
     struct Page {
@@ -224,9 +224,6 @@
     // So whenever we call DataSource::readAt it may end up in a call to
     // IMediaHTTPConnection::readAt and therefore call back into JAVA.
     mLooper->start(false /* runOnCallingThread */, true /* canCallJava */);
-
-    Mutex::Autolock autoLock(mLock);
-    (new AMessage(kWhatFetchMore, mReflector))->post();
 }
 
 NuCachedSource2::~NuCachedSource2() {
@@ -237,6 +234,18 @@
     mCache = NULL;
 }
 
+// static
+sp<NuCachedSource2> NuCachedSource2::Create(
+        const sp<DataSource> &source,
+        const char *cacheConfig,
+        bool disconnectAtHighwatermark) {
+    sp<NuCachedSource2> instance = new NuCachedSource2(
+            source, cacheConfig, disconnectAtHighwatermark);
+    Mutex::Autolock autoLock(instance->mLock);
+    (new AMessage(kWhatFetchMore, instance->mReflector))->post();
+    return instance;
+}
+
 status_t NuCachedSource2::getEstimatedBandwidthKbps(int32_t *kbps) {
     if (mSource->flags() & kIsHTTPBasedSource) {
         HTTPBase* source = static_cast<HTTPBase *>(mSource.get());
diff --git a/media/libstagefright/NuMediaExtractor.cpp b/media/libstagefright/NuMediaExtractor.cpp
index f24cf3a..8c67618 100644
--- a/media/libstagefright/NuMediaExtractor.cpp
+++ b/media/libstagefright/NuMediaExtractor.cpp
@@ -110,7 +110,8 @@
         // at the container mime type.
         // The cryptoPluginMode ensures that the extractor will actually
         // give us data in a call to MediaSource::read(), unlike its
-        // default mode that we use from AwesomePlayer.
+        // default mode that we used in AwesomePlayer.
+        // TODO: change default mode
         static_cast<WVMExtractor *>(mImpl.get())->setCryptoPluginMode(true);
     } else if (mImpl->getDrmFlag()) {
         // For all other drm content, we don't want to expose decrypted
diff --git a/media/libstagefright/OMXClient.cpp b/media/libstagefright/OMXClient.cpp
index e69890d..43e24f1 100644
--- a/media/libstagefright/OMXClient.cpp
+++ b/media/libstagefright/OMXClient.cpp
@@ -34,7 +34,7 @@
 namespace android {
 
 struct MuxOMX : public IOMX {
-    MuxOMX(const sp<IOMX> &remoteOMX);
+    explicit MuxOMX(const sp<IOMX> &remoteOMX);
     virtual ~MuxOMX();
 
     virtual IBinder *onAsBinder() { return IInterface::asBinder(mRemoteOMX).get(); }
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
deleted file mode 100644
index 4c39194..0000000
--- a/media/libstagefright/OMXCodec.cpp
+++ /dev/null
@@ -1,4457 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <inttypes.h>
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "OMXCodec"
-
-#ifdef __LP64__
-#define OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS
-#endif
-
-#include <utils/Log.h>
-
-#include "include/AACEncoder.h"
-
-#include "include/ESDS.h"
-
-#include <binder/IServiceManager.h>
-#include <binder/MemoryDealer.h>
-#include <binder/ProcessState.h>
-#include <HardwareAPI.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/IMediaPlayerService.h>
-#include <media/stagefright/ACodec.h>
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MediaBufferGroup.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaCodecList.h>
-#include <media/stagefright/MediaExtractor.h>
-#include <media/stagefright/MetaData.h>
-#include <media/stagefright/OMXCodec.h>
-#include <media/stagefright/SurfaceUtils.h>
-#include <media/stagefright/Utils.h>
-#include <media/stagefright/SkipCutBuffer.h>
-#include <utils/Vector.h>
-
-#include <OMX_AudioExt.h>
-#include <OMX_Component.h>
-#include <OMX_IndexExt.h>
-#include <OMX_VideoExt.h>
-#include <OMX_AsString.h>
-
-#include "include/avc_utils.h"
-
-namespace android {
-
-// Treat time out as an error if we have not received any output
-// buffers after 3 seconds.
-const static int64_t kBufferFilledEventTimeOutNs = 3000000000LL;
-
-// OMX Spec defines less than 50 color formats. If the query for
-// color format is executed for more than kMaxColorFormatSupported,
-// the query will fail to avoid looping forever.
-// 1000 is more than enough for us to tell whether the omx
-// component in question is buggy or not.
-const static uint32_t kMaxColorFormatSupported = 1000;
-
-#define FACTORY_CREATE_ENCODER(name) \
-static sp<MediaSource> Make##name(const sp<MediaSource> &source, const sp<MetaData> &meta) { \
-    return new name(source, meta); \
-}
-
-#define FACTORY_REF(name) { #name, Make##name },
-
-FACTORY_CREATE_ENCODER(AACEncoder)
-
-static sp<MediaSource> InstantiateSoftwareEncoder(
-        const char *name, const sp<MediaSource> &source,
-        const sp<MetaData> &meta) {
-    struct FactoryInfo {
-        const char *name;
-        sp<MediaSource> (*CreateFunc)(const sp<MediaSource> &, const sp<MetaData> &);
-    };
-
-    static const FactoryInfo kFactoryInfo[] = {
-        FACTORY_REF(AACEncoder)
-    };
-    for (size_t i = 0;
-         i < sizeof(kFactoryInfo) / sizeof(kFactoryInfo[0]); ++i) {
-        if (!strcmp(name, kFactoryInfo[i].name)) {
-            return (*kFactoryInfo[i].CreateFunc)(source, meta);
-        }
-    }
-
-    return NULL;
-}
-
-#undef FACTORY_CREATE_ENCODER
-#undef FACTORY_REF
-
-#define CODEC_LOGI(x, ...) ALOGI("[%s] " x, mComponentName, ##__VA_ARGS__)
-#define CODEC_LOGV(x, ...) ALOGV("[%s] " x, mComponentName, ##__VA_ARGS__)
-#define CODEC_LOGW(x, ...) ALOGW("[%s] " x, mComponentName, ##__VA_ARGS__)
-#define CODEC_LOGE(x, ...) ALOGE("[%s] " x, mComponentName, ##__VA_ARGS__)
-
-struct OMXCodecObserver : public BnOMXObserver {
-    OMXCodecObserver() {
-    }
-
-    void setCodec(const sp<OMXCodec> &target) {
-        mTarget = target;
-    }
-
-    // from IOMXObserver
-    virtual void onMessages(const std::list<omx_message> &messages) {
-        sp<OMXCodec> codec = mTarget.promote();
-
-        if (codec.get() != NULL) {
-            Mutex::Autolock autoLock(codec->mLock);
-            for (std::list<omx_message>::const_iterator it = messages.cbegin();
-                  it != messages.cend(); ++it) {
-                codec->on_message(*it);
-            }
-            codec.clear();
-        }
-    }
-
-protected:
-    virtual ~OMXCodecObserver() {}
-
-private:
-    wp<OMXCodec> mTarget;
-
-    OMXCodecObserver(const OMXCodecObserver &);
-    OMXCodecObserver &operator=(const OMXCodecObserver &);
-};
-
-template<class T>
-static void InitOMXParams(T *params) {
-    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(sizeof(OMX_PTR) == 4); // check OMX_PTR is 4 bytes.
-    params->nSize = sizeof(T);
-    params->nVersion.s.nVersionMajor = 1;
-    params->nVersion.s.nVersionMinor = 0;
-    params->nVersion.s.nRevision = 0;
-    params->nVersion.s.nStep = 0;
-}
-
-static bool IsSoftwareCodec(const char *componentName) {
-    if (!strncmp("OMX.google.", componentName, 11)) {
-        return true;
-    }
-
-    if (!strncmp("OMX.", componentName, 4)) {
-        return false;
-    }
-
-    return true;
-}
-
-// A sort order in which OMX software codecs are first, followed
-// by other (non-OMX) software codecs, followed by everything else.
-static int CompareSoftwareCodecsFirst(
-        const OMXCodec::CodecNameAndQuirks *elem1,
-        const OMXCodec::CodecNameAndQuirks *elem2) {
-    bool isOMX1 = !strncmp(elem1->mName.string(), "OMX.", 4);
-    bool isOMX2 = !strncmp(elem2->mName.string(), "OMX.", 4);
-
-    bool isSoftwareCodec1 = IsSoftwareCodec(elem1->mName.string());
-    bool isSoftwareCodec2 = IsSoftwareCodec(elem2->mName.string());
-
-    if (isSoftwareCodec1) {
-        if (!isSoftwareCodec2) { return -1; }
-
-        if (isOMX1) {
-            if (isOMX2) { return 0; }
-
-            return -1;
-        } else {
-            if (isOMX2) { return 0; }
-
-            return 1;
-        }
-
-        return -1;
-    }
-
-    if (isSoftwareCodec2) {
-        return 1;
-    }
-
-    return 0;
-}
-
-// static
-void OMXCodec::findMatchingCodecs(
-        const char *mime,
-        bool createEncoder, const char *matchComponentName,
-        uint32_t flags,
-        Vector<CodecNameAndQuirks> *matchingCodecs) {
-    matchingCodecs->clear();
-
-    const sp<IMediaCodecList> list = MediaCodecList::getInstance();
-    if (list == NULL) {
-        return;
-    }
-
-    size_t index = 0;
-    for (;;) {
-        ssize_t matchIndex =
-            list->findCodecByType(mime, createEncoder, index);
-
-        if (matchIndex < 0) {
-            break;
-        }
-
-        index = matchIndex + 1;
-
-        const sp<MediaCodecInfo> info = list->getCodecInfo(matchIndex);
-        CHECK(info != NULL);
-        const char *componentName = info->getCodecName();
-
-        // If a specific codec is requested, skip the non-matching ones.
-        if (matchComponentName && strcmp(componentName, matchComponentName)) {
-            continue;
-        }
-
-        // When requesting software-only codecs, only push software codecs
-        // When requesting hardware-only codecs, only push hardware codecs
-        // When there is request neither for software-only nor for
-        // hardware-only codecs, push all codecs
-        if (((flags & kSoftwareCodecsOnly) &&   IsSoftwareCodec(componentName)) ||
-            ((flags & kHardwareCodecsOnly) &&  !IsSoftwareCodec(componentName)) ||
-            (!(flags & (kSoftwareCodecsOnly | kHardwareCodecsOnly)))) {
-
-            ssize_t index = matchingCodecs->add();
-            CodecNameAndQuirks *entry = &matchingCodecs->editItemAt(index);
-            entry->mName = String8(componentName);
-            entry->mQuirks = getComponentQuirks(info);
-
-            ALOGV("matching '%s' quirks 0x%08x",
-                  entry->mName.string(), entry->mQuirks);
-        }
-    }
-
-    if (flags & kPreferSoftwareCodecs) {
-        matchingCodecs->sort(CompareSoftwareCodecsFirst);
-    }
-}
-
-// static
-uint32_t OMXCodec::getComponentQuirks(
-        const sp<MediaCodecInfo> &info) {
-    uint32_t quirks = 0;
-    if (info->hasQuirk("requires-allocate-on-input-ports")) {
-        quirks |= kRequiresAllocateBufferOnInputPorts;
-    }
-    if (info->hasQuirk("requires-allocate-on-output-ports")) {
-        quirks |= kRequiresAllocateBufferOnOutputPorts;
-    }
-    if (info->hasQuirk("output-buffers-are-unreadable")) {
-        quirks |= kOutputBuffersAreUnreadable;
-    }
-
-    return quirks;
-}
-
-// static
-bool OMXCodec::findCodecQuirks(const char *componentName, uint32_t *quirks) {
-    const sp<IMediaCodecList> list = MediaCodecList::getInstance();
-    if (list == NULL) {
-        return false;
-    }
-
-    ssize_t index = list->findCodecByName(componentName);
-
-    if (index < 0) {
-        return false;
-    }
-
-    const sp<MediaCodecInfo> info = list->getCodecInfo(index);
-    CHECK(info != NULL);
-    *quirks = getComponentQuirks(info);
-
-    return true;
-}
-
-// static
-sp<MediaSource> OMXCodec::Create(
-        const sp<IOMX> &omx,
-        const sp<MetaData> &meta, bool createEncoder,
-        const sp<MediaSource> &source,
-        const char *matchComponentName,
-        uint32_t flags,
-        const sp<ANativeWindow> &nativeWindow) {
-    int32_t requiresSecureBuffers;
-    if (source->getFormat()->findInt32(
-                kKeyRequiresSecureBuffers,
-                &requiresSecureBuffers)
-            && requiresSecureBuffers) {
-        flags |= kIgnoreCodecSpecificData;
-        flags |= kUseSecureInputBuffers;
-    }
-
-    const char *mime;
-    bool success = meta->findCString(kKeyMIMEType, &mime);
-    CHECK(success);
-
-    Vector<CodecNameAndQuirks> matchingCodecs;
-    findMatchingCodecs(
-            mime, createEncoder, matchComponentName, flags, &matchingCodecs);
-
-    if (matchingCodecs.isEmpty()) {
-        ALOGV("No matching codecs! (mime: %s, createEncoder: %s, "
-                "matchComponentName: %s, flags: 0x%x)",
-                mime, createEncoder ? "true" : "false", matchComponentName, flags);
-        return NULL;
-    }
-
-    sp<OMXCodecObserver> observer = new OMXCodecObserver;
-    IOMX::node_id node = 0;
-
-    for (size_t i = 0; i < matchingCodecs.size(); ++i) {
-        const char *componentNameBase = matchingCodecs[i].mName.string();
-        uint32_t quirks = matchingCodecs[i].mQuirks;
-        const char *componentName = componentNameBase;
-
-        AString tmp;
-        if (flags & kUseSecureInputBuffers) {
-            tmp = componentNameBase;
-            tmp.append(".secure");
-
-            componentName = tmp.c_str();
-        }
-
-        if (createEncoder) {
-            sp<MediaSource> softwareCodec =
-                InstantiateSoftwareEncoder(componentName, source, meta);
-
-            if (softwareCodec != NULL) {
-                ALOGV("Successfully allocated software codec '%s'", componentName);
-
-                return softwareCodec;
-            }
-        }
-
-        ALOGV("Attempting to allocate OMX node '%s'", componentName);
-
-        if (!createEncoder
-                && (quirks & kOutputBuffersAreUnreadable)
-                && (flags & kClientNeedsFramebuffer)) {
-            if (strncmp(componentName, "OMX.SEC.", 8)) {
-                // For OMX.SEC.* decoders we can enable a special mode that
-                // gives the client access to the framebuffer contents.
-
-                ALOGW("Component '%s' does not give the client access to "
-                     "the framebuffer contents. Skipping.",
-                     componentName);
-
-                continue;
-            }
-        }
-
-        status_t err = omx->allocateNode(componentName, observer, &node);
-        if (err == OK) {
-            ALOGV("Successfully allocated OMX node '%s'", componentName);
-
-            sp<OMXCodec> codec = new OMXCodec(
-                    omx, node, quirks, flags,
-                    createEncoder, mime, componentName,
-                    source, nativeWindow);
-
-            observer->setCodec(codec);
-
-            err = codec->configureCodec(meta);
-            if (err == OK) {
-                return codec;
-            }
-
-            ALOGV("Failed to configure codec '%s'", componentName);
-        }
-    }
-
-    return NULL;
-}
-
-status_t OMXCodec::parseHEVCCodecSpecificData(
-        const void *data, size_t size,
-        unsigned *profile, unsigned *level) {
-    const uint8_t *ptr = (const uint8_t *)data;
-
-    // verify minimum size and configurationVersion == 1.
-    if (size < 23 || ptr[0] != 1) {
-        return ERROR_MALFORMED;
-    }
-
-    *profile = (ptr[1] & 31);
-    *level = ptr[12];
-
-    ptr += 22;
-    size -= 22;
-
-    size_t numofArrays = (char)ptr[0];
-    ptr += 1;
-    size -= 1;
-    size_t j = 0, i = 0;
-    for (i = 0; i < numofArrays; i++) {
-        if (size < 3) {
-            return ERROR_MALFORMED;
-        }
-        ptr += 1;
-        size -= 1;
-
-        // Num of nals
-        size_t numofNals = U16_AT(ptr);
-        ptr += 2;
-        size -= 2;
-
-        for (j = 0;j < numofNals;j++) {
-            if (size < 2) {
-                return ERROR_MALFORMED;
-            }
-
-            size_t length = U16_AT(ptr);
-
-            ptr += 2;
-            size -= 2;
-
-            if (size < length) {
-                return ERROR_MALFORMED;
-            }
-            addCodecSpecificData(ptr, length);
-
-            ptr += length;
-            size -= length;
-        }
-    }
-    return OK;
-}
-
-status_t OMXCodec::parseAVCCodecSpecificData(
-        const void *data, size_t size,
-        unsigned *profile, unsigned *level) {
-    const uint8_t *ptr = (const uint8_t *)data;
-
-    // verify minimum size and configurationVersion == 1.
-    if (size < 7 || ptr[0] != 1) {
-        return ERROR_MALFORMED;
-    }
-
-    *profile = ptr[1];
-    *level = ptr[3];
-
-    // There is decodable content out there that fails the following
-    // assertion, let's be lenient for now...
-    // CHECK((ptr[4] >> 2) == 0x3f);  // reserved
-
-    size_t lengthSize __unused = 1 + (ptr[4] & 3);
-
-    // commented out check below as H264_QVGA_500_NO_AUDIO.3gp
-    // violates it...
-    // CHECK((ptr[5] >> 5) == 7);  // reserved
-
-    size_t numSeqParameterSets = ptr[5] & 31;
-
-    ptr += 6;
-    size -= 6;
-
-    for (size_t i = 0; i < numSeqParameterSets; ++i) {
-        if (size < 2) {
-            return ERROR_MALFORMED;
-        }
-
-        size_t length = U16_AT(ptr);
-
-        ptr += 2;
-        size -= 2;
-
-        if (size < length) {
-            return ERROR_MALFORMED;
-        }
-
-        addCodecSpecificData(ptr, length);
-
-        ptr += length;
-        size -= length;
-    }
-
-    if (size < 1) {
-        return ERROR_MALFORMED;
-    }
-
-    size_t numPictureParameterSets = *ptr;
-    ++ptr;
-    --size;
-
-    for (size_t i = 0; i < numPictureParameterSets; ++i) {
-        if (size < 2) {
-            return ERROR_MALFORMED;
-        }
-
-        size_t length = U16_AT(ptr);
-
-        ptr += 2;
-        size -= 2;
-
-        if (size < length) {
-            return ERROR_MALFORMED;
-        }
-
-        addCodecSpecificData(ptr, length);
-
-        ptr += length;
-        size -= length;
-    }
-
-    return OK;
-}
-
-status_t OMXCodec::configureCodec(const sp<MetaData> &meta) {
-    ALOGV("configureCodec protected=%d",
-         (mFlags & kEnableGrallocUsageProtected) ? 1 : 0);
-
-    if (!(mFlags & kIgnoreCodecSpecificData)) {
-        uint32_t type;
-        const void *data;
-        size_t size;
-        if (meta->findData(kKeyESDS, &type, &data, &size)) {
-            ESDS esds((const char *)data, size);
-            CHECK_EQ(esds.InitCheck(), (status_t)OK);
-
-            const void *codec_specific_data;
-            size_t codec_specific_data_size;
-            esds.getCodecSpecificInfo(
-                    &codec_specific_data, &codec_specific_data_size);
-
-            addCodecSpecificData(
-                    codec_specific_data, codec_specific_data_size);
-        } else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
-            // Parse the AVCDecoderConfigurationRecord
-
-            unsigned profile, level;
-            status_t err;
-            if ((err = parseAVCCodecSpecificData(
-                            data, size, &profile, &level)) != OK) {
-                ALOGE("Malformed AVC codec specific data.");
-                return err;
-            }
-
-            CODEC_LOGI(
-                    "AVC profile = %u (%s), level = %u",
-                    profile, AVCProfileToString(profile), level);
-        } else if (meta->findData(kKeyHVCC, &type, &data, &size)) {
-            // Parse the HEVCDecoderConfigurationRecord
-
-            unsigned profile, level;
-            status_t err;
-            if ((err = parseHEVCCodecSpecificData(
-                            data, size, &profile, &level)) != OK) {
-                ALOGE("Malformed HEVC codec specific data.");
-                return err;
-            }
-
-            CODEC_LOGI(
-                    "HEVC profile = %u , level = %u",
-                    profile, level);
-        } else if (meta->findData(kKeyVorbisInfo, &type, &data, &size)) {
-            addCodecSpecificData(data, size);
-
-            CHECK(meta->findData(kKeyVorbisBooks, &type, &data, &size));
-            addCodecSpecificData(data, size);
-        } else if (meta->findData(kKeyOpusHeader, &type, &data, &size)) {
-            addCodecSpecificData(data, size);
-
-            CHECK(meta->findData(kKeyOpusCodecDelay, &type, &data, &size));
-            addCodecSpecificData(data, size);
-            CHECK(meta->findData(kKeyOpusSeekPreRoll, &type, &data, &size));
-            addCodecSpecificData(data, size);
-        }
-    }
-
-    int32_t bitRate = 0;
-    if (mIsEncoder) {
-        CHECK(meta->findInt32(kKeyBitRate, &bitRate));
-    }
-    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mMIME)) {
-        setAMRFormat(false /* isWAMR */, bitRate);
-    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mMIME)) {
-        setAMRFormat(true /* isWAMR */, bitRate);
-    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mMIME)) {
-        int32_t numChannels, sampleRate, aacProfile;
-        CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
-        CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
-
-        if (!meta->findInt32(kKeyAACProfile, &aacProfile)) {
-            aacProfile = OMX_AUDIO_AACObjectNull;
-        }
-
-        int32_t isADTS;
-        if (!meta->findInt32(kKeyIsADTS, &isADTS)) {
-            isADTS = false;
-        }
-
-        status_t err = setAACFormat(numChannels, sampleRate, bitRate, aacProfile, isADTS);
-        if (err != OK) {
-            CODEC_LOGE("setAACFormat() failed (err = %d)", err);
-            return err;
-        }
-    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_MPEG, mMIME)) {
-        int32_t numChannels, sampleRate;
-        if (meta->findInt32(kKeyChannelCount, &numChannels)
-                && meta->findInt32(kKeySampleRate, &sampleRate)) {
-            // Since we did not always check for these, leave them optional
-            // and have the decoder figure it all out.
-            setRawAudioFormat(
-                    mIsEncoder ? kPortIndexInput : kPortIndexOutput,
-                    sampleRate,
-                    numChannels);
-        }
-    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AC3, mMIME)) {
-        int32_t numChannels;
-        int32_t sampleRate;
-        CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
-        CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
-
-        status_t err = setAC3Format(numChannels, sampleRate);
-        if (err != OK) {
-            CODEC_LOGE("setAC3Format() failed (err = %d)", err);
-            return err;
-        }
-    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_ALAW, mMIME)
-            || !strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_MLAW, mMIME)) {
-        // These are PCM-like formats with a fixed sample rate but
-        // a variable number of channels.
-
-        int32_t sampleRate;
-        int32_t numChannels;
-        CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
-        if (!meta->findInt32(kKeySampleRate, &sampleRate)) {
-            sampleRate = 8000;
-        }
-
-        setG711Format(sampleRate, numChannels);
-    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mMIME)) {
-        CHECK(!mIsEncoder);
-
-        int32_t numChannels, sampleRate;
-        CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
-        CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
-
-        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
-    }
-
-    if (!strncasecmp(mMIME, "video/", 6)) {
-
-        if (mIsEncoder) {
-            setVideoInputFormat(mMIME, meta);
-        } else {
-            status_t err = setVideoOutputFormat(
-                    mMIME, meta);
-
-            if (err != OK) {
-                return err;
-            }
-        }
-    }
-
-    int32_t maxInputSize;
-    if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
-        setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize);
-    }
-
-    initOutputFormat(meta);
-
-    if ((mFlags & kClientNeedsFramebuffer)
-            && !strncmp(mComponentName, "OMX.SEC.", 8)) {
-        // This appears to no longer be needed???
-
-        OMX_INDEXTYPE index;
-
-        status_t err =
-            mOMX->getExtensionIndex(
-                    mNode,
-                    "OMX.SEC.index.ThumbnailMode",
-                    &index);
-
-        if (err != OK) {
-            return err;
-        }
-
-        OMX_BOOL enable = OMX_TRUE;
-        err = mOMX->setConfig(mNode, index, &enable, sizeof(enable));
-
-        if (err != OK) {
-            CODEC_LOGE("setConfig('OMX.SEC.index.ThumbnailMode') "
-                       "returned error 0x%08x", err);
-
-            return err;
-        }
-
-        mQuirks &= ~kOutputBuffersAreUnreadable;
-    }
-
-    if (mNativeWindow != NULL
-        && !mIsEncoder
-        && !strncasecmp(mMIME, "video/", 6)
-        && !strncmp(mComponentName, "OMX.", 4)) {
-        status_t err = initNativeWindow();
-        if (err != OK) {
-            return err;
-        }
-    }
-
-    return OK;
-}
-
-void OMXCodec::setMinBufferSize(OMX_U32 portIndex, OMX_U32 size) {
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = portIndex;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    if ((portIndex == kPortIndexInput && (mQuirks & kInputBufferSizesAreBogus))
-        || (def.nBufferSize < size)) {
-        def.nBufferSize = size;
-    }
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    // Make sure the setting actually stuck.
-    if (portIndex == kPortIndexInput
-            && (mQuirks & kInputBufferSizesAreBogus)) {
-        CHECK_EQ(def.nBufferSize, size);
-    } else {
-        CHECK(def.nBufferSize >= size);
-    }
-}
-
-status_t OMXCodec::setVideoPortFormatType(
-        OMX_U32 portIndex,
-        OMX_VIDEO_CODINGTYPE compressionFormat,
-        OMX_COLOR_FORMATTYPE colorFormat) {
-    OMX_VIDEO_PARAM_PORTFORMATTYPE format;
-    InitOMXParams(&format);
-    format.nPortIndex = portIndex;
-    format.nIndex = 0;
-    bool found = false;
-
-    OMX_U32 index = 0;
-    for (;;) {
-        format.nIndex = index;
-        status_t err = mOMX->getParameter(
-                mNode, OMX_IndexParamVideoPortFormat,
-                &format, sizeof(format));
-
-        if (err != OK) {
-            return err;
-        }
-
-        // The following assertion is violated by TI's video decoder.
-        // CHECK_EQ(format.nIndex, index);
-
-#if 1
-        CODEC_LOGV("portIndex: %u, index: %u, eCompressionFormat=%d eColorFormat=%d",
-             portIndex,
-             index, format.eCompressionFormat, format.eColorFormat);
-#endif
-
-        if (format.eCompressionFormat == compressionFormat
-                && format.eColorFormat == colorFormat) {
-            found = true;
-            break;
-        }
-
-        ++index;
-        if (index >= kMaxColorFormatSupported) {
-            CODEC_LOGE("color format %d or compression format %d is not supported",
-                colorFormat, compressionFormat);
-            return UNKNOWN_ERROR;
-        }
-    }
-
-    if (!found) {
-        return UNKNOWN_ERROR;
-    }
-
-    CODEC_LOGV("found a match.");
-    status_t err = mOMX->setParameter(
-            mNode, OMX_IndexParamVideoPortFormat,
-            &format, sizeof(format));
-
-    return err;
-}
-
-static size_t getFrameSize(
-        OMX_COLOR_FORMATTYPE colorFormat, int32_t width, int32_t height) {
-    switch (colorFormat) {
-        case OMX_COLOR_FormatYCbYCr:
-        case OMX_COLOR_FormatCbYCrY:
-            return width * height * 2;
-
-        case OMX_COLOR_FormatYUV420Planar:
-        case OMX_COLOR_FormatYUV420SemiPlanar:
-        case OMX_TI_COLOR_FormatYUV420PackedSemiPlanar:
-        /*
-        * FIXME: For the Opaque color format, the frame size does not
-        * need to be (w*h*3)/2. It just needs to
-        * be larger than certain minimum buffer size. However,
-        * currently, this opaque foramt has been tested only on
-        * YUV420 formats. If that is changed, then we need to revisit
-        * this part in the future
-        */
-        case OMX_COLOR_FormatAndroidOpaque:
-            return (width * height * 3) / 2;
-
-        default:
-            CHECK(!"Should not be here. Unsupported color format.");
-            break;
-    }
-    return 0;
-}
-
-status_t OMXCodec::findTargetColorFormat(
-        const sp<MetaData>& meta, OMX_COLOR_FORMATTYPE *colorFormat) {
-    ALOGV("findTargetColorFormat");
-    CHECK(mIsEncoder);
-
-    *colorFormat = OMX_COLOR_FormatYUV420SemiPlanar;
-    int32_t targetColorFormat;
-    if (meta->findInt32(kKeyColorFormat, &targetColorFormat)) {
-        *colorFormat = (OMX_COLOR_FORMATTYPE) targetColorFormat;
-    }
-
-    // Check whether the target color format is supported.
-    return isColorFormatSupported(*colorFormat, kPortIndexInput);
-}
-
-status_t OMXCodec::isColorFormatSupported(
-        OMX_COLOR_FORMATTYPE colorFormat, int portIndex) {
-    ALOGV("isColorFormatSupported: %d", static_cast<int>(colorFormat));
-
-    // Enumerate all the color formats supported by
-    // the omx component to see whether the given
-    // color format is supported.
-    OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
-    InitOMXParams(&portFormat);
-    portFormat.nPortIndex = portIndex;
-    OMX_U32 index = 0;
-    portFormat.nIndex = index;
-    while (true) {
-        if (OMX_ErrorNone != mOMX->getParameter(
-                mNode, OMX_IndexParamVideoPortFormat,
-                &portFormat, sizeof(portFormat))) {
-            break;
-        }
-        // Make sure that omx component does not overwrite
-        // the incremented index (bug 2897413).
-        CHECK_EQ(index, portFormat.nIndex);
-        if (portFormat.eColorFormat == colorFormat) {
-            CODEC_LOGV("Found supported color format: %d", portFormat.eColorFormat);
-            return OK;  // colorFormat is supported!
-        }
-        ++index;
-        portFormat.nIndex = index;
-
-        if (index >= kMaxColorFormatSupported) {
-            CODEC_LOGE("More than %u color formats are supported???", index);
-            break;
-        }
-    }
-
-    CODEC_LOGE("color format %d is not supported", colorFormat);
-    return UNKNOWN_ERROR;
-}
-
-void OMXCodec::setVideoInputFormat(
-        const char *mime, const sp<MetaData>& meta) {
-
-    int32_t width, height, frameRate, bitRate, stride, sliceHeight;
-    bool success = meta->findInt32(kKeyWidth, &width);
-    success = success && meta->findInt32(kKeyHeight, &height);
-    success = success && meta->findInt32(kKeyFrameRate, &frameRate);
-    success = success && meta->findInt32(kKeyBitRate, &bitRate);
-    success = success && meta->findInt32(kKeyStride, &stride);
-    success = success && meta->findInt32(kKeySliceHeight, &sliceHeight);
-    CHECK(success);
-    CHECK(stride != 0);
-
-    OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
-    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
-        compressionFormat = OMX_VIDEO_CodingAVC;
-    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_HEVC, mime)) {
-        compressionFormat = OMX_VIDEO_CodingHEVC;
-    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
-        compressionFormat = OMX_VIDEO_CodingMPEG4;
-    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
-        compressionFormat = OMX_VIDEO_CodingH263;
-    } else {
-        ALOGE("Not a supported video mime type: %s", mime);
-        CHECK(!"Should not be here. Not a supported video mime type.");
-    }
-
-    OMX_COLOR_FORMATTYPE colorFormat;
-    CHECK_EQ((status_t)OK, findTargetColorFormat(meta, &colorFormat));
-
-    status_t err;
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
-
-    //////////////////////// Input port /////////////////////////
-    CHECK_EQ(setVideoPortFormatType(
-            kPortIndexInput, OMX_VIDEO_CodingUnused,
-            colorFormat), (status_t)OK);
-
-    InitOMXParams(&def);
-    def.nPortIndex = kPortIndexInput;
-
-    err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    def.nBufferSize = getFrameSize(colorFormat,
-            stride > 0? stride: -stride, sliceHeight);
-
-    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo);
-
-    video_def->nFrameWidth = width;
-    video_def->nFrameHeight = height;
-    video_def->nStride = stride;
-    video_def->nSliceHeight = sliceHeight;
-    video_def->xFramerate = (frameRate << 16);  // Q16 format
-    video_def->eCompressionFormat = OMX_VIDEO_CodingUnused;
-    video_def->eColorFormat = colorFormat;
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    //////////////////////// Output port /////////////////////////
-    CHECK_EQ(setVideoPortFormatType(
-            kPortIndexOutput, compressionFormat, OMX_COLOR_FormatUnused),
-            (status_t)OK);
-    InitOMXParams(&def);
-    def.nPortIndex = kPortIndexOutput;
-
-    err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-
-    CHECK_EQ(err, (status_t)OK);
-    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo);
-
-    video_def->nFrameWidth = width;
-    video_def->nFrameHeight = height;
-    video_def->xFramerate = 0;      // No need for output port
-    video_def->nBitrate = bitRate;  // Q16 format
-    video_def->eCompressionFormat = compressionFormat;
-    video_def->eColorFormat = OMX_COLOR_FormatUnused;
-    if (mQuirks & kRequiresLargerEncoderOutputBuffer) {
-        // Increases the output buffer size
-        def.nBufferSize = ((def.nBufferSize * 3) >> 1);
-    }
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    /////////////////// Codec-specific ////////////////////////
-    switch (compressionFormat) {
-        case OMX_VIDEO_CodingMPEG4:
-        {
-            CHECK_EQ(setupMPEG4EncoderParameters(meta), (status_t)OK);
-            break;
-        }
-
-        case OMX_VIDEO_CodingH263:
-            CHECK_EQ(setupH263EncoderParameters(meta), (status_t)OK);
-            break;
-
-        case OMX_VIDEO_CodingAVC:
-        {
-            CHECK_EQ(setupAVCEncoderParameters(meta), (status_t)OK);
-            break;
-        }
-
-        default:
-            CHECK(!"Support for this compressionFormat to be implemented.");
-            break;
-    }
-}
-
-static OMX_U32 setPFramesSpacing(int32_t iFramesInterval, int32_t frameRate) {
-    if (iFramesInterval < 0) {
-        return 0xFFFFFFFF;
-    } else if (iFramesInterval == 0) {
-        return 0;
-    }
-    OMX_U32 ret = frameRate * iFramesInterval - 1;
-    return ret;
-}
-
-status_t OMXCodec::setupErrorCorrectionParameters() {
-    OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE errorCorrectionType;
-    InitOMXParams(&errorCorrectionType);
-    errorCorrectionType.nPortIndex = kPortIndexOutput;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamVideoErrorCorrection,
-            &errorCorrectionType, sizeof(errorCorrectionType));
-    if (err != OK) {
-        ALOGW("Error correction param query is not supported");
-        return OK;  // Optional feature. Ignore this failure
-    }
-
-    errorCorrectionType.bEnableHEC = OMX_FALSE;
-    errorCorrectionType.bEnableResync = OMX_TRUE;
-    errorCorrectionType.nResynchMarkerSpacing = 256;
-    errorCorrectionType.bEnableDataPartitioning = OMX_FALSE;
-    errorCorrectionType.bEnableRVLC = OMX_FALSE;
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamVideoErrorCorrection,
-            &errorCorrectionType, sizeof(errorCorrectionType));
-    if (err != OK) {
-        ALOGW("Error correction param configuration is not supported");
-    }
-
-    // Optional feature. Ignore the failure.
-    return OK;
-}
-
-status_t OMXCodec::setupBitRate(int32_t bitRate) {
-    OMX_VIDEO_PARAM_BITRATETYPE bitrateType;
-    InitOMXParams(&bitrateType);
-    bitrateType.nPortIndex = kPortIndexOutput;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamVideoBitrate,
-            &bitrateType, sizeof(bitrateType));
-    CHECK_EQ(err, (status_t)OK);
-
-    bitrateType.eControlRate = OMX_Video_ControlRateVariable;
-    bitrateType.nTargetBitrate = bitRate;
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamVideoBitrate,
-            &bitrateType, sizeof(bitrateType));
-    CHECK_EQ(err, (status_t)OK);
-    return OK;
-}
-
-status_t OMXCodec::getVideoProfileLevel(
-        const sp<MetaData>& meta,
-        const CodecProfileLevel& defaultProfileLevel,
-        CodecProfileLevel &profileLevel) {
-    CODEC_LOGV("Default profile: %u, level #x%x",
-            defaultProfileLevel.mProfile, defaultProfileLevel.mLevel);
-
-    // Are the default profile and level overwriten?
-    int32_t profile, level;
-    if (!meta->findInt32(kKeyVideoProfile, &profile)) {
-        profile = defaultProfileLevel.mProfile;
-    }
-    if (!meta->findInt32(kKeyVideoLevel, &level)) {
-        level = defaultProfileLevel.mLevel;
-    }
-    CODEC_LOGV("Target profile: %d, level: %d", profile, level);
-
-    // Are the target profile and level supported by the encoder?
-    OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
-    InitOMXParams(&param);
-    param.nPortIndex = kPortIndexOutput;
-    for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
-        status_t err = mOMX->getParameter(
-                mNode, OMX_IndexParamVideoProfileLevelQuerySupported,
-                &param, sizeof(param));
-
-        if (err != OK) break;
-
-        int32_t supportedProfile = static_cast<int32_t>(param.eProfile);
-        int32_t supportedLevel = static_cast<int32_t>(param.eLevel);
-        CODEC_LOGV("Supported profile: %d, level %d",
-            supportedProfile, supportedLevel);
-
-        if (profile == supportedProfile &&
-            level <= supportedLevel) {
-            // We can further check whether the level is a valid
-            // value; but we will leave that to the omx encoder component
-            // via OMX_SetParameter call.
-            profileLevel.mProfile = profile;
-            profileLevel.mLevel = level;
-            return OK;
-        }
-    }
-
-    CODEC_LOGE("Target profile (%d) and level (%d) is not supported",
-            profile, level);
-    return BAD_VALUE;
-}
-
-status_t OMXCodec::setupH263EncoderParameters(const sp<MetaData>& meta) {
-    int32_t iFramesInterval, frameRate, bitRate;
-    bool success = meta->findInt32(kKeyBitRate, &bitRate);
-    success = success && meta->findInt32(kKeyFrameRate, &frameRate);
-    success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval);
-    CHECK(success);
-    OMX_VIDEO_PARAM_H263TYPE h263type;
-    InitOMXParams(&h263type);
-    h263type.nPortIndex = kPortIndexOutput;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type));
-    CHECK_EQ(err, (status_t)OK);
-
-    h263type.nAllowedPictureTypes =
-        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
-
-    h263type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate);
-    if (h263type.nPFrames == 0) {
-        h263type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI;
-    }
-    h263type.nBFrames = 0;
-
-    // Check profile and level parameters
-    CodecProfileLevel defaultProfileLevel, profileLevel;
-    defaultProfileLevel.mProfile = h263type.eProfile;
-    defaultProfileLevel.mLevel = h263type.eLevel;
-    err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel);
-    if (err != OK) return err;
-    h263type.eProfile = static_cast<OMX_VIDEO_H263PROFILETYPE>(profileLevel.mProfile);
-    h263type.eLevel = static_cast<OMX_VIDEO_H263LEVELTYPE>(profileLevel.mLevel);
-
-    h263type.bPLUSPTYPEAllowed = OMX_FALSE;
-    h263type.bForceRoundingTypeToZero = OMX_FALSE;
-    h263type.nPictureHeaderRepetition = 0;
-    h263type.nGOBHeaderInterval = 0;
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type));
-    CHECK_EQ(err, (status_t)OK);
-
-    CHECK_EQ(setupBitRate(bitRate), (status_t)OK);
-    CHECK_EQ(setupErrorCorrectionParameters(), (status_t)OK);
-
-    return OK;
-}
-
-status_t OMXCodec::setupMPEG4EncoderParameters(const sp<MetaData>& meta) {
-    int32_t iFramesInterval, frameRate, bitRate;
-    bool success = meta->findInt32(kKeyBitRate, &bitRate);
-    success = success && meta->findInt32(kKeyFrameRate, &frameRate);
-    success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval);
-    CHECK(success);
-    OMX_VIDEO_PARAM_MPEG4TYPE mpeg4type;
-    InitOMXParams(&mpeg4type);
-    mpeg4type.nPortIndex = kPortIndexOutput;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
-    CHECK_EQ(err, (status_t)OK);
-
-    mpeg4type.nSliceHeaderSpacing = 0;
-    mpeg4type.bSVH = OMX_FALSE;
-    mpeg4type.bGov = OMX_FALSE;
-
-    mpeg4type.nAllowedPictureTypes =
-        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
-
-    mpeg4type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate);
-    if (mpeg4type.nPFrames == 0) {
-        mpeg4type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI;
-    }
-    mpeg4type.nBFrames = 0;
-    mpeg4type.nIDCVLCThreshold = 0;
-    mpeg4type.bACPred = OMX_TRUE;
-    mpeg4type.nMaxPacketSize = 256;
-    mpeg4type.nTimeIncRes = 1000;
-    mpeg4type.nHeaderExtension = 0;
-    mpeg4type.bReversibleVLC = OMX_FALSE;
-
-    // Check profile and level parameters
-    CodecProfileLevel defaultProfileLevel, profileLevel;
-    defaultProfileLevel.mProfile = mpeg4type.eProfile;
-    defaultProfileLevel.mLevel = mpeg4type.eLevel;
-    err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel);
-    if (err != OK) return err;
-    mpeg4type.eProfile = static_cast<OMX_VIDEO_MPEG4PROFILETYPE>(profileLevel.mProfile);
-    mpeg4type.eLevel = static_cast<OMX_VIDEO_MPEG4LEVELTYPE>(profileLevel.mLevel);
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
-    CHECK_EQ(err, (status_t)OK);
-
-    CHECK_EQ(setupBitRate(bitRate), (status_t)OK);
-    CHECK_EQ(setupErrorCorrectionParameters(), (status_t)OK);
-
-    return OK;
-}
-
-status_t OMXCodec::setupAVCEncoderParameters(const sp<MetaData>& meta) {
-    int32_t iFramesInterval, frameRate, bitRate;
-    bool success = meta->findInt32(kKeyBitRate, &bitRate);
-    success = success && meta->findInt32(kKeyFrameRate, &frameRate);
-    success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval);
-    CHECK(success);
-
-    OMX_VIDEO_PARAM_AVCTYPE h264type;
-    InitOMXParams(&h264type);
-    h264type.nPortIndex = kPortIndexOutput;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
-    CHECK_EQ(err, (status_t)OK);
-
-    h264type.nAllowedPictureTypes =
-        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
-
-    // Check profile and level parameters
-    CodecProfileLevel defaultProfileLevel, profileLevel;
-    defaultProfileLevel.mProfile = h264type.eProfile;
-    defaultProfileLevel.mLevel = h264type.eLevel;
-    err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel);
-    if (err != OK) return err;
-    h264type.eProfile = static_cast<OMX_VIDEO_AVCPROFILETYPE>(profileLevel.mProfile);
-    h264type.eLevel = static_cast<OMX_VIDEO_AVCLEVELTYPE>(profileLevel.mLevel);
-
-    // XXX
-    if (h264type.eProfile != OMX_VIDEO_AVCProfileBaseline) {
-        ALOGW("Use baseline profile instead of %d for AVC recording",
-            h264type.eProfile);
-        h264type.eProfile = OMX_VIDEO_AVCProfileBaseline;
-    }
-
-    if (h264type.eProfile == OMX_VIDEO_AVCProfileBaseline) {
-        h264type.nSliceHeaderSpacing = 0;
-        h264type.bUseHadamard = OMX_TRUE;
-        h264type.nRefFrames = 1;
-        h264type.nBFrames = 0;
-        h264type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate);
-        if (h264type.nPFrames == 0) {
-            h264type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI;
-        }
-        h264type.nRefIdx10ActiveMinus1 = 0;
-        h264type.nRefIdx11ActiveMinus1 = 0;
-        h264type.bEntropyCodingCABAC = OMX_FALSE;
-        h264type.bWeightedPPrediction = OMX_FALSE;
-        h264type.bconstIpred = OMX_FALSE;
-        h264type.bDirect8x8Inference = OMX_FALSE;
-        h264type.bDirectSpatialTemporal = OMX_FALSE;
-        h264type.nCabacInitIdc = 0;
-    }
-
-    if (h264type.nBFrames != 0) {
-        h264type.nAllowedPictureTypes |= OMX_VIDEO_PictureTypeB;
-    }
-
-    h264type.bEnableUEP = OMX_FALSE;
-    h264type.bEnableFMO = OMX_FALSE;
-    h264type.bEnableASO = OMX_FALSE;
-    h264type.bEnableRS = OMX_FALSE;
-    h264type.bFrameMBsOnly = OMX_TRUE;
-    h264type.bMBAFF = OMX_FALSE;
-    h264type.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable;
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
-    CHECK_EQ(err, (status_t)OK);
-
-    CHECK_EQ(setupBitRate(bitRate), (status_t)OK);
-
-    return OK;
-}
-
-status_t OMXCodec::setVideoOutputFormat(
-        const char *mime, const sp<MetaData>& meta) {
-
-    int32_t width, height;
-    bool success = meta->findInt32(kKeyWidth, &width);
-    success = success && meta->findInt32(kKeyHeight, &height);
-    CHECK(success);
-
-    CODEC_LOGV("setVideoOutputFormat width=%d, height=%d", width, height);
-
-    OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
-    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
-        compressionFormat = OMX_VIDEO_CodingAVC;
-    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
-        compressionFormat = OMX_VIDEO_CodingMPEG4;
-    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_HEVC, mime)) {
-        compressionFormat = OMX_VIDEO_CodingHEVC;
-    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
-        compressionFormat = OMX_VIDEO_CodingH263;
-    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_VP8, mime)) {
-        compressionFormat = OMX_VIDEO_CodingVP8;
-    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_VP9, mime)) {
-        compressionFormat = OMX_VIDEO_CodingVP9;
-    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG2, mime)) {
-        compressionFormat = OMX_VIDEO_CodingMPEG2;
-    } else {
-        ALOGE("Not a supported video mime type: %s", mime);
-        CHECK(!"Should not be here. Not a supported video mime type.");
-    }
-
-    status_t err = setVideoPortFormatType(
-            kPortIndexInput, compressionFormat, OMX_COLOR_FormatUnused);
-
-    if (err != OK) {
-        return err;
-    }
-
-#if 1
-    {
-        OMX_VIDEO_PARAM_PORTFORMATTYPE format;
-        InitOMXParams(&format);
-        format.nPortIndex = kPortIndexOutput;
-        format.nIndex = 0;
-
-        status_t err = mOMX->getParameter(
-                mNode, OMX_IndexParamVideoPortFormat,
-                &format, sizeof(format));
-        CHECK_EQ(err, (status_t)OK);
-        CHECK_EQ((int)format.eCompressionFormat, (int)OMX_VIDEO_CodingUnused);
-
-        int32_t colorFormat;
-        if (meta->findInt32(kKeyColorFormat, &colorFormat)
-                && colorFormat != OMX_COLOR_FormatUnused
-                && colorFormat != format.eColorFormat) {
-
-            while (OMX_ErrorNoMore != err) {
-                format.nIndex++;
-                err = mOMX->getParameter(
-                        mNode, OMX_IndexParamVideoPortFormat,
-                            &format, sizeof(format));
-                if (format.eColorFormat == colorFormat) {
-                    break;
-                }
-            }
-            if (format.eColorFormat != colorFormat) {
-                CODEC_LOGE("Color format %d is not supported", colorFormat);
-                return ERROR_UNSUPPORTED;
-            }
-        }
-
-        err = mOMX->setParameter(
-                mNode, OMX_IndexParamVideoPortFormat,
-                &format, sizeof(format));
-
-        if (err != OK) {
-            return err;
-        }
-    }
-#endif
-
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = kPortIndexInput;
-
-    OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
-
-    err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-
-    CHECK_EQ(err, (status_t)OK);
-
-#if 1
-    // XXX Need a (much) better heuristic to compute input buffer sizes.
-    const size_t X = 64 * 1024;
-    if (def.nBufferSize < X) {
-        def.nBufferSize = X;
-    }
-#endif
-
-    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo);
-
-    video_def->nFrameWidth = width;
-    video_def->nFrameHeight = height;
-
-    video_def->eCompressionFormat = compressionFormat;
-    video_def->eColorFormat = OMX_COLOR_FormatUnused;
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-
-    if (err != OK) {
-        return err;
-    }
-
-    ////////////////////////////////////////////////////////////////////////////
-
-    InitOMXParams(&def);
-    def.nPortIndex = kPortIndexOutput;
-
-    err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo);
-
-#if 0
-    def.nBufferSize =
-        (((width + 15) & -16) * ((height + 15) & -16) * 3) / 2;  // YUV420
-#endif
-
-    video_def->nFrameWidth = width;
-    video_def->nFrameHeight = height;
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-
-    return err;
-}
-
-OMXCodec::OMXCodec(
-        const sp<IOMX> &omx, IOMX::node_id node,
-        uint32_t quirks, uint32_t flags,
-        bool isEncoder,
-        const char *mime,
-        const char *componentName,
-        const sp<MediaSource> &source,
-        const sp<ANativeWindow> &nativeWindow)
-    : mOMX(omx),
-      mOMXLivesLocally(omx->livesLocally(node, getpid())),
-      mNode(node),
-      mQuirks(quirks),
-      mFlags(flags),
-      mIsEncoder(isEncoder),
-      mIsVideo(!strncasecmp("video/", mime, 6)),
-      mMIME(strdup(mime)),
-      mComponentName(strdup(componentName)),
-      mSource(source),
-      mCodecSpecificDataIndex(0),
-      mState(LOADED),
-      mInitialBufferSubmit(true),
-      mSignalledEOS(false),
-      mNoMoreOutputData(false),
-      mOutputPortSettingsHaveChanged(false),
-      mSeekTimeUs(-1),
-      mSeekMode(ReadOptions::SEEK_CLOSEST_SYNC),
-      mTargetTimeUs(-1),
-      mOutputPortSettingsChangedPending(false),
-      mSkipCutBuffer(NULL),
-      mLeftOverBuffer(NULL),
-      mPaused(false),
-      mNativeWindow(
-              (!strncmp(componentName, "OMX.google.", 11))
-                        ? NULL : nativeWindow) {
-    mPortStatus[kPortIndexInput] = ENABLED;
-    mPortStatus[kPortIndexOutput] = ENABLED;
-
-    setComponentRole();
-}
-
-// static
-void OMXCodec::setComponentRole(
-        const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder,
-        const char *mime) {
-    struct MimeToRole {
-        const char *mime;
-        const char *decoderRole;
-        const char *encoderRole;
-    };
-
-    static const MimeToRole kMimeToRole[] = {
-        { MEDIA_MIMETYPE_AUDIO_MPEG,
-            "audio_decoder.mp3", "audio_encoder.mp3" },
-        { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I,
-            "audio_decoder.mp1", "audio_encoder.mp1" },
-        { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II,
-            "audio_decoder.mp2", "audio_encoder.mp2" },
-        { MEDIA_MIMETYPE_AUDIO_AMR_NB,
-            "audio_decoder.amrnb", "audio_encoder.amrnb" },
-        { MEDIA_MIMETYPE_AUDIO_AMR_WB,
-            "audio_decoder.amrwb", "audio_encoder.amrwb" },
-        { MEDIA_MIMETYPE_AUDIO_AAC,
-            "audio_decoder.aac", "audio_encoder.aac" },
-        { MEDIA_MIMETYPE_AUDIO_VORBIS,
-            "audio_decoder.vorbis", "audio_encoder.vorbis" },
-        { MEDIA_MIMETYPE_AUDIO_OPUS,
-            "audio_decoder.opus", "audio_encoder.opus" },
-        { MEDIA_MIMETYPE_AUDIO_G711_MLAW,
-            "audio_decoder.g711mlaw", "audio_encoder.g711mlaw" },
-        { MEDIA_MIMETYPE_AUDIO_G711_ALAW,
-            "audio_decoder.g711alaw", "audio_encoder.g711alaw" },
-        { MEDIA_MIMETYPE_VIDEO_AVC,
-            "video_decoder.avc", "video_encoder.avc" },
-        { MEDIA_MIMETYPE_VIDEO_HEVC,
-            "video_decoder.hevc", "video_encoder.hevc" },
-        { MEDIA_MIMETYPE_VIDEO_MPEG4,
-            "video_decoder.mpeg4", "video_encoder.mpeg4" },
-        { MEDIA_MIMETYPE_VIDEO_H263,
-            "video_decoder.h263", "video_encoder.h263" },
-        { MEDIA_MIMETYPE_VIDEO_VP8,
-            "video_decoder.vp8", "video_encoder.vp8" },
-        { MEDIA_MIMETYPE_VIDEO_VP9,
-            "video_decoder.vp9", "video_encoder.vp9" },
-        { MEDIA_MIMETYPE_AUDIO_RAW,
-            "audio_decoder.raw", "audio_encoder.raw" },
-        { MEDIA_MIMETYPE_AUDIO_FLAC,
-            "audio_decoder.flac", "audio_encoder.flac" },
-        { MEDIA_MIMETYPE_AUDIO_MSGSM,
-            "audio_decoder.gsm", "audio_encoder.gsm" },
-        { MEDIA_MIMETYPE_VIDEO_MPEG2,
-            "video_decoder.mpeg2", "video_encoder.mpeg2" },
-        { MEDIA_MIMETYPE_AUDIO_AC3,
-            "audio_decoder.ac3", "audio_encoder.ac3" },
-    };
-
-    static const size_t kNumMimeToRole =
-        sizeof(kMimeToRole) / sizeof(kMimeToRole[0]);
-
-    size_t i;
-    for (i = 0; i < kNumMimeToRole; ++i) {
-        if (!strcasecmp(mime, kMimeToRole[i].mime)) {
-            break;
-        }
-    }
-
-    if (i == kNumMimeToRole) {
-        return;
-    }
-
-    const char *role =
-        isEncoder ? kMimeToRole[i].encoderRole
-                  : kMimeToRole[i].decoderRole;
-
-    if (role != NULL) {
-        OMX_PARAM_COMPONENTROLETYPE roleParams;
-        InitOMXParams(&roleParams);
-
-        strncpy((char *)roleParams.cRole,
-                role, OMX_MAX_STRINGNAME_SIZE - 1);
-
-        roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
-
-        status_t err = omx->setParameter(
-                node, OMX_IndexParamStandardComponentRole,
-                &roleParams, sizeof(roleParams));
-
-        if (err != OK) {
-            ALOGW("Failed to set standard component role '%s'.", role);
-        }
-    }
-}
-
-void OMXCodec::setComponentRole() {
-    setComponentRole(mOMX, mNode, mIsEncoder, mMIME);
-}
-
-OMXCodec::~OMXCodec() {
-    mSource.clear();
-
-    CHECK(mState == LOADED || mState == ERROR || mState == LOADED_TO_IDLE);
-
-    status_t err = mOMX->freeNode(mNode);
-    CHECK_EQ(err, (status_t)OK);
-
-    mNode = 0;
-    setState(DEAD);
-
-    clearCodecSpecificData();
-
-    free(mComponentName);
-    mComponentName = NULL;
-
-    free(mMIME);
-    mMIME = NULL;
-}
-
-status_t OMXCodec::init() {
-    // mLock is held.
-
-    CHECK_EQ((int)mState, (int)LOADED);
-
-    status_t err;
-    if (!(mQuirks & kRequiresLoadedToIdleAfterAllocation)) {
-        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
-        CHECK_EQ(err, (status_t)OK);
-        setState(LOADED_TO_IDLE);
-    }
-
-    err = allocateBuffers();
-    if (err != (status_t)OK) {
-        return err;
-    }
-
-    if (mQuirks & kRequiresLoadedToIdleAfterAllocation) {
-        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
-        CHECK_EQ(err, (status_t)OK);
-
-        setState(LOADED_TO_IDLE);
-    }
-
-    while (mState != EXECUTING && mState != ERROR) {
-        mAsyncCompletion.wait(mLock);
-    }
-
-    return mState == ERROR ? UNKNOWN_ERROR : OK;
-}
-
-// static
-bool OMXCodec::isIntermediateState(State state) {
-    return state == LOADED_TO_IDLE
-        || state == IDLE_TO_EXECUTING
-        || state == EXECUTING_TO_IDLE
-        || state == IDLE_TO_LOADED
-        || state == RECONFIGURING;
-}
-
-status_t OMXCodec::allocateBuffers() {
-    status_t err = allocateBuffersOnPort(kPortIndexInput);
-
-    if (err != OK) {
-        return err;
-    }
-
-    return allocateBuffersOnPort(kPortIndexOutput);
-}
-
-status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) {
-    if (mNativeWindow != NULL && portIndex == kPortIndexOutput) {
-        return allocateOutputBuffersFromNativeWindow();
-    }
-
-    if ((mFlags & kEnableGrallocUsageProtected) && portIndex == kPortIndexOutput) {
-        ALOGE("protected output buffers must be stent to an ANativeWindow");
-        return PERMISSION_DENIED;
-    }
-
-    status_t err = OK;
-    if ((mFlags & kStoreMetaDataInVideoBuffers)
-            && portIndex == kPortIndexInput) {
-        err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE);
-        if (err != OK) {
-            ALOGE("Storing meta data in video buffers is not supported");
-            return err;
-        }
-    }
-
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = portIndex;
-
-    err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-
-    if (err != OK) {
-        return err;
-    }
-
-    CODEC_LOGV("allocating %u buffers of size %u on %s port",
-            def.nBufferCountActual, def.nBufferSize,
-            portIndex == kPortIndexInput ? "input" : "output");
-
-    if (def.nBufferSize != 0 && def.nBufferCountActual > SIZE_MAX / def.nBufferSize) {
-        return BAD_VALUE;
-    }
-    size_t totalSize = def.nBufferCountActual * def.nBufferSize;
-    mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec");
-
-    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
-        sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize);
-        CHECK(mem.get() != NULL);
-
-        BufferInfo info;
-        info.mData = NULL;
-        info.mSize = def.nBufferSize;
-
-        IOMX::buffer_id buffer;
-        if (portIndex == kPortIndexInput
-                && ((mQuirks & kRequiresAllocateBufferOnInputPorts)
-                    || (mFlags & kUseSecureInputBuffers))) {
-            if (mOMXLivesLocally) {
-                mem.clear();
-
-                err = mOMX->allocateBuffer(
-                        mNode, portIndex, def.nBufferSize, &buffer,
-                        &info.mData);
-            } else {
-                err = mOMX->allocateBufferWithBackup(
-                        mNode, portIndex, mem, &buffer, mem->size());
-            }
-        } else if (portIndex == kPortIndexOutput
-                && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) {
-            if (mOMXLivesLocally) {
-                mem.clear();
-
-                err = mOMX->allocateBuffer(
-                        mNode, portIndex, def.nBufferSize, &buffer,
-                        &info.mData);
-            } else {
-                err = mOMX->allocateBufferWithBackup(
-                        mNode, portIndex, mem, &buffer, mem->size());
-            }
-        } else {
-            err = mOMX->useBuffer(mNode, portIndex, mem, &buffer, mem->size());
-        }
-
-        if (err != OK) {
-            ALOGE("allocate_buffer_with_backup failed");
-            return err;
-        }
-
-        if (mem != NULL) {
-            info.mData = mem->pointer();
-        }
-
-        info.mBuffer = buffer;
-        info.mStatus = OWNED_BY_US;
-        info.mMem = mem;
-        info.mMediaBuffer = NULL;
-
-        if (portIndex == kPortIndexOutput) {
-            // Fail deferred MediaBuffer creation until FILL_BUFFER_DONE;
-            // this legacy mode is no longer supported.
-            LOG_ALWAYS_FATAL_IF((mOMXLivesLocally
-                    && (mQuirks & kRequiresAllocateBufferOnOutputPorts)
-                    && (mQuirks & kDefersOutputBufferAllocation)),
-                    "allocateBuffersOnPort cannot defer buffer allocation");
-
-            info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize);
-            info.mMediaBuffer->setObserver(this);
-        }
-
-        mPortBuffers[portIndex].push(info);
-
-        CODEC_LOGV("allocated buffer %u on %s port", buffer,
-             portIndex == kPortIndexInput ? "input" : "output");
-    }
-
-    if (portIndex == kPortIndexOutput) {
-
-        sp<MetaData> meta = mSource->getFormat();
-        int32_t delay = 0;
-        if (!meta->findInt32(kKeyEncoderDelay, &delay)) {
-            delay = 0;
-        }
-        int32_t padding = 0;
-        if (!meta->findInt32(kKeyEncoderPadding, &padding)) {
-            padding = 0;
-        }
-        int32_t numchannels = 0;
-        if (delay + padding) {
-            if (mOutputFormat->findInt32(kKeyChannelCount, &numchannels)) {
-                if (mSkipCutBuffer != NULL) {
-                    size_t prevbuffersize = mSkipCutBuffer->size();
-                    if (prevbuffersize != 0) {
-                        ALOGW("Replacing SkipCutBuffer holding %zu bytes", prevbuffersize);
-                    }
-                }
-                mSkipCutBuffer = new SkipCutBuffer(delay, padding, numchannels);
-            }
-        }
-    }
-
-    // dumpPortStatus(portIndex);
-
-    if (portIndex == kPortIndexInput && (mFlags & kUseSecureInputBuffers)) {
-        Vector<MediaBuffer *> buffers;
-        for (size_t i = 0; i < def.nBufferCountActual; ++i) {
-            const BufferInfo &info = mPortBuffers[kPortIndexInput].itemAt(i);
-
-            MediaBuffer *mbuf = new MediaBuffer(info.mData, info.mSize);
-            buffers.push(mbuf);
-        }
-
-        status_t err = mSource->setBuffers(buffers);
-
-        if (err != OK) {
-            for (size_t i = 0; i < def.nBufferCountActual; ++i) {
-                buffers.editItemAt(i)->release();
-            }
-            buffers.clear();
-
-            CODEC_LOGE(
-                    "Codec requested to use secure input buffers but "
-                    "upstream source didn't support that.");
-
-            return err;
-        }
-    }
-
-    return OK;
-}
-
-status_t OMXCodec::allocateOutputBuffersFromNativeWindow() {
-    // Get the number of buffers needed.
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = kPortIndexOutput;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    if (err != OK) {
-        CODEC_LOGE("getParameter failed: %d", err);
-        return err;
-    }
-
-    sp<MetaData> meta = mSource->getFormat();
-
-    int32_t rotationDegrees;
-    if (!meta->findInt32(kKeyRotation, &rotationDegrees)) {
-        rotationDegrees = 0;
-    }
-
-    // Set up the native window.
-    OMX_U32 usage = 0;
-    err = mOMX->getGraphicBufferUsage(mNode, kPortIndexOutput, &usage);
-    if (err != 0) {
-        ALOGW("querying usage flags from OMX IL component failed: %d", err);
-        // XXX: Currently this error is logged, but not fatal.
-        usage = 0;
-    }
-
-    if (mFlags & kEnableGrallocUsageProtected) {
-        usage |= GRALLOC_USAGE_PROTECTED;
-    }
-
-    err = setNativeWindowSizeFormatAndUsage(
-            mNativeWindow.get(),
-            def.format.video.nFrameWidth,
-            def.format.video.nFrameHeight,
-            def.format.video.eColorFormat,
-            rotationDegrees,
-            usage | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP);
-    if (err != 0) {
-        return err;
-    }
-
-    int minUndequeuedBufs = 0;
-    err = mNativeWindow->query(mNativeWindow.get(),
-            NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufs);
-    if (err != 0) {
-        ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
-                strerror(-err), -err);
-        return err;
-    }
-    // FIXME: assume that surface is controlled by app (native window
-    // returns the number for the case when surface is not controlled by app)
-    // FIXME2: This means that minUndeqeueudBufs can be 1 larger than reported
-    // For now, try to allocate 1 more buffer, but don't fail if unsuccessful
-
-    // Use conservative allocation while also trying to reduce starvation
-    //
-    // 1. allocate at least nBufferCountMin + minUndequeuedBuffers - that is the
-    //    minimum needed for the consumer to be able to work
-    // 2. try to allocate two (2) additional buffers to reduce starvation from
-    //    the consumer
-    //    plus an extra buffer to account for incorrect minUndequeuedBufs
-    CODEC_LOGI("OMX-buffers: min=%u actual=%u undeq=%d+1",
-            def.nBufferCountMin, def.nBufferCountActual, minUndequeuedBufs);
-
-    for (OMX_U32 extraBuffers = 2 + 1; /* condition inside loop */; extraBuffers--) {
-        OMX_U32 newBufferCount =
-            def.nBufferCountMin + minUndequeuedBufs + extraBuffers;
-        def.nBufferCountActual = newBufferCount;
-        err = mOMX->setParameter(
-                mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-
-        if (err == OK) {
-            minUndequeuedBufs += extraBuffers;
-            break;
-        }
-
-        CODEC_LOGW("setting nBufferCountActual to %u failed: %d",
-                newBufferCount, err);
-        /* exit condition */
-        if (extraBuffers == 0) {
-            return err;
-        }
-    }
-    CODEC_LOGI("OMX-buffers: min=%u actual=%u undeq=%d+1",
-            def.nBufferCountMin, def.nBufferCountActual, minUndequeuedBufs);
-
-    err = native_window_set_buffer_count(
-            mNativeWindow.get(), def.nBufferCountActual);
-    if (err != 0) {
-        ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
-                -err);
-        return err;
-    }
-
-    CODEC_LOGV("allocating %u buffers from a native window of size %u on "
-            "output port", def.nBufferCountActual, def.nBufferSize);
-
-    // Dequeue buffers and send them to OMX
-    for (OMX_U32 i = 0; i < def.nBufferCountActual; i++) {
-        ANativeWindowBuffer* buf;
-        err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(), &buf);
-        if (err != 0) {
-            ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), -err);
-            break;
-        }
-
-        sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false));
-        BufferInfo info;
-        info.mData = NULL;
-        info.mSize = def.nBufferSize;
-        info.mStatus = OWNED_BY_US;
-        info.mMem = NULL;
-        info.mMediaBuffer = new MediaBuffer(graphicBuffer);
-        info.mMediaBuffer->setObserver(this);
-        mPortBuffers[kPortIndexOutput].push(info);
-
-        IOMX::buffer_id bufferId;
-        err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
-                &bufferId);
-        if (err != 0) {
-            CODEC_LOGE("registering GraphicBuffer with OMX IL component "
-                    "failed: %d", err);
-            break;
-        }
-
-        mPortBuffers[kPortIndexOutput].editItemAt(i).mBuffer = bufferId;
-
-        CODEC_LOGV("registered graphic buffer with ID %u (pointer = %p)",
-                bufferId, graphicBuffer.get());
-    }
-
-    OMX_U32 cancelStart;
-    OMX_U32 cancelEnd;
-    if (err != 0) {
-        // If an error occurred while dequeuing we need to cancel any buffers
-        // that were dequeued.
-        cancelStart = 0;
-        cancelEnd = mPortBuffers[kPortIndexOutput].size();
-    } else {
-        // Return the last two buffers to the native window.
-        cancelStart = def.nBufferCountActual - minUndequeuedBufs;
-        cancelEnd = def.nBufferCountActual;
-    }
-
-    for (OMX_U32 i = cancelStart; i < cancelEnd; i++) {
-        BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(i);
-        cancelBufferToNativeWindow(info);
-    }
-
-    return err;
-}
-
-status_t OMXCodec::cancelBufferToNativeWindow(BufferInfo *info) {
-    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
-    CODEC_LOGV("Calling cancelBuffer on buffer %u", info->mBuffer);
-    int err = mNativeWindow->cancelBuffer(
-        mNativeWindow.get(), info->mMediaBuffer->graphicBuffer().get(), -1);
-    if (err != 0) {
-      CODEC_LOGE("cancelBuffer failed w/ error 0x%08x", err);
-
-      setState(ERROR);
-      return err;
-    }
-    info->mStatus = OWNED_BY_NATIVE_WINDOW;
-    return OK;
-}
-
-OMXCodec::BufferInfo* OMXCodec::dequeueBufferFromNativeWindow() {
-    // Dequeue the next buffer from the native window.
-    ANativeWindowBuffer* buf;
-    int err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(), &buf);
-    if (err != 0) {
-      CODEC_LOGE("dequeueBuffer failed w/ error 0x%08x", err);
-
-      setState(ERROR);
-      return 0;
-    }
-
-    // Determine which buffer we just dequeued.
-    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
-    BufferInfo *bufInfo = 0;
-    for (size_t i = 0; i < buffers->size(); i++) {
-      sp<GraphicBuffer> graphicBuffer = buffers->itemAt(i).
-          mMediaBuffer->graphicBuffer();
-      if (graphicBuffer->handle == buf->handle) {
-        bufInfo = &buffers->editItemAt(i);
-        break;
-      }
-    }
-
-    if (bufInfo == 0) {
-        CODEC_LOGE("dequeued unrecognized buffer: %p", buf);
-
-        setState(ERROR);
-        return 0;
-    }
-
-    // The native window no longer owns the buffer.
-    CHECK_EQ((int)bufInfo->mStatus, (int)OWNED_BY_NATIVE_WINDOW);
-    bufInfo->mStatus = OWNED_BY_US;
-
-    return bufInfo;
-}
-
-int64_t OMXCodec::getDecodingTimeUs() {
-    CHECK(mIsEncoder && mIsVideo);
-
-    if (mDecodingTimeList.empty()) {
-        CHECK(mSignalledEOS || mNoMoreOutputData);
-        // No corresponding input frame available.
-        // This could happen when EOS is reached.
-        return 0;
-    }
-
-    List<int64_t>::iterator it = mDecodingTimeList.begin();
-    int64_t timeUs = *it;
-    mDecodingTimeList.erase(it);
-    return timeUs;
-}
-
-void OMXCodec::on_message(const omx_message &msg) {
-    if (mState == ERROR) {
-        /*
-         * only drop EVENT messages, EBD and FBD are still
-         * processed for bookkeeping purposes
-         */
-        if (msg.type == omx_message::EVENT) {
-            ALOGW("Dropping OMX EVENT message - we're in ERROR state.");
-            return;
-        }
-    }
-
-    switch (msg.type) {
-        case omx_message::EVENT:
-        {
-            onEvent(
-                 msg.u.event_data.event, msg.u.event_data.data1,
-                 msg.u.event_data.data2);
-
-            break;
-        }
-
-        case omx_message::EMPTY_BUFFER_DONE:
-        {
-            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
-
-            CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %u)", buffer);
-
-            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
-            size_t i = 0;
-            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
-                ++i;
-            }
-
-            CHECK(i < buffers->size());
-            if ((*buffers)[i].mStatus != OWNED_BY_COMPONENT) {
-                ALOGW("We already own input buffer %u, yet received "
-                     "an EMPTY_BUFFER_DONE.", buffer);
-            }
-
-            BufferInfo* info = &buffers->editItemAt(i);
-            info->mStatus = OWNED_BY_US;
-
-            // Buffer could not be released until empty buffer done is called.
-            if (info->mMediaBuffer != NULL) {
-                info->mMediaBuffer->release();
-                info->mMediaBuffer = NULL;
-            }
-
-            if (mPortStatus[kPortIndexInput] == DISABLING) {
-                CODEC_LOGV("Port is disabled, freeing buffer %u", buffer);
-
-                status_t err = freeBuffer(kPortIndexInput, i);
-                CHECK_EQ(err, (status_t)OK);
-            } else if (mState != ERROR
-                    && mPortStatus[kPortIndexInput] != SHUTTING_DOWN) {
-                CHECK_EQ((int)mPortStatus[kPortIndexInput], (int)ENABLED);
-
-                if (mFlags & kUseSecureInputBuffers) {
-                    drainAnyInputBuffer();
-                } else {
-                    drainInputBuffer(&buffers->editItemAt(i));
-                }
-            }
-            break;
-        }
-
-        case omx_message::FILL_BUFFER_DONE:
-        {
-            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
-            OMX_U32 flags = msg.u.extended_buffer_data.flags;
-
-            CODEC_LOGV("FILL_BUFFER_DONE(buffer: %u, size: %u, flags: 0x%08x, timestamp: %lld us (%.2f secs))",
-                 buffer,
-                 msg.u.extended_buffer_data.range_length,
-                 flags,
-                 msg.u.extended_buffer_data.timestamp,
-                 msg.u.extended_buffer_data.timestamp / 1E6);
-
-            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
-            size_t i = 0;
-            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
-                ++i;
-            }
-
-            CHECK(i < buffers->size());
-            BufferInfo *info = &buffers->editItemAt(i);
-
-            if (info->mStatus != OWNED_BY_COMPONENT) {
-                ALOGW("We already own output buffer %u, yet received "
-                     "a FILL_BUFFER_DONE.", buffer);
-            }
-
-            info->mStatus = OWNED_BY_US;
-
-            if (mPortStatus[kPortIndexOutput] == DISABLING) {
-                CODEC_LOGV("Port is disabled, freeing buffer %u", buffer);
-
-                status_t err = freeBuffer(kPortIndexOutput, i);
-                CHECK_EQ(err, (status_t)OK);
-
-#if 0
-            } else if (mPortStatus[kPortIndexOutput] == ENABLED
-                       && (flags & OMX_BUFFERFLAG_EOS)) {
-                CODEC_LOGV("No more output data.");
-                mNoMoreOutputData = true;
-                mBufferFilled.signal();
-#endif
-            } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) {
-                CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED);
-
-                MediaBuffer *buffer = info->mMediaBuffer;
-                bool isGraphicBuffer = buffer->graphicBuffer() != NULL;
-
-                if (!isGraphicBuffer
-                    && msg.u.extended_buffer_data.range_offset
-                        + msg.u.extended_buffer_data.range_length
-                            > buffer->size()) {
-                    CODEC_LOGE(
-                            "Codec lied about its buffer size requirements, "
-                            "sending a buffer larger than the originally "
-                            "advertised size in FILL_BUFFER_DONE!");
-                }
-                buffer->set_range(
-                        msg.u.extended_buffer_data.range_offset,
-                        msg.u.extended_buffer_data.range_length);
-
-                buffer->meta_data()->clear();
-
-                buffer->meta_data()->setInt64(
-                        kKeyTime, msg.u.extended_buffer_data.timestamp);
-
-                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) {
-                    buffer->meta_data()->setInt32(kKeyIsSyncFrame, true);
-                }
-                bool isCodecSpecific = false;
-                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) {
-                    buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
-                    isCodecSpecific = true;
-                }
-
-                if (isGraphicBuffer || mQuirks & kOutputBuffersAreUnreadable) {
-                    buffer->meta_data()->setInt32(kKeyIsUnreadable, true);
-                }
-
-                buffer->meta_data()->setInt32(
-                        kKeyBufferID,
-                        msg.u.extended_buffer_data.buffer);
-
-                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) {
-                    CODEC_LOGV("No more output data.");
-                    mNoMoreOutputData = true;
-                }
-
-                if (mIsEncoder && mIsVideo) {
-                    int64_t decodingTimeUs = isCodecSpecific? 0: getDecodingTimeUs();
-                    buffer->meta_data()->setInt64(kKeyDecodingTime, decodingTimeUs);
-                }
-
-                if (mTargetTimeUs >= 0) {
-                    CHECK(msg.u.extended_buffer_data.timestamp <= mTargetTimeUs);
-
-                    if (msg.u.extended_buffer_data.timestamp < mTargetTimeUs) {
-                        CODEC_LOGV(
-                                "skipping output buffer at timestamp %lld us",
-                                msg.u.extended_buffer_data.timestamp);
-
-                        fillOutputBuffer(info);
-                        break;
-                    }
-
-                    CODEC_LOGV(
-                            "returning output buffer at target timestamp "
-                            "%lld us",
-                            msg.u.extended_buffer_data.timestamp);
-
-                    mTargetTimeUs = -1;
-                }
-
-                mFilledBuffers.push_back(i);
-                mBufferFilled.signal();
-                if (mIsEncoder) {
-                    sched_yield();
-                }
-            }
-
-            break;
-        }
-
-        default:
-        {
-            CHECK(!"should not be here.");
-            break;
-        }
-    }
-}
-
-// Has the format changed in any way that the client would have to be aware of?
-static bool formatHasNotablyChanged(
-        const sp<MetaData> &from, const sp<MetaData> &to) {
-    if (from.get() == NULL && to.get() == NULL) {
-        return false;
-    }
-
-    if ((from.get() == NULL && to.get() != NULL)
-        || (from.get() != NULL && to.get() == NULL)) {
-        return true;
-    }
-
-    const char *mime_from, *mime_to;
-    CHECK(from->findCString(kKeyMIMEType, &mime_from));
-    CHECK(to->findCString(kKeyMIMEType, &mime_to));
-
-    if (strcasecmp(mime_from, mime_to)) {
-        return true;
-    }
-
-    if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) {
-        int32_t colorFormat_from, colorFormat_to;
-        CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from));
-        CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to));
-
-        if (colorFormat_from != colorFormat_to) {
-            return true;
-        }
-
-        int32_t width_from, width_to;
-        CHECK(from->findInt32(kKeyWidth, &width_from));
-        CHECK(to->findInt32(kKeyWidth, &width_to));
-
-        if (width_from != width_to) {
-            return true;
-        }
-
-        int32_t height_from, height_to;
-        CHECK(from->findInt32(kKeyHeight, &height_from));
-        CHECK(to->findInt32(kKeyHeight, &height_to));
-
-        if (height_from != height_to) {
-            return true;
-        }
-
-        int32_t left_from, top_from, right_from, bottom_from;
-        CHECK(from->findRect(
-                    kKeyCropRect,
-                    &left_from, &top_from, &right_from, &bottom_from));
-
-        int32_t left_to, top_to, right_to, bottom_to;
-        CHECK(to->findRect(
-                    kKeyCropRect,
-                    &left_to, &top_to, &right_to, &bottom_to));
-
-        if (left_to != left_from || top_to != top_from
-                || right_to != right_from || bottom_to != bottom_from) {
-            return true;
-        }
-    } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) {
-        int32_t numChannels_from, numChannels_to;
-        CHECK(from->findInt32(kKeyChannelCount, &numChannels_from));
-        CHECK(to->findInt32(kKeyChannelCount, &numChannels_to));
-
-        if (numChannels_from != numChannels_to) {
-            return true;
-        }
-
-        int32_t sampleRate_from, sampleRate_to;
-        CHECK(from->findInt32(kKeySampleRate, &sampleRate_from));
-        CHECK(to->findInt32(kKeySampleRate, &sampleRate_to));
-
-        if (sampleRate_from != sampleRate_to) {
-            return true;
-        }
-    }
-
-    return false;
-}
-
-void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
-    switch (event) {
-        case OMX_EventCmdComplete:
-        {
-            onCmdComplete((OMX_COMMANDTYPE)data1, data2);
-            break;
-        }
-
-        case OMX_EventError:
-        {
-            CODEC_LOGE("OMX_EventError(0x%08x, %u)", data1, data2);
-
-            setState(ERROR);
-            break;
-        }
-
-        case OMX_EventPortSettingsChanged:
-        {
-            CODEC_LOGV("OMX_EventPortSettingsChanged(port=%u, data2=0x%08x)",
-                       data1, data2);
-
-            if (data2 == 0 || data2 == OMX_IndexParamPortDefinition) {
-                onPortSettingsChanged(data1);
-            } else if (data1 == kPortIndexOutput &&
-                        (data2 == OMX_IndexConfigCommonOutputCrop ||
-                         data2 == OMX_IndexConfigCommonScale)) {
-
-                sp<MetaData> oldOutputFormat = mOutputFormat;
-                initOutputFormat(mSource->getFormat());
-
-                if (data2 == OMX_IndexConfigCommonOutputCrop &&
-                    formatHasNotablyChanged(oldOutputFormat, mOutputFormat)) {
-                    mOutputPortSettingsHaveChanged = true;
-
-                } else if (data2 == OMX_IndexConfigCommonScale) {
-                    OMX_CONFIG_SCALEFACTORTYPE scale;
-                    InitOMXParams(&scale);
-                    scale.nPortIndex = kPortIndexOutput;
-
-                    // Change display dimension only when necessary.
-                    if (OK == mOMX->getConfig(
-                                        mNode,
-                                        OMX_IndexConfigCommonScale,
-                                        &scale, sizeof(scale))) {
-                        int32_t left, top, right, bottom;
-                        CHECK(mOutputFormat->findRect(kKeyCropRect,
-                                                      &left, &top,
-                                                      &right, &bottom));
-
-                        // The scale is in 16.16 format.
-                        // scale 1.0 = 0x010000. When there is no
-                        // need to change the display, skip it.
-                        ALOGV("Get OMX_IndexConfigScale: 0x%x/0x%x",
-                                scale.xWidth, scale.xHeight);
-
-                        if (scale.xWidth != 0x010000) {
-                            mOutputFormat->setInt32(kKeyDisplayWidth,
-                                    ((right - left +  1) * scale.xWidth)  >> 16);
-                            mOutputPortSettingsHaveChanged = true;
-                        }
-
-                        if (scale.xHeight != 0x010000) {
-                            mOutputFormat->setInt32(kKeyDisplayHeight,
-                                    ((bottom  - top + 1) * scale.xHeight) >> 16);
-                            mOutputPortSettingsHaveChanged = true;
-                        }
-                    }
-                }
-            }
-            break;
-        }
-
-#if 0
-        case OMX_EventBufferFlag:
-        {
-            CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1);
-
-            if (data1 == kPortIndexOutput) {
-                mNoMoreOutputData = true;
-            }
-            break;
-        }
-#endif
-
-        default:
-        {
-            CODEC_LOGV("EVENT(%d, %u, %u)", event, data1, data2);
-            break;
-        }
-    }
-}
-
-void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) {
-    switch (cmd) {
-        case OMX_CommandStateSet:
-        {
-            onStateChange((OMX_STATETYPE)data);
-            break;
-        }
-
-        case OMX_CommandPortDisable:
-        {
-            OMX_U32 portIndex = data;
-            CODEC_LOGV("PORT_DISABLED(%u)", portIndex);
-
-            CHECK(mState == EXECUTING || mState == RECONFIGURING);
-            CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLING);
-            CHECK_EQ(mPortBuffers[portIndex].size(), 0u);
-
-            mPortStatus[portIndex] = DISABLED;
-
-            if (mState == RECONFIGURING) {
-                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
-
-                sp<MetaData> oldOutputFormat = mOutputFormat;
-                initOutputFormat(mSource->getFormat());
-
-                // Don't notify clients if the output port settings change
-                // wasn't of importance to them, i.e. it may be that just the
-                // number of buffers has changed and nothing else.
-                bool formatChanged = formatHasNotablyChanged(oldOutputFormat, mOutputFormat);
-                if (!mOutputPortSettingsHaveChanged) {
-                    mOutputPortSettingsHaveChanged = formatChanged;
-                }
-
-                status_t err = enablePortAsync(portIndex);
-                if (err != OK) {
-                    CODEC_LOGE("enablePortAsync(%u) failed (err = %d)", portIndex, err);
-                    setState(ERROR);
-                } else {
-                    err = allocateBuffersOnPort(portIndex);
-                    if (err != OK) {
-                        CODEC_LOGE("allocateBuffersOnPort (%s) failed "
-                                   "(err = %d)",
-                                   portIndex == kPortIndexInput
-                                        ? "input" : "output",
-                                   err);
-
-                        setState(ERROR);
-                    }
-                }
-            }
-            break;
-        }
-
-        case OMX_CommandPortEnable:
-        {
-            OMX_U32 portIndex = data;
-            CODEC_LOGV("PORT_ENABLED(%u)", portIndex);
-
-            CHECK(mState == EXECUTING || mState == RECONFIGURING);
-            CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLING);
-
-            mPortStatus[portIndex] = ENABLED;
-
-            if (mState == RECONFIGURING) {
-                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
-
-                setState(EXECUTING);
-
-                fillOutputBuffers();
-            }
-            break;
-        }
-
-        case OMX_CommandFlush:
-        {
-            OMX_U32 portIndex = data;
-
-            CODEC_LOGV("FLUSH_DONE(%u)", portIndex);
-
-            CHECK_EQ((int)mPortStatus[portIndex], (int)SHUTTING_DOWN);
-            mPortStatus[portIndex] = ENABLED;
-
-            CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]),
-                     mPortBuffers[portIndex].size());
-
-            if (mSkipCutBuffer != NULL && mPortStatus[kPortIndexOutput] == ENABLED) {
-                mSkipCutBuffer->clear();
-            }
-
-            if (mState == RECONFIGURING) {
-                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
-
-                disablePortAsync(portIndex);
-            } else if (mState == EXECUTING_TO_IDLE) {
-                if (mPortStatus[kPortIndexInput] == ENABLED
-                    && mPortStatus[kPortIndexOutput] == ENABLED) {
-                    CODEC_LOGV("Finished flushing both ports, now completing "
-                         "transition from EXECUTING to IDLE.");
-
-                    mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
-                    mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
-
-                    status_t err =
-                        mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
-                    CHECK_EQ(err, (status_t)OK);
-                }
-            } else {
-                // We're flushing both ports in preparation for seeking.
-
-                if (mPortStatus[kPortIndexInput] == ENABLED
-                    && mPortStatus[kPortIndexOutput] == ENABLED) {
-                    CODEC_LOGV("Finished flushing both ports, now continuing from"
-                         " seek-time.");
-
-                    // We implicitly resume pulling on our upstream source.
-                    mPaused = false;
-
-                    drainInputBuffers();
-                    fillOutputBuffers();
-                }
-
-                if (mOutputPortSettingsChangedPending) {
-                    CODEC_LOGV(
-                            "Honoring deferred output port settings change.");
-
-                    mOutputPortSettingsChangedPending = false;
-                    onPortSettingsChanged(kPortIndexOutput);
-                }
-            }
-
-            break;
-        }
-
-        default:
-        {
-            CODEC_LOGV("CMD_COMPLETE(%d, %u)", cmd, data);
-            break;
-        }
-    }
-}
-
-void OMXCodec::onStateChange(OMX_STATETYPE newState) {
-    CODEC_LOGV("onStateChange %d", newState);
-
-    switch (newState) {
-        case OMX_StateIdle:
-        {
-            CODEC_LOGV("Now Idle.");
-            if (mState == LOADED_TO_IDLE) {
-                status_t err = mOMX->sendCommand(
-                        mNode, OMX_CommandStateSet, OMX_StateExecuting);
-
-                CHECK_EQ(err, (status_t)OK);
-
-                setState(IDLE_TO_EXECUTING);
-            } else {
-                CHECK_EQ((int)mState, (int)EXECUTING_TO_IDLE);
-
-                if (countBuffersWeOwn(mPortBuffers[kPortIndexInput]) !=
-                    mPortBuffers[kPortIndexInput].size()) {
-                    ALOGE("Codec did not return all input buffers "
-                          "(received %zu / %zu)",
-                            countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
-                            mPortBuffers[kPortIndexInput].size());
-                    TRESPASS();
-                }
-
-                if (countBuffersWeOwn(mPortBuffers[kPortIndexOutput]) !=
-                    mPortBuffers[kPortIndexOutput].size()) {
-                    ALOGE("Codec did not return all output buffers "
-                          "(received %zu / %zu)",
-                            countBuffersWeOwn(mPortBuffers[kPortIndexOutput]),
-                            mPortBuffers[kPortIndexOutput].size());
-                    TRESPASS();
-                }
-
-                status_t err = mOMX->sendCommand(
-                        mNode, OMX_CommandStateSet, OMX_StateLoaded);
-
-                CHECK_EQ(err, (status_t)OK);
-
-                err = freeBuffersOnPort(kPortIndexInput);
-                CHECK_EQ(err, (status_t)OK);
-
-                err = freeBuffersOnPort(kPortIndexOutput);
-                CHECK_EQ(err, (status_t)OK);
-
-                mPortStatus[kPortIndexInput] = ENABLED;
-                mPortStatus[kPortIndexOutput] = ENABLED;
-
-                if ((mFlags & kEnableGrallocUsageProtected) &&
-                        mNativeWindow != NULL) {
-                    // We push enough 1x1 blank buffers to ensure that one of
-                    // them has made it to the display.  This allows the OMX
-                    // component teardown to zero out any protected buffers
-                    // without the risk of scanning out one of those buffers.
-                    pushBlankBuffersToNativeWindow(mNativeWindow.get());
-                }
-
-                setState(IDLE_TO_LOADED);
-            }
-            break;
-        }
-
-        case OMX_StateExecuting:
-        {
-            CHECK_EQ((int)mState, (int)IDLE_TO_EXECUTING);
-
-            CODEC_LOGV("Now Executing.");
-
-            mOutputPortSettingsChangedPending = false;
-
-            setState(EXECUTING);
-
-            // Buffers will be submitted to the component in the first
-            // call to OMXCodec::read as mInitialBufferSubmit is true at
-            // this point. This ensures that this on_message call returns,
-            // releases the lock and ::init can notice the state change and
-            // itself return.
-            break;
-        }
-
-        case OMX_StateLoaded:
-        {
-            CHECK_EQ((int)mState, (int)IDLE_TO_LOADED);
-
-            CODEC_LOGV("Now Loaded.");
-
-            setState(LOADED);
-            break;
-        }
-
-        case OMX_StateInvalid:
-        {
-            setState(ERROR);
-            break;
-        }
-
-        default:
-        {
-            CHECK(!"should not be here.");
-            break;
-        }
-    }
-}
-
-// static
-size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) {
-    size_t n = 0;
-    for (size_t i = 0; i < buffers.size(); ++i) {
-        if (buffers[i].mStatus != OWNED_BY_COMPONENT) {
-            ++n;
-        }
-    }
-
-    return n;
-}
-
-status_t OMXCodec::freeBuffersOnPort(
-        OMX_U32 portIndex, bool onlyThoseWeOwn) {
-    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
-
-    status_t stickyErr = OK;
-
-    for (size_t i = buffers->size(); i > 0;) {
-        i--;
-        BufferInfo *info = &buffers->editItemAt(i);
-
-        if (onlyThoseWeOwn && info->mStatus == OWNED_BY_COMPONENT) {
-            continue;
-        }
-
-        CHECK(info->mStatus == OWNED_BY_US
-                || info->mStatus == OWNED_BY_NATIVE_WINDOW);
-
-        CODEC_LOGV("freeing buffer %u on port %u", info->mBuffer, portIndex);
-
-        status_t err = freeBuffer(portIndex, i);
-
-        if (err != OK) {
-            stickyErr = err;
-        }
-
-    }
-
-    CHECK(onlyThoseWeOwn || buffers->isEmpty());
-
-    return stickyErr;
-}
-
-status_t OMXCodec::freeBuffer(OMX_U32 portIndex, size_t bufIndex) {
-    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
-
-    BufferInfo *info = &buffers->editItemAt(bufIndex);
-
-    status_t err = mOMX->freeBuffer(mNode, portIndex, info->mBuffer);
-
-    if (err == OK && info->mMediaBuffer != NULL) {
-        CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
-        info->mMediaBuffer->setObserver(NULL);
-
-        // Make sure nobody but us owns this buffer at this point.
-        CHECK_EQ(info->mMediaBuffer->refcount(), 0);
-
-        // Cancel the buffer if it belongs to an ANativeWindow.
-        sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
-        if (info->mStatus == OWNED_BY_US && graphicBuffer != 0) {
-            err = cancelBufferToNativeWindow(info);
-        }
-
-        info->mMediaBuffer->release();
-        info->mMediaBuffer = NULL;
-    }
-
-    if (err == OK) {
-        buffers->removeAt(bufIndex);
-    }
-
-    return err;
-}
-
-void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) {
-    CODEC_LOGV("PORT_SETTINGS_CHANGED(%u)", portIndex);
-
-    CHECK(mState == EXECUTING || mState == EXECUTING_TO_IDLE);
-    CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
-    CHECK(!mOutputPortSettingsChangedPending);
-
-    if (mPortStatus[kPortIndexOutput] != ENABLED) {
-        CODEC_LOGV("Deferring output port settings change.");
-        mOutputPortSettingsChangedPending = true;
-        return;
-    }
-
-    setState(RECONFIGURING);
-
-    if (mQuirks & kNeedsFlushBeforeDisable) {
-        if (!flushPortAsync(portIndex)) {
-            onCmdComplete(OMX_CommandFlush, portIndex);
-        }
-    } else {
-        disablePortAsync(portIndex);
-    }
-}
-
-bool OMXCodec::flushPortAsync(OMX_U32 portIndex) {
-    CHECK(mState == EXECUTING || mState == RECONFIGURING
-            || mState == EXECUTING_TO_IDLE);
-
-    CODEC_LOGV("flushPortAsync(%u): we own %zu out of %zu buffers already.",
-         portIndex, countBuffersWeOwn(mPortBuffers[portIndex]),
-         mPortBuffers[portIndex].size());
-
-    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
-    mPortStatus[portIndex] = SHUTTING_DOWN;
-
-    if ((mQuirks & kRequiresFlushCompleteEmulation)
-        && countBuffersWeOwn(mPortBuffers[portIndex])
-                == mPortBuffers[portIndex].size()) {
-        // No flush is necessary and this component fails to send a
-        // flush-complete event in this case.
-
-        return false;
-    }
-
-    status_t err =
-        mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex);
-    CHECK_EQ(err, (status_t)OK);
-
-    return true;
-}
-
-void OMXCodec::disablePortAsync(OMX_U32 portIndex) {
-    CHECK(mState == EXECUTING || mState == RECONFIGURING);
-
-    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
-    mPortStatus[portIndex] = DISABLING;
-
-    CODEC_LOGV("sending OMX_CommandPortDisable(%u)", portIndex);
-    status_t err =
-        mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex);
-    CHECK_EQ(err, (status_t)OK);
-
-    freeBuffersOnPort(portIndex, true);
-}
-
-status_t OMXCodec::enablePortAsync(OMX_U32 portIndex) {
-    CHECK(mState == EXECUTING || mState == RECONFIGURING);
-
-    CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLED);
-    mPortStatus[portIndex] = ENABLING;
-
-    CODEC_LOGV("sending OMX_CommandPortEnable(%u)", portIndex);
-    return mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex);
-}
-
-void OMXCodec::fillOutputBuffers() {
-    CHECK_EQ((int)mState, (int)EXECUTING);
-
-    // This is a workaround for some decoders not properly reporting
-    // end-of-output-stream. If we own all input buffers and also own
-    // all output buffers and we already signalled end-of-input-stream,
-    // the end-of-output-stream is implied.
-    if (mSignalledEOS
-            && countBuffersWeOwn(mPortBuffers[kPortIndexInput])
-                == mPortBuffers[kPortIndexInput].size()
-            && countBuffersWeOwn(mPortBuffers[kPortIndexOutput])
-                == mPortBuffers[kPortIndexOutput].size()) {
-        mNoMoreOutputData = true;
-        mBufferFilled.signal();
-
-        return;
-    }
-
-    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
-    for (size_t i = 0; i < buffers->size(); ++i) {
-        BufferInfo *info = &buffers->editItemAt(i);
-        if (info->mStatus == OWNED_BY_US) {
-            fillOutputBuffer(&buffers->editItemAt(i));
-        }
-    }
-}
-
-void OMXCodec::drainInputBuffers() {
-    CHECK(mState == EXECUTING || mState == RECONFIGURING);
-
-    if (mFlags & kUseSecureInputBuffers) {
-        Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
-        for (size_t i = 0; i < buffers->size(); ++i) {
-            if (!drainAnyInputBuffer()
-                    || (mFlags & kOnlySubmitOneInputBufferAtOneTime)) {
-                break;
-            }
-        }
-    } else {
-        Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
-        for (size_t i = 0; i < buffers->size(); ++i) {
-            BufferInfo *info = &buffers->editItemAt(i);
-
-            if (info->mStatus != OWNED_BY_US) {
-                continue;
-            }
-
-            if (!drainInputBuffer(info)) {
-                break;
-            }
-
-            if (mFlags & kOnlySubmitOneInputBufferAtOneTime) {
-                break;
-            }
-        }
-    }
-}
-
-bool OMXCodec::drainAnyInputBuffer() {
-    return drainInputBuffer((BufferInfo *)NULL);
-}
-
-OMXCodec::BufferInfo *OMXCodec::findInputBufferByDataPointer(void *ptr) {
-    Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput];
-    for (size_t i = 0; i < infos->size(); ++i) {
-        BufferInfo *info = &infos->editItemAt(i);
-
-        if (info->mData == ptr) {
-            CODEC_LOGV(
-                    "input buffer data ptr = %p, buffer_id = %u",
-                    ptr,
-                    info->mBuffer);
-
-            return info;
-        }
-    }
-
-    TRESPASS();
-}
-
-OMXCodec::BufferInfo *OMXCodec::findEmptyInputBuffer() {
-    Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput];
-    for (size_t i = 0; i < infos->size(); ++i) {
-        BufferInfo *info = &infos->editItemAt(i);
-
-        if (info->mStatus == OWNED_BY_US) {
-            return info;
-        }
-    }
-
-    TRESPASS();
-}
-
-bool OMXCodec::drainInputBuffer(BufferInfo *info) {
-    if (info != NULL) {
-        CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
-    }
-
-    if (mSignalledEOS) {
-        return false;
-    }
-
-    if (mCodecSpecificDataIndex < mCodecSpecificData.size()) {
-        CHECK(!(mFlags & kUseSecureInputBuffers));
-
-        const CodecSpecificData *specific =
-            mCodecSpecificData[mCodecSpecificDataIndex];
-
-        size_t size = specific->mSize;
-
-        if ((!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME) ||
-             !strcasecmp(MEDIA_MIMETYPE_VIDEO_HEVC, mMIME))
-                && !(mQuirks & kWantsNALFragments)) {
-            static const uint8_t kNALStartCode[4] =
-                    { 0x00, 0x00, 0x00, 0x01 };
-
-            CHECK(info->mSize >= specific->mSize + 4);
-
-            size += 4;
-
-            memcpy(info->mData, kNALStartCode, 4);
-            memcpy((uint8_t *)info->mData + 4,
-                   specific->mData, specific->mSize);
-        } else {
-            CHECK(info->mSize >= specific->mSize);
-            memcpy(info->mData, specific->mData, specific->mSize);
-        }
-
-        mNoMoreOutputData = false;
-
-        CODEC_LOGV("calling emptyBuffer with codec specific data");
-
-        status_t err = mOMX->emptyBuffer(
-                mNode, info->mBuffer, 0, size,
-                OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
-                0);
-        CHECK_EQ(err, (status_t)OK);
-
-        info->mStatus = OWNED_BY_COMPONENT;
-
-        ++mCodecSpecificDataIndex;
-        return true;
-    }
-
-    if (mPaused) {
-        return false;
-    }
-
-    status_t err;
-
-    bool signalEOS = false;
-    int64_t timestampUs = 0;
-
-    size_t offset = 0;
-    int32_t n = 0;
-
-
-    for (;;) {
-        MediaBuffer *srcBuffer;
-        if (mSeekTimeUs >= 0) {
-            if (mLeftOverBuffer) {
-                mLeftOverBuffer->release();
-                mLeftOverBuffer = NULL;
-            }
-
-            MediaSource::ReadOptions options;
-            options.setSeekTo(mSeekTimeUs, mSeekMode);
-
-            mSeekTimeUs = -1;
-            mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
-            mBufferFilled.signal();
-
-            err = mSource->read(&srcBuffer, &options);
-
-            if (err == OK) {
-                int64_t targetTimeUs;
-                if (srcBuffer->meta_data()->findInt64(
-                            kKeyTargetTime, &targetTimeUs)
-                        && targetTimeUs >= 0) {
-                    CODEC_LOGV("targetTimeUs = %lld us", (long long)targetTimeUs);
-                    mTargetTimeUs = targetTimeUs;
-                } else {
-                    mTargetTimeUs = -1;
-                }
-            }
-        } else if (mLeftOverBuffer) {
-            srcBuffer = mLeftOverBuffer;
-            mLeftOverBuffer = NULL;
-
-            err = OK;
-        } else {
-            err = mSource->read(&srcBuffer);
-        }
-
-        if (err != OK) {
-            signalEOS = true;
-            mFinalStatus = err;
-            mSignalledEOS = true;
-            mBufferFilled.signal();
-            break;
-        }
-
-        if (mFlags & kUseSecureInputBuffers) {
-            info = findInputBufferByDataPointer(srcBuffer->data());
-            CHECK(info != NULL);
-        }
-
-        size_t remainingBytes = info->mSize - offset;
-
-        if (srcBuffer->range_length() > remainingBytes) {
-            if (offset == 0) {
-                CODEC_LOGE(
-                     "Codec's input buffers are too small to accomodate "
-                     "buffer read from source (info->mSize = %zu, srcLength = %zu)",
-                     info->mSize, srcBuffer->range_length());
-
-                srcBuffer->release();
-                srcBuffer = NULL;
-
-                setState(ERROR);
-                return false;
-            }
-
-            mLeftOverBuffer = srcBuffer;
-            break;
-        }
-
-        bool releaseBuffer = true;
-        if (mFlags & kStoreMetaDataInVideoBuffers) {
-                releaseBuffer = false;
-                info->mMediaBuffer = srcBuffer;
-        }
-
-        if (mFlags & kUseSecureInputBuffers) {
-                // Data in "info" is already provided at this time.
-
-                releaseBuffer = false;
-
-                CHECK(info->mMediaBuffer == NULL);
-                info->mMediaBuffer = srcBuffer;
-        } else {
-            CHECK(srcBuffer->data() != NULL) ;
-            memcpy((uint8_t *)info->mData + offset,
-                    (const uint8_t *)srcBuffer->data()
-                        + srcBuffer->range_offset(),
-                    srcBuffer->range_length());
-        }
-
-        int64_t lastBufferTimeUs;
-        CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs));
-        CHECK(lastBufferTimeUs >= 0);
-        if (mIsEncoder && mIsVideo) {
-            mDecodingTimeList.push_back(lastBufferTimeUs);
-        }
-
-        if (offset == 0) {
-            timestampUs = lastBufferTimeUs;
-        }
-
-        offset += srcBuffer->range_length();
-
-        if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_VORBIS, mMIME)) {
-            CHECK(!(mQuirks & kSupportsMultipleFramesPerInputBuffer));
-            CHECK_GE(info->mSize, offset + sizeof(int32_t));
-
-            int32_t numPageSamples;
-            if (!srcBuffer->meta_data()->findInt32(
-                        kKeyValidSamples, &numPageSamples)) {
-                numPageSamples = -1;
-            }
-
-            memcpy((uint8_t *)info->mData + offset,
-                   &numPageSamples,
-                   sizeof(numPageSamples));
-
-            offset += sizeof(numPageSamples);
-        }
-
-        if (releaseBuffer) {
-            srcBuffer->release();
-            srcBuffer = NULL;
-        }
-
-        ++n;
-
-        if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) {
-            break;
-        }
-
-        int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs;
-
-        if (coalescedDurationUs > 250000ll) {
-            // Don't coalesce more than 250ms worth of encoded data at once.
-            break;
-        }
-    }
-
-    if (n > 1) {
-        ALOGV("coalesced %d frames into one input buffer", n);
-    }
-
-    OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
-
-    if (signalEOS) {
-        flags |= OMX_BUFFERFLAG_EOS;
-    } else {
-        mNoMoreOutputData = false;
-    }
-
-    if (info == NULL) {
-        CHECK(mFlags & kUseSecureInputBuffers);
-        CHECK(signalEOS);
-
-        // This is fishy, there's still a MediaBuffer corresponding to this
-        // info available to the source at this point even though we're going
-        // to use it to signal EOS to the codec.
-        info = findEmptyInputBuffer();
-    }
-
-    CODEC_LOGV("Calling emptyBuffer on buffer %u (length %zu), "
-               "timestamp %lld us (%.2f secs)",
-               info->mBuffer, offset,
-               (long long)timestampUs, timestampUs / 1E6);
-
-    err = mOMX->emptyBuffer(
-            mNode, info->mBuffer, 0, offset,
-            flags, timestampUs);
-
-    if (err != OK) {
-        setState(ERROR);
-        return false;
-    }
-
-    info->mStatus = OWNED_BY_COMPONENT;
-
-    return true;
-}
-
-void OMXCodec::fillOutputBuffer(BufferInfo *info) {
-    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
-
-    if (mNoMoreOutputData) {
-        CODEC_LOGV("There is no more output data available, not "
-             "calling fillOutputBuffer");
-        return;
-    }
-
-    CODEC_LOGV("Calling fillBuffer on buffer %u", info->mBuffer);
-    status_t err = mOMX->fillBuffer(mNode, info->mBuffer);
-
-    if (err != OK) {
-        CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err);
-
-        setState(ERROR);
-        return;
-    }
-
-    info->mStatus = OWNED_BY_COMPONENT;
-}
-
-bool OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) {
-    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
-    for (size_t i = 0; i < buffers->size(); ++i) {
-        if ((*buffers)[i].mBuffer == buffer) {
-            return drainInputBuffer(&buffers->editItemAt(i));
-        }
-    }
-
-    CHECK(!"should not be here.");
-
-    return false;
-}
-
-void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) {
-    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
-    for (size_t i = 0; i < buffers->size(); ++i) {
-        if ((*buffers)[i].mBuffer == buffer) {
-            fillOutputBuffer(&buffers->editItemAt(i));
-            return;
-        }
-    }
-
-    CHECK(!"should not be here.");
-}
-
-void OMXCodec::setState(State newState) {
-    mState = newState;
-    mAsyncCompletion.signal();
-
-    // This may cause some spurious wakeups but is necessary to
-    // unblock the reader if we enter ERROR state.
-    mBufferFilled.signal();
-}
-
-status_t OMXCodec::waitForBufferFilled_l() {
-
-    if (mIsEncoder) {
-        // For timelapse video recording, the timelapse video recording may
-        // not send an input frame for a _long_ time. Do not use timeout
-        // for video encoding.
-        return mBufferFilled.wait(mLock);
-    }
-    status_t err = mBufferFilled.waitRelative(mLock, kBufferFilledEventTimeOutNs);
-    if (err != OK) {
-        CODEC_LOGE("Timed out waiting for output buffers: %zu/%zu",
-            countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
-            countBuffersWeOwn(mPortBuffers[kPortIndexOutput]));
-    }
-    return err;
-}
-
-void OMXCodec::setRawAudioFormat(
-        OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) {
-
-    // port definition
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = portIndex;
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
-    CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
-            &def, sizeof(def)), (status_t)OK);
-
-    // pcm param
-    OMX_AUDIO_PARAM_PCMMODETYPE pcmParams;
-    InitOMXParams(&pcmParams);
-    pcmParams.nPortIndex = portIndex;
-
-    err = mOMX->getParameter(
-            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
-
-    CHECK_EQ(err, (status_t)OK);
-
-    pcmParams.nChannels = numChannels;
-    pcmParams.eNumData = OMX_NumericalDataSigned;
-    pcmParams.bInterleaved = OMX_TRUE;
-    pcmParams.nBitPerSample = 16;
-    pcmParams.nSamplingRate = sampleRate;
-    pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear;
-
-    CHECK_EQ(getOMXChannelMapping(
-                numChannels, pcmParams.eChannelMapping), (status_t)OK);
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
-
-    CHECK_EQ(err, (status_t)OK);
-}
-
-static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate(bool isAMRWB, int32_t bps) {
-    if (isAMRWB) {
-        if (bps <= 6600) {
-            return OMX_AUDIO_AMRBandModeWB0;
-        } else if (bps <= 8850) {
-            return OMX_AUDIO_AMRBandModeWB1;
-        } else if (bps <= 12650) {
-            return OMX_AUDIO_AMRBandModeWB2;
-        } else if (bps <= 14250) {
-            return OMX_AUDIO_AMRBandModeWB3;
-        } else if (bps <= 15850) {
-            return OMX_AUDIO_AMRBandModeWB4;
-        } else if (bps <= 18250) {
-            return OMX_AUDIO_AMRBandModeWB5;
-        } else if (bps <= 19850) {
-            return OMX_AUDIO_AMRBandModeWB6;
-        } else if (bps <= 23050) {
-            return OMX_AUDIO_AMRBandModeWB7;
-        }
-
-        // 23850 bps
-        return OMX_AUDIO_AMRBandModeWB8;
-    } else {  // AMRNB
-        if (bps <= 4750) {
-            return OMX_AUDIO_AMRBandModeNB0;
-        } else if (bps <= 5150) {
-            return OMX_AUDIO_AMRBandModeNB1;
-        } else if (bps <= 5900) {
-            return OMX_AUDIO_AMRBandModeNB2;
-        } else if (bps <= 6700) {
-            return OMX_AUDIO_AMRBandModeNB3;
-        } else if (bps <= 7400) {
-            return OMX_AUDIO_AMRBandModeNB4;
-        } else if (bps <= 7950) {
-            return OMX_AUDIO_AMRBandModeNB5;
-        } else if (bps <= 10200) {
-            return OMX_AUDIO_AMRBandModeNB6;
-        }
-
-        // 12200 bps
-        return OMX_AUDIO_AMRBandModeNB7;
-    }
-}
-
-void OMXCodec::setAMRFormat(bool isWAMR, int32_t bitRate) {
-    OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput;
-
-    OMX_AUDIO_PARAM_AMRTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = portIndex;
-
-    status_t err =
-        mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
-
-    CHECK_EQ(err, (status_t)OK);
-
-    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
-
-    def.eAMRBandMode = pickModeFromBitRate(isWAMR, bitRate);
-    err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    ////////////////////////
-
-    if (mIsEncoder) {
-        sp<MetaData> format = mSource->getFormat();
-        int32_t sampleRate;
-        int32_t numChannels;
-        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
-        CHECK(format->findInt32(kKeyChannelCount, &numChannels));
-
-        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
-    }
-}
-
-status_t OMXCodec::setAACFormat(
-        int32_t numChannels, int32_t sampleRate, int32_t bitRate, int32_t aacProfile, bool isADTS) {
-    if (numChannels > 2) {
-        ALOGW("Number of channels: (%d) \n", numChannels);
-    }
-
-    if (mIsEncoder) {
-        if (isADTS) {
-            return -EINVAL;
-        }
-
-        //////////////// input port ////////////////////
-        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
-
-        //////////////// output port ////////////////////
-        // format
-        OMX_AUDIO_PARAM_PORTFORMATTYPE format;
-        InitOMXParams(&format);
-        format.nPortIndex = kPortIndexOutput;
-        format.nIndex = 0;
-        status_t err = OMX_ErrorNone;
-        while (OMX_ErrorNone == err) {
-            CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat,
-                    &format, sizeof(format)), (status_t)OK);
-            if (format.eEncoding == OMX_AUDIO_CodingAAC) {
-                break;
-            }
-            format.nIndex++;
-        }
-        CHECK_EQ((status_t)OK, err);
-        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat,
-                &format, sizeof(format)), (status_t)OK);
-
-        // port definition
-        OMX_PARAM_PORTDEFINITIONTYPE def;
-        InitOMXParams(&def);
-        def.nPortIndex = kPortIndexOutput;
-        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition,
-                &def, sizeof(def)), (status_t)OK);
-        def.format.audio.bFlagErrorConcealment = OMX_TRUE;
-        def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
-        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
-                &def, sizeof(def)), (status_t)OK);
-
-        // profile
-        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
-        InitOMXParams(&profile);
-        profile.nPortIndex = kPortIndexOutput;
-        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac,
-                &profile, sizeof(profile)), (status_t)OK);
-        profile.nChannels = numChannels;
-        profile.eChannelMode = (numChannels == 1?
-                OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo);
-        profile.nSampleRate = sampleRate;
-        profile.nBitRate = bitRate;
-        profile.nAudioBandWidth = 0;
-        profile.nFrameLength = 0;
-        profile.nAACtools = OMX_AUDIO_AACToolAll;
-        profile.nAACERtools = OMX_AUDIO_AACERNone;
-        profile.eAACProfile = (OMX_AUDIO_AACPROFILETYPE) aacProfile;
-        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
-        err = mOMX->setParameter(mNode, OMX_IndexParamAudioAac,
-                &profile, sizeof(profile));
-
-        if (err != OK) {
-            CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed "
-                       "(err = %d)",
-                       err);
-            return err;
-        }
-    } else {
-        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
-        InitOMXParams(&profile);
-        profile.nPortIndex = kPortIndexInput;
-
-        status_t err = mOMX->getParameter(
-                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
-        CHECK_EQ(err, (status_t)OK);
-
-        profile.nChannels = numChannels;
-        profile.nSampleRate = sampleRate;
-
-        profile.eAACStreamFormat =
-            isADTS
-                ? OMX_AUDIO_AACStreamFormatMP4ADTS
-                : OMX_AUDIO_AACStreamFormatMP4FF;
-
-        err = mOMX->setParameter(
-                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
-
-        if (err != OK) {
-            CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed "
-                       "(err = %d)",
-                       err);
-            return err;
-        }
-    }
-
-    return OK;
-}
-
-status_t OMXCodec::setAC3Format(int32_t numChannels, int32_t sampleRate) {
-    OMX_AUDIO_PARAM_ANDROID_AC3TYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = kPortIndexInput;
-
-    status_t err = mOMX->getParameter(
-            mNode,
-            (OMX_INDEXTYPE)OMX_IndexParamAudioAndroidAc3,
-            &def,
-            sizeof(def));
-
-    if (err != OK) {
-        return err;
-    }
-
-    def.nChannels = numChannels;
-    def.nSampleRate = sampleRate;
-
-    return mOMX->setParameter(
-            mNode,
-            (OMX_INDEXTYPE)OMX_IndexParamAudioAndroidAc3,
-            &def,
-            sizeof(def));
-}
-
-void OMXCodec::setG711Format(int32_t sampleRate, int32_t numChannels) {
-    CHECK(!mIsEncoder);
-    setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
-}
-
-void OMXCodec::setImageOutputFormat(
-        OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) {
-    CODEC_LOGV("setImageOutputFormat(%u, %u)", width, height);
-
-#if 0
-    OMX_INDEXTYPE index;
-    status_t err = mOMX->get_extension_index(
-            mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index);
-    CHECK_EQ(err, (status_t)OK);
-
-    err = mOMX->set_config(mNode, index, &format, sizeof(format));
-    CHECK_EQ(err, (status_t)OK);
-#endif
-
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = kPortIndexOutput;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
-
-    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
-
-    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingUnused);
-    imageDef->eColorFormat = format;
-    imageDef->nFrameWidth = width;
-    imageDef->nFrameHeight = height;
-
-    switch (format) {
-        case OMX_COLOR_FormatYUV420PackedPlanar:
-        case OMX_COLOR_FormatYUV411Planar:
-        {
-            def.nBufferSize = (width * height * 3) / 2;
-            break;
-        }
-
-        case OMX_COLOR_FormatCbYCrY:
-        {
-            def.nBufferSize = width * height * 2;
-            break;
-        }
-
-        case OMX_COLOR_Format32bitARGB8888:
-        {
-            def.nBufferSize = width * height * 4;
-            break;
-        }
-
-        case OMX_COLOR_Format16bitARGB4444:
-        case OMX_COLOR_Format16bitARGB1555:
-        case OMX_COLOR_Format16bitRGB565:
-        case OMX_COLOR_Format16bitBGR565:
-        {
-            def.nBufferSize = width * height * 2;
-            break;
-        }
-
-        default:
-            CHECK(!"Should not be here. Unknown color format.");
-            break;
-    }
-
-    def.nBufferCountActual = def.nBufferCountMin;
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-}
-
-void OMXCodec::setJPEGInputFormat(
-        OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) {
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = kPortIndexInput;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
-    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
-
-    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingJPEG);
-    imageDef->nFrameWidth = width;
-    imageDef->nFrameHeight = height;
-
-    def.nBufferSize = compressedSize;
-    def.nBufferCountActual = def.nBufferCountMin;
-
-    err = mOMX->setParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-}
-
-void OMXCodec::addCodecSpecificData(const void *data, size_t size) {
-    CodecSpecificData *specific =
-        (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1);
-
-    specific->mSize = size;
-    memcpy(specific->mData, data, size);
-
-    mCodecSpecificData.push(specific);
-}
-
-void OMXCodec::clearCodecSpecificData() {
-    for (size_t i = 0; i < mCodecSpecificData.size(); ++i) {
-        free(mCodecSpecificData.editItemAt(i));
-    }
-    mCodecSpecificData.clear();
-    mCodecSpecificDataIndex = 0;
-}
-
-status_t OMXCodec::start(MetaData *meta) {
-    Mutex::Autolock autoLock(mLock);
-
-    if (mState != LOADED) {
-        CODEC_LOGE("called start in the unexpected state: %d", mState);
-        return UNKNOWN_ERROR;
-    }
-
-    sp<MetaData> params = new MetaData;
-    if (mQuirks & kWantsNALFragments) {
-        params->setInt32(kKeyWantsNALFragments, true);
-    }
-    if (meta) {
-        int64_t startTimeUs = 0;
-        int64_t timeUs;
-        if (meta->findInt64(kKeyTime, &timeUs)) {
-            startTimeUs = timeUs;
-        }
-        params->setInt64(kKeyTime, startTimeUs);
-    }
-
-    mCodecSpecificDataIndex = 0;
-    mInitialBufferSubmit = true;
-    mSignalledEOS = false;
-    mNoMoreOutputData = false;
-    mOutputPortSettingsHaveChanged = false;
-    mSeekTimeUs = -1;
-    mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
-    mTargetTimeUs = -1;
-    mFilledBuffers.clear();
-    mPaused = false;
-
-    status_t err;
-    if (mIsEncoder) {
-        // Calling init() before starting its source so that we can configure,
-        // if supported, the source to use exactly the same number of input
-        // buffers as requested by the encoder.
-        if ((err = init()) != OK) {
-            CODEC_LOGE("init failed: %d", err);
-            return err;
-        }
-
-        params->setInt32(kKeyNumBuffers, mPortBuffers[kPortIndexInput].size());
-        err = mSource->start(params.get());
-        if (err != OK) {
-            CODEC_LOGE("source failed to start: %d", err);
-            stopOmxComponent_l();
-        }
-        return err;
-    }
-
-    // Decoder case
-    if ((err = mSource->start(params.get())) != OK) {
-        CODEC_LOGE("source failed to start: %d", err);
-        return err;
-    }
-    return init();
-}
-
-status_t OMXCodec::stop() {
-    CODEC_LOGV("stop mState=%d", mState);
-    Mutex::Autolock autoLock(mLock);
-    status_t err = stopOmxComponent_l();
-    mSource->stop();
-
-    CODEC_LOGV("stopped in state %d", mState);
-    return err;
-}
-
-status_t OMXCodec::stopOmxComponent_l() {
-    CODEC_LOGV("stopOmxComponent_l mState=%d", mState);
-
-    while (isIntermediateState(mState)) {
-        mAsyncCompletion.wait(mLock);
-    }
-
-    bool isError = false;
-    switch (mState) {
-        case LOADED:
-            break;
-
-        case ERROR:
-        {
-            if (mPortStatus[kPortIndexOutput] == ENABLING) {
-                // Codec is in a wedged state (technical term)
-                // We've seen an output port settings change from the codec,
-                // We've disabled the output port, then freed the output
-                // buffers, initiated re-enabling the output port but
-                // failed to reallocate the output buffers.
-                // There doesn't seem to be a way to orderly transition
-                // from executing->idle and idle->loaded now that the
-                // output port hasn't been reenabled yet...
-                // Simply free as many resources as we can and pretend
-                // that we're in LOADED state so that the destructor
-                // will free the component instance without asserting.
-                freeBuffersOnPort(kPortIndexInput, true /* onlyThoseWeOwn */);
-                freeBuffersOnPort(kPortIndexOutput, true /* onlyThoseWeOwn */);
-                setState(LOADED);
-                break;
-            } else {
-                OMX_STATETYPE state = OMX_StateInvalid;
-                status_t err = mOMX->getState(mNode, &state);
-                CHECK_EQ(err, (status_t)OK);
-
-                if (state != OMX_StateExecuting) {
-                    break;
-                }
-                // else fall through to the idling code
-            }
-
-            isError = true;
-        }
-
-        case EXECUTING:
-        {
-            setState(EXECUTING_TO_IDLE);
-
-            if (mQuirks & kRequiresFlushBeforeShutdown) {
-                CODEC_LOGV("This component requires a flush before transitioning "
-                     "from EXECUTING to IDLE...");
-
-                bool emulateInputFlushCompletion =
-                    !flushPortAsync(kPortIndexInput);
-
-                bool emulateOutputFlushCompletion =
-                    !flushPortAsync(kPortIndexOutput);
-
-                if (emulateInputFlushCompletion) {
-                    onCmdComplete(OMX_CommandFlush, kPortIndexInput);
-                }
-
-                if (emulateOutputFlushCompletion) {
-                    onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
-                }
-            } else {
-                mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
-                mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
-
-                status_t err =
-                    mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
-                CHECK_EQ(err, (status_t)OK);
-            }
-
-            while (mState != LOADED && mState != ERROR) {
-                mAsyncCompletion.wait(mLock);
-            }
-
-            if (isError) {
-                // We were in the ERROR state coming in, so restore that now
-                // that we've idled the OMX component.
-                setState(ERROR);
-            }
-
-            break;
-        }
-
-        default:
-        {
-            CHECK(!"should not be here.");
-            break;
-        }
-    }
-
-    if (mLeftOverBuffer) {
-        mLeftOverBuffer->release();
-        mLeftOverBuffer = NULL;
-    }
-
-    return OK;
-}
-
-sp<MetaData> OMXCodec::getFormat() {
-    Mutex::Autolock autoLock(mLock);
-
-    return mOutputFormat;
-}
-
-status_t OMXCodec::read(
-        MediaBuffer **buffer, const ReadOptions *options) {
-    status_t err = OK;
-    *buffer = NULL;
-
-    Mutex::Autolock autoLock(mLock);
-
-    if (mState != EXECUTING && mState != RECONFIGURING) {
-        return UNKNOWN_ERROR;
-    }
-
-    bool seeking = false;
-    int64_t seekTimeUs;
-    ReadOptions::SeekMode seekMode;
-    if (options && options->getSeekTo(&seekTimeUs, &seekMode)) {
-        seeking = true;
-    }
-
-    if (mInitialBufferSubmit) {
-        mInitialBufferSubmit = false;
-
-        if (seeking) {
-            CHECK(seekTimeUs >= 0);
-            mSeekTimeUs = seekTimeUs;
-            mSeekMode = seekMode;
-
-            // There's no reason to trigger the code below, there's
-            // nothing to flush yet.
-            seeking = false;
-            mPaused = false;
-        }
-
-        drainInputBuffers();
-
-        if (mState == EXECUTING) {
-            // Otherwise mState == RECONFIGURING and this code will trigger
-            // after the output port is reenabled.
-            fillOutputBuffers();
-        }
-    }
-
-    if (seeking) {
-        while (mState == RECONFIGURING) {
-            if ((err = waitForBufferFilled_l()) != OK) {
-                return err;
-            }
-        }
-
-        if (mState != EXECUTING) {
-            return UNKNOWN_ERROR;
-        }
-
-        CODEC_LOGV("seeking to %" PRId64 " us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
-
-        mSignalledEOS = false;
-
-        CHECK(seekTimeUs >= 0);
-        mSeekTimeUs = seekTimeUs;
-        mSeekMode = seekMode;
-
-        mFilledBuffers.clear();
-
-        CHECK_EQ((int)mState, (int)EXECUTING);
-
-        bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput);
-        bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput);
-
-        if (emulateInputFlushCompletion) {
-            onCmdComplete(OMX_CommandFlush, kPortIndexInput);
-        }
-
-        if (emulateOutputFlushCompletion) {
-            onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
-        }
-
-        while (mSeekTimeUs >= 0) {
-            if ((err = waitForBufferFilled_l()) != OK) {
-                return err;
-            }
-        }
-    }
-
-    while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) {
-        if ((err = waitForBufferFilled_l()) != OK) {
-            return err;
-        }
-    }
-
-    if (mState == ERROR) {
-        return UNKNOWN_ERROR;
-    }
-
-    if (mFilledBuffers.empty()) {
-        return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM;
-    }
-
-    if (mOutputPortSettingsHaveChanged) {
-        mOutputPortSettingsHaveChanged = false;
-
-        return INFO_FORMAT_CHANGED;
-    }
-
-    size_t index = *mFilledBuffers.begin();
-    mFilledBuffers.erase(mFilledBuffers.begin());
-
-    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
-    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
-    info->mStatus = OWNED_BY_CLIENT;
-
-    info->mMediaBuffer->add_ref();
-    if (mSkipCutBuffer != NULL) {
-        mSkipCutBuffer->submit(info->mMediaBuffer);
-    }
-    *buffer = info->mMediaBuffer;
-
-    return OK;
-}
-
-void OMXCodec::signalBufferReturned(MediaBuffer *buffer) {
-    Mutex::Autolock autoLock(mLock);
-
-    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
-    for (size_t i = 0; i < buffers->size(); ++i) {
-        BufferInfo *info = &buffers->editItemAt(i);
-
-        if (info->mMediaBuffer == buffer) {
-            CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED);
-            CHECK_EQ((int)info->mStatus, (int)OWNED_BY_CLIENT);
-
-            info->mStatus = OWNED_BY_US;
-
-            if (buffer->graphicBuffer() == 0) {
-                fillOutputBuffer(info);
-            } else {
-                sp<MetaData> metaData = info->mMediaBuffer->meta_data();
-                int32_t rendered = 0;
-                if (!metaData->findInt32(kKeyRendered, &rendered)) {
-                    rendered = 0;
-                }
-                if (!rendered) {
-                    status_t err = cancelBufferToNativeWindow(info);
-                    if (err < 0) {
-                        return;
-                    }
-                }
-
-                info->mStatus = OWNED_BY_NATIVE_WINDOW;
-
-                // Dequeue the next buffer from the native window.
-                BufferInfo *nextBufInfo = dequeueBufferFromNativeWindow();
-                if (nextBufInfo == 0) {
-                    return;
-                }
-
-                // Give the buffer to the OMX node to fill.
-                fillOutputBuffer(nextBufInfo);
-            }
-            return;
-        }
-    }
-
-    CHECK(!"should not be here.");
-}
-
-void OMXCodec::dumpPortStatus(OMX_U32 portIndex) {
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = portIndex;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output");
-
-    CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput)
-          || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput));
-
-    printf("  nBufferCountActual = %" PRIu32 "\n", def.nBufferCountActual);
-    printf("  nBufferCountMin = %" PRIu32 "\n", def.nBufferCountMin);
-    printf("  nBufferSize = %" PRIu32 "\n", def.nBufferSize);
-
-    switch (def.eDomain) {
-        case OMX_PortDomainImage:
-        {
-            const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
-
-            printf("\n");
-            printf("  // Image\n");
-            printf("  nFrameWidth = %" PRIu32 "\n", imageDef->nFrameWidth);
-            printf("  nFrameHeight = %" PRIu32 "\n", imageDef->nFrameHeight);
-            printf("  nStride = %" PRIu32 "\n", imageDef->nStride);
-
-            printf("  eCompressionFormat = %s\n",
-                   asString(imageDef->eCompressionFormat));
-
-            printf("  eColorFormat = %s\n",
-                   asString(imageDef->eColorFormat));
-
-            break;
-        }
-
-        case OMX_PortDomainVideo:
-        {
-            OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video;
-
-            printf("\n");
-            printf("  // Video\n");
-            printf("  nFrameWidth = %" PRIu32 "\n", videoDef->nFrameWidth);
-            printf("  nFrameHeight = %" PRIu32 "\n", videoDef->nFrameHeight);
-            printf("  nStride = %" PRIu32 "\n", videoDef->nStride);
-
-            printf("  eCompressionFormat = %s\n",
-                   asString(videoDef->eCompressionFormat));
-
-            printf("  eColorFormat = %s\n",
-                   asString(videoDef->eColorFormat));
-
-            break;
-        }
-
-        case OMX_PortDomainAudio:
-        {
-            OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio;
-
-            printf("\n");
-            printf("  // Audio\n");
-            printf("  eEncoding = %s\n",
-                   asString(audioDef->eEncoding));
-
-            if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) {
-                OMX_AUDIO_PARAM_PCMMODETYPE params;
-                InitOMXParams(&params);
-                params.nPortIndex = portIndex;
-
-                err = mOMX->getParameter(
-                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
-                CHECK_EQ(err, (status_t)OK);
-
-                printf("  nSamplingRate = %" PRIu32 "\n", params.nSamplingRate);
-                printf("  nChannels = %" PRIu32 "\n", params.nChannels);
-                printf("  bInterleaved = %d\n", params.bInterleaved);
-                printf("  nBitPerSample = %" PRIu32 "\n", params.nBitPerSample);
-
-                printf("  eNumData = %s\n",
-                       params.eNumData == OMX_NumericalDataSigned
-                        ? "signed" : "unsigned");
-
-                printf("  ePCMMode = %s\n", asString(params.ePCMMode));
-            } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) {
-                OMX_AUDIO_PARAM_AMRTYPE amr;
-                InitOMXParams(&amr);
-                amr.nPortIndex = portIndex;
-
-                err = mOMX->getParameter(
-                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
-                CHECK_EQ(err, (status_t)OK);
-
-                printf("  nChannels = %" PRIu32 "\n", amr.nChannels);
-                printf("  eAMRBandMode = %s\n",
-                        asString(amr.eAMRBandMode));
-                printf("  eAMRFrameFormat = %s\n",
-                        asString(amr.eAMRFrameFormat));
-            }
-
-            break;
-        }
-
-        default:
-        {
-            printf("  // Unknown\n");
-            break;
-        }
-    }
-
-    printf("}\n");
-}
-
-status_t OMXCodec::initNativeWindow() {
-    // Enable use of a GraphicBuffer as the output for this node.  This must
-    // happen before getting the IndexParamPortDefinition parameter because it
-    // will affect the pixel format that the node reports.
-    status_t err = mOMX->enableGraphicBuffers(mNode, kPortIndexOutput, OMX_TRUE);
-    if (err != 0) {
-        return err;
-    }
-
-    return OK;
-}
-
-void OMXCodec::initNativeWindowCrop() {
-    int32_t left, top, right, bottom;
-
-    CHECK(mOutputFormat->findRect(
-                        kKeyCropRect,
-                        &left, &top, &right, &bottom));
-
-    android_native_rect_t crop;
-    crop.left = left;
-    crop.top = top;
-    crop.right = right + 1;
-    crop.bottom = bottom + 1;
-
-    // We'll ignore any errors here, if the surface is
-    // already invalid, we'll know soon enough.
-    native_window_set_crop(mNativeWindow.get(), &crop);
-}
-
-void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) {
-    mOutputFormat = new MetaData;
-    mOutputFormat->setCString(kKeyDecoderComponent, mComponentName);
-    if (mIsEncoder) {
-        int32_t timeScale;
-        if (inputFormat->findInt32(kKeyTimeScale, &timeScale)) {
-            mOutputFormat->setInt32(kKeyTimeScale, timeScale);
-        }
-    }
-
-    OMX_PARAM_PORTDEFINITIONTYPE def;
-    InitOMXParams(&def);
-    def.nPortIndex = kPortIndexOutput;
-
-    status_t err = mOMX->getParameter(
-            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
-    CHECK_EQ(err, (status_t)OK);
-
-    switch (def.eDomain) {
-        case OMX_PortDomainImage:
-        {
-            OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
-            CHECK_EQ((int)imageDef->eCompressionFormat,
-                     (int)OMX_IMAGE_CodingUnused);
-
-            mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
-            mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat);
-            mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth);
-            mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight);
-            break;
-        }
-
-        case OMX_PortDomainAudio:
-        {
-            OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
-
-            if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) {
-                OMX_AUDIO_PARAM_PCMMODETYPE params;
-                InitOMXParams(&params);
-                params.nPortIndex = kPortIndexOutput;
-
-                err = mOMX->getParameter(
-                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
-                CHECK_EQ(err, (status_t)OK);
-
-                CHECK_EQ((int)params.eNumData, (int)OMX_NumericalDataSigned);
-                CHECK_EQ(params.nBitPerSample, 16u);
-                CHECK_EQ((int)params.ePCMMode, (int)OMX_AUDIO_PCMModeLinear);
-
-                int32_t numChannels, sampleRate;
-                inputFormat->findInt32(kKeyChannelCount, &numChannels);
-                inputFormat->findInt32(kKeySampleRate, &sampleRate);
-
-                if ((OMX_U32)numChannels != params.nChannels) {
-                    ALOGV("Codec outputs a different number of channels than "
-                         "the input stream contains (contains %d channels, "
-                         "codec outputs %u channels).",
-                         numChannels, params.nChannels);
-                }
-
-                if (sampleRate != (int32_t)params.nSamplingRate) {
-                    ALOGV("Codec outputs at different sampling rate than "
-                         "what the input stream contains (contains data at "
-                         "%d Hz, codec outputs %u Hz)",
-                         sampleRate, params.nSamplingRate);
-                }
-
-                mOutputFormat->setCString(
-                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
-
-                // Use the codec-advertised number of channels, as some
-                // codecs appear to output stereo even if the input data is
-                // mono. If we know the codec lies about this information,
-                // use the actual number of channels instead.
-                mOutputFormat->setInt32(
-                        kKeyChannelCount,
-                        (mQuirks & kDecoderLiesAboutNumberOfChannels)
-                            ? numChannels : params.nChannels);
-
-                mOutputFormat->setInt32(kKeySampleRate, params.nSamplingRate);
-            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) {
-                OMX_AUDIO_PARAM_AMRTYPE amr;
-                InitOMXParams(&amr);
-                amr.nPortIndex = kPortIndexOutput;
-
-                err = mOMX->getParameter(
-                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
-                CHECK_EQ(err, (status_t)OK);
-
-                CHECK_EQ(amr.nChannels, 1u);
-                mOutputFormat->setInt32(kKeyChannelCount, 1);
-
-                if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0
-                    && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) {
-                    mOutputFormat->setCString(
-                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
-                    mOutputFormat->setInt32(kKeySampleRate, 8000);
-                } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0
-                            && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) {
-                    mOutputFormat->setCString(
-                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
-                    mOutputFormat->setInt32(kKeySampleRate, 16000);
-                } else {
-                    CHECK(!"Unknown AMR band mode.");
-                }
-            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) {
-                mOutputFormat->setCString(
-                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
-                int32_t numChannels, sampleRate, bitRate;
-                inputFormat->findInt32(kKeyChannelCount, &numChannels);
-                inputFormat->findInt32(kKeySampleRate, &sampleRate);
-                inputFormat->findInt32(kKeyBitRate, &bitRate);
-                mOutputFormat->setInt32(kKeyChannelCount, numChannels);
-                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
-                mOutputFormat->setInt32(kKeyBitRate, bitRate);
-            } else if (audio_def->eEncoding ==
-                    (OMX_AUDIO_CODINGTYPE)OMX_AUDIO_CodingAndroidAC3) {
-                mOutputFormat->setCString(
-                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AC3);
-                int32_t numChannels, sampleRate, bitRate;
-                inputFormat->findInt32(kKeyChannelCount, &numChannels);
-                inputFormat->findInt32(kKeySampleRate, &sampleRate);
-                inputFormat->findInt32(kKeyBitRate, &bitRate);
-                mOutputFormat->setInt32(kKeyChannelCount, numChannels);
-                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
-                mOutputFormat->setInt32(kKeyBitRate, bitRate);
-            } else {
-                CHECK(!"Should not be here. Unknown audio encoding.");
-            }
-            break;
-        }
-
-        case OMX_PortDomainVideo:
-        {
-            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
-
-            if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) {
-                mOutputFormat->setCString(
-                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
-            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) {
-                mOutputFormat->setCString(
-                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
-            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) {
-                mOutputFormat->setCString(
-                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
-            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) {
-                mOutputFormat->setCString(
-                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
-            } else {
-                CHECK(!"Unknown compression format.");
-            }
-
-            mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth);
-            mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight);
-            mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat);
-
-            if (!mIsEncoder) {
-                OMX_CONFIG_RECTTYPE rect;
-                InitOMXParams(&rect);
-                rect.nPortIndex = kPortIndexOutput;
-                status_t err =
-                        mOMX->getConfig(
-                            mNode, OMX_IndexConfigCommonOutputCrop,
-                            &rect, sizeof(rect));
-
-                CODEC_LOGI("video dimensions are %u x %u",
-                        video_def->nFrameWidth, video_def->nFrameHeight);
-
-                if (err == OK) {
-                    CHECK_GE(rect.nLeft, 0);
-                    CHECK_GE(rect.nTop, 0);
-                    CHECK_GE(rect.nWidth, 0u);
-                    CHECK_GE(rect.nHeight, 0u);
-                    CHECK_LE(rect.nLeft + rect.nWidth - 1, video_def->nFrameWidth);
-                    CHECK_LE(rect.nTop + rect.nHeight - 1, video_def->nFrameHeight);
-
-                    mOutputFormat->setRect(
-                            kKeyCropRect,
-                            rect.nLeft,
-                            rect.nTop,
-                            rect.nLeft + rect.nWidth - 1,
-                            rect.nTop + rect.nHeight - 1);
-
-                    CODEC_LOGI("Crop rect is %u x %u @ (%d, %d)",
-                            rect.nWidth, rect.nHeight, rect.nLeft, rect.nTop);
-                } else {
-                    mOutputFormat->setRect(
-                            kKeyCropRect,
-                            0, 0,
-                            video_def->nFrameWidth - 1,
-                            video_def->nFrameHeight - 1);
-                }
-
-                if (mNativeWindow != NULL) {
-                     initNativeWindowCrop();
-                }
-            }
-            break;
-        }
-
-        default:
-        {
-            CHECK(!"should not be here, neither audio nor video.");
-            break;
-        }
-    }
-
-    // If the input format contains rotation information, flag the output
-    // format accordingly.
-
-    int32_t rotationDegrees;
-    if (mSource->getFormat()->findInt32(kKeyRotation, &rotationDegrees)) {
-        mOutputFormat->setInt32(kKeyRotation, rotationDegrees);
-    }
-}
-
-status_t OMXCodec::pause() {
-    Mutex::Autolock autoLock(mLock);
-
-    mPaused = true;
-
-    return OK;
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-status_t QueryCodecs(
-        const sp<IOMX> &omx,
-        const char *mime, bool queryDecoders, bool hwCodecOnly,
-        Vector<CodecCapabilities> *results) {
-    Vector<OMXCodec::CodecNameAndQuirks> matchingCodecs;
-    results->clear();
-
-    OMXCodec::findMatchingCodecs(mime,
-            !queryDecoders /*createEncoder*/,
-            NULL /*matchComponentName*/,
-            hwCodecOnly ? OMXCodec::kHardwareCodecsOnly : 0 /*flags*/,
-            &matchingCodecs);
-
-    for (size_t c = 0; c < matchingCodecs.size(); c++) {
-        const char *componentName = matchingCodecs.itemAt(c).mName.string();
-
-        results->push();
-        CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
-
-        status_t err =
-            QueryCodec(omx, componentName, mime, !queryDecoders, caps);
-
-        if (err != OK) {
-            results->removeAt(results->size() - 1);
-        }
-    }
-
-    return OK;
-}
-
-status_t QueryCodec(
-        const sp<IOMX> &omx,
-        const char *componentName, const char *mime,
-        bool isEncoder,
-        CodecCapabilities *caps) {
-    bool isVideo = !strncasecmp(mime, "video/", 6);
-
-    sp<OMXCodecObserver> observer = new OMXCodecObserver;
-    IOMX::node_id node;
-    status_t err = omx->allocateNode(componentName, observer, &node);
-
-    if (err != OK) {
-        return err;
-    }
-
-    OMXCodec::setComponentRole(omx, node, isEncoder, mime);
-
-    caps->mFlags = 0;
-    caps->mComponentName = componentName;
-
-    // NOTE: OMX does not provide a way to query AAC profile support
-    if (isVideo) {
-        OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
-        InitOMXParams(&param);
-
-        param.nPortIndex = !isEncoder ? 0 : 1;
-
-        for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
-            err = omx->getParameter(
-                    node, OMX_IndexParamVideoProfileLevelQuerySupported,
-                    &param, sizeof(param));
-
-            if (err != OK) {
-                break;
-            }
-
-            CodecProfileLevel profileLevel;
-            profileLevel.mProfile = param.eProfile;
-            profileLevel.mLevel = param.eLevel;
-
-            caps->mProfileLevels.push(profileLevel);
-        }
-
-        // Color format query
-        // return colors in the order reported by the OMX component
-        // prefix "flexible" standard ones with the flexible equivalent
-        OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
-        InitOMXParams(&portFormat);
-        portFormat.nPortIndex = !isEncoder ? 1 : 0;
-        for (portFormat.nIndex = 0;; ++portFormat.nIndex)  {
-            err = omx->getParameter(
-                    node, OMX_IndexParamVideoPortFormat,
-                    &portFormat, sizeof(portFormat));
-            if (err != OK) {
-                break;
-            }
-
-            OMX_U32 flexibleEquivalent;
-            if (ACodec::isFlexibleColorFormat(
-                        omx, node, portFormat.eColorFormat, false /* usingNativeWindow */,
-                        &flexibleEquivalent)) {
-                bool marked = false;
-                for (size_t i = 0; i < caps->mColorFormats.size(); i++) {
-                    if (caps->mColorFormats.itemAt(i) == flexibleEquivalent) {
-                        marked = true;
-                        break;
-                    }
-                }
-                if (!marked) {
-                    caps->mColorFormats.push(flexibleEquivalent);
-                }
-            }
-            caps->mColorFormats.push(portFormat.eColorFormat);
-        }
-    }
-
-    if (isVideo && !isEncoder) {
-        if (omx->storeMetaDataInBuffers(
-                    node, 1 /* port index */, OMX_TRUE) == OK ||
-            omx->prepareForAdaptivePlayback(
-                    node, 1 /* port index */, OMX_TRUE,
-                    1280 /* width */, 720 /* height */) == OK) {
-            caps->mFlags |= CodecCapabilities::kFlagSupportsAdaptivePlayback;
-        }
-    }
-
-    CHECK_EQ(omx->freeNode(node), (status_t)OK);
-
-    return OK;
-}
-
-status_t QueryCodecs(
-        const sp<IOMX> &omx,
-        const char *mimeType, bool queryDecoders,
-        Vector<CodecCapabilities> *results) {
-    return QueryCodecs(omx, mimeType, queryDecoders, false /*hwCodecOnly*/, results);
-}
-
-// These are supposed be equivalent to the logic in
-// "audio_channel_out_mask_from_count".
-status_t getOMXChannelMapping(size_t numChannels, OMX_AUDIO_CHANNELTYPE map[]) {
-    switch (numChannels) {
-        case 1:
-            map[0] = OMX_AUDIO_ChannelCF;
-            break;
-        case 2:
-            map[0] = OMX_AUDIO_ChannelLF;
-            map[1] = OMX_AUDIO_ChannelRF;
-            break;
-        case 3:
-            map[0] = OMX_AUDIO_ChannelLF;
-            map[1] = OMX_AUDIO_ChannelRF;
-            map[2] = OMX_AUDIO_ChannelCF;
-            break;
-        case 4:
-            map[0] = OMX_AUDIO_ChannelLF;
-            map[1] = OMX_AUDIO_ChannelRF;
-            map[2] = OMX_AUDIO_ChannelLR;
-            map[3] = OMX_AUDIO_ChannelRR;
-            break;
-        case 5:
-            map[0] = OMX_AUDIO_ChannelLF;
-            map[1] = OMX_AUDIO_ChannelRF;
-            map[2] = OMX_AUDIO_ChannelCF;
-            map[3] = OMX_AUDIO_ChannelLR;
-            map[4] = OMX_AUDIO_ChannelRR;
-            break;
-        case 6:
-            map[0] = OMX_AUDIO_ChannelLF;
-            map[1] = OMX_AUDIO_ChannelRF;
-            map[2] = OMX_AUDIO_ChannelCF;
-            map[3] = OMX_AUDIO_ChannelLFE;
-            map[4] = OMX_AUDIO_ChannelLR;
-            map[5] = OMX_AUDIO_ChannelRR;
-            break;
-        case 7:
-            map[0] = OMX_AUDIO_ChannelLF;
-            map[1] = OMX_AUDIO_ChannelRF;
-            map[2] = OMX_AUDIO_ChannelCF;
-            map[3] = OMX_AUDIO_ChannelLFE;
-            map[4] = OMX_AUDIO_ChannelLR;
-            map[5] = OMX_AUDIO_ChannelRR;
-            map[6] = OMX_AUDIO_ChannelCS;
-            break;
-        case 8:
-            map[0] = OMX_AUDIO_ChannelLF;
-            map[1] = OMX_AUDIO_ChannelRF;
-            map[2] = OMX_AUDIO_ChannelCF;
-            map[3] = OMX_AUDIO_ChannelLFE;
-            map[4] = OMX_AUDIO_ChannelLR;
-            map[5] = OMX_AUDIO_ChannelRR;
-            map[6] = OMX_AUDIO_ChannelLS;
-            map[7] = OMX_AUDIO_ChannelRS;
-            break;
-        default:
-            return -EINVAL;
-    }
-
-    return OK;
-}
-
-}  // namespace android
diff --git a/media/libstagefright/OggExtractor.cpp b/media/libstagefright/OggExtractor.cpp
index 4f5190c..895a1d4 100644
--- a/media/libstagefright/OggExtractor.cpp
+++ b/media/libstagefright/OggExtractor.cpp
@@ -23,6 +23,7 @@
 #include <cutils/properties.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/MediaBuffer.h>
 #include <media/stagefright/MediaBufferGroup.h>
@@ -45,7 +46,7 @@
 namespace android {
 
 struct OggSource : public MediaSource {
-    OggSource(const sp<OggExtractor> &extractor);
+    explicit OggSource(const sp<OggExtractor> &extractor);
 
     virtual sp<MetaData> getFormat();
 
@@ -163,7 +164,7 @@
 };
 
 struct MyVorbisExtractor : public MyOggExtractor {
-    MyVorbisExtractor(const sp<DataSource> &source)
+    explicit MyVorbisExtractor(const sp<DataSource> &source)
         : MyOggExtractor(source,
                 MEDIA_MIMETYPE_AUDIO_VORBIS,
                 /* numHeaders */ 3,
@@ -191,7 +192,7 @@
     static const int32_t kOpusSampleRate = 48000;
     static const int64_t kOpusSeekPreRollUs = 80000; // 80 ms
 
-    MyOpusExtractor(const sp<DataSource> &source)
+    explicit MyOpusExtractor(const sp<DataSource> &source)
         : MyOggExtractor(source, MEDIA_MIMETYPE_AUDIO_OPUS, /*numHeaders*/ 2, kOpusSeekPreRollUs),
           mChannelCount(0),
           mCodecDelay(0),
@@ -964,7 +965,7 @@
     mMeta->setInt32(kKeyChannelCount, mChannelCount);
     mMeta->setInt64(kKeyOpusSeekPreRoll /* ns */, kOpusSeekPreRollUs * 1000 /* = 80 ms*/);
     mMeta->setInt64(kKeyOpusCodecDelay /* ns */,
-            mCodecDelay /* sample/s */ * 1000000000 / kOpusSampleRate);
+            mCodecDelay /* sample/s */ * 1000000000ll / kOpusSampleRate);
 
     return OK;
 }
@@ -1213,83 +1214,18 @@
 
 }
 
-// The returned buffer should be free()d.
-static uint8_t *DecodeBase64(const char *s, size_t size, size_t *outSize) {
-    *outSize = 0;
-
-    if ((size % 4) != 0) {
-        return NULL;
-    }
-
-    size_t n = size;
-    size_t padding = 0;
-    if (n >= 1 && s[n - 1] == '=') {
-        padding = 1;
-
-        if (n >= 2 && s[n - 2] == '=') {
-            padding = 2;
-        }
-    }
-
-    size_t outLen = 3 * size / 4 - padding;
-
-    *outSize = outLen;
-
-    void *buffer = malloc(outLen);
-
-    uint8_t *out = (uint8_t *)buffer;
-    size_t j = 0;
-    uint32_t accum = 0;
-    for (size_t i = 0; i < n; ++i) {
-        char c = s[i];
-        unsigned value;
-        if (c >= 'A' && c <= 'Z') {
-            value = c - 'A';
-        } else if (c >= 'a' && c <= 'z') {
-            value = 26 + c - 'a';
-        } else if (c >= '0' && c <= '9') {
-            value = 52 + c - '0';
-        } else if (c == '+') {
-            value = 62;
-        } else if (c == '/') {
-            value = 63;
-        } else if (c != '=') {
-            return NULL;
-        } else {
-            if (i < n - padding) {
-                return NULL;
-            }
-
-            value = 0;
-        }
-
-        accum = (accum << 6) | value;
-
-        if (((i + 1) % 4) == 0) {
-            out[j++] = (accum >> 16);
-
-            if (j < outLen) { out[j++] = (accum >> 8) & 0xff; }
-            if (j < outLen) { out[j++] = accum & 0xff; }
-
-            accum = 0;
-        }
-    }
-
-    return (uint8_t *)buffer;
-}
-
 static void extractAlbumArt(
         const sp<MetaData> &fileMeta, const void *data, size_t size) {
     ALOGV("extractAlbumArt from '%s'", (const char *)data);
 
-    size_t flacSize;
-    uint8_t *flac = DecodeBase64((const char *)data, size, &flacSize);
-
-    if (flac == NULL) {
+    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;
@@ -1299,24 +1235,24 @@
     char type[128];
 
     if (flacSize < 8) {
-        goto exit;
+        return;
     }
 
     picType = U32_AT(flac);
 
     if (picType != 3) {
         // This is not a front cover.
-        goto exit;
+        return;
     }
 
     typeLen = U32_AT(&flac[4]);
     if (typeLen > sizeof(type) - 1) {
-        goto exit;
+        return;
     }
 
     // we've already checked above that flacSize >= 8
     if (flacSize - 8 < typeLen) {
-        goto exit;
+        return;
     }
 
     memcpy(type, &flac[8], typeLen);
@@ -1326,7 +1262,7 @@
 
     if (!strcmp(type, "-->")) {
         // This is not inline cover art, but an external url instead.
-        goto exit;
+        return;
     }
 
     descLen = U32_AT(&flac[8 + typeLen]);
@@ -1334,7 +1270,7 @@
     if (flacSize < 32 ||
         flacSize - 32 < typeLen ||
         flacSize - 32 - typeLen < descLen) {
-        goto exit;
+        return;
     }
 
     dataLen = U32_AT(&flac[8 + typeLen + 4 + descLen + 16]);
@@ -1342,7 +1278,7 @@
 
     // we've already checked above that (flacSize - 32 - typeLen - descLen) >= 0
     if (flacSize - 32 - typeLen - descLen < dataLen) {
-        goto exit;
+        return;
     }
 
     ALOGV("got image data, %zu trailing bytes",
@@ -1352,10 +1288,6 @@
             kKeyAlbumArt, 0, &flac[8 + typeLen + 4 + descLen + 20], dataLen);
 
     fileMeta->setCString(kKeyAlbumArtMIME, type);
-
-exit:
-    free(flac);
-    flac = NULL;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
diff --git a/media/libstagefright/SampleTable.cpp b/media/libstagefright/SampleTable.cpp
index 02b20c4..2f69fd8 100644
--- a/media/libstagefright/SampleTable.cpp
+++ b/media/libstagefright/SampleTable.cpp
@@ -209,6 +209,11 @@
 status_t SampleTable::setSampleToChunkParams(
         off64_t data_offset, size_t data_size) {
     if (mSampleToChunkOffset >= 0) {
+        // already set
+        return ERROR_MALFORMED;
+    }
+
+    if (data_offset < 0) {
         return ERROR_MALFORMED;
     }
 
@@ -246,7 +251,7 @@
     for (uint32_t i = 0; i < mNumSampleToChunkOffsets; ++i) {
         uint8_t buffer[12];
 
-        if ((off64_t)((SIZE_MAX / 12) - 8 - i) < mSampleToChunkOffset) {
+        if ((SIZE_MAX - 8 - (i * 12)) < (size_t)mSampleToChunkOffset) {
             return ERROR_MALFORMED;
         }
 
diff --git a/media/libstagefright/SimpleDecodingSource.cpp b/media/libstagefright/SimpleDecodingSource.cpp
new file mode 100644
index 0000000..d544e35
--- /dev/null
+++ b/media/libstagefright/SimpleDecodingSource.cpp
@@ -0,0 +1,362 @@
+/*
+ * 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.
+ */
+
+#include <gui/Surface.h>
+
+#include <media/ICrypto.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/MediaBuffer.h>
+#include <media/stagefright/MediaCodecList.h>
+#include <media/stagefright/MediaCodec.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/SimpleDecodingSource.h>
+#include <media/stagefright/Utils.h>
+
+using namespace android;
+
+const int64_t kTimeoutWaitForOutputUs = 500000; // 0.5 seconds
+const int64_t kTimeoutWaitForInputUs = 5000; // 5 milliseconds
+
+//static
+sp<SimpleDecodingSource> SimpleDecodingSource::Create(
+        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;
+    sp<MetaData> meta = source->getFormat();
+    CHECK(meta->findCString(kKeyMIMEType, &mime));
+
+    sp<AMessage> format = new AMessage;
+    convertMetaDataToMessage(source->getFormat(), &format);
+
+    Vector<AString> matchingCodecs;
+    MediaCodecList::findMatchingCodecs(
+            mime, false /* encoder */, flags, &matchingCodecs);
+
+    sp<ALooper> looper = new ALooper;
+    looper->setName("stagefright");
+    looper->start();
+
+    sp<MediaCodec> codec;
+
+    for (size_t i = 0; i < matchingCodecs.size(); ++i) {
+        const AString &componentName = matchingCodecs[i];
+        if (desiredCodec != NULL && componentName.compare(desiredCodec)) {
+            continue;
+        }
+
+        ALOGV("Attempting to allocate codec '%s'", componentName.c_str());
+
+        codec = MediaCodec::CreateByComponentName(looper, componentName);
+        if (codec != NULL) {
+            ALOGI("Successfully allocated codec '%s'", componentName.c_str());
+
+            status_t err = codec->configure(format, surface, NULL /* crypto */, 0 /* flags */);
+            if (err == OK) {
+                err = codec->getOutputFormat(&format);
+            }
+            if (err == OK) {
+                return new SimpleDecodingSource(codec, source, looper, surface != NULL, format);
+            }
+
+            ALOGD("Failed to configure codec '%s'", componentName.c_str());
+            codec->release();
+            codec = NULL;
+        }
+    }
+
+    looper->stop();
+    ALOGE("No matching decoder! (mime: %s)", mime);
+    return NULL;
+}
+
+SimpleDecodingSource::SimpleDecodingSource(
+        const sp<MediaCodec> &codec, const sp<MediaSource> &source, const sp<ALooper> &looper,
+        bool usingSurface, const sp<AMessage> &format)
+    : mCodec(codec),
+      mSource(source),
+      mLooper(looper),
+      mUsingSurface(usingSurface),
+      mProtectedState(format) {
+    mCodec->getName(&mComponentName);
+}
+
+SimpleDecodingSource::~SimpleDecodingSource() {
+    mCodec->release();
+    mLooper->stop();
+}
+
+status_t SimpleDecodingSource::start(MetaData *params) {
+    (void)params;
+    Mutexed<ProtectedState>::Locked me(mProtectedState);
+    if (me->mState != INIT) {
+        return -EINVAL;
+    }
+    status_t res = mCodec->start();
+    if (res == OK) {
+        res = mSource->start();
+    }
+
+    if (res == OK) {
+        me->mState = STARTED;
+        me->mQueuedInputEOS = false;
+        me->mGotOutputEOS = false;
+    } else {
+        me->mState = ERROR;
+    }
+
+    return res;
+}
+
+status_t SimpleDecodingSource::stop() {
+    Mutexed<ProtectedState>::Locked me(mProtectedState);
+    if (me->mState != STARTED) {
+        return -EINVAL;
+    }
+
+    // wait for any pending reads to complete
+    me->mState = STOPPING;
+    while (me->mReading) {
+        me.waitForCondition(me->mReadCondition);
+    }
+
+    status_t res1 = mCodec->stop();
+    if (res1 != OK) {
+        mCodec->release();
+    }
+    status_t res2 = mSource->stop();
+    if (res1 == OK && res2 == OK) {
+        me->mState = STOPPED;
+    } else {
+        me->mState = ERROR;
+    }
+    return res1 != OK ? res1 : res2;
+}
+
+sp<MetaData> SimpleDecodingSource::getFormat() {
+    Mutexed<ProtectedState>::Locked me(mProtectedState);
+    if (me->mState == STARTED || me->mState == INIT) {
+        sp<MetaData> meta = new MetaData();
+        convertMessageToMetaData(me->mFormat, meta);
+        return meta;
+    }
+    return NULL;
+}
+
+SimpleDecodingSource::ProtectedState::ProtectedState(const sp<AMessage> &format)
+    : mReading(false),
+      mFormat(format),
+      mState(INIT),
+      mQueuedInputEOS(false),
+      mGotOutputEOS(false) {
+}
+
+status_t SimpleDecodingSource::read(
+        MediaBuffer **buffer, const ReadOptions *options) {
+    *buffer = NULL;
+
+    Mutexed<ProtectedState>::Locked me(mProtectedState);
+    if (me->mState != STARTED) {
+        return ERROR_END_OF_STREAM;
+    }
+    me->mReading = true;
+
+    status_t res = doRead(me, buffer, options);
+
+    me.lock();
+    me->mReading = false;
+    if (me->mState != STARTED) {
+        me->mReadCondition.signal();
+    }
+
+    return res;
+}
+
+status_t SimpleDecodingSource::doRead(
+        Mutexed<ProtectedState>::Locked &me, MediaBuffer **buffer, const ReadOptions *options) {
+    // |me| is always locked on entry, but is allowed to be unlocked on exit
+    CHECK_EQ(me->mState, STARTED);
+
+    size_t out_ix, in_ix, out_offset, out_size;
+    int64_t out_pts;
+    uint32_t out_flags;
+    status_t res;
+
+    // flush codec on seek
+    MediaSource::ReadOptions::SeekMode mode;
+    if (options != NULL && options->getSeekTo(&out_pts, &mode)) {
+        me->mQueuedInputEOS = false;
+        me->mGotOutputEOS = false;
+        mCodec->flush();
+    }
+
+    if (me->mGotOutputEOS) {
+        return ERROR_END_OF_STREAM;
+    }
+
+    for (int retries = 0; ++retries; ) {
+        // If we fill all available input buffers, we should expect that
+        // the codec produces at least one output buffer. Also, the codec
+        // should produce an output buffer in at most 1 seconds. Retry a
+        // few times nonetheless.
+        while (!me->mQueuedInputEOS) {
+            // allow some time to get input buffer after flush
+            res = mCodec->dequeueInputBuffer(&in_ix, kTimeoutWaitForInputUs);
+            if (res == -EAGAIN) {
+                // no available input buffers
+                break;
+            }
+
+            sp<ABuffer> in_buffer;
+            if (res == OK) {
+                res = mCodec->getInputBuffer(in_ix, &in_buffer);
+            }
+
+            if (res != OK || in_buffer == NULL) {
+                ALOGW("[%s] could not get input buffer #%zu",
+                        mComponentName.c_str(), in_ix);
+                me->mState = ERROR;
+                return UNKNOWN_ERROR;
+            }
+
+            MediaBuffer *in_buf;
+            while (true) {
+                in_buf = NULL;
+                me.unlock();
+                res = mSource->read(&in_buf, options);
+                me.lock();
+                if (res != OK || me->mState != STARTED) {
+                    if (in_buf != NULL) {
+                        in_buf->release();
+                        in_buf = NULL;
+                    }
+
+                    // queue EOS
+                    me->mQueuedInputEOS = true;
+                    if (mCodec->queueInputBuffer(
+                                 in_ix, 0 /* offset */, 0 /* size */,
+                                 0 /* pts */, MediaCodec::BUFFER_FLAG_EOS) != OK) {
+                        ALOGI("[%s] failed to queue input EOS", mComponentName.c_str());
+                        me->mState = ERROR;
+                        return UNKNOWN_ERROR;
+                    }
+
+                    // don't stop on EOS, but report error or EOS on stop
+                    if (res != ERROR_END_OF_STREAM) {
+                        me->mState = ERROR;
+                        return res;
+                    }
+                    if (me->mState != STARTED) {
+                        return ERROR_END_OF_STREAM;
+                    }
+                    break;
+                }
+                if (in_buf == NULL) { // should not happen
+                    continue;
+                } else if (in_buf->range_length() != 0) {
+                    break;
+                }
+                in_buf->release();
+            }
+
+            if (in_buf != NULL) {
+                int64_t timestampUs = 0;
+                CHECK(in_buf->meta_data()->findInt64(kKeyTime, &timestampUs));
+                if (in_buf->range_length() > in_buffer->capacity()) {
+                    ALOGW("'%s' received %zu input bytes for buffer of size %zu",
+                            mComponentName.c_str(),
+                            in_buf->range_length(), in_buffer->capacity());
+                }
+                memcpy(in_buffer->base(), (uint8_t *)in_buf->data() + in_buf->range_offset(),
+                       min(in_buf->range_length(), in_buffer->capacity()));
+
+                res = mCodec->queueInputBuffer(
+                        in_ix, 0 /* offset */, in_buf->range_length(),
+                        timestampUs, 0 /* flags */);
+                if (res != OK) {
+                    ALOGI("[%s] failed to queue input buffer #%zu", mComponentName.c_str(), in_ix);
+                    me->mState = ERROR;
+                }
+                in_buf->release();
+            }
+        }
+
+        me.unlock();
+        res = mCodec->dequeueOutputBuffer(
+                &out_ix, &out_offset, &out_size, &out_pts,
+                &out_flags, kTimeoutWaitForOutputUs /* timeoutUs */);
+        me.lock();
+        // abort read on stop
+        if (me->mState != STARTED) {
+            if (res == OK) {
+                mCodec->releaseOutputBuffer(out_ix);
+            }
+            return ERROR_END_OF_STREAM;
+        }
+
+        if (res == -EAGAIN) {
+            ALOGD("[%s] did not produce an output buffer. retry count: %d",
+                  mComponentName.c_str(), retries);
+            continue;
+        } else if (res == INFO_FORMAT_CHANGED) {
+            if (mCodec->getOutputFormat(&me->mFormat) != OK) {
+                me->mState = ERROR;
+                res = UNKNOWN_ERROR;
+            }
+            return res;
+        } else if (res == INFO_OUTPUT_BUFFERS_CHANGED) {
+            ALOGV("output buffers changed");
+            continue;
+        } else if (res != OK) {
+            me->mState = ERROR;
+            return res;
+        }
+
+        sp<ABuffer> out_buffer;
+        res = mCodec->getOutputBuffer(out_ix, &out_buffer);
+        if (res != OK) {
+            ALOGW("[%s] could not get output buffer #%zu",
+                    mComponentName.c_str(), out_ix);
+            me->mState = ERROR;
+            return UNKNOWN_ERROR;
+        }
+        if (out_flags & MediaCodec::BUFFER_FLAG_EOS) {
+            me->mGotOutputEOS = true;
+            // return EOS immediately if last buffer is empty
+            if (out_size == 0) {
+                mCodec->releaseOutputBuffer(out_ix);
+                return ERROR_END_OF_STREAM;
+            }
+        }
+
+        if (mUsingSurface && out_size > 0) {
+            *buffer = new MediaBuffer(0);
+            mCodec->renderOutputBufferAndRelease(out_ix);
+        } else {
+            *buffer = new MediaBuffer(out_size);
+            CHECK_LE(out_buffer->size(), (*buffer)->size());
+            memcpy((*buffer)->data(), out_buffer->data(), out_buffer->size());
+            (*buffer)->meta_data()->setInt64(kKeyTime, out_pts);
+            mCodec->releaseOutputBuffer(out_ix);
+        }
+        return OK;
+    }
+
+    return TIMED_OUT;
+}
diff --git a/media/libstagefright/StagefrightMetadataRetriever.cpp b/media/libstagefright/StagefrightMetadataRetriever.cpp
index 7c554db..08342cf 100644
--- a/media/libstagefright/StagefrightMetadataRetriever.cpp
+++ b/media/libstagefright/StagefrightMetadataRetriever.cpp
@@ -35,11 +35,12 @@
 #include <media/stagefright/FileSource.h>
 #include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MediaCodec.h>
+#include <media/stagefright/MediaCodecList.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/OMXCodec.h>
 #include <media/stagefright/Utils.h>
 
 #include <CharacterEncodingDetector.h>
@@ -55,13 +56,11 @@
     ALOGV("StagefrightMetadataRetriever()");
 
     DataSource::RegisterDefaultSniffers();
-    CHECK_EQ(mClient.connect(), (status_t)OK);
 }
 
 StagefrightMetadataRetriever::~StagefrightMetadataRetriever() {
     ALOGV("~StagefrightMetadataRetriever()");
     clearMetadata();
-    mClient.disconnect();
 }
 
 status_t StagefrightMetadataRetriever::setDataSource(
@@ -137,7 +136,7 @@
 }
 
 static VideoFrame *extractVideoFrame(
-        const char *componentName,
+        const AString &componentName,
         const sp<MetaData> &trackMeta,
         const sp<MediaSource> &source,
         int64_t frameTimeUs,
@@ -146,7 +145,10 @@
     sp<MetaData> format = source->getFormat();
 
     sp<AMessage> videoFormat;
-    convertMetaDataToMessage(trackMeta, &videoFormat);
+    if (convertMetaDataToMessage(trackMeta, &videoFormat) != OK) {
+        ALOGW("Failed to convert meta data to message");
+        return NULL;
+    }
 
     // TODO: Use Flexible color instead
     videoFormat->setInt32("color-format", OMX_COLOR_FormatYUV420Planar);
@@ -158,7 +160,7 @@
             looper, componentName, &err);
 
     if (decoder.get() == NULL || err != OK) {
-        ALOGW("Failed to instantiate decoder [%s]", componentName);
+        ALOGW("Failed to instantiate decoder [%s]", componentName.c_str());
         return NULL;
     }
 
@@ -473,23 +475,22 @@
     const char *mime;
     CHECK(trackMeta->findCString(kKeyMIMEType, &mime));
 
-    Vector<OMXCodec::CodecNameAndQuirks> matchingCodecs;
-    OMXCodec::findMatchingCodecs(
+    Vector<AString> matchingCodecs;
+    MediaCodecList::findMatchingCodecs(
             mime,
             false, /* encoder */
-            NULL, /* matchComponentName */
-            OMXCodec::kPreferSoftwareCodecs,
+            MediaCodecList::kPreferSoftwareCodecs,
             &matchingCodecs);
 
     for (size_t i = 0; i < matchingCodecs.size(); ++i) {
-        const char *componentName = matchingCodecs[i].mName.string();
+        const AString &componentName = matchingCodecs[i];
         VideoFrame *frame =
             extractVideoFrame(componentName, trackMeta, source, timeUs, option);
 
         if (frame != NULL) {
             return frame;
         }
-        ALOGV("%s failed to extract thumbnail, trying next decoder.", componentName);
+        ALOGV("%s failed to extract thumbnail, trying next decoder.", componentName.c_str());
     }
 
     return NULL;
diff --git a/media/libstagefright/TimeSource.cpp b/media/libstagefright/TimeSource.cpp
deleted file mode 100644
index 041980f..0000000
--- a/media/libstagefright/TimeSource.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stddef.h>
-#include <sys/time.h>
-
-#include <media/stagefright/foundation/ALooper.h>
-#include <media/stagefright/TimeSource.h>
-
-namespace android {
-
-SystemTimeSource::SystemTimeSource()
-    : mStartTimeUs(ALooper::GetNowUs()) {
-}
-
-int64_t SystemTimeSource::getRealTimeUs() {
-    return ALooper::GetNowUs() - mStartTimeUs;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/TimedEventQueue.cpp b/media/libstagefright/TimedEventQueue.cpp
deleted file mode 100644
index 7d15220..0000000
--- a/media/libstagefright/TimedEventQueue.cpp
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#undef __STRICT_ANSI__
-#define __STDINT_LIMITS
-#define __STDC_LIMIT_MACROS
-
-#include <inttypes.h>
-#include <stdint.h>
-#include <sys/prctl.h>
-#include <sys/time.h>
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "TimedEventQueue"
-#include <utils/Log.h>
-#include <utils/threads.h>
-
-#include "include/TimedEventQueue.h"
-
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/ALooper.h>
-#include <binder/IServiceManager.h>
-#include <powermanager/PowerManager.h>
-#include <binder/IPCThreadState.h>
-#include <utils/CallStack.h>
-
-namespace android {
-
-static int64_t kWakelockMinDelay = 100000ll;  // 100ms
-
-TimedEventQueue::TimedEventQueue()
-    : mNextEventID(1),
-      mRunning(false),
-      mStopped(false),
-      mDeathRecipient(new PMDeathRecipient(this)),
-      mWakeLockCount(0) {
-}
-
-TimedEventQueue::~TimedEventQueue() {
-    stop();
-    if (mPowerManager != 0) {
-        sp<IBinder> binder = IInterface::asBinder(mPowerManager);
-        binder->unlinkToDeath(mDeathRecipient);
-    }
-}
-
-void TimedEventQueue::start() {
-    if (mRunning) {
-        return;
-    }
-
-    mStopped = false;
-
-    pthread_attr_t attr;
-    pthread_attr_init(&attr);
-    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
-
-    pthread_create(&mThread, &attr, ThreadWrapper, this);
-
-    pthread_attr_destroy(&attr);
-
-    mRunning = true;
-}
-
-void TimedEventQueue::stop(bool flush) {
-    if (!mRunning) {
-        return;
-    }
-
-    if (flush) {
-        postEventToBack(new StopEvent);
-    } else {
-        postTimedEvent(new StopEvent, INT64_MIN);
-    }
-
-    void *dummy;
-    pthread_join(mThread, &dummy);
-
-    // some events may be left in the queue if we did not flush and the wake lock
-    // must be released.
-    releaseWakeLock_l(true /*force*/);
-    mQueue.clear();
-
-    mRunning = false;
-}
-
-TimedEventQueue::event_id TimedEventQueue::postEvent(const sp<Event> &event) {
-    // Reserve an earlier timeslot an INT64_MIN to be able to post
-    // the StopEvent to the absolute head of the queue.
-    return postTimedEvent(event, INT64_MIN + 1);
-}
-
-TimedEventQueue::event_id TimedEventQueue::postEventToBack(
-        const sp<Event> &event) {
-    return postTimedEvent(event, INT64_MAX);
-}
-
-TimedEventQueue::event_id TimedEventQueue::postEventWithDelay(
-        const sp<Event> &event, int64_t delay_us) {
-    CHECK(delay_us >= 0);
-    return postTimedEvent(event, ALooper::GetNowUs() + delay_us);
-}
-
-TimedEventQueue::event_id TimedEventQueue::postTimedEvent(
-        const sp<Event> &event, int64_t realtime_us) {
-    Mutex::Autolock autoLock(mLock);
-
-    event->setEventID(mNextEventID++);
-
-    List<QueueItem>::iterator it = mQueue.begin();
-    while (it != mQueue.end() && realtime_us >= (*it).realtime_us) {
-        ++it;
-    }
-
-    QueueItem item;
-    item.event = event;
-    item.realtime_us = realtime_us;
-    item.has_wakelock = false;
-
-    if (it == mQueue.begin()) {
-        mQueueHeadChangedCondition.signal();
-    }
-
-    if (realtime_us > ALooper::GetNowUs() + kWakelockMinDelay) {
-        acquireWakeLock_l();
-        item.has_wakelock = true;
-    }
-    mQueue.insert(it, item);
-
-    mQueueNotEmptyCondition.signal();
-
-    return event->eventID();
-}
-
-static bool MatchesEventID(
-        void *cookie, const sp<TimedEventQueue::Event> &event) {
-    TimedEventQueue::event_id *id =
-        static_cast<TimedEventQueue::event_id *>(cookie);
-
-    if (event->eventID() != *id) {
-        return false;
-    }
-
-    *id = 0;
-
-    return true;
-}
-
-bool TimedEventQueue::cancelEvent(event_id id) {
-    if (id == 0) {
-        return false;
-    }
-
-    cancelEvents(&MatchesEventID, &id, true /* stopAfterFirstMatch */);
-
-    // if MatchesEventID found a match, it will have set id to 0
-    // (which is not a valid event_id).
-
-    return id == 0;
-}
-
-void TimedEventQueue::cancelEvents(
-        bool (*predicate)(void *cookie, const sp<Event> &event),
-        void *cookie,
-        bool stopAfterFirstMatch) {
-    Mutex::Autolock autoLock(mLock);
-
-    List<QueueItem>::iterator it = mQueue.begin();
-    while (it != mQueue.end()) {
-        if (!(*predicate)(cookie, (*it).event)) {
-            ++it;
-            continue;
-        }
-
-        if (it == mQueue.begin()) {
-            mQueueHeadChangedCondition.signal();
-        }
-
-        ALOGV("cancelling event %d", (*it).event->eventID());
-
-        (*it).event->setEventID(0);
-        if ((*it).has_wakelock) {
-            releaseWakeLock_l();
-        }
-        it = mQueue.erase(it);
-        if (stopAfterFirstMatch) {
-            return;
-        }
-    }
-}
-
-// static
-void *TimedEventQueue::ThreadWrapper(void *me) {
-
-    androidSetThreadPriority(0, ANDROID_PRIORITY_FOREGROUND);
-
-    static_cast<TimedEventQueue *>(me)->threadEntry();
-
-    return NULL;
-}
-
-void TimedEventQueue::threadEntry() {
-    prctl(PR_SET_NAME, (unsigned long)"TimedEventQueue", 0, 0, 0);
-
-    for (;;) {
-        int64_t now_us = 0;
-        sp<Event> event;
-        bool wakeLocked = false;
-
-        {
-            Mutex::Autolock autoLock(mLock);
-
-            if (mStopped) {
-                break;
-            }
-
-            while (mQueue.empty()) {
-                mQueueNotEmptyCondition.wait(mLock);
-            }
-
-            event_id eventID = 0;
-            for (;;) {
-                if (mQueue.empty()) {
-                    // The only event in the queue could have been cancelled
-                    // while we were waiting for its scheduled time.
-                    break;
-                }
-
-                List<QueueItem>::iterator it = mQueue.begin();
-                eventID = (*it).event->eventID();
-
-                now_us = ALooper::GetNowUs();
-                int64_t when_us = (*it).realtime_us;
-
-                int64_t delay_us;
-                if (when_us < 0 || when_us == INT64_MAX) {
-                    delay_us = 0;
-                } else {
-                    delay_us = when_us - now_us;
-                }
-
-                if (delay_us <= 0) {
-                    break;
-                }
-
-                static int64_t kMaxTimeoutUs = 10000000ll;  // 10 secs
-                bool timeoutCapped = false;
-                if (delay_us > kMaxTimeoutUs) {
-                    ALOGW("delay_us exceeds max timeout: %" PRId64 " us", delay_us);
-
-                    // We'll never block for more than 10 secs, instead
-                    // we will split up the full timeout into chunks of
-                    // 10 secs at a time. This will also avoid overflow
-                    // when converting from us to ns.
-                    delay_us = kMaxTimeoutUs;
-                    timeoutCapped = true;
-                }
-
-                status_t err = mQueueHeadChangedCondition.waitRelative(
-                        mLock, delay_us * 1000ll);
-
-                if (!timeoutCapped && err == -ETIMEDOUT) {
-                    // We finally hit the time this event is supposed to
-                    // trigger.
-                    now_us = ALooper::GetNowUs();
-                    break;
-                }
-            }
-
-            // The event w/ this id may have been cancelled while we're
-            // waiting for its trigger-time, in that case
-            // removeEventFromQueue_l will return NULL.
-            // Otherwise, the QueueItem will be removed
-            // from the queue and the referenced event returned.
-            event = removeEventFromQueue_l(eventID, &wakeLocked);
-        }
-
-        if (event != NULL) {
-            // Fire event with the lock NOT held.
-            event->fire(this, now_us);
-            if (wakeLocked) {
-                Mutex::Autolock autoLock(mLock);
-                releaseWakeLock_l();
-            }
-        }
-    }
-}
-
-sp<TimedEventQueue::Event> TimedEventQueue::removeEventFromQueue_l(
-        event_id id, bool *wakeLocked) {
-    for (List<QueueItem>::iterator it = mQueue.begin();
-         it != mQueue.end(); ++it) {
-        if ((*it).event->eventID() == id) {
-            sp<Event> event = (*it).event;
-            event->setEventID(0);
-            *wakeLocked = (*it).has_wakelock;
-            mQueue.erase(it);
-            return event;
-        }
-    }
-
-    ALOGW("Event %d was not found in the queue, already cancelled?", id);
-
-    return NULL;
-}
-
-void TimedEventQueue::acquireWakeLock_l()
-{
-    if (mWakeLockCount == 0) {
-        CHECK(mWakeLockToken == 0);
-        if (mPowerManager == 0) {
-            // use checkService() to avoid blocking if power service is not up yet
-            sp<IBinder> binder =
-                defaultServiceManager()->checkService(String16("power"));
-            if (binder == 0) {
-                ALOGW("cannot connect to the power manager service");
-            } else {
-                mPowerManager = interface_cast<IPowerManager>(binder);
-                binder->linkToDeath(mDeathRecipient);
-            }
-        }
-        if (mPowerManager != 0) {
-            sp<IBinder> binder = new BBinder();
-            int64_t token = IPCThreadState::self()->clearCallingIdentity();
-            status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
-                                                             binder,
-                                                             String16("TimedEventQueue"),
-                                                             String16("media"));    // not oneway
-            IPCThreadState::self()->restoreCallingIdentity(token);
-            if (status == NO_ERROR) {
-                mWakeLockToken = binder;
-                mWakeLockCount++;
-            }
-        }
-    } else {
-        mWakeLockCount++;
-    }
-}
-
-void TimedEventQueue::releaseWakeLock_l(bool force)
-{
-    if (mWakeLockCount == 0) {
-        return;
-    }
-    if (force) {
-        // Force wakelock release below by setting reference count to 1.
-        mWakeLockCount = 1;
-    }
-    if (--mWakeLockCount == 0) {
-        CHECK(mWakeLockToken != 0);
-        if (mPowerManager != 0) {
-            int64_t token = IPCThreadState::self()->clearCallingIdentity();
-            mPowerManager->releaseWakeLock(mWakeLockToken, 0);  // not oneway
-            IPCThreadState::self()->restoreCallingIdentity(token);
-        }
-        mWakeLockToken.clear();
-    }
-}
-
-void TimedEventQueue::clearPowerManager()
-{
-    Mutex::Autolock _l(mLock);
-    releaseWakeLock_l(true /*force*/);
-    mPowerManager.clear();
-}
-
-void TimedEventQueue::PMDeathRecipient::binderDied(
-        const wp<IBinder>& /* who */) {
-    mQueue->clearPowerManager();
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/Utils.cpp b/media/libstagefright/Utils.cpp
index f0a7277..17f0201 100644
--- a/media/libstagefright/Utils.cpp
+++ b/media/libstagefright/Utils.cpp
@@ -199,7 +199,7 @@
     }
 
     int32_t fps;
-    if (meta->findInt32(kKeyFrameRate, &fps)) {
+    if (meta->findInt32(kKeyFrameRate, &fps) && fps > 0) {
         msg->setInt32("frame-rate", fps);
     }
 
@@ -211,8 +211,10 @@
 
         const uint8_t *ptr = (const uint8_t *)data;
 
-        CHECK(size >= 7);
-        CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
+        if (size < 7 || ptr[0] != 1) {  // configurationVersion == 1
+            ALOGE("b/23680780");
+            return BAD_VALUE;
+        }
         uint8_t profile __unused = ptr[1];
         uint8_t level __unused = ptr[3];
 
@@ -238,7 +240,10 @@
         buffer->setRange(0, 0);
 
         for (size_t i = 0; i < numSeqParameterSets; ++i) {
-            CHECK(size >= 2);
+            if (size < 2) {
+                ALOGE("b/23680780");
+                return BAD_VALUE;
+            }
             size_t length = U16_AT(ptr);
 
             ptr += 2;
@@ -267,13 +272,19 @@
         }
         buffer->setRange(0, 0);
 
-        CHECK(size >= 1);
+        if (size < 1) {
+            ALOGE("b/23680780");
+            return BAD_VALUE;
+        }
         size_t numPictureParameterSets = *ptr;
         ++ptr;
         --size;
 
         for (size_t i = 0; i < numPictureParameterSets; ++i) {
-            CHECK(size >= 2);
+            if (size < 2) {
+                ALOGE("b/23680780");
+                return BAD_VALUE;
+            }
             size_t length = U16_AT(ptr);
 
             ptr += 2;
@@ -297,8 +308,10 @@
     } else if (meta->findData(kKeyHVCC, &type, &data, &size)) {
         const uint8_t *ptr = (const uint8_t *)data;
 
-        CHECK(size >= 7);
-        CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
+        if (size < 23 || ptr[0] != 1) {  // configurationVersion == 1
+            ALOGE("b/23680780");
+            return BAD_VALUE;
+        }
         uint8_t profile __unused = ptr[1] & 31;
         uint8_t level __unused = ptr[12];
         ptr += 22;
@@ -317,6 +330,10 @@
         buffer->setRange(0, 0);
 
         for (i = 0; i < numofArrays; i++) {
+            if (size < 3) {
+                ALOGE("b/23680780");
+                return BAD_VALUE;
+            }
             ptr += 1;
             size -= 1;
 
@@ -327,7 +344,10 @@
             size -= 2;
 
             for (j = 0; j < numofNals; j++) {
-                CHECK(size >= 2);
+                if (size < 2) {
+                    ALOGE("b/23680780");
+                    return BAD_VALUE;
+                }
                 size_t length = U16_AT(ptr);
 
                 ptr += 2;
@@ -644,7 +664,7 @@
     }
 
     int32_t fps;
-    if (msg->findInt32("frame-rate", &fps)) {
+    if (msg->findInt32("frame-rate", &fps) && fps > 0) {
         meta->setInt32(kKeyFrameRate, fps);
     }
 
diff --git a/media/libstagefright/VideoFrameScheduler.cpp b/media/libstagefright/VideoFrameScheduler.cpp
index 5fe9bf9..5564926 100644
--- a/media/libstagefright/VideoFrameScheduler.cpp
+++ b/media/libstagefright/VideoFrameScheduler.cpp
@@ -460,14 +460,16 @@
                 mTimeCorrection -= mVsyncPeriod / 2;
                 renderTime -= mVsyncPeriod / 2;
                 nextVsyncTime -= mVsyncPeriod;
-                --vsyncsForLastFrame;
+                if (vsyncsForLastFrame > 0)
+                    --vsyncsForLastFrame;
             } else if (mTimeCorrection < -correctionLimit &&
                     (vsyncsPerFrameAreNearlyConstant || vsyncsForLastFrame == minVsyncsPerFrame)) {
                 // add a VSYNC
                 mTimeCorrection += mVsyncPeriod / 2;
                 renderTime += mVsyncPeriod / 2;
                 nextVsyncTime += mVsyncPeriod;
-                ++vsyncsForLastFrame;
+                if (vsyncsForLastFrame < ULONG_MAX)
+                    ++vsyncsForLastFrame;
             }
             ATRACE_INT("FRAME_VSYNCS", vsyncsForLastFrame);
         }
diff --git a/media/libstagefright/WAVExtractor.cpp b/media/libstagefright/WAVExtractor.cpp
index 48b810a..811929b 100644
--- a/media/libstagefright/WAVExtractor.cpp
+++ b/media/libstagefright/WAVExtractor.cpp
@@ -193,15 +193,17 @@
             }
 
             mNumChannels = U16_LE_AT(&formatSpec[2]);
+
+            if (mNumChannels < 1 || mNumChannels > 8) {
+                ALOGE("Unsupported number of channels (%d)", mNumChannels);
+                return ERROR_UNSUPPORTED;
+            }
+
             if (mWaveFormat != WAVE_FORMAT_EXTENSIBLE) {
                 if (mNumChannels != 1 && mNumChannels != 2) {
                     ALOGW("More than 2 channels (%d) in non-WAVE_EXT, unknown channel mask",
                             mNumChannels);
                 }
-            } else {
-                if (mNumChannels < 1 && mNumChannels > 8) {
-                    return ERROR_UNSUPPORTED;
-                }
             }
 
             mSampleRate = U32_LE_AT(&formatSpec[4]);
diff --git a/media/libstagefright/codecs/aacdec/SoftAAC2.cpp b/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
index 965c55e..ac8c9bf 100644
--- a/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
+++ b/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
@@ -35,7 +35,7 @@
 #define DRC_DEFAULT_MOBILE_DRC_CUT   127 /* maximum compression of dynamic range for mobile conf */
 #define DRC_DEFAULT_MOBILE_DRC_BOOST 127 /* maximum compression of dynamic range for mobile conf */
 #define DRC_DEFAULT_MOBILE_DRC_HEAVY 1   /* switch for heavy compression for mobile conf */
-#define DRC_DEFAULT_MOBILE_ENC_LEVEL -1 /* encoder target level; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */
+#define DRC_DEFAULT_MOBILE_ENC_LEVEL (-1) /* encoder target level; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */
 #define MAX_CHANNEL_COUNT            8  /* maximum number of audio channels that can be decoded */
 // names of properties that can be used to override the default DRC settings
 #define PROP_DRC_OVERRIDE_REF_LEVEL  "aac_drc_reference_level"
diff --git a/media/libstagefright/codecs/aacenc/Android.mk b/media/libstagefright/codecs/aacenc/Android.mk
index 068cffe..71c374b 100644
--- a/media/libstagefright/codecs/aacenc/Android.mk
+++ b/media/libstagefright/codecs/aacenc/Android.mk
@@ -1,6 +1,5 @@
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
-include frameworks/av/media/libstagefright/codecs/common/Config.mk
 
 AAC_LIBRARY = fraunhofer
 
@@ -35,24 +34,28 @@
 	src/transform.c \
 	src/memalign.c
 
-ifeq ($(VOTT), v5)
-LOCAL_SRC_FILES += \
-	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
-endif
+ifneq ($(ARCH_ARM_HAVE_NEON),true)
+    LOCAL_SRC_FILES_arm := \
+        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
 
-ifeq ($(VOTT), v7)
-LOCAL_SRC_FILES += \
-	src/asm/ARMV5E/AutoCorrelation_v5.s \
-	src/asm/ARMV5E/band_nrg_v5.s \
-	src/asm/ARMV5E/CalcWindowEnergy_v5.s \
-	src/asm/ARMV7/PrePostMDCT_v7.s \
-	src/asm/ARMV7/R4R8First_v7.s \
-	src/asm/ARMV7/Radix4FFT_v7.s
+    LOCAL_CFLAGS_arm := -DARMV5E -DARM_INASM -DARMV5_INASM
+    LOCAL_C_INCLUDES_arm := $(LOCAL_PATH)/src/asm/ARMV5E
+else
+    LOCAL_SRC_FILES_arm := \
+        src/asm/ARMV5E/AutoCorrelation_v5.s \
+        src/asm/ARMV5E/band_nrg_v5.s \
+        src/asm/ARMV5E/CalcWindowEnergy_v5.s \
+        src/asm/ARMV7/PrePostMDCT_v7.s \
+        src/asm/ARMV7/R4R8First_v7.s \
+        src/asm/ARMV7/Radix4FFT_v7.s
+    LOCAL_CFLAGS_arm := -DARMV5E -DARMV7Neon -DARM_INASM -DARMV5_INASM -DARMV6_INASM
+    LOCAL_C_INCLUDES_arm := $(LOCAL_PATH)/src/asm/ARMV5E
+    LOCAL_C_INCLUDES_arm += $(LOCAL_PATH)/src/asm/ARMV7
 endif
 
 LOCAL_MODULE := libstagefright_aacenc
@@ -61,7 +64,10 @@
 
 LOCAL_STATIC_LIBRARIES :=
 
-LOCAL_SHARED_LIBRARIES :=
+# 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.
+LOCAL_SHARED_LIBRARIES := libbinder
 
 LOCAL_C_INCLUDES := \
 	frameworks/av/include \
@@ -71,17 +77,6 @@
 	$(LOCAL_PATH)/inc \
 	$(LOCAL_PATH)/basic_op
 
-ifeq ($(VOTT), v5)
-LOCAL_CFLAGS += -DARMV5E -DARM_INASM -DARMV5_INASM
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/src/asm/ARMV5E
-endif
-
-ifeq ($(VOTT), v7)
-LOCAL_CFLAGS += -DARMV5E -DARMV7Neon -DARM_INASM -DARMV5_INASM -DARMV6_INASM
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/src/asm/ARMV5E
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/src/asm/ARMV7
-endif
-
 LOCAL_CFLAGS += -Werror
 LOCAL_CLANG := true
 LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
@@ -112,7 +107,7 @@
 
   LOCAL_CFLAGS += -Werror
   LOCAL_CLANG := true
-  LOCAL_SANITIZE := signed-integer-overflow
+  LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
 
   LOCAL_STATIC_LIBRARIES := libFraunhoferAAC
 
@@ -138,7 +133,7 @@
 
   LOCAL_CFLAGS += -Werror
   LOCAL_CLANG := true
-  LOCAL_SANITIZE := signed-integer-overflow
+  LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
 
   LOCAL_STATIC_LIBRARIES := \
           libstagefright_aacenc
diff --git a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
index 4fd16a1..78f032b 100644
--- a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
+++ b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
@@ -234,10 +234,10 @@
 }
 
 #define step(shift) \
-    if ((0x40000000l >> shift) + root <= value)       \
+    if ((0x40000000l >> (shift)) + root <= value)       \
     {                                                 \
-        value -= (0x40000000l >> shift) + root;       \
-        root = (root >> 1) | (0x40000000l >> shift);  \
+        value -= (0x40000000l >> (shift)) + root;       \
+        root = (root >> 1) | (0x40000000l >> (shift));  \
     } else {                                          \
         root = root >> 1;                             \
     }
diff --git a/media/libstagefright/codecs/aacenc/basic_op/typedefs.h b/media/libstagefright/codecs/aacenc/basic_op/typedefs.h
index 6059237..80d350d 100644
--- a/media/libstagefright/codecs/aacenc/basic_op/typedefs.h
+++ b/media/libstagefright/codecs/aacenc/basic_op/typedefs.h
@@ -89,11 +89,11 @@
 #endif
 
 #ifndef min
-#define min(a,b) ( a < b ? a : b)
+#define min(a,b) ( (a) < (b) ? (a) : (b))
 #endif
 
 #ifndef max
-#define max(a,b) ( a > b ? a : b)
+#define max(a,b) ( (a) > (b) ? (a) : (b))
 #endif
 
 #ifdef ARM_INASM
diff --git a/media/libstagefright/codecs/aacenc/inc/psy_const.h b/media/libstagefright/codecs/aacenc/inc/psy_const.h
index 19fb9b2..0b9f8c3 100644
--- a/media/libstagefright/codecs/aacenc/inc/psy_const.h
+++ b/media/libstagefright/codecs/aacenc/inc/psy_const.h
@@ -73,7 +73,7 @@
 #define TRANSFORM_OFFSET_LONG    0
 #define TRANSFORM_OFFSET_SHORT   448
 
-#define LOG_NORM_PCM          -15
+#define LOG_NORM_PCM          (-15)
 
 #define NUM_SAMPLE_RATES	12
 
diff --git a/media/libstagefright/codecs/aacenc/src/bit_cnt.c b/media/libstagefright/codecs/aacenc/src/bit_cnt.c
index 9fe511c..65b035e 100644
--- a/media/libstagefright/codecs/aacenc/src/bit_cnt.c
+++ b/media/libstagefright/codecs/aacenc/src/bit_cnt.c
@@ -23,10 +23,10 @@
 #include "bit_cnt.h"
 #include "aac_rom.h"
 
-#define HI_LTAB(a) (a>>8)
-#define LO_LTAB(a) (a & 0xff)
+#define HI_LTAB(a) ((a)>>8)
+#define LO_LTAB(a) ((a) & 0xff)
 
-#define EXPAND(a)  ((((Word32)(a&0xff00)) << 8)|(Word32)(a&0xff))
+#define EXPAND(a)  ((((Word32)((a)&0xff00)) << 8)|(Word32)((a)&0xff))
 
 
 /*****************************************************************************
diff --git a/media/libstagefright/codecs/aacenc/src/transform.c b/media/libstagefright/codecs/aacenc/src/transform.c
index 0080810..5de2b96 100644
--- a/media/libstagefright/codecs/aacenc/src/transform.c
+++ b/media/libstagefright/codecs/aacenc/src/transform.c
@@ -30,8 +30,8 @@
 #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
+	(p0) = p1; *(&(p0)+1) = *(&(p1)+1);	\
+	(p1) = t; *(&(p1)+1) = t1
 
 /*********************************************************************************
 *
diff --git a/media/libstagefright/codecs/amrnb/common/Android.mk b/media/libstagefright/codecs/amrnb/common/Android.mk
index ec455c7..3e4c8c7 100644
--- a/media/libstagefright/codecs/amrnb/common/Android.mk
+++ b/media/libstagefright/codecs/amrnb/common/Android.mk
@@ -69,7 +69,7 @@
 
 LOCAL_CFLAGS += -Werror
 LOCAL_CLANG := true
-LOCAL_SANITIZE := signed-integer-overflow
+LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
 
 LOCAL_MODULE := libstagefright_amrnb_common
 
diff --git a/media/libstagefright/codecs/amrnb/common/src/az_lsp.cpp b/media/libstagefright/codecs/amrnb/common/src/az_lsp.cpp
index 976b1a6..f3098f5 100644
--- a/media/libstagefright/codecs/amrnb/common/src/az_lsp.cpp
+++ b/media/libstagefright/codecs/amrnb/common/src/az_lsp.cpp
@@ -103,7 +103,7 @@
 ; Include all pre-processor statements here. Include conditional
 ; compile variables also.
 ----------------------------------------------------------------------------*/
-#define NC   M/2                  /* M = LPC order, NC = M/2 */
+#define NC   (M/2)                  /* M = LPC order, NC = M/2 */
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
@@ -237,7 +237,9 @@
 
 ------------------------------------------------------------------------------
 */
-
+#ifdef __clang__
+__attribute__((no_sanitize("integer")))
+#endif
 static Word16 Chebps(Word16 x,
                      Word16 f[], /* (n) */
                      Word16 n,
diff --git a/media/libstagefright/codecs/amrnb/common/src/gc_pred.cpp b/media/libstagefright/codecs/amrnb/common/src/gc_pred.cpp
index 1c8a700..731dc52 100644
--- a/media/libstagefright/codecs/amrnb/common/src/gc_pred.cpp
+++ b/media/libstagefright/codecs/amrnb/common/src/gc_pred.cpp
@@ -69,8 +69,8 @@
 #define MEAN_ENER_MR122  783741L  /* 36/(20*log10(2)) (Q17) */
 
 /* minimum quantized energy: -14 dB */
-#define MIN_ENERGY       -14336       /* 14                 Q10 */
-#define MIN_ENERGY_MR122  -2381       /* 14 / (20*log10(2)) Q10 */
+#define MIN_ENERGY       (-14336)       /* 14                 Q10 */
+#define MIN_ENERGY_MR122  (-2381)       /* 14 / (20*log10(2)) Q10 */
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
diff --git a/media/libstagefright/codecs/amrnb/common/src/sub.cpp b/media/libstagefright/codecs/amrnb/common/src/sub.cpp
index d936128..b956912 100644
--- a/media/libstagefright/codecs/amrnb/common/src/sub.cpp
+++ b/media/libstagefright/codecs/amrnb/common/src/sub.cpp
@@ -187,6 +187,9 @@
 ; FUNCTION CODE
 ----------------------------------------------------------------------------*/
 
+#ifdef __clang__
+__attribute__((no_sanitize("integer")))
+#endif
 Word16 sub(Word16 var1, Word16 var2, Flag *pOverflow)
 {
 
diff --git a/media/libstagefright/codecs/amrnb/common/src/syn_filt.cpp b/media/libstagefright/codecs/amrnb/common/src/syn_filt.cpp
index bcdc696..36c1d84 100644
--- a/media/libstagefright/codecs/amrnb/common/src/syn_filt.cpp
+++ b/media/libstagefright/codecs/amrnb/common/src/syn_filt.cpp
@@ -245,7 +245,9 @@
 
 ------------------------------------------------------------------------------
 */
-
+#ifdef __clang__
+__attribute__((no_sanitize("integer")))
+#endif
 void Syn_filt(
     Word16 a[],     /* (i)   : a[M+1] prediction coefficients   (M=10)  */
     Word16 x[],     /* (i)   : input signal                             */
diff --git a/media/libstagefright/codecs/amrnb/dec/Android.mk b/media/libstagefright/codecs/amrnb/dec/Android.mk
index 5591af5..b966762 100644
--- a/media/libstagefright/codecs/amrnb/dec/Android.mk
+++ b/media/libstagefright/codecs/amrnb/dec/Android.mk
@@ -102,7 +102,7 @@
         libstagefright_amrnbdec libsndfile
 
 LOCAL_SHARED_LIBRARIES := \
-        libstagefright_amrnb_common libaudioutils
+        libstagefright_amrnb_common libaudioutils liblog
 
 LOCAL_CLANG := true
 LOCAL_SANITIZE := signed-integer-overflow
diff --git a/media/libstagefright/codecs/amrnb/dec/src/a_refl.cpp b/media/libstagefright/codecs/amrnb/dec/src/a_refl.cpp
index fb7cff3..696d2da 100644
--- a/media/libstagefright/codecs/amrnb/dec/src/a_refl.cpp
+++ b/media/libstagefright/codecs/amrnb/dec/src/a_refl.cpp
@@ -59,6 +59,8 @@
 /*----------------------------------------------------------------------------
 ; INCLUDES
 ----------------------------------------------------------------------------*/
+#include <log/log.h>
+
 #include "a_refl.h"
 #include "typedef.h"
 #include "cnst.h"
@@ -291,7 +293,8 @@
                 {
                     refl[i] = 0;
                 }
-                break;
+                ALOGE("b/23609206");
+                return;
             }
 
             bState[j] = extract_l(L_temp);
diff --git a/media/libstagefright/codecs/amrwb/src/dtx.h b/media/libstagefright/codecs/amrwb/src/dtx.h
index a81f089..cf686a0 100644
--- a/media/libstagefright/codecs/amrwb/src/dtx.h
+++ b/media/libstagefright/codecs/amrwb/src/dtx.h
@@ -77,7 +77,7 @@
 #define DTX_HANG_CONST 7                   /* yields eight frames of SP HANGOVER  */
 #define INV_MED_THRESH 14564
 #define ISF_GAP  128                       /* 50 */
-#define ONE_MINUS_ISF_GAP 16384 - ISF_GAP
+#define ONE_MINUS_ISF_GAP (16384 - ISF_GAP)
 
 #define ISF_GAP   128
 #define ISF_DITH_GAP   448
diff --git a/media/libstagefright/codecs/amrwb/src/homing_amr_wb_dec.cpp b/media/libstagefright/codecs/amrwb/src/homing_amr_wb_dec.cpp
index f032a08..dde3e43 100644
--- a/media/libstagefright/codecs/amrwb/src/homing_amr_wb_dec.cpp
+++ b/media/libstagefright/codecs/amrwb/src/homing_amr_wb_dec.cpp
@@ -105,15 +105,15 @@
 #define NUM_OF_SPMODES 9
 
 #define PRML 15
-#define PRMN_7k NBBITS_7k/PRML + 1
-#define PRMN_9k NBBITS_9k/PRML + 1
-#define PRMN_12k NBBITS_12k/PRML + 1
-#define PRMN_14k NBBITS_14k/PRML + 1
-#define PRMN_16k NBBITS_16k/PRML + 1
-#define PRMN_18k NBBITS_18k/PRML + 1
-#define PRMN_20k NBBITS_20k/PRML + 1
-#define PRMN_23k NBBITS_23k/PRML + 1
-#define PRMN_24k NBBITS_24k/PRML + 1
+#define PRMN_7k (NBBITS_7k/PRML + 1)
+#define PRMN_9k (NBBITS_9k/PRML + 1)
+#define PRMN_12k (NBBITS_12k/PRML + 1)
+#define PRMN_14k (NBBITS_14k/PRML + 1)
+#define PRMN_16k (NBBITS_16k/PRML + 1)
+#define PRMN_18k (NBBITS_18k/PRML + 1)
+#define PRMN_20k (NBBITS_20k/PRML + 1)
+#define PRMN_23k (NBBITS_23k/PRML + 1)
+#define PRMN_24k (NBBITS_24k/PRML + 1)
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.h b/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.h
index 8951e5c..2143c9a 100644
--- a/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.h
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.h
@@ -119,8 +119,8 @@
 #define norm_s( x)    (normalize_amr_wb(  x) - 16)
 
 
-#define extract_h( x)    (int16)(x>>16)
-#define L_deposit_h( x)    (int32)(x<<16)
+#define extract_h( x)    (int16)((x)>>16)
+#define L_deposit_h( x)    (int32)((x)<<16)
 
 
 #ifdef __cplusplus
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op.h
index df239d2..88ff9bc 100644
--- a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op.h
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op.h
@@ -56,8 +56,8 @@
 #define MAX_32 (int32)0x7fffffffL
 #define MIN_32 (int32)0x80000000L
 
-#define MAX_16 (int16)+32767    /* 0x7fff */
-#define MIN_16 (int16)-32768    /* 0x8000 */
+#define MAX_16 ((int16)+32767)    /* 0x7fff */
+#define MIN_16 ((int16)-32768)    /* 0x8000 */
 
 
 
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_cnst.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_cnst.h
index ecf1bf3..3981ce3 100644
--- a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_cnst.h
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_cnst.h
@@ -130,7 +130,7 @@
 
 #define EHF_MASK (int16)0x0008            /* homing frame pattern                       */
 
-#define BIT_0     (int16)-127
+#define BIT_0     ((int16)-127)
 #define BIT_1     (int16)127
 #define BIT_0_ITU (int16)0x007F
 #define BIT_1_ITU (int16)0x0081
diff --git a/media/libstagefright/codecs/amrwbenc/Android.mk b/media/libstagefright/codecs/amrwbenc/Android.mk
index fd6d007..77a7b1e 100644
--- a/media/libstagefright/codecs/amrwbenc/Android.mk
+++ b/media/libstagefright/codecs/amrwbenc/Android.mk
@@ -1,8 +1,5 @@
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
-include frameworks/av/media/libstagefright/codecs/common/Config.mk
-
-
 
 LOCAL_SRC_FILES := \
 	src/autocorr.c \
@@ -53,37 +50,39 @@
 	src/weight_a.c \
 	src/mem_align.c
 
+ifneq ($(ARCH_ARM_HAVE_NEON),true)
+    LOCAL_SRC_FILES_arm := \
+        src/asm/ARMV5E/convolve_opt.s \
+        src/asm/ARMV5E/cor_h_vec_opt.s \
+        src/asm/ARMV5E/Deemph_32_opt.s \
+        src/asm/ARMV5E/Dot_p_opt.s \
+        src/asm/ARMV5E/Filt_6k_7k_opt.s \
+        src/asm/ARMV5E/Norm_Corr_opt.s \
+        src/asm/ARMV5E/pred_lt4_1_opt.s \
+        src/asm/ARMV5E/residu_asm_opt.s \
+        src/asm/ARMV5E/scale_sig_opt.s \
+        src/asm/ARMV5E/Syn_filt_32_opt.s \
+        src/asm/ARMV5E/syn_filt_opt.s
 
-ifeq ($(VOTT), v5)
-LOCAL_SRC_FILES += \
-	src/asm/ARMV5E/convolve_opt.s \
-	src/asm/ARMV5E/cor_h_vec_opt.s \
-	src/asm/ARMV5E/Deemph_32_opt.s \
-	src/asm/ARMV5E/Dot_p_opt.s \
-	src/asm/ARMV5E/Filt_6k_7k_opt.s \
-	src/asm/ARMV5E/Norm_Corr_opt.s \
-	src/asm/ARMV5E/pred_lt4_1_opt.s \
-	src/asm/ARMV5E/residu_asm_opt.s \
-	src/asm/ARMV5E/scale_sig_opt.s \
-	src/asm/ARMV5E/Syn_filt_32_opt.s \
-	src/asm/ARMV5E/syn_filt_opt.s
+    LOCAL_CFLAGS_arm := -DARM -DASM_OPT
+    LOCAL_C_INCLUDES_arm = $(LOCAL_PATH)/src/asm/ARMV5E
+else
+    LOCAL_SRC_FILES_arm := \
+        src/asm/ARMV7/convolve_neon.s \
+        src/asm/ARMV7/cor_h_vec_neon.s \
+        src/asm/ARMV7/Deemph_32_neon.s \
+        src/asm/ARMV7/Dot_p_neon.s \
+        src/asm/ARMV7/Filt_6k_7k_neon.s \
+        src/asm/ARMV7/Norm_Corr_neon.s \
+        src/asm/ARMV7/pred_lt4_1_neon.s \
+        src/asm/ARMV7/residu_asm_neon.s \
+        src/asm/ARMV7/scale_sig_neon.s \
+        src/asm/ARMV7/Syn_filt_32_neon.s \
+        src/asm/ARMV7/syn_filt_neon.s
 
-endif
-
-ifeq ($(VOTT), v7)
-LOCAL_SRC_FILES += \
-	src/asm/ARMV7/convolve_neon.s \
-	src/asm/ARMV7/cor_h_vec_neon.s \
-	src/asm/ARMV7/Deemph_32_neon.s \
-	src/asm/ARMV7/Dot_p_neon.s \
-	src/asm/ARMV7/Filt_6k_7k_neon.s \
-	src/asm/ARMV7/Norm_Corr_neon.s \
-	src/asm/ARMV7/pred_lt4_1_neon.s \
-	src/asm/ARMV7/residu_asm_neon.s \
-	src/asm/ARMV7/scale_sig_neon.s \
-	src/asm/ARMV7/Syn_filt_32_neon.s \
-	src/asm/ARMV7/syn_filt_neon.s
-
+    LOCAL_CFLAGS_arm := -DARM -DARMV7 -DASM_OPT
+    LOCAL_C_INCLUDES_arm := $(LOCAL_PATH)/src/asm/ARMV5E
+    LOCAL_C_INCLUDES_arm += $(LOCAL_PATH)/src/asm/ARMV7
 endif
 
 LOCAL_MODULE := libstagefright_amrwbenc
@@ -101,17 +100,6 @@
 	$(LOCAL_PATH)/src \
 	$(LOCAL_PATH)/inc
 
-ifeq ($(VOTT), v5)
-LOCAL_CFLAGS += -DARM -DASM_OPT
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/src/asm/ARMV5E
-endif
-
-ifeq ($(VOTT), v7)
-LOCAL_CFLAGS += -DARM -DARMV7 -DASM_OPT
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/src/asm/ARMV5E
-LOCAL_C_INCLUDES += $(LOCAL_PATH)/src/asm/ARMV7
-endif
-
 LOCAL_CFLAGS += -Werror
 LOCAL_CLANG := true
 LOCAL_SANITIZE := signed-integer-overflow
diff --git a/media/libstagefright/codecs/amrwbenc/inc/acelp.h b/media/libstagefright/codecs/amrwbenc/inc/acelp.h
index 5a1e536..97555d5 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/acelp.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/acelp.h
@@ -18,7 +18,7 @@
 /*--------------------------------------------------------------------------*
  *                         ACELP.H                                          *
  *--------------------------------------------------------------------------*
- *       Function			 			             *
+ *       Function                                    *
  *--------------------------------------------------------------------------*/
 #ifndef __ACELP_H__
 #define __ACELP_H__
@@ -33,68 +33,68 @@
 Word16 median5(Word16 x[]);
 
 void Autocorr(
-		Word16 x[],                           /* (i)    : Input signal                      */
-		Word16 m,                             /* (i)    : LPC order                         */
-		Word16 r_h[],                         /* (o)    : Autocorrelations  (msb)           */
-		Word16 r_l[]                          /* (o)    : Autocorrelations  (lsb)           */
-	     );
+        Word16 x[],                           /* (i)    : Input signal                      */
+        Word16 m,                             /* (i)    : LPC order                         */
+        Word16 r_h[],                         /* (o)    : Autocorrelations  (msb)           */
+        Word16 r_l[]                          /* (o)    : Autocorrelations  (lsb)           */
+         );
 
 void Lag_window(
-		Word16 r_h[],                         /* (i/o)   : Autocorrelations  (msb)          */
-		Word16 r_l[]                          /* (i/o)   : Autocorrelations  (lsb)          */
-	       );
+        Word16 r_h[],                         /* (i/o)   : Autocorrelations  (msb)          */
+        Word16 r_l[]                          /* (i/o)   : Autocorrelations  (lsb)          */
+           );
 
 void Init_Levinson(
-		Word16 * mem                          /* output  :static memory (18 words) */
-		);
+        Word16 * mem                          /* output  :static memory (18 words) */
+        );
 
 void Levinson(
-		Word16 Rh[],                          /* (i)     : Rh[M+1] Vector of autocorrelations (msb) */
-		Word16 Rl[],                          /* (i)     : Rl[M+1] Vector of autocorrelations (lsb) */
-		Word16 A[],                           /* (o) Q12 : A[M]    LPC coefficients  (m = 16)       */
-		Word16 rc[],                          /* (o) Q15 : rc[M]   Reflection coefficients.         */
-		Word16 * mem                          /* (i/o)   :static memory (18 words)                  */
-	     );
+        Word16 Rh[],                          /* (i)     : Rh[M+1] Vector of autocorrelations (msb) */
+        Word16 Rl[],                          /* (i)     : Rl[M+1] Vector of autocorrelations (lsb) */
+        Word16 A[],                           /* (o) Q12 : A[M]    LPC coefficients  (m = 16)       */
+        Word16 rc[],                          /* (o) Q15 : rc[M]   Reflection coefficients.         */
+        Word16 * mem                          /* (i/o)   :static memory (18 words)                  */
+         );
 
 void Az_isp(
-		Word16 a[],                           /* (i) Q12 : predictor coefficients                 */
-		Word16 isp[],                         /* (o) Q15 : Immittance spectral pairs              */
-		Word16 old_isp[]                      /* (i)     : old isp[] (in case not found M roots)  */
-	   );
+        Word16 a[],                           /* (i) Q12 : predictor coefficients                 */
+        Word16 isp[],                         /* (o) Q15 : Immittance spectral pairs              */
+        Word16 old_isp[]                      /* (i)     : old isp[] (in case not found M roots)  */
+       );
 
 void Isp_Az(
-		Word16 isp[],                         /* (i) Q15 : Immittance spectral pairs            */
-		Word16 a[],                           /* (o) Q12 : predictor coefficients (order = M)   */
-		Word16 m,
-		Word16 adaptive_scaling               /* (i) 0   : adaptive scaling disabled */
-		/*     1   : adaptive scaling enabled  */
-	   );
+        Word16 isp[],                         /* (i) Q15 : Immittance spectral pairs            */
+        Word16 a[],                           /* (o) Q12 : predictor coefficients (order = M)   */
+        Word16 m,
+        Word16 adaptive_scaling               /* (i) 0   : adaptive scaling disabled */
+        /*     1   : adaptive scaling enabled  */
+       );
 
 void Isp_isf(
-		Word16 isp[],                         /* (i) Q15 : isp[m] (range: -1<=val<1)                */
-		Word16 isf[],                         /* (o) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
-		Word16 m                              /* (i)     : LPC order                                */
-	    );
+        Word16 isp[],                         /* (i) Q15 : isp[m] (range: -1<=val<1)                */
+        Word16 isf[],                         /* (o) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+        Word16 m                              /* (i)     : LPC order                                */
+        );
 
 void Isf_isp(
-		Word16 isf[],                         /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
-		Word16 isp[],                         /* (o) Q15 : isp[m] (range: -1<=val<1)                */
-		Word16 m                              /* (i)     : LPC order                                */
-	    );
+        Word16 isf[],                         /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+        Word16 isp[],                         /* (o) Q15 : isp[m] (range: -1<=val<1)                */
+        Word16 m                              /* (i)     : LPC order                                */
+        );
 
 void Int_isp(
-		Word16 isp_old[],                     /* input : isps from past frame              */
-		Word16 isp_new[],                     /* input : isps from present frame           */
-		Word16 frac[],                        /* input : fraction for 3 first subfr (Q15)  */
-		Word16 Az[]                           /* output: LP coefficients in 4 subframes    */
-	    );
+        Word16 isp_old[],                     /* input : isps from past frame              */
+        Word16 isp_new[],                     /* input : isps from present frame           */
+        Word16 frac[],                        /* input : fraction for 3 first subfr (Q15)  */
+        Word16 Az[]                           /* output: LP coefficients in 4 subframes    */
+        );
 
 void Weight_a(
-		Word16 a[],                           /* (i) Q12 : a[m+1]  LPC coefficients             */
-		Word16 ap[],                          /* (o) Q12 : Spectral expanded LPC coefficients   */
-		Word16 gamma,                         /* (i) Q15 : Spectral expansion factor.           */
-		Word16 m                              /* (i)     : LPC order.                           */
-	     );
+        Word16 a[],                           /* (i) Q12 : a[m+1]  LPC coefficients             */
+        Word16 ap[],                          /* (o) Q12 : Spectral expanded LPC coefficients   */
+        Word16 gamma,                         /* (i) Q15 : Spectral expansion factor.           */
+        Word16 m                              /* (i)     : LPC order.                           */
+         );
 
 
 /*-----------------------------------------------------------------*
@@ -102,214 +102,214 @@
  *-----------------------------------------------------------------*/
 
 void Qpisf_2s_46b(
-		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
-		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
-		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
-		Word16 * indice,                      /* (o)     : quantization indices                 */
-		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
-		);
+        Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
+        Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
+        Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
+        Word16 * indice,                      /* (o)     : quantization indices                 */
+        Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
+        );
 
 void Qpisf_2s_36b(
-		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
-		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
-		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
-		Word16 * indice,                      /* (o)     : quantization indices                 */
-		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
-		);
+        Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
+        Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
+        Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
+        Word16 * indice,                      /* (o)     : quantization indices                 */
+        Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
+        );
 
 void Dpisf_2s_46b(
-		Word16 * indice,                      /* input:  quantization indices                       */
-		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
-		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
-		Word16 * isfold,                      /* input : past quantized ISF                    */
-		Word16 * isf_buf,                     /* input : isf buffer                                                        */
-		Word16 bfi,                           /* input : Bad frame indicator                   */
-		Word16 enc_dec
-		);
+        Word16 * indice,                      /* input:  quantization indices                       */
+        Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+        Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+        Word16 * isfold,                      /* input : past quantized ISF                    */
+        Word16 * isf_buf,                     /* input : isf buffer                                                        */
+        Word16 bfi,                           /* input : Bad frame indicator                   */
+        Word16 enc_dec
+        );
 
 void Dpisf_2s_36b(
-		Word16 * indice,                      /* input:  quantization indices                       */
-		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
-		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
-		Word16 * isfold,                      /* input : past quantized ISF                    */
-		Word16 * isf_buf,                     /* input : isf buffer                                                        */
-		Word16 bfi,                           /* input : Bad frame indicator                   */
-		Word16 enc_dec
-		);
+        Word16 * indice,                      /* input:  quantization indices                       */
+        Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+        Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+        Word16 * isfold,                      /* input : past quantized ISF                    */
+        Word16 * isf_buf,                     /* input : isf buffer                                                        */
+        Word16 bfi,                           /* input : Bad frame indicator                   */
+        Word16 enc_dec
+        );
 
 void Qisf_ns(
-		Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */
-		Word16 * isf_q,                       /* output: quantized ISF                        */
-		Word16 * indice                       /* output: quantization indices                 */
-	    );
+        Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */
+        Word16 * isf_q,                       /* output: quantized ISF                        */
+        Word16 * indice                       /* output: quantization indices                 */
+        );
 
 void Disf_ns(
-		Word16 * indice,                      /* input:  quantization indices                  */
-		Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */
-	    );
+        Word16 * indice,                      /* input:  quantization indices                  */
+        Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */
+        );
 
 Word16 Sub_VQ(                             /* output: return quantization index     */
-		Word16 * x,                           /* input : ISF residual vector           */
-		Word16 * dico,                        /* input : quantization codebook         */
-		Word16 dim,                           /* input : dimention of vector           */
-		Word16 dico_size,                     /* input : size of quantization codebook */
-		Word32 * distance                     /* output: error of quantization         */
-	     );
+        Word16 * x,                           /* input : ISF residual vector           */
+        Word16 * dico,                        /* input : quantization codebook         */
+        Word16 dim,                           /* input : dimention of vector           */
+        Word16 dico_size,                     /* input : size of quantization codebook */
+        Word32 * distance                     /* output: error of quantization         */
+         );
 
 void Reorder_isf(
-		Word16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */
-		Word16 min_dist,                      /* (i) Q15  : minimum distance to keep             */
-		Word16 n                              /* (i)      : number of ISF                        */
-		);
+        Word16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */
+        Word16 min_dist,                      /* (i) Q15  : minimum distance to keep             */
+        Word16 n                              /* (i)      : number of ISF                        */
+        );
 
 /*-----------------------------------------------------------------*
  *                       filter prototypes                         *
  *-----------------------------------------------------------------*/
 
 void Init_Decim_12k8(
-		Word16 mem[]                          /* output: memory (2*NB_COEF_DOWN) set to zeros */
-		);
+        Word16 mem[]                          /* output: memory (2*NB_COEF_DOWN) set to zeros */
+        );
 void Decim_12k8(
-		Word16 sig16k[],                      /* input:  signal to downsampling  */
-		Word16 lg,                            /* input:  length of input         */
-		Word16 sig12k8[],                     /* output: decimated signal        */
-		Word16 mem[]                          /* in/out: memory (2*NB_COEF_DOWN) */
-	       );
+        Word16 sig16k[],                      /* input:  signal to downsampling  */
+        Word16 lg,                            /* input:  length of input         */
+        Word16 sig12k8[],                     /* output: decimated signal        */
+        Word16 mem[]                          /* in/out: memory (2*NB_COEF_DOWN) */
+           );
 
 void Init_HP50_12k8(Word16 mem[]);
 void HP50_12k8(
-		Word16 signal[],                      /* input/output signal */
-		Word16 lg,                            /* lenght of signal    */
-		Word16 mem[]                          /* filter memory [6]   */
-	      );
+        Word16 signal[],                      /* input/output signal */
+        Word16 lg,                            /* lenght of signal    */
+        Word16 mem[]                          /* filter memory [6]   */
+          );
 void Init_HP400_12k8(Word16 mem[]);
 void HP400_12k8(
-		Word16 signal[],                      /* input/output signal */
-		Word16 lg,                            /* lenght of signal    */
-		Word16 mem[]                          /* filter memory [6]   */
-	       );
+        Word16 signal[],                      /* input/output signal */
+        Word16 lg,                            /* lenght of signal    */
+        Word16 mem[]                          /* filter memory [6]   */
+           );
 
 void Init_Filt_6k_7k(Word16 mem[]);
 void Filt_6k_7k(
-		Word16 signal[],                      /* input:  signal                  */
-		Word16 lg,                            /* input:  length of input         */
-		Word16 mem[]                          /* in/out: memory (size=30)        */
-	       );
+        Word16 signal[],                      /* input:  signal                  */
+        Word16 lg,                            /* input:  length of input         */
+        Word16 mem[]                          /* in/out: memory (size=30)        */
+           );
 void Filt_6k_7k_asm(
-		Word16 signal[],                      /* input:  signal                  */
-		Word16 lg,                            /* input:  length of input         */
-		Word16 mem[]                          /* in/out: memory (size=30)        */
-	       );
+        Word16 signal[],                      /* input:  signal                  */
+        Word16 lg,                            /* input:  length of input         */
+        Word16 mem[]                          /* in/out: memory (size=30)        */
+           );
 
 void LP_Decim2(
-		Word16 x[],                           /* in/out: signal to process         */
-		Word16 l,                             /* input : size of filtering         */
-		Word16 mem[]                          /* in/out: memory (size=3)           */
-	      );
+        Word16 x[],                           /* in/out: signal to process         */
+        Word16 l,                             /* input : size of filtering         */
+        Word16 mem[]                          /* in/out: memory (size=3)           */
+          );
 
 void Preemph(
-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
-		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
-		Word16 lg,                            /* (i)     : lenght of filtering                    */
-		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
-	    );
+        Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+        Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
+        Word16 lg,                            /* (i)     : lenght of filtering                    */
+        Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
+        );
 void Preemph2(
-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
-		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
-		Word16 lg,                            /* (i)     : lenght of filtering                    */
-		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
-	     );
+        Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+        Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
+        Word16 lg,                            /* (i)     : lenght of filtering                    */
+        Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
+         );
 void Deemph(
-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
-		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
-		Word16 L,                             /* (i)     : vector size                            */
-		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
-	   );
+        Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+        Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
+        Word16 L,                             /* (i)     : vector size                            */
+        Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
+       );
 void Deemph2(
-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
-		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
-		Word16 L,                             /* (i)     : vector size                            */
-		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
-	    );
+        Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+        Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
+        Word16 L,                             /* (i)     : vector size                            */
+        Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
+        );
 void Deemph_32(
-		Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
-		Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
-		Word16 y[],                           /* (o)     : output signal (x16)      */
-		Word16 mu,                            /* (i) Q15 : deemphasis factor        */
-		Word16 L,                             /* (i)     : vector size              */
-		Word16 * mem                          /* (i/o)   : memory (y[-1])           */
-	      );
+        Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+        Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+        Word16 y[],                           /* (o)     : output signal (x16)      */
+        Word16 mu,                            /* (i) Q15 : deemphasis factor        */
+        Word16 L,                             /* (i)     : vector size              */
+        Word16 * mem                          /* (i/o)   : memory (y[-1])           */
+          );
 
 void Deemph_32_asm(
-		Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
-		Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
-		Word16 y[],                           /* (o)     : output signal (x16)      */
-		Word16 * mem                          /* (i/o)   : memory (y[-1])           */
-	      );
+        Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+        Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+        Word16 y[],                           /* (o)     : output signal (x16)      */
+        Word16 * mem                          /* (i/o)   : memory (y[-1])           */
+          );
 
 void Convolve(
-		Word16 x[],                           /* (i)     : input vector                              */
-		Word16 h[],                           /* (i) Q15    : impulse response                       */
-		Word16 y[],                           /* (o) 12 bits: output vector                          */
-		Word16 L                              /* (i)     : vector size                               */
-	     );
+        Word16 x[],                           /* (i)     : input vector                              */
+        Word16 h[],                           /* (i) Q15    : impulse response                       */
+        Word16 y[],                           /* (o) 12 bits: output vector                          */
+        Word16 L                              /* (i)     : vector size                               */
+         );
 
 void Convolve_asm(
-		Word16 x[],                           /* (i)     : input vector                              */
-		Word16 h[],                           /* (i) Q15    : impulse response                       */
-		Word16 y[],                           /* (o) 12 bits: output vector                          */
-		Word16 L                              /* (i)     : vector size                               */
-	     );
+        Word16 x[],                           /* (i)     : input vector                              */
+        Word16 h[],                           /* (i) Q15    : impulse response                       */
+        Word16 y[],                           /* (o) 12 bits: output vector                          */
+        Word16 L                              /* (i)     : vector size                               */
+         );
 
 void Residu(
-		Word16 a[],                           /* (i) Q12 : prediction coefficients                     */
-		Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */
-		Word16 y[],                           /* (o)     : residual signal                             */
-		Word16 lg                             /* (i)     : size of filtering                           */
-		);
+        Word16 a[],                           /* (i) Q12 : prediction coefficients                     */
+        Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */
+        Word16 y[],                           /* (o)     : residual signal                             */
+        Word16 lg                             /* (i)     : size of filtering                           */
+        );
 
 void Residu_opt(
-		Word16 a[],                           /* (i) Q12 : prediction coefficients                     */
-		Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */
-		Word16 y[],                           /* (o)     : residual signal                             */
-		Word16 lg                             /* (i)     : size of filtering                           */
-		);
+        Word16 a[],                           /* (i) Q12 : prediction coefficients                     */
+        Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */
+        Word16 y[],                           /* (o)     : residual signal                             */
+        Word16 lg                             /* (i)     : size of filtering                           */
+        );
 
 void Syn_filt(
-	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
-	Word16 x[],                           /* (i)     : input signal                             */
-	Word16 y[],                           /* (o)     : output signal                            */
-	Word16 lg,                            /* (i)     : size of filtering                        */
-	Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */
-	Word16 update                         /* (i)     : 0=no update, 1=update of memory.         */
-	);
+    Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
+    Word16 x[],                           /* (i)     : input signal                             */
+    Word16 y[],                           /* (o)     : output signal                            */
+    Word16 lg,                            /* (i)     : size of filtering                        */
+    Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */
+    Word16 update                         /* (i)     : 0=no update, 1=update of memory.         */
+    );
 
 void Syn_filt_asm(
-	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
-	Word16 x[],                           /* (i)     : input signal                             */
-	Word16 y[],                           /* (o)     : output signal                            */
-	Word16 mem[]                          /* (i/o)   : memory associated with this filtering.   */
-	);
+    Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
+    Word16 x[],                           /* (i)     : input signal                             */
+    Word16 y[],                           /* (o)     : output signal                            */
+    Word16 mem[]                          /* (i/o)   : memory associated with this filtering.   */
+    );
 
 void Syn_filt_32(
-	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
-	Word16 m,                             /* (i)     : order of LP filter             */
-	Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
-	Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
-	Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
-	Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
-	Word16 lg                             /* (i)     : size of filtering              */
-	);
+    Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
+    Word16 m,                             /* (i)     : order of LP filter             */
+    Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+    Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
+    Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
+    Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
+    Word16 lg                             /* (i)     : size of filtering              */
+    );
 
 void Syn_filt_32_asm(
-	Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
-	Word16 m,                             /* (i)     : order of LP filter             */
-	Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
-	Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
-	Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
-	Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
-	Word16 lg                             /* (i)     : size of filtering              */
-	);
+    Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
+    Word16 m,                             /* (i)     : order of LP filter             */
+    Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+    Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
+    Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
+    Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
+    Word16 lg                             /* (i)     : size of filtering              */
+    );
 /*-----------------------------------------------------------------*
  *                       pitch prototypes                          *
  *-----------------------------------------------------------------*/
@@ -443,12 +443,12 @@
      Word16 nbbits,                        /* (i) : 20, 36, 44, 52, 64, 72 or 88 bits                */
      Word16 ser_size,                      /* (i) : bit rate                                         */
      Word16 _index[]                       /* (o) : index (20): 5+5+5+5 = 20 bits.                   */
-					   /* (o) : index (36): 9+9+9+9 = 36 bits.                   */
-					   /* (o) : index (44): 13+9+13+9 = 44 bits.                 */
-					   /* (o) : index (52): 13+13+13+13 = 52 bits.               */
-					   /* (o) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.       */
-					   /* (o) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.     */
-					   /* (o) : index (88): 11+11+11+11+11+11+11+11 = 88 bits.   */
+                       /* (o) : index (36): 9+9+9+9 = 36 bits.                   */
+                       /* (o) : index (44): 13+9+13+9 = 44 bits.                 */
+                       /* (o) : index (52): 13+13+13+13 = 52 bits.               */
+                       /* (o) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.       */
+                       /* (o) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.     */
+                       /* (o) : index (88): 11+11+11+11+11+11+11+11 = 88 bits.   */
 );
 
 void Pit_shrp(
diff --git a/media/libstagefright/codecs/amrwbenc/inc/basic_op.h b/media/libstagefright/codecs/amrwbenc/inc/basic_op.h
index efa4a96..80ad7f1 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/basic_op.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/basic_op.h
@@ -25,8 +25,8 @@
 #define MAX_32 (Word32)0x7fffffffL
 #define MIN_32 (Word32)0x80000000L
 
-#define MAX_16 (Word16)+32767	/* 0x7fff */
-#define MIN_16 (Word16)-32768	/* 0x8000 */
+#define MAX_16 ((Word16)+32767)   /* 0x7fff */
+#define MIN_16 ((Word16)-32768)   /* 0x8000 */
 
 
 #define  static_vo  static __inline
@@ -41,23 +41,23 @@
 #define L_negate(L_var1) (((L_var1) == (MIN_32)) ? (MAX_32) : (-(L_var1)))                 /* Long negate,     2*/
 
 
-#define extract_h(a)			((Word16)(a >> 16))
-#define extract_l(x)            	(Word16)((x))
-#define add1(a,b)			(a + b)
-#define vo_L_msu(a,b,c)			( a - (( b * c ) << 1) )
+#define extract_h(a)            ((Word16)((a) >> 16))
+#define extract_l(x)            (Word16)((x))
+#define add1(a,b)               ((a) + (b))
+#define vo_L_msu(a,b,c)         ((a) - (((b) * (c)) << 1))
 #define vo_mult32(a, b)         ((a) * (b))
-#define vo_mult(a,b)			(( a * b ) >> 15 )
-#define	vo_L_mult(a,b)	    		(((a) * (b)) << 1)
-#define vo_shr_r(var1, var2)   		((var1+((Word16)(1L<<(var2-1))))>>var2)
-#define vo_sub(a,b)			(a - b)
-#define vo_L_deposit_h(a)		((Word32)((a) << 16))
-#define vo_round(a)			((a + 0x00008000) >> 16)
-#define vo_extract_l(a)			((Word16)(a))
-#define vo_L_add(a,b)			(a + b)
-#define vo_L_sub(a,b)			(a - b)
-#define vo_mult_r(a,b)			((( a * b ) + 0x4000 ) >> 15 )
-#define vo_negate(a)		        (-a)
-#define vo_L_shr_r(L_var1, var2)        ((L_var1+((Word32)(1L<<(var2-1))))>>var2)
+#define vo_mult(a,b)            (((a) * (b)) >> 15)
+#define vo_L_mult(a,b)          (((a) * (b)) << 1)
+#define vo_shr_r(var1, var2)    (((var1)+((Word16)(1L<<((var2)-1))))>>(var2))
+#define vo_sub(a,b)             ((a) - (b))
+#define vo_L_deposit_h(a)       ((Word32)((a) << 16))
+#define vo_round(a)             ((((a) >> 15) + 1) >> 1)
+#define vo_extract_l(a)         ((Word16)(a))
+#define vo_L_add(a,b)           ((a) + (b))
+#define vo_L_sub(a,b)           ((a) - (b))
+#define vo_mult_r(a,b)          (((( (a) * (b) ) >> 14) + 1 ) >> 1 )
+#define vo_negate(a)            (-(a))
+#define vo_L_shr_r(L_var1, var2) (((L_var1)+((Word32)(1L<<((var2)-1))))>>(var2))
 
 
 /*___________________________________________________________________________
@@ -65,25 +65,25 @@
 |   Prototypes for basic arithmetic operators                               |
 |___________________________________________________________________________|
 */
-static_vo Word16 add (Word16 var1, Word16 var2);				/* Short add,1 */
-static_vo Word16 sub (Word16 var1, Word16 var2);				/* Short sub,1 */
+static_vo Word16 add (Word16 var1, Word16 var2);                /* Short add,1 */
+static_vo Word16 sub (Word16 var1, Word16 var2);                /* Short sub,1 */
 static_vo Word16 shl (Word16 var1, Word16 var2);                                /* Short shift left,    1   */
 static_vo Word16 shr (Word16 var1, Word16 var2);                                /* Short shift right,   1   */
 static_vo Word16 mult (Word16 var1, Word16 var2);                               /* Short mult,          1   */
 static_vo Word32 L_mult (Word16 var1, Word16 var2);                             /* Long mult,           1   */
 static_vo Word16 voround (Word32 L_var1);                                       /* Round,               1   */
-static_vo Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);            	/* Mac,  1  */
-static_vo Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);   		/* Msu,  1  */
-static_vo Word32 L_add (Word32 L_var1, Word32 L_var2);   		 	/* Long add,        2 */
-static_vo Word32 L_sub (Word32 L_var1, Word32 L_var2);   			/* Long sub,        2 */
-static_vo Word16 mult_r (Word16 var1, Word16 var2);      		 	/* Mult with round, 2 */
-static_vo Word32 L_shl2(Word32 L_var1, Word16 var2);             		/* var2 > 0*/
-static_vo Word32 L_shl (Word32 L_var1, Word16 var2);    	 	 	/* Long shift left, 2 */
-static_vo Word32 L_shr (Word32 L_var1, Word16 var2);    	 	 	/* Long shift right, 2*/
-static_vo Word32 L_shr_r (Word32 L_var1, Word16 var2); 				/* Long shift right with round,  3   */
-static_vo Word16 norm_s (Word16 var1);             				/* Short norm,           15  */
-static_vo Word16 div_s (Word16 var1, Word16 var2); 				/* Short division,       18  */
-static_vo Word16 norm_l (Word32 L_var1);           				/* Long norm,            30  */
+static_vo Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2);               /* Mac,  1  */
+static_vo Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2);           /* Msu,  1  */
+static_vo Word32 L_add (Word32 L_var1, Word32 L_var2);              /* Long add,        2 */
+static_vo Word32 L_sub (Word32 L_var1, Word32 L_var2);              /* Long sub,        2 */
+static_vo Word16 mult_r (Word16 var1, Word16 var2);                 /* Mult with round, 2 */
+static_vo Word32 L_shl2(Word32 L_var1, Word16 var2);                    /* var2 > 0*/
+static_vo Word32 L_shl (Word32 L_var1, Word16 var2);                /* Long shift left, 2 */
+static_vo Word32 L_shr (Word32 L_var1, Word16 var2);                /* Long shift right, 2*/
+static_vo Word32 L_shr_r (Word32 L_var1, Word16 var2);              /* Long shift right with round,  3   */
+static_vo Word16 norm_s (Word16 var1);                          /* Short norm,           15  */
+static_vo Word16 div_s (Word16 var1, Word16 var2);              /* Short division,       18  */
+static_vo Word16 norm_l (Word32 L_var1);                        /* Long norm,            30  */
 
 /*___________________________________________________________________________
 |                                                                           |
@@ -125,11 +125,11 @@
 */
 static_vo Word16 add (Word16 var1, Word16 var2)
 {
-	Word16 var_out;
-	Word32 L_sum;
-	L_sum = (Word32) var1 + var2;
-	var_out = saturate (L_sum);
-	return (var_out);
+    Word16 var_out;
+    Word32 L_sum;
+    L_sum = (Word32) var1 + var2;
+    var_out = saturate (L_sum);
+    return (var_out);
 }
 
 /*___________________________________________________________________________
@@ -168,11 +168,11 @@
 
 static_vo 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);
+    Word16 var_out;
+    Word32 L_diff;
+    L_diff = (Word32) var1 - var2;
+    var_out = saturate (L_diff);
+    return (var_out);
 }
 
 /*___________________________________________________________________________
@@ -212,27 +212,31 @@
 
 static_vo Word16 shl (Word16 var1, Word16 var2)
 {
-	Word16 var_out;
-	Word32 result;
-	if (var2 < 0)
-	{
-		if (var2 < -16)
-			var2 = -16;
-		var_out = 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);
+    Word16 var_out;
+    Word32 result;
+    if (var2 < 0)
+    {
+        if (var2 < -16)
+            var2 = -16;
+        var_out = var1 >> ((Word16)-var2);
+    }
+    else
+    {
+        if (var2 > 15 && var1 != 0)
+        {
+            var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);
+        }
+        else
+        {
+            result = (Word32) var1 *((Word32) 1 << var2);
+            if ((result != (Word32) ((Word16) result))) {
+                var_out = (Word16)((var1 > 0) ? MAX_16 : MIN_16);
+            } else {
+                var_out = extract_l (result);
+            }
+        }
+    }
+    return (var_out);
 }
 
 /*___________________________________________________________________________
@@ -272,32 +276,32 @@
 
 static_vo 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);
+    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);
 }
 
 /*___________________________________________________________________________
@@ -337,14 +341,14 @@
 
 static_vo 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);
+    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);
 }
 
 /*___________________________________________________________________________
@@ -384,17 +388,17 @@
 
 static_vo 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 *= 2;
-	}
-	else
-	{
-		L_var_out = MAX_32;
-	}
-	return (L_var_out);
+    Word32 L_var_out;
+    L_var_out = (Word32) var1 *(Word32) var2;
+    if (L_var_out != (Word32) 0x40000000L)
+    {
+        L_var_out *= 2;
+    }
+    else
+    {
+        L_var_out = MAX_32;
+    }
+    return (L_var_out);
 }
 
 /*___________________________________________________________________________
@@ -430,11 +434,11 @@
 
 static_vo Word16 voround (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);
+    Word16 var_out;
+    Word32 L_rounded;
+    L_rounded = L_add (L_var1, (Word32) 0x00008000L);
+    var_out = extract_h (L_rounded);
+    return (var_out);
 }
 
 /*___________________________________________________________________________
@@ -476,11 +480,11 @@
 
 static_vo Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2)
 {
-	Word32 L_var_out;
-	Word32 L_product;
-	L_product = ((var1 * var2) << 1);
-	L_var_out = L_add (L_var3, L_product);
-	return (L_var_out);
+    Word32 L_var_out;
+    Word32 L_product;
+    L_product = ((var1 * var2) << 1);
+    L_var_out = L_add (L_var3, L_product);
+    return (L_var_out);
 }
 
 /*___________________________________________________________________________
@@ -522,11 +526,11 @@
 
 static_vo Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2)
 {
-	Word32 L_var_out;
-	Word32 L_product;
-	L_product = (var1 * var2)<<1;
-	L_var_out = L_sub (L_var3, L_product);
-	return (L_var_out);
+    Word32 L_var_out;
+    Word32 L_product;
+    L_product = (var1 * var2)<<1;
+    L_var_out = L_sub (L_var3, L_product);
+    return (L_var_out);
 }
 
 /*___________________________________________________________________________
@@ -564,16 +568,16 @@
 __attribute__((no_sanitize("integer")))
 static_vo 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;
-		}
-	}
-	return (L_var_out);
+    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);
 }
 
 /*___________________________________________________________________________
@@ -608,18 +612,19 @@
 |___________________________________________________________________________|
 */
 
+__attribute__((no_sanitize("integer")))
 static_vo 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;
-		}
-	}
-	return (L_var_out);
+    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);
 }
 
 
@@ -659,18 +664,18 @@
 
 static_vo 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);
+    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);
 }
 
 /*___________________________________________________________________________
@@ -709,61 +714,61 @@
 
 static_vo Word32 L_shl (Word32 L_var1, Word16 var2)
 {
-	Word32 L_var_out = 0L;
-	if (var2 <= 0)
-	{
-		if (var2 < -32)
-			var2 = -32;
-		L_var_out = (L_var1 >> (Word16)-var2);
-	}
-	else
-	{
-		for (; var2 > 0; var2--)
-		{
-			if (L_var1 > (Word32) 0X3fffffffL)
-			{
-				L_var_out = MAX_32;
-				break;
-			}
-			else
-			{
-				if (L_var1 < (Word32) 0xc0000000L)
-				{
-					//Overflow = 1;
-					L_var_out = MIN_32;
-					break;
-				}
-			}
-			L_var1 *= 2;
-			L_var_out = L_var1;
-		}
-	}
-	return (L_var_out);
+    Word32 L_var_out = 0L;
+    if (var2 <= 0)
+    {
+        if (var2 < -32)
+            var2 = -32;
+        L_var_out = (L_var1 >> (Word16)-var2);
+    }
+    else
+    {
+        for (; var2 > 0; var2--)
+        {
+            if (L_var1 > (Word32) 0X3fffffffL)
+            {
+                L_var_out = MAX_32;
+                break;
+            }
+            else
+            {
+                if (L_var1 < (Word32) 0xc0000000L)
+                {
+                    //Overflow = 1;
+                    L_var_out = MIN_32;
+                    break;
+                }
+            }
+            L_var1 *= 2;
+            L_var_out = L_var1;
+        }
+    }
+    return (L_var_out);
 }
 
 static_vo Word32 L_shl2(Word32 L_var1, Word16 var2)
 {
-	Word32 L_var_out = 0L;
+    Word32 L_var_out = 0L;
 
-	for (; var2 > 0; var2--)
-	{
-		if (L_var1 > (Word32) 0X3fffffffL)
-		{
-			L_var_out = MAX_32;
-			break;
-		}
-		else
-		{
-			if (L_var1 < (Word32) 0xc0000000L)
-			{
-				L_var_out = MIN_32;
-				break;
-			}
-		}
-		L_var1 <<=1 ;
-		L_var_out = L_var1;
-	}
-	return (L_var_out);
+    for (; var2 > 0; var2--)
+    {
+        if (L_var1 > (Word32) 0X3fffffffL)
+        {
+            L_var_out = MAX_32;
+            break;
+        }
+        else
+        {
+            if (L_var1 < (Word32) 0xc0000000L)
+            {
+                L_var_out = MIN_32;
+                break;
+            }
+        }
+        L_var1 *= 2 ;
+        L_var_out = L_var1;
+    }
+    return (L_var_out);
 }
 
 /*___________________________________________________________________________
@@ -802,32 +807,32 @@
 
 static_vo Word32 L_shr (Word32 L_var1, Word16 var2)
 {
-	Word32 L_var_out;
-	if (var2 < 0)
-	{
-		if (var2 < -32)
-			var2 = -32;
-		L_var_out = L_shl2(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);
+    Word32 L_var_out;
+    if (var2 < 0)
+    {
+        if (var2 < -32)
+            var2 = -32;
+        L_var_out = L_shl2(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);
 }
 
 /*___________________________________________________________________________
@@ -874,23 +879,23 @@
 
 static_vo 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);
+    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);
 }
 
 /*___________________________________________________________________________
@@ -928,30 +933,30 @@
 
 static_vo Word16 norm_s (Word16 var1)
 {
-	Word16 var_out = 0;
-	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);
+    Word16 var_out = 0;
+    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);
 }
 
 /*___________________________________________________________________________
@@ -993,47 +998,47 @@
 
 static_vo Word16 div_s (Word16 var1, Word16 var2)
 {
-	Word16 var_out = 0;
-	Word16 iteration;
-	Word32 L_num;
-	Word32 L_denom;
-	if ((var1 < 0) || (var2 < 0))
-	{
-		var_out = MAX_16;
-		return var_out;
-	}
-	if (var2 == 0)
-	{
-		var_out = MAX_16;
-		return var_out;
-	}
-	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_denom;
-					var_out += 1;
-				}
-			}
-		}
-	}
-	return (var_out);
+    Word16 var_out = 0;
+    Word16 iteration;
+    Word32 L_num;
+    Word32 L_denom;
+    if ((var1 < 0) || (var2 < 0))
+    {
+        var_out = MAX_16;
+        return var_out;
+    }
+    if (var2 == 0)
+    {
+        var_out = MAX_16;
+        return var_out;
+    }
+    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_denom;
+                    var_out += 1;
+                }
+            }
+        }
+    }
+    return (var_out);
 }
 
 /*___________________________________________________________________________
@@ -1071,20 +1076,20 @@
 
 static_vo Word16 norm_l (Word32 L_var1)
 {
-	Word16 var_out = 0;
-	if (L_var1 != 0)
-	{
-		var_out = 31;
-		if (L_var1 != (Word32) 0xffffffffL)
-		{
-			L_var1 ^= (L_var1 >>31);
-			for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++)
-			{
-				L_var1 <<= 1;
-			}
-		}
-	}
-	return (var_out);
+    Word16 var_out = 0;
+    if (L_var1 != 0)
+    {
+        var_out = 31;
+        if (L_var1 != (Word32) 0xffffffffL)
+        {
+            L_var1 ^= (L_var1 >>31);
+            for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++)
+            {
+                L_var1 <<= 1;
+            }
+        }
+    }
+    return (var_out);
 }
 
 #endif //__BASIC_OP_H__
diff --git a/media/libstagefright/codecs/amrwbenc/inc/bits.h b/media/libstagefright/codecs/amrwbenc/inc/bits.h
index e880684..57e71f7 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/bits.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/bits.h
@@ -18,7 +18,7 @@
 /*--------------------------------------------------------------------------*
 *                         BITS.H                                           *
 *--------------------------------------------------------------------------*
-*       Number of bits for different modes			           *
+*       Number of bits for different modes                     *
 *--------------------------------------------------------------------------*/
 
 #ifndef __BITS_H__
@@ -42,7 +42,7 @@
 #define NBBITS_SID    35
 #define NB_BITS_MAX   NBBITS_24k
 
-#define BIT_0     (Word16)-127
+#define BIT_0     ((Word16)-127)
 #define BIT_1     (Word16)127
 #define BIT_0_ITU (Word16)0x007F
 #define BIT_1_ITU (Word16)0x0081
@@ -52,16 +52,16 @@
 #define RX_FRAME_TYPE (Word16)0x6b20
 
 static const Word16 nb_of_bits[NUM_OF_MODES] = {
-	NBBITS_7k,
-	NBBITS_9k,
-	NBBITS_12k,
-	NBBITS_14k,
-	NBBITS_16k,
-	NBBITS_18k,
-	NBBITS_20k,
-	NBBITS_23k,
-	NBBITS_24k,
-	NBBITS_SID
+    NBBITS_7k,
+    NBBITS_9k,
+    NBBITS_12k,
+    NBBITS_14k,
+    NBBITS_16k,
+    NBBITS_18k,
+    NBBITS_20k,
+    NBBITS_23k,
+    NBBITS_24k,
+    NBBITS_SID
 };
 
 /*typedef struct
@@ -74,18 +74,18 @@
 
 //typedef struct
 //{
-//	Word16 prev_ft;
-//	Word16 prev_mode;
+//  Word16 prev_ft;
+//  Word16 prev_mode;
 //} RX_State;
 
 int PackBits(Word16 prms[], Word16 coding_mode, Word16 mode, Coder_State *st);
 
 
 void Parm_serial(
-		Word16 value,                         /* input : parameter value */
-		Word16 no_of_bits,                    /* input : number of bits  */
-		Word16 ** prms
-		);
+        Word16 value,                         /* input : parameter value */
+        Word16 no_of_bits,                    /* input : number of bits  */
+        Word16 ** prms
+        );
 
 
 #endif  //__BITS_H__
diff --git a/media/libstagefright/codecs/amrwbenc/inc/cod_main.h b/media/libstagefright/codecs/amrwbenc/inc/cod_main.h
index 53ca55e..170981e 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/cod_main.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/cod_main.h
@@ -18,7 +18,7 @@
 /*--------------------------------------------------------------------------*
  *                         COD_MAIN.H                                       *
  *--------------------------------------------------------------------------*
- *       Static memory in the encoder				            *
+ *       Static memory in the encoder                           *
  *--------------------------------------------------------------------------*/
 #ifndef __COD_MAIN_H__
 #define __COD_MAIN_H__
@@ -79,21 +79,21 @@
     Word16 vad_hist;
     Word16 gain_alpha;
     /*  TX_State structure  */
-	Word16 sid_update_counter;
+    Word16 sid_update_counter;
     Word16 sid_handover_debt;
     Word16 prev_ft;
-	Word16 allow_dtx;
-	/*some input/output buffer parameters */
-	unsigned char       *inputStream;
-	int			        inputSize;
-	VOAMRWBMODE  		mode;
-	VOAMRWBFRAMETYPE	frameType;
-	unsigned short      *outputStream;
-	int			        outputSize;
-	FrameStream         *stream;
-	VO_MEM_OPERATOR     *pvoMemop;
-	VO_MEM_OPERATOR     voMemoprator;
-	VO_PTR              hCheck;
+    Word16 allow_dtx;
+    /*some input/output buffer parameters */
+    unsigned char       *inputStream;
+    int                 inputSize;
+    VOAMRWBMODE         mode;
+    VOAMRWBFRAMETYPE    frameType;
+    unsigned short      *outputStream;
+    int                 outputSize;
+    FrameStream         *stream;
+    VO_MEM_OPERATOR     *pvoMemop;
+    VO_MEM_OPERATOR     voMemoprator;
+    VO_PTR              hCheck;
 } Coder_State;
 
 typedef void* HAMRENC;
diff --git a/media/libstagefright/codecs/amrwbenc/inc/dtx.h b/media/libstagefright/codecs/amrwbenc/inc/dtx.h
index 0bdda67..7d7ebd8 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/dtx.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/dtx.h
@@ -16,9 +16,9 @@
 
 
 /*--------------------------------------------------------------------------*
- *                         DTX.H					    *
+ *                         DTX.H                        *
  *--------------------------------------------------------------------------*
- *       Static memory, constants and frametypes for the DTX 		    *
+ *       Static memory, constants and frametypes for the DTX            *
  *--------------------------------------------------------------------------*/
 
 #ifndef __DTX_H__
@@ -31,7 +31,7 @@
 #define DTX_HANG_CONST 7                   /* yields eight frames of SP HANGOVER  */
 #define INV_MED_THRESH 14564
 #define ISF_GAP  128                       /* 50 */
-#define ONE_MINUS_ISF_GAP 16384 - ISF_GAP
+#define ONE_MINUS_ISF_GAP (16384 - ISF_GAP)
 #define ISF_GAP   128
 #define ISF_DITH_GAP   448
 #define ISF_FACTOR_LOW 256
diff --git a/media/libstagefright/codecs/amrwbenc/inc/homing.tab b/media/libstagefright/codecs/amrwbenc/inc/homing.tab
index e399fb8..6408d3a 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/homing.tab
+++ b/media/libstagefright/codecs/amrwbenc/inc/homing.tab
@@ -21,15 +21,15 @@
 #define NUM_OF_SPMODES 9
 
 #define PRML 15
-#define PRMN_7k NBBITS_7k/PRML + 1
-#define PRMN_9k NBBITS_9k/PRML + 1
-#define PRMN_12k NBBITS_12k/PRML + 1
-#define PRMN_14k NBBITS_14k/PRML + 1
-#define PRMN_16k NBBITS_16k/PRML + 1
-#define PRMN_18k NBBITS_18k/PRML + 1
-#define PRMN_20k NBBITS_20k/PRML + 1
-#define PRMN_23k NBBITS_23k/PRML + 1
-#define PRMN_24k NBBITS_24k/PRML + 1
+#define PRMN_7k (NBBITS_7k/PRML + 1)
+#define PRMN_9k (NBBITS_9k/PRML + 1)
+#define PRMN_12k (NBBITS_12k/PRML + 1)
+#define PRMN_14k (NBBITS_14k/PRML + 1)
+#define PRMN_16k (NBBITS_16k/PRML + 1)
+#define PRMN_18k (NBBITS_18k/PRML + 1)
+#define PRMN_20k (NBBITS_20k/PRML + 1)
+#define PRMN_23k (NBBITS_23k/PRML + 1)
+#define PRMN_24k (NBBITS_24k/PRML + 1)
 
 static const Word16 dfh_M7k[PRMN_7k] =
 {
diff --git a/media/libstagefright/codecs/amrwbenc/inc/log2.h b/media/libstagefright/codecs/amrwbenc/inc/log2.h
index b065eb4..3d9a6c4 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/log2.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/log2.h
@@ -45,17 +45,17 @@
 ********************************************************************************
 */
 void Log2 (
-		Word32 L_x,        /* (i) : input value                                 */
-		Word16 *exponent,  /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
-		Word16 *fraction   /* (o) : Fractional part of Log2. (range: 0<=val<1)*/
-	  );
+        Word32 L_x,        /* (i) : input value                                 */
+        Word16 *exponent,  /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+        Word16 *fraction   /* (o) : Fractional part of Log2. (range: 0<=val<1)*/
+      );
 
 void Log2_norm (
-		Word32 L_x,         /* (i) : input value (normalized)                    */
-		Word16 exp,         /* (i) : norm_l (L_x)                                */
-		Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
-		Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */
-	       );
+        Word32 L_x,         /* (i) : input value (normalized)                    */
+        Word16 exp,         /* (i) : norm_l (L_x)                                */
+        Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+        Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */
+           );
 
 #endif  //__LOG2_H__
 
diff --git a/media/libstagefright/codecs/amrwbenc/inc/main.h b/media/libstagefright/codecs/amrwbenc/inc/main.h
index 3a6f963..adef2df 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/main.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/main.h
@@ -17,9 +17,9 @@
 
 
 /*--------------------------------------------------------------------------*
- *                         MAIN.H	                                    *
+ *                         MAIN.H                                       *
  *--------------------------------------------------------------------------*
- *       Main functions							    *
+ *       Main functions                             *
  *--------------------------------------------------------------------------*/
 
 #ifndef __MAIN_H__
diff --git a/media/libstagefright/codecs/amrwbenc/inc/math_op.h b/media/libstagefright/codecs/amrwbenc/inc/math_op.h
index 7b6196b..c3c00bc 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/math_op.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/math_op.h
@@ -16,40 +16,40 @@
 
 
 /*--------------------------------------------------------------------------*
- *                         MATH_OP.H	                                    *
+ *                         MATH_OP.H                                        *
  *--------------------------------------------------------------------------*
- *       Mathematical operations					    *
+ *       Mathematical operations                        *
  *--------------------------------------------------------------------------*/
 
 #ifndef __MATH_OP_H__
 #define __MATH_OP_H__
 
 Word32 Isqrt(                              /* (o) Q31 : output value (range: 0<=val<1)         */
-		Word32 L_x                            /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */
-	    );
+        Word32 L_x                            /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */
+        );
 
 void Isqrt_n(
-		Word32 * frac,                        /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */
-		Word16 * exp                          /* (i/o)    : exponent (value = frac x 2^exponent) */
-	    );
+        Word32 * frac,                        /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */
+        Word16 * exp                          /* (i/o)    : exponent (value = frac x 2^exponent) */
+        );
 
 Word32 Pow2(                               /* (o) Q0  : result       (range: 0<=val<=0x7fffffff) */
-		Word16 exponant,                      /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */
-		Word16 fraction                       /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */
-	   );
+        Word16 exponant,                      /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */
+        Word16 fraction                       /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */
+       );
 
 Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */
-		Word16 x[],                           /* (i) 12bits: x vector                       */
-		Word16 y[],                           /* (i) 12bits: y vector                       */
-		Word16 lg,                            /* (i)    : vector length                     */
-		Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
-		);
+        Word16 x[],                           /* (i) 12bits: x vector                       */
+        Word16 y[],                           /* (i) 12bits: y vector                       */
+        Word16 lg,                            /* (i)    : vector length                     */
+        Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
+        );
 
 Word32 Dot_product12_asm(                      /* (o) Q31: normalized result (1 < val <= -1) */
-		Word16 x[],                           /* (i) 12bits: x vector                       */
-		Word16 y[],                           /* (i) 12bits: y vector                       */
-		Word16 lg,                            /* (i)    : vector length                     */
-		Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
-		);
+        Word16 x[],                           /* (i) 12bits: x vector                       */
+        Word16 y[],                           /* (i) 12bits: y vector                       */
+        Word16 lg,                            /* (i)    : vector length                     */
+        Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
+        );
 #endif //__MATH_OP_H__
 
diff --git a/media/libstagefright/codecs/amrwbenc/inc/mem_align.h b/media/libstagefright/codecs/amrwbenc/inc/mem_align.h
index 442786a..2ae5a6c 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/mem_align.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/mem_align.h
@@ -14,9 +14,9 @@
  ** limitations under the License.
  */
 /*******************************************************************************
-	File:		mem_align.h
+    File:       mem_align.h
 
-	Content:	Memory alloc alignments functions
+    Content:    Memory alloc alignments functions
 
 *******************************************************************************/
 
@@ -29,7 +29,7 @@
 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__ */
+#endif  /* __VO_MEM_ALIGN_H__ */
 
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/inc/p_med_o.h b/media/libstagefright/codecs/amrwbenc/inc/p_med_o.h
index 4a13f16..77487ed 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/p_med_o.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/p_med_o.h
@@ -17,36 +17,36 @@
 /*--------------------------------------------------------------------------*
  *                         P_MED_O.H                                        *
  *--------------------------------------------------------------------------*
- *       Median open-loop lag search				            *
+ *       Median open-loop lag search                            *
  *--------------------------------------------------------------------------*/
 
 #ifndef __P_MED_O_H__
 #define __P_MED_O_H__
 
 Word16 Pitch_med_ol(                       /* output: open loop pitch lag                        */
-		Word16 wsp[],                         /* input : signal used to compute the open loop pitch */
-		/* wsp[-pit_max] to wsp[-1] should be known   */
-		Word16 L_min,                         /* input : minimum pitch lag                          */
-		Word16 L_max,                         /* input : maximum pitch lag                          */
-		Word16 L_frame,                       /* input : length of frame to compute pitch           */
-		Word16 L_0,                           /* input : old_ open-loop pitch                       */
-		Word16 * gain,                        /* output: normalize correlation of hp_wsp for the Lag */
-		Word16 * hp_wsp_mem,                  /* i:o   : memory of the hypass filter for hp_wsp[] (lg=9)   */
-		Word16 * old_hp_wsp,                  /* i:o   : hypass wsp[]                               */
-		Word16 wght_flg                       /* input : is weighting function used                 */
-		);
+        Word16 wsp[],                         /* input : signal used to compute the open loop pitch */
+        /* wsp[-pit_max] to wsp[-1] should be known   */
+        Word16 L_min,                         /* input : minimum pitch lag                          */
+        Word16 L_max,                         /* input : maximum pitch lag                          */
+        Word16 L_frame,                       /* input : length of frame to compute pitch           */
+        Word16 L_0,                           /* input : old_ open-loop pitch                       */
+        Word16 * gain,                        /* output: normalize correlation of hp_wsp for the Lag */
+        Word16 * hp_wsp_mem,                  /* i:o   : memory of the hypass filter for hp_wsp[] (lg=9)   */
+        Word16 * old_hp_wsp,                  /* i:o   : hypass wsp[]                               */
+        Word16 wght_flg                       /* input : is weighting function used                 */
+        );
 
 Word16 Med_olag(                           /* output : median of  5 previous open-loop lags       */
-		Word16 prev_ol_lag,                   /* input  : previous open-loop lag                     */
-		Word16 old_ol_lag[5]
-	       );
+        Word16 prev_ol_lag,                   /* input  : previous open-loop lag                     */
+        Word16 old_ol_lag[5]
+           );
 
 void Hp_wsp(
-		Word16 wsp[],                         /* i   : wsp[]  signal       */
-		Word16 hp_wsp[],                      /* o   : hypass wsp[]        */
-		Word16 lg,                            /* i   : lenght of signal    */
-		Word16 mem[]                          /* i/o : filter memory [9]   */
-	   );
+        Word16 wsp[],                         /* i   : wsp[]  signal       */
+        Word16 hp_wsp[],                      /* o   : hypass wsp[]        */
+        Word16 lg,                            /* i   : lenght of signal    */
+        Word16 mem[]                          /* i/o : filter memory [9]   */
+       );
 
 #endif  //__P_MED_O_H__
 
diff --git a/media/libstagefright/codecs/amrwbenc/inc/q_pulse.h b/media/libstagefright/codecs/amrwbenc/inc/q_pulse.h
index b5d5280..67140fc 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/q_pulse.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/q_pulse.h
@@ -19,7 +19,7 @@
 /*--------------------------------------------------------------------------*
  *                         Q_PULSE.H                                        *
  *--------------------------------------------------------------------------*
- * Coding and decoding of algebraic codebook			            *
+ * Coding and decoding of algebraic codebook                        *
  *--------------------------------------------------------------------------*/
 
 #ifndef  __Q_PULSE_H__
@@ -28,38 +28,38 @@
 #include "typedef.h"
 
 Word32 quant_1p_N1(                        /* (o) return (N+1) bits           */
-		Word16 pos,                           /* (i) position of the pulse       */
-		Word16 N);                            /* (i) number of bits for position */
+        Word16 pos,                           /* (i) position of the pulse       */
+        Word16 N);                            /* (i) number of bits for position */
 
 Word32 quant_2p_2N1(                       /* (o) return (2*N)+1 bits         */
-		Word16 pos1,                          /* (i) position of the pulse 1     */
-		Word16 pos2,                          /* (i) position of the pulse 2     */
-		Word16 N);                            /* (i) number of bits for position */
+        Word16 pos1,                          /* (i) position of the pulse 1     */
+        Word16 pos2,                          /* (i) position of the pulse 2     */
+        Word16 N);                            /* (i) number of bits for position */
 
 Word32 quant_3p_3N1(                       /* (o) return (3*N)+1 bits         */
-		Word16 pos1,                          /* (i) position of the pulse 1     */
-		Word16 pos2,                          /* (i) position of the pulse 2     */
-		Word16 pos3,                          /* (i) position of the pulse 3     */
-		Word16 N);                            /* (i) number of bits for position */
+        Word16 pos1,                          /* (i) position of the pulse 1     */
+        Word16 pos2,                          /* (i) position of the pulse 2     */
+        Word16 pos3,                          /* (i) position of the pulse 3     */
+        Word16 N);                            /* (i) number of bits for position */
 
 Word32 quant_4p_4N1(                       /* (o) return (4*N)+1 bits         */
-		Word16 pos1,                          /* (i) position of the pulse 1     */
-		Word16 pos2,                          /* (i) position of the pulse 2     */
-		Word16 pos3,                          /* (i) position of the pulse 3     */
-		Word16 pos4,                          /* (i) position of the pulse 4     */
-		Word16 N);                            /* (i) number of bits for position */
+        Word16 pos1,                          /* (i) position of the pulse 1     */
+        Word16 pos2,                          /* (i) position of the pulse 2     */
+        Word16 pos3,                          /* (i) position of the pulse 3     */
+        Word16 pos4,                          /* (i) position of the pulse 4     */
+        Word16 N);                            /* (i) number of bits for position */
 
 Word32 quant_4p_4N(                        /* (o) return 4*N bits             */
-		Word16 pos[],                         /* (i) position of the pulse 1..4  */
-		Word16 N);                            /* (i) number of bits for position */
+        Word16 pos[],                         /* (i) position of the pulse 1..4  */
+        Word16 N);                            /* (i) number of bits for position */
 
 Word32 quant_5p_5N(                        /* (o) return 5*N bits             */
-		Word16 pos[],                         /* (i) position of the pulse 1..5  */
-		Word16 N);                            /* (i) number of bits for position */
+        Word16 pos[],                         /* (i) position of the pulse 1..5  */
+        Word16 N);                            /* (i) number of bits for position */
 
 Word32 quant_6p_6N_2(                      /* (o) return (6*N)-2 bits         */
-		Word16 pos[],                         /* (i) position of the pulse 1..6  */
-		Word16 N);                            /* (i) number of bits for position */
+        Word16 pos[],                         /* (i) position of the pulse 1..6  */
+        Word16 N);                            /* (i) number of bits for position */
 
 
 #endif //__Q_PULSE_H__
diff --git a/media/libstagefright/codecs/amrwbenc/inc/stream.h b/media/libstagefright/codecs/amrwbenc/inc/stream.h
index 4c1d0f0..fbaae9e 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/stream.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/stream.h
@@ -17,7 +17,7 @@
 
 
 /***********************************************************************
-File:		stream.h
+File:       stream.h
 
 Contains:       VOME API Buffer Operator Implement Header
 
@@ -26,18 +26,18 @@
 #define __STREAM_H__
 
 #include "voMem.h"
-#define Frame_Maxsize  1024 * 2  //Work Buffer 10K
+#define Frame_Maxsize  (1024 * 2)  //Work Buffer 10K
 #define Frame_MaxByte  640        //AMR_WB Encoder one frame 320 samples = 640 Bytes
-#define MIN(a,b)	 ((a) < (b)? (a) : (b))
+#define MIN(a,b)     ((a) < (b)? (a) : (b))
 
 typedef struct{
-	unsigned char *set_ptr;
-	unsigned char *frame_ptr;
-	unsigned char *frame_ptr_bk;
-	int  set_len;
-	int  framebuffer_len;
-	int  frame_storelen;
-	int  used_len;
+    unsigned char *set_ptr;
+    unsigned char *frame_ptr;
+    unsigned char *frame_ptr_bk;
+    int  set_len;
+    int  framebuffer_len;
+    int  frame_storelen;
+    int  used_len;
 }FrameStream;
 
 void voAWB_UpdateFrameBuffer(FrameStream *stream, VO_MEM_OPERATOR *pMemOP);
diff --git a/media/libstagefright/codecs/amrwbenc/inc/wb_vad.h b/media/libstagefright/codecs/amrwbenc/inc/wb_vad.h
index 6822f48..9a9af4f 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/wb_vad.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/wb_vad.h
@@ -37,28 +37,28 @@
 
 typedef struct
 {
-	Word16 bckr_est[COMPLEN];              /* background noise estimate                */
-	Word16 ave_level[COMPLEN];             /* averaged input components for stationary */
-	/* estimation                               */
-	Word16 old_level[COMPLEN];             /* input levels of the previous frame       */
-	Word16 sub_level[COMPLEN];             /* input levels calculated at the end of a frame (lookahead)  */
-	Word16 a_data5[F_5TH_CNT][2];          /* memory for the filter bank               */
-	Word16 a_data3[F_3TH_CNT];             /* memory for the filter bank               */
+    Word16 bckr_est[COMPLEN];              /* background noise estimate                */
+    Word16 ave_level[COMPLEN];             /* averaged input components for stationary */
+    /* estimation                               */
+    Word16 old_level[COMPLEN];             /* input levels of the previous frame       */
+    Word16 sub_level[COMPLEN];             /* input levels calculated at the end of a frame (lookahead)  */
+    Word16 a_data5[F_5TH_CNT][2];          /* memory for the filter bank               */
+    Word16 a_data3[F_3TH_CNT];             /* memory for the filter bank               */
 
-	Word16 burst_count;                    /* counts length of a speech burst          */
-	Word16 hang_count;                     /* hangover counter                         */
-	Word16 stat_count;                     /* stationary counter                       */
+    Word16 burst_count;                    /* counts length of a speech burst          */
+    Word16 hang_count;                     /* hangover counter                         */
+    Word16 stat_count;                     /* stationary counter                       */
 
-	/* Note that each of the following two variables holds 15 flags. Each flag reserves 1 bit of the
-	 * variable. The newest flag is in the bit 15 (assuming that LSB is bit 1 and MSB is bit 16). */
-	Word16 vadreg;                         /* flags for intermediate VAD decisions     */
-	Word16 tone_flag;                      /* tone detection flags                     */
+    /* Note that each of the following two variables holds 15 flags. Each flag reserves 1 bit of the
+     * variable. The newest flag is in the bit 15 (assuming that LSB is bit 1 and MSB is bit 16). */
+    Word16 vadreg;                         /* flags for intermediate VAD decisions     */
+    Word16 tone_flag;                      /* tone detection flags                     */
 
-	Word16 sp_est_cnt;                     /* counter for speech level estimation      */
-	Word16 sp_max;                         /* maximum level                            */
-	Word16 sp_max_cnt;                     /* counts frames that contains speech       */
-	Word16 speech_level;                   /* estimated speech level                   */
-	Word32 prev_pow_sum;                   /* power of previous frame                  */
+    Word16 sp_est_cnt;                     /* counter for speech level estimation      */
+    Word16 sp_max;                         /* maximum level                            */
+    Word16 sp_max_cnt;                     /* counts frames that contains speech       */
+    Word16 speech_level;                   /* estimated speech level                   */
+    Word32 prev_pow_sum;                   /* power of previous frame                  */
 
 } VadVars;
 
diff --git a/media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h b/media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h
index 04fd318..00b1779 100644
--- a/media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h
+++ b/media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h
@@ -16,9 +16,9 @@
 
 
 /*-------------------------------------------------------------------*
- *                         WB_VAD_C.H				     *
+ *                         WB_VAD_C.H                    *
  *-------------------------------------------------------------------*
- * Constants for Voice Activity Detection.			     *
+ * Constants for Voice Activity Detection.               *
  *-------------------------------------------------------------------*/
 
 #ifndef __WB_VAD_C_H__
diff --git a/media/libstagefright/codecs/amrwbenc/src/autocorr.c b/media/libstagefright/codecs/amrwbenc/src/autocorr.c
index 0b2ea89..3ea53f7 100644
--- a/media/libstagefright/codecs/amrwbenc/src/autocorr.c
+++ b/media/libstagefright/codecs/amrwbenc/src/autocorr.c
@@ -31,100 +31,100 @@
 #define UNUSED(x) (void)(x)
 
 void Autocorr(
-		Word16 x[],                           /* (i)    : Input signal                      */
-		Word16 m,                             /* (i)    : LPC order                         */
-		Word16 r_h[],                         /* (o) Q15: Autocorrelations  (msb)           */
-		Word16 r_l[]                          /* (o)    : Autocorrelations  (lsb)           */
-	     )
+        Word16 x[],                           /* (i)    : Input signal                      */
+        Word16 m,                             /* (i)    : LPC order                         */
+        Word16 r_h[],                         /* (o) Q15: Autocorrelations  (msb)           */
+        Word16 r_l[]                          /* (o)    : Autocorrelations  (lsb)           */
+         )
 {
-	Word32 i, norm, shift;
-	Word16 y[L_WINDOW];
-	Word32 L_sum, L_sum1, L_tmp, F_LEN;
-	Word16 *p1,*p2,*p3;
-	const Word16 *p4;
+    Word32 i, norm, shift;
+    Word16 y[L_WINDOW];
+    Word32 L_sum, L_sum1, L_tmp, F_LEN;
+    Word16 *p1,*p2,*p3;
+    const Word16 *p4;
         UNUSED(m);
 
-	/* Windowing of signal */
-	p1 = x;
-	p4 = vo_window;
-	p3 = y;
+    /* Windowing of signal */
+    p1 = x;
+    p4 = vo_window;
+    p3 = y;
 
-	for (i = 0; i < L_WINDOW; i+=4)
-	{
-		*p3++ = vo_mult_r((*p1++), (*p4++));
-		*p3++ = vo_mult_r((*p1++), (*p4++));
-		*p3++ = vo_mult_r((*p1++), (*p4++));
-		*p3++ = vo_mult_r((*p1++), (*p4++));
-	}
+    for (i = 0; i < L_WINDOW; i+=4)
+    {
+        *p3++ = vo_mult_r((*p1++), (*p4++));
+        *p3++ = vo_mult_r((*p1++), (*p4++));
+        *p3++ = vo_mult_r((*p1++), (*p4++));
+        *p3++ = vo_mult_r((*p1++), (*p4++));
+    }
 
-	/* calculate energy of signal */
-	L_sum = vo_L_deposit_h(16);               /* sqrt(256), avoid overflow after rounding */
-	for (i = 0; i < L_WINDOW; i++)
-	{
-		L_tmp = vo_L_mult(y[i], y[i]);
-		L_tmp = (L_tmp >> 8);
-		L_sum += L_tmp;
-	}
+    /* calculate energy of signal */
+    L_sum = vo_L_deposit_h(16);               /* sqrt(256), avoid overflow after rounding */
+    for (i = 0; i < L_WINDOW; i++)
+    {
+        L_tmp = vo_L_mult(y[i], y[i]);
+        L_tmp = (L_tmp >> 8);
+        L_sum += L_tmp;
+    }
 
-	/* scale signal to avoid overflow in autocorrelation */
-	norm = norm_l(L_sum);
-	shift = 4 - (norm >> 1);
-	if(shift > 0)
-	{
-		p1 = y;
-		for (i = 0; i < L_WINDOW; i+=4)
-		{
-			*p1 = vo_shr_r(*p1, shift);
-			p1++;
-			*p1 = vo_shr_r(*p1, shift);
-			p1++;
-			*p1 = vo_shr_r(*p1, shift);
-			p1++;
-			*p1 = vo_shr_r(*p1, shift);
-			p1++;
-		}
-	}
+    /* scale signal to avoid overflow in autocorrelation */
+    norm = norm_l(L_sum);
+    shift = 4 - (norm >> 1);
+    if(shift > 0)
+    {
+        p1 = y;
+        for (i = 0; i < L_WINDOW; i+=4)
+        {
+            *p1 = vo_shr_r(*p1, shift);
+            p1++;
+            *p1 = vo_shr_r(*p1, shift);
+            p1++;
+            *p1 = vo_shr_r(*p1, shift);
+            p1++;
+            *p1 = vo_shr_r(*p1, shift);
+            p1++;
+        }
+    }
 
-	/* Compute and normalize r[0] */
-	L_sum = 1;
-	for (i = 0; i < L_WINDOW; i+=4)
-	{
-		L_sum += vo_L_mult(y[i], y[i]);
-		L_sum += vo_L_mult(y[i+1], y[i+1]);
-		L_sum += vo_L_mult(y[i+2], y[i+2]);
-		L_sum += vo_L_mult(y[i+3], y[i+3]);
-	}
+    /* Compute and normalize r[0] */
+    L_sum = 1;
+    for (i = 0; i < L_WINDOW; i+=4)
+    {
+        L_sum += vo_L_mult(y[i], y[i]);
+        L_sum += vo_L_mult(y[i+1], y[i+1]);
+        L_sum += vo_L_mult(y[i+2], y[i+2]);
+        L_sum += vo_L_mult(y[i+3], y[i+3]);
+    }
 
-	norm = norm_l(L_sum);
-	L_sum = (L_sum << norm);
+    norm = norm_l(L_sum);
+    L_sum = (L_sum << norm);
 
-	r_h[0] = L_sum >> 16;
-	r_l[0] = (L_sum & 0xffff)>>1;
+    r_h[0] = L_sum >> 16;
+    r_l[0] = (L_sum & 0xffff)>>1;
 
-	/* Compute r[1] to r[m] */
-	for (i = 1; i <= 8; i++)
-	{
-		L_sum1 = 0;
-		L_sum = 0;
-		F_LEN = (Word32)(L_WINDOW - 2*i);
-		p1 = y;
-		p2 = y + (2*i)-1;
-		do{
-			L_sum1 += *p1 * *p2++;
-			L_sum += *p1++ * *p2;
-		}while(--F_LEN!=0);
+    /* Compute r[1] to r[m] */
+    for (i = 1; i <= 8; i++)
+    {
+        L_sum1 = 0;
+        L_sum = 0;
+        F_LEN = (Word32)(L_WINDOW - 2*i);
+        p1 = y;
+        p2 = y + (2*i)-1;
+        do{
+            L_sum1 += *p1 * *p2++;
+            L_sum += *p1++ * *p2;
+        }while(--F_LEN!=0);
 
-		L_sum1 += *p1 * *p2++;
+        L_sum1 += *p1 * *p2++;
 
-		L_sum1 = L_sum1<<norm;
-		L_sum = L_sum<<norm;
+        L_sum1 = L_sum1<<norm;
+        L_sum = L_sum<<norm;
 
-		r_h[(2*i)-1] = L_sum1 >> 15;
-		r_l[(2*i)-1] = L_sum1 & 0x00007fff;
-		r_h[(2*i)] = L_sum >> 15;
-		r_l[(2*i)] = L_sum & 0x00007fff;
-	}
-	return;
+        r_h[(2*i)-1] = L_sum1 >> 15;
+        r_l[(2*i)-1] = L_sum1 & 0x00007fff;
+        r_h[(2*i)] = L_sum >> 15;
+        r_l[(2*i)] = L_sum & 0x00007fff;
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/az_isp.c b/media/libstagefright/codecs/amrwbenc/src/az_isp.c
index 43db27a..d7074f0 100644
--- a/media/libstagefright/codecs/amrwbenc/src/az_isp.c
+++ b/media/libstagefright/codecs/amrwbenc/src/az_isp.c
@@ -58,138 +58,138 @@
 static __inline Word16 Chebps2(Word16 x, Word16 f[], Word32 n);
 
 void Az_isp(
-		Word16 a[],                           /* (i) Q12 : predictor coefficients                 */
-		Word16 isp[],                         /* (o) Q15 : Immittance spectral pairs              */
-		Word16 old_isp[]                      /* (i)     : old isp[] (in case not found M roots)  */
-	   )
+        Word16 a[],                           /* (i) Q12 : predictor coefficients                 */
+        Word16 isp[],                         /* (o) Q15 : Immittance spectral pairs              */
+        Word16 old_isp[]                      /* (i)     : old isp[] (in case not found M roots)  */
+       )
 {
-	Word32 i, j, nf, ip, order;
-	Word16 xlow, ylow, xhigh, yhigh, xmid, ymid, xint;
-	Word16 x, y, sign, exp;
-	Word16 *coef;
-	Word16 f1[NC + 1], f2[NC];
-	Word32 t0;
-	/*-------------------------------------------------------------*
-	 * find the sum and diff polynomials F1(z) and F2(z)           *
-	 *      F1(z) = [A(z) + z^M A(z^-1)]                           *
-	 *      F2(z) = [A(z) - z^M A(z^-1)]/(1-z^-2)                  *
-	 *                                                             *
-	 * for (i=0; i<NC; i++)                                        *
-	 * {                                                           *
-	 *   f1[i] = a[i] + a[M-i];                                    *
-	 *   f2[i] = a[i] - a[M-i];                                    *
-	 * }                                                           *
-	 * f1[NC] = 2.0*a[NC];                                         *
-	 *                                                             *
-	 * for (i=2; i<NC; i++)            Divide by (1-z^-2)          *
-	 *   f2[i] += f2[i-2];                                         *
-	 *-------------------------------------------------------------*/
-	for (i = 0; i < NC; i++)
-	{
-		t0 = a[i] << 15;
-		f1[i] = vo_round(t0 + (a[M - i] << 15));        /* =(a[i]+a[M-i])/2 */
-		f2[i] = vo_round(t0 - (a[M - i] << 15));        /* =(a[i]-a[M-i])/2 */
-	}
-	f1[NC] = a[NC];
-	for (i = 2; i < NC; i++)               /* Divide by (1-z^-2) */
-		f2[i] = add1(f2[i], f2[i - 2]);
+    Word32 i, j, nf, ip, order;
+    Word16 xlow, ylow, xhigh, yhigh, xmid, ymid, xint;
+    Word16 x, y, sign, exp;
+    Word16 *coef;
+    Word16 f1[NC + 1], f2[NC];
+    Word32 t0;
+    /*-------------------------------------------------------------*
+     * find the sum and diff polynomials F1(z) and F2(z)           *
+     *      F1(z) = [A(z) + z^M A(z^-1)]                           *
+     *      F2(z) = [A(z) - z^M A(z^-1)]/(1-z^-2)                  *
+     *                                                             *
+     * for (i=0; i<NC; i++)                                        *
+     * {                                                           *
+     *   f1[i] = a[i] + a[M-i];                                    *
+     *   f2[i] = a[i] - a[M-i];                                    *
+     * }                                                           *
+     * f1[NC] = 2.0*a[NC];                                         *
+     *                                                             *
+     * for (i=2; i<NC; i++)            Divide by (1-z^-2)          *
+     *   f2[i] += f2[i-2];                                         *
+     *-------------------------------------------------------------*/
+    for (i = 0; i < NC; i++)
+    {
+        t0 = a[i] << 15;
+        f1[i] = vo_round(t0 + (a[M - i] << 15));        /* =(a[i]+a[M-i])/2 */
+        f2[i] = vo_round(t0 - (a[M - i] << 15));        /* =(a[i]-a[M-i])/2 */
+    }
+    f1[NC] = a[NC];
+    for (i = 2; i < NC; i++)               /* Divide by (1-z^-2) */
+        f2[i] = add1(f2[i], f2[i - 2]);
 
-	/*---------------------------------------------------------------------*
-	 * Find the ISPs (roots of F1(z) and F2(z) ) using the                 *
-	 * Chebyshev polynomial evaluation.                                    *
-	 * The roots of F1(z) and F2(z) are alternatively searched.            *
-	 * We start by finding the first root of F1(z) then we switch          *
-	 * to F2(z) then back to F1(z) and so on until all roots are found.    *
-	 *                                                                     *
-	 *  - Evaluate Chebyshev pol. at grid points and check for sign change.*
-	 *  - If sign change track the root by subdividing the interval        *
-	 *    2 times and ckecking sign change.                                *
-	 *---------------------------------------------------------------------*/
-	nf = 0;                                  /* number of found frequencies */
-	ip = 0;                                  /* indicator for f1 or f2      */
-	coef = f1;
-	order = NC;
-	xlow = vogrid[0];
-	ylow = Chebps2(xlow, coef, order);
-	j = 0;
-	while ((nf < M - 1) && (j < GRID_POINTS))
-	{
-		j ++;
-		xhigh = xlow;
-		yhigh = ylow;
-		xlow = vogrid[j];
-		ylow = Chebps2(xlow, coef, order);
-		if ((ylow * yhigh) <= (Word32) 0)
-		{
-			/* divide 2 times the interval */
-			for (i = 0; i < 2; i++)
-			{
-				xmid = (xlow >> 1) + (xhigh >> 1);        /* xmid = (xlow + xhigh)/2 */
-				ymid = Chebps2(xmid, coef, order);
-				if ((ylow * ymid) <= (Word32) 0)
-				{
-					yhigh = ymid;
-					xhigh = xmid;
-				} else
-				{
-					ylow = ymid;
-					xlow = xmid;
-				}
-			}
-			/*-------------------------------------------------------------*
-			 * Linear interpolation                                        *
-			 *    xint = xlow - ylow*(xhigh-xlow)/(yhigh-ylow);            *
-			 *-------------------------------------------------------------*/
-			x = xhigh - xlow;
-			y = yhigh - ylow;
-			if (y == 0)
-			{
-				xint = xlow;
-			} else
-			{
-				sign = y;
-				y = abs_s(y);
-				exp = norm_s(y);
-				y = y << exp;
-				y = div_s((Word16) 16383, y);
-				t0 = x * y;
-				t0 = (t0 >> (19 - exp));
-				y = vo_extract_l(t0);         /* y= (xhigh-xlow)/(yhigh-ylow) in Q11 */
-				if (sign < 0)
-					y = -y;
-				t0 = ylow * y;      /* result in Q26 */
-				t0 = (t0 >> 10);        /* result in Q15 */
-				xint = vo_sub(xlow, vo_extract_l(t0));        /* xint = xlow - ylow*y */
-			}
-			isp[nf] = xint;
-			xlow = xint;
-			nf++;
-			if (ip == 0)
-			{
-				ip = 1;
-				coef = f2;
-				order = NC - 1;
-			} else
-			{
-				ip = 0;
-				coef = f1;
-				order = NC;
-			}
-			ylow = Chebps2(xlow, coef, order);
-		}
-	}
-	/* Check if M-1 roots found */
-	if(nf < M - 1)
-	{
-		for (i = 0; i < M; i++)
-		{
-			isp[i] = old_isp[i];
-		}
-	} else
-	{
-		isp[M - 1] = a[M] << 3;                      /* From Q12 to Q15 with saturation */
-	}
-	return;
+    /*---------------------------------------------------------------------*
+     * Find the ISPs (roots of F1(z) and F2(z) ) using the                 *
+     * Chebyshev polynomial evaluation.                                    *
+     * The roots of F1(z) and F2(z) are alternatively searched.            *
+     * We start by finding the first root of F1(z) then we switch          *
+     * to F2(z) then back to F1(z) and so on until all roots are found.    *
+     *                                                                     *
+     *  - Evaluate Chebyshev pol. at grid points and check for sign change.*
+     *  - If sign change track the root by subdividing the interval        *
+     *    2 times and ckecking sign change.                                *
+     *---------------------------------------------------------------------*/
+    nf = 0;                                  /* number of found frequencies */
+    ip = 0;                                  /* indicator for f1 or f2      */
+    coef = f1;
+    order = NC;
+    xlow = vogrid[0];
+    ylow = Chebps2(xlow, coef, order);
+    j = 0;
+    while ((nf < M - 1) && (j < GRID_POINTS))
+    {
+        j ++;
+        xhigh = xlow;
+        yhigh = ylow;
+        xlow = vogrid[j];
+        ylow = Chebps2(xlow, coef, order);
+        if ((ylow * yhigh) <= (Word32) 0)
+        {
+            /* divide 2 times the interval */
+            for (i = 0; i < 2; i++)
+            {
+                xmid = (xlow >> 1) + (xhigh >> 1);        /* xmid = (xlow + xhigh)/2 */
+                ymid = Chebps2(xmid, coef, order);
+                if ((ylow * ymid) <= (Word32) 0)
+                {
+                    yhigh = ymid;
+                    xhigh = xmid;
+                } else
+                {
+                    ylow = ymid;
+                    xlow = xmid;
+                }
+            }
+            /*-------------------------------------------------------------*
+             * Linear interpolation                                        *
+             *    xint = xlow - ylow*(xhigh-xlow)/(yhigh-ylow);            *
+             *-------------------------------------------------------------*/
+            x = xhigh - xlow;
+            y = yhigh - ylow;
+            if (y == 0)
+            {
+                xint = xlow;
+            } else
+            {
+                sign = y;
+                y = abs_s(y);
+                exp = norm_s(y);
+                y = y << exp;
+                y = div_s((Word16) 16383, y);
+                t0 = x * y;
+                t0 = (t0 >> (19 - exp));
+                y = vo_extract_l(t0);         /* y= (xhigh-xlow)/(yhigh-ylow) in Q11 */
+                if (sign < 0)
+                    y = -y;
+                t0 = ylow * y;      /* result in Q26 */
+                t0 = (t0 >> 10);        /* result in Q15 */
+                xint = vo_sub(xlow, vo_extract_l(t0));        /* xint = xlow - ylow*y */
+            }
+            isp[nf] = xint;
+            xlow = xint;
+            nf++;
+            if (ip == 0)
+            {
+                ip = 1;
+                coef = f2;
+                order = NC - 1;
+            } else
+            {
+                ip = 0;
+                coef = f1;
+                order = NC;
+            }
+            ylow = Chebps2(xlow, coef, order);
+        }
+    }
+    /* Check if M-1 roots found */
+    if(nf < M - 1)
+    {
+        for (i = 0; i < M; i++)
+        {
+            isp[i] = old_isp[i];
+        }
+    } else
+    {
+        isp[M - 1] = a[M] << 3;                      /* From Q12 to Q15 with saturation */
+    }
+    return;
 }
 
 /*--------------------------------------------------------------*
@@ -213,55 +213,55 @@
 
 static __inline Word16 Chebps2(Word16 x, Word16 f[], Word32 n)
 {
-	Word32 i, cheb;
-	Word16 b0_h, b0_l, b1_h, b1_l, b2_h, b2_l;
-	Word32 t0;
+    Word32 i, cheb;
+    Word16 b0_h, b0_l, b1_h, b1_l, b2_h, b2_l;
+    Word32 t0;
 
-	/* Note: All computation are done in Q24. */
+    /* Note: All computation are done in Q24. */
 
-	t0 = f[0] << 13;
-	b2_h = t0 >> 16;
-	b2_l = (t0 & 0xffff)>>1;
+    t0 = f[0] << 13;
+    b2_h = t0 >> 16;
+    b2_l = (t0 & 0xffff)>>1;
 
-	t0 = ((b2_h * x)<<1) + (((b2_l * x)>>15)<<1);
-	t0 <<= 1;
-	t0 += (f[1] << 13);						/* + f[1] in Q24        */
+    t0 = ((b2_h * x)<<1) + (((b2_l * x)>>15)<<1);
+    t0 <<= 1;
+    t0 += (f[1] << 13);                     /* + f[1] in Q24        */
 
-	b1_h = t0 >> 16;
-	b1_l = (t0 & 0xffff) >> 1;
+    b1_h = t0 >> 16;
+    b1_l = (t0 & 0xffff) >> 1;
 
-	for (i = 2; i < n; i++)
-	{
-		t0 = ((b1_h * x)<<1) + (((b1_l * x)>>15)<<1);
+    for (i = 2; i < n; i++)
+    {
+        t0 = ((b1_h * x)<<1) + (((b1_l * x)>>15)<<1);
 
-		t0 += (b2_h * (-16384))<<1;
-		t0 += (f[i] << 12);
-		t0 <<= 1;
-		t0 -= (b2_l << 1);					/* t0 = 2.0*x*b1 - b2 + f[i]; */
+        t0 += (b2_h * (-16384))<<1;
+        t0 += (f[i] << 12);
+        t0 <<= 1;
+        t0 -= (b2_l << 1);                  /* t0 = 2.0*x*b1 - b2 + f[i]; */
 
-		b0_h = t0 >> 16;
-		b0_l = (t0 & 0xffff) >> 1;
+        b0_h = t0 >> 16;
+        b0_l = (t0 & 0xffff) >> 1;
 
-		b2_l = b1_l;                         /* b2 = b1; */
-		b2_h = b1_h;
-		b1_l = b0_l;                         /* b1 = b0; */
-		b1_h = b0_h;
-	}
+        b2_l = b1_l;                         /* b2 = b1; */
+        b2_h = b1_h;
+        b1_l = b0_l;                         /* b1 = b0; */
+        b1_h = b0_h;
+    }
 
-	t0 = ((b1_h * x)<<1) + (((b1_l * x)>>15)<<1);
-	t0 += (b2_h * (-32768))<<1;				/* t0 = x*b1 - b2          */
-	t0 -= (b2_l << 1);
-	t0 += (f[n] << 12);						/* t0 = x*b1 - b2 + f[i]/2 */
+    t0 = ((b1_h * x)<<1) + (((b1_l * x)>>15)<<1);
+    t0 += (b2_h * (-32768))<<1;             /* t0 = x*b1 - b2          */
+    t0 -= (b2_l << 1);
+    t0 += (f[n] << 12);                     /* t0 = x*b1 - b2 + f[i]/2 */
 
-	t0 = L_shl2(t0, 6);                     /* Q24 to Q30 with saturation */
+    t0 = L_shl2(t0, 6);                     /* Q24 to Q30 with saturation */
 
-	cheb = extract_h(t0);                  /* Result in Q14              */
+    cheb = extract_h(t0);                  /* Result in Q14              */
 
-	if (cheb == -32768)
-	{
-		cheb = -32767;                     /* to avoid saturation in Az_isp */
-	}
-	return (cheb);
+    if (cheb == -32768)
+    {
+        cheb = -32767;                     /* to avoid saturation in Az_isp */
+    }
+    return (cheb);
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/bits.c b/media/libstagefright/codecs/amrwbenc/src/bits.c
index e78dc1f..6b8bddd 100644
--- a/media/libstagefright/codecs/amrwbenc/src/bits.c
+++ b/media/libstagefright/codecs/amrwbenc/src/bits.c
@@ -17,7 +17,7 @@
 /***********************************************************************
        File: bits.c
 
-	   Description: Performs bit stream manipulation
+       Description: Performs bit stream manipulation
 
 ************************************************************************/
 
@@ -33,151 +33,151 @@
 
 
 int PackBits(Word16 prms[],             /*  i: analysis parameters */
-			 Word16 coding_mode,        /*  i: coding bit-stream ratio mode */
-			 Word16 mode,               /*  i: coding bit-stream ratio mode*/
-			 Coder_State *st            /*i/o: coder global parameters struct */
-			 )
+             Word16 coding_mode,        /*  i: coding bit-stream ratio mode */
+             Word16 mode,               /*  i: coding bit-stream ratio mode*/
+             Coder_State *st            /*i/o: coder global parameters struct */
+             )
 {
-	Word16 i, frame_type;
-	UWord8 temp;
-	UWord8 *stream_ptr;
-	Word16 bitstreamformat = st->frameType;
+    Word16 i, frame_type;
+    UWord8 temp;
+    UWord8 *stream_ptr;
+    Word16 bitstreamformat = st->frameType;
 
-	unsigned short* dataOut = st->outputStream;
+    unsigned short* dataOut = st->outputStream;
 
-	if (coding_mode == MRDTX)
-	{
-		st->sid_update_counter--;
+    if (coding_mode == MRDTX)
+    {
+        st->sid_update_counter--;
 
-		if (st->prev_ft == TX_SPEECH)
-		{
-			frame_type = TX_SID_FIRST;
-			st->sid_update_counter = 3;
-		} else
-		{
-			if ((st->sid_handover_debt > 0) && (st->sid_update_counter > 2))
-			{
-				/* ensure extra updates are  properly delayed after a possible SID_FIRST */
-				frame_type = TX_SID_UPDATE;
-				st->sid_handover_debt--;
-			} else
-			{
-				if (st->sid_update_counter == 0)
-				{
-					frame_type = TX_SID_UPDATE;
-					st->sid_update_counter = 8;
-				} else
-				{
-					frame_type = TX_NO_DATA;
-				}
-			}
-		}
-	} else
-	{
-		st->sid_update_counter = 8;
-		frame_type = TX_SPEECH;
-	}
-	st->prev_ft = frame_type;
+        if (st->prev_ft == TX_SPEECH)
+        {
+            frame_type = TX_SID_FIRST;
+            st->sid_update_counter = 3;
+        } else
+        {
+            if ((st->sid_handover_debt > 0) && (st->sid_update_counter > 2))
+            {
+                /* ensure extra updates are  properly delayed after a possible SID_FIRST */
+                frame_type = TX_SID_UPDATE;
+                st->sid_handover_debt--;
+            } else
+            {
+                if (st->sid_update_counter == 0)
+                {
+                    frame_type = TX_SID_UPDATE;
+                    st->sid_update_counter = 8;
+                } else
+                {
+                    frame_type = TX_NO_DATA;
+                }
+            }
+        }
+    } else
+    {
+        st->sid_update_counter = 8;
+        frame_type = TX_SPEECH;
+    }
+    st->prev_ft = frame_type;
 
-	if(bitstreamformat == 0)				/* default file format */
-	{
-		*(dataOut) = TX_FRAME_TYPE;
-		*(dataOut + 1) = frame_type;
-		*(dataOut + 2) = mode;
-		for (i = 0; i < nb_of_bits[coding_mode]; i++)
-		{
-			*(dataOut + 3 + i) = prms[i];
-		}
-		return  (3 + nb_of_bits[coding_mode])<<1;
-	} else
-	{
-		if (bitstreamformat == 1)		/* ITU file format */
-		{
-			*(dataOut) = 0x6b21;
-			if(frame_type != TX_NO_DATA && frame_type != TX_SID_FIRST)
-			{
-				*(dataOut + 1) = nb_of_bits[coding_mode];
-				for (i = 0; i < nb_of_bits[coding_mode]; i++)
-				{
-					if(prms[i] == BIT_0){
-						*(dataOut + 2 + i) = BIT_0_ITU;
-					}
-					else{
-						*(dataOut + 2 + i) = BIT_1_ITU;
-					}
-				}
-				return (2 + nb_of_bits[coding_mode])<<1;
-			} else
-			{
-				*(dataOut + 1) = 0;
-				return 2<<1;
-			}
-		} else							/* MIME/storage file format */
-		{
+    if(bitstreamformat == 0)                /* default file format */
+    {
+        *(dataOut) = TX_FRAME_TYPE;
+        *(dataOut + 1) = frame_type;
+        *(dataOut + 2) = mode;
+        for (i = 0; i < nb_of_bits[coding_mode]; i++)
+        {
+            *(dataOut + 3 + i) = prms[i];
+        }
+        return  (3 + nb_of_bits[coding_mode])<<1;
+    } else
+    {
+        if (bitstreamformat == 1)       /* ITU file format */
+        {
+            *(dataOut) = 0x6b21;
+            if(frame_type != TX_NO_DATA && frame_type != TX_SID_FIRST)
+            {
+                *(dataOut + 1) = nb_of_bits[coding_mode];
+                for (i = 0; i < nb_of_bits[coding_mode]; i++)
+                {
+                    if(prms[i] == BIT_0){
+                        *(dataOut + 2 + i) = BIT_0_ITU;
+                    }
+                    else{
+                        *(dataOut + 2 + i) = BIT_1_ITU;
+                    }
+                }
+                return (2 + nb_of_bits[coding_mode])<<1;
+            } else
+            {
+                *(dataOut + 1) = 0;
+                return 2<<1;
+            }
+        } else                          /* MIME/storage file format */
+        {
 #define MRSID 9
-			/* change mode index in case of SID frame */
-			if (coding_mode == MRDTX)
-			{
-				coding_mode = MRSID;
-				if (frame_type == TX_SID_FIRST)
-				{
-					for (i = 0; i < NBBITS_SID; i++)	prms[i] = BIT_0;
-				}
-			}
-			/* -> force NO_DATA frame */
-			if (coding_mode < 0 || coding_mode > 15 || (coding_mode > MRSID && coding_mode < 14))
-			{
-				coding_mode = 15;
-			}
-			/* mark empty frames between SID updates as NO_DATA frames */
-			if (coding_mode == MRSID && frame_type == TX_NO_DATA)
-			{
-				coding_mode = 15;
-			}
-			/* set pointer for packed frame, note that we handle data as bytes */
-			stream_ptr = (UWord8*)dataOut;
-			/* insert table of contents (ToC) byte at the beginning of the packet */
-			*stream_ptr = toc_byte[coding_mode];
-			stream_ptr++;
-			temp = 0;
-			/* sort and pack AMR-WB speech or SID bits */
-			for (i = 1; i < unpacked_size[coding_mode] + 1; i++)
-			{
-				if (prms[sort_ptr[coding_mode][i-1]] == BIT_1)
-				{
-					temp++;
-				}
-				if (i&0x7)
-				{
-					temp <<= 1;
-				}
-				else
-				{
-					*stream_ptr = temp;
-					stream_ptr++;
-					temp = 0;
-				}
-			}
-			/* insert SID type indication and speech mode in case of SID frame */
-			if (coding_mode == MRSID)
-			{
-				if (frame_type == TX_SID_UPDATE)
-				{
-					temp++;
-				}
-				temp <<= 4;
-				temp += mode & 0x000F;
-			}
-			/* insert unused bits (zeros) at the tail of the last byte */
-			if (unused_size[coding_mode])
-			{
-				temp <<= (unused_size[coding_mode] - 1);
-			}
-			*stream_ptr = temp;
-			/* write packed frame into file (1 byte added to cover ToC entry) */
-			return (1 + packed_size[coding_mode]);
-		}
-	}
+            /* change mode index in case of SID frame */
+            if (coding_mode == MRDTX)
+            {
+                coding_mode = MRSID;
+                if (frame_type == TX_SID_FIRST)
+                {
+                    for (i = 0; i < NBBITS_SID; i++)    prms[i] = BIT_0;
+                }
+            }
+            /* -> force NO_DATA frame */
+            if (coding_mode < 0 || coding_mode > 15 || (coding_mode > MRSID && coding_mode < 14))
+            {
+                coding_mode = 15;
+            }
+            /* mark empty frames between SID updates as NO_DATA frames */
+            if (coding_mode == MRSID && frame_type == TX_NO_DATA)
+            {
+                coding_mode = 15;
+            }
+            /* set pointer for packed frame, note that we handle data as bytes */
+            stream_ptr = (UWord8*)dataOut;
+            /* insert table of contents (ToC) byte at the beginning of the packet */
+            *stream_ptr = toc_byte[coding_mode];
+            stream_ptr++;
+            temp = 0;
+            /* sort and pack AMR-WB speech or SID bits */
+            for (i = 1; i < unpacked_size[coding_mode] + 1; i++)
+            {
+                if (prms[sort_ptr[coding_mode][i-1]] == BIT_1)
+                {
+                    temp++;
+                }
+                if (i&0x7)
+                {
+                    temp <<= 1;
+                }
+                else
+                {
+                    *stream_ptr = temp;
+                    stream_ptr++;
+                    temp = 0;
+                }
+            }
+            /* insert SID type indication and speech mode in case of SID frame */
+            if (coding_mode == MRSID)
+            {
+                if (frame_type == TX_SID_UPDATE)
+                {
+                    temp++;
+                }
+                temp <<= 4;
+                temp += mode & 0x000F;
+            }
+            /* insert unused bits (zeros) at the tail of the last byte */
+            if (unused_size[coding_mode])
+            {
+                temp <<= (unused_size[coding_mode] - 1);
+            }
+            *stream_ptr = temp;
+            /* write packed frame into file (1 byte added to cover ToC entry) */
+            return (1 + packed_size[coding_mode]);
+        }
+    }
 }
 
 /*-----------------------------------------------------*
@@ -185,24 +185,24 @@
 *-----------------------------------------------------*/
 
 void Parm_serial(
-		Word16 value,                         /* input : parameter value */
-		Word16 no_of_bits,                    /* input : number of bits  */
-		Word16 ** prms
-		)
+        Word16 value,                         /* input : parameter value */
+        Word16 no_of_bits,                    /* input : number of bits  */
+        Word16 ** prms
+        )
 {
-	Word16 i, bit;
-	*prms += no_of_bits;
-	for (i = 0; i < no_of_bits; i++)
-	{
-		bit = (Word16) (value & 0x0001);    /* get lsb */
-		if (bit == 0)
-			*--(*prms) = BIT_0;
-		else
-			*--(*prms) = BIT_1;
-		value >>= 1;
-	}
-	*prms += no_of_bits;
-	return;
+    Word16 i, bit;
+    *prms += no_of_bits;
+    for (i = 0; i < no_of_bits; i++)
+    {
+        bit = (Word16) (value & 0x0001);    /* get lsb */
+        if (bit == 0)
+            *--(*prms) = BIT_0;
+        else
+            *--(*prms) = BIT_1;
+        value >>= 1;
+    }
+    *prms += no_of_bits;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/c2t64fx.c b/media/libstagefright/codecs/amrwbenc/src/c2t64fx.c
index 768abd4..dbb94c6 100644
--- a/media/libstagefright/codecs/amrwbenc/src/c2t64fx.c
+++ b/media/libstagefright/codecs/amrwbenc/src/c2t64fx.c
@@ -17,7 +17,7 @@
 /************************************************************************
 *      File: c2t64fx.c                                                  *
 *                                                                       *
-*	   Description:Performs algebraic codebook search for 6.60kbits mode*
+*      Description:Performs algebraic codebook search for 6.60kbits mode*
 *                                                                       *
 *************************************************************************/
 
@@ -44,257 +44,256 @@
 * Each pulse can have 32 possible positions.                             *
 **************************************************************************/
 
-// There are many integer overflows in this function, as none of them appear to
-// lead to memory accesses, and performing the appropriate checks will lead
-// to considerably larger code, mark this as ignore.
-__attribute__((no_sanitize("integer")))
 void ACELP_2t64_fx(
-		Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */
-		Word16 cn[],                          /* (i) <12b : residual after long term prediction         */
-		Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */
-		Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */
-		Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */
-		Word16 * index                        /* (o) : index (12): 5+1+5+1 = 11 bits.                   */
-		)
+        Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */
+        Word16 cn[],                          /* (i) <12b : residual after long term prediction         */
+        Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */
+        Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */
+        Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */
+        Word16 * index                        /* (o) : index (12): 5+1+5+1 = 11 bits.                   */
+        )
 {
-	Word32 i, j, k, i0, i1, ix, iy, pos, pos2;
-	Word16 ps, psk, ps1, ps2, alpk, alp1, alp2, sq;
-	Word16 alp, val, exp, k_cn, k_dn;
-	Word16 *p0, *p1, *p2, *psign;
-	Word16 *h, *h_inv, *ptr_h1, *ptr_h2, *ptr_hf;
+    Word32 i, j, k, i0, i1, ix, iy, pos, pos2;
+    Word16 ps, psk, ps1, ps2, alpk, alp1, alp2, sq;
+    Word16 alp, val, exp, k_cn, k_dn;
+    Word16 *p0, *p1, *p2, *psign;
+    Word16 *h, *h_inv, *ptr_h1, *ptr_h2, *ptr_hf;
 
-	Word16 sign[L_SUBFR], vec[L_SUBFR], dn2[L_SUBFR];
-	Word16 h_buf[4 * L_SUBFR] = {0};
-	Word16 rrixix[NB_TRACK][NB_POS];
-	Word16 rrixiy[MSIZE];
-	Word32 s, cor;
+    Word16 sign[L_SUBFR], vec[L_SUBFR], dn2[L_SUBFR];
+    Word16 h_buf[4 * L_SUBFR] = {0};
+    Word16 rrixix[NB_TRACK][NB_POS];
+    Word16 rrixiy[MSIZE];
+    Word32 s, cor;
 
-	/*----------------------------------------------------------------*
-	 * Find sign for each pulse position.                             *
-	 *----------------------------------------------------------------*/
-	alp = 8192;                              /* alp = 2.0 (Q12) */
+    /*----------------------------------------------------------------*
+     * Find sign for each pulse position.                             *
+     *----------------------------------------------------------------*/
+    alp = 8192;                              /* alp = 2.0 (Q12) */
 
-	/* calculate energy for normalization of cn[] and dn[] */
-	/* set k_cn = 32..32767 (ener_cn = 2^30..256-0) */
+    /* calculate energy for normalization of cn[] and dn[] */
+    /* set k_cn = 32..32767 (ener_cn = 2^30..256-0) */
 #ifdef ASM_OPT             /* asm optimization branch */
-	s = Dot_product12_asm(cn, cn, L_SUBFR, &exp);
+    s = Dot_product12_asm(cn, cn, L_SUBFR, &exp);
 #else
-	s = Dot_product12(cn, cn, L_SUBFR, &exp);
+    s = Dot_product12(cn, cn, L_SUBFR, &exp);
 #endif
 
-	Isqrt_n(&s, &exp);
-	s = L_shl(s, add1(exp, 5));
-	k_cn = vo_round(s);
+    Isqrt_n(&s, &exp);
+    s = L_shl(s, add1(exp, 5));
+    if (s > INT_MAX - 0x8000) {
+        s = INT_MAX - 0x8000;
+    }
+    k_cn = vo_round(s);
 
-	/* set k_dn = 32..512 (ener_dn = 2^30..2^22) */
+    /* set k_dn = 32..512 (ener_dn = 2^30..2^22) */
 #ifdef ASM_OPT                  /* asm optimization branch */
-	s = Dot_product12_asm(dn, dn, L_SUBFR, &exp);
+    s = Dot_product12_asm(dn, dn, L_SUBFR, &exp);
 #else
-	s = Dot_product12(dn, dn, L_SUBFR, &exp);
+    s = Dot_product12(dn, dn, L_SUBFR, &exp);
 #endif
 
-	Isqrt_n(&s, &exp);
-	k_dn = vo_round(L_shl(s, (exp + 8)));    /* k_dn = 256..4096 */
-	k_dn = vo_mult_r(alp, k_dn);              /* alp in Q12 */
+    Isqrt_n(&s, &exp);
+    k_dn = voround(L_shl(s, (exp + 8)));    /* k_dn = 256..4096 */
+    k_dn = vo_mult_r(alp, k_dn);              /* alp in Q12 */
 
-	/* mix normalized cn[] and dn[] */
-	p0 = cn;
-	p1 = dn;
-	p2 = dn2;
+    /* mix normalized cn[] and dn[] */
+    p0 = cn;
+    p1 = dn;
+    p2 = dn2;
 
-	for (i = 0; i < L_SUBFR/4; i++)
-	{
-		s = (k_cn* (*p0++))+(k_dn * (*p1++));
-		*p2++ = s >> 7;
-		s = (k_cn* (*p0++))+(k_dn * (*p1++));
-		*p2++ = s >> 7;
-		s = (k_cn* (*p0++))+(k_dn * (*p1++));
-		*p2++ = s >> 7;
-		s = (k_cn* (*p0++))+(k_dn * (*p1++));
-		*p2++ = s >> 7;
-	}
+    for (i = 0; i < L_SUBFR/4; i++)
+    {
+        s = (k_cn* (*p0++))+(k_dn * (*p1++));
+        *p2++ = s >> 7;
+        s = (k_cn* (*p0++))+(k_dn * (*p1++));
+        *p2++ = s >> 7;
+        s = (k_cn* (*p0++))+(k_dn * (*p1++));
+        *p2++ = s >> 7;
+        s = (k_cn* (*p0++))+(k_dn * (*p1++));
+        *p2++ = s >> 7;
+    }
 
-	/* set sign according to dn2[] = k_cn*cn[] + k_dn*dn[]    */
-	for (i = 0; i < L_SUBFR; i ++)
-	{
-		val = dn[i];
-		ps = dn2[i];
-		if (ps >= 0)
-		{
-			sign[i] = 32767;             /* sign = +1 (Q12) */
-			vec[i] = -32768;
-		} else
-		{
-			sign[i] = -32768;            /* sign = -1 (Q12) */
-			vec[i] = 32767;
-			dn[i] = -val;
-		}
-	}
-	/*------------------------------------------------------------*
-	 * Compute h_inv[i].                                          *
-	 *------------------------------------------------------------*/
-	/* impulse response buffer for fast computation */
-	h = h_buf + L_SUBFR;
-	h_inv = h + (L_SUBFR<<1);
+    /* set sign according to dn2[] = k_cn*cn[] + k_dn*dn[]    */
+    for (i = 0; i < L_SUBFR; i ++)
+    {
+        val = dn[i];
+        ps = dn2[i];
+        if (ps >= 0)
+        {
+            sign[i] = 32767;             /* sign = +1 (Q12) */
+            vec[i] = -32768;
+        } else
+        {
+            sign[i] = -32768;            /* sign = -1 (Q12) */
+            vec[i] = 32767;
+            dn[i] = -val;
+        }
+    }
+    /*------------------------------------------------------------*
+     * Compute h_inv[i].                                          *
+     *------------------------------------------------------------*/
+    /* impulse response buffer for fast computation */
+    h = h_buf + L_SUBFR;
+    h_inv = h + (L_SUBFR<<1);
 
-	for (i = 0; i < L_SUBFR; i++)
-	{
-		h[i] = H[i];
-		h_inv[i] = vo_negate(h[i]);
-	}
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        h[i] = H[i];
+        h_inv[i] = vo_negate(h[i]);
+    }
 
-	/*------------------------------------------------------------*
-	 * Compute rrixix[][] needed for the codebook search.         *
-	 * Result is multiplied by 0.5                                *
-	 *------------------------------------------------------------*/
-	/* Init pointers to last position of rrixix[] */
-	p0 = &rrixix[0][NB_POS - 1];
-	p1 = &rrixix[1][NB_POS - 1];
+    /*------------------------------------------------------------*
+     * Compute rrixix[][] needed for the codebook search.         *
+     * Result is multiplied by 0.5                                *
+     *------------------------------------------------------------*/
+    /* Init pointers to last position of rrixix[] */
+    p0 = &rrixix[0][NB_POS - 1];
+    p1 = &rrixix[1][NB_POS - 1];
 
-	ptr_h1 = h;
-	cor = 0x00010000L;                          /* for rounding */
-	for (i = 0; i < NB_POS; i++)
-	{
-		cor += ((*ptr_h1) * (*ptr_h1) << 1);
-		ptr_h1++;
-		*p1-- = (extract_h(cor) >> 1);
-		cor += ((*ptr_h1) * (*ptr_h1) << 1);
-		ptr_h1++;
-		*p0-- = (extract_h(cor) >> 1);
-	}
+    ptr_h1 = h;
+    cor = 0x00010000L;                          /* for rounding */
+    for (i = 0; i < NB_POS; i++)
+    {
+        cor += ((*ptr_h1) * (*ptr_h1) << 1);
+        ptr_h1++;
+        *p1-- = (extract_h(cor) >> 1);
+        cor += ((*ptr_h1) * (*ptr_h1) << 1);
+        ptr_h1++;
+        *p0-- = (extract_h(cor) >> 1);
+    }
 
-	/*------------------------------------------------------------*
-	 * Compute rrixiy[][] needed for the codebook search.         *
-	 *------------------------------------------------------------*/
-	pos = MSIZE - 1;
-	pos2 = MSIZE - 2;
-	ptr_hf = h + 1;
+    /*------------------------------------------------------------*
+     * Compute rrixiy[][] needed for the codebook search.         *
+     *------------------------------------------------------------*/
+    pos = MSIZE - 1;
+    pos2 = MSIZE - 2;
+    ptr_hf = h + 1;
 
-	for (k = 0; k < NB_POS; k++)
-	{
-		p1 = &rrixiy[pos];
-		p0 = &rrixiy[pos2];
-		cor = 0x00008000L;                        /* for rounding */
-		ptr_h1 = h;
-		ptr_h2 = ptr_hf;
+    for (k = 0; k < NB_POS; k++)
+    {
+        p1 = &rrixiy[pos];
+        p0 = &rrixiy[pos2];
+        cor = 0x00008000L;                        /* for rounding */
+        ptr_h1 = h;
+        ptr_h2 = ptr_hf;
 
-		for (i = (k + 1); i < NB_POS; i++)
-		{
-			cor += ((*ptr_h1) * (*ptr_h2))<<1;
-			ptr_h1++;
-			ptr_h2++;
-			*p1 = extract_h(cor);
-			cor += ((*ptr_h1) * (*ptr_h2))<<1;
-			ptr_h1++;
-			ptr_h2++;
-			*p0 = extract_h(cor);
+        for (i = (k + 1); i < NB_POS; i++)
+        {
+            cor += ((*ptr_h1) * (*ptr_h2))<<1;
+            ptr_h1++;
+            ptr_h2++;
+            *p1 = extract_h(cor);
+            cor += ((*ptr_h1) * (*ptr_h2))<<1;
+            ptr_h1++;
+            ptr_h2++;
+            *p0 = extract_h(cor);
 
-			p1 -= (NB_POS + 1);
-			p0 -= (NB_POS + 1);
-		}
-		cor += ((*ptr_h1) * (*ptr_h2))<<1;
-		ptr_h1++;
-		ptr_h2++;
-		*p1 = extract_h(cor);
+            p1 -= (NB_POS + 1);
+            p0 -= (NB_POS + 1);
+        }
+        cor += ((*ptr_h1) * (*ptr_h2))<<1;
+        ptr_h1++;
+        ptr_h2++;
+        *p1 = extract_h(cor);
 
-		pos -= NB_POS;
-		pos2--;
-		ptr_hf += STEP;
-	}
+        pos -= NB_POS;
+        pos2--;
+        ptr_hf += STEP;
+    }
 
-	/*------------------------------------------------------------*
-	 * Modification of rrixiy[][] to take signs into account.     *
-	 *------------------------------------------------------------*/
-	p0 = rrixiy;
-	for (i = 0; i < L_SUBFR; i += STEP)
-	{
-		psign = sign;
-		if (psign[i] < 0)
-		{
-			psign = vec;
-		}
-		for (j = 1; j < L_SUBFR; j += STEP)
-		{
-			*p0 = vo_mult(*p0, psign[j]);
-			p0++;
-		}
-	}
-	/*-------------------------------------------------------------------*
-	 * search 2 pulses:                                                  *
-	 * ~@~~~~~~~~~~~~~~                                                  *
-	 * 32 pos x 32 pos = 1024 tests (all combinaisons is tested)         *
-	 *-------------------------------------------------------------------*/
-	p0 = rrixix[0];
-	p1 = rrixix[1];
-	p2 = rrixiy;
+    /*------------------------------------------------------------*
+     * Modification of rrixiy[][] to take signs into account.     *
+     *------------------------------------------------------------*/
+    p0 = rrixiy;
+    for (i = 0; i < L_SUBFR; i += STEP)
+    {
+        psign = sign;
+        if (psign[i] < 0)
+        {
+            psign = vec;
+        }
+        for (j = 1; j < L_SUBFR; j += STEP)
+        {
+            *p0 = vo_mult(*p0, psign[j]);
+            p0++;
+        }
+    }
+    /*-------------------------------------------------------------------*
+     * search 2 pulses:                                                  *
+     * ~@~~~~~~~~~~~~~~                                                  *
+     * 32 pos x 32 pos = 1024 tests (all combinaisons is tested)         *
+     *-------------------------------------------------------------------*/
+    p0 = rrixix[0];
+    p1 = rrixix[1];
+    p2 = rrixiy;
 
-	psk = -1;
-	alpk = 1;
-	ix = 0;
-	iy = 1;
+    psk = -1;
+    alpk = 1;
+    ix = 0;
+    iy = 1;
 
-	for (i0 = 0; i0 < L_SUBFR; i0 += STEP)
-	{
-		ps1 = dn[i0];
-		alp1 = (*p0++);
-		pos = -1;
-		for (i1 = 1; i1 < L_SUBFR; i1 += STEP)
-		{
-			ps2 = add1(ps1, dn[i1]);
-			alp2 = add1(alp1, add1(*p1++, *p2++));
-			sq = vo_mult(ps2, ps2);
-			s = vo_L_mult(alpk, sq) - ((psk * alp2)<<1);
-			if (s > 0)
-			{
-				psk = sq;
-				alpk = alp2;
-				pos = i1;
-			}
-		}
-		p1 -= NB_POS;
-		if (pos >= 0)
-		{
-			ix = i0;
-			iy = pos;
-		}
-	}
-	/*-------------------------------------------------------------------*
-	 * Build the codeword, the filtered codeword and index of codevector.*
-	 *-------------------------------------------------------------------*/
+    for (i0 = 0; i0 < L_SUBFR; i0 += STEP)
+    {
+        ps1 = dn[i0];
+        alp1 = (*p0++);
+        pos = -1;
+        for (i1 = 1; i1 < L_SUBFR; i1 += STEP)
+        {
+            ps2 = add1(ps1, dn[i1]);
+            alp2 = add1(alp1, add1(*p1++, *p2++));
+            sq = vo_mult(ps2, ps2);
+            s = vo_L_mult(alpk, sq) - ((psk * alp2)<<1);
+            if (s > 0)
+            {
+                psk = sq;
+                alpk = alp2;
+                pos = i1;
+            }
+        }
+        p1 -= NB_POS;
+        if (pos >= 0)
+        {
+            ix = i0;
+            iy = pos;
+        }
+    }
+    /*-------------------------------------------------------------------*
+     * Build the codeword, the filtered codeword and index of codevector.*
+     *-------------------------------------------------------------------*/
 
-	for (i = 0; i < L_SUBFR; i++)
-	{
-		code[i] = 0;
-	}
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        code[i] = 0;
+    }
 
-	i0 = (ix >> 1);                       /* pos of pulse 1 (0..31) */
-	i1 = (iy >> 1);                       /* pos of pulse 2 (0..31) */
-	if (sign[ix] > 0)
-	{
-		code[ix] = 512;                     /* codeword in Q9 format */
-		p0 = h - ix;
-	} else
-	{
-		code[ix] = -512;
-		i0 += NB_POS;
-		p0 = h_inv - ix;
-	}
-	if (sign[iy] > 0)
-	{
-		code[iy] = 512;
-		p1 = h - iy;
-	} else
-	{
-		code[iy] = -512;
-		i1 += NB_POS;
-		p1 = h_inv - iy;
-	}
-	*index = add1((i0 << 6), i1);
-	for (i = 0; i < L_SUBFR; i++)
-	{
-		y[i] = vo_shr_r(add1((*p0++), (*p1++)), 3);
-	}
-	return;
+    i0 = (ix >> 1);                       /* pos of pulse 1 (0..31) */
+    i1 = (iy >> 1);                       /* pos of pulse 2 (0..31) */
+    if (sign[ix] > 0)
+    {
+        code[ix] = 512;                     /* codeword in Q9 format */
+        p0 = h - ix;
+    } else
+    {
+        code[ix] = -512;
+        i0 += NB_POS;
+        p0 = h_inv - ix;
+    }
+    if (sign[iy] > 0)
+    {
+        code[iy] = 512;
+        p1 = h - iy;
+    } else
+    {
+        code[iy] = -512;
+        i1 += NB_POS;
+        p1 = h_inv - iy;
+    }
+    *index = add1((i0 << 6), i1);
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        y[i] = vo_shr_r(add1((*p0++), (*p1++)), 3);
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/c4t64fx.c b/media/libstagefright/codecs/amrwbenc/src/c4t64fx.c
index 1ecc11f..8cebb09 100644
--- a/media/libstagefright/codecs/amrwbenc/src/c4t64fx.c
+++ b/media/libstagefright/codecs/amrwbenc/src/c4t64fx.c
@@ -17,7 +17,7 @@
 /***********************************************************************
 *      File: c4t64fx.c                                                 *
 *                                                                      *
-*	   Description:Performs algebraic codebook search for higher modes *
+*      Description:Performs algebraic codebook search for higher modes *
 *                                                                      *
 ************************************************************************/
 
@@ -48,15 +48,15 @@
 #include "q_pulse.h"
 
 static Word16 tipos[36] = {
-	0, 1, 2, 3,                            /* starting point &ipos[0], 1st iter */
-	1, 2, 3, 0,                            /* starting point &ipos[4], 2nd iter */
-	2, 3, 0, 1,                            /* starting point &ipos[8], 3rd iter */
-	3, 0, 1, 2,                            /* starting point &ipos[12], 4th iter */
-	0, 1, 2, 3,
-	1, 2, 3, 0,
-	2, 3, 0, 1,
-	3, 0, 1, 2,
-	0, 1, 2, 3};                           /* end point for 24 pulses &ipos[35], 4th iter */
+    0, 1, 2, 3,                            /* starting point &ipos[0], 1st iter */
+    1, 2, 3, 0,                            /* starting point &ipos[4], 2nd iter */
+    2, 3, 0, 1,                            /* starting point &ipos[8], 3rd iter */
+    3, 0, 1, 2,                            /* starting point &ipos[12], 4th iter */
+    0, 1, 2, 3,
+    1, 2, 3, 0,
+    2, 3, 0, 1,
+    3, 0, 1, 2,
+    0, 1, 2, 3};                           /* end point for 24 pulses &ipos[35], 4th iter */
 
 #define NB_PULSE_MAX  24
 
@@ -70,751 +70,759 @@
 
 /* Private functions */
 void cor_h_vec_012(
-		Word16 h[],                           /* (i) scaled impulse response                 */
-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
-		Word16 track,                         /* (i) track to use                            */
-		Word16 sign[],                        /* (i) sign vector                             */
-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
-		);
+        Word16 h[],                           /* (i) scaled impulse response                 */
+        Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+        Word16 track,                         /* (i) track to use                            */
+        Word16 sign[],                        /* (i) sign vector                             */
+        Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+        Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+        Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+        );
 
 void cor_h_vec_012_asm(
-		Word16 h[],                           /* (i) scaled impulse response                 */
-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
-		Word16 track,                         /* (i) track to use                            */
-		Word16 sign[],                        /* (i) sign vector                             */
-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
-		);
+        Word16 h[],                           /* (i) scaled impulse response                 */
+        Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+        Word16 track,                         /* (i) track to use                            */
+        Word16 sign[],                        /* (i) sign vector                             */
+        Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+        Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+        Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+        );
 
 void cor_h_vec_30(
-		Word16 h[],                           /* (i) scaled impulse response                 */
-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
-		Word16 track,                         /* (i) track to use                            */
-		Word16 sign[],                        /* (i) sign vector                             */
-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
-		);
+        Word16 h[],                           /* (i) scaled impulse response                 */
+        Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+        Word16 track,                         /* (i) track to use                            */
+        Word16 sign[],                        /* (i) sign vector                             */
+        Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+        Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+        Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+        );
 
 void search_ixiy(
-		Word16 nb_pos_ix,                     /* (i) nb of pos for pulse 1 (1..8)       */
-		Word16 track_x,                       /* (i) track of pulse 1                   */
-		Word16 track_y,                       /* (i) track of pulse 2                   */
-		Word16 * ps,                          /* (i/o) correlation of all fixed pulses  */
-		Word16 * alp,                         /* (i/o) energy of all fixed pulses       */
-		Word16 * ix,                          /* (o) position of pulse 1                */
-		Word16 * iy,                          /* (o) position of pulse 2                */
-		Word16 dn[],                          /* (i) corr. between target and h[]       */
-		Word16 dn2[],                         /* (i) vector of selected positions       */
-		Word16 cor_x[],                       /* (i) corr. of pulse 1 with fixed pulses */
-		Word16 cor_y[],                       /* (i) corr. of pulse 2 with fixed pulses */
-		Word16 rrixiy[][MSIZE]                /* (i) corr. of pulse 1 with pulse 2   */
-		);
+        Word16 nb_pos_ix,                     /* (i) nb of pos for pulse 1 (1..8)       */
+        Word16 track_x,                       /* (i) track of pulse 1                   */
+        Word16 track_y,                       /* (i) track of pulse 2                   */
+        Word16 * ps,                          /* (i/o) correlation of all fixed pulses  */
+        Word16 * alp,                         /* (i/o) energy of all fixed pulses       */
+        Word16 * ix,                          /* (o) position of pulse 1                */
+        Word16 * iy,                          /* (o) position of pulse 2                */
+        Word16 dn[],                          /* (i) corr. between target and h[]       */
+        Word16 dn2[],                         /* (i) vector of selected positions       */
+        Word16 cor_x[],                       /* (i) corr. of pulse 1 with fixed pulses */
+        Word16 cor_y[],                       /* (i) corr. of pulse 2 with fixed pulses */
+        Word16 rrixiy[][MSIZE]                /* (i) corr. of pulse 1 with pulse 2   */
+        );
 
 
 void ACELP_4t64_fx(
-		Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */
-		Word16 cn[],                          /* (i) <12b : residual after long term prediction         */
-		Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */
-		Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */
-		Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */
-		Word16 nbbits,                        /* (i) : 20, 36, 44, 52, 64, 72 or 88 bits                */
-		Word16 ser_size,                      /* (i) : bit rate                                         */
-		Word16 _index[]                       /* (o) : index (20): 5+5+5+5 = 20 bits.                   */
-		/* (o) : index (36): 9+9+9+9 = 36 bits.                   */
-		/* (o) : index (44): 13+9+13+9 = 44 bits.                 */
-		/* (o) : index (52): 13+13+13+13 = 52 bits.               */
-		/* (o) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.       */
-		/* (o) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.     */
-		/* (o) : index (88): 11+11+11+11+11+11+11+11 = 88 bits.   */
-		)
+        Word16 dn[],                          /* (i) <12b : correlation between target x[] and H[]      */
+        Word16 cn[],                          /* (i) <12b : residual after long term prediction         */
+        Word16 H[],                           /* (i) Q12: impulse response of weighted synthesis filter */
+        Word16 code[],                        /* (o) Q9 : algebraic (fixed) codebook excitation         */
+        Word16 y[],                           /* (o) Q9 : filtered fixed codebook excitation            */
+        Word16 nbbits,                        /* (i) : 20, 36, 44, 52, 64, 72 or 88 bits                */
+        Word16 ser_size,                      /* (i) : bit rate                                         */
+        Word16 _index[]                       /* (o) : index (20): 5+5+5+5 = 20 bits.                   */
+        /* (o) : index (36): 9+9+9+9 = 36 bits.                   */
+        /* (o) : index (44): 13+9+13+9 = 44 bits.                 */
+        /* (o) : index (52): 13+13+13+13 = 52 bits.               */
+        /* (o) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.       */
+        /* (o) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.     */
+        /* (o) : index (88): 11+11+11+11+11+11+11+11 = 88 bits.   */
+        )
 {
-	Word32 i, j, k;
-	Word16 st, ix, iy, pos, index, track, nb_pulse, nbiter, j_temp;
-	Word16 psk, ps, alpk, alp, val, k_cn, k_dn, exp;
-	Word16 *p0, *p1, *p2, *p3, *psign;
-	Word16 *h, *h_inv, *ptr_h1, *ptr_h2, *ptr_hf, h_shift;
-	Word32 s, cor, L_tmp, L_index;
-	Word16 dn2[L_SUBFR], sign[L_SUBFR], vec[L_SUBFR];
-	Word16 ind[NPMAXPT * NB_TRACK];
-	Word16 codvec[NB_PULSE_MAX], nbpos[10];
-	Word16 cor_x[NB_POS], cor_y[NB_POS], pos_max[NB_TRACK];
-	Word16 h_buf[4 * L_SUBFR];
-	Word16 rrixix[NB_TRACK][NB_POS], rrixiy[NB_TRACK][MSIZE];
-	Word16 ipos[NB_PULSE_MAX];
+    Word32 i, j, k;
+    Word16 st, ix, iy, pos, index, track, nb_pulse, nbiter, j_temp;
+    Word16 psk, ps, alpk, alp, val, k_cn, k_dn, exp;
+    Word16 *p0, *p1, *p2, *p3, *psign;
+    Word16 *h, *h_inv, *ptr_h1, *ptr_h2, *ptr_hf, h_shift;
+    Word32 s, cor, L_tmp, L_index;
+    Word16 dn2[L_SUBFR], sign[L_SUBFR], vec[L_SUBFR];
+    Word16 ind[NPMAXPT * NB_TRACK];
+    Word16 codvec[NB_PULSE_MAX], nbpos[10];
+    Word16 cor_x[NB_POS], cor_y[NB_POS], pos_max[NB_TRACK];
+    Word16 h_buf[4 * L_SUBFR];
+    Word16 rrixix[NB_TRACK][NB_POS], rrixiy[NB_TRACK][MSIZE];
+    Word16 ipos[NB_PULSE_MAX];
 
-	switch (nbbits)
-	{
-		case 20:                               /* 20 bits, 4 pulses, 4 tracks */
-			nbiter = 4;                          /* 4x16x16=1024 loop */
-			alp = 8192;                          /* alp = 2.0 (Q12) */
-			nb_pulse = 4;
-			nbpos[0] = 4;
-			nbpos[1] = 8;
-			break;
-		case 36:                               /* 36 bits, 8 pulses, 4 tracks */
-			nbiter = 4;                          /* 4x20x16=1280 loop */
-			alp = 4096;                          /* alp = 1.0 (Q12) */
-			nb_pulse = 8;
-			nbpos[0] = 4;
-			nbpos[1] = 8;
-			nbpos[2] = 8;
-			break;
-		case 44:                               /* 44 bits, 10 pulses, 4 tracks */
-			nbiter = 4;                          /* 4x26x16=1664 loop */
-			alp = 4096;                          /* alp = 1.0 (Q12) */
-			nb_pulse = 10;
-			nbpos[0] = 4;
-			nbpos[1] = 6;
-			nbpos[2] = 8;
-			nbpos[3] = 8;
-			break;
-		case 52:                               /* 52 bits, 12 pulses, 4 tracks */
-			nbiter = 4;                          /* 4x26x16=1664 loop */
-			alp = 4096;                          /* alp = 1.0 (Q12) */
-			nb_pulse = 12;
-			nbpos[0] = 4;
-			nbpos[1] = 6;
-			nbpos[2] = 8;
-			nbpos[3] = 8;
-			break;
-		case 64:                               /* 64 bits, 16 pulses, 4 tracks */
-			nbiter = 3;                          /* 3x36x16=1728 loop */
-			alp = 3277;                          /* alp = 0.8 (Q12) */
-			nb_pulse = 16;
-			nbpos[0] = 4;
-			nbpos[1] = 4;
-			nbpos[2] = 6;
-			nbpos[3] = 6;
-			nbpos[4] = 8;
-			nbpos[5] = 8;
-			break;
-		case 72:                               /* 72 bits, 18 pulses, 4 tracks */
-			nbiter = 3;                          /* 3x35x16=1680 loop */
-			alp = 3072;                          /* alp = 0.75 (Q12) */
-			nb_pulse = 18;
-			nbpos[0] = 2;
-			nbpos[1] = 3;
-			nbpos[2] = 4;
-			nbpos[3] = 5;
-			nbpos[4] = 6;
-			nbpos[5] = 7;
-			nbpos[6] = 8;
-			break;
-		case 88:                               /* 88 bits, 24 pulses, 4 tracks */
-			if(ser_size > 462)
-				nbiter = 1;
-			else
-				nbiter = 2;                    /* 2x53x16=1696 loop */
+    switch (nbbits)
+    {
+        case 20:                               /* 20 bits, 4 pulses, 4 tracks */
+            nbiter = 4;                          /* 4x16x16=1024 loop */
+            alp = 8192;                          /* alp = 2.0 (Q12) */
+            nb_pulse = 4;
+            nbpos[0] = 4;
+            nbpos[1] = 8;
+            break;
+        case 36:                               /* 36 bits, 8 pulses, 4 tracks */
+            nbiter = 4;                          /* 4x20x16=1280 loop */
+            alp = 4096;                          /* alp = 1.0 (Q12) */
+            nb_pulse = 8;
+            nbpos[0] = 4;
+            nbpos[1] = 8;
+            nbpos[2] = 8;
+            break;
+        case 44:                               /* 44 bits, 10 pulses, 4 tracks */
+            nbiter = 4;                          /* 4x26x16=1664 loop */
+            alp = 4096;                          /* alp = 1.0 (Q12) */
+            nb_pulse = 10;
+            nbpos[0] = 4;
+            nbpos[1] = 6;
+            nbpos[2] = 8;
+            nbpos[3] = 8;
+            break;
+        case 52:                               /* 52 bits, 12 pulses, 4 tracks */
+            nbiter = 4;                          /* 4x26x16=1664 loop */
+            alp = 4096;                          /* alp = 1.0 (Q12) */
+            nb_pulse = 12;
+            nbpos[0] = 4;
+            nbpos[1] = 6;
+            nbpos[2] = 8;
+            nbpos[3] = 8;
+            break;
+        case 64:                               /* 64 bits, 16 pulses, 4 tracks */
+            nbiter = 3;                          /* 3x36x16=1728 loop */
+            alp = 3277;                          /* alp = 0.8 (Q12) */
+            nb_pulse = 16;
+            nbpos[0] = 4;
+            nbpos[1] = 4;
+            nbpos[2] = 6;
+            nbpos[3] = 6;
+            nbpos[4] = 8;
+            nbpos[5] = 8;
+            break;
+        case 72:                               /* 72 bits, 18 pulses, 4 tracks */
+            nbiter = 3;                          /* 3x35x16=1680 loop */
+            alp = 3072;                          /* alp = 0.75 (Q12) */
+            nb_pulse = 18;
+            nbpos[0] = 2;
+            nbpos[1] = 3;
+            nbpos[2] = 4;
+            nbpos[3] = 5;
+            nbpos[4] = 6;
+            nbpos[5] = 7;
+            nbpos[6] = 8;
+            break;
+        case 88:                               /* 88 bits, 24 pulses, 4 tracks */
+            if(ser_size > 462)
+                nbiter = 1;
+            else
+                nbiter = 2;                    /* 2x53x16=1696 loop */
 
-			alp = 2048;                          /* alp = 0.5 (Q12) */
-			nb_pulse = 24;
-			nbpos[0] = 2;
-			nbpos[1] = 2;
-			nbpos[2] = 3;
-			nbpos[3] = 4;
-			nbpos[4] = 5;
-			nbpos[5] = 6;
-			nbpos[6] = 7;
-			nbpos[7] = 8;
-			nbpos[8] = 8;
-			nbpos[9] = 8;
-			break;
-		default:
-			nbiter = 0;
-			alp = 0;
-			nb_pulse = 0;
-	}
+            alp = 2048;                          /* alp = 0.5 (Q12) */
+            nb_pulse = 24;
+            nbpos[0] = 2;
+            nbpos[1] = 2;
+            nbpos[2] = 3;
+            nbpos[3] = 4;
+            nbpos[4] = 5;
+            nbpos[5] = 6;
+            nbpos[6] = 7;
+            nbpos[7] = 8;
+            nbpos[8] = 8;
+            nbpos[9] = 8;
+            break;
+        default:
+            nbiter = 0;
+            alp = 0;
+            nb_pulse = 0;
+    }
 
-	for (i = 0; i < nb_pulse; i++)
-	{
-		codvec[i] = i;
-	}
+    for (i = 0; i < nb_pulse; i++)
+    {
+        codvec[i] = i;
+    }
 
-	/*----------------------------------------------------------------*
-	 * Find sign for each pulse position.                             *
-	 *----------------------------------------------------------------*/
-	/* calculate energy for normalization of cn[] and dn[] */
-	/* set k_cn = 32..32767 (ener_cn = 2^30..256-0) */
+    /*----------------------------------------------------------------*
+     * Find sign for each pulse position.                             *
+     *----------------------------------------------------------------*/
+    /* calculate energy for normalization of cn[] and dn[] */
+    /* set k_cn = 32..32767 (ener_cn = 2^30..256-0) */
 #ifdef ASM_OPT                  /* asm optimization branch */
-	s = Dot_product12_asm(cn, cn, L_SUBFR, &exp);
+    s = Dot_product12_asm(cn, cn, L_SUBFR, &exp);
 #else
-	s = Dot_product12(cn, cn, L_SUBFR, &exp);
+    s = Dot_product12(cn, cn, L_SUBFR, &exp);
 #endif
 
-	Isqrt_n(&s, &exp);
-	s = L_shl(s, (exp + 5));
-	k_cn = extract_h(L_add(s, 0x8000));
+    Isqrt_n(&s, &exp);
+    s = L_shl(s, (exp + 5));
+    k_cn = extract_h(L_add(s, 0x8000));
 
-	/* set k_dn = 32..512 (ener_dn = 2^30..2^22) */
+    /* set k_dn = 32..512 (ener_dn = 2^30..2^22) */
 #ifdef ASM_OPT                      /* asm optimization branch */
-	s = Dot_product12_asm(dn, dn, L_SUBFR, &exp);
+    s = Dot_product12_asm(dn, dn, L_SUBFR, &exp);
 #else
-	s = Dot_product12(dn, dn, L_SUBFR, &exp);
+    s = Dot_product12(dn, dn, L_SUBFR, &exp);
 #endif
 
-	Isqrt_n(&s, &exp);
-	k_dn = (L_shl(s, (exp + 5 + 3)) + 0x8000) >> 16;    /* k_dn = 256..4096 */
-	k_dn = vo_mult_r(alp, k_dn);              /* alp in Q12 */
+    Isqrt_n(&s, &exp);
+    k_dn = voround(L_shl(s, (exp + 5 + 3)));    /* k_dn = 256..4096 */
+    k_dn = vo_mult_r(alp, k_dn);              /* alp in Q12 */
 
-	/* mix normalized cn[] and dn[] */
-	p0 = cn;
-	p1 = dn;
-	p2 = dn2;
+    /* mix normalized cn[] and dn[] */
+    p0 = cn;
+    p1 = dn;
+    p2 = dn2;
 
-	for (i = 0; i < L_SUBFR/4; i++)
-	{
-		s = (k_cn* (*p0++))+(k_dn * (*p1++));
-		*p2++ = s >> 7;
-		s = (k_cn* (*p0++))+(k_dn * (*p1++));
-		*p2++ = s >> 7;
-		s = (k_cn* (*p0++))+(k_dn * (*p1++));
-		*p2++ = s >> 7;
-		s = (k_cn* (*p0++))+(k_dn * (*p1++));
-		*p2++ = s >> 7;
-	}
+    for (i = 0; i < L_SUBFR/4; i++)
+    {
+        s = L_add((k_cn* (*p0++)), (k_dn * (*p1++)));
+        *p2++ = s >> 7;
+        s = L_add((k_cn* (*p0++)), (k_dn * (*p1++)));
+        *p2++ = s >> 7;
+        s = L_add((k_cn* (*p0++)), (k_dn * (*p1++)));
+        *p2++ = s >> 7;
+        s = L_add((k_cn* (*p0++)), (k_dn * (*p1++)));
+        *p2++ = s >> 7;
+    }
 
-	/* set sign according to dn2[] = k_cn*cn[] + k_dn*dn[]    */
-	for(i = 0; i < L_SUBFR; i++)
-	{
-		val = dn[i];
-		ps = dn2[i];
-		if (ps >= 0)
-		{
-			sign[i] = 32767;             /* sign = +1 (Q12) */
-			vec[i] = -32768;
-		} else
-		{
-			sign[i] = -32768;            /* sign = -1 (Q12) */
-			vec[i] = 32767;
-			dn[i] = -val;
-			dn2[i] = -ps;
-		}
-	}
-	/*----------------------------------------------------------------*
-	 * Select NB_MAX position per track according to max of dn2[].    *
-	 *----------------------------------------------------------------*/
-	pos = 0;
-	for (i = 0; i < NB_TRACK; i++)
-	{
-		for (k = 0; k < NB_MAX; k++)
-		{
-			ps = -1;
-			for (j = i; j < L_SUBFR; j += STEP)
-			{
-				if(dn2[j] > ps)
-				{
-					ps = dn2[j];
-					pos = j;
-				}
-			}
-			dn2[pos] = (k - NB_MAX);     /* dn2 < 0 when position is selected */
-			if (k == 0)
-			{
-				pos_max[i] = pos;
-			}
-		}
-	}
+    /* set sign according to dn2[] = k_cn*cn[] + k_dn*dn[]    */
+    for(i = 0; i < L_SUBFR; i++)
+    {
+        val = dn[i];
+        ps = dn2[i];
+        if (ps >= 0)
+        {
+            sign[i] = 32767;             /* sign = +1 (Q12) */
+            vec[i] = -32768;
+        } else
+        {
+            sign[i] = -32768;            /* sign = -1 (Q12) */
+            vec[i] = 32767;
+            dn[i] = -val;
+            dn2[i] = -ps;
+        }
+    }
+    /*----------------------------------------------------------------*
+     * Select NB_MAX position per track according to max of dn2[].    *
+     *----------------------------------------------------------------*/
+    pos = 0;
+    for (i = 0; i < NB_TRACK; i++)
+    {
+        for (k = 0; k < NB_MAX; k++)
+        {
+            ps = -1;
+            for (j = i; j < L_SUBFR; j += STEP)
+            {
+                if(dn2[j] > ps)
+                {
+                    ps = dn2[j];
+                    pos = j;
+                }
+            }
+            dn2[pos] = (k - NB_MAX);     /* dn2 < 0 when position is selected */
+            if (k == 0)
+            {
+                pos_max[i] = pos;
+            }
+        }
+    }
 
-	/*--------------------------------------------------------------*
-	 * Scale h[] to avoid overflow and to get maximum of precision  *
-	 * on correlation.                                              *
-	 *                                                              *
-	 * Maximum of h[] (h[0]) is fixed to 2048 (MAX16 / 16).         *
-	 *  ==> This allow addition of 16 pulses without saturation.    *
-	 *                                                              *
-	 * Energy worst case (on resonant impulse response),            *
-	 * - energy of h[] is approximately MAX/16.                     *
-	 * - During search, the energy is divided by 8 to avoid         *
-	 *   overflow on "alp". (energy of h[] = MAX/128).              *
-	 *  ==> "alp" worst case detected is 22854 on sinusoidal wave.  *
-	 *--------------------------------------------------------------*/
+    /*--------------------------------------------------------------*
+     * Scale h[] to avoid overflow and to get maximum of precision  *
+     * on correlation.                                              *
+     *                                                              *
+     * Maximum of h[] (h[0]) is fixed to 2048 (MAX16 / 16).         *
+     *  ==> This allow addition of 16 pulses without saturation.    *
+     *                                                              *
+     * Energy worst case (on resonant impulse response),            *
+     * - energy of h[] is approximately MAX/16.                     *
+     * - During search, the energy is divided by 8 to avoid         *
+     *   overflow on "alp". (energy of h[] = MAX/128).              *
+     *  ==> "alp" worst case detected is 22854 on sinusoidal wave.  *
+     *--------------------------------------------------------------*/
 
-	/* impulse response buffer for fast computation */
+    /* impulse response buffer for fast computation */
 
-	h = h_buf;
-	h_inv = h_buf + (2 * L_SUBFR);
-	L_tmp = 0;
-	for (i = 0; i < L_SUBFR; i++)
-	{
-		*h++ = 0;
-		*h_inv++ = 0;
-		L_tmp += (H[i] * H[i]) << 1;
-	}
-	/* scale h[] down (/2) when energy of h[] is high with many pulses used */
-	val = extract_h(L_tmp);
-	h_shift = 0;
+    h = h_buf;
+    h_inv = h_buf + (2 * L_SUBFR);
+    L_tmp = 0;
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        *h++ = 0;
+        *h_inv++ = 0;
+        L_tmp = L_add(L_tmp, (H[i] * H[i]) << 1);
+    }
+    /* scale h[] down (/2) when energy of h[] is high with many pulses used */
+    val = extract_h(L_tmp);
+    h_shift = 0;
 
-	if ((nb_pulse >= 12) && (val > 1024))
-	{
-		h_shift = 1;
-	}
-	p0 = H;
-	p1 = h;
-	p2 = h_inv;
+    if ((nb_pulse >= 12) && (val > 1024))
+    {
+        h_shift = 1;
+    }
+    p0 = H;
+    p1 = h;
+    p2 = h_inv;
 
-	for (i = 0; i < L_SUBFR/4; i++)
-	{
-		*p1 = *p0++ >> h_shift;
-		*p2++ = -(*p1++);
-		*p1 = *p0++ >> h_shift;
-		*p2++ = -(*p1++);
-		*p1 = *p0++ >> h_shift;
-		*p2++ = -(*p1++);
-		*p1 = *p0++ >> h_shift;
-		*p2++ = -(*p1++);
-	}
+    for (i = 0; i < L_SUBFR/4; i++)
+    {
+        *p1 = *p0++ >> h_shift;
+        *p2++ = -(*p1++);
+        *p1 = *p0++ >> h_shift;
+        *p2++ = -(*p1++);
+        *p1 = *p0++ >> h_shift;
+        *p2++ = -(*p1++);
+        *p1 = *p0++ >> h_shift;
+        *p2++ = -(*p1++);
+    }
 
-	/*------------------------------------------------------------*
-	 * Compute rrixix[][] needed for the codebook search.         *
-	 * This algorithm compute impulse response energy of all      *
-	 * positions (16) in each track (4).       Total = 4x16 = 64. *
-	 *------------------------------------------------------------*/
+    /*------------------------------------------------------------*
+     * Compute rrixix[][] needed for the codebook search.         *
+     * This algorithm compute impulse response energy of all      *
+     * positions (16) in each track (4).       Total = 4x16 = 64. *
+     *------------------------------------------------------------*/
 
-	/* storage order --> i3i3, i2i2, i1i1, i0i0 */
+    /* storage order --> i3i3, i2i2, i1i1, i0i0 */
 
-	/* Init pointers to last position of rrixix[] */
-	p0 = &rrixix[0][NB_POS - 1];
-	p1 = &rrixix[1][NB_POS - 1];
-	p2 = &rrixix[2][NB_POS - 1];
-	p3 = &rrixix[3][NB_POS - 1];
+    /* Init pointers to last position of rrixix[] */
+    p0 = &rrixix[0][NB_POS - 1];
+    p1 = &rrixix[1][NB_POS - 1];
+    p2 = &rrixix[2][NB_POS - 1];
+    p3 = &rrixix[3][NB_POS - 1];
 
-	ptr_h1 = h;
-	cor = 0x00008000L;                             /* for rounding */
-	for (i = 0; i < NB_POS; i++)
-	{
-		cor += vo_L_mult((*ptr_h1), (*ptr_h1));
-		ptr_h1++;
-		*p3-- = extract_h(cor);
-		cor += vo_L_mult((*ptr_h1), (*ptr_h1));
-		ptr_h1++;
-		*p2-- = extract_h(cor);
-		cor += vo_L_mult((*ptr_h1), (*ptr_h1));
-		ptr_h1++;
-		*p1-- = extract_h(cor);
-		cor += vo_L_mult((*ptr_h1), (*ptr_h1));
-		ptr_h1++;
-		*p0-- = extract_h(cor);
-	}
+    ptr_h1 = h;
+    cor = 0x00008000L;                             /* for rounding */
+    for (i = 0; i < NB_POS; i++)
+    {
+        cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h1)));
+        ptr_h1++;
+        *p3-- = extract_h(cor);
+        cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h1)));
+        ptr_h1++;
+        *p2-- = extract_h(cor);
+        cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h1)));
+        ptr_h1++;
+        *p1-- = extract_h(cor);
+        cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h1)));
+        ptr_h1++;
+        *p0-- = extract_h(cor);
+    }
 
-	/*------------------------------------------------------------*
-	 * Compute rrixiy[][] needed for the codebook search.         *
-	 * This algorithm compute correlation between 2 pulses        *
-	 * (2 impulses responses) in 4 possible adjacents tracks.     *
-	 * (track 0-1, 1-2, 2-3 and 3-0).     Total = 4x16x16 = 1024. *
-	 *------------------------------------------------------------*/
+    /*------------------------------------------------------------*
+     * Compute rrixiy[][] needed for the codebook search.         *
+     * This algorithm compute correlation between 2 pulses        *
+     * (2 impulses responses) in 4 possible adjacents tracks.     *
+     * (track 0-1, 1-2, 2-3 and 3-0).     Total = 4x16x16 = 1024. *
+     *------------------------------------------------------------*/
 
-	/* storage order --> i2i3, i1i2, i0i1, i3i0 */
+    /* storage order --> i2i3, i1i2, i0i1, i3i0 */
 
-	pos = MSIZE - 1;
-	ptr_hf = h + 1;
+    pos = MSIZE - 1;
+    ptr_hf = h + 1;
 
-	for (k = 0; k < NB_POS; k++)
-	{
-		p3 = &rrixiy[2][pos];
-		p2 = &rrixiy[1][pos];
-		p1 = &rrixiy[0][pos];
-		p0 = &rrixiy[3][pos - NB_POS];
+    for (k = 0; k < NB_POS; k++)
+    {
+        p3 = &rrixiy[2][pos];
+        p2 = &rrixiy[1][pos];
+        p1 = &rrixiy[0][pos];
+        p0 = &rrixiy[3][pos - NB_POS];
 
-		cor = 0x00008000L;                   /* for rounding */
-		ptr_h1 = h;
-		ptr_h2 = ptr_hf;
+        cor = 0x00008000L;                   /* for rounding */
+        ptr_h1 = h;
+        ptr_h2 = ptr_hf;
 
-		for (i = k + 1; i < NB_POS; i++)
-		{
-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-			ptr_h1++;
-			ptr_h2++;
-			*p3 = extract_h(cor);
-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-			ptr_h1++;
-			ptr_h2++;
-			*p2 = extract_h(cor);
-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-			ptr_h1++;
-			ptr_h2++;
-			*p1 = extract_h(cor);
-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-			ptr_h1++;
-			ptr_h2++;
-			*p0 = extract_h(cor);
+        for (i = k + 1; i < NB_POS; i++)
+        {
+            cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+            ptr_h1++;
+            ptr_h2++;
+            *p3 = extract_h(cor);
+            cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+            ptr_h1++;
+            ptr_h2++;
+            *p2 = extract_h(cor);
+            cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+            ptr_h1++;
+            ptr_h2++;
+            *p1 = extract_h(cor);
+            cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+            ptr_h1++;
+            ptr_h2++;
+            *p0 = extract_h(cor);
 
-			p3 -= (NB_POS + 1);
-			p2 -= (NB_POS + 1);
-			p1 -= (NB_POS + 1);
-			p0 -= (NB_POS + 1);
-		}
-		cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-		ptr_h1++;
-		ptr_h2++;
-		*p3 = extract_h(cor);
-		cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-		ptr_h1++;
-		ptr_h2++;
-		*p2 = extract_h(cor);
-		cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-		ptr_h1++;
-		ptr_h2++;
-		*p1 = extract_h(cor);
+            p3 -= (NB_POS + 1);
+            p2 -= (NB_POS + 1);
+            p1 -= (NB_POS + 1);
+            p0 -= (NB_POS + 1);
+        }
+        cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+        ptr_h1++;
+        ptr_h2++;
+        *p3 = extract_h(cor);
+        cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+        ptr_h1++;
+        ptr_h2++;
+        *p2 = extract_h(cor);
+        cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+        ptr_h1++;
+        ptr_h2++;
+        *p1 = extract_h(cor);
 
-		pos -= NB_POS;
-		ptr_hf += STEP;
-	}
+        pos -= NB_POS;
+        ptr_hf += STEP;
+    }
 
-	/* storage order --> i3i0, i2i3, i1i2, i0i1 */
+    /* storage order --> i3i0, i2i3, i1i2, i0i1 */
 
-	pos = MSIZE - 1;
-	ptr_hf = h + 3;
+    pos = MSIZE - 1;
+    ptr_hf = h + 3;
 
-	for (k = 0; k < NB_POS; k++)
-	{
-		p3 = &rrixiy[3][pos];
-		p2 = &rrixiy[2][pos - 1];
-		p1 = &rrixiy[1][pos - 1];
-		p0 = &rrixiy[0][pos - 1];
+    for (k = 0; k < NB_POS; k++)
+    {
+        p3 = &rrixiy[3][pos];
+        p2 = &rrixiy[2][pos - 1];
+        p1 = &rrixiy[1][pos - 1];
+        p0 = &rrixiy[0][pos - 1];
 
-		cor = 0x00008000L;								/* for rounding */
-		ptr_h1 = h;
-		ptr_h2 = ptr_hf;
+        cor = 0x00008000L;                              /* for rounding */
+        ptr_h1 = h;
+        ptr_h2 = ptr_hf;
 
-		for (i = k + 1; i < NB_POS; i++)
-		{
-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-			ptr_h1++;
-			ptr_h2++;
-			*p3 = extract_h(cor);
-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-			ptr_h1++;
-			ptr_h2++;
-			*p2 = extract_h(cor);
-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-			ptr_h1++;
-			ptr_h2++;
-			*p1 = extract_h(cor);
-			cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-			ptr_h1++;
-			ptr_h2++;
-			*p0 = extract_h(cor);
+        for (i = k + 1; i < NB_POS; i++)
+        {
+            cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+            ptr_h1++;
+            ptr_h2++;
+            *p3 = extract_h(cor);
+            cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+            ptr_h1++;
+            ptr_h2++;
+            *p2 = extract_h(cor);
+            cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+            ptr_h1++;
+            ptr_h2++;
+            *p1 = extract_h(cor);
+            cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+            ptr_h1++;
+            ptr_h2++;
+            *p0 = extract_h(cor);
 
-			p3 -= (NB_POS + 1);
-			p2 -= (NB_POS + 1);
-			p1 -= (NB_POS + 1);
-			p0 -= (NB_POS + 1);
-		}
-		cor += vo_L_mult((*ptr_h1), (*ptr_h2));
-		ptr_h1++;
-		ptr_h2++;
-		*p3 = extract_h(cor);
+            p3 -= (NB_POS + 1);
+            p2 -= (NB_POS + 1);
+            p1 -= (NB_POS + 1);
+            p0 -= (NB_POS + 1);
+        }
+        cor = L_add(cor, vo_L_mult((*ptr_h1), (*ptr_h2)));
+        ptr_h1++;
+        ptr_h2++;
+        *p3 = extract_h(cor);
 
-		pos--;
-		ptr_hf += STEP;
-	}
+        pos--;
+        ptr_hf += STEP;
+    }
 
-	/*------------------------------------------------------------*
-	 * Modification of rrixiy[][] to take signs into account.     *
-	 *------------------------------------------------------------*/
+    /*------------------------------------------------------------*
+     * Modification of rrixiy[][] to take signs into account.     *
+     *------------------------------------------------------------*/
 
-	p0 = &rrixiy[0][0];
+    p0 = &rrixiy[0][0];
 
-	for (k = 0; k < NB_TRACK; k++)
-	{
-		j_temp = (k + 1)&0x03;
-		for (i = k; i < L_SUBFR; i += STEP)
-		{
-			psign = sign;
-			if (psign[i] < 0)
-			{
-				psign = vec;
-			}
-			j = j_temp;
-			for (; j < L_SUBFR; j += STEP)
-			{
-				*p0 = vo_mult(*p0, psign[j]);
-				p0++;
-			}
-		}
-	}
+    for (k = 0; k < NB_TRACK; k++)
+    {
+        j_temp = (k + 1)&0x03;
+        for (i = k; i < L_SUBFR; i += STEP)
+        {
+            psign = sign;
+            if (psign[i] < 0)
+            {
+                psign = vec;
+            }
+            j = j_temp;
+            for (; j < L_SUBFR; j += STEP)
+            {
+                *p0 = vo_mult(*p0, psign[j]);
+                p0++;
+            }
+        }
+    }
 
-	/*-------------------------------------------------------------------*
-	 *                       Deep first search                           *
-	 *-------------------------------------------------------------------*/
+    /*-------------------------------------------------------------------*
+     *                       Deep first search                           *
+     *-------------------------------------------------------------------*/
 
-	psk = -1;
-	alpk = 1;
+    psk = -1;
+    alpk = 1;
 
-	for (k = 0; k < nbiter; k++)
-	{
-		j_temp = k<<2;
-		for (i = 0; i < nb_pulse; i++)
-			ipos[i] = tipos[j_temp + i];
+    for (k = 0; k < nbiter; k++)
+    {
+        j_temp = k<<2;
+        for (i = 0; i < nb_pulse; i++)
+            ipos[i] = tipos[j_temp + i];
 
-		if(nbbits == 20)
-		{
-			pos = 0;
-			ps = 0;
-			alp = 0;
-			for (i = 0; i < L_SUBFR; i++)
-			{
-				vec[i] = 0;
-			}
-		} else if ((nbbits == 36) || (nbbits == 44))
-		{
-			/* first stage: fix 2 pulses */
-			pos = 2;
+        if(nbbits == 20)
+        {
+            pos = 0;
+            ps = 0;
+            alp = 0;
+            for (i = 0; i < L_SUBFR; i++)
+            {
+                vec[i] = 0;
+            }
+        } else if ((nbbits == 36) || (nbbits == 44))
+        {
+            /* first stage: fix 2 pulses */
+            pos = 2;
 
-			ix = ind[0] = pos_max[ipos[0]];
-			iy = ind[1] = pos_max[ipos[1]];
-			ps = dn[ix] + dn[iy];
-			i = ix >> 2;                /* ix / STEP */
-			j = iy >> 2;                /* iy / STEP */
-			s = rrixix[ipos[0]][i] << 13;
-			s += rrixix[ipos[1]][j] << 13;
-			i = (i << 4) + j;         /* (ix/STEP)*NB_POS + (iy/STEP) */
-			s += rrixiy[ipos[0]][i] << 14;
-			alp = (s + 0x8000) >> 16;
-			if (sign[ix] < 0)
-				p0 = h_inv - ix;
-			else
-				p0 = h - ix;
-			if (sign[iy] < 0)
-				p1 = h_inv - iy;
-			else
-				p1 = h - iy;
+            ix = ind[0] = pos_max[ipos[0]];
+            iy = ind[1] = pos_max[ipos[1]];
+            ps = dn[ix] + dn[iy];
+            i = ix >> 2;                /* ix / STEP */
+            j = iy >> 2;                /* iy / STEP */
+            s = rrixix[ipos[0]][i] << 13;
+            s += rrixix[ipos[1]][j] << 13;
+            i = (i << 4) + j;         /* (ix/STEP)*NB_POS + (iy/STEP) */
+            s += rrixiy[ipos[0]][i] << 14;
+            alp = (s + 0x8000) >> 16;
+            if (sign[ix] < 0)
+                p0 = h_inv - ix;
+            else
+                p0 = h - ix;
+            if (sign[iy] < 0)
+                p1 = h_inv - iy;
+            else
+                p1 = h - iy;
 
-			for (i = 0; i < L_SUBFR; i++)
-			{
-				vec[i] = (*p0++) + (*p1++);
-			}
+            for (i = 0; i < L_SUBFR; i++)
+            {
+                vec[i] = (*p0++) + (*p1++);
+            }
 
-			if(nbbits == 44)
-			{
-				ipos[8] = 0;
-				ipos[9] = 1;
-			}
-		} else
-		{
-			/* first stage: fix 4 pulses */
-			pos = 4;
+            if(nbbits == 44)
+            {
+                ipos[8] = 0;
+                ipos[9] = 1;
+            }
+        } else
+        {
+            /* first stage: fix 4 pulses */
+            pos = 4;
 
-			ix = ind[0] = pos_max[ipos[0]];
-			iy = ind[1] = pos_max[ipos[1]];
-			i = ind[2] = pos_max[ipos[2]];
-			j = ind[3] = pos_max[ipos[3]];
-			ps = add1(add1(add1(dn[ix], dn[iy]), dn[i]), dn[j]);
+            ix = ind[0] = pos_max[ipos[0]];
+            iy = ind[1] = pos_max[ipos[1]];
+            i = ind[2] = pos_max[ipos[2]];
+            j = ind[3] = pos_max[ipos[3]];
+            ps = add1(add1(add1(dn[ix], dn[iy]), dn[i]), dn[j]);
 
-			if (sign[ix] < 0)
-				p0 = h_inv - ix;
-			else
-				p0 = h - ix;
+            if (sign[ix] < 0)
+                p0 = h_inv - ix;
+            else
+                p0 = h - ix;
 
-			if (sign[iy] < 0)
-				p1 = h_inv - iy;
-			else
-				p1 = h - iy;
+            if (sign[iy] < 0)
+                p1 = h_inv - iy;
+            else
+                p1 = h - iy;
 
-			if (sign[i] < 0)
-				p2 = h_inv - i;
-			else
-				p2 = h - i;
+            if (sign[i] < 0)
+                p2 = h_inv - i;
+            else
+                p2 = h - i;
 
-			if (sign[j] < 0)
-				p3 = h_inv - j;
-			else
-				p3 = h - j;
+            if (sign[j] < 0)
+                p3 = h_inv - j;
+            else
+                p3 = h - j;
 
-			L_tmp = 0L;
-			for(i = 0; i < L_SUBFR; i++)
-			{
-				vec[i]  = add1(add1(add1(*p0++, *p1++), *p2++), *p3++);
-				L_tmp  += (vec[i] * vec[i]) << 1;
-			}
+            L_tmp = 0L;
+            for(i = 0; i < L_SUBFR; i++)
+            {
+                Word32 vecSq2;
+                vec[i]  = add1(add1(add1(*p0++, *p1++), *p2++), *p3++);
+                vecSq2 = (vec[i] * vec[i]) << 1;
+                if (vecSq2 > 0 && L_tmp > INT_MAX - vecSq2) {
+                    L_tmp = INT_MAX;
+                } else if (vecSq2 < 0 && L_tmp < INT_MIN - vecSq2) {
+                    L_tmp = INT_MIN;
+                } else {
+                    L_tmp  += vecSq2;
+                }
+            }
 
-			alp = ((L_tmp >> 3) + 0x8000) >> 16;
+            alp = ((L_tmp >> 3) + 0x8000) >> 16;
 
-			if(nbbits == 72)
-			{
-				ipos[16] = 0;
-				ipos[17] = 1;
-			}
-		}
+            if(nbbits == 72)
+            {
+                ipos[16] = 0;
+                ipos[17] = 1;
+            }
+        }
 
-		/* other stages of 2 pulses */
+        /* other stages of 2 pulses */
 
-		for (j = pos, st = 0; j < nb_pulse; j += 2, st++)
-		{
-			/*--------------------------------------------------*
-			 * Calculate correlation of all possible positions  *
-			 * of the next 2 pulses with previous fixed pulses. *
-			 * Each pulse can have 16 possible positions.       *
-			 *--------------------------------------------------*/
-			if(ipos[j] == 3)
-			{
-				cor_h_vec_30(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);
-			}
-			else
-			{
+        for (j = pos, st = 0; j < nb_pulse; j += 2, st++)
+        {
+            /*--------------------------------------------------*
+             * Calculate correlation of all possible positions  *
+             * of the next 2 pulses with previous fixed pulses. *
+             * Each pulse can have 16 possible positions.       *
+             *--------------------------------------------------*/
+            if(ipos[j] == 3)
+            {
+                cor_h_vec_30(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);
+            }
+            else
+            {
 #ifdef ASM_OPT                 /* asm optimization branch */
-				cor_h_vec_012_asm(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);
+                cor_h_vec_012_asm(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);
 #else
-				cor_h_vec_012(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);
+                cor_h_vec_012(h, vec, ipos[j], sign, rrixix, cor_x, cor_y);
 #endif
-			}
-			/*--------------------------------------------------*
-			 * Find best positions of 2 pulses.                 *
-			 *--------------------------------------------------*/
-			search_ixiy(nbpos[st], ipos[j], ipos[j + 1], &ps, &alp,
-					&ix, &iy, dn, dn2, cor_x, cor_y, rrixiy);
+            }
+            /*--------------------------------------------------*
+             * Find best positions of 2 pulses.                 *
+             *--------------------------------------------------*/
+            search_ixiy(nbpos[st], ipos[j], ipos[j + 1], &ps, &alp,
+                    &ix, &iy, dn, dn2, cor_x, cor_y, rrixiy);
 
-			ind[j] = ix;
-			ind[j + 1] = iy;
+            ind[j] = ix;
+            ind[j + 1] = iy;
 
-			if (sign[ix] < 0)
-				p0 = h_inv - ix;
-			else
-				p0 = h - ix;
-			if (sign[iy] < 0)
-				p1 = h_inv - iy;
-			else
-				p1 = h - iy;
+            if (sign[ix] < 0)
+                p0 = h_inv - ix;
+            else
+                p0 = h - ix;
+            if (sign[iy] < 0)
+                p1 = h_inv - iy;
+            else
+                p1 = h - iy;
 
-			for (i = 0; i < L_SUBFR; i+=4)
-			{
-				vec[i]   += add1((*p0++), (*p1++));
-				vec[i+1] += add1((*p0++), (*p1++));
-				vec[i+2] += add1((*p0++), (*p1++));
-				vec[i+3] += add1((*p0++), (*p1++));
-			}
-		}
-		/* memorise the best codevector */
-		ps = vo_mult(ps, ps);
-		s = vo_L_msu(vo_L_mult(alpk, ps), psk, alp);
-		if (s > 0)
-		{
-			psk = ps;
-			alpk = alp;
-			for (i = 0; i < nb_pulse; i++)
-			{
-				codvec[i] = ind[i];
-			}
-			for (i = 0; i < L_SUBFR; i++)
-			{
-				y[i] = vec[i];
-			}
-		}
-	}
-	/*-------------------------------------------------------------------*
-	 * Build the codeword, the filtered codeword and index of codevector.*
-	 *-------------------------------------------------------------------*/
-	for (i = 0; i < NPMAXPT * NB_TRACK; i++)
-	{
-		ind[i] = -1;
-	}
-	for (i = 0; i < L_SUBFR; i++)
-	{
-		code[i] = 0;
-		y[i] = vo_shr_r(y[i], 3);               /* Q12 to Q9 */
-	}
-	val = (512 >> h_shift);               /* codeword in Q9 format */
-	for (k = 0; k < nb_pulse; k++)
-	{
-		i = codvec[k];                       /* read pulse position */
-		j = sign[i];                         /* read sign           */
-		index = i >> 2;                 /* index = pos of pulse (0..15) */
-		track = (Word16) (i & 0x03);         /* track = i % NB_TRACK (0..3)  */
+            for (i = 0; i < L_SUBFR; i+=4)
+            {
+                vec[i]   += add1((*p0++), (*p1++));
+                vec[i+1] += add1((*p0++), (*p1++));
+                vec[i+2] += add1((*p0++), (*p1++));
+                vec[i+3] += add1((*p0++), (*p1++));
+            }
+        }
+        /* memorise the best codevector */
+        ps = vo_mult(ps, ps);
+        s = L_sub(vo_L_mult(alpk, ps), vo_L_mult(psk, alp));
+        if (s > 0)
+        {
+            psk = ps;
+            alpk = alp;
+            for (i = 0; i < nb_pulse; i++)
+            {
+                codvec[i] = ind[i];
+            }
+            for (i = 0; i < L_SUBFR; i++)
+            {
+                y[i] = vec[i];
+            }
+        }
+    }
+    /*-------------------------------------------------------------------*
+     * Build the codeword, the filtered codeword and index of codevector.*
+     *-------------------------------------------------------------------*/
+    for (i = 0; i < NPMAXPT * NB_TRACK; i++)
+    {
+        ind[i] = -1;
+    }
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        code[i] = 0;
+        y[i] = vo_shr_r(y[i], 3);               /* Q12 to Q9 */
+    }
+    val = (512 >> h_shift);               /* codeword in Q9 format */
+    for (k = 0; k < nb_pulse; k++)
+    {
+        i = codvec[k];                       /* read pulse position */
+        j = sign[i];                         /* read sign           */
+        index = i >> 2;                 /* index = pos of pulse (0..15) */
+        track = (Word16) (i & 0x03);         /* track = i % NB_TRACK (0..3)  */
 
-		if (j > 0)
-		{
-			code[i] += val;
-			codvec[k] += 128;
-		} else
-		{
-			code[i] -= val;
-			index += NB_POS;
-		}
+        if (j > 0)
+        {
+            code[i] += val;
+            codvec[k] += 128;
+        } else
+        {
+            code[i] -= val;
+            index += NB_POS;
+        }
 
-		i = (Word16)((vo_L_mult(track, NPMAXPT) >> 1));
+        i = (Word16)((vo_L_mult(track, NPMAXPT) >> 1));
 
-		while (ind[i] >= 0)
-		{
-			i += 1;
-		}
-		ind[i] = index;
-	}
+        while (ind[i] >= 0)
+        {
+            i += 1;
+        }
+        ind[i] = index;
+    }
 
-	k = 0;
-	/* Build index of codevector */
-	if(nbbits == 20)
-	{
-		for (track = 0; track < NB_TRACK; track++)
-		{
-			_index[track] = (Word16)(quant_1p_N1(ind[k], 4));
-			k += NPMAXPT;
-		}
-	} else if(nbbits == 36)
-	{
-		for (track = 0; track < NB_TRACK; track++)
-		{
-			_index[track] = (Word16)(quant_2p_2N1(ind[k], ind[k + 1], 4));
-			k += NPMAXPT;
-		}
-	} else if(nbbits == 44)
-	{
-		for (track = 0; track < NB_TRACK - 2; track++)
-		{
-			_index[track] = (Word16)(quant_3p_3N1(ind[k], ind[k + 1], ind[k + 2], 4));
-			k += NPMAXPT;
-		}
-		for (track = 2; track < NB_TRACK; track++)
-		{
-			_index[track] = (Word16)(quant_2p_2N1(ind[k], ind[k + 1], 4));
-			k += NPMAXPT;
-		}
-	} else if(nbbits == 52)
-	{
-		for (track = 0; track < NB_TRACK; track++)
-		{
-			_index[track] = (Word16)(quant_3p_3N1(ind[k], ind[k + 1], ind[k + 2], 4));
-			k += NPMAXPT;
-		}
-	} else if(nbbits == 64)
-	{
-		for (track = 0; track < NB_TRACK; track++)
-		{
-			L_index = quant_4p_4N(&ind[k], 4);
-			_index[track] = (Word16)((L_index >> 14) & 3);
-			_index[track + NB_TRACK] = (Word16)(L_index & 0x3FFF);
-			k += NPMAXPT;
-		}
-	} else if(nbbits == 72)
-	{
-		for (track = 0; track < NB_TRACK - 2; track++)
-		{
-			L_index = quant_5p_5N(&ind[k], 4);
-			_index[track] = (Word16)((L_index >> 10) & 0x03FF);
-			_index[track + NB_TRACK] = (Word16)(L_index & 0x03FF);
-			k += NPMAXPT;
-		}
-		for (track = 2; track < NB_TRACK; track++)
-		{
-			L_index = quant_4p_4N(&ind[k], 4);
-			_index[track] = (Word16)((L_index >> 14) & 3);
-			_index[track + NB_TRACK] = (Word16)(L_index & 0x3FFF);
-			k += NPMAXPT;
-		}
-	} else if(nbbits == 88)
-	{
-		for (track = 0; track < NB_TRACK; track++)
-		{
-			L_index = quant_6p_6N_2(&ind[k], 4);
-			_index[track] = (Word16)((L_index >> 11) & 0x07FF);
-			_index[track + NB_TRACK] = (Word16)(L_index & 0x07FF);
-			k += NPMAXPT;
-		}
-	}
-	return;
+    k = 0;
+    /* Build index of codevector */
+    if(nbbits == 20)
+    {
+        for (track = 0; track < NB_TRACK; track++)
+        {
+            _index[track] = (Word16)(quant_1p_N1(ind[k], 4));
+            k += NPMAXPT;
+        }
+    } else if(nbbits == 36)
+    {
+        for (track = 0; track < NB_TRACK; track++)
+        {
+            _index[track] = (Word16)(quant_2p_2N1(ind[k], ind[k + 1], 4));
+            k += NPMAXPT;
+        }
+    } else if(nbbits == 44)
+    {
+        for (track = 0; track < NB_TRACK - 2; track++)
+        {
+            _index[track] = (Word16)(quant_3p_3N1(ind[k], ind[k + 1], ind[k + 2], 4));
+            k += NPMAXPT;
+        }
+        for (track = 2; track < NB_TRACK; track++)
+        {
+            _index[track] = (Word16)(quant_2p_2N1(ind[k], ind[k + 1], 4));
+            k += NPMAXPT;
+        }
+    } else if(nbbits == 52)
+    {
+        for (track = 0; track < NB_TRACK; track++)
+        {
+            _index[track] = (Word16)(quant_3p_3N1(ind[k], ind[k + 1], ind[k + 2], 4));
+            k += NPMAXPT;
+        }
+    } else if(nbbits == 64)
+    {
+        for (track = 0; track < NB_TRACK; track++)
+        {
+            L_index = quant_4p_4N(&ind[k], 4);
+            _index[track] = (Word16)((L_index >> 14) & 3);
+            _index[track + NB_TRACK] = (Word16)(L_index & 0x3FFF);
+            k += NPMAXPT;
+        }
+    } else if(nbbits == 72)
+    {
+        for (track = 0; track < NB_TRACK - 2; track++)
+        {
+            L_index = quant_5p_5N(&ind[k], 4);
+            _index[track] = (Word16)((L_index >> 10) & 0x03FF);
+            _index[track + NB_TRACK] = (Word16)(L_index & 0x03FF);
+            k += NPMAXPT;
+        }
+        for (track = 2; track < NB_TRACK; track++)
+        {
+            L_index = quant_4p_4N(&ind[k], 4);
+            _index[track] = (Word16)((L_index >> 14) & 3);
+            _index[track + NB_TRACK] = (Word16)(L_index & 0x3FFF);
+            k += NPMAXPT;
+        }
+    } else if(nbbits == 88)
+    {
+        for (track = 0; track < NB_TRACK; track++)
+        {
+            L_index = quant_6p_6N_2(&ind[k], 4);
+            _index[track] = (Word16)((L_index >> 11) & 0x07FF);
+            _index[track + NB_TRACK] = (Word16)(L_index & 0x07FF);
+            k += NPMAXPT;
+        }
+    }
+    return;
 }
 
 
@@ -824,135 +832,135 @@
  * Compute correlations of h[] with vec[] for the specified track.   *
  *-------------------------------------------------------------------*/
 void cor_h_vec_30(
-		Word16 h[],                           /* (i) scaled impulse response                 */
-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
-		Word16 track,                         /* (i) track to use                            */
-		Word16 sign[],                        /* (i) sign vector                             */
-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
-		)
+        Word16 h[],                           /* (i) scaled impulse response                 */
+        Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+        Word16 track,                         /* (i) track to use                            */
+        Word16 sign[],                        /* (i) sign vector                             */
+        Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+        Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+        Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+        )
 {
-	Word32 i, j, pos, corr;
-	Word16 *p0, *p1, *p2,*p3,*cor_x,*cor_y;
-	Word32 L_sum1,L_sum2;
-	cor_x = cor_1;
-	cor_y = cor_2;
-	p0 = rrixix[track];
-	p3 = rrixix[0];
-	pos = track;
+    Word32 i, j, pos, corr;
+    Word16 *p0, *p1, *p2,*p3,*cor_x,*cor_y;
+    Word32 L_sum1,L_sum2;
+    cor_x = cor_1;
+    cor_y = cor_2;
+    p0 = rrixix[track];
+    p3 = rrixix[0];
+    pos = track;
 
-	for (i = 0; i < NB_POS; i+=2)
-	{
-		L_sum1 = L_sum2 = 0L;
-		p1 = h;
-		p2 = &vec[pos];
-		for (j=pos;j < L_SUBFR; j++)
-		{
-			L_sum1 += *p1 * *p2;
-			p2-=3;
-			L_sum2 += *p1++ * *p2;
-			p2+=4;
-		}
-		p2-=3;
-		L_sum2 += *p1++ * *p2++;
-		L_sum2 += *p1++ * *p2++;
-		L_sum2 += *p1++ * *p2++;
+    for (i = 0; i < NB_POS; i+=2)
+    {
+        L_sum1 = L_sum2 = 0L;
+        p1 = h;
+        p2 = &vec[pos];
+        for (j=pos;j < L_SUBFR; j++)
+        {
+            L_sum1 = L_add(L_sum1, *p1 * *p2);
+            p2-=3;
+            L_sum2 = L_add(L_sum2, *p1++ * *p2);
+            p2+=4;
+        }
+        p2-=3;
+        L_sum2 = L_add(L_sum2, *p1++ * *p2++);
+        L_sum2 = L_add(L_sum2, *p1++ * *p2++);
+        L_sum2 = L_add(L_sum2, *p1++ * *p2++);
 
-		L_sum1 = (L_sum1 << 2);
-		L_sum2 = (L_sum2 << 2);
+        L_sum1 = L_shl(L_sum1, 2);
+        L_sum2 = L_shl(L_sum2, 2);
 
-		corr = vo_round(L_sum1);
-		*cor_x++ = vo_mult(corr, sign[pos]) + (*p0++);
-		corr = vo_round(L_sum2);
-		*cor_y++ = vo_mult(corr, sign[pos-3]) + (*p3++);
-		pos += STEP;
+        corr = voround(L_sum1);
+        *cor_x++ = mult(corr, sign[pos]) + (*p0++);
+        corr = voround(L_sum2);
+        *cor_y++ = mult(corr, sign[pos-3]) + (*p3++);
+        pos += STEP;
 
-		L_sum1 = L_sum2 = 0L;
-		p1 = h;
-		p2 = &vec[pos];
-		for (j=pos;j < L_SUBFR; j++)
-		{
-			L_sum1 += *p1 * *p2;
-			p2-=3;
-			L_sum2 += *p1++ * *p2;
-			p2+=4;
-		}
-		p2-=3;
-		L_sum2 += *p1++ * *p2++;
-		L_sum2 += *p1++ * *p2++;
-		L_sum2 += *p1++ * *p2++;
+        L_sum1 = L_sum2 = 0L;
+        p1 = h;
+        p2 = &vec[pos];
+        for (j=pos;j < L_SUBFR; j++)
+        {
+            L_sum1 = L_add(L_sum1, *p1 * *p2);
+            p2-=3;
+            L_sum2 = L_add(L_sum2, *p1++ * *p2);
+            p2+=4;
+        }
+        p2-=3;
+        L_sum2 = L_add(L_sum2, *p1++ * *p2++);
+        L_sum2 = L_add(L_sum2, *p1++ * *p2++);
+        L_sum2 = L_add(L_sum2, *p1++ * *p2++);
 
-		L_sum1 = (L_sum1 << 2);
-		L_sum2 = (L_sum2 << 2);
+        L_sum1 = L_shl(L_sum1, 2);
+        L_sum2 = L_shl(L_sum2, 2);
 
-		corr = vo_round(L_sum1);
-		*cor_x++ = vo_mult(corr, sign[pos]) + (*p0++);
-		corr = vo_round(L_sum2);
-		*cor_y++ = vo_mult(corr, sign[pos-3]) + (*p3++);
-		pos += STEP;
-	}
-	return;
+        corr = voround(L_sum1);
+        *cor_x++ = mult(corr, sign[pos]) + (*p0++);
+        corr = voround(L_sum2);
+        *cor_y++ = mult(corr, sign[pos-3]) + (*p3++);
+        pos += STEP;
+    }
+    return;
 }
 
 void cor_h_vec_012(
-		Word16 h[],                           /* (i) scaled impulse response                 */
-		Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
-		Word16 track,                         /* (i) track to use                            */
-		Word16 sign[],                        /* (i) sign vector                             */
-		Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
-		Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
-		Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
-		)
+        Word16 h[],                           /* (i) scaled impulse response                 */
+        Word16 vec[],                         /* (i) scaled vector (/8) to correlate with h[] */
+        Word16 track,                         /* (i) track to use                            */
+        Word16 sign[],                        /* (i) sign vector                             */
+        Word16 rrixix[][NB_POS],              /* (i) correlation of h[x] with h[x]      */
+        Word16 cor_1[],                       /* (o) result of correlation (NB_POS elements) */
+        Word16 cor_2[]                        /* (o) result of correlation (NB_POS elements) */
+        )
 {
-	Word32 i, j, pos, corr;
-	Word16 *p0, *p1, *p2,*p3,*cor_x,*cor_y;
-	Word32 L_sum1,L_sum2;
-	cor_x = cor_1;
-	cor_y = cor_2;
-	p0 = rrixix[track];
-	p3 = rrixix[track+1];
-	pos = track;
+    Word32 i, j, pos, corr;
+    Word16 *p0, *p1, *p2,*p3,*cor_x,*cor_y;
+    Word32 L_sum1,L_sum2;
+    cor_x = cor_1;
+    cor_y = cor_2;
+    p0 = rrixix[track];
+    p3 = rrixix[track+1];
+    pos = track;
 
-	for (i = 0; i < NB_POS; i+=2)
-	{
-		L_sum1 = L_sum2 = 0L;
-		p1 = h;
-		p2 = &vec[pos];
-		for (j=62-pos ;j >= 0; j--)
-		{
-			L_sum1 += *p1 * *p2++;
-			L_sum2 += *p1++ * *p2;
-		}
-		L_sum1 += *p1 * *p2;
-		L_sum1 = (L_sum1 << 2);
-		L_sum2 = (L_sum2 << 2);
+    for (i = 0; i < NB_POS; i+=2)
+    {
+        L_sum1 = L_sum2 = 0L;
+        p1 = h;
+        p2 = &vec[pos];
+        for (j=62-pos ;j >= 0; j--)
+        {
+            L_sum1 = L_add(L_sum1, *p1 * *p2++);
+            L_sum2 = L_add(L_sum2, *p1++ * *p2);
+        }
+        L_sum1 = L_add(L_sum1, *p1 * *p2);
+        L_sum1 = L_shl(L_sum1, 2);
+        L_sum2 = L_shl(L_sum2, 2);
 
-		corr = (L_sum1 + 0x8000) >> 16;
-		cor_x[i] = vo_mult(corr, sign[pos]) + (*p0++);
-		corr = (L_sum2 + 0x8000) >> 16;
-		cor_y[i] = vo_mult(corr, sign[pos + 1]) + (*p3++);
-		pos += STEP;
+        corr = voround(L_sum1);
+        cor_x[i] = vo_mult(corr, sign[pos]) + (*p0++);
+        corr = voround(L_sum2);
+        cor_y[i] = vo_mult(corr, sign[pos + 1]) + (*p3++);
+        pos += STEP;
 
-		L_sum1 = L_sum2 = 0L;
-		p1 = h;
-		p2 = &vec[pos];
-		for (j= 62-pos;j >= 0; j--)
-		{
-			L_sum1 += *p1 * *p2++;
-			L_sum2 += *p1++ * *p2;
-		}
-		L_sum1 += *p1 * *p2;
-		L_sum1 = (L_sum1 << 2);
-		L_sum2 = (L_sum2 << 2);
+        L_sum1 = L_sum2 = 0L;
+        p1 = h;
+        p2 = &vec[pos];
+        for (j= 62-pos;j >= 0; j--)
+        {
+            L_sum1 = L_add(L_sum1, *p1 * *p2++);
+            L_sum2 = L_add(L_sum2, *p1++ * *p2);
+        }
+        L_sum1 = L_add(L_sum1, *p1 * *p2);
+        L_sum1 = L_shl(L_sum1, 2);
+        L_sum2 = L_shl(L_sum2, 2);
 
-		corr = (L_sum1 + 0x8000) >> 16;
-		cor_x[i+1] = vo_mult(corr, sign[pos]) + (*p0++);
-		corr = (L_sum2 + 0x8000) >> 16;
-		cor_y[i+1] = vo_mult(corr, sign[pos + 1]) + (*p3++);
-		pos += STEP;
-	}
-	return;
+        corr = voround(L_sum1);
+        cor_x[i+1] = vo_mult(corr, sign[pos]) + (*p0++);
+        corr = voround(L_sum2);
+        cor_y[i+1] = vo_mult(corr, sign[pos + 1]) + (*p3++);
+        pos += STEP;
+    }
+    return;
 }
 
 /*-------------------------------------------------------------------*
@@ -962,80 +970,80 @@
  *-------------------------------------------------------------------*/
 
 void search_ixiy(
-		Word16 nb_pos_ix,                     /* (i) nb of pos for pulse 1 (1..8)       */
-		Word16 track_x,                       /* (i) track of pulse 1                   */
-		Word16 track_y,                       /* (i) track of pulse 2                   */
-		Word16 * ps,                          /* (i/o) correlation of all fixed pulses  */
-		Word16 * alp,                         /* (i/o) energy of all fixed pulses       */
-		Word16 * ix,                          /* (o) position of pulse 1                */
-		Word16 * iy,                          /* (o) position of pulse 2                */
-		Word16 dn[],                          /* (i) corr. between target and h[]       */
-		Word16 dn2[],                         /* (i) vector of selected positions       */
-		Word16 cor_x[],                       /* (i) corr. of pulse 1 with fixed pulses */
-		Word16 cor_y[],                       /* (i) corr. of pulse 2 with fixed pulses */
-		Word16 rrixiy[][MSIZE]                /* (i) corr. of pulse 1 with pulse 2   */
-		)
+        Word16 nb_pos_ix,                     /* (i) nb of pos for pulse 1 (1..8)       */
+        Word16 track_x,                       /* (i) track of pulse 1                   */
+        Word16 track_y,                       /* (i) track of pulse 2                   */
+        Word16 * ps,                          /* (i/o) correlation of all fixed pulses  */
+        Word16 * alp,                         /* (i/o) energy of all fixed pulses       */
+        Word16 * ix,                          /* (o) position of pulse 1                */
+        Word16 * iy,                          /* (o) position of pulse 2                */
+        Word16 dn[],                          /* (i) corr. between target and h[]       */
+        Word16 dn2[],                         /* (i) vector of selected positions       */
+        Word16 cor_x[],                       /* (i) corr. of pulse 1 with fixed pulses */
+        Word16 cor_y[],                       /* (i) corr. of pulse 2 with fixed pulses */
+        Word16 rrixiy[][MSIZE]                /* (i) corr. of pulse 1 with pulse 2   */
+        )
 {
-	Word32 x, y, pos, thres_ix;
-	Word16 ps1, ps2, sq, sqk;
-	Word16 alp_16, alpk;
-	Word16 *p0, *p1, *p2;
-	Word32 s, alp0, alp1, alp2;
+    Word32 x, y, pos, thres_ix;
+    Word16 ps1, ps2, sq, sqk;
+    Word16 alp_16, alpk;
+    Word16 *p0, *p1, *p2;
+    Word32 s, alp0, alp1, alp2;
 
-	p0 = cor_x;
-	p1 = cor_y;
-	p2 = rrixiy[track_x];
+    p0 = cor_x;
+    p1 = cor_y;
+    p2 = rrixiy[track_x];
 
-	thres_ix = nb_pos_ix - NB_MAX;
+    thres_ix = nb_pos_ix - NB_MAX;
 
-	alp0 = L_deposit_h(*alp);
-	alp0 = (alp0 + 0x00008000L);       /* for rounding */
+    alp0 = L_deposit_h(*alp);
+    alp0 = (alp0 + 0x00008000L);       /* for rounding */
 
-	sqk = -1;
-	alpk = 1;
+    sqk = -1;
+    alpk = 1;
 
-	for (x = track_x; x < L_SUBFR; x += STEP)
-	{
-		ps1 = *ps + dn[x];
-		alp1 = alp0 + ((*p0++)<<13);
+    for (x = track_x; x < L_SUBFR; x += STEP)
+    {
+        ps1 = *ps + dn[x];
+        alp1 = L_add(alp0, ((*p0++)<<13));
 
-		if (dn2[x] < thres_ix)
-		{
-			pos = -1;
-			for (y = track_y; y < L_SUBFR; y += STEP)
-			{
-				ps2 = add1(ps1, dn[y]);
+        if (dn2[x] < thres_ix)
+        {
+            pos = -1;
+            for (y = track_y; y < L_SUBFR; y += STEP)
+            {
+                ps2 = add1(ps1, dn[y]);
 
-				alp2 = alp1 + ((*p1++)<<13);
-				alp2 = alp2 + ((*p2++)<<14);
-				alp_16 = extract_h(alp2);
-				sq = vo_mult(ps2, ps2);
-				s = vo_L_mult(alpk, sq) - ((sqk * alp_16)<<1);
+                alp2 = L_add(alp1, ((*p1++)<<13));
+                alp2 = L_add(alp2, ((*p2++)<<14));
+                alp_16 = extract_h(alp2);
+                sq = vo_mult(ps2, ps2);
+                s = L_sub(vo_L_mult(alpk, sq), L_mult(sqk, alp_16));
 
-				if (s > 0)
-				{
-					sqk = sq;
-					alpk = alp_16;
-					pos = y;
-				}
-			}
-			p1 -= NB_POS;
+                if (s > 0)
+                {
+                    sqk = sq;
+                    alpk = alp_16;
+                    pos = y;
+                }
+            }
+            p1 -= NB_POS;
 
-			if (pos >= 0)
-			{
-				*ix = x;
-				*iy = pos;
-			}
-		} else
-		{
-			p2 += NB_POS;
-		}
-	}
+            if (pos >= 0)
+            {
+                *ix = x;
+                *iy = pos;
+            }
+        } else
+        {
+            p2 += NB_POS;
+        }
+    }
 
-	*ps = add1(*ps, add1(dn[*ix], dn[*iy]));
-	*alp = alpk;
+    *ps = add1(*ps, add1(dn[*ix], dn[*iy]));
+    *alp = alpk;
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/convolve.c b/media/libstagefright/codecs/amrwbenc/src/convolve.c
index 4c1f7d4..8c24414 100644
--- a/media/libstagefright/codecs/amrwbenc/src/convolve.c
+++ b/media/libstagefright/codecs/amrwbenc/src/convolve.c
@@ -17,8 +17,8 @@
 /***********************************************************************
        File: convolve.c
 
-	   Description:Perform the convolution between two vectors x[] and h[]
-	               and write the result in the vector y[]
+       Description:Perform the convolution between two vectors x[] and h[]
+                   and write the result in the vector y[]
 
 ************************************************************************/
 
@@ -28,85 +28,90 @@
 #define UNUSED(x) (void)(x)
 
 void Convolve (
-		Word16 x[],        /* (i)     : input vector                           */
-		Word16 h[],        /* (i)     : impulse response                       */
-		Word16 y[],        /* (o)     : output vector                          */
-		Word16 L           /* (i)     : vector size                            */
-	      )
+        Word16 x[],        /* (i)     : input vector                           */
+        Word16 h[],        /* (i)     : impulse response                       */
+        Word16 y[],        /* (o)     : output vector                          */
+        Word16 L           /* (i)     : vector size                            */
+          )
 {
-	Word32  i, n;
-	Word16 *tmpH,*tmpX;
-	Word32 s;
+    Word32  i, n;
+    Word16 *tmpH,*tmpX;
+    Word32 s;
         UNUSED(L);
 
-	for (n = 0; n < 64;)
-	{
-		tmpH = h+n;
-		tmpX = x;
-		i=n+1;
-		s = vo_mult32((*tmpX++), (*tmpH--));i--;
-		while(i>0)
-		{
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			i -= 4;
-		}
-		y[n] = ((s<<1) + 0x8000)>>16;
-		n++;
+    for (n = 0; n < 64;)
+    {
+        tmpH = h+n;
+        tmpX = x;
+        i=n+1;
+        s = vo_mult32((*tmpX++), (*tmpH--));i--;
+        while(i>0)
+        {
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            i -= 4;
+        }
+        y[n] = voround(L_shl(s, 1));
+        n++;
 
-		tmpH = h+n;
-		tmpX = x;
-		i=n+1;
-		s =  vo_mult32((*tmpX++), (*tmpH--));i--;
-		s += vo_mult32((*tmpX++), (*tmpH--));i--;
+        tmpH = h+n;
+        tmpX = x;
+        i=n+1;
+        s =  vo_mult32((*tmpX++), (*tmpH--));
+        i--;
+        s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+        i--;
 
-		while(i>0)
-		{
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			i -= 4;
-		}
-		y[n] = ((s<<1) + 0x8000)>>16;
-		n++;
+        while(i>0)
+        {
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            i -= 4;
+        }
+        y[n] = voround(L_shl(s, 1));
+        n++;
 
-		tmpH = h+n;
-		tmpX = x;
-		i=n+1;
-		s =  vo_mult32((*tmpX++), (*tmpH--));i--;
-		s += vo_mult32((*tmpX++), (*tmpH--));i--;
-		s += vo_mult32((*tmpX++), (*tmpH--));i--;
+        tmpH = h+n;
+        tmpX = x;
+        i=n+1;
+        s =  vo_mult32((*tmpX++), (*tmpH--));
+        i--;
+        s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+        i--;
+        s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+        i--;
 
-		while(i>0)
-		{
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			i -= 4;
-		}
-		y[n] = ((s<<1) + 0x8000)>>16;
-		n++;
+        while(i>0)
+        {
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            i -= 4;
+        }
+        y[n] = voround(L_shl(s, 1));
+        n++;
 
-		s = 0;
-		tmpH = h+n;
-		tmpX = x;
-		i=n+1;
-		while(i>0)
-		{
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			s += vo_mult32((*tmpX++), (*tmpH--));
-			i -= 4;
-		}
-		y[n] = ((s<<1) + 0x8000)>>16;
-		n++;
-	}
-	return;
+        s = 0;
+        tmpH = h+n;
+        tmpX = x;
+        i=n+1;
+        while(i>0)
+        {
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            s = L_add(s, vo_mult32((*tmpX++), (*tmpH--)));
+            i -= 4;
+        }
+        y[n] = voround(L_shl(s, 1));
+        n++;
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/cor_h_x.c b/media/libstagefright/codecs/amrwbenc/src/cor_h_x.c
index d9245ed..e834396 100644
--- a/media/libstagefright/codecs/amrwbenc/src/cor_h_x.c
+++ b/media/libstagefright/codecs/amrwbenc/src/cor_h_x.c
@@ -17,10 +17,10 @@
 /***********************************************************************
 *       File: cor_h_x.c                                                *
 *                                                                      *
-*	   Description:Compute correlation between target "x[]" and "h[]"  *
-*	               Designed for codebook search (24 pulses, 4 tracks,  *
-*				   4 pulses per track, 16 positions in each track) to  *
-*				   avoid saturation.                                   *
+*      Description:Compute correlation between target "x[]" and "h[]"  *
+*                  Designed for codebook search (24 pulses, 4 tracks,  *
+*                  4 pulses per track, 16 positions in each track) to  *
+*                  avoid saturation.                                   *
 *                                                                      *
 ************************************************************************/
 
@@ -33,94 +33,100 @@
 #define STEP      4
 
 void cor_h_x(
-		Word16 h[],                           /* (i) Q12 : impulse response of weighted synthesis filter */
-		Word16 x[],                           /* (i) Q0  : target vector                                 */
-		Word16 dn[]                           /* (o) <12bit : correlation between target and h[]         */
-	    )
+        Word16 h[],                           /* (i) Q12 : impulse response of weighted synthesis filter */
+        Word16 x[],                           /* (i) Q0  : target vector                                 */
+        Word16 dn[]                           /* (o) <12bit : correlation between target and h[]         */
+        )
 {
-	Word32 i, j;
-	Word32 L_tmp, y32[L_SUBFR], L_tot;
-	Word16 *p1, *p2;
-	Word32 *p3;
-	Word32 L_max, L_max1, L_max2, L_max3;
-	/* first keep the result on 32 bits and find absolute maximum */
-	L_tot  = 1;
-	L_max  = 0;
-	L_max1 = 0;
-	L_max2 = 0;
-	L_max3 = 0;
-	for (i = 0; i < L_SUBFR; i += STEP)
-	{
-		L_tmp = 1;                                    /* 1 -> to avoid null dn[] */
-		p1 = &x[i];
-		p2 = &h[0];
-		for (j = i; j < L_SUBFR; j++)
-			L_tmp += vo_L_mult(*p1++, *p2++);
+    Word32 i, j;
+    Word32 L_tmp, y32[L_SUBFR], L_tot;
+    Word16 *p1, *p2;
+    Word32 *p3;
+    Word32 L_max, L_max1, L_max2, L_max3;
+    /* first keep the result on 32 bits and find absolute maximum */
+    L_tot  = 1;
+    L_max  = 0;
+    L_max1 = 0;
+    L_max2 = 0;
+    L_max3 = 0;
+    for (i = 0; i < L_SUBFR; i += STEP)
+    {
+        L_tmp = 1;                                    /* 1 -> to avoid null dn[] */
+        p1 = &x[i];
+        p2 = &h[0];
+        for (j = i; j < L_SUBFR; j++)
+            L_tmp = L_add(L_tmp, vo_L_mult(*p1++, *p2++));
 
-		y32[i] = L_tmp;
-		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;
-		if(L_tmp > L_max)
-		{
-			L_max = L_tmp;
-		}
+        y32[i] = L_tmp;
+        L_tmp = (L_tmp > 0)? L_tmp: (L_tmp == INT_MIN ? INT_MAX : -L_tmp);
+        if(L_tmp > L_max)
+        {
+            L_max = L_tmp;
+        }
 
-		L_tmp = 1L;
-		p1 = &x[i+1];
-		p2 = &h[0];
-		for (j = i+1; j < L_SUBFR; j++)
-			L_tmp += vo_L_mult(*p1++, *p2++);
+        L_tmp = 1L;
+        p1 = &x[i+1];
+        p2 = &h[0];
+        for (j = i+1; j < L_SUBFR; j++)
+            L_tmp = L_add(L_tmp, vo_L_mult(*p1++, *p2++));
 
-		y32[i+1] = L_tmp;
-		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;
-		if(L_tmp > L_max1)
-		{
-			L_max1 = L_tmp;
-		}
+        y32[i+1] = L_tmp;
+        L_tmp = (L_tmp > 0)? L_tmp: (L_tmp == INT_MIN ? INT_MAX : -L_tmp);
+        if(L_tmp > L_max1)
+        {
+            L_max1 = L_tmp;
+        }
 
-		L_tmp = 1;
-		p1 = &x[i+2];
-		p2 = &h[0];
-		for (j = i+2; j < L_SUBFR; j++)
-			L_tmp += vo_L_mult(*p1++, *p2++);
+        L_tmp = 1;
+        p1 = &x[i+2];
+        p2 = &h[0];
+        for (j = i+2; j < L_SUBFR; j++)
+            L_tmp = L_add(L_tmp, vo_L_mult(*p1++, *p2++));
 
-		y32[i+2] = L_tmp;
-		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;
-		if(L_tmp > L_max2)
-		{
-			L_max2 = L_tmp;
-		}
+        y32[i+2] = L_tmp;
+        L_tmp = (L_tmp > 0)? L_tmp: (L_tmp == INT_MIN ? INT_MAX : -L_tmp);
+        if(L_tmp > L_max2)
+        {
+            L_max2 = L_tmp;
+        }
 
-		L_tmp = 1;
-		p1 = &x[i+3];
-		p2 = &h[0];
-		for (j = i+3; j < L_SUBFR; j++)
-			L_tmp += vo_L_mult(*p1++, *p2++);
+        L_tmp = 1;
+        p1 = &x[i+3];
+        p2 = &h[0];
+        for (j = i+3; j < L_SUBFR; j++)
+            L_tmp = L_add(L_tmp, vo_L_mult(*p1++, *p2++));
 
-		y32[i+3] = L_tmp;
-		L_tmp = (L_tmp > 0)? L_tmp:-L_tmp;
-		if(L_tmp > L_max3)
-		{
-			L_max3 = L_tmp;
-		}
-	}
-	/* tot += 3*max / 8 */
-	L_max = ((L_max + L_max1 + L_max2 + L_max3) >> 2);
-	L_tot = vo_L_add(L_tot, L_max);       /* +max/4 */
-	L_tot = vo_L_add(L_tot, (L_max >> 1));  /* +max/8 */
+        y32[i+3] = L_tmp;
+        L_tmp = (L_tmp > 0)? L_tmp: (L_tmp == INT_MIN ? INT_MAX : -L_tmp);
+        if(L_tmp > L_max3)
+        {
+            L_max3 = L_tmp;
+        }
+    }
+    /* tot += 3*max / 8 */
+    if (L_max > INT_MAX - L_max1 ||
+            L_max + L_max1 > INT_MAX - L_max2 ||
+            L_max + L_max1 + L_max2 > INT_MAX - L_max3) {
+        L_max = INT_MAX >> 2;
+    } else {
+        L_max = ((L_max + L_max1 + L_max2 + L_max3) >> 2);
+    }
+    L_tot = vo_L_add(L_tot, L_max);       /* +max/4 */
+    L_tot = vo_L_add(L_tot, (L_max >> 1));  /* +max/8 */
 
-	/* Find the number of right shifts to do on y32[] so that    */
-	/* 6.0 x sumation of max of dn[] in each track not saturate. */
-	j = norm_l(L_tot) - 4;             /* 4 -> 16 x tot */
-	p1 = dn;
-	p3 = y32;
-	for (i = 0; i < L_SUBFR; i+=4)
-	{
-		*p1++ = vo_round(L_shl(*p3++, j));
-		*p1++ = vo_round(L_shl(*p3++, j));
-		*p1++ = vo_round(L_shl(*p3++, j));
-		*p1++ = vo_round(L_shl(*p3++, j));
-	}
-	return;
+    /* Find the number of right shifts to do on y32[] so that    */
+    /* 6.0 x sumation of max of dn[] in each track not saturate. */
+    j = norm_l(L_tot) - 4;             /* 4 -> 16 x tot */
+    p1 = dn;
+    p3 = y32;
+    for (i = 0; i < L_SUBFR; i+=4)
+    {
+        *p1++ = vo_round(L_shl(*p3++, j));
+        *p1++ = vo_round(L_shl(*p3++, j));
+        *p1++ = vo_round(L_shl(*p3++, j));
+        *p1++ = vo_round(L_shl(*p3++, j));
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/decim54.c b/media/libstagefright/codecs/amrwbenc/src/decim54.c
index 3b88514..e4c7940 100644
--- a/media/libstagefright/codecs/amrwbenc/src/decim54.c
+++ b/media/libstagefright/codecs/amrwbenc/src/decim54.c
@@ -17,7 +17,7 @@
 /***********************************************************************
 *      File: decim54.c                                                 *
 *                                                                      *
-*	   Description:Decimation of 16kHz signal to 12.8kHz           *
+*      Description:Decimation of 16kHz signal to 12.8kHz           *
 *                                                                      *
 ************************************************************************/
 
@@ -33,114 +33,114 @@
 
 /* Local functions */
 static void Down_samp(
-		Word16 * sig,                         /* input:  signal to downsampling  */
-		Word16 * sig_d,                       /* output: downsampled signal      */
-		Word16 L_frame_d                      /* input:  length of output        */
-		);
+        Word16 * sig,                         /* input:  signal to downsampling  */
+        Word16 * sig_d,                       /* output: downsampled signal      */
+        Word16 L_frame_d                      /* input:  length of output        */
+        );
 
 /* 1/5 resolution interpolation filter  (in Q14)  */
 /* -1.5dB @ 6kHz, -6dB @ 6.4kHz, -10dB @ 6.6kHz, -20dB @ 6.9kHz, -25dB @ 7kHz, -55dB @ 8kHz */
 
 static Word16 fir_down1[4][30] =
 {
-	{-5, 24, -50, 54, 0, -128, 294, -408, 344, 0, -647, 1505, -2379, 3034, 13107, 3034, -2379, 1505, -647, 0, 344, -408,
-	294, -128, 0, 54, -50, 24, -5, 0},
+    {-5, 24, -50, 54, 0, -128, 294, -408, 344, 0, -647, 1505, -2379, 3034, 13107, 3034, -2379, 1505, -647, 0, 344, -408,
+    294, -128, 0, 54, -50, 24, -5, 0},
 
-	{-6, 19, -26, 0, 77, -188, 270, -233, 0, 434, -964, 1366, -1293, 0, 12254, 6575, -2746, 1030, 0, -507, 601, -441,
-	198, 0, -95, 99, -58, 18, 0, -1},
+    {-6, 19, -26, 0, 77, -188, 270, -233, 0, 434, -964, 1366, -1293, 0, 12254, 6575, -2746, 1030, 0, -507, 601, -441,
+    198, 0, -95, 99, -58, 18, 0, -1},
 
-	{-3, 9, 0, -41, 111, -170, 153, 0, -295, 649, -888, 770, 0, -1997, 9894, 9894, -1997, 0, 770, -888, 649, -295, 0,
-	153, -170, 111, -41, 0, 9, -3},
+    {-3, 9, 0, -41, 111, -170, 153, 0, -295, 649, -888, 770, 0, -1997, 9894, 9894, -1997, 0, 770, -888, 649, -295, 0,
+    153, -170, 111, -41, 0, 9, -3},
 
-	{-1, 0, 18, -58, 99, -95, 0, 198, -441, 601, -507, 0, 1030, -2746, 6575, 12254, 0, -1293, 1366, -964, 434, 0,
-	-233, 270, -188, 77, 0, -26, 19, -6}
+    {-1, 0, 18, -58, 99, -95, 0, 198, -441, 601, -507, 0, 1030, -2746, 6575, 12254, 0, -1293, 1366, -964, 434, 0,
+    -233, 270, -188, 77, 0, -26, 19, -6}
 };
 
 void Init_Decim_12k8(
-		Word16 mem[]                          /* output: memory (2*NB_COEF_DOWN) set to zeros */
-		)
+        Word16 mem[]                          /* output: memory (2*NB_COEF_DOWN) set to zeros */
+        )
 {
-	Set_zero(mem, 2 * NB_COEF_DOWN);
-	return;
+    Set_zero(mem, 2 * NB_COEF_DOWN);
+    return;
 }
 
 void Decim_12k8(
-		Word16 sig16k[],                      /* input:  signal to downsampling  */
-		Word16 lg,                            /* input:  length of input         */
-		Word16 sig12k8[],                     /* output: decimated signal        */
-		Word16 mem[]                          /* in/out: memory (2*NB_COEF_DOWN) */
-	       )
+        Word16 sig16k[],                      /* input:  signal to downsampling  */
+        Word16 lg,                            /* input:  length of input         */
+        Word16 sig12k8[],                     /* output: decimated signal        */
+        Word16 mem[]                          /* in/out: memory (2*NB_COEF_DOWN) */
+           )
 {
-	Word16 lg_down;
-	Word16 signal[L_FRAME16k + (2 * NB_COEF_DOWN)];
+    Word16 lg_down;
+    Word16 signal[L_FRAME16k + (2 * NB_COEF_DOWN)];
 
-	Copy(mem, signal, 2 * NB_COEF_DOWN);
+    Copy(mem, signal, 2 * NB_COEF_DOWN);
 
-	Copy(sig16k, signal + (2 * NB_COEF_DOWN), lg);
+    Copy(sig16k, signal + (2 * NB_COEF_DOWN), lg);
 
-	lg_down = (lg * DOWN_FAC)>>15;
+    lg_down = (lg * DOWN_FAC)>>15;
 
-	Down_samp(signal + NB_COEF_DOWN, sig12k8, lg_down);
+    Down_samp(signal + NB_COEF_DOWN, sig12k8, lg_down);
 
-	Copy(signal + lg, mem, 2 * NB_COEF_DOWN);
+    Copy(signal + lg, mem, 2 * NB_COEF_DOWN);
 
-	return;
+    return;
 }
 
 static void Down_samp(
-		Word16 * sig,                         /* input:  signal to downsampling  */
-		Word16 * sig_d,                       /* output: downsampled signal      */
-		Word16 L_frame_d                      /* input:  length of output        */
-		)
+        Word16 * sig,                         /* input:  signal to downsampling  */
+        Word16 * sig_d,                       /* output: downsampled signal      */
+        Word16 L_frame_d                      /* input:  length of output        */
+        )
 {
-	Word32 i, j, frac, pos;
-	Word16 *x, *y;
-	Word32 L_sum;
+    Word32 i, j, frac, pos;
+    Word16 *x, *y;
+    Word32 L_sum;
 
-	pos = 0;                                 /* position is in Q2 -> 1/4 resolution  */
-	for (j = 0; j < L_frame_d; j++)
-	{
-		i = (pos >> 2);                   /* integer part     */
-		frac = pos & 3;                   /* fractional part */
-		x = sig + i - NB_COEF_DOWN + 1;
-		y = (Word16 *)(fir_down1 + frac);
+    pos = 0;                                 /* position is in Q2 -> 1/4 resolution  */
+    for (j = 0; j < L_frame_d; j++)
+    {
+        i = (pos >> 2);                   /* integer part     */
+        frac = pos & 3;                   /* fractional part */
+        x = sig + i - NB_COEF_DOWN + 1;
+        y = (Word16 *)(fir_down1 + frac);
 
-		L_sum = vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x++),(*y++));
-		L_sum += vo_mult32((*x),(*y));
+        L_sum = vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x++),(*y++));
+        L_sum += vo_mult32((*x),(*y));
 
-		L_sum = L_shl2(L_sum, 2);
-		sig_d[j] = extract_h(L_add(L_sum, 0x8000));
-		pos += FAC5;              /* pos + 5/4 */
-	}
-	return;
+        L_sum = L_shl2(L_sum, 2);
+        sig_d[j] = extract_h(L_add(L_sum, 0x8000));
+        pos += FAC5;              /* pos + 5/4 */
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/deemph.c b/media/libstagefright/codecs/amrwbenc/src/deemph.c
index 0c49d6b..cc27f6e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/deemph.c
+++ b/media/libstagefright/codecs/amrwbenc/src/deemph.c
@@ -17,9 +17,9 @@
 /***********************************************************************
 *       File: deemph.c                                                 *
 *                                                                      *
-*	   Description:filtering through 1/(1-mu z^ -1)                    *
-*	               Deemph2 --> signal is divided by 2                  *
-*				   Deemph_32 --> for 32 bits signal.                   *
+*      Description:filtering through 1/(1-mu z^ -1)                    *
+*                  Deemph2 --> signal is divided by 2                  *
+*                  Deemph_32 --> for 32 bits signal.                   *
 *                                                                      *
 ************************************************************************/
 
@@ -28,89 +28,92 @@
 #include "math_op.h"
 
 void Deemph(
-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
-		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
-		Word16 L,                             /* (i)     : vector size                            */
-		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
-	   )
+        Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+        Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
+        Word16 L,                             /* (i)     : vector size                            */
+        Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
+       )
 {
-	Word32 i;
-	Word32 L_tmp;
+    Word32 i;
+    Word32 L_tmp;
 
-	L_tmp = L_deposit_h(x[0]);
-	L_tmp = L_mac(L_tmp, *mem, mu);
-	x[0] = vo_round(L_tmp);
+    L_tmp = L_deposit_h(x[0]);
+    L_tmp = L_mac(L_tmp, *mem, mu);
+    x[0] = vo_round(L_tmp);
 
-	for (i = 1; i < L; i++)
-	{
-		L_tmp = L_deposit_h(x[i]);
-		L_tmp = L_mac(L_tmp, x[i - 1], mu);
-		x[i] = voround(L_tmp);
-	}
+    for (i = 1; i < L; i++)
+    {
+        L_tmp = L_deposit_h(x[i]);
+        L_tmp = L_mac(L_tmp, x[i - 1], mu);
+        x[i] = voround(L_tmp);
+    }
 
-	*mem = x[L - 1];
+    *mem = x[L - 1];
 
-	return;
+    return;
 }
 
 
 void Deemph2(
-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
-		Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
-		Word16 L,                             /* (i)     : vector size                            */
-		Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
-	    )
+        Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+        Word16 mu,                            /* (i) Q15 : deemphasis factor                      */
+        Word16 L,                             /* (i)     : vector size                            */
+        Word16 * mem                          /* (i/o)   : memory (y[-1])                         */
+        )
 {
-	Word32 i;
-	Word32 L_tmp;
-	L_tmp = x[0] << 15;
-	L_tmp += ((*mem) * mu)<<1;
-	x[0] = (L_tmp + 0x8000)>>16;
-	for (i = 1; i < L; i++)
-	{
-		L_tmp = x[i] << 15;
-		L_tmp += (x[i - 1] * mu)<<1;
-		x[i] = (L_tmp + 0x8000)>>16;
-	}
-	*mem = x[L - 1];
-	return;
+    Word32 i;
+    Word32 L_tmp;
+    L_tmp = x[0] << 15;
+    i = L_mult(*mem, mu);
+    L_tmp = L_add(L_tmp, i);
+    x[0] = voround(L_tmp);
+    for (i = 1; i < L; i++)
+    {
+        Word32 tmp;
+        L_tmp = x[i] << 15;
+        tmp = (x[i - 1] * mu)<<1;
+        L_tmp = L_add(L_tmp, tmp);
+        x[i] = voround(L_tmp);
+    }
+    *mem = x[L - 1];
+    return;
 }
 
 
 void Deemph_32(
-		Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
-		Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
-		Word16 y[],                           /* (o)     : output signal (x16)      */
-		Word16 mu,                            /* (i) Q15 : deemphasis factor        */
-		Word16 L,                             /* (i)     : vector size              */
-		Word16 * mem                          /* (i/o)   : memory (y[-1])           */
-	      )
+        Word16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+        Word16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+        Word16 y[],                           /* (o)     : output signal (x16)      */
+        Word16 mu,                            /* (i) Q15 : deemphasis factor        */
+        Word16 L,                             /* (i)     : vector size              */
+        Word16 * mem                          /* (i/o)   : memory (y[-1])           */
+          )
 {
-	Word16 fac;
-	Word32 i, L_tmp;
+    Word16 fac;
+    Word32 i, L_tmp;
 
-	fac = mu >> 1;                                /* Q15 --> Q14 */
+    fac = mu >> 1;                                /* Q15 --> Q14 */
 
-	L_tmp = L_deposit_h(x_hi[0]);
-	L_tmp += (x_lo[0] * 8)<<1;
-	L_tmp = (L_tmp << 3);
-	L_tmp += ((*mem) * fac)<<1;
-	L_tmp = (L_tmp << 1);
-	y[0] = (L_tmp + 0x8000)>>16;
+    L_tmp = L_deposit_h(x_hi[0]);
+    L_tmp += (x_lo[0] * 8)<<1;
+    L_tmp = (L_tmp << 3);
+    L_tmp += ((*mem) * fac)<<1;
+    L_tmp = (L_tmp << 1);
+    y[0] = (L_tmp + 0x8000)>>16;
 
-	for (i = 1; i < L; i++)
-	{
-		L_tmp = L_deposit_h(x_hi[i]);
-		L_tmp += (x_lo[i] * 8)<<1;
-		L_tmp = (L_tmp << 3);
-		L_tmp += (y[i - 1] * fac)<<1;
-		L_tmp = (L_tmp << 1);
-		y[i] = (L_tmp + 0x8000)>>16;
-	}
+    for (i = 1; i < L; i++)
+    {
+        L_tmp = L_deposit_h(x_hi[i]);
+        L_tmp += (x_lo[i] * 8)<<1;
+        L_tmp = (L_tmp << 3);
+        L_tmp += (y[i - 1] * fac)<<1;
+        L_tmp = (L_tmp << 1);
+        y[i] = (L_tmp + 0x8000)>>16;
+    }
 
-	*mem = y[L - 1];
+    *mem = y[L - 1];
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/dtx.c b/media/libstagefright/codecs/amrwbenc/src/dtx.c
index 2cfaced..6be8683 100644
--- a/media/libstagefright/codecs/amrwbenc/src/dtx.c
+++ b/media/libstagefright/codecs/amrwbenc/src/dtx.c
@@ -17,7 +17,7 @@
 /***********************************************************************
 *       File: dtx.c                                                    *
 *                                                                      *
-*	    Description:DTX functions                                  *
+*       Description:DTX functions                                  *
 *                                                                      *
 ************************************************************************/
 
@@ -35,33 +35,33 @@
 #include "mem_align.h"
 
 static void aver_isf_history(
-		Word16 isf_old[],
-		Word16 indices[],
-		Word32 isf_aver[]
-		);
+        Word16 isf_old[],
+        Word16 indices[],
+        Word32 isf_aver[]
+        );
 
 static void find_frame_indices(
-		Word16 isf_old_tx[],
-		Word16 indices[],
-		dtx_encState * st
-		);
+        Word16 isf_old_tx[],
+        Word16 indices[],
+        dtx_encState * st
+        );
 
 static Word16 dithering_control(
-		dtx_encState * st
-		);
+        dtx_encState * st
+        );
 
 /* excitation energy adjustment depending on speech coder mode used, Q7 */
 static Word16 en_adjust[9] =
 {
-	230,                                   /* mode0 = 7k  :  -5.4dB  */
-	179,                                   /* mode1 = 9k  :  -4.2dB  */
-	141,                                   /* mode2 = 12k :  -3.3dB  */
-	128,                                   /* mode3 = 14k :  -3.0dB  */
-	122,                                   /* mode4 = 16k :  -2.85dB */
-	115,                                   /* mode5 = 18k :  -2.7dB  */
-	115,                                   /* mode6 = 20k :  -2.7dB  */
-	115,                                   /* mode7 = 23k :  -2.7dB  */
-	115                                    /* mode8 = 24k :  -2.7dB  */
+    230,                                   /* mode0 = 7k  :  -5.4dB  */
+    179,                                   /* mode1 = 9k  :  -4.2dB  */
+    141,                                   /* mode2 = 12k :  -3.3dB  */
+    128,                                   /* mode3 = 14k :  -3.0dB  */
+    122,                                   /* mode4 = 16k :  -2.85dB */
+    115,                                   /* mode5 = 18k :  -2.7dB  */
+    115,                                   /* mode6 = 20k :  -2.7dB  */
+    115,                                   /* mode7 = 23k :  -2.7dB  */
+    115                                    /* mode8 = 24k :  -2.7dB  */
 };
 
 /**************************************************************************
@@ -71,24 +71,24 @@
 **************************************************************************/
 Word16 dtx_enc_init(dtx_encState ** st, Word16 isf_init[], VO_MEM_OPERATOR *pMemOP)
 {
-	dtx_encState *s;
+    dtx_encState *s;
 
-	if (st == (dtx_encState **) NULL)
-	{
-		fprintf(stderr, "dtx_enc_init: invalid parameter\n");
-		return -1;
-	}
-	*st = NULL;
+    if (st == (dtx_encState **) NULL)
+    {
+        fprintf(stderr, "dtx_enc_init: invalid parameter\n");
+        return -1;
+    }
+    *st = NULL;
 
-	/* allocate memory */
-	if ((s = (dtx_encState *)mem_malloc(pMemOP, sizeof(dtx_encState), 32, VO_INDEX_ENC_AMRWB)) == NULL)
-	{
-		fprintf(stderr, "dtx_enc_init: can not malloc state structure\n");
-		return -1;
-	}
-	dtx_enc_reset(s, isf_init);
-	*st = s;
-	return 0;
+    /* allocate memory */
+    if ((s = (dtx_encState *)mem_malloc(pMemOP, sizeof(dtx_encState), 32, VO_INDEX_ENC_AMRWB)) == NULL)
+    {
+        fprintf(stderr, "dtx_enc_init: can not malloc state structure\n");
+        return -1;
+    }
+    dtx_enc_reset(s, isf_init);
+    *st = s;
+    return 0;
 }
 
 /**************************************************************************
@@ -98,40 +98,40 @@
 **************************************************************************/
 Word16 dtx_enc_reset(dtx_encState * st, Word16 isf_init[])
 {
-	Word32 i;
+    Word32 i;
 
-	if (st == (dtx_encState *) NULL)
-	{
-		fprintf(stderr, "dtx_enc_reset: invalid parameter\n");
-		return -1;
-	}
-	st->hist_ptr = 0;
-	st->log_en_index = 0;
+    if (st == (dtx_encState *) NULL)
+    {
+        fprintf(stderr, "dtx_enc_reset: invalid parameter\n");
+        return -1;
+    }
+    st->hist_ptr = 0;
+    st->log_en_index = 0;
 
-	/* Init isf_hist[] */
-	for (i = 0; i < DTX_HIST_SIZE; i++)
-	{
-		Copy(isf_init, &st->isf_hist[i * M], M);
-	}
-	st->cng_seed = RANDOM_INITSEED;
+    /* Init isf_hist[] */
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        Copy(isf_init, &st->isf_hist[i * M], M);
+    }
+    st->cng_seed = RANDOM_INITSEED;
 
-	/* Reset energy history */
-	Set_zero(st->log_en_hist, DTX_HIST_SIZE);
+    /* Reset energy history */
+    Set_zero(st->log_en_hist, DTX_HIST_SIZE);
 
-	st->dtxHangoverCount = DTX_HANG_CONST;
-	st->decAnaElapsedCount = 32767;
+    st->dtxHangoverCount = DTX_HANG_CONST;
+    st->decAnaElapsedCount = 32767;
 
-	for (i = 0; i < 28; i++)
-	{
-		st->D[i] = 0;
-	}
+    for (i = 0; i < 28; i++)
+    {
+        st->D[i] = 0;
+    }
 
-	for (i = 0; i < DTX_HIST_SIZE - 1; i++)
-	{
-		st->sumD[i] = 0;
-	}
+    for (i = 0; i < DTX_HIST_SIZE - 1; i++)
+    {
+        st->sumD[i] = 0;
+    }
 
-	return 1;
+    return 1;
 }
 
 /**************************************************************************
@@ -141,12 +141,12 @@
 **************************************************************************/
 void dtx_enc_exit(dtx_encState ** st, VO_MEM_OPERATOR *pMemOP)
 {
-	if (st == NULL || *st == NULL)
-		return;
-	/* deallocate memory */
-	mem_free(pMemOP, *st, VO_INDEX_ENC_AMRWB);
-	*st = NULL;
-	return;
+    if (st == NULL || *st == NULL)
+        return;
+    /* deallocate memory */
+    mem_free(pMemOP, *st, VO_INDEX_ENC_AMRWB);
+    *st = NULL;
+    return;
 }
 
 
@@ -156,133 +156,133 @@
 *
 **************************************************************************/
 Word16 dtx_enc(
-		dtx_encState * st,                    /* i/o : State struct                                         */
-		Word16 isf[M],                        /* o   : CN ISF vector                                        */
-		Word16 * exc2,                        /* o   : CN excitation                                        */
-		Word16 ** prms
-	      )
+        dtx_encState * st,                    /* i/o : State struct                                         */
+        Word16 isf[M],                        /* o   : CN ISF vector                                        */
+        Word16 * exc2,                        /* o   : CN excitation                                        */
+        Word16 ** prms
+          )
 {
-	Word32 i, j;
-	Word16 indice[7];
-	Word16 log_en, gain, level, exp, exp0, tmp;
-	Word16 log_en_int_e, log_en_int_m;
-	Word32 L_isf[M], ener32, level32;
-	Word16 isf_order[3];
-	Word16 CN_dith;
+    Word32 i, j;
+    Word16 indice[7];
+    Word16 log_en, gain, level, exp, exp0, tmp;
+    Word16 log_en_int_e, log_en_int_m;
+    Word32 L_isf[M], ener32, level32;
+    Word16 isf_order[3];
+    Word16 CN_dith;
 
-	/* VOX mode computation of SID parameters */
-	log_en = 0;
-	for (i = 0; i < M; i++)
-	{
-		L_isf[i] = 0;
-	}
-	/* average energy and isf */
-	for (i = 0; i < DTX_HIST_SIZE; i++)
-	{
-		/* Division by DTX_HIST_SIZE = 8 has been done in dtx_buffer. log_en is in Q10 */
-		log_en = add(log_en, st->log_en_hist[i]);
+    /* VOX mode computation of SID parameters */
+    log_en = 0;
+    for (i = 0; i < M; i++)
+    {
+        L_isf[i] = 0;
+    }
+    /* average energy and isf */
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        /* Division by DTX_HIST_SIZE = 8 has been done in dtx_buffer. log_en is in Q10 */
+        log_en = add(log_en, st->log_en_hist[i]);
 
-	}
-	find_frame_indices(st->isf_hist, isf_order, st);
-	aver_isf_history(st->isf_hist, isf_order, L_isf);
+    }
+    find_frame_indices(st->isf_hist, isf_order, st);
+    aver_isf_history(st->isf_hist, isf_order, L_isf);
 
-	for (j = 0; j < M; j++)
-	{
-		isf[j] = (Word16)(L_isf[j] >> 3);  /* divide by 8 */
-	}
+    for (j = 0; j < M; j++)
+    {
+        isf[j] = (Word16)(L_isf[j] >> 3);  /* divide by 8 */
+    }
 
-	/* quantize logarithmic energy to 6 bits (-6 : 66 dB) which corresponds to -2:22 in log2(E).  */
-	/* st->log_en_index = (short)( (log_en + 2.0) * 2.625 ); */
+    /* quantize logarithmic energy to 6 bits (-6 : 66 dB) which corresponds to -2:22 in log2(E).  */
+    /* st->log_en_index = (short)( (log_en + 2.0) * 2.625 ); */
 
-	/* increase dynamics to 7 bits (Q8) */
-	log_en = (log_en >> 2);
+    /* increase dynamics to 7 bits (Q8) */
+    log_en = (log_en >> 2);
 
-	/* Add 2 in Q8 = 512 to get log2(E) between 0:24 */
-	log_en = add(log_en, 512);
+    /* Add 2 in Q8 = 512 to get log2(E) between 0:24 */
+    log_en = add(log_en, 512);
 
-	/* Multiply by 2.625 to get full 6 bit range. 2.625 = 21504 in Q13. The result is in Q6 */
-	log_en = mult(log_en, 21504);
+    /* Multiply by 2.625 to get full 6 bit range. 2.625 = 21504 in Q13. The result is in Q6 */
+    log_en = mult(log_en, 21504);
 
-	/* Quantize Energy */
-	st->log_en_index = shr(log_en, 6);
+    /* Quantize Energy */
+    st->log_en_index = shr(log_en, 6);
 
-	if(st->log_en_index > 63)
-	{
-		st->log_en_index = 63;
-	}
-	if (st->log_en_index < 0)
-	{
-		st->log_en_index = 0;
-	}
-	/* Quantize ISFs */
-	Qisf_ns(isf, isf, indice);
+    if(st->log_en_index > 63)
+    {
+        st->log_en_index = 63;
+    }
+    if (st->log_en_index < 0)
+    {
+        st->log_en_index = 0;
+    }
+    /* Quantize ISFs */
+    Qisf_ns(isf, isf, indice);
 
 
-	Parm_serial(indice[0], 6, prms);
-	Parm_serial(indice[1], 6, prms);
-	Parm_serial(indice[2], 6, prms);
-	Parm_serial(indice[3], 5, prms);
-	Parm_serial(indice[4], 5, prms);
+    Parm_serial(indice[0], 6, prms);
+    Parm_serial(indice[1], 6, prms);
+    Parm_serial(indice[2], 6, prms);
+    Parm_serial(indice[3], 5, prms);
+    Parm_serial(indice[4], 5, prms);
 
-	Parm_serial((st->log_en_index), 6, prms);
+    Parm_serial((st->log_en_index), 6, prms);
 
-	CN_dith = dithering_control(st);
-	Parm_serial(CN_dith, 1, prms);
+    CN_dith = dithering_control(st);
+    Parm_serial(CN_dith, 1, prms);
 
-	/* level = (float)( pow( 2.0f, (float)st->log_en_index / 2.625 - 2.0 ) );    */
-	/* log2(E) in Q9 (log2(E) lies in between -2:22) */
-	log_en = shl(st->log_en_index, 15 - 6);
+    /* level = (float)( pow( 2.0f, (float)st->log_en_index / 2.625 - 2.0 ) );    */
+    /* log2(E) in Q9 (log2(E) lies in between -2:22) */
+    log_en = shl(st->log_en_index, 15 - 6);
 
-	/* Divide by 2.625; log_en will be between 0:24  */
-	log_en = mult(log_en, 12483);
-	/* the result corresponds to log2(gain) in Q10 */
+    /* Divide by 2.625; log_en will be between 0:24  */
+    log_en = mult(log_en, 12483);
+    /* the result corresponds to log2(gain) in Q10 */
 
-	/* Find integer part  */
-	log_en_int_e = (log_en >> 10);
+    /* Find integer part  */
+    log_en_int_e = (log_en >> 10);
 
-	/* Find fractional part */
-	log_en_int_m = (Word16) (log_en & 0x3ff);
-	log_en_int_m = shl(log_en_int_m, 5);
+    /* Find fractional part */
+    log_en_int_m = (Word16) (log_en & 0x3ff);
+    log_en_int_m = shl(log_en_int_m, 5);
 
-	/* Subtract 2 from log_en in Q9, i.e divide the gain by 2 (energy by 4) */
-	/* Add 16 in order to have the result of pow2 in Q16 */
-	log_en_int_e = add(log_en_int_e, 16 - 1);
+    /* Subtract 2 from log_en in Q9, i.e divide the gain by 2 (energy by 4) */
+    /* Add 16 in order to have the result of pow2 in Q16 */
+    log_en_int_e = add(log_en_int_e, 16 - 1);
 
-	level32 = Pow2(log_en_int_e, log_en_int_m); /* Q16 */
-	exp0 = norm_l(level32);
-	level32 = (level32 << exp0);        /* level in Q31 */
-	exp0 = (15 - exp0);
-	level = extract_h(level32);            /* level in Q15 */
+    level32 = Pow2(log_en_int_e, log_en_int_m); /* Q16 */
+    exp0 = norm_l(level32);
+    level32 = (level32 << exp0);        /* level in Q31 */
+    exp0 = (15 - exp0);
+    level = extract_h(level32);            /* level in Q15 */
 
-	/* generate white noise vector */
-	for (i = 0; i < L_FRAME; i++)
-	{
-		exc2[i] = (Random(&(st->cng_seed)) >> 4);
-	}
+    /* generate white noise vector */
+    for (i = 0; i < L_FRAME; i++)
+    {
+        exc2[i] = (Random(&(st->cng_seed)) >> 4);
+    }
 
-	/* gain = level / sqrt(ener) * sqrt(L_FRAME) */
+    /* gain = level / sqrt(ener) * sqrt(L_FRAME) */
 
-	/* energy of generated excitation */
-	ener32 = Dot_product12(exc2, exc2, L_FRAME, &exp);
+    /* energy of generated excitation */
+    ener32 = Dot_product12(exc2, exc2, L_FRAME, &exp);
 
-	Isqrt_n(&ener32, &exp);
+    Isqrt_n(&ener32, &exp);
 
-	gain = extract_h(ener32);
+    gain = extract_h(ener32);
 
-	gain = mult(level, gain);              /* gain in Q15 */
+    gain = mult(level, gain);              /* gain in Q15 */
 
-	exp = add(exp0, exp);
+    exp = add(exp0, exp);
 
-	/* Multiply by sqrt(L_FRAME)=16, i.e. shift left by 4 */
-	exp += 4;
+    /* Multiply by sqrt(L_FRAME)=16, i.e. shift left by 4 */
+    exp += 4;
 
-	for (i = 0; i < L_FRAME; i++)
-	{
-		tmp = mult(exc2[i], gain);         /* Q0 * Q15 */
-		exc2[i] = shl(tmp, exp);
-	}
+    for (i = 0; i < L_FRAME; i++)
+    {
+        tmp = mult(exc2[i], gain);         /* Q0 * Q15 */
+        exc2[i] = shl(tmp, exp);
+    }
 
-	return 0;
+    return 0;
 }
 
 /**************************************************************************
@@ -291,45 +291,45 @@
 *
 **************************************************************************/
 Word16 dtx_buffer(
-		dtx_encState * st,                    /* i/o : State struct                    */
-		Word16 isf_new[],                     /* i   : isf vector                      */
-		Word32 enr,                           /* i   : residual energy (in L_FRAME)    */
-		Word16 codec_mode
-		)
+        dtx_encState * st,                    /* i/o : State struct                    */
+        Word16 isf_new[],                     /* i   : isf vector                      */
+        Word32 enr,                           /* i   : residual energy (in L_FRAME)    */
+        Word16 codec_mode
+        )
 {
-	Word16 log_en;
+    Word16 log_en;
 
-	Word16 log_en_e;
-	Word16 log_en_m;
-	st->hist_ptr = add(st->hist_ptr, 1);
-	if(st->hist_ptr == DTX_HIST_SIZE)
-	{
-		st->hist_ptr = 0;
-	}
-	/* copy lsp vector into buffer */
-	Copy(isf_new, &st->isf_hist[st->hist_ptr * M], M);
+    Word16 log_en_e;
+    Word16 log_en_m;
+    st->hist_ptr = add(st->hist_ptr, 1);
+    if(st->hist_ptr == DTX_HIST_SIZE)
+    {
+        st->hist_ptr = 0;
+    }
+    /* copy lsp vector into buffer */
+    Copy(isf_new, &st->isf_hist[st->hist_ptr * M], M);
 
-	/* log_en = (float)log10(enr*0.0059322)/(float)log10(2.0f);  */
-	Log2(enr, &log_en_e, &log_en_m);
+    /* log_en = (float)log10(enr*0.0059322)/(float)log10(2.0f);  */
+    Log2(enr, &log_en_e, &log_en_m);
 
-	/* convert exponent and mantissa to Word16 Q7. Q7 is used to simplify averaging in dtx_enc */
-	log_en = shl(log_en_e, 7);             /* Q7 */
-	log_en = add(log_en, shr(log_en_m, 15 - 7));
+    /* convert exponent and mantissa to Word16 Q7. Q7 is used to simplify averaging in dtx_enc */
+    log_en = shl(log_en_e, 7);             /* Q7 */
+    log_en = add(log_en, shr(log_en_m, 15 - 7));
 
-	/* Find energy per sample by multiplying with 0.0059322, i.e subtract log2(1/0.0059322) = 7.39722 The
-	 * constant 0.0059322 takes into account windowings and analysis length from autocorrelation
-	 * computations; 7.39722 in Q7 = 947  */
-	/* Subtract 3 dB = 0.99658 in log2(E) = 127 in Q7. */
-	/* log_en = sub( log_en, 947 + en_adjust[codec_mode] ); */
+    /* Find energy per sample by multiplying with 0.0059322, i.e subtract log2(1/0.0059322) = 7.39722 The
+     * constant 0.0059322 takes into account windowings and analysis length from autocorrelation
+     * computations; 7.39722 in Q7 = 947  */
+    /* Subtract 3 dB = 0.99658 in log2(E) = 127 in Q7. */
+    /* log_en = sub( log_en, 947 + en_adjust[codec_mode] ); */
 
-	/* Find energy per sample (divide by L_FRAME=256), i.e subtract log2(256) = 8.0  (1024 in Q7) */
-	/* Subtract 3 dB = 0.99658 in log2(E) = 127 in Q7. */
+    /* Find energy per sample (divide by L_FRAME=256), i.e subtract log2(256) = 8.0  (1024 in Q7) */
+    /* Subtract 3 dB = 0.99658 in log2(E) = 127 in Q7. */
 
-	log_en = sub(log_en, add(1024, en_adjust[codec_mode]));
+    log_en = sub(log_en, add(1024, en_adjust[codec_mode]));
 
-	/* Insert into the buffer */
-	st->log_en_hist[st->hist_ptr] = log_en;
-	return 0;
+    /* Insert into the buffer */
+    st->log_en_hist[st->hist_ptr] = log_en;
+    return 0;
 }
 
 /**************************************************************************
@@ -339,267 +339,267 @@
 *                                            the decoding side.
 **************************************************************************/
 void tx_dtx_handler(dtx_encState * st,     /* i/o : State struct           */
-		Word16 vad_flag,                      /* i   : vad decision           */
-		Word16 * usedMode                     /* i/o : mode changed or not    */
-		)
+        Word16 vad_flag,                      /* i   : vad decision           */
+        Word16 * usedMode                     /* i/o : mode changed or not    */
+        )
 {
 
-	/* this state machine is in synch with the GSMEFR txDtx machine      */
-	st->decAnaElapsedCount = add(st->decAnaElapsedCount, 1);
+    /* this state machine is in synch with the GSMEFR txDtx machine      */
+    st->decAnaElapsedCount = add(st->decAnaElapsedCount, 1);
 
-	if (vad_flag != 0)
-	{
-		st->dtxHangoverCount = DTX_HANG_CONST;
-	} else
-	{                                      /* non-speech */
-		if (st->dtxHangoverCount == 0)
-		{                                  /* out of decoder analysis hangover  */
-			st->decAnaElapsedCount = 0;
-			*usedMode = MRDTX;
-		} else
-		{                                  /* in possible analysis hangover */
-			st->dtxHangoverCount = sub(st->dtxHangoverCount, 1);
+    if (vad_flag != 0)
+    {
+        st->dtxHangoverCount = DTX_HANG_CONST;
+    } else
+    {                                      /* non-speech */
+        if (st->dtxHangoverCount == 0)
+        {                                  /* out of decoder analysis hangover  */
+            st->decAnaElapsedCount = 0;
+            *usedMode = MRDTX;
+        } else
+        {                                  /* in possible analysis hangover */
+            st->dtxHangoverCount = sub(st->dtxHangoverCount, 1);
 
-			/* decAnaElapsedCount + dtxHangoverCount < DTX_ELAPSED_FRAMES_THRESH */
-			if (sub(add(st->decAnaElapsedCount, st->dtxHangoverCount),
-						DTX_ELAPSED_FRAMES_THRESH) < 0)
-			{
-				*usedMode = MRDTX;
-				/* if short time since decoder update, do not add extra HO */
-			}
-			/* else override VAD and stay in speech mode *usedMode and add extra hangover */
-		}
-	}
+            /* decAnaElapsedCount + dtxHangoverCount < DTX_ELAPSED_FRAMES_THRESH */
+            if (sub(add(st->decAnaElapsedCount, st->dtxHangoverCount),
+                        DTX_ELAPSED_FRAMES_THRESH) < 0)
+            {
+                *usedMode = MRDTX;
+                /* if short time since decoder update, do not add extra HO */
+            }
+            /* else override VAD and stay in speech mode *usedMode and add extra hangover */
+        }
+    }
 
-	return;
+    return;
 }
 
 
 
 static void aver_isf_history(
-		Word16 isf_old[],
-		Word16 indices[],
-		Word32 isf_aver[]
-		)
+        Word16 isf_old[],
+        Word16 indices[],
+        Word32 isf_aver[]
+        )
 {
-	Word32 i, j, k;
-	Word16 isf_tmp[2 * M];
-	Word32 L_tmp;
+    Word32 i, j, k;
+    Word16 isf_tmp[2 * M];
+    Word32 L_tmp;
 
-	/* Memorize in isf_tmp[][] the ISF vectors to be replaced by */
-	/* the median ISF vector prior to the averaging               */
-	for (k = 0; k < 2; k++)
-	{
-		if ((indices[k] + 1) != 0)
-		{
-			for (i = 0; i < M; i++)
-			{
-				isf_tmp[k * M + i] = isf_old[indices[k] * M + i];
-				isf_old[indices[k] * M + i] = isf_old[indices[2] * M + i];
-			}
-		}
-	}
+    /* Memorize in isf_tmp[][] the ISF vectors to be replaced by */
+    /* the median ISF vector prior to the averaging               */
+    for (k = 0; k < 2; k++)
+    {
+        if ((indices[k] + 1) != 0)
+        {
+            for (i = 0; i < M; i++)
+            {
+                isf_tmp[k * M + i] = isf_old[indices[k] * M + i];
+                isf_old[indices[k] * M + i] = isf_old[indices[2] * M + i];
+            }
+        }
+    }
 
-	/* Perform the ISF averaging */
-	for (j = 0; j < M; j++)
-	{
-		L_tmp = 0;
+    /* Perform the ISF averaging */
+    for (j = 0; j < M; j++)
+    {
+        L_tmp = 0;
 
-		for (i = 0; i < DTX_HIST_SIZE; i++)
-		{
-			L_tmp = L_add(L_tmp, L_deposit_l(isf_old[i * M + j]));
-		}
-		isf_aver[j] = L_tmp;
-	}
+        for (i = 0; i < DTX_HIST_SIZE; i++)
+        {
+            L_tmp = L_add(L_tmp, L_deposit_l(isf_old[i * M + j]));
+        }
+        isf_aver[j] = L_tmp;
+    }
 
-	/* Retrieve from isf_tmp[][] the ISF vectors saved prior to averaging */
-	for (k = 0; k < 2; k++)
-	{
-		if ((indices[k] + 1) != 0)
-		{
-			for (i = 0; i < M; i++)
-			{
-				isf_old[indices[k] * M + i] = isf_tmp[k * M + i];
-			}
-		}
-	}
+    /* Retrieve from isf_tmp[][] the ISF vectors saved prior to averaging */
+    for (k = 0; k < 2; k++)
+    {
+        if ((indices[k] + 1) != 0)
+        {
+            for (i = 0; i < M; i++)
+            {
+                isf_old[indices[k] * M + i] = isf_tmp[k * M + i];
+            }
+        }
+    }
 
-	return;
+    return;
 }
 
 static void find_frame_indices(
-		Word16 isf_old_tx[],
-		Word16 indices[],
-		dtx_encState * st
-		)
+        Word16 isf_old_tx[],
+        Word16 indices[],
+        dtx_encState * st
+        )
 {
-	Word32 L_tmp, summin, summax, summax2nd;
-	Word16 i, j, tmp;
-	Word16 ptr;
+    Word32 L_tmp, summin, summax, summax2nd;
+    Word16 i, j, tmp;
+    Word16 ptr;
 
-	/* Remove the effect of the oldest frame from the column */
-	/* sum sumD[0..DTX_HIST_SIZE-1]. sumD[DTX_HIST_SIZE] is    */
-	/* not updated since it will be removed later.           */
+    /* Remove the effect of the oldest frame from the column */
+    /* sum sumD[0..DTX_HIST_SIZE-1]. sumD[DTX_HIST_SIZE] is    */
+    /* not updated since it will be removed later.           */
 
-	tmp = DTX_HIST_SIZE_MIN_ONE;
-	j = -1;
-	for (i = 0; i < DTX_HIST_SIZE_MIN_ONE; i++)
-	{
-		j = add(j, tmp);
-		st->sumD[i] = L_sub(st->sumD[i], st->D[j]);
-		tmp = sub(tmp, 1);
-	}
+    tmp = DTX_HIST_SIZE_MIN_ONE;
+    j = -1;
+    for (i = 0; i < DTX_HIST_SIZE_MIN_ONE; i++)
+    {
+        j = add(j, tmp);
+        st->sumD[i] = L_sub(st->sumD[i], st->D[j]);
+        tmp = sub(tmp, 1);
+    }
 
-	/* Shift the column sum sumD. The element sumD[DTX_HIST_SIZE-1]    */
-	/* corresponding to the oldest frame is removed. The sum of     */
-	/* the distances between the latest isf and other isfs, */
-	/* i.e. the element sumD[0], will be computed during this call. */
-	/* Hence this element is initialized to zero.                   */
+    /* Shift the column sum sumD. The element sumD[DTX_HIST_SIZE-1]    */
+    /* corresponding to the oldest frame is removed. The sum of     */
+    /* the distances between the latest isf and other isfs, */
+    /* i.e. the element sumD[0], will be computed during this call. */
+    /* Hence this element is initialized to zero.                   */
 
-	for (i = DTX_HIST_SIZE_MIN_ONE; i > 0; i--)
-	{
-		st->sumD[i] = st->sumD[i - 1];
-	}
-	st->sumD[0] = 0;
+    for (i = DTX_HIST_SIZE_MIN_ONE; i > 0; i--)
+    {
+        st->sumD[i] = st->sumD[i - 1];
+    }
+    st->sumD[0] = 0;
 
-	/* Remove the oldest frame from the distance matrix.           */
-	/* Note that the distance matrix is replaced by a one-         */
-	/* dimensional array to save static memory.                    */
+    /* Remove the oldest frame from the distance matrix.           */
+    /* Note that the distance matrix is replaced by a one-         */
+    /* dimensional array to save static memory.                    */
 
-	tmp = 0;
-	for (i = 27; i >= 12; i = (Word16) (i - tmp))
-	{
-		tmp = add(tmp, 1);
-		for (j = tmp; j > 0; j--)
-		{
-			st->D[i - j + 1] = st->D[i - j - tmp];
-		}
-	}
+    tmp = 0;
+    for (i = 27; i >= 12; i = (Word16) (i - tmp))
+    {
+        tmp = add(tmp, 1);
+        for (j = tmp; j > 0; j--)
+        {
+            st->D[i - j + 1] = st->D[i - j - tmp];
+        }
+    }
 
-	/* Compute the first column of the distance matrix D            */
-	/* (squared Euclidean distances from isf1[] to isf_old_tx[][]). */
+    /* Compute the first column of the distance matrix D            */
+    /* (squared Euclidean distances from isf1[] to isf_old_tx[][]). */
 
-	ptr = st->hist_ptr;
-	for (i = 1; i < DTX_HIST_SIZE; i++)
-	{
-		/* Compute the distance between the latest isf and the other isfs. */
-		ptr = sub(ptr, 1);
-		if (ptr < 0)
-		{
-			ptr = DTX_HIST_SIZE_MIN_ONE;
-		}
-		L_tmp = 0;
-		for (j = 0; j < M; j++)
-		{
-			tmp = sub(isf_old_tx[st->hist_ptr * M + j], isf_old_tx[ptr * M + j]);
-			L_tmp = L_mac(L_tmp, tmp, tmp);
-		}
-		st->D[i - 1] = L_tmp;
+    ptr = st->hist_ptr;
+    for (i = 1; i < DTX_HIST_SIZE; i++)
+    {
+        /* Compute the distance between the latest isf and the other isfs. */
+        ptr = sub(ptr, 1);
+        if (ptr < 0)
+        {
+            ptr = DTX_HIST_SIZE_MIN_ONE;
+        }
+        L_tmp = 0;
+        for (j = 0; j < M; j++)
+        {
+            tmp = sub(isf_old_tx[st->hist_ptr * M + j], isf_old_tx[ptr * M + j]);
+            L_tmp = L_mac(L_tmp, tmp, tmp);
+        }
+        st->D[i - 1] = L_tmp;
 
-		/* Update also the column sums. */
-		st->sumD[0] = L_add(st->sumD[0], st->D[i - 1]);
-		st->sumD[i] = L_add(st->sumD[i], st->D[i - 1]);
-	}
+        /* Update also the column sums. */
+        st->sumD[0] = L_add(st->sumD[0], st->D[i - 1]);
+        st->sumD[i] = L_add(st->sumD[i], st->D[i - 1]);
+    }
 
-	/* Find the minimum and maximum distances */
-	summax = st->sumD[0];
-	summin = st->sumD[0];
-	indices[0] = 0;
-	indices[2] = 0;
-	for (i = 1; i < DTX_HIST_SIZE; i++)
-	{
-		if (L_sub(st->sumD[i], summax) > 0)
-		{
-			indices[0] = i;
-			summax = st->sumD[i];
-		}
-		if (L_sub(st->sumD[i], summin) < 0)
-		{
-			indices[2] = i;
-			summin = st->sumD[i];
-		}
-	}
+    /* Find the minimum and maximum distances */
+    summax = st->sumD[0];
+    summin = st->sumD[0];
+    indices[0] = 0;
+    indices[2] = 0;
+    for (i = 1; i < DTX_HIST_SIZE; i++)
+    {
+        if (L_sub(st->sumD[i], summax) > 0)
+        {
+            indices[0] = i;
+            summax = st->sumD[i];
+        }
+        if (L_sub(st->sumD[i], summin) < 0)
+        {
+            indices[2] = i;
+            summin = st->sumD[i];
+        }
+    }
 
-	/* Find the second largest distance */
-	summax2nd = -2147483647L;
-	indices[1] = -1;
-	for (i = 0; i < DTX_HIST_SIZE; i++)
-	{
-		if ((L_sub(st->sumD[i], summax2nd) > 0) && (sub(i, indices[0]) != 0))
-		{
-			indices[1] = i;
-			summax2nd = st->sumD[i];
-		}
-	}
+    /* Find the second largest distance */
+    summax2nd = -2147483647L;
+    indices[1] = -1;
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        if ((L_sub(st->sumD[i], summax2nd) > 0) && (sub(i, indices[0]) != 0))
+        {
+            indices[1] = i;
+            summax2nd = st->sumD[i];
+        }
+    }
 
-	for (i = 0; i < 3; i++)
-	{
-		indices[i] = sub(st->hist_ptr, indices[i]);
-		if (indices[i] < 0)
-		{
-			indices[i] = add(indices[i], DTX_HIST_SIZE);
-		}
-	}
+    for (i = 0; i < 3; i++)
+    {
+        indices[i] = sub(st->hist_ptr, indices[i]);
+        if (indices[i] < 0)
+        {
+            indices[i] = add(indices[i], DTX_HIST_SIZE);
+        }
+    }
 
-	/* If maximum distance/MED_THRESH is smaller than minimum distance */
-	/* then the median ISF vector replacement is not performed         */
-	tmp = norm_l(summax);
-	summax = (summax << tmp);
-	summin = (summin << tmp);
-	L_tmp = L_mult(voround(summax), INV_MED_THRESH);
-	if(L_tmp <= summin)
-	{
-		indices[0] = -1;
-	}
-	/* If second largest distance/MED_THRESH is smaller than     */
-	/* minimum distance then the median ISF vector replacement is    */
-	/* not performed                                                 */
-	summax2nd = L_shl(summax2nd, tmp);
-	L_tmp = L_mult(voround(summax2nd), INV_MED_THRESH);
-	if(L_tmp <= summin)
-	{
-		indices[1] = -1;
-	}
-	return;
+    /* If maximum distance/MED_THRESH is smaller than minimum distance */
+    /* then the median ISF vector replacement is not performed         */
+    tmp = norm_l(summax);
+    summax = (summax << tmp);
+    summin = (summin << tmp);
+    L_tmp = L_mult(voround(summax), INV_MED_THRESH);
+    if(L_tmp <= summin)
+    {
+        indices[0] = -1;
+    }
+    /* If second largest distance/MED_THRESH is smaller than     */
+    /* minimum distance then the median ISF vector replacement is    */
+    /* not performed                                                 */
+    summax2nd = L_shl(summax2nd, tmp);
+    L_tmp = L_mult(voround(summax2nd), INV_MED_THRESH);
+    if(L_tmp <= summin)
+    {
+        indices[1] = -1;
+    }
+    return;
 }
 
 static Word16 dithering_control(
-		dtx_encState * st
-		)
+        dtx_encState * st
+        )
 {
-	Word16 tmp, mean, CN_dith, gain_diff;
-	Word32 i, ISF_diff;
+    Word16 tmp, mean, CN_dith, gain_diff;
+    Word32 i, ISF_diff;
 
-	/* determine how stationary the spectrum of background noise is */
-	ISF_diff = 0;
-	for (i = 0; i < 8; i++)
-	{
-		ISF_diff = L_add(ISF_diff, st->sumD[i]);
-	}
-	if ((ISF_diff >> 26) > 0)
-	{
-		CN_dith = 1;
-	} else
-	{
-		CN_dith = 0;
-	}
+    /* determine how stationary the spectrum of background noise is */
+    ISF_diff = 0;
+    for (i = 0; i < 8; i++)
+    {
+        ISF_diff = L_add(ISF_diff, st->sumD[i]);
+    }
+    if ((ISF_diff >> 26) > 0)
+    {
+        CN_dith = 1;
+    } else
+    {
+        CN_dith = 0;
+    }
 
-	/* determine how stationary the energy of background noise is */
-	mean = 0;
-	for (i = 0; i < DTX_HIST_SIZE; i++)
-	{
-		mean = add(mean, st->log_en_hist[i]);
-	}
-	mean = (mean >> 3);
-	gain_diff = 0;
-	for (i = 0; i < DTX_HIST_SIZE; i++)
-	{
-		tmp = abs_s(sub(st->log_en_hist[i], mean));
-		gain_diff = add(gain_diff, tmp);
-	}
-	if (gain_diff > GAIN_THR)
-	{
-		CN_dith = 1;
-	}
-	return CN_dith;
+    /* determine how stationary the energy of background noise is */
+    mean = 0;
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        mean = add(mean, st->log_en_hist[i]);
+    }
+    mean = (mean >> 3);
+    gain_diff = 0;
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        tmp = abs_s(sub(st->log_en_hist[i], mean));
+        gain_diff = add(gain_diff, tmp);
+    }
+    if (gain_diff > GAIN_THR)
+    {
+        CN_dith = 1;
+    }
+    return CN_dith;
 }
diff --git a/media/libstagefright/codecs/amrwbenc/src/g_pitch.c b/media/libstagefright/codecs/amrwbenc/src/g_pitch.c
index d681f2e..98ee87e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/g_pitch.c
+++ b/media/libstagefright/codecs/amrwbenc/src/g_pitch.c
@@ -17,9 +17,9 @@
 /***********************************************************************
 *      File: g_pitch.c                                                 *
 *                                                                      *
-*	   Description:Compute the gain of pitch. Result in Q12        *
-*	               if(gain < 0) gain = 0                           *
-*				   if(gain > 1.2) gain = 1.2           *
+*      Description:Compute the gain of pitch. Result in Q12        *
+*                  if(gain < 0) gain = 0                           *
+*                  if(gain > 1.2) gain = 1.2           *
 ************************************************************************/
 
 #include "typedef.h"
@@ -27,52 +27,52 @@
 #include "math_op.h"
 
 Word16 G_pitch(                            /* (o) Q14 : Gain of pitch lag saturated to 1.2   */
-		Word16 xn[],                          /* (i)     : Pitch target.                        */
-		Word16 y1[],                          /* (i)     : filtered adaptive codebook.          */
-		Word16 g_coeff[],                     /* : Correlations need for gain quantization.     */
-		Word16 L_subfr                        /* : Length of subframe.                          */
-	      )
+        Word16 xn[],                          /* (i)     : Pitch target.                        */
+        Word16 y1[],                          /* (i)     : filtered adaptive codebook.          */
+        Word16 g_coeff[],                     /* : Correlations need for gain quantization.     */
+        Word16 L_subfr                        /* : Length of subframe.                          */
+          )
 {
-	Word32 i;
-	Word16 xy, yy, exp_xy, exp_yy, gain;
-	/* Compute scalar product <y1[],y1[]> */
+    Word32 i;
+    Word16 xy, yy, exp_xy, exp_yy, gain;
+    /* Compute scalar product <y1[],y1[]> */
 #ifdef ASM_OPT                  /* asm optimization branch */
-	/* Compute scalar product <xn[],y1[]> */
-	xy = extract_h(Dot_product12_asm(xn, y1, L_subfr, &exp_xy));
-	yy = extract_h(Dot_product12_asm(y1, y1, L_subfr, &exp_yy));
+    /* Compute scalar product <xn[],y1[]> */
+    xy = extract_h(Dot_product12_asm(xn, y1, L_subfr, &exp_xy));
+    yy = extract_h(Dot_product12_asm(y1, y1, L_subfr, &exp_yy));
 
 #else
-	/* Compute scalar product <xn[],y1[]> */
-	xy = extract_h(Dot_product12(xn, y1, L_subfr, &exp_xy));
-	yy = extract_h(Dot_product12(y1, y1, L_subfr, &exp_yy));
+    /* Compute scalar product <xn[],y1[]> */
+    xy = extract_h(Dot_product12(xn, y1, L_subfr, &exp_xy));
+    yy = extract_h(Dot_product12(y1, y1, L_subfr, &exp_yy));
 
 #endif
 
-	g_coeff[0] = yy;
-	g_coeff[1] = exp_yy;
-	g_coeff[2] = xy;
-	g_coeff[3] = exp_xy;
+    g_coeff[0] = yy;
+    g_coeff[1] = exp_yy;
+    g_coeff[2] = xy;
+    g_coeff[3] = exp_xy;
 
-	/* If (xy < 0) gain = 0 */
-	if (xy < 0)
-		return ((Word16) 0);
+    /* If (xy < 0) gain = 0 */
+    if (xy < 0)
+        return ((Word16) 0);
 
-	/* compute gain = xy/yy */
+    /* compute gain = xy/yy */
 
-	xy >>= 1;                       /* Be sure xy < yy */
-	gain = div_s(xy, yy);
+    xy >>= 1;                       /* Be sure xy < yy */
+    gain = div_s(xy, yy);
 
-	i = exp_xy;
-	i -= exp_yy;
+    i = exp_xy;
+    i -= exp_yy;
 
-	gain = shl(gain, i);
+    gain = shl(gain, i);
 
-	/* if (gain > 1.2) gain = 1.2  in Q14 */
-	if(gain > 19661)
-	{
-		gain = 19661;
-	}
-	return (gain);
+    /* if (gain > 1.2) gain = 1.2  in Q14 */
+    if(gain > 19661)
+    {
+        gain = 19661;
+    }
+    return (gain);
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/gpclip.c b/media/libstagefright/codecs/amrwbenc/src/gpclip.c
index 800b3f9..4ce3daa 100644
--- a/media/libstagefright/codecs/amrwbenc/src/gpclip.c
+++ b/media/libstagefright/codecs/amrwbenc/src/gpclip.c
@@ -35,75 +35,75 @@
 
 
 void Init_gp_clip(
-		Word16 mem[]                          /* (o) : memory of gain of pitch clipping algorithm */
-		)
+        Word16 mem[]                          /* (o) : memory of gain of pitch clipping algorithm */
+        )
 {
-	mem[0] = DIST_ISF_MAX;
-	mem[1] = GAIN_PIT_MIN;
+    mem[0] = DIST_ISF_MAX;
+    mem[1] = GAIN_PIT_MIN;
 }
 
 
 Word16 Gp_clip(
-		Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */
-	      )
+        Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */
+          )
 {
-	Word16 clip = 0;
-	if ((mem[0] < DIST_ISF_THRES) && (mem[1] > GAIN_PIT_THRES))
-		clip = 1;
+    Word16 clip = 0;
+    if ((mem[0] < DIST_ISF_THRES) && (mem[1] > GAIN_PIT_THRES))
+        clip = 1;
 
-	return (clip);
+    return (clip);
 }
 
 
 void Gp_clip_test_isf(
-		Word16 isf[],                         /* (i)   : isf values (in frequency domain)           */
-		Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */
-		)
+        Word16 isf[],                         /* (i)   : isf values (in frequency domain)           */
+        Word16 mem[]                          /* (i/o) : memory of gain of pitch clipping algorithm */
+        )
 {
-	Word16 dist, dist_min;
-	Word32 i;
+    Word16 dist, dist_min;
+    Word32 i;
 
-	dist_min = vo_sub(isf[1], isf[0]);
+    dist_min = vo_sub(isf[1], isf[0]);
 
-	for (i = 2; i < M - 1; i++)
-	{
-		dist = vo_sub(isf[i], isf[i - 1]);
-		if(dist < dist_min)
-		{
-			dist_min = dist;
-		}
-	}
+    for (i = 2; i < M - 1; i++)
+    {
+        dist = vo_sub(isf[i], isf[i - 1]);
+        if(dist < dist_min)
+        {
+            dist_min = dist;
+        }
+    }
 
-	dist = extract_h(L_mac(vo_L_mult(26214, mem[0]), 6554, dist_min));
+    dist = extract_h(L_mac(vo_L_mult(26214, mem[0]), 6554, dist_min));
 
-	if (dist > DIST_ISF_MAX)
-	{
-		dist = DIST_ISF_MAX;
-	}
-	mem[0] = dist;
+    if (dist > DIST_ISF_MAX)
+    {
+        dist = DIST_ISF_MAX;
+    }
+    mem[0] = dist;
 
-	return;
+    return;
 }
 
 
 void Gp_clip_test_gain_pit(
-		Word16 gain_pit,                      /* (i) Q14 : gain of quantized pitch                    */
-		Word16 mem[]                          /* (i/o)   : memory of gain of pitch clipping algorithm */
-		)
+        Word16 gain_pit,                      /* (i) Q14 : gain of quantized pitch                    */
+        Word16 mem[]                          /* (i/o)   : memory of gain of pitch clipping algorithm */
+        )
 {
-	Word16 gain;
-	Word32 L_tmp;
-	L_tmp = (29491 * mem[1])<<1;
-	L_tmp += (3277 * gain_pit)<<1;
+    Word16 gain;
+    Word32 L_tmp;
+    L_tmp = (29491 * mem[1])<<1;
+    L_tmp += (3277 * gain_pit)<<1;
 
-	gain = extract_h(L_tmp);
+    gain = extract_h(L_tmp);
 
-	if(gain < GAIN_PIT_MIN)
-	{
-		gain = GAIN_PIT_MIN;
-	}
-	mem[1] = gain;
-	return;
+    if(gain < GAIN_PIT_MIN)
+    {
+        gain = GAIN_PIT_MIN;
+    }
+    mem[1] = gain;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/homing.c b/media/libstagefright/codecs/amrwbenc/src/homing.c
index 565040f..a96e7db 100644
--- a/media/libstagefright/codecs/amrwbenc/src/homing.c
+++ b/media/libstagefright/codecs/amrwbenc/src/homing.c
@@ -29,18 +29,18 @@
 
 Word16 encoder_homing_frame_test(Word16 input_frame[])
 {
-	Word32 i;
-	Word16 j = 0;
+    Word32 i;
+    Word16 j = 0;
 
-	/* check 320 input samples for matching EHF_MASK: defined in e_homing.h */
-	for (i = 0; i < L_FRAME16k; i++)
-	{
-		j = (Word16) (input_frame[i] ^ EHF_MASK);
+    /* check 320 input samples for matching EHF_MASK: defined in e_homing.h */
+    for (i = 0; i < L_FRAME16k; i++)
+    {
+        j = (Word16) (input_frame[i] ^ EHF_MASK);
 
-		if (j)
-			break;
-	}
+        if (j)
+            break;
+    }
 
-	return (Word16) (!j);
+    return (Word16) (!j);
 }
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp400.c b/media/libstagefright/codecs/amrwbenc/src/hp400.c
index a6f9701..c658a92 100644
--- a/media/libstagefright/codecs/amrwbenc/src/hp400.c
+++ b/media/libstagefright/codecs/amrwbenc/src/hp400.c
@@ -50,56 +50,56 @@
 
 void Init_HP400_12k8(Word16 mem[])
 {
-	Set_zero(mem, 6);
+    Set_zero(mem, 6);
 }
 
 
 void HP400_12k8(
-		Word16 signal[],                      /* input signal / output is divided by 16 */
-		Word16 lg,                            /* lenght of signal    */
-		Word16 mem[]                          /* filter memory [6]   */
-	       )
+        Word16 signal[],                      /* input signal / output is divided by 16 */
+        Word16 lg,                            /* lenght of signal    */
+        Word16 mem[]                          /* filter memory [6]   */
+           )
 {
-	Word16  x2;
-	Word16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;
-	Word32 L_tmp;
-	Word32 num;
-	y2_hi = *mem++;
-	y2_lo = *mem++;
-	y1_hi = *mem++;
-	y1_lo = *mem++;
-	x0 = *mem++;
-	x1 = *mem;
-	num = (Word32)lg;
-	do
-	{
-		x2 = x1;
-		x1 = x0;
-		x0 = *signal;
-		/* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2]  */
-		/* + a[1]*y[i-1] + a[2] * y[i-2];  */
-		L_tmp = 8192L;                    /* rounding to maximise precision */
-		L_tmp += y1_lo * a[1];
-		L_tmp += y2_lo * a[2];
-		L_tmp = L_tmp >> 14;
-		L_tmp += (y1_hi * a[1] + y2_hi * a[2] + (x0 + x2)* b[0] + x1 * b[1]) << 1;
-		L_tmp <<= 1;           /* coeff Q12 --> Q13 */
-		y2_hi = y1_hi;
-		y2_lo = y1_lo;
-		y1_hi = (Word16)(L_tmp>>16);
-		y1_lo = (Word16)((L_tmp & 0xffff)>>1);
+    Word16  x2;
+    Word16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;
+    Word32 L_tmp;
+    Word32 num;
+    y2_hi = *mem++;
+    y2_lo = *mem++;
+    y1_hi = *mem++;
+    y1_lo = *mem++;
+    x0 = *mem++;
+    x1 = *mem;
+    num = (Word32)lg;
+    do
+    {
+        x2 = x1;
+        x1 = x0;
+        x0 = *signal;
+        /* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2]  */
+        /* + a[1]*y[i-1] + a[2] * y[i-2];  */
+        L_tmp = 8192L;                    /* rounding to maximise precision */
+        L_tmp += y1_lo * a[1];
+        L_tmp += y2_lo * a[2];
+        L_tmp = L_tmp >> 14;
+        L_tmp += (y1_hi * a[1] + y2_hi * a[2] + (x0 + x2)* b[0] + x1 * b[1]) << 1;
+        L_tmp <<= 1;           /* coeff Q12 --> Q13 */
+        y2_hi = y1_hi;
+        y2_lo = y1_lo;
+        y1_hi = (Word16)(L_tmp>>16);
+        y1_lo = (Word16)((L_tmp & 0xffff)>>1);
 
-		/* signal is divided by 16 to avoid overflow in energy computation */
-		*signal++ = (L_tmp + 0x8000) >> 16;
-	}while(--num !=0);
+        /* signal is divided by 16 to avoid overflow in energy computation */
+        *signal++ = (L_tmp + 0x8000) >> 16;
+    }while(--num !=0);
 
-	*mem-- = x1;
-	*mem-- = x0;
-	*mem-- = y1_lo;
-	*mem-- = y1_hi;
-	*mem-- = y2_lo;
-	*mem   = y2_hi;
-	return;
+    *mem-- = x1;
+    *mem-- = x0;
+    *mem-- = y1_lo;
+    *mem-- = y1_hi;
+    *mem-- = y2_lo;
+    *mem   = y2_hi;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp50.c b/media/libstagefright/codecs/amrwbenc/src/hp50.c
index c1c7b83..807d672 100644
--- a/media/libstagefright/codecs/amrwbenc/src/hp50.c
+++ b/media/libstagefright/codecs/amrwbenc/src/hp50.c
@@ -17,7 +17,7 @@
 /***********************************************************************
 *      File: hp50.c                                                     *
 *                                                                       *
-*	   Description:                                                 *
+*      Description:                                                 *
 * 2nd order high pass filter with cut off frequency at 31 Hz.           *
 * Designed with cheby2 function in MATLAB.                              *
 * Optimized for fixed-point to get the following frequency response:    *
@@ -51,56 +51,56 @@
 
 void Init_HP50_12k8(Word16 mem[])
 {
-	Set_zero(mem, 6);
+    Set_zero(mem, 6);
 }
 
 
 void HP50_12k8(
-		Word16 signal[],                      /* input/output signal */
-		Word16 lg,                            /* lenght of signal    */
-		Word16 mem[]                          /* filter memory [6]   */
-	      )
+        Word16 signal[],                      /* input/output signal */
+        Word16 lg,                            /* lenght of signal    */
+        Word16 mem[]                          /* filter memory [6]   */
+          )
 {
-	Word16 x2;
-	Word16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;
-	Word32 L_tmp;
-	Word32 num;
+    Word16 x2;
+    Word16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;
+    Word32 L_tmp;
+    Word32 num;
 
-	y2_hi = *mem++;
-	y2_lo = *mem++;
-	y1_hi = *mem++;
-	y1_lo = *mem++;
-	x0 = *mem++;
-	x1 = *mem;
-	num = (Word32)lg;
-	do
-	{
-		x2 = x1;
-		x1 = x0;
-		x0 = *signal;
-		/* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2]  */
-		/* + a[1]*y[i-1] + a[2] * y[i-2];  */
-		L_tmp = 8192 ;                    /* rounding to maximise precision */
-		L_tmp += y1_lo * a[1];
-		L_tmp += y2_lo * a[2];
-		L_tmp = L_tmp >> 14;
-		L_tmp += (y1_hi * a[1] + y2_hi * a[2] + (x0 + x2) * b[0] + x1 * b[1]) << 1;
-		L_tmp <<= 2;           /* coeff Q12 --> Q13 */
-		y2_hi = y1_hi;
-		y2_lo = y1_lo;
-		y1_hi = (Word16)(L_tmp>>16);
-		y1_lo = (Word16)((L_tmp & 0xffff)>>1);
-		*signal++ = extract_h((L_add((L_tmp<<1), 0x8000)));
-	}while(--num !=0);
+    y2_hi = *mem++;
+    y2_lo = *mem++;
+    y1_hi = *mem++;
+    y1_lo = *mem++;
+    x0 = *mem++;
+    x1 = *mem;
+    num = (Word32)lg;
+    do
+    {
+        x2 = x1;
+        x1 = x0;
+        x0 = *signal;
+        /* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2]  */
+        /* + a[1]*y[i-1] + a[2] * y[i-2];  */
+        L_tmp = 8192 ;                    /* rounding to maximise precision */
+        L_tmp += y1_lo * a[1];
+        L_tmp += y2_lo * a[2];
+        L_tmp = L_tmp >> 14;
+        L_tmp += (y1_hi * a[1] + y2_hi * a[2] + (x0 + x2) * b[0] + x1 * b[1]) << 1;
+        L_tmp <<= 2;           /* coeff Q12 --> Q13 */
+        y2_hi = y1_hi;
+        y2_lo = y1_lo;
+        y1_hi = (Word16)(L_tmp>>16);
+        y1_lo = (Word16)((L_tmp & 0xffff)>>1);
+        *signal++ = extract_h((L_add((L_tmp<<1), 0x8000)));
+    }while(--num !=0);
 
-	*mem-- = x1;
-	*mem-- = x0;
-	*mem-- = y1_lo;
-	*mem-- = y1_hi;
-	*mem-- = y2_lo;
-	*mem-- = y2_hi;
+    *mem-- = x1;
+    *mem-- = x0;
+    *mem-- = y1_lo;
+    *mem-- = y1_hi;
+    *mem-- = y2_lo;
+    *mem-- = y2_hi;
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp6k.c b/media/libstagefright/codecs/amrwbenc/src/hp6k.c
index 8e66eb0..0baf612 100644
--- a/media/libstagefright/codecs/amrwbenc/src/hp6k.c
+++ b/media/libstagefright/codecs/amrwbenc/src/hp6k.c
@@ -17,10 +17,10 @@
 /***********************************************************************
 *       File: hp6k.c                                                    *
 *                                                                       *
-*	Description:15th order band pass 6kHz to 7kHz FIR filter        *
+*   Description:15th order band pass 6kHz to 7kHz FIR filter        *
 *       frequency: 4kHz   5kHz  5.5kHz  6kHz  6.5kHz  7kHz 7.5kHz 8kHz  *
-*	dB loss:  -60dB  -45dB  -13dB   -3dB   0dB    -3dB -13dB  -45dB *
-*	                                                                *
+*   dB loss:  -60dB  -45dB  -13dB   -3dB   0dB    -3dB -13dB  -45dB *
+*                                                                   *
 ************************************************************************/
 
 #include "typedef.h"
@@ -34,58 +34,58 @@
 
 Word16 fir_6k_7k[L_FIR] =
 {
-	-32, 47, 32, -27, -369,
-	1122, -1421, 0, 3798, -8880,
-	12349, -10984, 3548, 7766, -18001,
-	22118, -18001, 7766, 3548, -10984,
-	12349, -8880, 3798, 0, -1421,
-	1122, -369, -27, 32, 47,
-	-32
+    -32, 47, 32, -27, -369,
+    1122, -1421, 0, 3798, -8880,
+    12349, -10984, 3548, 7766, -18001,
+    22118, -18001, 7766, 3548, -10984,
+    12349, -8880, 3798, 0, -1421,
+    1122, -369, -27, 32, 47,
+    -32
 };
 
 
 void Init_Filt_6k_7k(Word16 mem[])         /* mem[30] */
 {
-	Set_zero(mem, L_FIR - 1);
-	return;
+    Set_zero(mem, L_FIR - 1);
+    return;
 }
 
 void Filt_6k_7k(
-		Word16 signal[],                      /* input:  signal                  */
-		Word16 lg,                            /* input:  length of input         */
-		Word16 mem[]                          /* in/out: memory (size=30)        */
-	       )
+        Word16 signal[],                      /* input:  signal                  */
+        Word16 lg,                            /* input:  length of input         */
+        Word16 mem[]                          /* in/out: memory (size=30)        */
+           )
 {
-	Word16 x[L_SUBFR16k + (L_FIR - 1)];
-	Word32 i, L_tmp;
+    Word16 x[L_SUBFR16k + (L_FIR - 1)];
+    Word32 i, L_tmp;
 
-	Copy(mem, x, L_FIR - 1);
-	for (i = lg - 1; i >= 0; i--)
-	{
-		x[i + L_FIR - 1] = signal[i] >> 2;                         /* gain of filter = 4 */
-	}
-	for (i = 0; i < lg; i++)
-	{
-		L_tmp =  (x[i] + x[i+ 30]) * fir_6k_7k[0];
-		L_tmp += (x[i+1] + x[i + 29]) * fir_6k_7k[1];
-		L_tmp += (x[i+2] + x[i + 28]) * fir_6k_7k[2];
-		L_tmp += (x[i+3] + x[i + 27]) * fir_6k_7k[3];
-		L_tmp += (x[i+4] + x[i + 26]) * fir_6k_7k[4];
-		L_tmp += (x[i+5] + x[i + 25]) * fir_6k_7k[5];
-		L_tmp += (x[i+6] + x[i + 24]) * fir_6k_7k[6];
-		L_tmp += (x[i+7] + x[i + 23]) * fir_6k_7k[7];
-		L_tmp += (x[i+8] + x[i + 22]) * fir_6k_7k[8];
-		L_tmp += (x[i+9] + x[i + 21]) * fir_6k_7k[9];
-		L_tmp += (x[i+10] + x[i + 20]) * fir_6k_7k[10];
-		L_tmp += (x[i+11] + x[i + 19]) * fir_6k_7k[11];
-		L_tmp += (x[i+12] + x[i + 18]) * fir_6k_7k[12];
-		L_tmp += (x[i+13] + x[i + 17]) * fir_6k_7k[13];
-		L_tmp += (x[i+14] + x[i + 16]) * fir_6k_7k[14];
-		L_tmp += (x[i+15]) * fir_6k_7k[15];
-		signal[i] = (L_tmp + 0x4000) >> 15;
-	}
+    Copy(mem, x, L_FIR - 1);
+    for (i = lg - 1; i >= 0; i--)
+    {
+        x[i + L_FIR - 1] = signal[i] >> 2;                         /* gain of filter = 4 */
+    }
+    for (i = 0; i < lg; i++)
+    {
+        L_tmp =  (x[i] + x[i+ 30]) * fir_6k_7k[0];
+        L_tmp += (x[i+1] + x[i + 29]) * fir_6k_7k[1];
+        L_tmp += (x[i+2] + x[i + 28]) * fir_6k_7k[2];
+        L_tmp += (x[i+3] + x[i + 27]) * fir_6k_7k[3];
+        L_tmp += (x[i+4] + x[i + 26]) * fir_6k_7k[4];
+        L_tmp += (x[i+5] + x[i + 25]) * fir_6k_7k[5];
+        L_tmp += (x[i+6] + x[i + 24]) * fir_6k_7k[6];
+        L_tmp += (x[i+7] + x[i + 23]) * fir_6k_7k[7];
+        L_tmp += (x[i+8] + x[i + 22]) * fir_6k_7k[8];
+        L_tmp += (x[i+9] + x[i + 21]) * fir_6k_7k[9];
+        L_tmp += (x[i+10] + x[i + 20]) * fir_6k_7k[10];
+        L_tmp += (x[i+11] + x[i + 19]) * fir_6k_7k[11];
+        L_tmp += (x[i+12] + x[i + 18]) * fir_6k_7k[12];
+        L_tmp += (x[i+13] + x[i + 17]) * fir_6k_7k[13];
+        L_tmp += (x[i+14] + x[i + 16]) * fir_6k_7k[14];
+        L_tmp += (x[i+15]) * fir_6k_7k[15];
+        signal[i] = (L_tmp + 0x4000) >> 15;
+    }
 
-	Copy(x + lg, mem, L_FIR - 1);
+    Copy(x + lg, mem, L_FIR - 1);
 
 }
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp_wsp.c b/media/libstagefright/codecs/amrwbenc/src/hp_wsp.c
index bc1ec49..f0347cb 100644
--- a/media/libstagefright/codecs/amrwbenc/src/hp_wsp.c
+++ b/media/libstagefright/codecs/amrwbenc/src/hp_wsp.c
@@ -48,101 +48,101 @@
 /* Initialization of static values */
 void Init_Hp_wsp(Word16 mem[])
 {
-	Set_zero(mem, 9);
+    Set_zero(mem, 9);
 
-	return;
+    return;
 }
 
 void scale_mem_Hp_wsp(Word16 mem[], Word16 exp)
 {
-	Word32 i;
-	Word32 L_tmp;
+    Word32 i;
+    Word32 L_tmp;
 
-	for (i = 0; i < 6; i += 2)
-	{
-		L_tmp = ((mem[i] << 16) + (mem[i + 1]<<1));
-		L_tmp = L_shl(L_tmp, exp);
-		mem[i] = L_tmp >> 16;
-		mem[i + 1] = (L_tmp & 0xffff)>>1;
-	}
+    for (i = 0; i < 6; i += 2)
+    {
+        L_tmp = ((mem[i] << 16) + (mem[i + 1]<<1));
+        L_tmp = L_shl(L_tmp, exp);
+        mem[i] = L_tmp >> 16;
+        mem[i + 1] = (L_tmp & 0xffff)>>1;
+    }
 
-	for (i = 6; i < 9; i++)
-	{
-		L_tmp = L_deposit_h(mem[i]);       /* x[i] */
-		L_tmp = L_shl(L_tmp, exp);
-		mem[i] = vo_round(L_tmp);
-	}
+    for (i = 6; i < 9; i++)
+    {
+        L_tmp = L_deposit_h(mem[i]);       /* x[i] */
+        L_tmp = L_shl(L_tmp, exp);
+        mem[i] = vo_round(L_tmp);
+    }
 
-	return;
+    return;
 }
 
 
 void Hp_wsp(
-		Word16 wsp[],                         /* i   : wsp[]  signal       */
-		Word16 hp_wsp[],                      /* o   : hypass wsp[]        */
-		Word16 lg,                            /* i   : lenght of signal    */
-		Word16 mem[]                          /* i/o : filter memory [9]   */
-	   )
+        Word16 wsp[],                         /* i   : wsp[]  signal       */
+        Word16 hp_wsp[],                      /* o   : hypass wsp[]        */
+        Word16 lg,                            /* i   : lenght of signal    */
+        Word16 mem[]                          /* i/o : filter memory [9]   */
+       )
 {
-	Word16 x0, x1, x2, x3;
-	Word16 y3_hi, y3_lo, y2_hi, y2_lo, y1_hi, y1_lo;
-	Word32 i, L_tmp;
+    Word16 x0, x1, x2, x3;
+    Word16 y3_hi, y3_lo, y2_hi, y2_lo, y1_hi, y1_lo;
+    Word32 i, L_tmp;
 
-	y3_hi = mem[0];
-	y3_lo = mem[1];
-	y2_hi = mem[2];
-	y2_lo = mem[3];
-	y1_hi = mem[4];
-	y1_lo = mem[5];
-	x0 = mem[6];
-	x1 = mem[7];
-	x2 = mem[8];
+    y3_hi = mem[0];
+    y3_lo = mem[1];
+    y2_hi = mem[2];
+    y2_lo = mem[3];
+    y1_hi = mem[4];
+    y1_lo = mem[5];
+    x0 = mem[6];
+    x1 = mem[7];
+    x2 = mem[8];
 
-	for (i = 0; i < lg; i++)
-	{
-		x3 = x2;
-		x2 = x1;
-		x1 = x0;
-		x0 = wsp[i];
-		/* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2] + b[3]*x[i-3]  */
-		/* + a[1]*y[i-1] + a[2] * y[i-2]  + a[3]*y[i-3]  */
+    for (i = 0; i < lg; i++)
+    {
+        x3 = x2;
+        x2 = x1;
+        x1 = x0;
+        x0 = wsp[i];
+        /* y[i] = b[0]*x[i] + b[1]*x[i-1] + b140[2]*x[i-2] + b[3]*x[i-3]  */
+        /* + a[1]*y[i-1] + a[2] * y[i-2]  + a[3]*y[i-3]  */
 
-		L_tmp = 16384L;                    /* rounding to maximise precision */
-		L_tmp += (y1_lo * a[1])<<1;
-		L_tmp += (y2_lo * a[2])<<1;
-		L_tmp += (y3_lo * a[3])<<1;
-		L_tmp = L_tmp >> 15;
-		L_tmp += (y1_hi * a[1])<<1;
-		L_tmp += (y2_hi * a[2])<<1;
-		L_tmp += (y3_hi * a[3])<<1;
-		L_tmp += (x0 * b[0])<<1;
-		L_tmp += (x1 * b[1])<<1;
-		L_tmp += (x2 * b[2])<<1;
-		L_tmp += (x3 * b[3])<<1;
+        L_tmp = 16384L;                    /* rounding to maximise precision */
+        L_tmp += (y1_lo * a[1])<<1;
+        L_tmp += (y2_lo * a[2])<<1;
+        L_tmp += (y3_lo * a[3])<<1;
+        L_tmp = L_tmp >> 15;
+        L_tmp += (y1_hi * a[1])<<1;
+        L_tmp += (y2_hi * a[2])<<1;
+        L_tmp += (y3_hi * a[3])<<1;
+        L_tmp += (x0 * b[0])<<1;
+        L_tmp += (x1 * b[1])<<1;
+        L_tmp += (x2 * b[2])<<1;
+        L_tmp += (x3 * b[3])<<1;
 
-		L_tmp = L_tmp << 2;
+        L_tmp = L_tmp << 2;
 
-		y3_hi = y2_hi;
-		y3_lo = y2_lo;
-		y2_hi = y1_hi;
-		y2_lo = y1_lo;
-		y1_hi = L_tmp >> 16;
-		y1_lo = (L_tmp & 0xffff) >>1;
+        y3_hi = y2_hi;
+        y3_lo = y2_lo;
+        y2_hi = y1_hi;
+        y2_lo = y1_lo;
+        y1_hi = L_tmp >> 16;
+        y1_lo = (L_tmp & 0xffff) >>1;
 
-		hp_wsp[i] = (L_tmp + 0x4000)>>15;
-	}
+        hp_wsp[i] = (L_tmp + 0x4000)>>15;
+    }
 
-	mem[0] = y3_hi;
-	mem[1] = y3_lo;
-	mem[2] = y2_hi;
-	mem[3] = y2_lo;
-	mem[4] = y1_hi;
-	mem[5] = y1_lo;
-	mem[6] = x0;
-	mem[7] = x1;
-	mem[8] = x2;
+    mem[0] = y3_hi;
+    mem[1] = y3_lo;
+    mem[2] = y2_hi;
+    mem[3] = y2_lo;
+    mem[4] = y1_hi;
+    mem[5] = y1_lo;
+    mem[6] = x0;
+    mem[7] = x1;
+    mem[8] = x2;
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/int_lpc.c b/media/libstagefright/codecs/amrwbenc/src/int_lpc.c
index 1119bc7..3d8b8cb 100644
--- a/media/libstagefright/codecs/amrwbenc/src/int_lpc.c
+++ b/media/libstagefright/codecs/amrwbenc/src/int_lpc.c
@@ -30,36 +30,36 @@
 
 
 void Int_isp(
-		Word16 isp_old[],                     /* input : isps from past frame              */
-		Word16 isp_new[],                     /* input : isps from present frame           */
-		Word16 frac[],                        /* input : fraction for 3 first subfr (Q15)  */
-		Word16 Az[]                           /* output: LP coefficients in 4 subframes    */
-	    )
+        Word16 isp_old[],                     /* input : isps from past frame              */
+        Word16 isp_new[],                     /* input : isps from present frame           */
+        Word16 frac[],                        /* input : fraction for 3 first subfr (Q15)  */
+        Word16 Az[]                           /* output: LP coefficients in 4 subframes    */
+        )
 {
-	Word32 i, k;
-	Word16 fac_old, fac_new;
-	Word16 isp[M];
-	Word32 L_tmp;
+    Word32 i, k;
+    Word16 fac_old, fac_new;
+    Word16 isp[M];
+    Word32 L_tmp;
 
-	for (k = 0; k < 3; k++)
-	{
-		fac_new = frac[k];
-		fac_old = (32767 - fac_new) + 1;  /* 1.0 - fac_new */
+    for (k = 0; k < 3; k++)
+    {
+        fac_new = frac[k];
+        fac_old = (32767 - fac_new) + 1;  /* 1.0 - fac_new */
 
-		for (i = 0; i < M; i++)
-		{
-			L_tmp = (isp_old[i] * fac_old)<<1;
-			L_tmp += (isp_new[i] * fac_new)<<1;
-			isp[i] = (L_tmp + 0x8000)>>16;
-		}
-		Isp_Az(isp, Az, M, 0);
-		Az += MP1;
-	}
+        for (i = 0; i < M; i++)
+        {
+            L_tmp = (isp_old[i] * fac_old)<<1;
+            L_tmp += (isp_new[i] * fac_new)<<1;
+            isp[i] = (L_tmp + 0x8000)>>16;
+        }
+        Isp_Az(isp, Az, M, 0);
+        Az += MP1;
+    }
 
-	/* 4th subframe: isp_new (frac=1.0) */
-	Isp_Az(isp_new, Az, M, 0);
+    /* 4th subframe: isp_new (frac=1.0) */
+    Isp_Az(isp_new, Az, M, 0);
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/isp_az.c b/media/libstagefright/codecs/amrwbenc/src/isp_az.c
index 30a8bbd..62e29e7 100644
--- a/media/libstagefright/codecs/amrwbenc/src/isp_az.c
+++ b/media/libstagefright/codecs/amrwbenc/src/isp_az.c
@@ -35,132 +35,132 @@
 static void Get_isp_pol_16kHz(Word16 * isp, Word32 * f, Word16 n);
 
 void Isp_Az(
-		Word16 isp[],                         /* (i) Q15 : Immittance spectral pairs            */
-		Word16 a[],                           /* (o) Q12 : predictor coefficients (order = M)   */
-		Word16 m,
-		Word16 adaptive_scaling               /* (i) 0   : adaptive scaling disabled */
-		                                      /*     1   : adaptive scaling enabled  */
-	   )
+        Word16 isp[],                         /* (i) Q15 : Immittance spectral pairs            */
+        Word16 a[],                           /* (o) Q12 : predictor coefficients (order = M)   */
+        Word16 m,
+        Word16 adaptive_scaling               /* (i) 0   : adaptive scaling disabled */
+                                              /*     1   : adaptive scaling enabled  */
+       )
 {
-	Word32 i, j;
-	Word16 hi, lo;
-	Word32 f1[NC16k + 1], f2[NC16k];
-	Word16 nc;
-	Word32 t0;
-	Word16 q, q_sug;
-	Word32 tmax;
+    Word32 i, j;
+    Word16 hi, lo;
+    Word32 f1[NC16k + 1], f2[NC16k];
+    Word16 nc;
+    Word32 t0;
+    Word16 q, q_sug;
+    Word32 tmax;
 
-	nc = (m >> 1);
-	if(nc > 8)
-	{
-		Get_isp_pol_16kHz(&isp[0], f1, nc);
-		for (i = 0; i <= nc; i++)
-		{
-			f1[i] = f1[i] << 2;
-		}
-	} else
-		Get_isp_pol(&isp[0], f1, nc);
+    nc = (m >> 1);
+    if(nc > 8)
+    {
+        Get_isp_pol_16kHz(&isp[0], f1, nc);
+        for (i = 0; i <= nc; i++)
+        {
+            f1[i] = f1[i] << 2;
+        }
+    } else
+        Get_isp_pol(&isp[0], f1, nc);
 
-	if (nc > 8)
-	{
-		Get_isp_pol_16kHz(&isp[1], f2, (nc - 1));
-		for (i = 0; i <= nc - 1; i++)
-		{
-			f2[i] = f2[i] << 2;
-		}
-	} else
-		Get_isp_pol(&isp[1], f2, (nc - 1));
+    if (nc > 8)
+    {
+        Get_isp_pol_16kHz(&isp[1], f2, (nc - 1));
+        for (i = 0; i <= nc - 1; i++)
+        {
+            f2[i] = f2[i] << 2;
+        }
+    } else
+        Get_isp_pol(&isp[1], f2, (nc - 1));
 
-	/*-----------------------------------------------------*
-	 *  Multiply F2(z) by (1 - z^-2)                       *
-	 *-----------------------------------------------------*/
+    /*-----------------------------------------------------*
+     *  Multiply F2(z) by (1 - z^-2)                       *
+     *-----------------------------------------------------*/
 
-	for (i = (nc - 1); i > 1; i--)
-	{
-		f2[i] = vo_L_sub(f2[i], f2[i - 2]);          /* f2[i] -= f2[i-2]; */
-	}
+    for (i = (nc - 1); i > 1; i--)
+    {
+        f2[i] = vo_L_sub(f2[i], f2[i - 2]);          /* f2[i] -= f2[i-2]; */
+    }
 
-	/*----------------------------------------------------------*
-	 *  Scale F1(z) by (1+isp[m-1])  and  F2(z) by (1-isp[m-1]) *
-	 *----------------------------------------------------------*/
+    /*----------------------------------------------------------*
+     *  Scale F1(z) by (1+isp[m-1])  and  F2(z) by (1-isp[m-1]) *
+     *----------------------------------------------------------*/
 
-	for (i = 0; i < nc; i++)
-	{
-		/* f1[i] *= (1.0 + isp[M-1]); */
+    for (i = 0; i < nc; i++)
+    {
+        /* f1[i] *= (1.0 + isp[M-1]); */
 
-		hi = f1[i] >> 16;
-		lo = (f1[i] & 0xffff)>>1;
+        hi = f1[i] >> 16;
+        lo = (f1[i] & 0xffff)>>1;
 
-		t0 = Mpy_32_16(hi, lo, isp[m - 1]);
-		f1[i] = vo_L_add(f1[i], t0);
+        t0 = Mpy_32_16(hi, lo, isp[m - 1]);
+        f1[i] = vo_L_add(f1[i], t0);
 
-		/* f2[i] *= (1.0 - isp[M-1]); */
+        /* f2[i] *= (1.0 - isp[M-1]); */
 
-		hi = f2[i] >> 16;
-		lo = (f2[i] & 0xffff)>>1;
-		t0 = Mpy_32_16(hi, lo, isp[m - 1]);
-		f2[i] = vo_L_sub(f2[i], t0);
-	}
+        hi = f2[i] >> 16;
+        lo = (f2[i] & 0xffff)>>1;
+        t0 = Mpy_32_16(hi, lo, isp[m - 1]);
+        f2[i] = vo_L_sub(f2[i], t0);
+    }
 
-	/*-----------------------------------------------------*
-	 *  A(z) = (F1(z)+F2(z))/2                             *
-	 *  F1(z) is symmetric and F2(z) is antisymmetric      *
-	 *-----------------------------------------------------*/
+    /*-----------------------------------------------------*
+     *  A(z) = (F1(z)+F2(z))/2                             *
+     *  F1(z) is symmetric and F2(z) is antisymmetric      *
+     *-----------------------------------------------------*/
 
-	/* a[0] = 1.0; */
-	a[0] = 4096;
-	tmax = 1;
-	for (i = 1, j = m - 1; i < nc; i++, j--)
-	{
-		/* a[i] = 0.5*(f1[i] + f2[i]); */
+    /* a[0] = 1.0; */
+    a[0] = 4096;
+    tmax = 1;
+    for (i = 1, j = m - 1; i < nc; i++, j--)
+    {
+        /* a[i] = 0.5*(f1[i] + f2[i]); */
 
-		t0 = vo_L_add(f1[i], f2[i]);          /* f1[i] + f2[i]             */
-		tmax |= L_abs(t0);
-		a[i] = (Word16)(vo_L_shr_r(t0, 12)); /* from Q23 to Q12 and * 0.5 */
+        t0 = vo_L_add(f1[i], f2[i]);          /* f1[i] + f2[i]             */
+        tmax |= L_abs(t0);
+        a[i] = (Word16)(vo_L_shr_r(t0, 12)); /* from Q23 to Q12 and * 0.5 */
 
-		/* a[j] = 0.5*(f1[i] - f2[i]); */
+        /* a[j] = 0.5*(f1[i] - f2[i]); */
 
-		t0 = vo_L_sub(f1[i], f2[i]);          /* f1[i] - f2[i]             */
-		tmax |= L_abs(t0);
-		a[j] = (Word16)(vo_L_shr_r(t0, 12)); /* from Q23 to Q12 and * 0.5 */
-	}
+        t0 = vo_L_sub(f1[i], f2[i]);          /* f1[i] - f2[i]             */
+        tmax |= L_abs(t0);
+        a[j] = (Word16)(vo_L_shr_r(t0, 12)); /* from Q23 to Q12 and * 0.5 */
+    }
 
-	/* rescale data if overflow has occured and reprocess the loop */
-	if(adaptive_scaling == 1)
-		q = 4 - norm_l(tmax);        /* adaptive scaling enabled */
-	else
-		q = 0;                           /* adaptive scaling disabled */
+    /* rescale data if overflow has occured and reprocess the loop */
+    if(adaptive_scaling == 1)
+        q = 4 - norm_l(tmax);        /* adaptive scaling enabled */
+    else
+        q = 0;                           /* adaptive scaling disabled */
 
-	if (q > 0)
-	{
-		q_sug = (12 + q);
-		for (i = 1, j = m - 1; i < nc; i++, j--)
-		{
-			/* a[i] = 0.5*(f1[i] + f2[i]); */
-			t0 = vo_L_add(f1[i], f2[i]);          /* f1[i] + f2[i]             */
-			a[i] = (Word16)(vo_L_shr_r(t0, q_sug)); /* from Q23 to Q12 and * 0.5 */
+    if (q > 0)
+    {
+        q_sug = (12 + q);
+        for (i = 1, j = m - 1; i < nc; i++, j--)
+        {
+            /* a[i] = 0.5*(f1[i] + f2[i]); */
+            t0 = vo_L_add(f1[i], f2[i]);          /* f1[i] + f2[i]             */
+            a[i] = (Word16)(vo_L_shr_r(t0, q_sug)); /* from Q23 to Q12 and * 0.5 */
 
-			/* a[j] = 0.5*(f1[i] - f2[i]); */
-			t0 = vo_L_sub(f1[i], f2[i]);          /* f1[i] - f2[i]             */
-			a[j] = (Word16)(vo_L_shr_r(t0, q_sug)); /* from Q23 to Q12 and * 0.5 */
-		}
-		a[0] = shr(a[0], q);
-	}
-	else
-	{
-		q_sug = 12;
-		q     = 0;
-	}
-	/* a[NC] = 0.5*f1[NC]*(1.0 + isp[M-1]); */
-	hi = f1[nc] >> 16;
-	lo = (f1[nc] & 0xffff)>>1;
-	t0 = Mpy_32_16(hi, lo, isp[m - 1]);
-	t0 = vo_L_add(f1[nc], t0);
-	a[nc] = (Word16)(L_shr_r(t0, q_sug));    /* from Q23 to Q12 and * 0.5 */
-	/* a[m] = isp[m-1]; */
+            /* a[j] = 0.5*(f1[i] - f2[i]); */
+            t0 = vo_L_sub(f1[i], f2[i]);          /* f1[i] - f2[i]             */
+            a[j] = (Word16)(vo_L_shr_r(t0, q_sug)); /* from Q23 to Q12 and * 0.5 */
+        }
+        a[0] = shr(a[0], q);
+    }
+    else
+    {
+        q_sug = 12;
+        q     = 0;
+    }
+    /* a[NC] = 0.5*f1[NC]*(1.0 + isp[M-1]); */
+    hi = f1[nc] >> 16;
+    lo = (f1[nc] & 0xffff)>>1;
+    t0 = Mpy_32_16(hi, lo, isp[m - 1]);
+    t0 = vo_L_add(f1[nc], t0);
+    a[nc] = (Word16)(L_shr_r(t0, q_sug));    /* from Q23 to Q12 and * 0.5 */
+    /* a[m] = isp[m-1]; */
 
-	a[m] = vo_shr_r(isp[m - 1], (3 + q));           /* from Q15 to Q12          */
-	return;
+    a[m] = vo_shr_r(isp[m - 1], (3 + q));           /* from Q15 to Q12          */
+    return;
 }
 
 /*-----------------------------------------------------------*
@@ -185,63 +185,63 @@
 
 static void Get_isp_pol(Word16 * isp, Word32 * f, Word16 n)
 {
-	Word16 hi, lo;
-	Word32 i, j, t0;
-	/* All computation in Q23 */
+    Word16 hi, lo;
+    Word32 i, j, t0;
+    /* All computation in Q23 */
 
-	f[0] = vo_L_mult(4096, 1024);               /* f[0] = 1.0;        in Q23  */
-	f[1] = vo_L_mult(isp[0], -256);             /* f[1] = -2.0*isp[0] in Q23  */
+    f[0] = vo_L_mult(4096, 1024);               /* f[0] = 1.0;        in Q23  */
+    f[1] = vo_L_mult(isp[0], -256);             /* f[1] = -2.0*isp[0] in Q23  */
 
-	f += 2;                                  /* Advance f pointer          */
-	isp += 2;                                /* Advance isp pointer        */
-	for (i = 2; i <= n; i++)
-	{
-		*f = f[-2];
-		for (j = 1; j < i; j++, f--)
-		{
-			hi = f[-1]>>16;
-			lo = (f[-1] & 0xffff)>>1;
+    f += 2;                                  /* Advance f pointer          */
+    isp += 2;                                /* Advance isp pointer        */
+    for (i = 2; i <= n; i++)
+    {
+        *f = f[-2];
+        for (j = 1; j < i; j++, f--)
+        {
+            hi = f[-1]>>16;
+            lo = (f[-1] & 0xffff)>>1;
 
-			t0 = Mpy_32_16(hi, lo, *isp);  /* t0 = f[-1] * isp    */
-			t0 = t0 << 1;
-			*f = vo_L_sub(*f, t0);              /* *f -= t0            */
-			*f = vo_L_add(*f, f[-2]);           /* *f += f[-2]         */
-		}
-		*f -= (*isp << 9);           /* *f -= isp<<8        */
-		f += i;                            /* Advance f pointer   */
-		isp += 2;                          /* Advance isp pointer */
-	}
-	return;
+            t0 = Mpy_32_16(hi, lo, *isp);  /* t0 = f[-1] * isp    */
+            t0 = t0 << 1;
+            *f = vo_L_sub(*f, t0);              /* *f -= t0            */
+            *f = vo_L_add(*f, f[-2]);           /* *f += f[-2]         */
+        }
+        *f -= (*isp << 9);           /* *f -= isp<<8        */
+        f += i;                            /* Advance f pointer   */
+        isp += 2;                          /* Advance isp pointer */
+    }
+    return;
 }
 
 static void Get_isp_pol_16kHz(Word16 * isp, Word32 * f, Word16 n)
 {
-	Word16 hi, lo;
-	Word32 i, j, t0;
+    Word16 hi, lo;
+    Word32 i, j, t0;
 
-	/* All computation in Q23 */
-	f[0] = L_mult(4096, 256);                /* f[0] = 1.0;        in Q23  */
-	f[1] = L_mult(isp[0], -64);              /* f[1] = -2.0*isp[0] in Q23  */
+    /* All computation in Q23 */
+    f[0] = L_mult(4096, 256);                /* f[0] = 1.0;        in Q23  */
+    f[1] = L_mult(isp[0], -64);              /* f[1] = -2.0*isp[0] in Q23  */
 
-	f += 2;                                  /* Advance f pointer          */
-	isp += 2;                                /* Advance isp pointer        */
+    f += 2;                                  /* Advance f pointer          */
+    isp += 2;                                /* Advance isp pointer        */
 
-	for (i = 2; i <= n; i++)
-	{
-		*f = f[-2];
-		for (j = 1; j < i; j++, f--)
-		{
-			VO_L_Extract(f[-1], &hi, &lo);
-			t0 = Mpy_32_16(hi, lo, *isp);  /* t0 = f[-1] * isp    */
-			t0 = L_shl2(t0, 1);
-			*f = L_sub(*f, t0);              /* *f -= t0            */
-			*f = L_add(*f, f[-2]);           /* *f += f[-2]         */
-		}
-		*f = L_msu(*f, *isp, 64);            /* *f -= isp<<8        */
-		f += i;                            /* Advance f pointer   */
-		isp += 2;                          /* Advance isp pointer */
-	}
-	return;
+    for (i = 2; i <= n; i++)
+    {
+        *f = f[-2];
+        for (j = 1; j < i; j++, f--)
+        {
+            VO_L_Extract(f[-1], &hi, &lo);
+            t0 = Mpy_32_16(hi, lo, *isp);  /* t0 = f[-1] * isp    */
+            t0 = L_shl2(t0, 1);
+            *f = L_sub(*f, t0);              /* *f -= t0            */
+            *f = L_add(*f, f[-2]);           /* *f += f[-2]         */
+        }
+        *f = L_msu(*f, *isp, 64);            /* *f -= isp<<8        */
+        f += i;                            /* Advance f pointer   */
+        isp += 2;                          /* Advance isp pointer */
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/isp_isf.c b/media/libstagefright/codecs/amrwbenc/src/isp_isf.c
index b4ba408..56798e0 100644
--- a/media/libstagefright/codecs/amrwbenc/src/isp_isf.c
+++ b/media/libstagefright/codecs/amrwbenc/src/isp_isf.c
@@ -18,11 +18,11 @@
 *       File: isp_isf.c                                                *
 *                                                                      *
 *       Description:                                                   *
-*	Isp_isf   Transformation isp to isf                            *
-*	Isf_isp   Transformation isf to isp                            *
+*   Isp_isf   Transformation isp to isf                            *
+*   Isf_isp   Transformation isf to isp                            *
 *                                                                      *
-*	The transformation from isp[i] to isf[i] and isf[i] to isp[i]  *
-*	are approximated by a look-up table and interpolation          *
+*   The transformation from isp[i] to isf[i] and isf[i] to isp[i]  *
+*   are approximated by a look-up table and interpolation          *
 *                                                                      *
 ************************************************************************/
 
@@ -31,59 +31,59 @@
 #include "isp_isf.tab"                     /* Look-up table for transformations */
 
 void Isp_isf(
-		Word16 isp[],                         /* (i) Q15 : isp[m] (range: -1<=val<1)                */
-		Word16 isf[],                         /* (o) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
-		Word16 m                              /* (i)     : LPC order                                */
-	    )
+        Word16 isp[],                         /* (i) Q15 : isp[m] (range: -1<=val<1)                */
+        Word16 isf[],                         /* (o) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+        Word16 m                              /* (i)     : LPC order                                */
+        )
 {
-	Word32 i, ind;
-	Word32 L_tmp;
-	ind = 127;                               /* beging at end of table -1 */
-	for (i = (m - 1); i >= 0; i--)
-	{
-		if (i >= (m - 2))
-		{                                  /* m-2 is a constant */
-			ind = 127;                       /* beging at end of table -1 */
-		}
-		/* find value in table that is just greater than isp[i] */
-		while (table[ind] < isp[i])
-			ind--;
-		/* acos(isp[i])= ind*128 + ( ( isp[i]-table[ind] ) * slope[ind] )/2048 */
-		L_tmp = vo_L_mult(vo_sub(isp[i], table[ind]), slope[ind]);
-		isf[i] = vo_round((L_tmp << 4));   /* (isp[i]-table[ind])*slope[ind])>>11 */
-		isf[i] = add1(isf[i], (ind << 7));
-	}
-	isf[m - 1] = (isf[m - 1] >> 1);
-	return;
+    Word32 i, ind;
+    Word32 L_tmp;
+    ind = 127;                               /* beging at end of table -1 */
+    for (i = (m - 1); i >= 0; i--)
+    {
+        if (i >= (m - 2))
+        {                                  /* m-2 is a constant */
+            ind = 127;                       /* beging at end of table -1 */
+        }
+        /* find value in table that is just greater than isp[i] */
+        while (table[ind] < isp[i])
+            ind--;
+        /* acos(isp[i])= ind*128 + ( ( isp[i]-table[ind] ) * slope[ind] )/2048 */
+        L_tmp = vo_L_mult(vo_sub(isp[i], table[ind]), slope[ind]);
+        isf[i] = vo_round((L_tmp << 4));   /* (isp[i]-table[ind])*slope[ind])>>11 */
+        isf[i] = add1(isf[i], (ind << 7));
+    }
+    isf[m - 1] = (isf[m - 1] >> 1);
+    return;
 }
 
 
 void Isf_isp(
-		Word16 isf[],                         /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
-		Word16 isp[],                         /* (o) Q15 : isp[m] (range: -1<=val<1)                */
-		Word16 m                              /* (i)     : LPC order                                */
-	    )
+        Word16 isf[],                         /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+        Word16 isp[],                         /* (o) Q15 : isp[m] (range: -1<=val<1)                */
+        Word16 m                              /* (i)     : LPC order                                */
+        )
 {
-	Word16 offset;
-	Word32 i, ind, L_tmp;
+    Word16 offset;
+    Word32 i, ind, L_tmp;
 
-	for (i = 0; i < m - 1; i++)
-	{
-		isp[i] = isf[i];
-	}
-	isp[m - 1] = (isf[m - 1] << 1);
+    for (i = 0; i < m - 1; i++)
+    {
+        isp[i] = isf[i];
+    }
+    isp[m - 1] = (isf[m - 1] << 1);
 
-	for (i = 0; i < m; i++)
-	{
-		ind = (isp[i] >> 7);                      /* ind    = b7-b15 of isf[i] */
-		offset = (Word16) (isp[i] & 0x007f);      /* offset = b0-b6  of isf[i] */
+    for (i = 0; i < m; i++)
+    {
+        ind = (isp[i] >> 7);                      /* ind    = b7-b15 of isf[i] */
+        offset = (Word16) (isp[i] & 0x007f);      /* offset = b0-b6  of isf[i] */
 
-		/* isp[i] = table[ind]+ ((table[ind+1]-table[ind])*offset) / 128 */
-		L_tmp = vo_L_mult(vo_sub(table[ind + 1], table[ind]), offset);
-		isp[i] = add1(table[ind], (Word16)((L_tmp >> 8)));
-	}
+        /* isp[i] = table[ind]+ ((table[ind+1]-table[ind])*offset) / 128 */
+        L_tmp = vo_L_mult(vo_sub(table[ind + 1], table[ind]), offset);
+        isp[i] = add1(table[ind], (Word16)((L_tmp >> 8)));
+    }
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/lag_wind.c b/media/libstagefright/codecs/amrwbenc/src/lag_wind.c
index 49c622c..527430b 100644
--- a/media/libstagefright/codecs/amrwbenc/src/lag_wind.c
+++ b/media/libstagefright/codecs/amrwbenc/src/lag_wind.c
@@ -17,8 +17,8 @@
 /***********************************************************************
 *      File: lag_wind.c                                                *
 *                                                                      *
-*	   Description: Lag_windows on autocorrelations                *
-*	                r[i] *= lag_wind[i]                            *
+*      Description: Lag_windows on autocorrelations                *
+*                   r[i] *= lag_wind[i]                            *
 *                                                                      *
 ************************************************************************/
 
@@ -29,20 +29,20 @@
 
 
 void Lag_window(
-		Word16 r_h[],                         /* (i/o)   : Autocorrelations  (msb)          */
-		Word16 r_l[]                          /* (i/o)   : Autocorrelations  (lsb)          */
-	       )
+        Word16 r_h[],                         /* (i/o)   : Autocorrelations  (msb)          */
+        Word16 r_l[]                          /* (i/o)   : Autocorrelations  (lsb)          */
+           )
 {
-	Word32 i;
-	Word32 x;
+    Word32 i;
+    Word32 x;
 
-	for (i = 1; i <= M; i++)
-	{
-		x = Mpy_32(r_h[i], r_l[i], volag_h[i - 1], volag_l[i - 1]);
-		r_h[i] = x >> 16;
-		r_l[i] = (x & 0xffff)>>1;
-	}
-	return;
+    for (i = 1; i <= M; i++)
+    {
+        x = Mpy_32(r_h[i], r_l[i], volag_h[i - 1], volag_l[i - 1]);
+        r_h[i] = x >> 16;
+        r_l[i] = (x & 0xffff)>>1;
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/levinson.c b/media/libstagefright/codecs/amrwbenc/src/levinson.c
index 4b2f8ed..9d5a3bd 100644
--- a/media/libstagefright/codecs/amrwbenc/src/levinson.c
+++ b/media/libstagefright/codecs/amrwbenc/src/levinson.c
@@ -21,7 +21,7 @@
 *                                                                      *
 ************************************************************************/
 /*---------------------------------------------------------------------------*
- *                         LEVINSON.C					     *
+ *                         LEVINSON.C                        *
  *---------------------------------------------------------------------------*
  *                                                                           *
  *      LEVINSON-DURBIN algorithm in double precision                        *
@@ -96,154 +96,154 @@
 #define NC  (M/2)
 
 void Init_Levinson(
-		Word16 * mem                          /* output  :static memory (18 words) */
-		)
+        Word16 * mem                          /* output  :static memory (18 words) */
+        )
 {
-	Set_zero(mem, 18);                     /* old_A[0..M-1] = 0, old_rc[0..1] = 0 */
-	return;
+    Set_zero(mem, 18);                     /* old_A[0..M-1] = 0, old_rc[0..1] = 0 */
+    return;
 }
 
 
 void Levinson(
-		Word16 Rh[],                          /* (i)     : Rh[M+1] Vector of autocorrelations (msb) */
-		Word16 Rl[],                          /* (i)     : Rl[M+1] Vector of autocorrelations (lsb) */
-		Word16 A[],                           /* (o) Q12 : A[M]    LPC coefficients  (m = 16)       */
-		Word16 rc[],                          /* (o) Q15 : rc[M]   Reflection coefficients.         */
-		Word16 * mem                          /* (i/o)   :static memory (18 words)                  */
-	     )
+        Word16 Rh[],                          /* (i)     : Rh[M+1] Vector of autocorrelations (msb) */
+        Word16 Rl[],                          /* (i)     : Rl[M+1] Vector of autocorrelations (lsb) */
+        Word16 A[],                           /* (o) Q12 : A[M]    LPC coefficients  (m = 16)       */
+        Word16 rc[],                          /* (o) Q15 : rc[M]   Reflection coefficients.         */
+        Word16 * mem                          /* (i/o)   :static memory (18 words)                  */
+         )
 {
-	Word32 i, j;
-	Word16 hi, lo;
-	Word16 Kh, Kl;                         /* reflection coefficient; hi and lo           */
-	Word16 alp_h, alp_l, alp_exp;          /* Prediction gain; hi lo and exponent         */
-	Word16 Ah[M + 1], Al[M + 1];           /* LPC coef. in double prec.                   */
-	Word16 Anh[M + 1], Anl[M + 1];         /* LPC coef.for next iteration in double prec. */
-	Word32 t0, t1, t2;                     /* temporary variable                          */
-	Word16 *old_A, *old_rc;
+    Word32 i, j;
+    Word16 hi, lo;
+    Word16 Kh, Kl;                         /* reflection coefficient; hi and lo           */
+    Word16 alp_h, alp_l, alp_exp;          /* Prediction gain; hi lo and exponent         */
+    Word16 Ah[M + 1], Al[M + 1];           /* LPC coef. in double prec.                   */
+    Word16 Anh[M + 1], Anl[M + 1];         /* LPC coef.for next iteration in double prec. */
+    Word32 t0, t1, t2;                     /* temporary variable                          */
+    Word16 *old_A, *old_rc;
 
-	/* Last A(z) for case of unstable filter */
-	old_A = mem;
-	old_rc = mem + M;
+    /* Last A(z) for case of unstable filter */
+    old_A = mem;
+    old_rc = mem + M;
 
-	/* K = A[1] = -R[1] / R[0] */
+    /* K = A[1] = -R[1] / R[0] */
 
-	t1 = ((Rh[1] << 16) + (Rl[1] << 1));   /* R[1] in Q31 */
-	t2 = L_abs(t1);                        /* abs R[1]         */
-	t0 = Div_32(t2, Rh[0], Rl[0]);         /* R[1]/R[0] in Q31 */
-	if (t1 > 0)
-		t0 = -t0;                          /* -R[1]/R[0]       */
+    t1 = ((Rh[1] << 16) + (Rl[1] << 1));   /* R[1] in Q31 */
+    t2 = L_abs(t1);                        /* abs R[1]         */
+    t0 = Div_32(t2, Rh[0], Rl[0]);         /* R[1]/R[0] in Q31 */
+    if (t1 > 0)
+        t0 = -t0;                          /* -R[1]/R[0]       */
 
-	Kh = t0 >> 16;
-	Kl = (t0 & 0xffff)>>1;
-	rc[0] = Kh;
-	t0 = (t0 >> 4);                        /* A[1] in Q27      */
+    Kh = t0 >> 16;
+    Kl = (t0 & 0xffff)>>1;
+    rc[0] = Kh;
+    t0 = (t0 >> 4);                        /* A[1] in Q27      */
 
-	Ah[1] = t0 >> 16;
-	Al[1] = (t0 & 0xffff)>>1;
+    Ah[1] = t0 >> 16;
+    Al[1] = (t0 & 0xffff)>>1;
 
-	/* Alpha = R[0] * (1-K**2) */
-	t0 = Mpy_32(Kh, Kl, Kh, Kl);           /* K*K      in Q31 */
-	t0 = L_abs(t0);                        /* Some case <0 !! */
-	t0 = vo_L_sub((Word32) 0x7fffffffL, t0);  /* 1 - K*K  in Q31 */
+    /* Alpha = R[0] * (1-K**2) */
+    t0 = Mpy_32(Kh, Kl, Kh, Kl);           /* K*K      in Q31 */
+    t0 = L_abs(t0);                        /* Some case <0 !! */
+    t0 = vo_L_sub((Word32) 0x7fffffffL, t0);  /* 1 - K*K  in Q31 */
 
-	hi = t0 >> 16;
-	lo = (t0 & 0xffff)>>1;
+    hi = t0 >> 16;
+    lo = (t0 & 0xffff)>>1;
 
-	t0 = Mpy_32(Rh[0], Rl[0], hi, lo);     /* Alpha in Q31    */
+    t0 = Mpy_32(Rh[0], Rl[0], hi, lo);     /* Alpha in Q31    */
 
-	/* Normalize Alpha */
-	alp_exp = norm_l(t0);
-	t0 = (t0 << alp_exp);
+    /* Normalize Alpha */
+    alp_exp = norm_l(t0);
+    t0 = (t0 << alp_exp);
 
-	alp_h = t0 >> 16;
-	alp_l = (t0 & 0xffff)>>1;
-	/*--------------------------------------*
-	 * ITERATIONS  I=2 to M                 *
-	 *--------------------------------------*/
-	for (i = 2; i <= M; i++)
-	{
-		/* t0 = SUM ( R[j]*A[i-j] ,j=1,i-1 ) +  R[i] */
-		t0 = 0;
-		for (j = 1; j < i; j++)
-			t0 = vo_L_add(t0, Mpy_32(Rh[j], Rl[j], Ah[i - j], Al[i - j]));
+    alp_h = t0 >> 16;
+    alp_l = (t0 & 0xffff)>>1;
+    /*--------------------------------------*
+     * ITERATIONS  I=2 to M                 *
+     *--------------------------------------*/
+    for (i = 2; i <= M; i++)
+    {
+        /* t0 = SUM ( R[j]*A[i-j] ,j=1,i-1 ) +  R[i] */
+        t0 = 0;
+        for (j = 1; j < i; j++)
+            t0 = vo_L_add(t0, Mpy_32(Rh[j], Rl[j], Ah[i - j], Al[i - j]));
 
-		t0 = t0 << 4;                 /* result in Q27 -> convert to Q31 */
-		/* No overflow possible            */
-		t1 = ((Rh[i] << 16) + (Rl[i] << 1));
-		t0 = vo_L_add(t0, t1);                /* add R[i] in Q31                 */
+        t0 = t0 << 4;                 /* result in Q27 -> convert to Q31 */
+        /* No overflow possible            */
+        t1 = ((Rh[i] << 16) + (Rl[i] << 1));
+        t0 = vo_L_add(t0, t1);                /* add R[i] in Q31                 */
 
-		/* K = -t0 / Alpha */
-		t1 = L_abs(t0);
-		t2 = Div_32(t1, alp_h, alp_l);     /* abs(t0)/Alpha                   */
-		if (t0 > 0)
-			t2 = -t2;                   /* K =-t0/Alpha                    */
-		t2 = (t2 << alp_exp);           /* denormalize; compare to Alpha   */
+        /* K = -t0 / Alpha */
+        t1 = L_abs(t0);
+        t2 = Div_32(t1, alp_h, alp_l);     /* abs(t0)/Alpha                   */
+        if (t0 > 0)
+            t2 = -t2;                   /* K =-t0/Alpha                    */
+        t2 = (t2 << alp_exp);           /* denormalize; compare to Alpha   */
 
-		Kh = t2 >> 16;
-		Kl = (t2 & 0xffff)>>1;
+        Kh = t2 >> 16;
+        Kl = (t2 & 0xffff)>>1;
 
-		rc[i - 1] = Kh;
-		/* Test for unstable filter. If unstable keep old A(z) */
-		if (abs_s(Kh) > 32750)
-		{
-			A[0] = 4096;                    /* Ai[0] not stored (always 1.0) */
-			for (j = 0; j < M; j++)
-			{
-				A[j + 1] = old_A[j];
-			}
-			rc[0] = old_rc[0];             /* only two rc coefficients are needed */
-			rc[1] = old_rc[1];
-			return;
-		}
-		/*------------------------------------------*
-		 *  Compute new LPC coeff. -> An[i]         *
-		 *  An[j]= A[j] + K*A[i-j]     , j=1 to i-1 *
-		 *  An[i]= K                                *
-		 *------------------------------------------*/
-		for (j = 1; j < i; j++)
-		{
-			t0 = Mpy_32(Kh, Kl, Ah[i - j], Al[i - j]);
-			t0 = vo_L_add(t0, ((Ah[j] << 16) + (Al[j] << 1)));
-			Anh[j] = t0 >> 16;
-			Anl[j] = (t0 & 0xffff)>>1;
-		}
-		t2 = (t2 >> 4);                 /* t2 = K in Q31 ->convert to Q27  */
+        rc[i - 1] = Kh;
+        /* Test for unstable filter. If unstable keep old A(z) */
+        if (abs_s(Kh) > 32750)
+        {
+            A[0] = 4096;                    /* Ai[0] not stored (always 1.0) */
+            for (j = 0; j < M; j++)
+            {
+                A[j + 1] = old_A[j];
+            }
+            rc[0] = old_rc[0];             /* only two rc coefficients are needed */
+            rc[1] = old_rc[1];
+            return;
+        }
+        /*------------------------------------------*
+         *  Compute new LPC coeff. -> An[i]         *
+         *  An[j]= A[j] + K*A[i-j]     , j=1 to i-1 *
+         *  An[i]= K                                *
+         *------------------------------------------*/
+        for (j = 1; j < i; j++)
+        {
+            t0 = Mpy_32(Kh, Kl, Ah[i - j], Al[i - j]);
+            t0 = vo_L_add(t0, ((Ah[j] << 16) + (Al[j] << 1)));
+            Anh[j] = t0 >> 16;
+            Anl[j] = (t0 & 0xffff)>>1;
+        }
+        t2 = (t2 >> 4);                 /* t2 = K in Q31 ->convert to Q27  */
 
-		VO_L_Extract(t2, &Anh[i], &Anl[i]);   /* An[i] in Q27                    */
+        VO_L_Extract(t2, &Anh[i], &Anl[i]);   /* An[i] in Q27                    */
 
-		/* Alpha = Alpha * (1-K**2) */
-		t0 = Mpy_32(Kh, Kl, Kh, Kl);               /* K*K      in Q31 */
-		t0 = L_abs(t0);                            /* Some case <0 !! */
-		t0 = vo_L_sub((Word32) 0x7fffffffL, t0);   /* 1 - K*K  in Q31 */
-		hi = t0 >> 16;
-		lo = (t0 & 0xffff)>>1;
-		t0 = Mpy_32(alp_h, alp_l, hi, lo); /* Alpha in Q31    */
+        /* Alpha = Alpha * (1-K**2) */
+        t0 = Mpy_32(Kh, Kl, Kh, Kl);               /* K*K      in Q31 */
+        t0 = L_abs(t0);                            /* Some case <0 !! */
+        t0 = vo_L_sub((Word32) 0x7fffffffL, t0);   /* 1 - K*K  in Q31 */
+        hi = t0 >> 16;
+        lo = (t0 & 0xffff)>>1;
+        t0 = Mpy_32(alp_h, alp_l, hi, lo); /* Alpha in Q31    */
 
-		/* Normalize Alpha */
-		j = norm_l(t0);
-		t0 = (t0 << j);
-		alp_h = t0 >> 16;
-		alp_l = (t0 & 0xffff)>>1;
-		alp_exp += j;         /* Add normalization to alp_exp */
+        /* Normalize Alpha */
+        j = norm_l(t0);
+        t0 = (t0 << j);
+        alp_h = t0 >> 16;
+        alp_l = (t0 & 0xffff)>>1;
+        alp_exp += j;         /* Add normalization to alp_exp */
 
-		/* A[j] = An[j] */
-		for (j = 1; j <= i; j++)
-		{
-			Ah[j] = Anh[j];
-			Al[j] = Anl[j];
-		}
-	}
-	/* Truncate A[i] in Q27 to Q12 with rounding */
-	A[0] = 4096;
-	for (i = 1; i <= M; i++)
-	{
-		t0 = (Ah[i] << 16) + (Al[i] << 1);
-		old_A[i - 1] = A[i] = vo_round((t0 << 1));
-	}
-	old_rc[0] = rc[0];
-	old_rc[1] = rc[1];
+        /* A[j] = An[j] */
+        for (j = 1; j <= i; j++)
+        {
+            Ah[j] = Anh[j];
+            Al[j] = Anl[j];
+        }
+    }
+    /* Truncate A[i] in Q27 to Q12 with rounding */
+    A[0] = 4096;
+    for (i = 1; i <= M; i++)
+    {
+        t0 = (Ah[i] << 16) + (Al[i] << 1);
+        old_A[i - 1] = A[i] = vo_round((t0 << 1));
+    }
+    old_rc[0] = rc[0];
+    old_rc[1] = rc[1];
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/log2.c b/media/libstagefright/codecs/amrwbenc/src/log2.c
index 0f65541..f14058e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/log2.c
+++ b/media/libstagefright/codecs/amrwbenc/src/log2.c
@@ -54,33 +54,33 @@
 *************************************************************************/
 
 void Log2_norm (
-		Word32 L_x,         /* (i) : input value (normalized)                    */
-		Word16 exp,         /* (i) : norm_l (L_x)                                */
-		Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
-		Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */
-	       )
+        Word32 L_x,         /* (i) : input value (normalized)                    */
+        Word16 exp,         /* (i) : norm_l (L_x)                                */
+        Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+        Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */
+           )
 {
-	Word16 i, a, tmp;
-	Word32 L_y;
-	if (L_x <= (Word32) 0)
-	{
-		*exponent = 0;
-		*fraction = 0;
-		return;
-	}
-	*exponent = (30 - exp);
-	L_x = (L_x >> 9);
-	i = extract_h (L_x);                /* Extract b25-b31 */
-	L_x = (L_x >> 1);
-	a = (Word16)(L_x);                /* Extract b10-b24 of fraction */
-	a = (Word16)(a & (Word16)0x7fff);
-	i -= 32;
-	L_y = L_deposit_h (table[i]);       /* table[i] << 16        */
-	tmp = vo_sub(table[i], table[i + 1]); /* table[i] - table[i+1] */
-	L_y = vo_L_msu (L_y, tmp, a);          /* L_y -= tmp*a*2        */
-	*fraction = extract_h (L_y);
+    Word16 i, a, tmp;
+    Word32 L_y;
+    if (L_x <= (Word32) 0)
+    {
+        *exponent = 0;
+        *fraction = 0;
+        return;
+    }
+    *exponent = (30 - exp);
+    L_x = (L_x >> 9);
+    i = extract_h (L_x);                /* Extract b25-b31 */
+    L_x = (L_x >> 1);
+    a = (Word16)(L_x);                /* Extract b10-b24 of fraction */
+    a = (Word16)(a & (Word16)0x7fff);
+    i -= 32;
+    L_y = L_deposit_h (table[i]);       /* table[i] << 16        */
+    tmp = vo_sub(table[i], table[i + 1]); /* table[i] - table[i+1] */
+    L_y = vo_L_msu (L_y, tmp, a);          /* L_y -= tmp*a*2        */
+    *fraction = extract_h (L_y);
 
-	return;
+    return;
 }
 
 /*************************************************************************
@@ -96,15 +96,15 @@
 *************************************************************************/
 
 void Log2 (
-		Word32 L_x,         /* (i) : input value                                 */
-		Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
-		Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1) */
-	  )
+        Word32 L_x,         /* (i) : input value                                 */
+        Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+        Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1) */
+      )
 {
-	Word16 exp;
+    Word16 exp;
 
-	exp = norm_l(L_x);
-	Log2_norm ((L_x << exp), exp, exponent, fraction);
+    exp = norm_l(L_x);
+    Log2_norm ((L_x << exp), exp, exponent, fraction);
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/lp_dec2.c b/media/libstagefright/codecs/amrwbenc/src/lp_dec2.c
index 1d5d076..9a9dd34 100644
--- a/media/libstagefright/codecs/amrwbenc/src/lp_dec2.c
+++ b/media/libstagefright/codecs/amrwbenc/src/lp_dec2.c
@@ -17,7 +17,7 @@
 /***********************************************************************
 *       File: lp_dec2.c                                                *
 *                                                                      *
-*	Description:Decimate a vector by 2 with 2nd order fir filter   *
+*   Description:Decimate a vector by 2 with 2nd order fir filter   *
 *                                                                      *
 ************************************************************************/
 
@@ -33,36 +33,36 @@
 static Word16 h_fir[L_FIR] = {4260, 7536, 9175, 7536, 4260};
 
 void LP_Decim2(
-		Word16 x[],                           /* in/out: signal to process         */
-		Word16 l,                             /* input : size of filtering         */
-		Word16 mem[]                          /* in/out: memory (size=3)           */
-	      )
+        Word16 x[],                           /* in/out: signal to process         */
+        Word16 l,                             /* input : size of filtering         */
+        Word16 mem[]                          /* in/out: memory (size=3)           */
+          )
 {
-	Word16 *p_x, x_buf[L_FRAME + L_MEM];
-	Word32 i, j;
-	Word32 L_tmp;
-	/* copy initial filter states into buffer */
-	p_x = x_buf;
-	for (i = 0; i < L_MEM; i++)
-	{
-		*p_x++ = mem[i];
-		mem[i] = x[l - L_MEM + i];
-	}
-	for (i = 0; i < l; i++)
-	{
-		*p_x++ = x[i];
-	}
-	for (i = 0, j = 0; i < l; i += 2, j++)
-	{
-		p_x = &x_buf[i];
-		L_tmp  = ((*p_x++) * h_fir[0]);
-		L_tmp += ((*p_x++) * h_fir[1]);
-		L_tmp += ((*p_x++) * h_fir[2]);
-		L_tmp += ((*p_x++) * h_fir[3]);
-		L_tmp += ((*p_x++) * h_fir[4]);
-		x[j] = (L_tmp + 0x4000)>>15;
-	}
-	return;
+    Word16 *p_x, x_buf[L_FRAME + L_MEM];
+    Word32 i, j;
+    Word32 L_tmp;
+    /* copy initial filter states into buffer */
+    p_x = x_buf;
+    for (i = 0; i < L_MEM; i++)
+    {
+        *p_x++ = mem[i];
+        mem[i] = x[l - L_MEM + i];
+    }
+    for (i = 0; i < l; i++)
+    {
+        *p_x++ = x[i];
+    }
+    for (i = 0, j = 0; i < l; i += 2, j++)
+    {
+        p_x = &x_buf[i];
+        L_tmp  = ((*p_x++) * h_fir[0]);
+        L_tmp += ((*p_x++) * h_fir[1]);
+        L_tmp += ((*p_x++) * h_fir[2]);
+        L_tmp += ((*p_x++) * h_fir[3]);
+        L_tmp += ((*p_x++) * h_fir[4]);
+        x[j] = (L_tmp + 0x4000)>>15;
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/math_op.c b/media/libstagefright/codecs/amrwbenc/src/math_op.c
index 7affbb2..9d7c74e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/math_op.c
+++ b/media/libstagefright/codecs/amrwbenc/src/math_op.c
@@ -55,17 +55,17 @@
 |___________________________________________________________________________|
 */
 Word32 Isqrt(                              /* (o) Q31 : output value (range: 0<=val<1)         */
-		Word32 L_x                            /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */
-	    )
+        Word32 L_x                            /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */
+        )
 {
-	Word16 exp;
-	Word32 L_y;
-	exp = norm_l(L_x);
-	L_x = (L_x << exp);                 /* L_x is normalized */
-	exp = (31 - exp);
-	Isqrt_n(&L_x, &exp);
-	L_y = (L_x << exp);                 /* denormalization   */
-	return (L_y);
+    Word16 exp;
+    Word32 L_y;
+    exp = norm_l(L_x);
+    L_x = (L_x << exp);                 /* L_x is normalized */
+    exp = (31 - exp);
+    Isqrt_n(&L_x, &exp);
+    L_y = (L_x << exp);                 /* denormalization   */
+    return (L_y);
 }
 
 /*___________________________________________________________________________
@@ -90,43 +90,43 @@
 */
 static Word16 table_isqrt[49] =
 {
-	32767, 31790, 30894, 30070, 29309, 28602, 27945, 27330, 26755, 26214,
-	25705, 25225, 24770, 24339, 23930, 23541, 23170, 22817, 22479, 22155,
-	21845, 21548, 21263, 20988, 20724, 20470, 20225, 19988, 19760, 19539,
-	19326, 19119, 18919, 18725, 18536, 18354, 18176, 18004, 17837, 17674,
-	17515, 17361, 17211, 17064, 16921, 16782, 16646, 16514, 16384
+    32767, 31790, 30894, 30070, 29309, 28602, 27945, 27330, 26755, 26214,
+    25705, 25225, 24770, 24339, 23930, 23541, 23170, 22817, 22479, 22155,
+    21845, 21548, 21263, 20988, 20724, 20470, 20225, 19988, 19760, 19539,
+    19326, 19119, 18919, 18725, 18536, 18354, 18176, 18004, 17837, 17674,
+    17515, 17361, 17211, 17064, 16921, 16782, 16646, 16514, 16384
 };
 
 void Isqrt_n(
-		Word32 * frac,                        /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */
-		Word16 * exp                          /* (i/o)    : exponent (value = frac x 2^exponent) */
-	    )
+        Word32 * frac,                        /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */
+        Word16 * exp                          /* (i/o)    : exponent (value = frac x 2^exponent) */
+        )
 {
-	Word16 i, a, tmp;
+    Word16 i, a, tmp;
 
-	if (*frac <= (Word32) 0)
-	{
-		*exp = 0;
-		*frac = 0x7fffffffL;
-		return;
-	}
+    if (*frac <= (Word32) 0)
+    {
+        *exp = 0;
+        *frac = 0x7fffffffL;
+        return;
+    }
 
-	if((*exp & 1) == 1)                       /*If exponant odd -> shift right */
-		*frac = (*frac) >> 1;
+    if((*exp & 1) == 1)                       /*If exponant odd -> shift right */
+        *frac = (*frac) >> 1;
 
-	*exp = negate((*exp - 1) >> 1);
+    *exp = negate((*exp - 1) >> 1);
 
-	*frac = (*frac >> 9);
-	i = extract_h(*frac);                  /* Extract b25-b31 */
-	*frac = (*frac >> 1);
-	a = (Word16)(*frac);                  /* Extract b10-b24 */
-	a = (Word16) (a & (Word16) 0x7fff);
-	i -= 16;
-	*frac = L_deposit_h(table_isqrt[i]);   /* table[i] << 16         */
-	tmp = vo_sub(table_isqrt[i], table_isqrt[i + 1]);      /* table[i] - table[i+1]) */
-	*frac = vo_L_msu(*frac, tmp, a);          /* frac -=  tmp*a*2       */
+    *frac = (*frac >> 9);
+    i = extract_h(*frac);                  /* Extract b25-b31 */
+    *frac = (*frac >> 1);
+    a = (Word16)(*frac);                  /* Extract b10-b24 */
+    a = (Word16) (a & (Word16) 0x7fff);
+    i -= 16;
+    *frac = L_deposit_h(table_isqrt[i]);   /* table[i] << 16         */
+    tmp = vo_sub(table_isqrt[i], table_isqrt[i + 1]);      /* table[i] - table[i+1]) */
+    *frac = vo_L_msu(*frac, tmp, a);          /* frac -=  tmp*a*2       */
 
-	return;
+    return;
 }
 
 /*___________________________________________________________________________
@@ -149,34 +149,34 @@
 */
 static Word16 table_pow2[33] =
 {
-	16384, 16743, 17109, 17484, 17867, 18258, 18658, 19066, 19484, 19911,
-	20347, 20792, 21247, 21713, 22188, 22674, 23170, 23678, 24196, 24726,
-	25268, 25821, 26386, 26964, 27554, 28158, 28774, 29405, 30048, 30706,
-	31379, 32066, 32767
+    16384, 16743, 17109, 17484, 17867, 18258, 18658, 19066, 19484, 19911,
+    20347, 20792, 21247, 21713, 22188, 22674, 23170, 23678, 24196, 24726,
+    25268, 25821, 26386, 26964, 27554, 28158, 28774, 29405, 30048, 30706,
+    31379, 32066, 32767
 };
 
 Word32 Pow2(                               /* (o) Q0  : result       (range: 0<=val<=0x7fffffff) */
-		Word16 exponant,                      /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */
-		Word16 fraction                       /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */
-	   )
+        Word16 exponant,                      /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */
+        Word16 fraction                       /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */
+       )
 {
-	Word16 exp, i, a, tmp;
-	Word32 L_x;
+    Word16 exp, i, a, tmp;
+    Word32 L_x;
 
-	L_x = vo_L_mult(fraction, 32);            /* L_x = fraction<<6           */
-	i = extract_h(L_x);                    /* Extract b10-b16 of fraction */
-	L_x =L_x >> 1;
-	a = (Word16)(L_x);                    /* Extract b0-b9   of fraction */
-	a = (Word16) (a & (Word16) 0x7fff);
+    L_x = vo_L_mult(fraction, 32);            /* L_x = fraction<<6           */
+    i = extract_h(L_x);                    /* Extract b10-b16 of fraction */
+    L_x =L_x >> 1;
+    a = (Word16)(L_x);                    /* Extract b0-b9   of fraction */
+    a = (Word16) (a & (Word16) 0x7fff);
 
-	L_x = L_deposit_h(table_pow2[i]);      /* table[i] << 16        */
-	tmp = vo_sub(table_pow2[i], table_pow2[i + 1]);        /* table[i] - table[i+1] */
-	L_x -= (tmp * a)<<1;              /* L_x -= tmp*a*2        */
+    L_x = L_deposit_h(table_pow2[i]);      /* table[i] << 16        */
+    tmp = vo_sub(table_pow2[i], table_pow2[i + 1]);        /* table[i] - table[i+1] */
+    L_x -= (tmp * a)<<1;              /* L_x -= tmp*a*2        */
 
-	exp = vo_sub(30, exponant);
-	L_x = vo_L_shr_r(L_x, exp);
+    exp = vo_sub(30, exponant);
+    L_x = vo_L_shr_r(L_x, exp);
 
-	return (L_x);
+    return (L_x);
 }
 
 /*___________________________________________________________________________
@@ -194,25 +194,30 @@
 */
 
 Word32 Dot_product12(                      /* (o) Q31: normalized result (1 < val <= -1) */
-		Word16 x[],                           /* (i) 12bits: x vector                       */
-		Word16 y[],                           /* (i) 12bits: y vector                       */
-		Word16 lg,                            /* (i)    : vector length                     */
-		Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
-		)
+        Word16 x[],                           /* (i) 12bits: x vector                       */
+        Word16 y[],                           /* (i) 12bits: y vector                       */
+        Word16 lg,                            /* (i)    : vector length                     */
+        Word16 * exp                          /* (o)    : exponent of result (0..+30)       */
+        )
 {
-	Word16 sft;
-	Word32 i, L_sum;
-	L_sum = 0;
-	for (i = 0; i < lg; i++)
-	{
-		L_sum += x[i] * y[i];
-	}
-	L_sum = (L_sum << 1) + 1;
-	/* Normalize acc in Q31 */
-	sft = norm_l(L_sum);
-	L_sum = L_sum << sft;
-	*exp = 30 - sft;            /* exponent = 0..30 */
-	return (L_sum);
+    Word16 sft;
+    Word32 i, L_sum;
+    L_sum = 0;
+    for (i = 0; i < lg; i++)
+    {
+        Word32 tmp = (Word32) x[i] * (Word32) y[i];
+        if (tmp == (Word32) 0x40000000L) {
+            tmp = MAX_32;
+        }
+        L_sum = L_add(L_sum, tmp);
+    }
+    L_sum = L_shl2(L_sum, 1);
+    L_sum = L_add(L_sum, 1);
+    /* Normalize acc in Q31 */
+    sft = norm_l(L_sum);
+    L_sum = L_sum << sft;
+    *exp = 30 - sft;            /* exponent = 0..30 */
+    return (L_sum);
 
 }
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/mem_align.c b/media/libstagefright/codecs/amrwbenc/src/mem_align.c
index 3b7853f..04e5976 100644
--- a/media/libstagefright/codecs/amrwbenc/src/mem_align.c
+++ b/media/libstagefright/codecs/amrwbenc/src/mem_align.c
@@ -15,18 +15,18 @@
  */
 
 /*******************************************************************************
-	File:		mem_align.c
+    File:       mem_align.c
 
-	Content:	Memory alloc alignments functions
+    Content:    Memory alloc alignments functions
 
 *******************************************************************************/
 
 
-#include	"mem_align.h"
+#include    "mem_align.h"
 #ifdef _MSC_VER
-#include	<stddef.h>
+#include    <stddef.h>
 #else
-#include	<stdint.h>
+#include    <stdint.h>
 #endif
 
 /*****************************************************************************
@@ -39,50 +39,50 @@
 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;
+    int ret;
+    unsigned char *mem_ptr;
+    VO_MEM_INFO MemInfo;
 
-	if (!alignment) {
+    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;
+        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);
+        pMemop->Set(CodecID, mem_ptr, 0, size + 1);
 
-		*mem_ptr = (unsigned char)1;
+        *mem_ptr = (unsigned char)1;
 
-		return ((void *)(mem_ptr+1));
-	} else {
-		unsigned char *tmp;
+        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;
+        MemInfo.Flag = 0;
+        MemInfo.Size = size + alignment;
+        ret = pMemop->Alloc(CodecID, &MemInfo);
+        if(ret != 0)
+            return 0;
 
-		tmp = (unsigned char *)MemInfo.VBuffer;
+        tmp = (unsigned char *)MemInfo.VBuffer;
 
-		pMemop->Set(CodecID, tmp, 0, size + alignment);
+        pMemop->Set(CodecID, tmp, 0, size + alignment);
 
-		mem_ptr =
-			(unsigned char *) ((intptr_t) (tmp + alignment - 1) &
-					(~((intptr_t) (alignment - 1))));
+        mem_ptr =
+            (unsigned char *) ((intptr_t) (tmp + alignment - 1) &
+                    (~((intptr_t) (alignment - 1))));
 
-		if (mem_ptr == tmp)
-			mem_ptr += alignment;
+        if (mem_ptr == tmp)
+            mem_ptr += alignment;
 
-		*(mem_ptr - 1) = (unsigned char) (mem_ptr - tmp);
+        *(mem_ptr - 1) = (unsigned char) (mem_ptr - tmp);
 
-		return ((void *)mem_ptr);
-	}
+        return ((void *)mem_ptr);
+    }
 
-	return(0);
+    return(0);
 }
 
 
@@ -96,16 +96,16 @@
 mem_free(VO_MEM_OPERATOR *pMemop, void *mem_ptr, unsigned int CodecID)
 {
 
-	unsigned char *ptr;
+    unsigned char *ptr;
 
-	if (mem_ptr == 0)
-		return;
+    if (mem_ptr == 0)
+        return;
 
-	ptr = mem_ptr;
+    ptr = mem_ptr;
 
-	ptr -= *(ptr - 1);
+    ptr -= *(ptr - 1);
 
-	pMemop->Free(CodecID, ptr);
+    pMemop->Free(CodecID, ptr);
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/oper_32b.c b/media/libstagefright/codecs/amrwbenc/src/oper_32b.c
index 27cad76..e6f80d0 100644
--- a/media/libstagefright/codecs/amrwbenc/src/oper_32b.c
+++ b/media/libstagefright/codecs/amrwbenc/src/oper_32b.c
@@ -56,9 +56,9 @@
 
 __inline void VO_L_Extract (Word32 L_32, Word16 *hi, Word16 *lo)
 {
-	*hi = (Word16)(L_32 >> 16);
-	*lo = (Word16)((L_32 & 0xffff) >> 1);
-	return;
+    *hi = (Word16)(L_32 >> 16);
+    *lo = (Word16)((L_32 & 0xffff) >> 1);
+    return;
 }
 
 /*****************************************************************************
@@ -84,11 +84,11 @@
 
 Word32 L_Comp (Word16 hi, Word16 lo)
 {
-	Word32 L_32;
+    Word32 L_32;
 
-	L_32 = L_deposit_h (hi);
+    L_32 = L_deposit_h (hi);
 
-	return (L_mac (L_32, lo, 1));       /* = hi<<16 + lo<<1 */
+    return (L_mac (L_32, lo, 1));       /* = hi<<16 + lo<<1 */
 }
 
 /*****************************************************************************
@@ -113,13 +113,13 @@
 
 __inline Word32  Mpy_32 (Word16 hi1, Word16 lo1, Word16 hi2, Word16 lo2)
 {
-	Word32 L_32;
-	L_32 = (hi1 * hi2);
-	L_32 += (hi1 * lo2) >> 15;
-	L_32 += (lo1 * hi2) >> 15;
-	L_32 <<= 1;
+    Word32 L_32;
+    L_32 = (hi1 * hi2);
+    L_32 += (hi1 * lo2) >> 15;
+    L_32 += (lo1 * hi2) >> 15;
+    L_32 <<= 1;
 
-	return (L_32);
+    return (L_32);
 }
 
 /*****************************************************************************
@@ -142,12 +142,12 @@
 
 __inline Word32 Mpy_32_16 (Word16 hi, Word16 lo, Word16 n)
 {
-	Word32 L_32;
+    Word32 L_32;
 
-	L_32 = (hi * n)<<1;
-	L_32 += (((lo * n)>>15)<<1);
+    L_32 = (hi * n)<<1;
+    L_32 += (((lo * n)>>15)<<1);
 
-	return (L_32);
+    return (L_32);
 }
 
 /*****************************************************************************
@@ -194,30 +194,30 @@
 
 Word32 Div_32 (Word32 L_num, Word16 denom_hi, Word16 denom_lo)
 {
-	Word16 approx, hi, lo, n_hi, n_lo;
-	Word32 L_32;
+    Word16 approx, hi, lo, n_hi, n_lo;
+    Word32 L_32;
 
-	/* First approximation: 1 / L_denom = 1/denom_hi */
+    /* First approximation: 1 / L_denom = 1/denom_hi */
 
-	approx = div_s ((Word16) 0x3fff, denom_hi);
+    approx = div_s ((Word16) 0x3fff, denom_hi);
 
-	/* 1/L_denom = approx * (2.0 - L_denom * approx) */
+    /* 1/L_denom = approx * (2.0 - L_denom * approx) */
 
-	L_32 = Mpy_32_16 (denom_hi, denom_lo, approx);
+    L_32 = Mpy_32_16 (denom_hi, denom_lo, approx);
 
-	L_32 = L_sub ((Word32) 0x7fffffffL, L_32);
-	hi = L_32 >> 16;
-	lo = (L_32 & 0xffff) >> 1;
+    L_32 = L_sub ((Word32) 0x7fffffffL, L_32);
+    hi = L_32 >> 16;
+    lo = (L_32 & 0xffff) >> 1;
 
-	L_32 = Mpy_32_16 (hi, lo, approx);
+    L_32 = Mpy_32_16 (hi, lo, approx);
 
-	/* L_num * (1/L_denom) */
-	hi = L_32 >> 16;
-	lo = (L_32 & 0xffff) >> 1;
-	VO_L_Extract (L_num, &n_hi, &n_lo);
-	L_32 = Mpy_32 (n_hi, n_lo, hi, lo);
-	L_32 = L_shl2(L_32, 2);
+    /* L_num * (1/L_denom) */
+    hi = L_32 >> 16;
+    lo = (L_32 & 0xffff) >> 1;
+    VO_L_Extract (L_num, &n_hi, &n_lo);
+    L_32 = Mpy_32 (n_hi, n_lo, hi, lo);
+    L_32 = L_shl2(L_32, 2);
 
-	return (L_32);
+    return (L_32);
 }
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/p_med_ol.c b/media/libstagefright/codecs/amrwbenc/src/p_med_ol.c
index b8174b9..5d2b4bd 100644
--- a/media/libstagefright/codecs/amrwbenc/src/p_med_ol.c
+++ b/media/libstagefright/codecs/amrwbenc/src/p_med_ol.c
@@ -18,7 +18,7 @@
 *      File: p_med_ol.c                                                *
 *                                                                      *
 *      Description: Compute the open loop pitch lag                    *
-*	            output: open loop pitch lag                        *
+*               output: open loop pitch lag                        *
 ************************************************************************/
 
 #include "typedef.h"
@@ -29,131 +29,131 @@
 #include "p_med_ol.tab"
 
 Word16 Pitch_med_ol(
-		   Word16      wsp[],        /*   i: signal used to compute the open loop pitch*/
+           Word16      wsp[],        /*   i: signal used to compute the open loop pitch*/
                                      /*      wsp[-pit_max] to wsp[-1] should be known */
-		   Coder_State *st,          /* i/o: codec global structure */
-		   Word16      L_frame       /*   i: length of frame to compute pitch */
-		)
+           Coder_State *st,          /* i/o: codec global structure */
+           Word16      L_frame       /*   i: length of frame to compute pitch */
+        )
 {
-	Word16 Tm;
-	Word16 hi, lo;
-	Word16 *ww, *we, *hp_wsp;
-	Word16 exp_R0, exp_R1, exp_R2;
-	Word32 i, j, max, R0, R1, R2;
-	Word16 *p1, *p2;
-	Word16 L_min = 17;                   /* minimum pitch lag: PIT_MIN / OPL_DECIM */
-	Word16 L_max = 115;                  /* maximum pitch lag: PIT_MAX / OPL_DECIM */
-	Word16 L_0 = st->old_T0_med;         /* old open-loop pitch */
-	Word16 *gain = &(st->ol_gain);       /* normalize correlation of hp_wsp for the lag */
-	Word16 *hp_wsp_mem = st->hp_wsp_mem; /* memory of the hypass filter for hp_wsp[] (lg = 9)*/
-	Word16 *old_hp_wsp = st->old_hp_wsp; /* hypass wsp[] */
-	Word16 wght_flg = st->ol_wght_flg;   /* is weighting function used */
+    Word16 Tm;
+    Word16 hi, lo;
+    Word16 *ww, *we, *hp_wsp;
+    Word16 exp_R0, exp_R1, exp_R2;
+    Word32 i, j, max, R0, R1, R2;
+    Word16 *p1, *p2;
+    Word16 L_min = 17;                   /* minimum pitch lag: PIT_MIN / OPL_DECIM */
+    Word16 L_max = 115;                  /* maximum pitch lag: PIT_MAX / OPL_DECIM */
+    Word16 L_0 = st->old_T0_med;         /* old open-loop pitch */
+    Word16 *gain = &(st->ol_gain);       /* normalize correlation of hp_wsp for the lag */
+    Word16 *hp_wsp_mem = st->hp_wsp_mem; /* memory of the hypass filter for hp_wsp[] (lg = 9)*/
+    Word16 *old_hp_wsp = st->old_hp_wsp; /* hypass wsp[] */
+    Word16 wght_flg = st->ol_wght_flg;   /* is weighting function used */
 
-	ww = &corrweight[198];
-	we = &corrweight[98 + L_max - L_0];
+    ww = &corrweight[198];
+    we = &corrweight[98 + L_max - L_0];
 
-	max = MIN_32;
-	Tm = 0;
-	for (i = L_max; i > L_min; i--)
-	{
-		/* Compute the correlation */
-		R0 = 0;
-		p1 = wsp;
-		p2 = &wsp[-i];
-		for (j = 0; j < L_frame; j+=4)
-		{
-			R0 += vo_L_mult((*p1++), (*p2++));
-			R0 += vo_L_mult((*p1++), (*p2++));
-			R0 += vo_L_mult((*p1++), (*p2++));
-			R0 += vo_L_mult((*p1++), (*p2++));
-		}
-		/* Weighting of the correlation function.   */
-		hi = R0>>16;
-		lo = (R0 & 0xffff)>>1;
+    max = MIN_32;
+    Tm = 0;
+    for (i = L_max; i > L_min; i--)
+    {
+        /* Compute the correlation */
+        R0 = 0;
+        p1 = wsp;
+        p2 = &wsp[-i];
+        for (j = 0; j < L_frame; j+=4)
+        {
+            R0 += vo_L_mult((*p1++), (*p2++));
+            R0 += vo_L_mult((*p1++), (*p2++));
+            R0 += vo_L_mult((*p1++), (*p2++));
+            R0 += vo_L_mult((*p1++), (*p2++));
+        }
+        /* Weighting of the correlation function.   */
+        hi = R0>>16;
+        lo = (R0 & 0xffff)>>1;
 
-		R0 = Mpy_32_16(hi, lo, *ww);
-		ww--;
+        R0 = Mpy_32_16(hi, lo, *ww);
+        ww--;
 
-		if ((L_0 > 0) && (wght_flg > 0))
-		{
-			/* Weight the neighbourhood of the old lag. */
-			hi = R0>>16;
-			lo = (R0 & 0xffff)>>1;
-			R0 = Mpy_32_16(hi, lo, *we);
-			we--;
-		}
-		if(R0 >= max)
-		{
-			max = R0;
-			Tm = i;
-		}
-	}
+        if ((L_0 > 0) && (wght_flg > 0))
+        {
+            /* Weight the neighbourhood of the old lag. */
+            hi = R0>>16;
+            lo = (R0 & 0xffff)>>1;
+            R0 = Mpy_32_16(hi, lo, *we);
+            we--;
+        }
+        if(R0 >= max)
+        {
+            max = R0;
+            Tm = i;
+        }
+    }
 
-	/* Hypass the wsp[] vector */
-	hp_wsp = old_hp_wsp + L_max;
-	Hp_wsp(wsp, hp_wsp, L_frame, hp_wsp_mem);
+    /* Hypass the wsp[] vector */
+    hp_wsp = old_hp_wsp + L_max;
+    Hp_wsp(wsp, hp_wsp, L_frame, hp_wsp_mem);
 
-	/* Compute normalize correlation at delay Tm */
-	R0 = 0;
-	R1 = 0;
-	R2 = 0;
-	p1 = hp_wsp;
-	p2 = hp_wsp - Tm;
-	for (j = 0; j < L_frame; j+=4)
-	{
-		R2 += vo_mult32(*p1, *p1);
-		R1 += vo_mult32(*p2, *p2);
-		R0 += vo_mult32(*p1++, *p2++);
-		R2 += vo_mult32(*p1, *p1);
-		R1 += vo_mult32(*p2, *p2);
-		R0 += vo_mult32(*p1++, *p2++);
-		R2 += vo_mult32(*p1, *p1);
-		R1 += vo_mult32(*p2, *p2);
-		R0 += vo_mult32(*p1++, *p2++);
-		R2 += vo_mult32(*p1, *p1);
-		R1 += vo_mult32(*p2, *p2);
-		R0 += vo_mult32(*p1++, *p2++);
-	}
-	R0 = R0 <<1;
-	R1 = (R1 <<1) + 1L;
-	R2 = (R2 <<1) + 1L;
-	/* gain = R0/ sqrt(R1*R2) */
+    /* Compute normalize correlation at delay Tm */
+    R0 = 0;
+    R1 = 0;
+    R2 = 0;
+    p1 = hp_wsp;
+    p2 = hp_wsp - Tm;
+    for (j = 0; j < L_frame; j+=4)
+    {
+        R2 += vo_mult32(*p1, *p1);
+        R1 += vo_mult32(*p2, *p2);
+        R0 += vo_mult32(*p1++, *p2++);
+        R2 += vo_mult32(*p1, *p1);
+        R1 += vo_mult32(*p2, *p2);
+        R0 += vo_mult32(*p1++, *p2++);
+        R2 += vo_mult32(*p1, *p1);
+        R1 += vo_mult32(*p2, *p2);
+        R0 += vo_mult32(*p1++, *p2++);
+        R2 += vo_mult32(*p1, *p1);
+        R1 += vo_mult32(*p2, *p2);
+        R0 += vo_mult32(*p1++, *p2++);
+    }
+    R0 = R0 <<1;
+    R1 = (R1 <<1) + 1L;
+    R2 = (R2 <<1) + 1L;
+    /* gain = R0/ sqrt(R1*R2) */
 
-	exp_R0 = norm_l(R0);
-	R0 = (R0 << exp_R0);
+    exp_R0 = norm_l(R0);
+    R0 = (R0 << exp_R0);
 
-	exp_R1 = norm_l(R1);
-	R1 = (R1 << exp_R1);
+    exp_R1 = norm_l(R1);
+    R1 = (R1 << exp_R1);
 
-	exp_R2 = norm_l(R2);
-	R2 = (R2 << exp_R2);
+    exp_R2 = norm_l(R2);
+    R2 = (R2 << exp_R2);
 
 
-	R1 = vo_L_mult(vo_round(R1), vo_round(R2));
+    R1 = vo_L_mult(voround(R1), voround(R2));
 
-	i = norm_l(R1);
-	R1 = (R1 << i);
+    i = norm_l(R1);
+    R1 = (R1 << i);
 
-	exp_R1 += exp_R2;
-	exp_R1 += i;
-	exp_R1 = 62 - exp_R1;
+    exp_R1 += exp_R2;
+    exp_R1 += i;
+    exp_R1 = 62 - exp_R1;
 
-	Isqrt_n(&R1, &exp_R1);
+    Isqrt_n(&R1, &exp_R1);
 
-	R0 = vo_L_mult(voround(R0), voround(R1));
-	exp_R0 = 31 - exp_R0;
-	exp_R0 += exp_R1;
+    R0 = vo_L_mult(voround(R0), voround(R1));
+    exp_R0 = 31 - exp_R0;
+    exp_R0 += exp_R1;
 
-	*gain = vo_round(L_shl(R0, exp_R0));
+    *gain = vo_round(L_shl(R0, exp_R0));
 
-	/* Shitf hp_wsp[] for next frame */
+    /* Shitf hp_wsp[] for next frame */
 
-	for (i = 0; i < L_max; i++)
-	{
-		old_hp_wsp[i] = old_hp_wsp[i + L_frame];
-	}
+    for (i = 0; i < L_max; i++)
+    {
+        old_hp_wsp[i] = old_hp_wsp[i + L_frame];
+    }
 
-	return (Tm);
+    return (Tm);
 }
 
 /************************************************************************
@@ -171,84 +171,84 @@
 
 Word16 median5(Word16 x[])
 {
-	Word16 x1, x2, x3, x4, x5;
-	Word16 tmp;
+    Word16 x1, x2, x3, x4, x5;
+    Word16 tmp;
 
-	x1 = x[-2];
-	x2 = x[-1];
-	x3 = x[0];
-	x4 = x[1];
-	x5 = x[2];
+    x1 = x[-2];
+    x2 = x[-1];
+    x3 = x[0];
+    x4 = x[1];
+    x5 = x[2];
 
-	if (x2 < x1)
-	{
-		tmp = x1;
-		x1 = x2;
-		x2 = tmp;
-	}
-	if (x3 < x1)
-	{
-		tmp = x1;
-		x1 = x3;
-		x3 = tmp;
-	}
-	if (x4 < x1)
-	{
-		tmp = x1;
-		x1 = x4;
-		x4 = tmp;
-	}
-	if (x5 < x1)
-	{
-		x5 = x1;
-	}
-	if (x3 < x2)
-	{
-		tmp = x2;
-		x2 = x3;
-		x3 = tmp;
-	}
-	if (x4 < x2)
-	{
-		tmp = x2;
-		x2 = x4;
-		x4 = tmp;
-	}
-	if (x5 < x2)
-	{
-		x5 = x2;
-	}
-	if (x4 < x3)
-	{
-		x3 = x4;
-	}
-	if (x5 < x3)
-	{
-		x3 = x5;
-	}
-	return (x3);
+    if (x2 < x1)
+    {
+        tmp = x1;
+        x1 = x2;
+        x2 = tmp;
+    }
+    if (x3 < x1)
+    {
+        tmp = x1;
+        x1 = x3;
+        x3 = tmp;
+    }
+    if (x4 < x1)
+    {
+        tmp = x1;
+        x1 = x4;
+        x4 = tmp;
+    }
+    if (x5 < x1)
+    {
+        x5 = x1;
+    }
+    if (x3 < x2)
+    {
+        tmp = x2;
+        x2 = x3;
+        x3 = tmp;
+    }
+    if (x4 < x2)
+    {
+        tmp = x2;
+        x2 = x4;
+        x4 = tmp;
+    }
+    if (x5 < x2)
+    {
+        x5 = x2;
+    }
+    if (x4 < x3)
+    {
+        x3 = x4;
+    }
+    if (x5 < x3)
+    {
+        x3 = x5;
+    }
+    return (x3);
 }
 
 
 Word16 Med_olag(                           /* output : median of  5 previous open-loop lags       */
-		Word16 prev_ol_lag,                /* input  : previous open-loop lag                     */
-		Word16 old_ol_lag[5]
-	       )
+        Word16 prev_ol_lag,                /* input  : previous open-loop lag                     */
+        Word16 old_ol_lag[5]
+           )
 {
-	Word32 i;
+    Word32 i;
 
-	/* Use median of 5 previous open-loop lags as old lag */
+    /* Use median of 5 previous open-loop lags as old lag */
 
-	for (i = 4; i > 0; i--)
-	{
-		old_ol_lag[i] = old_ol_lag[i - 1];
-	}
+    for (i = 4; i > 0; i--)
+    {
+        old_ol_lag[i] = old_ol_lag[i - 1];
+    }
 
-	old_ol_lag[0] = prev_ol_lag;
+    old_ol_lag[0] = prev_ol_lag;
 
-	i = median5(&old_ol_lag[2]);
+    i = median5(&old_ol_lag[2]);
 
-	return i;
+    return i;
 
 }
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/pit_shrp.c b/media/libstagefright/codecs/amrwbenc/src/pit_shrp.c
index 6f55b8f..f100253 100644
--- a/media/libstagefright/codecs/amrwbenc/src/pit_shrp.c
+++ b/media/libstagefright/codecs/amrwbenc/src/pit_shrp.c
@@ -25,24 +25,24 @@
 #include "basic_op.h"
 
 void Pit_shrp(
-		Word16 * x,                           /* in/out: impulse response (or algebraic code) */
-		Word16 pit_lag,                       /* input : pitch lag                            */
-		Word16 sharp,                         /* input : pitch sharpening factor (Q15)        */
-		Word16 L_subfr                        /* input : subframe size                        */
-	     )
+        Word16 * x,                           /* in/out: impulse response (or algebraic code) */
+        Word16 pit_lag,                       /* input : pitch lag                            */
+        Word16 sharp,                         /* input : pitch sharpening factor (Q15)        */
+        Word16 L_subfr                        /* input : subframe size                        */
+         )
 {
-	Word32 i;
-	Word32 L_tmp;
-	Word16 *x_ptr = x + pit_lag;
+    Word32 i;
+    Word32 L_tmp;
+    Word16 *x_ptr = x + pit_lag;
 
-	for (i = pit_lag; i < L_subfr; i++)
-	{
-		L_tmp = (*x_ptr << 15);
-		L_tmp += *x++ * sharp;
-		*x_ptr++ = ((L_tmp + 0x4000)>>15);
-	}
+    for (i = pit_lag; i < L_subfr; i++)
+    {
+        L_tmp = (*x_ptr << 15);
+        L_tmp += *x++ * sharp;
+        *x_ptr++ = ((L_tmp + 0x4000)>>15);
+    }
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c b/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
index b66b55e..b453b25 100644
--- a/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
+++ b/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
@@ -18,7 +18,7 @@
 *      File: pitch_f4.c                                                *
 *                                                                      *
 *      Description: Find the closed loop pitch period with             *
-*	            1/4 subsample resolution.                          *
+*               1/4 subsample resolution.                          *
 *                                                                      *
 ************************************************************************/
 
@@ -37,117 +37,117 @@
 
 #ifdef ASM_OPT
 void Norm_corr_asm(
-		Word16 exc[],                         /* (i)     : excitation buffer                     */
-		Word16 xn[],                          /* (i)     : target vector                         */
-		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
-		Word16 L_subfr,
-		Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */
-		Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */
-		Word16 corr_norm[]                    /* (o) Q15 : normalized correlation                */
-		);
+        Word16 exc[],                         /* (i)     : excitation buffer                     */
+        Word16 xn[],                          /* (i)     : target vector                         */
+        Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
+        Word16 L_subfr,
+        Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */
+        Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */
+        Word16 corr_norm[]                    /* (o) Q15 : normalized correlation                */
+        );
 #else
 static void Norm_Corr(
-		Word16 exc[],                         /* (i)     : excitation buffer                     */
-		Word16 xn[],                          /* (i)     : target vector                         */
-		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
-		Word16 L_subfr,
-		Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */
-		Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */
-		Word16 corr_norm[]                    /* (o) Q15 : normalized correlation                */
-		);
+        Word16 exc[],                         /* (i)     : excitation buffer                     */
+        Word16 xn[],                          /* (i)     : target vector                         */
+        Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
+        Word16 L_subfr,
+        Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */
+        Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */
+        Word16 corr_norm[]                    /* (o) Q15 : normalized correlation                */
+        );
 #endif
 
 static Word16 Interpol_4(                  /* (o)  : interpolated value  */
-		Word16 * x,                           /* (i)  : input vector        */
-		Word32 frac                           /* (i)  : fraction (-4..+3)   */
-		);
+        Word16 * x,                           /* (i)  : input vector        */
+        Word32 frac                           /* (i)  : fraction (-4..+3)   */
+        );
 
 
 Word16 Pitch_fr4(                          /* (o)     : pitch period.                         */
-		Word16 exc[],                         /* (i)     : excitation buffer                     */
-		Word16 xn[],                          /* (i)     : target vector                         */
-		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
-		Word16 t0_min,                        /* (i)     : minimum value in the searched range.  */
-		Word16 t0_max,                        /* (i)     : maximum value in the searched range.  */
-		Word16 * pit_frac,                    /* (o)     : chosen fraction (0, 1, 2 or 3).       */
-		Word16 i_subfr,                       /* (i)     : indicator for first subframe.         */
-		Word16 t0_fr2,                        /* (i)     : minimum value for resolution 1/2      */
-		Word16 t0_fr1,                        /* (i)     : minimum value for resolution 1        */
-		Word16 L_subfr                        /* (i)     : Length of subframe                    */
-		)
+        Word16 exc[],                         /* (i)     : excitation buffer                     */
+        Word16 xn[],                          /* (i)     : target vector                         */
+        Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
+        Word16 t0_min,                        /* (i)     : minimum value in the searched range.  */
+        Word16 t0_max,                        /* (i)     : maximum value in the searched range.  */
+        Word16 * pit_frac,                    /* (o)     : chosen fraction (0, 1, 2 or 3).       */
+        Word16 i_subfr,                       /* (i)     : indicator for first subframe.         */
+        Word16 t0_fr2,                        /* (i)     : minimum value for resolution 1/2      */
+        Word16 t0_fr1,                        /* (i)     : minimum value for resolution 1        */
+        Word16 L_subfr                        /* (i)     : Length of subframe                    */
+        )
 {
-	Word32 fraction, i;
-	Word16 t_min, t_max;
-	Word16 max, t0, step, temp;
-	Word16 *corr;
-	Word16 corr_v[40];                     /* Total length = t0_max-t0_min+1+2*L_inter */
+    Word32 fraction, i;
+    Word16 t_min, t_max;
+    Word16 max, t0, step, temp;
+    Word16 *corr;
+    Word16 corr_v[40];                     /* Total length = t0_max-t0_min+1+2*L_inter */
 
-	/* Find interval to compute normalized correlation */
+    /* Find interval to compute normalized correlation */
 
-	t_min = t0_min - L_INTERPOL1;
-	t_max = t0_max + L_INTERPOL1;
-	corr = &corr_v[-t_min];
-	/* Compute normalized correlation between target and filtered excitation */
+    t_min = L_sub(t0_min, L_INTERPOL1);
+    t_max = L_add(t0_max, L_INTERPOL1);
+    corr = &corr_v[-t_min];
+    /* Compute normalized correlation between target and filtered excitation */
 #ifdef ASM_OPT               /* asm optimization branch */
     Norm_corr_asm(exc, xn, h, L_subfr, t_min, t_max, corr);
 #else
-	Norm_Corr(exc, xn, h, L_subfr, t_min, t_max, corr);
+    Norm_Corr(exc, xn, h, L_subfr, t_min, t_max, corr);
 #endif
 
-	/* Find integer pitch */
+    /* Find integer pitch */
 
-	max = corr[t0_min];
-	t0 = t0_min;
-	for (i = t0_min + 1; i <= t0_max; i++)
-	{
-		if (corr[i] >= max)
-		{
-			max = corr[i];
-			t0 = i;
-		}
-	}
-	/* If first subframe and t0 >= t0_fr1, do not search fractionnal pitch */
-	if ((i_subfr == 0) && (t0 >= t0_fr1))
-	{
-		*pit_frac = 0;
-		return (t0);
-	}
-	/*------------------------------------------------------------------*
-	 * Search fractionnal pitch with 1/4 subsample resolution.          *
-	 * Test the fractions around t0 and choose the one which maximizes  *
-	 * the interpolated normalized correlation.                         *
-	 *------------------------------------------------------------------*/
+    max = corr[t0_min];
+    t0 = t0_min;
+    for (i = t0_min + 1; i <= t0_max; i++)
+    {
+        if (corr[i] >= max)
+        {
+            max = corr[i];
+            t0 = i;
+        }
+    }
+    /* If first subframe and t0 >= t0_fr1, do not search fractionnal pitch */
+    if ((i_subfr == 0) && (t0 >= t0_fr1))
+    {
+        *pit_frac = 0;
+        return (t0);
+    }
+    /*------------------------------------------------------------------*
+     * Search fractionnal pitch with 1/4 subsample resolution.          *
+     * Test the fractions around t0 and choose the one which maximizes  *
+     * the interpolated normalized correlation.                         *
+     *------------------------------------------------------------------*/
 
-	step = 1;               /* 1/4 subsample resolution */
-	fraction = -3;
-	if ((t0_fr2 == PIT_MIN)||((i_subfr == 0) && (t0 >= t0_fr2)))
-	{
-		step = 2;              /* 1/2 subsample resolution */
-		fraction = -2;
-	}
-	if(t0 == t0_min)
-	{
-		fraction = 0;
-	}
-	max = Interpol_4(&corr[t0], fraction);
+    step = 1;               /* 1/4 subsample resolution */
+    fraction = -3;
+    if ((t0_fr2 == PIT_MIN)||((i_subfr == 0) && (t0 >= t0_fr2)))
+    {
+        step = 2;              /* 1/2 subsample resolution */
+        fraction = -2;
+    }
+    if(t0 == t0_min)
+    {
+        fraction = 0;
+    }
+    max = Interpol_4(&corr[t0], fraction);
 
-	for (i = fraction + step; i <= 3; i += step)
-	{
-		temp = Interpol_4(&corr[t0], i);
-		if(temp > max)
-		{
-			max = temp;
-			fraction = i;
-		}
-	}
-	/* limit the fraction value in the interval [0,1,2,3] */
-	if (fraction < 0)
-	{
-		fraction += UP_SAMP;
-		t0 -= 1;
-	}
-	*pit_frac = fraction;
-	return (t0);
+    for (i = fraction + step; i <= 3; i += step)
+    {
+        temp = Interpol_4(&corr[t0], i);
+        if(temp > max)
+        {
+            max = temp;
+            fraction = i;
+        }
+    }
+    /* limit the fraction value in the interval [0,1,2,3] */
+    if (fraction < 0)
+    {
+        fraction += UP_SAMP;
+        t0 -= 1;
+    }
+    *pit_frac = fraction;
+    return (t0);
 }
 
 
@@ -161,109 +161,109 @@
 ************************************************************************************/
 #ifndef ASM_OPT
 static void Norm_Corr(
-		Word16 exc[],                         /* (i)     : excitation buffer                     */
-		Word16 xn[],                          /* (i)     : target vector                         */
-		Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
-		Word16 L_subfr,
-		Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */
-		Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */
-		Word16 corr_norm[])                   /* (o) Q15 : normalized correlation                */
+        Word16 exc[],                         /* (i)     : excitation buffer                     */
+        Word16 xn[],                          /* (i)     : target vector                         */
+        Word16 h[],                           /* (i) Q15 : impulse response of synth/wgt filters */
+        Word16 L_subfr,
+        Word16 t_min,                         /* (i)     : minimum value of pitch lag.           */
+        Word16 t_max,                         /* (i)     : maximum value of pitch lag.           */
+        Word16 corr_norm[])                   /* (o) Q15 : normalized correlation                */
 {
-	Word32 i, k, t;
-	Word32 corr, exp_corr, norm, exp, scale;
-	Word16 exp_norm, excf[L_SUBFR], tmp;
-	Word32 L_tmp, L_tmp1, L_tmp2;
+    Word32 i, k, t;
+    Word32 corr, exp_corr, norm, exp, scale;
+    Word16 exp_norm, excf[L_SUBFR], tmp;
+    Word32 L_tmp, L_tmp1, L_tmp2;
         UNUSED(L_subfr);
 
-	/* compute the filtered excitation for the first delay t_min */
-	k = -t_min;
+    /* compute the filtered excitation for the first delay t_min */
+    k = -t_min;
 
 #ifdef ASM_OPT              /* asm optimization branch */
-	Convolve_asm(&exc[k], h, excf, 64);
+    Convolve_asm(&exc[k], h, excf, 64);
 #else
-	Convolve(&exc[k], h, excf, 64);
+    Convolve(&exc[k], h, excf, 64);
 #endif
 
-	/* Compute rounded down 1/sqrt(energy of xn[]) */
-	L_tmp = 0;
-	for (i = 0; i < 64; i+=4)
-	{
-		L_tmp += (xn[i] * xn[i]);
-		L_tmp += (xn[i+1] * xn[i+1]);
-		L_tmp += (xn[i+2] * xn[i+2]);
-		L_tmp += (xn[i+3] * xn[i+3]);
-	}
+    /* Compute rounded down 1/sqrt(energy of xn[]) */
+    L_tmp = 0;
+    for (i = 0; i < 64; i+=4)
+    {
+        L_tmp = L_add(L_tmp, (xn[i] * xn[i]));
+        L_tmp = L_add(L_tmp, (xn[i+1] * xn[i+1]));
+        L_tmp = L_add(L_tmp, (xn[i+2] * xn[i+2]));
+        L_tmp = L_add(L_tmp, (xn[i+3] * xn[i+3]));
+    }
 
-	L_tmp = (L_tmp << 1) + 1;
-	exp = norm_l(L_tmp);
-	exp = (32 - exp);
-	//exp = exp + 2;                     /* energy of xn[] x 2 + rounded up     */
-	scale = -(exp >> 1);           /* (1<<scale) < 1/sqrt(energy rounded) */
+    L_tmp = L_add(L_shl(L_tmp, 1), 1);
+    exp = norm_l(L_tmp);
+    exp = L_sub(32, exp);
+    //exp = exp + 2;                     /* energy of xn[] x 2 + rounded up     */
+    scale = -(exp >> 1);           /* (1<<scale) < 1/sqrt(energy rounded) */
 
-	/* loop for every possible period */
+    /* loop for every possible period */
 
-	for (t = t_min; t <= t_max; t++)
-	{
-		/* Compute correlation between xn[] and excf[] */
-		L_tmp  = 0;
-		L_tmp1 = 0;
-		for (i = 0; i < 64; i+=4)
-		{
-			L_tmp  += (xn[i] * excf[i]);
-			L_tmp1 += (excf[i] * excf[i]);
-			L_tmp  += (xn[i+1] * excf[i+1]);
-			L_tmp1 += (excf[i+1] * excf[i+1]);
-			L_tmp  += (xn[i+2] * excf[i+2]);
-			L_tmp1 += (excf[i+2] * excf[i+2]);
-			L_tmp  += (xn[i+3] * excf[i+3]);
-			L_tmp1 += (excf[i+3] * excf[i+3]);
-		}
+    for (t = t_min; t <= t_max; t++)
+    {
+        /* Compute correlation between xn[] and excf[] */
+        L_tmp  = 0;
+        L_tmp1 = 0;
+        for (i = 0; i < 64; i+=4)
+        {
+            L_tmp = L_add(L_tmp, (xn[i] * excf[i]));
+            L_tmp1 = L_add(L_tmp1, (excf[i] * excf[i]));
+            L_tmp = L_add(L_tmp, (xn[i+1] * excf[i+1]));
+            L_tmp1 = L_add(L_tmp1, (excf[i+1] * excf[i+1]));
+            L_tmp = L_add(L_tmp, (xn[i+2] * excf[i+2]));
+            L_tmp1 = L_add(L_tmp1, (excf[i+2] * excf[i+2]));
+            L_tmp = L_add(L_tmp, (xn[i+3] * excf[i+3]));
+            L_tmp1 = L_add(L_tmp1, (excf[i+3] * excf[i+3]));
+        }
 
-		L_tmp = (L_tmp << 1) + 1;
-		L_tmp1 = (L_tmp1 << 1) + 1;
+        L_tmp = L_add(L_shl(L_tmp, 1), 1);
+        L_tmp1 = L_add(L_shl(L_tmp1, 1), 1);
 
-		exp = norm_l(L_tmp);
-		L_tmp = (L_tmp << exp);
-		exp_corr = (30 - exp);
-		corr = extract_h(L_tmp);
+        exp = norm_l(L_tmp);
+        L_tmp = L_shl(L_tmp, exp);
+        exp_corr = L_sub(30, exp);
+        corr = extract_h(L_tmp);
 
-		exp = norm_l(L_tmp1);
-		L_tmp = (L_tmp1 << exp);
-		exp_norm = (30 - exp);
+        exp = norm_l(L_tmp1);
+        L_tmp = L_shl(L_tmp1, exp);
+        exp_norm = L_sub(30, exp);
 
-		Isqrt_n(&L_tmp, &exp_norm);
-		norm = extract_h(L_tmp);
+        Isqrt_n(&L_tmp, &exp_norm);
+        norm = extract_h(L_tmp);
 
-		/* Normalize correlation = correlation * (1/sqrt(energy)) */
+        /* Normalize correlation = correlation * (1/sqrt(energy)) */
 
-		L_tmp = vo_L_mult(corr, norm);
+        L_tmp = L_mult(corr, norm);
 
-		L_tmp2 = exp_corr + exp_norm + scale;
-		if(L_tmp2 < 0)
-		{
-			L_tmp2 = -L_tmp2;
-			L_tmp = L_tmp >> L_tmp2;
-		}
-		else
-		{
-			L_tmp = L_tmp << L_tmp2;
-		}
+        L_tmp2 = L_add(exp_corr, exp_norm + scale);
+        if(L_tmp2 < 0)
+        {
+            L_tmp2 = -L_tmp2;
+            L_tmp = L_tmp >> L_tmp2;
+        }
+        else
+        {
+            L_tmp = L_shl(L_tmp, L_tmp2);
+        }
 
-		corr_norm[t] = vo_round(L_tmp);
-		/* modify the filtered excitation excf[] for the next iteration */
+        corr_norm[t] = voround(L_tmp);
+        /* modify the filtered excitation excf[] for the next iteration */
 
-		if(t != t_max)
-		{
-			k = -(t + 1);
-			tmp = exc[k];
-			for (i = 63; i > 0; i--)
-			{
-				excf[i] = add1(vo_mult(tmp, h[i]), excf[i - 1]);
-			}
-			excf[0] = vo_mult(tmp, h[0]);
-		}
-	}
-	return;
+        if(t != t_max)
+        {
+            k = -(t + 1);
+            tmp = exc[k];
+            for (i = 63; i > 0; i--)
+            {
+                excf[i] = add1(vo_mult(tmp, h[i]), excf[i - 1]);
+            }
+            excf[0] = vo_mult(tmp, h[0]);
+        }
+    }
+    return;
 }
 
 #endif
@@ -276,10 +276,10 @@
 /* 1/4 resolution interpolation filter (-3 dB at 0.791*fs/2) in Q14 */
 static Word16 inter4_1[4][8] =
 {
-	{-12, 420, -1732, 5429, 13418, -1242, 73, 32},
-	{-26, 455, -2142, 9910, 9910,  -2142, 455, -26},
-	{32,  73, -1242, 13418, 5429, -1732, 420, -12},
-	{206, -766, 1376, 14746, 1376, -766, 206, 0}
+    {-12, 420, -1732, 5429, 13418, -1242, 73, 32},
+    {-26, 455, -2142, 9910, 9910,  -2142, 455, -26},
+    {32,  73, -1242, 13418, 5429, -1732, 420, -12},
+    {206, -766, 1376, 14746, 1376, -766, 206, 0}
 };
 
 /*** Coefficients in floating point
@@ -292,34 +292,34 @@
 ***/
 
 static Word16 Interpol_4(                  /* (o)  : interpolated value  */
-		Word16 * x,                           /* (i)  : input vector        */
-		Word32 frac                           /* (i)  : fraction (-4..+3)   */
-		)
+        Word16 * x,                           /* (i)  : input vector        */
+        Word32 frac                           /* (i)  : fraction (-4..+3)   */
+        )
 {
-	Word16 sum;
-	Word32  k, L_sum;
-	Word16 *ptr;
+    Word16 sum;
+    Word32  k, L_sum;
+    Word16 *ptr;
 
-	if (frac < 0)
-	{
-		frac += UP_SAMP;
-		x--;
-	}
-	x = x - L_INTERPOL1 + 1;
-	k = UP_SAMP - 1 - frac;
-	ptr = &(inter4_1[k][0]);
+    if (frac < 0)
+    {
+        frac += UP_SAMP;
+        x--;
+    }
+    x = x - L_INTERPOL1 + 1;
+    k = UP_SAMP - 1 - frac;
+    ptr = &(inter4_1[k][0]);
 
-	L_sum  = vo_mult32(x[0], (*ptr++));
-	L_sum += vo_mult32(x[1], (*ptr++));
-	L_sum += vo_mult32(x[2], (*ptr++));
-	L_sum += vo_mult32(x[3], (*ptr++));
-	L_sum += vo_mult32(x[4], (*ptr++));
-	L_sum += vo_mult32(x[5], (*ptr++));
-	L_sum += vo_mult32(x[6], (*ptr++));
-	L_sum += vo_mult32(x[7], (*ptr++));
+    L_sum  = vo_mult32(x[0], (*ptr++));
+    L_sum = L_add(L_sum, vo_mult32(x[1], (*ptr++)));
+    L_sum = L_add(L_sum, vo_mult32(x[2], (*ptr++)));
+    L_sum = L_add(L_sum, vo_mult32(x[3], (*ptr++)));
+    L_sum = L_add(L_sum, vo_mult32(x[4], (*ptr++)));
+    L_sum = L_add(L_sum, vo_mult32(x[5], (*ptr++)));
+    L_sum = L_add(L_sum, vo_mult32(x[6], (*ptr++)));
+    L_sum = L_add(L_sum, vo_mult32(x[7], (*ptr++)));
 
-	sum = extract_h(L_add(L_shl2(L_sum, 2), 0x8000));
-	return (sum);
+    sum = extract_h(L_add(L_shl2(L_sum, 2), 0x8000));
+    return (sum);
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/pred_lt4.c b/media/libstagefright/codecs/amrwbenc/src/pred_lt4.c
index 8404cf9..386cab3 100644
--- a/media/libstagefright/codecs/amrwbenc/src/pred_lt4.c
+++ b/media/libstagefright/codecs/amrwbenc/src/pred_lt4.c
@@ -34,86 +34,86 @@
 
 Word16 inter4_2[4][32] =
 {
-	{0,-2,4,-2,-10,38,-88,165,-275,424,-619,871,-1207,1699,-2598,5531,14031,-2147,780,-249,
-	-16,153,-213,226,-209,175,-133,91,-55,28,-10,2},
+    {0,-2,4,-2,-10,38,-88,165,-275,424,-619,871,-1207,1699,-2598,5531,14031,-2147,780,-249,
+    -16,153,-213,226,-209,175,-133,91,-55,28,-10,2},
 
-	{1,-7,19,-33,47,-52,43,-9,-60,175,-355,626,-1044,1749,-3267,10359,10359,-3267,1749,-1044,
-	626,-355,175,-60,-9,43,-52,47,-33,19, -7, 1},
+    {1,-7,19,-33,47,-52,43,-9,-60,175,-355,626,-1044,1749,-3267,10359,10359,-3267,1749,-1044,
+    626,-355,175,-60,-9,43,-52,47,-33,19, -7, 1},
 
-	{2,-10,28,-55,91,-133,175,-209,226,-213,153,-16,-249,780,-2147,14031,5531,-2598,1699,-1207,
-	871,-619,424,-275,165,-88,38,-10,-2,4,-2,0},
+    {2,-10,28,-55,91,-133,175,-209,226,-213,153,-16,-249,780,-2147,14031,5531,-2598,1699,-1207,
+    871,-619,424,-275,165,-88,38,-10,-2,4,-2,0},
 
-	{1,-7,22,-49,92,-153,231,-325,431,-544,656,-762,853,-923,968,15401,968,-923,853,-762,
-	656,-544,431,-325,231,-153,92,-49,22,-7, 1, 0}
+    {1,-7,22,-49,92,-153,231,-325,431,-544,656,-762,853,-923,968,15401,968,-923,853,-762,
+    656,-544,431,-325,231,-153,92,-49,22,-7, 1, 0}
 
 };
 
 void Pred_lt4(
-		Word16 exc[],                         /* in/out: excitation buffer */
-		Word16 T0,                            /* input : integer pitch lag */
-		Word16 frac,                          /* input : fraction of lag   */
-		Word16 L_subfr                        /* input : subframe size     */
-	     )
+        Word16 exc[],                         /* in/out: excitation buffer */
+        Word16 T0,                            /* input : integer pitch lag */
+        Word16 frac,                          /* input : fraction of lag   */
+        Word16 L_subfr                        /* input : subframe size     */
+         )
 {
-	Word16 j, k, *x;
-	Word32 L_sum;
-	Word16 *ptr, *ptr1;
-	Word16 *ptr2;
+    Word16 j, k, *x;
+    Word32 L_sum;
+    Word16 *ptr, *ptr1;
+    Word16 *ptr2;
 
-	x = exc - T0;
-	frac = -frac;
-	if (frac < 0)
-	{
-		frac += UP_SAMP;
-		x--;
-	}
-	x -= 15;                                     /* x = L_INTERPOL2 - 1 */
-	k = 3 - frac;                                /* k = UP_SAMP - 1 - frac */
+    x = exc - T0;
+    frac = -frac;
+    if (frac < 0)
+    {
+        frac += UP_SAMP;
+        x--;
+    }
+    x -= 15;                                     /* x = L_INTERPOL2 - 1 */
+    k = 3 - frac;                                /* k = UP_SAMP - 1 - frac */
 
-	ptr2 = &(inter4_2[k][0]);
-	for (j = 0; j < L_subfr; j++)
-	{
-		ptr = ptr2;
-		ptr1 = x;
-		L_sum  = vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
-		L_sum += vo_mult32((*ptr1++), (*ptr++));
+    ptr2 = &(inter4_2[k][0]);
+    for (j = 0; j < L_subfr; j++)
+    {
+        ptr = ptr2;
+        ptr1 = x;
+        L_sum  = vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
+        L_sum += vo_mult32((*ptr1++), (*ptr++));
 
-		L_sum = L_shl2(L_sum, 2);
-		exc[j] = extract_h(L_add(L_sum, 0x8000));
-		x++;
-	}
+        L_sum = L_shl2(L_sum, 2);
+        exc[j] = extract_h(L_add(L_sum, 0x8000));
+        x++;
+    }
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/preemph.c b/media/libstagefright/codecs/amrwbenc/src/preemph.c
index c867bf7..70c8650 100644
--- a/media/libstagefright/codecs/amrwbenc/src/preemph.c
+++ b/media/libstagefright/codecs/amrwbenc/src/preemph.c
@@ -18,7 +18,7 @@
 *      File: preemph.c                                                *
 *                                                                     *
 *      Description: Preemphasis: filtering through 1 - g z^-1         *
-*	           Preemph2 --> signal is multiplied by 2             *
+*              Preemph2 --> signal is multiplied by 2             *
 *                                                                     *
 ************************************************************************/
 
@@ -26,62 +26,74 @@
 #include "basic_op.h"
 
 void Preemph(
-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
-		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
-		Word16 lg,                            /* (i)     : lenght of filtering                    */
-		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
-	    )
+        Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+        Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
+        Word16 lg,                            /* (i)     : lenght of filtering                    */
+        Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
+        )
 {
-	Word16 temp;
-	Word32 i, L_tmp;
+    Word16 temp;
+    Word32 i, L_tmp;
 
-	temp = x[lg - 1];
+    temp = x[lg - 1];
 
-	for (i = lg - 1; i > 0; i--)
-	{
-		L_tmp = L_deposit_h(x[i]);
-		L_tmp -= (x[i - 1] * mu)<<1;
-		x[i] = (L_tmp + 0x8000)>>16;
-	}
+    for (i = lg - 1; i > 0; i--)
+    {
+        L_tmp = L_deposit_h(x[i]);
+        L_tmp -= (x[i - 1] * mu)<<1;
+        x[i] = (L_tmp + 0x8000)>>16;
+    }
 
-	L_tmp = L_deposit_h(x[0]);
-	L_tmp -= ((*mem) * mu)<<1;
-	x[0] = (L_tmp + 0x8000)>>16;
+    L_tmp = L_deposit_h(x[0]);
+    L_tmp -= ((*mem) * mu)<<1;
+    x[0] = (L_tmp + 0x8000)>>16;
 
-	*mem = temp;
+    *mem = temp;
 
-	return;
+    return;
 }
 
 
 void Preemph2(
-		Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
-		Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
-		Word16 lg,                            /* (i)     : lenght of filtering                    */
-		Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
-	     )
+        Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
+        Word16 mu,                            /* (i) Q15 : preemphasis coefficient                */
+        Word16 lg,                            /* (i)     : lenght of filtering                    */
+        Word16 * mem                          /* (i/o)   : memory (x[-1])                         */
+         )
 {
-	Word16 temp;
-	Word32 i, L_tmp;
+    Word16 temp;
+    Word32 i, L_tmp;
 
-	temp = x[lg - 1];
+    temp = x[lg - 1];
 
-	for (i = (Word16) (lg - 1); i > 0; i--)
-	{
-		L_tmp = L_deposit_h(x[i]);
-		L_tmp -= (x[i - 1] * mu)<<1;
-		L_tmp = (L_tmp << 1);
-		x[i] = (L_tmp + 0x8000)>>16;
-	}
+    for (i = (Word16) (lg - 1); i > 0; i--)
+    {
+        L_tmp = L_deposit_h(x[i]);
+        L_tmp -= (x[i - 1] * mu)<<1; // only called with mu == 22282, so this won't overflow
+        if (L_tmp > INT32_MAX / 2) {
+            L_tmp = INT32_MAX / 2;
+        }
+        L_tmp = (L_tmp << 1);
+        if (L_tmp > INT32_MAX - 0x8000) {
+            L_tmp = INT32_MAX - 0x8000;
+        }
+        x[i] = (L_tmp + 0x8000)>>16;
+    }
 
-	L_tmp = L_deposit_h(x[0]);
-	L_tmp -= ((*mem) * mu)<<1;
-	L_tmp = (L_tmp << 1);
-	x[0] = (L_tmp + 0x8000)>>16;
+    L_tmp = L_deposit_h(x[0]);
+    L_tmp -= ((*mem) * mu)<<1;
+    if (L_tmp > INT32_MAX / 2) {
+        L_tmp = INT32_MAX / 2;
+    }
+    L_tmp = (L_tmp << 1);
+    if (L_tmp > INT32_MAX - 0x8000) {
+        L_tmp = INT32_MAX - 0x8000;
+    }
+    x[0] = (L_tmp + 0x8000)>>16;
 
-	*mem = temp;
+    *mem = temp;
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/q_gain2.c b/media/libstagefright/codecs/amrwbenc/src/q_gain2.c
index e8ca043..bb797d8 100644
--- a/media/libstagefright/codecs/amrwbenc/src/q_gain2.c
+++ b/media/libstagefright/codecs/amrwbenc/src/q_gain2.c
@@ -45,300 +45,300 @@
 
 
 void Init_Q_gain2(
-		Word16 * mem                          /* output  :static memory (2 words)      */
-		)
+        Word16 * mem                          /* output  :static memory (2 words)      */
+        )
 {
-	Word32 i;
+    Word32 i;
 
-	/* 4nd order quantizer energy predictor (init to -14.0 in Q10) */
-	for (i = 0; i < PRED_ORDER; i++)
-	{
-		mem[i] = -14336;                     /* past_qua_en[i] */
-	}
+    /* 4nd order quantizer energy predictor (init to -14.0 in Q10) */
+    for (i = 0; i < PRED_ORDER; i++)
+    {
+        mem[i] = -14336;                     /* past_qua_en[i] */
+    }
 
-	return;
+    return;
 }
 
 Word16 Q_gain2(                            /* Return index of quantization.          */
-		Word16 xn[],                          /* (i) Q_xn: Target vector.               */
-		Word16 y1[],                          /* (i) Q_xn: Adaptive codebook.           */
-		Word16 Q_xn,                          /* (i)     : xn and y1 format             */
-		Word16 y2[],                          /* (i) Q9  : Filtered innovative vector.  */
-		Word16 code[],                        /* (i) Q9  : Innovative vector.           */
-		Word16 g_coeff[],                     /* (i)     : Correlations <xn y1> <y1 y1> */
-		/*           Compute in G_pitch().        */
-		Word16 L_subfr,                       /* (i)     : Subframe lenght.             */
-		Word16 nbits,                         /* (i)     : number of bits (6 or 7)      */
-		Word16 * gain_pit,                    /* (i/o)Q14: Pitch gain.                  */
-		Word32 * gain_cod,                    /* (o) Q16 : Code gain.                   */
-		Word16 gp_clip,                       /* (i)     : Gp Clipping flag             */
-		Word16 * mem                          /* (i/o)   : static memory (2 words)      */
-	      )
+        Word16 xn[],                          /* (i) Q_xn: Target vector.               */
+        Word16 y1[],                          /* (i) Q_xn: Adaptive codebook.           */
+        Word16 Q_xn,                          /* (i)     : xn and y1 format             */
+        Word16 y2[],                          /* (i) Q9  : Filtered innovative vector.  */
+        Word16 code[],                        /* (i) Q9  : Innovative vector.           */
+        Word16 g_coeff[],                     /* (i)     : Correlations <xn y1> <y1 y1> */
+        /*           Compute in G_pitch().        */
+        Word16 L_subfr,                       /* (i)     : Subframe lenght.             */
+        Word16 nbits,                         /* (i)     : number of bits (6 or 7)      */
+        Word16 * gain_pit,                    /* (i/o)Q14: Pitch gain.                  */
+        Word32 * gain_cod,                    /* (o) Q16 : Code gain.                   */
+        Word16 gp_clip,                       /* (i)     : Gp Clipping flag             */
+        Word16 * mem                          /* (i/o)   : static memory (2 words)      */
+          )
 {
-	Word16 index, *p, min_ind, size;
-	Word16 exp, frac, gcode0, exp_gcode0, e_max, exp_code, qua_ener;
-	Word16 g_pitch, g2_pitch, g_code, g_pit_cod, g2_code, g2_code_lo;
-	Word16 coeff[5], coeff_lo[5], exp_coeff[5];
-	Word16 exp_max[5];
-	Word32 i, j, L_tmp, dist_min;
-	Word16 *past_qua_en, *t_qua_gain;
+    Word16 index, *p, min_ind, size;
+    Word16 exp, frac, gcode0, exp_gcode0, e_max, exp_code, qua_ener;
+    Word16 g_pitch, g2_pitch, g_code, g_pit_cod, g2_code, g2_code_lo;
+    Word16 coeff[5], coeff_lo[5], exp_coeff[5];
+    Word16 exp_max[5];
+    Word32 i, j, L_tmp, dist_min;
+    Word16 *past_qua_en, *t_qua_gain;
 
-	past_qua_en = mem;
+    past_qua_en = mem;
 
-	/*-----------------------------------------------------------------*
-	 * - Find the initial quantization pitch index                     *
-	 * - Set gains search range                                        *
-	 *-----------------------------------------------------------------*/
-	if (nbits == 6)
-	{
-		t_qua_gain = t_qua_gain6b;
-		min_ind = 0;
-		size = RANGE;
+    /*-----------------------------------------------------------------*
+     * - Find the initial quantization pitch index                     *
+     * - Set gains search range                                        *
+     *-----------------------------------------------------------------*/
+    if (nbits == 6)
+    {
+        t_qua_gain = t_qua_gain6b;
+        min_ind = 0;
+        size = RANGE;
 
-		if(gp_clip == 1)
-		{
-			size = size - 16;          /* limit gain pitch to 1.0 */
-		}
-	} else
-	{
-		t_qua_gain = t_qua_gain7b;
+        if(gp_clip == 1)
+        {
+            size = size - 16;          /* limit gain pitch to 1.0 */
+        }
+    } else
+    {
+        t_qua_gain = t_qua_gain7b;
 
-		p = t_qua_gain7b + RANGE;            /* pt at 1/4th of table */
+        p = t_qua_gain7b + RANGE;            /* pt at 1/4th of table */
 
-		j = nb_qua_gain7b - RANGE;
+        j = nb_qua_gain7b - RANGE;
 
-		if (gp_clip == 1)
-		{
-			j = j - 27;                /* limit gain pitch to 1.0 */
-		}
-		min_ind = 0;
-		g_pitch = *gain_pit;
+        if (gp_clip == 1)
+        {
+            j = j - 27;                /* limit gain pitch to 1.0 */
+        }
+        min_ind = 0;
+        g_pitch = *gain_pit;
 
-		for (i = 0; i < j; i++, p += 2)
-		{
-			if (g_pitch > *p)
-			{
-				min_ind = min_ind + 1;
-			}
-		}
-		size = RANGE;
-	}
+        for (i = 0; i < j; i++, p += 2)
+        {
+            if (g_pitch > *p)
+            {
+                min_ind = min_ind + 1;
+            }
+        }
+        size = RANGE;
+    }
 
-	/*------------------------------------------------------------------*
-	 *  Compute coefficient need for the quantization.                  *
-	 *                                                                  *
-	 *  coeff[0] =    y1 y1                                             *
-	 *  coeff[1] = -2 xn y1                                             *
-	 *  coeff[2] =    y2 y2                                             *
-	 *  coeff[3] = -2 xn y2                                             *
-	 *  coeff[4] =  2 y1 y2                                             *
-	 *                                                                  *
-	 * Product <y1 y1> and <xn y1> have been compute in G_pitch() and   *
-	 * are in vector g_coeff[].                                         *
-	 *------------------------------------------------------------------*/
+    /*------------------------------------------------------------------*
+     *  Compute coefficient need for the quantization.                  *
+     *                                                                  *
+     *  coeff[0] =    y1 y1                                             *
+     *  coeff[1] = -2 xn y1                                             *
+     *  coeff[2] =    y2 y2                                             *
+     *  coeff[3] = -2 xn y2                                             *
+     *  coeff[4] =  2 y1 y2                                             *
+     *                                                                  *
+     * Product <y1 y1> and <xn y1> have been compute in G_pitch() and   *
+     * are in vector g_coeff[].                                         *
+     *------------------------------------------------------------------*/
 
-	coeff[0] = g_coeff[0];
-	exp_coeff[0] = g_coeff[1];
-	coeff[1] = negate(g_coeff[2]);                    /* coeff[1] = -2 xn y1 */
-	exp_coeff[1] = g_coeff[3] + 1;
+    coeff[0] = g_coeff[0];
+    exp_coeff[0] = g_coeff[1];
+    coeff[1] = negate(g_coeff[2]);                    /* coeff[1] = -2 xn y1 */
+    exp_coeff[1] = g_coeff[3] + 1;
 
-	/* Compute scalar product <y2[],y2[]> */
+    /* Compute scalar product <y2[],y2[]> */
 #ifdef ASM_OPT                   /* asm optimization branch */
-	coeff[2] = extract_h(Dot_product12_asm(y2, y2, L_subfr, &exp));
+    coeff[2] = extract_h(Dot_product12_asm(y2, y2, L_subfr, &exp));
 #else
-	coeff[2] = extract_h(Dot_product12(y2, y2, L_subfr, &exp));
+    coeff[2] = extract_h(Dot_product12(y2, y2, L_subfr, &exp));
 #endif
-	exp_coeff[2] = (exp - 18) + (Q_xn << 1);     /* -18 (y2 Q9) */
+    exp_coeff[2] = (exp - 18) + (Q_xn << 1);     /* -18 (y2 Q9) */
 
-	/* Compute scalar product -2*<xn[],y2[]> */
+    /* Compute scalar product -2*<xn[],y2[]> */
 #ifdef ASM_OPT                  /* asm optimization branch */
-	coeff[3] = extract_h(L_negate(Dot_product12_asm(xn, y2, L_subfr, &exp)));
+    coeff[3] = extract_h(L_negate(Dot_product12_asm(xn, y2, L_subfr, &exp)));
 #else
-	coeff[3] = extract_h(L_negate(Dot_product12(xn, y2, L_subfr, &exp)));
+    coeff[3] = extract_h(L_negate(Dot_product12(xn, y2, L_subfr, &exp)));
 #endif
 
-	exp_coeff[3] = (exp - 8) + Q_xn;  /* -9 (y2 Q9), +1 (2 xn y2) */
+    exp_coeff[3] = (exp - 8) + Q_xn;  /* -9 (y2 Q9), +1 (2 xn y2) */
 
-	/* Compute scalar product 2*<y1[],y2[]> */
+    /* Compute scalar product 2*<y1[],y2[]> */
 #ifdef ASM_OPT                 /* asm optimization branch */
-	coeff[4] = extract_h(Dot_product12_asm(y1, y2, L_subfr, &exp));
+    coeff[4] = extract_h(Dot_product12_asm(y1, y2, L_subfr, &exp));
 #else
-	coeff[4] = extract_h(Dot_product12(y1, y2, L_subfr, &exp));
+    coeff[4] = extract_h(Dot_product12(y1, y2, L_subfr, &exp));
 #endif
-	exp_coeff[4] = (exp - 8) + Q_xn;  /* -9 (y2 Q9), +1 (2 y1 y2) */
+    exp_coeff[4] = (exp - 8) + Q_xn;  /* -9 (y2 Q9), +1 (2 y1 y2) */
 
-	/*-----------------------------------------------------------------*
-	 *  Find energy of code and compute:                               *
-	 *                                                                 *
-	 *    L_tmp = MEAN_ENER - 10log10(energy of code/ L_subfr)         *
-	 *          = MEAN_ENER - 3.0103*log2(energy of code/ L_subfr)     *
-	 *-----------------------------------------------------------------*/
+    /*-----------------------------------------------------------------*
+     *  Find energy of code and compute:                               *
+     *                                                                 *
+     *    L_tmp = MEAN_ENER - 10log10(energy of code/ L_subfr)         *
+     *          = MEAN_ENER - 3.0103*log2(energy of code/ L_subfr)     *
+     *-----------------------------------------------------------------*/
 #ifdef ASM_OPT                 /* asm optimization branch */
-	L_tmp = Dot_product12_asm(code, code, L_subfr, &exp_code);
+    L_tmp = Dot_product12_asm(code, code, L_subfr, &exp_code);
 #else
-	L_tmp = Dot_product12(code, code, L_subfr, &exp_code);
+    L_tmp = Dot_product12(code, code, L_subfr, &exp_code);
 #endif
-	/* exp_code: -18 (code in Q9), -6 (/L_subfr), -31 (L_tmp Q31->Q0) */
-	exp_code = (exp_code - (18 + 6 + 31));
+    /* exp_code: -18 (code in Q9), -6 (/L_subfr), -31 (L_tmp Q31->Q0) */
+    exp_code = (exp_code - (18 + 6 + 31));
 
-	Log2(L_tmp, &exp, &frac);
-	exp += exp_code;
-	L_tmp = Mpy_32_16(exp, frac, -24660);  /* x -3.0103(Q13) -> Q14 */
+    Log2(L_tmp, &exp, &frac);
+    exp += exp_code;
+    L_tmp = Mpy_32_16(exp, frac, -24660);  /* x -3.0103(Q13) -> Q14 */
 
-	L_tmp += (MEAN_ENER * 8192)<<1; /* + MEAN_ENER in Q14 */
+    L_tmp += (MEAN_ENER * 8192)<<1; /* + MEAN_ENER in Q14 */
 
-	/*-----------------------------------------------------------------*
-	 * Compute gcode0.                                                 *
-	 *  = Sum(i=0,1) pred[i]*past_qua_en[i] + mean_ener - ener_code    *
-	 *-----------------------------------------------------------------*/
-	L_tmp = (L_tmp << 10);              /* From Q14 to Q24 */
-	L_tmp += (pred[0] * past_qua_en[0])<<1;      /* Q13*Q10 -> Q24 */
-	L_tmp += (pred[1] * past_qua_en[1])<<1;      /* Q13*Q10 -> Q24 */
-	L_tmp += (pred[2] * past_qua_en[2])<<1;      /* Q13*Q10 -> Q24 */
-	L_tmp += (pred[3] * past_qua_en[3])<<1;      /* Q13*Q10 -> Q24 */
+    /*-----------------------------------------------------------------*
+     * Compute gcode0.                                                 *
+     *  = Sum(i=0,1) pred[i]*past_qua_en[i] + mean_ener - ener_code    *
+     *-----------------------------------------------------------------*/
+    L_tmp = (L_tmp << 10);              /* From Q14 to Q24 */
+    L_tmp += (pred[0] * past_qua_en[0])<<1;      /* Q13*Q10 -> Q24 */
+    L_tmp += (pred[1] * past_qua_en[1])<<1;      /* Q13*Q10 -> Q24 */
+    L_tmp += (pred[2] * past_qua_en[2])<<1;      /* Q13*Q10 -> Q24 */
+    L_tmp += (pred[3] * past_qua_en[3])<<1;      /* Q13*Q10 -> Q24 */
 
-	gcode0 = extract_h(L_tmp);             /* From Q24 to Q8  */
+    gcode0 = extract_h(L_tmp);             /* From Q24 to Q8  */
 
-	/*-----------------------------------------------------------------*
-	 * gcode0 = pow(10.0, gcode0/20)                                   *
-	 *        = pow(2, 3.321928*gcode0/20)                             *
-	 *        = pow(2, 0.166096*gcode0)                                *
-	 *-----------------------------------------------------------------*/
+    /*-----------------------------------------------------------------*
+     * gcode0 = pow(10.0, gcode0/20)                                   *
+     *        = pow(2, 3.321928*gcode0/20)                             *
+     *        = pow(2, 0.166096*gcode0)                                *
+     *-----------------------------------------------------------------*/
 
-	L_tmp = vo_L_mult(gcode0, 5443);          /* *0.166096 in Q15 -> Q24     */
-	L_tmp = L_tmp >> 8;               /* From Q24 to Q16             */
-	VO_L_Extract(L_tmp, &exp_gcode0, &frac);  /* Extract exponent of gcode0  */
+    L_tmp = vo_L_mult(gcode0, 5443);          /* *0.166096 in Q15 -> Q24     */
+    L_tmp = L_tmp >> 8;               /* From Q24 to Q16             */
+    VO_L_Extract(L_tmp, &exp_gcode0, &frac);  /* Extract exponent of gcode0  */
 
-	gcode0 = (Word16)(Pow2(14, frac));    /* Put 14 as exponent so that  */
-	/* output of Pow2() will be:   */
-	/* 16384 < Pow2() <= 32767     */
-	exp_gcode0 -= 14;
+    gcode0 = (Word16)(Pow2(14, frac));    /* Put 14 as exponent so that  */
+    /* output of Pow2() will be:   */
+    /* 16384 < Pow2() <= 32767     */
+    exp_gcode0 -= 14;
 
-	/*-------------------------------------------------------------------------*
-	 * Find the best quantizer                                                 *
-	 * ~~~~~~~~~~~~~~~~~~~~~~~                                                 *
-	 * Before doing the computation we need to aling exponents of coeff[]      *
-	 * to be sure to have the maximum precision.                               *
-	 *                                                                         *
-	 * In the table the pitch gains are in Q14, the code gains are in Q11 and  *
-	 * are multiply by gcode0 which have been multiply by 2^exp_gcode0.        *
-	 * Also when we compute g_pitch*g_pitch, g_code*g_code and g_pitch*g_code  *
-	 * we divide by 2^15.                                                      *
-	 * Considering all the scaling above we have:                              *
-	 *                                                                         *
-	 *   exp_code = exp_gcode0-11+15 = exp_gcode0+4                            *
-	 *                                                                         *
-	 *   g_pitch*g_pitch  = -14-14+15                                          *
-	 *   g_pitch          = -14                                                *
-	 *   g_code*g_code    = (2*exp_code)+15                                    *
-	 *   g_code           = exp_code                                           *
-	 *   g_pitch*g_code   = -14 + exp_code +15                                 *
-	 *                                                                         *
-	 *   g_pitch*g_pitch * coeff[0]  ;exp_max0 = exp_coeff[0] - 13             *
-	 *   g_pitch         * coeff[1]  ;exp_max1 = exp_coeff[1] - 14             *
-	 *   g_code*g_code   * coeff[2]  ;exp_max2 = exp_coeff[2] +15+(2*exp_code) *
-	 *   g_code          * coeff[3]  ;exp_max3 = exp_coeff[3] + exp_code       *
-	 *   g_pitch*g_code  * coeff[4]  ;exp_max4 = exp_coeff[4] + 1 + exp_code   *
-	 *-------------------------------------------------------------------------*/
+    /*-------------------------------------------------------------------------*
+     * Find the best quantizer                                                 *
+     * ~~~~~~~~~~~~~~~~~~~~~~~                                                 *
+     * Before doing the computation we need to aling exponents of coeff[]      *
+     * to be sure to have the maximum precision.                               *
+     *                                                                         *
+     * In the table the pitch gains are in Q14, the code gains are in Q11 and  *
+     * are multiply by gcode0 which have been multiply by 2^exp_gcode0.        *
+     * Also when we compute g_pitch*g_pitch, g_code*g_code and g_pitch*g_code  *
+     * we divide by 2^15.                                                      *
+     * Considering all the scaling above we have:                              *
+     *                                                                         *
+     *   exp_code = exp_gcode0-11+15 = exp_gcode0+4                            *
+     *                                                                         *
+     *   g_pitch*g_pitch  = -14-14+15                                          *
+     *   g_pitch          = -14                                                *
+     *   g_code*g_code    = (2*exp_code)+15                                    *
+     *   g_code           = exp_code                                           *
+     *   g_pitch*g_code   = -14 + exp_code +15                                 *
+     *                                                                         *
+     *   g_pitch*g_pitch * coeff[0]  ;exp_max0 = exp_coeff[0] - 13             *
+     *   g_pitch         * coeff[1]  ;exp_max1 = exp_coeff[1] - 14             *
+     *   g_code*g_code   * coeff[2]  ;exp_max2 = exp_coeff[2] +15+(2*exp_code) *
+     *   g_code          * coeff[3]  ;exp_max3 = exp_coeff[3] + exp_code       *
+     *   g_pitch*g_code  * coeff[4]  ;exp_max4 = exp_coeff[4] + 1 + exp_code   *
+     *-------------------------------------------------------------------------*/
 
-	exp_code = (exp_gcode0 + 4);
-	exp_max[0] = (exp_coeff[0] - 13);
-	exp_max[1] = (exp_coeff[1] - 14);
-	exp_max[2] = (exp_coeff[2] + (15 + (exp_code << 1)));
-	exp_max[3] = (exp_coeff[3] + exp_code);
-	exp_max[4] = (exp_coeff[4] + (1 + exp_code));
+    exp_code = (exp_gcode0 + 4);
+    exp_max[0] = (exp_coeff[0] - 13);
+    exp_max[1] = (exp_coeff[1] - 14);
+    exp_max[2] = (exp_coeff[2] + (15 + (exp_code << 1)));
+    exp_max[3] = (exp_coeff[3] + exp_code);
+    exp_max[4] = (exp_coeff[4] + (1 + exp_code));
 
-	/* Find maximum exponant */
+    /* Find maximum exponant */
 
-	e_max = exp_max[0];
-	for (i = 1; i < 5; i++)
-	{
-		if(exp_max[i] > e_max)
-		{
-			e_max = exp_max[i];
-		}
-	}
+    e_max = exp_max[0];
+    for (i = 1; i < 5; i++)
+    {
+        if(exp_max[i] > e_max)
+        {
+            e_max = exp_max[i];
+        }
+    }
 
-	/* align coeff[] and save in special 32 bit double precision */
+    /* align coeff[] and save in special 32 bit double precision */
 
-	for (i = 0; i < 5; i++)
-	{
-		j = add1(vo_sub(e_max, exp_max[i]), 2);/* /4 to avoid overflow */
-		L_tmp = L_deposit_h(coeff[i]);
-		L_tmp = L_shr(L_tmp, j);
-		VO_L_Extract(L_tmp, &coeff[i], &coeff_lo[i]);
-		coeff_lo[i] = (coeff_lo[i] >> 3);   /* lo >> 3 */
-	}
+    for (i = 0; i < 5; i++)
+    {
+        j = add1(vo_sub(e_max, exp_max[i]), 2);/* /4 to avoid overflow */
+        L_tmp = L_deposit_h(coeff[i]);
+        L_tmp = L_shr(L_tmp, j);
+        VO_L_Extract(L_tmp, &coeff[i], &coeff_lo[i]);
+        coeff_lo[i] = (coeff_lo[i] >> 3);   /* lo >> 3 */
+    }
 
-	/* Codebook search */
-	dist_min = MAX_32;
-	p = &t_qua_gain[min_ind << 1];
+    /* Codebook search */
+    dist_min = MAX_32;
+    p = &t_qua_gain[min_ind << 1];
 
-	index = 0;
-	for (i = 0; i < size; i++)
-	{
-		g_pitch = *p++;
-		g_code = *p++;
+    index = 0;
+    for (i = 0; i < size; i++)
+    {
+        g_pitch = *p++;
+        g_code = *p++;
 
-		g_code = ((g_code * gcode0) + 0x4000)>>15;
-		g2_pitch = ((g_pitch * g_pitch) + 0x4000)>>15;
-		g_pit_cod = ((g_code * g_pitch) + 0x4000)>>15;
-		L_tmp = (g_code * g_code)<<1;
-		VO_L_Extract(L_tmp, &g2_code, &g2_code_lo);
+        g_code = ((g_code * gcode0) + 0x4000)>>15;
+        g2_pitch = ((g_pitch * g_pitch) + 0x4000)>>15;
+        g_pit_cod = ((g_code * g_pitch) + 0x4000)>>15;
+        L_tmp = (g_code * g_code)<<1;
+        VO_L_Extract(L_tmp, &g2_code, &g2_code_lo);
 
-		L_tmp = (coeff[2] * g2_code_lo)<<1;
-		L_tmp =  (L_tmp >> 3);
-		L_tmp += (coeff_lo[0] * g2_pitch)<<1;
-		L_tmp += (coeff_lo[1] * g_pitch)<<1;
-		L_tmp += (coeff_lo[2] * g2_code)<<1;
-		L_tmp += (coeff_lo[3] * g_code)<<1;
-		L_tmp += (coeff_lo[4] * g_pit_cod)<<1;
-		L_tmp =  (L_tmp >> 12);
-		L_tmp += (coeff[0] * g2_pitch)<<1;
-		L_tmp += (coeff[1] * g_pitch)<<1;
-		L_tmp += (coeff[2] * g2_code)<<1;
-		L_tmp += (coeff[3] * g_code)<<1;
-		L_tmp += (coeff[4] * g_pit_cod)<<1;
+        L_tmp = (coeff[2] * g2_code_lo)<<1;
+        L_tmp =  (L_tmp >> 3);
+        L_tmp += (coeff_lo[0] * g2_pitch)<<1;
+        L_tmp += (coeff_lo[1] * g_pitch)<<1;
+        L_tmp += (coeff_lo[2] * g2_code)<<1;
+        L_tmp += (coeff_lo[3] * g_code)<<1;
+        L_tmp += (coeff_lo[4] * g_pit_cod)<<1;
+        L_tmp =  (L_tmp >> 12);
+        L_tmp += (coeff[0] * g2_pitch)<<1;
+        L_tmp += (coeff[1] * g_pitch)<<1;
+        L_tmp += (coeff[2] * g2_code)<<1;
+        L_tmp += (coeff[3] * g_code)<<1;
+        L_tmp += (coeff[4] * g_pit_cod)<<1;
 
-		if(L_tmp < dist_min)
-		{
-			dist_min = L_tmp;
-			index = i;
-		}
-	}
+        if(L_tmp < dist_min)
+        {
+            dist_min = L_tmp;
+            index = i;
+        }
+    }
 
-	/* Read the quantized gains */
-	index = index + min_ind;
-	p = &t_qua_gain[(index + index)];
-	*gain_pit = *p++;                       /* selected pitch gain in Q14 */
-	g_code = *p++;                          /* selected code gain in Q11  */
+    /* Read the quantized gains */
+    index = index + min_ind;
+    p = &t_qua_gain[(index + index)];
+    *gain_pit = *p++;                       /* selected pitch gain in Q14 */
+    g_code = *p++;                          /* selected code gain in Q11  */
 
-	L_tmp = vo_L_mult(g_code, gcode0);             /* Q11*Q0 -> Q12 */
-	L_tmp = L_shl(L_tmp, (exp_gcode0 + 4));   /* Q12 -> Q16 */
+    L_tmp = vo_L_mult(g_code, gcode0);             /* Q11*Q0 -> Q12 */
+    L_tmp = L_shl(L_tmp, (exp_gcode0 + 4));   /* Q12 -> Q16 */
 
-	*gain_cod = L_tmp;                       /* gain of code in Q16 */
+    *gain_cod = L_tmp;                       /* gain of code in Q16 */
 
-	/*---------------------------------------------------*
-	 * qua_ener = 20*log10(g_code)                       *
-	 *          = 6.0206*log2(g_code)                    *
-	 *          = 6.0206*(log2(g_codeQ11) - 11)          *
-	 *---------------------------------------------------*/
+    /*---------------------------------------------------*
+     * qua_ener = 20*log10(g_code)                       *
+     *          = 6.0206*log2(g_code)                    *
+     *          = 6.0206*(log2(g_codeQ11) - 11)          *
+     *---------------------------------------------------*/
 
-	L_tmp = L_deposit_l(g_code);
-	Log2(L_tmp, &exp, &frac);
-	exp -= 11;
-	L_tmp = Mpy_32_16(exp, frac, 24660);   /* x 6.0206 in Q12 */
+    L_tmp = L_deposit_l(g_code);
+    Log2(L_tmp, &exp, &frac);
+    exp -= 11;
+    L_tmp = Mpy_32_16(exp, frac, 24660);   /* x 6.0206 in Q12 */
 
-	qua_ener = (Word16)(L_tmp >> 3); /* result in Q10 */
+    qua_ener = (Word16)(L_tmp >> 3); /* result in Q10 */
 
-	/* update table of past quantized energies */
+    /* update table of past quantized energies */
 
-	past_qua_en[3] = past_qua_en[2];
-	past_qua_en[2] = past_qua_en[1];
-	past_qua_en[1] = past_qua_en[0];
-	past_qua_en[0] = qua_ener;
+    past_qua_en[3] = past_qua_en[2];
+    past_qua_en[2] = past_qua_en[1];
+    past_qua_en[1] = past_qua_en[0];
+    past_qua_en[0] = qua_ener;
 
-	return (index);
+    return (index);
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/q_pulse.c b/media/libstagefright/codecs/amrwbenc/src/q_pulse.c
index d658602..fe0bdda 100644
--- a/media/libstagefright/codecs/amrwbenc/src/q_pulse.c
+++ b/media/libstagefright/codecs/amrwbenc/src/q_pulse.c
@@ -29,372 +29,372 @@
 #define NB_POS 16                          /* pos in track, mask for sign bit */
 
 Word32 quant_1p_N1(                        /* (o) return N+1 bits             */
-		Word16 pos,                        /* (i) position of the pulse       */
-		Word16 N)                          /* (i) number of bits for position */
+        Word16 pos,                        /* (i) position of the pulse       */
+        Word16 N)                          /* (i) number of bits for position */
 {
-	Word16 mask;
-	Word32 index;
+    Word16 mask;
+    Word32 index;
 
-	mask = (1 << N) - 1;              /* mask = ((1<<N)-1); */
-	/*-------------------------------------------------------*
-	 * Quantization of 1 pulse with N+1 bits:                *
-	 *-------------------------------------------------------*/
-	index = L_deposit_l((Word16) (pos & mask));
-	if ((pos & NB_POS) != 0)
-	{
-		index = vo_L_add(index, L_deposit_l(1 << N));   /* index += 1 << N; */
-	}
-	return (index);
+    mask = (1 << N) - 1;              /* mask = ((1<<N)-1); */
+    /*-------------------------------------------------------*
+     * Quantization of 1 pulse with N+1 bits:                *
+     *-------------------------------------------------------*/
+    index = L_deposit_l((Word16) (pos & mask));
+    if ((pos & NB_POS) != 0)
+    {
+        index = vo_L_add(index, L_deposit_l(1 << N));   /* index += 1 << N; */
+    }
+    return (index);
 }
 
 
 Word32 quant_2p_2N1(                       /* (o) return (2*N)+1 bits         */
-		Word16 pos1,                          /* (i) position of the pulse 1     */
-		Word16 pos2,                          /* (i) position of the pulse 2     */
-		Word16 N)                             /* (i) number of bits for position */
+        Word16 pos1,                          /* (i) position of the pulse 1     */
+        Word16 pos2,                          /* (i) position of the pulse 2     */
+        Word16 N)                             /* (i) number of bits for position */
 {
-	Word16 mask, tmp;
-	Word32 index;
-	mask = (1 << N) - 1;              /* mask = ((1<<N)-1); */
-	/*-------------------------------------------------------*
-	 * Quantization of 2 pulses with 2*N+1 bits:             *
-	 *-------------------------------------------------------*/
-	if (((pos2 ^ pos1) & NB_POS) == 0)
-	{
-		/* sign of 1st pulse == sign of 2th pulse */
-		if(pos1 <= pos2)          /* ((pos1 - pos2) <= 0) */
-		{
-			/* index = ((pos1 & mask) << N) + (pos2 & mask); */
-			index = L_deposit_l(add1((((Word16) (pos1 & mask)) << N), ((Word16) (pos2 & mask))));
-		} else
-		{
-			/* ((pos2 & mask) << N) + (pos1 & mask); */
-			index = L_deposit_l(add1((((Word16) (pos2 & mask)) << N), ((Word16) (pos1 & mask))));
-		}
-		if ((pos1 & NB_POS) != 0)
-		{
-			tmp = (N << 1);
-			index = vo_L_add(index, (1L << tmp));       /* index += 1 << (2*N); */
-		}
-	} else
-	{
-		/* sign of 1st pulse != sign of 2th pulse */
-		if (vo_sub((Word16) (pos1 & mask), (Word16) (pos2 & mask)) <= 0)
-		{
-			/* index = ((pos2 & mask) << N) + (pos1 & mask); */
-			index = L_deposit_l(add1((((Word16) (pos2 & mask)) << N), ((Word16) (pos1 & mask))));
-			if ((pos2 & NB_POS) != 0)
-			{
-				tmp = (N << 1);           /* index += 1 << (2*N); */
-				index = vo_L_add(index, (1L << tmp));
-			}
-		} else
-		{
-			/* index = ((pos1 & mask) << N) + (pos2 & mask);	 */
-			index = L_deposit_l(add1((((Word16) (pos1 & mask)) << N), ((Word16) (pos2 & mask))));
-			if ((pos1 & NB_POS) != 0)
-			{
-				tmp = (N << 1);
-				index = vo_L_add(index, (1 << tmp));    /* index += 1 << (2*N); */
-			}
-		}
-	}
-	return (index);
+    Word16 mask, tmp;
+    Word32 index;
+    mask = (1 << N) - 1;              /* mask = ((1<<N)-1); */
+    /*-------------------------------------------------------*
+     * Quantization of 2 pulses with 2*N+1 bits:             *
+     *-------------------------------------------------------*/
+    if (((pos2 ^ pos1) & NB_POS) == 0)
+    {
+        /* sign of 1st pulse == sign of 2th pulse */
+        if(pos1 <= pos2)          /* ((pos1 - pos2) <= 0) */
+        {
+            /* index = ((pos1 & mask) << N) + (pos2 & mask); */
+            index = L_deposit_l(add1((((Word16) (pos1 & mask)) << N), ((Word16) (pos2 & mask))));
+        } else
+        {
+            /* ((pos2 & mask) << N) + (pos1 & mask); */
+            index = L_deposit_l(add1((((Word16) (pos2 & mask)) << N), ((Word16) (pos1 & mask))));
+        }
+        if ((pos1 & NB_POS) != 0)
+        {
+            tmp = (N << 1);
+            index = vo_L_add(index, (1L << tmp));       /* index += 1 << (2*N); */
+        }
+    } else
+    {
+        /* sign of 1st pulse != sign of 2th pulse */
+        if (vo_sub((Word16) (pos1 & mask), (Word16) (pos2 & mask)) <= 0)
+        {
+            /* index = ((pos2 & mask) << N) + (pos1 & mask); */
+            index = L_deposit_l(add1((((Word16) (pos2 & mask)) << N), ((Word16) (pos1 & mask))));
+            if ((pos2 & NB_POS) != 0)
+            {
+                tmp = (N << 1);           /* index += 1 << (2*N); */
+                index = vo_L_add(index, (1L << tmp));
+            }
+        } else
+        {
+            /* index = ((pos1 & mask) << N) + (pos2 & mask);     */
+            index = L_deposit_l(add1((((Word16) (pos1 & mask)) << N), ((Word16) (pos2 & mask))));
+            if ((pos1 & NB_POS) != 0)
+            {
+                tmp = (N << 1);
+                index = vo_L_add(index, (1 << tmp));    /* index += 1 << (2*N); */
+            }
+        }
+    }
+    return (index);
 }
 
 
 Word32 quant_3p_3N1(                       /* (o) return (3*N)+1 bits         */
-		Word16 pos1,                          /* (i) position of the pulse 1     */
-		Word16 pos2,                          /* (i) position of the pulse 2     */
-		Word16 pos3,                          /* (i) position of the pulse 3     */
-		Word16 N)                             /* (i) number of bits for position */
+        Word16 pos1,                          /* (i) position of the pulse 1     */
+        Word16 pos2,                          /* (i) position of the pulse 2     */
+        Word16 pos3,                          /* (i) position of the pulse 3     */
+        Word16 N)                             /* (i) number of bits for position */
 {
-	Word16 nb_pos;
-	Word32 index;
+    Word16 nb_pos;
+    Word32 index;
 
-	nb_pos =(1 <<(N - 1));            /* nb_pos = (1<<(N-1)); */
-	/*-------------------------------------------------------*
-	 * Quantization of 3 pulses with 3*N+1 bits:             *
-	 *-------------------------------------------------------*/
-	if (((pos1 ^ pos2) & nb_pos) == 0)
-	{
-		index = quant_2p_2N1(pos1, pos2, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos2, (N-1)); */
-		/* index += (pos1 & nb_pos) << N; */
-		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
-		/* index += quant_1p_N1(pos3, N) << (2*N); */
-		index = vo_L_add(index, (quant_1p_N1(pos3, N)<<(N << 1)));
+    nb_pos =(1 <<(N - 1));            /* nb_pos = (1<<(N-1)); */
+    /*-------------------------------------------------------*
+     * Quantization of 3 pulses with 3*N+1 bits:             *
+     *-------------------------------------------------------*/
+    if (((pos1 ^ pos2) & nb_pos) == 0)
+    {
+        index = quant_2p_2N1(pos1, pos2, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos2, (N-1)); */
+        /* index += (pos1 & nb_pos) << N; */
+        index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
+        /* index += quant_1p_N1(pos3, N) << (2*N); */
+        index = vo_L_add(index, (quant_1p_N1(pos3, N)<<(N << 1)));
 
-	} else if (((pos1 ^ pos3) & nb_pos) == 0)
-	{
-		index = quant_2p_2N1(pos1, pos3, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos3, (N-1)); */
-		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
-		/* index += (pos1 & nb_pos) << N; */
-		index = vo_L_add(index, (quant_1p_N1(pos2, N) << (N << 1)));
-		/* index += quant_1p_N1(pos2, N) <<
-		 * (2*N); */
-	} else
-	{
-		index = quant_2p_2N1(pos2, pos3, (N - 1));    /* index = quant_2p_2N1(pos2, pos3, (N-1)); */
-		/* index += (pos2 & nb_pos) << N;			 */
-		index = vo_L_add(index, (L_deposit_l((Word16) (pos2 & nb_pos)) << N));
-		/* index += quant_1p_N1(pos1, N) << (2*N);	 */
-		index = vo_L_add(index, (quant_1p_N1(pos1, N) << (N << 1)));
-	}
-	return (index);
+    } else if (((pos1 ^ pos3) & nb_pos) == 0)
+    {
+        index = quant_2p_2N1(pos1, pos3, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos3, (N-1)); */
+        index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
+        /* index += (pos1 & nb_pos) << N; */
+        index = vo_L_add(index, (quant_1p_N1(pos2, N) << (N << 1)));
+        /* index += quant_1p_N1(pos2, N) <<
+         * (2*N); */
+    } else
+    {
+        index = quant_2p_2N1(pos2, pos3, (N - 1));    /* index = quant_2p_2N1(pos2, pos3, (N-1)); */
+        /* index += (pos2 & nb_pos) << N;            */
+        index = vo_L_add(index, (L_deposit_l((Word16) (pos2 & nb_pos)) << N));
+        /* index += quant_1p_N1(pos1, N) << (2*N);   */
+        index = vo_L_add(index, (quant_1p_N1(pos1, N) << (N << 1)));
+    }
+    return (index);
 }
 
 
 Word32 quant_4p_4N1(                       /* (o) return (4*N)+1 bits         */
-		Word16 pos1,                          /* (i) position of the pulse 1     */
-		Word16 pos2,                          /* (i) position of the pulse 2     */
-		Word16 pos3,                          /* (i) position of the pulse 3     */
-		Word16 pos4,                          /* (i) position of the pulse 4     */
-		Word16 N)                             /* (i) number of bits for position */
+        Word16 pos1,                          /* (i) position of the pulse 1     */
+        Word16 pos2,                          /* (i) position of the pulse 2     */
+        Word16 pos3,                          /* (i) position of the pulse 3     */
+        Word16 pos4,                          /* (i) position of the pulse 4     */
+        Word16 N)                             /* (i) number of bits for position */
 {
-	Word16 nb_pos;
-	Word32 index;
+    Word16 nb_pos;
+    Word32 index;
 
-	nb_pos = 1 << (N - 1);            /* nb_pos = (1<<(N-1));  */
-	/*-------------------------------------------------------*
-	 * Quantization of 4 pulses with 4*N+1 bits:             *
-	 *-------------------------------------------------------*/
-	if (((pos1 ^ pos2) & nb_pos) == 0)
-	{
-		index = quant_2p_2N1(pos1, pos2, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos2, (N-1)); */
-		/* index += (pos1 & nb_pos) << N;	 */
-		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
-		/* index += quant_2p_2N1(pos3, pos4, N) << (2*N); */
-		index = vo_L_add(index, (quant_2p_2N1(pos3, pos4, N) << (N << 1)));
-	} else if (((pos1 ^ pos3) & nb_pos) == 0)
-	{
-		index = quant_2p_2N1(pos1, pos3, (N - 1));
-		/* index += (pos1 & nb_pos) << N; */
-		index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
-		/* index += quant_2p_2N1(pos2, pos4, N) << (2*N); */
-		index = vo_L_add(index, (quant_2p_2N1(pos2, pos4, N) << (N << 1)));
-	} else
-	{
-		index = quant_2p_2N1(pos2, pos3, (N - 1));
-		/* index += (pos2 & nb_pos) << N; */
-		index = vo_L_add(index, (L_deposit_l((Word16) (pos2 & nb_pos)) << N));
-		/* index += quant_2p_2N1(pos1, pos4, N) << (2*N); */
-		index = vo_L_add(index, (quant_2p_2N1(pos1, pos4, N) << (N << 1)));
-	}
-	return (index);
+    nb_pos = 1 << (N - 1);            /* nb_pos = (1<<(N-1));  */
+    /*-------------------------------------------------------*
+     * Quantization of 4 pulses with 4*N+1 bits:             *
+     *-------------------------------------------------------*/
+    if (((pos1 ^ pos2) & nb_pos) == 0)
+    {
+        index = quant_2p_2N1(pos1, pos2, sub(N, 1));    /* index = quant_2p_2N1(pos1, pos2, (N-1)); */
+        /* index += (pos1 & nb_pos) << N;    */
+        index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
+        /* index += quant_2p_2N1(pos3, pos4, N) << (2*N); */
+        index = vo_L_add(index, (quant_2p_2N1(pos3, pos4, N) << (N << 1)));
+    } else if (((pos1 ^ pos3) & nb_pos) == 0)
+    {
+        index = quant_2p_2N1(pos1, pos3, (N - 1));
+        /* index += (pos1 & nb_pos) << N; */
+        index = vo_L_add(index, (L_deposit_l((Word16) (pos1 & nb_pos)) << N));
+        /* index += quant_2p_2N1(pos2, pos4, N) << (2*N); */
+        index = vo_L_add(index, (quant_2p_2N1(pos2, pos4, N) << (N << 1)));
+    } else
+    {
+        index = quant_2p_2N1(pos2, pos3, (N - 1));
+        /* index += (pos2 & nb_pos) << N; */
+        index = vo_L_add(index, (L_deposit_l((Word16) (pos2 & nb_pos)) << N));
+        /* index += quant_2p_2N1(pos1, pos4, N) << (2*N); */
+        index = vo_L_add(index, (quant_2p_2N1(pos1, pos4, N) << (N << 1)));
+    }
+    return (index);
 }
 
 
 Word32 quant_4p_4N(                        /* (o) return 4*N bits             */
-		Word16 pos[],                         /* (i) position of the pulse 1..4  */
-		Word16 N)                             /* (i) number of bits for position */
+        Word16 pos[],                         /* (i) position of the pulse 1..4  */
+        Word16 N)                             /* (i) number of bits for position */
 {
-	Word16 nb_pos, mask __unused, n_1, tmp;
-	Word16 posA[4], posB[4];
-	Word32 i, j, k, index;
+    Word16 nb_pos, mask __unused, n_1, tmp;
+    Word16 posA[4], posB[4];
+    Word32 i, j, k, index;
 
-	n_1 = (Word16) (N - 1);
-	nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */
-	mask = vo_sub((1 << N), 1);              /* mask = ((1<<N)-1); */
+    n_1 = (Word16) (N - 1);
+    nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */
+    mask = vo_sub((1 << N), 1);              /* mask = ((1<<N)-1); */
 
-	i = 0;
-	j = 0;
-	for (k = 0; k < 4; k++)
-	{
-		if ((pos[k] & nb_pos) == 0)
-		{
-			posA[i++] = pos[k];
-		} else
-		{
-			posB[j++] = pos[k];
-		}
-	}
+    i = 0;
+    j = 0;
+    for (k = 0; k < 4; k++)
+    {
+        if ((pos[k] & nb_pos) == 0)
+        {
+            posA[i++] = pos[k];
+        } else
+        {
+            posB[j++] = pos[k];
+        }
+    }
 
-	switch (i)
-	{
-		case 0:
-			tmp = vo_sub((N << 2), 3);           /* index = 1 << ((4*N)-3); */
-			index = (1L << tmp);
-			/* index += quant_4p_4N1(posB[0], posB[1], posB[2], posB[3], n_1); */
-			index = vo_L_add(index, quant_4p_4N1(posB[0], posB[1], posB[2], posB[3], n_1));
-			break;
-		case 1:
-			/* index = quant_1p_N1(posA[0], n_1) << ((3*n_1)+1); */
-			tmp = add1((Word16)((vo_L_mult(3, n_1) >> 1)), 1);
-			index = L_shl(quant_1p_N1(posA[0], n_1), tmp);
-			/* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1); */
-			index = vo_L_add(index, quant_3p_3N1(posB[0], posB[1], posB[2], n_1));
-			break;
-		case 2:
-			tmp = ((n_1 << 1) + 1);         /* index = quant_2p_2N1(posA[0], posA[1], n_1) << ((2*n_1)+1); */
-			index = L_shl(quant_2p_2N1(posA[0], posA[1], n_1), tmp);
-			/* index += quant_2p_2N1(posB[0], posB[1], n_1); */
-			index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], n_1));
-			break;
-		case 3:
-			/* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << N; */
-			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), N);
-			index = vo_L_add(index, quant_1p_N1(posB[0], n_1));        /* index += quant_1p_N1(posB[0], n_1); */
-			break;
-		case 4:
-			index = quant_4p_4N1(posA[0], posA[1], posA[2], posA[3], n_1);
-			break;
-		default:
-			index = 0;
-			fprintf(stderr, "Error in function quant_4p_4N\n");
-	}
-	tmp = ((N << 2) - 2);               /* index += (i & 3) << ((4*N)-2); */
-	index = vo_L_add(index, L_shl((L_deposit_l(i) & (3L)), tmp));
+    switch (i)
+    {
+        case 0:
+            tmp = vo_sub((N << 2), 3);           /* index = 1 << ((4*N)-3); */
+            index = (1L << tmp);
+            /* index += quant_4p_4N1(posB[0], posB[1], posB[2], posB[3], n_1); */
+            index = vo_L_add(index, quant_4p_4N1(posB[0], posB[1], posB[2], posB[3], n_1));
+            break;
+        case 1:
+            /* index = quant_1p_N1(posA[0], n_1) << ((3*n_1)+1); */
+            tmp = add1((Word16)((vo_L_mult(3, n_1) >> 1)), 1);
+            index = L_shl(quant_1p_N1(posA[0], n_1), tmp);
+            /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1); */
+            index = vo_L_add(index, quant_3p_3N1(posB[0], posB[1], posB[2], n_1));
+            break;
+        case 2:
+            tmp = ((n_1 << 1) + 1);         /* index = quant_2p_2N1(posA[0], posA[1], n_1) << ((2*n_1)+1); */
+            index = L_shl(quant_2p_2N1(posA[0], posA[1], n_1), tmp);
+            /* index += quant_2p_2N1(posB[0], posB[1], n_1); */
+            index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], n_1));
+            break;
+        case 3:
+            /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << N; */
+            index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), N);
+            index = vo_L_add(index, quant_1p_N1(posB[0], n_1));        /* index += quant_1p_N1(posB[0], n_1); */
+            break;
+        case 4:
+            index = quant_4p_4N1(posA[0], posA[1], posA[2], posA[3], n_1);
+            break;
+        default:
+            index = 0;
+            fprintf(stderr, "Error in function quant_4p_4N\n");
+    }
+    tmp = ((N << 2) - 2);               /* index += (i & 3) << ((4*N)-2); */
+    index = vo_L_add(index, L_shl((L_deposit_l(i) & (3L)), tmp));
 
-	return (index);
+    return (index);
 }
 
 
 
 Word32 quant_5p_5N(                        /* (o) return 5*N bits             */
-		Word16 pos[],                         /* (i) position of the pulse 1..5  */
-		Word16 N)                             /* (i) number of bits for position */
+        Word16 pos[],                         /* (i) position of the pulse 1..5  */
+        Word16 N)                             /* (i) number of bits for position */
 {
-	Word16 nb_pos, n_1, tmp;
-	Word16 posA[5], posB[5];
-	Word32 i, j, k, index, tmp2;
+    Word16 nb_pos, n_1, tmp;
+    Word16 posA[5], posB[5];
+    Word32 i, j, k, index, tmp2;
 
-	n_1 = (Word16) (N - 1);
-	nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */
+    n_1 = (Word16) (N - 1);
+    nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */
 
-	i = 0;
-	j = 0;
-	for (k = 0; k < 5; k++)
-	{
-		if ((pos[k] & nb_pos) == 0)
-		{
-			posA[i++] = pos[k];
-		} else
-		{
-			posB[j++] = pos[k];
-		}
-	}
+    i = 0;
+    j = 0;
+    for (k = 0; k < 5; k++)
+    {
+        if ((pos[k] & nb_pos) == 0)
+        {
+            posA[i++] = pos[k];
+        } else
+        {
+            posB[j++] = pos[k];
+        }
+    }
 
-	switch (i)
-	{
-		case 0:
-			tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* ((5*N)-1)) */
-			index = L_shl(1L, tmp);   /* index = 1 << ((5*N)-1); */
-			tmp = add1((N << 1), 1);  /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) << ((2*N)+1);*/
-			tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);
-			index = vo_L_add(index, tmp2);
-			index = vo_L_add(index, quant_2p_2N1(posB[3], posB[4], N));        /* index += quant_2p_2N1(posB[3], posB[4], N); */
-			break;
-		case 1:
-			tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* index = 1 << ((5*N)-1); */
-			index = L_shl(1L, tmp);
-			tmp = add1((N << 1), 1);   /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) <<((2*N)+1);  */
-			tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);
-			index = vo_L_add(index, tmp2);
-			index = vo_L_add(index, quant_2p_2N1(posB[3], posA[0], N));        /* index += quant_2p_2N1(posB[3], posA[0], N); */
-			break;
-		case 2:
-			tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* ((5*N)-1)) */
-			index = L_shl(1L, tmp);            /* index = 1 << ((5*N)-1); */
-			tmp = add1((N << 1), 1);           /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) << ((2*N)+1);  */
-			tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);
-			index = vo_L_add(index, tmp2);
-			index = vo_L_add(index, quant_2p_2N1(posA[0], posA[1], N));        /* index += quant_2p_2N1(posA[0], posA[1], N); */
-			break;
-		case 3:
-			tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */
-			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);
-			index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], N));        /* index += quant_2p_2N1(posB[0], posB[1], N); */
-			break;
-		case 4:
-			tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */
-			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);
-			index = vo_L_add(index, quant_2p_2N1(posA[3], posB[0], N));        /* index += quant_2p_2N1(posA[3], posB[0], N); */
-			break;
-		case 5:
-			tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */
-			index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);
-			index = vo_L_add(index, quant_2p_2N1(posA[3], posA[4], N));        /* index += quant_2p_2N1(posA[3], posA[4], N); */
-			break;
-		default:
-			index = 0;
-			fprintf(stderr, "Error in function quant_5p_5N\n");
-	}
+    switch (i)
+    {
+        case 0:
+            tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* ((5*N)-1)) */
+            index = L_shl(1L, tmp);   /* index = 1 << ((5*N)-1); */
+            tmp = add1((N << 1), 1);  /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) << ((2*N)+1);*/
+            tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);
+            index = vo_L_add(index, tmp2);
+            index = vo_L_add(index, quant_2p_2N1(posB[3], posB[4], N));        /* index += quant_2p_2N1(posB[3], posB[4], N); */
+            break;
+        case 1:
+            tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* index = 1 << ((5*N)-1); */
+            index = L_shl(1L, tmp);
+            tmp = add1((N << 1), 1);   /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) <<((2*N)+1);  */
+            tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);
+            index = vo_L_add(index, tmp2);
+            index = vo_L_add(index, quant_2p_2N1(posB[3], posA[0], N));        /* index += quant_2p_2N1(posB[3], posA[0], N); */
+            break;
+        case 2:
+            tmp = vo_sub((Word16)((vo_L_mult(5, N) >> 1)), 1);        /* ((5*N)-1)) */
+            index = L_shl(1L, tmp);            /* index = 1 << ((5*N)-1); */
+            tmp = add1((N << 1), 1);           /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1) << ((2*N)+1);  */
+            tmp2 = L_shl(quant_3p_3N1(posB[0], posB[1], posB[2], n_1), tmp);
+            index = vo_L_add(index, tmp2);
+            index = vo_L_add(index, quant_2p_2N1(posA[0], posA[1], N));        /* index += quant_2p_2N1(posA[0], posA[1], N); */
+            break;
+        case 3:
+            tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */
+            index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);
+            index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], N));        /* index += quant_2p_2N1(posB[0], posB[1], N); */
+            break;
+        case 4:
+            tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */
+            index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);
+            index = vo_L_add(index, quant_2p_2N1(posA[3], posB[0], N));        /* index += quant_2p_2N1(posA[3], posB[0], N); */
+            break;
+        case 5:
+            tmp = add1((N << 1), 1);           /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((2*N)+1);  */
+            index = L_shl(quant_3p_3N1(posA[0], posA[1], posA[2], n_1), tmp);
+            index = vo_L_add(index, quant_2p_2N1(posA[3], posA[4], N));        /* index += quant_2p_2N1(posA[3], posA[4], N); */
+            break;
+        default:
+            index = 0;
+            fprintf(stderr, "Error in function quant_5p_5N\n");
+    }
 
-	return (index);
+    return (index);
 }
 
 
 Word32 quant_6p_6N_2(                      /* (o) return (6*N)-2 bits         */
-		Word16 pos[],                         /* (i) position of the pulse 1..6  */
-		Word16 N)                             /* (i) number of bits for position */
+        Word16 pos[],                         /* (i) position of the pulse 1..6  */
+        Word16 N)                             /* (i) number of bits for position */
 {
-	Word16 nb_pos, n_1;
-	Word16 posA[6], posB[6];
-	Word32 i, j, k, index;
+    Word16 nb_pos, n_1;
+    Word16 posA[6], posB[6];
+    Word32 i, j, k, index;
 
-	/* !!  N and n_1 are constants -> it doesn't need to be operated by Basic Operators */
-	n_1 = (Word16) (N - 1);
-	nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */
+    /* !!  N and n_1 are constants -> it doesn't need to be operated by Basic Operators */
+    n_1 = (Word16) (N - 1);
+    nb_pos = (1 << n_1);                  /* nb_pos = (1<<n_1); */
 
-	i = 0;
-	j = 0;
-	for (k = 0; k < 6; k++)
-	{
-		if ((pos[k] & nb_pos) == 0)
-		{
-			posA[i++] = pos[k];
-		} else
-		{
-			posB[j++] = pos[k];
-		}
-	}
+    i = 0;
+    j = 0;
+    for (k = 0; k < 6; k++)
+    {
+        if ((pos[k] & nb_pos) == 0)
+        {
+            posA[i++] = pos[k];
+        } else
+        {
+            posB[j++] = pos[k];
+        }
+    }
 
-	switch (i)
-	{
-		case 0:
-			index = (1 << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */
-			index = vo_L_add(index, (quant_5p_5N(posB, n_1) << N)); /* index += quant_5p_5N(posB, n_1) << N; */
-			index = vo_L_add(index, quant_1p_N1(posB[5], n_1));        /* index += quant_1p_N1(posB[5], n_1); */
-			break;
-		case 1:
-			index = (1L << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */
-			index = vo_L_add(index, (quant_5p_5N(posB, n_1) << N)); /* index += quant_5p_5N(posB, n_1) << N; */
-			index = vo_L_add(index, quant_1p_N1(posA[0], n_1));        /* index += quant_1p_N1(posA[0], n_1); */
-			break;
-		case 2:
-			index = (1L << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */
-			/* index += quant_4p_4N(posB, n_1) << ((2*n_1)+1); */
-			index = vo_L_add(index, (quant_4p_4N(posB, n_1) << (Word16) (2 * n_1 + 1)));
-			index = vo_L_add(index, quant_2p_2N1(posA[0], posA[1], n_1));      /* index += quant_2p_2N1(posA[0], posA[1], n_1); */
-			break;
-		case 3:
-			index = (quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << (Word16) (3 * n_1 + 1));
-			                                  /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((3*n_1)+1); */
-			index =vo_L_add(index, quant_3p_3N1(posB[0], posB[1], posB[2], n_1));
-			                                 /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1); */
-			break;
-		case 4:
-			i = 2;
-			index = (quant_4p_4N(posA, n_1) << (Word16) (2 * n_1 + 1));  /* index = quant_4p_4N(posA, n_1) << ((2*n_1)+1); */
-			index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], n_1));      /* index += quant_2p_2N1(posB[0], posB[1], n_1); */
-			break;
-		case 5:
-			i = 1;
-			index = (quant_5p_5N(posA, n_1) << N);       /* index = quant_5p_5N(posA, n_1) << N; */
-			index = vo_L_add(index, quant_1p_N1(posB[0], n_1));        /* index += quant_1p_N1(posB[0], n_1); */
-			break;
-		case 6:
-			i = 0;
-			index = (quant_5p_5N(posA, n_1) << N);       /* index = quant_5p_5N(posA, n_1) << N; */
-			index = vo_L_add(index, quant_1p_N1(posA[5], n_1));        /* index += quant_1p_N1(posA[5], n_1); */
-			break;
-		default:
-			index = 0;
-			fprintf(stderr, "Error in function quant_6p_6N_2\n");
-	}
-	index = vo_L_add(index, ((L_deposit_l(i) & 3L) << (Word16) (6 * N - 4)));   /* index += (i & 3) << ((6*N)-4); */
+    switch (i)
+    {
+        case 0:
+            index = (1 << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */
+            index = vo_L_add(index, (quant_5p_5N(posB, n_1) << N)); /* index += quant_5p_5N(posB, n_1) << N; */
+            index = vo_L_add(index, quant_1p_N1(posB[5], n_1));        /* index += quant_1p_N1(posB[5], n_1); */
+            break;
+        case 1:
+            index = (1L << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */
+            index = vo_L_add(index, (quant_5p_5N(posB, n_1) << N)); /* index += quant_5p_5N(posB, n_1) << N; */
+            index = vo_L_add(index, quant_1p_N1(posA[0], n_1));        /* index += quant_1p_N1(posA[0], n_1); */
+            break;
+        case 2:
+            index = (1L << (Word16) (6 * N - 5));        /* index = 1 << ((6*N)-5); */
+            /* index += quant_4p_4N(posB, n_1) << ((2*n_1)+1); */
+            index = vo_L_add(index, (quant_4p_4N(posB, n_1) << (Word16) (2 * n_1 + 1)));
+            index = vo_L_add(index, quant_2p_2N1(posA[0], posA[1], n_1));      /* index += quant_2p_2N1(posA[0], posA[1], n_1); */
+            break;
+        case 3:
+            index = (quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << (Word16) (3 * n_1 + 1));
+                                              /* index = quant_3p_3N1(posA[0], posA[1], posA[2], n_1) << ((3*n_1)+1); */
+            index =vo_L_add(index, quant_3p_3N1(posB[0], posB[1], posB[2], n_1));
+                                             /* index += quant_3p_3N1(posB[0], posB[1], posB[2], n_1); */
+            break;
+        case 4:
+            i = 2;
+            index = (quant_4p_4N(posA, n_1) << (Word16) (2 * n_1 + 1));  /* index = quant_4p_4N(posA, n_1) << ((2*n_1)+1); */
+            index = vo_L_add(index, quant_2p_2N1(posB[0], posB[1], n_1));      /* index += quant_2p_2N1(posB[0], posB[1], n_1); */
+            break;
+        case 5:
+            i = 1;
+            index = (quant_5p_5N(posA, n_1) << N);       /* index = quant_5p_5N(posA, n_1) << N; */
+            index = vo_L_add(index, quant_1p_N1(posB[0], n_1));        /* index += quant_1p_N1(posB[0], n_1); */
+            break;
+        case 6:
+            i = 0;
+            index = (quant_5p_5N(posA, n_1) << N);       /* index = quant_5p_5N(posA, n_1) << N; */
+            index = vo_L_add(index, quant_1p_N1(posA[5], n_1));        /* index += quant_1p_N1(posA[5], n_1); */
+            break;
+        default:
+            index = 0;
+            fprintf(stderr, "Error in function quant_6p_6N_2\n");
+    }
+    index = vo_L_add(index, ((L_deposit_l(i) & 3L) << (Word16) (6 * N - 4)));   /* index += (i & 3) << ((6*N)-4); */
 
-	return (index);
+    return (index);
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/qisf_ns.c b/media/libstagefright/codecs/amrwbenc/src/qisf_ns.c
index fc2f00d..eac98e2 100644
--- a/media/libstagefright/codecs/amrwbenc/src/qisf_ns.c
+++ b/media/libstagefright/codecs/amrwbenc/src/qisf_ns.c
@@ -33,30 +33,30 @@
 *------------------------------------------------------------------*/
 
 void Qisf_ns(
-		Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */
-		Word16 * isf_q,                       /* output: quantized ISF                        */
-		Word16 * indice                       /* output: quantization indices                 */
-	    )
+        Word16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */
+        Word16 * isf_q,                       /* output: quantized ISF                        */
+        Word16 * indice                       /* output: quantization indices                 */
+        )
 {
-	Word16 i;
-	Word32 tmp;
+    Word16 i;
+    Word32 tmp;
 
-	for (i = 0; i < ORDER; i++)
-	{
-		isf_q[i] = sub(isf1[i], mean_isf_noise[i]);
-	}
+    for (i = 0; i < ORDER; i++)
+    {
+        isf_q[i] = sub(isf1[i], mean_isf_noise[i]);
+    }
 
-	indice[0] = Sub_VQ(&isf_q[0], dico1_isf_noise, 2, SIZE_BK_NOISE1, &tmp);
-	indice[1] = Sub_VQ(&isf_q[2], dico2_isf_noise, 3, SIZE_BK_NOISE2, &tmp);
-	indice[2] = Sub_VQ(&isf_q[5], dico3_isf_noise, 3, SIZE_BK_NOISE3, &tmp);
-	indice[3] = Sub_VQ(&isf_q[8], dico4_isf_noise, 4, SIZE_BK_NOISE4, &tmp);
-	indice[4] = Sub_VQ(&isf_q[12], dico5_isf_noise, 4, SIZE_BK_NOISE5, &tmp);
+    indice[0] = Sub_VQ(&isf_q[0], dico1_isf_noise, 2, SIZE_BK_NOISE1, &tmp);
+    indice[1] = Sub_VQ(&isf_q[2], dico2_isf_noise, 3, SIZE_BK_NOISE2, &tmp);
+    indice[2] = Sub_VQ(&isf_q[5], dico3_isf_noise, 3, SIZE_BK_NOISE3, &tmp);
+    indice[3] = Sub_VQ(&isf_q[8], dico4_isf_noise, 4, SIZE_BK_NOISE4, &tmp);
+    indice[4] = Sub_VQ(&isf_q[12], dico5_isf_noise, 4, SIZE_BK_NOISE5, &tmp);
 
-	/* decoding the ISFs */
+    /* decoding the ISFs */
 
-	Disf_ns(indice, isf_q);
+    Disf_ns(indice, isf_q);
 
-	return;
+    return;
 }
 
 /********************************************************************
@@ -70,41 +70,41 @@
 *********************************************************************/
 
 void Disf_ns(
-		Word16 * indice,                      /* input:  quantization indices                  */
-		Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */
-	    )
+        Word16 * indice,                      /* input:  quantization indices                  */
+        Word16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */
+        )
 {
-	Word16 i;
+    Word16 i;
 
-	for (i = 0; i < 2; i++)
-	{
-		isf_q[i] = dico1_isf_noise[indice[0] * 2 + i];
-	}
-	for (i = 0; i < 3; i++)
-	{
-		isf_q[i + 2] = dico2_isf_noise[indice[1] * 3 + i];
-	}
-	for (i = 0; i < 3; i++)
-	{
-		isf_q[i + 5] = dico3_isf_noise[indice[2] * 3 + i];
-	}
-	for (i = 0; i < 4; i++)
-	{
-		isf_q[i + 8] = dico4_isf_noise[indice[3] * 4 + i];
-	}
-	for (i = 0; i < 4; i++)
-	{
-		isf_q[i + 12] = dico5_isf_noise[indice[4] * 4 + i];
-	}
+    for (i = 0; i < 2; i++)
+    {
+        isf_q[i] = dico1_isf_noise[indice[0] * 2 + i];
+    }
+    for (i = 0; i < 3; i++)
+    {
+        isf_q[i + 2] = dico2_isf_noise[indice[1] * 3 + i];
+    }
+    for (i = 0; i < 3; i++)
+    {
+        isf_q[i + 5] = dico3_isf_noise[indice[2] * 3 + i];
+    }
+    for (i = 0; i < 4; i++)
+    {
+        isf_q[i + 8] = dico4_isf_noise[indice[3] * 4 + i];
+    }
+    for (i = 0; i < 4; i++)
+    {
+        isf_q[i + 12] = dico5_isf_noise[indice[4] * 4 + i];
+    }
 
-	for (i = 0; i < ORDER; i++)
-	{
-		isf_q[i] = add(isf_q[i], mean_isf_noise[i]);
-	}
+    for (i = 0; i < ORDER; i++)
+    {
+        isf_q[i] = add(isf_q[i], mean_isf_noise[i]);
+    }
 
-	Reorder_isf(isf_q, ISF_GAP, ORDER);
+    Reorder_isf(isf_q, ISF_GAP, ORDER);
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c b/media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c
index c711cd0..bec334e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c
+++ b/media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c
@@ -36,13 +36,13 @@
 
 /* private functions */
 static void VQ_stage1(
-		Word16 * x,                           /* input : ISF residual vector           */
-		Word16 * dico,                        /* input : quantization codebook         */
-		Word16 dim,                           /* input : dimention of vector           */
-		Word16 dico_size,                     /* input : size of quantization codebook */
-		Word16 * index,                       /* output: indices of survivors          */
-		Word16 surv                           /* input : number of survivor            */
-		);
+        Word16 * x,                           /* input : ISF residual vector           */
+        Word16 * dico,                        /* input : quantization codebook         */
+        Word16 dim,                           /* input : dimention of vector           */
+        Word16 dico_size,                     /* input : size of quantization codebook */
+        Word16 * index,                       /* output: indices of survivors          */
+        Word16 surv                           /* input : number of survivor            */
+        );
 
 /**************************************************************************
 * Function:   Qpisf_2s_46B()                                              *
@@ -54,84 +54,84 @@
 ***************************************************************************/
 
 void Qpisf_2s_46b(
-		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
-		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
-		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
-		Word16 * indice,                      /* (o)     : quantization indices                 */
-		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
-		)
+        Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
+        Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
+        Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
+        Word16 * indice,                      /* (o)     : quantization indices                 */
+        Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
+        )
 {
-	Word16 tmp_ind[5];
-	Word16 surv1[N_SURV_MAX];              /* indices of survivors from 1st stage */
-	Word32 i, k, temp, min_err, distance;
-	Word16 isf[ORDER];
-	Word16 isf_stage2[ORDER];
+    Word16 tmp_ind[5];
+    Word16 surv1[N_SURV_MAX];              /* indices of survivors from 1st stage */
+    Word32 i, k, temp, min_err, distance;
+    Word16 isf[ORDER];
+    Word16 isf_stage2[ORDER];
 
-	for (i = 0; i < ORDER; i++)
-	{
-		isf[i] = vo_sub(isf1[i], mean_isf[i]);
-		isf[i] = vo_sub(isf[i], vo_mult(MU, past_isfq[i]));
-	}
+    for (i = 0; i < ORDER; i++)
+    {
+        isf[i] = vo_sub(isf1[i], mean_isf[i]);
+        isf[i] = vo_sub(isf[i], vo_mult(MU, past_isfq[i]));
+    }
 
-	VQ_stage1(&isf[0], dico1_isf, 9, SIZE_BK1, surv1, nb_surv);
+    VQ_stage1(&isf[0], dico1_isf, 9, SIZE_BK1, surv1, nb_surv);
 
-	distance = MAX_32;
+    distance = MAX_32;
 
-	for (k = 0; k < nb_surv; k++)
-	{
-		for (i = 0; i < 9; i++)
-		{
-			isf_stage2[i] = vo_sub(isf[i], dico1_isf[i + surv1[k] * 9]);
-		}
-		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico21_isf, 3, SIZE_BK21, &min_err);
-		temp = min_err;
-		tmp_ind[1] = Sub_VQ(&isf_stage2[3], dico22_isf, 3, SIZE_BK22, &min_err);
-		temp = vo_L_add(temp, min_err);
-		tmp_ind[2] = Sub_VQ(&isf_stage2[6], dico23_isf, 3, SIZE_BK23, &min_err);
-		temp = vo_L_add(temp, min_err);
+    for (k = 0; k < nb_surv; k++)
+    {
+        for (i = 0; i < 9; i++)
+        {
+            isf_stage2[i] = vo_sub(isf[i], dico1_isf[i + surv1[k] * 9]);
+        }
+        tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico21_isf, 3, SIZE_BK21, &min_err);
+        temp = min_err;
+        tmp_ind[1] = Sub_VQ(&isf_stage2[3], dico22_isf, 3, SIZE_BK22, &min_err);
+        temp = vo_L_add(temp, min_err);
+        tmp_ind[2] = Sub_VQ(&isf_stage2[6], dico23_isf, 3, SIZE_BK23, &min_err);
+        temp = vo_L_add(temp, min_err);
 
-		if(temp < distance)
-		{
-			distance = temp;
-			indice[0] = surv1[k];
-			for (i = 0; i < 3; i++)
-			{
-				indice[i + 2] = tmp_ind[i];
-			}
-		}
-	}
+        if(temp < distance)
+        {
+            distance = temp;
+            indice[0] = surv1[k];
+            for (i = 0; i < 3; i++)
+            {
+                indice[i + 2] = tmp_ind[i];
+            }
+        }
+    }
 
 
-	VQ_stage1(&isf[9], dico2_isf, 7, SIZE_BK2, surv1, nb_surv);
+    VQ_stage1(&isf[9], dico2_isf, 7, SIZE_BK2, surv1, nb_surv);
 
-	distance = MAX_32;
+    distance = MAX_32;
 
-	for (k = 0; k < nb_surv; k++)
-	{
-		for (i = 0; i < 7; i++)
-		{
-			isf_stage2[i] = vo_sub(isf[9 + i], dico2_isf[i + surv1[k] * 7]);
-		}
+    for (k = 0; k < nb_surv; k++)
+    {
+        for (i = 0; i < 7; i++)
+        {
+            isf_stage2[i] = vo_sub(isf[9 + i], dico2_isf[i + surv1[k] * 7]);
+        }
 
-		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico24_isf, 3, SIZE_BK24, &min_err);
-		temp = min_err;
-		tmp_ind[1] = Sub_VQ(&isf_stage2[3], dico25_isf, 4, SIZE_BK25, &min_err);
-		temp = vo_L_add(temp, min_err);
+        tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico24_isf, 3, SIZE_BK24, &min_err);
+        temp = min_err;
+        tmp_ind[1] = Sub_VQ(&isf_stage2[3], dico25_isf, 4, SIZE_BK25, &min_err);
+        temp = vo_L_add(temp, min_err);
 
-		if(temp < distance)
-		{
-			distance = temp;
-			indice[1] = surv1[k];
-			for (i = 0; i < 2; i++)
-			{
-				indice[i + 5] = tmp_ind[i];
-			}
-		}
-	}
+        if(temp < distance)
+        {
+            distance = temp;
+            indice[1] = surv1[k];
+            for (i = 0; i < 2; i++)
+            {
+                indice[i + 5] = tmp_ind[i];
+            }
+        }
+    }
 
-	Dpisf_2s_46b(indice, isf_q, past_isfq, isf_q, isf_q, 0, 0);
+    Dpisf_2s_46b(indice, isf_q, past_isfq, isf_q, isf_q, 0, 0);
 
-	return;
+    return;
 }
 
 /*****************************************************************************
@@ -144,76 +144,76 @@
 ******************************************************************************/
 
 void Qpisf_2s_36b(
-		Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
-		Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
-		Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
-		Word16 * indice,                      /* (o)     : quantization indices                 */
-		Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
-		)
+        Word16 * isf1,                        /* (i) Q15 : ISF in the frequency domain (0..0.5) */
+        Word16 * isf_q,                       /* (o) Q15 : quantized ISF               (0..0.5) */
+        Word16 * past_isfq,                   /* (io)Q15 : past ISF quantizer                   */
+        Word16 * indice,                      /* (o)     : quantization indices                 */
+        Word16 nb_surv                        /* (i)     : number of survivor (1, 2, 3 or 4)    */
+        )
 {
-	Word16 i, k, tmp_ind[5];
-	Word16 surv1[N_SURV_MAX];              /* indices of survivors from 1st stage */
-	Word32 temp, min_err, distance;
-	Word16 isf[ORDER];
-	Word16 isf_stage2[ORDER];
+    Word16 i, k, tmp_ind[5];
+    Word16 surv1[N_SURV_MAX];              /* indices of survivors from 1st stage */
+    Word32 temp, min_err, distance;
+    Word16 isf[ORDER];
+    Word16 isf_stage2[ORDER];
 
-	for (i = 0; i < ORDER; i++)
-	{
-		isf[i] = vo_sub(isf1[i], mean_isf[i]);
-		isf[i] = vo_sub(isf[i], vo_mult(MU, past_isfq[i]));
-	}
+    for (i = 0; i < ORDER; i++)
+    {
+        isf[i] = vo_sub(isf1[i], mean_isf[i]);
+        isf[i] = vo_sub(isf[i], vo_mult(MU, past_isfq[i]));
+    }
 
-	VQ_stage1(&isf[0], dico1_isf, 9, SIZE_BK1, surv1, nb_surv);
+    VQ_stage1(&isf[0], dico1_isf, 9, SIZE_BK1, surv1, nb_surv);
 
-	distance = MAX_32;
+    distance = MAX_32;
 
-	for (k = 0; k < nb_surv; k++)
-	{
-		for (i = 0; i < 9; i++)
-		{
-			isf_stage2[i] = vo_sub(isf[i], dico1_isf[i + surv1[k] * 9]);
-		}
+    for (k = 0; k < nb_surv; k++)
+    {
+        for (i = 0; i < 9; i++)
+        {
+            isf_stage2[i] = vo_sub(isf[i], dico1_isf[i + surv1[k] * 9]);
+        }
 
-		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico21_isf_36b, 5, SIZE_BK21_36b, &min_err);
-		temp = min_err;
-		tmp_ind[1] = Sub_VQ(&isf_stage2[5], dico22_isf_36b, 4, SIZE_BK22_36b, &min_err);
-		temp = vo_L_add(temp, min_err);
+        tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico21_isf_36b, 5, SIZE_BK21_36b, &min_err);
+        temp = min_err;
+        tmp_ind[1] = Sub_VQ(&isf_stage2[5], dico22_isf_36b, 4, SIZE_BK22_36b, &min_err);
+        temp = vo_L_add(temp, min_err);
 
-		if(temp < distance)
-		{
-			distance = temp;
-			indice[0] = surv1[k];
-			for (i = 0; i < 2; i++)
-			{
-				indice[i + 2] = tmp_ind[i];
-			}
-		}
-	}
+        if(temp < distance)
+        {
+            distance = temp;
+            indice[0] = surv1[k];
+            for (i = 0; i < 2; i++)
+            {
+                indice[i + 2] = tmp_ind[i];
+            }
+        }
+    }
 
-	VQ_stage1(&isf[9], dico2_isf, 7, SIZE_BK2, surv1, nb_surv);
-	distance = MAX_32;
+    VQ_stage1(&isf[9], dico2_isf, 7, SIZE_BK2, surv1, nb_surv);
+    distance = MAX_32;
 
-	for (k = 0; k < nb_surv; k++)
-	{
-		for (i = 0; i < 7; i++)
-		{
-			isf_stage2[i] = vo_sub(isf[9 + i], dico2_isf[i + surv1[k] * 7]);
-		}
+    for (k = 0; k < nb_surv; k++)
+    {
+        for (i = 0; i < 7; i++)
+        {
+            isf_stage2[i] = vo_sub(isf[9 + i], dico2_isf[i + surv1[k] * 7]);
+        }
 
-		tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico23_isf_36b, 7, SIZE_BK23_36b, &min_err);
-		temp = min_err;
+        tmp_ind[0] = Sub_VQ(&isf_stage2[0], dico23_isf_36b, 7, SIZE_BK23_36b, &min_err);
+        temp = min_err;
 
-		if(temp < distance)
-		{
-			distance = temp;
-			indice[1] = surv1[k];
-			indice[4] = tmp_ind[0];
-		}
-	}
+        if(temp < distance)
+        {
+            distance = temp;
+            indice[1] = surv1[k];
+            indice[4] = tmp_ind[0];
+        }
+    }
 
-	Dpisf_2s_36b(indice, isf_q, past_isfq, isf_q, isf_q, 0, 0);
+    Dpisf_2s_36b(indice, isf_q, past_isfq, isf_q, isf_q, 0, 0);
 
-	return;
+    return;
 }
 
 /*********************************************************************
@@ -223,90 +223,90 @@
 **********************************************************************/
 
 void Dpisf_2s_46b(
-		Word16 * indice,                      /* input:  quantization indices                       */
-		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
-		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
-		Word16 * isfold,                      /* input : past quantized ISF                    */
-		Word16 * isf_buf,                     /* input : isf buffer                                                        */
-		Word16 bfi,                           /* input : Bad frame indicator                   */
-		Word16 enc_dec
-		)
+        Word16 * indice,                      /* input:  quantization indices                       */
+        Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+        Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+        Word16 * isfold,                      /* input : past quantized ISF                    */
+        Word16 * isf_buf,                     /* input : isf buffer                                                        */
+        Word16 bfi,                           /* input : Bad frame indicator                   */
+        Word16 enc_dec
+        )
 {
-	Word16 ref_isf[M], tmp;
-	Word32 i, j, L_tmp;
+    Word16 ref_isf[M], tmp;
+    Word32 i, j, L_tmp;
 
-	if (bfi == 0)                          /* Good frame */
-	{
-		for (i = 0; i < 9; i++)
-		{
-			isf_q[i] = dico1_isf[indice[0] * 9 + i];
-		}
-		for (i = 0; i < 7; i++)
-		{
-			isf_q[i + 9] = dico2_isf[indice[1] * 7 + i];
-		}
+    if (bfi == 0)                          /* Good frame */
+    {
+        for (i = 0; i < 9; i++)
+        {
+            isf_q[i] = dico1_isf[indice[0] * 9 + i];
+        }
+        for (i = 0; i < 7; i++)
+        {
+            isf_q[i + 9] = dico2_isf[indice[1] * 7 + i];
+        }
 
-		for (i = 0; i < 3; i++)
-		{
-			isf_q[i] = add1(isf_q[i], dico21_isf[indice[2] * 3 + i]);
-			isf_q[i + 3] = add1(isf_q[i + 3], dico22_isf[indice[3] * 3 + i]);
-			isf_q[i + 6] = add1(isf_q[i + 6], dico23_isf[indice[4] * 3 + i]);
-			isf_q[i + 9] = add1(isf_q[i + 9], dico24_isf[indice[5] * 3 + i]);
-		}
+        for (i = 0; i < 3; i++)
+        {
+            isf_q[i] = add1(isf_q[i], dico21_isf[indice[2] * 3 + i]);
+            isf_q[i + 3] = add1(isf_q[i + 3], dico22_isf[indice[3] * 3 + i]);
+            isf_q[i + 6] = add1(isf_q[i + 6], dico23_isf[indice[4] * 3 + i]);
+            isf_q[i + 9] = add1(isf_q[i + 9], dico24_isf[indice[5] * 3 + i]);
+        }
 
-		for (i = 0; i < 4; i++)
-		{
-			isf_q[i + 12] = add1(isf_q[i + 12], dico25_isf[indice[6] * 4 + i]);
-		}
+        for (i = 0; i < 4; i++)
+        {
+            isf_q[i + 12] = add1(isf_q[i + 12], dico25_isf[indice[6] * 4 + i]);
+        }
 
-		for (i = 0; i < ORDER; i++)
-		{
-			tmp = isf_q[i];
-			isf_q[i] = add1(tmp, mean_isf[i]);
-			isf_q[i] = add1(isf_q[i], vo_mult(MU, past_isfq[i]));
-			past_isfq[i] = tmp;
-		}
+        for (i = 0; i < ORDER; i++)
+        {
+            tmp = isf_q[i];
+            isf_q[i] = add1(tmp, mean_isf[i]);
+            isf_q[i] = add1(isf_q[i], vo_mult(MU, past_isfq[i]));
+            past_isfq[i] = tmp;
+        }
 
-		if (enc_dec)
-		{
-			for (i = 0; i < M; i++)
-			{
-				for (j = (L_MEANBUF - 1); j > 0; j--)
-				{
-					isf_buf[j * M + i] = isf_buf[(j - 1) * M + i];
-				}
-				isf_buf[i] = isf_q[i];
-			}
-		}
-	} else
-	{                                      /* bad frame */
-		for (i = 0; i < M; i++)
-		{
-			L_tmp = mean_isf[i] << 14;
-			for (j = 0; j < L_MEANBUF; j++)
-			{
-				L_tmp += (isf_buf[j * M + i] << 14);
-			}
-			ref_isf[i] = vo_round(L_tmp);
-		}
+        if (enc_dec)
+        {
+            for (i = 0; i < M; i++)
+            {
+                for (j = (L_MEANBUF - 1); j > 0; j--)
+                {
+                    isf_buf[j * M + i] = isf_buf[(j - 1) * M + i];
+                }
+                isf_buf[i] = isf_q[i];
+            }
+        }
+    } else
+    {                                      /* bad frame */
+        for (i = 0; i < M; i++)
+        {
+            L_tmp = mean_isf[i] << 14;
+            for (j = 0; j < L_MEANBUF; j++)
+            {
+                L_tmp += (isf_buf[j * M + i] << 14);
+            }
+            ref_isf[i] = vo_round(L_tmp);
+        }
 
-		/* use the past ISFs slightly shifted towards their mean */
-		for (i = 0; i < ORDER; i++)
-		{
-			isf_q[i] = add1(vo_mult(ALPHA, isfold[i]), vo_mult(ONE_ALPHA, ref_isf[i]));
-		}
+        /* use the past ISFs slightly shifted towards their mean */
+        for (i = 0; i < ORDER; i++)
+        {
+            isf_q[i] = add1(vo_mult(ALPHA, isfold[i]), vo_mult(ONE_ALPHA, ref_isf[i]));
+        }
 
-		/* estimate past quantized residual to be used in next frame */
-		for (i = 0; i < ORDER; i++)
-		{
-			tmp = add1(ref_isf[i], vo_mult(past_isfq[i], MU));      /* predicted ISF */
-			past_isfq[i] = vo_sub(isf_q[i], tmp);
-			past_isfq[i] = (past_isfq[i] >> 1);        /* past_isfq[i] *= 0.5 */
-		}
-	}
+        /* estimate past quantized residual to be used in next frame */
+        for (i = 0; i < ORDER; i++)
+        {
+            tmp = add1(ref_isf[i], vo_mult(past_isfq[i], MU));      /* predicted ISF */
+            past_isfq[i] = vo_sub(isf_q[i], tmp);
+            past_isfq[i] = (past_isfq[i] >> 1);        /* past_isfq[i] *= 0.5 */
+        }
+    }
 
-	Reorder_isf(isf_q, ISF_GAP, ORDER);
-	return;
+    Reorder_isf(isf_q, ISF_GAP, ORDER);
+    return;
 }
 
 /*********************************************************************
@@ -316,92 +316,92 @@
 *********************************************************************/
 
 void Dpisf_2s_36b(
-		Word16 * indice,                      /* input:  quantization indices                       */
-		Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
-		Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
-		Word16 * isfold,                      /* input : past quantized ISF                    */
-		Word16 * isf_buf,                     /* input : isf buffer                                                        */
-		Word16 bfi,                           /* input : Bad frame indicator                   */
-		Word16 enc_dec
-		)
+        Word16 * indice,                      /* input:  quantization indices                       */
+        Word16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+        Word16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+        Word16 * isfold,                      /* input : past quantized ISF                    */
+        Word16 * isf_buf,                     /* input : isf buffer                                                        */
+        Word16 bfi,                           /* input : Bad frame indicator                   */
+        Word16 enc_dec
+        )
 {
-	Word16 ref_isf[M], tmp;
-	Word32 i, j, L_tmp;
+    Word16 ref_isf[M], tmp;
+    Word32 i, j, L_tmp;
 
-	if (bfi == 0)                          /* Good frame */
-	{
-		for (i = 0; i < 9; i++)
-		{
-			isf_q[i] = dico1_isf[indice[0] * 9 + i];
-		}
-		for (i = 0; i < 7; i++)
-		{
-			isf_q[i + 9] = dico2_isf[indice[1] * 7 + i];
-		}
+    if (bfi == 0)                          /* Good frame */
+    {
+        for (i = 0; i < 9; i++)
+        {
+            isf_q[i] = dico1_isf[indice[0] * 9 + i];
+        }
+        for (i = 0; i < 7; i++)
+        {
+            isf_q[i + 9] = dico2_isf[indice[1] * 7 + i];
+        }
 
-		for (i = 0; i < 5; i++)
-		{
-			isf_q[i] = add1(isf_q[i], dico21_isf_36b[indice[2] * 5 + i]);
-		}
-		for (i = 0; i < 4; i++)
-		{
-			isf_q[i + 5] = add1(isf_q[i + 5], dico22_isf_36b[indice[3] * 4 + i]);
-		}
-		for (i = 0; i < 7; i++)
-		{
-			isf_q[i + 9] = add1(isf_q[i + 9], dico23_isf_36b[indice[4] * 7 + i]);
-		}
+        for (i = 0; i < 5; i++)
+        {
+            isf_q[i] = add1(isf_q[i], dico21_isf_36b[indice[2] * 5 + i]);
+        }
+        for (i = 0; i < 4; i++)
+        {
+            isf_q[i + 5] = add1(isf_q[i + 5], dico22_isf_36b[indice[3] * 4 + i]);
+        }
+        for (i = 0; i < 7; i++)
+        {
+            isf_q[i + 9] = add1(isf_q[i + 9], dico23_isf_36b[indice[4] * 7 + i]);
+        }
 
-		for (i = 0; i < ORDER; i++)
-		{
-			tmp = isf_q[i];
-			isf_q[i] = add1(tmp, mean_isf[i]);
-			isf_q[i] = add1(isf_q[i], vo_mult(MU, past_isfq[i]));
-			past_isfq[i] = tmp;
-		}
+        for (i = 0; i < ORDER; i++)
+        {
+            tmp = isf_q[i];
+            isf_q[i] = add1(tmp, mean_isf[i]);
+            isf_q[i] = add1(isf_q[i], vo_mult(MU, past_isfq[i]));
+            past_isfq[i] = tmp;
+        }
 
 
-		if (enc_dec)
-		{
-			for (i = 0; i < M; i++)
-			{
-				for (j = (L_MEANBUF - 1); j > 0; j--)
-				{
-					isf_buf[j * M + i] = isf_buf[(j - 1) * M + i];
-				}
-				isf_buf[i] = isf_q[i];
-			}
-		}
-	} else
-	{                                      /* bad frame */
-		for (i = 0; i < M; i++)
-		{
-			L_tmp = (mean_isf[i] << 14);
-			for (j = 0; j < L_MEANBUF; j++)
-			{
-				L_tmp += (isf_buf[j * M + i] << 14);
-			}
-			ref_isf[i] = vo_round(L_tmp);
-		}
+        if (enc_dec)
+        {
+            for (i = 0; i < M; i++)
+            {
+                for (j = (L_MEANBUF - 1); j > 0; j--)
+                {
+                    isf_buf[j * M + i] = isf_buf[(j - 1) * M + i];
+                }
+                isf_buf[i] = isf_q[i];
+            }
+        }
+    } else
+    {                                      /* bad frame */
+        for (i = 0; i < M; i++)
+        {
+            L_tmp = (mean_isf[i] << 14);
+            for (j = 0; j < L_MEANBUF; j++)
+            {
+                L_tmp += (isf_buf[j * M + i] << 14);
+            }
+            ref_isf[i] = vo_round(L_tmp);
+        }
 
-		/* use the past ISFs slightly shifted towards their mean */
-		for (i = 0; i < ORDER; i++)
-		{
-			isf_q[i] = add1(vo_mult(ALPHA, isfold[i]), vo_mult(ONE_ALPHA, ref_isf[i]));
-		}
+        /* use the past ISFs slightly shifted towards their mean */
+        for (i = 0; i < ORDER; i++)
+        {
+            isf_q[i] = add1(vo_mult(ALPHA, isfold[i]), vo_mult(ONE_ALPHA, ref_isf[i]));
+        }
 
-		/* estimate past quantized residual to be used in next frame */
-		for (i = 0; i < ORDER; i++)
-		{
-			tmp = add1(ref_isf[i], vo_mult(past_isfq[i], MU));      /* predicted ISF */
-			past_isfq[i] = vo_sub(isf_q[i], tmp);
-			past_isfq[i] = past_isfq[i] >> 1;         /* past_isfq[i] *= 0.5 */
-		}
-	}
+        /* estimate past quantized residual to be used in next frame */
+        for (i = 0; i < ORDER; i++)
+        {
+            tmp = add1(ref_isf[i], vo_mult(past_isfq[i], MU));      /* predicted ISF */
+            past_isfq[i] = vo_sub(isf_q[i], tmp);
+            past_isfq[i] = past_isfq[i] >> 1;         /* past_isfq[i] *= 0.5 */
+        }
+    }
 
-	Reorder_isf(isf_q, ISF_GAP, ORDER);
+    Reorder_isf(isf_q, ISF_GAP, ORDER);
 
-	return;
+    return;
 }
 
 
@@ -419,122 +419,122 @@
 ****************************************************************************/
 
 void Reorder_isf(
-		Word16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */
-		Word16 min_dist,                      /* (i) Q15  : minimum distance to keep             */
-		Word16 n                              /* (i)      : number of ISF                        */
-		)
+        Word16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */
+        Word16 min_dist,                      /* (i) Q15  : minimum distance to keep             */
+        Word16 n                              /* (i)      : number of ISF                        */
+        )
 {
-	Word32 i;
-	Word16 isf_min;
+    Word32 i;
+    Word16 isf_min;
 
-	isf_min = min_dist;
-	for (i = 0; i < n - 1; i++)
-	{
-		if(isf[i] < isf_min)
-		{
-			isf[i] = isf_min;
-		}
-		isf_min = (isf[i] + min_dist);
-	}
-	return;
+    isf_min = min_dist;
+    for (i = 0; i < n - 1; i++)
+    {
+        if(isf[i] < isf_min)
+        {
+            isf[i] = isf_min;
+        }
+        isf_min = (isf[i] + min_dist);
+    }
+    return;
 }
 
 
 Word16 Sub_VQ(                             /* output: return quantization index     */
-		Word16 * x,                           /* input : ISF residual vector           */
-		Word16 * dico,                        /* input : quantization codebook         */
-		Word16 dim,                           /* input : dimention of vector           */
-		Word16 dico_size,                     /* input : size of quantization codebook */
-		Word32 * distance                     /* output: error of quantization         */
-	     )
+        Word16 * x,                           /* input : ISF residual vector           */
+        Word16 * dico,                        /* input : quantization codebook         */
+        Word16 dim,                           /* input : dimention of vector           */
+        Word16 dico_size,                     /* input : size of quantization codebook */
+        Word32 * distance                     /* output: error of quantization         */
+         )
 {
-	Word16 temp, *p_dico;
-	Word32 i, j, index;
-	Word32 dist_min, dist;
+    Word16 temp, *p_dico;
+    Word32 i, j, index;
+    Word32 dist_min, dist;
 
-	dist_min = MAX_32;
-	p_dico = dico;
+    dist_min = MAX_32;
+    p_dico = dico;
 
-	index = 0;
-	for (i = 0; i < dico_size; i++)
-	{
-		dist = 0;
+    index = 0;
+    for (i = 0; i < dico_size; i++)
+    {
+        dist = 0;
 
-		for (j = 0; j < dim; j++)
-		{
-			temp = x[j] - (*p_dico++);
-			dist += (temp * temp)<<1;
-		}
+        for (j = 0; j < dim; j++)
+        {
+            temp = x[j] - (*p_dico++);
+            dist += (temp * temp)<<1;
+        }
 
-		if(dist < dist_min)
-		{
-			dist_min = dist;
-			index = i;
-		}
-	}
+        if(dist < dist_min)
+        {
+            dist_min = dist;
+            index = i;
+        }
+    }
 
-	*distance = dist_min;
+    *distance = dist_min;
 
-	/* Reading the selected vector */
-	p_dico = &dico[index * dim];
-	for (j = 0; j < dim; j++)
-	{
-		x[j] = *p_dico++;
-	}
+    /* Reading the selected vector */
+    p_dico = &dico[index * dim];
+    for (j = 0; j < dim; j++)
+    {
+        x[j] = *p_dico++;
+    }
 
-	return index;
+    return index;
 }
 
 
 static void VQ_stage1(
-		Word16 * x,                           /* input : ISF residual vector           */
-		Word16 * dico,                        /* input : quantization codebook         */
-		Word16 dim,                           /* input : dimention of vector           */
-		Word16 dico_size,                     /* input : size of quantization codebook */
-		Word16 * index,                       /* output: indices of survivors          */
-		Word16 surv                           /* input : number of survivor            */
-		)
+        Word16 * x,                           /* input : ISF residual vector           */
+        Word16 * dico,                        /* input : quantization codebook         */
+        Word16 dim,                           /* input : dimention of vector           */
+        Word16 dico_size,                     /* input : size of quantization codebook */
+        Word16 * index,                       /* output: indices of survivors          */
+        Word16 surv                           /* input : number of survivor            */
+        )
 {
-	Word16 temp, *p_dico;
-	Word32 i, j, k, l;
-	Word32 dist_min[N_SURV_MAX], dist;
+    Word16 temp, *p_dico;
+    Word32 i, j, k, l;
+    Word32 dist_min[N_SURV_MAX], dist;
 
-	dist_min[0] = MAX_32;
-	dist_min[1] = MAX_32;
-	dist_min[2] = MAX_32;
-	dist_min[3] = MAX_32;
-	index[0] = 0;
-	index[1] = 1;
-	index[2] = 2;
-	index[3] = 3;
+    dist_min[0] = MAX_32;
+    dist_min[1] = MAX_32;
+    dist_min[2] = MAX_32;
+    dist_min[3] = MAX_32;
+    index[0] = 0;
+    index[1] = 1;
+    index[2] = 2;
+    index[3] = 3;
 
-	p_dico = dico;
+    p_dico = dico;
 
-	for (i = 0; i < dico_size; i++)
-	{
-		dist = 0;
-		for (j = 0; j < dim; j++)
-		{
-			temp = x[j] -  (*p_dico++);
-			dist += (temp * temp)<<1;
-		}
+    for (i = 0; i < dico_size; i++)
+    {
+        dist = 0;
+        for (j = 0; j < dim; j++)
+        {
+            temp = x[j] -  (*p_dico++);
+            dist += (temp * temp)<<1;
+        }
 
-		for (k = 0; k < surv; k++)
-		{
-			if(dist < dist_min[k])
-			{
-				for (l = surv - 1; l > k; l--)
-				{
-					dist_min[l] = dist_min[l - 1];
-					index[l] = index[l - 1];
-				}
-				dist_min[k] = dist;
-				index[k] = i;
-				break;
-			}
-		}
-	}
-	return;
+        for (k = 0; k < surv; k++)
+        {
+            if(dist < dist_min[k])
+            {
+                for (l = surv - 1; l > k; l--)
+                {
+                    dist_min[l] = dist_min[l - 1];
+                    index[l] = index[l - 1];
+                }
+                dist_min[k] = dist;
+                index[k] = i;
+                break;
+            }
+        }
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/random.c b/media/libstagefright/codecs/amrwbenc/src/random.c
index b896863..758343c 100644
--- a/media/libstagefright/codecs/amrwbenc/src/random.c
+++ b/media/libstagefright/codecs/amrwbenc/src/random.c
@@ -26,8 +26,8 @@
 
 Word16 Random(Word16 * seed)
 {
-	/* static Word16 seed = 21845; */
-	*seed = (Word16)(L_add((L_mult(*seed, 31821) >> 1), 13849L));
-	return (*seed);
+    /* static Word16 seed = 21845; */
+    *seed = (Word16)(L_add((L_mult(*seed, 31821) >> 1), 13849L));
+    return (*seed);
 }
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/residu.c b/media/libstagefright/codecs/amrwbenc/src/residu.c
index b0c04b5..76d0e41 100644
--- a/media/libstagefright/codecs/amrwbenc/src/residu.c
+++ b/media/libstagefright/codecs/amrwbenc/src/residu.c
@@ -26,41 +26,41 @@
 #include "basic_op.h"
 
 void Residu(
-		Word16 a[],                           /* (i) Q12 : prediction coefficients                     */
-		Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */
-		Word16 y[],                           /* (o) x2  : residual signal                             */
-		Word16 lg                             /* (i)     : size of filtering                           */
-		)
+        Word16 a[],                           /* (i) Q12 : prediction coefficients                     */
+        Word16 x[],                           /* (i)     : speech (values x[-m..-1] are needed         */
+        Word16 y[],                           /* (o) x2  : residual signal                             */
+        Word16 lg                             /* (i)     : size of filtering                           */
+        )
 {
-	Word16 i,*p1, *p2;
-	Word32 s;
-	for (i = 0; i < lg; i++)
-	{
-		p1 = a;
-		p2 = &x[i];
-		s  = vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1++), (*p2--));
-		s += vo_mult32((*p1), (*p2));
+    Word16 i,*p1, *p2;
+    Word32 s;
+    for (i = 0; i < lg; i++)
+    {
+        p1 = a;
+        p2 = &x[i];
+        s  = vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1++), (*p2--));
+        s += vo_mult32((*p1), (*p2));
 
-		s = L_shl2(s, 5);
-		y[i] = extract_h(L_add(s, 0x8000));
-	}
+        s = L_shl2(s, 5);
+        y[i] = extract_h(L_add(s, 0x8000));
+    }
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/scale.c b/media/libstagefright/codecs/amrwbenc/src/scale.c
index 418cc06..21458c8 100644
--- a/media/libstagefright/codecs/amrwbenc/src/scale.c
+++ b/media/libstagefright/codecs/amrwbenc/src/scale.c
@@ -25,32 +25,32 @@
 #include "basic_op.h"
 
 void Scale_sig(
-		Word16 x[],                           /* (i/o) : signal to scale               */
-		Word16 lg,                            /* (i)   : size of x[]                   */
-		Word16 exp                            /* (i)   : exponent: x = round(x << exp) */
-	      )
+        Word16 x[],                           /* (i/o) : signal to scale               */
+        Word16 lg,                            /* (i)   : size of x[]                   */
+        Word16 exp                            /* (i)   : exponent: x = round(x << exp) */
+          )
 {
-	Word32 i;
-	Word32 L_tmp;
-	if(exp > 0)
-	{
-		for (i = lg - 1 ; i >= 0; i--)
-		{
-			L_tmp = L_shl2(x[i], 16 + exp);
-			x[i] = extract_h(L_add(L_tmp, 0x8000));
-		}
-	}
-	else
-	{
-		exp = -exp;
-		for (i = lg - 1; i >= 0; i--)
-		{
-			L_tmp = x[i] << 16;
-			L_tmp >>= exp;
-			x[i] = (L_tmp + 0x8000)>>16;
-		}
-	}
-	return;
+    Word32 i;
+    Word32 L_tmp;
+    if(exp > 0)
+    {
+        for (i = lg - 1 ; i >= 0; i--)
+        {
+            L_tmp = L_shl2(x[i], 16 + exp);
+            x[i] = extract_h(L_add(L_tmp, 0x8000));
+        }
+    }
+    else
+    {
+        exp = -exp;
+        for (i = lg - 1; i >= 0; i--)
+        {
+            L_tmp = x[i] << 16;
+            L_tmp >>= exp;
+            x[i] = (L_tmp + 0x8000)>>16;
+        }
+    }
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/stream.c b/media/libstagefright/codecs/amrwbenc/src/stream.c
index 780f009..a39149e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/stream.c
+++ b/media/libstagefright/codecs/amrwbenc/src/stream.c
@@ -25,34 +25,34 @@
 
 void voAWB_InitFrameBuffer(FrameStream *stream)
 {
-	stream->set_ptr = NULL;
-	stream->frame_ptr_bk = stream->frame_ptr;
-	stream->set_len = 0;
-	stream->framebuffer_len = 0;
-	stream->frame_storelen = 0;
+    stream->set_ptr = NULL;
+    stream->frame_ptr_bk = stream->frame_ptr;
+    stream->set_len = 0;
+    stream->framebuffer_len = 0;
+    stream->frame_storelen = 0;
 }
 
 void voAWB_UpdateFrameBuffer(
-		FrameStream *stream,
-		VO_MEM_OPERATOR *pMemOP
-		)
+        FrameStream *stream,
+        VO_MEM_OPERATOR *pMemOP
+        )
 {
-	int  len;
-	len  = MIN(Frame_Maxsize - stream->frame_storelen, stream->set_len);
-	pMemOP->Copy(VO_INDEX_ENC_AMRWB, stream->frame_ptr_bk + stream->frame_storelen , stream->set_ptr, len);
-	stream->set_len -= len;
-	stream->set_ptr += len;
-	stream->framebuffer_len = stream->frame_storelen + len;
-	stream->frame_ptr = stream->frame_ptr_bk;
-	stream->used_len += len;
+    int  len;
+    len  = MIN(Frame_Maxsize - stream->frame_storelen, stream->set_len);
+    pMemOP->Copy(VO_INDEX_ENC_AMRWB, stream->frame_ptr_bk + stream->frame_storelen , stream->set_ptr, len);
+    stream->set_len -= len;
+    stream->set_ptr += len;
+    stream->framebuffer_len = stream->frame_storelen + len;
+    stream->frame_ptr = stream->frame_ptr_bk;
+    stream->used_len += len;
 }
 
 void voAWB_FlushFrameBuffer(FrameStream *stream)
 {
-	stream->set_ptr = NULL;
-	stream->frame_ptr_bk = stream->frame_ptr;
-	stream->set_len = 0;
-	stream->framebuffer_len = 0;
-	stream->frame_storelen = 0;
+    stream->set_ptr = NULL;
+    stream->frame_ptr_bk = stream->frame_ptr;
+    stream->set_len = 0;
+    stream->framebuffer_len = 0;
+    stream->frame_storelen = 0;
 }
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/syn_filt.c b/media/libstagefright/codecs/amrwbenc/src/syn_filt.c
index 961aadc..7eba12f 100644
--- a/media/libstagefright/codecs/amrwbenc/src/syn_filt.c
+++ b/media/libstagefright/codecs/amrwbenc/src/syn_filt.c
@@ -29,134 +29,134 @@
 #define UNUSED(x) (void)(x)
 
 void Syn_filt(
-		Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
-		Word16 x[],                           /* (i)     : input signal                             */
-		Word16 y[],                           /* (o)     : output signal                            */
-		Word16 lg,                            /* (i)     : size of filtering                        */
-		Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */
-		Word16 update                         /* (i)     : 0=no update, 1=update of memory.         */
-	     )
+        Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
+        Word16 x[],                           /* (i)     : input signal                             */
+        Word16 y[],                           /* (o)     : output signal                            */
+        Word16 lg,                            /* (i)     : size of filtering                        */
+        Word16 mem[],                         /* (i/o)   : memory associated with this filtering.   */
+        Word16 update                         /* (i)     : 0=no update, 1=update of memory.         */
+         )
 {
-	Word32 i, a0;
-	Word16 y_buf[L_SUBFR16k + M16k];
-	Word32 L_tmp;
-	Word16 *yy, *p1, *p2;
-	yy = &y_buf[0];
-	/* copy initial filter states into synthesis buffer */
-	for (i = 0; i < 16; i++)
-	{
-		*yy++ = mem[i];
-	}
-	a0 = (a[0] >> 1);                     /* input / 2 */
-	/* Do the filtering. */
-	for (i = 0; i < lg; i++)
-	{
-		p1 = &a[1];
-		p2 = &yy[i-1];
-		L_tmp  = vo_mult32(a0, x[i]);
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1++), (*p2--));
-		L_tmp -= vo_mult32((*p1), (*p2));
+    Word32 i, a0;
+    Word16 y_buf[L_SUBFR16k + M16k];
+    Word32 L_tmp;
+    Word16 *yy, *p1, *p2;
+    yy = &y_buf[0];
+    /* copy initial filter states into synthesis buffer */
+    for (i = 0; i < 16; i++)
+    {
+        *yy++ = mem[i];
+    }
+    a0 = (a[0] >> 1);                     /* input / 2 */
+    /* Do the filtering. */
+    for (i = 0; i < lg; i++)
+    {
+        p1 = &a[1];
+        p2 = &yy[i-1];
+        L_tmp  = vo_mult32(a0, x[i]);
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1++), (*p2--));
+        L_tmp -= vo_mult32((*p1), (*p2));
 
-		L_tmp = L_shl2(L_tmp, 4);
-		y[i] = yy[i] = extract_h(L_add(L_tmp, 0x8000));
-	}
-	/* Update memory if required */
-	if (update)
-		for (i = 0; i < 16; i++)
-		{
-			mem[i] = yy[lg - 16 + i];
-		}
-	return;
+        L_tmp = L_shl2(L_tmp, 4);
+        y[i] = yy[i] = extract_h(L_add(L_tmp, 0x8000));
+    }
+    /* Update memory if required */
+    if (update)
+        for (i = 0; i < 16; i++)
+        {
+            mem[i] = yy[lg - 16 + i];
+        }
+    return;
 }
 
 
 void Syn_filt_32(
-		Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
-		Word16 m,                             /* (i)     : order of LP filter             */
-		Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
-		Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
-		Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
-		Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
-		Word16 lg                             /* (i)     : size of filtering              */
-		)
+        Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
+        Word16 m,                             /* (i)     : order of LP filter             */
+        Word16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+        Word16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
+        Word16 sig_hi[],                      /* (o) /16 : synthesis high                 */
+        Word16 sig_lo[],                      /* (o) /16 : synthesis low                  */
+        Word16 lg                             /* (i)     : size of filtering              */
+        )
 {
-	Word32 i,a0;
-	Word32 L_tmp, L_tmp1;
-	Word16 *p1, *p2, *p3;
+    Word32 i,a0;
+    Word32 L_tmp, L_tmp1;
+    Word16 *p1, *p2, *p3;
         UNUSED(m);
 
-	a0 = a[0] >> (4 + Qnew);          /* input / 16 and >>Qnew */
-	/* Do the filtering. */
-	for (i = 0; i < lg; i++)
-	{
-		L_tmp  = 0;
-		L_tmp1 = 0;
-		p1 = a;
-		p2 = &sig_lo[i - 1];
-		p3 = &sig_hi[i - 1];
+    a0 = a[0] >> (4 + Qnew);          /* input / 16 and >>Qnew */
+    /* Do the filtering. */
+    for (i = 0; i < lg; i++)
+    {
+        L_tmp  = 0;
+        L_tmp1 = 0;
+        p1 = a;
+        p2 = &sig_lo[i - 1];
+        p3 = &sig_hi[i - 1];
 
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
-		L_tmp  -= vo_mult32((*p2--), (*p1));
-		L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
+        L_tmp  -= vo_mult32((*p2--), (*p1));
+        L_tmp1 -= vo_mult32((*p3--), (*p1++));
 
-		L_tmp = L_tmp >> 11;
-		L_tmp += vo_L_mult(exc[i], a0);
+        L_tmp = L_tmp >> 11;
+        L_tmp += vo_L_mult(exc[i], a0);
 
-		/* sig_hi = bit16 to bit31 of synthesis */
-		L_tmp = L_tmp - (L_tmp1<<1);
+        /* sig_hi = bit16 to bit31 of synthesis */
+        L_tmp = L_tmp - (L_tmp1<<1);
 
-		L_tmp = L_tmp >> 3;           /* ai in Q12 */
-		sig_hi[i] = extract_h(L_tmp);
+        L_tmp = L_tmp >> 3;           /* ai in Q12 */
+        sig_hi[i] = extract_h(L_tmp);
 
-		/* sig_lo = bit4 to bit15 of synthesis */
-		L_tmp >>= 4;           /* 4 : sig_lo[i] >> 4 */
-		sig_lo[i] = (Word16)((L_tmp - (sig_hi[i] << 13)));
-	}
+        /* sig_lo = bit4 to bit15 of synthesis */
+        L_tmp >>= 4;           /* 4 : sig_lo[i] >> 4 */
+        sig_lo[i] = (Word16)((L_tmp - (sig_hi[i] << 13)));
+    }
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/updt_tar.c b/media/libstagefright/codecs/amrwbenc/src/updt_tar.c
index 96779fd..ba7c2ff 100644
--- a/media/libstagefright/codecs/amrwbenc/src/updt_tar.c
+++ b/media/libstagefright/codecs/amrwbenc/src/updt_tar.c
@@ -25,24 +25,25 @@
 #include "basic_op.h"
 
 void Updt_tar(
-		Word16 * x,                           /* (i) Q0  : old target (for pitch search)     */
-		Word16 * x2,                          /* (o) Q0  : new target (for codebook search)  */
-		Word16 * y,                           /* (i) Q0  : filtered adaptive codebook vector */
-		Word16 gain,                          /* (i) Q14 : adaptive codebook gain            */
-		Word16 L                              /* (i)     : subframe size                     */
-	     )
+        Word16 * x,                           /* (i) Q0  : old target (for pitch search)     */
+        Word16 * x2,                          /* (o) Q0  : new target (for codebook search)  */
+        Word16 * y,                           /* (i) Q0  : filtered adaptive codebook vector */
+        Word16 gain,                          /* (i) Q14 : adaptive codebook gain            */
+        Word16 L                              /* (i)     : subframe size                     */
+         )
 {
-	Word32 i;
-	Word32 L_tmp;
+    Word32 i;
+    Word32 L_tmp, L_tmp2;
 
-	for (i = 0; i < L; i++)
-	{
-		L_tmp = x[i] << 15;
-		L_tmp -= (y[i] * gain)<<1;
-		x2[i] = extract_h(L_shl2(L_tmp, 1));
-	}
+    for (i = 0; i < L; i++)
+    {
+        L_tmp = x[i] << 15;
+        L_tmp2 = L_mult(y[i], gain);
+        L_tmp = L_sub(L_tmp, L_tmp2);
+        x2[i] = extract_h(L_shl2(L_tmp, 1));
+    }
 
-	return;
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/util.c b/media/libstagefright/codecs/amrwbenc/src/util.c
index 333140d..374245f 100644
--- a/media/libstagefright/codecs/amrwbenc/src/util.c
+++ b/media/libstagefright/codecs/amrwbenc/src/util.c
@@ -30,15 +30,15 @@
 ************************************************************************/
 
 void Set_zero(
-		Word16 x[],                           /* (o)    : vector to clear     */
-		Word16 L                              /* (i)    : length of vector    */
-	     )
+        Word16 x[],                           /* (o)    : vector to clear     */
+        Word16 L                              /* (i)    : length of vector    */
+         )
 {
-	Word32 num = (Word32)L;
-	while (num > 0) {
-		*x++ = 0;
+    Word32 num = (Word32)L;
+    while (num > 0) {
+        *x++ = 0;
                 --num;
-	}
+    }
 }
 
 
@@ -49,28 +49,28 @@
 *********************************************************************/
 
 void Copy(
-		Word16 x[],                           /* (i)   : input vector   */
-		Word16 y[],                           /* (o)   : output vector  */
-		Word16 L                              /* (i)   : vector length  */
-	 )
+        Word16 x[],                           /* (i)   : input vector   */
+        Word16 y[],                           /* (o)   : output vector  */
+        Word16 L                              /* (i)   : vector length  */
+     )
 {
-	Word32	temp1,temp2,num;
+    Word32  temp1,temp2,num;
         if (L <= 0) {
                 return;
         }
-	if(L&1)
-	{
-		temp1 = *x++;
-		*y++ = temp1;
-	}
-	num = (Word32)(L>>1);
-	while (num > 0) {
-		temp1 = *x++;
-		temp2 = *x++;
-		*y++ = temp1;
-		*y++ = temp2;
+    if(L&1)
+    {
+        temp1 = *x++;
+        *y++ = temp1;
+    }
+    num = (Word32)(L>>1);
+    while (num > 0) {
+        temp1 = *x++;
+        temp2 = *x++;
+        *y++ = temp1;
+        *y++ = temp2;
                 --num;
-	}
+    }
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c b/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
index df7b9b3..b908ff8 100644
--- a/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
+++ b/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
@@ -19,8 +19,8 @@
 *                                                                      *
 *      Description: Performs the main encoder routine                  *
 *                   Fixed-point C simulation of AMR WB ACELP coding    *
-*		    algorithm with 20 msspeech frames for              *
-*		    wideband speech signals.                           *
+*           algorithm with 20 msspeech frames for              *
+*           wideband speech signals.                           *
 *                                                                      *
 ************************************************************************/
 
@@ -51,95 +51,95 @@
 /* isp tables for initialization */
 static Word16 isp_init[M] =
 {
-	32138, 30274, 27246, 23170, 18205, 12540, 6393, 0,
-	-6393, -12540, -18205, -23170, -27246, -30274, -32138, 1475
+    32138, 30274, 27246, 23170, 18205, 12540, 6393, 0,
+    -6393, -12540, -18205, -23170, -27246, -30274, -32138, 1475
 };
 
 static Word16 isf_init[M] =
 {
-	1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192,
-	9216, 10240, 11264, 12288, 13312, 14336, 15360, 3840
+    1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192,
+    9216, 10240, 11264, 12288, 13312, 14336, 15360, 3840
 };
 
 /* High Band encoding */
 static const Word16 HP_gain[16] =
 {
-	3624, 4673, 5597, 6479, 7425, 8378, 9324, 10264,
-	11210, 12206, 13391, 14844, 16770, 19655, 24289, 32728
+    3624, 4673, 5597, 6479, 7425, 8378, 9324, 10264,
+    11210, 12206, 13391, 14844, 16770, 19655, 24289, 32728
 };
 
 /* Private function declaration */
 static Word16 synthesis(
-			Word16 Aq[],                          /* A(z)  : quantized Az               */
-			Word16 exc[],                         /* (i)   : excitation at 12kHz        */
-			Word16 Q_new,                         /* (i)   : scaling performed on exc   */
-			Word16 synth16k[],                    /* (o)   : 16kHz synthesis signal     */
-			Coder_State * st                      /* (i/o) : State structure            */
-			);
+            Word16 Aq[],                          /* A(z)  : quantized Az               */
+            Word16 exc[],                         /* (i)   : excitation at 12kHz        */
+            Word16 Q_new,                         /* (i)   : scaling performed on exc   */
+            Word16 synth16k[],                    /* (o)   : 16kHz synthesis signal     */
+            Coder_State * st                      /* (i/o) : State structure            */
+            );
 
 /* Codec some parameters initialization */
 void Reset_encoder(void *st, Word16 reset_all)
 {
-	Word16 i;
-	Coder_State *cod_state;
-	cod_state = (Coder_State *) st;
-	Set_zero(cod_state->old_exc, PIT_MAX + L_INTERPOL);
-	Set_zero(cod_state->mem_syn, M);
-	Set_zero(cod_state->past_isfq, M);
-	cod_state->mem_w0 = 0;
-	cod_state->tilt_code = 0;
-	cod_state->first_frame = 1;
-	Init_gp_clip(cod_state->gp_clip);
-	cod_state->L_gc_thres = 0;
-	if (reset_all != 0)
-	{
-		/* Static vectors to zero */
-		Set_zero(cod_state->old_speech, L_TOTAL - L_FRAME);
-		Set_zero(cod_state->old_wsp, (PIT_MAX / OPL_DECIM));
-		Set_zero(cod_state->mem_decim2, 3);
-		/* routines initialization */
-		Init_Decim_12k8(cod_state->mem_decim);
-		Init_HP50_12k8(cod_state->mem_sig_in);
-		Init_Levinson(cod_state->mem_levinson);
-		Init_Q_gain2(cod_state->qua_gain);
-		Init_Hp_wsp(cod_state->hp_wsp_mem);
-		/* isp initialization */
-		Copy(isp_init, cod_state->ispold, M);
-		Copy(isp_init, cod_state->ispold_q, M);
-		/* variable initialization */
-		cod_state->mem_preemph = 0;
-		cod_state->mem_wsp = 0;
-		cod_state->Q_old = 15;
-		cod_state->Q_max[0] = 15;
-		cod_state->Q_max[1] = 15;
-		cod_state->old_wsp_max = 0;
-		cod_state->old_wsp_shift = 0;
-		/* pitch ol initialization */
-		cod_state->old_T0_med = 40;
-		cod_state->ol_gain = 0;
-		cod_state->ada_w = 0;
-		cod_state->ol_wght_flg = 0;
-		for (i = 0; i < 5; i++)
-		{
-			cod_state->old_ol_lag[i] = 40;
-		}
-		Set_zero(cod_state->old_hp_wsp, (L_FRAME / 2) / OPL_DECIM + (PIT_MAX / OPL_DECIM));
-		Set_zero(cod_state->mem_syn_hf, M);
-		Set_zero(cod_state->mem_syn_hi, M);
-		Set_zero(cod_state->mem_syn_lo, M);
-		Init_HP50_12k8(cod_state->mem_sig_out);
-		Init_Filt_6k_7k(cod_state->mem_hf);
-		Init_HP400_12k8(cod_state->mem_hp400);
-		Copy(isf_init, cod_state->isfold, M);
-		cod_state->mem_deemph = 0;
-		cod_state->seed2 = 21845;
-		Init_Filt_6k_7k(cod_state->mem_hf2);
-		cod_state->gain_alpha = 32767;
-		cod_state->vad_hist = 0;
-		wb_vad_reset(cod_state->vadSt);
-		dtx_enc_reset(cod_state->dtx_encSt, isf_init);
-	}
-	return;
+    Word16 i;
+    Coder_State *cod_state;
+    cod_state = (Coder_State *) st;
+    Set_zero(cod_state->old_exc, PIT_MAX + L_INTERPOL);
+    Set_zero(cod_state->mem_syn, M);
+    Set_zero(cod_state->past_isfq, M);
+    cod_state->mem_w0 = 0;
+    cod_state->tilt_code = 0;
+    cod_state->first_frame = 1;
+    Init_gp_clip(cod_state->gp_clip);
+    cod_state->L_gc_thres = 0;
+    if (reset_all != 0)
+    {
+        /* Static vectors to zero */
+        Set_zero(cod_state->old_speech, L_TOTAL - L_FRAME);
+        Set_zero(cod_state->old_wsp, (PIT_MAX / OPL_DECIM));
+        Set_zero(cod_state->mem_decim2, 3);
+        /* routines initialization */
+        Init_Decim_12k8(cod_state->mem_decim);
+        Init_HP50_12k8(cod_state->mem_sig_in);
+        Init_Levinson(cod_state->mem_levinson);
+        Init_Q_gain2(cod_state->qua_gain);
+        Init_Hp_wsp(cod_state->hp_wsp_mem);
+        /* isp initialization */
+        Copy(isp_init, cod_state->ispold, M);
+        Copy(isp_init, cod_state->ispold_q, M);
+        /* variable initialization */
+        cod_state->mem_preemph = 0;
+        cod_state->mem_wsp = 0;
+        cod_state->Q_old = 15;
+        cod_state->Q_max[0] = 15;
+        cod_state->Q_max[1] = 15;
+        cod_state->old_wsp_max = 0;
+        cod_state->old_wsp_shift = 0;
+        /* pitch ol initialization */
+        cod_state->old_T0_med = 40;
+        cod_state->ol_gain = 0;
+        cod_state->ada_w = 0;
+        cod_state->ol_wght_flg = 0;
+        for (i = 0; i < 5; i++)
+        {
+            cod_state->old_ol_lag[i] = 40;
+        }
+        Set_zero(cod_state->old_hp_wsp, (L_FRAME / 2) / OPL_DECIM + (PIT_MAX / OPL_DECIM));
+        Set_zero(cod_state->mem_syn_hf, M);
+        Set_zero(cod_state->mem_syn_hi, M);
+        Set_zero(cod_state->mem_syn_lo, M);
+        Init_HP50_12k8(cod_state->mem_sig_out);
+        Init_Filt_6k_7k(cod_state->mem_hf);
+        Init_HP400_12k8(cod_state->mem_hp400);
+        Copy(isf_init, cod_state->isfold, M);
+        cod_state->mem_deemph = 0;
+        cod_state->seed2 = 21845;
+        Init_Filt_6k_7k(cod_state->mem_hf2);
+        cod_state->gain_alpha = 32767;
+        cod_state->vad_hist = 0;
+        wb_vad_reset(cod_state->vadSt);
+        dtx_enc_reset(cod_state->dtx_encSt, isf_init);
+    }
+    return;
 }
 
 /*-----------------------------------------------------------------*
@@ -149,1176 +149,1180 @@
 *                                                                 *
 *-----------------------------------------------------------------*/
 void coder(
-		Word16 * mode,                        /* input :  used mode                             */
-		Word16 speech16k[],                   /* input :  320 new speech samples (at 16 kHz)    */
-		Word16 prms[],                        /* output:  output parameters                     */
-		Word16 * ser_size,                    /* output:  bit rate of the used mode             */
-		void *spe_state,                      /* i/o   :  State structure                       */
-		Word16 allow_dtx                      /* input :  DTX ON/OFF                            */
-	  )
+        Word16 * mode,                        /* input :  used mode                             */
+        Word16 speech16k[],                   /* input :  320 new speech samples (at 16 kHz)    */
+        Word16 prms[],                        /* output:  output parameters                     */
+        Word16 * ser_size,                    /* output:  bit rate of the used mode             */
+        void *spe_state,                      /* i/o   :  State structure                       */
+        Word16 allow_dtx                      /* input :  DTX ON/OFF                            */
+      )
 {
-	/* Coder states */
-	Coder_State *st;
-	/* Speech vector */
-	Word16 old_speech[L_TOTAL];
-	Word16 *new_speech, *speech, *p_window;
+    /* Coder states */
+    Coder_State *st;
+    /* Speech vector */
+    Word16 old_speech[L_TOTAL];
+    Word16 *new_speech, *speech, *p_window;
 
-	/* Weighted speech vector */
-	Word16 old_wsp[L_FRAME + (PIT_MAX / OPL_DECIM)];
-	Word16 *wsp;
+    /* Weighted speech vector */
+    Word16 old_wsp[L_FRAME + (PIT_MAX / OPL_DECIM)];
+    Word16 *wsp;
 
-	/* Excitation vector */
-	Word16 old_exc[(L_FRAME + 1) + PIT_MAX + L_INTERPOL];
-	Word16 *exc;
+    /* Excitation vector */
+    Word16 old_exc[(L_FRAME + 1) + PIT_MAX + L_INTERPOL];
+    Word16 *exc;
 
-	/* LPC coefficients */
-	Word16 r_h[M + 1], r_l[M + 1];         /* Autocorrelations of windowed speech  */
-	Word16 rc[M];                          /* Reflection coefficients.             */
-	Word16 Ap[M + 1];                      /* A(z) with spectral expansion         */
-	Word16 ispnew[M];                      /* immittance spectral pairs at 4nd sfr */
-	Word16 ispnew_q[M];                    /* quantized ISPs at 4nd subframe       */
-	Word16 isf[M];                         /* ISF (frequency domain) at 4nd sfr    */
-	Word16 *p_A, *p_Aq;                    /* ptr to A(z) for the 4 subframes      */
-	Word16 A[NB_SUBFR * (M + 1)];          /* A(z) unquantized for the 4 subframes */
-	Word16 Aq[NB_SUBFR * (M + 1)];         /* A(z)   quantized for the 4 subframes */
+    /* LPC coefficients */
+    Word16 r_h[M + 1], r_l[M + 1];         /* Autocorrelations of windowed speech  */
+    Word16 rc[M];                          /* Reflection coefficients.             */
+    Word16 Ap[M + 1];                      /* A(z) with spectral expansion         */
+    Word16 ispnew[M];                      /* immittance spectral pairs at 4nd sfr */
+    Word16 ispnew_q[M];                    /* quantized ISPs at 4nd subframe       */
+    Word16 isf[M];                         /* ISF (frequency domain) at 4nd sfr    */
+    Word16 *p_A, *p_Aq;                    /* ptr to A(z) for the 4 subframes      */
+    Word16 A[NB_SUBFR * (M + 1)];          /* A(z) unquantized for the 4 subframes */
+    Word16 Aq[NB_SUBFR * (M + 1)];         /* A(z)   quantized for the 4 subframes */
 
-	/* Other vectors */
-	Word16 xn[L_SUBFR];                    /* Target vector for pitch search     */
-	Word16 xn2[L_SUBFR];                   /* Target vector for codebook search  */
-	Word16 dn[L_SUBFR];                    /* Correlation between xn2 and h1     */
-	Word16 cn[L_SUBFR];                    /* Target vector in residual domain   */
-	Word16 h1[L_SUBFR];                    /* Impulse response vector            */
-	Word16 h2[L_SUBFR];                    /* Impulse response vector            */
-	Word16 code[L_SUBFR];                  /* Fixed codebook excitation          */
-	Word16 y1[L_SUBFR];                    /* Filtered adaptive excitation       */
-	Word16 y2[L_SUBFR];                    /* Filtered adaptive excitation       */
-	Word16 error[M + L_SUBFR];             /* error of quantization              */
-	Word16 synth[L_SUBFR];                 /* 12.8kHz synthesis vector           */
-	Word16 exc2[L_FRAME];                  /* excitation vector                  */
-	Word16 buf[L_FRAME];                   /* VAD buffer                         */
+    /* Other vectors */
+    Word16 xn[L_SUBFR];                    /* Target vector for pitch search     */
+    Word16 xn2[L_SUBFR];                   /* Target vector for codebook search  */
+    Word16 dn[L_SUBFR];                    /* Correlation between xn2 and h1     */
+    Word16 cn[L_SUBFR];                    /* Target vector in residual domain   */
+    Word16 h1[L_SUBFR];                    /* Impulse response vector            */
+    Word16 h2[L_SUBFR];                    /* Impulse response vector            */
+    Word16 code[L_SUBFR];                  /* Fixed codebook excitation          */
+    Word16 y1[L_SUBFR];                    /* Filtered adaptive excitation       */
+    Word16 y2[L_SUBFR];                    /* Filtered adaptive excitation       */
+    Word16 error[M + L_SUBFR];             /* error of quantization              */
+    Word16 synth[L_SUBFR];                 /* 12.8kHz synthesis vector           */
+    Word16 exc2[L_FRAME];                  /* excitation vector                  */
+    Word16 buf[L_FRAME];                   /* VAD buffer                         */
 
-	/* Scalars */
-	Word32 i, j, i_subfr, select, pit_flag, clip_gain, vad_flag;
-	Word16 codec_mode;
-	Word16 T_op, T_op2, T0, T0_min, T0_max, T0_frac, index;
-	Word16 gain_pit, gain_code, g_coeff[4], g_coeff2[4];
-	Word16 tmp, gain1, gain2, exp, Q_new, mu, shift, max;
-	Word16 voice_fac;
-	Word16 indice[8];
-	Word32 L_tmp, L_gain_code, L_max, L_tmp1;
-	Word16 code2[L_SUBFR];                         /* Fixed codebook excitation  */
-	Word16 stab_fac, fac, gain_code_lo;
+    /* Scalars */
+    Word32 i, j, i_subfr, select, pit_flag, clip_gain, vad_flag;
+    Word16 codec_mode;
+    Word16 T_op, T_op2, T0, T0_min, T0_max, T0_frac, index;
+    Word16 gain_pit, gain_code, g_coeff[4], g_coeff2[4];
+    Word16 tmp, gain1, gain2, exp, Q_new, mu, shift, max;
+    Word16 voice_fac;
+    Word16 indice[8];
+    Word32 L_tmp, L_gain_code, L_max, L_tmp1;
+    Word16 code2[L_SUBFR];                         /* Fixed codebook excitation  */
+    Word16 stab_fac, fac, gain_code_lo;
 
-	Word16 corr_gain;
-	Word16 *vo_p0, *vo_p1, *vo_p2, *vo_p3;
+    Word16 corr_gain;
+    Word16 *vo_p0, *vo_p1, *vo_p2, *vo_p3;
 
-	st = (Coder_State *) spe_state;
+    st = (Coder_State *) spe_state;
 
-	*ser_size = nb_of_bits[*mode];
-	codec_mode = *mode;
+    *ser_size = nb_of_bits[*mode];
+    codec_mode = *mode;
 
-	/*--------------------------------------------------------------------------*
-	 *          Initialize pointers to speech vector.                           *
-	 *                                                                          *
-	 *                                                                          *
-	 *                    |-------|-------|-------|-------|-------|-------|     *
-	 *                     past sp   sf1     sf2     sf3     sf4    L_NEXT      *
-	 *                    <-------  Total speech buffer (L_TOTAL)   ------>     *
-	 *              old_speech                                                  *
-	 *                    <-------  LPC analysis window (L_WINDOW)  ------>     *
-	 *                    |       <-- present frame (L_FRAME) ---->             *
-	 *                   p_window |       <----- new speech (L_FRAME) ---->     *
-	 *                            |       |                                     *
-	 *                          speech    |                                     *
-	 *                                 new_speech                               *
-	 *--------------------------------------------------------------------------*/
+    /*--------------------------------------------------------------------------*
+     *          Initialize pointers to speech vector.                           *
+     *                                                                          *
+     *                                                                          *
+     *                    |-------|-------|-------|-------|-------|-------|     *
+     *                     past sp   sf1     sf2     sf3     sf4    L_NEXT      *
+     *                    <-------  Total speech buffer (L_TOTAL)   ------>     *
+     *              old_speech                                                  *
+     *                    <-------  LPC analysis window (L_WINDOW)  ------>     *
+     *                    |       <-- present frame (L_FRAME) ---->             *
+     *                   p_window |       <----- new speech (L_FRAME) ---->     *
+     *                            |       |                                     *
+     *                          speech    |                                     *
+     *                                 new_speech                               *
+     *--------------------------------------------------------------------------*/
 
-	new_speech = old_speech + L_TOTAL - L_FRAME - L_FILT;         /* New speech     */
-	speech = old_speech + L_TOTAL - L_FRAME - L_NEXT;             /* Present frame  */
-	p_window = old_speech + L_TOTAL - L_WINDOW;
+    new_speech = old_speech + L_TOTAL - L_FRAME - L_FILT;         /* New speech     */
+    speech = old_speech + L_TOTAL - L_FRAME - L_NEXT;             /* Present frame  */
+    p_window = old_speech + L_TOTAL - L_WINDOW;
 
-	exc = old_exc + PIT_MAX + L_INTERPOL;
-	wsp = old_wsp + (PIT_MAX / OPL_DECIM);
+    exc = old_exc + PIT_MAX + L_INTERPOL;
+    wsp = old_wsp + (PIT_MAX / OPL_DECIM);
 
-	/* copy coder memory state into working space */
-	Copy(st->old_speech, old_speech, L_TOTAL - L_FRAME);
-	Copy(st->old_wsp, old_wsp, PIT_MAX / OPL_DECIM);
-	Copy(st->old_exc, old_exc, PIT_MAX + L_INTERPOL);
+    /* copy coder memory state into working space */
+    Copy(st->old_speech, old_speech, L_TOTAL - L_FRAME);
+    Copy(st->old_wsp, old_wsp, PIT_MAX / OPL_DECIM);
+    Copy(st->old_exc, old_exc, PIT_MAX + L_INTERPOL);
 
-	/*---------------------------------------------------------------*
-	 * Down sampling signal from 16kHz to 12.8kHz                    *
-	 * -> The signal is extended by L_FILT samples (padded to zero)  *
-	 * to avoid additional delay (L_FILT samples) in the coder.      *
-	 * The last L_FILT samples are approximated after decimation and *
-	 * are used (and windowed) only in autocorrelations.             *
-	 *---------------------------------------------------------------*/
+    /*---------------------------------------------------------------*
+     * Down sampling signal from 16kHz to 12.8kHz                    *
+     * -> The signal is extended by L_FILT samples (padded to zero)  *
+     * to avoid additional delay (L_FILT samples) in the coder.      *
+     * The last L_FILT samples are approximated after decimation and *
+     * are used (and windowed) only in autocorrelations.             *
+     *---------------------------------------------------------------*/
 
-	Decim_12k8(speech16k, L_FRAME16k, new_speech, st->mem_decim);
+    Decim_12k8(speech16k, L_FRAME16k, new_speech, st->mem_decim);
 
-	/* last L_FILT samples for autocorrelation window */
-	Copy(st->mem_decim, code, 2 * L_FILT16k);
-	Set_zero(error, L_FILT16k);            /* set next sample to zero */
-	Decim_12k8(error, L_FILT16k, new_speech + L_FRAME, code);
+    /* last L_FILT samples for autocorrelation window */
+    Copy(st->mem_decim, code, 2 * L_FILT16k);
+    Set_zero(error, L_FILT16k);            /* set next sample to zero */
+    Decim_12k8(error, L_FILT16k, new_speech + L_FRAME, code);
 
-	/*---------------------------------------------------------------*
-	 * Perform 50Hz HP filtering of input signal.                    *
-	 *---------------------------------------------------------------*/
+    /*---------------------------------------------------------------*
+     * Perform 50Hz HP filtering of input signal.                    *
+     *---------------------------------------------------------------*/
 
-	HP50_12k8(new_speech, L_FRAME, st->mem_sig_in);
+    HP50_12k8(new_speech, L_FRAME, st->mem_sig_in);
 
-	/* last L_FILT samples for autocorrelation window */
-	Copy(st->mem_sig_in, code, 6);
-	HP50_12k8(new_speech + L_FRAME, L_FILT, code);
+    /* last L_FILT samples for autocorrelation window */
+    Copy(st->mem_sig_in, code, 6);
+    HP50_12k8(new_speech + L_FRAME, L_FILT, code);
 
-	/*---------------------------------------------------------------*
-	 * Perform fixed preemphasis through 1 - g z^-1                  *
-	 * Scale signal to get maximum of precision in filtering         *
-	 *---------------------------------------------------------------*/
+    /*---------------------------------------------------------------*
+     * Perform fixed preemphasis through 1 - g z^-1                  *
+     * Scale signal to get maximum of precision in filtering         *
+     *---------------------------------------------------------------*/
 
-	mu = PREEMPH_FAC >> 1;              /* Q15 --> Q14 */
+    mu = PREEMPH_FAC >> 1;              /* Q15 --> Q14 */
 
-	/* get max of new preemphased samples (L_FRAME+L_FILT) */
-	L_tmp = new_speech[0] << 15;
-	L_tmp -= (st->mem_preemph * mu)<<1;
-	L_max = L_abs(L_tmp);
+    /* get max of new preemphased samples (L_FRAME+L_FILT) */
+    L_tmp = new_speech[0] << 15;
+    L_tmp -= (st->mem_preemph * mu)<<1;
+    L_max = L_abs(L_tmp);
 
-	for (i = 1; i < L_FRAME + L_FILT; i++)
-	{
-		L_tmp = new_speech[i] << 15;
-		L_tmp -= (new_speech[i - 1] * mu)<<1;
-		L_tmp = L_abs(L_tmp);
-		if(L_tmp > L_max)
-		{
-			L_max = L_tmp;
-		}
-	}
+    for (i = 1; i < L_FRAME + L_FILT; i++)
+    {
+        L_tmp = new_speech[i] << 15;
+        L_tmp -= (new_speech[i - 1] * mu)<<1;
+        L_tmp = L_abs(L_tmp);
+        if(L_tmp > L_max)
+        {
+            L_max = L_tmp;
+        }
+    }
 
-	/* get scaling factor for new and previous samples */
-	/* limit scaling to Q_MAX to keep dynamic for ringing in low signal */
-	/* limit scaling to Q_MAX also to avoid a[0]<1 in syn_filt_32 */
-	tmp = extract_h(L_max);
-	if (tmp == 0)
-	{
-		shift = Q_MAX;
-	} else
-	{
-		shift = norm_s(tmp) - 1;
-		if (shift < 0)
-		{
-			shift = 0;
-		}
-		if (shift > Q_MAX)
-		{
-			shift = Q_MAX;
-		}
-	}
-	Q_new = shift;
-	if (Q_new > st->Q_max[0])
-	{
-		Q_new = st->Q_max[0];
-	}
-	if (Q_new > st->Q_max[1])
-	{
-		Q_new = st->Q_max[1];
-	}
-	exp = (Q_new - st->Q_old);
-	st->Q_old = Q_new;
-	st->Q_max[1] = st->Q_max[0];
-	st->Q_max[0] = shift;
+    /* get scaling factor for new and previous samples */
+    /* limit scaling to Q_MAX to keep dynamic for ringing in low signal */
+    /* limit scaling to Q_MAX also to avoid a[0]<1 in syn_filt_32 */
+    tmp = extract_h(L_max);
+    if (tmp == 0)
+    {
+        shift = Q_MAX;
+    } else
+    {
+        shift = norm_s(tmp) - 1;
+        if (shift < 0)
+        {
+            shift = 0;
+        }
+        if (shift > Q_MAX)
+        {
+            shift = Q_MAX;
+        }
+    }
+    Q_new = shift;
+    if (Q_new > st->Q_max[0])
+    {
+        Q_new = st->Q_max[0];
+    }
+    if (Q_new > st->Q_max[1])
+    {
+        Q_new = st->Q_max[1];
+    }
+    exp = (Q_new - st->Q_old);
+    st->Q_old = Q_new;
+    st->Q_max[1] = st->Q_max[0];
+    st->Q_max[0] = shift;
 
-	/* preemphasis with scaling (L_FRAME+L_FILT) */
-	tmp = new_speech[L_FRAME - 1];
+    /* preemphasis with scaling (L_FRAME+L_FILT) */
+    tmp = new_speech[L_FRAME - 1];
 
-	for (i = L_FRAME + L_FILT - 1; i > 0; i--)
-	{
-		L_tmp = new_speech[i] << 15;
-		L_tmp -= (new_speech[i - 1] * mu)<<1;
-		L_tmp = (L_tmp << Q_new);
-		new_speech[i] = vo_round(L_tmp);
-	}
+    for (i = L_FRAME + L_FILT - 1; i > 0; i--)
+    {
+        L_tmp = new_speech[i] << 15;
+        L_tmp -= (new_speech[i - 1] * mu)<<1;
+        L_tmp = (L_tmp << Q_new);
+        new_speech[i] = vo_round(L_tmp);
+    }
 
-	L_tmp = new_speech[0] << 15;
-	L_tmp -= (st->mem_preemph * mu)<<1;
-	L_tmp = (L_tmp << Q_new);
-	new_speech[0] = vo_round(L_tmp);
+    L_tmp = new_speech[0] << 15;
+    L_tmp -= (st->mem_preemph * mu)<<1;
+    L_tmp = (L_tmp << Q_new);
+    new_speech[0] = vo_round(L_tmp);
 
-	st->mem_preemph = tmp;
+    st->mem_preemph = tmp;
 
-	/* scale previous samples and memory */
+    /* scale previous samples and memory */
 
-	Scale_sig(old_speech, L_TOTAL - L_FRAME - L_FILT, exp);
-	Scale_sig(old_exc, PIT_MAX + L_INTERPOL, exp);
-	Scale_sig(st->mem_syn, M, exp);
-	Scale_sig(st->mem_decim2, 3, exp);
-	Scale_sig(&(st->mem_wsp), 1, exp);
-	Scale_sig(&(st->mem_w0), 1, exp);
+    Scale_sig(old_speech, L_TOTAL - L_FRAME - L_FILT, exp);
+    Scale_sig(old_exc, PIT_MAX + L_INTERPOL, exp);
+    Scale_sig(st->mem_syn, M, exp);
+    Scale_sig(st->mem_decim2, 3, exp);
+    Scale_sig(&(st->mem_wsp), 1, exp);
+    Scale_sig(&(st->mem_w0), 1, exp);
 
-	/*------------------------------------------------------------------------*
-	 *  Call VAD                                                              *
-	 *  Preemphesis scale down signal in low frequency and keep dynamic in HF.*
-	 *  Vad work slightly in futur (new_speech = speech + L_NEXT - L_FILT).   *
-	 *------------------------------------------------------------------------*/
-	Copy(new_speech, buf, L_FRAME);
+    /*------------------------------------------------------------------------*
+     *  Call VAD                                                              *
+     *  Preemphesis scale down signal in low frequency and keep dynamic in HF.*
+     *  Vad work slightly in futur (new_speech = speech + L_NEXT - L_FILT).   *
+     *------------------------------------------------------------------------*/
+    Copy(new_speech, buf, L_FRAME);
 
 #ifdef ASM_OPT        /* asm optimization branch */
-	Scale_sig_opt(buf, L_FRAME, 1 - Q_new);
+    Scale_sig_opt(buf, L_FRAME, 1 - Q_new);
 #else
-	Scale_sig(buf, L_FRAME, 1 - Q_new);
+    Scale_sig(buf, L_FRAME, 1 - Q_new);
 #endif
 
-	vad_flag = wb_vad(st->vadSt, buf);          /* Voice Activity Detection */
-	if (vad_flag == 0)
-	{
-		st->vad_hist = (st->vad_hist + 1);
-	} else
-	{
-		st->vad_hist = 0;
-	}
+    vad_flag = wb_vad(st->vadSt, buf);          /* Voice Activity Detection */
+    if (vad_flag == 0)
+    {
+        st->vad_hist = (st->vad_hist + 1);
+    } else
+    {
+        st->vad_hist = 0;
+    }
 
-	/* DTX processing */
-	if (allow_dtx != 0)
-	{
-		/* Note that mode may change here */
-		tx_dtx_handler(st->dtx_encSt, vad_flag, mode);
-		*ser_size = nb_of_bits[*mode];
-	}
+    /* DTX processing */
+    if (allow_dtx != 0)
+    {
+        /* Note that mode may change here */
+        tx_dtx_handler(st->dtx_encSt, vad_flag, mode);
+        *ser_size = nb_of_bits[*mode];
+    }
 
-	if(*mode != MRDTX)
-	{
-		Parm_serial(vad_flag, 1, &prms);
-	}
-	/*------------------------------------------------------------------------*
-	 *  Perform LPC analysis                                                  *
-	 *  ~~~~~~~~~~~~~~~~~~~~                                                  *
-	 *   - autocorrelation + lag windowing                                    *
-	 *   - Levinson-durbin algorithm to find a[]                              *
-	 *   - convert a[] to isp[]                                               *
-	 *   - convert isp[] to isf[] for quantization                            *
-	 *   - quantize and code the isf[]                                        *
-	 *   - convert isf[] to isp[] for interpolation                           *
-	 *   - find the interpolated ISPs and convert to a[] for the 4 subframes  *
-	 *------------------------------------------------------------------------*/
+    if(*mode != MRDTX)
+    {
+        Parm_serial(vad_flag, 1, &prms);
+    }
+    /*------------------------------------------------------------------------*
+     *  Perform LPC analysis                                                  *
+     *  ~~~~~~~~~~~~~~~~~~~~                                                  *
+     *   - autocorrelation + lag windowing                                    *
+     *   - Levinson-durbin algorithm to find a[]                              *
+     *   - convert a[] to isp[]                                               *
+     *   - convert isp[] to isf[] for quantization                            *
+     *   - quantize and code the isf[]                                        *
+     *   - convert isf[] to isp[] for interpolation                           *
+     *   - find the interpolated ISPs and convert to a[] for the 4 subframes  *
+     *------------------------------------------------------------------------*/
 
-	/* LP analysis centered at 4nd subframe */
-	Autocorr(p_window, M, r_h, r_l);                        /* Autocorrelations */
-	Lag_window(r_h, r_l);                                   /* Lag windowing    */
-	Levinson(r_h, r_l, A, rc, st->mem_levinson);            /* Levinson Durbin  */
-	Az_isp(A, ispnew, st->ispold);                          /* From A(z) to ISP */
+    /* LP analysis centered at 4nd subframe */
+    Autocorr(p_window, M, r_h, r_l);                        /* Autocorrelations */
+    Lag_window(r_h, r_l);                                   /* Lag windowing    */
+    Levinson(r_h, r_l, A, rc, st->mem_levinson);            /* Levinson Durbin  */
+    Az_isp(A, ispnew, st->ispold);                          /* From A(z) to ISP */
 
-	/* Find the interpolated ISPs and convert to a[] for all subframes */
-	Int_isp(st->ispold, ispnew, interpol_frac, A);
+    /* Find the interpolated ISPs and convert to a[] for all subframes */
+    Int_isp(st->ispold, ispnew, interpol_frac, A);
 
-	/* update ispold[] for the next frame */
-	Copy(ispnew, st->ispold, M);
+    /* update ispold[] for the next frame */
+    Copy(ispnew, st->ispold, M);
 
-	/* Convert ISPs to frequency domain 0..6400 */
-	Isp_isf(ispnew, isf, M);
+    /* Convert ISPs to frequency domain 0..6400 */
+    Isp_isf(ispnew, isf, M);
 
-	/* check resonance for pitch clipping algorithm */
-	Gp_clip_test_isf(isf, st->gp_clip);
+    /* check resonance for pitch clipping algorithm */
+    Gp_clip_test_isf(isf, st->gp_clip);
 
-	/*----------------------------------------------------------------------*
-	 *  Perform PITCH_OL analysis                                           *
-	 *  ~~~~~~~~~~~~~~~~~~~~~~~~~                                           *
-	 * - Find the residual res[] for the whole speech frame                 *
-	 * - Find the weighted input speech wsp[] for the whole speech frame    *
-	 * - scale wsp[] to avoid overflow in pitch estimation                  *
-	 * - Find open loop pitch lag for whole speech frame                    *
-	 *----------------------------------------------------------------------*/
-	p_A = A;
-	for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
-	{
-		/* Weighting of LPC coefficients */
-		Weight_a(p_A, Ap, GAMMA1, M);
+    /*----------------------------------------------------------------------*
+     *  Perform PITCH_OL analysis                                           *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~                                           *
+     * - Find the residual res[] for the whole speech frame                 *
+     * - Find the weighted input speech wsp[] for the whole speech frame    *
+     * - scale wsp[] to avoid overflow in pitch estimation                  *
+     * - Find open loop pitch lag for whole speech frame                    *
+     *----------------------------------------------------------------------*/
+    p_A = A;
+    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+    {
+        /* Weighting of LPC coefficients */
+        Weight_a(p_A, Ap, GAMMA1, M);
 
 #ifdef ASM_OPT                    /* asm optimization branch */
-		Residu_opt(Ap, &speech[i_subfr], &wsp[i_subfr], L_SUBFR);
+        Residu_opt(Ap, &speech[i_subfr], &wsp[i_subfr], L_SUBFR);
 #else
-		Residu(Ap, &speech[i_subfr], &wsp[i_subfr], L_SUBFR);
+        Residu(Ap, &speech[i_subfr], &wsp[i_subfr], L_SUBFR);
 #endif
 
-		p_A += (M + 1);
-	}
+        p_A += (M + 1);
+    }
 
-	Deemph2(wsp, TILT_FAC, L_FRAME, &(st->mem_wsp));
+    Deemph2(wsp, TILT_FAC, L_FRAME, &(st->mem_wsp));
 
-	/* find maximum value on wsp[] for 12 bits scaling */
-	max = 0;
-	for (i = 0; i < L_FRAME; i++)
-	{
-		tmp = abs_s(wsp[i]);
-		if(tmp > max)
-		{
-			max = tmp;
-		}
-	}
-	tmp = st->old_wsp_max;
-	if(max > tmp)
-	{
-		tmp = max;                         /* tmp = max(wsp_max, old_wsp_max) */
-	}
-	st->old_wsp_max = max;
+    /* find maximum value on wsp[] for 12 bits scaling */
+    max = 0;
+    for (i = 0; i < L_FRAME; i++)
+    {
+        tmp = abs_s(wsp[i]);
+        if(tmp > max)
+        {
+            max = tmp;
+        }
+    }
+    tmp = st->old_wsp_max;
+    if(max > tmp)
+    {
+        tmp = max;                         /* tmp = max(wsp_max, old_wsp_max) */
+    }
+    st->old_wsp_max = max;
 
-	shift = norm_s(tmp) - 3;
-	if (shift > 0)
-	{
-		shift = 0;                         /* shift = 0..-3 */
-	}
-	/* decimation of wsp[] to search pitch in LF and to reduce complexity */
-	LP_Decim2(wsp, L_FRAME, st->mem_decim2);
+    shift = norm_s(tmp) - 3;
+    if (shift > 0)
+    {
+        shift = 0;                         /* shift = 0..-3 */
+    }
+    /* decimation of wsp[] to search pitch in LF and to reduce complexity */
+    LP_Decim2(wsp, L_FRAME, st->mem_decim2);
 
-	/* scale wsp[] in 12 bits to avoid overflow */
+    /* scale wsp[] in 12 bits to avoid overflow */
 #ifdef  ASM_OPT                  /* asm optimization branch */
-	Scale_sig_opt(wsp, L_FRAME / OPL_DECIM, shift);
+    Scale_sig_opt(wsp, L_FRAME / OPL_DECIM, shift);
 #else
-	Scale_sig(wsp, L_FRAME / OPL_DECIM, shift);
+    Scale_sig(wsp, L_FRAME / OPL_DECIM, shift);
 #endif
-	/* scale old_wsp (warning: exp must be Q_new-Q_old) */
-	exp = exp + (shift - st->old_wsp_shift);
-	st->old_wsp_shift = shift;
+    /* scale old_wsp (warning: exp must be Q_new-Q_old) */
+    exp = exp + (shift - st->old_wsp_shift);
+    st->old_wsp_shift = shift;
 
-	Scale_sig(old_wsp, PIT_MAX / OPL_DECIM, exp);
-	Scale_sig(st->old_hp_wsp, PIT_MAX / OPL_DECIM, exp);
+    Scale_sig(old_wsp, PIT_MAX / OPL_DECIM, exp);
+    Scale_sig(st->old_hp_wsp, PIT_MAX / OPL_DECIM, exp);
 
-	scale_mem_Hp_wsp(st->hp_wsp_mem, exp);
+    scale_mem_Hp_wsp(st->hp_wsp_mem, exp);
 
-	/* Find open loop pitch lag for whole speech frame */
+    /* Find open loop pitch lag for whole speech frame */
 
-	if(*ser_size == NBBITS_7k)
-	{
-		/* Find open loop pitch lag for whole speech frame */
-		T_op = Pitch_med_ol(wsp, st, L_FRAME / OPL_DECIM);
-	} else
-	{
-		/* Find open loop pitch lag for first 1/2 frame */
-		T_op = Pitch_med_ol(wsp, st, (L_FRAME/2) / OPL_DECIM);
-	}
+    if(*ser_size == NBBITS_7k)
+    {
+        /* Find open loop pitch lag for whole speech frame */
+        T_op = Pitch_med_ol(wsp, st, L_FRAME / OPL_DECIM);
+    } else
+    {
+        /* Find open loop pitch lag for first 1/2 frame */
+        T_op = Pitch_med_ol(wsp, st, (L_FRAME/2) / OPL_DECIM);
+    }
 
-	if(st->ol_gain > 19661)       /* 0.6 in Q15 */
-	{
-		st->old_T0_med = Med_olag(T_op, st->old_ol_lag);
-		st->ada_w = 32767;
-	} else
-	{
-		st->ada_w = vo_mult(st->ada_w, 29491);
-	}
+    if(st->ol_gain > 19661)       /* 0.6 in Q15 */
+    {
+        st->old_T0_med = Med_olag(T_op, st->old_ol_lag);
+        st->ada_w = 32767;
+    } else
+    {
+        st->ada_w = vo_mult(st->ada_w, 29491);
+    }
 
-	if(st->ada_w < 26214)
-		st->ol_wght_flg = 0;
-	else
-		st->ol_wght_flg = 1;
+    if(st->ada_w < 26214)
+        st->ol_wght_flg = 0;
+    else
+        st->ol_wght_flg = 1;
 
-	wb_vad_tone_detection(st->vadSt, st->ol_gain);
-	T_op *= OPL_DECIM;
+    wb_vad_tone_detection(st->vadSt, st->ol_gain);
+    T_op *= OPL_DECIM;
 
-	if(*ser_size != NBBITS_7k)
-	{
-		/* Find open loop pitch lag for second 1/2 frame */
-		T_op2 = Pitch_med_ol(wsp + ((L_FRAME / 2) / OPL_DECIM), st, (L_FRAME/2) / OPL_DECIM);
+    if(*ser_size != NBBITS_7k)
+    {
+        /* Find open loop pitch lag for second 1/2 frame */
+        T_op2 = Pitch_med_ol(wsp + ((L_FRAME / 2) / OPL_DECIM), st, (L_FRAME/2) / OPL_DECIM);
 
-		if(st->ol_gain > 19661)   /* 0.6 in Q15 */
-		{
-			st->old_T0_med = Med_olag(T_op2, st->old_ol_lag);
-			st->ada_w = 32767;
-		} else
-		{
-			st->ada_w = mult(st->ada_w, 29491);
-		}
+        if(st->ol_gain > 19661)   /* 0.6 in Q15 */
+        {
+            st->old_T0_med = Med_olag(T_op2, st->old_ol_lag);
+            st->ada_w = 32767;
+        } else
+        {
+            st->ada_w = mult(st->ada_w, 29491);
+        }
 
-		if(st->ada_w < 26214)
-			st->ol_wght_flg = 0;
-		else
-			st->ol_wght_flg = 1;
+        if(st->ada_w < 26214)
+            st->ol_wght_flg = 0;
+        else
+            st->ol_wght_flg = 1;
 
-		wb_vad_tone_detection(st->vadSt, st->ol_gain);
+        wb_vad_tone_detection(st->vadSt, st->ol_gain);
 
-		T_op2 *= OPL_DECIM;
+        T_op2 *= OPL_DECIM;
 
-	} else
-	{
-		T_op2 = T_op;
-	}
-	/*----------------------------------------------------------------------*
-	 *                              DTX-CNG                                 *
-	 *----------------------------------------------------------------------*/
-	if(*mode == MRDTX)            /* CNG mode */
-	{
-		/* Buffer isf's and energy */
+    } else
+    {
+        T_op2 = T_op;
+    }
+    /*----------------------------------------------------------------------*
+     *                              DTX-CNG                                 *
+     *----------------------------------------------------------------------*/
+    if(*mode == MRDTX)            /* CNG mode */
+    {
+        /* Buffer isf's and energy */
 #ifdef ASM_OPT                   /* asm optimization branch */
-		Residu_opt(&A[3 * (M + 1)], speech, exc, L_FRAME);
+        Residu_opt(&A[3 * (M + 1)], speech, exc, L_FRAME);
 #else
-		Residu(&A[3 * (M + 1)], speech, exc, L_FRAME);
+        Residu(&A[3 * (M + 1)], speech, exc, L_FRAME);
 #endif
 
-		for (i = 0; i < L_FRAME; i++)
-		{
-			exc2[i] = shr(exc[i], Q_new);
-		}
+        for (i = 0; i < L_FRAME; i++)
+        {
+            exc2[i] = shr(exc[i], Q_new);
+        }
 
-		L_tmp = 0;
-		for (i = 0; i < L_FRAME; i++)
-			L_tmp += (exc2[i] * exc2[i])<<1;
+        L_tmp = 0;
+        for (i = 0; i < L_FRAME; i++)
+            L_tmp += (exc2[i] * exc2[i])<<1;
 
-		L_tmp >>= 1;
+        L_tmp >>= 1;
 
-		dtx_buffer(st->dtx_encSt, isf, L_tmp, codec_mode);
+        dtx_buffer(st->dtx_encSt, isf, L_tmp, codec_mode);
 
-		/* Quantize and code the ISFs */
-		dtx_enc(st->dtx_encSt, isf, exc2, &prms);
+        /* Quantize and code the ISFs */
+        dtx_enc(st->dtx_encSt, isf, exc2, &prms);
 
-		/* Convert ISFs to the cosine domain */
-		Isf_isp(isf, ispnew_q, M);
-		Isp_Az(ispnew_q, Aq, M, 0);
+        /* Convert ISFs to the cosine domain */
+        Isf_isp(isf, ispnew_q, M);
+        Isp_Az(ispnew_q, Aq, M, 0);
 
-		for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
-		{
-			corr_gain = synthesis(Aq, &exc2[i_subfr], 0, &speech16k[i_subfr * 5 / 4], st);
-		}
-		Copy(isf, st->isfold, M);
+        for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+        {
+            corr_gain = synthesis(Aq, &exc2[i_subfr], 0, &speech16k[i_subfr * 5 / 4], st);
+        }
+        Copy(isf, st->isfold, M);
 
-		/* reset speech coder memories */
-		Reset_encoder(st, 0);
+        /* reset speech coder memories */
+        Reset_encoder(st, 0);
 
-		/*--------------------------------------------------*
-		 * Update signal for next frame.                    *
-		 * -> save past of speech[] and wsp[].              *
-		 *--------------------------------------------------*/
+        /*--------------------------------------------------*
+         * Update signal for next frame.                    *
+         * -> save past of speech[] and wsp[].              *
+         *--------------------------------------------------*/
 
-		Copy(&old_speech[L_FRAME], st->old_speech, L_TOTAL - L_FRAME);
-		Copy(&old_wsp[L_FRAME / OPL_DECIM], st->old_wsp, PIT_MAX / OPL_DECIM);
+        Copy(&old_speech[L_FRAME], st->old_speech, L_TOTAL - L_FRAME);
+        Copy(&old_wsp[L_FRAME / OPL_DECIM], st->old_wsp, PIT_MAX / OPL_DECIM);
 
-		return;
-	}
-	/*----------------------------------------------------------------------*
-	 *                               ACELP                                  *
-	 *----------------------------------------------------------------------*/
+        return;
+    }
+    /*----------------------------------------------------------------------*
+     *                               ACELP                                  *
+     *----------------------------------------------------------------------*/
 
-	/* Quantize and code the ISFs */
+    /* Quantize and code the ISFs */
 
-	if (*ser_size <= NBBITS_7k)
-	{
-		Qpisf_2s_36b(isf, isf, st->past_isfq, indice, 4);
+    if (*ser_size <= NBBITS_7k)
+    {
+        Qpisf_2s_36b(isf, isf, st->past_isfq, indice, 4);
 
-		Parm_serial(indice[0], 8, &prms);
-		Parm_serial(indice[1], 8, &prms);
-		Parm_serial(indice[2], 7, &prms);
-		Parm_serial(indice[3], 7, &prms);
-		Parm_serial(indice[4], 6, &prms);
-	} else
-	{
-		Qpisf_2s_46b(isf, isf, st->past_isfq, indice, 4);
+        Parm_serial(indice[0], 8, &prms);
+        Parm_serial(indice[1], 8, &prms);
+        Parm_serial(indice[2], 7, &prms);
+        Parm_serial(indice[3], 7, &prms);
+        Parm_serial(indice[4], 6, &prms);
+    } else
+    {
+        Qpisf_2s_46b(isf, isf, st->past_isfq, indice, 4);
 
-		Parm_serial(indice[0], 8, &prms);
-		Parm_serial(indice[1], 8, &prms);
-		Parm_serial(indice[2], 6, &prms);
-		Parm_serial(indice[3], 7, &prms);
-		Parm_serial(indice[4], 7, &prms);
-		Parm_serial(indice[5], 5, &prms);
-		Parm_serial(indice[6], 5, &prms);
-	}
+        Parm_serial(indice[0], 8, &prms);
+        Parm_serial(indice[1], 8, &prms);
+        Parm_serial(indice[2], 6, &prms);
+        Parm_serial(indice[3], 7, &prms);
+        Parm_serial(indice[4], 7, &prms);
+        Parm_serial(indice[5], 5, &prms);
+        Parm_serial(indice[6], 5, &prms);
+    }
 
-	/* Check stability on isf : distance between old isf and current isf */
+    /* Check stability on isf : distance between old isf and current isf */
 
-	L_tmp = 0;
-	for (i = 0; i < M - 1; i++)
-	{
-		tmp = vo_sub(isf[i], st->isfold[i]);
-		L_tmp += (tmp * tmp)<<1;
-	}
+    L_tmp = 0;
+    for (i = 0; i < M - 1; i++)
+    {
+        tmp = vo_sub(isf[i], st->isfold[i]);
+        L_tmp += (tmp * tmp)<<1;
+    }
 
-	tmp = extract_h(L_shl2(L_tmp, 8));
+    tmp = extract_h(L_shl2(L_tmp, 8));
 
-	tmp = vo_mult(tmp, 26214);                /* tmp = L_tmp*0.8/256 */
-	tmp = vo_sub(20480, tmp);                 /* 1.25 - tmp (in Q14) */
+    tmp = vo_mult(tmp, 26214);                /* tmp = L_tmp*0.8/256 */
+    tmp = vo_sub(20480, tmp);                 /* 1.25 - tmp (in Q14) */
 
-	stab_fac = shl(tmp, 1);
+    stab_fac = shl(tmp, 1);
 
-	if (stab_fac < 0)
-	{
-		stab_fac = 0;
-	}
-	Copy(isf, st->isfold, M);
+    if (stab_fac < 0)
+    {
+        stab_fac = 0;
+    }
+    Copy(isf, st->isfold, M);
 
-	/* Convert ISFs to the cosine domain */
-	Isf_isp(isf, ispnew_q, M);
+    /* Convert ISFs to the cosine domain */
+    Isf_isp(isf, ispnew_q, M);
 
-	if (st->first_frame != 0)
-	{
-		st->first_frame = 0;
-		Copy(ispnew_q, st->ispold_q, M);
-	}
-	/* Find the interpolated ISPs and convert to a[] for all subframes */
+    if (st->first_frame != 0)
+    {
+        st->first_frame = 0;
+        Copy(ispnew_q, st->ispold_q, M);
+    }
+    /* Find the interpolated ISPs and convert to a[] for all subframes */
 
-	Int_isp(st->ispold_q, ispnew_q, interpol_frac, Aq);
+    Int_isp(st->ispold_q, ispnew_q, interpol_frac, Aq);
 
-	/* update ispold[] for the next frame */
-	Copy(ispnew_q, st->ispold_q, M);
+    /* update ispold[] for the next frame */
+    Copy(ispnew_q, st->ispold_q, M);
 
-	p_Aq = Aq;
-	for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
-	{
+    p_Aq = Aq;
+    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+    {
 #ifdef ASM_OPT               /* asm optimization branch */
-		Residu_opt(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
+        Residu_opt(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
 #else
-		Residu(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
+        Residu(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
 #endif
-		p_Aq += (M + 1);
-	}
+        p_Aq += (M + 1);
+    }
 
-	/* Buffer isf's and energy for dtx on non-speech frame */
-	if (vad_flag == 0)
-	{
-		for (i = 0; i < L_FRAME; i++)
-		{
-			exc2[i] = exc[i] >> Q_new;
-		}
-		L_tmp = 0;
-		for (i = 0; i < L_FRAME; i++)
-			L_tmp += (exc2[i] * exc2[i])<<1;
-		L_tmp >>= 1;
+    /* Buffer isf's and energy for dtx on non-speech frame */
+    if (vad_flag == 0)
+    {
+        for (i = 0; i < L_FRAME; i++)
+        {
+            exc2[i] = exc[i] >> Q_new;
+        }
+        L_tmp = 0;
+        for (i = 0; i < L_FRAME; i++) {
+            Word32 tmp = L_mult(exc2[i], exc2[i]); // (exc2[i] * exc2[i])<<1;
+            L_tmp = L_add(L_tmp, tmp);
+        }
+        L_tmp >>= 1;
 
-		dtx_buffer(st->dtx_encSt, isf, L_tmp, codec_mode);
-	}
-	/* range for closed loop pitch search in 1st subframe */
+        dtx_buffer(st->dtx_encSt, isf, L_tmp, codec_mode);
+    }
+    /* range for closed loop pitch search in 1st subframe */
 
-	T0_min = T_op - 8;
-	if (T0_min < PIT_MIN)
-	{
-		T0_min = PIT_MIN;
-	}
-	T0_max = (T0_min + 15);
+    T0_min = T_op - 8;
+    if (T0_min < PIT_MIN)
+    {
+        T0_min = PIT_MIN;
+    }
+    T0_max = (T0_min + 15);
 
-	if(T0_max > PIT_MAX)
-	{
-		T0_max = PIT_MAX;
-		T0_min = T0_max - 15;
-	}
-	/*------------------------------------------------------------------------*
-	 *          Loop for every subframe in the analysis frame                 *
-	 *------------------------------------------------------------------------*
-	 *  To find the pitch and innovation parameters. The subframe size is     *
-	 *  L_SUBFR and the loop is repeated L_FRAME/L_SUBFR times.               *
-	 *     - compute the target signal for pitch search                       *
-	 *     - compute impulse response of weighted synthesis filter (h1[])     *
-	 *     - find the closed-loop pitch parameters                            *
-	 *     - encode the pitch dealy                                           *
-	 *     - find 2 lt prediction (with / without LP filter for lt pred)      *
-	 *     - find 2 pitch gains and choose the best lt prediction.            *
-	 *     - find target vector for codebook search                           *
-	 *     - update the impulse response h1[] for codebook search             *
-	 *     - correlation between target vector and impulse response           *
-	 *     - codebook search and encoding                                     *
-	 *     - VQ of pitch and codebook gains                                   *
-	 *     - find voicing factor and tilt of code for next subframe.          *
-	 *     - update states of weighting filter                                *
-	 *     - find excitation and synthesis speech                             *
-	 *------------------------------------------------------------------------*/
-	p_A = A;
-	p_Aq = Aq;
-	for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
-	{
-		pit_flag = i_subfr;
-		if ((i_subfr == 2 * L_SUBFR) && (*ser_size > NBBITS_7k))
-		{
-			pit_flag = 0;
-			/* range for closed loop pitch search in 3rd subframe */
-			T0_min = (T_op2 - 8);
+    if(T0_max > PIT_MAX)
+    {
+        T0_max = PIT_MAX;
+        T0_min = T0_max - 15;
+    }
+    /*------------------------------------------------------------------------*
+     *          Loop for every subframe in the analysis frame                 *
+     *------------------------------------------------------------------------*
+     *  To find the pitch and innovation parameters. The subframe size is     *
+     *  L_SUBFR and the loop is repeated L_FRAME/L_SUBFR times.               *
+     *     - compute the target signal for pitch search                       *
+     *     - compute impulse response of weighted synthesis filter (h1[])     *
+     *     - find the closed-loop pitch parameters                            *
+     *     - encode the pitch dealy                                           *
+     *     - find 2 lt prediction (with / without LP filter for lt pred)      *
+     *     - find 2 pitch gains and choose the best lt prediction.            *
+     *     - find target vector for codebook search                           *
+     *     - update the impulse response h1[] for codebook search             *
+     *     - correlation between target vector and impulse response           *
+     *     - codebook search and encoding                                     *
+     *     - VQ of pitch and codebook gains                                   *
+     *     - find voicing factor and tilt of code for next subframe.          *
+     *     - update states of weighting filter                                *
+     *     - find excitation and synthesis speech                             *
+     *------------------------------------------------------------------------*/
+    p_A = A;
+    p_Aq = Aq;
+    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+    {
+        pit_flag = i_subfr;
+        if ((i_subfr == 2 * L_SUBFR) && (*ser_size > NBBITS_7k))
+        {
+            pit_flag = 0;
+            /* range for closed loop pitch search in 3rd subframe */
+            T0_min = (T_op2 - 8);
 
-			if (T0_min < PIT_MIN)
-			{
-				T0_min = PIT_MIN;
-			}
-			T0_max = (T0_min + 15);
-			if (T0_max > PIT_MAX)
-			{
-				T0_max = PIT_MAX;
-				T0_min = (T0_max - 15);
-			}
-		}
-		/*-----------------------------------------------------------------------*
-		 *                                                                       *
-		 *        Find the target vector for pitch search:                       *
-		 *        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                        *
-		 *                                                                       *
-		 *             |------|  res[n]                                          *
-		 * speech[n]---| A(z) |--------                                          *
-		 *             |------|       |   |--------| error[n]  |------|          *
-		 *                   zero -- (-)--| 1/A(z) |-----------| W(z) |-- target *
-		 *                   exc          |--------|           |------|          *
-		 *                                                                       *
-		 * Instead of subtracting the zero-input response of filters from        *
-		 * the weighted input speech, the above configuration is used to         *
-		 * compute the target vector.                                            *
-		 *                                                                       *
-		 *-----------------------------------------------------------------------*/
+            if (T0_min < PIT_MIN)
+            {
+                T0_min = PIT_MIN;
+            }
+            T0_max = (T0_min + 15);
+            if (T0_max > PIT_MAX)
+            {
+                T0_max = PIT_MAX;
+                T0_min = (T0_max - 15);
+            }
+        }
+        /*-----------------------------------------------------------------------*
+         *                                                                       *
+         *        Find the target vector for pitch search:                       *
+         *        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                        *
+         *                                                                       *
+         *             |------|  res[n]                                          *
+         * speech[n]---| A(z) |--------                                          *
+         *             |------|       |   |--------| error[n]  |------|          *
+         *                   zero -- (-)--| 1/A(z) |-----------| W(z) |-- target *
+         *                   exc          |--------|           |------|          *
+         *                                                                       *
+         * Instead of subtracting the zero-input response of filters from        *
+         * the weighted input speech, the above configuration is used to         *
+         * compute the target vector.                                            *
+         *                                                                       *
+         *-----------------------------------------------------------------------*/
 
-		for (i = 0; i < M; i++)
-		{
-			error[i] = vo_sub(speech[i + i_subfr - M], st->mem_syn[i]);
-		}
+        for (i = 0; i < M; i++)
+        {
+            error[i] = vo_sub(speech[i + i_subfr - M], st->mem_syn[i]);
+        }
 
 #ifdef ASM_OPT              /* asm optimization branch */
-		Residu_opt(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
+        Residu_opt(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
 #else
-		Residu(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
+        Residu(p_Aq, &speech[i_subfr], &exc[i_subfr], L_SUBFR);
 #endif
-		Syn_filt(p_Aq, &exc[i_subfr], error + M, L_SUBFR, error, 0);
-		Weight_a(p_A, Ap, GAMMA1, M);
+        Syn_filt(p_Aq, &exc[i_subfr], error + M, L_SUBFR, error, 0);
+        Weight_a(p_A, Ap, GAMMA1, M);
 
 #ifdef ASM_OPT             /* asm optimization branch */
-		Residu_opt(Ap, error + M, xn, L_SUBFR);
+        Residu_opt(Ap, error + M, xn, L_SUBFR);
 #else
-		Residu(Ap, error + M, xn, L_SUBFR);
+        Residu(Ap, error + M, xn, L_SUBFR);
 #endif
-		Deemph2(xn, TILT_FAC, L_SUBFR, &(st->mem_w0));
+        Deemph2(xn, TILT_FAC, L_SUBFR, &(st->mem_w0));
 
-		/*----------------------------------------------------------------------*
-		 * Find approx. target in residual domain "cn[]" for inovation search.  *
-		 *----------------------------------------------------------------------*/
-		/* first half: xn[] --> cn[] */
-		Set_zero(code, M);
-		Copy(xn, code + M, L_SUBFR / 2);
-		tmp = 0;
-		Preemph2(code + M, TILT_FAC, L_SUBFR / 2, &tmp);
-		Weight_a(p_A, Ap, GAMMA1, M);
-		Syn_filt(Ap,code + M, code + M, L_SUBFR / 2, code, 0);
+        /*----------------------------------------------------------------------*
+         * Find approx. target in residual domain "cn[]" for inovation search.  *
+         *----------------------------------------------------------------------*/
+        /* first half: xn[] --> cn[] */
+        Set_zero(code, M);
+        Copy(xn, code + M, L_SUBFR / 2);
+        tmp = 0;
+        Preemph2(code + M, TILT_FAC, L_SUBFR / 2, &tmp);
+        Weight_a(p_A, Ap, GAMMA1, M);
+        Syn_filt(Ap,code + M, code + M, L_SUBFR / 2, code, 0);
 
 #ifdef ASM_OPT                /* asm optimization branch */
-		Residu_opt(p_Aq,code + M, cn, L_SUBFR / 2);
+        Residu_opt(p_Aq,code + M, cn, L_SUBFR / 2);
 #else
-		Residu(p_Aq,code + M, cn, L_SUBFR / 2);
+        Residu(p_Aq,code + M, cn, L_SUBFR / 2);
 #endif
 
-		/* second half: res[] --> cn[] (approximated and faster) */
-		Copy(&exc[i_subfr + (L_SUBFR / 2)], cn + (L_SUBFR / 2), L_SUBFR / 2);
+        /* second half: res[] --> cn[] (approximated and faster) */
+        Copy(&exc[i_subfr + (L_SUBFR / 2)], cn + (L_SUBFR / 2), L_SUBFR / 2);
 
-		/*---------------------------------------------------------------*
-		 * Compute impulse response, h1[], of weighted synthesis filter  *
-		 *---------------------------------------------------------------*/
+        /*---------------------------------------------------------------*
+         * Compute impulse response, h1[], of weighted synthesis filter  *
+         *---------------------------------------------------------------*/
 
-		Set_zero(error, M + L_SUBFR);
-		Weight_a(p_A, error + M, GAMMA1, M);
+        Set_zero(error, M + L_SUBFR);
+        Weight_a(p_A, error + M, GAMMA1, M);
 
-		vo_p0 = error+M;
-		vo_p3 = h1;
-		for (i = 0; i < L_SUBFR; i++)
-		{
-			L_tmp = *vo_p0 << 14;        /* x4 (Q12 to Q14) */
-			vo_p1 = p_Aq + 1;
-			vo_p2 = vo_p0-1;
-			for (j = 1; j <= M/4; j++)
-			{
-				L_tmp -= *vo_p1++ * *vo_p2--;
-				L_tmp -= *vo_p1++ * *vo_p2--;
-				L_tmp -= *vo_p1++ * *vo_p2--;
-				L_tmp -= *vo_p1++ * *vo_p2--;
-			}
-			*vo_p3++ = *vo_p0++ = vo_round((L_tmp <<4));
-		}
-		/* deemph without division by 2 -> Q14 to Q15 */
-		tmp = 0;
-		Deemph2(h1, TILT_FAC, L_SUBFR, &tmp);   /* h1 in Q14 */
+        vo_p0 = error+M;
+        vo_p3 = h1;
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            L_tmp = *vo_p0 << 14;        /* x4 (Q12 to Q14) */
+            vo_p1 = p_Aq + 1;
+            vo_p2 = vo_p0-1;
+            for (j = 1; j <= M/4; j++)
+            {
+                L_tmp = L_sub(L_tmp, *vo_p1++ * *vo_p2--);
+                L_tmp = L_sub(L_tmp, *vo_p1++ * *vo_p2--);
+                L_tmp = L_sub(L_tmp, *vo_p1++ * *vo_p2--);
+                L_tmp = L_sub(L_tmp, *vo_p1++ * *vo_p2--);
+            }
+            *vo_p3++ = *vo_p0++ = vo_round((L_tmp <<4));
+        }
+        /* deemph without division by 2 -> Q14 to Q15 */
+        tmp = 0;
+        Deemph2(h1, TILT_FAC, L_SUBFR, &tmp);   /* h1 in Q14 */
 
-		/* h2 in Q12 for codebook search */
-		Copy(h1, h2, L_SUBFR);
+        /* h2 in Q12 for codebook search */
+        Copy(h1, h2, L_SUBFR);
 
-		/*---------------------------------------------------------------*
-		 * scale xn[] and h1[] to avoid overflow in dot_product12()      *
-		 *---------------------------------------------------------------*/
+        /*---------------------------------------------------------------*
+         * scale xn[] and h1[] to avoid overflow in dot_product12()      *
+         *---------------------------------------------------------------*/
 #ifdef  ASM_OPT                  /* asm optimization branch */
-		Scale_sig_opt(h2, L_SUBFR, -2);
-		Scale_sig_opt(xn, L_SUBFR, shift);     /* scaling of xn[] to limit dynamic at 12 bits */
-		Scale_sig_opt(h1, L_SUBFR, 1 + shift);  /* set h1[] in Q15 with scaling for convolution */
+        Scale_sig_opt(h2, L_SUBFR, -2);
+        Scale_sig_opt(xn, L_SUBFR, shift);     /* scaling of xn[] to limit dynamic at 12 bits */
+        Scale_sig_opt(h1, L_SUBFR, 1 + shift);  /* set h1[] in Q15 with scaling for convolution */
 #else
-		Scale_sig(h2, L_SUBFR, -2);
-		Scale_sig(xn, L_SUBFR, shift);     /* scaling of xn[] to limit dynamic at 12 bits */
-		Scale_sig(h1, L_SUBFR, 1 + shift);  /* set h1[] in Q15 with scaling for convolution */
+        Scale_sig(h2, L_SUBFR, -2);
+        Scale_sig(xn, L_SUBFR, shift);     /* scaling of xn[] to limit dynamic at 12 bits */
+        Scale_sig(h1, L_SUBFR, 1 + shift);  /* set h1[] in Q15 with scaling for convolution */
 #endif
-		/*----------------------------------------------------------------------*
-		 *                 Closed-loop fractional pitch search                  *
-		 *----------------------------------------------------------------------*/
-		/* find closed loop fractional pitch  lag */
-		if(*ser_size <= NBBITS_9k)
-		{
-			T0 = Pitch_fr4(&exc[i_subfr], xn, h1, T0_min, T0_max, &T0_frac,
-					pit_flag, PIT_MIN, PIT_FR1_8b, L_SUBFR);
+        /*----------------------------------------------------------------------*
+         *                 Closed-loop fractional pitch search                  *
+         *----------------------------------------------------------------------*/
+        /* find closed loop fractional pitch  lag */
+        if(*ser_size <= NBBITS_9k)
+        {
+            T0 = Pitch_fr4(&exc[i_subfr], xn, h1, T0_min, T0_max, &T0_frac,
+                    pit_flag, PIT_MIN, PIT_FR1_8b, L_SUBFR);
 
-			/* encode pitch lag */
-			if (pit_flag == 0)             /* if 1st/3rd subframe */
-			{
-				/*--------------------------------------------------------------*
-				 * The pitch range for the 1st/3rd subframe is encoded with     *
-				 * 8 bits and is divided as follows:                            *
-				 *   PIT_MIN to PIT_FR1-1  resolution 1/2 (frac = 0 or 2)       *
-				 *   PIT_FR1 to PIT_MAX    resolution 1   (frac = 0)            *
-				 *--------------------------------------------------------------*/
-				if (T0 < PIT_FR1_8b)
-				{
-					index = ((T0 << 1) + (T0_frac >> 1) - (PIT_MIN<<1));
-				} else
-				{
-					index = ((T0 - PIT_FR1_8b) + ((PIT_FR1_8b - PIT_MIN)*2));
-				}
+            /* encode pitch lag */
+            if (pit_flag == 0)             /* if 1st/3rd subframe */
+            {
+                /*--------------------------------------------------------------*
+                 * The pitch range for the 1st/3rd subframe is encoded with     *
+                 * 8 bits and is divided as follows:                            *
+                 *   PIT_MIN to PIT_FR1-1  resolution 1/2 (frac = 0 or 2)       *
+                 *   PIT_FR1 to PIT_MAX    resolution 1   (frac = 0)            *
+                 *--------------------------------------------------------------*/
+                if (T0 < PIT_FR1_8b)
+                {
+                    index = ((T0 << 1) + (T0_frac >> 1) - (PIT_MIN<<1));
+                } else
+                {
+                    index = ((T0 - PIT_FR1_8b) + ((PIT_FR1_8b - PIT_MIN)*2));
+                }
 
-				Parm_serial(index, 8, &prms);
+                Parm_serial(index, 8, &prms);
 
-				/* find T0_min and T0_max for subframe 2 and 4 */
-				T0_min = (T0 - 8);
-				if (T0_min < PIT_MIN)
-				{
-					T0_min = PIT_MIN;
-				}
-				T0_max = T0_min + 15;
-				if (T0_max > PIT_MAX)
-				{
-					T0_max = PIT_MAX;
-					T0_min = (T0_max - 15);
-				}
-			} else
-			{                              /* if subframe 2 or 4 */
-				/*--------------------------------------------------------------*
-				 * The pitch range for subframe 2 or 4 is encoded with 5 bits:  *
-				 *   T0_min  to T0_max     resolution 1/2 (frac = 0 or 2)       *
-				 *--------------------------------------------------------------*/
-				i = (T0 - T0_min);
-				index = (i << 1) + (T0_frac >> 1);
+                /* find T0_min and T0_max for subframe 2 and 4 */
+                T0_min = (T0 - 8);
+                if (T0_min < PIT_MIN)
+                {
+                    T0_min = PIT_MIN;
+                }
+                T0_max = T0_min + 15;
+                if (T0_max > PIT_MAX)
+                {
+                    T0_max = PIT_MAX;
+                    T0_min = (T0_max - 15);
+                }
+            } else
+            {                              /* if subframe 2 or 4 */
+                /*--------------------------------------------------------------*
+                 * The pitch range for subframe 2 or 4 is encoded with 5 bits:  *
+                 *   T0_min  to T0_max     resolution 1/2 (frac = 0 or 2)       *
+                 *--------------------------------------------------------------*/
+                i = (T0 - T0_min);
+                index = (i << 1) + (T0_frac >> 1);
 
-				Parm_serial(index, 5, &prms);
-			}
-		} else
-		{
-			T0 = Pitch_fr4(&exc[i_subfr], xn, h1, T0_min, T0_max, &T0_frac,
-					pit_flag, PIT_FR2, PIT_FR1_9b, L_SUBFR);
+                Parm_serial(index, 5, &prms);
+            }
+        } else
+        {
+            T0 = Pitch_fr4(&exc[i_subfr], xn, h1, T0_min, T0_max, &T0_frac,
+                    pit_flag, PIT_FR2, PIT_FR1_9b, L_SUBFR);
 
-			/* encode pitch lag */
-			if (pit_flag == 0)             /* if 1st/3rd subframe */
-			{
-				/*--------------------------------------------------------------*
-				 * The pitch range for the 1st/3rd subframe is encoded with     *
-				 * 9 bits and is divided as follows:                            *
-				 *   PIT_MIN to PIT_FR2-1  resolution 1/4 (frac = 0,1,2 or 3)   *
-				 *   PIT_FR2 to PIT_FR1-1  resolution 1/2 (frac = 0 or 1)       *
-				 *   PIT_FR1 to PIT_MAX    resolution 1   (frac = 0)            *
-				 *--------------------------------------------------------------*/
+            /* encode pitch lag */
+            if (pit_flag == 0)             /* if 1st/3rd subframe */
+            {
+                /*--------------------------------------------------------------*
+                 * The pitch range for the 1st/3rd subframe is encoded with     *
+                 * 9 bits and is divided as follows:                            *
+                 *   PIT_MIN to PIT_FR2-1  resolution 1/4 (frac = 0,1,2 or 3)   *
+                 *   PIT_FR2 to PIT_FR1-1  resolution 1/2 (frac = 0 or 1)       *
+                 *   PIT_FR1 to PIT_MAX    resolution 1   (frac = 0)            *
+                 *--------------------------------------------------------------*/
 
-				if (T0 < PIT_FR2)
-				{
-					index = ((T0 << 2) + T0_frac) - (PIT_MIN << 2);
-				} else if(T0 < PIT_FR1_9b)
-				{
-					index = ((((T0 << 1) + (T0_frac >> 1)) - (PIT_FR2<<1)) + ((PIT_FR2 - PIT_MIN)<<2));
-				} else
-				{
-					index = (((T0 - PIT_FR1_9b) + ((PIT_FR2 - PIT_MIN)<<2)) + ((PIT_FR1_9b - PIT_FR2)<<1));
-				}
+                if (T0 < PIT_FR2)
+                {
+                    index = ((T0 << 2) + T0_frac) - (PIT_MIN << 2);
+                } else if(T0 < PIT_FR1_9b)
+                {
+                    index = ((((T0 << 1) + (T0_frac >> 1)) - (PIT_FR2<<1)) + ((PIT_FR2 - PIT_MIN)<<2));
+                } else
+                {
+                    index = (((T0 - PIT_FR1_9b) + ((PIT_FR2 - PIT_MIN)<<2)) + ((PIT_FR1_9b - PIT_FR2)<<1));
+                }
 
-				Parm_serial(index, 9, &prms);
+                Parm_serial(index, 9, &prms);
 
-				/* find T0_min and T0_max for subframe 2 and 4 */
+                /* find T0_min and T0_max for subframe 2 and 4 */
 
-				T0_min = (T0 - 8);
-				if (T0_min < PIT_MIN)
-				{
-					T0_min = PIT_MIN;
-				}
-				T0_max = T0_min + 15;
+                T0_min = (T0 - 8);
+                if (T0_min < PIT_MIN)
+                {
+                    T0_min = PIT_MIN;
+                }
+                T0_max = T0_min + 15;
 
-				if (T0_max > PIT_MAX)
-				{
-					T0_max = PIT_MAX;
-					T0_min = (T0_max - 15);
-				}
-			} else
-			{                              /* if subframe 2 or 4 */
-				/*--------------------------------------------------------------*
-				 * The pitch range for subframe 2 or 4 is encoded with 6 bits:  *
-				 *   T0_min  to T0_max     resolution 1/4 (frac = 0,1,2 or 3)   *
-				 *--------------------------------------------------------------*/
-				i = (T0 - T0_min);
-				index = (i << 2) + T0_frac;
-				Parm_serial(index, 6, &prms);
-			}
-		}
+                if (T0_max > PIT_MAX)
+                {
+                    T0_max = PIT_MAX;
+                    T0_min = (T0_max - 15);
+                }
+            } else
+            {                              /* if subframe 2 or 4 */
+                /*--------------------------------------------------------------*
+                 * The pitch range for subframe 2 or 4 is encoded with 6 bits:  *
+                 *   T0_min  to T0_max     resolution 1/4 (frac = 0,1,2 or 3)   *
+                 *--------------------------------------------------------------*/
+                i = (T0 - T0_min);
+                index = (i << 2) + T0_frac;
+                Parm_serial(index, 6, &prms);
+            }
+        }
 
-		/*-----------------------------------------------------------------*
-		 * Gain clipping test to avoid unstable synthesis on frame erasure *
-		 *-----------------------------------------------------------------*/
+        /*-----------------------------------------------------------------*
+         * Gain clipping test to avoid unstable synthesis on frame erasure *
+         *-----------------------------------------------------------------*/
 
-		clip_gain = 0;
-		if((st->gp_clip[0] < 154) && (st->gp_clip[1] > 14746))
-			clip_gain = 1;
+        clip_gain = 0;
+        if((st->gp_clip[0] < 154) && (st->gp_clip[1] > 14746))
+            clip_gain = 1;
 
-		/*-----------------------------------------------------------------*
-		 * - find unity gain pitch excitation (adaptive codebook entry)    *
-		 *   with fractional interpolation.                                *
-		 * - find filtered pitch exc. y1[]=exc[] convolved with h1[])      *
-		 * - compute pitch gain1                                           *
-		 *-----------------------------------------------------------------*/
-		/* find pitch exitation */
+        /*-----------------------------------------------------------------*
+         * - find unity gain pitch excitation (adaptive codebook entry)    *
+         *   with fractional interpolation.                                *
+         * - find filtered pitch exc. y1[]=exc[] convolved with h1[])      *
+         * - compute pitch gain1                                           *
+         *-----------------------------------------------------------------*/
+        /* find pitch exitation */
 #ifdef ASM_OPT                  /* asm optimization branch */
-		pred_lt4_asm(&exc[i_subfr], T0, T0_frac, L_SUBFR + 1);
+        pred_lt4_asm(&exc[i_subfr], T0, T0_frac, L_SUBFR + 1);
 #else
-		Pred_lt4(&exc[i_subfr], T0, T0_frac, L_SUBFR + 1);
+        Pred_lt4(&exc[i_subfr], T0, T0_frac, L_SUBFR + 1);
 #endif
-		if (*ser_size > NBBITS_9k)
-		{
+        if (*ser_size > NBBITS_9k)
+        {
 #ifdef ASM_OPT                   /* asm optimization branch */
-			Convolve_asm(&exc[i_subfr], h1, y1, L_SUBFR);
+            Convolve_asm(&exc[i_subfr], h1, y1, L_SUBFR);
 #else
-			Convolve(&exc[i_subfr], h1, y1, L_SUBFR);
+            Convolve(&exc[i_subfr], h1, y1, L_SUBFR);
 #endif
-			gain1 = G_pitch(xn, y1, g_coeff, L_SUBFR);
-			/* clip gain if necessary to avoid problem at decoder */
-			if ((clip_gain != 0) && (gain1 > GP_CLIP))
-			{
-				gain1 = GP_CLIP;
-			}
-			/* find energy of new target xn2[] */
-			Updt_tar(xn, dn, y1, gain1, L_SUBFR);       /* dn used temporary */
-		} else
-		{
-			gain1 = 0;
-		}
-		/*-----------------------------------------------------------------*
-		 * - find pitch excitation filtered by 1st order LP filter.        *
-		 * - find filtered pitch exc. y2[]=exc[] convolved with h1[])      *
-		 * - compute pitch gain2                                           *
-		 *-----------------------------------------------------------------*/
-		/* find pitch excitation with lp filter */
-		vo_p0 = exc + i_subfr-1;
-		vo_p1 = code;
-		/* find pitch excitation with lp filter */
-		for (i = 0; i < L_SUBFR/2; i++)
-		{
-			L_tmp = 5898 * *vo_p0++;
-			L_tmp1 = 5898 * *vo_p0;
-			L_tmp += 20972 * *vo_p0++;
-			L_tmp1 += 20972 * *vo_p0++;
-			L_tmp1 += 5898 * *vo_p0--;
-			L_tmp += 5898 * *vo_p0;
-			*vo_p1++ = (L_tmp + 0x4000)>>15;
-			*vo_p1++ = (L_tmp1 + 0x4000)>>15;
-		}
+            gain1 = G_pitch(xn, y1, g_coeff, L_SUBFR);
+            /* clip gain if necessary to avoid problem at decoder */
+            if ((clip_gain != 0) && (gain1 > GP_CLIP))
+            {
+                gain1 = GP_CLIP;
+            }
+            /* find energy of new target xn2[] */
+            Updt_tar(xn, dn, y1, gain1, L_SUBFR);       /* dn used temporary */
+        } else
+        {
+            gain1 = 0;
+        }
+        /*-----------------------------------------------------------------*
+         * - find pitch excitation filtered by 1st order LP filter.        *
+         * - find filtered pitch exc. y2[]=exc[] convolved with h1[])      *
+         * - compute pitch gain2                                           *
+         *-----------------------------------------------------------------*/
+        /* find pitch excitation with lp filter */
+        vo_p0 = exc + i_subfr-1;
+        vo_p1 = code;
+        /* find pitch excitation with lp filter */
+        for (i = 0; i < L_SUBFR/2; i++)
+        {
+            L_tmp = 5898 * *vo_p0++;
+            L_tmp1 = 5898 * *vo_p0;
+            L_tmp += 20972 * *vo_p0++;
+            L_tmp1 += 20972 * *vo_p0++;
+            L_tmp1 += 5898 * *vo_p0--;
+            L_tmp += 5898 * *vo_p0;
+            *vo_p1++ = (L_tmp + 0x4000)>>15;
+            *vo_p1++ = (L_tmp1 + 0x4000)>>15;
+        }
 
 #ifdef ASM_OPT                 /* asm optimization branch */
-		Convolve_asm(code, h1, y2, L_SUBFR);
+        Convolve_asm(code, h1, y2, L_SUBFR);
 #else
-		Convolve(code, h1, y2, L_SUBFR);
+        Convolve(code, h1, y2, L_SUBFR);
 #endif
 
-		gain2 = G_pitch(xn, y2, g_coeff2, L_SUBFR);
+        gain2 = G_pitch(xn, y2, g_coeff2, L_SUBFR);
 
-		/* clip gain if necessary to avoid problem at decoder */
-		if ((clip_gain != 0) && (gain2 > GP_CLIP))
-		{
-			gain2 = GP_CLIP;
-		}
-		/* find energy of new target xn2[] */
-		Updt_tar(xn, xn2, y2, gain2, L_SUBFR);
-		/*-----------------------------------------------------------------*
-		 * use the best prediction (minimise quadratic error).             *
-		 *-----------------------------------------------------------------*/
-		select = 0;
-		if(*ser_size > NBBITS_9k)
-		{
-			L_tmp = 0L;
-			vo_p0 = dn;
-			vo_p1 = xn2;
-			for (i = 0; i < L_SUBFR/2; i++)
-			{
-				L_tmp += *vo_p0 * *vo_p0;
-				vo_p0++;
-				L_tmp -= *vo_p1 * *vo_p1;
-				vo_p1++;
-				L_tmp += *vo_p0 * *vo_p0;
-				vo_p0++;
-				L_tmp -= *vo_p1 * *vo_p1;
-				vo_p1++;
-			}
+        /* clip gain if necessary to avoid problem at decoder */
+        if ((clip_gain != 0) && (gain2 > GP_CLIP))
+        {
+            gain2 = GP_CLIP;
+        }
+        /* find energy of new target xn2[] */
+        Updt_tar(xn, xn2, y2, gain2, L_SUBFR);
+        /*-----------------------------------------------------------------*
+         * use the best prediction (minimise quadratic error).             *
+         *-----------------------------------------------------------------*/
+        select = 0;
+        if(*ser_size > NBBITS_9k)
+        {
+            L_tmp = 0L;
+            vo_p0 = dn;
+            vo_p1 = xn2;
+            for (i = 0; i < L_SUBFR/2; i++)
+            {
+                L_tmp = L_add(L_tmp, *vo_p0 * *vo_p0);
+                vo_p0++;
+                L_tmp = L_sub(L_tmp, *vo_p1 * *vo_p1);
+                vo_p1++;
+                L_tmp = L_add(L_tmp, *vo_p0 * *vo_p0);
+                vo_p0++;
+                L_tmp = L_sub(L_tmp, *vo_p1 * *vo_p1);
+                vo_p1++;
+            }
 
-			if (L_tmp <= 0)
-			{
-				select = 1;
-			}
-			Parm_serial(select, 1, &prms);
-		}
-		if (select == 0)
-		{
-			/* use the lp filter for pitch excitation prediction */
-			gain_pit = gain2;
-			Copy(code, &exc[i_subfr], L_SUBFR);
-			Copy(y2, y1, L_SUBFR);
-			Copy(g_coeff2, g_coeff, 4);
-		} else
-		{
-			/* no filter used for pitch excitation prediction */
-			gain_pit = gain1;
-			Copy(dn, xn2, L_SUBFR);        /* target vector for codebook search */
-		}
-		/*-----------------------------------------------------------------*
-		 * - update cn[] for codebook search                               *
-		 *-----------------------------------------------------------------*/
-		Updt_tar(cn, cn, &exc[i_subfr], gain_pit, L_SUBFR);
+            if (L_tmp <= 0)
+            {
+                select = 1;
+            }
+            Parm_serial(select, 1, &prms);
+        }
+        if (select == 0)
+        {
+            /* use the lp filter for pitch excitation prediction */
+            gain_pit = gain2;
+            Copy(code, &exc[i_subfr], L_SUBFR);
+            Copy(y2, y1, L_SUBFR);
+            Copy(g_coeff2, g_coeff, 4);
+        } else
+        {
+            /* no filter used for pitch excitation prediction */
+            gain_pit = gain1;
+            Copy(dn, xn2, L_SUBFR);        /* target vector for codebook search */
+        }
+        /*-----------------------------------------------------------------*
+         * - update cn[] for codebook search                               *
+         *-----------------------------------------------------------------*/
+        Updt_tar(cn, cn, &exc[i_subfr], gain_pit, L_SUBFR);
 
 #ifdef  ASM_OPT                           /* asm optimization branch */
-		Scale_sig_opt(cn, L_SUBFR, shift);     /* scaling of cn[] to limit dynamic at 12 bits */
+        Scale_sig_opt(cn, L_SUBFR, shift);     /* scaling of cn[] to limit dynamic at 12 bits */
 #else
-		Scale_sig(cn, L_SUBFR, shift);     /* scaling of cn[] to limit dynamic at 12 bits */
+        Scale_sig(cn, L_SUBFR, shift);     /* scaling of cn[] to limit dynamic at 12 bits */
 #endif
-		/*-----------------------------------------------------------------*
-		 * - include fixed-gain pitch contribution into impulse resp. h1[] *
-		 *-----------------------------------------------------------------*/
-		tmp = 0;
-		Preemph(h2, st->tilt_code, L_SUBFR, &tmp);
+        /*-----------------------------------------------------------------*
+         * - include fixed-gain pitch contribution into impulse resp. h1[] *
+         *-----------------------------------------------------------------*/
+        tmp = 0;
+        Preemph(h2, st->tilt_code, L_SUBFR, &tmp);
 
-		if (T0_frac > 2)
-			T0 = (T0 + 1);
-		Pit_shrp(h2, T0, PIT_SHARP, L_SUBFR);
-		/*-----------------------------------------------------------------*
-		 * - Correlation between target xn2[] and impulse response h1[]    *
-		 * - Innovative codebook search                                    *
-		 *-----------------------------------------------------------------*/
-		cor_h_x(h2, xn2, dn);
-		if (*ser_size <= NBBITS_7k)
-		{
-			ACELP_2t64_fx(dn, cn, h2, code, y2, indice);
+        if (T0_frac > 2)
+            T0 = (T0 + 1);
+        Pit_shrp(h2, T0, PIT_SHARP, L_SUBFR);
+        /*-----------------------------------------------------------------*
+         * - Correlation between target xn2[] and impulse response h1[]    *
+         * - Innovative codebook search                                    *
+         *-----------------------------------------------------------------*/
+        cor_h_x(h2, xn2, dn);
+        if (*ser_size <= NBBITS_7k)
+        {
+            ACELP_2t64_fx(dn, cn, h2, code, y2, indice);
 
-			Parm_serial(indice[0], 12, &prms);
-		} else if(*ser_size <= NBBITS_9k)
-		{
-			ACELP_4t64_fx(dn, cn, h2, code, y2, 20, *ser_size, indice);
+            Parm_serial(indice[0], 12, &prms);
+        } else if(*ser_size <= NBBITS_9k)
+        {
+            ACELP_4t64_fx(dn, cn, h2, code, y2, 20, *ser_size, indice);
 
-			Parm_serial(indice[0], 5, &prms);
-			Parm_serial(indice[1], 5, &prms);
-			Parm_serial(indice[2], 5, &prms);
-			Parm_serial(indice[3], 5, &prms);
-		} else if(*ser_size <= NBBITS_12k)
-		{
-			ACELP_4t64_fx(dn, cn, h2, code, y2, 36, *ser_size, indice);
+            Parm_serial(indice[0], 5, &prms);
+            Parm_serial(indice[1], 5, &prms);
+            Parm_serial(indice[2], 5, &prms);
+            Parm_serial(indice[3], 5, &prms);
+        } else if(*ser_size <= NBBITS_12k)
+        {
+            ACELP_4t64_fx(dn, cn, h2, code, y2, 36, *ser_size, indice);
 
-			Parm_serial(indice[0], 9, &prms);
-			Parm_serial(indice[1], 9, &prms);
-			Parm_serial(indice[2], 9, &prms);
-			Parm_serial(indice[3], 9, &prms);
-		} else if(*ser_size <= NBBITS_14k)
-		{
-			ACELP_4t64_fx(dn, cn, h2, code, y2, 44, *ser_size, indice);
+            Parm_serial(indice[0], 9, &prms);
+            Parm_serial(indice[1], 9, &prms);
+            Parm_serial(indice[2], 9, &prms);
+            Parm_serial(indice[3], 9, &prms);
+        } else if(*ser_size <= NBBITS_14k)
+        {
+            ACELP_4t64_fx(dn, cn, h2, code, y2, 44, *ser_size, indice);
 
-			Parm_serial(indice[0], 13, &prms);
-			Parm_serial(indice[1], 13, &prms);
-			Parm_serial(indice[2], 9, &prms);
-			Parm_serial(indice[3], 9, &prms);
-		} else if(*ser_size <= NBBITS_16k)
-		{
-			ACELP_4t64_fx(dn, cn, h2, code, y2, 52, *ser_size, indice);
+            Parm_serial(indice[0], 13, &prms);
+            Parm_serial(indice[1], 13, &prms);
+            Parm_serial(indice[2], 9, &prms);
+            Parm_serial(indice[3], 9, &prms);
+        } else if(*ser_size <= NBBITS_16k)
+        {
+            ACELP_4t64_fx(dn, cn, h2, code, y2, 52, *ser_size, indice);
 
-			Parm_serial(indice[0], 13, &prms);
-			Parm_serial(indice[1], 13, &prms);
-			Parm_serial(indice[2], 13, &prms);
-			Parm_serial(indice[3], 13, &prms);
-		} else if(*ser_size <= NBBITS_18k)
-		{
-			ACELP_4t64_fx(dn, cn, h2, code, y2, 64, *ser_size, indice);
+            Parm_serial(indice[0], 13, &prms);
+            Parm_serial(indice[1], 13, &prms);
+            Parm_serial(indice[2], 13, &prms);
+            Parm_serial(indice[3], 13, &prms);
+        } else if(*ser_size <= NBBITS_18k)
+        {
+            ACELP_4t64_fx(dn, cn, h2, code, y2, 64, *ser_size, indice);
 
-			Parm_serial(indice[0], 2, &prms);
-			Parm_serial(indice[1], 2, &prms);
-			Parm_serial(indice[2], 2, &prms);
-			Parm_serial(indice[3], 2, &prms);
-			Parm_serial(indice[4], 14, &prms);
-			Parm_serial(indice[5], 14, &prms);
-			Parm_serial(indice[6], 14, &prms);
-			Parm_serial(indice[7], 14, &prms);
-		} else if(*ser_size <= NBBITS_20k)
-		{
-			ACELP_4t64_fx(dn, cn, h2, code, y2, 72, *ser_size, indice);
+            Parm_serial(indice[0], 2, &prms);
+            Parm_serial(indice[1], 2, &prms);
+            Parm_serial(indice[2], 2, &prms);
+            Parm_serial(indice[3], 2, &prms);
+            Parm_serial(indice[4], 14, &prms);
+            Parm_serial(indice[5], 14, &prms);
+            Parm_serial(indice[6], 14, &prms);
+            Parm_serial(indice[7], 14, &prms);
+        } else if(*ser_size <= NBBITS_20k)
+        {
+            ACELP_4t64_fx(dn, cn, h2, code, y2, 72, *ser_size, indice);
 
-			Parm_serial(indice[0], 10, &prms);
-			Parm_serial(indice[1], 10, &prms);
-			Parm_serial(indice[2], 2, &prms);
-			Parm_serial(indice[3], 2, &prms);
-			Parm_serial(indice[4], 10, &prms);
-			Parm_serial(indice[5], 10, &prms);
-			Parm_serial(indice[6], 14, &prms);
-			Parm_serial(indice[7], 14, &prms);
-		} else
-		{
-			ACELP_4t64_fx(dn, cn, h2, code, y2, 88, *ser_size, indice);
+            Parm_serial(indice[0], 10, &prms);
+            Parm_serial(indice[1], 10, &prms);
+            Parm_serial(indice[2], 2, &prms);
+            Parm_serial(indice[3], 2, &prms);
+            Parm_serial(indice[4], 10, &prms);
+            Parm_serial(indice[5], 10, &prms);
+            Parm_serial(indice[6], 14, &prms);
+            Parm_serial(indice[7], 14, &prms);
+        } else
+        {
+            ACELP_4t64_fx(dn, cn, h2, code, y2, 88, *ser_size, indice);
 
-			Parm_serial(indice[0], 11, &prms);
-			Parm_serial(indice[1], 11, &prms);
-			Parm_serial(indice[2], 11, &prms);
-			Parm_serial(indice[3], 11, &prms);
-			Parm_serial(indice[4], 11, &prms);
-			Parm_serial(indice[5], 11, &prms);
-			Parm_serial(indice[6], 11, &prms);
-			Parm_serial(indice[7], 11, &prms);
-		}
-		/*-------------------------------------------------------*
-		 * - Add the fixed-gain pitch contribution to code[].    *
-		 *-------------------------------------------------------*/
-		tmp = 0;
-		Preemph(code, st->tilt_code, L_SUBFR, &tmp);
-		Pit_shrp(code, T0, PIT_SHARP, L_SUBFR);
-		/*----------------------------------------------------------*
-		 *  - Compute the fixed codebook gain                       *
-		 *  - quantize fixed codebook gain                          *
-		 *----------------------------------------------------------*/
-		if(*ser_size <= NBBITS_9k)
-		{
-			index = Q_gain2(xn, y1, Q_new + shift, y2, code, g_coeff, L_SUBFR, 6,
-					&gain_pit, &L_gain_code, clip_gain, st->qua_gain);
-			Parm_serial(index, 6, &prms);
-		} else
-		{
-			index = Q_gain2(xn, y1, Q_new + shift, y2, code, g_coeff, L_SUBFR, 7,
-					&gain_pit, &L_gain_code, clip_gain, st->qua_gain);
-			Parm_serial(index, 7, &prms);
-		}
-		/* test quantized gain of pitch for pitch clipping algorithm */
-		Gp_clip_test_gain_pit(gain_pit, st->gp_clip);
+            Parm_serial(indice[0], 11, &prms);
+            Parm_serial(indice[1], 11, &prms);
+            Parm_serial(indice[2], 11, &prms);
+            Parm_serial(indice[3], 11, &prms);
+            Parm_serial(indice[4], 11, &prms);
+            Parm_serial(indice[5], 11, &prms);
+            Parm_serial(indice[6], 11, &prms);
+            Parm_serial(indice[7], 11, &prms);
+        }
+        /*-------------------------------------------------------*
+         * - Add the fixed-gain pitch contribution to code[].    *
+         *-------------------------------------------------------*/
+        tmp = 0;
+        Preemph(code, st->tilt_code, L_SUBFR, &tmp);
+        Pit_shrp(code, T0, PIT_SHARP, L_SUBFR);
+        /*----------------------------------------------------------*
+         *  - Compute the fixed codebook gain                       *
+         *  - quantize fixed codebook gain                          *
+         *----------------------------------------------------------*/
+        if(*ser_size <= NBBITS_9k)
+        {
+            index = Q_gain2(xn, y1, Q_new + shift, y2, code, g_coeff, L_SUBFR, 6,
+                    &gain_pit, &L_gain_code, clip_gain, st->qua_gain);
+            Parm_serial(index, 6, &prms);
+        } else
+        {
+            index = Q_gain2(xn, y1, Q_new + shift, y2, code, g_coeff, L_SUBFR, 7,
+                    &gain_pit, &L_gain_code, clip_gain, st->qua_gain);
+            Parm_serial(index, 7, &prms);
+        }
+        /* test quantized gain of pitch for pitch clipping algorithm */
+        Gp_clip_test_gain_pit(gain_pit, st->gp_clip);
 
-		L_tmp = L_shl(L_gain_code, Q_new);
-		gain_code = extract_h(L_add(L_tmp, 0x8000));
+        L_tmp = L_shl(L_gain_code, Q_new);
+        gain_code = extract_h(L_add(L_tmp, 0x8000));
 
-		/*----------------------------------------------------------*
-		 * Update parameters for the next subframe.                 *
-		 * - tilt of code: 0.0 (unvoiced) to 0.5 (voiced)           *
-		 *----------------------------------------------------------*/
-		/* find voice factor in Q15 (1=voiced, -1=unvoiced) */
-		Copy(&exc[i_subfr], exc2, L_SUBFR);
+        /*----------------------------------------------------------*
+         * Update parameters for the next subframe.                 *
+         * - tilt of code: 0.0 (unvoiced) to 0.5 (voiced)           *
+         *----------------------------------------------------------*/
+        /* find voice factor in Q15 (1=voiced, -1=unvoiced) */
+        Copy(&exc[i_subfr], exc2, L_SUBFR);
 
 #ifdef ASM_OPT                           /* asm optimization branch */
-		Scale_sig_opt(exc2, L_SUBFR, shift);
+        Scale_sig_opt(exc2, L_SUBFR, shift);
 #else
-		Scale_sig(exc2, L_SUBFR, shift);
+        Scale_sig(exc2, L_SUBFR, shift);
 #endif
-		voice_fac = voice_factor(exc2, shift, gain_pit, code, gain_code, L_SUBFR);
-		/* tilt of code for next subframe: 0.5=voiced, 0=unvoiced */
-		st->tilt_code = ((voice_fac >> 2) + 8192);
-		/*------------------------------------------------------*
-		 * - Update filter's memory "mem_w0" for finding the    *
-		 *   target vector in the next subframe.                *
-		 * - Find the total excitation                          *
-		 * - Find synthesis speech to update mem_syn[].         *
-		 *------------------------------------------------------*/
+        voice_fac = voice_factor(exc2, shift, gain_pit, code, gain_code, L_SUBFR);
+        /* tilt of code for next subframe: 0.5=voiced, 0=unvoiced */
+        st->tilt_code = ((voice_fac >> 2) + 8192);
+        /*------------------------------------------------------*
+         * - Update filter's memory "mem_w0" for finding the    *
+         *   target vector in the next subframe.                *
+         * - Find the total excitation                          *
+         * - Find synthesis speech to update mem_syn[].         *
+         *------------------------------------------------------*/
 
-		/* y2 in Q9, gain_pit in Q14 */
-		L_tmp = (gain_code * y2[L_SUBFR - 1])<<1;
-		L_tmp = L_shl(L_tmp, (5 + shift));
-		L_tmp = L_negate(L_tmp);
-		L_tmp += (xn[L_SUBFR - 1] * 16384)<<1;
-		L_tmp -= (y1[L_SUBFR - 1] * gain_pit)<<1;
-		L_tmp = L_shl(L_tmp, (1 - shift));
-		st->mem_w0 = extract_h(L_add(L_tmp, 0x8000));
+        /* y2 in Q9, gain_pit in Q14 */
+        L_tmp = L_mult(gain_code, y2[L_SUBFR - 1]);
+        L_tmp = L_shl(L_tmp, (5 + shift));
+        L_tmp = L_negate(L_tmp);
+        L_tmp += (xn[L_SUBFR - 1] * 16384)<<1;
+        L_tmp -= (y1[L_SUBFR - 1] * gain_pit)<<1;
+        L_tmp = L_shl(L_tmp, (1 - shift));
+        st->mem_w0 = extract_h(L_add(L_tmp, 0x8000));
 
-		if (*ser_size >= NBBITS_24k)
-			Copy(&exc[i_subfr], exc2, L_SUBFR);
+        if (*ser_size >= NBBITS_24k)
+            Copy(&exc[i_subfr], exc2, L_SUBFR);
 
-		for (i = 0; i < L_SUBFR; i++)
-		{
-			/* code in Q9, gain_pit in Q14 */
-			L_tmp = (gain_code * code[i])<<1;
-			L_tmp = (L_tmp << 5);
-			L_tmp += (exc[i + i_subfr] * gain_pit)<<1;
-			L_tmp = L_shl2(L_tmp, 1);
-			exc[i + i_subfr] = extract_h(L_add(L_tmp, 0x8000));
-		}
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            Word32 tmp;
+            /* code in Q9, gain_pit in Q14 */
+            L_tmp = L_mult(gain_code, code[i]);
+            L_tmp = L_shl(L_tmp, 5);
+            tmp = L_mult(exc[i + i_subfr], gain_pit); // (exc[i + i_subfr] * gain_pit)<<1
+            L_tmp = L_add(L_tmp, tmp);
+            L_tmp = L_shl2(L_tmp, 1);
+            exc[i + i_subfr] = extract_h(L_add(L_tmp, 0x8000));
+        }
 
-		Syn_filt(p_Aq,&exc[i_subfr], synth, L_SUBFR, st->mem_syn, 1);
+        Syn_filt(p_Aq,&exc[i_subfr], synth, L_SUBFR, st->mem_syn, 1);
 
-		if(*ser_size >= NBBITS_24k)
-		{
-			/*------------------------------------------------------------*
-			 * phase dispersion to enhance noise in low bit rate          *
-			 *------------------------------------------------------------*/
-			/* L_gain_code in Q16 */
-			VO_L_Extract(L_gain_code, &gain_code, &gain_code_lo);
+        if(*ser_size >= NBBITS_24k)
+        {
+            /*------------------------------------------------------------*
+             * phase dispersion to enhance noise in low bit rate          *
+             *------------------------------------------------------------*/
+            /* L_gain_code in Q16 */
+            VO_L_Extract(L_gain_code, &gain_code, &gain_code_lo);
 
-			/*------------------------------------------------------------*
-			 * noise enhancer                                             *
-			 * ~~~~~~~~~~~~~~                                             *
-			 * - Enhance excitation on noise. (modify gain of code)       *
-			 *   If signal is noisy and LPC filter is stable, move gain   *
-			 *   of code 1.5 dB toward gain of code threshold.            *
-			 *   This decrease by 3 dB noise energy variation.            *
-			 *------------------------------------------------------------*/
-			tmp = (16384 - (voice_fac >> 1));        /* 1=unvoiced, 0=voiced */
-			fac = vo_mult(stab_fac, tmp);
-			L_tmp = L_gain_code;
-			if(L_tmp < st->L_gc_thres)
-			{
-				L_tmp = vo_L_add(L_tmp, Mpy_32_16(gain_code, gain_code_lo, 6226));
-				if(L_tmp > st->L_gc_thres)
-				{
-					L_tmp = st->L_gc_thres;
-				}
-			} else
-			{
-				L_tmp = Mpy_32_16(gain_code, gain_code_lo, 27536);
-				if(L_tmp < st->L_gc_thres)
-				{
-					L_tmp = st->L_gc_thres;
-				}
-			}
-			st->L_gc_thres = L_tmp;
+            /*------------------------------------------------------------*
+             * noise enhancer                                             *
+             * ~~~~~~~~~~~~~~                                             *
+             * - Enhance excitation on noise. (modify gain of code)       *
+             *   If signal is noisy and LPC filter is stable, move gain   *
+             *   of code 1.5 dB toward gain of code threshold.            *
+             *   This decrease by 3 dB noise energy variation.            *
+             *------------------------------------------------------------*/
+            tmp = (16384 - (voice_fac >> 1));        /* 1=unvoiced, 0=voiced */
+            fac = vo_mult(stab_fac, tmp);
+            L_tmp = L_gain_code;
+            if(L_tmp < st->L_gc_thres)
+            {
+                L_tmp = vo_L_add(L_tmp, Mpy_32_16(gain_code, gain_code_lo, 6226));
+                if(L_tmp > st->L_gc_thres)
+                {
+                    L_tmp = st->L_gc_thres;
+                }
+            } else
+            {
+                L_tmp = Mpy_32_16(gain_code, gain_code_lo, 27536);
+                if(L_tmp < st->L_gc_thres)
+                {
+                    L_tmp = st->L_gc_thres;
+                }
+            }
+            st->L_gc_thres = L_tmp;
 
-			L_gain_code = Mpy_32_16(gain_code, gain_code_lo, (32767 - fac));
-			VO_L_Extract(L_tmp, &gain_code, &gain_code_lo);
-			L_gain_code = vo_L_add(L_gain_code, Mpy_32_16(gain_code, gain_code_lo, fac));
+            L_gain_code = Mpy_32_16(gain_code, gain_code_lo, (32767 - fac));
+            VO_L_Extract(L_tmp, &gain_code, &gain_code_lo);
+            L_gain_code = vo_L_add(L_gain_code, Mpy_32_16(gain_code, gain_code_lo, fac));
 
-			/*------------------------------------------------------------*
-			 * pitch enhancer                                             *
-			 * ~~~~~~~~~~~~~~                                             *
-			 * - Enhance excitation on voice. (HP filtering of code)      *
-			 *   On voiced signal, filtering of code by a smooth fir HP   *
-			 *   filter to decrease energy of code in low frequency.      *
-			 *------------------------------------------------------------*/
+            /*------------------------------------------------------------*
+             * pitch enhancer                                             *
+             * ~~~~~~~~~~~~~~                                             *
+             * - Enhance excitation on voice. (HP filtering of code)      *
+             *   On voiced signal, filtering of code by a smooth fir HP   *
+             *   filter to decrease energy of code in low frequency.      *
+             *------------------------------------------------------------*/
 
-			tmp = ((voice_fac >> 3) + 4096); /* 0.25=voiced, 0=unvoiced */
+            tmp = ((voice_fac >> 3) + 4096); /* 0.25=voiced, 0=unvoiced */
 
-			L_tmp = L_deposit_h(code[0]);
-			L_tmp -= (code[1] * tmp)<<1;
-			code2[0] = vo_round(L_tmp);
+            L_tmp = L_deposit_h(code[0]);
+            L_tmp -= (code[1] * tmp)<<1;
+            code2[0] = vo_round(L_tmp);
 
-			for (i = 1; i < L_SUBFR - 1; i++)
-			{
-				L_tmp = L_deposit_h(code[i]);
-				L_tmp -= (code[i + 1] * tmp)<<1;
-				L_tmp -= (code[i - 1] * tmp)<<1;
-				code2[i] = vo_round(L_tmp);
-			}
+            for (i = 1; i < L_SUBFR - 1; i++)
+            {
+                L_tmp = L_deposit_h(code[i]);
+                L_tmp -= (code[i + 1] * tmp)<<1;
+                L_tmp -= (code[i - 1] * tmp)<<1;
+                code2[i] = vo_round(L_tmp);
+            }
 
-			L_tmp = L_deposit_h(code[L_SUBFR - 1]);
-			L_tmp -= (code[L_SUBFR - 2] * tmp)<<1;
-			code2[L_SUBFR - 1] = vo_round(L_tmp);
+            L_tmp = L_deposit_h(code[L_SUBFR - 1]);
+            L_tmp -= (code[L_SUBFR - 2] * tmp)<<1;
+            code2[L_SUBFR - 1] = vo_round(L_tmp);
 
-			/* build excitation */
-			gain_code = vo_round(L_shl(L_gain_code, Q_new));
+            /* build excitation */
+            gain_code = vo_round(L_shl(L_gain_code, Q_new));
 
-			for (i = 0; i < L_SUBFR; i++)
-			{
-				L_tmp = (code2[i] * gain_code)<<1;
-				L_tmp = (L_tmp << 5);
-				L_tmp += (exc2[i] * gain_pit)<<1;
-				L_tmp = (L_tmp << 1);
-				exc2[i] = vo_round(L_tmp);
-			}
+            for (i = 0; i < L_SUBFR; i++)
+            {
+                L_tmp = L_mult(code2[i], gain_code);
+                L_tmp = L_shl(L_tmp, 5);
+                L_tmp = L_add(L_tmp, L_mult(exc2[i], gain_pit));
+                L_tmp = L_shl(L_tmp, 1);
+                exc2[i] = voround(L_tmp);
+            }
 
-			corr_gain = synthesis(p_Aq, exc2, Q_new, &speech16k[i_subfr * 5 / 4], st);
-			Parm_serial(corr_gain, 4, &prms);
-		}
-		p_A += (M + 1);
-		p_Aq += (M + 1);
-	}                                      /* end of subframe loop */
+            corr_gain = synthesis(p_Aq, exc2, Q_new, &speech16k[i_subfr * 5 / 4], st);
+            Parm_serial(corr_gain, 4, &prms);
+        }
+        p_A += (M + 1);
+        p_Aq += (M + 1);
+    }                                      /* end of subframe loop */
 
-	/*--------------------------------------------------*
-	 * Update signal for next frame.                    *
-	 * -> save past of speech[], wsp[] and exc[].       *
-	 *--------------------------------------------------*/
-	Copy(&old_speech[L_FRAME], st->old_speech, L_TOTAL - L_FRAME);
-	Copy(&old_wsp[L_FRAME / OPL_DECIM], st->old_wsp, PIT_MAX / OPL_DECIM);
-	Copy(&old_exc[L_FRAME], st->old_exc, PIT_MAX + L_INTERPOL);
-	return;
+    /*--------------------------------------------------*
+     * Update signal for next frame.                    *
+     * -> save past of speech[], wsp[] and exc[].       *
+     *--------------------------------------------------*/
+    Copy(&old_speech[L_FRAME], st->old_speech, L_TOTAL - L_FRAME);
+    Copy(&old_wsp[L_FRAME / OPL_DECIM], st->old_wsp, PIT_MAX / OPL_DECIM);
+    Copy(&old_exc[L_FRAME], st->old_exc, PIT_MAX + L_INTERPOL);
+    return;
 }
 
 /*-----------------------------------------------------*
@@ -1329,225 +1333,225 @@
 *-----------------------------------------------------*/
 
 static Word16 synthesis(
-		Word16 Aq[],                          /* A(z)  : quantized Az               */
-		Word16 exc[],                         /* (i)   : excitation at 12kHz        */
-		Word16 Q_new,                         /* (i)   : scaling performed on exc   */
-		Word16 synth16k[],                    /* (o)   : 16kHz synthesis signal     */
-		Coder_State * st                      /* (i/o) : State structure            */
-		)
+        Word16 Aq[],                          /* A(z)  : quantized Az               */
+        Word16 exc[],                         /* (i)   : excitation at 12kHz        */
+        Word16 Q_new,                         /* (i)   : scaling performed on exc   */
+        Word16 synth16k[],                    /* (o)   : 16kHz synthesis signal     */
+        Coder_State * st                      /* (i/o) : State structure            */
+        )
 {
-	Word16 fac, tmp, exp;
-	Word16 ener, exp_ener;
-	Word32 L_tmp, i;
+    Word16 fac, tmp, exp;
+    Word16 ener, exp_ener;
+    Word32 L_tmp, i;
 
-	Word16 synth_hi[M + L_SUBFR], synth_lo[M + L_SUBFR];
-	Word16 synth[L_SUBFR];
-	Word16 HF[L_SUBFR16k];                 /* High Frequency vector      */
-	Word16 Ap[M + 1];
+    Word16 synth_hi[M + L_SUBFR], synth_lo[M + L_SUBFR];
+    Word16 synth[L_SUBFR];
+    Word16 HF[L_SUBFR16k];                 /* High Frequency vector      */
+    Word16 Ap[M + 1];
 
-	Word16 HF_SP[L_SUBFR16k];              /* High Frequency vector (from original signal) */
+    Word16 HF_SP[L_SUBFR16k];              /* High Frequency vector (from original signal) */
 
-	Word16 HP_est_gain, HP_calc_gain, HP_corr_gain;
-	Word16 dist_min, dist;
-	Word16 HP_gain_ind = 0;
-	Word16 gain1, gain2;
-	Word16 weight1, weight2;
+    Word16 HP_est_gain, HP_calc_gain, HP_corr_gain;
+    Word16 dist_min, dist;
+    Word16 HP_gain_ind = 0;
+    Word16 gain1, gain2;
+    Word16 weight1, weight2;
 
-	/*------------------------------------------------------------*
-	 * speech synthesis                                           *
-	 * ~~~~~~~~~~~~~~~~                                           *
-	 * - Find synthesis speech corresponding to exc2[].           *
-	 * - Perform fixed deemphasis and hp 50hz filtering.          *
-	 * - Oversampling from 12.8kHz to 16kHz.                      *
-	 *------------------------------------------------------------*/
-	Copy(st->mem_syn_hi, synth_hi, M);
-	Copy(st->mem_syn_lo, synth_lo, M);
+    /*------------------------------------------------------------*
+     * speech synthesis                                           *
+     * ~~~~~~~~~~~~~~~~                                           *
+     * - Find synthesis speech corresponding to exc2[].           *
+     * - Perform fixed deemphasis and hp 50hz filtering.          *
+     * - Oversampling from 12.8kHz to 16kHz.                      *
+     *------------------------------------------------------------*/
+    Copy(st->mem_syn_hi, synth_hi, M);
+    Copy(st->mem_syn_lo, synth_lo, M);
 
 #ifdef ASM_OPT                 /* asm optimization branch */
-	Syn_filt_32_asm(Aq, M, exc, Q_new, synth_hi + M, synth_lo + M, L_SUBFR);
+    Syn_filt_32_asm(Aq, M, exc, Q_new, synth_hi + M, synth_lo + M, L_SUBFR);
 #else
-	Syn_filt_32(Aq, M, exc, Q_new, synth_hi + M, synth_lo + M, L_SUBFR);
+    Syn_filt_32(Aq, M, exc, Q_new, synth_hi + M, synth_lo + M, L_SUBFR);
 #endif
 
-	Copy(synth_hi + L_SUBFR, st->mem_syn_hi, M);
-	Copy(synth_lo + L_SUBFR, st->mem_syn_lo, M);
+    Copy(synth_hi + L_SUBFR, st->mem_syn_hi, M);
+    Copy(synth_lo + L_SUBFR, st->mem_syn_lo, M);
 
 #ifdef ASM_OPT                 /* asm optimization branch */
-	Deemph_32_asm(synth_hi + M, synth_lo + M, synth, &(st->mem_deemph));
+    Deemph_32_asm(synth_hi + M, synth_lo + M, synth, &(st->mem_deemph));
 #else
-	Deemph_32(synth_hi + M, synth_lo + M, synth, PREEMPH_FAC, L_SUBFR, &(st->mem_deemph));
+    Deemph_32(synth_hi + M, synth_lo + M, synth, PREEMPH_FAC, L_SUBFR, &(st->mem_deemph));
 #endif
 
-	HP50_12k8(synth, L_SUBFR, st->mem_sig_out);
+    HP50_12k8(synth, L_SUBFR, st->mem_sig_out);
 
-	/* Original speech signal as reference for high band gain quantisation */
-	for (i = 0; i < L_SUBFR16k; i++)
-	{
-		HF_SP[i] = synth16k[i];
-	}
+    /* Original speech signal as reference for high band gain quantisation */
+    for (i = 0; i < L_SUBFR16k; i++)
+    {
+        HF_SP[i] = synth16k[i];
+    }
 
-	/*------------------------------------------------------*
-	 * HF noise synthesis                                   *
-	 * ~~~~~~~~~~~~~~~~~~                                   *
-	 * - Generate HF noise between 5.5 and 7.5 kHz.         *
-	 * - Set energy of noise according to synthesis tilt.   *
-	 *     tilt > 0.8 ==> - 14 dB (voiced)                  *
-	 *     tilt   0.5 ==> - 6 dB  (voiced or noise)         *
-	 *     tilt < 0.0 ==>   0 dB  (noise)                   *
-	 *------------------------------------------------------*/
-	/* generate white noise vector */
-	for (i = 0; i < L_SUBFR16k; i++)
-	{
-		HF[i] = Random(&(st->seed2))>>3;
-	}
-	/* energy of excitation */
+    /*------------------------------------------------------*
+     * HF noise synthesis                                   *
+     * ~~~~~~~~~~~~~~~~~~                                   *
+     * - Generate HF noise between 5.5 and 7.5 kHz.         *
+     * - Set energy of noise according to synthesis tilt.   *
+     *     tilt > 0.8 ==> - 14 dB (voiced)                  *
+     *     tilt   0.5 ==> - 6 dB  (voiced or noise)         *
+     *     tilt < 0.0 ==>   0 dB  (noise)                   *
+     *------------------------------------------------------*/
+    /* generate white noise vector */
+    for (i = 0; i < L_SUBFR16k; i++)
+    {
+        HF[i] = Random(&(st->seed2))>>3;
+    }
+    /* energy of excitation */
 #ifdef ASM_OPT                    /* asm optimization branch */
-	Scale_sig_opt(exc, L_SUBFR, -3);
-	Q_new = Q_new - 3;
-	ener = extract_h(Dot_product12_asm(exc, exc, L_SUBFR, &exp_ener));
+    Scale_sig_opt(exc, L_SUBFR, -3);
+    Q_new = Q_new - 3;
+    ener = extract_h(Dot_product12_asm(exc, exc, L_SUBFR, &exp_ener));
 #else
-	Scale_sig(exc, L_SUBFR, -3);
-	Q_new = Q_new - 3;
-	ener = extract_h(Dot_product12(exc, exc, L_SUBFR, &exp_ener));
+    Scale_sig(exc, L_SUBFR, -3);
+    Q_new = Q_new - 3;
+    ener = extract_h(Dot_product12(exc, exc, L_SUBFR, &exp_ener));
 #endif
 
-	exp_ener = exp_ener - (Q_new + Q_new);
-	/* set energy of white noise to energy of excitation */
+    exp_ener = exp_ener - (Q_new + Q_new);
+    /* set energy of white noise to energy of excitation */
 #ifdef ASM_OPT              /* asm optimization branch */
-	tmp = extract_h(Dot_product12_asm(HF, HF, L_SUBFR16k, &exp));
+    tmp = extract_h(Dot_product12_asm(HF, HF, L_SUBFR16k, &exp));
 #else
-	tmp = extract_h(Dot_product12(HF, HF, L_SUBFR16k, &exp));
+    tmp = extract_h(Dot_product12(HF, HF, L_SUBFR16k, &exp));
 #endif
 
-	if(tmp > ener)
-	{
-		tmp = (tmp >> 1);                 /* Be sure tmp < ener */
-		exp = (exp + 1);
-	}
-	L_tmp = L_deposit_h(div_s(tmp, ener)); /* result is normalized */
-	exp = (exp - exp_ener);
-	Isqrt_n(&L_tmp, &exp);
-	L_tmp = L_shl(L_tmp, (exp + 1));       /* L_tmp x 2, L_tmp in Q31 */
-	tmp = extract_h(L_tmp);                /* tmp = 2 x sqrt(ener_exc/ener_hf) */
+    if(tmp > ener)
+    {
+        tmp = (tmp >> 1);                 /* Be sure tmp < ener */
+        exp = (exp + 1);
+    }
+    L_tmp = L_deposit_h(div_s(tmp, ener)); /* result is normalized */
+    exp = (exp - exp_ener);
+    Isqrt_n(&L_tmp, &exp);
+    L_tmp = L_shl(L_tmp, (exp + 1));       /* L_tmp x 2, L_tmp in Q31 */
+    tmp = extract_h(L_tmp);                /* tmp = 2 x sqrt(ener_exc/ener_hf) */
 
-	for (i = 0; i < L_SUBFR16k; i++)
-	{
-		HF[i] = vo_mult(HF[i], tmp);
-	}
+    for (i = 0; i < L_SUBFR16k; i++)
+    {
+        HF[i] = vo_mult(HF[i], tmp);
+    }
 
-	/* find tilt of synthesis speech (tilt: 1=voiced, -1=unvoiced) */
-	HP400_12k8(synth, L_SUBFR, st->mem_hp400);
+    /* find tilt of synthesis speech (tilt: 1=voiced, -1=unvoiced) */
+    HP400_12k8(synth, L_SUBFR, st->mem_hp400);
 
-	L_tmp = 1L;
-	for (i = 0; i < L_SUBFR; i++)
-		L_tmp += (synth[i] * synth[i])<<1;
+    L_tmp = 1L;
+    for (i = 0; i < L_SUBFR; i++)
+        L_tmp += (synth[i] * synth[i])<<1;
 
-	exp = norm_l(L_tmp);
-	ener = extract_h(L_tmp << exp);   /* ener = r[0] */
+    exp = norm_l(L_tmp);
+    ener = extract_h(L_tmp << exp);   /* ener = r[0] */
 
-	L_tmp = 1L;
-	for (i = 1; i < L_SUBFR; i++)
-		L_tmp +=(synth[i] * synth[i - 1])<<1;
+    L_tmp = 1L;
+    for (i = 1; i < L_SUBFR; i++)
+        L_tmp +=(synth[i] * synth[i - 1])<<1;
 
-	tmp = extract_h(L_tmp << exp);    /* tmp = r[1] */
+    tmp = extract_h(L_tmp << exp);    /* tmp = r[1] */
 
-	if (tmp > 0)
-	{
-		fac = div_s(tmp, ener);
-	} else
-	{
-		fac = 0;
-	}
+    if (tmp > 0)
+    {
+        fac = div_s(tmp, ener);
+    } else
+    {
+        fac = 0;
+    }
 
-	/* modify energy of white noise according to synthesis tilt */
-	gain1 = 32767 - fac;
-	gain2 = vo_mult(gain1, 20480);
-	gain2 = shl(gain2, 1);
+    /* modify energy of white noise according to synthesis tilt */
+    gain1 = 32767 - fac;
+    gain2 = vo_mult(gain1, 20480);
+    gain2 = shl(gain2, 1);
 
-	if (st->vad_hist > 0)
-	{
-		weight1 = 0;
-		weight2 = 32767;
-	} else
-	{
-		weight1 = 32767;
-		weight2 = 0;
-	}
-	tmp = vo_mult(weight1, gain1);
-	tmp = add1(tmp, vo_mult(weight2, gain2));
+    if (st->vad_hist > 0)
+    {
+        weight1 = 0;
+        weight2 = 32767;
+    } else
+    {
+        weight1 = 32767;
+        weight2 = 0;
+    }
+    tmp = vo_mult(weight1, gain1);
+    tmp = add1(tmp, vo_mult(weight2, gain2));
 
-	if (tmp != 0)
-	{
-		tmp = (tmp + 1);
-	}
-	HP_est_gain = tmp;
+    if (tmp != 0)
+    {
+        tmp = (tmp + 1);
+    }
+    HP_est_gain = tmp;
 
-	if(HP_est_gain < 3277)
-	{
-		HP_est_gain = 3277;                /* 0.1 in Q15 */
-	}
-	/* synthesis of noise: 4.8kHz..5.6kHz --> 6kHz..7kHz */
-	Weight_a(Aq, Ap, 19661, M);            /* fac=0.6 */
+    if(HP_est_gain < 3277)
+    {
+        HP_est_gain = 3277;                /* 0.1 in Q15 */
+    }
+    /* synthesis of noise: 4.8kHz..5.6kHz --> 6kHz..7kHz */
+    Weight_a(Aq, Ap, 19661, M);            /* fac=0.6 */
 
 #ifdef ASM_OPT                /* asm optimization branch */
-	Syn_filt_asm(Ap, HF, HF, st->mem_syn_hf);
-	/* noise High Pass filtering (1ms of delay) */
-	Filt_6k_7k_asm(HF, L_SUBFR16k, st->mem_hf);
-	/* filtering of the original signal */
-	Filt_6k_7k_asm(HF_SP, L_SUBFR16k, st->mem_hf2);
+    Syn_filt_asm(Ap, HF, HF, st->mem_syn_hf);
+    /* noise High Pass filtering (1ms of delay) */
+    Filt_6k_7k_asm(HF, L_SUBFR16k, st->mem_hf);
+    /* filtering of the original signal */
+    Filt_6k_7k_asm(HF_SP, L_SUBFR16k, st->mem_hf2);
 
-	/* check the gain difference */
-	Scale_sig_opt(HF_SP, L_SUBFR16k, -1);
-	ener = extract_h(Dot_product12_asm(HF_SP, HF_SP, L_SUBFR16k, &exp_ener));
-	/* set energy of white noise to energy of excitation */
-	tmp = extract_h(Dot_product12_asm(HF, HF, L_SUBFR16k, &exp));
+    /* check the gain difference */
+    Scale_sig_opt(HF_SP, L_SUBFR16k, -1);
+    ener = extract_h(Dot_product12_asm(HF_SP, HF_SP, L_SUBFR16k, &exp_ener));
+    /* set energy of white noise to energy of excitation */
+    tmp = extract_h(Dot_product12_asm(HF, HF, L_SUBFR16k, &exp));
 #else
-	Syn_filt(Ap, HF, HF, L_SUBFR16k, st->mem_syn_hf, 1);
-	/* noise High Pass filtering (1ms of delay) */
-	Filt_6k_7k(HF, L_SUBFR16k, st->mem_hf);
-	/* filtering of the original signal */
-	Filt_6k_7k(HF_SP, L_SUBFR16k, st->mem_hf2);
-	/* check the gain difference */
-	Scale_sig(HF_SP, L_SUBFR16k, -1);
-	ener = extract_h(Dot_product12(HF_SP, HF_SP, L_SUBFR16k, &exp_ener));
-	/* set energy of white noise to energy of excitation */
-	tmp = extract_h(Dot_product12(HF, HF, L_SUBFR16k, &exp));
+    Syn_filt(Ap, HF, HF, L_SUBFR16k, st->mem_syn_hf, 1);
+    /* noise High Pass filtering (1ms of delay) */
+    Filt_6k_7k(HF, L_SUBFR16k, st->mem_hf);
+    /* filtering of the original signal */
+    Filt_6k_7k(HF_SP, L_SUBFR16k, st->mem_hf2);
+    /* check the gain difference */
+    Scale_sig(HF_SP, L_SUBFR16k, -1);
+    ener = extract_h(Dot_product12(HF_SP, HF_SP, L_SUBFR16k, &exp_ener));
+    /* set energy of white noise to energy of excitation */
+    tmp = extract_h(Dot_product12(HF, HF, L_SUBFR16k, &exp));
 #endif
 
-	if (tmp > ener)
-	{
-		tmp = (tmp >> 1);                 /* Be sure tmp < ener */
-		exp = (exp + 1);
-	}
-	L_tmp = L_deposit_h(div_s(tmp, ener)); /* result is normalized */
-	exp = vo_sub(exp, exp_ener);
-	Isqrt_n(&L_tmp, &exp);
-	L_tmp = L_shl(L_tmp, exp);             /* L_tmp, L_tmp in Q31 */
-	HP_calc_gain = extract_h(L_tmp);       /* tmp = sqrt(ener_input/ener_hf) */
+    if (tmp > ener)
+    {
+        tmp = (tmp >> 1);                 /* Be sure tmp < ener */
+        exp = (exp + 1);
+    }
+    L_tmp = L_deposit_h(div_s(tmp, ener)); /* result is normalized */
+    exp = vo_sub(exp, exp_ener);
+    Isqrt_n(&L_tmp, &exp);
+    L_tmp = L_shl(L_tmp, exp);             /* L_tmp, L_tmp in Q31 */
+    HP_calc_gain = extract_h(L_tmp);       /* tmp = sqrt(ener_input/ener_hf) */
 
-	/* st->gain_alpha *= st->dtx_encSt->dtxHangoverCount/7 */
-	L_tmp = (vo_L_mult(st->dtx_encSt->dtxHangoverCount, 4681) << 15);
-	st->gain_alpha = vo_mult(st->gain_alpha, extract_h(L_tmp));
+    /* st->gain_alpha *= st->dtx_encSt->dtxHangoverCount/7 */
+    L_tmp = (vo_L_mult(st->dtx_encSt->dtxHangoverCount, 4681) << 15);
+    st->gain_alpha = vo_mult(st->gain_alpha, extract_h(L_tmp));
 
-	if(st->dtx_encSt->dtxHangoverCount > 6)
-		st->gain_alpha = 32767;
-	HP_est_gain = HP_est_gain >> 1;     /* From Q15 to Q14 */
-	HP_corr_gain = add1(vo_mult(HP_calc_gain, st->gain_alpha), vo_mult((32767 - st->gain_alpha), HP_est_gain));
+    if(st->dtx_encSt->dtxHangoverCount > 6)
+        st->gain_alpha = 32767;
+    HP_est_gain = HP_est_gain >> 1;     /* From Q15 to Q14 */
+    HP_corr_gain = add1(vo_mult(HP_calc_gain, st->gain_alpha), vo_mult((32767 - st->gain_alpha), HP_est_gain));
 
-	/* Quantise the correction gain */
-	dist_min = 32767;
-	for (i = 0; i < 16; i++)
-	{
-		dist = vo_mult((HP_corr_gain - HP_gain[i]), (HP_corr_gain - HP_gain[i]));
-		if (dist_min > dist)
-		{
-			dist_min = dist;
-			HP_gain_ind = i;
-		}
-	}
-	HP_corr_gain = HP_gain[HP_gain_ind];
-	/* return the quantised gain index when using the highest mode, otherwise zero */
-	return (HP_gain_ind);
+    /* Quantise the correction gain */
+    dist_min = 32767;
+    for (i = 0; i < 16; i++)
+    {
+        dist = vo_mult((HP_corr_gain - HP_gain[i]), (HP_corr_gain - HP_gain[i]));
+        if (dist_min > dist)
+        {
+            dist_min = dist;
+            HP_gain_ind = i;
+        }
+    }
+    HP_corr_gain = HP_gain[HP_gain_ind];
+    /* return the quantised gain index when using the highest mode, otherwise zero */
+    return (HP_gain_ind);
 }
 
 /*************************************************
@@ -1558,33 +1562,33 @@
 
 int AMR_Enc_Encode(HAMRENC hCodec)
 {
-	Word32 i;
-	Coder_State *gData = (Coder_State*)hCodec;
-	Word16 *signal;
-	Word16 packed_size = 0;
-	Word16 prms[NB_BITS_MAX];
-	Word16 coding_mode = 0, nb_bits, allow_dtx, mode, reset_flag;
-	mode = gData->mode;
-	coding_mode = gData->mode;
-	nb_bits = nb_of_bits[mode];
-	signal = (Word16 *)gData->inputStream;
-	allow_dtx = gData->allow_dtx;
+    Word32 i;
+    Coder_State *gData = (Coder_State*)hCodec;
+    Word16 *signal;
+    Word16 packed_size = 0;
+    Word16 prms[NB_BITS_MAX];
+    Word16 coding_mode = 0, nb_bits, allow_dtx, mode, reset_flag;
+    mode = gData->mode;
+    coding_mode = gData->mode;
+    nb_bits = nb_of_bits[mode];
+    signal = (Word16 *)gData->inputStream;
+    allow_dtx = gData->allow_dtx;
 
-	/* check for homing frame */
-	reset_flag = encoder_homing_frame_test(signal);
+    /* check for homing frame */
+    reset_flag = encoder_homing_frame_test(signal);
 
-	for (i = 0; i < L_FRAME16k; i++)   /* Delete the 2 LSBs (14-bit input) */
-	{
-		*(signal + i) = (Word16) (*(signal + i) & 0xfffC);
-	}
+    for (i = 0; i < L_FRAME16k; i++)   /* Delete the 2 LSBs (14-bit input) */
+    {
+        *(signal + i) = (Word16) (*(signal + i) & 0xfffC);
+    }
 
-	coder(&coding_mode, signal, prms, &nb_bits, gData, allow_dtx);
-	packed_size = PackBits(prms, coding_mode, mode, gData);
-	if (reset_flag != 0)
-	{
-		Reset_encoder(gData, 1);
-	}
-	return packed_size;
+    coder(&coding_mode, signal, prms, &nb_bits, gData, allow_dtx);
+    packed_size = PackBits(prms, coding_mode, mode, gData);
+    if (reset_flag != 0)
+    {
+        Reset_encoder(gData, 1);
+    }
+    return packed_size;
 }
 
 /***************************************************************************
@@ -1594,94 +1598,94 @@
 ***************************************************************************/
 
 VO_U32 VO_API voAMRWB_Init(VO_HANDLE * phCodec,                   /* o: the audio codec handle */
-						   VO_AUDIO_CODINGTYPE vType,             /* i: Codec Type ID */
-						   VO_CODEC_INIT_USERDATA * pUserData     /* i: init Parameters */
-						   )
+                           VO_AUDIO_CODINGTYPE vType,             /* i: Codec Type ID */
+                           VO_CODEC_INIT_USERDATA * pUserData     /* i: init Parameters */
+                           )
 {
-	Coder_State *st;
-	FrameStream *stream;
+    Coder_State *st;
+    FrameStream *stream;
 #ifdef USE_DEAULT_MEM
-	VO_MEM_OPERATOR voMemoprator;
+    VO_MEM_OPERATOR voMemoprator;
 #endif
-	VO_MEM_OPERATOR *pMemOP;
+    VO_MEM_OPERATOR *pMemOP;
         UNUSED(vType);
 
-	int interMem = 0;
+    int interMem = 0;
 
-	if(pUserData == NULL || pUserData->memflag != VO_IMF_USERMEMOPERATOR || pUserData->memData == NULL )
-	{
+    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;
+        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;
+        *phCodec = NULL;
+        return VO_ERR_INVALID_ARG;
 #endif
-	}
-	else
-	{
-		pMemOP = (VO_MEM_OPERATOR *)pUserData->memData;
-	}
-	/*-------------------------------------------------------------------------*
-	 * Memory allocation for coder state.                                      *
-	 *-------------------------------------------------------------------------*/
-	if ((st = (Coder_State *)mem_malloc(pMemOP, sizeof(Coder_State), 32, VO_INDEX_ENC_AMRWB)) == NULL)
-	{
-		return VO_ERR_OUTOF_MEMORY;
-	}
+    }
+    else
+    {
+        pMemOP = (VO_MEM_OPERATOR *)pUserData->memData;
+    }
+    /*-------------------------------------------------------------------------*
+     * Memory allocation for coder state.                                      *
+     *-------------------------------------------------------------------------*/
+    if ((st = (Coder_State *)mem_malloc(pMemOP, sizeof(Coder_State), 32, VO_INDEX_ENC_AMRWB)) == NULL)
+    {
+        return VO_ERR_OUTOF_MEMORY;
+    }
 
-	st->vadSt = NULL;
-	st->dtx_encSt = NULL;
-	st->sid_update_counter = 3;
-	st->sid_handover_debt = 0;
-	st->prev_ft = TX_SPEECH;
-	st->inputStream = NULL;
-	st->inputSize = 0;
+    st->vadSt = NULL;
+    st->dtx_encSt = NULL;
+    st->sid_update_counter = 3;
+    st->sid_handover_debt = 0;
+    st->prev_ft = TX_SPEECH;
+    st->inputStream = NULL;
+    st->inputSize = 0;
 
-	/* Default setting */
-	st->mode = VOAMRWB_MD2385;                        /* bit rate 23.85kbps */
-	st->frameType = VOAMRWB_RFC3267;                  /* frame type: RFC3267 */
-	st->allow_dtx = 0;                                /* disable DTX mode */
+    /* Default setting */
+    st->mode = VOAMRWB_MD2385;                        /* bit rate 23.85kbps */
+    st->frameType = VOAMRWB_RFC3267;                  /* frame type: RFC3267 */
+    st->allow_dtx = 0;                                /* disable DTX mode */
 
-	st->outputStream = NULL;
-	st->outputSize = 0;
+    st->outputStream = NULL;
+    st->outputSize = 0;
 
-	st->stream = (FrameStream *)mem_malloc(pMemOP, sizeof(FrameStream), 32, VO_INDEX_ENC_AMRWB);
-	if(st->stream == NULL)
-		return VO_ERR_OUTOF_MEMORY;
+    st->stream = (FrameStream *)mem_malloc(pMemOP, sizeof(FrameStream), 32, VO_INDEX_ENC_AMRWB);
+    if(st->stream == NULL)
+        return VO_ERR_OUTOF_MEMORY;
 
-	st->stream->frame_ptr = (unsigned char *)mem_malloc(pMemOP, Frame_Maxsize, 32, VO_INDEX_ENC_AMRWB);
-	if(st->stream->frame_ptr == NULL)
-		return  VO_ERR_OUTOF_MEMORY;
+    st->stream->frame_ptr = (unsigned char *)mem_malloc(pMemOP, Frame_Maxsize, 32, VO_INDEX_ENC_AMRWB);
+    if(st->stream->frame_ptr == NULL)
+        return  VO_ERR_OUTOF_MEMORY;
 
-	stream = st->stream;
-	voAWB_InitFrameBuffer(stream);
+    stream = st->stream;
+    voAWB_InitFrameBuffer(stream);
 
-	wb_vad_init(&(st->vadSt), pMemOP);
-	dtx_enc_init(&(st->dtx_encSt), isf_init, pMemOP);
+    wb_vad_init(&(st->vadSt), pMemOP);
+    dtx_enc_init(&(st->dtx_encSt), isf_init, pMemOP);
 
-	Reset_encoder((void *) st, 1);
+    Reset_encoder((void *) st, 1);
 
-	if(interMem)
-	{
-		st->voMemoprator.Alloc = cmnMemAlloc;
-		st->voMemoprator.Copy = cmnMemCopy;
-		st->voMemoprator.Free = cmnMemFree;
-		st->voMemoprator.Set = cmnMemSet;
-		st->voMemoprator.Check = cmnMemCheck;
-		pMemOP = &st->voMemoprator;
-	}
+    if(interMem)
+    {
+        st->voMemoprator.Alloc = cmnMemAlloc;
+        st->voMemoprator.Copy = cmnMemCopy;
+        st->voMemoprator.Free = cmnMemFree;
+        st->voMemoprator.Set = cmnMemSet;
+        st->voMemoprator.Check = cmnMemCheck;
+        pMemOP = &st->voMemoprator;
+    }
 
-	st->pvoMemop = pMemOP;
+    st->pvoMemop = pMemOP;
 
-	*phCodec = (void *) st;
+    *phCodec = (void *) st;
 
-	return VO_ERR_NONE;
+    return VO_ERR_NONE;
 }
 
 /**********************************************************************************
@@ -1691,32 +1695,32 @@
 ***********************************************************************************/
 
 VO_U32 VO_API voAMRWB_SetInputData(
-		VO_HANDLE hCodec,                   /* i/o: The codec handle which was created by Init function */
-		VO_CODECBUFFER * pInput             /*   i: The input buffer parameter  */
-		)
+        VO_HANDLE hCodec,                   /* i/o: The codec handle which was created by Init function */
+        VO_CODECBUFFER * pInput             /*   i: The input buffer parameter  */
+        )
 {
-	Coder_State  *gData;
-	FrameStream  *stream;
+    Coder_State  *gData;
+    FrameStream  *stream;
 
-	if(NULL == hCodec)
-	{
-		return VO_ERR_INVALID_ARG;
-	}
+    if(NULL == hCodec)
+    {
+        return VO_ERR_INVALID_ARG;
+    }
 
-	gData = (Coder_State *)hCodec;
-	stream = gData->stream;
+    gData = (Coder_State *)hCodec;
+    stream = gData->stream;
 
-	if(NULL == pInput || NULL == pInput->Buffer)
-	{
-		return VO_ERR_INVALID_ARG;
-	}
+    if(NULL == pInput || NULL == pInput->Buffer)
+    {
+        return VO_ERR_INVALID_ARG;
+    }
 
-	stream->set_ptr    = pInput->Buffer;
-	stream->set_len    = pInput->Length;
-	stream->frame_ptr  = stream->frame_ptr_bk;
-	stream->used_len   = 0;
+    stream->set_ptr    = pInput->Buffer;
+    stream->set_len    = pInput->Length;
+    stream->frame_ptr  = stream->frame_ptr_bk;
+    stream->used_len   = 0;
 
-	return VO_ERR_NONE;
+    return VO_ERR_NONE;
 }
 
 /**************************************************************************************
@@ -1726,52 +1730,52 @@
 ***************************************************************************************/
 
 VO_U32 VO_API voAMRWB_GetOutputData(
-		VO_HANDLE hCodec,                    /* i: The Codec Handle which was created by Init function*/
-		VO_CODECBUFFER * pOutput,            /* o: The output audio data */
-		VO_AUDIO_OUTPUTINFO * pAudioFormat   /* o: The encoder module filled audio format and used the input size*/
-		)
+        VO_HANDLE hCodec,                    /* i: The Codec Handle which was created by Init function*/
+        VO_CODECBUFFER * pOutput,            /* o: The output audio data */
+        VO_AUDIO_OUTPUTINFO * pAudioFormat   /* o: The encoder module filled audio format and used the input size*/
+        )
 {
-	Coder_State* gData = (Coder_State*)hCodec;
-	VO_MEM_OPERATOR  *pMemOP;
-	FrameStream  *stream = (FrameStream *)gData->stream;
-	pMemOP = (VO_MEM_OPERATOR  *)gData->pvoMemop;
+    Coder_State* gData = (Coder_State*)hCodec;
+    VO_MEM_OPERATOR  *pMemOP;
+    FrameStream  *stream = (FrameStream *)gData->stream;
+    pMemOP = (VO_MEM_OPERATOR  *)gData->pvoMemop;
 
-	if(stream->framebuffer_len  < Frame_MaxByte)         /* check the work buffer len */
-	{
-		stream->frame_storelen = stream->framebuffer_len;
-		if(stream->frame_storelen)
-		{
-			pMemOP->Copy(VO_INDEX_ENC_AMRWB, stream->frame_ptr_bk , stream->frame_ptr , stream->frame_storelen);
-		}
-		if(stream->set_len > 0)
-		{
-			voAWB_UpdateFrameBuffer(stream, pMemOP);
-		}
-		if(stream->framebuffer_len < Frame_MaxByte)
-		{
-			if(pAudioFormat)
-				pAudioFormat->InputUsed = stream->used_len;
-			return VO_ERR_INPUT_BUFFER_SMALL;
-		}
-	}
+    if(stream->framebuffer_len  < Frame_MaxByte)         /* check the work buffer len */
+    {
+        stream->frame_storelen = stream->framebuffer_len;
+        if(stream->frame_storelen)
+        {
+            pMemOP->Copy(VO_INDEX_ENC_AMRWB, stream->frame_ptr_bk , stream->frame_ptr , stream->frame_storelen);
+        }
+        if(stream->set_len > 0)
+        {
+            voAWB_UpdateFrameBuffer(stream, pMemOP);
+        }
+        if(stream->framebuffer_len < Frame_MaxByte)
+        {
+            if(pAudioFormat)
+                pAudioFormat->InputUsed = stream->used_len;
+            return VO_ERR_INPUT_BUFFER_SMALL;
+        }
+    }
 
-	gData->inputStream = stream->frame_ptr;
-	gData->outputStream = (unsigned short*)pOutput->Buffer;
+    gData->inputStream = stream->frame_ptr;
+    gData->outputStream = (unsigned short*)pOutput->Buffer;
 
-	gData->outputSize = AMR_Enc_Encode(gData);         /* encoder main function */
+    gData->outputSize = AMR_Enc_Encode(gData);         /* encoder main function */
 
-	pOutput->Length = gData->outputSize;               /* get the output buffer length */
-	stream->frame_ptr += 640;                          /* update the work buffer ptr */
-	stream->framebuffer_len  -= 640;
+    pOutput->Length = gData->outputSize;               /* get the output buffer length */
+    stream->frame_ptr += 640;                          /* update the work buffer ptr */
+    stream->framebuffer_len  -= 640;
 
-	if(pAudioFormat)                                   /* return output audio information */
-	{
-		pAudioFormat->Format.Channels = 1;
-		pAudioFormat->Format.SampleRate = 8000;
-		pAudioFormat->Format.SampleBits = 16;
-		pAudioFormat->InputUsed = stream->used_len;
-	}
-	return VO_ERR_NONE;
+    if(pAudioFormat)                                   /* return output audio information */
+    {
+        pAudioFormat->Format.Channels = 1;
+        pAudioFormat->Format.SampleRate = 8000;
+        pAudioFormat->Format.SampleBits = 16;
+        pAudioFormat->InputUsed = stream->used_len;
+    }
+    return VO_ERR_NONE;
 }
 
 /*************************************************************************
@@ -1782,50 +1786,50 @@
 
 
 VO_U32 VO_API voAMRWB_SetParam(
-		VO_HANDLE hCodec,   /* i/o: The Codec Handle which was created by Init function */
-		VO_S32 uParamID,    /*   i: The param ID */
-		VO_PTR pData        /*   i: The param value depend on the ID */
-		)
+        VO_HANDLE hCodec,   /* i/o: The Codec Handle which was created by Init function */
+        VO_S32 uParamID,    /*   i: The param ID */
+        VO_PTR pData        /*   i: The param value depend on the ID */
+        )
 {
-	Coder_State* gData = (Coder_State*)hCodec;
-	FrameStream *stream = (FrameStream *)(gData->stream);
-	int *lValue = (int*)pData;
+    Coder_State* gData = (Coder_State*)hCodec;
+    FrameStream *stream = (FrameStream *)(gData->stream);
+    int *lValue = (int*)pData;
 
-	switch(uParamID)
-	{
-		/* setting AMR-WB frame type*/
-		case VO_PID_AMRWB_FRAMETYPE:
-			if(*lValue < VOAMRWB_DEFAULT || *lValue > VOAMRWB_RFC3267)
-				return VO_ERR_WRONG_PARAM_ID;
-			gData->frameType = *lValue;
-			break;
-		/* setting AMR-WB bit rate */
-		case VO_PID_AMRWB_MODE:
-			{
-				if(*lValue < VOAMRWB_MD66 || *lValue > VOAMRWB_MD2385)
-					return VO_ERR_WRONG_PARAM_ID;
-				gData->mode = *lValue;
-			}
-			break;
-		/* enable or disable DTX mode */
-		case VO_PID_AMRWB_DTX:
-			gData->allow_dtx = (Word16)(*lValue);
-			break;
+    switch(uParamID)
+    {
+        /* setting AMR-WB frame type*/
+        case VO_PID_AMRWB_FRAMETYPE:
+            if(*lValue < VOAMRWB_DEFAULT || *lValue > VOAMRWB_RFC3267)
+                return VO_ERR_WRONG_PARAM_ID;
+            gData->frameType = *lValue;
+            break;
+        /* setting AMR-WB bit rate */
+        case VO_PID_AMRWB_MODE:
+            {
+                if(*lValue < VOAMRWB_MD66 || *lValue > VOAMRWB_MD2385)
+                    return VO_ERR_WRONG_PARAM_ID;
+                gData->mode = *lValue;
+            }
+            break;
+        /* enable or disable DTX mode */
+        case VO_PID_AMRWB_DTX:
+            gData->allow_dtx = (Word16)(*lValue);
+            break;
 
-		case VO_PID_COMMON_HEADDATA:
-			break;
+        case VO_PID_COMMON_HEADDATA:
+            break;
         /* flush the work buffer */
-		case VO_PID_COMMON_FLUSH:
-			stream->set_ptr = NULL;
-			stream->frame_storelen = 0;
-			stream->framebuffer_len = 0;
-			stream->set_len = 0;
-			break;
+        case VO_PID_COMMON_FLUSH:
+            stream->set_ptr = NULL;
+            stream->frame_storelen = 0;
+            stream->framebuffer_len = 0;
+            stream->set_len = 0;
+            break;
 
-		default:
-			return VO_ERR_WRONG_PARAM_ID;
-	}
-	return VO_ERR_NONE;
+        default:
+            return VO_ERR_WRONG_PARAM_ID;
+    }
+    return VO_ERR_NONE;
 }
 
 /**************************************************************************
@@ -1835,52 +1839,52 @@
 ***************************************************************************/
 
 VO_U32 VO_API voAMRWB_GetParam(
-		VO_HANDLE hCodec,      /* i: The Codec Handle which was created by Init function */
-		VO_S32 uParamID,       /* i: The param ID */
-		VO_PTR pData           /* o: The param value depend on the ID */
-		)
+        VO_HANDLE hCodec,      /* i: The Codec Handle which was created by Init function */
+        VO_S32 uParamID,       /* i: The param ID */
+        VO_PTR pData           /* o: The param value depend on the ID */
+        )
 {
-	int    temp;
-	Coder_State* gData = (Coder_State*)hCodec;
+    int    temp;
+    Coder_State* gData = (Coder_State*)hCodec;
 
-	if (gData==NULL)
-		return VO_ERR_INVALID_ARG;
-	switch(uParamID)
-	{
-		/* output audio format */
-		case VO_PID_AMRWB_FORMAT:
-			{
-				VO_AUDIO_FORMAT* fmt = (VO_AUDIO_FORMAT*)pData;
-				fmt->Channels   = 1;
-				fmt->SampleRate = 16000;
-				fmt->SampleBits = 16;
-				break;
-			}
+    if (gData==NULL)
+        return VO_ERR_INVALID_ARG;
+    switch(uParamID)
+    {
+        /* output audio format */
+        case VO_PID_AMRWB_FORMAT:
+            {
+                VO_AUDIO_FORMAT* fmt = (VO_AUDIO_FORMAT*)pData;
+                fmt->Channels   = 1;
+                fmt->SampleRate = 16000;
+                fmt->SampleBits = 16;
+                break;
+            }
         /* output audio channel number */
-		case VO_PID_AMRWB_CHANNELS:
-			temp = 1;
-			pData = (void *)(&temp);
-			break;
+        case VO_PID_AMRWB_CHANNELS:
+            temp = 1;
+            pData = (void *)(&temp);
+            break;
         /* output audio sample rate */
-		case VO_PID_AMRWB_SAMPLERATE:
-			temp = 16000;
-			pData = (void *)(&temp);
-			break;
-		/* output audio frame type */
-		case VO_PID_AMRWB_FRAMETYPE:
-			temp = gData->frameType;
-			pData = (void *)(&temp);
-			break;
-		/* output audio bit rate */
-		case VO_PID_AMRWB_MODE:
-			temp = gData->mode;
-			pData = (void *)(&temp);
-			break;
-		default:
-			return VO_ERR_WRONG_PARAM_ID;
-	}
+        case VO_PID_AMRWB_SAMPLERATE:
+            temp = 16000;
+            pData = (void *)(&temp);
+            break;
+        /* output audio frame type */
+        case VO_PID_AMRWB_FRAMETYPE:
+            temp = gData->frameType;
+            pData = (void *)(&temp);
+            break;
+        /* output audio bit rate */
+        case VO_PID_AMRWB_MODE:
+            temp = gData->mode;
+            pData = (void *)(&temp);
+            break;
+        default:
+            return VO_ERR_WRONG_PARAM_ID;
+    }
 
-	return VO_ERR_NONE;
+    return VO_ERR_NONE;
 }
 
 /***********************************************************************************
@@ -1890,32 +1894,32 @@
 *************************************************************************************/
 
 VO_U32 VO_API voAMRWB_Uninit(VO_HANDLE hCodec           /* i/o: Codec handle pointer */
-							 )
+                             )
 {
-	Coder_State* gData = (Coder_State*)hCodec;
-	VO_MEM_OPERATOR *pMemOP;
-	pMemOP = gData->pvoMemop;
+    Coder_State* gData = (Coder_State*)hCodec;
+    VO_MEM_OPERATOR *pMemOP;
+    pMemOP = gData->pvoMemop;
 
-	if(hCodec)
-	{
-		if(gData->stream)
-		{
-			if(gData->stream->frame_ptr_bk)
-			{
-				mem_free(pMemOP, gData->stream->frame_ptr_bk, VO_INDEX_ENC_AMRWB);
-				gData->stream->frame_ptr_bk = NULL;
-			}
-			mem_free(pMemOP, gData->stream, VO_INDEX_ENC_AMRWB);
-			gData->stream = NULL;
-		}
-		wb_vad_exit(&(((Coder_State *) gData)->vadSt), pMemOP);
-		dtx_enc_exit(&(((Coder_State *) gData)->dtx_encSt), pMemOP);
+    if(hCodec)
+    {
+        if(gData->stream)
+        {
+            if(gData->stream->frame_ptr_bk)
+            {
+                mem_free(pMemOP, gData->stream->frame_ptr_bk, VO_INDEX_ENC_AMRWB);
+                gData->stream->frame_ptr_bk = NULL;
+            }
+            mem_free(pMemOP, gData->stream, VO_INDEX_ENC_AMRWB);
+            gData->stream = NULL;
+        }
+        wb_vad_exit(&(((Coder_State *) gData)->vadSt), pMemOP);
+        dtx_enc_exit(&(((Coder_State *) gData)->dtx_encSt), pMemOP);
 
-		mem_free(pMemOP, hCodec, VO_INDEX_ENC_AMRWB);
-		hCodec = NULL;
-	}
+        mem_free(pMemOP, hCodec, VO_INDEX_ENC_AMRWB);
+        hCodec = NULL;
+    }
 
-	return VO_ERR_NONE;
+    return VO_ERR_NONE;
 }
 
 /********************************************************************************
@@ -1925,19 +1929,19 @@
 ********************************************************************************/
 
 VO_S32 VO_API voGetAMRWBEncAPI(
-							   VO_AUDIO_CODECAPI * pEncHandle      /* i/o: Codec handle pointer */
-							   )
+                               VO_AUDIO_CODECAPI * pEncHandle      /* i/o: Codec handle pointer */
+                               )
 {
-	if(NULL == pEncHandle)
-		return VO_ERR_INVALID_ARG;
-	pEncHandle->Init = voAMRWB_Init;
-	pEncHandle->SetInputData = voAMRWB_SetInputData;
-	pEncHandle->GetOutputData = voAMRWB_GetOutputData;
-	pEncHandle->SetParam = voAMRWB_SetParam;
-	pEncHandle->GetParam = voAMRWB_GetParam;
-	pEncHandle->Uninit = voAMRWB_Uninit;
+    if(NULL == pEncHandle)
+        return VO_ERR_INVALID_ARG;
+    pEncHandle->Init = voAMRWB_Init;
+    pEncHandle->SetInputData = voAMRWB_SetInputData;
+    pEncHandle->GetOutputData = voAMRWB_GetOutputData;
+    pEncHandle->SetParam = voAMRWB_SetParam;
+    pEncHandle->GetParam = voAMRWB_GetParam;
+    pEncHandle->Uninit = voAMRWB_Uninit;
 
-	return VO_ERR_NONE;
+    return VO_ERR_NONE;
 }
 
 #ifdef __cplusplus
diff --git a/media/libstagefright/codecs/amrwbenc/src/voicefac.c b/media/libstagefright/codecs/amrwbenc/src/voicefac.c
index d890044..c9f48c2 100644
--- a/media/libstagefright/codecs/amrwbenc/src/voicefac.c
+++ b/media/libstagefright/codecs/amrwbenc/src/voicefac.c
@@ -26,65 +26,65 @@
 #include "math_op.h"
 
 Word16 voice_factor(                                  /* (o) Q15   : factor (-1=unvoiced to 1=voiced) */
-		Word16 exc[],                         /* (i) Q_exc : pitch excitation                 */
-		Word16 Q_exc,                         /* (i)       : exc format                       */
-		Word16 gain_pit,                      /* (i) Q14   : gain of pitch                    */
-		Word16 code[],                        /* (i) Q9    : Fixed codebook excitation        */
-		Word16 gain_code,                     /* (i) Q0    : gain of code                     */
-		Word16 L_subfr                        /* (i)       : subframe length                  */
-		)
+        Word16 exc[],                         /* (i) Q_exc : pitch excitation                 */
+        Word16 Q_exc,                         /* (i)       : exc format                       */
+        Word16 gain_pit,                      /* (i) Q14   : gain of pitch                    */
+        Word16 code[],                        /* (i) Q9    : Fixed codebook excitation        */
+        Word16 gain_code,                     /* (i) Q0    : gain of code                     */
+        Word16 L_subfr                        /* (i)       : subframe length                  */
+        )
 {
-	Word16 tmp, exp, ener1, exp1, ener2, exp2;
-	Word32 i, L_tmp;
+    Word16 tmp, exp, ener1, exp1, ener2, exp2;
+    Word32 i, L_tmp;
 
 #ifdef ASM_OPT               /* asm optimization branch */
-	ener1 = extract_h(Dot_product12_asm(exc, exc, L_subfr, &exp1));
+    ener1 = extract_h(Dot_product12_asm(exc, exc, L_subfr, &exp1));
 #else
-	ener1 = extract_h(Dot_product12(exc, exc, L_subfr, &exp1));
+    ener1 = extract_h(Dot_product12(exc, exc, L_subfr, &exp1));
 #endif
-	exp1 = exp1 - (Q_exc + Q_exc);
-	L_tmp = vo_L_mult(gain_pit, gain_pit);
-	exp = norm_l(L_tmp);
-	tmp = extract_h(L_tmp << exp);
-	ener1 = vo_mult(ener1, tmp);
-	exp1 = exp1 - exp - 10;        /* 10 -> gain_pit Q14 to Q9 */
+    exp1 = exp1 - (Q_exc + Q_exc);
+    L_tmp = vo_L_mult(gain_pit, gain_pit);
+    exp = norm_l(L_tmp);
+    tmp = extract_h(L_tmp << exp);
+    ener1 = vo_mult(ener1, tmp);
+    exp1 = exp1 - exp - 10;        /* 10 -> gain_pit Q14 to Q9 */
 
 #ifdef ASM_OPT                /* asm optimization branch */
-	ener2 = extract_h(Dot_product12_asm(code, code, L_subfr, &exp2));
+    ener2 = extract_h(Dot_product12_asm(code, code, L_subfr, &exp2));
 #else
-	ener2 = extract_h(Dot_product12(code, code, L_subfr, &exp2));
+    ener2 = extract_h(Dot_product12(code, code, L_subfr, &exp2));
 #endif
 
-	exp = norm_s(gain_code);
-	tmp = gain_code << exp;
-	tmp = vo_mult(tmp, tmp);
-	ener2 = vo_mult(ener2, tmp);
-	exp2 = exp2 - (exp + exp);
+    exp = norm_s(gain_code);
+    tmp = gain_code << exp;
+    tmp = vo_mult(tmp, tmp);
+    ener2 = vo_mult(ener2, tmp);
+    exp2 = exp2 - (exp + exp);
 
-	i = exp1 - exp2;
+    i = exp1 - exp2;
 
-	if (i >= 0)
-	{
-		ener1 = ener1 >> 1;
-		ener2 = ener2 >> (i + 1);
-	} else
-	{
-		ener1 = ener1 >> (1 - i);
-		ener2 = ener2 >> 1;
-	}
+    if (i >= 0)
+    {
+        ener1 = ener1 >> 1;
+        ener2 = ener2 >> (i + 1);
+    } else
+    {
+        ener1 = ener1 >> (1 - i);
+        ener2 = ener2 >> 1;
+    }
 
-	tmp = vo_sub(ener1, ener2);
-	ener1 = add1(add1(ener1, ener2), 1);
+    tmp = vo_sub(ener1, ener2);
+    ener1 = add1(add1(ener1, ener2), 1);
 
-	if (tmp >= 0)
-	{
-		tmp = div_s(tmp, ener1);
-	} else
-	{
-		tmp = vo_negate(div_s(vo_negate(tmp), ener1));
-	}
+    if (tmp >= 0)
+    {
+        tmp = div_s(tmp, ener1);
+    } else
+    {
+        tmp = vo_negate(div_s(vo_negate(tmp), ener1));
+    }
 
-	return (tmp);
+    return (tmp);
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/wb_vad.c b/media/libstagefright/codecs/amrwbenc/src/wb_vad.c
index 2beaefd..866a69c 100644
--- a/media/libstagefright/codecs/amrwbenc/src/wb_vad.c
+++ b/media/libstagefright/codecs/amrwbenc/src/wb_vad.c
@@ -44,30 +44,30 @@
 *********************************************************************************/
 
 static Word16 ilog2(                       /* return: output value of the log2 */
-		Word16 mant                        /* i: value to be converted */
-		)
+        Word16 mant                        /* i: value to be converted */
+        )
 {
-	Word16 ex, ex2, res;
-	Word32 i, l_temp;
+    Word16 ex, ex2, res;
+    Word32 i, l_temp;
 
-	if (mant <= 0)
-	{
-		mant = 1;
-	}
-	ex = norm_s(mant);
-	mant = mant << ex;
+    if (mant <= 0)
+    {
+        mant = 1;
+    }
+    ex = norm_s(mant);
+    mant = mant << ex;
 
-	for (i = 0; i < 3; i++)
-		mant = vo_mult(mant, mant);
-	l_temp = vo_L_mult(mant, mant);
+    for (i = 0; i < 3; i++)
+        mant = vo_mult(mant, mant);
+    l_temp = vo_L_mult(mant, mant);
 
-	ex2 = norm_l(l_temp);
-	mant = extract_h(l_temp << ex2);
+    ex2 = norm_l(l_temp);
+    mant = extract_h(l_temp << ex2);
 
-	res = (ex + 16) << 10;
-	res = add1(res, (ex2 << 6));
-	res = vo_sub(add1(res, 127), (mant >> 8));
-	return (res);
+    res = (ex + 16) << 10;
+    res = add1(res, (ex2 << 6));
+    res = vo_sub(add1(res, 127), (mant >> 8));
+    return (res);
 }
 
 /******************************************************************************
@@ -79,23 +79,23 @@
 *******************************************************************************/
 
 static void filter5(
-		Word16 * in0,                         /* i/o : input values; output low-pass part  */
-		Word16 * in1,                         /* i/o : input values; output high-pass part */
-		Word16 data[]                         /* i/o : filter memory                       */
-		)
+        Word16 * in0,                         /* i/o : input values; output low-pass part  */
+        Word16 * in1,                         /* i/o : input values; output high-pass part */
+        Word16 data[]                         /* i/o : filter memory                       */
+        )
 {
-	Word16 temp0, temp1, temp2;
+    Word16 temp0, temp1, temp2;
 
-	temp0 = vo_sub(*in0, vo_mult(COEFF5_1, data[0]));
-	temp1 = add1(data[0], vo_mult(COEFF5_1, temp0));
-	data[0] = temp0;
+    temp0 = vo_sub(*in0, vo_mult(COEFF5_1, data[0]));
+    temp1 = add1(data[0], vo_mult(COEFF5_1, temp0));
+    data[0] = temp0;
 
-	temp0 = vo_sub(*in1, vo_mult(COEFF5_2, data[1]));
-	temp2 = add1(data[1], vo_mult(COEFF5_2, temp0));
-	data[1] = temp0;
+    temp0 = vo_sub(*in1, vo_mult(COEFF5_2, data[1]));
+    temp2 = add1(data[1], vo_mult(COEFF5_2, temp0));
+    data[1] = temp0;
 
-	*in0 = extract_h((vo_L_add(temp1, temp2) << 15));
-	*in1 = extract_h((vo_L_sub(temp1, temp2) << 15));
+    *in0 = extract_h((vo_L_add(temp1, temp2) << 15));
+    *in1 = extract_h((vo_L_sub(temp1, temp2) << 15));
 }
 
 /******************************************************************************
@@ -107,19 +107,19 @@
 *******************************************************************************/
 
 static void filter3(
-		Word16 * in0,                         /* i/o : input values; output low-pass part  */
-		Word16 * in1,                         /* i/o : input values; output high-pass part */
-		Word16 * data                         /* i/o : filter memory                       */
-		)
+        Word16 * in0,                         /* i/o : input values; output low-pass part  */
+        Word16 * in1,                         /* i/o : input values; output high-pass part */
+        Word16 * data                         /* i/o : filter memory                       */
+        )
 {
-	Word16 temp1, temp2;
+    Word16 temp1, temp2;
 
-	temp1 = vo_sub(*in1, vo_mult(COEFF3, *data));
-	temp2 = add1(*data, vo_mult(COEFF3, temp1));
-	*data = temp1;
+    temp1 = vo_sub(*in1, vo_mult(COEFF3, *data));
+    temp2 = add1(*data, vo_mult(COEFF3, temp1));
+    *data = temp1;
 
-	*in1 = extract_h((vo_L_sub(*in0, temp2) << 15));
-	*in0 = extract_h((vo_L_add(*in0, temp2) << 15));
+    *in1 = extract_h((vo_L_sub(*in0, temp2) << 15));
+    *in0 = extract_h((vo_L_add(*in0, temp2) << 15));
 }
 
 /******************************************************************************
@@ -135,36 +135,36 @@
 ******************************************************************************/
 
 static Word16 level_calculation(                      /* return: signal level */
-		Word16 data[],                        /* i   : signal buffer                                    */
-		Word16 * sub_level,                   /* i   : level calculated at the end of the previous frame*/
-		                                      /* o   : level of signal calculated from the last         */
-		                                      /*       (count2 - count1) samples                        */
-		Word16 count1,                        /* i   : number of samples to be counted                  */
-		Word16 count2,                        /* i   : number of samples to be counted                  */
-		Word16 ind_m,                         /* i   : step size for the index of the data buffer       */
-		Word16 ind_a,                         /* i   : starting index of the data buffer                */
-		Word16 scale                          /* i   : scaling for the level calculation                */
-		)
+        Word16 data[],                        /* i   : signal buffer                                    */
+        Word16 * sub_level,                   /* i   : level calculated at the end of the previous frame*/
+                                              /* o   : level of signal calculated from the last         */
+                                              /*       (count2 - count1) samples                        */
+        Word16 count1,                        /* i   : number of samples to be counted                  */
+        Word16 count2,                        /* i   : number of samples to be counted                  */
+        Word16 ind_m,                         /* i   : step size for the index of the data buffer       */
+        Word16 ind_a,                         /* i   : starting index of the data buffer                */
+        Word16 scale                          /* i   : scaling for the level calculation                */
+        )
 {
-	Word32 i, l_temp1, l_temp2;
-	Word16 level;
+    Word32 i, l_temp1, l_temp2;
+    Word16 level;
 
-	l_temp1 = 0L;
-	for (i = count1; i < count2; i++)
-	{
-		l_temp1 += (abs_s(data[ind_m * i + ind_a])<<1);
-	}
+    l_temp1 = 0L;
+    for (i = count1; i < count2; i++)
+    {
+        l_temp1 += (abs_s(data[ind_m * i + ind_a])<<1);
+    }
 
-	l_temp2 = vo_L_add(l_temp1, L_shl(*sub_level, 16 - scale));
-	*sub_level = extract_h(L_shl(l_temp1, scale));
+    l_temp2 = vo_L_add(l_temp1, L_shl(*sub_level, 16 - scale));
+    *sub_level = extract_h(L_shl(l_temp1, scale));
 
-	for (i = 0; i < count1; i++)
-	{
-		l_temp2 += (abs_s(data[ind_m * i + ind_a])<<1);
-	}
-	level = extract_h(L_shl2(l_temp2, scale));
+    for (i = 0; i < count1; i++)
+    {
+        l_temp2 += (abs_s(data[ind_m * i + ind_a])<<1);
+    }
+    level = extract_h(L_shl2(l_temp2, scale));
 
-	return level;
+    return level;
 }
 
 /******************************************************************************
@@ -176,75 +176,75 @@
 *******************************************************************************/
 
 static void filter_bank(
-		VadVars * st,                         /* i/o : State struct               */
-		Word16 in[],                          /* i   : input frame                */
-		Word16 level[]                        /* o   : signal levels at each band */
-		)
+        VadVars * st,                         /* i/o : State struct               */
+        Word16 in[],                          /* i   : input frame                */
+        Word16 level[]                        /* o   : signal levels at each band */
+        )
 {
-	Word32 i;
-	Word16 tmp_buf[FRAME_LEN];
+    Word32 i;
+    Word16 tmp_buf[FRAME_LEN];
 
-	/* shift input 1 bit down for safe scaling */
-	for (i = 0; i < FRAME_LEN; i++)
-	{
-		tmp_buf[i] = in[i] >> 1;
-	}
+    /* shift input 1 bit down for safe scaling */
+    for (i = 0; i < FRAME_LEN; i++)
+    {
+        tmp_buf[i] = in[i] >> 1;
+    }
 
-	/* run the filter bank */
-	for (i = 0; i < 128; i++)
-	{
-		filter5(&tmp_buf[2 * i], &tmp_buf[2 * i + 1], st->a_data5[0]);
-	}
-	for (i = 0; i < 64; i++)
-	{
-		filter5(&tmp_buf[4 * i], &tmp_buf[4 * i + 2], st->a_data5[1]);
-		filter5(&tmp_buf[4 * i + 1], &tmp_buf[4 * i + 3], st->a_data5[2]);
-	}
-	for (i = 0; i < 32; i++)
-	{
-		filter5(&tmp_buf[8 * i], &tmp_buf[8 * i + 4], st->a_data5[3]);
-		filter5(&tmp_buf[8 * i + 2], &tmp_buf[8 * i + 6], st->a_data5[4]);
-		filter3(&tmp_buf[8 * i + 3], &tmp_buf[8 * i + 7], &st->a_data3[0]);
-	}
-	for (i = 0; i < 16; i++)
-	{
-		filter3(&tmp_buf[16 * i + 0], &tmp_buf[16 * i + 8], &st->a_data3[1]);
-		filter3(&tmp_buf[16 * i + 4], &tmp_buf[16 * i + 12], &st->a_data3[2]);
-		filter3(&tmp_buf[16 * i + 6], &tmp_buf[16 * i + 14], &st->a_data3[3]);
-	}
+    /* run the filter bank */
+    for (i = 0; i < 128; i++)
+    {
+        filter5(&tmp_buf[2 * i], &tmp_buf[2 * i + 1], st->a_data5[0]);
+    }
+    for (i = 0; i < 64; i++)
+    {
+        filter5(&tmp_buf[4 * i], &tmp_buf[4 * i + 2], st->a_data5[1]);
+        filter5(&tmp_buf[4 * i + 1], &tmp_buf[4 * i + 3], st->a_data5[2]);
+    }
+    for (i = 0; i < 32; i++)
+    {
+        filter5(&tmp_buf[8 * i], &tmp_buf[8 * i + 4], st->a_data5[3]);
+        filter5(&tmp_buf[8 * i + 2], &tmp_buf[8 * i + 6], st->a_data5[4]);
+        filter3(&tmp_buf[8 * i + 3], &tmp_buf[8 * i + 7], &st->a_data3[0]);
+    }
+    for (i = 0; i < 16; i++)
+    {
+        filter3(&tmp_buf[16 * i + 0], &tmp_buf[16 * i + 8], &st->a_data3[1]);
+        filter3(&tmp_buf[16 * i + 4], &tmp_buf[16 * i + 12], &st->a_data3[2]);
+        filter3(&tmp_buf[16 * i + 6], &tmp_buf[16 * i + 14], &st->a_data3[3]);
+    }
 
-	for (i = 0; i < 8; i++)
-	{
-		filter3(&tmp_buf[32 * i + 0], &tmp_buf[32 * i + 16], &st->a_data3[4]);
-		filter3(&tmp_buf[32 * i + 8], &tmp_buf[32 * i + 24], &st->a_data3[5]);
-	}
+    for (i = 0; i < 8; i++)
+    {
+        filter3(&tmp_buf[32 * i + 0], &tmp_buf[32 * i + 16], &st->a_data3[4]);
+        filter3(&tmp_buf[32 * i + 8], &tmp_buf[32 * i + 24], &st->a_data3[5]);
+    }
 
-	/* calculate levels in each frequency band */
+    /* calculate levels in each frequency band */
 
-	/* 4800 - 6400 Hz */
-	level[11] = level_calculation(tmp_buf, &st->sub_level[11], 16, 64, 4, 1, 14);
-	/* 4000 - 4800 Hz */
-	level[10] = level_calculation(tmp_buf, &st->sub_level[10], 8, 32, 8, 7, 15);
-	/* 3200 - 4000 Hz */
-	level[9] = level_calculation(tmp_buf, &st->sub_level[9],8, 32, 8, 3, 15);
-	/* 2400 - 3200 Hz */
-	level[8] = level_calculation(tmp_buf, &st->sub_level[8],8, 32, 8, 2, 15);
-	/* 2000 - 2400 Hz */
-	level[7] = level_calculation(tmp_buf, &st->sub_level[7],4, 16, 16, 14, 16);
-	/* 1600 - 2000 Hz */
-	level[6] = level_calculation(tmp_buf, &st->sub_level[6],4, 16, 16, 6, 16);
-	/* 1200 - 1600 Hz */
-	level[5] = level_calculation(tmp_buf, &st->sub_level[5],4, 16, 16, 4, 16);
-	/* 800 - 1200 Hz */
-	level[4] = level_calculation(tmp_buf, &st->sub_level[4],4, 16, 16, 12, 16);
-	/* 600 - 800 Hz */
-	level[3] = level_calculation(tmp_buf, &st->sub_level[3],2, 8, 32, 8, 17);
-	/* 400 - 600 Hz */
-	level[2] = level_calculation(tmp_buf, &st->sub_level[2],2, 8, 32, 24, 17);
-	/* 200 - 400 Hz */
-	level[1] = level_calculation(tmp_buf, &st->sub_level[1],2, 8, 32, 16, 17);
-	/* 0 - 200 Hz */
-	level[0] = level_calculation(tmp_buf, &st->sub_level[0],2, 8, 32, 0, 17);
+    /* 4800 - 6400 Hz */
+    level[11] = level_calculation(tmp_buf, &st->sub_level[11], 16, 64, 4, 1, 14);
+    /* 4000 - 4800 Hz */
+    level[10] = level_calculation(tmp_buf, &st->sub_level[10], 8, 32, 8, 7, 15);
+    /* 3200 - 4000 Hz */
+    level[9] = level_calculation(tmp_buf, &st->sub_level[9],8, 32, 8, 3, 15);
+    /* 2400 - 3200 Hz */
+    level[8] = level_calculation(tmp_buf, &st->sub_level[8],8, 32, 8, 2, 15);
+    /* 2000 - 2400 Hz */
+    level[7] = level_calculation(tmp_buf, &st->sub_level[7],4, 16, 16, 14, 16);
+    /* 1600 - 2000 Hz */
+    level[6] = level_calculation(tmp_buf, &st->sub_level[6],4, 16, 16, 6, 16);
+    /* 1200 - 1600 Hz */
+    level[5] = level_calculation(tmp_buf, &st->sub_level[5],4, 16, 16, 4, 16);
+    /* 800 - 1200 Hz */
+    level[4] = level_calculation(tmp_buf, &st->sub_level[4],4, 16, 16, 12, 16);
+    /* 600 - 800 Hz */
+    level[3] = level_calculation(tmp_buf, &st->sub_level[3],2, 8, 32, 8, 17);
+    /* 400 - 600 Hz */
+    level[2] = level_calculation(tmp_buf, &st->sub_level[2],2, 8, 32, 24, 17);
+    /* 200 - 400 Hz */
+    level[1] = level_calculation(tmp_buf, &st->sub_level[1],2, 8, 32, 16, 17);
+    /* 0 - 200 Hz */
+    level[0] = level_calculation(tmp_buf, &st->sub_level[0],2, 8, 32, 0, 17);
 }
 
 /******************************************************************************
@@ -255,86 +255,86 @@
 *******************************************************************************/
 
 static void update_cntrl(
-		VadVars * st,                         /* i/o : State structure                    */
-		Word16 level[]                        /* i   : sub-band levels of the input frame */
-		)
+        VadVars * st,                         /* i/o : State structure                    */
+        Word16 level[]                        /* i   : sub-band levels of the input frame */
+        )
 {
-	Word32 i;
-	Word16 num, temp, stat_rat, exp, denom;
-	Word16 alpha;
+    Word32 i;
+    Word16 num, temp, stat_rat, exp, denom;
+    Word16 alpha;
 
-	/* if a tone has been detected for a while, initialize stat_count */
-	if (sub((Word16) (st->tone_flag & 0x7c00), 0x7c00) == 0)
-	{
-		st->stat_count = STAT_COUNT;
-	} else
-	{
-		/* if 8 last vad-decisions have been "0", reinitialize stat_count */
-		if ((st->vadreg & 0x7f80) == 0)
-		{
-			st->stat_count = STAT_COUNT;
-		} else
-		{
-			stat_rat = 0;
-			for (i = 0; i < COMPLEN; i++)
-			{
-				if(level[i] > st->ave_level[i])
-				{
-					num = level[i];
-					denom = st->ave_level[i];
-				} else
-				{
-					num = st->ave_level[i];
-					denom = level[i];
-				}
-				/* Limit nimimum value of num and denom to STAT_THR_LEVEL */
-				if(num < STAT_THR_LEVEL)
-				{
-					num = STAT_THR_LEVEL;
-				}
-				if(denom < STAT_THR_LEVEL)
-				{
-					denom = STAT_THR_LEVEL;
-				}
-				exp = norm_s(denom);
-				denom = denom << exp;
+    /* if a tone has been detected for a while, initialize stat_count */
+    if (sub((Word16) (st->tone_flag & 0x7c00), 0x7c00) == 0)
+    {
+        st->stat_count = STAT_COUNT;
+    } else
+    {
+        /* if 8 last vad-decisions have been "0", reinitialize stat_count */
+        if ((st->vadreg & 0x7f80) == 0)
+        {
+            st->stat_count = STAT_COUNT;
+        } else
+        {
+            stat_rat = 0;
+            for (i = 0; i < COMPLEN; i++)
+            {
+                if(level[i] > st->ave_level[i])
+                {
+                    num = level[i];
+                    denom = st->ave_level[i];
+                } else
+                {
+                    num = st->ave_level[i];
+                    denom = level[i];
+                }
+                /* Limit nimimum value of num and denom to STAT_THR_LEVEL */
+                if(num < STAT_THR_LEVEL)
+                {
+                    num = STAT_THR_LEVEL;
+                }
+                if(denom < STAT_THR_LEVEL)
+                {
+                    denom = STAT_THR_LEVEL;
+                }
+                exp = norm_s(denom);
+                denom = denom << exp;
 
-				/* stat_rat = num/denom * 64 */
-				temp = div_s(num >> 1, denom);
-				stat_rat = add1(stat_rat, shr(temp, (8 - exp)));
-			}
+                /* stat_rat = num/denom * 64 */
+                temp = div_s(num >> 1, denom);
+                stat_rat = add1(stat_rat, shr(temp, (8 - exp)));
+            }
 
-			/* compare stat_rat with a threshold and update stat_count */
-			if(stat_rat > STAT_THR)
-			{
-				st->stat_count = STAT_COUNT;
-			} else
-			{
-				if ((st->vadreg & 0x4000) != 0)
-				{
+            /* compare stat_rat with a threshold and update stat_count */
+            if(stat_rat > STAT_THR)
+            {
+                st->stat_count = STAT_COUNT;
+            } else
+            {
+                if ((st->vadreg & 0x4000) != 0)
+                {
 
-					if (st->stat_count != 0)
-					{
-						st->stat_count = st->stat_count - 1;
-					}
-				}
-			}
-		}
-	}
+                    if (st->stat_count != 0)
+                    {
+                        st->stat_count = st->stat_count - 1;
+                    }
+                }
+            }
+        }
+    }
 
-	/* Update average amplitude estimate for stationarity estimation */
-	alpha = ALPHA4;
-	if(st->stat_count == STAT_COUNT)
-	{
-		alpha = 32767;
-	} else if ((st->vadreg & 0x4000) == 0)
-	{
-		alpha = ALPHA5;
-	}
-	for (i = 0; i < COMPLEN; i++)
-	{
-		st->ave_level[i] = add1(st->ave_level[i], vo_mult_r(alpha, vo_sub(level[i], st->ave_level[i])));
-	}
+    /* Update average amplitude estimate for stationarity estimation */
+    alpha = ALPHA4;
+    if(st->stat_count == STAT_COUNT)
+    {
+        alpha = 32767;
+    } else if ((st->vadreg & 0x4000) == 0)
+    {
+        alpha = ALPHA5;
+    }
+    for (i = 0; i < COMPLEN; i++)
+    {
+        st->ave_level[i] = add1(st->ave_level[i], vo_mult_r(alpha, vo_sub(level[i], st->ave_level[i])));
+    }
 }
 
 /******************************************************************************
@@ -345,38 +345,38 @@
 *******************************************************************************/
 
 static Word16 hangover_addition(                      /* return: VAD_flag indicating final VAD decision */
-		VadVars * st,                         /* i/o : State structure                     */
-		Word16 low_power,                     /* i   : flag power of the input frame    */
-		Word16 hang_len,                      /* i   : hangover length */
-		Word16 burst_len                      /* i   : minimum burst length for hangover addition */
-		)
+        VadVars * st,                         /* i/o : State structure                     */
+        Word16 low_power,                     /* i   : flag power of the input frame    */
+        Word16 hang_len,                      /* i   : hangover length */
+        Word16 burst_len                      /* i   : minimum burst length for hangover addition */
+        )
 {
-	/* if the input power (pow_sum) is lower than a threshold, clear counters and set VAD_flag to "0"         */
-	if (low_power != 0)
-	{
-		st->burst_count = 0;
-		st->hang_count = 0;
-		return 0;
-	}
-	/* update the counters (hang_count, burst_count) */
-	if ((st->vadreg & 0x4000) != 0)
-	{
-		st->burst_count = st->burst_count + 1;
-		if(st->burst_count >= burst_len)
-		{
-			st->hang_count = hang_len;
-		}
-		return 1;
-	} else
-	{
-		st->burst_count = 0;
-		if (st->hang_count > 0)
-		{
-			st->hang_count = st->hang_count - 1;
-			return 1;
-		}
-	}
-	return 0;
+    /* if the input power (pow_sum) is lower than a threshold, clear counters and set VAD_flag to "0"         */
+    if (low_power != 0)
+    {
+        st->burst_count = 0;
+        st->hang_count = 0;
+        return 0;
+    }
+    /* update the counters (hang_count, burst_count) */
+    if ((st->vadreg & 0x4000) != 0)
+    {
+        st->burst_count = st->burst_count + 1;
+        if(st->burst_count >= burst_len)
+        {
+            st->hang_count = hang_len;
+        }
+        return 1;
+    } else
+    {
+        st->burst_count = 0;
+        if (st->hang_count > 0)
+        {
+            st->hang_count = st->hang_count - 1;
+            return 1;
+        }
+    }
+    return 0;
 }
 
 /******************************************************************************
@@ -387,66 +387,66 @@
 *******************************************************************************/
 
 static void noise_estimate_update(
-		VadVars * st,                         /* i/o : State structure                       */
-		Word16 level[]                        /* i   : sub-band levels of the input frame */
-		)
+        VadVars * st,                         /* i/o : State structure                       */
+        Word16 level[]                        /* i   : sub-band levels of the input frame */
+        )
 {
-	Word32 i;
-	Word16 alpha_up, alpha_down, bckr_add = 2;
+    Word32 i;
+    Word16 alpha_up, alpha_down, bckr_add = 2;
 
-	/* Control update of bckr_est[] */
-	update_cntrl(st, level);
+    /* Control update of bckr_est[] */
+    update_cntrl(st, level);
 
-	/* Choose update speed */
-	if ((0x7800 & st->vadreg) == 0)
-	{
-		alpha_up = ALPHA_UP1;
-		alpha_down = ALPHA_DOWN1;
-	} else
-	{
-		if (st->stat_count == 0)
-		{
-			alpha_up = ALPHA_UP2;
-			alpha_down = ALPHA_DOWN2;
-		} else
-		{
-			alpha_up = 0;
-			alpha_down = ALPHA3;
-			bckr_add = 0;
-		}
-	}
+    /* Choose update speed */
+    if ((0x7800 & st->vadreg) == 0)
+    {
+        alpha_up = ALPHA_UP1;
+        alpha_down = ALPHA_DOWN1;
+    } else
+    {
+        if (st->stat_count == 0)
+        {
+            alpha_up = ALPHA_UP2;
+            alpha_down = ALPHA_DOWN2;
+        } else
+        {
+            alpha_up = 0;
+            alpha_down = ALPHA3;
+            bckr_add = 0;
+        }
+    }
 
-	/* Update noise estimate (bckr_est) */
-	for (i = 0; i < COMPLEN; i++)
-	{
-		Word16 temp;
-		temp = (st->old_level[i] - st->bckr_est[i]);
+    /* Update noise estimate (bckr_est) */
+    for (i = 0; i < COMPLEN; i++)
+    {
+        Word16 temp;
+        temp = (st->old_level[i] - st->bckr_est[i]);
 
-		if (temp < 0)
-		{                                  /* update downwards */
-			st->bckr_est[i] = add1(-2, add(st->bckr_est[i],vo_mult_r(alpha_down, temp)));
-			/* limit minimum value of the noise estimate to NOISE_MIN */
-			if(st->bckr_est[i] < NOISE_MIN)
-			{
-				st->bckr_est[i] = NOISE_MIN;
-			}
-		} else
-		{                                  /* update upwards */
-			st->bckr_est[i] = add1(bckr_add, add1(st->bckr_est[i],vo_mult_r(alpha_up, temp)));
+        if (temp < 0)
+        {                                  /* update downwards */
+            st->bckr_est[i] = add1(-2, add(st->bckr_est[i],vo_mult_r(alpha_down, temp)));
+            /* limit minimum value of the noise estimate to NOISE_MIN */
+            if(st->bckr_est[i] < NOISE_MIN)
+            {
+                st->bckr_est[i] = NOISE_MIN;
+            }
+        } else
+        {                                  /* update upwards */
+            st->bckr_est[i] = add1(bckr_add, add1(st->bckr_est[i],vo_mult_r(alpha_up, temp)));
 
-			/* limit maximum value of the noise estimate to NOISE_MAX */
-			if(st->bckr_est[i] > NOISE_MAX)
-			{
-				st->bckr_est[i] = NOISE_MAX;
-			}
-		}
-	}
+            /* limit maximum value of the noise estimate to NOISE_MAX */
+            if(st->bckr_est[i] > NOISE_MAX)
+            {
+                st->bckr_est[i] = NOISE_MAX;
+            }
+        }
+    }
 
-	/* Update signal levels of the previous frame (old_level) */
-	for (i = 0; i < COMPLEN; i++)
-	{
-		st->old_level[i] = level[i];
-	}
+    /* Update signal levels of the previous frame (old_level) */
+    for (i = 0; i < COMPLEN; i++)
+    {
+        st->old_level[i] = level[i];
+    }
 }
 
 /******************************************************************************
@@ -457,100 +457,100 @@
 *******************************************************************************/
 
 static Word16 vad_decision(                           /* return value : VAD_flag */
-		VadVars * st,                         /* i/o : State structure                       */
-		Word16 level[COMPLEN],                /* i   : sub-band levels of the input frame */
-		Word32 pow_sum                        /* i   : power of the input frame           */
-		)
+        VadVars * st,                         /* i/o : State structure                       */
+        Word16 level[COMPLEN],                /* i   : sub-band levels of the input frame */
+        Word32 pow_sum                        /* i   : power of the input frame           */
+        )
 {
-	Word32 i;
-	Word32 L_snr_sum;
-	Word32 L_temp;
-	Word16 vad_thr, temp, noise_level;
-	Word16 low_power_flag;
-	Word16 hang_len, burst_len;
-	Word16 ilog2_speech_level, ilog2_noise_level;
-	Word16 temp2;
+    Word32 i;
+    Word32 L_snr_sum;
+    Word32 L_temp;
+    Word16 vad_thr, temp, noise_level;
+    Word16 low_power_flag;
+    Word16 hang_len, burst_len;
+    Word16 ilog2_speech_level, ilog2_noise_level;
+    Word16 temp2;
 
-	/* Calculate squared sum of the input levels (level) divided by the background noise components
-	 * (bckr_est). */
-	L_snr_sum = 0;
-	for (i = 0; i < COMPLEN; i++)
-	{
-		Word16 exp;
+    /* Calculate squared sum of the input levels (level) divided by the background noise components
+     * (bckr_est). */
+    L_snr_sum = 0;
+    for (i = 0; i < COMPLEN; i++)
+    {
+        Word16 exp;
 
-		exp = norm_s(st->bckr_est[i]);
-		temp = (st->bckr_est[i] << exp);
-		temp = div_s((level[i] >> 1), temp);
-		temp = shl(temp, (exp - (UNIRSHFT - 1)));
-		L_snr_sum = L_mac(L_snr_sum, temp, temp);
-	}
+        exp = norm_s(st->bckr_est[i]);
+        temp = (st->bckr_est[i] << exp);
+        temp = div_s((level[i] >> 1), temp);
+        temp = shl(temp, (exp - (UNIRSHFT - 1)));
+        L_snr_sum = L_mac(L_snr_sum, temp, temp);
+    }
 
-	/* Calculate average level of estimated background noise */
-	L_temp = 0;
-	for (i = 1; i < COMPLEN; i++)          /* ignore lowest band */
-	{
-		L_temp = vo_L_add(L_temp, st->bckr_est[i]);
-	}
+    /* Calculate average level of estimated background noise */
+    L_temp = 0;
+    for (i = 1; i < COMPLEN; i++)          /* ignore lowest band */
+    {
+        L_temp = vo_L_add(L_temp, st->bckr_est[i]);
+    }
 
-	noise_level = extract_h((L_temp << 12));
-	/* if SNR is lower than a threshold (MIN_SPEECH_SNR), and increase speech_level */
-	temp = vo_mult(noise_level, MIN_SPEECH_SNR) << 3;
+    noise_level = extract_h((L_temp << 12));
+    /* if SNR is lower than a threshold (MIN_SPEECH_SNR), and increase speech_level */
+    temp = vo_mult(noise_level, MIN_SPEECH_SNR) << 3;
 
-	if(st->speech_level < temp)
-	{
-		st->speech_level = temp;
-	}
-	ilog2_noise_level = ilog2(noise_level);
+    if(st->speech_level < temp)
+    {
+        st->speech_level = temp;
+    }
+    ilog2_noise_level = ilog2(noise_level);
 
-	/* If SNR is very poor, speech_level is probably corrupted by noise level. This is correctred by
-	 * subtracting MIN_SPEECH_SNR*noise_level from speech level */
-	ilog2_speech_level = ilog2(st->speech_level - temp);
+    /* If SNR is very poor, speech_level is probably corrupted by noise level. This is correctred by
+     * subtracting MIN_SPEECH_SNR*noise_level from speech level */
+    ilog2_speech_level = ilog2(st->speech_level - temp);
 
-	temp = add1(vo_mult(NO_SLOPE, (ilog2_noise_level - NO_P1)), THR_HIGH);
+    temp = add1(vo_mult(NO_SLOPE, (ilog2_noise_level - NO_P1)), THR_HIGH);
 
-	temp2 = add1(SP_CH_MIN, vo_mult(SP_SLOPE, (ilog2_speech_level - SP_P1)));
-	if (temp2 < SP_CH_MIN)
-	{
-		temp2 = SP_CH_MIN;
-	}
-	if (temp2 > SP_CH_MAX)
-	{
-		temp2 = SP_CH_MAX;
-	}
-	vad_thr = temp + temp2;
+    temp2 = add1(SP_CH_MIN, vo_mult(SP_SLOPE, (ilog2_speech_level - SP_P1)));
+    if (temp2 < SP_CH_MIN)
+    {
+        temp2 = SP_CH_MIN;
+    }
+    if (temp2 > SP_CH_MAX)
+    {
+        temp2 = SP_CH_MAX;
+    }
+    vad_thr = temp + temp2;
 
-	if(vad_thr < THR_MIN)
-	{
-		vad_thr = THR_MIN;
-	}
-	/* Shift VAD decision register */
-	st->vadreg = (st->vadreg >> 1);
+    if(vad_thr < THR_MIN)
+    {
+        vad_thr = THR_MIN;
+    }
+    /* Shift VAD decision register */
+    st->vadreg = (st->vadreg >> 1);
 
-	/* Make intermediate VAD decision */
-	if(L_snr_sum > vo_L_mult(vad_thr, (512 * COMPLEN)))
-	{
-		st->vadreg = (Word16) (st->vadreg | 0x4000);
-	}
-	/* check if the input power (pow_sum) is lower than a threshold" */
-	if(pow_sum < VAD_POW_LOW)
-	{
-		low_power_flag = 1;
-	} else
-	{
-		low_power_flag = 0;
-	}
-	/* Update background noise estimates */
-	noise_estimate_update(st, level);
+    /* Make intermediate VAD decision */
+    if(L_snr_sum > vo_L_mult(vad_thr, (512 * COMPLEN)))
+    {
+        st->vadreg = (Word16) (st->vadreg | 0x4000);
+    }
+    /* check if the input power (pow_sum) is lower than a threshold" */
+    if(pow_sum < VAD_POW_LOW)
+    {
+        low_power_flag = 1;
+    } else
+    {
+        low_power_flag = 0;
+    }
+    /* Update background noise estimates */
+    noise_estimate_update(st, level);
 
-	/* Calculate values for hang_len and burst_len based on vad_thr */
-	hang_len = add1(vo_mult(HANG_SLOPE, (vad_thr - HANG_P1)), HANG_HIGH);
-	if(hang_len < HANG_LOW)
-	{
-		hang_len = HANG_LOW;
-	}
-	burst_len = add1(vo_mult(BURST_SLOPE, (vad_thr - BURST_P1)), BURST_HIGH);
+    /* Calculate values for hang_len and burst_len based on vad_thr */
+    hang_len = add1(vo_mult(HANG_SLOPE, (vad_thr - HANG_P1)), HANG_HIGH);
+    if(hang_len < HANG_LOW)
+    {
+        hang_len = HANG_LOW;
+    }
+    burst_len = add1(vo_mult(BURST_SLOPE, (vad_thr - BURST_P1)), BURST_HIGH);
 
-	return (hangover_addition(st, low_power_flag, hang_len, burst_len));
+    return (hangover_addition(st, low_power_flag, hang_len, burst_len));
 }
 
 /******************************************************************************
@@ -566,54 +566,54 @@
 *******************************************************************************/
 
 static void Estimate_Speech(
-		VadVars * st,                         /* i/o : State structure    */
-		Word16 in_level                       /* level of the input frame */
-		)
+        VadVars * st,                         /* i/o : State structure    */
+        Word16 in_level                       /* level of the input frame */
+        )
 {
-	Word16 alpha;
+    Word16 alpha;
 
-	/* if the required activity count cannot be achieved, reset counters */
-	if((st->sp_est_cnt - st->sp_max_cnt) > (SP_EST_COUNT - SP_ACTIVITY_COUNT))
-	{
-		st->sp_est_cnt = 0;
-		st->sp_max = 0;
-		st->sp_max_cnt = 0;
-	}
-	st->sp_est_cnt += 1;
+    /* if the required activity count cannot be achieved, reset counters */
+    if((st->sp_est_cnt - st->sp_max_cnt) > (SP_EST_COUNT - SP_ACTIVITY_COUNT))
+    {
+        st->sp_est_cnt = 0;
+        st->sp_max = 0;
+        st->sp_max_cnt = 0;
+    }
+    st->sp_est_cnt += 1;
 
-	if (((st->vadreg & 0x4000)||(in_level > st->speech_level)) && (in_level > MIN_SPEECH_LEVEL1))
-	{
-		/* update sp_max */
-		if(in_level > st->sp_max)
-		{
-			st->sp_max = in_level;
-		}
-		st->sp_max_cnt += 1;
+    if (((st->vadreg & 0x4000)||(in_level > st->speech_level)) && (in_level > MIN_SPEECH_LEVEL1))
+    {
+        /* update sp_max */
+        if(in_level > st->sp_max)
+        {
+            st->sp_max = in_level;
+        }
+        st->sp_max_cnt += 1;
 
-		if(st->sp_max_cnt >= SP_ACTIVITY_COUNT)
-		{
-			Word16 tmp;
-			/* update speech estimate */
-			tmp = (st->sp_max >> 1);      /* scale to get "average" speech level */
+        if(st->sp_max_cnt >= SP_ACTIVITY_COUNT)
+        {
+            Word16 tmp;
+            /* update speech estimate */
+            tmp = (st->sp_max >> 1);      /* scale to get "average" speech level */
 
-			/* select update speed */
-			if(tmp > st->speech_level)
-			{
-				alpha = ALPHA_SP_UP;
-			} else
-			{
-				alpha = ALPHA_SP_DOWN;
-			}
-			if(tmp > MIN_SPEECH_LEVEL2)
-			{
-				st->speech_level = add1(st->speech_level, vo_mult_r(alpha, vo_sub(tmp, st->speech_level)));
-			}
-			/* clear all counters used for speech estimation */
-			st->sp_max = 0;
-			st->sp_max_cnt = 0;
-			st->sp_est_cnt = 0;
-		}
-	}
+            /* select update speed */
+            if(tmp > st->speech_level)
+            {
+                alpha = ALPHA_SP_UP;
+            } else
+            {
+                alpha = ALPHA_SP_DOWN;
+            }
+            if(tmp > MIN_SPEECH_LEVEL2)
+            {
+                st->speech_level = add1(st->speech_level, vo_mult_r(alpha, vo_sub(tmp, st->speech_level)));
+            }
+            /* clear all counters used for speech estimation */
+            st->sp_max = 0;
+            st->sp_max_cnt = 0;
+            st->sp_est_cnt = 0;
+        }
+    }
 }
 
 /******************************************************************************
@@ -624,30 +624,30 @@
 *******************************************************************************/
 
 Word16 wb_vad_init(                        /* return: non-zero with error, zero for ok. */
-		VadVars ** state,                     /* i/o : State structure    */
-		VO_MEM_OPERATOR *pMemOP
-		)
+        VadVars ** state,                     /* i/o : State structure    */
+        VO_MEM_OPERATOR *pMemOP
+        )
 {
-	VadVars *s;
+    VadVars *s;
 
-	if (state == (VadVars **) NULL)
-	{
-		fprintf(stderr, "vad_init: invalid parameter\n");
-		return -1;
-	}
-	*state = NULL;
+    if (state == (VadVars **) NULL)
+    {
+        fprintf(stderr, "vad_init: invalid parameter\n");
+        return -1;
+    }
+    *state = NULL;
 
-	/* allocate memory */
-	if ((s = (VadVars *) mem_malloc(pMemOP, sizeof(VadVars), 32, VO_INDEX_ENC_AMRWB)) == NULL)
-	{
-		fprintf(stderr, "vad_init: can not malloc state structure\n");
-		return -1;
-	}
-	wb_vad_reset(s);
+    /* allocate memory */
+    if ((s = (VadVars *) mem_malloc(pMemOP, sizeof(VadVars), 32, VO_INDEX_ENC_AMRWB)) == NULL)
+    {
+        fprintf(stderr, "vad_init: can not malloc state structure\n");
+        return -1;
+    }
+    wb_vad_reset(s);
 
-	*state = s;
+    *state = s;
 
-	return 0;
+    return 0;
 }
 
 /******************************************************************************
@@ -658,51 +658,51 @@
 *******************************************************************************/
 
 Word16 wb_vad_reset(                       /* return: non-zero with error, zero for ok. */
-		VadVars * state                       /* i/o : State structure    */
-		)
+        VadVars * state                       /* i/o : State structure    */
+        )
 {
-	Word32 i, j;
+    Word32 i, j;
 
-	if (state == (VadVars *) NULL)
-	{
-		fprintf(stderr, "vad_reset: invalid parameter\n");
-		return -1;
-	}
-	state->tone_flag = 0;
-	state->vadreg = 0;
-	state->hang_count = 0;
-	state->burst_count = 0;
-	state->hang_count = 0;
+    if (state == (VadVars *) NULL)
+    {
+        fprintf(stderr, "vad_reset: invalid parameter\n");
+        return -1;
+    }
+    state->tone_flag = 0;
+    state->vadreg = 0;
+    state->hang_count = 0;
+    state->burst_count = 0;
+    state->hang_count = 0;
 
-	/* initialize memory used by the filter bank */
-	for (i = 0; i < F_5TH_CNT; i++)
-	{
-		for (j = 0; j < 2; j++)
-		{
-			state->a_data5[i][j] = 0;
-		}
-	}
+    /* initialize memory used by the filter bank */
+    for (i = 0; i < F_5TH_CNT; i++)
+    {
+        for (j = 0; j < 2; j++)
+        {
+            state->a_data5[i][j] = 0;
+        }
+    }
 
-	for (i = 0; i < F_3TH_CNT; i++)
-	{
-		state->a_data3[i] = 0;
-	}
+    for (i = 0; i < F_3TH_CNT; i++)
+    {
+        state->a_data3[i] = 0;
+    }
 
-	/* initialize the rest of the memory */
-	for (i = 0; i < COMPLEN; i++)
-	{
-		state->bckr_est[i] = NOISE_INIT;
-		state->old_level[i] = NOISE_INIT;
-		state->ave_level[i] = NOISE_INIT;
-		state->sub_level[i] = 0;
-	}
+    /* initialize the rest of the memory */
+    for (i = 0; i < COMPLEN; i++)
+    {
+        state->bckr_est[i] = NOISE_INIT;
+        state->old_level[i] = NOISE_INIT;
+        state->ave_level[i] = NOISE_INIT;
+        state->sub_level[i] = 0;
+    }
 
-	state->sp_est_cnt = 0;
-	state->sp_max = 0;
-	state->sp_max_cnt = 0;
-	state->speech_level = SPEECH_LEVEL_INIT;
-	state->prev_pow_sum = 0;
-	return 0;
+    state->sp_est_cnt = 0;
+    state->sp_max = 0;
+    state->sp_max_cnt = 0;
+    state->speech_level = SPEECH_LEVEL_INIT;
+    state->prev_pow_sum = 0;
+    return 0;
 }
 
 /******************************************************************************
@@ -713,16 +713,16 @@
 *******************************************************************************/
 
 void wb_vad_exit(
-		VadVars ** state,                      /* i/o : State structure    */
-		VO_MEM_OPERATOR *pMemOP
-		)
+        VadVars ** state,                      /* i/o : State structure    */
+        VO_MEM_OPERATOR *pMemOP
+        )
 {
-	if (state == NULL || *state == NULL)
-		return;
-	/* deallocate memory */
-	mem_free(pMemOP, *state, VO_INDEX_ENC_AMRWB);
-	*state = NULL;
-	return;
+    if (state == NULL || *state == NULL)
+        return;
+    /* deallocate memory */
+    mem_free(pMemOP, *state, VO_INDEX_ENC_AMRWB);
+    *state = NULL;
+    return;
 }
 
 /******************************************************************************
@@ -735,18 +735,18 @@
 *******************************************************************************/
 
 void wb_vad_tone_detection(
-		VadVars * st,                         /* i/o : State struct            */
-		Word16 p_gain                         /* pitch gain      */
-		)
+        VadVars * st,                         /* i/o : State struct            */
+        Word16 p_gain                         /* pitch gain      */
+        )
 {
-	/* update tone flag */
-	st->tone_flag = (st->tone_flag >> 1);
+    /* update tone flag */
+    st->tone_flag = (st->tone_flag >> 1);
 
-	/* if (pitch_gain > TONE_THR) set tone flag */
-	if (p_gain > TONE_THR)
-	{
-		st->tone_flag = (Word16) (st->tone_flag | 0x4000);
-	}
+    /* if (pitch_gain > TONE_THR) set tone flag */
+    if (p_gain > TONE_THR)
+    {
+        st->tone_flag = (Word16) (st->tone_flag | 0x4000);
+    }
 }
 
 /******************************************************************************
@@ -757,50 +757,50 @@
 *******************************************************************************/
 
 Word16 wb_vad(                                /* Return value : VAD Decision, 1 = speech, 0 = noise */
-		VadVars * st,                         /* i/o : State structure                 */
-		Word16 in_buf[]                       /* i   : samples of the input frame   */
-	     )
+        VadVars * st,                         /* i/o : State structure                 */
+        Word16 in_buf[]                       /* i   : samples of the input frame   */
+         )
 {
-	Word16 level[COMPLEN];
-	Word32 i;
-	Word16 VAD_flag, temp;
-	Word32 L_temp, pow_sum;
+    Word16 level[COMPLEN];
+    Word32 i;
+    Word16 VAD_flag, temp;
+    Word32 L_temp, pow_sum;
 
-	/* Calculate power of the input frame. */
-	L_temp = 0L;
-	for (i = 0; i < FRAME_LEN; i++)
-	{
-		L_temp = L_mac(L_temp, in_buf[i], in_buf[i]);
-	}
+    /* Calculate power of the input frame. */
+    L_temp = 0L;
+    for (i = 0; i < FRAME_LEN; i++)
+    {
+        L_temp = L_mac(L_temp, in_buf[i], in_buf[i]);
+    }
 
-	/* pow_sum = power of current frame and previous frame */
-	pow_sum = L_add(L_temp, st->prev_pow_sum);
+    /* pow_sum = power of current frame and previous frame */
+    pow_sum = L_add(L_temp, st->prev_pow_sum);
 
-	/* save power of current frame for next call */
-	st->prev_pow_sum = L_temp;
+    /* save power of current frame for next call */
+    st->prev_pow_sum = L_temp;
 
-	/* If input power is very low, clear tone flag */
-	if (pow_sum < POW_TONE_THR)
-	{
-		st->tone_flag = (Word16) (st->tone_flag & 0x1fff);
-	}
-	/* Run the filter bank and calculate signal levels at each band */
-	filter_bank(st, in_buf, level);
+    /* If input power is very low, clear tone flag */
+    if (pow_sum < POW_TONE_THR)
+    {
+        st->tone_flag = (Word16) (st->tone_flag & 0x1fff);
+    }
+    /* Run the filter bank and calculate signal levels at each band */
+    filter_bank(st, in_buf, level);
 
-	/* compute VAD decision */
-	VAD_flag = vad_decision(st, level, pow_sum);
+    /* compute VAD decision */
+    VAD_flag = vad_decision(st, level, pow_sum);
 
-	/* Calculate input level */
-	L_temp = 0;
-	for (i = 1; i < COMPLEN; i++)          /* ignore lowest band */
-	{
-		L_temp = vo_L_add(L_temp, level[i]);
-	}
+    /* Calculate input level */
+    L_temp = 0;
+    for (i = 1; i < COMPLEN; i++)          /* ignore lowest band */
+    {
+        L_temp = vo_L_add(L_temp, level[i]);
+    }
 
-	temp = extract_h(L_temp << 12);
+    temp = extract_h(L_temp << 12);
 
-	Estimate_Speech(st, temp);             /* Estimate speech level */
-	return (VAD_flag);
+    Estimate_Speech(st, temp);             /* Estimate speech level */
+    return (VAD_flag);
 }
 
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/weight_a.c b/media/libstagefright/codecs/amrwbenc/src/weight_a.c
index a02b48d..23b774e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/weight_a.c
+++ b/media/libstagefright/codecs/amrwbenc/src/weight_a.c
@@ -18,7 +18,7 @@
 *       File: weight_a.c                                               *
 *                                                                      *
 *       Description:Weighting of LPC coefficients                      *
-*	               ap[i] = a[i] * (gamma ** i)                     *
+*                  ap[i] = a[i] * (gamma ** i)                     *
 *                                                                      *
 ************************************************************************/
 
@@ -26,22 +26,22 @@
 #include "basic_op.h"
 
 void Weight_a(
-		Word16 a[],                           /* (i) Q12 : a[m+1]  LPC coefficients             */
-		Word16 ap[],                          /* (o) Q12 : Spectral expanded LPC coefficients   */
-		Word16 gamma,                         /* (i) Q15 : Spectral expansion factor.           */
-		Word16 m                              /* (i)     : LPC order.                           */
-	     )
+        Word16 a[],                           /* (i) Q12 : a[m+1]  LPC coefficients             */
+        Word16 ap[],                          /* (o) Q12 : Spectral expanded LPC coefficients   */
+        Word16 gamma,                         /* (i) Q15 : Spectral expansion factor.           */
+        Word16 m                              /* (i)     : LPC order.                           */
+         )
 {
-	Word32 num = m - 1, fac;
-	*ap++ = *a++;
-	fac = gamma;
-	do{
-		*ap++ =(Word16)(((vo_L_mult((*a++), fac)) + 0x8000) >> 16);
-		fac = (vo_L_mult(fac, gamma) + 0x8000) >> 16;
-	}while(--num != 0);
+    Word32 num = m - 1, fac;
+    *ap++ = *a++;
+    fac = gamma;
+    do{
+        *ap++ =(Word16)(((vo_L_mult((*a++), fac)) + 0x8000) >> 16);
+        fac = (vo_L_mult(fac, gamma) + 0x8000) >> 16;
+    }while(--num != 0);
 
-	*ap++ = (Word16)(((vo_L_mult((*a++), fac)) + 0x8000) >> 16);
-	return;
+    *ap++ = (Word16)(((vo_L_mult((*a++), fac)) + 0x8000) >> 16);
+    return;
 }
 
 
diff --git a/media/libstagefright/codecs/avc/common/Android.mk b/media/libstagefright/codecs/avc/common/Android.mk
index 844ef0a..ed0f8ca 100644
--- a/media/libstagefright/codecs/avc/common/Android.mk
+++ b/media/libstagefright/codecs/avc/common/Android.mk
@@ -17,5 +17,7 @@
  	$(LOCAL_PATH)/include
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/avc/enc/Android.mk b/media/libstagefright/codecs/avc/enc/Android.mk
index d5131cb..8ff2f35 100644
--- a/media/libstagefright/codecs/avc/enc/Android.mk
+++ b/media/libstagefright/codecs/avc/enc/Android.mk
@@ -31,6 +31,8 @@
     -DOSCL_IMPORT_REF= -D"OSCL_UNUSED_ARG(x)=(void)(x)" -DOSCL_EXPORT_REF=
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 include $(BUILD_STATIC_LIBRARY)
 
@@ -72,6 +74,8 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 include $(BUILD_SHARED_LIBRARY)
 
@@ -90,6 +94,8 @@
 
 LOCAL_CFLAGS := \
     -DOSCL_IMPORT_REF= -DOSCL_UNUSED_ARG= -DOSCL_EXPORT_REF=
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 LOCAL_STATIC_LIBRARIES := \
         libstagefright_avcenc
diff --git a/media/libstagefright/codecs/avc/enc/src/avcenc_int.h b/media/libstagefright/codecs/avc/enc/src/avcenc_int.h
index 3fe08a1..22042a5 100644
--- a/media/libstagefright/codecs/avc/enc/src/avcenc_int.h
+++ b/media/libstagefright/codecs/avc/enc/src/avcenc_int.h
@@ -43,7 +43,7 @@
 #define MAX_QP          51
 #define SHIFT_QP        12
 #define  LAMBDA_ACCURACY_BITS         16
-#define  LAMBDA_FACTOR(lambda)        ((int)((double)(1<<LAMBDA_ACCURACY_BITS)*lambda+0.5))
+#define  LAMBDA_FACTOR(lambda)        ((int)((double)(1<<LAMBDA_ACCURACY_BITS)*(lambda)+0.5))
 
 
 #define DISABLE_THRESHOLDING  0
@@ -55,8 +55,8 @@
 #define MAX_VALUE       999999   //!< used for start value for some variables
 
 #define  WEIGHTED_COST(factor,bits)   (((factor)*(bits))>>LAMBDA_ACCURACY_BITS)
-#define  MV_COST(f,s,cx,cy,px,py)     (WEIGHTED_COST(f,mvbits[((cx)<<(s))-px]+mvbits[((cy)<<(s))-py]))
-#define  MV_COST_S(f,cx,cy,px,py)     (WEIGHTED_COST(f,mvbits[cx-px]+mvbits[cy-py]))
+#define  MV_COST(f,s,cx,cy,px,py)     (WEIGHTED_COST(f,mvbits[((cx)<<(s))-(px)]+mvbits[((cy)<<((s)))-(py)]))
+#define  MV_COST_S(f,cx,cy,px,py)     (WEIGHTED_COST(f,mvbits[(cx)-(px)]+mvbits[(cy)-(py)]))
 
 /* for sub-pel search and interpolation */
 #define SUBPEL_PRED_BLK_SIZE 576 // 24x24
diff --git a/media/libstagefright/codecs/avc/enc/src/findhalfpel.cpp b/media/libstagefright/codecs/avc/enc/src/findhalfpel.cpp
index d0bbee2..941ae5a 100644
--- a/media/libstagefright/codecs/avc/enc/src/findhalfpel.cpp
+++ b/media/libstagefright/codecs/avc/enc/src/findhalfpel.cpp
@@ -23,13 +23,13 @@
 
 #define PREF_16_VEC 129     /* 1MV bias versus 4MVs*/
 
-#define CLIP_RESULT(x)      if((uint)x > 0xFF){ \
-                 x = 0xFF & (~(x>>31));}
+#define CLIP_RESULT(x)      if((uint)(x) > 0xFF){ \
+                 (x) = 0xFF & (~((x)>>31));}
 
-#define CLIP_UPPER16(x)     if((uint)x >= 0x20000000){ \
-        x = 0xFF0000 & (~(x>>31));} \
+#define CLIP_UPPER16(x)     if((uint)(x) >= 0x20000000){ \
+        (x) = 0xFF0000 & (~((x)>>31));} \
         else { \
-        x = (x>>5)&0xFF0000; \
+        (x) = ((x)>>5)&0xFF0000; \
         }
 
 /*=====================================================================
diff --git a/media/libstagefright/codecs/avc/enc/src/intra_est.cpp b/media/libstagefright/codecs/avc/enc/src/intra_est.cpp
index 17e5985..e397805 100644
--- a/media/libstagefright/codecs/avc/enc/src/intra_est.cpp
+++ b/media/libstagefright/codecs/avc/enc/src/intra_est.cpp
@@ -25,8 +25,8 @@
 #define FIXED_I4_MODE   AVC_I4_Diagonal_Down_Left
 #define FIXED_INTRA_CHROMA_MODE AVC_IC_DC
 
-#define CLIP_RESULT(x)      if((uint)x > 0xFF){ \
-                 x = 0xFF & (~(x>>31));}
+#define CLIP_RESULT(x)      if((uint)(x) > 0xFF){ \
+                 (x) = 0xFF & (~((x)>>31));}
 
 
 bool IntraDecisionABE(AVCEncObject *encvid, int min_cost, uint8 *curL, int picPitch)
diff --git a/media/libstagefright/codecs/avc/enc/src/motion_comp.cpp b/media/libstagefright/codecs/avc/enc/src/motion_comp.cpp
index a390f88..d19125f 100644
--- a/media/libstagefright/codecs/avc/enc/src/motion_comp.cpp
+++ b/media/libstagefright/codecs/avc/enc/src/motion_comp.cpp
@@ -19,8 +19,8 @@
 #include "avcenc_int.h"
 
 
-#define CLIP_RESULT(x)      if((uint)x > 0xFF){ \
-                 x = 0xFF & (~(x>>31));}
+#define CLIP_RESULT(x)      if((uint)(x) > 0xFF){ \
+                 (x) = 0xFF & (~((x)>>31));}
 
 /* (blkwidth << 2) + (dy << 1) + dx */
 static void (*const eChromaMC_SIMD[8])(uint8 *, int , int , int , uint8 *, int, int , int) =
diff --git a/media/libstagefright/codecs/avcdec/Android.mk b/media/libstagefright/codecs/avcdec/Android.mk
index 902ab57..ef0dbfd 100644
--- a/media/libstagefright/codecs/avcdec/Android.mk
+++ b/media/libstagefright/codecs/avcdec/Android.mk
@@ -20,6 +20,9 @@
 LOCAL_SHARED_LIBRARIES  += libutils
 LOCAL_SHARED_LIBRARIES  += liblog
 
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
+
 LOCAL_LDFLAGS := -Wl,-Bsymbolic
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/avcdec/SoftAVCDec.cpp b/media/libstagefright/codecs/avcdec/SoftAVCDec.cpp
index afbe230..653e812 100644
--- a/media/libstagefright/codecs/avcdec/SoftAVCDec.cpp
+++ b/media/libstagefright/codecs/avcdec/SoftAVCDec.cpp
@@ -492,16 +492,6 @@
     List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
     List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
 
-    /* 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();
-    }
-
     while (!outQueue.empty()) {
         BufferInfo *inInfo;
         OMX_BUFFERHEADERTYPE *inHeader;
@@ -628,6 +618,8 @@
                 mChangingResolution = false;
                 resetDecoder();
                 resetPlugin();
+                mStride = outputBufferWidth();
+                setParams(mStride);
                 continue;
             }
 
@@ -662,7 +654,7 @@
                 outInfo = NULL;
                 notifyFillBufferDone(outHeader);
                 outHeader = NULL;
-            } else {
+            } else if (mIsInFlush) {
                 /* If in flush mode and no output is returned by the codec,
                  * then come out of flush mode */
                 mIsInFlush = false;
@@ -683,6 +675,16 @@
             }
         }
 
+        /* 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();
+        }
+
         if (inHeader != NULL) {
             inInfo->mOwnedByUs = false;
             inQueue.erase(inQueue.begin());
diff --git a/media/libstagefright/codecs/avcdec/SoftAVCDec.h b/media/libstagefright/codecs/avcdec/SoftAVCDec.h
index 9dcabb4..bdac784 100644
--- a/media/libstagefright/codecs/avcdec/SoftAVCDec.h
+++ b/media/libstagefright/codecs/avcdec/SoftAVCDec.h
@@ -46,8 +46,8 @@
 
 /** 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);
+    diff = (((end).tv_sec - (start).tv_sec) * 1000000) + \
+            ((end).tv_usec - (start).tv_usec);
 
 struct SoftAVC : public SoftVideoDecoderOMXComponent {
     SoftAVC(const char *name, const OMX_CALLBACKTYPE *callbacks,
diff --git a/media/libstagefright/codecs/avcenc/Android.mk b/media/libstagefright/codecs/avcenc/Android.mk
index 24a4db9..70e531b 100644
--- a/media/libstagefright/codecs/avcenc/Android.mk
+++ b/media/libstagefright/codecs/avcenc/Android.mk
@@ -23,6 +23,9 @@
 LOCAL_SHARED_LIBRARIES  += libutils
 LOCAL_SHARED_LIBRARIES  += liblog
 
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
+
 LOCAL_LDFLAGS := -Wl,-Bsymbolic
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/avcenc/SoftAVCEnc.cpp b/media/libstagefright/codecs/avcenc/SoftAVCEnc.cpp
index 387d17d..760ebaa 100644
--- a/media/libstagefright/codecs/avcenc/SoftAVCEnc.cpp
+++ b/media/libstagefright/codecs/avcenc/SoftAVCEnc.cpp
@@ -157,8 +157,7 @@
             kProfileLevels, NELEM(kProfileLevels),
             176 /* width */, 144 /* height */,
             callbacks, appData, component),
-      mBitrateUpdated(false),
-      mKeyFrameRequested(false),
+      mUpdateFlag(0),
       mIvVideoColorFormat(IV_YUV_420P),
       mAVCEncProfile(IV_PROFILE_BASE),
       mAVCEncLevel(41),
@@ -207,6 +206,7 @@
     mEnableAltRef = DEFAULT_ENABLE_ALT_REF;
     mEncSpeed = DEFAULT_ENC_SPEED;
     mIntra4x4 = DEFAULT_INTRA4x4;
+    mConstrainedIntraFlag = DEFAULT_CONSTRAINED_INTRA;
     mAIRMode = DEFAULT_AIR;
     mAIRRefreshPeriod = DEFAULT_AIR_REFRESH_PERIOD;
     mPSNREnable = DEFAULT_PSNR_ENABLE;
@@ -304,6 +304,7 @@
 
     s_ipe_params_ip.u4_enable_intra_4x4 = mIntra4x4;
     s_ipe_params_ip.u4_enc_speed_preset = mEncSpeed;
+    s_ipe_params_ip.u4_constrained_intra_pred = mConstrainedIntraFlag;
 
     s_ipe_params_ip.u4_timestamp_high = -1;
     s_ipe_params_ip.u4_timestamp_low = -1;
@@ -999,6 +1000,7 @@
             }
 
             mIInterval = avcType->nPFrames + avcType->nBFrames;
+            mConstrainedIntraFlag = avcType->bconstIpred;
 
             if (OMX_VIDEO_AVCLoopFilterDisable == avcType->eLoopFilterMode)
                 mDisableDeblkLevel = 4;
@@ -1008,7 +1010,6 @@
                     || avcType->nRefIdx10ActiveMinus1 != 0
                     || avcType->nRefIdx11ActiveMinus1 != 0
                     || avcType->bWeightedPPrediction != OMX_FALSE
-                    || avcType->bconstIpred != OMX_FALSE
                     || avcType->bDirect8x8Inference != OMX_FALSE
                     || avcType->bDirectSpatialTemporal != OMX_FALSE
                     || avcType->nCabacInitIdc != 0) {
@@ -1039,7 +1040,9 @@
                 return OMX_ErrorBadPortIndex;
             }
 
-            mKeyFrameRequested = params->IntraRefreshVOP;
+            if (params->IntraRefreshVOP) {
+                mUpdateFlag |= kRequestKeyFrame;
+            }
             return OMX_ErrorNone;
         }
 
@@ -1054,7 +1057,7 @@
 
             if (mBitrate != params->nEncodeBitrate) {
                 mBitrate = params->nEncodeBitrate;
-                mBitrateUpdated = true;
+                mUpdateFlag |= kUpdateBitrate;
             }
             return OMX_ErrorNone;
         }
@@ -1071,7 +1074,7 @@
     }
 
     mBitrate = bitrate->nTargetBitrate;
-    mBitrateUpdated = true;
+    mUpdateFlag |= kUpdateBitrate;
 
     return OMX_ErrorNone;
 }
@@ -1291,12 +1294,14 @@
             return;
         }
 
-        if (mBitrateUpdated) {
-            setBitRate();
-        }
-
-        if (mKeyFrameRequested) {
-            setFrameType(IV_IDR_FRAME);
+        if (mUpdateFlag) {
+            if (mUpdateFlag & kUpdateBitrate) {
+                setBitRate();
+            }
+            if (mUpdateFlag & kRequestKeyFrame) {
+                setFrameType(IV_IDR_FRAME);
+            }
+            mUpdateFlag = 0;
         }
 
         if ((inputBufferHeader != NULL)
diff --git a/media/libstagefright/codecs/avcenc/SoftAVCEnc.h b/media/libstagefright/codecs/avcenc/SoftAVCEnc.h
index 4418a7f..a35ec17 100644
--- a/media/libstagefright/codecs/avcenc/SoftAVCEnc.h
+++ b/media/libstagefright/codecs/avcenc/SoftAVCEnc.h
@@ -95,8 +95,7 @@
 #define DEFAULT_SOC                 SOC_GENERIC
 #define DEFAULT_INTRA4x4            0
 #define STRLENGTH                   500
-
-
+#define DEFAULT_CONSTRAINED_INTRA   0
 
 #define MIN(a, b) ((a) < (b))? (a) : (b)
 #define MAX(a, b) ((a) > (b))? (a) : (b)
@@ -112,8 +111,8 @@
 
 /** 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);
+    diff = (((end).tv_sec - (start).tv_sec) * 1000000) + \
+            ((end).tv_usec - (start).tv_usec);
 
 #define ive_aligned_malloc(alignment, size) memalign(alignment, size)
 #define ive_aligned_free(buf) free(buf)
@@ -142,6 +141,11 @@
         kNumBuffers = 2,
     };
 
+    enum {
+      kUpdateBitrate            = 1 << 0,
+      kRequestKeyFrame          = 1 << 1,
+    };
+
     // OMX input buffer's timestamp and flags
     typedef struct {
         int64_t mTimeUs;
@@ -153,11 +157,7 @@
     struct timeval mTimeStart;   // Time at the start of decode()
     struct timeval mTimeEnd;     // Time at the end of decode()
 
-
-    // If a request for a change it bitrate has been received.
-    bool mBitrateUpdated;
-
-    bool mKeyFrameRequested;
+    int mUpdateFlag;
 
 #ifdef FILE_DUMP_ENABLE
     char mInFile[200];
@@ -180,6 +180,7 @@
     bool     mReconEnable;
     bool     mPSNREnable;
     bool     mEntropyMode;
+    bool     mConstrainedIntraFlag;
     IVE_SPEED_CONFIG     mEncSpeed;
 
     uint8_t *mConversionBuffers[MAX_CONVERSION_BUFFERS];
diff --git a/media/libstagefright/codecs/common/Config.mk b/media/libstagefright/codecs/common/Config.mk
deleted file mode 100644
index a843cef..0000000
--- a/media/libstagefright/codecs/common/Config.mk
+++ /dev/null
@@ -1,24 +0,0 @@
-#
-# This configure file is just for Linux projects against Android
-#
-
-VOPRJ :=
-VONJ :=
-
-# WARNING:
-# Using v7 breaks generic build
-ifeq ($(TARGET_ARCH),arm)
-VOTT := v5
-else
-VOTT := pc
-endif
-
-# Do we also need to check on ARCH_ARM_HAVE_ARMV7A? - probably not
-ifeq ($(TARGET_ARCH),arm)
-  ifeq ($(ARCH_ARM_HAVE_NEON),true)
-    VOTT := v7
-  endif
-endif
-
-VOTEST := 0
-
diff --git a/media/libstagefright/codecs/common/include/voAAC.h b/media/libstagefright/codecs/common/include/voAAC.h
index 9ecb142..0a02feb 100644
--- a/media/libstagefright/codecs/common/include/voAAC.h
+++ b/media/libstagefright/codecs/common/include/voAAC.h
@@ -50,7 +50,7 @@
 
 /* AAC Param ID */
 #define VO_PID_AAC_Mdoule				0x42211000
-#define VO_PID_AAC_ENCPARAM				VO_PID_AAC_Mdoule | 0x0040  /*!< get/set AAC encoder parameter, the parameter is a pointer to AACENC_PARAM */
+#define VO_PID_AAC_ENCPARAM				(VO_PID_AAC_Mdoule | 0x0040)  /*!< get/set AAC encoder parameter, the parameter is a pointer to AACENC_PARAM */
 
 /* AAC decoder error ID */
 #define VO_ERR_AAC_Mdoule				0x82210000
diff --git a/media/libstagefright/codecs/common/include/voAudio.h b/media/libstagefright/codecs/common/include/voAudio.h
index d8628ee..98d3f44 100644
--- a/media/libstagefright/codecs/common/include/voAudio.h
+++ b/media/libstagefright/codecs/common/include/voAudio.h
@@ -38,9 +38,9 @@
 #define VO_PID_AUDIO_CHANNELMODE	(VO_PID_AUDIO_BASE | 0X0005)		/*!< The channel mode of audio */
 
 #define	VO_ERR_AUDIO_BASE			0x82000000
-#define VO_ERR_AUDIO_UNSCHANNEL		VO_ERR_AUDIO_BASE | 0x0001
-#define VO_ERR_AUDIO_UNSSAMPLERATE	VO_ERR_AUDIO_BASE | 0x0002
-#define VO_ERR_AUDIO_UNSFEATURE		VO_ERR_AUDIO_BASE | 0x0003
+#define VO_ERR_AUDIO_UNSCHANNEL		(VO_ERR_AUDIO_BASE | 0x0001)
+#define VO_ERR_AUDIO_UNSSAMPLERATE	(VO_ERR_AUDIO_BASE | 0x0002)
+#define VO_ERR_AUDIO_UNSFEATURE		(VO_ERR_AUDIO_BASE | 0x0003)
 
 
 /**
diff --git a/media/libstagefright/codecs/common/include/voIndex.h b/media/libstagefright/codecs/common/include/voIndex.h
index 320a2f8..97b21f3 100644
--- a/media/libstagefright/codecs/common/include/voIndex.h
+++ b/media/libstagefright/codecs/common/include/voIndex.h
@@ -31,26 +31,26 @@
 
 /* Define the module ID */
 #define _MAKE_SOURCE_ID(id, name) \
-VO_INDEX_SRC_##name = _VO_INDEX_SOURCE | id,
+VO_INDEX_SRC_##name = _VO_INDEX_SOURCE | (id),
 
 #define _MAKE_CODEC_ID(id, name) \
-VO_INDEX_DEC_##name = _VO_INDEX_DEC | id, \
-VO_INDEX_ENC_##name = _VO_INDEX_ENC | id,
+VO_INDEX_DEC_##name = _VO_INDEX_DEC | (id), \
+VO_INDEX_ENC_##name = _VO_INDEX_ENC | (id),
 
 #define _MAKE_EFFECT_ID(id, name) \
-VO_INDEX_EFT_##name = _VO_INDEX_EFFECT | id,
+VO_INDEX_EFT_##name = _VO_INDEX_EFFECT | (id),
 
 #define _MAKE_SINK_ID(id, name) \
-VO_INDEX_SNK_##name = _VO_INDEX_SINK | id,
+VO_INDEX_SNK_##name = _VO_INDEX_SINK | (id),
 
 #define _MAKE_FILTER_ID(id, name) \
-VO_INDEX_FLT_##name = _VO_INDEX_FILTER | id,
+VO_INDEX_FLT_##name = _VO_INDEX_FILTER | (id),
 
 #define _MAKE_OMX_ID(id, name) \
-VO_INDEX_OMX_##name = _VO_INDEX_OMX | id,
+VO_INDEX_OMX_##name = _VO_INDEX_OMX | (id),
 
 #define _MAKE_MFW_ID(id, name) \
-VO_INDEX_MFW_##name = _VO_INDEX_MFW | id,
+VO_INDEX_MFW_##name = _VO_INDEX_MFW | (id),
 
 enum
 {
diff --git a/media/libstagefright/codecs/common/include/voMem.h b/media/libstagefright/codecs/common/include/voMem.h
index 8dfb634..2b5aef1 100644
--- a/media/libstagefright/codecs/common/include/voMem.h
+++ b/media/libstagefright/codecs/common/include/voMem.h
@@ -53,8 +53,8 @@
 { \
 	VO_MEM_INFO voMemInfo; \
 	voMemInfo.Size=nSize; \
-	pMemOP->Alloc(ID, &voMemInfo); \
-	pBuff=(VO_PBYTE)voMemInfo.VBuffer; \
+	(pMemOP)->Alloc(ID, &voMemInfo); \
+	(pBuff)=(VO_PBYTE)voMemInfo.VBuffer; \
 }
 
 
diff --git a/media/libstagefright/codecs/flac/enc/Android.mk b/media/libstagefright/codecs/flac/enc/Android.mk
index c4c4a68..7e6e015 100644
--- a/media/libstagefright/codecs/flac/enc/Android.mk
+++ b/media/libstagefright/codecs/flac/enc/Android.mk
@@ -11,7 +11,7 @@
 
 LOCAL_CFLAGS += -Werror
 LOCAL_CLANG := true
-LOCAL_SANITIZE := signed-integer-overflow
+LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
 
 LOCAL_SHARED_LIBRARIES := \
         libstagefright libstagefright_omx libstagefright_foundation libutils liblog
diff --git a/media/libstagefright/codecs/g711/dec/Android.mk b/media/libstagefright/codecs/g711/dec/Android.mk
index a0112e1..b36c99d 100644
--- a/media/libstagefright/codecs/g711/dec/Android.mk
+++ b/media/libstagefright/codecs/g711/dec/Android.mk
@@ -15,5 +15,7 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/g711/dec/SoftG711.cpp b/media/libstagefright/codecs/g711/dec/SoftG711.cpp
index 015515e..e342d7c 100644
--- a/media/libstagefright/codecs/g711/dec/SoftG711.cpp
+++ b/media/libstagefright/codecs/g711/dec/SoftG711.cpp
@@ -262,7 +262,8 @@
 // static
 void SoftG711::DecodeALaw(
         int16_t *out, const uint8_t *in, size_t inSize) {
-    while (inSize-- > 0) {
+    while (inSize > 0) {
+        inSize--;
         int32_t x = *in++;
 
         int32_t ix = x ^ 0x55;
@@ -288,7 +289,8 @@
 // static
 void SoftG711::DecodeMLaw(
         int16_t *out, const uint8_t *in, size_t inSize) {
-    while (inSize-- > 0) {
+    while (inSize > 0) {
+        inSize--;
         int32_t x = *in++;
 
         int32_t mantissa = ~x;
diff --git a/media/libstagefright/codecs/gsm/dec/Android.mk b/media/libstagefright/codecs/gsm/dec/Android.mk
index 30868d5..fe8c830 100644
--- a/media/libstagefright/codecs/gsm/dec/Android.mk
+++ b/media/libstagefright/codecs/gsm/dec/Android.mk
@@ -10,6 +10,8 @@
         external/libgsm/inc
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
 
 LOCAL_SHARED_LIBRARIES := \
         libstagefright libstagefright_omx libstagefright_foundation libutils liblog
diff --git a/media/libstagefright/codecs/hevcdec/Android.mk b/media/libstagefright/codecs/hevcdec/Android.mk
index c0c694e..78c4637 100644
--- a/media/libstagefright/codecs/hevcdec/Android.mk
+++ b/media/libstagefright/codecs/hevcdec/Android.mk
@@ -13,6 +13,8 @@
 LOCAL_C_INCLUDES += $(TOP)/external/libhevc/common
 LOCAL_C_INCLUDES += $(TOP)/frameworks/av/media/libstagefright/include
 LOCAL_C_INCLUDES += $(TOP)/frameworks/native/include/media/openmax
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 LOCAL_SHARED_LIBRARIES  := libstagefright
 LOCAL_SHARED_LIBRARIES  += libstagefright_omx
diff --git a/media/libstagefright/codecs/hevcdec/SoftHEVC.cpp b/media/libstagefright/codecs/hevcdec/SoftHEVC.cpp
index e601125..6a9f17c 100644
--- a/media/libstagefright/codecs/hevcdec/SoftHEVC.cpp
+++ b/media/libstagefright/codecs/hevcdec/SoftHEVC.cpp
@@ -451,16 +451,6 @@
     List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
     List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
 
-    /* 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();
-    }
-
     while (!outQueue.empty()) {
         BufferInfo *inInfo;
         OMX_BUFFERHEADERTYPE *inHeader;
@@ -554,6 +544,8 @@
                 mChangingResolution = false;
                 resetDecoder();
                 resetPlugin();
+                mStride = outputBufferWidth();
+                setParams(mStride);
                 continue;
             }
 
@@ -588,7 +580,7 @@
                 outInfo = NULL;
                 notifyFillBufferDone(outHeader);
                 outHeader = NULL;
-            } else {
+            } else if (mIsInFlush) {
                 /* If in flush mode and no output is returned by the codec,
                  * then come out of flush mode */
                 mIsInFlush = false;
@@ -609,6 +601,16 @@
             }
         }
 
+        /* 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();
+        }
+
         // TODO: Handle more than one picture data
         if (inHeader != NULL) {
             inInfo->mOwnedByUs = false;
diff --git a/media/libstagefright/codecs/hevcdec/SoftHEVC.h b/media/libstagefright/codecs/hevcdec/SoftHEVC.h
index 21bb99e..488e13d 100644
--- a/media/libstagefright/codecs/hevcdec/SoftHEVC.h
+++ b/media/libstagefright/codecs/hevcdec/SoftHEVC.h
@@ -46,8 +46,8 @@
 
 /** 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);
+    diff = (((end).tv_sec - (start).tv_sec) * 1000000) + \
+            ((end).tv_usec - (start).tv_usec);
 
 struct SoftHEVC: public SoftVideoDecoderOMXComponent {
     SoftHEVC(const char *name, const OMX_CALLBACKTYPE *callbacks,
diff --git a/media/libstagefright/codecs/m4v_h263/dec/Android.mk b/media/libstagefright/codecs/m4v_h263/dec/Android.mk
index 1d232c6..eb39b44 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/Android.mk
+++ b/media/libstagefright/codecs/m4v_h263/dec/Android.mk
@@ -47,6 +47,8 @@
 LOCAL_CFLAGS := -DOSCL_EXPORT_REF= -DOSCL_IMPORT_REF=
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 include $(BUILD_STATIC_LIBRARY)
 
@@ -75,5 +77,7 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/conceal.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/conceal.cpp
index e9ead01..03e4119 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/conceal.cpp
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/conceal.cpp
@@ -19,6 +19,7 @@
 #include "vlc_decode.h"
 #include "bitstream.h"
 #include "scaling.h"
+#include "log/log.h"
 
 /* ====================================================================== /
 Function : ConcealTexture_I()
@@ -137,6 +138,10 @@
 ****************************************************************************/
 void CopyVopMB(Vop *curr, uint8 *prevFrame, int mbnum, int width_Y, int height)
 {
+    if (curr == NULL || prevFrame == NULL) {
+        ALOGE("b/24630158");
+        return;
+    }
     int width_C = width_Y >> 1;
     int row = MB_SIZE;
     uint8              *y1, *y2, *u1, *u2, *v1, *v2;
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/idct.h b/media/libstagefright/codecs/m4v_h263/dec/src/idct.h
index 8edb654..484631b 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/idct.h
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/idct.h
@@ -80,9 +80,9 @@
 #define W7 565                  /* 2048*sqrt(2)*cos(7*pi/16) */
 #define W1mW7 2276
 #define W1pW7 3406
-#define W5mW3 -799
-#define mW3mW5 -4017
-#define mW2mW6 -3784
+#define W5mW3 (-799)
+#define mW3mW5 (-4017)
+#define mW2mW6 (-3784)
 #define W2mW6 1568
 
 /* left shift by 11 is to maintain the accuracy of the decimal point */
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/motion_comp.h b/media/libstagefright/codecs/m4v_h263/dec/src/motion_comp.h
index 0c12f20..68281ba 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/motion_comp.h
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/motion_comp.h
@@ -54,20 +54,20 @@
 {
 #endif
 
-#define CLIP_RESULT(x)      if(x & -256){x = 0xFF & (~(x>>31));}
+#define CLIP_RESULT(x)      if((x) & -256){(x) = 0xFF & (~((x)>>31));}
 #define ADD_AND_CLIP1(x)    x += (pred_word&0xFF); CLIP_RESULT(x);
 #define ADD_AND_CLIP2(x)    x += ((pred_word>>8)&0xFF); CLIP_RESULT(x);
 #define ADD_AND_CLIP3(x)    x += ((pred_word>>16)&0xFF); CLIP_RESULT(x);
 #define ADD_AND_CLIP4(x)    x += ((pred_word>>24)&0xFF); CLIP_RESULT(x);
 
-#define ADD_AND_CLIP(x,y)    {  x9 = ~(x>>8); \
+#define ADD_AND_CLIP(x,y)    {  x9 = ~((x)>>8); \
                             if(x9!=-1){ \
                                 x9 = ((uint32)x9)>>24; \
-                                y = x9|(y<<8); \
+                                (y) = x9|((y)<<8); \
                             } \
                             else \
                             {    \
-                                y =  x|(y<<8); \
+                                (y) =  (x)|((y)<<8); \
                             } \
                             }
 
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mp4def.h b/media/libstagefright/codecs/m4v_h263/dec/src/mp4def.h
index 3388d89..20f458d 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/mp4def.h
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/mp4def.h
@@ -47,7 +47,7 @@
 /* You don't want to use ((x>UB)?UB:(x<LB)?LB:x) for the clipping */
 /*    because it will use one extra comparison if the compiler is */
 /*    not well-optimized.    04/19/2000.                        */
-#define CLIP_THE_RANGE(x,LB,UB) if (x<LB) x = LB; else if (x>UB) x = UB
+#define CLIP_THE_RANGE(x,LB,UB) if ((x)<(LB)) (x) = (LB); else if ((x)>(UB)) (x) = (UB)
 
 #define MODE_INTRA      0x08 //01000
 #define MODE_INTRA_Q    0x09 //01001
@@ -72,7 +72,7 @@
 #define START_CODE_LENGTH       32
 
 /* 11/30/98 */
-#define NoMarkerFound -1
+#define NoMarkerFound (-1)
 #define FoundRM     1   /* Resync Marker */
 #define FoundVSC    2   /* VOP_START_CODE. */
 #define FoundGSC    3   /* GROUP_START_CODE */
@@ -153,7 +153,7 @@
 
 
 /* macro utility */
-#define  ZERO_OUT_64BYTES(x)    { *((uint32*)x) = *(((uint32*)(x))+1) =  \
+#define  ZERO_OUT_64BYTES(x)    { *((uint32*)(x)) = *(((uint32*)(x))+1) =  \
         *(((uint32*)(x))+2) = *(((uint32*)(x))+3) =  \
         *(((uint32*)(x))+4) = *(((uint32*)(x))+5) =  \
         *(((uint32*)(x))+6) = *(((uint32*)(x))+7) =  \
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/post_proc.h b/media/libstagefright/codecs/m4v_h263/dec/src/post_proc.h
index 091fdaf..a8ab37f 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/post_proc.h
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/post_proc.h
@@ -32,9 +32,9 @@
 ; DEFINES
 ; Include all pre-processor statements here.
 ----------------------------------------------------------------------------*/
-#define UPDATE_PV_MAXPV_MIN(p,max,min) if ((p) > max) max=(p); else if ((p) < min) min = (p);
+#define UPDATE_PV_MAXPV_MIN(p,max,min) if ((p) > (max)) (max)=(p); else if ((p) < (min)) (min) = (p);
 
-#define     INDEX(x,thr)    (((x)>=thr)?1:0)
+#define     INDEX(x,thr)    (((x)>=(thr))?1:0)
 #define     BLKSIZE     8
 #define     MBSIZE      16
 #define     DERING_THR  16
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.h b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.h
index a804606..e242820 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.h
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.h
@@ -79,10 +79,10 @@
 #include "mp4lib_int.h"
 
 #define VLC_ERROR_DETECTED(x) ((x) < 0)
-#define VLC_IO_ERROR    -1
-#define VLC_CODE_ERROR  -2
-#define VLC_MB_STUFFING -4
-#define VLC_NO_LAST_BIT -5
+#define VLC_IO_ERROR    (-1)
+#define VLC_CODE_ERROR  (-2)
+#define VLC_MB_STUFFING (-4)
+#define VLC_NO_LAST_BIT (-5)
 
 #define VLC_ESCAPE_CODE  7167
 
diff --git a/media/libstagefright/codecs/m4v_h263/enc/Android.mk b/media/libstagefright/codecs/m4v_h263/enc/Android.mk
index 762e6fe..ab079e8 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/Android.mk
+++ b/media/libstagefright/codecs/m4v_h263/enc/Android.mk
@@ -34,6 +34,8 @@
     $(TOP)/frameworks/native/include/media/openmax
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 include $(BUILD_STATIC_LIBRARY)
 
@@ -75,6 +77,8 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 include $(BUILD_SHARED_LIBRARY)
 
@@ -89,6 +93,8 @@
         $(LOCAL_PATH)/include
 
 LOCAL_CFLAGS := -DOSCL_EXPORT_REF= -DOSCL_IMPORT_REF= -DBX_RC
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 LOCAL_STATIC_LIBRARIES := \
         libstagefright_m4vh263enc
diff --git a/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp b/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp
index 8240f83..f2a4e65 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp
+++ b/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp
@@ -37,6 +37,10 @@
 
 #include <inttypes.h>
 
+#ifndef INT32_MAX
+#define INT32_MAX   2147483647
+#endif
+
 namespace android {
 
 template<class T>
@@ -137,6 +141,11 @@
     if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) {
         // Color conversion is needed.
         free(mInputFrameData);
+        mInputFrameData = NULL;
+        if (((uint64_t)mWidth * mHeight) > ((uint64_t)INT32_MAX / 3)) {
+            ALOGE("b/25812794, Buffer size is too big.");
+            return OMX_ErrorBadParameter;
+        }
         mInputFrameData =
             (uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1);
         CHECK(mInputFrameData != NULL);
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp b/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp
index 0ad39a6..50c8161 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp
+++ b/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp
@@ -527,6 +527,9 @@
 /*  Modified :                                                              */
 /*      8/15/01,  - do 4 pixel at a time    assuming 32 bit register        */
 /* ======================================================================== */
+#ifdef __clang__
+__attribute((no_sanitize("integer")))
+#endif
 Int Sad8x8(UChar *cur, UChar *prev, Int width)
 {
     UChar *end = cur + (width << 3);
@@ -590,7 +593,9 @@
 /*  Modified :                                                              */
 /*          8/15/01,  - SIMD 4 pixels at a time                         */
 /* ======================================================================== */
-
+#ifdef __clang__
+__attribute((no_sanitize("integer")))
+#endif
 Int getBlockSum(UChar *cur, Int width)
 {
     Int sad = 0, sum4 = 0, sum2 = 0;
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/fastidct.cpp b/media/libstagefright/codecs/m4v_h263/enc/src/fastidct.cpp
index 21d7427..688effc 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/src/fastidct.cpp
+++ b/media/libstagefright/codecs/m4v_h263/enc/src/fastidct.cpp
@@ -55,7 +55,7 @@
         }
 
 
-#define CLIP_RESULT(x)      if((UInt)x > 0xFF){x = 0xFF & (~(x>>31));}
+#define CLIP_RESULT(x)      if((UInt)(x) > 0xFF){(x) = 0xFF & (~((x)>>31));}
 #define ADD_AND_CLIP1(x)    x += (pred_word&0xFF); CLIP_RESULT(x);
 #define ADD_AND_CLIP2(x)    x += ((pred_word>>8)&0xFF); CLIP_RESULT(x);
 #define ADD_AND_CLIP3(x)    x += ((pred_word>>16)&0xFF); CLIP_RESULT(x);
diff --git a/media/libstagefright/codecs/mp3dec/Android.mk b/media/libstagefright/codecs/mp3dec/Android.mk
index e611f68..11581c1 100644
--- a/media/libstagefright/codecs/mp3dec/Android.mk
+++ b/media/libstagefright/codecs/mp3dec/Android.mk
@@ -28,19 +28,22 @@
  	src/pvmp3_stereo_proc.cpp \
  	src/pvmp3_reorder.cpp \
 
-ifeq ($(TARGET_ARCH),arm)
-LOCAL_SRC_FILES += \
+LOCAL_SRC_FILES_arm += \
 	src/asm/pvmp3_polyphase_filter_window_gcc.s \
  	src/asm/pvmp3_mdct_18_gcc.s \
  	src/asm/pvmp3_dct_9_gcc.s \
 	src/asm/pvmp3_dct_16_gcc.s
-else
-LOCAL_SRC_FILES += \
+LOCAL_SRC_FILES_other_archs := \
  	src/pvmp3_polyphase_filter_window.cpp \
  	src/pvmp3_mdct_18.cpp \
  	src/pvmp3_dct_9.cpp \
  	src/pvmp3_dct_16.cpp
-endif
+
+LOCAL_SRC_FILES_arm64  := $(LOCAL_SRC_FILES_other_archs)
+LOCAL_SRC_FILES_mips   := $(LOCAL_SRC_FILES_other_archs)
+LOCAL_SRC_FILES_mips64 := $(LOCAL_SRC_FILES_other_archs)
+LOCAL_SRC_FILES_x86    := $(LOCAL_SRC_FILES_other_archs)
+LOCAL_SRC_FILES_x86_64 := $(LOCAL_SRC_FILES_other_archs)
 
 LOCAL_C_INCLUDES := \
         frameworks/av/media/libstagefright/include \
@@ -51,6 +54,8 @@
         -D"OSCL_UNUSED_ARG(x)=(void)(x)"
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 LOCAL_MODULE := libstagefright_mp3dec
 
@@ -72,6 +77,8 @@
         $(LOCAL_PATH)/include
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 LOCAL_SHARED_LIBRARIES := \
         libstagefright libstagefright_omx libstagefright_foundation libutils liblog
@@ -96,6 +103,8 @@
         $(LOCAL_PATH)/test/include \
         $(call include-path-for, audio-utils)
 
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 LOCAL_STATIC_LIBRARIES := \
         libstagefright_mp3dec libsndfile
 
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h
index ba43820..337bff0 100644
--- a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h
+++ b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h
@@ -44,9 +44,9 @@
 #endif
 
 #include "pvmp3_audio_type_defs.h"
-#define Qfmt_31(a)   (Int32)((float)a*0x7FFFFFFF)
+#define Qfmt_31(a)   (Int32)((float)(a)*0x7FFFFFFF)
 
-#define Qfmt15(x)   (Int16)(x*((Int32)1<<15) + (x>=0?0.5F:-0.5F))
+#define Qfmt15(x)   (Int16)((x)*((Int32)1<<15) + ((x)>=0?0.5F:-0.5F))
 
 
 
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.cpp
index 32c76c6..af738ba 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.cpp
@@ -109,7 +109,7 @@
 ----------------------------------------------------------------------------*/
 #define NUM_BUTTERFLIES 8
 
-#define Q31_fmt(a)    (int32(double(0x7FFFFFFF)*a))
+#define Q31_fmt(a)    (int32(double(0x7FFFFFFF)*(a)))
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.cpp
index a71efc4..9b9ae4b 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.cpp
@@ -109,7 +109,7 @@
 ; Include all pre-processor statements here. Include conditional
 ; compile variables also.
 ----------------------------------------------------------------------------*/
-#define Qfmt(a)   (int32)(a*((int32)1<<27))
+#define Qfmt(a)   (int32)((a)*((int32)1<<27))
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp
index 4c5fb03..1f8018a 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp
@@ -79,7 +79,7 @@
 ; Include all pre-processor statements here. Include conditional
 ; compile variables also.
 ----------------------------------------------------------------------------*/
-#define Qfmt30(a)   (Int32)(a*((Int32)1<<30) + (a>=0?0.5F:-0.5F))
+#define Qfmt30(a)   (Int32)((a)*((Int32)1<<30) + ((a)>=0?0.5F:-0.5F))
 
 #define cos_pi_6     Qfmt30(  0.86602540378444f)
 #define cos_2_pi_6   Qfmt30(  0.5f)
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_9.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_9.cpp
index ce3ec64..d30ce4a 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_9.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_9.cpp
@@ -77,7 +77,7 @@
 ; Include all pre-processor statements here. Include conditional
 ; compile variables also.
 ----------------------------------------------------------------------------*/
-#define Qfmt31(a)   (int32)(a*(0x7FFFFFFF))
+#define Qfmt31(a)   (int32)((a)*(0x7FFFFFFF))
 
 #define cos_pi_9    Qfmt31( 0.93969262078591f)
 #define cos_2pi_9   Qfmt31( 0.76604444311898f)
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dec_defs.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_dec_defs.h
index 6cf8e3e..2be9ab9 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_dec_defs.h
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dec_defs.h
@@ -53,7 +53,7 @@
 ; MACROS
 ; Define module specific macros here
 ----------------------------------------------------------------------------*/
-#define module(x, POW2)   ((x)&(POW2-1))
+#define module(x, POW2)   ((x)&((POW2)-1))
 
 /*----------------------------------------------------------------------------
 ; DEFINES
@@ -75,7 +75,7 @@
 #define MPEG_1              0
 #define MPEG_2              1
 #define MPEG_2_5            2
-#define INVALID_VERSION     -1
+#define INVALID_VERSION   (-1)
 
 /* MPEG Header Definitions - Mode Values */
 
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp
index 69e1987..639df81 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp
@@ -108,8 +108,8 @@
 ; Include all pre-processor statements here. Include conditional
 ; compile variables also.
 ----------------------------------------------------------------------------*/
-#define Q30_fmt(a)(int32(double(0x40000000)*a))
-#define Q29_fmt(a)(int32(double(0x20000000)*a))
+#define Q30_fmt(a)(int32(double(0x40000000)*(a)))
+#define Q29_fmt(a)(int32(double(0x20000000)*(a)))
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.cpp
index f4a4efb..61aef30 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.cpp
@@ -98,7 +98,7 @@
 #define LEVEL_45__dB  0.005524271f
 #define LEVEL_60__dB  0.000976562f
 
-#define Qmf31( x)    (int32)(x*(float)0x7FFFFFFF)
+#define Qmf31( x)    (int32)((x)*(float)0x7FFFFFFF)
 
 
 /*----------------------------------------------------------------------------
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp
index f1a3ff8..d4a2060 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp
@@ -86,7 +86,7 @@
 ; Include all pre-processor statements here. Include conditional
 ; compile variables also.
 ----------------------------------------------------------------------------*/
-#define Qfmt_28(a)(int32(double(0x10000000)*a))
+#define Qfmt_28(a)(int32(double(0x10000000)*(a)))
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.h
index e497aee..2f2f65c 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.h
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.h
@@ -59,9 +59,9 @@
 ; DEFINES
 ; Include all pre-processor statements here.
 ----------------------------------------------------------------------------*/
-#define Qfmt(a)    (Int32)(a*((Int32)1<<28) )
-#define Qfmt1(a)   (Int32)(a*((Int32)0x7FFFFFFF))
-#define Qfmt2(a)   (Int32)(a*((Int32)1<<27))
+#define Qfmt(a)    (Int32)((a)*((Int32)1<<28) )
+#define Qfmt1(a)   (Int32)((a)*((Int32)0x7FFFFFFF))
+#define Qfmt2(a)   (Int32)((a)*((Int32)1<<27))
 
 /*----------------------------------------------------------------------------
 ; EXTERNAL VARIABLES REFERENCES
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp
index 6a72aad..8d80e8f 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp
@@ -81,7 +81,7 @@
 ; compile variables also.
 ----------------------------------------------------------------------------*/
 #define QFORMAT    29
-#define Qfmt29(a)   (int32)(a*((int32)1<<QFORMAT) + (a>=0?0.5F:-0.5F))
+#define Qfmt29(a)   (int32)((a)*((int32)1<<QFORMAT) + ((a)>=0?0.5F:-0.5F))
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.h
index 6ba53d7..af4f286 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.h
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.h
@@ -59,9 +59,9 @@
 ; DEFINES
 ; Include all pre-processor statements here.
 ----------------------------------------------------------------------------*/
-#define Qfmt(a)    (Int32)(a*((Int32)1<<28) )
-#define Qfmt1(a)   (Int32)(a*((Int32)0x7FFFFFFF))
-#define Qfmt2(a)   (Int32)(a*((Int32)1<<27))
+#define Qfmt(a)    (Int32)((a)*((Int32)1<<28) )
+#define Qfmt1(a)   (Int32)((a)*((Int32)0x7FFFFFFF))
+#define Qfmt2(a)   (Int32)((a)*((Int32)1<<27))
 
 /*----------------------------------------------------------------------------
 ; EXTERNAL VARIABLES REFERENCES
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp
index c79062c..a70e716 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp
@@ -123,7 +123,7 @@
 ; compile variables also.
 ----------------------------------------------------------------------------*/
 
-#define Q31_fmt(a)    (int32(double(0x7FFFFFFF)*a))
+#define Q31_fmt(a)    (int32(double(0x7FFFFFFF)*(a)))
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.cpp
index d69a46d..10edfc3 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.cpp
@@ -140,7 +140,7 @@
 ----------------------------------------------------------------------------*/
 #define N31 31
 
-#define Q31_fmt(a)    (int32(double(0x7FFFFFFF)*a))
+#define Q31_fmt(a)    (int32(double(0x7FFFFFFF)*(a)))
 
 /*----------------------------------------------------------------------------
 ; LOCAL FUNCTION DEFINITIONS
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.cpp
index 90e524a..91113e3 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.cpp
@@ -136,7 +136,7 @@
 
 };
 
-#define INV_Q31( x)   (int32)(0x7FFFFFFF/(float)x - 1.0f)
+#define INV_Q31( x)   (int32)(0x7FFFFFFF/(float)(x) - 1.0f)
 
 const int32 mp3_shortwindBandWidths[9][13] =
 {
@@ -161,7 +161,7 @@
 };
 
 
-#define Q30_fmt(a)    (int32((0x40000000)*a))
+#define Q30_fmt(a)    (int32((0x40000000)*(a)))
 
 const int32 pqmfSynthWin[(HAN_SIZE/2) + 8] =
 {
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.h
index b54c5bf..8f8509c 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.h
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.h
@@ -52,7 +52,7 @@
 /*----------------------------------------------------------------------------
 ; DEFINES AND SIMPLE TYPEDEF'S
 ----------------------------------------------------------------------------*/
-#define Qfmt_28(a) (int32(double(0x10000000)*a))
+#define Qfmt_28(a) (int32(double(0x10000000)*(a)))
 
 /*----------------------------------------------------------------------------
 ; SIMPLE TYPEDEF'S
diff --git a/media/libstagefright/codecs/mpeg2dec/Android.mk b/media/libstagefright/codecs/mpeg2dec/Android.mk
index 23b126d..f1c1719 100644
--- a/media/libstagefright/codecs/mpeg2dec/Android.mk
+++ b/media/libstagefright/codecs/mpeg2dec/Android.mk
@@ -21,6 +21,8 @@
 LOCAL_SHARED_LIBRARIES  += liblog
 
 LOCAL_LDFLAGS := -Wl,-Bsymbolic
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
 
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.cpp b/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.cpp
index 4307c4e..49bf42f 100644
--- a/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.cpp
+++ b/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.cpp
@@ -74,7 +74,8 @@
       mIvColorFormat(IV_YUV_420P),
       mNewWidth(mWidth),
       mNewHeight(mHeight),
-      mChangingResolution(false) {
+      mChangingResolution(false),
+      mStride(mWidth) {
     initPorts(kNumBuffers, INPUT_BUF_SIZE, kNumBuffers, CODEC_MIME_TYPE);
 
     // If input dump is enabled, then open create an empty file
@@ -202,6 +203,8 @@
     /* Set number of cores/threads to be used by the codec */
     setNumCores();
 
+    mStride = 0;
+
     return OK;
 }
 
@@ -384,7 +387,8 @@
     resetPlugin();
 
     /* Set the run time (dynamic) parameters */
-    setParams(displayStride);
+    mStride = outputBufferWidth();
+    setParams(mStride);
 
     /* Set number of cores/threads to be used by the codec */
     setNumCores();
@@ -543,14 +547,10 @@
     List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
     List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
 
-    /* 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();
+    if (outputBufferWidth() != mStride) {
+        /* Set the run-time (dynamic) parameters */
+        mStride = outputBufferWidth();
+        setParams(mStride);
     }
 
     while (!outQueue.empty()) {
@@ -677,6 +677,8 @@
                 mChangingResolution = false;
                 resetDecoder();
                 resetPlugin();
+                mStride = outputBufferWidth();
+                setParams(mStride);
                 continue;
             }
 
@@ -730,7 +732,7 @@
                     notifyFillBufferDone(outHeader);
                     outHeader = NULL;
                 }
-            } else {
+            } else if (mIsInFlush) {
                 /* If in flush mode and no output is returned by the codec,
                  * then come out of flush mode */
                 mIsInFlush = false;
@@ -751,6 +753,16 @@
             }
         }
 
+        /* 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();
+        }
+
         // TODO: Handle more than one picture data
         if (inHeader != NULL) {
             inInfo->mOwnedByUs = false;
diff --git a/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.h b/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.h
index a625e08..beddcd9 100644
--- a/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.h
+++ b/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.h
@@ -49,8 +49,8 @@
 
 /** 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);
+    diff = (((end).tv_sec - (start).tv_sec) * 1000000) + \
+            ((end).tv_usec - (start).tv_usec);
 
 struct SoftMPEG2 : public SoftVideoDecoderOMXComponent {
     SoftMPEG2(
@@ -106,6 +106,7 @@
     bool mChangingResolution;
     bool mFlushNeeded;
     bool mWaitForI;
+    size_t mStride;
 
     status_t initDecoder();
     status_t deInitDecoder();
diff --git a/media/libstagefright/codecs/on2/dec/Android.mk b/media/libstagefright/codecs/on2/dec/Android.mk
index 93ff64c..76f7600 100644
--- a/media/libstagefright/codecs/on2/dec/Android.mk
+++ b/media/libstagefright/codecs/on2/dec/Android.mk
@@ -21,5 +21,7 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/on2/enc/Android.mk b/media/libstagefright/codecs/on2/enc/Android.mk
index 253fa04..1de318a 100644
--- a/media/libstagefright/codecs/on2/enc/Android.mk
+++ b/media/libstagefright/codecs/on2/enc/Android.mk
@@ -11,6 +11,9 @@
         frameworks/av/media/libstagefright/include \
         frameworks/native/include/media/openmax \
 
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
+
 LOCAL_STATIC_LIBRARIES := \
         libvpx
 
diff --git a/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp b/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
index e654843..410f9d0 100644
--- a/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
+++ b/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
@@ -26,6 +26,10 @@
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/MediaDefs.h>
 
+#ifndef INT32_MAX
+#define INT32_MAX   2147483647
+#endif
+
 namespace android {
 
 template<class T>
@@ -315,6 +319,11 @@
 
     if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) {
         free(mConversionBuffer);
+        mConversionBuffer = NULL;
+        if (((uint64_t)mWidth * mHeight) > ((uint64_t)INT32_MAX / 3)) {
+            ALOGE("b/25812794, Buffer size is too big.");
+            return UNKNOWN_ERROR;
+        }
         mConversionBuffer = (uint8_t *)malloc(mWidth * mHeight * 3 / 2);
         if (mConversionBuffer == NULL) {
             ALOGE("Allocating conversion buffer failed.");
diff --git a/media/libstagefright/codecs/on2/h264dec/Android.mk b/media/libstagefright/codecs/on2/h264dec/Android.mk
index bf03ad9..7159674 100644
--- a/media/libstagefright/codecs/on2/h264dec/Android.mk
+++ b/media/libstagefright/codecs/on2/h264dec/Android.mk
@@ -84,19 +84,20 @@
 	./omxdl/arm_neon/vc/m4p10/src_gcc/omxVCM4P10_DequantTransformResidualFromPairAndAdd_s.S \
 	./omxdl/arm_neon/vc/m4p10/src_gcc/omxVCM4P10_TransformDequantChromaDCFromPair_s.S \
 
-ifeq ($(TARGET_ARCH),arm)
-  ifeq ($(ARCH_ARM_HAVE_NEON),true)
+
+ifeq ($(ARCH_ARM_HAVE_NEON),true)
     LOCAL_ARM_NEON   := true
-#    LOCAL_CFLAGS     := -std=c99 -D._NEON -D._OMXDL
-    LOCAL_CFLAGS     := -DH264DEC_NEON -DH264DEC_OMXDL
-    LOCAL_SRC_FILES  += $(MY_ASM) $(MY_OMXDL_C_SRC) $(MY_OMXDL_ASM_SRC)
-    LOCAL_C_INCLUDES += $(LOCAL_PATH)/./source/arm_neon_asm_gcc
-    LOCAL_C_INCLUDES += $(LOCAL_PATH)/./omxdl/arm_neon/api \
+    LOCAL_CFLAGS_arm     := -DH264DEC_NEON -DH264DEC_OMXDL
+    LOCAL_SRC_FILES_arm  := $(MY_ASM) $(MY_OMXDL_C_SRC) $(MY_OMXDL_ASM_SRC)
+    LOCAL_C_INCLUDES_arm := $(LOCAL_PATH)/./source/arm_neon_asm_gcc
+    LOCAL_C_INCLUDES_arm += $(LOCAL_PATH)/./omxdl/arm_neon/api \
                         $(LOCAL_PATH)/./omxdl/arm_neon/vc/api \
                         $(LOCAL_PATH)/./omxdl/arm_neon/vc/m4p10/api
-  endif
 endif
 
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow
+
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright libstagefright_omx libstagefright_foundation libutils liblog \
 
diff --git a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_cavlc.c b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_cavlc.c
index 91d78bd..422d7ba 100644
--- a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_cavlc.c
+++ b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_cavlc.c
@@ -60,7 +60,7 @@
 #define INFO(vlc) (((vlc) >> 4) & 0xF)  /* 4 MSB bits contain information */
 /* macro to obtain trailing ones from the coeff token information word,
  * bits [5,10] */
-#define TRAILING_ONES(coeffToken) ((coeffToken>>5) & 0x3F)
+#define TRAILING_ONES(coeffToken) (((coeffToken)>>5) & 0x3F)
 /* macro to obtain total coeff from the coeff token information word,
  * bits [11,15] */
 #define TOTAL_COEFF(coeffToken) (((coeffToken) >> 11) & 0x1F)
@@ -323,45 +323,45 @@
 /* macro to initialize stream buffer cache, fills the buffer (32 bits) */
 #define BUFFER_INIT(value, bits) \
 { \
-    bits = 32; \
-    value = h264bsdShowBits32(pStrmData); \
+    (bits) = 32; \
+    (value) = h264bsdShowBits32(pStrmData); \
 }
 
 /* macro to read numBits bits from the buffer, bits will be written to
  * outVal. Refills the buffer if not enough bits left */
 #define BUFFER_SHOW(value, bits, outVal, numBits) \
 { \
-    if (bits < (numBits)) \
+    if ((bits) < (numBits)) \
     { \
-        if(h264bsdFlushBits(pStrmData,32-bits) == END_OF_STREAM) \
+        if(h264bsdFlushBits(pStrmData,32-(bits)) == END_OF_STREAM) \
             return(HANTRO_NOK); \
-        value = h264bsdShowBits32(pStrmData); \
-        bits = 32; \
+        (value) = h264bsdShowBits32(pStrmData); \
+        (bits) = 32; \
     } \
-    (outVal) = value >> (32 - (numBits)); \
+    (outVal) = (value) >> (32 - (numBits)); \
 }
 
 /* macro to flush numBits bits from the buffer */
 #define BUFFER_FLUSH(value, bits, numBits) \
 { \
-    value <<= (numBits); \
-    bits -= (numBits); \
+    (value) <<= (numBits); \
+    (bits) -= (numBits); \
 }
 
 /* macro to read and flush  numBits bits from the buffer, bits will be written
  * to outVal. Refills the buffer if not enough bits left */
 #define BUFFER_GET(value, bits, outVal, numBits) \
 { \
-    if (bits < (numBits)) \
+    if ((bits) < (numBits)) \
     { \
-        if(h264bsdFlushBits(pStrmData,32-bits) == END_OF_STREAM) \
+        if(h264bsdFlushBits(pStrmData,32-(bits)) == END_OF_STREAM) \
             return(HANTRO_NOK); \
-        value = h264bsdShowBits32(pStrmData); \
-        bits = 32; \
+        (value) = h264bsdShowBits32(pStrmData); \
+        (bits) = 32; \
     } \
-    (outVal) = value >> (32 - (numBits)); \
-    value <<= (numBits); \
-    bits -= (numBits); \
+    (outVal) = (value) >> (32 - (numBits)); \
+    (value) <<= (numBits); \
+    (bits) -= (numBits); \
 }
 
 /*------------------------------------------------------------------------------
diff --git a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.h b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.h
index 216ad04..3082e27 100644
--- a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.h
+++ b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.h
@@ -151,7 +151,7 @@
 }
 
 #define ALIGN(ptr, bytePos) \
-        (ptr + ( ((bytePos - (uintptr_t)ptr) & (bytePos - 1)) / sizeof(*ptr) ))
+        ((ptr) + ( (((bytePos) - (uintptr_t)(ptr)) & ((bytePos) - 1)) / sizeof(*(ptr)) ))
 
 extern const u32 h264bsdQpC[52];
 
diff --git a/media/libstagefright/codecs/opus/dec/Android.mk b/media/libstagefright/codecs/opus/dec/Android.mk
index 2379c5f..f272763 100644
--- a/media/libstagefright/codecs/opus/dec/Android.mk
+++ b/media/libstagefright/codecs/opus/dec/Android.mk
@@ -13,7 +13,10 @@
         libopus libstagefright libstagefright_omx \
         libstagefright_foundation libutils liblog
 
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
+
 LOCAL_MODULE := libstagefright_soft_opusdec
 LOCAL_MODULE_TAGS := optional
 
-include $(BUILD_SHARED_LIBRARY)
\ No newline at end of file
+include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/raw/Android.mk b/media/libstagefright/codecs/raw/Android.mk
index 87080e7..e454c84 100644
--- a/media/libstagefright/codecs/raw/Android.mk
+++ b/media/libstagefright/codecs/raw/Android.mk
@@ -9,6 +9,8 @@
         frameworks/native/include/media/openmax
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
 
 LOCAL_SHARED_LIBRARIES := \
         libstagefright_omx libstagefright_foundation libutils liblog
diff --git a/media/libstagefright/codecs/vorbis/dec/Android.mk b/media/libstagefright/codecs/vorbis/dec/Android.mk
index 217a6d2..039be6f 100644
--- a/media/libstagefright/codecs/vorbis/dec/Android.mk
+++ b/media/libstagefright/codecs/vorbis/dec/Android.mk
@@ -17,5 +17,7 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_CFLAGS += -Werror
+LOCAL_CLANG := true
+LOCAL_SANITIZE := signed-integer-overflow unsigned-integer-overflow
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/data/media_codecs_google_tv.xml b/media/libstagefright/data/media_codecs_google_tv.xml
new file mode 100644
index 0000000..330c6fb
--- /dev/null
+++ b/media/libstagefright/data/media_codecs_google_tv.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!-- Copyright (C) 2015 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.
+-->
+
+<Included>
+    <Decoders>
+        <MediaCodec name="OMX.google.mpeg2.decoder" type="video/mpeg2">
+            <!-- profiles and levels:  ProfileMain : LevelHL -->
+            <Limit name="size" min="16x16" max="1920x1088" />
+            <Limit name="alignment" value="2x2" />
+            <Limit name="block-size" value="16x16" />
+            <Limit name="blocks-per-second" range="1-244800" />
+            <Limit name="bitrate" range="1-20000000" />
+            <Feature name="adaptive-playback" />
+        </MediaCodec>
+    </Decoders>
+</Included>
diff --git a/media/libstagefright/data/media_codecs_google_video.xml b/media/libstagefright/data/media_codecs_google_video.xml
old mode 100755
new mode 100644
index 740f96b..81a6d00
--- a/media/libstagefright/data/media_codecs_google_video.xml
+++ b/media/libstagefright/data/media_codecs_google_video.xml
@@ -16,15 +16,6 @@
 
 <Included>
     <Decoders>
-        <MediaCodec name="OMX.google.mpeg2.decoder" type="video/mpeg2">
-            <!-- profiles and levels:  ProfileMain : LevelHL -->
-            <Limit name="size" min="16x16" max="1920x1088" />
-            <Limit name="alignment" value="2x2" />
-            <Limit name="block-size" value="16x16" />
-            <Limit name="blocks-per-second" range="1-244800" />
-            <Limit name="bitrate" range="1-20000000" />
-            <Feature name="adaptive-playback" />
-        </MediaCodec>
         <MediaCodec name="OMX.google.mpeg4.decoder" type="video/mp4v-es">
             <!-- profiles and levels:  ProfileSimple : Level3 -->
             <Limit name="size" min="2x2" max="352x288" />
diff --git a/media/libstagefright/filters/Android.mk b/media/libstagefright/filters/Android.mk
index 179f054..bd75a88 100644
--- a/media/libstagefright/filters/Android.mk
+++ b/media/libstagefright/filters/Android.mk
@@ -23,6 +23,8 @@
 LOCAL_CFLAGS += -Wno-multichar -Werror -Wall
 LOCAL_CLANG := true
 
+LOCAL_SHARED_LIBRARIES := libmedia
+
 LOCAL_MODULE:= libstagefright_mediafilter
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/foundation/ABuffer.cpp b/media/libstagefright/foundation/ABuffer.cpp
index a5b81a8..804046a 100644
--- a/media/libstagefright/foundation/ABuffer.cpp
+++ b/media/libstagefright/foundation/ABuffer.cpp
@@ -67,10 +67,6 @@
         }
     }
 
-    if (mFarewell != NULL) {
-        mFarewell->post();
-    }
-
     setMediaBufferBase(NULL);
 }
 
@@ -82,10 +78,6 @@
     mRangeLength = size;
 }
 
-void ABuffer::setFarewellMessage(const sp<AMessage> msg) {
-    mFarewell = msg;
-}
-
 sp<AMessage> ABuffer::meta() {
     if (mMeta == NULL) {
         mMeta = new AMessage;
diff --git a/media/libstagefright/foundation/ADebug.cpp b/media/libstagefright/foundation/ADebug.cpp
index 2c5f544..1a5b2a3 100644
--- a/media/libstagefright/foundation/ADebug.cpp
+++ b/media/libstagefright/foundation/ADebug.cpp
@@ -49,7 +49,7 @@
             ++current;
         }
         // check for :
-        char *colon = strchr(current, ':');
+        const char *colon = strchr(current, ':');
 
         // get level
         char *end;
diff --git a/media/libstagefright/foundation/ALooper.cpp b/media/libstagefright/foundation/ALooper.cpp
index 90b5f68..9921636 100644
--- a/media/libstagefright/foundation/ALooper.cpp
+++ b/media/libstagefright/foundation/ALooper.cpp
@@ -151,6 +151,10 @@
     }
 
     mQueueChangedCondition.signal();
+    {
+        Mutex::Autolock autoLock(mRepliesLock);
+        mRepliesCondition.broadcast();
+    }
 
     if (!runningLocally && !thread->isCurrentThread()) {
         // If not running locally and this thread _is_ the looper thread,
@@ -234,6 +238,12 @@
     Mutex::Autolock autoLock(mRepliesLock);
     CHECK(replyToken != NULL);
     while (!replyToken->retrieveReply(response)) {
+        {
+            Mutex::Autolock autoLock(mLock);
+            if (mThread == NULL) {
+                return -ENOENT;
+            }
+        }
         mRepliesCondition.wait(mRepliesLock);
     }
     return OK;
diff --git a/media/libstagefright/foundation/AMessage.cpp b/media/libstagefright/foundation/AMessage.cpp
index e549ff6..91045aa 100644
--- a/media/libstagefright/foundation/AMessage.cpp
+++ b/media/libstagefright/foundation/AMessage.cpp
@@ -225,7 +225,8 @@
     item->u.FIELDNAME = value;                                          \
 }                                                                       \
                                                                         \
-bool AMessage::find##NAME(const char *name, TYPENAME *value) const {    \
+/* NOLINT added to avoid incorrect warning/fix from clang.tidy */       \
+bool AMessage::find##NAME(const char *name, TYPENAME *value) const {  /* NOLINT */ \
     const Item *item = findItem(name, kType##NAME);                     \
     if (item) {                                                         \
         *value = item->u.FIELDNAME;                                     \
@@ -601,13 +602,24 @@
     msg->setWhat(what);
 
     msg->mNumItems = static_cast<size_t>(parcel.readInt32());
+    if (msg->mNumItems > kMaxNumItems) {
+        ALOGE("Too large number of items clipped.");
+        msg->mNumItems = kMaxNumItems;
+    }
+
     for (size_t i = 0; i < msg->mNumItems; ++i) {
         Item *item = &msg->mItems[i];
 
         const char *name = parcel.readCString();
-        item->setName(name, strlen(name));
-        item->mType = static_cast<Type>(parcel.readInt32());
+        if (name == NULL) {
+            ALOGE("Failed reading name for an item. Parsing aborted.");
+            msg->mNumItems = i;
+            break;
+        }
 
+        item->mType = static_cast<Type>(parcel.readInt32());
+        // setName() happens below so that we don't leak memory when parsing
+        // is aborted in the middle.
         switch (item->mType) {
             case kTypeInt32:
             {
@@ -641,7 +653,16 @@
 
             case kTypeString:
             {
-                item->u.stringValue = new AString(parcel.readCString());
+                const char *stringValue = parcel.readCString();
+                if (stringValue == NULL) {
+                    ALOGE("Failed reading string value from a parcel. "
+                        "Parsing aborted.");
+                    msg->mNumItems = i;
+                    continue;
+                    // The loop will terminate subsequently.
+                } else {
+                    item->u.stringValue = new AString(stringValue);
+                }
                 break;
             }
 
@@ -660,6 +681,8 @@
                 TRESPASS();
             }
         }
+
+        item->setName(name, strlen(name));
     }
 
     return msg;
diff --git a/media/libstagefright/foundation/ANetworkSession.cpp b/media/libstagefright/foundation/ANetworkSession.cpp
index 4bcb1f6..b404a47 100644
--- a/media/libstagefright/foundation/ANetworkSession.cpp
+++ b/media/libstagefright/foundation/ANetworkSession.cpp
@@ -53,7 +53,7 @@
 static const int32_t kMaxUDPRetries = 200;
 
 struct ANetworkSession::NetworkThread : public Thread {
-    NetworkThread(ANetworkSession *session);
+    explicit NetworkThread(ANetworkSession *session);
 
 protected:
     virtual ~NetworkThread();
diff --git a/media/libstagefright/foundation/Android.mk b/media/libstagefright/foundation/Android.mk
index 6c70e98..f9e5fd6 100644
--- a/media/libstagefright/foundation/Android.mk
+++ b/media/libstagefright/foundation/Android.mk
@@ -29,6 +29,8 @@
         liblog            \
         libpowermanager
 
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libbinder
+
 LOCAL_CFLAGS += -Wno-multichar -Werror -Wall
 LOCAL_CLANG := true
 LOCAL_SANITIZE := unsigned-integer-overflow signed-integer-overflow
diff --git a/media/libstagefright/foundation/base64.cpp b/media/libstagefright/foundation/base64.cpp
index dcf5bef..7da7db9 100644
--- a/media/libstagefright/foundation/base64.cpp
+++ b/media/libstagefright/foundation/base64.cpp
@@ -22,11 +22,11 @@
 namespace android {
 
 sp<ABuffer> decodeBase64(const AString &s) {
-    if ((s.size() % 4) != 0) {
+    size_t n = s.size();
+    if ((n % 4) != 0) {
         return NULL;
     }
 
-    size_t n = s.size();
     size_t padding = 0;
     if (n >= 1 && s.c_str()[n - 1] == '=') {
         padding = 1;
@@ -40,11 +40,16 @@
         }
     }
 
-    size_t outLen = 3 * s.size() / 4 - padding;
+    // We divide first to avoid overflow. It's OK to do this because we
+    // already made sure that n % 4 == 0.
+    size_t outLen = (n / 4) * 3 - padding;
 
     sp<ABuffer> buffer = new ABuffer(outLen);
 
     uint8_t *out = buffer->data();
+    if (out == NULL || buffer->size() < outLen) {
+        return NULL;
+    }
     size_t j = 0;
     uint32_t accum = 0;
     for (size_t i = 0; i < n; ++i) {
diff --git a/media/libstagefright/httplive/Android.mk b/media/libstagefright/httplive/Android.mk
index f904212..2c985fc 100644
--- a/media/libstagefright/httplive/Android.mk
+++ b/media/libstagefright/httplive/Android.mk
@@ -18,6 +18,7 @@
 LOCAL_SANITIZE := unsigned-integer-overflow signed-integer-overflow
 
 LOCAL_SHARED_LIBRARIES := \
+        liblog \
         libbinder \
         libcrypto \
         libcutils \
diff --git a/media/libstagefright/httplive/LiveSession.cpp b/media/libstagefright/httplive/LiveSession.cpp
index 1557401..3db6164 100644
--- a/media/libstagefright/httplive/LiveSession.cpp
+++ b/media/libstagefright/httplive/LiveSession.cpp
@@ -1175,7 +1175,7 @@
 #endif
 
 bool LiveSession::UriIsSameAsIndex(const AString &uri, int32_t i, bool newUri) {
-    ALOGI("[timed_id3] i %d UriIsSameAsIndex newUri %s, %s", i,
+    ALOGV("[timed_id3] i %d UriIsSameAsIndex newUri %s, %s", i,
             newUri ? "true" : "false",
             newUri ? mStreams[i].mNewUri.c_str() : mStreams[i].mUri.c_str());
     return i >= 0
diff --git a/media/libstagefright/httplive/M3UParser.cpp b/media/libstagefright/httplive/M3UParser.cpp
index ff2bb27..09c2f9f 100644
--- a/media/libstagefright/httplive/M3UParser.cpp
+++ b/media/libstagefright/httplive/M3UParser.cpp
@@ -46,7 +46,7 @@
         FLAG_HAS_URI            = 16,
     };
 
-    MediaGroup(Type type);
+    explicit MediaGroup(Type type);
 
     Type type() const;
 
@@ -498,8 +498,8 @@
     if (url[0] == '/') {
         // URL is an absolute path.
 
-        char *protocolEnd = strstr(baseURL, "//") + 2;
-        char *pathStart = strchr(protocolEnd, '/');
+        const char *protocolEnd = strstr(baseURL, "//") + 2;
+        const char *pathStart = strchr(protocolEnd, '/');
 
         if (pathStart != NULL) {
             out->setTo(baseURL, pathStart - baseURL);
diff --git a/media/libstagefright/id3/Android.mk b/media/libstagefright/id3/Android.mk
index 2cfba44..bd2e459 100644
--- a/media/libstagefright/id3/Android.mk
+++ b/media/libstagefright/id3/Android.mk
@@ -8,6 +8,8 @@
 LOCAL_CLANG := true
 LOCAL_SANITIZE := unsigned-integer-overflow signed-integer-overflow
 
+LOCAL_SHARED_LIBRARIES := libmedia
+
 LOCAL_MODULE := libstagefright_id3
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/id3/ID3.cpp b/media/libstagefright/id3/ID3.cpp
index c164fd8..35691b9 100644
--- a/media/libstagefright/id3/ID3.cpp
+++ b/media/libstagefright/id3/ID3.cpp
@@ -194,6 +194,13 @@
 
     if (header.version_major == 4) {
         void *copy = malloc(size);
+        if (copy == NULL) {
+            free(mData);
+            mData = NULL;
+            ALOGE("b/24623447, no more memory");
+            return false;
+        }
+
         memcpy(copy, mData, size);
 
         bool success = removeUnsynchronizationV2_4(false /* iTunesHack */);
@@ -234,7 +241,14 @@
             return false;
         }
 
-        size_t extendedHeaderSize = U32_AT(&mData[0]) + 4;
+        size_t extendedHeaderSize = U32_AT(&mData[0]);
+        if (extendedHeaderSize > SIZE_MAX - 4) {
+            free(mData);
+            mData = NULL;
+            ALOGE("b/24623447, extendedHeaderSize is too large");
+            return false;
+        }
+        extendedHeaderSize += 4;
 
         if (extendedHeaderSize > mSize) {
             free(mData);
@@ -252,7 +266,10 @@
             if (extendedHeaderSize >= 10) {
                 size_t paddingSize = U32_AT(&mData[6]);
 
-                if (mFirstFrameOffset + paddingSize > mSize) {
+                if (paddingSize > SIZE_MAX - mFirstFrameOffset) {
+                    ALOGE("b/24623447, paddingSize is too large");
+                }
+                if (paddingSize > mSize - mFirstFrameOffset) {
                     free(mData);
                     mData = NULL;
 
diff --git a/media/libstagefright/include/AwesomePlayer.h b/media/libstagefright/include/AwesomePlayer.h
deleted file mode 100644
index 758b2c9..0000000
--- a/media/libstagefright/include/AwesomePlayer.h
+++ /dev/null
@@ -1,376 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef AWESOME_PLAYER_H_
-
-#define AWESOME_PLAYER_H_
-
-#include "HTTPBase.h"
-#include "TimedEventQueue.h"
-
-#include <media/AudioResamplerPublic.h>
-#include <media/MediaPlayerInterface.h>
-#include <media/stagefright/DataSource.h>
-#include <media/stagefright/OMXClient.h>
-#include <media/stagefright/TimeSource.h>
-#include <media/stagefright/MetaData.h>
-#include <utils/threads.h>
-#include <drm/DrmManagerClient.h>
-
-namespace android {
-
-class AudioPlayer;
-struct ClockEstimator;
-class IDataSource;
-class MediaBuffer;
-struct MediaExtractor;
-struct MediaSource;
-struct NuCachedSource2;
-class IGraphicBufferProducer;
-
-class DrmManagerClinet;
-class DecryptHandle;
-
-class TimedTextDriver;
-class WVMExtractor;
-
-struct AwesomeRenderer : public RefBase {
-    AwesomeRenderer() {}
-
-    virtual void render(MediaBuffer *buffer) = 0;
-
-private:
-    AwesomeRenderer(const AwesomeRenderer &);
-    AwesomeRenderer &operator=(const AwesomeRenderer &);
-};
-
-struct AwesomePlayer {
-    AwesomePlayer();
-    ~AwesomePlayer();
-
-    void setListener(const wp<MediaPlayerBase> &listener);
-    void setUID(uid_t uid);
-
-    status_t setDataSource(
-            const sp<IMediaHTTPService> &httpService,
-            const char *uri,
-            const KeyedVector<String8, String8> *headers = NULL);
-
-    status_t setDataSource(int fd, int64_t offset, int64_t length);
-
-    status_t setDataSource(const sp<IStreamSource> &source);
-
-    void reset();
-
-    status_t prepare();
-    status_t prepare_l();
-    status_t prepareAsync();
-    status_t prepareAsync_l();
-
-    status_t play();
-    status_t pause();
-
-    bool isPlaying() const;
-
-    status_t setSurfaceTexture(const sp<IGraphicBufferProducer> &bufferProducer);
-    void setAudioSink(const sp<MediaPlayerBase::AudioSink> &audioSink);
-    status_t setLooping(bool shouldLoop);
-
-    status_t getDuration(int64_t *durationUs);
-    status_t getPosition(int64_t *positionUs);
-
-    status_t setParameter(int key, const Parcel &request);
-    status_t getParameter(int key, Parcel *reply);
-    status_t setPlaybackSettings(const AudioPlaybackRate &rate);
-    status_t getPlaybackSettings(AudioPlaybackRate *rate /* nonnull */);
-    status_t invoke(const Parcel &request, Parcel *reply);
-    status_t setCacheStatCollectFreq(const Parcel &request);
-
-    status_t seekTo(int64_t timeUs);
-
-    // This is a mask of MediaExtractor::Flags.
-    uint32_t flags() const;
-
-    void postAudioEOS(int64_t delayUs = 0ll);
-    void postAudioSeekComplete();
-    void postAudioTearDown();
-    status_t dump(int fd, const Vector<String16> &args) const;
-
-private:
-    friend struct AwesomeEvent;
-    friend struct PreviewPlayer;
-
-    enum {
-        PLAYING             = 0x01,
-        LOOPING             = 0x02,
-        FIRST_FRAME         = 0x04,
-        PREPARING           = 0x08,
-        PREPARED            = 0x10,
-        AT_EOS              = 0x20,
-        PREPARE_CANCELLED   = 0x40,
-        CACHE_UNDERRUN      = 0x80,
-        AUDIO_AT_EOS        = 0x0100,
-        VIDEO_AT_EOS        = 0x0200,
-        AUTO_LOOPING        = 0x0400,
-
-        // We are basically done preparing but are currently buffering
-        // sufficient data to begin playback and finish the preparation phase
-        // for good.
-        PREPARING_CONNECTED = 0x0800,
-
-        // We're triggering a single video event to display the first frame
-        // after the seekpoint.
-        SEEK_PREVIEW        = 0x1000,
-
-        AUDIO_RUNNING       = 0x2000,
-        AUDIOPLAYER_STARTED = 0x4000,
-
-        INCOGNITO           = 0x8000,
-
-        TEXT_RUNNING        = 0x10000,
-        TEXTPLAYER_INITIALIZED  = 0x20000,
-
-        SLOW_DECODER_HACK   = 0x40000,
-    };
-
-    mutable Mutex mLock;
-    Mutex mMiscStateLock;
-    mutable Mutex mStatsLock;
-    Mutex mAudioLock;
-
-    OMXClient mClient;
-    TimedEventQueue mQueue;
-    bool mQueueStarted;
-    wp<MediaPlayerBase> mListener;
-    bool mUIDValid;
-    uid_t mUID;
-
-    sp<ANativeWindow> mNativeWindow;
-    sp<MediaPlayerBase::AudioSink> mAudioSink;
-
-    SystemTimeSource mSystemTimeSource;
-    TimeSource *mTimeSource;
-
-    sp<IMediaHTTPService> mHTTPService;
-    String8 mUri;
-    KeyedVector<String8, String8> mUriHeaders;
-
-    sp<DataSource> mFileSource;
-
-    sp<MediaSource> mVideoTrack;
-    sp<MediaSource> mVideoSource;
-    sp<AwesomeRenderer> mVideoRenderer;
-    bool mVideoRenderingStarted;
-    bool mVideoRendererIsPreview;
-    int32_t mMediaRenderingStartGeneration;
-    int32_t mStartGeneration;
-
-    ssize_t mActiveAudioTrackIndex;
-    sp<MediaSource> mAudioTrack;
-    sp<MediaSource> mOmxSource;
-    sp<MediaSource> mAudioSource;
-    AudioPlayer *mAudioPlayer;
-    AudioPlaybackRate mPlaybackSettings;
-    int64_t mDurationUs;
-
-    int32_t mDisplayWidth;
-    int32_t mDisplayHeight;
-    int32_t mVideoScalingMode;
-
-    uint32_t mFlags;
-    uint32_t mExtractorFlags;
-    uint32_t mSinceLastDropped;
-
-    int64_t mTimeSourceDeltaUs;
-    int64_t mVideoTimeUs;
-
-    enum SeekType {
-        NO_SEEK,
-        SEEK,
-        SEEK_VIDEO_ONLY
-    };
-    SeekType mSeeking;
-
-    bool mSeekNotificationSent;
-    int64_t mSeekTimeUs;
-
-    int64_t mBitrate;  // total bitrate of the file (in bps) or -1 if unknown.
-
-    bool mWatchForAudioSeekComplete;
-    bool mWatchForAudioEOS;
-
-    sp<TimedEventQueue::Event> mVideoEvent;
-    bool mVideoEventPending;
-    sp<TimedEventQueue::Event> mStreamDoneEvent;
-    bool mStreamDoneEventPending;
-    sp<TimedEventQueue::Event> mBufferingEvent;
-    bool mBufferingEventPending;
-    sp<TimedEventQueue::Event> mCheckAudioStatusEvent;
-    bool mAudioStatusEventPending;
-    sp<TimedEventQueue::Event> mVideoLagEvent;
-    bool mVideoLagEventPending;
-    sp<TimedEventQueue::Event> mAudioTearDownEvent;
-    bool mAudioTearDownEventPending;
-    sp<TimedEventQueue::Event> mAsyncPrepareEvent;
-    Condition mPreparedCondition;
-    bool mIsAsyncPrepare;
-    status_t mPrepareResult;
-    status_t mStreamDoneStatus;
-
-    void postVideoEvent_l(int64_t delayUs = -1);
-    void postBufferingEvent_l();
-    void postStreamDoneEvent_l(status_t status);
-    void postCheckAudioStatusEvent(int64_t delayUs);
-    void postVideoLagEvent_l();
-    void postAudioTearDownEvent(int64_t delayUs);
-
-    status_t play_l();
-
-    MediaBuffer *mVideoBuffer;
-
-    sp<ClockEstimator> mClockEstimator;
-    sp<HTTPBase> mConnectingDataSource;
-    sp<NuCachedSource2> mCachedSource;
-
-    DrmManagerClient *mDrmManagerClient;
-    sp<DecryptHandle> mDecryptHandle;
-
-    int64_t mLastVideoTimeUs;
-    TimedTextDriver *mTextDriver;
-
-    sp<WVMExtractor> mWVMExtractor;
-    sp<MediaExtractor> mExtractor;
-
-    status_t setDataSource_l(
-            const sp<IMediaHTTPService> &httpService,
-            const char *uri,
-            const KeyedVector<String8, String8> *headers = NULL);
-
-    status_t setDataSource_l(const sp<DataSource> &dataSource);
-    status_t setDataSource_l(const sp<MediaExtractor> &extractor);
-    void reset_l();
-    status_t seekTo_l(int64_t timeUs);
-    status_t pause_l(bool at_eos = false);
-    void initRenderer_l();
-    void notifyVideoSize_l();
-    void seekAudioIfNecessary_l();
-
-    void cancelPlayerEvents(bool keepNotifications = false);
-
-    void setAudioSource(sp<MediaSource> source);
-    status_t initAudioDecoder();
-
-
-    void setVideoSource(sp<MediaSource> source);
-    status_t initVideoDecoder(uint32_t flags = 0);
-
-    void addTextSource_l(size_t trackIndex, const sp<MediaSource>& source);
-
-    void onStreamDone();
-
-    void notifyListener_l(int msg, int ext1 = 0, int ext2 = 0);
-
-    void onVideoEvent();
-    void onBufferingUpdate();
-    void onCheckAudioStatus();
-    void onPrepareAsyncEvent();
-    void abortPrepare(status_t err);
-    void finishAsyncPrepare_l();
-    void onVideoLagUpdate();
-    void onAudioTearDownEvent();
-
-    void beginPrepareAsync_l();
-
-    bool getCachedDuration_l(int64_t *durationUs, bool *eos);
-
-    status_t finishSetDataSource_l();
-
-    static bool ContinuePreparation(void *cookie);
-
-    bool getBitrate(int64_t *bitrate);
-
-    int64_t estimateRealTimeUs(TimeSource *ts, int64_t systemTimeUs);
-    void finishSeekIfNecessary(int64_t videoTimeUs);
-    void ensureCacheIsFetching_l();
-
-    void notifyIfMediaStarted_l();
-    void createAudioPlayer_l();
-    status_t startAudioPlayer_l(bool sendErrorNotification = true);
-
-    void shutdownVideoDecoder_l();
-    status_t setNativeWindow_l(const sp<ANativeWindow> &native);
-
-    bool isStreamingHTTP() const;
-    void sendCacheStats();
-    void checkDrmStatus(const sp<DataSource>& dataSource);
-
-    enum FlagMode {
-        SET,
-        CLEAR,
-        ASSIGN
-    };
-    void modifyFlags(unsigned value, FlagMode mode);
-
-    struct TrackStat {
-        String8 mMIME;
-        String8 mDecoderName;
-    };
-
-    // protected by mStatsLock
-    struct Stats {
-        int mFd;
-        String8 mURI;
-        int64_t mBitrate;
-
-        // FIXME:
-        // These two indices are just 0 or 1 for now
-        // They are not representing the actual track
-        // indices in the stream.
-        ssize_t mAudioTrackIndex;
-        ssize_t mVideoTrackIndex;
-
-        int64_t mNumVideoFramesDecoded;
-        int64_t mNumVideoFramesDropped;
-        int32_t mVideoWidth;
-        int32_t mVideoHeight;
-        uint32_t mFlags;
-        Vector<TrackStat> mTracks;
-    } mStats;
-
-    bool    mOffloadAudio;
-    bool    mAudioTearDown;
-    bool    mAudioTearDownWasPlaying;
-    int64_t mAudioTearDownPosition;
-
-    status_t setVideoScalingMode(int32_t mode);
-    status_t setVideoScalingMode_l(int32_t mode);
-    status_t getTrackInfo(Parcel* reply) const;
-
-    status_t selectAudioTrack_l(const sp<MediaSource>& source, size_t trackIndex);
-
-    // when select is true, the given track is selected.
-    // otherwise, the given track is unselected.
-    status_t selectTrack(size_t trackIndex, bool select);
-
-    size_t countTracks() const;
-
-    AwesomePlayer(const AwesomePlayer &);
-    AwesomePlayer &operator=(const AwesomePlayer &);
-};
-
-}  // namespace android
-
-#endif  // AWESOME_PLAYER_H_
diff --git a/media/libstagefright/include/NuCachedSource2.h b/media/libstagefright/include/NuCachedSource2.h
index 4252706..a29bdf9 100644
--- a/media/libstagefright/include/NuCachedSource2.h
+++ b/media/libstagefright/include/NuCachedSource2.h
@@ -28,7 +28,7 @@
 struct PageCache;
 
 struct NuCachedSource2 : public DataSource {
-    NuCachedSource2(
+    static sp<NuCachedSource2> Create(
             const sp<DataSource> &source,
             const char *cacheConfig = NULL,
             bool disconnectAtHighwatermark = false);
@@ -72,6 +72,11 @@
 private:
     friend struct AHandlerReflector<NuCachedSource2>;
 
+    NuCachedSource2(
+            const sp<DataSource> &source,
+            const char *cacheConfig,
+            bool disconnectAtHighwatermark);
+
     enum {
         kPageSize                       = 65536,
         kDefaultHighWaterThreshold      = 20 * 1024 * 1024,
diff --git a/media/libstagefright/include/OMX.h b/media/libstagefright/include/OMX.h
index d468dfc..e7c4f6d 100644
--- a/media/libstagefright/include/OMX.h
+++ b/media/libstagefright/include/OMX.h
@@ -140,6 +140,8 @@
 
     virtual void binderDied(const wp<IBinder> &the_late_who);
 
+    virtual bool isSecure(IOMX::node_id node);
+
     OMX_ERRORTYPE OnEvent(
             node_id node,
             OMX_IN OMX_EVENTTYPE eEvent,
diff --git a/media/libstagefright/include/OMXNodeInstance.h b/media/libstagefright/include/OMXNodeInstance.h
index f68e0a9..e5fb45b 100644
--- a/media/libstagefright/include/OMXNodeInstance.h
+++ b/media/libstagefright/include/OMXNodeInstance.h
@@ -125,6 +125,10 @@
             const void *data,
             size_t size);
 
+    bool isSecure() const {
+        return mIsSecure;
+    }
+
     // handles messages and removes them from the list
     void onMessages(std::list<omx_message> &messages);
     void onMessage(const omx_message &msg);
@@ -142,6 +146,7 @@
     OMX_HANDLETYPE mHandle;
     sp<IOMXObserver> mObserver;
     bool mDying;
+    bool mIsSecure;
 
     // Lock only covers mGraphicBufferSource.  We can't always use mLock
     // because of rare instances where we'd end up locking it recursively.
diff --git a/media/libstagefright/include/StagefrightMetadataRetriever.h b/media/libstagefright/include/StagefrightMetadataRetriever.h
index fd739d0..61bbf6c 100644
--- a/media/libstagefright/include/StagefrightMetadataRetriever.h
+++ b/media/libstagefright/include/StagefrightMetadataRetriever.h
@@ -20,7 +20,6 @@
 
 #include <media/MediaMetadataRetrieverInterface.h>
 
-#include <media/stagefright/OMXClient.h>
 #include <utils/KeyedVector.h>
 
 namespace android {
@@ -45,7 +44,6 @@
     virtual const char *extractMetadata(int keyCode);
 
 private:
-    OMXClient mClient;
     sp<DataSource> mSource;
     sp<MediaExtractor> mExtractor;
 
diff --git a/media/libstagefright/include/TimedEventQueue.h b/media/libstagefright/include/TimedEventQueue.h
deleted file mode 100644
index 890f7e8..0000000
--- a/media/libstagefright/include/TimedEventQueue.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef TIMED_EVENT_QUEUE_H_
-
-#define TIMED_EVENT_QUEUE_H_
-
-#include <pthread.h>
-
-#include <utils/List.h>
-#include <utils/RefBase.h>
-#include <utils/threads.h>
-#include <powermanager/IPowerManager.h>
-
-namespace android {
-
-struct TimedEventQueue {
-
-    typedef int32_t event_id;
-
-    struct Event : public RefBase {
-        Event()
-            : mEventID(0) {
-        }
-
-        virtual ~Event() {}
-
-        event_id eventID() {
-            return mEventID;
-        }
-
-    protected:
-        virtual void fire(TimedEventQueue *queue, int64_t now_us) = 0;
-
-    private:
-        friend struct TimedEventQueue;
-
-        event_id mEventID;
-
-        void setEventID(event_id id) {
-            mEventID = id;
-        }
-
-        Event(const Event &);
-        Event &operator=(const Event &);
-    };
-
-    class PMDeathRecipient : public IBinder::DeathRecipient {
-    public:
-                    PMDeathRecipient(TimedEventQueue *queue) : mQueue(queue) {}
-        virtual     ~PMDeathRecipient() {}
-
-        // IBinder::DeathRecipient
-        virtual     void        binderDied(const wp<IBinder>& who);
-
-    private:
-                    PMDeathRecipient(const PMDeathRecipient&);
-                    PMDeathRecipient& operator = (const PMDeathRecipient&);
-
-                    TimedEventQueue *mQueue;
-    };
-
-    TimedEventQueue();
-    ~TimedEventQueue();
-
-    // Start executing the event loop.
-    void start();
-
-    // Stop executing the event loop, if flush is false, any pending
-    // events are discarded, otherwise the queue will stop (and this call
-    // return) once all pending events have been handled.
-    void stop(bool flush = false);
-
-    // Posts an event to the front of the queue (after all events that
-    // have previously been posted to the front but before timed events).
-    event_id postEvent(const sp<Event> &event);
-
-    event_id postEventToBack(const sp<Event> &event);
-
-    // It is an error to post an event with a negative delay.
-    event_id postEventWithDelay(const sp<Event> &event, int64_t delay_us);
-
-    // If the event is to be posted at a time that has already passed,
-    // it will fire as soon as possible.
-    event_id postTimedEvent(const sp<Event> &event, int64_t realtime_us);
-
-    // Returns true iff event is currently in the queue and has been
-    // successfully cancelled. In this case the event will have been
-    // removed from the queue and won't fire.
-    bool cancelEvent(event_id id);
-
-    // Cancel any pending event that satisfies the predicate.
-    // If stopAfterFirstMatch is true, only cancels the first event
-    // satisfying the predicate (if any).
-    void cancelEvents(
-            bool (*predicate)(void *cookie, const sp<Event> &event),
-            void *cookie,
-            bool stopAfterFirstMatch = false);
-
-    static int64_t getRealTimeUs();
-
-    void clearPowerManager();
-
-private:
-    struct QueueItem {
-        sp<Event> event;
-        int64_t realtime_us;
-        bool has_wakelock;
-    };
-
-    struct StopEvent : public TimedEventQueue::Event {
-        virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) {
-            queue->mStopped = true;
-        }
-    };
-
-    pthread_t mThread;
-    List<QueueItem> mQueue;
-    Mutex mLock;
-    Condition mQueueNotEmptyCondition;
-    Condition mQueueHeadChangedCondition;
-    event_id mNextEventID;
-
-    bool mRunning;
-    bool mStopped;
-
-    sp<IPowerManager>       mPowerManager;
-    sp<IBinder>             mWakeLockToken;
-    const sp<PMDeathRecipient> mDeathRecipient;
-    uint32_t                mWakeLockCount;
-
-    static void *ThreadWrapper(void *me);
-    void threadEntry();
-
-    sp<Event> removeEventFromQueue_l(event_id id, bool *wakeLocked);
-
-    void acquireWakeLock_l();
-    void releaseWakeLock_l(bool force = false);
-
-    TimedEventQueue(const TimedEventQueue &);
-    TimedEventQueue &operator=(const TimedEventQueue &);
-};
-
-}  // namespace android
-
-#endif  // TIMED_EVENT_QUEUE_H_
diff --git a/media/libstagefright/include/avc_utils.h b/media/libstagefright/include/avc_utils.h
index dafa07e..26afd73 100644
--- a/media/libstagefright/include/avc_utils.h
+++ b/media/libstagefright/include/avc_utils.h
@@ -37,8 +37,8 @@
 };
 
 struct NALPosition {
-    size_t nalOffset;
-    size_t nalSize;
+    uint32_t nalOffset;
+    uint32_t nalSize;
 };
 
 // Optionally returns sample aspect ratio as well.
diff --git a/media/libstagefright/matroska/Android.mk b/media/libstagefright/matroska/Android.mk
index 1e8c2b2..84be00e 100644
--- a/media/libstagefright/matroska/Android.mk
+++ b/media/libstagefright/matroska/Android.mk
@@ -11,6 +11,8 @@
 LOCAL_CFLAGS += -Wno-multichar -Werror -Wall
 LOCAL_CLANG := true
 
+LOCAL_SHARED_LIBRARIES := libmedia
+
 LOCAL_MODULE:= libstagefright_matroska
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/matroska/MatroskaExtractor.cpp b/media/libstagefright/matroska/MatroskaExtractor.cpp
index ecc2573..747710b 100644
--- a/media/libstagefright/matroska/MatroskaExtractor.cpp
+++ b/media/libstagefright/matroska/MatroskaExtractor.cpp
@@ -37,7 +37,7 @@
 namespace android {
 
 struct DataSourceReader : public mkvparser::IMkvReader {
-    DataSourceReader(const sp<DataSource> &source)
+    explicit DataSourceReader(const sp<DataSource> &source)
         : mSource(source) {
     }
 
@@ -534,6 +534,7 @@
             mPendingFrames.clear();
 
             mBlockIter.advance();
+            mbuf->release();
             return ERROR_IO;
         }
 
@@ -633,9 +634,11 @@
             if (pass == 1) {
                 memcpy(&dstPtr[dstOffset], "\x00\x00\x00\x01", 4);
 
-                memcpy(&dstPtr[dstOffset + 4],
-                       &srcPtr[srcOffset + mNALSizeLen],
-                       NALsize);
+                if (frame != buffer) {
+                    memcpy(&dstPtr[dstOffset + 4],
+                           &srcPtr[srcOffset + mNALSizeLen],
+                           NALsize);
+                }
             }
 
             dstOffset += 4;  // 0x00 00 00 01
@@ -657,7 +660,13 @@
         if (pass == 0) {
             dstSize = dstOffset;
 
-            buffer = new MediaBuffer(dstSize);
+            if (dstSize == srcSize && mNALSizeLen == 4) {
+                // In this special case we can re-use the input buffer by substituting
+                // each 4-byte nal size with a 4-byte start code
+                buffer = frame;
+            } else {
+                buffer = new MediaBuffer(dstSize);
+            }
 
             int64_t timeUs;
             CHECK(frame->meta_data()->findInt64(kKeyTime, &timeUs));
@@ -671,8 +680,10 @@
         }
     }
 
-    frame->release();
-    frame = NULL;
+    if (frame != buffer) {
+        frame->release();
+        frame = NULL;
+    }
 
     if (targetSampleTimeUs >= 0ll) {
         buffer->meta_data()->setInt64(
diff --git a/media/libstagefright/matroska/MatroskaExtractor.h b/media/libstagefright/matroska/MatroskaExtractor.h
index db36bf8..f15f533 100644
--- a/media/libstagefright/matroska/MatroskaExtractor.h
+++ b/media/libstagefright/matroska/MatroskaExtractor.h
@@ -18,7 +18,7 @@
 
 #define MATROSKA_EXTRACTOR_H_
 
-#include "mkvparser.hpp"
+#include "mkvparser/mkvparser.h"
 
 #include <media/stagefright/MediaExtractor.h>
 #include <utils/Vector.h>
diff --git a/media/libstagefright/mpeg2ts/Android.mk b/media/libstagefright/mpeg2ts/Android.mk
index 70afde9..66722a8 100644
--- a/media/libstagefright/mpeg2ts/Android.mk
+++ b/media/libstagefright/mpeg2ts/Android.mk
@@ -17,6 +17,8 @@
 LOCAL_CLANG := true
 LOCAL_SANITIZE := unsigned-integer-overflow signed-integer-overflow
 
+LOCAL_SHARED_LIBRARIES := libmedia
+
 LOCAL_MODULE:= libstagefright_mpeg2ts
 
 ifeq ($(TARGET_ARCH),arm)
diff --git a/media/libstagefright/omx/OMX.cpp b/media/libstagefright/omx/OMX.cpp
index cb7ab5e..72005b2 100644
--- a/media/libstagefright/omx/OMX.cpp
+++ b/media/libstagefright/omx/OMX.cpp
@@ -44,7 +44,7 @@
 // Note that deriving CallbackDispatcher from Thread does not work.
 
 struct OMX::CallbackDispatcherThread : public Thread {
-    CallbackDispatcherThread(CallbackDispatcher *dispatcher)
+    explicit CallbackDispatcherThread(CallbackDispatcher *dispatcher)
         : mDispatcher(dispatcher) {
     }
 
@@ -60,7 +60,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 struct OMX::CallbackDispatcher : public RefBase {
-    CallbackDispatcher(OMXNodeInstance *owner);
+    explicit CallbackDispatcher(OMXNodeInstance *owner);
 
     // Posts |msg| to the listener's queue. If |realTime| is true, the listener thread is notified
     // that a new message is available on the queue. Otherwise, the message stays on the queue, but
@@ -194,6 +194,11 @@
     instance->onObserverDied(mMaster);
 }
 
+bool OMX::isSecure(node_id node) {
+    OMXNodeInstance *instance = findInstance(node);
+    return (instance == NULL ? false : instance->isSecure());
+}
+
 bool OMX::livesLocally(node_id /* node */, pid_t pid) {
     return pid == getpid();
 }
diff --git a/media/libstagefright/omx/OMXNodeInstance.cpp b/media/libstagefright/omx/OMXNodeInstance.cpp
index fad38b7..da04737 100644
--- a/media/libstagefright/omx/OMXNodeInstance.cpp
+++ b/media/libstagefright/omx/OMXNodeInstance.cpp
@@ -101,17 +101,17 @@
 namespace android {
 
 struct BufferMeta {
-    BufferMeta(const sp<IMemory> &mem, bool is_backup = false)
+    explicit BufferMeta(const sp<IMemory> &mem, bool is_backup = false)
         : mMem(mem),
           mIsBackup(is_backup) {
     }
 
-    BufferMeta(size_t size)
+    explicit BufferMeta(size_t size)
         : mSize(size),
           mIsBackup(false) {
     }
 
-    BufferMeta(const sp<GraphicBuffer> &graphicBuffer)
+    explicit BufferMeta(const sp<GraphicBuffer> &graphicBuffer)
         : mGraphicBuffer(graphicBuffer),
           mIsBackup(false) {
     }
@@ -203,6 +203,7 @@
     mDebugLevelBumpPendingBuffers[1] = 0;
     mMetadataType[0] = kMetadataBufferTypeInvalid;
     mMetadataType[1] = kMetadataBufferTypeInvalid;
+    mIsSecure = AString(name).endsWith(".secure");
 }
 
 OMXNodeInstance::~OMXNodeInstance() {
diff --git a/media/libstagefright/omx/tests/OMXHarness.cpp b/media/libstagefright/omx/tests/OMXHarness.cpp
index 644b6ed..9a4e867 100644
--- a/media/libstagefright/omx/tests/OMXHarness.cpp
+++ b/media/libstagefright/omx/tests/OMXHarness.cpp
@@ -37,7 +37,7 @@
 #include <media/stagefright/MediaExtractor.h>
 #include <media/stagefright/MediaSource.h>
 #include <media/stagefright/MetaData.h>
-#include <media/stagefright/OMXCodec.h>
+#include <media/stagefright/SimpleDecodingSource.h>
 
 #define DEFAULT_TIMEOUT         500000
 
@@ -576,9 +576,8 @@
 
     CHECK_EQ(seekSource->start(), (status_t)OK);
 
-    sp<MediaSource> codec = OMXCodec::Create(
-            mOMX, source->getFormat(), false /* createEncoder */,
-            source, componentName);
+    sp<MediaSource> codec = SimpleDecodingSource::Create(
+            source, 0 /* flags */, NULL /* nativeWindow */, componentName);
 
     CHECK(codec != NULL);
 
diff --git a/media/libstagefright/rtsp/AMPEG4AudioAssembler.cpp b/media/libstagefright/rtsp/AMPEG4AudioAssembler.cpp
index a1a6576..82a0631 100644
--- a/media/libstagefright/rtsp/AMPEG4AudioAssembler.cpp
+++ b/media/libstagefright/rtsp/AMPEG4AudioAssembler.cpp
@@ -379,7 +379,10 @@
                 unsigned muxSlotLengthBytes = 0;
                 unsigned tmp;
                 do {
-                    CHECK_LT(offset, buffer->size());
+                    if (offset >= buffer->size()) {
+                        ALOGW("Malformed buffer received");
+                        return out;
+                    }
                     tmp = ptr[offset++];
                     muxSlotLengthBytes += tmp;
                 } while (tmp == 0xff);
diff --git a/media/libstagefright/rtsp/Android.mk b/media/libstagefright/rtsp/Android.mk
index a6f38bb..f81405a 100644
--- a/media/libstagefright/rtsp/Android.mk
+++ b/media/libstagefright/rtsp/Android.mk
@@ -19,7 +19,7 @@
         ASessionDescription.cpp     \
         SDPLoader.cpp               \
 
-LOCAL_SHARED_LIBRARIES += libcrypto
+LOCAL_SHARED_LIBRARIES += libcrypto libmedia
 
 LOCAL_C_INCLUDES:= \
 	$(TOP)/frameworks/av/media/libstagefright \
@@ -43,17 +43,18 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:=         \
-        rtp_test.cpp
+LOCAL_SRC_FILES := \
+	rtp_test.cpp \
 
 LOCAL_SHARED_LIBRARIES := \
-	libstagefright liblog libutils libbinder libstagefright_foundation
+	libstagefright liblog libutils libbinder libstagefright_foundation libmedia
 
 LOCAL_STATIC_LIBRARIES := \
-        libstagefright_rtsp
+	libstagefright_rtsp
 
-LOCAL_C_INCLUDES:= \
+LOCAL_C_INCLUDES := \
 	frameworks/av/media/libstagefright \
+	frameworks/av/cmds/stagefright \
 	$(TOP)/frameworks/native/include/media/openmax
 
 LOCAL_CFLAGS += -Wno-multichar -Werror -Wall
diff --git a/media/libstagefright/rtsp/MyTransmitter.h b/media/libstagefright/rtsp/MyTransmitter.h
index 369f276..bf44aff 100644
--- a/media/libstagefright/rtsp/MyTransmitter.h
+++ b/media/libstagefright/rtsp/MyTransmitter.h
@@ -31,9 +31,10 @@
 
 #ifdef ANDROID
 #include "VideoSource.h"
-
-#include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/ALooper.h>
+#include <media/stagefright/foundation/AMessage.h>
+#include <media/stagefright/MediaCodecSource.h>
 #endif
 
 namespace android {
@@ -109,17 +110,19 @@
 
         sp<MediaSource> source = new VideoSource(width, height);
 
-        sp<MetaData> encMeta = new MetaData;
-        encMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
-        encMeta->setInt32(kKeyWidth, width);
-        encMeta->setInt32(kKeyHeight, height);
+        sp<AMessage> encMeta = new AMessage;
+        encMeta->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
+        encMeta->setInt32("width", width);
+        encMeta->setInt32("height", height);
+        encMeta->setInt32("frame-rate", 30);
+        encMeta->setInt32("bitrate", 256000);
+        encMeta->setInt32("i-frame-interval", 10);
 
-        OMXClient client;
-        client.connect();
+        sp<ALooper> encLooper = new ALooper;
+        encLooper->setName("rtsp_transmitter");
+        encLooper->start();
 
-        mEncoder = OMXCodec::Create(
-                client.interface(), encMeta,
-                true /* createEncoder */, source);
+        mEncoder = MediaCodecSource::Create(encLooper, encMeta, source);
 
         mEncoder->start();
 
diff --git a/media/libstagefright/rtsp/rtp_test.cpp b/media/libstagefright/rtsp/rtp_test.cpp
index d43cd2a..24f529b 100644
--- a/media/libstagefright/rtsp/rtp_test.cpp
+++ b/media/libstagefright/rtsp/rtp_test.cpp
@@ -20,13 +20,13 @@
 
 #include <binder/ProcessState.h>
 
+#include <media/stagefright/foundation/base64.h>
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/ALooper.h>
 #include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MetaData.h>
-#include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
-#include <media/stagefright/foundation/base64.h>
+#include <media/stagefright/SimpleDecodingSource.h>
 
 #include "ARTPSession.h"
 #include "ASessionDescription.h"
@@ -178,15 +178,8 @@
     CHECK_EQ(session->countTracks(), 1u);
     sp<MediaSource> source = session->trackAt(0);
 
-    OMXClient client;
-    CHECK_EQ(client.connect(), (status_t)OK);
-
-    sp<MediaSource> decoder = OMXCodec::Create(
-            client.interface(),
-            source->getFormat(), false /* createEncoder */,
-            source,
-            NULL,
-            0);  // OMXCodec::kPreferSoftwareCodecs);
+    sp<MediaSource> decoder = SimpleDecodingSource::Create(
+            source, 0 /* flags: ACodec::kPreferSoftwareCodecs */);
     CHECK(decoder != NULL);
 
     CHECK_EQ(decoder->start(), (status_t)OK);
@@ -213,7 +206,7 @@
             int64_t timeUs;
             CHECK(buffer->meta_data()->findInt64(kKeyTime, &timeUs));
 
-            printf("decoder returned frame of size %d at time %.2f secs\n",
+            printf("decoder returned frame of size %zu at time %.2f secs\n",
                    buffer->range_length(), timeUs / 1E6);
         }
 #endif
diff --git a/media/libstagefright/tests/SurfaceMediaSource_test.cpp b/media/libstagefright/tests/SurfaceMediaSource_test.cpp
index 3860e9b..d419133 100644
--- a/media/libstagefright/tests/SurfaceMediaSource_test.cpp
+++ b/media/libstagefright/tests/SurfaceMediaSource_test.cpp
@@ -38,11 +38,6 @@
 #include <binder/ProcessState.h>
 
 #include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/MediaBufferGroup.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MetaData.h>
-#include <media/stagefright/OMXClient.h>
-#include <media/stagefright/OMXCodec.h>
 #include <OMX_Component.h>
 
 #include "DummyRecorder.h"
@@ -598,7 +593,7 @@
 struct SimpleDummyRecorder {
         sp<MediaSource> mSource;
 
-        SimpleDummyRecorder
+        explicit SimpleDummyRecorder
                 (const sp<MediaSource> &source): mSource(source) {}
 
         status_t start() { return mSource->start();}
diff --git a/media/libstagefright/timedtext/Android.mk b/media/libstagefright/timedtext/Android.mk
index 4d4ffba..8d128b8 100644
--- a/media/libstagefright/timedtext/Android.mk
+++ b/media/libstagefright/timedtext/Android.mk
@@ -3,11 +3,6 @@
 
 LOCAL_SRC_FILES:=                 \
         TextDescriptions.cpp      \
-        TimedTextDriver.cpp       \
-        TimedText3GPPSource.cpp \
-        TimedTextSource.cpp       \
-        TimedTextSRTSource.cpp    \
-        TimedTextPlayer.cpp
 
 LOCAL_CFLAGS += -Wno-multichar -Werror -Wall
 LOCAL_CLANG := true
@@ -17,6 +12,8 @@
         $(TOP)/frameworks/av/include/media/stagefright/timedtext \
         $(TOP)/frameworks/av/media/libstagefright
 
+LOCAL_SHARED_LIBRARIES := libmedia
+
 LOCAL_MODULE:= libstagefright_timedtext
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/timedtext/TextDescriptions.cpp b/media/libstagefright/timedtext/TextDescriptions.cpp
index f9c1fe0..c762a74 100644
--- a/media/libstagefright/timedtext/TextDescriptions.cpp
+++ b/media/libstagefright/timedtext/TextDescriptions.cpp
@@ -30,9 +30,9 @@
 
     if (flags & IN_BAND_TEXT_3GPP) {
         if (flags & GLOBAL_DESCRIPTIONS) {
-            return extract3GPPGlobalDescriptions(data, size, parcel, 0);
+            return extract3GPPGlobalDescriptions(data, size, parcel);
         } else if (flags & LOCAL_DESCRIPTIONS) {
-            return extract3GPPLocalDescriptions(data, size, timeMs, parcel, 0);
+            return extract3GPPLocalDescriptions(data, size, timeMs, parcel);
         }
     } else if (flags & OUT_OF_BAND_TEXT_SRT) {
         if (flags & LOCAL_DESCRIPTIONS) {
@@ -69,49 +69,361 @@
 // styles, and 'krok' box contains karaoke timing and positions.
 status_t TextDescriptions::extract3GPPLocalDescriptions(
         const uint8_t *data, ssize_t size,
-        int timeMs, Parcel *parcel, int depth) {
-    if (depth == 0) {
-        parcel->writeInt32(KEY_LOCAL_SETTING);
+        int timeMs, Parcel *parcel) {
 
-        // write start time to display this text sample
-        parcel->writeInt32(KEY_START_TIME);
-        parcel->writeInt32(timeMs);
+    parcel->writeInt32(KEY_LOCAL_SETTING);
 
-        ssize_t textLen = (*data) << 8 | (*(data + 1));
+    // write start time to display this text sample
+    parcel->writeInt32(KEY_START_TIME);
+    parcel->writeInt32(timeMs);
 
-        // write text sample length and text sample itself
-        parcel->writeInt32(KEY_STRUCT_TEXT);
-        parcel->writeInt32(textLen);
-        parcel->writeInt32(textLen);
-        parcel->write(data + 2, textLen);
-
-        if (size > textLen) {
-            data += (textLen + 2);
-            size -= (textLen + 2);
-        } else {
-            return OK;
-        }
+    if (size < 2) {
+        return OK;
     }
+    ssize_t textLen = (*data) << 8 | (*(data + 1));
 
-    const uint8_t *tmpData = data;
-    ssize_t chunkSize = U32_AT(tmpData);
-    uint32_t chunkType = U32_AT(tmpData + 4);
-
-    if (chunkSize <= 0) {
+    if (size < textLen + 2) {
         return OK;
     }
 
-    tmpData += 8;
+    // write text sample length and text sample itself
+    parcel->writeInt32(KEY_STRUCT_TEXT);
+    parcel->writeInt32(textLen);
+    parcel->writeInt32(textLen);
+    parcel->write(data + 2, textLen);
 
-    switch(chunkType) {
-        // 'styl' box specifies the style of the text.
-        case FOURCC('s', 't', 'y', 'l'):
-        {
-            uint16_t count = U16_AT(tmpData);
+    if (size > textLen + 2) {
+        data += (textLen + 2);
+        size -= (textLen + 2);
+    } else {
+        return OK;
+    }
 
-            tmpData += 2;
+    while (size >= 8) {
+        const uint8_t *tmpData = data;
+        ssize_t chunkSize = U32_AT(tmpData);      // size includes size and type
+        uint32_t chunkType = U32_AT(tmpData + 4);
 
-            for (int i = 0; i < count; i++) {
+        if (chunkSize <= 8 || chunkSize > size) {
+            return OK;
+        }
+
+        size_t remaining = chunkSize - 8;
+
+        tmpData += 8;
+
+        switch(chunkType) {
+            // 'styl' box specifies the style of the text.
+            case FOURCC('s', 't', 'y', 'l'):
+            {
+                if (remaining < 2) {
+                    return OK;
+                }
+                size_t dataPos = parcel->dataPosition();
+                uint16_t count = U16_AT(tmpData);
+
+                tmpData += 2;
+                remaining -= 2;
+
+                for (int i = 0; i < count; i++) {
+                    if (remaining < 12) {
+                        // roll back
+                        parcel->setDataPosition(dataPos);
+                        return OK;
+                    }
+                    parcel->writeInt32(KEY_STRUCT_STYLE_LIST);
+                    parcel->writeInt32(KEY_START_CHAR);
+                    parcel->writeInt32(U16_AT(tmpData));
+
+                    parcel->writeInt32(KEY_END_CHAR);
+                    parcel->writeInt32(U16_AT(tmpData + 2));
+
+                    parcel->writeInt32(KEY_FONT_ID);
+                    parcel->writeInt32(U16_AT(tmpData + 4));
+
+                    parcel->writeInt32(KEY_STYLE_FLAGS);
+                    parcel->writeInt32(*(tmpData + 6));
+
+                    parcel->writeInt32(KEY_FONT_SIZE);
+                    parcel->writeInt32(*(tmpData + 7));
+
+                    parcel->writeInt32(KEY_TEXT_COLOR_RGBA);
+                    uint32_t rgba = *(tmpData + 8) << 24 | *(tmpData + 9) << 16
+                        | *(tmpData + 10) << 8 | *(tmpData + 11);
+                    parcel->writeInt32(rgba);
+
+                    tmpData += 12;
+                    remaining -= 12;
+                }
+
+                break;
+            }
+            // 'krok' box. The number of highlight events is specified, and each
+            // event is specified by a starting and ending char offset and an end
+            // time for the event.
+            case FOURCC('k', 'r', 'o', 'k'):
+            {
+                if (remaining < 6) {
+                    return OK;
+                }
+                size_t dataPos = parcel->dataPosition();
+
+                parcel->writeInt32(KEY_STRUCT_KARAOKE_LIST);
+
+                int startTime = U32_AT(tmpData);
+                uint16_t count = U16_AT(tmpData + 4);
+                parcel->writeInt32(count);
+
+                tmpData += 6;
+                remaining -= 6;
+                int lastEndTime = 0;
+
+                for (int i = 0; i < count; i++) {
+                    if (remaining < 8) {
+                        // roll back
+                        parcel->setDataPosition(dataPos);
+                        return OK;
+                    }
+                    parcel->writeInt32(startTime + lastEndTime);
+
+                    lastEndTime = U32_AT(tmpData);
+                    parcel->writeInt32(lastEndTime);
+
+                    parcel->writeInt32(U16_AT(tmpData + 4));
+                    parcel->writeInt32(U16_AT(tmpData + 6));
+
+                    tmpData += 8;
+                    remaining -= 8;
+                }
+
+                break;
+            }
+            // 'hlit' box specifies highlighted text
+            case FOURCC('h', 'l', 'i', 't'):
+            {
+                if (remaining < 4) {
+                    return OK;
+                }
+
+                parcel->writeInt32(KEY_STRUCT_HIGHLIGHT_LIST);
+
+                // the start char offset to highlight
+                parcel->writeInt32(U16_AT(tmpData));
+                // the last char offset to highlight
+                parcel->writeInt32(U16_AT(tmpData + 2));
+
+                tmpData += 4;
+                remaining -= 4;
+                break;
+            }
+            // 'hclr' box specifies the RGBA color: 8 bits each of
+            // red, green, blue, and an alpha(transparency) value
+            case FOURCC('h', 'c', 'l', 'r'):
+            {
+                if (remaining < 4) {
+                    return OK;
+                }
+                parcel->writeInt32(KEY_HIGHLIGHT_COLOR_RGBA);
+
+                uint32_t rgba = *(tmpData) << 24 | *(tmpData + 1) << 16
+                    | *(tmpData + 2) << 8 | *(tmpData + 3);
+                parcel->writeInt32(rgba);
+
+                tmpData += 4;
+                remaining -= 4;
+                break;
+            }
+            // 'dlay' box specifies a delay after a scroll in and/or
+            // before scroll out.
+            case FOURCC('d', 'l', 'a', 'y'):
+            {
+                if (remaining < 4) {
+                    return OK;
+                }
+                parcel->writeInt32(KEY_SCROLL_DELAY);
+
+                uint32_t delay = *(tmpData) << 24 | *(tmpData + 1) << 16
+                    | *(tmpData + 2) << 8 | *(tmpData + 3);
+                parcel->writeInt32(delay);
+
+                tmpData += 4;
+                remaining -= 4;
+                break;
+            }
+            // 'href' box for hyper text link
+            case FOURCC('h', 'r', 'e', 'f'):
+            {
+                if (remaining < 5) {
+                    return OK;
+                }
+
+                size_t dataPos = parcel->dataPosition();
+
+                parcel->writeInt32(KEY_STRUCT_HYPER_TEXT_LIST);
+
+                // the start offset of the text to be linked
+                parcel->writeInt32(U16_AT(tmpData));
+                // the end offset of the text
+                parcel->writeInt32(U16_AT(tmpData + 2));
+
+                // the number of bytes in the following URL
+                size_t len = *(tmpData + 4);
+                parcel->writeInt32(len);
+
+                remaining -= 5;
+
+                if (remaining  < len) {
+                    parcel->setDataPosition(dataPos);
+                    return OK;
+                }
+                // the linked-to URL
+                parcel->writeInt32(len);
+                parcel->write(tmpData + 5, len);
+
+                tmpData += (5 + len);
+                remaining -= len;
+
+                if (remaining  < 1) {
+                    parcel->setDataPosition(dataPos);
+                    return OK;
+                }
+
+                // the number of bytes in the following "alt" string
+                len = *tmpData;
+                parcel->writeInt32(len);
+
+                tmpData += 1;
+                remaining -= 1;
+                if (remaining  < len) {
+                    parcel->setDataPosition(dataPos);
+                    return OK;
+                }
+
+                // an "alt" string for user display
+                parcel->writeInt32(len);
+                parcel->write(tmpData, len);
+
+                tmpData += 1;
+                remaining -= 1;
+                break;
+            }
+            // 'tbox' box to indicate the position of the text with values
+            // of top, left, bottom and right
+            case FOURCC('t', 'b', 'o', 'x'):
+            {
+                if (remaining < 8) {
+                    return OK;
+                }
+                parcel->writeInt32(KEY_STRUCT_TEXT_POS);
+                parcel->writeInt32(U16_AT(tmpData));
+                parcel->writeInt32(U16_AT(tmpData + 2));
+                parcel->writeInt32(U16_AT(tmpData + 4));
+                parcel->writeInt32(U16_AT(tmpData + 6));
+
+                tmpData += 8;
+                remaining -= 8;
+                break;
+            }
+            // 'blnk' to specify the char range to be blinked
+            case FOURCC('b', 'l', 'n', 'k'):
+            {
+                if (remaining < 4) {
+                    return OK;
+                }
+
+                parcel->writeInt32(KEY_STRUCT_BLINKING_TEXT_LIST);
+
+                // start char offset
+                parcel->writeInt32(U16_AT(tmpData));
+                // end char offset
+                parcel->writeInt32(U16_AT(tmpData + 2));
+
+                tmpData += 4;
+                remaining -= 4;
+                break;
+            }
+            // 'twrp' box specifies text wrap behavior. If the value if 0x00,
+            // then no wrap. If it's 0x01, then automatic 'soft' wrap is enabled.
+            // 0x02-0xff are reserved.
+            case FOURCC('t', 'w', 'r', 'p'):
+            {
+                if (remaining < 1) {
+                    return OK;
+                }
+                parcel->writeInt32(KEY_WRAP_TEXT);
+                parcel->writeInt32(*tmpData);
+
+                tmpData += 1;
+                remaining -= 1;
+                break;
+            }
+            default:
+            {
+                break;
+            }
+        }
+
+        data += chunkSize;
+        size -= chunkSize;
+    }
+
+    return OK;
+}
+
+// To extract box 'tx3g' defined in 3GPP TS 26.245, and store it in a Parcel
+status_t TextDescriptions::extract3GPPGlobalDescriptions(
+        const uint8_t *data, ssize_t size, Parcel *parcel) {
+
+    parcel->writeInt32(KEY_GLOBAL_SETTING);
+
+    while (size >= 8) {
+        ssize_t chunkSize = U32_AT(data);
+        uint32_t chunkType = U32_AT(data + 4);
+        const uint8_t *tmpData = data;
+        tmpData += 8;
+        size_t remaining = size - 8;
+
+        if (size < chunkSize) {
+            return OK;
+        }
+        switch(chunkType) {
+            case FOURCC('t', 'x', '3', 'g'):
+            {
+                if (remaining < 18) { // 8 just below, and another 10 a little further down
+                    return OK;
+                }
+                tmpData += 8; // skip the first 8 bytes
+                remaining -=8;
+                parcel->writeInt32(KEY_DISPLAY_FLAGS);
+                parcel->writeInt32(U32_AT(tmpData));
+
+                parcel->writeInt32(KEY_STRUCT_JUSTIFICATION);
+                parcel->writeInt32(tmpData[4]);
+                parcel->writeInt32(tmpData[5]);
+
+                parcel->writeInt32(KEY_BACKGROUND_COLOR_RGBA);
+                uint32_t rgba = *(tmpData + 6) << 24 | *(tmpData + 7) << 16
+                    | *(tmpData + 8) << 8 | *(tmpData + 9);
+                parcel->writeInt32(rgba);
+
+                tmpData += 10;
+                remaining -= 10;
+
+                if (remaining < 8) {
+                    return OK;
+                }
+                parcel->writeInt32(KEY_STRUCT_TEXT_POS);
+                parcel->writeInt32(U16_AT(tmpData));
+                parcel->writeInt32(U16_AT(tmpData + 2));
+                parcel->writeInt32(U16_AT(tmpData + 4));
+                parcel->writeInt32(U16_AT(tmpData + 6));
+
+                tmpData += 8;
+                remaining -= 8;
+
+                if (remaining < 12) {
+                    return OK;
+                }
                 parcel->writeInt32(KEY_STRUCT_STYLE_LIST);
                 parcel->writeInt32(KEY_START_CHAR);
                 parcel->writeInt32(U16_AT(tmpData));
@@ -129,254 +441,65 @@
                 parcel->writeInt32(*(tmpData + 7));
 
                 parcel->writeInt32(KEY_TEXT_COLOR_RGBA);
-                uint32_t rgba = *(tmpData + 8) << 24 | *(tmpData + 9) << 16
+                rgba = *(tmpData + 8) << 24 | *(tmpData + 9) << 16
                     | *(tmpData + 10) << 8 | *(tmpData + 11);
                 parcel->writeInt32(rgba);
 
                 tmpData += 12;
+                remaining -= 12;
+
+                if (remaining < 2) {
+                    return OK;
+                }
+
+                size_t dataPos = parcel->dataPosition();
+
+                parcel->writeInt32(KEY_STRUCT_FONT_LIST);
+                uint16_t count = U16_AT(tmpData);
+                parcel->writeInt32(count);
+
+                tmpData += 2;
+                remaining -= 2;
+
+                for (int i = 0; i < count; i++) {
+                    if (remaining < 3) {
+                        // roll back
+                        parcel->setDataPosition(dataPos);
+                        return OK;
+                    }
+                    // font ID
+                    parcel->writeInt32(U16_AT(tmpData));
+
+                    // font name length
+                    parcel->writeInt32(*(tmpData + 2));
+
+                    size_t len = *(tmpData + 2);
+
+                    tmpData += 3;
+                    remaining -= 3;
+
+                    if (remaining < len) {
+                        // roll back
+                        parcel->setDataPosition(dataPos);
+                        return OK;
+                    }
+
+                    parcel->write(tmpData, len);
+                    tmpData += len;
+                    remaining -= len;
+                }
+
+                // there is a "DisparityBox" after this according to the spec, but we ignore it
+                break;
             }
-
-            break;
-        }
-        // 'krok' box. The number of highlight events is specified, and each
-        // event is specified by a starting and ending char offset and an end
-        // time for the event.
-        case FOURCC('k', 'r', 'o', 'k'):
-        {
-
-            parcel->writeInt32(KEY_STRUCT_KARAOKE_LIST);
-
-            int startTime = U32_AT(tmpData);
-            uint16_t count = U16_AT(tmpData + 4);
-            parcel->writeInt32(count);
-
-            tmpData += 6;
-            int lastEndTime = 0;
-
-            for (int i = 0; i < count; i++) {
-                parcel->writeInt32(startTime + lastEndTime);
-
-                lastEndTime = U32_AT(tmpData);
-                parcel->writeInt32(lastEndTime);
-
-                parcel->writeInt32(U16_AT(tmpData + 4));
-                parcel->writeInt32(U16_AT(tmpData + 6));
-
-                tmpData += 8;
+            default:
+            {
+                break;
             }
-
-            break;
         }
-        // 'hlit' box specifies highlighted text
-        case FOURCC('h', 'l', 'i', 't'):
-        {
-            parcel->writeInt32(KEY_STRUCT_HIGHLIGHT_LIST);
 
-            // the start char offset to highlight
-            parcel->writeInt32(U16_AT(tmpData));
-            // the last char offset to highlight
-            parcel->writeInt32(U16_AT(tmpData + 2));
-
-            break;
-        }
-        // 'hclr' box specifies the RGBA color: 8 bits each of
-        // red, green, blue, and an alpha(transparency) value
-        case FOURCC('h', 'c', 'l', 'r'):
-        {
-            parcel->writeInt32(KEY_HIGHLIGHT_COLOR_RGBA);
-
-            uint32_t rgba = *(tmpData) << 24 | *(tmpData + 1) << 16
-                | *(tmpData + 2) << 8 | *(tmpData + 3);
-            parcel->writeInt32(rgba);
-
-            break;
-        }
-        // 'dlay' box specifies a delay after a scroll in and/or
-        // before scroll out.
-        case FOURCC('d', 'l', 'a', 'y'):
-        {
-            parcel->writeInt32(KEY_SCROLL_DELAY);
-
-            uint32_t delay = *(tmpData) << 24 | *(tmpData + 1) << 16
-                | *(tmpData + 2) << 8 | *(tmpData + 3);
-            parcel->writeInt32(delay);
-
-            break;
-        }
-        // 'href' box for hyper text link
-        case FOURCC('h', 'r', 'e', 'f'):
-        {
-            parcel->writeInt32(KEY_STRUCT_HYPER_TEXT_LIST);
-
-            // the start offset of the text to be linked
-            parcel->writeInt32(U16_AT(tmpData));
-            // the end offset of the text
-            parcel->writeInt32(U16_AT(tmpData + 2));
-
-            // the number of bytes in the following URL
-            int len = *(tmpData + 4);
-            parcel->writeInt32(len);
-
-            // the linked-to URL
-            parcel->writeInt32(len);
-            parcel->write(tmpData + 5, len);
-
-            tmpData += (5 + len);
-
-            // the number of bytes in the following "alt" string
-            len = *tmpData;
-            parcel->writeInt32(len);
-
-            // an "alt" string for user display
-            parcel->writeInt32(len);
-            parcel->write(tmpData + 1, len);
-
-            break;
-        }
-        // 'tbox' box to indicate the position of the text with values
-        // of top, left, bottom and right
-        case FOURCC('t', 'b', 'o', 'x'):
-        {
-            parcel->writeInt32(KEY_STRUCT_TEXT_POS);
-            parcel->writeInt32(U16_AT(tmpData));
-            parcel->writeInt32(U16_AT(tmpData + 2));
-            parcel->writeInt32(U16_AT(tmpData + 4));
-            parcel->writeInt32(U16_AT(tmpData + 6));
-
-            break;
-        }
-        // 'blnk' to specify the char range to be blinked
-        case FOURCC('b', 'l', 'n', 'k'):
-        {
-            parcel->writeInt32(KEY_STRUCT_BLINKING_TEXT_LIST);
-
-            // start char offset
-            parcel->writeInt32(U16_AT(tmpData));
-            // end char offset
-            parcel->writeInt32(U16_AT(tmpData + 2));
-
-            break;
-        }
-        // 'twrp' box specifies text wrap behavior. If the value if 0x00,
-        // then no wrap. If it's 0x01, then automatic 'soft' wrap is enabled.
-        // 0x02-0xff are reserved.
-        case FOURCC('t', 'w', 'r', 'p'):
-        {
-            parcel->writeInt32(KEY_WRAP_TEXT);
-            parcel->writeInt32(*tmpData);
-
-            break;
-        }
-        default:
-        {
-            break;
-        }
-    }
-
-    if (size > chunkSize) {
         data += chunkSize;
         size -= chunkSize;
-        // continue to parse next box
-        return extract3GPPLocalDescriptions(data, size, 0, parcel, 1);
-    }
-
-    return OK;
-}
-
-// To extract box 'tx3g' defined in 3GPP TS 26.245, and store it in a Parcel
-status_t TextDescriptions::extract3GPPGlobalDescriptions(
-        const uint8_t *data, ssize_t size, Parcel *parcel, int depth) {
-
-    ssize_t chunkSize = U32_AT(data);
-    uint32_t chunkType = U32_AT(data + 4);
-    const uint8_t *tmpData = data;
-    tmpData += 8;
-
-    if (size < chunkSize) {
-        return OK;
-    }
-
-    if (depth == 0) {
-        parcel->writeInt32(KEY_GLOBAL_SETTING);
-    }
-    switch(chunkType) {
-        case FOURCC('t', 'x', '3', 'g'):
-        {
-            tmpData += 8; // skip the first 8 bytes
-            parcel->writeInt32(KEY_DISPLAY_FLAGS);
-            parcel->writeInt32(U32_AT(tmpData));
-
-            parcel->writeInt32(KEY_STRUCT_JUSTIFICATION);
-            parcel->writeInt32(tmpData[4]);
-            parcel->writeInt32(tmpData[5]);
-
-            parcel->writeInt32(KEY_BACKGROUND_COLOR_RGBA);
-            uint32_t rgba = *(tmpData + 6) << 24 | *(tmpData + 7) << 16
-                | *(tmpData + 8) << 8 | *(tmpData + 9);
-            parcel->writeInt32(rgba);
-
-            tmpData += 10;
-            parcel->writeInt32(KEY_STRUCT_TEXT_POS);
-            parcel->writeInt32(U16_AT(tmpData));
-            parcel->writeInt32(U16_AT(tmpData + 2));
-            parcel->writeInt32(U16_AT(tmpData + 4));
-            parcel->writeInt32(U16_AT(tmpData + 6));
-
-            tmpData += 8;
-            parcel->writeInt32(KEY_STRUCT_STYLE_LIST);
-            parcel->writeInt32(KEY_START_CHAR);
-            parcel->writeInt32(U16_AT(tmpData));
-
-            parcel->writeInt32(KEY_END_CHAR);
-            parcel->writeInt32(U16_AT(tmpData + 2));
-
-            parcel->writeInt32(KEY_FONT_ID);
-            parcel->writeInt32(U16_AT(tmpData + 4));
-
-            parcel->writeInt32(KEY_STYLE_FLAGS);
-            parcel->writeInt32(*(tmpData + 6));
-
-            parcel->writeInt32(KEY_FONT_SIZE);
-            parcel->writeInt32(*(tmpData + 7));
-
-            parcel->writeInt32(KEY_TEXT_COLOR_RGBA);
-            rgba = *(tmpData + 8) << 24 | *(tmpData + 9) << 16
-                | *(tmpData + 10) << 8 | *(tmpData + 11);
-            parcel->writeInt32(rgba);
-
-            tmpData += 12;
-            parcel->writeInt32(KEY_STRUCT_FONT_LIST);
-            uint16_t count = U16_AT(tmpData);
-            parcel->writeInt32(count);
-
-            tmpData += 2;
-            for (int i = 0; i < count; i++) {
-                // font ID
-                parcel->writeInt32(U16_AT(tmpData));
-
-                // font name length
-                parcel->writeInt32(*(tmpData + 2));
-
-                int len = *(tmpData + 2);
-
-                parcel->write(tmpData + 3, len);
-                tmpData += 3 + len;
-            }
-
-            break;
-        }
-        default:
-        {
-            break;
-        }
-    }
-
-    data += chunkSize;
-    size -= chunkSize;
-
-    if (size > 0) {
-        // continue to extract next 'tx3g'
-        return extract3GPPGlobalDescriptions(data, size, parcel, 1);
     }
 
     return OK;
diff --git a/media/libstagefright/timedtext/TextDescriptions.h b/media/libstagefright/timedtext/TextDescriptions.h
index 0144917..bf67f3f 100644
--- a/media/libstagefright/timedtext/TextDescriptions.h
+++ b/media/libstagefright/timedtext/TextDescriptions.h
@@ -72,10 +72,10 @@
             int timeMs, Parcel *parcel);
     static status_t extract3GPPGlobalDescriptions(
             const uint8_t *data, ssize_t size,
-            Parcel *parcel, int depth);
+            Parcel *parcel);
     static status_t extract3GPPLocalDescriptions(
             const uint8_t *data, ssize_t size,
-            int timeMs, Parcel *parcel, int depth);
+            int timeMs, Parcel *parcel);
 
     DISALLOW_EVIL_CONSTRUCTORS(TextDescriptions);
 };
diff --git a/media/libstagefright/timedtext/TimedText3GPPSource.cpp b/media/libstagefright/timedtext/TimedText3GPPSource.cpp
deleted file mode 100644
index 4854121..0000000
--- a/media/libstagefright/timedtext/TimedText3GPPSource.cpp
+++ /dev/null
@@ -1,119 +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 "TimedText3GPPSource"
-#include <utils/Log.h>
-
-#include <binder/Parcel.h>
-#include <media/stagefright/foundation/ADebug.h>  // CHECK_XX macro
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MediaDefs.h>  // for MEDIA_MIMETYPE_xxx
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-
-#include "TimedText3GPPSource.h"
-#include "TextDescriptions.h"
-
-namespace android {
-
-TimedText3GPPSource::TimedText3GPPSource(const sp<MediaSource>& mediaSource)
-    : mSource(mediaSource) {
-}
-
-TimedText3GPPSource::~TimedText3GPPSource() {
-}
-
-status_t TimedText3GPPSource::read(
-        int64_t *startTimeUs, int64_t *endTimeUs, Parcel *parcel,
-        const MediaSource::ReadOptions *options) {
-    MediaBuffer *textBuffer = NULL;
-    status_t err = mSource->read(&textBuffer, options);
-    if (err != OK) {
-        return err;
-    }
-    CHECK(textBuffer != NULL);
-    textBuffer->meta_data()->findInt64(kKeyTime, startTimeUs);
-    CHECK_GE(*startTimeUs, 0);
-    extractAndAppendLocalDescriptions(*startTimeUs, textBuffer, parcel);
-    textBuffer->release();
-    // endTimeUs is a dummy parameter for 3gpp timed text format.
-    // Set a negative value to it to mark it is unavailable.
-    *endTimeUs = -1;
-    return OK;
-}
-
-// Each text sample consists of a string of text, optionally with sample
-// modifier description. The modifier description could specify a new
-// text style for the string of text. These descriptions are present only
-// if they are needed. This method is used to extract the modifier
-// description and append it at the end of the text.
-status_t TimedText3GPPSource::extractAndAppendLocalDescriptions(
-        int64_t timeUs, const MediaBuffer *textBuffer, Parcel *parcel) {
-    const void *data;
-    size_t size = 0;
-    int32_t flag = TextDescriptions::LOCAL_DESCRIPTIONS;
-
-    const char *mime;
-    CHECK(mSource->getFormat()->findCString(kKeyMIMEType, &mime));
-    CHECK(strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) == 0);
-
-    data = textBuffer->data();
-    size = textBuffer->size();
-
-    if (size > 0) {
-      parcel->freeData();
-      flag |= TextDescriptions::IN_BAND_TEXT_3GPP;
-      return TextDescriptions::getParcelOfDescriptions(
-          (const uint8_t *)data, size, flag, timeUs / 1000, parcel);
-    }
-    return OK;
-}
-
-// To extract and send the global text descriptions for all the text samples
-// in the text track or text file.
-// TODO: send error message to application via notifyListener()...?
-status_t TimedText3GPPSource::extractGlobalDescriptions(Parcel *parcel) {
-    const void *data;
-    size_t size = 0;
-    int32_t flag = TextDescriptions::GLOBAL_DESCRIPTIONS;
-
-    const char *mime;
-    CHECK(mSource->getFormat()->findCString(kKeyMIMEType, &mime));
-    CHECK(strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) == 0);
-
-    uint32_t type;
-    // get the 'tx3g' box content. This box contains the text descriptions
-    // used to render the text track
-    if (!mSource->getFormat()->findData(
-            kKeyTextFormatData, &type, &data, &size)) {
-        return ERROR_MALFORMED;
-    }
-
-    if (size > 0) {
-        flag |= TextDescriptions::IN_BAND_TEXT_3GPP;
-        return TextDescriptions::getParcelOfDescriptions(
-                (const uint8_t *)data, size, flag, 0, parcel);
-    }
-    return OK;
-}
-
-sp<MetaData> TimedText3GPPSource::getFormat() {
-    return mSource->getFormat();
-}
-
-}  // namespace android
diff --git a/media/libstagefright/timedtext/TimedText3GPPSource.h b/media/libstagefright/timedtext/TimedText3GPPSource.h
deleted file mode 100644
index 4170940..0000000
--- a/media/libstagefright/timedtext/TimedText3GPPSource.h
+++ /dev/null
@@ -1,57 +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 TIMED_TEXT_3GPP_SOURCE_H_
-#define TIMED_TEXT_3GPP_SOURCE_H_
-
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MediaSource.h>
-
-#include "TimedTextSource.h"
-
-namespace android {
-
-class MediaBuffer;
-class Parcel;
-
-class TimedText3GPPSource : public TimedTextSource {
-public:
-    TimedText3GPPSource(const sp<MediaSource>& mediaSource);
-    virtual status_t start() { return mSource->start(); }
-    virtual status_t stop() { return mSource->stop(); }
-    virtual status_t read(
-            int64_t *startTimeUs,
-            int64_t *endTimeUs,
-            Parcel *parcel,
-            const MediaSource::ReadOptions *options = NULL);
-    virtual status_t extractGlobalDescriptions(Parcel *parcel);
-    virtual sp<MetaData> getFormat();
-
-protected:
-    virtual ~TimedText3GPPSource();
-
-private:
-    sp<MediaSource> mSource;
-
-    status_t extractAndAppendLocalDescriptions(
-            int64_t timeUs, const MediaBuffer *textBuffer, Parcel *parcel);
-
-    DISALLOW_EVIL_CONSTRUCTORS(TimedText3GPPSource);
-};
-
-}  // namespace android
-
-#endif  // TIMED_TEXT_3GPP_SOURCE_H_
diff --git a/media/libstagefright/timedtext/TimedTextDriver.cpp b/media/libstagefright/timedtext/TimedTextDriver.cpp
deleted file mode 100644
index 55a9803..0000000
--- a/media/libstagefright/timedtext/TimedTextDriver.cpp
+++ /dev/null
@@ -1,287 +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 "TimedTextDriver"
-#include <utils/Log.h>
-
-#include <binder/IPCThreadState.h>
-
-#include <media/IMediaHTTPService.h>
-#include <media/mediaplayer.h>
-#include <media/MediaPlayerInterface.h>
-#include <media/stagefright/DataSource.h>
-#include <media/stagefright/FileSource.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-#include <media/stagefright/Utils.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/ALooper.h>
-#include <media/stagefright/timedtext/TimedTextDriver.h>
-
-#include "TextDescriptions.h"
-#include "TimedTextPlayer.h"
-#include "TimedTextSource.h"
-
-namespace android {
-
-TimedTextDriver::TimedTextDriver(
-        const wp<MediaPlayerBase> &listener,
-        const sp<IMediaHTTPService> &httpService)
-    : mLooper(new ALooper),
-      mListener(listener),
-      mHTTPService(httpService),
-      mState(UNINITIALIZED),
-      mCurrentTrackIndex(UINT_MAX) {
-    mLooper->setName("TimedTextDriver");
-    mLooper->start();
-    mPlayer = new TimedTextPlayer(listener);
-    mLooper->registerHandler(mPlayer);
-}
-
-TimedTextDriver::~TimedTextDriver() {
-    mTextSourceVector.clear();
-    mTextSourceTypeVector.clear();
-    mLooper->stop();
-}
-
-status_t TimedTextDriver::selectTrack_l(size_t index) {
-    if (mCurrentTrackIndex == index) {
-        return OK;
-    }
-    sp<TimedTextSource> source;
-    source = mTextSourceVector.valueFor(index);
-    mPlayer->setDataSource(source);
-    if (mState == UNINITIALIZED) {
-        mState = PREPARED;
-    }
-    mCurrentTrackIndex = index;
-    return OK;
-}
-
-status_t TimedTextDriver::start() {
-    Mutex::Autolock autoLock(mLock);
-    switch (mState) {
-        case UNINITIALIZED:
-            return INVALID_OPERATION;
-        case PLAYING:
-            return OK;
-        case PREPARED:
-            mPlayer->start();
-            mState = PLAYING;
-            return OK;
-        case PAUSED:
-            mPlayer->resume();
-            mState = PLAYING;
-            return OK;
-        default:
-            TRESPASS();
-    }
-    return UNKNOWN_ERROR;
-}
-
-status_t TimedTextDriver::pause() {
-    Mutex::Autolock autoLock(mLock);
-    ALOGV("%s() is called", __FUNCTION__);
-    switch (mState) {
-        case UNINITIALIZED:
-            return INVALID_OPERATION;
-        case PLAYING:
-            mPlayer->pause();
-            mState = PAUSED;
-            return OK;
-        case PREPARED:
-            return INVALID_OPERATION;
-        case PAUSED:
-            return OK;
-        default:
-            TRESPASS();
-    }
-    return UNKNOWN_ERROR;
-}
-
-status_t TimedTextDriver::selectTrack(size_t index) {
-    status_t ret = OK;
-    Mutex::Autolock autoLock(mLock);
-    ALOGV("%s() is called", __FUNCTION__);
-    switch (mState) {
-        case UNINITIALIZED:
-        case PREPARED:
-        case PAUSED:
-            ret = selectTrack_l(index);
-            break;
-        case PLAYING:
-            mPlayer->pause();
-            ret = selectTrack_l(index);
-            if (ret != OK) {
-                break;
-            }
-            mPlayer->start();
-            break;
-        default:
-            TRESPASS();
-    }
-    return ret;
-}
-
-status_t TimedTextDriver::unselectTrack(size_t index) {
-    Mutex::Autolock autoLock(mLock);
-    ALOGV("%s() is called", __FUNCTION__);
-    if (mCurrentTrackIndex != index) {
-        return INVALID_OPERATION;
-    }
-    mCurrentTrackIndex = UINT_MAX;
-    switch (mState) {
-        case UNINITIALIZED:
-            return INVALID_OPERATION;
-        case PLAYING:
-            mPlayer->setDataSource(NULL);
-            mState = UNINITIALIZED;
-            return OK;
-        case PREPARED:
-        case PAUSED:
-            mState = UNINITIALIZED;
-            return OK;
-        default:
-            TRESPASS();
-    }
-    return UNKNOWN_ERROR;
-}
-
-status_t TimedTextDriver::seekToAsync(int64_t timeUs) {
-    Mutex::Autolock autoLock(mLock);
-    ALOGV("%s() is called", __FUNCTION__);
-    switch (mState) {
-        case UNINITIALIZED:
-            return INVALID_OPERATION;
-        case PREPARED:
-            mPlayer->seekToAsync(timeUs);
-            mPlayer->pause();
-            mState = PAUSED;
-            return OK;
-        case PAUSED:
-            mPlayer->seekToAsync(timeUs);
-            mPlayer->pause();
-            return OK;
-        case PLAYING:
-            mPlayer->seekToAsync(timeUs);
-            return OK;
-        default:
-            TRESPASS();
-    }
-    return UNKNOWN_ERROR;
-}
-
-status_t TimedTextDriver::addInBandTextSource(
-        size_t trackIndex, const sp<MediaSource>& mediaSource) {
-    sp<TimedTextSource> source =
-            TimedTextSource::CreateTimedTextSource(mediaSource);
-    if (source == NULL) {
-        return ERROR_UNSUPPORTED;
-    }
-    Mutex::Autolock autoLock(mLock);
-    mTextSourceVector.add(trackIndex, source);
-    mTextSourceTypeVector.add(TEXT_SOURCE_TYPE_IN_BAND);
-    return OK;
-}
-
-status_t TimedTextDriver::addOutOfBandTextSource(
-        size_t trackIndex, const char *uri, const char *mimeType) {
-
-    // To support local subtitle file only for now
-    if (strncasecmp("file://", uri, 7)) {
-        ALOGE("uri('%s') is not a file", uri);
-        return ERROR_UNSUPPORTED;
-    }
-
-    sp<DataSource> dataSource =
-            DataSource::CreateFromURI(mHTTPService, uri);
-    return createOutOfBandTextSource(trackIndex, mimeType, dataSource);
-}
-
-status_t TimedTextDriver::addOutOfBandTextSource(
-        size_t trackIndex, int fd, off64_t offset, off64_t length, const char *mimeType) {
-
-    if (fd < 0) {
-        ALOGE("Invalid file descriptor: %d", fd);
-        return ERROR_UNSUPPORTED;
-    }
-
-    sp<DataSource> dataSource = new FileSource(dup(fd), offset, length);
-    return createOutOfBandTextSource(trackIndex, mimeType, dataSource);
-}
-
-status_t TimedTextDriver::createOutOfBandTextSource(
-        size_t trackIndex,
-        const char *mimeType,
-        const sp<DataSource>& dataSource) {
-
-    if (dataSource == NULL) {
-        return ERROR_UNSUPPORTED;
-    }
-
-    sp<TimedTextSource> source;
-    if (strcasecmp(mimeType, MEDIA_MIMETYPE_TEXT_SUBRIP) == 0) {
-        source = TimedTextSource::CreateTimedTextSource(
-                dataSource, TimedTextSource::OUT_OF_BAND_FILE_SRT);
-    }
-
-    if (source == NULL) {
-        ALOGE("Failed to create timed text source");
-        return ERROR_UNSUPPORTED;
-    }
-
-    Mutex::Autolock autoLock(mLock);
-    mTextSourceVector.add(trackIndex, source);
-    mTextSourceTypeVector.add(TEXT_SOURCE_TYPE_OUT_OF_BAND);
-    return OK;
-}
-
-size_t TimedTextDriver::countExternalTracks() const {
-    size_t nTracks = 0;
-    for (size_t i = 0, n = mTextSourceTypeVector.size(); i < n; ++i) {
-        if (mTextSourceTypeVector[i] == TEXT_SOURCE_TYPE_OUT_OF_BAND) {
-            ++nTracks;
-        }
-    }
-    return nTracks;
-}
-
-void TimedTextDriver::getExternalTrackInfo(Parcel *parcel) {
-    Mutex::Autolock autoLock(mLock);
-    for (size_t i = 0, n = mTextSourceTypeVector.size(); i < n; ++i) {
-        if (mTextSourceTypeVector[i] == TEXT_SOURCE_TYPE_IN_BAND) {
-            continue;
-        }
-
-        sp<MetaData> meta = mTextSourceVector.valueAt(i)->getFormat();
-
-        // There are two fields.
-        parcel->writeInt32(2);
-
-        // track type.
-        parcel->writeInt32(MEDIA_TRACK_TYPE_TIMEDTEXT);
-        const char *lang = "und";
-        if (meta != NULL) {
-            meta->findCString(kKeyMediaLanguage, &lang);
-        }
-        parcel->writeString16(String16(lang));
-    }
-}
-
-}  // namespace android
diff --git a/media/libstagefright/timedtext/TimedTextPlayer.cpp b/media/libstagefright/timedtext/TimedTextPlayer.cpp
deleted file mode 100644
index aecf666..0000000
--- a/media/libstagefright/timedtext/TimedTextPlayer.cpp
+++ /dev/null
@@ -1,316 +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 "TimedTextPlayer"
-#include <utils/Log.h>
-
-#include <inttypes.h>
-#include <limits.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/timedtext/TimedTextDriver.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/MediaPlayerInterface.h>
-
-#include "TimedTextPlayer.h"
-
-#include "TimedTextSource.h"
-
-namespace android {
-
-// Event should be fired a bit earlier considering the processing time till
-// application actually gets the notification message.
-static const int64_t kAdjustmentProcessingTimeUs = 100000ll;
-static const int64_t kMaxDelayUs = 5000000ll;
-static const int64_t kWaitTimeUsToRetryRead = 100000ll;
-static const int64_t kInvalidTimeUs = INT_MIN;
-
-TimedTextPlayer::TimedTextPlayer(const wp<MediaPlayerBase> &listener)
-    : mListener(listener),
-      mSource(NULL),
-      mPendingSeekTimeUs(kInvalidTimeUs),
-      mPaused(false),
-      mSendSubtitleGeneration(0) {
-}
-
-TimedTextPlayer::~TimedTextPlayer() {
-    if (mSource != NULL) {
-        mSource->stop();
-        mSource.clear();
-        mSource = NULL;
-    }
-}
-
-void TimedTextPlayer::start() {
-    (new AMessage(kWhatStart, this))->post();
-}
-
-void TimedTextPlayer::pause() {
-    (new AMessage(kWhatPause, this))->post();
-}
-
-void TimedTextPlayer::resume() {
-    (new AMessage(kWhatResume, this))->post();
-}
-
-void TimedTextPlayer::seekToAsync(int64_t timeUs) {
-    sp<AMessage> msg = new AMessage(kWhatSeek, this);
-    msg->setInt64("seekTimeUs", timeUs);
-    msg->post();
-}
-
-void TimedTextPlayer::setDataSource(sp<TimedTextSource> source) {
-    sp<AMessage> msg = new AMessage(kWhatSetSource, this);
-    msg->setObject("source", source);
-    msg->post();
-}
-
-void TimedTextPlayer::onMessageReceived(const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatPause: {
-            mPaused = true;
-            break;
-        }
-        case kWhatResume: {
-            mPaused = false;
-            if (mPendingSeekTimeUs != kInvalidTimeUs) {
-                seekToAsync(mPendingSeekTimeUs);
-                mPendingSeekTimeUs = kInvalidTimeUs;
-            } else {
-                doRead();
-            }
-            break;
-        }
-        case kWhatStart: {
-            sp<MediaPlayerBase> listener = mListener.promote();
-            if (listener == NULL) {
-                ALOGE("Listener is NULL when kWhatStart is received.");
-                break;
-            }
-            mPaused = false;
-            mPendingSeekTimeUs = kInvalidTimeUs;
-            int32_t positionMs = 0;
-            listener->getCurrentPosition(&positionMs);
-            int64_t seekTimeUs = positionMs * 1000ll;
-
-            notifyListener();
-            mSendSubtitleGeneration++;
-            doSeekAndRead(seekTimeUs);
-            break;
-        }
-        case kWhatRetryRead: {
-            int32_t generation = -1;
-            CHECK(msg->findInt32("generation", &generation));
-            if (generation != mSendSubtitleGeneration) {
-                // Drop obsolete msg.
-                break;
-            }
-            int64_t seekTimeUs;
-            int seekMode;
-            if (msg->findInt64("seekTimeUs", &seekTimeUs) &&
-                msg->findInt32("seekMode", &seekMode)) {
-                MediaSource::ReadOptions options;
-                options.setSeekTo(
-                    seekTimeUs,
-                    static_cast<MediaSource::ReadOptions::SeekMode>(seekMode));
-                doRead(&options);
-            } else {
-                doRead();
-            }
-            break;
-        }
-        case kWhatSeek: {
-            int64_t seekTimeUs = kInvalidTimeUs;
-            // Clear a displayed timed text before seeking.
-            notifyListener();
-            msg->findInt64("seekTimeUs", &seekTimeUs);
-            if (seekTimeUs == kInvalidTimeUs) {
-                sp<MediaPlayerBase> listener = mListener.promote();
-                if (listener != NULL) {
-                    int32_t positionMs = 0;
-                    listener->getCurrentPosition(&positionMs);
-                    seekTimeUs = positionMs * 1000ll;
-                }
-            }
-            if (mPaused) {
-                mPendingSeekTimeUs = seekTimeUs;
-                break;
-            }
-            mSendSubtitleGeneration++;
-            doSeekAndRead(seekTimeUs);
-            break;
-        }
-        case kWhatSendSubtitle: {
-            int32_t generation;
-            CHECK(msg->findInt32("generation", &generation));
-            if (generation != mSendSubtitleGeneration) {
-                // Drop obsolete msg.
-                break;
-            }
-            // If current time doesn't reach to the fire time,
-            // re-post the message with the adjusted delay time.
-            int64_t fireTimeUs = kInvalidTimeUs;
-            if (msg->findInt64("fireTimeUs", &fireTimeUs)) {
-                // TODO: check if fireTimeUs is not kInvalidTimeUs.
-                int64_t delayUs = delayUsFromCurrentTime(fireTimeUs);
-                if (delayUs > 0) {
-                    msg->post(delayUs);
-                    break;
-                }
-            }
-            sp<RefBase> obj;
-            if (msg->findObject("subtitle", &obj)) {
-                sp<ParcelEvent> parcelEvent;
-                parcelEvent = static_cast<ParcelEvent*>(obj.get());
-                notifyListener(&(parcelEvent->parcel));
-                doRead();
-            } else {
-                notifyListener();
-            }
-            break;
-        }
-        case kWhatSetSource: {
-            mSendSubtitleGeneration++;
-            sp<RefBase> obj;
-            msg->findObject("source", &obj);
-            if (mSource != NULL) {
-                mSource->stop();
-                mSource.clear();
-                mSource = NULL;
-            }
-            // null source means deselect track.
-            if (obj == NULL) {
-                mPendingSeekTimeUs = kInvalidTimeUs;
-                mPaused = false;
-                notifyListener();
-                break;
-            }
-            mSource = static_cast<TimedTextSource*>(obj.get());
-            status_t err = mSource->start();
-            if (err != OK) {
-                notifyError(err);
-                break;
-            }
-            Parcel parcel;
-            err = mSource->extractGlobalDescriptions(&parcel);
-            if (err != OK) {
-                notifyError(err);
-                break;
-            }
-            notifyListener(&parcel);
-            break;
-        }
-    }
-}
-
-void TimedTextPlayer::doSeekAndRead(int64_t seekTimeUs) {
-    MediaSource::ReadOptions options;
-    options.setSeekTo(seekTimeUs, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-    doRead(&options);
-}
-
-void TimedTextPlayer::doRead(MediaSource::ReadOptions* options) {
-    int64_t startTimeUs = 0;
-    int64_t endTimeUs = 0;
-    sp<ParcelEvent> parcelEvent = new ParcelEvent();
-    CHECK(mSource != NULL);
-    status_t err = mSource->read(&startTimeUs, &endTimeUs,
-                                 &(parcelEvent->parcel), options);
-    if (err == WOULD_BLOCK) {
-        sp<AMessage> msg = new AMessage(kWhatRetryRead, this);
-        if (options != NULL) {
-            int64_t seekTimeUs = kInvalidTimeUs;
-            MediaSource::ReadOptions::SeekMode seekMode =
-                MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC;
-            CHECK(options->getSeekTo(&seekTimeUs, &seekMode));
-            msg->setInt64("seekTimeUs", seekTimeUs);
-            msg->setInt32("seekMode", seekMode);
-        }
-        msg->setInt32("generation", mSendSubtitleGeneration);
-        msg->post(kWaitTimeUsToRetryRead);
-        return;
-    } else if (err != OK) {
-        notifyError(err);
-        return;
-    }
-
-    postTextEvent(parcelEvent, startTimeUs);
-    if (endTimeUs > 0) {
-        CHECK_GE(endTimeUs, startTimeUs);
-        // send an empty timed text to clear the subtitle when it reaches to the
-        // end time.
-        postTextEvent(NULL, endTimeUs);
-    }
-}
-
-void TimedTextPlayer::postTextEvent(const sp<ParcelEvent>& parcel, int64_t timeUs) {
-    int64_t delayUs = delayUsFromCurrentTime(timeUs);
-    sp<AMessage> msg = new AMessage(kWhatSendSubtitle, this);
-    msg->setInt32("generation", mSendSubtitleGeneration);
-    if (parcel != NULL) {
-        msg->setObject("subtitle", parcel);
-    }
-    msg->setInt64("fireTimeUs", timeUs);
-    msg->post(delayUs);
-}
-
-int64_t TimedTextPlayer::delayUsFromCurrentTime(int64_t fireTimeUs) {
-    sp<MediaPlayerBase> listener = mListener.promote();
-    if (listener == NULL) {
-        // TODO: it may be better to return kInvalidTimeUs
-        ALOGE("%s: Listener is NULL. (fireTimeUs = %" PRId64" )",
-              __FUNCTION__, fireTimeUs);
-        return 0;
-    }
-    int32_t positionMs = 0;
-    listener->getCurrentPosition(&positionMs);
-    int64_t positionUs = positionMs * 1000ll;
-
-    if (fireTimeUs <= positionUs + kAdjustmentProcessingTimeUs) {
-        return 0;
-    } else {
-        int64_t delayUs = fireTimeUs - positionUs - kAdjustmentProcessingTimeUs;
-        if (delayUs > kMaxDelayUs) {
-            return kMaxDelayUs;
-        }
-        return delayUs;
-    }
-}
-
-void TimedTextPlayer::notifyError(int error) {
-    sp<MediaPlayerBase> listener = mListener.promote();
-    if (listener == NULL) {
-        ALOGE("%s(error=%d): Listener is NULL.", __FUNCTION__, error);
-        return;
-    }
-    listener->sendEvent(MEDIA_INFO, MEDIA_INFO_TIMED_TEXT_ERROR, error);
-}
-
-void TimedTextPlayer::notifyListener(const Parcel *parcel) {
-    sp<MediaPlayerBase> listener = mListener.promote();
-    if (listener == NULL) {
-        ALOGE("%s: Listener is NULL.", __FUNCTION__);
-        return;
-    }
-    if (parcel != NULL && (parcel->dataSize() > 0)) {
-        listener->sendEvent(MEDIA_TIMED_TEXT, 0, 0, parcel);
-    } else {  // send an empty timed text to clear the screen
-        listener->sendEvent(MEDIA_TIMED_TEXT);
-    }
-}
-
-}  // namespace android
diff --git a/media/libstagefright/timedtext/TimedTextPlayer.h b/media/libstagefright/timedtext/TimedTextPlayer.h
deleted file mode 100644
index 9cb49ec..0000000
--- a/media/libstagefright/timedtext/TimedTextPlayer.h
+++ /dev/null
@@ -1,85 +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 TIMEDTEXT_PLAYER_H_
-#define TIMEDTEXT_PLAYER_H_
-
-#include <binder/Parcel.h>
-#include <media/stagefright/foundation/ABase.h>
-#include <media/stagefright/foundation/AHandler.h>
-#include <media/stagefright/MediaSource.h>
-#include <utils/RefBase.h>
-
-#include "TimedTextSource.h"
-
-namespace android {
-
-struct AMessage;
-class MediaPlayerBase;
-class TimedTextDriver;
-class TimedTextSource;
-
-class TimedTextPlayer : public AHandler {
-public:
-    TimedTextPlayer(const wp<MediaPlayerBase> &listener);
-
-    virtual ~TimedTextPlayer();
-
-    void start();
-    void pause();
-    void resume();
-    void seekToAsync(int64_t timeUs);
-    void setDataSource(sp<TimedTextSource> source);
-
-protected:
-    virtual void onMessageReceived(const sp<AMessage> &msg);
-
-private:
-    enum {
-        kWhatPause = 'paus',
-        kWhatResume = 'resm',
-        kWhatStart = 'strt',
-        kWhatSeek = 'seek',
-        kWhatRetryRead = 'read',
-        kWhatSendSubtitle = 'send',
-        kWhatSetSource = 'ssrc',
-    };
-
-    // To add Parcel into an AMessage as an object, it should be 'RefBase'.
-    struct ParcelEvent : public RefBase {
-        Parcel parcel;
-    };
-
-    wp<MediaPlayerBase> mListener;
-    sp<TimedTextSource> mSource;
-    int64_t mPendingSeekTimeUs;
-    bool mPaused;
-    int32_t mSendSubtitleGeneration;
-
-    void doSeekAndRead(int64_t seekTimeUs);
-    void doRead(MediaSource::ReadOptions* options = NULL);
-    void onTextEvent();
-    void postTextEvent(const sp<ParcelEvent>& parcel = NULL, int64_t timeUs = -1);
-    int64_t delayUsFromCurrentTime(int64_t fireTimeUs);
-    void notifyError(int error = 0);
-    void notifyListener(const Parcel *parcel = NULL);
-
-    DISALLOW_EVIL_CONSTRUCTORS(TimedTextPlayer);
-};
-
-}  // namespace android
-
-#endif  // TIMEDTEXT_PLAYER_H_
diff --git a/media/libstagefright/timedtext/TimedTextSRTSource.cpp b/media/libstagefright/timedtext/TimedTextSRTSource.cpp
deleted file mode 100644
index 2ac1e72..0000000
--- a/media/libstagefright/timedtext/TimedTextSRTSource.cpp
+++ /dev/null
@@ -1,297 +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 "TimedTextSRTSource"
-#include <utils/Log.h>
-
-#include <binder/Parcel.h>
-#include <media/stagefright/foundation/ADebug.h>  // for CHECK_xx
-#include <media/stagefright/foundation/AString.h>
-#include <media/stagefright/DataSource.h>
-#include <media/stagefright/MediaDefs.h>  // for MEDIA_MIMETYPE_xxx
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-
-#include "TimedTextSRTSource.h"
-#include "TextDescriptions.h"
-
-namespace android {
-
-TimedTextSRTSource::TimedTextSRTSource(const sp<DataSource>& dataSource)
-        : mSource(dataSource),
-          mMetaData(new MetaData),
-          mIndex(0) {
-    // TODO: Need to detect the language, because SRT doesn't give language
-    // information explicitly.
-    mMetaData->setCString(kKeyMediaLanguage, "und");
-}
-
-TimedTextSRTSource::~TimedTextSRTSource() {
-}
-
-status_t TimedTextSRTSource::start() {
-    status_t err = scanFile();
-    if (err != OK) {
-        reset();
-    }
-    return err;
-}
-
-void TimedTextSRTSource::reset() {
-    mTextVector.clear();
-    mIndex = 0;
-}
-
-status_t TimedTextSRTSource::stop() {
-    reset();
-    return OK;
-}
-
-status_t TimedTextSRTSource::read(
-        int64_t *startTimeUs,
-        int64_t *endTimeUs,
-        Parcel *parcel,
-        const MediaSource::ReadOptions *options) {
-    AString text;
-    status_t err = getText(options, &text, startTimeUs, endTimeUs);
-    if (err != OK) {
-        return err;
-    }
-
-    CHECK_GE(*startTimeUs, 0);
-    extractAndAppendLocalDescriptions(*startTimeUs, text, parcel);
-    return OK;
-}
-
-sp<MetaData> TimedTextSRTSource::getFormat() {
-    return mMetaData;
-}
-
-status_t TimedTextSRTSource::scanFile() {
-    off64_t offset = 0;
-    int64_t startTimeUs;
-    bool endOfFile = false;
-
-    while (!endOfFile) {
-        TextInfo info;
-        status_t err = getNextSubtitleInfo(&offset, &startTimeUs, &info);
-        switch (err) {
-            case OK:
-                mTextVector.add(startTimeUs, info);
-                break;
-            case ERROR_END_OF_STREAM:
-                endOfFile = true;
-                break;
-            default:
-                return err;
-        }
-    }
-    if (mTextVector.isEmpty()) {
-        return ERROR_MALFORMED;
-    }
-    return OK;
-}
-
-/* SRT format:
- *   Subtitle number
- *   Start time --> End time
- *   Text of subtitle (one or more lines)
- *   Blank lines
- *
- * .srt file example:
- * 1
- * 00:00:20,000 --> 00:00:24,400
- * Altocumulus clouds occr between six thousand
- *
- * 2
- * 00:00:24,600 --> 00:00:27,800
- * and twenty thousand feet above ground level.
- */
-status_t TimedTextSRTSource::getNextSubtitleInfo(
-          off64_t *offset, int64_t *startTimeUs, TextInfo *info) {
-    AString data;
-    status_t err;
-
-    // To skip blank lines.
-    do {
-        if ((err = readNextLine(offset, &data)) != OK) {
-            return err;
-        }
-        data.trim();
-    } while (data.empty());
-
-    // Just ignore the first non-blank line which is subtitle sequence number.
-    if ((err = readNextLine(offset, &data)) != OK) {
-        return err;
-    }
-    int hour1, hour2, min1, min2, sec1, sec2, msec1, msec2;
-    // the start time format is: hours:minutes:seconds,milliseconds
-    // 00:00:24,600 --> 00:00:27,800
-    if (sscanf(data.c_str(), "%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d",
-               &hour1, &min1, &sec1, &msec1, &hour2, &min2, &sec2, &msec2) != 8) {
-        return ERROR_MALFORMED;
-    }
-
-    *startTimeUs = ((hour1 * 3600 + min1 * 60 + sec1) * 1000 + msec1) * 1000ll;
-    info->endTimeUs = ((hour2 * 3600 + min2 * 60 + sec2) * 1000 + msec2) * 1000ll;
-    if (info->endTimeUs <= *startTimeUs) {
-        return ERROR_MALFORMED;
-    }
-
-    info->offset = *offset;
-    bool needMoreData = true;
-    while (needMoreData) {
-        if ((err = readNextLine(offset, &data)) != OK) {
-            if (err == ERROR_END_OF_STREAM) {
-                break;
-            } else {
-                return err;
-            }
-        }
-
-        data.trim();
-        if (data.empty()) {
-            // it's an empty line used to separate two subtitles
-            needMoreData = false;
-        }
-    }
-    info->textLen = *offset - info->offset;
-    return OK;
-}
-
-status_t TimedTextSRTSource::readNextLine(off64_t *offset, AString *data) {
-    data->clear();
-    while (true) {
-        ssize_t readSize;
-        char character;
-        if ((readSize = mSource->readAt(*offset, &character, 1)) < 1) {
-            if (readSize == 0) {
-                return ERROR_END_OF_STREAM;
-            }
-            return ERROR_IO;
-        }
-
-        (*offset)++;
-
-        // a line could end with CR, LF or CR + LF
-        if (character == 10) {
-            break;
-        } else if (character == 13) {
-            if ((readSize = mSource->readAt(*offset, &character, 1)) < 1) {
-                if (readSize == 0) {  // end of the stream
-                    return OK;
-                }
-                return ERROR_IO;
-            }
-
-            (*offset)++;
-            if (character != 10) {
-                (*offset)--;
-            }
-            break;
-        }
-        data->append(character);
-    }
-    return OK;
-}
-
-status_t TimedTextSRTSource::getText(
-        const MediaSource::ReadOptions *options,
-        AString *text, int64_t *startTimeUs, int64_t *endTimeUs) {
-    if (mTextVector.size() == 0) {
-        return ERROR_END_OF_STREAM;
-    }
-    text->clear();
-    int64_t seekTimeUs;
-    MediaSource::ReadOptions::SeekMode mode;
-    if (options != NULL && options->getSeekTo(&seekTimeUs, &mode)) {
-        int64_t lastEndTimeUs =
-                mTextVector.valueAt(mTextVector.size() - 1).endTimeUs;
-        if (seekTimeUs < 0) {
-            return ERROR_OUT_OF_RANGE;
-        } else if (seekTimeUs >= lastEndTimeUs) {
-            return ERROR_END_OF_STREAM;
-        } else {
-            // binary search
-            size_t low = 0;
-            size_t high = mTextVector.size() - 1;
-            size_t mid = 0;
-
-            while (low <= high) {
-                mid = low + (high - low)/2;
-                int diff = compareExtendedRangeAndTime(mid, seekTimeUs);
-                if (diff == 0) {
-                    break;
-                } else if (diff < 0) {
-                    low = mid + 1;
-                } else {
-                    high = mid - 1;
-                }
-            }
-            mIndex = mid;
-        }
-    }
-
-    if (mIndex >= mTextVector.size()) {
-        return ERROR_END_OF_STREAM;
-    }
-
-    const TextInfo &info = mTextVector.valueAt(mIndex);
-    *startTimeUs = mTextVector.keyAt(mIndex);
-    *endTimeUs = info.endTimeUs;
-    mIndex++;
-
-    char *str = new char[info.textLen];
-    if (mSource->readAt(info.offset, str, info.textLen) < info.textLen) {
-        delete[] str;
-        return ERROR_IO;
-    }
-    text->append(str, info.textLen);
-    delete[] str;
-    return OK;
-}
-
-status_t TimedTextSRTSource::extractAndAppendLocalDescriptions(
-        int64_t timeUs, const AString &text, Parcel *parcel) {
-    const void *data = text.c_str();
-    size_t size = text.size();
-    int32_t flag = TextDescriptions::LOCAL_DESCRIPTIONS |
-                   TextDescriptions::OUT_OF_BAND_TEXT_SRT;
-
-    if (size > 0) {
-        return TextDescriptions::getParcelOfDescriptions(
-                (const uint8_t *)data, size, flag, timeUs / 1000, parcel);
-    }
-    return OK;
-}
-
-int TimedTextSRTSource::compareExtendedRangeAndTime(size_t index, int64_t timeUs) {
-    CHECK_LT(index, mTextVector.size());
-    int64_t endTimeUs = mTextVector.valueAt(index).endTimeUs;
-    int64_t startTimeUs = (index > 0) ?
-            mTextVector.valueAt(index - 1).endTimeUs : 0;
-    if (timeUs >= startTimeUs && timeUs < endTimeUs) {
-        return 0;
-    } else if (endTimeUs <= timeUs) {
-        return -1;
-    } else {
-        return 1;
-    }
-}
-
-}  // namespace android
diff --git a/media/libstagefright/timedtext/TimedTextSRTSource.h b/media/libstagefright/timedtext/TimedTextSRTSource.h
deleted file mode 100644
index 232675e..0000000
--- a/media/libstagefright/timedtext/TimedTextSRTSource.h
+++ /dev/null
@@ -1,97 +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 TIMED_TEXT_SRT_SOURCE_H_
-#define TIMED_TEXT_SRT_SOURCE_H_
-
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MediaSource.h>
-#include <utils/Compat.h>  // off64_t
-
-#include "TimedTextSource.h"
-
-namespace android {
-
-struct AString;
-class DataSource;
-class MediaBuffer;
-class Parcel;
-
-class TimedTextSRTSource : public TimedTextSource {
-public:
-    TimedTextSRTSource(const sp<DataSource>& dataSource);
-    virtual status_t start();
-    virtual status_t stop();
-    virtual status_t read(
-            int64_t *startTimeUs,
-            int64_t *endTimeUs,
-            Parcel *parcel,
-            const MediaSource::ReadOptions *options = NULL);
-    virtual sp<MetaData> getFormat();
-
-protected:
-    virtual ~TimedTextSRTSource();
-
-private:
-    sp<DataSource> mSource;
-    sp<MetaData> mMetaData;
-
-    struct TextInfo {
-        int64_t endTimeUs;
-        // The offset of the text in the original file.
-        off64_t offset;
-        int textLen;
-    };
-
-    size_t mIndex;
-    KeyedVector<int64_t, TextInfo> mTextVector;
-
-    void reset();
-    status_t scanFile();
-    status_t getNextSubtitleInfo(
-            off64_t *offset, int64_t *startTimeUs, TextInfo *info);
-    status_t readNextLine(off64_t *offset, AString *data);
-    status_t getText(
-            const MediaSource::ReadOptions *options,
-            AString *text, int64_t *startTimeUs, int64_t *endTimeUs);
-    status_t extractAndAppendLocalDescriptions(
-            int64_t timeUs, const AString &text, Parcel *parcel);
-
-    // Compares the time range of the subtitle at index to the given timeUs.
-    // The time range of the subtitle to match with given timeUs is extended to
-    // [endTimeUs of the previous subtitle, endTimeUs of current subtitle).
-    //
-    // This compare function is used to find a next subtitle when read() is
-    // called with seek options. Note that timeUs within gap ranges, such as
-    // [200, 300) in the below example, will be matched to the closest future
-    // subtitle, [300, 400).
-    //
-    // For instance, assuming there are 3 subtitles in mTextVector,
-    // 0: [100, 200)      ----> [0, 200)
-    // 1: [300, 400)      ----> [200, 400)
-    // 2: [500, 600)      ----> [400, 600)
-    // If the 'index' parameter contains 1, this function
-    // returns 0, if timeUs is in [200, 400)
-    // returns -1, if timeUs >= 400,
-    // returns 1, if timeUs < 200.
-    int compareExtendedRangeAndTime(size_t index, int64_t timeUs);
-
-    DISALLOW_EVIL_CONSTRUCTORS(TimedTextSRTSource);
-};
-
-}  // namespace android
-
-#endif  // TIMED_TEXT_SRT_SOURCE_H_
diff --git a/media/libstagefright/timedtext/TimedTextSource.cpp b/media/libstagefright/timedtext/TimedTextSource.cpp
deleted file mode 100644
index 953f7b5..0000000
--- a/media/libstagefright/timedtext/TimedTextSource.cpp
+++ /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.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "TimedTextSource"
-#include <utils/Log.h>
-
-#include <media/stagefright/foundation/ADebug.h>  // CHECK_XX macro
-#include <media/stagefright/DataSource.h>
-#include <media/stagefright/MediaDefs.h>  // for MEDIA_MIMETYPE_xxx
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-
-#include "TimedTextSource.h"
-
-#include "TimedText3GPPSource.h"
-#include "TimedTextSRTSource.h"
-
-namespace android {
-
-// static
-sp<TimedTextSource> TimedTextSource::CreateTimedTextSource(
-        const sp<MediaSource>& mediaSource) {
-    const char *mime;
-    CHECK(mediaSource->getFormat()->findCString(kKeyMIMEType, &mime));
-    if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) == 0) {
-        return new TimedText3GPPSource(mediaSource);
-    }
-    ALOGE("Unsupported mime type for subtitle. : %s", mime);
-    return NULL;
-}
-
-// static
-sp<TimedTextSource> TimedTextSource::CreateTimedTextSource(
-        const sp<DataSource>& dataSource, FileType filetype) {
-    switch(filetype) {
-        case OUT_OF_BAND_FILE_SRT:
-            return new TimedTextSRTSource(dataSource);
-        case OUT_OF_BAND_FILE_SMI:
-            // TODO: Implement for SMI.
-            ALOGE("Supporting SMI is not implemented yet");
-            break;
-        default:
-            ALOGE("Undefined subtitle format. : %d", filetype);
-    }
-    return NULL;
-}
-
-sp<MetaData> TimedTextSource::getFormat() {
-    return NULL;
-}
-
-}  // namespace android
diff --git a/media/libstagefright/timedtext/TimedTextSource.h b/media/libstagefright/timedtext/TimedTextSource.h
deleted file mode 100644
index 8c1c1cd..0000000
--- a/media/libstagefright/timedtext/TimedTextSource.h
+++ /dev/null
@@ -1,64 +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 TIMED_TEXT_SOURCE_H_
-#define TIMED_TEXT_SOURCE_H_
-
-#include <media/stagefright/foundation/ABase.h>  // for DISALLOW_XXX macro.
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MediaSource.h>  // for MediaSource::ReadOptions
-#include <utils/RefBase.h>
-
-namespace android {
-
-class DataSource;
-class MetaData;
-class Parcel;
-
-class TimedTextSource : public RefBase {
- public:
-  enum FileType {
-      OUT_OF_BAND_FILE_SRT = 1,
-      OUT_OF_BAND_FILE_SMI = 2,
-  };
-  static sp<TimedTextSource> CreateTimedTextSource(
-      const sp<MediaSource>& source);
-  static sp<TimedTextSource> CreateTimedTextSource(
-      const sp<DataSource>& source, FileType filetype);
-  TimedTextSource() {}
-  virtual status_t start() = 0;
-  virtual status_t stop() = 0;
-  // Returns subtitle parcel and its start time.
-  virtual status_t read(
-          int64_t *startTimeUs,
-          int64_t *endTimeUs,
-          Parcel *parcel,
-          const MediaSource::ReadOptions *options = NULL) = 0;
-  virtual status_t extractGlobalDescriptions(Parcel * /* parcel */) {
-      return INVALID_OPERATION;
-  }
-  virtual sp<MetaData> getFormat();
-
- protected:
-  virtual ~TimedTextSource() { }
-
- private:
-  DISALLOW_EVIL_CONSTRUCTORS(TimedTextSource);
-};
-
-}  // namespace android
-
-#endif  // TIMED_TEXT_SOURCE_H_
diff --git a/media/libstagefright/timedtext/test/Android.mk b/media/libstagefright/timedtext/test/Android.mk
deleted file mode 100644
index e0e0e0d..0000000
--- a/media/libstagefright/timedtext/test/Android.mk
+++ /dev/null
@@ -1,32 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-# ================================================================
-# Unit tests for libstagefright_timedtext
-# ================================================================
-
-# ================================================================
-# A test for TimedTextSRTSource
-# ================================================================
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := TimedTextSRTSource_test
-
-LOCAL_MODULE_TAGS := eng tests
-
-LOCAL_SRC_FILES := TimedTextSRTSource_test.cpp
-
-LOCAL_C_INCLUDES := \
-    $(TOP)/external/expat/lib \
-    $(TOP)/frameworks/av/media/libstagefright/timedtext
-
-LOCAL_SHARED_LIBRARIES := \
-    libbinder \
-    libexpat \
-    libstagefright \
-    libstagefright_foundation \
-    libutils
-
-LOCAL_CFLAGS += -Werror -Wall
-LOCAL_CLANG := true
-
-include $(BUILD_NATIVE_TEST)
diff --git a/media/libstagefright/timedtext/test/TimedTextSRTSource_test.cpp b/media/libstagefright/timedtext/test/TimedTextSRTSource_test.cpp
deleted file mode 100644
index 211e732..0000000
--- a/media/libstagefright/timedtext/test/TimedTextSRTSource_test.cpp
+++ /dev/null
@@ -1,224 +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_TAG "TimedTextSRTSource_test"
-#include <utils/Log.h>
-
-#include <gtest/gtest.h>
-
-#include <binder/Parcel.h>
-#include <media/stagefright/foundation/AString.h>
-#include <media/stagefright/DataSource.h>
-#include <media/stagefright/MediaErrors.h>
-#include <utils/misc.h>
-
-#include <TimedTextSource.h>
-#include <TimedTextSRTSource.h>
-
-namespace android {
-namespace test {
-
-static const int kSecToUsec = 1000000;
-static const int kSecToMsec = 1000;
-static const int kMsecToUsec = 1000;
-
-/* SRT format (http://en.wikipedia.org/wiki/SubRip)
- *   Subtitle number
- *   Start time --> End time
- *   Text of subtitle (one or more lines)
- *   Blank lines
- */
-static const char *kSRTString =
-    "1\n00:00:1,000 --> 00:00:1,500\n1\n\n"
-    "2\n00:00:2,000 --> 00:00:2,500\n2\n\n"
-    "3\n00:00:3,000 --> 00:00:3,500\n3\n\n"
-    "4\n00:00:4,000 --> 00:00:4,500\n4\n\n"
-    "5\n00:00:5,000 --> 00:00:5,500\n5\n\n"
-    // edge case : previos end time = next start time
-    "6\n00:00:5,500 --> 00:00:5,800\n6\n\n"
-    "7\n00:00:5,800 --> 00:00:6,000\n7\n\n"
-    "8\n00:00:6,000 --> 00:00:7,000\n8\n\n";
-
-class SRTDataSourceStub : public DataSource {
-public:
-    SRTDataSourceStub(const char *data, size_t size) :
-        mData(data), mSize(size) {}
-    virtual ~SRTDataSourceStub() {}
-
-    virtual status_t initCheck() const {
-        return OK;
-    }
-
-    virtual ssize_t readAt(off64_t offset, void *data, size_t size) {
-        if ((size_t)offset >= mSize) return 0;
-
-        ssize_t avail = mSize - offset;
-        if ((size_t)avail > size) {
-            avail = size;
-        }
-        memcpy(data, mData + offset, avail);
-        return avail;
-    }
-
-private:
-    const char *mData;
-    size_t mSize;
-};
-
-class TimedTextSRTSourceTest : public testing::Test {
-protected:
-    void SetUp() {
-        sp<DataSource> stub= new SRTDataSourceStub(
-                kSRTString,
-                strlen(kSRTString));
-        mSource = new TimedTextSRTSource(stub);
-        mSource->start();
-    }
-
-    void CheckStartTimeMs(const Parcel& parcel, int32_t timeMs) {
-        int32_t intval;
-        parcel.setDataPosition(8);
-        parcel.readInt32(&intval);
-        EXPECT_EQ(timeMs, intval);
-    }
-
-    void CheckDataEquals(const Parcel& parcel, const char* content) {
-        int32_t intval;
-        parcel.setDataPosition(16);
-        parcel.readInt32(&intval);
-        parcel.setDataPosition(24);
-        const char* data = (const char*) parcel.readInplace(intval);
-
-        int32_t content_len = strlen(content);
-        EXPECT_EQ(content_len, intval);
-        EXPECT_TRUE(strncmp(data, content, content_len) == 0);
-    }
-
-    sp<TimedTextSource> mSource;
-    int64_t startTimeUs;
-    int64_t endTimeUs;
-    Parcel parcel;
-    AString subtitle;
-    status_t err;
-};
-
-TEST_F(TimedTextSRTSourceTest, readAll) {
-    for (int i = 1; i <= 5; i++) {
-        err = mSource->read(&startTimeUs, &endTimeUs, &parcel);
-        EXPECT_EQ(OK, err);
-        CheckStartTimeMs(parcel, i * kSecToMsec);
-        subtitle = AStringPrintf("%d\n\n", i);
-        CheckDataEquals(parcel, subtitle.c_str());
-    }
-    // read edge cases
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel);
-    EXPECT_EQ(OK, err);
-    CheckStartTimeMs(parcel, 5500);
-    subtitle = AStringPrintf("6\n\n");
-    CheckDataEquals(parcel, subtitle.c_str());
-
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel);
-    EXPECT_EQ(OK, err);
-    CheckStartTimeMs(parcel, 5800);
-    subtitle = AStringPrintf("7\n\n");
-    CheckDataEquals(parcel, subtitle.c_str());
-
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel);
-    EXPECT_EQ(OK, err);
-    CheckStartTimeMs(parcel, 6000);
-    subtitle = AStringPrintf("8\n\n");
-    CheckDataEquals(parcel, subtitle.c_str());
-
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel);
-    EXPECT_EQ(ERROR_END_OF_STREAM, err);
-}
-
-TEST_F(TimedTextSRTSourceTest, seekTimeIsEarlierThanFirst) {
-    MediaSource::ReadOptions options;
-    options.setSeekTo(500, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-    EXPECT_EQ(OK, err);
-    EXPECT_EQ(1 * kSecToUsec, startTimeUs);
-    CheckStartTimeMs(parcel, 1 * kSecToMsec);
-}
-
-TEST_F(TimedTextSRTSourceTest, seekTimeIsLaterThanLast) {
-    MediaSource::ReadOptions options;
-    options.setSeekTo(7 * kSecToUsec, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-    EXPECT_EQ(ERROR_END_OF_STREAM, err);
-
-    options.setSeekTo(8 * kSecToUsec, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-    EXPECT_EQ(ERROR_END_OF_STREAM, err);
-}
-
-TEST_F(TimedTextSRTSourceTest, seekTimeIsMatched) {
-    for (int i = 1; i <= 5; i++) {
-        MediaSource::ReadOptions options;
-        options.setSeekTo(i * kSecToUsec, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-        err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-        EXPECT_EQ(OK, err);
-        EXPECT_EQ(i * kSecToUsec, startTimeUs);
-
-        options.setSeekTo(i * kSecToUsec + 100, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-        err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-        EXPECT_EQ(OK, err);
-        EXPECT_EQ(i * kSecToUsec, startTimeUs);
-    }
-}
-
-TEST_F(TimedTextSRTSourceTest, seekTimeInBetweenTwo) {
-    for (int i = 1; i <= 4; i++) {
-        MediaSource::ReadOptions options;
-        options.setSeekTo(i * kSecToUsec + 500000, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-        err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-        EXPECT_EQ(OK, err);
-        EXPECT_EQ((i + 1) * kSecToUsec, startTimeUs);
-
-        options.setSeekTo(i * kSecToUsec + 600000, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-        err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-        EXPECT_EQ(OK, err);
-        EXPECT_EQ((i + 1) * kSecToUsec, startTimeUs);
-    }
-}
-
-TEST_F(TimedTextSRTSourceTest, checkEdgeCase) {
-    MediaSource::ReadOptions options;
-    options.setSeekTo(5500 * kMsecToUsec, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-    EXPECT_EQ(OK, err);
-    EXPECT_EQ(5500 * kMsecToUsec, startTimeUs);
-    subtitle = AStringPrintf("6\n\n");
-    CheckDataEquals(parcel, subtitle.c_str());
-
-    options.setSeekTo(5800 * kMsecToUsec, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-    EXPECT_EQ(OK, err);
-    EXPECT_EQ(5800 * kMsecToUsec, startTimeUs);
-    subtitle = AStringPrintf("7\n\n");
-    CheckDataEquals(parcel, subtitle.c_str());
-
-    options.setSeekTo(6000 * kMsecToUsec, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
-    err = mSource->read(&startTimeUs, &endTimeUs, &parcel, &options);
-    EXPECT_EQ(OK, err);
-    EXPECT_EQ(6000 * kMsecToUsec, startTimeUs);
-    subtitle = AStringPrintf("8\n\n");
-    CheckDataEquals(parcel, subtitle.c_str());
-}
-
-}  // namespace test
-}  // namespace android
diff --git a/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp b/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp
index e26165e..f0a4ded 100644
--- a/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp
+++ b/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp
@@ -782,7 +782,7 @@
             return;
         }
 
-        char *commaPos = strchr(s, ',');
+        const char *commaPos = strchr(s, ',');
         if (commaPos != NULL) {
             s = commaPos + 1;
 
@@ -1669,7 +1669,7 @@
 }
 
 struct WifiDisplaySource::HDCPObserver : public BnHDCPObserver {
-    HDCPObserver(const sp<AMessage> &notify);
+    explicit HDCPObserver(const sp<AMessage> &notify);
 
     virtual void notify(
             int msg, int ext1, int ext2, const Parcel *obj);
diff --git a/media/mediaserver/main_mediaserver.cpp b/media/mediaserver/main_mediaserver.cpp
index 4a485ed..315aff4 100644
--- a/media/mediaserver/main_mediaserver.cpp
+++ b/media/mediaserver/main_mediaserver.cpp
@@ -125,7 +125,11 @@
             prctl(PR_SET_PDEATHSIG, SIGKILL);   // if parent media.log dies before me, kill me also
             setpgid(0, 0);                      // but if I die first, don't kill my parent
         }
+#ifndef __BRILLO__
+        // Brillo is headless and very resource constrained. As such, it doesn't
+        // need an internationalization library for now.
         InitializeIcuOrDie();
+#endif
         sp<ProcessState> proc(ProcessState::self());
         sp<IServiceManager> sm = defaultServiceManager();
         ALOGI("ServiceManager: %p", sm.get());
diff --git a/media/mtp/MtpUtils.cpp b/media/mtp/MtpUtils.cpp
index 0667bdd..ebf3601 100644
--- a/media/mtp/MtpUtils.cpp
+++ b/media/mtp/MtpUtils.cpp
@@ -19,8 +19,6 @@
 #include <stdio.h>
 #include <time.h>
 
-#include <../private/bionic_time.h> /* TODO: switch this code to icu4c! */
-
 #include "MtpUtils.h"
 
 namespace android {
@@ -32,38 +30,40 @@
 DD replaced by the day (01-31), T is a constant character 'T' delimiting time from date,
 hh is replaced by the hour (00-23), mm is replaced by the minute (00-59), and ss by the
 second (00-59). The ".s" is optional, and represents tenths of a second.
+This is followed by a UTC offset given as "[+-]zzzz" or the literal "Z", meaning UTC.
 */
 
 bool parseDateTime(const char* dateTime, time_t& outSeconds) {
     int year, month, day, hour, minute, second;
-    struct tm tm;
-
     if (sscanf(dateTime, "%04d%02d%02dT%02d%02d%02d",
-            &year, &month, &day, &hour, &minute, &second) != 6)
+               &year, &month, &day, &hour, &minute, &second) != 6)
         return false;
-    const char* tail = dateTime + 15;
+
     // skip optional tenth of second
-    if (tail[0] == '.' && tail[1])
-        tail += 2;
-    //FIXME - support +/-hhmm
+    const char* tail = dateTime + 15;
+    if (tail[0] == '.' && tail[1]) tail += 2;
+
+    // FIXME: "Z" means UTC, but non-"Z" doesn't mean local time.
+    // It might be that you're in Asia/Seoul on vacation and your Android
+    // device has noticed this via the network, but your camera was set to
+    // America/Los_Angeles once when you bought it and doesn't know where
+    // it is right now, so the camera says "20160106T081700-0800" but we
+    // just ignore the "-0800" and assume local time which is actually "+0900".
+    // I think to support this (without switching to Java or using icu4c)
+    // you'd want to always use timegm(3) and then manually add/subtract
+    // the UTC offset parsed from the string (taking care of wrapping).
+    // mktime(3) ignores the tm_gmtoff field, so you can't let it do the work.
     bool useUTC = (tail[0] == 'Z');
 
-    // hack to compute timezone
-    time_t dummy;
-    localtime_r(&dummy, &tm);
-
+    struct tm tm = {};
     tm.tm_sec = second;
     tm.tm_min = minute;
     tm.tm_hour = hour;
     tm.tm_mday = day;
     tm.tm_mon = month - 1;  // mktime uses months in 0 - 11 range
     tm.tm_year = year - 1900;
-    tm.tm_wday = 0;
     tm.tm_isdst = -1;
-    if (useUTC)
-        outSeconds = mktime(&tm);
-    else
-        outSeconds = mktime_tz(&tm, tm.tm_zone);
+    outSeconds = useUTC ? timegm(&tm) : mktime(&tm);
 
     return true;
 }
@@ -73,7 +73,7 @@
 
     localtime_r(&seconds, &tm);
     snprintf(buffer, bufferLength, "%04d%02d%02dT%02d%02d%02d",
-        tm.tm_year + 1900, 
+        tm.tm_year + 1900,
         tm.tm_mon + 1, // localtime_r uses months in 0 - 11 range
         tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
 }
diff --git a/media/ndk/NdkMediaCodec.cpp b/media/ndk/NdkMediaCodec.cpp
index cd0c462..e954ed5 100644
--- a/media/ndk/NdkMediaCodec.cpp
+++ b/media/ndk/NdkMediaCodec.cpp
@@ -59,7 +59,7 @@
 private:
     AMediaCodec* mCodec;
 public:
-    CodecHandler(AMediaCodec *codec);
+    explicit CodecHandler(AMediaCodec *codec);
     virtual void onMessageReceived(const sp<AMessage> &msg);
 };
 
diff --git a/media/utils/Android.mk b/media/utils/Android.mk
index dfadbc8..54d22b1 100644
--- a/media/utils/Android.mk
+++ b/media/utils/Android.mk
@@ -18,6 +18,8 @@
 
 LOCAL_SRC_FILES := \
   BatteryNotifier.cpp \
+  ISchedulingPolicyService.cpp \
+  SchedulingPolicyService.cpp
 
 LOCAL_SHARED_LIBRARIES := \
   libbinder \
diff --git a/services/audioflinger/ISchedulingPolicyService.cpp b/media/utils/ISchedulingPolicyService.cpp
similarity index 97%
rename from services/audioflinger/ISchedulingPolicyService.cpp
rename to media/utils/ISchedulingPolicyService.cpp
index f55bc02..f5bfe20 100644
--- a/services/audioflinger/ISchedulingPolicyService.cpp
+++ b/media/utils/ISchedulingPolicyService.cpp
@@ -32,7 +32,7 @@
 class BpSchedulingPolicyService : public BpInterface<ISchedulingPolicyService>
 {
 public:
-    BpSchedulingPolicyService(const sp<IBinder>& impl)
+    explicit BpSchedulingPolicyService(const sp<IBinder>& impl)
         : BpInterface<ISchedulingPolicyService>(impl)
     {
     }
diff --git a/services/audioflinger/ISchedulingPolicyService.h b/media/utils/ISchedulingPolicyService.h
similarity index 100%
rename from services/audioflinger/ISchedulingPolicyService.h
rename to media/utils/ISchedulingPolicyService.h
diff --git a/services/audioflinger/SchedulingPolicyService.cpp b/media/utils/SchedulingPolicyService.cpp
similarity index 97%
rename from services/audioflinger/SchedulingPolicyService.cpp
rename to media/utils/SchedulingPolicyService.cpp
index 70a3f1a..17ee9bc 100644
--- a/services/audioflinger/SchedulingPolicyService.cpp
+++ b/media/utils/SchedulingPolicyService.cpp
@@ -20,7 +20,7 @@
 #include <binder/IServiceManager.h>
 #include <utils/Mutex.h>
 #include "ISchedulingPolicyService.h"
-#include "SchedulingPolicyService.h"
+#include "mediautils/SchedulingPolicyService.h"
 
 namespace android {
 
diff --git a/services/audioflinger/SchedulingPolicyService.h b/media/utils/include/mediautils/SchedulingPolicyService.h
similarity index 100%
rename from services/audioflinger/SchedulingPolicyService.h
rename to media/utils/include/mediautils/SchedulingPolicyService.h
diff --git a/radio/IRadio.cpp b/radio/IRadio.cpp
index 242df77..0881a91 100644
--- a/radio/IRadio.cpp
+++ b/radio/IRadio.cpp
@@ -44,7 +44,7 @@
 class BpRadio: public BpInterface<IRadio>
 {
 public:
-    BpRadio(const sp<IBinder>& impl)
+    explicit BpRadio(const sp<IBinder>& impl)
         : BpInterface<IRadio>(impl)
     {
     }
diff --git a/radio/IRadioClient.cpp b/radio/IRadioClient.cpp
index 033ca49..ca21949 100644
--- a/radio/IRadioClient.cpp
+++ b/radio/IRadioClient.cpp
@@ -33,7 +33,7 @@
 {
 
 public:
-    BpRadioClient(const sp<IBinder>& impl)
+    explicit BpRadioClient(const sp<IBinder>& impl)
         : BpInterface<IRadioClient>(impl)
     {
     }
diff --git a/radio/IRadioService.cpp b/radio/IRadioService.cpp
index 8c2b3ef..341fb33 100644
--- a/radio/IRadioService.cpp
+++ b/radio/IRadioService.cpp
@@ -45,7 +45,7 @@
 class BpRadioService: public BpInterface<IRadioService>
 {
 public:
-    BpRadioService(const sp<IBinder>& impl)
+    explicit BpRadioService(const sp<IBinder>& impl)
         : BpInterface<IRadioService>(impl)
     {
     }
diff --git a/services/audioflinger/Android.mk b/services/audioflinger/Android.mk
index debcdf9..9b4ba79 100644
--- a/services/audioflinger/Android.mk
+++ b/services/audioflinger/Android.mk
@@ -3,17 +3,6 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := \
-    ISchedulingPolicyService.cpp \
-    SchedulingPolicyService.cpp
-
-# FIXME Move this library to frameworks/native
-LOCAL_MODULE := libscheduling_policy
-
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := \
     ServiceUtilities.cpp
 
 # FIXME Move this library to frameworks/native
@@ -64,10 +53,10 @@
     libeffects \
     libpowermanager \
     libserviceutility \
-    libsonic
+    libsonic \
+    libmediautils
 
 LOCAL_STATIC_LIBRARIES := \
-    libscheduling_policy \
     libcpustats \
     libmedia_helper
 
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 9ec5802..b85b649 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -1352,12 +1352,20 @@
 AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
     :   RefBase(),
         mAudioFlinger(audioFlinger),
-        // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
-        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
         mPid(pid),
         mTimedTrackCount(0)
 {
-    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
+    size_t heapSize = property_get_int32("ro.af.client_heap_size_kbyte", 0);
+    heapSize *= 1024;
+    if (!heapSize) {
+        heapSize = kClientSharedHeapSizeBytes;
+        // Increase heap size on non low ram devices to limit risk of reconnection failure for
+        // invalidated tracks
+        if (!audioFlinger->isLowRamDevice()) {
+            heapSize *= kClientSharedHeapSizeMultiplier;
+        }
+    }
+    mMemoryDealer = new MemoryDealer(heapSize, "AudioFlinger::Client");
 }
 
 // Client destructor must be called with AudioFlinger::mClientLock held
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index 20c34ef..08fa70d 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -88,6 +88,12 @@
 
 static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
 
+
+// Max shared memory size for audio tracks and audio records per client process
+static const size_t kClientSharedHeapSizeBytes = 1024*1024;
+// Shared memory size multiplier for non low ram devices
+static const size_t kClientSharedHeapSizeMultiplier = 4;
+
 #define INCLUDING_FROM_AUDIOFLINGER_H
 
 class AudioFlinger :
@@ -423,7 +429,7 @@
                             Client(const Client&);
                             Client& operator = (const Client&);
         const sp<AudioFlinger> mAudioFlinger;
-        const sp<MemoryDealer> mMemoryDealer;
+              sp<MemoryDealer> mMemoryDealer;
         const pid_t         mPid;
 
         Mutex               mTimedTrackLock;
diff --git a/services/audioflinger/AudioMixer.cpp b/services/audioflinger/AudioMixer.cpp
index 8a9a837..d84cf63 100644
--- a/services/audioflinger/AudioMixer.cpp
+++ b/services/audioflinger/AudioMixer.cpp
@@ -1704,8 +1704,8 @@
 
 // Needs to derive a compile time constant (constexpr).  Could be targeted to go
 // to a MONOVOL mixtype based on MAX_NUM_VOLUMES, but that's an unnecessary complication.
-#define MIXTYPE_MONOVOL(mixtype) (mixtype == MIXTYPE_MULTI ? MIXTYPE_MULTI_MONOVOL : \
-        mixtype == MIXTYPE_MULTI_SAVEONLY ? MIXTYPE_MULTI_SAVEONLY_MONOVOL : mixtype)
+#define MIXTYPE_MONOVOL(mixtype) ((mixtype) == MIXTYPE_MULTI ? MIXTYPE_MULTI_MONOVOL : \
+        (mixtype) == MIXTYPE_MULTI_SAVEONLY ? MIXTYPE_MULTI_SAVEONLY_MONOVOL : (mixtype))
 
 /* MIXTYPE     (see AudioMixerOps.h MIXTYPE_* enumeration)
  * TO: int32_t (Q4.27) or float
diff --git a/services/audioflinger/FastCapture.cpp b/services/audioflinger/FastCapture.cpp
index 79ac12b..1bba5f6 100644
--- a/services/audioflinger/FastCapture.cpp
+++ b/services/audioflinger/FastCapture.cpp
@@ -131,7 +131,9 @@
             // FIXME new may block for unbounded time at internal mutex of the heap
             //       implementation; it would be better to have normal capture thread allocate for
             //       us to avoid blocking here and to prevent possible priority inversion
-            (void)posix_memalign(&mReadBuffer, 32, frameCount * Format_frameSize(mFormat));
+            size_t bufferSize = frameCount * Format_frameSize(mFormat);
+            (void)posix_memalign(&mReadBuffer, 32, bufferSize);
+            memset(mReadBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
             mPeriodNs = (frameCount * 1000000000LL) / mSampleRate;      // 1.00
             mUnderrunNs = (frameCount * 1750000000LL) / mSampleRate;    // 1.75
             mOverrunNs = (frameCount * 500000000LL) / mSampleRate;      // 0.50
diff --git a/services/audioflinger/FastMixer.cpp b/services/audioflinger/FastMixer.cpp
index 45c68b5..2bc8066 100644
--- a/services/audioflinger/FastMixer.cpp
+++ b/services/audioflinger/FastMixer.cpp
@@ -334,6 +334,11 @@
 
     if ((command & FastMixerState::MIX) && (mMixer != NULL) && mIsWarm) {
         ALOG_ASSERT(mMixerBuffer != NULL);
+
+        // AudioMixer::mState.enabledTracks is undefined if mState.hook == process__validate,
+        // so we keep a side copy of enabledTracks
+        bool anyEnabledTracks = false;
+
         // for each track, update volume and check for underrun
         unsigned currentTrackMask = current->mTrackMask;
         while (currentTrackMask != 0) {
@@ -392,11 +397,13 @@
                     underruns.mBitFields.mPartial++;
                     underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
                     mMixer->enable(name);
+                    anyEnabledTracks = true;
                 }
             } else {
                 underruns.mBitFields.mFull++;
                 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
                 mMixer->enable(name);
+                anyEnabledTracks = true;
             }
             ftDump->mUnderruns = underruns;
             ftDump->mFramesReady = framesReady;
@@ -407,9 +414,14 @@
             pts = AudioBufferProvider::kInvalidPTS;
         }
 
-        // process() is CPU-bound
-        mMixer->process(pts);
-        mMixerBufferState = MIXED;
+        if (anyEnabledTracks) {
+            // process() is CPU-bound
+            mMixer->process(pts);
+            mMixerBufferState = MIXED;
+        } else if (mMixerBufferState != ZEROED) {
+            mMixerBufferState = UNDEFINED;
+        }
+
     } else if (mMixerBufferState == MIXED) {
         mMixerBufferState = UNDEFINED;
     }
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index 0a7d4a2..595c543 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -60,7 +60,7 @@
 #include "FastMixer.h"
 #include "FastCapture.h"
 #include "ServiceUtilities.h"
-#include "SchedulingPolicyService.h"
+#include "mediautils/SchedulingPolicyService.h"
 
 #ifdef ADD_BATTERY_DATA
 #include <media/IMediaPlayerService.h>
@@ -96,7 +96,7 @@
 }
 
 #ifndef ARRAY_SIZE
-#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
 #endif
 
 namespace android {
@@ -1589,6 +1589,7 @@
     dprintf(fd, "  Mixer buffer: %p\n", mMixerBuffer);
     dprintf(fd, "  Effect buffer: %p\n", mEffectBuffer);
     dprintf(fd, "  Fast track availMask=%#x\n", mFastTrackAvailMask);
+    dprintf(fd, "  Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
     AudioStreamOut *output = mOutput;
     audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
     String8 flagsAsString = outputFlagsToString(flags);
@@ -2513,7 +2514,8 @@
  - mSinkBufferSize from frame count * frame size
  - mActiveSleepTimeUs from activeSleepTimeUs()
  - mIdleSleepTimeUs from idleSleepTimeUs()
- - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only)
+ - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
+   kDefaultStandbyTimeInNsecs when connected to an A2DP device.
  - maxPeriod from frame count and sample rate (MIXER only)
 
 The parameters that affect these derived values are:
@@ -2532,6 +2534,15 @@
     mSinkBufferSize = mNormalFrameCount * mFrameSize;
     mActiveSleepTimeUs = activeSleepTimeUs();
     mIdleSleepTimeUs = idleSleepTimeUs();
+
+    // make sure standby delay is not too short when connected to an A2DP sink to avoid
+    // truncating audio when going to standby.
+    mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
+    if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
+        if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
+            mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
+        }
+    }
 }
 
 void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
@@ -3479,6 +3490,12 @@
         if (state->mCommand != FastMixerState::MIX_WRITE &&
                 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
             if (state->mCommand == FastMixerState::COLD_IDLE) {
+
+                // FIXME workaround for first HAL write being CPU bound on some devices
+                ATRACE_BEGIN("write");
+                mOutput->write((char *)mSinkBuffer, 0);
+                ATRACE_END();
+
                 int32_t old = android_atomic_inc(&mFastMixerFutex);
                 if (old == -1) {
                     (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
@@ -4242,6 +4259,7 @@
                                                        status_t& status)
 {
     bool reconfig = false;
+    bool a2dpDeviceChanged = false;
 
     status = NO_ERROR;
 
@@ -4318,6 +4336,8 @@
         // forward device change to effects that have requested to be
         // aware of attached audio device.
         if (value != AUDIO_DEVICE_NONE) {
+            a2dpDeviceChanged =
+                    (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
             mOutDevice = value;
             for (size_t i = 0; i < mEffectChains.size(); i++) {
                 mEffectChains[i]->setDevice_l(mOutDevice);
@@ -4361,7 +4381,7 @@
         sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
     }
 
-    return reconfig;
+    return reconfig || a2dpDeviceChanged;
 }
 
 
@@ -4797,6 +4817,7 @@
                                                               status_t& status)
 {
     bool reconfig = false;
+    bool a2dpDeviceChanged = false;
 
     status = NO_ERROR;
 
@@ -4806,6 +4827,8 @@
         // forward device change to effects that have requested to be
         // aware of attached audio device.
         if (value != AUDIO_DEVICE_NONE) {
+            a2dpDeviceChanged =
+                    (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
             mOutDevice = value;
             for (size_t i = 0; i < mEffectChains.size(); i++) {
                 mEffectChains[i]->setDevice_l(mOutDevice);
@@ -4838,7 +4861,7 @@
         }
     }
 
-    return reconfig;
+    return reconfig || a2dpDeviceChanged;
 }
 
 uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
@@ -6926,6 +6949,7 @@
     mRsmpInFrames = mFrameCount * 7;
     mRsmpInFramesP2 = roundup(mRsmpInFrames);
     free(mRsmpInBuffer);
+    mRsmpInBuffer = NULL;
 
     // TODO optimize audio capture buffer sizes ...
     // Here we calculate the size of the sliding buffer used as a source
@@ -6935,7 +6959,9 @@
     // The current value is higher than necessary.  However it should not add to latency.
 
     // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
-    (void)posix_memalign(&mRsmpInBuffer, 32, (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize);
+    size_t bufferSize = (mRsmpInFramesP2 + mFrameCount - 1) * mFrameSize;
+    (void)posix_memalign(&mRsmpInBuffer, 32, bufferSize);
+    memset(mRsmpInBuffer, 0, bufferSize); // if posix_memalign fails, will segv here.
 
     // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
     // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index f7da209..0e24b52 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -432,7 +432,10 @@
     }
     // only allocate a fast track index if we were able to allocate a normal track name
     if (flags & IAudioFlinger::TRACK_FAST) {
-        mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
+        // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
+        // race with setSyncEvent(). However, if we call it, we cannot properly start
+        // static fast tracks (SoundPool) immediately after stopping.
+        //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
         ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
         int i = __builtin_ctz(thread->mFastTrackAvailMask);
         ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
@@ -712,6 +715,7 @@
             // But in this case we know the mixer thread (whether normal mixer or fast mixer)
             // isn't looking at this track yet:  we still hold the normal mixer thread lock,
             // and for fast tracks the track is not yet in the fast mixer thread's active set.
+            // For static tracks, this is used to acknowledge change in position or loop.
             ServerProxy::Buffer buffer;
             buffer.mFrameCount = 1;
             (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
diff --git a/services/audiopolicy/common/managerdefinitions/Android.mk b/services/audiopolicy/common/managerdefinitions/Android.mk
index 8728ff3..e608e64 100644
--- a/services/audiopolicy/common/managerdefinitions/Android.mk
+++ b/services/audiopolicy/common/managerdefinitions/Android.mk
@@ -20,9 +20,12 @@
 
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
+    libmedia \
     libutils \
     liblog \
 
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libmedia
+
 LOCAL_C_INCLUDES += \
     $(LOCAL_PATH)/include \
     $(TOPDIR)frameworks/av/services/audiopolicy/common/include \
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioInputDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/AudioInputDescriptor.h
index 18bcfdb..48d09ed 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioInputDescriptor.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioInputDescriptor.h
@@ -56,9 +56,21 @@
             const struct audio_port_config *srcConfig = NULL) const;
     virtual sp<AudioPort> getAudioPort() const { return mProfile; }
     void toAudioPort(struct audio_port *port) const;
+    void setPreemptedSessions(const SortedVector<audio_session_t>& sessions);
+    SortedVector<audio_session_t> getPreemptedSessions() const;
+    bool hasPreemptedSession(audio_session_t session) const;
+    void clearPreemptedSessions();
 
 private:
     audio_port_handle_t           mId;
+    // Because a preemtible capture session can preempt another one, we end up in an endless loop
+    // situation were each session is allowed to restart after being preempted,
+    // thus preempting the other one which restarts and so on.
+    // To avoid this situation, we store which audio session was preempted when
+    // a particular input started and prevent preemption of this active input by this session.
+    // We also inherit sessions from the preempted input to avoid a 3 way preemption loop etc...
+    SortedVector<audio_session_t> mPreemptedSessions;
+
 };
 
 class AudioInputCollection :
diff --git a/services/audiopolicy/common/managerdefinitions/include/ConfigParsingUtils.h b/services/audiopolicy/common/managerdefinitions/include/ConfigParsingUtils.h
index 78d2cdf..6f4bc70 100644
--- a/services/audiopolicy/common/managerdefinitions/include/ConfigParsingUtils.h
+++ b/services/audiopolicy/common/managerdefinitions/include/ConfigParsingUtils.h
@@ -39,7 +39,7 @@
 };
 
 // TODO: move to a separate file. Should be in sync with audio.h.
-#define STRING_TO_ENUM(string) { #string, (uint32_t)string } // uint32_t cast removes warning
+#define STRING_TO_ENUM(string) { #string, (uint32_t)(string) } // uint32_t cast removes warning
 #define NAME_TO_ENUM(name, value) { name, value }
 #ifndef ARRAY_SIZE
 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp
index 937160b..626fdae 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp
@@ -93,6 +93,26 @@
     port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
 }
 
+void AudioInputDescriptor::setPreemptedSessions(const SortedVector<audio_session_t>& sessions)
+{
+    mPreemptedSessions = sessions;
+}
+
+SortedVector<audio_session_t> AudioInputDescriptor::getPreemptedSessions() const
+{
+    return mPreemptedSessions;
+}
+
+bool AudioInputDescriptor::hasPreemptedSession(audio_session_t session) const
+{
+    return (mPreemptedSessions.indexOf(session) >= 0);
+}
+
+void AudioInputDescriptor::clearPreemptedSessions()
+{
+    mPreemptedSessions.clear();
+}
+
 status_t AudioInputDescriptor::dump(int fd)
 {
     const size_t SIZE = 256;
diff --git a/services/audiopolicy/common/managerdefinitions/src/StreamDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/StreamDescriptor.cpp
index b682e2c..4ca27c2 100644
--- a/services/audiopolicy/common/managerdefinitions/src/StreamDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/StreamDescriptor.cpp
@@ -35,7 +35,10 @@
 StreamDescriptor::StreamDescriptor()
     :   mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
 {
-    mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
+    // Initialize the current stream's index to mIndexMax so volume isn't 0 in
+    // cases where the Java layer doesn't call into the audio policy service to
+    // set the default volume.
+    mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, mIndexMax);
 }
 
 int StreamDescriptor::getVolumeIndex(audio_devices_t device) const
diff --git a/services/audiopolicy/engineconfigurable/src/Stream.cpp b/services/audiopolicy/engineconfigurable/src/Stream.cpp
index bea2c19..a929435 100755
--- a/services/audiopolicy/engineconfigurable/src/Stream.cpp
+++ b/services/audiopolicy/engineconfigurable/src/Stream.cpp
@@ -98,13 +98,13 @@
     if (it == mVolumeProfiles.end()) {
         ALOGE("%s: device category %d not found for stream %s", __FUNCTION__, deviceCategory,
               getName().c_str());
-        return 1.0f;
+        return 0.0f;
     }
     const VolumeCurvePoints curve = mVolumeProfiles[deviceCategory];
     if (curve.size() != Volume::VOLCNT) {
         ALOGE("%s: invalid profile for category %d and for stream %s", __FUNCTION__, deviceCategory,
               getName().c_str());
-        return 1.0f;
+        return 0.0f;
     }
 
     // the volume index in the UI is relative to the min and max volume indices for this stream type
@@ -113,7 +113,7 @@
 
     if (mIndexMax - mIndexMin == 0) {
         ALOGE("%s: Invalid volume indexes Min=Max=%d", __FUNCTION__, mIndexMin);
-        return 1.0f;
+        return 0.0f;
     }
     int volIdx = (nbSteps * (indexInUi - mIndexMin)) /
             (mIndexMax - mIndexMin);
@@ -121,7 +121,7 @@
     // find what part of the curve this index volume belongs to, or if it's out of bounds
     int segment = 0;
     if (volIdx < curve[Volume::VOLMIN].mIndex) {         // out of bounds
-        return 0.0f;
+        return VOLUME_MIN_DB;
     } else if (volIdx < curve[Volume::VOLKNEE1].mIndex) {
         segment = 0;
     } else if (volIdx < curve[Volume::VOLKNEE2].mIndex) {
@@ -129,7 +129,7 @@
     } else if (volIdx <= curve[Volume::VOLMAX].mIndex) {
         segment = 2;
     } else {                                                               // out of bounds
-        return 1.0f;
+        return 0.0f;
     }
 
     // linear interpolation in the attenuation table in dB
diff --git a/services/audiopolicy/enginedefault/Android.mk b/services/audiopolicy/enginedefault/Android.mk
index 8d43b89..ba9b50a 100755
--- a/services/audiopolicy/enginedefault/Android.mk
+++ b/services/audiopolicy/enginedefault/Android.mk
@@ -39,6 +39,7 @@
     libaudiopolicycomponents
 
 LOCAL_SHARED_LIBRARIES += \
+    liblog \
     libcutils \
     libutils \
     libaudioutils \
diff --git a/services/audiopolicy/enginedefault/src/Gains.cpp b/services/audiopolicy/enginedefault/src/Gains.cpp
index 78f2909..d06365c 100644
--- a/services/audiopolicy/enginedefault/src/Gains.cpp
+++ b/services/audiopolicy/enginedefault/src/Gains.cpp
@@ -171,10 +171,10 @@
     },
     { // AUDIO_STREAM_TTS
       // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
-        Gains::sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
-        Gains::sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
-        Gains::sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
-        Gains::sSilentVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
+        Gains::sSilentVolumeCurve,    // DEVICE_CATEGORY_HEADSET
+        Gains::sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
+        Gains::sSilentVolumeCurve,    // DEVICE_CATEGORY_EARPIECE
+        Gains::sSilentVolumeCurve     // DEVICE_CATEGORY_EXT_MEDIA
     },
     { // AUDIO_STREAM_ACCESSIBILITY
         Gains::sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index e7f6864..d6e3c16 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -55,6 +55,17 @@
     return setDeviceConnectionStateInt(device, state, device_address, device_name);
 }
 
+void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
+                                                        audio_policy_dev_state_t state,
+                                                        const String8 &device_address)
+{
+    AudioParameter param(device_address);
+    const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
+                AUDIO_PARAMETER_DEVICE_CONNECT : AUDIO_PARAMETER_DEVICE_DISCONNECT);
+    param.addInt(key, device);
+    mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
+}
+
 status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
                                                          audio_policy_dev_state_t state,
                                                          const char *device_address,
@@ -103,8 +114,15 @@
                 return NO_MEMORY;
             }
 
+            // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
+            // parameters on newly connected devices (instead of opening the outputs...)
+            broadcastDeviceConnectionState(device, state, devDesc->mAddress);
+
             if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
                 mAvailableOutputDevices.remove(devDesc);
+
+                broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
+                                               devDesc->mAddress);
                 return INVALID_OPERATION;
             }
             // Propagate device availability to Engine
@@ -116,11 +134,6 @@
             ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
                   outputs.size());
 
-            // Send connect to HALs
-            AudioParameter param = AudioParameter(devDesc->mAddress);
-            param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
-            mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
-
             } break;
         // handle output device disconnection
         case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
@@ -132,9 +145,7 @@
             ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
 
             // Send Disconnect to HALs
-            AudioParameter param = AudioParameter(devDesc->mAddress);
-            param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
-            mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
+            broadcastDeviceConnectionState(device, state, devDesc->mAddress);
 
             // remove device from available output devices
             mAvailableOutputDevices.remove(devDesc);
@@ -213,7 +224,14 @@
                       device);
                 return INVALID_OPERATION;
             }
+
+            // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
+            // parameters on newly connected devices (instead of opening the inputs...)
+            broadcastDeviceConnectionState(device, state, devDesc->mAddress);
+
             if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
+                broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
+                                               devDesc->mAddress);
                 return INVALID_OPERATION;
             }
 
@@ -224,11 +242,6 @@
                 return NO_MEMORY;
             }
 
-            // Set connect to HALs
-            AudioParameter param = AudioParameter(devDesc->mAddress);
-            param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
-            mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
-
             // Propagate device availability to Engine
             mEngine->setDeviceConnectionState(devDesc, state);
         } break;
@@ -243,9 +256,7 @@
             ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
 
             // Set Disconnect to HALs
-            AudioParameter param = AudioParameter(devDesc->mAddress);
-            param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
-            mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
+            broadcastDeviceConnectionState(device, state, devDesc->mAddress);
 
             checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
             mAvailableInputDevices.remove(devDesc);
@@ -402,6 +413,20 @@
             patch.num_sources = 2;
         }
 
+        // terminate active capture if on the same HW module as the call TX source device
+        // FIXME: would be better to refine to only inputs whose profile connects to the
+        // call TX device but this information is not in the audio patch and logic here must be
+        // symmetric to the one in startInput()
+        audio_io_handle_t activeInput = mInputs.getActiveInput();
+        if (activeInput != 0) {
+            sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
+            if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
+                audio_session_t activeSession = activeDesc->mSessions.itemAt(0);
+                stopInput(activeInput, activeSession);
+                releaseInput(activeInput, activeSession);
+            }
+        }
+
         afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
         status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
         ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
@@ -566,9 +591,15 @@
 
     audio_io_handle_t activeInput = mInputs.getActiveInput();
     if (activeInput != 0) {
-        setInputDevice(activeInput, getNewInputDevice(activeInput));
+        sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
+        audio_devices_t newDevice = getNewInputDevice(activeInput);
+        // Force new input selection if the new device can not be reached via current input
+        if (activeDesc->mProfile->mSupportedDevices.types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
+            setInputDevice(activeInput, newDevice);
+        } else {
+            closeInput(activeInput);
+        }
     }
-
 }
 
 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
@@ -1066,7 +1097,7 @@
     *delayMs = 0;
     if (stream == AUDIO_STREAM_TTS) {
         ALOGV("\t found BEACON stream");
-        if (mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
+        if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
             return INVALID_OPERATION;
         } else {
             beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
@@ -1485,15 +1516,29 @@
             // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
             // otherwise the active input continues and the new input cannot be started.
             sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
-            if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
+            if ((activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) &&
+                    !activeDesc->hasPreemptedSession(session)) {
                 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
-                stopInput(activeInput, activeDesc->mSessions.itemAt(0));
-                releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
+                audio_session_t activeSession = activeDesc->mSessions.itemAt(0);
+                SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
+                sessions.add(activeSession);
+                inputDesc->setPreemptedSessions(sessions);
+                stopInput(activeInput, activeSession);
+                releaseInput(activeInput, activeSession);
             } else {
                 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
                 return INVALID_OPERATION;
             }
         }
+
+        // Do not allow capture if an active voice call is using a software patch and
+        // the call TX source device is on the same HW module.
+        // FIXME: would be better to refine to only inputs whose profile connects to the
+        // call TX device but this information is not in the audio patch
+        if (mCallTxPatch != 0 &&
+            inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
+            return INVALID_OPERATION;
+        }
     }
 
     // Routing?
@@ -1592,6 +1637,7 @@
         if (mInputs.activeInputsCount() == 0) {
             SoundTrigger::setCaptureState(false);
         }
+        inputDesc->clearPreemptedSessions();
     }
     return NO_ERROR;
 }
@@ -1718,7 +1764,9 @@
                 status = volStatus;
             }
         }
-        if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
+        if ((accessibilityDevice != AUDIO_DEVICE_NONE) &&
+                ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)))
+        {
             status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
                                                    index, desc, curDevice);
         }
@@ -2000,6 +2048,9 @@
     snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
             mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
     result.append(buffer);
+    snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
+    result.append(buffer);
+
     write(fd, result.string(), result.size());
 
     mAvailableOutputDevices.dump(fd, String8("output"));
@@ -2680,7 +2731,8 @@
     mAudioPortGeneration(1),
     mBeaconMuteRefCount(0),
     mBeaconPlayingRefCount(0),
-    mBeaconMuted(false)
+    mBeaconMuted(false),
+    mTtsOutputAvailable(false)
 {
     audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
     if (!engineInstance) {
@@ -2737,6 +2789,9 @@
                 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
                 continue;
             }
+            if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_TTS) != 0) {
+                mTtsOutputAvailable = true;
+            }
 
             if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
                 continue;
@@ -4036,6 +4091,12 @@
 }
 
 uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
+
+    // skip beacon mute management if a dedicated TTS output is available
+    if (mTtsOutputAvailable) {
+        return 0;
+    }
+
     switch(event) {
     case STARTING_OUTPUT:
         mBeaconMuteRefCount++;
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h
index bf3ae4a..ebf9315 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.h
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h
@@ -548,6 +548,7 @@
         uint32_t mBeaconMuteRefCount;   // ref count for stream that would mute beacon
         uint32_t mBeaconPlayingRefCount;// ref count for the playing beacon streams
         bool mBeaconMuted;              // has STREAM_TTS been muted
+        bool mTtsOutputAvailable;       // true if a dedicated output for TTS stream is available
 
         AudioPolicyMixCollection mPolicyMixes; // list of registered mixes
 
@@ -571,6 +572,15 @@
         // Audio Policy Engine Interface.
         AudioPolicyManagerInterface *mEngine;
 private:
+        // Notify the policy client of any change of device state with AUDIO_IO_HANDLE_NONE,
+        // so that the client interprets it as global to audio hardware interfaces.
+        // It can give a chance to HAL implementer to retrieve dynamic capabilities associated
+        // to this device for example.
+        // TODO avoid opening stream to retrieve capabilities of a profile.
+        void broadcastDeviceConnectionState(audio_devices_t device,
+                                            audio_policy_dev_state_t state,
+                                            const String8 &device_address);
+
         // updates device caching and output for streams that can influence the
         //    routing of notifications
         void handleNotificationRoutingForStream(audio_stream_type_t stream);
diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
index 793c26a..a228798 100644
--- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
+++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
@@ -76,10 +76,14 @@
 
     ALOGV("setPhoneState()");
 
+    // acquire lock before calling setMode() so that setMode() + setPhoneState() are an atomic
+    // operation from policy manager standpoint (no other operation (e.g track start or stop)
+    // can be interleaved).
+    Mutex::Autolock _l(mLock);
+
     // TODO: check if it is more appropriate to do it in platform specific policy manager
     AudioSystem::setMode(state);
 
-    Mutex::Autolock _l(mLock);
     mAudioPolicyManager->setPhoneState(state);
     mPhoneState = state;
     return NO_ERROR;
@@ -459,6 +463,7 @@
     if (mAudioPolicyManager == NULL) {
         return AUDIO_DEVICE_NONE;
     }
+    Mutex::Autolock _l(mLock);
     return mAudioPolicyManager->getDevicesForStream(stream);
 }
 
diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp
index eefff3d..c77cc45 100644
--- a/services/audiopolicy/service/AudioPolicyService.cpp
+++ b/services/audiopolicy/service/AudioPolicyService.cpp
@@ -577,22 +577,28 @@
                     }
                 }
                 waitTime = INT64_MAX;
+                // release mLock before releasing strong reference on the service as
+                // AudioPolicyService destructor calls AudioCommandThread::exit() which
+                // acquires mLock.
+                mLock.unlock();
+                svc.clear();
+                mLock.lock();
             } else {
                 waitTime = mAudioCommands[0]->mTime - curTime;
                 break;
             }
         }
-        // release mLock before releasing strong reference on the service as
-        // AudioPolicyService destructor calls AudioCommandThread::exit() which acquires mLock.
-        mLock.unlock();
-        svc.clear();
-        mLock.lock();
-        if (!exitPending() && (mAudioCommands.isEmpty() || waitTime != INT64_MAX)) {
-            // release delayed commands wake lock
+
+        // release delayed commands wake lock if the queue is empty
+        if (mAudioCommands.isEmpty()) {
             release_wake_lock(mName.string());
+        }
+
+        // At this stage we have either an empty command queue or the first command in the queue
+        // has a finite delay. So unless we are exiting it is safe to wait.
+        if (!exitPending()) {
             ALOGV("AudioCommandThread() going to sleep");
             mWaitWorkCV.waitRelative(mLock, waitTime);
-            ALOGV("AudioCommandThread() waking up");
         }
     }
     // release delayed commands wake lock before quitting
@@ -1003,6 +1009,8 @@
         requestExit();
         mWaitWorkCV.signal();
     }
+    // Note that we can call it from the thread loop if all other references have been released
+    // but it will safely return WOULD_BLOCK in this case
     requestExitAndWait();
 }
 
diff --git a/services/camera/libcameraservice/Android.mk b/services/camera/libcameraservice/Android.mk
index e8ef24e..5044a7a 100644
--- a/services/camera/libcameraservice/Android.mk
+++ b/services/camera/libcameraservice/Android.mk
@@ -53,7 +53,7 @@
     device3/StatusTracker.cpp \
     gui/RingBufferConsumer.cpp \
     utils/CameraTraces.cpp \
-    utils/AutoConditionLock.cpp \
+    utils/AutoConditionLock.cpp
 
 LOCAL_SHARED_LIBRARIES:= \
     libui \
@@ -70,6 +70,8 @@
     libcamera_metadata \
     libjpeg
 
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libbinder
+
 LOCAL_C_INCLUDES += \
     system/media/camera/include \
     system/media/private/camera/include \
diff --git a/services/camera/libcameraservice/CameraFlashlight.cpp b/services/camera/libcameraservice/CameraFlashlight.cpp
index e42c596..406c1c4 100644
--- a/services/camera/libcameraservice/CameraFlashlight.cpp
+++ b/services/camera/libcameraservice/CameraFlashlight.cpp
@@ -99,7 +99,8 @@
 
 status_t CameraFlashlight::setTorchMode(const String8& cameraId, bool enabled) {
     if (!mFlashlightMapInitialized) {
-        ALOGE("%s: findFlashUnits() must be called before this method.");
+        ALOGE("%s: findFlashUnits() must be called before this method.",
+               __FUNCTION__);
         return NO_INIT;
     }
 
@@ -200,7 +201,8 @@
 
 bool CameraFlashlight::hasFlashUnitLocked(const String8& cameraId) {
     if (!mFlashlightMapInitialized) {
-        ALOGE("%s: findFlashUnits() must be called before this method.");
+        ALOGE("%s: findFlashUnits() must be called before this method.",
+               __FUNCTION__);
         return false;
     }
 
@@ -219,7 +221,8 @@
 
     Mutex::Autolock l(mLock);
     if (!mFlashlightMapInitialized) {
-        ALOGE("%s: findFlashUnits() must be called before this method.");
+        ALOGE("%s: findFlashUnits() must be called before this method.",
+               __FUNCTION__);
         return NO_INIT;
     }
 
@@ -256,7 +259,8 @@
 
     Mutex::Autolock l(mLock);
     if (!mFlashlightMapInitialized) {
-        ALOGE("%s: findFlashUnits() must be called before this method.");
+        ALOGE("%s: findFlashUnits() must be called before this method.",
+               __FUNCTION__);
         return NO_INIT;
     }
 
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index 5736b9e..4119140 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -15,6 +15,7 @@
  */
 
 #define LOG_TAG "CameraService"
+#define ATRACE_TAG ATRACE_TAG_CAMERA
 //#define LOG_NDEBUG 0
 
 #include <algorithm>
@@ -33,7 +34,6 @@
 #include <binder/MemoryBase.h>
 #include <binder/MemoryHeapBase.h>
 #include <binder/ProcessInfoService.h>
-#include <camera/ICameraServiceProxy.h>
 #include <cutils/atomic.h>
 #include <cutils/properties.h>
 #include <gui/Surface.h>
@@ -81,7 +81,7 @@
     sp<CameraService> cs = const_cast<CameraService*>(
             static_cast<const CameraService*>(callbacks));
 
-    cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
+    cs->onDeviceStatusChanged(camera_id,
             static_cast<camera_device_status_t>(new_status));
 }
 
@@ -153,11 +153,11 @@
         ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
         logServiceError("Could not load camera HAL module", err);
         mNumberOfCameras = 0;
+        mNumberOfNormalCameras = 0;
         return;
     }
 
     mModule = new CameraModule(rawModule);
-    ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
     err = mModule->init();
     if (err != OK) {
         ALOGE("Could not initialize camera HAL module: %d (%s)", err,
@@ -169,10 +169,18 @@
         mModule = nullptr;
         return;
     }
+    ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
 
     mNumberOfCameras = mModule->getNumberOfCameras();
     mNumberOfNormalCameras = mNumberOfCameras;
 
+    // Setup vendor tags before we call get_camera_info the first time
+    // because HAL might need to setup static vendor keys in get_camera_info
+    VendorTagDescriptor::clearGlobalVendorTagDescriptor();
+    if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
+        setUpVendorTags();
+    }
+
     mFlashlight = new CameraFlashlight(*mModule, *this);
     status_t res = mFlashlight->findFlashUnits();
     if (res) {
@@ -239,24 +247,26 @@
         mModule->setCallbacks(this);
     }
 
-    VendorTagDescriptor::clearGlobalVendorTagDescriptor();
-
-    if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
-        setUpVendorTags();
-    }
-
     CameraDeviceFactory::registerService(this);
 
     CameraService::pingCameraServiceProxy();
 }
 
-void CameraService::pingCameraServiceProxy() {
+sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
+    sp<ICameraServiceProxy> proxyBinder = nullptr;
+#ifndef __BRILLO__
     sp<IServiceManager> sm = defaultServiceManager();
     sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
-    if (binder == nullptr) {
-        return;
+    if (binder != nullptr) {
+        proxyBinder = interface_cast<ICameraServiceProxy>(binder);
     }
-    sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
+#endif
+    return proxyBinder;
+}
+
+void CameraService::pingCameraServiceProxy() {
+    sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
+    if (proxyBinder == nullptr) return;
     proxyBinder->pingForUserUpdate();
 }
 
@@ -269,7 +279,7 @@
     gCameraService = nullptr;
 }
 
-void CameraService::onDeviceStatusChanged(camera_device_status_t  cameraId,
+void CameraService::onDeviceStatusChanged(int  cameraId,
         camera_device_status_t newStatus) {
     ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
           cameraId, newStatus);
@@ -365,7 +375,7 @@
 
     {
         // Update battery life logging for flashlight
-        Mutex::Autolock al(mTorchClientMapMutex);
+        Mutex::Autolock al(mTorchUidMapMutex);
         auto iter = mTorchUidMap.find(cameraId);
         if (iter != mTorchUidMap.end()) {
             int oldUid = iter->second.second;
@@ -400,10 +410,12 @@
 }
 
 int32_t CameraService::getNumberOfCameras() {
+    ATRACE_CALL();
     return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
 }
 
 int32_t CameraService::getNumberOfCameras(int type) {
+    ATRACE_CALL();
     switch (type) {
         case CAMERA_TYPE_BACKWARD_COMPATIBLE:
             return mNumberOfNormalCameras;
@@ -418,6 +430,7 @@
 
 status_t CameraService::getCameraInfo(int cameraId,
                                       struct CameraInfo* cameraInfo) {
+    ATRACE_CALL();
     if (!mModule) {
         return -ENODEV;
     }
@@ -431,6 +444,12 @@
         mModule->getCameraInfo(cameraId, &info));
     cameraInfo->facing = info.facing;
     cameraInfo->orientation = info.orientation;
+    // CameraInfo is for android.hardware.Camera which does not
+    // support external camera facing. The closest approximation would be
+    // front camera.
+    if (cameraInfo->orientation == CAMERA_FACING_EXTERNAL) {
+        cameraInfo->orientation = CAMERA_FACING_FRONT;
+    }
     return rc;
 }
 
@@ -445,6 +464,7 @@
 }
 
 status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
+    ATRACE_CALL();
     status_t ret = OK;
     struct CameraInfo info;
     if ((ret = getCameraInfo(cameraId, &info)) != OK) {
@@ -531,6 +551,7 @@
 
 status_t CameraService::getCameraCharacteristics(int cameraId,
                                                 CameraMetadata* cameraInfo) {
+    ATRACE_CALL();
     if (!cameraInfo) {
         ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
         return BAD_VALUE;
@@ -599,10 +620,16 @@
                 procState);
         return -1;
     }
+    // Treat sleeping TOP processes the same as regular TOP processes, for
+    // access priority.  This is important for lock-screen camera launch scenarios
+    if (procState == PROCESS_STATE_TOP_SLEEPING) {
+        procState = PROCESS_STATE_TOP;
+    }
     return INT_MAX - procState;
 }
 
 status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
+    ATRACE_CALL();
     if (!mModule) {
         ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
         return -ENODEV;
@@ -613,6 +640,7 @@
 }
 
 int CameraService::getDeviceVersion(int cameraId, int* facing) {
+    ATRACE_CALL();
     struct camera_info info;
     if (mModule->getCameraInfo(cameraId, &info) != OK) {
         return -1;
@@ -644,6 +672,7 @@
 }
 
 bool CameraService::setUpVendorTags() {
+    ATRACE_CALL();
     vendor_tag_ops_t vOps = vendor_tag_ops_t();
 
     // Check if vendor operations have been implemented
@@ -652,9 +681,7 @@
         return false;
     }
 
-    ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
     mModule->getVendorTagOps(&vOps);
-    ATRACE_END();
 
     // Ensure all vendor operations are present
     if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
@@ -846,17 +873,6 @@
 
     int callingPid = getCallingPid();
 
-    if (clientUid == USE_CALLING_UID) {
-        clientUid = getCallingUid();
-    } else {
-        // We only trust our own process to forward client UIDs
-        if (callingPid != getpid()) {
-            ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
-                    callingPid, clientUid);
-            return PERMISSION_DENIED;
-        }
-    }
-
     if (!mModule) {
         ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
                 callingPid);
@@ -869,6 +885,31 @@
         return -ENODEV;
     }
 
+#if !defined(__BRILLO__)
+    status_t allowed = validateClientPermissionsLocked(cameraId, clientUid);
+    if (allowed != OK) {
+        return allowed;
+    }
+#endif  // defined(__BRILLO__)
+
+    return checkIfDeviceIsUsable(cameraId);
+}
+
+status_t CameraService::validateClientPermissionsLocked(const String8& cameraId, int& clientUid)
+        const {
+    int callingPid = getCallingPid();
+
+    if (clientUid == USE_CALLING_UID) {
+        clientUid = getCallingUid();
+    } else {
+        // We only trust our own process to forward client UIDs
+        if (callingPid != getpid()) {
+            ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
+                    callingPid, clientUid);
+            return PERMISSION_DENIED;
+        }
+    }
+
     // Check device policy for this camera
     char value[PROPERTY_VALUE_MAX];
     char key[PROPERTY_KEY_MAX];
@@ -891,7 +932,7 @@
         return PERMISSION_DENIED;
     }
 
-    return checkIfDeviceIsUsable(cameraId);
+    return OK;
 }
 
 status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
@@ -937,6 +978,16 @@
         LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
                 __FUNCTION__);
     }
+
+    // And register a death notification for the client callback. Do
+    // this last to avoid Binder policy where a nested Binder
+    // transaction might be pre-empted to service the client death
+    // notification if the client process dies before linkToDeath is
+    // invoked.
+    sp<IBinder> remoteCallback = client->getRemote();
+    if (remoteCallback != nullptr) {
+        remoteCallback->linkToDeath(this);
+    }
 }
 
 status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
@@ -944,7 +995,7 @@
         /*out*/
         sp<BasicClient>* client,
         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
-
+    ATRACE_CALL();
     status_t ret = NO_ERROR;
     std::vector<DescriptorPtr> evictedClients;
     DescriptorPtr clientDescriptor;
@@ -1133,6 +1184,7 @@
         /*out*/
         sp<ICamera>& device) {
 
+    ATRACE_CALL();
     status_t ret = NO_ERROR;
     String8 id = String8::format("%d", cameraId);
     sp<Client> client = nullptr;
@@ -1157,6 +1209,7 @@
         /*out*/
         sp<ICamera>& device) {
 
+    ATRACE_CALL();
     String8 id = String8::format("%d", cameraId);
     int apiVersion = mModule->getModuleApiVersion();
     if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
@@ -1197,6 +1250,7 @@
         /*out*/
         sp<ICameraDeviceUser>& device) {
 
+    ATRACE_CALL();
     status_t ret = NO_ERROR;
     String8 id = String8::format("%d", cameraId);
     sp<CameraDeviceClient> client = nullptr;
@@ -1216,6 +1270,8 @@
 
 status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
         const sp<IBinder>& clientBinder) {
+
+    ATRACE_CALL();
     if (enabled && clientBinder == nullptr) {
         ALOGE("%s: torch client binder is NULL", __FUNCTION__);
         return -EINVAL;
@@ -1264,7 +1320,7 @@
     {
         // Update UID map - this is used in the torch status changed callbacks, so must be done
         // before setTorchMode
-        Mutex::Autolock al(mTorchClientMapMutex);
+        Mutex::Autolock al(mTorchUidMapMutex);
         if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
             mTorchUidMap[id].first = uid;
             mTorchUidMap[id].second = uid;
@@ -1304,6 +1360,8 @@
 }
 
 void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
+    ATRACE_CALL();
+
     switch(eventId) {
         case ICameraService::USER_SWITCHED: {
             doUserSwitch(/*newUserIds*/args, /*length*/length);
@@ -1319,6 +1377,8 @@
 }
 
 status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
+    ATRACE_CALL();
+
     ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
 
     if (listener == nullptr) {
@@ -1367,6 +1427,8 @@
 }
 
 status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
+    ATRACE_CALL();
+
     ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
 
     if (listener == 0) {
@@ -1393,6 +1455,8 @@
 }
 
 status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
+
+    ATRACE_CALL();
     ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
 
     if (parameters == NULL) {
@@ -1417,6 +1481,8 @@
 }
 
 status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
+    ATRACE_CALL();
+
     ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
 
     switch (apiVersion) {
@@ -1784,12 +1850,15 @@
 }
 
 void CameraService::loadSound() {
+    ATRACE_CALL();
+
     Mutex::Autolock lock(mSoundLock);
     LOG1("CameraService::loadSound ref=%d", mSoundRef);
     if (mSoundRef++) return;
 
     mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
-    mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
+    mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
+    mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
 }
 
 void CameraService::releaseSound() {
@@ -1806,6 +1875,8 @@
 }
 
 void CameraService::playSound(sound_kind kind) {
+    ATRACE_CALL();
+
     LOG1("playSound(%d)", kind);
     Mutex::Autolock lock(mSoundLock);
     sp<MediaPlayer> player = mSoundPlayer[kind];
@@ -1876,11 +1947,9 @@
 
 void CameraService::BasicClient::disconnect() {
     if (mDisconnected) {
-        ALOGE("%s: Disconnect called on already disconnected client for device %d", __FUNCTION__,
-                mCameraId);
         return;
     }
-    mDisconnected = true;;
+    mDisconnected = true;
 
     mCameraService->removeByClient(this);
     mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
@@ -1898,6 +1967,14 @@
     mClientPid = 0;
 }
 
+status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
+    // No dumping of clients directly over Binder,
+    // must go through CameraService::dump
+    android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
+            IPCThreadState::self()->getCallingUid(), NULL, 0);
+    return OK;
+}
+
 String16 CameraService::BasicClient::getPackageName() const {
     return mClientPackageName;
 }
@@ -1917,6 +1994,8 @@
 }
 
 status_t CameraService::BasicClient::startCameraOps() {
+    ATRACE_CALL();
+
     int32_t res;
     // Notify app ops that the camera is not available
     mOpsCallback = new OpsCallback(this);
@@ -1950,10 +2029,16 @@
     mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
             String8::format("%d", mCameraId));
 
+    // Transition device state to OPEN
+    mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
+            String8::format("%d", mCameraId));
+
     return OK;
 }
 
 status_t CameraService::BasicClient::finishCameraOps() {
+    ATRACE_CALL();
+
     // Check if startCameraOps succeeded, and if so, finish the camera op
     if (mOpsActive) {
         // Notify app ops that the camera is available again
@@ -1968,6 +2053,10 @@
         mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
                 String8::format("%d", mCameraId), rejected);
 
+        // Transition device state to CLOSED
+        mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
+                String8::format("%d", mCameraId));
+
         // Notify flashlight that a camera device is closed.
         mCameraService->mFlashlight->deviceClosed(
                 String8::format("%d", mCameraId));
@@ -1982,6 +2071,8 @@
 }
 
 void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
+    ATRACE_CALL();
+
     String8 name(packageName);
     String8 myName(mClientPackageName);
 
@@ -2026,7 +2117,11 @@
 
 void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
         const CaptureResultExtras& resultExtras) {
-    mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
+    if (mRemoteCallback != NULL) {
+        mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
+    } else {
+        ALOGE("mRemoteCallback is NULL!!");
+    }
 }
 
 // NOTE: function is idempotent
@@ -2205,9 +2300,11 @@
 }
 
 status_t CameraService::dump(int fd, const Vector<String16>& args) {
+    ATRACE_CALL();
+
     String8 result("Dump of the Camera Service:\n");
     if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
-        result.appendFormat("Permission Denial: "
+        result = result.format("Permission Denial: "
                 "can't dump CameraService from pid=%d, uid=%d\n",
                 getCallingPid(),
                 getCallingUid());
@@ -2287,7 +2384,7 @@
                 result.appendFormat("  Resource Cost: %d\n", state.second->getCost());
                 result.appendFormat("  Conflicting Devices:");
                 for (auto& id : conflicting) {
-                    result.appendFormat(" %s", cameraId.string());
+                    result.appendFormat(" %s", id.string());
                 }
                 if (conflicting.size() == 0) {
                     result.appendFormat(" NONE");
@@ -2330,7 +2427,7 @@
                     String8(client->getPackageName()).string());
             write(fd, result.string(), result.size());
 
-            client->dump(fd, args);
+            client->dumpClient(fd, args);
         }
 
         if (stateLocked) mCameraStatesLock.unlock();
@@ -2468,6 +2565,14 @@
         });
 }
 
+void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
+        const String8& cameraId) {
+    sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
+    if (proxyBinder == nullptr) return;
+    String16 id(cameraId);
+    proxyBinder->notifyCameraState(id, newState);
+}
+
 status_t CameraService::getTorchStatusLocked(
         const String8& cameraId,
         ICameraServiceListener::TorchStatus *status) const {
diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h
index 7f4d43f..ec8c5e9 100644
--- a/services/camera/libcameraservice/CameraService.h
+++ b/services/camera/libcameraservice/CameraService.h
@@ -24,6 +24,7 @@
 #include <binder/BinderService.h>
 #include <binder/IAppOpsCallback.h>
 #include <camera/ICameraService.h>
+#include <camera/ICameraServiceProxy.h>
 #include <hardware/camera.h>
 
 #include <camera/ICamera.h>
@@ -74,6 +75,8 @@
 
     // Process state (mirrors frameworks/base/core/java/android/app/ActivityManager.java)
     static const int PROCESS_STATE_NONEXISTENT = -1;
+    static const int PROCESS_STATE_TOP = 2;
+    static const int PROCESS_STATE_TOP_SLEEPING = 5;
 
     // 3 second busy timeout when other clients are connecting
     static const nsecs_t DEFAULT_CONNECT_TIMEOUT_NS = 3000000000;
@@ -84,6 +87,9 @@
     // Default number of messages to store in eviction log
     static const size_t DEFAULT_EVENT_LOG_LENGTH = 100;
 
+    // Event log ID
+    static const int SN_EVENT_LOG_ID = 0x534e4554;
+
     // Implementation of BinderService<T>
     static char const* getServiceName() { return "media.camera"; }
 
@@ -92,7 +98,7 @@
 
     /////////////////////////////////////////////////////////////////////
     // HAL Callbacks
-    virtual void        onDeviceStatusChanged(camera_device_status_t cameraId,
+    virtual void        onDeviceStatusChanged(int cameraId,
                                               camera_device_status_t newStatus);
     virtual void        onTorchStatusChanged(const String8& cameraId,
                                              ICameraServiceListener::TorchStatus
@@ -156,7 +162,8 @@
 
     enum sound_kind {
         SOUND_SHUTTER = 0,
-        SOUND_RECORDING = 1,
+        SOUND_RECORDING_START = 1,
+        SOUND_RECORDING_STOP = 2,
         NUM_SOUNDS
     };
 
@@ -164,6 +171,14 @@
     void                playSound(sound_kind kind);
     void                releaseSound();
 
+    /**
+     * Update the state of a given camera device (open/close/active/idle) with
+     * the camera proxy service in the system service
+     */
+    static void         updateProxyDeviceState(
+            ICameraServiceProxy::CameraState newState,
+            const String8& cameraId);
+
     /////////////////////////////////////////////////////////////////////
     // CameraDeviceFactory functionality
     int                 getDeviceVersion(int cameraId, int* facing = NULL);
@@ -189,7 +204,10 @@
             return mRemoteBinder;
         }
 
-        virtual status_t    dump(int fd, const Vector<String16>& args) = 0;
+        // Disallows dumping over binder interface
+        virtual status_t      dump(int fd, const Vector<String16>& args);
+        // Internal dump method to be called by CameraService
+        virtual status_t      dumpClient(int fd, const Vector<String16>& args) = 0;
 
         // Return the package name for this client
         virtual String16 getPackageName() const;
@@ -470,6 +488,7 @@
 
     // Check if we can connect, before we acquire the service lock.
     status_t validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid) const;
+    status_t validateClientPermissionsLocked(const String8& cameraId, /*inout*/int& clientUid) const;
 
     // Handle active client evictions, and update service state.
     // Only call with with mServiceLock held.
@@ -648,8 +667,10 @@
     sp<CameraFlashlight> mFlashlight;
     // guard mTorchStatusMap
     Mutex                mTorchStatusMutex;
-    // guard mTorchClientMap, mTorchUidMap
+    // guard mTorchClientMap
     Mutex                mTorchClientMapMutex;
+    // guard mTorchUidMap
+    Mutex                mTorchUidMapMutex;
     // camera id -> torch status
     KeyedVector<String8, ICameraServiceListener::TorchStatus> mTorchStatusMap;
     // camera id -> torch client binder
@@ -728,6 +749,7 @@
 
     static String8 toString(std::set<userid_t> intSet);
 
+    static sp<ICameraServiceProxy> getCameraServiceProxy();
     static void pingCameraServiceProxy();
 
 };
@@ -859,11 +881,6 @@
             return ret;
         }
 
-        sp<IBinder> remoteCallback = client->getRemote();
-        if (remoteCallback != nullptr) {
-            remoteCallback->linkToDeath(this);
-        }
-
         // Update shim paremeters for legacy clients
         if (effectiveApiLevel == API_1) {
             // Assume we have always received a Client subclass for API1
diff --git a/services/camera/libcameraservice/api1/Camera2Client.cpp b/services/camera/libcameraservice/api1/Camera2Client.cpp
index 36e99dd..fbd4034 100644
--- a/services/camera/libcameraservice/api1/Camera2Client.cpp
+++ b/services/camera/libcameraservice/api1/Camera2Client.cpp
@@ -163,6 +163,10 @@
 }
 
 status_t Camera2Client::dump(int fd, const Vector<String16>& args) {
+    return BasicClient::dump(fd, args);
+}
+
+status_t Camera2Client::dumpClient(int fd, const Vector<String16>& args) {
     String8 result;
     result.appendFormat("Client2[%d] (%p) PID: %d, dump:\n", mCameraId,
             (getRemoteCallback() != NULL ?
@@ -1040,7 +1044,7 @@
     }
 
     if (!restart) {
-        mCameraService->playSound(CameraService::SOUND_RECORDING);
+        mCameraService->playSound(CameraService::SOUND_RECORDING_START);
         mStreamingProcessor->updateRecordingRequest(params);
         if (res != OK) {
             ALOGE("%s: Camera %d: Unable to update recording request: %s (%d)",
@@ -1212,7 +1216,7 @@
             return;
     };
 
-    mCameraService->playSound(CameraService::SOUND_RECORDING);
+    mCameraService->playSound(CameraService::SOUND_RECORDING_STOP);
 
     // Remove recording stream to prevent it from slowing down takePicture later
     if (!l.mParameters.recordingHint && l.mParameters.isJpegSizeOverridden()) {
@@ -1638,7 +1642,7 @@
 }
 
 status_t Camera2Client::commandPlayRecordingSoundL() {
-    mCameraService->playSound(CameraService::SOUND_RECORDING);
+    mCameraService->playSound(CameraService::SOUND_RECORDING_START);
     return OK;
 }
 
@@ -1912,6 +1916,8 @@
     ALOGV("%s: Shutter notification for request id %" PRId32 " at time %" PRId64,
             __FUNCTION__, resultExtras.requestId, timestamp);
     mCaptureSequencer->notifyShutter(resultExtras, timestamp);
+
+    Camera2ClientBase::notifyShutter(resultExtras, timestamp);
 }
 
 camera2::SharedParameters& Camera2Client::getParameters() {
diff --git a/services/camera/libcameraservice/api1/Camera2Client.h b/services/camera/libcameraservice/api1/Camera2Client.h
index d50bf63..7e7a284 100644
--- a/services/camera/libcameraservice/api1/Camera2Client.h
+++ b/services/camera/libcameraservice/api1/Camera2Client.h
@@ -100,6 +100,8 @@
 
     virtual status_t dump(int fd, const Vector<String16>& args);
 
+    virtual status_t dumpClient(int fd, const Vector<String16>& args);
+
     /**
      * Interface used by CameraDeviceBase
      */
diff --git a/services/camera/libcameraservice/api1/CameraClient.cpp b/services/camera/libcameraservice/api1/CameraClient.cpp
index e552633..b942813 100644
--- a/services/camera/libcameraservice/api1/CameraClient.cpp
+++ b/services/camera/libcameraservice/api1/CameraClient.cpp
@@ -108,6 +108,10 @@
 }
 
 status_t CameraClient::dump(int fd, const Vector<String16>& args) {
+    return BasicClient::dump(fd, args);
+}
+
+status_t CameraClient::dumpClient(int fd, const Vector<String16>& args) {
     const size_t SIZE = 256;
     char buffer[SIZE];
 
@@ -236,11 +240,6 @@
         return;
     }
 
-    if (mClientPid <= 0) {
-        LOG1("camera is unlocked (mClientPid = %d), don't tear down hardware", mClientPid);
-        return;
-    }
-
     // Make sure disconnect() is done once and once only, whether it is called
     // from the user directly, or called by the destructor.
     if (mHardware == 0) return;
@@ -251,6 +250,9 @@
     // Turn off all messages.
     disableMsgType(CAMERA_MSG_ALL_MSGS);
     mHardware->stopPreview();
+    mCameraService->updateProxyDeviceState(
+        ICameraServiceProxy::CAMERA_STATE_IDLE,
+        String8::format("%d", mCameraId));
     mHardware->cancelPicture();
     // Release the hardware resources.
     mHardware->release();
@@ -409,7 +411,11 @@
     }
     mHardware->setPreviewWindow(mPreviewWindow);
     result = mHardware->startPreview();
-
+    if (result == NO_ERROR) {
+        mCameraService->updateProxyDeviceState(
+            ICameraServiceProxy::CAMERA_STATE_ACTIVE,
+            String8::format("%d", mCameraId));
+    }
     return result;
 }
 
@@ -432,7 +438,7 @@
 
     // start recording mode
     enableMsgType(CAMERA_MSG_VIDEO_FRAME);
-    mCameraService->playSound(CameraService::SOUND_RECORDING);
+    mCameraService->playSound(CameraService::SOUND_RECORDING_START);
     result = mHardware->startRecording();
     if (result != NO_ERROR) {
         ALOGE("mHardware->startRecording() failed with status %d", result);
@@ -449,7 +455,9 @@
 
     disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
     mHardware->stopPreview();
-
+    mCameraService->updateProxyDeviceState(
+        ICameraServiceProxy::CAMERA_STATE_IDLE,
+        String8::format("%d", mCameraId));
     mPreviewBuffer.clear();
 }
 
@@ -461,7 +469,7 @@
 
     disableMsgType(CAMERA_MSG_VIDEO_FRAME);
     mHardware->stopRecording();
-    mCameraService->playSound(CameraService::SOUND_RECORDING);
+    mCameraService->playSound(CameraService::SOUND_RECORDING_STOP);
 
     mPreviewBuffer.clear();
 }
@@ -639,7 +647,7 @@
         }
         return OK;
     } else if (cmd == CAMERA_CMD_PLAY_RECORDING_SOUND) {
-        mCameraService->playSound(CameraService::SOUND_RECORDING);
+        mCameraService->playSound(CameraService::SOUND_RECORDING_START);
     } else if (cmd == CAMERA_CMD_SET_VIDEO_BUFFER_COUNT) {
         // Silently ignore this command
         return INVALID_OPERATION;
@@ -790,6 +798,12 @@
     }
     disableMsgType(CAMERA_MSG_SHUTTER);
 
+    // Shutters only happen in response to takePicture, so mark device as
+    // idle now, until preview is restarted
+    mCameraService->updateProxyDeviceState(
+        ICameraServiceProxy::CAMERA_STATE_IDLE,
+        String8::format("%d", mCameraId));
+
     mLock.unlock();
 }
 
diff --git a/services/camera/libcameraservice/api1/CameraClient.h b/services/camera/libcameraservice/api1/CameraClient.h
index 95616b2..17999a5 100644
--- a/services/camera/libcameraservice/api1/CameraClient.h
+++ b/services/camera/libcameraservice/api1/CameraClient.h
@@ -70,7 +70,9 @@
 
     status_t initialize(CameraModule *module);
 
-    status_t dump(int fd, const Vector<String16>& args);
+    virtual status_t dump(int fd, const Vector<String16>& args);
+
+    virtual status_t dumpClient(int fd, const Vector<String16>& args);
 
 private:
 
diff --git a/services/camera/libcameraservice/api1/client2/Parameters.cpp b/services/camera/libcameraservice/api1/client2/Parameters.cpp
index ea75679..fc5ebac 100644
--- a/services/camera/libcameraservice/api1/client2/Parameters.cpp
+++ b/services/camera/libcameraservice/api1/client2/Parameters.cpp
@@ -214,8 +214,8 @@
                 supportedPreviewFormats);
     }
 
-    previewFpsRange[0] = availableFpsRanges.data.i32[0];
-    previewFpsRange[1] = availableFpsRanges.data.i32[1];
+    previewFpsRange[0] = fastInfo.bestStillCaptureFpsRange[0];
+    previewFpsRange[1] = fastInfo.bestStillCaptureFpsRange[1];
 
     // PREVIEW_FRAME_RATE / SUPPORTED_PREVIEW_FRAME_RATES are deprecated, but
     // still have to do something sane for them
diff --git a/services/camera/libcameraservice/api1/client2/StreamingProcessor.cpp b/services/camera/libcameraservice/api1/client2/StreamingProcessor.cpp
index 66d7b00..75c6f00 100644
--- a/services/camera/libcameraservice/api1/client2/StreamingProcessor.cpp
+++ b/services/camera/libcameraservice/api1/client2/StreamingProcessor.cpp
@@ -401,6 +401,7 @@
             currentFormat != (uint32_t)mRecordingFormat ||
             currentDataSpace != mRecordingDataSpace) {
         *needsUpdate = true;
+        return res;
     }
     *needsUpdate = false;
     return res;
diff --git a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
index c717a56..bd9fea3 100644
--- a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
+++ b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
@@ -719,6 +719,43 @@
     return res;
 }
 
+status_t CameraDeviceClient::prepare2(int maxCount, int streamId) {
+    ATRACE_CALL();
+    ALOGV("%s", __FUNCTION__);
+
+    status_t res = OK;
+    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
+
+    Mutex::Autolock icl(mBinderSerializationLock);
+
+    // Guard against trying to prepare non-created streams
+    ssize_t index = NAME_NOT_FOUND;
+    for (size_t i = 0; i < mStreamMap.size(); ++i) {
+        if (streamId == mStreamMap.valueAt(i)) {
+            index = i;
+            break;
+        }
+    }
+
+    if (index == NAME_NOT_FOUND) {
+        ALOGW("%s: Camera %d: Invalid stream ID (%d) specified, no stream created yet",
+                __FUNCTION__, mCameraId, streamId);
+        return BAD_VALUE;
+    }
+
+    if (maxCount <= 0) {
+        ALOGE("%s: Camera %d: Invalid maxCount (%d) specified, must be greater than 0.",
+                __FUNCTION__, mCameraId, maxCount);
+        return BAD_VALUE;
+    }
+
+    // Also returns BAD_VALUE if stream ID was not valid, or stream already
+    // has been used
+    res = mDevice->prepare(maxCount, streamId);
+
+    return res;
+}
+
 status_t CameraDeviceClient::tearDown(int streamId) {
     ATRACE_CALL();
     ALOGV("%s", __FUNCTION__);
@@ -750,8 +787,11 @@
     return res;
 }
 
-
 status_t CameraDeviceClient::dump(int fd, const Vector<String16>& args) {
+    return BasicClient::dump(fd, args);
+}
+
+status_t CameraDeviceClient::dumpClient(int fd, const Vector<String16>& args) {
     String8 result;
     result.appendFormat("CameraDeviceClient[%d] (%p) dump:\n",
             mCameraId,
@@ -799,6 +839,7 @@
     if (remoteCb != 0) {
         remoteCb->onDeviceIdle();
     }
+    Camera2ClientBase::notifyIdle();
 }
 
 void CameraDeviceClient::notifyShutter(const CaptureResultExtras& resultExtras,
@@ -808,6 +849,7 @@
     if (remoteCb != 0) {
         remoteCb->onCaptureStarted(resultExtras, timestamp);
     }
+    Camera2ClientBase::notifyShutter(resultExtras, timestamp);
 }
 
 void CameraDeviceClient::notifyPrepared(int streamId) {
diff --git a/services/camera/libcameraservice/api2/CameraDeviceClient.h b/services/camera/libcameraservice/api2/CameraDeviceClient.h
index 1f8b39d..b1d1762 100644
--- a/services/camera/libcameraservice/api2/CameraDeviceClient.h
+++ b/services/camera/libcameraservice/api2/CameraDeviceClient.h
@@ -114,6 +114,9 @@
     // Tear down stream resources by freeing its unused buffers
     virtual status_t      tearDown(int streamId);
 
+    // Prepare stream by preallocating up to maxCount of its buffers
+    virtual status_t      prepare2(int maxCount, int streamId);
+
     /**
      * Interface used by CameraService
      */
@@ -132,6 +135,8 @@
 
     virtual status_t      dump(int fd, const Vector<String16>& args);
 
+    virtual status_t      dumpClient(int fd, const Vector<String16>& args);
+
     /**
      * Device listener interface
      */
@@ -189,6 +194,7 @@
     Vector<int> mStreamingRequestList;
 
     int32_t mRequestIdCounter;
+
 };
 
 }; // namespace android
diff --git a/services/camera/libcameraservice/common/Camera2ClientBase.cpp b/services/camera/libcameraservice/common/Camera2ClientBase.cpp
index ba0b264..c7de56a 100644
--- a/services/camera/libcameraservice/common/Camera2ClientBase.cpp
+++ b/services/camera/libcameraservice/common/Camera2ClientBase.cpp
@@ -55,7 +55,8 @@
         TClientBase(cameraService, remoteCallback, clientPackageName,
                 cameraId, cameraFacing, clientPid, clientUid, servicePid),
         mSharedCameraCallbacks(remoteCallback),
-        mDeviceVersion(cameraService->getDeviceVersion(cameraId))
+        mDeviceVersion(cameraService->getDeviceVersion(cameraId)),
+        mDeviceActive(false)
 {
     ALOGI("Camera %d: Opened. Client: %s (PID %d, UID %d)", cameraId,
             String8(clientPackageName).string(), clientPid, clientUid);
@@ -123,7 +124,7 @@
 }
 
 template <typename TClientBase>
-status_t Camera2ClientBase<TClientBase>::dump(int fd,
+status_t Camera2ClientBase<TClientBase>::dumpClient(int fd,
                                               const Vector<String16>& args) {
     String8 result;
     result.appendFormat("Camera2ClientBase[%d] (%p) PID: %d, dump:\n",
@@ -235,6 +236,13 @@
 
 template <typename TClientBase>
 void Camera2ClientBase<TClientBase>::notifyIdle() {
+    if (mDeviceActive) {
+        getCameraService()->updateProxyDeviceState(
+            ICameraServiceProxy::CAMERA_STATE_IDLE,
+            String8::format("%d", TClientBase::mCameraId));
+    }
+    mDeviceActive = false;
+
     ALOGV("Camera device is now idle");
 }
 
@@ -244,6 +252,13 @@
     (void)resultExtras;
     (void)timestamp;
 
+    if (!mDeviceActive) {
+        getCameraService()->updateProxyDeviceState(
+            ICameraServiceProxy::CAMERA_STATE_ACTIVE,
+            String8::format("%d", TClientBase::mCameraId));
+    }
+    mDeviceActive = true;
+
     ALOGV("%s: Shutter notification for request id %" PRId32 " at time %" PRId64,
             __FUNCTION__, resultExtras.requestId, timestamp);
 }
diff --git a/services/camera/libcameraservice/common/Camera2ClientBase.h b/services/camera/libcameraservice/common/Camera2ClientBase.h
index f1cacdf..4568af0 100644
--- a/services/camera/libcameraservice/common/Camera2ClientBase.h
+++ b/services/camera/libcameraservice/common/Camera2ClientBase.h
@@ -57,7 +57,7 @@
     virtual ~Camera2ClientBase();
 
     virtual status_t      initialize(CameraModule *module);
-    virtual status_t      dump(int fd, const Vector<String16>& args);
+    virtual status_t      dumpClient(int fd, const Vector<String16>& args);
 
     /**
      * CameraDeviceBase::NotificationListener implementation
@@ -136,6 +136,8 @@
     status_t              checkPid(const char *checkLocation) const;
 
     virtual void          detachDevice();
+
+    bool                  mDeviceActive;
 };
 
 }; // namespace android
diff --git a/services/camera/libcameraservice/common/CameraDeviceBase.h b/services/camera/libcameraservice/common/CameraDeviceBase.h
index cd25949..7b083a3 100644
--- a/services/camera/libcameraservice/common/CameraDeviceBase.h
+++ b/services/camera/libcameraservice/common/CameraDeviceBase.h
@@ -294,6 +294,12 @@
     virtual status_t tearDown(int streamId) = 0;
 
     /**
+     * Prepare stream by preallocating up to maxCount buffers for it asynchronously.
+     * Calls notifyPrepared() once allocation is complete.
+     */
+    virtual status_t prepare(int maxCount, int streamId) = 0;
+
+    /**
      * Get the HAL device version.
      */
     virtual uint32_t getDeviceVersion() = 0;
diff --git a/services/camera/libcameraservice/common/CameraModule.cpp b/services/camera/libcameraservice/common/CameraModule.cpp
index 6a4dfe0..16b8aba 100644
--- a/services/camera/libcameraservice/common/CameraModule.cpp
+++ b/services/camera/libcameraservice/common/CameraModule.cpp
@@ -15,14 +15,18 @@
  */
 
 #define LOG_TAG "CameraModule"
+#define ATRACE_TAG ATRACE_TAG_CAMERA
 //#define LOG_NDEBUG 0
 
+#include <utils/Trace.h>
+
 #include "CameraModule.h"
 
 namespace android {
 
 void CameraModule::deriveCameraCharacteristicsKeys(
         uint32_t deviceVersion, CameraMetadata &chars) {
+    ATRACE_CALL();
     // HAL1 devices should not reach here
     if (deviceVersion < CAMERA_DEVICE_API_VERSION_2_0) {
         ALOGV("%s: Cannot derive keys for HAL version < 2.0");
@@ -150,9 +154,7 @@
         ALOGE("%s: camera hardware module must not be null", __FUNCTION__);
         assert(0);
     }
-
     mModule = module;
-    mCameraInfoMap.setCapacity(getNumberOfCameras());
 }
 
 CameraModule::~CameraModule()
@@ -168,14 +170,20 @@
 }
 
 int CameraModule::init() {
+    ATRACE_CALL();
+    int res = OK;
     if (getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 &&
             mModule->init != NULL) {
-        return mModule->init();
+        ATRACE_BEGIN("camera_module->init");
+        res = mModule->init();
+        ATRACE_END();
     }
-    return OK;
+    mCameraInfoMap.setCapacity(getNumberOfCameras());
+    return res;
 }
 
 int CameraModule::getCameraInfo(int cameraId, struct camera_info *info) {
+    ATRACE_CALL();
     Mutex::Autolock lock(mCameraInfoLock);
     if (cameraId < 0) {
         ALOGE("%s: Invalid camera ID %d", __FUNCTION__, cameraId);
@@ -185,14 +193,20 @@
     // Only override static_camera_characteristics for API2 devices
     int apiVersion = mModule->common.module_api_version;
     if (apiVersion < CAMERA_MODULE_API_VERSION_2_0) {
-        return mModule->get_camera_info(cameraId, info);
+        int ret;
+        ATRACE_BEGIN("camera_module->get_camera_info");
+        ret = mModule->get_camera_info(cameraId, info);
+        ATRACE_END();
+        return ret;
     }
 
     ssize_t index = mCameraInfoMap.indexOfKey(cameraId);
     if (index == NAME_NOT_FOUND) {
         // Get camera info from raw module and cache it
         camera_info rawInfo, cameraInfo;
+        ATRACE_BEGIN("camera_module->get_camera_info");
         int ret = mModule->get_camera_info(cameraId, &rawInfo);
+        ATRACE_END();
         if (ret != 0) {
             return ret;
         }
@@ -217,20 +231,36 @@
 }
 
 int CameraModule::open(const char* id, struct hw_device_t** device) {
-    return filterOpenErrorCode(mModule->common.methods->open(&mModule->common, id, device));
+    int res;
+    ATRACE_BEGIN("camera_module->open");
+    res = filterOpenErrorCode(mModule->common.methods->open(&mModule->common, id, device));
+    ATRACE_END();
+    return res;
 }
 
 int CameraModule::openLegacy(
         const char* id, uint32_t halVersion, struct hw_device_t** device) {
-    return mModule->open_legacy(&mModule->common, id, halVersion, device);
+    int res;
+    ATRACE_BEGIN("camera_module->open_legacy");
+    res = mModule->open_legacy(&mModule->common, id, halVersion, device);
+    ATRACE_END();
+    return res;
 }
 
 int CameraModule::getNumberOfCameras() {
-    return mModule->get_number_of_cameras();
+    int numCameras;
+    ATRACE_BEGIN("camera_module->get_number_of_cameras");
+    numCameras = mModule->get_number_of_cameras();
+    ATRACE_END();
+    return numCameras;
 }
 
 int CameraModule::setCallbacks(const camera_module_callbacks_t *callbacks) {
-    return mModule->set_callbacks(callbacks);
+    int res;
+    ATRACE_BEGIN("camera_module->set_callbacks");
+    res = mModule->set_callbacks(callbacks);
+    ATRACE_END();
+    return res;
 }
 
 bool CameraModule::isVendorTagDefined() {
@@ -239,12 +269,18 @@
 
 void CameraModule::getVendorTagOps(vendor_tag_ops_t* ops) {
     if (mModule->get_vendor_tag_ops) {
+        ATRACE_BEGIN("camera_module->get_vendor_tag_ops");
         mModule->get_vendor_tag_ops(ops);
+        ATRACE_END();
     }
 }
 
 int CameraModule::setTorchMode(const char* camera_id, bool enable) {
-    return mModule->set_torch_mode(camera_id, enable);
+    int res;
+    ATRACE_BEGIN("camera_module->set_torch_mode");
+    res = mModule->set_torch_mode(camera_id, enable);
+    ATRACE_END();
+    return res;
 }
 
 status_t CameraModule::filterOpenErrorCode(status_t err) {
diff --git a/services/camera/libcameraservice/device1/CameraHardwareInterface.h b/services/camera/libcameraservice/device1/CameraHardwareInterface.h
index 7f14cd4..454d60f 100644
--- a/services/camera/libcameraservice/device1/CameraHardwareInterface.h
+++ b/services/camera/libcameraservice/device1/CameraHardwareInterface.h
@@ -568,7 +568,7 @@
                 reinterpret_cast<CameraHardwareInterface *>(user);
         return __this->mPreviewWindow.get();
     }
-#define anw(n) __to_anw(((struct camera_preview_window *)n)->user)
+#define anw(n) __to_anw(((struct camera_preview_window *)(n))->user)
 
     static int __dequeue_buffer(struct preview_stream_ops* w,
                                 buffer_handle_t** buffer, int *stride)
diff --git a/services/camera/libcameraservice/device2/Camera2Device.cpp b/services/camera/libcameraservice/device2/Camera2Device.cpp
index c9c990c..d74f976 100644
--- a/services/camera/libcameraservice/device2/Camera2Device.cpp
+++ b/services/camera/libcameraservice/device2/Camera2Device.cpp
@@ -632,6 +632,12 @@
     return NO_INIT;
 }
 
+status_t Camera2Device::prepare(int maxCount, int streamId) {
+    ATRACE_CALL();
+    ALOGE("%s: Camera %d: unimplemented", __FUNCTION__, mId);
+    return NO_INIT;
+}
+
 uint32_t Camera2Device::getDeviceVersion() {
     ATRACE_CALL();
     return mDeviceVersion;
diff --git a/services/camera/libcameraservice/device2/Camera2Device.h b/services/camera/libcameraservice/device2/Camera2Device.h
index 34c1ded..b4d343c 100644
--- a/services/camera/libcameraservice/device2/Camera2Device.h
+++ b/services/camera/libcameraservice/device2/Camera2Device.h
@@ -88,6 +88,7 @@
     // Prepare and tearDown are no-ops
     virtual status_t prepare(int streamId);
     virtual status_t tearDown(int streamId);
+    virtual status_t prepare(int maxCount, int streamId);
 
     virtual uint32_t getDeviceVersion();
     virtual ssize_t getJpegBufferSize(uint32_t width, uint32_t height) const;
diff --git a/services/camera/libcameraservice/device3/Camera3Device.cpp b/services/camera/libcameraservice/device3/Camera3Device.cpp
index 0c941fb..50d9d75 100644
--- a/services/camera/libcameraservice/device3/Camera3Device.cpp
+++ b/services/camera/libcameraservice/device3/Camera3Device.cpp
@@ -44,6 +44,7 @@
 #include <utils/Timers.h>
 
 #include "utils/CameraTraces.h"
+#include "mediautils/SchedulingPolicyService.h"
 #include "device3/Camera3Device.h"
 #include "device3/Camera3OutputStream.h"
 #include "device3/Camera3InputStream.h"
@@ -66,6 +67,7 @@
         mNextResultFrameNumber(0),
         mNextReprocessResultFrameNumber(0),
         mNextShutterFrameNumber(0),
+        mNextReprocessShutterFrameNumber(0),
         mListener(NULL)
 {
     ATRACE_CALL();
@@ -285,19 +287,27 @@
         mStatusTracker->join();
     }
 
+    camera3_device_t *hal3Device;
     {
         Mutex::Autolock l(mLock);
 
         mRequestThread.clear();
         mStatusTracker.clear();
 
-        if (mHal3Device != NULL) {
-            ATRACE_BEGIN("camera3->close");
-            mHal3Device->common.close(&mHal3Device->common);
-            ATRACE_END();
-            mHal3Device = NULL;
-        }
+        hal3Device = mHal3Device;
+    }
 
+    // Call close without internal mutex held, as the HAL close may need to
+    // wait on assorted callbacks,etc, to complete before it can return.
+    if (hal3Device != NULL) {
+        ATRACE_BEGIN("camera3->close");
+        hal3Device->common.close(&hal3Device->common);
+        ATRACE_END();
+    }
+
+    {
+        Mutex::Autolock l(mLock);
+        mHal3Device = NULL;
         internalUpdateStatusLocked(STATUS_UNINITIALIZED);
     }
 
@@ -557,6 +567,18 @@
 
         ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
     }
+
+    // Setup batch size if this is a high speed video recording request.
+    if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
+        auto firstRequest = requestList->begin();
+        for (auto& outputStream : (*firstRequest)->mOutputStreams) {
+            if (outputStream->isVideoStream()) {
+                (*firstRequest)->mBatchSize = requestList->size();
+                break;
+            }
+        }
+    }
+
     return OK;
 }
 
@@ -1398,7 +1420,7 @@
 
     status_t res;
     if (mHal3Device->common.version >= CAMERA_DEVICE_API_VERSION_3_1) {
-        res = mHal3Device->ops->flush(mHal3Device);
+        res = mRequestThread->flush();
     } else {
         Mutex::Autolock l(mLock);
         res = waitUntilDrainedLocked();
@@ -1408,6 +1430,10 @@
 }
 
 status_t Camera3Device::prepare(int streamId) {
+    return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
+}
+
+status_t Camera3Device::prepare(int maxCount, int streamId) {
     ATRACE_CALL();
     ALOGV("%s: Camera %d: Preparing stream %d", __FUNCTION__, mId, streamId);
     Mutex::Autolock il(mInterfaceLock);
@@ -1432,7 +1458,7 @@
         return BAD_VALUE;
     }
 
-    return mPreparerThread->prepare(stream);
+    return mPreparerThread->prepare(maxCount, stream);
 }
 
 status_t Camera3Device::tearDown(int streamId) {
@@ -1583,6 +1609,7 @@
         newRequest->mOutputStreams.push(stream);
     }
     newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
+    newRequest->mBatchSize = 1;
 
     return newRequest;
 }
@@ -1741,6 +1768,21 @@
     // across configure_streams() calls
     mRequestThread->configurationComplete();
 
+    // Boost priority of request thread for high speed recording to SCHED_FIFO
+    if (mIsConstrainedHighSpeedConfiguration) {
+        pid_t requestThreadTid = mRequestThread->getTid();
+        res = requestPriority(getpid(), requestThreadTid,
+                kConstrainedHighSpeedThreadPriority, true);
+        if (res != OK) {
+            ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
+                    strerror(-res), res);
+        } else {
+            ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
+        }
+    } else {
+        // TODO: Set/restore normal priority for normal use cases
+    }
+
     // Update device state
 
     mNeedConfig = false;
@@ -2493,18 +2535,6 @@
 void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
         NotificationListener *listener) {
     ssize_t idx;
-    // Verify ordering of shutter notifications
-    {
-        Mutex::Autolock l(mOutputLock);
-        // TODO: need to track errors for tighter bounds on expected frame number.
-        if (msg.frame_number < mNextShutterFrameNumber) {
-            SET_ERR("Shutter notification out-of-order. Expected "
-                    "notification for frame %d, got frame %d",
-                    mNextShutterFrameNumber, msg.frame_number);
-            return;
-        }
-        mNextShutterFrameNumber = msg.frame_number + 1;
-    }
 
     // Set timestamp for the request in the in-flight tracking
     // and get the request ID to send upstream
@@ -2514,6 +2544,29 @@
         if (idx >= 0) {
             InFlightRequest &r = mInFlightMap.editValueAt(idx);
 
+            // Verify ordering of shutter notifications
+            {
+                Mutex::Autolock l(mOutputLock);
+                // TODO: need to track errors for tighter bounds on expected frame number.
+                if (r.hasInputBuffer) {
+                    if (msg.frame_number < mNextReprocessShutterFrameNumber) {
+                        SET_ERR("Shutter notification out-of-order. Expected "
+                                "notification for frame %d, got frame %d",
+                                mNextReprocessShutterFrameNumber, msg.frame_number);
+                        return;
+                    }
+                    mNextReprocessShutterFrameNumber = msg.frame_number + 1;
+                } else {
+                    if (msg.frame_number < mNextShutterFrameNumber) {
+                        SET_ERR("Shutter notification out-of-order. Expected "
+                                "notification for frame %d, got frame %d",
+                                mNextShutterFrameNumber, msg.frame_number);
+                        return;
+                    }
+                    mNextShutterFrameNumber = msg.frame_number + 1;
+                }
+            }
+
             ALOGVV("Camera %d: %s: Shutter fired for frame %d (id %d) at %" PRId64,
                     mId, __FUNCTION__,
                     msg.frame_number, r.resultExtras.requestId, msg.timestamp);
@@ -2754,6 +2807,17 @@
     return OK;
 }
 
+status_t Camera3Device::RequestThread::flush() {
+    ATRACE_CALL();
+    Mutex::Autolock l(mFlushLock);
+
+    if (mHal3Device->common.version >= CAMERA_DEVICE_API_VERSION_3_1) {
+        return mHal3Device->ops->flush(mHal3Device);
+    }
+
+    return -ENOTSUP;
+}
+
 void Camera3Device::RequestThread::setPaused(bool paused) {
     Mutex::Autolock l(mPauseLock);
     mDoPause = paused;
@@ -2844,7 +2908,7 @@
 }
 
 bool Camera3Device::RequestThread::threadLoop() {
-
+    ATRACE_CALL();
     status_t res;
 
     // Handle paused state.
@@ -2852,147 +2916,31 @@
         return true;
     }
 
-    // Get work to do
-
-    sp<CaptureRequest> nextRequest = waitForNextRequest();
-    if (nextRequest == NULL) {
+    // Wait for the next batch of requests.
+    waitForNextRequestBatch();
+    if (mNextRequests.size() == 0) {
         return true;
     }
 
-    // Create request to HAL
-    camera3_capture_request_t request = camera3_capture_request_t();
-    request.frame_number = nextRequest->mResultExtras.frameNumber;
-    Vector<camera3_stream_buffer_t> outputBuffers;
-
-    // Get the request ID, if any
-    int requestId;
-    camera_metadata_entry_t requestIdEntry =
-            nextRequest->mSettings.find(ANDROID_REQUEST_ID);
+    // Get the latest request ID, if any
+    int latestRequestId;
+    camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
+            captureRequest->mSettings.find(ANDROID_REQUEST_ID);
     if (requestIdEntry.count > 0) {
-        requestId = requestIdEntry.data.i32[0];
+        latestRequestId = requestIdEntry.data.i32[0];
     } else {
-        ALOGW("%s: Did not have android.request.id set in the request",
-                __FUNCTION__);
-        requestId = NAME_NOT_FOUND;
+        ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
+        latestRequestId = NAME_NOT_FOUND;
     }
 
-    // Insert any queued triggers (before metadata is locked)
-    int32_t triggerCount;
-    res = insertTriggers(nextRequest);
-    if (res < 0) {
-        SET_ERR("RequestThread: Unable to insert triggers "
-                "(capture request %d, HAL device: %s (%d)",
-                request.frame_number, strerror(-res), res);
-        cleanUpFailedRequest(request, nextRequest, outputBuffers);
-        return false;
-    }
-    triggerCount = res;
-
-    bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
-
-    // If the request is the same as last, or we had triggers last time
-    if (mPrevRequest != nextRequest || triggersMixedIn) {
-        /**
-         * HAL workaround:
-         * Insert a dummy trigger ID if a trigger is set but no trigger ID is
-         */
-        res = addDummyTriggerIds(nextRequest);
-        if (res != OK) {
-            SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
-                    "(capture request %d, HAL device: %s (%d)",
-                    request.frame_number, strerror(-res), res);
-            cleanUpFailedRequest(request, nextRequest, outputBuffers);
-            return false;
-        }
-
-        /**
-         * The request should be presorted so accesses in HAL
-         *   are O(logn). Sidenote, sorting a sorted metadata is nop.
-         */
-        nextRequest->mSettings.sort();
-        request.settings = nextRequest->mSettings.getAndLock();
-        mPrevRequest = nextRequest;
-        ALOGVV("%s: Request settings are NEW", __FUNCTION__);
-
-        IF_ALOGV() {
-            camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
-            find_camera_metadata_ro_entry(
-                    request.settings,
-                    ANDROID_CONTROL_AF_TRIGGER,
-                    &e
-            );
-            if (e.count > 0) {
-                ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
-                      __FUNCTION__,
-                      request.frame_number,
-                      e.data.u8[0]);
-            }
-        }
-    } else {
-        // leave request.settings NULL to indicate 'reuse latest given'
-        ALOGVV("%s: Request settings are REUSED",
-               __FUNCTION__);
-    }
-
-    uint32_t totalNumBuffers = 0;
-
-    // Fill in buffers
-    if (nextRequest->mInputStream != NULL) {
-        request.input_buffer = &nextRequest->mInputBuffer;
-        totalNumBuffers += 1;
-    } else {
-        request.input_buffer = NULL;
-    }
-
-    outputBuffers.insertAt(camera3_stream_buffer_t(), 0,
-            nextRequest->mOutputStreams.size());
-    request.output_buffers = outputBuffers.array();
-    for (size_t i = 0; i < nextRequest->mOutputStreams.size(); i++) {
-        res = nextRequest->mOutputStreams.editItemAt(i)->
-                getBuffer(&outputBuffers.editItemAt(i));
-        if (res != OK) {
-            // Can't get output buffer from gralloc queue - this could be due to
-            // abandoned queue or other consumer misbehavior, so not a fatal
-            // error
-            ALOGE("RequestThread: Can't get output buffer, skipping request:"
-                    " %s (%d)", strerror(-res), res);
-            {
-                Mutex::Autolock l(mRequestLock);
-                if (mListener != NULL) {
-                    mListener->notifyError(
-                            ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
-                            nextRequest->mResultExtras);
-                }
-            }
-            cleanUpFailedRequest(request, nextRequest, outputBuffers);
-            return true;
-        }
-        request.num_output_buffers++;
-    }
-    totalNumBuffers += request.num_output_buffers;
-
-    // Log request in the in-flight queue
-    sp<Camera3Device> parent = mParent.promote();
-    if (parent == NULL) {
-        // Should not happen, and nowhere to send errors to, so just log it
-        CLOGE("RequestThread: Parent is gone");
-        cleanUpFailedRequest(request, nextRequest, outputBuffers);
-        return false;
-    }
-
-    res = parent->registerInFlight(request.frame_number,
-            totalNumBuffers, nextRequest->mResultExtras,
-            /*hasInput*/request.input_buffer != NULL,
-            nextRequest->mAeTriggerCancelOverride);
-    ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
-           ", burstId = %" PRId32 ".",
-            __FUNCTION__,
-            nextRequest->mResultExtras.requestId, nextRequest->mResultExtras.frameNumber,
-            nextRequest->mResultExtras.burstId);
-    if (res != OK) {
-        SET_ERR("RequestThread: Unable to register new in-flight request:"
-                " %s (%d)", strerror(-res), res);
-        cleanUpFailedRequest(request, nextRequest, outputBuffers);
+    // Prepare a batch of HAL requests and output buffers.
+    res = prepareHalRequests();
+    if (res == TIMED_OUT) {
+        // Not a fatal error if getting output buffers time out.
+        cleanUpFailedRequests(/*sendRequestError*/ true);
+        return true;
+    } else if (res != OK) {
+        cleanUpFailedRequests(/*sendRequestError*/ false);
         return false;
     }
 
@@ -3000,57 +2948,210 @@
     {
         Mutex::Autolock al(mLatestRequestMutex);
 
-        mLatestRequestId = requestId;
+        mLatestRequestId = latestRequestId;
         mLatestRequestSignal.signal();
     }
 
-    // Submit request and block until ready for next one
-    ATRACE_ASYNC_BEGIN("frame capture", request.frame_number);
-    ATRACE_BEGIN("camera3->process_capture_request");
-    res = mHal3Device->ops->process_capture_request(mHal3Device, &request);
-    ATRACE_END();
+    // Submit a batch of requests to HAL.
+    // Use flush lock only when submitting multilple requests in a batch.
+    // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
+    // which may take a long time to finish so synchronizing flush() and
+    // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
+    // For now, only synchronize for high speed recording and we should figure something out for
+    // removing the synchronization.
+    bool useFlushLock = mNextRequests.size() > 1;
 
-    if (res != OK) {
-        // Should only get a failure here for malformed requests or device-level
-        // errors, so consider all errors fatal.  Bad metadata failures should
-        // come through notify.
-        SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
-                " device: %s (%d)", request.frame_number, strerror(-res), res);
-        cleanUpFailedRequest(request, nextRequest, outputBuffers);
-        return false;
+    if (useFlushLock) {
+        mFlushLock.lock();
     }
 
-    // Update the latest request sent to HAL
-    if (request.settings != NULL) { // Don't update them if they were unchanged
-        Mutex::Autolock al(mLatestRequestMutex);
+    ALOGVV("%s: %d: submitting %d requests in a batch.", __FUNCTION__, __LINE__,
+            mNextRequests.size());
+    for (auto& nextRequest : mNextRequests) {
+        // Submit request and block until ready for next one
+        ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
+        ATRACE_BEGIN("camera3->process_capture_request");
+        res = mHal3Device->ops->process_capture_request(mHal3Device, &nextRequest.halRequest);
+        ATRACE_END();
 
-        camera_metadata_t* cloned = clone_camera_metadata(request.settings);
-        mLatestRequest.acquire(cloned);
+        if (res != OK) {
+            // Should only get a failure here for malformed requests or device-level
+            // errors, so consider all errors fatal.  Bad metadata failures should
+            // come through notify.
+            SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
+                    " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
+                    res);
+            cleanUpFailedRequests(/*sendRequestError*/ false);
+            if (useFlushLock) {
+                mFlushLock.unlock();
+            }
+            return false;
+        }
+
+        // Mark that the request has be submitted successfully.
+        nextRequest.submitted = true;
+
+        // Update the latest request sent to HAL
+        if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
+            Mutex::Autolock al(mLatestRequestMutex);
+
+            camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
+            mLatestRequest.acquire(cloned);
+        }
+
+        if (nextRequest.halRequest.settings != NULL) {
+            nextRequest.captureRequest->mSettings.unlock(nextRequest.halRequest.settings);
+        }
+
+        // Remove any previously queued triggers (after unlock)
+        res = removeTriggers(mPrevRequest);
+        if (res != OK) {
+            SET_ERR("RequestThread: Unable to remove triggers "
+                  "(capture request %d, HAL device: %s (%d)",
+                  nextRequest.halRequest.frame_number, strerror(-res), res);
+            cleanUpFailedRequests(/*sendRequestError*/ false);
+            if (useFlushLock) {
+                mFlushLock.unlock();
+            }
+            return false;
+        }
     }
 
-    if (request.settings != NULL) {
-        nextRequest->mSettings.unlock(request.settings);
+    if (useFlushLock) {
+        mFlushLock.unlock();
     }
 
     // Unset as current request
     {
         Mutex::Autolock l(mRequestLock);
-        mNextRequest.clear();
+        mNextRequests.clear();
     }
 
-    // Remove any previously queued triggers (after unlock)
-    res = removeTriggers(mPrevRequest);
-    if (res != OK) {
-        SET_ERR("RequestThread: Unable to remove triggers "
-              "(capture request %d, HAL device: %s (%d)",
-              request.frame_number, strerror(-res), res);
-        return false;
-    }
-    mPrevTriggers = triggerCount;
-
     return true;
 }
 
+status_t Camera3Device::RequestThread::prepareHalRequests() {
+    ATRACE_CALL();
+
+    for (auto& nextRequest : mNextRequests) {
+        sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
+        camera3_capture_request_t* halRequest = &nextRequest.halRequest;
+        Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
+
+        // Prepare a request to HAL
+        halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
+
+        // Insert any queued triggers (before metadata is locked)
+        status_t res = insertTriggers(captureRequest);
+
+        if (res < 0) {
+            SET_ERR("RequestThread: Unable to insert triggers "
+                    "(capture request %d, HAL device: %s (%d)",
+                    halRequest->frame_number, strerror(-res), res);
+            return INVALID_OPERATION;
+        }
+        int triggerCount = res;
+        bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
+        mPrevTriggers = triggerCount;
+
+        // If the request is the same as last, or we had triggers last time
+        if (mPrevRequest != captureRequest || triggersMixedIn) {
+            /**
+             * HAL workaround:
+             * Insert a dummy trigger ID if a trigger is set but no trigger ID is
+             */
+            res = addDummyTriggerIds(captureRequest);
+            if (res != OK) {
+                SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
+                        "(capture request %d, HAL device: %s (%d)",
+                        halRequest->frame_number, strerror(-res), res);
+                return INVALID_OPERATION;
+            }
+
+            /**
+             * The request should be presorted so accesses in HAL
+             *   are O(logn). Sidenote, sorting a sorted metadata is nop.
+             */
+            captureRequest->mSettings.sort();
+            halRequest->settings = captureRequest->mSettings.getAndLock();
+            mPrevRequest = captureRequest;
+            ALOGVV("%s: Request settings are NEW", __FUNCTION__);
+
+            IF_ALOGV() {
+                camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
+                find_camera_metadata_ro_entry(
+                        halRequest->settings,
+                        ANDROID_CONTROL_AF_TRIGGER,
+                        &e
+                );
+                if (e.count > 0) {
+                    ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
+                          __FUNCTION__,
+                          halRequest->frame_number,
+                          e.data.u8[0]);
+                }
+            }
+        } else {
+            // leave request.settings NULL to indicate 'reuse latest given'
+            ALOGVV("%s: Request settings are REUSED",
+                   __FUNCTION__);
+        }
+
+        uint32_t totalNumBuffers = 0;
+
+        // Fill in buffers
+        if (captureRequest->mInputStream != NULL) {
+            halRequest->input_buffer = &captureRequest->mInputBuffer;
+            totalNumBuffers += 1;
+        } else {
+            halRequest->input_buffer = NULL;
+        }
+
+        outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
+                captureRequest->mOutputStreams.size());
+        halRequest->output_buffers = outputBuffers->array();
+        for (size_t i = 0; i < captureRequest->mOutputStreams.size(); i++) {
+            res = captureRequest->mOutputStreams.editItemAt(i)->
+                    getBuffer(&outputBuffers->editItemAt(i));
+            if (res != OK) {
+                // Can't get output buffer from gralloc queue - this could be due to
+                // abandoned queue or other consumer misbehavior, so not a fatal
+                // error
+                ALOGE("RequestThread: Can't get output buffer, skipping request:"
+                        " %s (%d)", strerror(-res), res);
+
+                return TIMED_OUT;
+            }
+            halRequest->num_output_buffers++;
+        }
+        totalNumBuffers += halRequest->num_output_buffers;
+
+        // Log request in the in-flight queue
+        sp<Camera3Device> parent = mParent.promote();
+        if (parent == NULL) {
+            // Should not happen, and nowhere to send errors to, so just log it
+            CLOGE("RequestThread: Parent is gone");
+            return INVALID_OPERATION;
+        }
+        res = parent->registerInFlight(halRequest->frame_number,
+                totalNumBuffers, captureRequest->mResultExtras,
+                /*hasInput*/halRequest->input_buffer != NULL,
+                captureRequest->mAeTriggerCancelOverride);
+        ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
+               ", burstId = %" PRId32 ".",
+                __FUNCTION__,
+                captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
+                captureRequest->mResultExtras.burstId);
+        if (res != OK) {
+            SET_ERR("RequestThread: Unable to register new in-flight request:"
+                    " %s (%d)", strerror(-res), res);
+            return INVALID_OPERATION;
+        }
+    }
+
+    return OK;
+}
+
 CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
     Mutex::Autolock al(mLatestRequestMutex);
 
@@ -3063,11 +3164,13 @@
         sp<Camera3StreamInterface>& stream) {
     Mutex::Autolock l(mRequestLock);
 
-    if (mNextRequest != nullptr) {
-        for (const auto& s : mNextRequest->mOutputStreams) {
-            if (stream == s) return true;
+    for (const auto& nextRequest : mNextRequests) {
+        if (!nextRequest.submitted) {
+            for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
+                if (stream == s) return true;
+            }
+            if (stream == nextRequest.captureRequest->mInputStream) return true;
         }
-        if (stream == mNextRequest->mInputStream) return true;
     }
 
     for (const auto& request : mRequestQueue) {
@@ -3087,37 +3190,95 @@
     return false;
 }
 
-void Camera3Device::RequestThread::cleanUpFailedRequest(
-        camera3_capture_request_t &request,
-        sp<CaptureRequest> &nextRequest,
-        Vector<camera3_stream_buffer_t> &outputBuffers) {
+void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
+    if (mNextRequests.empty()) {
+        return;
+    }
 
-    if (request.settings != NULL) {
-        nextRequest->mSettings.unlock(request.settings);
-    }
-    if (nextRequest->mInputStream != NULL) {
-        nextRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
-        nextRequest->mInputStream->returnInputBuffer(nextRequest->mInputBuffer);
-    }
-    for (size_t i = 0; i < request.num_output_buffers; i++) {
-        outputBuffers.editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
-        nextRequest->mOutputStreams.editItemAt(i)->returnBuffer(
-            outputBuffers[i], 0);
+    for (auto& nextRequest : mNextRequests) {
+        // Skip the ones that have been submitted successfully.
+        if (nextRequest.submitted) {
+            continue;
+        }
+
+        sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
+        camera3_capture_request_t* halRequest = &nextRequest.halRequest;
+        Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
+
+        if (halRequest->settings != NULL) {
+            captureRequest->mSettings.unlock(halRequest->settings);
+        }
+
+        if (captureRequest->mInputStream != NULL) {
+            captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
+            captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
+        }
+
+        for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
+            outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
+            captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
+        }
+
+        if (sendRequestError) {
+            Mutex::Autolock l(mRequestLock);
+            if (mListener != NULL) {
+                mListener->notifyError(
+                        ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
+                        captureRequest->mResultExtras);
+            }
+        }
     }
 
     Mutex::Autolock l(mRequestLock);
-    mNextRequest.clear();
+    mNextRequests.clear();
 }
 
-sp<Camera3Device::CaptureRequest>
-        Camera3Device::RequestThread::waitForNextRequest() {
-    status_t res;
-    sp<CaptureRequest> nextRequest;
-
+void Camera3Device::RequestThread::waitForNextRequestBatch() {
     // Optimized a bit for the simple steady-state case (single repeating
     // request), to avoid putting that request in the queue temporarily.
     Mutex::Autolock l(mRequestLock);
 
+    assert(mNextRequests.empty());
+
+    NextRequest nextRequest;
+    nextRequest.captureRequest = waitForNextRequestLocked();
+    if (nextRequest.captureRequest == nullptr) {
+        return;
+    }
+
+    nextRequest.halRequest = camera3_capture_request_t();
+    nextRequest.submitted = false;
+    mNextRequests.add(nextRequest);
+
+    // Wait for additional requests
+    const size_t batchSize = nextRequest.captureRequest->mBatchSize;
+
+    for (size_t i = 1; i < batchSize; i++) {
+        NextRequest additionalRequest;
+        additionalRequest.captureRequest = waitForNextRequestLocked();
+        if (additionalRequest.captureRequest == nullptr) {
+            break;
+        }
+
+        additionalRequest.halRequest = camera3_capture_request_t();
+        additionalRequest.submitted = false;
+        mNextRequests.add(additionalRequest);
+    }
+
+    if (mNextRequests.size() < batchSize) {
+        ALOGE("RequestThread: only get %d out of %d requests. Skipping requests.",
+                mNextRequests.size(), batchSize);
+        cleanUpFailedRequests(/*sendRequestError*/true);
+    }
+
+    return;
+}
+
+sp<Camera3Device::CaptureRequest>
+        Camera3Device::RequestThread::waitForNextRequestLocked() {
+    status_t res;
+    sp<CaptureRequest> nextRequest;
+
     while (mRequestQueue.empty()) {
         if (!mRepeatingRequests.empty()) {
             // Always atomically enqueue all requests in a repeating request
@@ -3212,8 +3373,6 @@
 
     handleAePrecaptureCancelRequest(nextRequest);
 
-    mNextRequest = nextRequest;
-
     return nextRequest;
 }
 
@@ -3478,12 +3637,12 @@
     clear();
 }
 
-status_t Camera3Device::PreparerThread::prepare(sp<Camera3StreamInterface>& stream) {
+status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
     status_t res;
 
     Mutex::Autolock l(mLock);
 
-    res = stream->startPrepare();
+    res = stream->startPrepare(maxCount);
     if (res == OK) {
         // No preparation needed, fire listener right off
         ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
diff --git a/services/camera/libcameraservice/device3/Camera3Device.h b/services/camera/libcameraservice/device3/Camera3Device.h
index 5287058..2cd5af3 100644
--- a/services/camera/libcameraservice/device3/Camera3Device.h
+++ b/services/camera/libcameraservice/device3/Camera3Device.h
@@ -62,6 +62,7 @@
             public CameraDeviceBase,
             private camera3_callback_ops {
   public:
+
     Camera3Device(int id);
 
     virtual ~Camera3Device();
@@ -143,6 +144,8 @@
 
     virtual status_t tearDown(int streamId);
 
+    virtual status_t prepare(int maxCount, int streamId);
+
     virtual uint32_t getDeviceVersion();
 
     virtual ssize_t getJpegBufferSize(uint32_t width, uint32_t height) const;
@@ -158,6 +161,8 @@
     static const nsecs_t       kActiveTimeout     = 500000000;  // 500 ms
     static const size_t        kInFlightWarnLimit = 20;
     static const size_t        kInFlightWarnLimitHighSpeed = 256; // batch size 32 * pipe depth 8
+    // SCHED_FIFO priority for request submission thread in HFR mode
+    static const int           kConstrainedHighSpeedThreadPriority = 1;
 
     struct                     RequestTrigger;
     // minimal jpeg buffer size: 256KB + blob header
@@ -261,6 +266,11 @@
         // Used to cancel AE precapture trigger for devices doesn't support
         // CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL
         AeTriggerCancelOverride_t           mAeTriggerCancelOverride;
+        // The number of requests that should be submitted to HAL at a time.
+        // For example, if batch size is 8, this request and the following 7
+        // requests will be submitted to HAL at a time. The batch size for
+        // the following 7 requests will be ignored by the request thread.
+        int                                 mBatchSize;
     };
     typedef List<sp<CaptureRequest> > RequestList;
 
@@ -438,6 +448,11 @@
                        int64_t *lastFrameNumber = NULL);
 
         /**
+         * Flush all pending requests in HAL.
+         */
+        status_t flush();
+
+        /**
          * Queue a trigger to be dispatched with the next outgoing
          * process_capture_request. The settings for that request only
          * will be temporarily rewritten to add the trigger tag/value.
@@ -498,16 +513,30 @@
 
         static const nsecs_t kRequestTimeout = 50e6; // 50 ms
 
-        // Waits for a request, or returns NULL if times out.
-        sp<CaptureRequest> waitForNextRequest();
+        // Used to prepare a batch of requests.
+        struct NextRequest {
+            sp<CaptureRequest>              captureRequest;
+            camera3_capture_request_t       halRequest;
+            Vector<camera3_stream_buffer_t> outputBuffers;
+            bool                            submitted;
+        };
 
-        // Return buffers, etc, for a request that couldn't be fully
-        // constructed. The buffers will be returned in the ERROR state
-        // to mark them as not having valid data.
-        // All arguments will be modified.
-        void cleanUpFailedRequest(camera3_capture_request_t &request,
-                sp<CaptureRequest> &nextRequest,
-                Vector<camera3_stream_buffer_t> &outputBuffers);
+        // Wait for the next batch of requests and put them in mNextRequests. mNextRequests will
+        // be empty if it times out.
+        void waitForNextRequestBatch();
+
+        // Waits for a request, or returns NULL if times out. Must be called with mRequestLock hold.
+        sp<CaptureRequest> waitForNextRequestLocked();
+
+        // Prepare HAL requests and output buffers in mNextRequests. Return TIMED_OUT if getting any
+        // output buffer timed out. If an error is returned, the caller should clean up the pending
+        // request batch.
+        status_t prepareHalRequests();
+
+        // Return buffers, etc, for requests in mNextRequests that couldn't be fully constructed and
+        // send request errors if sendRequestError is true. The buffers will be returned in the
+        // ERROR state to mark them as not having valid data. mNextRequests will be cleared.
+        void cleanUpFailedRequests(bool sendRequestError);
 
         // Pause handling
         bool               waitIfPaused();
@@ -536,10 +565,13 @@
         Condition          mRequestSignal;
         RequestList        mRequestQueue;
         RequestList        mRepeatingRequests;
-        // The next request being prepped for submission to the HAL, no longer
+        // The next batch of requests being prepped for submission to the HAL, no longer
         // on the request queue. Read-only even with mRequestLock held, outside
         // of threadLoop
-        sp<const CaptureRequest> mNextRequest;
+        Vector<NextRequest> mNextRequests;
+
+        // To protect flush() and sending a request batch to HAL.
+        Mutex              mFlushLock;
 
         bool               mReconfigured;
 
@@ -698,10 +730,11 @@
         void setNotificationListener(NotificationListener *listener);
 
         /**
-         * Queue up a stream to be prepared. Streams are processed by
-         * a background thread in FIFO order
+         * Queue up a stream to be prepared. Streams are processed by a background thread in FIFO
+         * order.  Pre-allocate up to maxCount buffers for the stream, or the maximum number needed
+         * for the pipeline if maxCount is ALLOCATE_PIPELINE_MAX.
          */
-        status_t prepare(sp<camera3::Camera3StreamInterface>& stream);
+        status_t prepare(int maxCount, sp<camera3::Camera3StreamInterface>& stream);
 
         /**
          * Cancel all current and pending stream preparation
@@ -738,7 +771,10 @@
     uint32_t               mNextResultFrameNumber;
     // the minimal frame number of the next reprocess result
     uint32_t               mNextReprocessResultFrameNumber;
+    // the minimal frame number of the next non-reprocess shutter
     uint32_t               mNextShutterFrameNumber;
+    // the minimal frame number of the next reprocess shutter
+    uint32_t               mNextReprocessShutterFrameNumber;
     List<CaptureResult>   mResultQueue;
     Condition              mResultSignal;
     NotificationListener  *mListener;
diff --git a/services/camera/libcameraservice/device3/Camera3DummyStream.cpp b/services/camera/libcameraservice/device3/Camera3DummyStream.cpp
index ecb8ac8..1d9d04f 100644
--- a/services/camera/libcameraservice/device3/Camera3DummyStream.cpp
+++ b/services/camera/libcameraservice/device3/Camera3DummyStream.cpp
@@ -92,6 +92,10 @@
     return OK;
 }
 
+bool Camera3DummyStream::isVideoStream() const {
+    return false;
+}
+
 }; // namespace camera3
 
 }; // namespace android
diff --git a/services/camera/libcameraservice/device3/Camera3DummyStream.h b/services/camera/libcameraservice/device3/Camera3DummyStream.h
index 3a3dbf4..97c0c96 100644
--- a/services/camera/libcameraservice/device3/Camera3DummyStream.h
+++ b/services/camera/libcameraservice/device3/Camera3DummyStream.h
@@ -54,6 +54,11 @@
 
     status_t         setTransform(int transform);
 
+    /**
+     * Return if this output stream is for video encoding.
+     */
+    bool isVideoStream() const;
+
   protected:
 
     /**
diff --git a/services/camera/libcameraservice/device3/Camera3OutputStream.cpp b/services/camera/libcameraservice/device3/Camera3OutputStream.cpp
index 8c611d5..3f0a736 100644
--- a/services/camera/libcameraservice/device3/Camera3OutputStream.cpp
+++ b/services/camera/libcameraservice/device3/Camera3OutputStream.cpp
@@ -426,6 +426,17 @@
     return res;
 }
 
+bool Camera3OutputStream::isVideoStream() const {
+    uint32_t usage = 0;
+    status_t res = getEndpointUsage(&usage);
+    if (res != OK) {
+        ALOGE("%s: getting end point usage failed: %s (%d).", __FUNCTION__, strerror(-res), res);
+        return false;
+    }
+
+    return (usage & GRALLOC_USAGE_HW_VIDEO_ENCODER) != 0;
+}
+
 }; // namespace camera3
 
 }; // namespace android
diff --git a/services/camera/libcameraservice/device3/Camera3OutputStream.h b/services/camera/libcameraservice/device3/Camera3OutputStream.h
index 941d693..3c083ec 100644
--- a/services/camera/libcameraservice/device3/Camera3OutputStream.h
+++ b/services/camera/libcameraservice/device3/Camera3OutputStream.h
@@ -64,6 +64,11 @@
      */
     status_t         setTransform(int transform);
 
+    /**
+     * Return if this output stream is for video encoding.
+     */
+    bool isVideoStream() const;
+
   protected:
     Camera3OutputStream(int id, camera3_stream_type_t type,
             uint32_t width, uint32_t height, int format,
diff --git a/services/camera/libcameraservice/device3/Camera3OutputStreamInterface.h b/services/camera/libcameraservice/device3/Camera3OutputStreamInterface.h
index aae72cf..df89b34 100644
--- a/services/camera/libcameraservice/device3/Camera3OutputStreamInterface.h
+++ b/services/camera/libcameraservice/device3/Camera3OutputStreamInterface.h
@@ -34,6 +34,11 @@
      * HAL_TRANSFORM_* / NATIVE_WINDOW_TRANSFORM_* constants.
      */
     virtual status_t setTransform(int transform) = 0;
+
+    /**
+     * Return if this output stream is for video encoding.
+     */
+    virtual bool isVideoStream() const = 0;
 };
 
 } // namespace camera3
diff --git a/services/camera/libcameraservice/device3/Camera3Stream.cpp b/services/camera/libcameraservice/device3/Camera3Stream.cpp
index 2527fd6..96299b3 100644
--- a/services/camera/libcameraservice/device3/Camera3Stream.cpp
+++ b/services/camera/libcameraservice/device3/Camera3Stream.cpp
@@ -53,7 +53,8 @@
     mName(String8::format("Camera3Stream[%d]", id)),
     mMaxSize(maxSize),
     mState(STATE_CONSTRUCTED),
-    mStatusId(StatusTracker::NO_STATUS_ID) {
+    mStatusId(StatusTracker::NO_STATUS_ID),
+    mLastMaxCount(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX) {
 
     camera3_stream::stream_type = type;
     camera3_stream::width = width;
@@ -252,12 +253,18 @@
     return mStreamUnpreparable;
 }
 
-status_t Camera3Stream::startPrepare() {
+status_t Camera3Stream::startPrepare(int maxCount) {
     ATRACE_CALL();
 
     Mutex::Autolock l(mLock);
     status_t res = OK;
 
+    if (maxCount < 0) {
+        ALOGE("%s: Stream %d: Can't prepare stream if max buffer count (%d) is < 0",
+                __FUNCTION__, mId, maxCount);
+        return BAD_VALUE;
+    }
+
     // This function should be only called when the stream is configured already.
     if (mState != STATE_CONFIGURED) {
         ALOGE("%s: Stream %d: Can't prepare stream if stream is not in CONFIGURED "
@@ -279,9 +286,19 @@
         return INVALID_OPERATION;
     }
 
+
+
+    size_t pipelineMax = getBufferCountLocked();
+    size_t clampedCount = (pipelineMax < static_cast<size_t>(maxCount)) ?
+            pipelineMax : static_cast<size_t>(maxCount);
+    size_t bufferCount = (maxCount == Camera3StreamInterface::ALLOCATE_PIPELINE_MAX) ?
+            pipelineMax : clampedCount;
+
+    mPrepared = bufferCount <= mLastMaxCount;
+
     if (mPrepared) return OK;
 
-    size_t bufferCount = getBufferCountLocked();
+    mLastMaxCount = bufferCount;
 
     mPreparedBuffers.insertAt(camera3_stream_buffer_t(), /*index*/0, bufferCount);
     mPreparedBufferIdx = 0;
@@ -438,8 +455,9 @@
         res = mOutputBufferReturnedSignal.waitRelative(mLock, kWaitForBufferDuration);
         if (res != OK) {
             if (res == TIMED_OUT) {
-                ALOGE("%s: wait for output buffer return timed out after %lldms", __FUNCTION__,
-                        kWaitForBufferDuration / 1000000LL);
+                ALOGE("%s: wait for output buffer return timed out after %lldms (max_buffers %d)",
+                        __FUNCTION__, kWaitForBufferDuration / 1000000LL,
+                        camera3_stream::max_buffers);
             }
             return res;
         }
@@ -469,9 +487,12 @@
     status_t res = returnBufferLocked(buffer, timestamp);
     if (res == OK) {
         fireBufferListenersLocked(buffer, /*acquired*/false, /*output*/true);
-        mOutputBufferReturnedSignal.signal();
     }
 
+    // Even if returning the buffer failed, we still want to signal whoever is waiting for the
+    // buffer to be returned.
+    mOutputBufferReturnedSignal.signal();
+
     return res;
 }
 
diff --git a/services/camera/libcameraservice/device3/Camera3Stream.h b/services/camera/libcameraservice/device3/Camera3Stream.h
index bab2177..753280b 100644
--- a/services/camera/libcameraservice/device3/Camera3Stream.h
+++ b/services/camera/libcameraservice/device3/Camera3Stream.h
@@ -188,7 +188,9 @@
 
     /**
      * Start stream preparation. May only be called in the CONFIGURED state,
-     * when no valid buffers have yet been returned to this stream.
+     * when no valid buffers have yet been returned to this stream. Prepares
+     * up to maxCount buffers, or the maximum number of buffers needed by the
+     * pipeline if maxCount is ALLOCATE_PIPELINE_MAX.
      *
      * If no prepartion is necessary, returns OK and does not transition to
      * PREPARING state. Otherwise, returns NOT_ENOUGH_DATA and transitions
@@ -204,7 +206,7 @@
      *    INVALID_OPERATION if called when not in CONFIGURED state, or a
      *        valid buffer has already been returned to this stream.
      */
-    status_t         startPrepare();
+    status_t         startPrepare(int maxCount);
 
     /**
      * Check if the stream is mid-preparing.
@@ -444,6 +446,9 @@
     Vector<camera3_stream_buffer_t> mPreparedBuffers;
     size_t mPreparedBufferIdx;
 
+    // Number of buffers allocated on last prepare call.
+    int mLastMaxCount;
+
 }; // class Camera3Stream
 
 }; // namespace camera3
diff --git a/services/camera/libcameraservice/device3/Camera3StreamInterface.h b/services/camera/libcameraservice/device3/Camera3StreamInterface.h
index c086eaf..54009ae 100644
--- a/services/camera/libcameraservice/device3/Camera3StreamInterface.h
+++ b/services/camera/libcameraservice/device3/Camera3StreamInterface.h
@@ -34,6 +34,11 @@
  */
 class Camera3StreamInterface : public virtual RefBase {
   public:
+
+    enum {
+        ALLOCATE_PIPELINE_MAX = 0, // Allocate max buffers used by a given surface
+    };
+
     /**
      * Get the stream's ID
      */
@@ -98,7 +103,9 @@
 
     /**
      * Start stream preparation. May only be called in the CONFIGURED state,
-     * when no valid buffers have yet been returned to this stream.
+     * when no valid buffers have yet been returned to this stream. Prepares
+     * up to maxCount buffers, or the maximum number of buffers needed by the
+     * pipeline if maxCount is ALLOCATE_PIPELINE_MAX.
      *
      * If no prepartion is necessary, returns OK and does not transition to
      * PREPARING state. Otherwise, returns NOT_ENOUGH_DATA and transitions
@@ -112,7 +119,7 @@
      *    INVALID_OPERATION if called when not in CONFIGURED state, or a
      *        valid buffer has already been returned to this stream.
      */
-    virtual status_t startPrepare() = 0;
+    virtual status_t startPrepare(int maxCount) = 0;
 
     /**
      * Check if the stream is mid-preparing.
diff --git a/services/camera/libcameraservice/device3/Camera3ZslStream.cpp b/services/camera/libcameraservice/device3/Camera3ZslStream.cpp
index eefcb44..d753b71 100644
--- a/services/camera/libcameraservice/device3/Camera3ZslStream.cpp
+++ b/services/camera/libcameraservice/device3/Camera3ZslStream.cpp
@@ -40,7 +40,7 @@
         SELECT_NEITHER = 0,
     };
 
-    TimestampFinder(nsecs_t timestamp) : mTimestamp(timestamp) {}
+    explicit TimestampFinder(nsecs_t timestamp) : mTimestamp(timestamp) {}
     ~TimestampFinder() {}
 
     template <typename T>
diff --git a/services/mediaresourcemanager/ResourceManagerService.cpp b/services/mediaresourcemanager/ResourceManagerService.cpp
index e54cc5a..6781a36 100644
--- a/services/mediaresourcemanager/ResourceManagerService.cpp
+++ b/services/mediaresourcemanager/ResourceManagerService.cpp
@@ -90,26 +90,46 @@
 }
 
 status_t ResourceManagerService::dump(int fd, const Vector<String16>& /* args */) {
-    Mutex::Autolock lock(mLock);
-
     String8 result;
+
+    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
+        result.format("Permission Denial: "
+                "can't dump ResourceManagerService from pid=%d, uid=%d\n",
+                IPCThreadState::self()->getCallingPid(),
+                IPCThreadState::self()->getCallingUid());
+        write(fd, result.string(), result.size());
+        return PERMISSION_DENIED;
+    }
+
+    PidResourceInfosMap mapCopy;
+    bool supportsMultipleSecureCodecs;
+    bool supportsSecureWithNonSecureCodec;
+    String8 serviceLog;
+    {
+        Mutex::Autolock lock(mLock);
+        mapCopy = mMap;  // Shadow copy, real copy will happen on write.
+        supportsMultipleSecureCodecs = mSupportsMultipleSecureCodecs;
+        supportsSecureWithNonSecureCodec = mSupportsSecureWithNonSecureCodec;
+        serviceLog = mServiceLog->toString("    " /* linePrefix */);
+    }
+
     const size_t SIZE = 256;
     char buffer[SIZE];
-
     snprintf(buffer, SIZE, "ResourceManagerService: %p\n", this);
     result.append(buffer);
     result.append("  Policies:\n");
-    snprintf(buffer, SIZE, "    SupportsMultipleSecureCodecs: %d\n", mSupportsMultipleSecureCodecs);
+    snprintf(buffer, SIZE, "    SupportsMultipleSecureCodecs: %d\n", supportsMultipleSecureCodecs);
     result.append(buffer);
-    snprintf(buffer, SIZE, "    SupportsSecureWithNonSecureCodec: %d\n", mSupportsSecureWithNonSecureCodec);
+    snprintf(buffer, SIZE, "    SupportsSecureWithNonSecureCodec: %d\n",
+            supportsSecureWithNonSecureCodec);
     result.append(buffer);
 
     result.append("  Processes:\n");
-    for (size_t i = 0; i < mMap.size(); ++i) {
-        snprintf(buffer, SIZE, "    Pid: %d\n", mMap.keyAt(i));
+    for (size_t i = 0; i < mapCopy.size(); ++i) {
+        snprintf(buffer, SIZE, "    Pid: %d\n", mapCopy.keyAt(i));
         result.append(buffer);
 
-        const ResourceInfos &infos = mMap.valueAt(i);
+        const ResourceInfos &infos = mapCopy.valueAt(i);
         for (size_t j = 0; j < infos.size(); ++j) {
             result.append("      Client:\n");
             snprintf(buffer, SIZE, "        Id: %lld\n", (long long)infos[j].clientId);
@@ -127,7 +147,7 @@
         }
     }
     result.append("  Events logs (most recent at top):\n");
-    result.append(mServiceLog->toString("    " /* linePrefix */));
+    result.append(serviceLog);
 
     write(fd, result.string(), result.size());
     return OK;
@@ -298,6 +318,10 @@
         }
     }
 
+    if (failedClient == NULL) {
+        return true;
+    }
+
     {
         Mutex::Autolock lock(mLock);
         bool found = false;
@@ -320,7 +344,7 @@
         }
     }
 
-    return (failedClient == NULL);
+    return false;
 }
 
 bool ResourceManagerService::getAllClients_l(
diff --git a/soundtrigger/ISoundTrigger.cpp b/soundtrigger/ISoundTrigger.cpp
index eecc1ea..25332a4 100644
--- a/soundtrigger/ISoundTrigger.cpp
+++ b/soundtrigger/ISoundTrigger.cpp
@@ -37,7 +37,7 @@
 class BpSoundTrigger: public BpInterface<ISoundTrigger>
 {
 public:
-    BpSoundTrigger(const sp<IBinder>& impl)
+    explicit BpSoundTrigger(const sp<IBinder>& impl)
         : BpInterface<ISoundTrigger>(impl)
     {
     }
@@ -60,11 +60,13 @@
         data.writeInterfaceToken(ISoundTrigger::getInterfaceDescriptor());
         data.writeStrongBinder(IInterface::asBinder(modelMemory));
         status_t status = remote()->transact(LOAD_SOUND_MODEL, data, &reply);
-        if (status != NO_ERROR ||
-                (status = (status_t)reply.readInt32()) != NO_ERROR) {
+        if (status != NO_ERROR) {
             return status;
         }
-        reply.read(handle, sizeof(sound_model_handle_t));
+        status = (status_t)reply.readInt32();
+        if (status == NO_ERROR) {
+            reply.read(handle, sizeof(sound_model_handle_t));
+        }
         return status;
     }
 
@@ -74,7 +76,7 @@
         data.writeInterfaceToken(ISoundTrigger::getInterfaceDescriptor());
         data.write(&handle, sizeof(sound_model_handle_t));
         status_t status = remote()->transact(UNLOAD_SOUND_MODEL, data, &reply);
-        if (status != NO_ERROR) {
+        if (status == NO_ERROR) {
             status = (status_t)reply.readInt32();
         }
         return status;
@@ -93,7 +95,7 @@
         }
         data.writeStrongBinder(IInterface::asBinder(dataMemory));
         status_t status = remote()->transact(START_RECOGNITION, data, &reply);
-        if (status != NO_ERROR) {
+        if (status == NO_ERROR) {
             status = (status_t)reply.readInt32();
         }
         return status;
@@ -105,7 +107,7 @@
         data.writeInterfaceToken(ISoundTrigger::getInterfaceDescriptor());
         data.write(&handle, sizeof(sound_model_handle_t));
         status_t status = remote()->transact(STOP_RECOGNITION, data, &reply);
-        if (status != NO_ERROR) {
+        if (status == NO_ERROR) {
             status = (status_t)reply.readInt32();
         }
         return status;
diff --git a/soundtrigger/ISoundTriggerClient.cpp b/soundtrigger/ISoundTriggerClient.cpp
index e0d3add..1385631 100644
--- a/soundtrigger/ISoundTriggerClient.cpp
+++ b/soundtrigger/ISoundTriggerClient.cpp
@@ -35,7 +35,7 @@
 {
 
 public:
-    BpSoundTriggerClient(const sp<IBinder>& impl)
+    explicit BpSoundTriggerClient(const sp<IBinder>& impl)
         : BpInterface<ISoundTriggerClient>(impl)
     {
     }
diff --git a/soundtrigger/ISoundTriggerHwService.cpp b/soundtrigger/ISoundTriggerHwService.cpp
index e14a771..d44f5cb 100644
--- a/soundtrigger/ISoundTriggerHwService.cpp
+++ b/soundtrigger/ISoundTriggerHwService.cpp
@@ -45,7 +45,7 @@
 class BpSoundTriggerHwService: public BpInterface<ISoundTriggerHwService>
 {
 public:
-    BpSoundTriggerHwService(const sp<IBinder>& impl)
+    explicit BpSoundTriggerHwService(const sp<IBinder>& impl)
         : BpInterface<ISoundTriggerHwService>(impl)
     {
     }
@@ -85,8 +85,11 @@
         data.writeInterfaceToken(ISoundTriggerHwService::getInterfaceDescriptor());
         data.write(&handle, sizeof(sound_trigger_module_handle_t));
         data.writeStrongBinder(IInterface::asBinder(client));
-        remote()->transact(ATTACH, data, &reply);
-        status_t status = reply.readInt32();
+        status_t status = remote()->transact(ATTACH, data, &reply);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        status = reply.readInt32();
         if (reply.readInt32() != 0) {
             module = interface_cast<ISoundTrigger>(reply.readStrongBinder());
         }