Merge "Fix WaveGenerator memory leak"
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 694e9c3..a9d0836 100644
--- a/camera/ICameraServiceProxy.cpp
+++ b/camera/ICameraServiceProxy.cpp
@@ -26,7 +26,8 @@
 
 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;
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 2a9fd2b..1aca242 100644
--- a/camera/camera2/ICameraDeviceUser.cpp
+++ b/camera/camera2/ICameraDeviceUser.cpp
@@ -69,7 +69,7 @@
 class BpCameraDeviceUser : public BpInterface<ICameraDeviceUser>
 {
 public:
-    BpCameraDeviceUser(const sp<IBinder>& impl)
+    explicit BpCameraDeviceUser(const sp<IBinder>& impl)
         : BpInterface<ICameraDeviceUser>(impl)
     {
     }
diff --git a/camera/tests/Android.mk b/camera/tests/Android.mk
index 3777d94..de18df8 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 f2e14b6..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;
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/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/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/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/MediaCodec.h b/include/media/stagefright/MediaCodec.h
index cdfa159..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,
@@ -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);
 
diff --git a/include/media/stagefright/MediaCodecList.h b/include/media/stagefright/MediaCodecList.h
index bf4db87..44dbde0 100644
--- a/include/media/stagefright/MediaCodecList.h
+++ b/include/media/stagefright/MediaCodecList.h
@@ -65,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/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/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/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/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/AudioTrack.cpp b/media/libmedia/AudioTrack.cpp
index 82b6736..b999623 100644
--- a/media/libmedia/AudioTrack.cpp
+++ b/media/libmedia/AudioTrack.cpp
@@ -2332,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/IAudioFlinger.cpp b/media/libmedia/IAudioFlinger.cpp
index 0bf503a..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)
     {
     }
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 76b5924..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)
     {
     }
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 a398ff7..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) {
     }
 
@@ -321,7 +321,9 @@
 
             if (overflow || sumSubsampleSizes != totalSize) {
                 result = -EINVAL;
-            } else if (offset + totalSize > sharedBuffer->size()) {
+            } 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 faf5795..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)
     {
     }
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 942aec3..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)
     {
     }
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 5423c2a..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)
@@ -1079,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 037a236..68f2403 100644
--- a/media/libmedia/ToneGenerator.cpp
+++ b/media/libmedia/ToneGenerator.cpp
@@ -813,11 +813,13 @@
     mProcessSize = (mSamplingRate * 20) / 1000;
 
     char value[PROPERTY_VALUE_MAX];
-    property_get("gsm.operator.iso-country", value, "");
-    if (strcmp(value,"us") == 0 ||
-        strcmp(value,"ca") == 0) {
+    if (property_get("gsm.operator.iso-country", value, "") == 0) {
+        property_get("gsm.sim.operator.iso-country", value, "");
+    }
+    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 8db07ca..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>
@@ -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/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index 36c38a2..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) {
     }
 
@@ -949,6 +949,7 @@
                 sp<AMessage> inputFormat =
                         mSource->getFormat(false /* audio */);
 
+                setVideoScalingMode(mVideoScalingMode);
                 updateVideoSize(inputFormat, format);
             } else if (what == DecoderBase::kWhatShutdownCompleted) {
                 ALOGV("%s shutdown completed", audio ? "audio" : "video");
@@ -1688,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;
     }
 
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/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index fad06b8..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(
@@ -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 72bae5c..9d0dbe9 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -10,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                 \
@@ -48,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           \
@@ -126,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/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
deleted file mode 100644
index ba59e00..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 = NuCachedSource2::Create(
-                    new ThrottledSource(
-                        mConnectingDataSource, 50 * 1024 /* bytes/sec */));
-#else
-            mCachedSource = NuCachedSource2::Create(
-                    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/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/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 bfdff38..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
@@ -4545,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 c2ffdf2..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>
@@ -66,7 +65,7 @@
 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();
@@ -171,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);
@@ -183,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 */);
@@ -194,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);
@@ -299,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();
 
@@ -312,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;
     }
 
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 d6255d6..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 {
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)) {