am ee567e08: am c3c36b4f: am 9d25b82d: Merge "Rename LOG_ASSERT to ALOG_ASSERT"

* commit 'ee567e08d973c0fad214889e8d980f9bfb535b34':
  Rename LOG_ASSERT to ALOG_ASSERT
diff --git a/drm/common/DrmEngineBase.cpp b/drm/common/DrmEngineBase.cpp
index 9b16c36..1c345a2 100644
--- a/drm/common/DrmEngineBase.cpp
+++ b/drm/common/DrmEngineBase.cpp
@@ -120,13 +120,23 @@
 }
 
 status_t DrmEngineBase::openDecryptSession(
-    int uniqueId, DecryptHandle* decryptHandle, int fd, off64_t offset, off64_t length) {
-    return onOpenDecryptSession(uniqueId, decryptHandle, fd, offset, length);
+    int uniqueId, DecryptHandle* decryptHandle,
+    int fd, off64_t offset, off64_t length, const char* mime) {
+
+    if (!mime || mime[0] == '\0') {
+        return onOpenDecryptSession(uniqueId, decryptHandle, fd, offset, length);
+    }
+
+    return onOpenDecryptSession(uniqueId, decryptHandle, fd, offset, length, mime);
 }
 
 status_t DrmEngineBase::openDecryptSession(
-    int uniqueId, DecryptHandle* decryptHandle, const char* uri) {
-    return onOpenDecryptSession(uniqueId, decryptHandle, uri);
+    int uniqueId, DecryptHandle* decryptHandle,
+    const char* uri, const char* mime) {
+    if (!mime || mime[0] == '\0') {
+        return onOpenDecryptSession(uniqueId, decryptHandle, uri);
+    }
+    return onOpenDecryptSession(uniqueId, decryptHandle, uri, mime);
 }
 
 status_t DrmEngineBase::closeDecryptSession(int uniqueId, DecryptHandle* decryptHandle) {
diff --git a/drm/common/IDrmManagerService.cpp b/drm/common/IDrmManagerService.cpp
index 3ed8ade..43f64f2 100644
--- a/drm/common/IDrmManagerService.cpp
+++ b/drm/common/IDrmManagerService.cpp
@@ -600,7 +600,7 @@
 }
 
 DecryptHandle* BpDrmManagerService::openDecryptSession(
-            int uniqueId, int fd, off64_t offset, off64_t length) {
+            int uniqueId, int fd, off64_t offset, off64_t length, const char* mime) {
     ALOGV("Entering BpDrmManagerService::openDecryptSession");
     Parcel data, reply;
 
@@ -609,6 +609,11 @@
     data.writeFileDescriptor(fd);
     data.writeInt64(offset);
     data.writeInt64(length);
+    String8 mimeType;
+    if (mime) {
+        mimeType = mime;
+    }
+    data.writeString8(mimeType);
 
     remote()->transact(OPEN_DECRYPT_SESSION, data, &reply);
 
@@ -620,13 +625,20 @@
     return handle;
 }
 
-DecryptHandle* BpDrmManagerService::openDecryptSession(int uniqueId, const char* uri) {
-    ALOGV("Entering BpDrmManagerService::openDecryptSession");
+DecryptHandle* BpDrmManagerService::openDecryptSession(
+        int uniqueId, const char* uri, const char* mime) {
+
+    ALOGV("Entering BpDrmManagerService::openDecryptSession: mime=%s", mime? mime: "NULL");
     Parcel data, reply;
 
     data.writeInterfaceToken(IDrmManagerService::getInterfaceDescriptor());
     data.writeInt32(uniqueId);
     data.writeString8(String8(uri));
+    String8 mimeType;
+    if (mime) {
+        mimeType = mime;
+    }
+    data.writeString8(mimeType);
 
     remote()->transact(OPEN_DECRYPT_SESSION_FROM_URI, data, &reply);
 
@@ -1265,8 +1277,10 @@
 
         const off64_t offset = data.readInt64();
         const off64_t length = data.readInt64();
+        const String8 mime = data.readString8();
+
         DecryptHandle* handle
-            = openDecryptSession(uniqueId, fd, offset, length);
+            = openDecryptSession(uniqueId, fd, offset, length, mime.string());
 
         if (NULL != handle) {
             writeDecryptHandleToParcelData(handle, reply);
@@ -1283,8 +1297,9 @@
 
         const int uniqueId = data.readInt32();
         const String8 uri = data.readString8();
+        const String8 mime = data.readString8();
 
-        DecryptHandle* handle = openDecryptSession(uniqueId, uri.string());
+        DecryptHandle* handle = openDecryptSession(uniqueId, uri.string(), mime.string());
 
         if (NULL != handle) {
             writeDecryptHandleToParcelData(handle, reply);
diff --git a/drm/drmserver/DrmManager.cpp b/drm/drmserver/DrmManager.cpp
index 3abf3d3..999295a 100644
--- a/drm/drmserver/DrmManager.cpp
+++ b/drm/drmserver/DrmManager.cpp
@@ -426,7 +426,9 @@
     return DRM_NO_ERROR;
 }
 
-DecryptHandle* DrmManager::openDecryptSession(int uniqueId, int fd, off64_t offset, off64_t length) {
+DecryptHandle* DrmManager::openDecryptSession(
+        int uniqueId, int fd, off64_t offset, off64_t length, const char* mime) {
+
     Mutex::Autolock _l(mDecryptLock);
     status_t result = DRM_ERROR_CANNOT_HANDLE;
     Vector<String8> plugInIdList = mPlugInManager.getPlugInIdList();
@@ -438,7 +440,7 @@
         for (unsigned int index = 0; index < plugInIdList.size(); index++) {
             String8 plugInId = plugInIdList.itemAt(index);
             IDrmEngine& rDrmEngine = mPlugInManager.getPlugIn(plugInId);
-            result = rDrmEngine.openDecryptSession(uniqueId, handle, fd, offset, length);
+            result = rDrmEngine.openDecryptSession(uniqueId, handle, fd, offset, length, mime);
 
             if (DRM_NO_ERROR == result) {
                 ++mDecryptSessionId;
@@ -453,7 +455,8 @@
     return handle;
 }
 
-DecryptHandle* DrmManager::openDecryptSession(int uniqueId, const char* uri) {
+DecryptHandle* DrmManager::openDecryptSession(
+        int uniqueId, const char* uri, const char* mime) {
     Mutex::Autolock _l(mDecryptLock);
     status_t result = DRM_ERROR_CANNOT_HANDLE;
     Vector<String8> plugInIdList = mPlugInManager.getPlugInIdList();
@@ -465,7 +468,7 @@
         for (unsigned int index = 0; index < plugInIdList.size(); index++) {
             String8 plugInId = plugInIdList.itemAt(index);
             IDrmEngine& rDrmEngine = mPlugInManager.getPlugIn(plugInId);
-            result = rDrmEngine.openDecryptSession(uniqueId, handle, uri);
+            result = rDrmEngine.openDecryptSession(uniqueId, handle, uri, mime);
 
             if (DRM_NO_ERROR == result) {
                 ++mDecryptSessionId;
diff --git a/drm/drmserver/DrmManagerService.cpp b/drm/drmserver/DrmManagerService.cpp
index df17ac5..caeb026 100644
--- a/drm/drmserver/DrmManagerService.cpp
+++ b/drm/drmserver/DrmManagerService.cpp
@@ -208,20 +208,20 @@
 }
 
 DecryptHandle* DrmManagerService::openDecryptSession(
-            int uniqueId, int fd, off64_t offset, off64_t length) {
+            int uniqueId, int fd, off64_t offset, off64_t length, const char* mime) {
     ALOGV("Entering DrmManagerService::openDecryptSession");
     if (isProtectedCallAllowed()) {
-        return mDrmManager->openDecryptSession(uniqueId, fd, offset, length);
+        return mDrmManager->openDecryptSession(uniqueId, fd, offset, length, mime);
     }
 
     return NULL;
 }
 
 DecryptHandle* DrmManagerService::openDecryptSession(
-            int uniqueId, const char* uri) {
+            int uniqueId, const char* uri, const char* mime) {
     ALOGV("Entering DrmManagerService::openDecryptSession with uri");
     if (isProtectedCallAllowed()) {
-        return mDrmManager->openDecryptSession(uniqueId, uri);
+        return mDrmManager->openDecryptSession(uniqueId, uri, mime);
     }
 
     return NULL;
diff --git a/drm/drmserver/main_drmserver.cpp b/drm/drmserver/main_drmserver.cpp
index ed42818..e61b269 100644
--- a/drm/drmserver/main_drmserver.cpp
+++ b/drm/drmserver/main_drmserver.cpp
@@ -14,6 +14,9 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "drmserver"
+//#define LOG_NDEBUG 0
+
 #include <sys/types.h>
 #include <unistd.h>
 #include <grp.h>
@@ -32,7 +35,7 @@
 {
     sp<ProcessState> proc(ProcessState::self());
     sp<IServiceManager> sm = defaultServiceManager();
-    ALOGI("ServiceManager: %p", sm.get());
+    ALOGV("ServiceManager: %p", sm.get());
     DrmManagerService::instantiate();
     ProcessState::self()->startThreadPool();
     IPCThreadState::self()->joinThreadPool();
diff --git a/drm/libdrmframework/DrmManagerClient.cpp b/drm/libdrmframework/DrmManagerClient.cpp
index c9c0d57..8768c08 100644
--- a/drm/libdrmframework/DrmManagerClient.cpp
+++ b/drm/libdrmframework/DrmManagerClient.cpp
@@ -116,12 +116,18 @@
     return mDrmManagerClientImpl->getAllSupportInfo(mUniqueId, length, drmSupportInfoArray);
 }
 
-sp<DecryptHandle> DrmManagerClient::openDecryptSession(int fd, off64_t offset, off64_t length) {
-    return mDrmManagerClientImpl->openDecryptSession(mUniqueId, fd, offset, length);
+sp<DecryptHandle> DrmManagerClient::openDecryptSession(
+        int fd, off64_t offset, off64_t length, const char* mime) {
+
+    return mDrmManagerClientImpl->openDecryptSession(
+                    mUniqueId, fd, offset, length, mime);
 }
 
-sp<DecryptHandle> DrmManagerClient::openDecryptSession(const char* uri) {
-    return mDrmManagerClientImpl->openDecryptSession(mUniqueId, uri);
+sp<DecryptHandle> DrmManagerClient::openDecryptSession(
+        const char* uri, const char* mime) {
+
+    return mDrmManagerClientImpl->openDecryptSession(
+                    mUniqueId, uri, mime);
 }
 
 status_t DrmManagerClient::closeDecryptSession(sp<DecryptHandle> &decryptHandle) {
diff --git a/drm/libdrmframework/DrmManagerClientImpl.cpp b/drm/libdrmframework/DrmManagerClientImpl.cpp
index b222b8f..fb0439e 100644
--- a/drm/libdrmframework/DrmManagerClientImpl.cpp
+++ b/drm/libdrmframework/DrmManagerClientImpl.cpp
@@ -255,15 +255,19 @@
 }
 
 sp<DecryptHandle> DrmManagerClientImpl::openDecryptSession(
-            int uniqueId, int fd, off64_t offset, off64_t length) {
-    return getDrmManagerService()->openDecryptSession(uniqueId, fd, offset, length);
+            int uniqueId, int fd, off64_t offset,
+            off64_t length, const char* mime) {
+
+    return getDrmManagerService()->openDecryptSession(
+                uniqueId, fd, offset, length, mime);
 }
 
 sp<DecryptHandle> DrmManagerClientImpl::openDecryptSession(
-        int uniqueId, const char* uri) {
+        int uniqueId, const char* uri, const char* mime) {
+
     DecryptHandle* handle = NULL;
     if (NULL != uri) {
-        handle = getDrmManagerService()->openDecryptSession(uniqueId, uri);
+        handle = getDrmManagerService()->openDecryptSession(uniqueId, uri, mime);
     }
     return handle;
 }
diff --git a/drm/libdrmframework/include/DrmManager.h b/drm/libdrmframework/include/DrmManager.h
index ac2b946..c9167d4 100644
--- a/drm/libdrmframework/include/DrmManager.h
+++ b/drm/libdrmframework/include/DrmManager.h
@@ -111,9 +111,10 @@
 
     status_t getAllSupportInfo(int uniqueId, int* length, DrmSupportInfo** drmSupportInfoArray);
 
-    DecryptHandle* openDecryptSession(int uniqueId, int fd, off64_t offset, off64_t length);
+    DecryptHandle* openDecryptSession(
+            int uniqueId, int fd, off64_t offset, off64_t length, const char* mime);
 
-    DecryptHandle* openDecryptSession(int uniqueId, const char* uri);
+    DecryptHandle* openDecryptSession(int uniqueId, const char* uri, const char* mime);
 
     status_t closeDecryptSession(int uniqueId, DecryptHandle* decryptHandle);
 
diff --git a/drm/libdrmframework/include/DrmManagerClientImpl.h b/drm/libdrmframework/include/DrmManagerClientImpl.h
index e3338d9..2aa493f 100644
--- a/drm/libdrmframework/include/DrmManagerClientImpl.h
+++ b/drm/libdrmframework/include/DrmManagerClientImpl.h
@@ -300,20 +300,24 @@
      * @param[in] fd File descriptor of the protected content to be decrypted
      * @param[in] offset Start position of the content
      * @param[in] length The length of the protected content
+     * @param[in] mime The mime type of the protected content if it is not NULL or empty
      * @return
      *     Handle for the decryption session
      */
-    sp<DecryptHandle> openDecryptSession(int uniqueId, int fd, off64_t offset, off64_t length);
+    sp<DecryptHandle> openDecryptSession(
+            int uniqueId, int fd, off64_t offset, off64_t length, const char* mime);
 
     /**
      * Open the decrypt session to decrypt the given protected content
      *
      * @param[in] uniqueId Unique identifier for a session
      * @param[in] uri Path of the protected content to be decrypted
+     * @param[in] mime The mime type of the protected content if it is not NULL or empty
      * @return
      *     Handle for the decryption session
      */
-    sp<DecryptHandle> openDecryptSession(int uniqueId, const char* uri);
+    sp<DecryptHandle> openDecryptSession(
+            int uniqueId, const char* uri, const char* mime);
 
     /**
      * Close the decrypt session for the given handle
diff --git a/drm/libdrmframework/include/DrmManagerService.h b/drm/libdrmframework/include/DrmManagerService.h
index 9cb5804..1a8c2ae 100644
--- a/drm/libdrmframework/include/DrmManagerService.h
+++ b/drm/libdrmframework/include/DrmManagerService.h
@@ -98,9 +98,11 @@
 
     status_t getAllSupportInfo(int uniqueId, int* length, DrmSupportInfo** drmSupportInfoArray);
 
-    DecryptHandle* openDecryptSession(int uniqueId, int fd, off64_t offset, off64_t length);
+    DecryptHandle* openDecryptSession(
+        int uniqueId, int fd, off64_t offset, off64_t length, const char *mime);
 
-    DecryptHandle* openDecryptSession(int uniqueId, const char* uri);
+    DecryptHandle* openDecryptSession(
+        int uniqueId, const char* uri, const char* mime);
 
     status_t closeDecryptSession(int uniqueId, DecryptHandle* decryptHandle);
 
diff --git a/drm/libdrmframework/include/IDrmManagerService.h b/drm/libdrmframework/include/IDrmManagerService.h
index b9618bb..a7d21c5 100644
--- a/drm/libdrmframework/include/IDrmManagerService.h
+++ b/drm/libdrmframework/include/IDrmManagerService.h
@@ -139,9 +139,12 @@
     virtual status_t getAllSupportInfo(
             int uniqueId, int* length, DrmSupportInfo** drmSupportInfoArray) = 0;
 
-    virtual DecryptHandle* openDecryptSession(int uniqueId, int fd, off64_t offset, off64_t length) = 0;
+    virtual DecryptHandle* openDecryptSession(
+                int uniqueId, int fd, off64_t offset,
+                off64_t length, const char* mime) = 0;
 
-    virtual DecryptHandle* openDecryptSession(int uniqueId, const char* uri) = 0;
+    virtual DecryptHandle* openDecryptSession(
+                int uniqueId, const char* uri, const char* mime) = 0;
 
     virtual status_t closeDecryptSession(int uniqueId, DecryptHandle* decryptHandle) = 0;
 
@@ -222,9 +225,12 @@
     virtual status_t getAllSupportInfo(
             int uniqueId, int* length, DrmSupportInfo** drmSupportInfoArray);
 
-    virtual DecryptHandle* openDecryptSession(int uniqueId, int fd, off64_t offset, off64_t length);
+    virtual DecryptHandle* openDecryptSession(
+                int uniqueId, int fd, off64_t offset, off64_t length,
+                const char* mime);
 
-    virtual DecryptHandle* openDecryptSession(int uniqueId, const char* uri);
+    virtual DecryptHandle* openDecryptSession(
+                int uniqueId, const char* uri, const char* mime);
 
     virtual status_t closeDecryptSession(int uniqueId, DecryptHandle* decryptHandle);
 
diff --git a/drm/libdrmframework/plugins/common/include/DrmEngineBase.h b/drm/libdrmframework/plugins/common/include/DrmEngineBase.h
index 4a5afcf..08f6e6d 100644
--- a/drm/libdrmframework/plugins/common/include/DrmEngineBase.h
+++ b/drm/libdrmframework/plugins/common/include/DrmEngineBase.h
@@ -80,10 +80,12 @@
     DrmSupportInfo* getSupportInfo(int uniqueId);
 
     status_t openDecryptSession(
-            int uniqueId, DecryptHandle* decryptHandle, int fd, off64_t offset, off64_t length);
+            int uniqueId, DecryptHandle* decryptHandle,
+            int fd, off64_t offset, off64_t length, const char* mime);
 
     status_t openDecryptSession(
-            int uniqueId, DecryptHandle* decryptHandle, const char* uri);
+            int uniqueId, DecryptHandle* decryptHandle,
+            const char* uri, const char* mime);
 
     status_t closeDecryptSession(int uniqueId, DecryptHandle* decryptHandle);
 
@@ -375,7 +377,29 @@
      *     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) = 0;
+            int uniqueId, DecryptHandle* decryptHandle,
+            int fd, off64_t offset, off64_t length) = 0;
+
+    /**
+     * Open the decrypt session to decrypt the given protected content
+     *
+     * @param[in] uniqueId Unique identifier for a session
+     * @param[in] decryptHandle Handle for the current decryption session
+     * @param[in] fd File descriptor of the protected content to be decrypted
+     * @param[in] offset Start position of the content
+     * @param[in] length The length of the protected content
+     * @param[in] mime Mime type of the protected content
+     *     drm plugin may do some optimization since the mime type is known.
+     * @return
+     *     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) {
+
+        return DRM_ERROR_CANNOT_HANDLE;
+    }
 
     /**
      * Open the decrypt session to decrypt the given protected content
@@ -387,7 +411,26 @@
      *     DRM_ERROR_CANNOT_HANDLE for failure and DRM_NO_ERROR for success
      */
     virtual status_t onOpenDecryptSession(
-            int uniqueId, DecryptHandle* decryptHandle, const char* uri) = 0;
+            int uniqueId, DecryptHandle* decryptHandle,
+            const char* uri) = 0;
+
+    /**
+     * Open the decrypt session to decrypt the given protected content
+     *
+     * @param[in] uniqueId Unique identifier for a session
+     * @param[in] decryptHandle Handle for the current decryption session
+     * @param[in] uri Path of the protected content to be decrypted
+     * @param[in] mime Mime type of the protected content. The corresponding
+     *     drm plugin may do some optimization since the mime type is known.
+     * @return
+     *     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) {
+
+        return DRM_ERROR_CANNOT_HANDLE;
+    }
 
     /**
      * Close the decrypt session for the given handle
diff --git a/drm/libdrmframework/plugins/common/include/IDrmEngine.h b/drm/libdrmframework/plugins/common/include/IDrmEngine.h
index 77460f6..dcf5977 100644
--- a/drm/libdrmframework/plugins/common/include/IDrmEngine.h
+++ b/drm/libdrmframework/plugins/common/include/IDrmEngine.h
@@ -320,11 +320,14 @@
      * @param[in] fd File descriptor of the protected content to be decrypted
      * @param[in] offset Start position of the content
      * @param[in] length The length of the protected content
+     * @param[in] mime Mime type of the protected content if it is
+     *     not NULL or empty
      * @return
      *     DRM_ERROR_CANNOT_HANDLE for failure and DRM_NO_ERROR for success
      */
     virtual status_t openDecryptSession(
-        int uniqueId, DecryptHandle* decryptHandle, int fd, off64_t offset, off64_t length) = 0;
+        int uniqueId, DecryptHandle* decryptHandle,
+        int fd, off64_t offset, off64_t length, const char* mime) = 0;
 
     /**
      * Open the decrypt session to decrypt the given protected content
@@ -332,11 +335,14 @@
      * @param[in] uniqueId Unique identifier for a session
      * @param[in] decryptHandle Handle for the current decryption session
      * @param[in] uri Path of the protected content to be decrypted
+     * @param[in] mime Mime type of the protected content if it is
+     *     not NULL or empty
      * @return
      *     DRM_ERROR_CANNOT_HANDLE for failure and DRM_NO_ERROR for success
      */
     virtual status_t openDecryptSession(
-        int uniqueId, DecryptHandle* decryptHandle, const char* uri) = 0;
+        int uniqueId, DecryptHandle* decryptHandle,
+        const char* uri, const char* mime) = 0;
 
     /**
      * Close the decrypt session for the given handle
diff --git a/include/drm/DrmManagerClient.h b/include/drm/DrmManagerClient.h
index b8fe46d..c47bbfb 100644
--- a/include/drm/DrmManagerClient.h
+++ b/include/drm/DrmManagerClient.h
@@ -66,19 +66,21 @@
      * @param[in] fd File descriptor of the protected content to be decrypted
      * @param[in] offset Start position of the content
      * @param[in] length The length of the protected content
+     * @param[in] mime Mime type of the protected content if it is not NULL or empty
      * @return
      *     Handle for the decryption session
      */
-    sp<DecryptHandle> openDecryptSession(int fd, off64_t offset, off64_t length);
+    sp<DecryptHandle> openDecryptSession(int fd, off64_t offset, off64_t length, const char* mime);
 
     /**
      * Open the decrypt session to decrypt the given protected content
      *
      * @param[in] uri Path of the protected content to be decrypted
+     * @param[in] mime Mime type of the protected content if it is not NULL or empty
      * @return
      *     Handle for the decryption session
      */
-    sp<DecryptHandle> openDecryptSession(const char* uri);
+    sp<DecryptHandle> openDecryptSession(const char* uri, const char* mime);
 
     /**
      * Close the decrypt session for the given handle
diff --git a/include/media/AudioRecord.h b/include/media/AudioRecord.h
index 605680a..756e91d 100644
--- a/include/media/AudioRecord.h
+++ b/include/media/AudioRecord.h
@@ -22,7 +22,6 @@
 
 #include <media/IAudioFlinger.h>
 #include <media/IAudioRecord.h>
-#include <media/AudioTrack.h>
 
 #include <utils/RefBase.h>
 #include <utils/Errors.h>
@@ -34,6 +33,8 @@
 
 namespace android {
 
+class audio_track_cblk_t;
+
 // ----------------------------------------------------------------------------
 
 class AudioRecord
@@ -67,7 +68,7 @@
         };
         uint32_t    flags;
         int         channelCount;
-        int         format;
+        audio_format_t format;
         size_t      frameCount;
         size_t      size;
         union {
@@ -111,7 +112,7 @@
 
      static status_t getMinFrameCount(int* frameCount,
                                       uint32_t sampleRate,
-                                      int format,
+                                      audio_format_t format,
                                       int channelCount);
 
     /* Constructs an uninitialized AudioRecord. No connection with
@@ -150,7 +151,7 @@
 
                         AudioRecord(int inputSource,
                                     uint32_t sampleRate = 0,
-                                    int format          = 0,
+                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
                                     uint32_t channelMask = AUDIO_CHANNEL_IN_MONO,
                                     int frameCount      = 0,
                                     uint32_t flags      = 0,
@@ -176,7 +177,7 @@
      * */
             status_t    set(int inputSource     = 0,
                             uint32_t sampleRate = 0,
-                            int format          = 0,
+                            audio_format_t format = AUDIO_FORMAT_DEFAULT,
                             uint32_t channelMask = AUDIO_CHANNEL_IN_MONO,
                             int frameCount      = 0,
                             uint32_t flags      = 0,
@@ -202,11 +203,11 @@
 
    /* getters, see constructor */
 
-            int         format() const;
+            audio_format_t format() const;
             int         channelCount() const;
             int         channels() const;
             uint32_t    frameCount() const;
-            int         frameSize() const;
+            size_t      frameSize() const;
             int         inputSource() const;
 
 
@@ -348,7 +349,7 @@
 
             bool processAudioBuffer(const sp<ClientRecordThread>& thread);
             status_t openRecord_l(uint32_t sampleRate,
-                                uint32_t format,
+                                audio_format_t format,
                                 uint32_t channelMask,
                                 int frameCount,
                                 uint32_t flags,
@@ -364,7 +365,7 @@
     uint32_t                mFrameCount;
 
     audio_track_cblk_t*     mCblk;
-    uint32_t                mFormat;
+    audio_format_t          mFormat;
     uint8_t                 mChannelCount;
     uint8_t                 mInputSource;
     uint8_t                 mReserved[2];
@@ -385,6 +386,8 @@
     uint32_t                mChannelMask;
     audio_io_handle_t       mInput;
     int                     mSessionId;
+    int                     mPreviousPriority;          // before start()
+    int                     mPreviousSchedulingGroup;
 };
 
 }; // namespace android
diff --git a/include/media/AudioSystem.h b/include/media/AudioSystem.h
index 6a15f6e..c6368fb 100644
--- a/include/media/AudioSystem.h
+++ b/include/media/AudioSystem.h
@@ -55,19 +55,19 @@
     static status_t getMasterMute(bool* mute);
 
     // set/get stream volume on specified output
-    static status_t setStreamVolume(int stream, float value, int output);
-    static status_t getStreamVolume(int stream, float* volume, int output);
+    static status_t setStreamVolume(audio_stream_type_t stream, float value, int output);
+    static status_t getStreamVolume(audio_stream_type_t stream, float* volume, int output);
 
     // mute/unmute stream
-    static status_t setStreamMute(int stream, bool mute);
-    static status_t getStreamMute(int stream, bool* mute);
+    static status_t setStreamMute(audio_stream_type_t stream, bool mute);
+    static status_t getStreamMute(audio_stream_type_t stream, bool* mute);
 
-    // set audio mode in audio hardware (see audio_mode_t)
-    static status_t setMode(int mode);
+    // set audio mode in audio hardware
+    static status_t setMode(audio_mode_t mode);
 
     // returns true in *state if tracks are active on the specified stream or has been active
     // in the past inPastMs milliseconds
-    static status_t isStreamActive(int stream, bool *state, uint32_t inPastMs = 0);
+    static status_t isStreamActive(audio_stream_type_t stream, bool *state, uint32_t inPastMs = 0);
 
     // set/get audio hardware parameters. The function accepts a list of parameters
     // key value pairs in the form: key1=value1;key2=value2;...
@@ -83,13 +83,19 @@
     static float linearToLog(int volume);
     static int logToLinear(float volume);
 
+    static status_t getOutputSamplingRate(int* samplingRate, audio_stream_type_t stream = AUDIO_STREAM_DEFAULT);
+    static status_t getOutputFrameCount(int* frameCount, audio_stream_type_t stream = AUDIO_STREAM_DEFAULT);
+    static status_t getOutputLatency(uint32_t* latency, audio_stream_type_t stream = AUDIO_STREAM_DEFAULT);
+
+    // DEPRECATED
     static status_t getOutputSamplingRate(int* samplingRate, int stream = AUDIO_STREAM_DEFAULT);
+
+    // DEPRECATED
     static status_t getOutputFrameCount(int* frameCount, int stream = AUDIO_STREAM_DEFAULT);
-    static status_t getOutputLatency(uint32_t* latency, int stream = AUDIO_STREAM_DEFAULT);
 
-    static bool routedToA2dpOutput(int streamType);
+    static bool routedToA2dpOutput(audio_stream_type_t streamType);
 
-    static status_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
+    static status_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount,
         size_t* buffSize);
 
     static status_t setVoiceVolume(float volume);
@@ -103,7 +109,7 @@
     // - BAD_VALUE: invalid parameter
     // NOTE: this feature is not supported on all hardware platforms and it is
     // necessary to check returned status before using the returned values.
-    static status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int stream = AUDIO_STREAM_DEFAULT);
+    static status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, audio_stream_type_t stream = AUDIO_STREAM_DEFAULT);
 
     static unsigned int  getInputFramesLost(audio_io_handle_t ioHandle);
 
@@ -128,7 +134,7 @@
     class OutputDescriptor {
     public:
         OutputDescriptor()
-        : samplingRate(0), format(0), channels(0), frameCount(0), latency(0)  {}
+        : samplingRate(0), format(AUDIO_FORMAT_DEFAULT), channels(0), frameCount(0), latency(0)  {}
 
         uint32_t samplingRate;
         int32_t format;
@@ -142,13 +148,12 @@
     //
     static status_t setDeviceConnectionState(audio_devices_t device, audio_policy_dev_state_t state, const char *device_address);
     static audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, const char *device_address);
-    static status_t setPhoneState(int state);
-    static status_t setRingerMode(uint32_t mode, uint32_t mask);
+    static status_t setPhoneState(audio_mode_t state);
     static status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config);
     static audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage);
     static audio_io_handle_t getOutput(audio_stream_type_t stream,
                                         uint32_t samplingRate = 0,
-                                        uint32_t format = AUDIO_FORMAT_DEFAULT,
+                                        audio_format_t format = AUDIO_FORMAT_DEFAULT,
                                         uint32_t channels = AUDIO_CHANNEL_OUT_STEREO,
                                         audio_policy_output_flags_t flags = AUDIO_POLICY_OUTPUT_FLAG_INDIRECT);
     static status_t startOutput(audio_io_handle_t output,
@@ -160,7 +165,7 @@
     static void releaseOutput(audio_io_handle_t output);
     static audio_io_handle_t getInput(int inputSource,
                                     uint32_t samplingRate = 0,
-                                    uint32_t format = AUDIO_FORMAT_DEFAULT,
+                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
                                     uint32_t channels = AUDIO_CHANNEL_IN_MONO,
                                     audio_in_acoustics_t acoustics = (audio_in_acoustics_t)0,
                                     int sessionId = 0);
@@ -170,8 +175,12 @@
     static status_t initStreamVolume(audio_stream_type_t stream,
                                       int indexMin,
                                       int indexMax);
-    static status_t setStreamVolumeIndex(audio_stream_type_t stream, int index);
-    static status_t getStreamVolumeIndex(audio_stream_type_t stream, int *index);
+    static status_t setStreamVolumeIndex(audio_stream_type_t stream,
+                                         int index,
+                                         audio_devices_t device);
+    static status_t getStreamVolumeIndex(audio_stream_type_t stream,
+                                         int *index,
+                                         audio_devices_t device);
 
     static uint32_t getStrategyForStream(audio_stream_type_t stream);
     static uint32_t getDevicesForStream(audio_stream_type_t stream);
@@ -233,7 +242,7 @@
     static size_t gInBuffSize;
     // previous parameters for recording buffer size queries
     static uint32_t gPrevInSamplingRate;
-    static int gPrevInFormat;
+    static audio_format_t gPrevInFormat;
     static int gPrevInChannelCount;
 
     static sp<IAudioPolicyService> gAudioPolicyService;
diff --git a/include/media/AudioTrack.h b/include/media/AudioTrack.h
index d1a8105..fe91799 100644
--- a/include/media/AudioTrack.h
+++ b/include/media/AudioTrack.h
@@ -38,7 +38,7 @@
 
 // ----------------------------------------------------------------------------
 
-class AudioTrack
+class AudioTrack : virtual public RefBase
 {
 public:
     enum channel_index {
@@ -69,21 +69,22 @@
             MUTE    = 0x00000001
         };
         uint32_t    flags;
-        int         format;
+        audio_format_t format; // but AUDIO_FORMAT_PCM_8_BIT -> AUDIO_FORMAT_PCM_16_BIT
+        // accessed directly by WebKit ANP callback
         int         channelCount; // will be removed in the future, do not use
         size_t      frameCount;
         size_t      size;
         union {
             void*       raw;
-            short*      i16;
-            int8_t*     i8;
+            short*      i16;    // signed 16-bit
+            int8_t*     i8;     // unsigned 8-bit, offset by 0x80
         };
     };
 
 
     /* As a convenience, if a callback is supplied, a handler thread
      * is automatically created with the appropriate priority. This thread
-     * invokes the callback when a new buffer becomes availlable or an underrun condition occurs.
+     * invokes the callback when a new buffer becomes available or an underrun condition occurs.
      * Parameters:
      *
      * event:   type of event notified (see enum AudioTrack::event_type).
@@ -94,8 +95,8 @@
      *          written.
      *          - EVENT_UNDERRUN: unused.
      *          - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
-     *          - EVENT_MARKER: pointer to an uin32_t containing the marker position in frames.
-     *          - EVENT_NEW_POS: pointer to an uin32_t containing the new position in frames.
+     *          - EVENT_MARKER: pointer to an uint32_t containing the marker position in frames.
+     *          - EVENT_NEW_POS: pointer to an uint32_t containing the new position in frames.
      *          - EVENT_BUFFER_END: unused.
      */
 
@@ -109,7 +110,7 @@
      */
 
      static status_t getMinFrameCount(int* frameCount,
-                                      int streamType      =-1,
+                                      audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT,
                                       uint32_t sampleRate = 0);
 
     /* Constructs an uninitialized AudioTrack. No connection with
@@ -135,14 +136,27 @@
      * flags:              Reserved for future use.
      * cbf:                Callback function. If not null, this function is called periodically
      *                     to request new PCM data.
+     * user:               Context for use by the callback receiver.
      * notificationFrames: The callback function is called each time notificationFrames PCM
-     *                     frames have been comsumed from track input buffer.
-     * user                Context for use by the callback receiver.
+     *                     frames have been consumed from track input buffer.
+     * sessionId:          Specific session ID, or zero to use default.
      */
 
-                        AudioTrack( int streamType,
+                        AudioTrack( audio_stream_type_t streamType,
                                     uint32_t sampleRate  = 0,
-                                    int format           = 0,
+                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
+                                    int channelMask      = 0,
+                                    int frameCount       = 0,
+                                    uint32_t flags       = 0,
+                                    callback_t cbf       = 0,
+                                    void* user           = 0,
+                                    int notificationFrames = 0,
+                                    int sessionId = 0);
+
+                        // DEPRECATED
+                        explicit AudioTrack( int streamType,
+                                    uint32_t sampleRate  = 0,
+                                    int format = AUDIO_FORMAT_DEFAULT,
                                     int channelMask      = 0,
                                     int frameCount       = 0,
                                     uint32_t flags       = 0,
@@ -152,17 +166,17 @@
                                     int sessionId = 0);
 
     /* Creates an audio track and registers it with AudioFlinger. With this constructor,
-     * The PCM data to be rendered by AudioTrack is passed in a shared memory buffer
+     * the PCM data to be rendered by AudioTrack is passed in a shared memory buffer
      * identified by the argument sharedBuffer. This prototype is for static buffer playback.
-     * PCM data must be present into memory before the AudioTrack is started.
-     * The Write() and Flush() methods are not supported in this case.
-     * It is recommented to pass a callback function to be notified of playback end by an
+     * PCM data must be present in memory before the AudioTrack is started.
+     * The write() and flush() methods are not supported in this case.
+     * It is recommended to pass a callback function to be notified of playback end by an
      * EVENT_UNDERRUN event.
      */
 
-                        AudioTrack( int streamType,
+                        AudioTrack( audio_stream_type_t streamType,
                                     uint32_t sampleRate = 0,
-                                    int format          = 0,
+                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
                                     int channelMask     = 0,
                                     const sp<IMemory>& sharedBuffer = 0,
                                     uint32_t flags      = 0,
@@ -172,21 +186,21 @@
                                     int sessionId = 0);
 
     /* Terminates the AudioTrack and unregisters it from AudioFlinger.
-     * Also destroys all resources assotiated with the AudioTrack.
+     * Also destroys all resources associated with the AudioTrack.
      */
                         ~AudioTrack();
 
 
     /* Initialize an uninitialized AudioTrack.
      * Returned status (from utils/Errors.h) can be:
-     *  - NO_ERROR: successful intialization
-     *  - INVALID_OPERATION: AudioTrack is already intitialized
+     *  - NO_ERROR: successful initialization
+     *  - INVALID_OPERATION: AudioTrack is already initialized
      *  - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
      *  - NO_INIT: audio server or audio hardware not initialized
      * */
-            status_t    set(int streamType      =-1,
+            status_t    set(audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT,
                             uint32_t sampleRate = 0,
-                            int format          = 0,
+                            audio_format_t format = AUDIO_FORMAT_DEFAULT,
                             int channelMask     = 0,
                             int frameCount      = 0,
                             uint32_t flags      = 0,
@@ -199,13 +213,13 @@
 
 
     /* Result of constructing the AudioTrack. This must be checked
-     * before using any AudioTrack API (except for set()), using
+     * before using any AudioTrack API (except for set()), because using
      * an uninitialized AudioTrack produces undefined results.
      * See set() method above for possible return codes.
      */
             status_t    initCheck() const;
 
-    /* Returns this track's latency in milliseconds.
+    /* Returns this track's estimated latency in milliseconds.
      * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
      * and audio hardware driver.
      */
@@ -213,11 +227,16 @@
 
     /* getters, see constructor */
 
-            int         streamType() const;
-            int         format() const;
+            audio_stream_type_t streamType() const;
+            audio_format_t format() const;
             int         channelCount() const;
             uint32_t    frameCount() const;
-            int         frameSize() const;
+
+    /* Return channelCount * (bit depth per channel / 8).
+     * channelCount is determined from channelMask, and bit depth comes from format.
+     */
+            size_t      frameSize() const;
+
             sp<IMemory>& sharedBuffer();
 
 
@@ -233,8 +252,8 @@
             void        stop();
             bool        stopped() const;
 
-    /* flush a stopped track. All pending buffers are discarded.
-     * This function has no effect if the track is not stoped.
+    /* Flush a stopped track. All pending buffers are discarded.
+     * This function has no effect if the track is not stopped.
      */
             void        flush();
 
@@ -244,26 +263,25 @@
      */
             void        pause();
 
-    /* mute or unmutes this track.
-     * While mutted, the callback, if set, is still called.
+    /* Mute or unmute this track.
+     * While muted, the callback, if set, is still called.
      */
             void        mute(bool);
             bool        muted() const;
 
-
-    /* set volume for this track, mostly used for games' sound effects
-     * left and right volumes. Levels must be <= 1.0.
+    /* Set volume for this track, mostly used for games' sound effects
+     * left and right volumes. Levels must be >= 0.0 and <= 1.0.
      */
             status_t    setVolume(float left, float right);
             void        getVolume(float* left, float* right);
 
-    /* set the send level for this track. An auxiliary effect should be attached
-     * to the track with attachEffect(). Level must be <= 1.0.
+    /* Set the send level for this track. An auxiliary effect should be attached
+     * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0.
      */
             status_t    setAuxEffectSendLevel(float level);
             void        getAuxEffectSendLevel(float* level);
 
-    /* set sample rate for this track, mostly used for games' sound effects
+    /* Set sample rate for this track, mostly used for games' sound effects
      */
             status_t    setSampleRate(int sampleRate);
             uint32_t    getSampleRate();
@@ -274,8 +292,8 @@
      *
      * loopStart:   loop start expressed as the number of PCM frames played since AudioTrack start.
      * loopEnd:     loop end expressed as the number of PCM frames played since AudioTrack start.
-     * loopCount:   number of loops to execute. Calling setLoop() with loopCount == 0 cancels any pending or
-     *          active loop. loopCount = -1 means infinite looping.
+     * loopCount:   number of loops to execute. Calling setLoop() with loopCount == 0 cancels any
+     *              pending or active loop. loopCount = -1 means infinite looping.
      *
      * For proper operation the following condition must be respected:
      *          (loopEnd-loopStart) <= framecount()
@@ -283,10 +301,9 @@
             status_t    setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
             status_t    getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount);
 
-
-    /* Sets marker position. When playback reaches the number of frames specified, a callback with event 
-     * type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker notification 
-     * callback. 
+    /* Sets marker position. When playback reaches the number of frames specified, a callback with
+     * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker
+     * notification callback.
      * If the AudioTrack has been opened with no callback function associated, the operation will fail.
      *
      * Parameters:
@@ -301,10 +318,10 @@
             status_t    getMarkerPosition(uint32_t *marker);
 
 
-    /* Sets position update period. Every time the number of frames specified has been played, 
-     * a callback with event type EVENT_NEW_POS is called. 
-     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 
-     * callback. 
+    /* Sets position update period. Every time the number of frames specified has been played,
+     * a callback with event type EVENT_NEW_POS is called.
+     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
+     * callback.
      * If the AudioTrack has been opened with no callback function associated, the operation will fail.
      *
      * Parameters:
@@ -318,12 +335,11 @@
             status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
             status_t    getPositionUpdatePeriod(uint32_t *updatePeriod);
 
-
     /* Sets playback head position within AudioTrack buffer. The new position is specified
-     * in number of frames. 
+     * in number of frames.
      * This method must be called with the AudioTrack in paused or stopped state.
-     * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames. 
-     * Therefore using this method makes sense only when playing a "static" audio buffer 
+     * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames.
+     * Therefore using this method makes sense only when playing a "static" audio buffer
      * as opposed to streaming.
      * The getPosition() method on the other hand returns the total number of frames played since
      * playback start.
@@ -335,12 +351,12 @@
      * Returned status (from utils/Errors.h) can be:
      *  - NO_ERROR: successful operation
      *  - INVALID_OPERATION: the AudioTrack is not stopped.
-     *  - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer 
+     *  - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer
      */
             status_t    setPosition(uint32_t position);
             status_t    getPosition(uint32_t *position);
 
-    /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids 
+    /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
      * rewriting the buffer before restarting playback after a stop.
      * This method must be called with the AudioTrack in paused or stopped state.
      *
@@ -350,7 +366,7 @@
      */
             status_t    reload();
 
-    /* returns a handle on the audio output used by this AudioTrack.
+    /* Returns a handle on the audio output used by this AudioTrack.
      *
      * Parameters:
      *  none.
@@ -360,18 +376,17 @@
      */
             audio_io_handle_t    getOutput();
 
-    /* returns the unique ID associated to this track.
+    /* Returns the unique session ID associated with this track.
      *
      * Parameters:
      *  none.
      *
      * Returned value:
-     *  AudioTrack ID.
+     *  AudioTrack session ID.
      */
             int    getSessionId();
 
-
-    /* Attach track auxiliary output to specified effect. Used effectId = 0
+    /* Attach track auxiliary output to specified effect. Use effectId = 0
      * to detach track from effect.
      *
      * Parameters:
@@ -385,9 +400,9 @@
      */
             status_t    attachAuxEffect(int effectId);
 
-    /* obtains a buffer of "frameCount" frames. The buffer must be
+    /* Obtains a buffer of "frameCount" frames. The buffer must be
      * filled entirely. If the track is stopped, obtainBuffer() returns
-     * STOPPED instead of NO_ERROR as long as there are buffers availlable,
+     * STOPPED instead of NO_ERROR as long as there are buffers available,
      * at which point NO_MORE_BUFFERS is returned.
      * Buffers will be returned until the pool (buffercount())
      * is exhausted, at which point obtainBuffer() will either block
@@ -403,10 +418,9 @@
             status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
             void        releaseBuffer(Buffer* audioBuffer);
 
-
     /* As a convenience we provide a write() interface to the audio buffer.
      * This is implemented on top of lockBuffer/unlockBuffer. For best
-     * performance
+     * performance use callbacks. Return actual number of bytes written.
      *
      */
             ssize_t     write(const void* buffer, size_t size);
@@ -436,9 +450,9 @@
     };
 
             bool processAudioBuffer(const sp<AudioTrackThread>& thread);
-            status_t createTrack_l(int streamType,
+            status_t createTrack_l(audio_stream_type_t streamType,
                                  uint32_t sampleRate,
-                                 uint32_t format,
+                                 audio_format_t format,
                                  uint32_t channelMask,
                                  int frameCount,
                                  uint32_t flags,
@@ -449,6 +463,7 @@
             status_t setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
             audio_io_handle_t getOutput_l();
             status_t restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart);
+            bool stopped_l() const { return !mActive; }
 
     sp<IAudioTrack>         mAudioTrack;
     sp<IMemory>             mCblkMemory;
@@ -459,8 +474,8 @@
     uint32_t                mFrameCount;
 
     audio_track_cblk_t*     mCblk;
-    uint32_t                mFormat;
-    uint8_t                 mStreamType;
+    audio_format_t          mFormat;
+    audio_stream_type_t     mStreamType;
     uint8_t                 mChannelCount;
     uint8_t                 mMuted;
     uint8_t                 mReserved;
@@ -468,7 +483,7 @@
     status_t                mStatus;
     uint32_t                mLatency;
 
-    volatile int32_t        mActive;
+    bool                    mActive;                // protected by mLock
 
     callback_t              mCbf;
     void*                   mUserData;
@@ -485,8 +500,10 @@
     uint32_t                mFlags;
     int                     mSessionId;
     int                     mAuxEffectId;
-    Mutex                   mLock;
+    mutable Mutex           mLock;
     status_t                mRestoreStatus;
+    int                     mPreviousPriority;          // before start()
+    int                     mPreviousSchedulingGroup;
 };
 
 
diff --git a/include/media/IAudioFlinger.h b/include/media/IAudioFlinger.h
index 9e3cb7f..7c0d886 100644
--- a/include/media/IAudioFlinger.h
+++ b/include/media/IAudioFlinger.h
@@ -46,9 +46,9 @@
      */
     virtual sp<IAudioTrack> createTrack(
                                 pid_t pid,
-                                int streamType,
+                                audio_stream_type_t streamType,
                                 uint32_t sampleRate,
-                                uint32_t format,
+                                audio_format_t format,
                                 uint32_t channelMask,
                                 int frameCount,
                                 uint32_t flags,
@@ -61,7 +61,7 @@
                                 pid_t pid,
                                 int input,
                                 uint32_t sampleRate,
-                                uint32_t format,
+                                audio_format_t format,
                                 uint32_t channelMask,
                                 int frameCount,
                                 uint32_t flags,
@@ -73,7 +73,7 @@
      */
     virtual     uint32_t    sampleRate(int output) const = 0;
     virtual     int         channelCount(int output) const = 0;
-    virtual     uint32_t    format(int output) const = 0;
+    virtual     audio_format_t format(int output) const = 0;
     virtual     size_t      frameCount(int output) const = 0;
     virtual     uint32_t    latency(int output) const = 0;
 
@@ -89,14 +89,14 @@
     /* set/get stream type state. This will probably be used by
      * the preference panel, mostly.
      */
-    virtual     status_t    setStreamVolume(int stream, float value, int output) = 0;
-    virtual     status_t    setStreamMute(int stream, bool muted) = 0;
+    virtual     status_t    setStreamVolume(audio_stream_type_t stream, float value, int output) = 0;
+    virtual     status_t    setStreamMute(audio_stream_type_t stream, bool muted) = 0;
 
-    virtual     float       streamVolume(int stream, int output) const = 0;
-    virtual     bool        streamMute(int stream) const = 0;
+    virtual     float       streamVolume(audio_stream_type_t stream, int output) const = 0;
+    virtual     bool        streamMute(audio_stream_type_t stream) const = 0;
 
     // set audio mode
-    virtual     status_t    setMode(int mode) = 0;
+    virtual     status_t    setMode(audio_mode_t mode) = 0;
 
     // mic mute/state
     virtual     status_t    setMicMute(bool state) = 0;
@@ -109,11 +109,11 @@
     virtual void registerClient(const sp<IAudioFlingerClient>& client) = 0;
 
     // retrieve the audio recording buffer size
-    virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount) = 0;
+    virtual size_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) = 0;
 
     virtual int openOutput(uint32_t *pDevices,
                                     uint32_t *pSamplingRate,
-                                    uint32_t *pFormat,
+                                    audio_format_t *pFormat,
                                     uint32_t *pChannels,
                                     uint32_t *pLatencyMs,
                                     uint32_t flags) = 0;
@@ -124,12 +124,12 @@
 
     virtual int openInput(uint32_t *pDevices,
                                     uint32_t *pSamplingRate,
-                                    uint32_t *pFormat,
+                                    audio_format_t *pFormat,
                                     uint32_t *pChannels,
                                     uint32_t acoustics) = 0;
     virtual status_t closeInput(int input) = 0;
 
-    virtual status_t setStreamOutput(uint32_t stream, int output) = 0;
+    virtual status_t setStreamOutput(audio_stream_type_t stream, int output) = 0;
 
     virtual status_t setVoiceVolume(float volume) = 0;
 
diff --git a/include/media/IAudioPolicyService.h b/include/media/IAudioPolicyService.h
index 9807cbe..07d17c5 100644
--- a/include/media/IAudioPolicyService.h
+++ b/include/media/IAudioPolicyService.h
@@ -45,13 +45,12 @@
                                               const char *device_address) = 0;
     virtual audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device,
                                                                           const char *device_address) = 0;
-    virtual status_t setPhoneState(int state) = 0;
-    virtual status_t setRingerMode(uint32_t mode, uint32_t mask) = 0;
+    virtual status_t setPhoneState(audio_mode_t state) = 0;
     virtual status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config) = 0;
     virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage) = 0;
     virtual audio_io_handle_t getOutput(audio_stream_type_t stream,
                                         uint32_t samplingRate = 0,
-                                        uint32_t format = AUDIO_FORMAT_DEFAULT,
+                                        audio_format_t format = AUDIO_FORMAT_DEFAULT,
                                         uint32_t channels = 0,
                                         audio_policy_output_flags_t flags = AUDIO_POLICY_OUTPUT_FLAG_INDIRECT) = 0;
     virtual status_t startOutput(audio_io_handle_t output,
@@ -63,7 +62,7 @@
     virtual void releaseOutput(audio_io_handle_t output) = 0;
     virtual audio_io_handle_t getInput(int inputSource,
                                     uint32_t samplingRate = 0,
-                                    uint32_t format = AUDIO_FORMAT_DEFAULT,
+                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
                                     uint32_t channels = 0,
                                     audio_in_acoustics_t acoustics = (audio_in_acoustics_t)0,
                                     int audioSession = 0) = 0;
@@ -73,8 +72,12 @@
     virtual status_t initStreamVolume(audio_stream_type_t stream,
                                       int indexMin,
                                       int indexMax) = 0;
-    virtual status_t setStreamVolumeIndex(audio_stream_type_t stream, int index) = 0;
-    virtual status_t getStreamVolumeIndex(audio_stream_type_t stream, int *index) = 0;
+    virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
+                                          int index,
+                                          audio_devices_t device) = 0;
+    virtual status_t getStreamVolumeIndex(audio_stream_type_t stream,
+                                          int *index,
+                                          audio_devices_t device) = 0;
     virtual uint32_t getStrategyForStream(audio_stream_type_t stream) = 0;
     virtual uint32_t getDevicesForStream(audio_stream_type_t stream) = 0;
     virtual audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc) = 0;
@@ -85,7 +88,7 @@
                                     int id) = 0;
     virtual status_t unregisterEffect(int id) = 0;
     virtual status_t setEffectEnabled(int id, bool enabled) = 0;
-    virtual bool     isStreamActive(int stream, uint32_t inPastMs = 0) const = 0;
+    virtual bool     isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const = 0;
     virtual status_t queryDefaultPreProcessing(int audioSession,
                                               effect_descriptor_t *descriptors,
                                               uint32_t *count) = 0;
diff --git a/include/media/IAudioTrack.h b/include/media/IAudioTrack.h
index 47d530b..b83e552 100644
--- a/include/media/IAudioTrack.h
+++ b/include/media/IAudioTrack.h
@@ -35,6 +35,9 @@
 public: 
     DECLARE_META_INTERFACE(AudioTrack);
 
+    /* Get this track's control block */
+    virtual sp<IMemory> getCblk() const = 0;
+
     /* After it's created the track is not active. Call start() to
      * make it active. If set, the callback will start being called.
      */
@@ -46,13 +49,13 @@
      */
     virtual void        stop() = 0;
 
-    /* flush a stopped track. All pending buffers are discarded.
-     * This function has no effect if the track is not stoped.
+    /* Flush a stopped track. All pending buffers are discarded.
+     * This function has no effect if the track is not stopped.
      */
     virtual void        flush() = 0;
 
-    /* mute or unmutes this track.
-     * While mutted, the callback, if set, is still called.
+    /* Mute or unmute this track.
+     * While muted, the callback, if set, is still called.
      */
     virtual void        mute(bool) = 0;
     
@@ -67,8 +70,6 @@
      */
     virtual status_t    attachAuxEffect(int effectId) = 0;
 
-    /* get this tracks control block */
-    virtual sp<IMemory> getCblk() const = 0;    
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/media/IMediaPlayer.h b/include/media/IMediaPlayer.h
index e905903..6425886 100644
--- a/include/media/IMediaPlayer.h
+++ b/include/media/IMediaPlayer.h
@@ -21,6 +21,7 @@
 #include <binder/IInterface.h>
 #include <binder/Parcel.h>
 #include <utils/KeyedVector.h>
+#include <system/audio.h>
 
 namespace android {
 
@@ -51,7 +52,7 @@
     virtual status_t        getCurrentPosition(int* msec) = 0;
     virtual status_t        getDuration(int* msec) = 0;
     virtual status_t        reset() = 0;
-    virtual status_t        setAudioStreamType(int type) = 0;
+    virtual status_t        setAudioStreamType(audio_stream_type_t type) = 0;
     virtual status_t        setLooping(int loop) = 0;
     virtual status_t        setVolume(float leftVolume, float rightVolume) = 0;
     virtual status_t        setAuxEffectSendLevel(float level) = 0;
diff --git a/include/media/IMediaPlayerService.h b/include/media/IMediaPlayerService.h
index 93bbe13..4f46fcd 100644
--- a/include/media/IMediaPlayerService.h
+++ b/include/media/IMediaPlayerService.h
@@ -23,6 +23,7 @@
 #include <utils/String8.h>
 #include <binder/IInterface.h>
 #include <binder/Parcel.h>
+#include <system/audio.h>
 
 #include <media/IMediaPlayerClient.h>
 #include <media/IMediaPlayer.h>
@@ -43,8 +44,8 @@
     virtual sp<IMediaMetadataRetriever> createMetadataRetriever(pid_t pid) = 0;
     virtual sp<IMediaPlayer> create(pid_t pid, const sp<IMediaPlayerClient>& client, int audioSessionId = 0) = 0;
 
-    virtual sp<IMemory>         decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) = 0;
-    virtual sp<IMemory>         decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat) = 0;
+    virtual sp<IMemory>         decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat) = 0;
+    virtual sp<IMemory>         decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat) = 0;
     virtual sp<IOMX>            getOMX() = 0;
 
     // codecs and audio devices usage tracking for the battery app
diff --git a/include/media/JetPlayer.h b/include/media/JetPlayer.h
index 16764a9..491a950 100644
--- a/include/media/JetPlayer.h
+++ b/include/media/JetPlayer.h
@@ -65,7 +65,6 @@
 
 
 private:
-    static  int         renderThread(void*);
     int                 render();
     void                fireUpdateOnStatusChange();
     void                fireEventsFromJetQueue();
@@ -95,8 +94,30 @@
     S_JET_STATUS        mJetStatus;
     S_JET_STATUS        mPreviousJetStatus;
 
-    char                mJetFilePath[256];
+    char                mJetFilePath[PATH_MAX];
 
+    class JetPlayerThread : public Thread {
+    public:
+        JetPlayerThread(JetPlayer *player) : mPlayer(player) {
+        }
+
+    protected:
+        virtual ~JetPlayerThread() {}
+
+    private:
+        JetPlayer *mPlayer;
+
+        bool threadLoop() {
+            int result;
+            result = mPlayer->render();
+            return false;
+        }
+
+        JetPlayerThread(const JetPlayerThread &);
+        JetPlayerThread &operator=(const JetPlayerThread &);
+    };
+
+    sp<JetPlayerThread> mThread;
 
 }; // end class JetPlayer
 
diff --git a/include/media/MediaPlayerInterface.h b/include/media/MediaPlayerInterface.h
index 80f43a3..7beb176 100644
--- a/include/media/MediaPlayerInterface.h
+++ b/include/media/MediaPlayerInterface.h
@@ -85,7 +85,7 @@
         // audio data.
         virtual status_t    open(
                 uint32_t sampleRate, int channelCount,
-                int format=AUDIO_FORMAT_PCM_16_BIT,
+                audio_format_t format=AUDIO_FORMAT_PCM_16_BIT,
                 int bufferCount=DEFAULT_AUDIOSINK_BUFFERCOUNT,
                 AudioCallback cb = NULL,
                 void *cookie = NULL) = 0;
@@ -199,7 +199,7 @@
     virtual             ~MediaPlayerHWInterface() {}
     virtual bool        hardwareOutput() { return true; }
     virtual status_t    setVolume(float leftVolume, float rightVolume) = 0;
-    virtual status_t    setAudioStreamType(int streamType) = 0;
+    virtual status_t    setAudioStreamType(audio_stream_type_t streamType) = 0;
 };
 
 }; // namespace android
diff --git a/include/media/ToneGenerator.h b/include/media/ToneGenerator.h
index 1ad1f26..7d890bd 100644
--- a/include/media/ToneGenerator.h
+++ b/include/media/ToneGenerator.h
@@ -151,7 +151,7 @@
         NUM_SUP_TONES = LAST_SUP_TONE-FIRST_SUP_TONE+1
     };
 
-    ToneGenerator(int streamType, float volume, bool threadCanCallJava = false);
+    ToneGenerator(audio_stream_type_t streamType, float volume, bool threadCanCallJava = false);
     ~ToneGenerator();
 
     bool startTone(int toneType, int durationMs = -1);
@@ -266,7 +266,7 @@
     Mutex mCbkCondLock; // Mutex associated to mWaitCbkCond
     Condition mWaitCbkCond; // condition enabling interface to wait for audio callback completion after a change is requested
     float mVolume;  // Volume applied to audio track
-    int mStreamType; // Audio stream used for output
+    audio_stream_type_t mStreamType; // Audio stream used for output
     unsigned int mProcessSize;  // Size of audio blocks generated at a time by audioCallback() (in PCM frames).
 
     bool initAudioTrack();
diff --git a/include/media/Visualizer.h b/include/media/Visualizer.h
index 5d2c874..1a4cbca 100644
--- a/include/media/Visualizer.h
+++ b/include/media/Visualizer.h
@@ -143,7 +143,7 @@
     void periodicCapture();
     uint32_t initCaptureSize();
 
-    Mutex mLock;
+    Mutex mCaptureLock;
     uint32_t mCaptureRate;
     uint32_t mCaptureSize;
     uint32_t mSampleRate;
diff --git a/include/media/mediaplayer.h b/include/media/mediaplayer.h
index e6a0cc5..00b7dd5 100644
--- a/include/media/mediaplayer.h
+++ b/include/media/mediaplayer.h
@@ -185,13 +185,13 @@
             status_t        getCurrentPosition(int *msec);
             status_t        getDuration(int *msec);
             status_t        reset();
-            status_t        setAudioStreamType(int type);
+            status_t        setAudioStreamType(audio_stream_type_t type);
             status_t        setLooping(int loop);
             bool            isLooping();
             status_t        setVolume(float leftVolume, float rightVolume);
             void            notify(int msg, int ext1, int ext2, const Parcel *obj = NULL);
-    static  sp<IMemory>     decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
-    static  sp<IMemory>     decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
+    static  sp<IMemory>     decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat);
+    static  sp<IMemory>     decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat);
             status_t        invoke(const Parcel& request, Parcel *reply);
             status_t        setMetadataFilter(const Parcel& filter);
             status_t        getMetadata(bool update_only, bool apply_filter, Parcel *metadata);
@@ -223,7 +223,7 @@
     int                         mSeekPosition;
     bool                        mPrepareSync;
     status_t                    mPrepareStatus;
-    int                         mStreamType;
+    audio_stream_type_t         mStreamType;
     bool                        mLoop;
     float                       mLeftVolume;
     float                       mRightVolume;
diff --git a/include/media/stagefright/DataSource.h b/include/media/stagefright/DataSource.h
index 713af92..00d583e 100644
--- a/include/media/stagefright/DataSource.h
+++ b/include/media/stagefright/DataSource.h
@@ -81,7 +81,7 @@
     static void RegisterDefaultSniffers();
 
     // for DRM
-    virtual sp<DecryptHandle> DrmInitialization() {
+    virtual sp<DecryptHandle> DrmInitialization(const char *mime = NULL) {
         return NULL;
     }
     virtual void getDrmInfo(sp<DecryptHandle> &handle, DrmManagerClient **client) {};
diff --git a/include/media/stagefright/FileSource.h b/include/media/stagefright/FileSource.h
index 6cf86dc..d994cb3 100644
--- a/include/media/stagefright/FileSource.h
+++ b/include/media/stagefright/FileSource.h
@@ -38,7 +38,7 @@
 
     virtual status_t getSize(off64_t *size);
 
-    virtual sp<DecryptHandle> DrmInitialization();
+    virtual sp<DecryptHandle> DrmInitialization(const char *mime);
 
     virtual void getDrmInfo(sp<DecryptHandle> &handle, DrmManagerClient **client);
 
diff --git a/include/media/stagefright/MediaExtractor.h b/include/media/stagefright/MediaExtractor.h
index eb45237..94090ee 100644
--- a/include/media/stagefright/MediaExtractor.h
+++ b/include/media/stagefright/MediaExtractor.h
@@ -56,10 +56,10 @@
     virtual uint32_t flags() const;
 
     // for DRM
-    virtual void setDrmFlag(bool flag) {
+    void setDrmFlag(bool flag) {
         mIsDrm = flag;
     };
-    virtual bool getDrmFlag() {
+    bool getDrmFlag() {
         return mIsDrm;
     }
     virtual char* getDrmTrackInfo(size_t trackID, int *len) {
diff --git a/include/media/thread_init.h b/include/media/thread_init.h
deleted file mode 100644
index 2feac86..0000000
--- a/include/media/thread_init.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef THREAD_INIT_H
-#define THREAD_INIT_H
-
-bool InitializeForThread();
-void UninitializeForThread();
-
-#endif /* THREAD_INIT_H*/
-	
diff --git a/include/private/gui/ComposerService.h b/include/private/gui/ComposerService.h
new file mode 100644
index 0000000..d04491a
--- /dev/null
+++ b/include/private/gui/ComposerService.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2011 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_PRIVATE_GUI_COMPOSER_SERVICE_H
+#define ANDROID_PRIVATE_GUI_COMPOSER_SERVICE_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Singleton.h>
+#include <utils/StrongPointer.h>
+
+
+namespace android {
+
+// ---------------------------------------------------------------------------
+
+class IMemoryHeap;
+class ISurfaceComposer;
+class surface_flinger_cblk_t;
+
+// ---------------------------------------------------------------------------
+
+class ComposerService : public Singleton<ComposerService>
+{
+    // these are constants
+    sp<ISurfaceComposer> mComposerService;
+    sp<IMemoryHeap> mServerCblkMemory;
+    surface_flinger_cblk_t volatile* mServerCblk;
+    ComposerService();
+    friend class Singleton<ComposerService>;
+public:
+    static sp<ISurfaceComposer> getComposerService();
+    static surface_flinger_cblk_t const volatile * getControlBlock();
+};
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_PRIVATE_GUI_COMPOSER_SERVICE_H
diff --git a/include/private/media/AudioTrackShared.h b/include/private/media/AudioTrackShared.h
index 20abd51..ffc546e 100644
--- a/include/private/media/AudioTrackShared.h
+++ b/include/private/media/AudioTrackShared.h
@@ -59,8 +59,8 @@
 
     // The data members are grouped so that members accessed frequently and in the same context
     // are in the same line of data cache.
-                Mutex       lock;
-                Condition   cv;
+                Mutex       lock;           // sizeof(int)
+                Condition   cv;             // sizeof(int)
     volatile    uint32_t    user;
     volatile    uint32_t    server;
                 uint32_t    userBase;
@@ -71,21 +71,26 @@
                 uint32_t    loopStart;
                 uint32_t    loopEnd;
                 int         loopCount;
-    volatile    union {
-                    uint16_t    volume[2];
-                    uint32_t    volumeLR;
-                };
+
+                // Channel volumes are fixed point U4.12, so 0x1000 means 1.0.
+                // Left channel is in [0:15], right channel is in [16:31].
+                // Always read and write the combined pair atomically.
+                // For AudioTrack only, not used by AudioRecord.
+                uint32_t    volumeLR;
+
                 uint32_t    sampleRate;
                 // NOTE: audio_track_cblk_t::frameSize is not equal to AudioTrack::frameSize() for
                 // 8 bit PCM data: in this case,  mCblk->frameSize is based on a sample size of
                 // 16 bit because data is converted to 16 bit before being stored in buffer
 
-                uint8_t     frameSize;
+                uint8_t     frameSize;       // would normally be size_t, but 8 bits is plenty
                 uint8_t     pad1;
                 uint16_t    bufferTimeoutMs; // Maximum cumulated timeout before restarting audioflinger
 
                 uint16_t    waitTimeMs;      // Cumulated wait time
-                uint16_t    sendLevel;
+private:
+                uint16_t    mSendLevel;      // Fixed point U4.12 so 0x1000 means 1.0
+public:
     volatile    int32_t     flags;
 
                 // Cache line boundary (32 bytes)
@@ -98,6 +103,19 @@
                 uint32_t    framesAvailable_l();
                 uint32_t    framesReady();
                 bool        tryLock();
+
+                // No barriers on the following operations, so the ordering of loads/stores
+                // with respect to other parameters is UNPREDICTABLE. That's considered safe.
+
+                // for AudioTrack client only, caller must limit to 0.0 <= sendLevel <= 1.0
+                void        setSendLevel(float sendLevel) {
+                    mSendLevel = uint16_t(sendLevel * 0x1000);
+                }
+
+                // for AudioFlinger only; the return value must be validated by the caller
+                uint16_t    getSendLevel_U4_12() const {
+                    return mSendLevel;
+                }
 };
 
 
diff --git a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
index 62be78c..108d36a 100644
--- a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
+++ b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
@@ -133,7 +133,8 @@
 int  LvmEffect_enable          (EffectContext *pContext);
 int  LvmEffect_disable         (EffectContext *pContext);
 void LvmEffect_free            (EffectContext *pContext);
-int  Effect_configure          (EffectContext *pContext, effect_config_t *pConfig);
+int  Effect_setConfig          (EffectContext *pContext, effect_config_t *pConfig);
+void Effect_getConfig          (EffectContext *pContext, effect_config_t *pConfig);
 int  BassBoost_setParameter    (EffectContext *pContext, void *pParam, void *pValue);
 int  BassBoost_getParameter    (EffectContext *pContext,
                                void           *pParam,
@@ -936,7 +937,7 @@
 }    /* end LvmEffect_free */
 
 //----------------------------------------------------------------------------
-// Effect_configure()
+// Effect_setConfig()
 //----------------------------------------------------------------------------
 // Purpose: Set input and output audio configuration.
 //
@@ -949,9 +950,9 @@
 //
 //----------------------------------------------------------------------------
 
-int Effect_configure(EffectContext *pContext, effect_config_t *pConfig){
+int Effect_setConfig(EffectContext *pContext, effect_config_t *pConfig){
     LVM_Fs_en   SampleRate;
-    //ALOGV("\tEffect_configure start");
+    //ALOGV("\tEffect_setConfig start");
 
     CHECK_ARG(pContext != NULL);
     CHECK_ARG(pConfig != NULL);
@@ -992,7 +993,7 @@
         pContext->pBundledContext->SamplesPerSecond = 48000*2; // 2 secs Stereo
         break;
     default:
-        ALOGV("\tEffect_Configure invalid sampling rate %d", pConfig->inputCfg.samplingRate);
+        ALOGV("\tEffect_setConfig invalid sampling rate %d", pConfig->inputCfg.samplingRate);
         return -EINVAL;
     }
 
@@ -1001,28 +1002,47 @@
         LVM_ControlParams_t     ActiveParams;
         LVM_ReturnStatus_en     LvmStatus = LVM_SUCCESS;
 
-        ALOGV("\tEffect_configure change sampling rate to %d", SampleRate);
+        ALOGV("\tEffect_setConfig change sampling rate to %d", SampleRate);
 
         /* Get the current settings */
         LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance,
                                          &ActiveParams);
 
-        LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "Effect_configure")
+        LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "Effect_setConfig")
         if(LvmStatus != LVM_SUCCESS) return -EINVAL;
 
         LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
-        LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "Effect_configure")
-        ALOGV("\tEffect_configure Succesfully called LVM_SetControlParameters\n");
+        LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "Effect_setConfig")
+        ALOGV("\tEffect_setConfig Succesfully called LVM_SetControlParameters\n");
         pContext->pBundledContext->SampleRate = SampleRate;
 
     }else{
-        //ALOGV("\tEffect_configure keep sampling rate at %d", SampleRate);
+        //ALOGV("\tEffect_setConfig keep sampling rate at %d", SampleRate);
     }
 
-    //ALOGV("\tEffect_configure End....");
+    //ALOGV("\tEffect_setConfig End....");
     return 0;
-}   /* end Effect_configure */
+}   /* end Effect_setConfig */
+
+//----------------------------------------------------------------------------
+// Effect_getConfig()
+//----------------------------------------------------------------------------
+// Purpose: Get input and output audio configuration.
+//
+// Inputs:
+//  pContext:   effect engine context
+//  pConfig:    pointer to effect_config_t structure holding input and output
+//      configuration parameters
+//
+// Outputs:
+//
+//----------------------------------------------------------------------------
+
+void Effect_getConfig(EffectContext *pContext, effect_config_t *pConfig)
+{
+    memcpy(pConfig, &pContext->config, sizeof(effect_config_t));
+}   /* end Effect_getConfig */
 
 //----------------------------------------------------------------------------
 // BassGetStrength()
@@ -2778,23 +2798,34 @@
             }
             break;
 
-        case EFFECT_CMD_CONFIGURE:
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_CONFIGURE start");
+        case EFFECT_CMD_SET_CONFIG:
+            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_CONFIG start");
             if (pCmdData    == NULL||
                 cmdSize     != sizeof(effect_config_t)||
                 pReplyData  == NULL||
                 *replySize  != sizeof(int)){
                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: "
-                        "EFFECT_CMD_CONFIGURE: ERROR");
+                        "EFFECT_CMD_SET_CONFIG: ERROR");
                 return -EINVAL;
             }
-            *(int *) pReplyData = android::Effect_configure(pContext, (effect_config_t *) pCmdData);
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_CONFIGURE end");
+            *(int *) pReplyData = android::Effect_setConfig(pContext, (effect_config_t *) pCmdData);
+            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_CONFIG end");
+            break;
+
+        case EFFECT_CMD_GET_CONFIG:
+            if (pReplyData == NULL ||
+                *replySize != sizeof(effect_config_t)) {
+                ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: "
+                        "EFFECT_CMD_GET_CONFIG: ERROR");
+                return -EINVAL;
+            }
+
+            android::Effect_getConfig(pContext, (effect_config_t *)pReplyData);
             break;
 
         case EFFECT_CMD_RESET:
             //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_RESET start");
-            android::Effect_configure(pContext, &pContext->config);
+            android::Effect_setConfig(pContext, &pContext->config);
             //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_RESET end");
             break;
 
@@ -3078,20 +3109,20 @@
 
                     if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
                         ALOGV("\tEFFECT_CMD_SET_DEVICE disable LVM_BASS_BOOST %d",
-                              *(int32_t *)pCmdData);
+                             *(int32_t *)pCmdData);
                         android::LvmEffect_disable(pContext);
                     }
                     pContext->pBundledContext->bBassTempDisabled = LVM_TRUE;
                 } else {
                     ALOGV("\tEFFECT_CMD_SET_DEVICE device is valid for LVM_BASS_BOOST %d",
-                          *(int32_t *)pCmdData);
+                         *(int32_t *)pCmdData);
 
                     // If a device supports bassboost and the effect has been temporarily disabled
                     // previously then re-enable it
 
                     if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
                         ALOGV("\tEFFECT_CMD_SET_DEVICE re-enable LVM_BASS_BOOST %d",
-                              *(int32_t *)pCmdData);
+                             *(int32_t *)pCmdData);
                         android::LvmEffect_enable(pContext);
                     }
                     pContext->pBundledContext->bBassTempDisabled = LVM_FALSE;
diff --git a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
index 1825aab..09cd5cc 100755
--- a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
+++ b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
@@ -175,7 +175,8 @@
 //--- local function prototypes
 int  Reverb_init            (ReverbContext *pContext);
 void Reverb_free            (ReverbContext *pContext);
-int  Reverb_configure       (ReverbContext *pContext, effect_config_t *pConfig);
+int  Reverb_setConfig       (ReverbContext *pContext, effect_config_t *pConfig);
+void Reverb_getConfig       (ReverbContext *pContext, effect_config_t *pConfig);
 int  Reverb_setParameter    (ReverbContext *pContext, void *pParam, void *pValue);
 int  Reverb_getParameter    (ReverbContext *pContext,
                              void          *pParam,
@@ -609,7 +610,7 @@
 }    /* end Reverb_free */
 
 //----------------------------------------------------------------------------
-// Reverb_configure()
+// Reverb_setConfig()
 //----------------------------------------------------------------------------
 // Purpose: Set input and output audio configuration.
 //
@@ -622,9 +623,9 @@
 //
 //----------------------------------------------------------------------------
 
-int Reverb_configure(ReverbContext *pContext, effect_config_t *pConfig){
+int Reverb_setConfig(ReverbContext *pContext, effect_config_t *pConfig){
     LVM_Fs_en   SampleRate;
-    //ALOGV("\tReverb_configure start");
+    //ALOGV("\tReverb_setConfig start");
 
     CHECK_ARG(pContext != NULL);
     CHECK_ARG(pConfig != NULL);
@@ -642,7 +643,7 @@
         return -EINVAL;
     }
 
-    //ALOGV("\tReverb_configure calling memcpy");
+    //ALOGV("\tReverb_setConfig calling memcpy");
     memcpy(&pContext->config, pConfig, sizeof(effect_config_t));
 
 
@@ -666,7 +667,7 @@
         SampleRate = LVM_FS_48000;
         break;
     default:
-        ALOGV("\rReverb_Configure invalid sampling rate %d", pConfig->inputCfg.samplingRate);
+        ALOGV("\rReverb_setConfig invalid sampling rate %d", pConfig->inputCfg.samplingRate);
         return -EINVAL;
     }
 
@@ -675,28 +676,46 @@
         LVREV_ControlParams_st    ActiveParams;
         LVREV_ReturnStatus_en     LvmStatus = LVREV_SUCCESS;
 
-        //ALOGV("\tReverb_configure change sampling rate to %d", SampleRate);
+        //ALOGV("\tReverb_setConfig change sampling rate to %d", SampleRate);
 
         /* Get the current settings */
         LvmStatus = LVREV_GetControlParameters(pContext->hInstance,
                                          &ActiveParams);
 
-        LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "Reverb_configure")
+        LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "Reverb_setConfig")
         if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
 
         LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
 
-        LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "Reverb_configure")
-        //ALOGV("\tReverb_configure Succesfully called LVREV_SetControlParameters\n");
+        LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "Reverb_setConfig")
+        //ALOGV("\tReverb_setConfig Succesfully called LVREV_SetControlParameters\n");
 
     }else{
-        //ALOGV("\tReverb_configure keep sampling rate at %d", SampleRate);
+        //ALOGV("\tReverb_setConfig keep sampling rate at %d", SampleRate);
     }
 
-    //ALOGV("\tReverb_configure End");
+    //ALOGV("\tReverb_setConfig End");
     return 0;
-}   /* end Reverb_configure */
+}   /* end Reverb_setConfig */
 
+//----------------------------------------------------------------------------
+// Reverb_getConfig()
+//----------------------------------------------------------------------------
+// Purpose: Get input and output audio configuration.
+//
+// Inputs:
+//  pContext:   effect engine context
+//  pConfig:    pointer to effect_config_t structure holding input and output
+//      configuration parameters
+//
+// Outputs:
+//
+//----------------------------------------------------------------------------
+
+void Reverb_getConfig(ReverbContext *pContext, effect_config_t *pConfig)
+{
+    memcpy(pConfig, &pContext->config, sizeof(effect_config_t));
+}   /* end Reverb_getConfig */
 
 //----------------------------------------------------------------------------
 // Reverb_init()
@@ -1924,24 +1943,36 @@
             *(int *) pReplyData = 0;
             break;
 
-        case EFFECT_CMD_CONFIGURE:
+        case EFFECT_CMD_SET_CONFIG:
             //ALOGV("\tReverb_command cmdCode Case: "
-            //        "EFFECT_CMD_CONFIGURE start");
-            if (pCmdData    == NULL||
-                cmdSize     != sizeof(effect_config_t)||
-                pReplyData  == NULL||
-                *replySize  != sizeof(int)){
+            //        "EFFECT_CMD_SET_CONFIG start");
+            if (pCmdData == NULL ||
+                cmdSize != sizeof(effect_config_t) ||
+                pReplyData == NULL ||
+                *replySize != sizeof(int)) {
                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_CONFIGURE: ERROR");
+                        "EFFECT_CMD_SET_CONFIG: ERROR");
                 return -EINVAL;
             }
-            *(int *) pReplyData = Reverb_configure(pContext, (effect_config_t *) pCmdData);
+            *(int *) pReplyData = android::Reverb_setConfig(pContext,
+                                                            (effect_config_t *) pCmdData);
+            break;
+
+        case EFFECT_CMD_GET_CONFIG:
+            if (pReplyData == NULL ||
+                *replySize != sizeof(effect_config_t)) {
+                ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+                        "EFFECT_CMD_GET_CONFIG: ERROR");
+                return -EINVAL;
+            }
+
+            android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
             break;
 
         case EFFECT_CMD_RESET:
             //ALOGV("\tReverb_command cmdCode Case: "
             //        "EFFECT_CMD_RESET start");
-            Reverb_configure(pContext, &pContext->config);
+            Reverb_setConfig(pContext, &pContext->config);
             break;
 
         case EFFECT_CMD_GET_PARAM:{
diff --git a/media/libeffects/preprocessing/PreProcessing.cpp b/media/libeffects/preprocessing/PreProcessing.cpp
index 6267d1d..e988e06 100755
--- a/media/libeffects/preprocessing/PreProcessing.cpp
+++ b/media/libeffects/preprocessing/PreProcessing.cpp
@@ -940,6 +940,19 @@
     return 0;
 }
 
+void Session_GetConfig(preproc_session_t *session, effect_config_t *config)
+{
+    memset(config, 0, sizeof(effect_config_t));
+    config->inputCfg.samplingRate = config->outputCfg.samplingRate = session->samplingRate;
+    config->inputCfg.format = config->outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
+    config->inputCfg.channels = session->inChannelCount == 1 ?
+                                    AUDIO_CHANNEL_IN_MONO : AUDIO_CHANNEL_IN_STEREO;
+    config->outputCfg.channels = session->outChannelCount == 1 ?
+                                    AUDIO_CHANNEL_IN_MONO : AUDIO_CHANNEL_IN_STEREO;
+    config->inputCfg.mask = config->outputCfg.mask =
+            (EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT);
+}
+
 int Session_SetReverseConfig(preproc_session_t *session, effect_config_t *config)
 {
     if (config->inputCfg.samplingRate != config->outputCfg.samplingRate ||
@@ -969,6 +982,17 @@
     return 0;
 }
 
+void Session_GetReverseConfig(preproc_session_t *session, effect_config_t *config)
+{
+    memset(config, 0, sizeof(effect_config_t));
+    config->inputCfg.samplingRate = config->outputCfg.samplingRate = session->samplingRate;
+    config->inputCfg.format = config->outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
+    config->inputCfg.channels = config->outputCfg.channels =
+            session->revChannelCount == 1 ? AUDIO_CHANNEL_IN_MONO : AUDIO_CHANNEL_IN_STEREO;
+    config->inputCfg.mask = config->outputCfg.mask =
+            (EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT);
+}
+
 void Session_SetProcEnabled(preproc_session_t *session, uint32_t procId, bool enabled)
 {
     if (enabled) {
@@ -1250,13 +1274,13 @@
             *(int *)pReplyData = 0;
             break;
 
-        case EFFECT_CMD_CONFIGURE:
+        case EFFECT_CMD_SET_CONFIG:
             if (pCmdData    == NULL||
                 cmdSize     != sizeof(effect_config_t)||
                 pReplyData  == NULL||
                 *replySize  != sizeof(int)){
                 ALOGV("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_CONFIGURE: ERROR");
+                        "EFFECT_CMD_SET_CONFIG: ERROR");
                 return -EINVAL;
             }
             *(int *)pReplyData = Session_SetConfig(effect->session, (effect_config_t *)pCmdData);
@@ -1266,13 +1290,24 @@
             *(int *)pReplyData = Effect_SetState(effect, PREPROC_EFFECT_STATE_CONFIG);
             break;
 
-        case EFFECT_CMD_CONFIGURE_REVERSE:
-            if (pCmdData    == NULL||
-                cmdSize     != sizeof(effect_config_t)||
-                pReplyData  == NULL||
-                *replySize  != sizeof(int)){
+        case EFFECT_CMD_GET_CONFIG:
+            if (pReplyData == NULL ||
+                *replySize != sizeof(effect_config_t)) {
+                ALOGV("\tLVM_ERROR : PreProcessingFx_Command cmdCode Case: "
+                        "EFFECT_CMD_GET_CONFIG: ERROR");
+                return -EINVAL;
+            }
+
+            Session_GetConfig(effect->session, (effect_config_t *)pCmdData);
+            break;
+
+        case EFFECT_CMD_SET_CONFIG_REVERSE:
+            if (pCmdData == NULL ||
+                cmdSize != sizeof(effect_config_t) ||
+                pReplyData == NULL ||
+                *replySize != sizeof(int)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_CONFIGURE_REVERSE: ERROR");
+                        "EFFECT_CMD_SET_CONFIG_REVERSE: ERROR");
                 return -EINVAL;
             }
             *(int *)pReplyData = Session_SetReverseConfig(effect->session,
@@ -1282,6 +1317,16 @@
             }
             break;
 
+        case EFFECT_CMD_GET_CONFIG_REVERSE:
+            if (pReplyData == NULL ||
+                *replySize != sizeof(effect_config_t)){
+                ALOGV("PreProcessingFx_Command cmdCode Case: "
+                        "EFFECT_CMD_GET_CONFIG_REVERSE: ERROR");
+                return -EINVAL;
+            }
+            Session_GetReverseConfig(effect->session, (effect_config_t *)pCmdData);
+            break;
+
         case EFFECT_CMD_RESET:
             if (effect->ops->reset) {
                 effect->ops->reset(effect);
diff --git a/media/libeffects/testlibs/AudioBiquadFilter.cpp b/media/libeffects/testlibs/AudioBiquadFilter.cpp
index 72917a3..16dd1c5 100644
--- a/media/libeffects/testlibs/AudioBiquadFilter.cpp
+++ b/media/libeffects/testlibs/AudioBiquadFilter.cpp
@@ -17,12 +17,10 @@
 
 #include <string.h>
 #include <assert.h>
+#include <cutils/compiler.h>
 
 #include "AudioBiquadFilter.h"
 
-#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
-#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
-
 namespace android {
 
 const audio_coef_t AudioBiquadFilter::IDENTITY_COEFS[AudioBiquadFilter::NUM_COEFS] = { AUDIO_COEF_ONE, 0, 0, 0, 0 };
@@ -55,7 +53,7 @@
 void AudioBiquadFilter::setCoefs(const audio_coef_t coefs[NUM_COEFS], bool immediate) {
     memcpy(mTargetCoefs, coefs, sizeof(mTargetCoefs));
     if (mState & STATE_ENABLED_MASK) {
-        if (UNLIKELY(immediate)) {
+        if (CC_UNLIKELY(immediate)) {
             memcpy(mCoefs, coefs, sizeof(mCoefs));
             setState(STATE_NORMAL);
         } else {
@@ -70,7 +68,7 @@
 }
 
 void AudioBiquadFilter::enable(bool immediate) {
-    if (UNLIKELY(immediate)) {
+    if (CC_UNLIKELY(immediate)) {
         memcpy(mCoefs, mTargetCoefs, sizeof(mCoefs));
         setState(STATE_NORMAL);
     } else {
@@ -79,7 +77,7 @@
 }
 
 void AudioBiquadFilter::disable(bool immediate) {
-    if (UNLIKELY(immediate)) {
+    if (CC_UNLIKELY(immediate)) {
         memcpy(mCoefs, IDENTITY_COEFS, sizeof(mCoefs));
         setState(STATE_BYPASS);
     } else {
@@ -142,7 +140,7 @@
                                        audio_sample_t * out,
                                        int frameCount) {
     // The common case is in-place processing, because this is what the EQ does.
-    if (UNLIKELY(in != out)) {
+    if (CC_UNLIKELY(in != out)) {
         memcpy(out, in, frameCount * mNumChannels * sizeof(audio_sample_t));
     }
 }
diff --git a/media/libeffects/testlibs/AudioCoefInterpolator.cpp b/media/libeffects/testlibs/AudioCoefInterpolator.cpp
index 039ab9f..6b56922 100644
--- a/media/libeffects/testlibs/AudioCoefInterpolator.cpp
+++ b/media/libeffects/testlibs/AudioCoefInterpolator.cpp
@@ -16,10 +16,10 @@
  */
 
 #include <string.h>
-#include "AudioCoefInterpolator.h"
 
-#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
-#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
+#include <cutils/compiler.h>
+
+#include "AudioCoefInterpolator.h"
 
 namespace android {
 
@@ -44,9 +44,9 @@
     size_t index = 0;
     size_t dim = mNumInDims;
     while (dim-- > 0) {
-        if (UNLIKELY(intCoord[dim] < 0)) {
+        if (CC_UNLIKELY(intCoord[dim] < 0)) {
             fracCoord[dim] = 0;
-        } else if (UNLIKELY(intCoord[dim] >= (int)mInDims[dim] - 1)) {
+        } else if (CC_UNLIKELY(intCoord[dim] >= (int)mInDims[dim] - 1)) {
             fracCoord[dim] = 0;
             index += mInDimOffsets[dim] * (mInDims[dim] - 1);
         } else {
@@ -63,7 +63,7 @@
         memcpy(out, mTable + index, mNumOutDims * sizeof(audio_coef_t));
     } else {
         getCoefRecurse(index, fracCoord, out, dim + 1);
-        if (LIKELY(fracCoord != 0)) {
+        if (CC_LIKELY(fracCoord != 0)) {
            audio_coef_t tempCoef[MAX_OUT_DIMS];
            getCoefRecurse(index + mInDimOffsets[dim], fracCoord, tempCoef,
                            dim + 1);
diff --git a/media/libeffects/testlibs/AudioCommon.h b/media/libeffects/testlibs/AudioCommon.h
index 444f93a..e8080dc 100644
--- a/media/libeffects/testlibs/AudioCommon.h
+++ b/media/libeffects/testlibs/AudioCommon.h
@@ -20,6 +20,7 @@
 
 #include <stdint.h>
 #include <stddef.h>
+#include <cutils/compiler.h>
 
 namespace android {
 
@@ -76,9 +77,9 @@
 // Convert a audio_sample_t sample to S15 (with clipping)
 inline int16_t audio_sample_t_to_s15_clip(audio_sample_t sample) {
     // TODO: optimize for targets supporting this as an atomic operation.
-    if (__builtin_expect(sample >= (0x7FFF << 9), 0)) {
+    if (CC_UNLIKELY(sample >= (0x7FFF << 9))) {
         return 0x7FFF;
-    } else if (__builtin_expect(sample <= -(0x8000 << 9), 0)) {
+    } else if (CC_UNLIKELY(sample <= -(0x8000 << 9))) {
         return 0x8000;
     } else {
         return audio_sample_t_to_s15(sample);
diff --git a/media/libeffects/testlibs/AudioPeakingFilter.cpp b/media/libeffects/testlibs/AudioPeakingFilter.cpp
index 60fefe6..99323ac 100644
--- a/media/libeffects/testlibs/AudioPeakingFilter.cpp
+++ b/media/libeffects/testlibs/AudioPeakingFilter.cpp
@@ -21,9 +21,7 @@
 
 #include <new>
 #include <assert.h>
-
-#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
-#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
+#include <cutils/compiler.h>
 
 namespace android {
 // Format of the coefficient table:
@@ -66,12 +64,12 @@
 
 void AudioPeakingFilter::setFrequency(uint32_t millihertz) {
     mNominalFrequency = millihertz;
-    if (UNLIKELY(millihertz > mNiquistFreq / 2)) {
+    if (CC_UNLIKELY(millihertz > mNiquistFreq / 2)) {
         millihertz = mNiquistFreq / 2;
     }
     uint32_t normFreq = static_cast<uint32_t>(
             (static_cast<uint64_t>(millihertz) * mFrequencyFactor) >> 10);
-    if (LIKELY(normFreq > (1 << 23))) {
+    if (CC_LIKELY(normFreq > (1 << 23))) {
         mFrequency = (Effects_log2(normFreq) - ((32-9) << 15)) << (FREQ_PRECISION_BITS - 15);
     } else {
         mFrequency = 0;
@@ -107,11 +105,11 @@
     int32_t halfBW = (((mBandwidth + 1) / 2) << 15) / 1200;
 
     low = static_cast<uint32_t>((static_cast<uint64_t>(mNominalFrequency) * Effects_exp2(-halfBW + (16 << 15))) >> 16);
-    if (UNLIKELY(halfBW >= (16 << 15))) {
+    if (CC_UNLIKELY(halfBW >= (16 << 15))) {
         high = mNiquistFreq;
     } else {
         high = static_cast<uint32_t>((static_cast<uint64_t>(mNominalFrequency) * Effects_exp2(halfBW + (16 << 15))) >> 16);
-        if (UNLIKELY(high > mNiquistFreq)) {
+        if (CC_UNLIKELY(high > mNiquistFreq)) {
             high = mNiquistFreq;
         }
     }
diff --git a/media/libeffects/testlibs/AudioShelvingFilter.cpp b/media/libeffects/testlibs/AudioShelvingFilter.cpp
index b8650ba..e031287 100644
--- a/media/libeffects/testlibs/AudioShelvingFilter.cpp
+++ b/media/libeffects/testlibs/AudioShelvingFilter.cpp
@@ -21,9 +21,7 @@
 
 #include <new>
 #include <assert.h>
-
-#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
-#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
+#include <cutils/compiler.h>
 
 namespace android {
 // Format of the coefficient tables:
@@ -71,13 +69,13 @@
 
 void AudioShelvingFilter::setFrequency(uint32_t millihertz) {
     mNominalFrequency = millihertz;
-    if (UNLIKELY(millihertz > mNiquistFreq / 2)) {
+    if (CC_UNLIKELY(millihertz > mNiquistFreq / 2)) {
         millihertz = mNiquistFreq / 2;
     }
     uint32_t normFreq = static_cast<uint32_t>(
             (static_cast<uint64_t>(millihertz) * mFrequencyFactor) >> 10);
     uint32_t log2minFreq = (mType == kLowShelf ? (32-10) : (32-2));
-    if (LIKELY(normFreq > (1U << log2minFreq))) {
+    if (CC_LIKELY(normFreq > (1U << log2minFreq))) {
         mFrequency = (Effects_log2(normFreq) - (log2minFreq << 15)) << (FREQ_PRECISION_BITS - 15);
     } else {
         mFrequency = 0;
diff --git a/media/libeffects/testlibs/EffectEqualizer.cpp b/media/libeffects/testlibs/EffectEqualizer.cpp
index 43f34de..5241660 100644
--- a/media/libeffects/testlibs/EffectEqualizer.cpp
+++ b/media/libeffects/testlibs/EffectEqualizer.cpp
@@ -114,7 +114,7 @@
 //--- local function prototypes
 
 int Equalizer_init(EqualizerContext *pContext);
-int Equalizer_configure(EqualizerContext *pContext, effect_config_t *pConfig);
+int Equalizer_setConfig(EqualizerContext *pContext, effect_config_t *pConfig);
 int Equalizer_getParameter(AudioEqualizer * pEqualizer, int32_t *pParam, size_t *pValueSize, void *pValue);
 int Equalizer_setParameter(AudioEqualizer * pEqualizer, int32_t *pParam, void *pValue);
 
@@ -224,7 +224,7 @@
 }
 
 //----------------------------------------------------------------------------
-// Equalizer_configure()
+// Equalizer_setConfig()
 //----------------------------------------------------------------------------
 // Purpose: Set input and output audio configuration.
 //
@@ -237,9 +237,9 @@
 //
 //----------------------------------------------------------------------------
 
-int Equalizer_configure(EqualizerContext *pContext, effect_config_t *pConfig)
+int Equalizer_setConfig(EqualizerContext *pContext, effect_config_t *pConfig)
 {
-    ALOGV("Equalizer_configure start");
+    ALOGV("Equalizer_setConfig start");
 
     CHECK_ARG(pContext != NULL);
     CHECK_ARG(pConfig != NULL);
@@ -272,7 +272,26 @@
                         pConfig->outputCfg.accessMode);
 
     return 0;
-}   // end Equalizer_configure
+}   // end Equalizer_setConfig
+
+//----------------------------------------------------------------------------
+// Equalizer_getConfig()
+//----------------------------------------------------------------------------
+// Purpose: Get input and output audio configuration.
+//
+// Inputs:
+//  pContext:   effect engine context
+//  pConfig:    pointer to effect_config_t structure holding input and output
+//      configuration parameters
+//
+// Outputs:
+//
+//----------------------------------------------------------------------------
+
+void Equalizer_getConfig(EqualizerContext *pContext, effect_config_t *pConfig)
+{
+    memcpy(pConfig, &pContext->config, sizeof(effect_config_t));
+}   // end Equalizer_getConfig
 
 
 //----------------------------------------------------------------------------
@@ -332,7 +351,7 @@
 
     pContext->pEqualizer->enable(true);
 
-    Equalizer_configure(pContext, &pContext->config);
+    Equalizer_setConfig(pContext, &pContext->config);
 
     return 0;
 }   // end Equalizer_init
@@ -643,16 +662,22 @@
         }
         *(int *) pReplyData = Equalizer_init(pContext);
         break;
-    case EFFECT_CMD_CONFIGURE:
+    case EFFECT_CMD_SET_CONFIG:
         if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
                 || pReplyData == NULL || *replySize != sizeof(int)) {
             return -EINVAL;
         }
-        *(int *) pReplyData = Equalizer_configure(pContext,
+        *(int *) pReplyData = Equalizer_setConfig(pContext,
                 (effect_config_t *) pCmdData);
         break;
+    case EFFECT_CMD_GET_CONFIG:
+        if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) {
+            return -EINVAL;
+        }
+        Equalizer_getConfig(pContext, (effect_config_t *) pCmdData);
+        break;
     case EFFECT_CMD_RESET:
-        Equalizer_configure(pContext, &pContext->config);
+        Equalizer_setConfig(pContext, &pContext->config);
         break;
     case EFFECT_CMD_GET_PARAM: {
         if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)) ||
diff --git a/media/libeffects/testlibs/EffectReverb.c b/media/libeffects/testlibs/EffectReverb.c
index d22868a..ebb72c1 100644
--- a/media/libeffects/testlibs/EffectReverb.c
+++ b/media/libeffects/testlibs/EffectReverb.c
@@ -318,14 +318,20 @@
             pRvbModule->context.mState = REVERB_STATE_INITIALIZED;
         }
         break;
-    case EFFECT_CMD_CONFIGURE:
+    case EFFECT_CMD_SET_CONFIG:
         if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
                 || pReplyData == NULL || *replySize != sizeof(int)) {
             return -EINVAL;
         }
-        *(int *) pReplyData = Reverb_Configure(pRvbModule,
+        *(int *) pReplyData = Reverb_setConfig(pRvbModule,
                 (effect_config_t *)pCmdData, false);
         break;
+    case EFFECT_CMD_GET_CONFIG:
+        if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) {
+            return -EINVAL;
+        }
+        Reverb_getConfig(pRvbModule, (effect_config_t *) pCmdData);
+        break;
     case EFFECT_CMD_RESET:
         Reverb_Reset(pReverb, false);
         break;
@@ -492,7 +498,7 @@
     pRvbModule->config.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
     pRvbModule->config.outputCfg.mask = EFFECT_CONFIG_ALL;
 
-    ret = Reverb_Configure(pRvbModule, &pRvbModule->config, true);
+    ret = Reverb_setConfig(pRvbModule, &pRvbModule->config, true);
     if (ret < 0) {
         ALOGV("Reverb_Init error %d on module %p", ret, pRvbModule);
     }
@@ -501,7 +507,7 @@
 }
 
 /*----------------------------------------------------------------------------
- * Reverb_Init()
+ * Reverb_setConfig()
  *----------------------------------------------------------------------------
  * Purpose:
  *  Set input and output audio configuration.
@@ -518,7 +524,7 @@
  *----------------------------------------------------------------------------
  */
 
-int Reverb_Configure(reverb_module_t *pRvbModule, effect_config_t *pConfig,
+int Reverb_setConfig(reverb_module_t *pRvbModule, effect_config_t *pConfig,
         bool init) {
     reverb_object_t *pReverb = &pRvbModule->context;
     int bufferSizeInSamples;
@@ -531,12 +537,12 @@
         || pConfig->outputCfg.channels != OUTPUT_CHANNELS
         || pConfig->inputCfg.format != AUDIO_FORMAT_PCM_16_BIT
         || pConfig->outputCfg.format != AUDIO_FORMAT_PCM_16_BIT) {
-        ALOGV("Reverb_Configure invalid config");
+        ALOGV("Reverb_setConfig invalid config");
         return -EINVAL;
     }
     if ((pReverb->m_Aux && (pConfig->inputCfg.channels != AUDIO_CHANNEL_OUT_MONO)) ||
         (!pReverb->m_Aux && (pConfig->inputCfg.channels != AUDIO_CHANNEL_OUT_STEREO))) {
-        ALOGV("Reverb_Configure invalid config");
+        ALOGV("Reverb_setConfig invalid config");
         return -EINVAL;
     }
 
@@ -576,7 +582,7 @@
         pReverb->m_nCosWT_5KHz = 25997;
         break;
     default:
-        ALOGV("Reverb_Configure invalid sampling rate %d", pReverb->m_nSamplingRate);
+        ALOGV("Reverb_setConfig invalid sampling rate %d", pReverb->m_nSamplingRate);
         return -EINVAL;
     }
 
@@ -620,6 +626,28 @@
 }
 
 /*----------------------------------------------------------------------------
+ * Reverb_getConfig()
+ *----------------------------------------------------------------------------
+ * Purpose:
+ *  Get input and output audio configuration.
+ *
+ * Inputs:
+ *  pRvbModule    - pointer to reverb effect module
+ *  pConfig       - pointer to effect_config_t structure containing input
+ *              and output audio parameters configuration
+ * Outputs:
+ *
+ * Side Effects:
+ *
+ *----------------------------------------------------------------------------
+ */
+
+void Reverb_getConfig(reverb_module_t *pRvbModule, effect_config_t *pConfig)
+{
+    memcpy(pConfig, &pRvbModule->config, sizeof(effect_config_t));
+}
+
+/*----------------------------------------------------------------------------
  * Reverb_Reset()
  *----------------------------------------------------------------------------
  * Purpose:
@@ -844,7 +872,7 @@
             if (param == REVERB_PARAM_ROOM_HF_LEVEL) {
                 break;
             }
-            pValue32 = &pProperties->decayTime;
+            pValue32 = (int32_t *)&pProperties->decayTime;
             /* FALL THROUGH */
 
         case REVERB_PARAM_DECAY_TIME:
@@ -916,7 +944,7 @@
             if (param == REVERB_PARAM_REFLECTIONS_LEVEL) {
                 break;
             }
-            pValue32 = &pProperties->reflectionsDelay;
+            pValue32 = (int32_t *)&pProperties->reflectionsDelay;
             /* FALL THROUGH */
 
         case REVERB_PARAM_REFLECTIONS_DELAY:
@@ -940,7 +968,7 @@
             if (param == REVERB_PARAM_REVERB_LEVEL) {
                 break;
             }
-            pValue32 = &pProperties->reverbDelay;
+            pValue32 = (int32_t *)&pProperties->reverbDelay;
             /* FALL THROUGH */
 
         case REVERB_PARAM_REVERB_DELAY:
diff --git a/media/libeffects/testlibs/EffectReverb.h b/media/libeffects/testlibs/EffectReverb.h
index 8e2cc31..5137074 100644
--- a/media/libeffects/testlibs/EffectReverb.h
+++ b/media/libeffects/testlibs/EffectReverb.h
@@ -329,7 +329,8 @@
 */
 
 int Reverb_Init(reverb_module_t *pRvbModule, int aux, int preset);
-int Reverb_Configure(reverb_module_t *pRvbModule, effect_config_t *pConfig, bool init);
+int Reverb_setConfig(reverb_module_t *pRvbModule, effect_config_t *pConfig, bool init);
+void Reverb_getConfig(reverb_module_t *pRvbModule, effect_config_t *pConfig);
 void Reverb_Reset(reverb_object_t *pReverb, bool init);
 
 int Reverb_setParameter (reverb_object_t *pReverb, int32_t param, size_t size, void *pValue);
diff --git a/media/libeffects/visualizer/EffectVisualizer.cpp b/media/libeffects/visualizer/EffectVisualizer.cpp
index c441710..5d70a9b 100644
--- a/media/libeffects/visualizer/EffectVisualizer.cpp
+++ b/media/libeffects/visualizer/EffectVisualizer.cpp
@@ -78,7 +78,7 @@
 }
 
 //----------------------------------------------------------------------------
-// Visualizer_configure()
+// Visualizer_setConfig()
 //----------------------------------------------------------------------------
 // Purpose: Set input and output audio configuration.
 //
@@ -91,9 +91,9 @@
 //
 //----------------------------------------------------------------------------
 
-int Visualizer_configure(VisualizerContext *pContext, effect_config_t *pConfig)
+int Visualizer_setConfig(VisualizerContext *pContext, effect_config_t *pConfig)
 {
-    ALOGV("Visualizer_configure start");
+    ALOGV("Visualizer_setConfig start");
 
     if (pConfig->inputCfg.samplingRate != pConfig->outputCfg.samplingRate) return -EINVAL;
     if (pConfig->inputCfg.channels != pConfig->outputCfg.channels) return -EINVAL;
@@ -112,6 +112,26 @@
 
 
 //----------------------------------------------------------------------------
+// Visualizer_getConfig()
+//----------------------------------------------------------------------------
+// Purpose: Get input and output audio configuration.
+//
+// Inputs:
+//  pContext:   effect engine context
+//  pConfig:    pointer to effect_config_t structure holding input and output
+//      configuration parameters
+//
+// Outputs:
+//
+//----------------------------------------------------------------------------
+
+void Visualizer_getConfig(VisualizerContext *pContext, effect_config_t *pConfig)
+{
+    memcpy(pConfig, &pContext->mConfig, sizeof(effect_config_t));
+}
+
+
+//----------------------------------------------------------------------------
 // Visualizer_init()
 //----------------------------------------------------------------------------
 // Purpose: Initialize engine with default configuration.
@@ -144,7 +164,7 @@
 
     pContext->mCaptureSize = VISUALIZER_CAPTURE_SIZE_MAX;
 
-    Visualizer_configure(pContext, &pContext->mConfig);
+    Visualizer_setConfig(pContext, &pContext->mConfig);
 
     return 0;
 }
@@ -337,14 +357,21 @@
         }
         *(int *) pReplyData = Visualizer_init(pContext);
         break;
-    case EFFECT_CMD_CONFIGURE:
+    case EFFECT_CMD_SET_CONFIG:
         if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
                 || pReplyData == NULL || *replySize != sizeof(int)) {
             return -EINVAL;
         }
-        *(int *) pReplyData = Visualizer_configure(pContext,
+        *(int *) pReplyData = Visualizer_setConfig(pContext,
                 (effect_config_t *) pCmdData);
         break;
+    case EFFECT_CMD_GET_CONFIG:
+        if (pReplyData == NULL ||
+            *replySize != sizeof(effect_config_t)) {
+            return -EINVAL;
+        }
+        Visualizer_getConfig(pContext, (effect_config_t *)pReplyData);
+        break;
     case EFFECT_CMD_RESET:
         Visualizer_reset(pContext);
         break;
diff --git a/media/libmedia/Android.mk b/media/libmedia/Android.mk
index 7af4a87..23670df 100644
--- a/media/libmedia/Android.mk
+++ b/media/libmedia/Android.mk
@@ -43,13 +43,12 @@
     IEffectClient.cpp \
     AudioEffect.cpp \
     Visualizer.cpp \
-    MemoryLeakTrackUtil.cpp \
-    fixedfft.cpp.arm
+    MemoryLeakTrackUtil.cpp
 
 LOCAL_SHARED_LIBRARIES := \
 	libui libcutils libutils libbinder libsonivox libicuuc libexpat \
         libcamera_client libstagefright_foundation \
-        libgui libdl
+        libgui libdl libaudioutils
 
 LOCAL_WHOLE_STATIC_LIBRARY := libmedia_helper
 
@@ -61,6 +60,7 @@
     $(TOP)/frameworks/base/include/media/stagefright/openmax \
     external/icu4c/common \
     external/expat/lib \
-    system/media/audio_effects/include
+    system/media/audio_effects/include \
+    system/media/audio_utils/include
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libmedia/AudioRecord.cpp b/media/libmedia/AudioRecord.cpp
index 34a5eb7..5b5b076 100644
--- a/media/libmedia/AudioRecord.cpp
+++ b/media/libmedia/AudioRecord.cpp
@@ -39,9 +39,7 @@
 
 #include <system/audio.h>
 #include <cutils/bitops.h>
-
-#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
-#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
+#include <cutils/compiler.h>
 
 namespace android {
 // ---------------------------------------------------------------------------
@@ -50,7 +48,7 @@
 status_t AudioRecord::getMinFrameCount(
         int* frameCount,
         uint32_t sampleRate,
-        int format,
+        audio_format_t format,
         int channelCount)
 {
     size_t size = 0;
@@ -80,14 +78,15 @@
 // ---------------------------------------------------------------------------
 
 AudioRecord::AudioRecord()
-    : mStatus(NO_INIT), mSessionId(0)
+    : mStatus(NO_INIT), mSessionId(0),
+      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
 {
 }
 
 AudioRecord::AudioRecord(
         int inputSource,
         uint32_t sampleRate,
-        int format,
+        audio_format_t format,
         uint32_t channelMask,
         int frameCount,
         uint32_t flags,
@@ -95,7 +94,8 @@
         void* user,
         int notificationFrames,
         int sessionId)
-    : mStatus(NO_INIT), mSessionId(0)
+    : mStatus(NO_INIT), mSessionId(0),
+      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
 {
     mStatus = set(inputSource, sampleRate, format, channelMask,
             frameCount, flags, cbf, user, notificationFrames, sessionId);
@@ -121,7 +121,7 @@
 status_t AudioRecord::set(
         int inputSource,
         uint32_t sampleRate,
-        int format,
+        audio_format_t format,
         uint32_t channelMask,
         int frameCount,
         uint32_t flags,
@@ -148,7 +148,7 @@
         sampleRate = DEFAULT_SAMPLE_RATE;
     }
     // these below should probably come from the audioFlinger too...
-    if (format == 0) {
+    if (format == AUDIO_FORMAT_DEFAULT) {
         format = AUDIO_FORMAT_PCM_16_BIT;
     }
     // validate parameters
@@ -208,9 +208,6 @@
 
     if (cbf != 0) {
         mClientRecordThread = new ClientRecordThread(*this, threadCanCallJava);
-        if (mClientRecordThread == 0) {
-            return NO_INIT;
-        }
     }
 
     mStatus = NO_ERROR;
@@ -251,7 +248,7 @@
     return mLatency;
 }
 
-int AudioRecord::format() const
+audio_format_t AudioRecord::format() const
 {
     return mFormat;
 }
@@ -266,7 +263,7 @@
     return mFrameCount;
 }
 
-int AudioRecord::frameSize() const
+size_t AudioRecord::frameSize() const
 {
     if (audio_is_linear_pcm(mFormat)) {
         return channelCount()*audio_bytes_per_sample(mFormat);
@@ -326,9 +323,11 @@
             cblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
             cblk->waitTimeMs = 0;
             if (t != 0) {
-               t->run("ClientRecordThread", ANDROID_PRIORITY_AUDIO);
+                t->run("ClientRecordThread", ANDROID_PRIORITY_AUDIO);
             } else {
-                setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
+                mPreviousPriority = getpriority(PRIO_PROCESS, 0);
+                mPreviousSchedulingGroup = androidGetThreadSchedulingGroup(0);
+                androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
             }
         } else {
             mActive = 0;
@@ -363,7 +362,8 @@
         if (t != 0) {
             t->requestExit();
         } else {
-            setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
+            setpriority(PRIO_PROCESS, 0, mPreviousPriority);
+            androidSetThreadSchedulingGroup(0, mPreviousSchedulingGroup);
         }
     }
 
@@ -448,7 +448,7 @@
 // must be called with mLock held
 status_t AudioRecord::openRecord_l(
         uint32_t sampleRate,
-        uint32_t format,
+        audio_format_t format,
         uint32_t channelMask,
         int frameCount,
         uint32_t flags,
@@ -508,11 +508,11 @@
         goto start_loop_here;
         while (framesReady == 0) {
             active = mActive;
-            if (UNLIKELY(!active)) {
+            if (CC_UNLIKELY(!active)) {
                 cblk->lock.unlock();
                 return NO_MORE_BUFFERS;
             }
-            if (UNLIKELY(!waitCount)) {
+            if (CC_UNLIKELY(!waitCount)) {
                 cblk->lock.unlock();
                 return WOULD_BLOCK;
             }
@@ -529,7 +529,7 @@
             if (cblk->flags & CBLK_INVALID_MSK) {
                 goto create_new_record;
             }
-            if (__builtin_expect(result!=NO_ERROR, false)) {
+            if (CC_UNLIKELY(result != NO_ERROR)) {
                 cblk->waitTimeMs += waitTimeMs;
                 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
                     ALOGW(   "obtainBuffer timed out (is the CPU pegged?) "
diff --git a/media/libmedia/AudioSystem.cpp b/media/libmedia/AudioSystem.cpp
index f7f129c..952d634 100644
--- a/media/libmedia/AudioSystem.cpp
+++ b/media/libmedia/AudioSystem.cpp
@@ -38,9 +38,9 @@
 DefaultKeyedVector<int, audio_io_handle_t> AudioSystem::gStreamOutputMap(0);
 DefaultKeyedVector<audio_io_handle_t, AudioSystem::OutputDescriptor *> AudioSystem::gOutputs(0);
 
-// Cached values for recording queries
+// Cached values for recording queries, all protected by gLock
 uint32_t AudioSystem::gPrevInSamplingRate = 16000;
-int AudioSystem::gPrevInFormat = AUDIO_FORMAT_PCM_16_BIT;
+audio_format_t AudioSystem::gPrevInFormat = AUDIO_FORMAT_PCM_16_BIT;
 int AudioSystem::gPrevInChannelCount = 1;
 size_t AudioSystem::gInBuffSize = 0;
 
@@ -49,7 +49,7 @@
 const sp<IAudioFlinger>& AudioSystem::get_audio_flinger()
 {
     Mutex::Autolock _l(gLock);
-    if (gAudioFlinger.get() == 0) {
+    if (gAudioFlinger == 0) {
         sp<IServiceManager> sm = defaultServiceManager();
         sp<IBinder> binder;
         do {
@@ -120,7 +120,7 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::setStreamVolume(int stream, float value, int output)
+status_t AudioSystem::setStreamVolume(audio_stream_type_t stream, float value, int output)
 {
     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
@@ -129,7 +129,7 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::setStreamMute(int stream, bool mute)
+status_t AudioSystem::setStreamMute(audio_stream_type_t stream, bool mute)
 {
     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
@@ -138,7 +138,7 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::getStreamVolume(int stream, float* volume, int output)
+status_t AudioSystem::getStreamVolume(audio_stream_type_t stream, float* volume, int output)
 {
     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
@@ -147,7 +147,7 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::getStreamMute(int stream, bool* mute)
+status_t AudioSystem::getStreamMute(audio_stream_type_t stream, bool* mute)
 {
     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
@@ -156,9 +156,9 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::setMode(int mode)
+status_t AudioSystem::setMode(audio_mode_t mode)
 {
-    if (mode >= AUDIO_MODE_CNT) return BAD_VALUE;
+    if (uint32_t(mode) >= AUDIO_MODE_CNT) return BAD_VALUE;
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     if (af == 0) return PERMISSION_DENIED;
     return af->setMode(mode);
@@ -203,7 +203,12 @@
     return volume ? 100 - int(dBConvertInverse * log(volume) + 0.5) : 0;
 }
 
-status_t AudioSystem::getOutputSamplingRate(int* samplingRate, int streamType)
+// DEPRECATED
+status_t AudioSystem::getOutputSamplingRate(int* samplingRate, int streamType) {
+    return getOutputSamplingRate(samplingRate, (audio_stream_type_t)streamType);
+}
+
+status_t AudioSystem::getOutputSamplingRate(int* samplingRate, audio_stream_type_t streamType)
 {
     OutputDescriptor *outputDesc;
     audio_io_handle_t output;
@@ -212,7 +217,7 @@
         streamType = AUDIO_STREAM_MUSIC;
     }
 
-    output = getOutput((audio_stream_type_t)streamType);
+    output = getOutput(streamType);
     if (output == 0) {
         return PERMISSION_DENIED;
     }
@@ -236,7 +241,12 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::getOutputFrameCount(int* frameCount, int streamType)
+// DEPRECATED
+status_t AudioSystem::getOutputFrameCount(int* frameCount, int streamType) {
+    return getOutputFrameCount(frameCount, (audio_stream_type_t)streamType);
+}
+
+status_t AudioSystem::getOutputFrameCount(int* frameCount, audio_stream_type_t streamType)
 {
     OutputDescriptor *outputDesc;
     audio_io_handle_t output;
@@ -245,7 +255,7 @@
         streamType = AUDIO_STREAM_MUSIC;
     }
 
-    output = getOutput((audio_stream_type_t)streamType);
+    output = getOutput(streamType);
     if (output == 0) {
         return PERMISSION_DENIED;
     }
@@ -267,7 +277,7 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::getOutputLatency(uint32_t* latency, int streamType)
+status_t AudioSystem::getOutputLatency(uint32_t* latency, audio_stream_type_t streamType)
 {
     OutputDescriptor *outputDesc;
     audio_io_handle_t output;
@@ -276,7 +286,7 @@
         streamType = AUDIO_STREAM_MUSIC;
     }
 
-    output = getOutput((audio_stream_type_t)streamType);
+    output = getOutput(streamType);
     if (output == 0) {
         return PERMISSION_DENIED;
     }
@@ -298,25 +308,30 @@
     return NO_ERROR;
 }
 
-status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
+status_t AudioSystem::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount,
     size_t* buffSize)
 {
+    gLock.lock();
     // Do we have a stale gInBufferSize or are we requesting the input buffer size for new values
-    if ((gInBuffSize == 0) || (sampleRate != gPrevInSamplingRate) || (format != gPrevInFormat)
+    size_t inBuffSize = gInBuffSize;
+    if ((inBuffSize == 0) || (sampleRate != gPrevInSamplingRate) || (format != gPrevInFormat)
         || (channelCount != gPrevInChannelCount)) {
+        gLock.unlock();
+        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
+        if (af == 0) {
+            return PERMISSION_DENIED;
+        }
+        inBuffSize = af->getInputBufferSize(sampleRate, format, channelCount);
+        gLock.lock();
         // save the request params
         gPrevInSamplingRate = sampleRate;
         gPrevInFormat = format;
         gPrevInChannelCount = channelCount;
 
-        gInBuffSize = 0;
-        const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
-        if (af == 0) {
-            return PERMISSION_DENIED;
-        }
-        gInBuffSize = af->getInputBufferSize(sampleRate, format, channelCount);
+        gInBuffSize = inBuffSize;
     }
-    *buffSize = gInBuffSize;
+    gLock.unlock();
+    *buffSize = inBuffSize;
 
     return NO_ERROR;
 }
@@ -328,7 +343,7 @@
     return af->setVoiceVolume(value);
 }
 
-status_t AudioSystem::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int stream)
+status_t AudioSystem::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, audio_stream_type_t stream)
 {
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     if (af == 0) return PERMISSION_DENIED;
@@ -337,7 +352,7 @@
         stream = AUDIO_STREAM_MUSIC;
     }
 
-    return af->getRenderPosition(halFrames, dspFrames, getOutput((audio_stream_type_t)stream));
+    return af->getRenderPosition(halFrames, dspFrames, getOutput(stream));
 }
 
 unsigned int AudioSystem::getInputFramesLost(audio_io_handle_t ioHandle) {
@@ -462,7 +477,7 @@
     gAudioErrorCallback = cb;
 }
 
-bool AudioSystem::routedToA2dpOutput(int streamType) {
+bool AudioSystem::routedToA2dpOutput(audio_stream_type_t streamType) {
     switch(streamType) {
     case AUDIO_STREAM_MUSIC:
     case AUDIO_STREAM_VOICE_CALL:
@@ -484,7 +499,7 @@
 const sp<IAudioPolicyService>& AudioSystem::get_audio_policy_service()
 {
     gLock.lock();
-    if (gAudioPolicyService.get() == 0) {
+    if (gAudioPolicyService == 0) {
         sp<IServiceManager> sm = defaultServiceManager();
         sp<IBinder> binder;
         do {
@@ -531,21 +546,15 @@
     return aps->getDeviceConnectionState(device, device_address);
 }
 
-status_t AudioSystem::setPhoneState(int state)
+status_t AudioSystem::setPhoneState(audio_mode_t state)
 {
+    if (uint32_t(state) >= AUDIO_MODE_CNT) return BAD_VALUE;
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
     if (aps == 0) return PERMISSION_DENIED;
 
     return aps->setPhoneState(state);
 }
 
-status_t AudioSystem::setRingerMode(uint32_t mode, uint32_t mask)
-{
-    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
-    if (aps == 0) return PERMISSION_DENIED;
-    return aps->setRingerMode(mode, mask);
-}
-
 status_t AudioSystem::setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config)
 {
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
@@ -563,7 +572,7 @@
 
 audio_io_handle_t AudioSystem::getOutput(audio_stream_type_t stream,
                                     uint32_t samplingRate,
-                                    uint32_t format,
+                                    audio_format_t format,
                                     uint32_t channels,
                                     audio_policy_output_flags_t flags)
 {
@@ -623,7 +632,7 @@
 
 audio_io_handle_t AudioSystem::getInput(int inputSource,
                                     uint32_t samplingRate,
-                                    uint32_t format,
+                                    audio_format_t format,
                                     uint32_t channels,
                                     audio_in_acoustics_t acoustics,
                                     int sessionId)
@@ -663,18 +672,22 @@
     return aps->initStreamVolume(stream, indexMin, indexMax);
 }
 
-status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream, int index)
+status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,
+                                           int index,
+                                           audio_devices_t device)
 {
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
     if (aps == 0) return PERMISSION_DENIED;
-    return aps->setStreamVolumeIndex(stream, index);
+    return aps->setStreamVolumeIndex(stream, index, device);
 }
 
-status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream, int *index)
+status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream,
+                                           int *index,
+                                           audio_devices_t device)
 {
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
     if (aps == 0) return PERMISSION_DENIED;
-    return aps->getStreamVolumeIndex(stream, index);
+    return aps->getStreamVolumeIndex(stream, index, device);
 }
 
 uint32_t AudioSystem::getStrategyForStream(audio_stream_type_t stream)
@@ -723,7 +736,7 @@
     return aps->setEffectEnabled(id, enabled);
 }
 
-status_t AudioSystem::isStreamActive(int stream, bool* state, uint32_t inPastMs)
+status_t AudioSystem::isStreamActive(audio_stream_type_t stream, bool* state, uint32_t inPastMs)
 {
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
     if (aps == 0) return PERMISSION_DENIED;
diff --git a/media/libmedia/AudioTrack.cpp b/media/libmedia/AudioTrack.cpp
index d51cd69..17e3d4b 100644
--- a/media/libmedia/AudioTrack.cpp
+++ b/media/libmedia/AudioTrack.cpp
@@ -1,4 +1,4 @@
-/* //device/extlibs/pv/android/AudioTrack.cpp
+/* frameworks/base/media/libmedia/AudioTrack.cpp
 **
 ** Copyright 2007, The Android Open Source Project
 **
@@ -38,12 +38,12 @@
 #include <utils/Atomic.h>
 
 #include <cutils/bitops.h>
+#include <cutils/compiler.h>
 
 #include <system/audio.h>
 #include <system/audio_policy.h>
 
-#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
-#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
+#include <audio_utils/primitives.h>
 
 namespace android {
 // ---------------------------------------------------------------------------
@@ -51,7 +51,7 @@
 // static
 status_t AudioTrack::getMinFrameCount(
         int* frameCount,
-        int streamType,
+        audio_stream_type_t streamType,
         uint32_t sampleRate)
 {
     int afSampleRate;
@@ -79,11 +79,31 @@
 // ---------------------------------------------------------------------------
 
 AudioTrack::AudioTrack()
-    : mStatus(NO_INIT)
+    : mStatus(NO_INIT),
+      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
 {
 }
 
 AudioTrack::AudioTrack(
+        audio_stream_type_t streamType,
+        uint32_t sampleRate,
+        audio_format_t format,
+        int channelMask,
+        int frameCount,
+        uint32_t flags,
+        callback_t cbf,
+        void* user,
+        int notificationFrames,
+        int sessionId)
+    : mStatus(NO_INIT),
+      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
+{
+    mStatus = set(streamType, sampleRate, format, channelMask,
+            frameCount, flags, cbf, user, notificationFrames,
+            0, false, sessionId);
+}
+
+AudioTrack::AudioTrack(
         int streamType,
         uint32_t sampleRate,
         int format,
@@ -94,17 +114,18 @@
         void* user,
         int notificationFrames,
         int sessionId)
-    : mStatus(NO_INIT)
+    : mStatus(NO_INIT),
+      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
 {
-    mStatus = set(streamType, sampleRate, format, channelMask,
+    mStatus = set((audio_stream_type_t)streamType, sampleRate, (audio_format_t)format, channelMask,
             frameCount, flags, cbf, user, notificationFrames,
             0, false, sessionId);
 }
 
 AudioTrack::AudioTrack(
-        int streamType,
+        audio_stream_type_t streamType,
         uint32_t sampleRate,
-        int format,
+        audio_format_t format,
         int channelMask,
         const sp<IMemory>& sharedBuffer,
         uint32_t flags,
@@ -112,7 +133,8 @@
         void* user,
         int notificationFrames,
         int sessionId)
-    : mStatus(NO_INIT)
+    : mStatus(NO_INIT),
+      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(ANDROID_TGROUP_DEFAULT)
 {
     mStatus = set(streamType, sampleRate, format, channelMask,
             0, flags, cbf, user, notificationFrames,
@@ -139,9 +161,9 @@
 }
 
 status_t AudioTrack::set(
-        int streamType,
+        audio_stream_type_t streamType,
         uint32_t sampleRate,
-        int format,
+        audio_format_t format,
         int channelMask,
         int frameCount,
         uint32_t flags,
@@ -178,7 +200,7 @@
         sampleRate = afSampleRate;
     }
     // these below should probably come from the audioFlinger too...
-    if (format == 0) {
+    if (format == AUDIO_FORMAT_DEFAULT) {
         format = AUDIO_FORMAT_PCM_16_BIT;
     }
     if (channelMask == 0) {
@@ -203,8 +225,8 @@
     uint32_t channelCount = popcount(channelMask);
 
     audio_io_handle_t output = AudioSystem::getOutput(
-                                    (audio_stream_type_t)streamType,
-                                    sampleRate,format, channelMask,
+                                    streamType,
+                                    sampleRate, format, channelMask,
                                     (audio_policy_output_flags_t)flags);
 
     if (output == 0) {
@@ -214,7 +236,7 @@
 
     mVolume[LEFT] = 1.0f;
     mVolume[RIGHT] = 1.0f;
-    mSendLevel = 0;
+    mSendLevel = 0.0f;
     mFrameCount = frameCount;
     mNotificationFramesReq = notificationFrames;
     mSessionId = sessionId;
@@ -223,7 +245,7 @@
     // create the IAudioTrack
     status_t status = createTrack_l(streamType,
                                   sampleRate,
-                                  (uint32_t)format,
+                                  format,
                                   (uint32_t)channelMask,
                                   frameCount,
                                   flags,
@@ -237,21 +259,17 @@
 
     if (cbf != 0) {
         mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
-        if (mAudioTrackThread == 0) {
-          ALOGE("Could not create callback thread");
-          return NO_INIT;
-        }
     }
 
     mStatus = NO_ERROR;
 
     mStreamType = streamType;
-    mFormat = (uint32_t)format;
+    mFormat = format;
     mChannelMask = (uint32_t)channelMask;
     mChannelCount = channelCount;
     mSharedBuffer = sharedBuffer;
     mMuted = false;
-    mActive = 0;
+    mActive = false;
     mCbf = cbf;
     mUserData = user;
     mLoopCount = 0;
@@ -278,12 +296,12 @@
     return mLatency;
 }
 
-int AudioTrack::streamType() const
+audio_stream_type_t AudioTrack::streamType() const
 {
     return mStreamType;
 }
 
-int AudioTrack::format() const
+audio_format_t AudioTrack::format() const
 {
     return mFormat;
 }
@@ -298,7 +316,7 @@
     return mCblk->frameCount;
 }
 
-int AudioTrack::frameSize() const
+size_t AudioTrack::frameSize() const
 {
     if (audio_is_linear_pcm(mFormat)) {
         return channelCount()*audio_bytes_per_sample(mFormat);
@@ -337,18 +355,20 @@
     sp <IMemory> iMem = mCblkMemory;
     audio_track_cblk_t* cblk = mCblk;
 
-    if (mActive == 0) {
+    if (!mActive) {
         mFlushed = false;
-        mActive = 1;
+        mActive = true;
         mNewPosition = cblk->server + mUpdatePeriod;
         cblk->lock.lock();
         cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
         cblk->waitTimeMs = 0;
         android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
         if (t != 0) {
-           t->run("AudioTrackThread", ANDROID_PRIORITY_AUDIO);
+            t->run("AudioTrackThread", ANDROID_PRIORITY_AUDIO);
         } else {
-            setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_AUDIO);
+            mPreviousPriority = getpriority(PRIO_PROCESS, 0);
+            mPreviousSchedulingGroup = androidGetThreadSchedulingGroup(0);
+            androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
         }
 
         ALOGV("start %p before lock cblk %p", this, mCblk);
@@ -366,11 +386,12 @@
         cblk->lock.unlock();
         if (status != NO_ERROR) {
             ALOGV("start() failed");
-            mActive = 0;
+            mActive = false;
             if (t != 0) {
                 t->requestExit();
             } else {
-                setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
+                setpriority(PRIO_PROCESS, 0, mPreviousPriority);
+                androidSetThreadSchedulingGroup(0, mPreviousSchedulingGroup);
             }
         }
     }
@@ -390,8 +411,8 @@
     }
 
     AutoMutex lock(mLock);
-    if (mActive == 1) {
-        mActive = 0;
+    if (mActive) {
+        mActive = false;
         mCblk->cv.signal();
         mAudioTrack->stop();
         // Cancel loops (If we are in the middle of a loop, playback
@@ -408,7 +429,8 @@
         if (t != 0) {
             t->requestExit();
         } else {
-            setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL);
+            setpriority(PRIO_PROCESS, 0, mPreviousPriority);
+            androidSetThreadSchedulingGroup(0, mPreviousSchedulingGroup);
         }
     }
 
@@ -419,7 +441,8 @@
 
 bool AudioTrack::stopped() const
 {
-    return !mActive;
+    AutoMutex lock(mLock);
+    return stopped_l();
 }
 
 void AudioTrack::flush()
@@ -451,8 +474,8 @@
 {
     ALOGV("pause");
     AutoMutex lock(mLock);
-    if (mActive == 1) {
-        mActive = 0;
+    if (mActive) {
+        mActive = false;
         mAudioTrack->pause();
     }
 }
@@ -470,7 +493,7 @@
 
 status_t AudioTrack::setVolume(float left, float right)
 {
-    if (left > 1.0f || right > 1.0f) {
+    if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
         return BAD_VALUE;
     }
 
@@ -478,7 +501,6 @@
     mVolume[LEFT] = left;
     mVolume[RIGHT] = right;
 
-    // write must be atomic
     mCblk->volumeLR = (uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000);
 
     return NO_ERROR;
@@ -497,14 +519,14 @@
 status_t AudioTrack::setAuxEffectSendLevel(float level)
 {
     ALOGV("setAuxEffectSendLevel(%f)", level);
-    if (level > 1.0f) {
+    if (level < 0.0f || level > 1.0f) {
         return BAD_VALUE;
     }
     AutoMutex lock(mLock);
 
     mSendLevel = level;
 
-    mCblk->sendLevel = uint16_t(level * 0x1000);
+    mCblk->setSendLevel(level);
 
     return NO_ERROR;
 }
@@ -642,9 +664,10 @@
 status_t AudioTrack::setPosition(uint32_t position)
 {
     AutoMutex lock(mLock);
-    Mutex::Autolock _l(mCblk->lock);
 
-    if (!stopped()) return INVALID_OPERATION;
+    if (!stopped_l()) return INVALID_OPERATION;
+
+    Mutex::Autolock _l(mCblk->lock);
 
     if (position > mCblk->user) return BAD_VALUE;
 
@@ -667,7 +690,7 @@
 {
     AutoMutex lock(mLock);
 
-    if (!stopped()) return INVALID_OPERATION;
+    if (!stopped_l()) return INVALID_OPERATION;
 
     flush_l();
 
@@ -685,7 +708,7 @@
 // must be called with mLock held
 audio_io_handle_t AudioTrack::getOutput_l()
 {
-    return AudioSystem::getOutput((audio_stream_type_t)mStreamType,
+    return AudioSystem::getOutput(mStreamType,
             mCblk->sampleRate, mFormat, mChannelMask, (audio_policy_output_flags_t)mFlags);
 }
 
@@ -708,9 +731,9 @@
 
 // must be called with mLock held
 status_t AudioTrack::createTrack_l(
-        int streamType,
+        audio_stream_type_t streamType,
         uint32_t sampleRate,
-        uint32_t format,
+        audio_format_t format,
         uint32_t channelMask,
         int frameCount,
         uint32_t flags,
@@ -802,9 +825,7 @@
         ALOGE("Could not get control block");
         return NO_INIT;
     }
-    mAudioTrack.clear();
     mAudioTrack = track;
-    mCblkMemory.clear();
     mCblkMemory = cblk;
     mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
     android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
@@ -817,7 +838,7 @@
     }
 
     mCblk->volumeLR = (uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) | uint16_t(mVolume[LEFT] * 0x1000);
-    mCblk->sendLevel = uint16_t(mSendLevel * 0x1000);
+    mCblk->setSendLevel(mSendLevel);
     mAudioTrack->attachAuxEffect(mAuxEffectId);
     mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
     mCblk->waitTimeMs = 0;
@@ -829,7 +850,7 @@
 status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
 {
     AutoMutex lock(mLock);
-    int active;
+    bool active;
     status_t result = NO_ERROR;
     audio_track_cblk_t* cblk = mCblk;
     uint32_t framesReq = audioBuffer->frameCount;
@@ -851,12 +872,12 @@
         goto start_loop_here;
         while (framesAvail == 0) {
             active = mActive;
-            if (UNLIKELY(!active)) {
+            if (CC_UNLIKELY(!active)) {
                 ALOGV("Not active and NO_MORE_BUFFERS");
                 cblk->lock.unlock();
                 return NO_MORE_BUFFERS;
             }
-            if (UNLIKELY(!waitCount)) {
+            if (CC_UNLIKELY(!waitCount)) {
                 cblk->lock.unlock();
                 return WOULD_BLOCK;
             }
@@ -865,7 +886,7 @@
                 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
                 cblk->lock.unlock();
                 mLock.lock();
-                if (mActive == 0) {
+                if (!mActive) {
                     return status_t(STOPPED);
                 }
                 cblk->lock.lock();
@@ -874,7 +895,7 @@
             if (cblk->flags & CBLK_INVALID_MSK) {
                 goto create_new_track;
             }
-            if (__builtin_expect(result!=NO_ERROR, false)) {
+            if (CC_UNLIKELY(result != NO_ERROR)) {
                 cblk->waitTimeMs += waitTimeMs;
                 if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
                     // timing out when a loop has been set and we have already written upto loop end
@@ -978,7 +999,7 @@
     ssize_t written = 0;
     const int8_t *src = (const int8_t *)buffer;
     Buffer audioBuffer;
-    size_t frameSz = (size_t)frameSize();
+    size_t frameSz = frameSize();
 
     do {
         audioBuffer.frameCount = userSize/frameSz;
@@ -998,12 +1019,7 @@
         if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
             // Divide capacity by 2 to take expansion into account
             toWrite = audioBuffer.size>>1;
-            // 8 to 16 bit conversion
-            int count = toWrite;
-            int16_t *dst = (int16_t *)(audioBuffer.i8);
-            while(count--) {
-                *dst++ = (int16_t)(*src++^0x80) << 8;
-            }
+            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) src, toWrite);
         } else {
             toWrite = audioBuffer.size;
             memcpy(audioBuffer.i8, src, toWrite);
@@ -1032,10 +1048,11 @@
     sp <IAudioTrack> audioTrack = mAudioTrack;
     sp <IMemory> iMem = mCblkMemory;
     audio_track_cblk_t* cblk = mCblk;
+    bool active = mActive;
     mLock.unlock();
 
     // Manage underrun callback
-    if (mActive && (cblk->framesAvailable() == cblk->frameCount)) {
+    if (active && (cblk->framesAvailable() == cblk->frameCount)) {
         ALOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
         if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
             mCbf(EVENT_UNDERRUN, mUserData, 0);
@@ -1123,19 +1140,14 @@
         if (writtenSize > reqSize) writtenSize = reqSize;
 
         if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT)) {
-            // 8 to 16 bit conversion
-            const int8_t *src = audioBuffer.i8 + writtenSize-1;
-            int count = writtenSize;
-            int16_t *dst = audioBuffer.i16 + writtenSize-1;
-            while(count--) {
-                *dst-- = (int16_t)(*src--^0x80) << 8;
-            }
+            // 8 to 16 bit conversion, note that source and destination are the same address
+            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
             writtenSize <<= 1;
         }
 
         audioBuffer.size = writtenSize;
         // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
-        // 8 bit PCM data: in this case,  mCblk->frameSize is based on a sampel size of
+        // 8 bit PCM data: in this case,  mCblk->frameSize is based on a sample size of
         // 16 bit.
         audioBuffer.frameCount = writtenSize/mCblk->frameSize;
 
@@ -1309,13 +1321,13 @@
     : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
     userBase(0), serverBase(0), buffers(0), frameCount(0),
     loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), volumeLR(0),
-    sendLevel(0), flags(0)
+    mSendLevel(0), flags(0)
 {
 }
 
 uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
 {
-    uint32_t u = this->user;
+    uint32_t u = user;
 
     u += frameCount;
     // Ensure that user is never ahead of server for AudioRecord
@@ -1324,16 +1336,16 @@
         if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
             bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
         }
-    } else if (u > this->server) {
-        ALOGW("stepServer occured after track reset");
-        u = this->server;
+    } else if (u > server) {
+        ALOGW("stepServer occurred after track reset");
+        u = server;
     }
 
     if (u >= userBase + this->frameCount) {
         userBase += this->frameCount;
     }
 
-    this->user = u;
+    user = u;
 
     // Clear flow control error condition as new data has been written/read to/from buffer.
     if (flags & CBLK_UNDERRUN_MSK) {
@@ -1350,7 +1362,7 @@
         return false;
     }
 
-    uint32_t s = this->server;
+    uint32_t s = server;
 
     s += frameCount;
     if (flags & CBLK_DIRECTION_MSK) {
@@ -1363,9 +1375,9 @@
         // while the mixer is processing a block: in this case,
         // stepServer() is called After the flush() has reset u & s and
         // we have s > u
-        if (s > this->user) {
-            ALOGW("stepServer occured after track reset");
-            s = this->user;
+        if (s > user) {
+            ALOGW("stepServer occurred after track reset");
+            s = user;
         }
     }
 
@@ -1381,7 +1393,7 @@
         serverBase += this->frameCount;
     }
 
-    this->server = s;
+    server = s;
 
     if (!(flags & CBLK_INVALID_MSK)) {
         cv.signal();
@@ -1392,7 +1404,7 @@
 
 void* audio_track_cblk_t::buffer(uint32_t offset) const
 {
-    return (int8_t *)this->buffers + (offset - userBase) * this->frameSize;
+    return (int8_t *)buffers + (offset - userBase) * frameSize;
 }
 
 uint32_t audio_track_cblk_t::framesAvailable()
@@ -1403,8 +1415,8 @@
 
 uint32_t audio_track_cblk_t::framesAvailable_l()
 {
-    uint32_t u = this->user;
-    uint32_t s = this->server;
+    uint32_t u = user;
+    uint32_t s = server;
 
     if (flags & CBLK_DIRECTION_MSK) {
         uint32_t limit = (s < loopStart) ? s : loopStart;
@@ -1416,8 +1428,8 @@
 
 uint32_t audio_track_cblk_t::framesReady()
 {
-    uint32_t u = this->user;
-    uint32_t s = this->server;
+    uint32_t u = user;
+    uint32_t s = server;
 
     if (flags & CBLK_DIRECTION_MSK) {
         if (u < loopEnd) {
@@ -1462,4 +1474,3 @@
 // -------------------------------------------------------------------------
 
 }; // namespace android
-
diff --git a/media/libmedia/IAudioFlinger.cpp b/media/libmedia/IAudioFlinger.cpp
index abd491f..0d442ef 100644
--- a/media/libmedia/IAudioFlinger.cpp
+++ b/media/libmedia/IAudioFlinger.cpp
@@ -82,9 +82,9 @@
 
     virtual sp<IAudioTrack> createTrack(
                                 pid_t pid,
-                                int streamType,
+                                audio_stream_type_t streamType,
                                 uint32_t sampleRate,
-                                uint32_t format,
+                                audio_format_t format,
                                 uint32_t channelMask,
                                 int frameCount,
                                 uint32_t flags,
@@ -97,7 +97,7 @@
         sp<IAudioTrack> track;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
         data.writeInt32(pid);
-        data.writeInt32(streamType);
+        data.writeInt32((int32_t) streamType);
         data.writeInt32(sampleRate);
         data.writeInt32(format);
         data.writeInt32(channelMask);
@@ -131,7 +131,7 @@
                                 pid_t pid,
                                 int input,
                                 uint32_t sampleRate,
-                                uint32_t format,
+                                audio_format_t format,
                                 uint32_t channelMask,
                                 int frameCount,
                                 uint32_t flags,
@@ -188,13 +188,13 @@
         return reply.readInt32();
     }
 
-    virtual uint32_t format(int output) const
+    virtual audio_format_t format(int output) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
         data.writeInt32(output);
         remote()->transact(FORMAT, data, &reply);
-        return reply.readInt32();
+        return (audio_format_t) reply.readInt32();
     }
 
     virtual size_t frameCount(int output) const
@@ -249,47 +249,47 @@
         return reply.readInt32();
     }
 
-    virtual status_t setStreamVolume(int stream, float value, int output)
+    virtual status_t setStreamVolume(audio_stream_type_t stream, float value, int output)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(stream);
+        data.writeInt32((int32_t) stream);
         data.writeFloat(value);
         data.writeInt32(output);
         remote()->transact(SET_STREAM_VOLUME, data, &reply);
         return reply.readInt32();
     }
 
-    virtual status_t setStreamMute(int stream, bool muted)
+    virtual status_t setStreamMute(audio_stream_type_t stream, bool muted)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(stream);
+        data.writeInt32((int32_t) stream);
         data.writeInt32(muted);
         remote()->transact(SET_STREAM_MUTE, data, &reply);
         return reply.readInt32();
     }
 
-    virtual float streamVolume(int stream, int output) const
+    virtual float streamVolume(audio_stream_type_t stream, int output) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(stream);
+        data.writeInt32((int32_t) stream);
         data.writeInt32(output);
         remote()->transact(STREAM_VOLUME, data, &reply);
         return reply.readFloat();
     }
 
-    virtual bool streamMute(int stream) const
+    virtual bool streamMute(audio_stream_type_t stream) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(stream);
+        data.writeInt32((int32_t) stream);
         remote()->transact(STREAM_MUTE, data, &reply);
         return reply.readInt32();
     }
 
-    virtual status_t setMode(int mode)
+    virtual status_t setMode(audio_mode_t mode)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
@@ -343,7 +343,7 @@
         remote()->transact(REGISTER_CLIENT, data, &reply);
     }
 
-    virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
+    virtual size_t getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
@@ -356,7 +356,7 @@
 
     virtual int openOutput(uint32_t *pDevices,
                             uint32_t *pSamplingRate,
-                            uint32_t *pFormat,
+                            audio_format_t *pFormat,
                             uint32_t *pChannels,
                             uint32_t *pLatencyMs,
                             uint32_t flags)
@@ -364,7 +364,7 @@
         Parcel data, reply;
         uint32_t devices = pDevices ? *pDevices : 0;
         uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
-        uint32_t format = pFormat ? *pFormat : 0;
+        audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
         uint32_t channels = pChannels ? *pChannels : 0;
         uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
 
@@ -382,7 +382,7 @@
         if (pDevices) *pDevices = devices;
         samplingRate = reply.readInt32();
         if (pSamplingRate) *pSamplingRate = samplingRate;
-        format = reply.readInt32();
+        format = (audio_format_t) reply.readInt32();
         if (pFormat) *pFormat = format;
         channels = reply.readInt32();
         if (pChannels) *pChannels = channels;
@@ -430,14 +430,14 @@
 
     virtual int openInput(uint32_t *pDevices,
                             uint32_t *pSamplingRate,
-                            uint32_t *pFormat,
+                            audio_format_t *pFormat,
                             uint32_t *pChannels,
                             uint32_t acoustics)
     {
         Parcel data, reply;
         uint32_t devices = pDevices ? *pDevices : 0;
         uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
-        uint32_t format = pFormat ? *pFormat : 0;
+        audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
         uint32_t channels = pChannels ? *pChannels : 0;
 
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
@@ -452,7 +452,7 @@
         if (pDevices) *pDevices = devices;
         samplingRate = reply.readInt32();
         if (pSamplingRate) *pSamplingRate = samplingRate;
-        format = reply.readInt32();
+        format = (audio_format_t) reply.readInt32();
         if (pFormat) *pFormat = format;
         channels = reply.readInt32();
         if (pChannels) *pChannels = channels;
@@ -468,11 +468,11 @@
         return reply.readInt32();
     }
 
-    virtual status_t setStreamOutput(uint32_t stream, int output)
+    virtual status_t setStreamOutput(audio_stream_type_t stream, int output)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
-        data.writeInt32(stream);
+        data.writeInt32((int32_t) stream);
         data.writeInt32(output);
         remote()->transact(SET_STREAM_OUTPUT, data, &reply);
         return reply.readInt32();
@@ -678,7 +678,7 @@
             pid_t pid = data.readInt32();
             int streamType = data.readInt32();
             uint32_t sampleRate = data.readInt32();
-            int format = data.readInt32();
+            audio_format_t format = (audio_format_t) data.readInt32();
             int channelCount = data.readInt32();
             size_t bufferCount = data.readInt32();
             uint32_t flags = data.readInt32();
@@ -687,7 +687,7 @@
             int sessionId = data.readInt32();
             status_t status;
             sp<IAudioTrack> track = createTrack(pid,
-                    streamType, sampleRate, format,
+                    (audio_stream_type_t) streamType, sampleRate, format,
                     channelCount, bufferCount, flags, buffer, output, &sessionId, &status);
             reply->writeInt32(sessionId);
             reply->writeInt32(status);
@@ -699,7 +699,7 @@
             pid_t pid = data.readInt32();
             int input = data.readInt32();
             uint32_t sampleRate = data.readInt32();
-            int format = data.readInt32();
+            audio_format_t format = (audio_format_t) data.readInt32();
             int channelCount = data.readInt32();
             size_t bufferCount = data.readInt32();
             uint32_t flags = data.readInt32();
@@ -762,31 +762,31 @@
             int stream = data.readInt32();
             float volume = data.readFloat();
             int output = data.readInt32();
-            reply->writeInt32( setStreamVolume(stream, volume, output) );
+            reply->writeInt32( setStreamVolume((audio_stream_type_t) stream, volume, output) );
             return NO_ERROR;
         } break;
         case SET_STREAM_MUTE: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             int stream = data.readInt32();
-            reply->writeInt32( setStreamMute(stream, data.readInt32()) );
+            reply->writeInt32( setStreamMute((audio_stream_type_t) stream, data.readInt32()) );
             return NO_ERROR;
         } break;
         case STREAM_VOLUME: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             int stream = data.readInt32();
             int output = data.readInt32();
-            reply->writeFloat( streamVolume(stream, output) );
+            reply->writeFloat( streamVolume((audio_stream_type_t) stream, output) );
             return NO_ERROR;
         } break;
         case STREAM_MUTE: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             int stream = data.readInt32();
-            reply->writeInt32( streamMute(stream) );
+            reply->writeInt32( streamMute((audio_stream_type_t) stream) );
             return NO_ERROR;
         } break;
         case SET_MODE: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
-            int mode = data.readInt32();
+            audio_mode_t mode = (audio_mode_t) data.readInt32();
             reply->writeInt32( setMode(mode) );
             return NO_ERROR;
         } break;
@@ -825,7 +825,7 @@
         case GET_INPUTBUFFERSIZE: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             uint32_t sampleRate = data.readInt32();
-            int format = data.readInt32();
+            audio_format_t format = (audio_format_t) data.readInt32();
             int channelCount = data.readInt32();
             reply->writeInt32( getInputBufferSize(sampleRate, format, channelCount) );
             return NO_ERROR;
@@ -834,7 +834,7 @@
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             uint32_t devices = data.readInt32();
             uint32_t samplingRate = data.readInt32();
-            uint32_t format = data.readInt32();
+            audio_format_t format = (audio_format_t) data.readInt32();
             uint32_t channels = data.readInt32();
             uint32_t latency = data.readInt32();
             uint32_t flags = data.readInt32();
@@ -879,7 +879,7 @@
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             uint32_t devices = data.readInt32();
             uint32_t samplingRate = data.readInt32();
-            uint32_t format = data.readInt32();
+            audio_format_t format = (audio_format_t) data.readInt32();
             uint32_t channels = data.readInt32();
             uint32_t acoutics = data.readInt32();
 
@@ -904,7 +904,7 @@
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             uint32_t stream = data.readInt32();
             int output = data.readInt32();
-            reply->writeInt32(setStreamOutput(stream, output));
+            reply->writeInt32(setStreamOutput((audio_stream_type_t) stream, output));
             return NO_ERROR;
         } break;
         case SET_VOICE_VOLUME: {
diff --git a/media/libmedia/IAudioPolicyService.cpp b/media/libmedia/IAudioPolicyService.cpp
index 50b4855..b5c857f 100644
--- a/media/libmedia/IAudioPolicyService.cpp
+++ b/media/libmedia/IAudioPolicyService.cpp
@@ -33,7 +33,7 @@
     SET_DEVICE_CONNECTION_STATE = IBinder::FIRST_CALL_TRANSACTION,
     GET_DEVICE_CONNECTION_STATE,
     SET_PHONE_STATE,
-    SET_RINGER_MODE,
+    SET_RINGER_MODE,    // reserved, no longer used
     SET_FORCE_USE,
     GET_FORCE_USE,
     GET_OUTPUT,
@@ -91,7 +91,7 @@
         return static_cast <audio_policy_dev_state_t>(reply.readInt32());
     }
 
-    virtual status_t setPhoneState(int state)
+    virtual status_t setPhoneState(audio_mode_t state)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
@@ -100,16 +100,6 @@
         return static_cast <status_t> (reply.readInt32());
     }
 
-    virtual status_t setRingerMode(uint32_t mode, uint32_t mask)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(mode);
-        data.writeInt32(mask);
-        remote()->transact(SET_RINGER_MODE, data, &reply);
-        return static_cast <status_t> (reply.readInt32());
-    }
-
     virtual status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config)
     {
         Parcel data, reply;
@@ -132,7 +122,7 @@
     virtual audio_io_handle_t getOutput(
                                         audio_stream_type_t stream,
                                         uint32_t samplingRate,
-                                        uint32_t format,
+                                        audio_format_t format,
                                         uint32_t channels,
                                         audio_policy_output_flags_t flags)
     {
@@ -154,7 +144,7 @@
         Parcel data, reply;
         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
         data.writeInt32(output);
-        data.writeInt32(stream);
+        data.writeInt32((int32_t) stream);
         data.writeInt32(session);
         remote()->transact(START_OUTPUT, data, &reply);
         return static_cast <status_t> (reply.readInt32());
@@ -167,7 +157,7 @@
         Parcel data, reply;
         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
         data.writeInt32(output);
-        data.writeInt32(stream);
+        data.writeInt32((int32_t) stream);
         data.writeInt32(session);
         remote()->transact(STOP_OUTPUT, data, &reply);
         return static_cast <status_t> (reply.readInt32());
@@ -184,7 +174,7 @@
     virtual audio_io_handle_t getInput(
                                     int inputSource,
                                     uint32_t samplingRate,
-                                    uint32_t format,
+                                    audio_format_t format,
                                     uint32_t channels,
                                     audio_in_acoustics_t acoustics,
                                     int audioSession)
@@ -240,21 +230,28 @@
         return static_cast <status_t> (reply.readInt32());
     }
 
-    virtual status_t setStreamVolumeIndex(audio_stream_type_t stream, int index)
+    virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
+                                          int index,
+                                          audio_devices_t device)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
         data.writeInt32(static_cast <uint32_t>(stream));
         data.writeInt32(index);
+        data.writeInt32(static_cast <uint32_t>(device));
         remote()->transact(SET_STREAM_VOLUME, data, &reply);
         return static_cast <status_t> (reply.readInt32());
     }
 
-    virtual status_t getStreamVolumeIndex(audio_stream_type_t stream, int *index)
+    virtual status_t getStreamVolumeIndex(audio_stream_type_t stream,
+                                          int *index,
+                                          audio_devices_t device)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
         data.writeInt32(static_cast <uint32_t>(stream));
+        data.writeInt32(static_cast <uint32_t>(device));
+
         remote()->transact(GET_STREAM_VOLUME, data, &reply);
         int lIndex = reply.readInt32();
         if (index) *index = lIndex;
@@ -324,11 +321,11 @@
         return static_cast <status_t> (reply.readInt32());
     }
 
-    virtual bool isStreamActive(int stream, uint32_t inPastMs) const
+    virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeInt32(stream);
+        data.writeInt32((int32_t) stream);
         data.writeInt32(inPastMs);
         remote()->transact(IS_STREAM_ACTIVE, data, &reply);
         return reply.readInt32();
@@ -394,15 +391,7 @@
 
         case SET_PHONE_STATE: {
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            reply->writeInt32(static_cast <uint32_t>(setPhoneState(data.readInt32())));
-            return NO_ERROR;
-        } break;
-
-        case SET_RINGER_MODE: {
-            CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            uint32_t mode = data.readInt32();
-            uint32_t mask = data.readInt32();
-            reply->writeInt32(static_cast <uint32_t>(setRingerMode(mode, mask)));
+            reply->writeInt32(static_cast <uint32_t>(setPhoneState((audio_mode_t) data.readInt32())));
             return NO_ERROR;
         } break;
 
@@ -427,7 +416,7 @@
             audio_stream_type_t stream =
                     static_cast <audio_stream_type_t>(data.readInt32());
             uint32_t samplingRate = data.readInt32();
-            uint32_t format = data.readInt32();
+            audio_format_t format = (audio_format_t) data.readInt32();
             uint32_t channels = data.readInt32();
             audio_policy_output_flags_t flags =
                     static_cast <audio_policy_output_flags_t>(data.readInt32());
@@ -474,7 +463,7 @@
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             int inputSource = data.readInt32();
             uint32_t samplingRate = data.readInt32();
-            uint32_t format = data.readInt32();
+            audio_format_t format = (audio_format_t) data.readInt32();
             uint32_t channels = data.readInt32();
             audio_in_acoustics_t acoustics =
                     static_cast <audio_in_acoustics_t>(data.readInt32());
@@ -525,7 +514,10 @@
             audio_stream_type_t stream =
                     static_cast <audio_stream_type_t>(data.readInt32());
             int index = data.readInt32();
-            reply->writeInt32(static_cast <uint32_t>(setStreamVolumeIndex(stream, index)));
+            audio_devices_t device = static_cast <audio_devices_t>(data.readInt32());
+            reply->writeInt32(static_cast <uint32_t>(setStreamVolumeIndex(stream,
+                                                                          index,
+                                                                          device)));
             return NO_ERROR;
         } break;
 
@@ -533,8 +525,9 @@
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             audio_stream_type_t stream =
                     static_cast <audio_stream_type_t>(data.readInt32());
+            audio_devices_t device = static_cast <audio_devices_t>(data.readInt32());
             int index;
-            status_t status = getStreamVolumeIndex(stream, &index);
+            status_t status = getStreamVolumeIndex(stream, &index, device);
             reply->writeInt32(index);
             reply->writeInt32(static_cast <uint32_t>(status));
             return NO_ERROR;
@@ -598,9 +591,9 @@
 
         case IS_STREAM_ACTIVE: {
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
-            int stream = data.readInt32();
+            audio_stream_type_t stream = (audio_stream_type_t) data.readInt32();
             uint32_t inPastMs = (uint32_t)data.readInt32();
-            reply->writeInt32( isStreamActive(stream, inPastMs) );
+            reply->writeInt32( isStreamActive((audio_stream_type_t) stream, inPastMs) );
             return NO_ERROR;
         } break;
 
diff --git a/media/libmedia/IAudioTrack.cpp b/media/libmedia/IAudioTrack.cpp
index 0b372f3..e618619 100644
--- a/media/libmedia/IAudioTrack.cpp
+++ b/media/libmedia/IAudioTrack.cpp
@@ -46,6 +46,18 @@
     {
     }
     
+    virtual sp<IMemory> getCblk() const
+    {
+        Parcel data, reply;
+        sp<IMemory> cblk;
+        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
+        status_t status = remote()->transact(GET_CBLK, data, &reply);
+        if (status == NO_ERROR) {
+            cblk = interface_cast<IMemory>(reply.readStrongBinder());
+        }
+        return cblk;
+    }
+
     virtual status_t start()
     {
         Parcel data, reply;
@@ -88,18 +100,6 @@
         remote()->transact(PAUSE, data, &reply);
     }
     
-    virtual sp<IMemory> getCblk() const
-    {
-        Parcel data, reply;
-        sp<IMemory> cblk;
-        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
-        status_t status = remote()->transact(GET_CBLK, data, &reply);
-        if (status == NO_ERROR) {
-            cblk = interface_cast<IMemory>(reply.readStrongBinder());
-        }
-        return cblk;
-    }
-
     virtual status_t attachAuxEffect(int effectId)
     {
         Parcel data, reply;
diff --git a/media/libmedia/IMediaDeathNotifier.cpp b/media/libmedia/IMediaDeathNotifier.cpp
index 8525482..aeb35a5 100644
--- a/media/libmedia/IMediaDeathNotifier.cpp
+++ b/media/libmedia/IMediaDeathNotifier.cpp
@@ -36,7 +36,7 @@
 {
     ALOGV("getMediaPlayerService");
     Mutex::Autolock _l(sServiceLock);
-    if (sMediaPlayerService.get() == 0) {
+    if (sMediaPlayerService == 0) {
         sp<IServiceManager> sm = defaultServiceManager();
         sp<IBinder> binder;
         do {
diff --git a/media/libmedia/IMediaPlayer.cpp b/media/libmedia/IMediaPlayer.cpp
index 9c1e6b7..64cc919 100644
--- a/media/libmedia/IMediaPlayer.cpp
+++ b/media/libmedia/IMediaPlayer.cpp
@@ -198,11 +198,11 @@
         return reply.readInt32();
     }
 
-    status_t setAudioStreamType(int type)
+    status_t setAudioStreamType(audio_stream_type_t stream)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IMediaPlayer::getInterfaceDescriptor());
-        data.writeInt32(type);
+        data.writeInt32((int32_t) stream);
         remote()->transact(SET_AUDIO_STREAM_TYPE, data, &reply);
         return reply.readInt32();
     }
@@ -397,7 +397,7 @@
         } break;
         case SET_AUDIO_STREAM_TYPE: {
             CHECK_INTERFACE(IMediaPlayer, data, reply);
-            reply->writeInt32(setAudioStreamType(data.readInt32()));
+            reply->writeInt32(setAudioStreamType((audio_stream_type_t) data.readInt32()));
             return NO_ERROR;
         } break;
         case SET_LOOPING: {
diff --git a/media/libmedia/IMediaPlayerService.cpp b/media/libmedia/IMediaPlayerService.cpp
index 8e4dd04..f5b5cbd 100644
--- a/media/libmedia/IMediaPlayerService.cpp
+++ b/media/libmedia/IMediaPlayerService.cpp
@@ -78,7 +78,7 @@
         return interface_cast<IMediaRecorder>(reply.readStrongBinder());
     }
 
-    virtual sp<IMemory> decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
+    virtual sp<IMemory> decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor());
@@ -86,11 +86,11 @@
         remote()->transact(DECODE_URL, data, &reply);
         *pSampleRate = uint32_t(reply.readInt32());
         *pNumChannels = reply.readInt32();
-        *pFormat = reply.readInt32();
+        *pFormat = (audio_format_t) reply.readInt32();
         return interface_cast<IMemory>(reply.readStrongBinder());
     }
 
-    virtual sp<IMemory> decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
+    virtual sp<IMemory> decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor());
@@ -100,7 +100,7 @@
         remote()->transact(DECODE_FD, data, &reply);
         *pSampleRate = uint32_t(reply.readInt32());
         *pNumChannels = reply.readInt32();
-        *pFormat = reply.readInt32();
+        *pFormat = (audio_format_t) reply.readInt32();
         return interface_cast<IMemory>(reply.readStrongBinder());
     }
 
@@ -148,11 +148,11 @@
             const char* url = data.readCString();
             uint32_t sampleRate;
             int numChannels;
-            int format;
+            audio_format_t format;
             sp<IMemory> player = decode(url, &sampleRate, &numChannels, &format);
             reply->writeInt32(sampleRate);
             reply->writeInt32(numChannels);
-            reply->writeInt32(format);
+            reply->writeInt32((int32_t) format);
             reply->writeStrongBinder(player->asBinder());
             return NO_ERROR;
         } break;
@@ -163,11 +163,11 @@
             int64_t length = data.readInt64();
             uint32_t sampleRate;
             int numChannels;
-            int format;
+            audio_format_t format;
             sp<IMemory> player = decode(fd, offset, length, &sampleRate, &numChannels, &format);
             reply->writeInt32(sampleRate);
             reply->writeInt32(numChannels);
-            reply->writeInt32(format);
+            reply->writeInt32((int32_t) format);
             reply->writeStrongBinder(player->asBinder());
             return NO_ERROR;
         } break;
diff --git a/media/libmedia/JetPlayer.cpp b/media/libmedia/JetPlayer.cpp
index fa5b67a..8456db5 100644
--- a/media/libmedia/JetPlayer.cpp
+++ b/media/libmedia/JetPlayer.cpp
@@ -91,7 +91,7 @@
     mAudioTrack = new AudioTrack();
     mAudioTrack->set(AUDIO_STREAM_MUSIC,  //TODO parametrize this
             pLibConfig->sampleRate,
-            1, // format = PCM 16bits per sample,
+            AUDIO_FORMAT_PCM_16_BIT,
             (pLibConfig->numChannels == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
             mTrackBufferSize,
             0);
@@ -100,7 +100,8 @@
     {
         Mutex::Autolock l(mMutex);
         ALOGV("JetPlayer::init(): trying to start render thread");
-        createThreadEtc(renderThread, this, "jetRenderThread", ANDROID_PRIORITY_AUDIO);
+        mThread = new JetPlayerThread(this);
+        mThread->run("jetRenderThread", ANDROID_PRIORITY_AUDIO);
         mCondition.wait(mMutex);
     }
     if (mTid > 0) {
@@ -156,12 +157,6 @@
 
 
 //-------------------------------------------------------------------------------------------------
-int JetPlayer::renderThread(void* p) {
-
-    return ((JetPlayer*)p)->render();
-}
-
-//-------------------------------------------------------------------------------------------------
 int JetPlayer::render() {
     EAS_RESULT result = EAS_FAILURE;
     EAS_I32 count;
@@ -173,10 +168,6 @@
     // allocate render buffer
     mAudioBuffer = 
         new EAS_PCM[pLibConfig->mixBufferSize * pLibConfig->numChannels * MIX_NUM_BUFFERS];
-    if (!mAudioBuffer) {
-        ALOGE("JetPlayer::render(): mAudioBuffer allocate failed");
-        goto threadExit;
-    }
 
     // signal main thread that we started
     {
@@ -343,8 +334,8 @@
     Mutex::Autolock lock(mMutex);
 
     mEasJetFileLoc = (EAS_FILE_LOCATOR) malloc(sizeof(EAS_FILE));
-    memset(mJetFilePath, 0, 256);
-    strncpy(mJetFilePath, path, strlen(path));
+    strncpy(mJetFilePath, path, sizeof(mJetFilePath));
+    mJetFilePath[sizeof(mJetFilePath) - 1] = '\0';
     mEasJetFileLoc->path = mJetFilePath;
 
     mEasJetFileLoc->fd = 0;
diff --git a/media/libmedia/MediaScannerClient.cpp b/media/libmedia/MediaScannerClient.cpp
index 40b8188..9fe1820 100644
--- a/media/libmedia/MediaScannerClient.cpp
+++ b/media/libmedia/MediaScannerClient.cpp
@@ -173,6 +173,7 @@
             const char* source = mValues->getEntry(i);
             int targetLength = len * 3 + 1;
             char* buffer = new char[targetLength];
+            // don't normally check for NULL, but in this case targetLength may be large
             if (!buffer)
                 break;
             char* target = buffer;
diff --git a/media/libmedia/ToneGenerator.cpp b/media/libmedia/ToneGenerator.cpp
index 35dfbb8..5ceb912 100644
--- a/media/libmedia/ToneGenerator.cpp
+++ b/media/libmedia/ToneGenerator.cpp
@@ -798,7 +798,7 @@
 //        none
 //
 ////////////////////////////////////////////////////////////////////////////////
-ToneGenerator::ToneGenerator(int streamType, float volume, bool threadCanCallJava) {
+ToneGenerator::ToneGenerator(audio_stream_type_t streamType, float volume, bool threadCanCallJava) {
 
     ALOGV("ToneGenerator constructor: streamType=%d, volume=%f\n", streamType, volume);
 
@@ -1017,10 +1017,6 @@
 
    // Open audio track in mono, PCM 16bit, default sampling rate, default buffer size
     mpAudioTrack = new AudioTrack();
-    if (mpAudioTrack == 0) {
-        ALOGE("AudioTrack allocation failed");
-        goto initAudioTrack_exit;
-    }
     ALOGV("Create Track: %p\n", mpAudioTrack);
 
     mpAudioTrack->set(mStreamType,
@@ -1353,9 +1349,6 @@
                         new ToneGenerator::WaveGenerator((unsigned short)mSamplingRate,
                                 frequency,
                                 TONEGEN_GAIN/lNumWaves);
-                if (lpWaveGen == 0) {
-                    goto prepareWave_exit;
-                }
                 mWaveGens.add(frequency, lpWaveGen);
             }
             frequency = mpNewToneDesc->segments[segmentIdx].waveFreq[++freqIdx];
@@ -1375,12 +1368,6 @@
     }
 
     return true;
-
-prepareWave_exit:
-
-    clearWaveGens();
-
-    return false;
 }
 
 
diff --git a/media/libmedia/Visualizer.cpp b/media/libmedia/Visualizer.cpp
index d08ffa5..13b64e9 100644
--- a/media/libmedia/Visualizer.cpp
+++ b/media/libmedia/Visualizer.cpp
@@ -27,8 +27,7 @@
 #include <cutils/bitops.h>
 
 #include <media/Visualizer.h>
-
-extern void fixed_fft_real(int n, int32_t *v);
+#include <audio_utils/fixedfft.h>
 
 namespace android {
 
@@ -54,7 +53,7 @@
 
 status_t Visualizer::setEnabled(bool enabled)
 {
-    Mutex::Autolock _l(mLock);
+    Mutex::Autolock _l(mCaptureLock);
 
     sp<CaptureThread> t = mCaptureThread;
     if (t != 0) {
@@ -74,7 +73,7 @@
     if (status == NO_ERROR) {
         if (t != 0) {
             if (enabled) {
-                t->run("AudioTrackThread");
+                t->run("Visualizer");
             } else {
                 t->requestExit();
             }
@@ -93,7 +92,7 @@
     if (rate > CAPTURE_RATE_MAX) {
         return BAD_VALUE;
     }
-    Mutex::Autolock _l(mLock);
+    Mutex::Autolock _l(mCaptureLock);
 
     if (mEnabled) {
         return INVALID_OPERATION;
@@ -115,10 +114,6 @@
 
     if (cbk != NULL) {
         mCaptureThread = new CaptureThread(*this, rate, ((flags & CAPTURE_CALL_JAVA) != 0));
-        if (mCaptureThread == 0) {
-            ALOGE("Could not create callback thread");
-            return NO_INIT;
-        }
     }
     ALOGV("setCaptureCallBack() rate: %d thread %p flags 0x%08x",
             rate, mCaptureThread.get(), mCaptureFlags);
@@ -133,7 +128,7 @@
         return BAD_VALUE;
     }
 
-    Mutex::Autolock _l(mLock);
+    Mutex::Autolock _l(mCaptureLock);
     if (mEnabled) {
         return INVALID_OPERATION;
     }
@@ -235,7 +230,7 @@
 
 void Visualizer::periodicCapture()
 {
-    Mutex::Autolock _l(mLock);
+    Mutex::Autolock _l(mCaptureLock);
     ALOGV("periodicCapture() %p mCaptureCallBack %p mCaptureFlags 0x%08x",
             this, mCaptureCallBack, mCaptureFlags);
     if (mCaptureCallBack != NULL &&
diff --git a/media/libmedia/autodetect.cpp b/media/libmedia/autodetect.cpp
index dfcc6a0..be5c3b2 100644
--- a/media/libmedia/autodetect.cpp
+++ b/media/libmedia/autodetect.cpp
@@ -16,7 +16,7 @@
 
 #include "autodetect.h"
 
-typedef struct CharRange {
+struct CharRange {
     uint16_t first;
     uint16_t last;
 };
diff --git a/media/libmedia/fixedfft.cpp b/media/libmedia/fixedfft.cpp
deleted file mode 100644
index 2b495e6..0000000
--- a/media/libmedia/fixedfft.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* A Fixed point implementation of Fast Fourier Transform (FFT). Complex numbers
- * are represented by 32-bit integers, where higher 16 bits are real part and
- * lower ones are imaginary part. Few compromises are made between efficiency,
- * accuracy, and maintainability. To make it fast, arithmetic shifts are used
- * instead of divisions, and bitwise inverses are used instead of negates. To
- * keep it small, only radix-2 Cooley-Tukey algorithm is implemented, and only
- * half of the twiddle factors are stored. Although there are still ways to make
- * it even faster or smaller, it costs too much on one of the aspects.
- */
-
-#include <stdio.h>
-#include <stdint.h>
-#ifdef __arm__
-#include <machine/cpu-features.h>
-#endif
-
-#define LOG_FFT_SIZE 10
-#define MAX_FFT_SIZE (1 << LOG_FFT_SIZE)
-
-static const int32_t twiddle[MAX_FFT_SIZE / 4] = {
-    0x00008000, 0xff378001, 0xfe6e8002, 0xfda58006, 0xfcdc800a, 0xfc13800f,
-    0xfb4a8016, 0xfa81801e, 0xf9b88027, 0xf8ef8032, 0xf827803e, 0xf75e804b,
-    0xf6958059, 0xf5cd8068, 0xf5058079, 0xf43c808b, 0xf374809e, 0xf2ac80b2,
-    0xf1e480c8, 0xf11c80de, 0xf05580f6, 0xef8d8110, 0xeec6812a, 0xedff8146,
-    0xed388163, 0xec718181, 0xebab81a0, 0xeae481c1, 0xea1e81e2, 0xe9588205,
-    0xe892822a, 0xe7cd824f, 0xe7078276, 0xe642829d, 0xe57d82c6, 0xe4b982f1,
-    0xe3f4831c, 0xe3308349, 0xe26d8377, 0xe1a983a6, 0xe0e683d6, 0xe0238407,
-    0xdf61843a, 0xde9e846e, 0xdddc84a3, 0xdd1b84d9, 0xdc598511, 0xdb998549,
-    0xdad88583, 0xda1885be, 0xd95885fa, 0xd8988637, 0xd7d98676, 0xd71b86b6,
-    0xd65c86f6, 0xd59e8738, 0xd4e1877b, 0xd42487c0, 0xd3678805, 0xd2ab884c,
-    0xd1ef8894, 0xd13488dd, 0xd0798927, 0xcfbe8972, 0xcf0489be, 0xce4b8a0c,
-    0xcd928a5a, 0xccd98aaa, 0xcc218afb, 0xcb698b4d, 0xcab28ba0, 0xc9fc8bf5,
-    0xc9468c4a, 0xc8908ca1, 0xc7db8cf8, 0xc7278d51, 0xc6738dab, 0xc5c08e06,
-    0xc50d8e62, 0xc45b8ebf, 0xc3a98f1d, 0xc2f88f7d, 0xc2488fdd, 0xc198903e,
-    0xc0e990a1, 0xc03a9105, 0xbf8c9169, 0xbedf91cf, 0xbe329236, 0xbd86929e,
-    0xbcda9307, 0xbc2f9371, 0xbb8593dc, 0xbadc9448, 0xba3394b5, 0xb98b9523,
-    0xb8e39592, 0xb83c9603, 0xb7969674, 0xb6f196e6, 0xb64c9759, 0xb5a897ce,
-    0xb5059843, 0xb46298b9, 0xb3c09930, 0xb31f99a9, 0xb27f9a22, 0xb1df9a9c,
-    0xb1409b17, 0xb0a29b94, 0xb0059c11, 0xaf689c8f, 0xaecc9d0e, 0xae319d8e,
-    0xad979e0f, 0xacfd9e91, 0xac659f14, 0xabcd9f98, 0xab36a01c, 0xaaa0a0a2,
-    0xaa0aa129, 0xa976a1b0, 0xa8e2a238, 0xa84fa2c2, 0xa7bda34c, 0xa72ca3d7,
-    0xa69ca463, 0xa60ca4f0, 0xa57ea57e, 0xa4f0a60c, 0xa463a69c, 0xa3d7a72c,
-    0xa34ca7bd, 0xa2c2a84f, 0xa238a8e2, 0xa1b0a976, 0xa129aa0a, 0xa0a2aaa0,
-    0xa01cab36, 0x9f98abcd, 0x9f14ac65, 0x9e91acfd, 0x9e0fad97, 0x9d8eae31,
-    0x9d0eaecc, 0x9c8faf68, 0x9c11b005, 0x9b94b0a2, 0x9b17b140, 0x9a9cb1df,
-    0x9a22b27f, 0x99a9b31f, 0x9930b3c0, 0x98b9b462, 0x9843b505, 0x97ceb5a8,
-    0x9759b64c, 0x96e6b6f1, 0x9674b796, 0x9603b83c, 0x9592b8e3, 0x9523b98b,
-    0x94b5ba33, 0x9448badc, 0x93dcbb85, 0x9371bc2f, 0x9307bcda, 0x929ebd86,
-    0x9236be32, 0x91cfbedf, 0x9169bf8c, 0x9105c03a, 0x90a1c0e9, 0x903ec198,
-    0x8fddc248, 0x8f7dc2f8, 0x8f1dc3a9, 0x8ebfc45b, 0x8e62c50d, 0x8e06c5c0,
-    0x8dabc673, 0x8d51c727, 0x8cf8c7db, 0x8ca1c890, 0x8c4ac946, 0x8bf5c9fc,
-    0x8ba0cab2, 0x8b4dcb69, 0x8afbcc21, 0x8aaaccd9, 0x8a5acd92, 0x8a0cce4b,
-    0x89becf04, 0x8972cfbe, 0x8927d079, 0x88ddd134, 0x8894d1ef, 0x884cd2ab,
-    0x8805d367, 0x87c0d424, 0x877bd4e1, 0x8738d59e, 0x86f6d65c, 0x86b6d71b,
-    0x8676d7d9, 0x8637d898, 0x85fad958, 0x85beda18, 0x8583dad8, 0x8549db99,
-    0x8511dc59, 0x84d9dd1b, 0x84a3dddc, 0x846ede9e, 0x843adf61, 0x8407e023,
-    0x83d6e0e6, 0x83a6e1a9, 0x8377e26d, 0x8349e330, 0x831ce3f4, 0x82f1e4b9,
-    0x82c6e57d, 0x829de642, 0x8276e707, 0x824fe7cd, 0x822ae892, 0x8205e958,
-    0x81e2ea1e, 0x81c1eae4, 0x81a0ebab, 0x8181ec71, 0x8163ed38, 0x8146edff,
-    0x812aeec6, 0x8110ef8d, 0x80f6f055, 0x80def11c, 0x80c8f1e4, 0x80b2f2ac,
-    0x809ef374, 0x808bf43c, 0x8079f505, 0x8068f5cd, 0x8059f695, 0x804bf75e,
-    0x803ef827, 0x8032f8ef, 0x8027f9b8, 0x801efa81, 0x8016fb4a, 0x800ffc13,
-    0x800afcdc, 0x8006fda5, 0x8002fe6e, 0x8001ff37,
-};
-
-/* Returns the multiplication of \conj{a} and {b}. */
-static inline int32_t mult(int32_t a, int32_t b)
-{
-#if __ARM_ARCH__ >= 6
-    int32_t t = b;
-    __asm__("smuad  %0, %0, %1"          : "+r" (t) : "r" (a));
-    __asm__("smusdx %0, %0, %1"          : "+r" (b) : "r" (a));
-    __asm__("pkhtb  %0, %0, %1, ASR #16" : "+r" (t) : "r" (b));
-    return t;
-#else
-    return (((a >> 16) * (b >> 16) + (int16_t)a * (int16_t)b) & ~0xFFFF) |
-        ((((a >> 16) * (int16_t)b - (int16_t)a * (b >> 16)) >> 16) & 0xFFFF);
-#endif
-}
-
-static inline int32_t half(int32_t a)
-{
-#if __ARM_ARCH__ >= 6
-    __asm__("shadd16 %0, %0, %1" : "+r" (a) : "r" (0));
-    return a;
-#else
-    return ((a >> 1) & ~0x8000) | (a & 0x8000);
-#endif
-}
-
-void fixed_fft(int n, int32_t *v)
-{
-    int scale = LOG_FFT_SIZE, i, p, r;
-
-    for (r = 0, i = 1; i < n; ++i) {
-        for (p = n; !(p & r); p >>= 1, r ^= p);
-        if (i < r) {
-            int32_t t = v[i];
-            v[i] = v[r];
-            v[r] = t;
-        }
-    }
-
-    for (p = 1; p < n; p <<= 1) {
-        --scale;
-
-        for (i = 0; i < n; i += p << 1) {
-            int32_t x = half(v[i]);
-            int32_t y = half(v[i + p]);
-            v[i] = x + y;
-            v[i + p] = x - y;
-        }
-
-        for (r = 1; r < p; ++r) {
-            int32_t w = MAX_FFT_SIZE / 4 - (r << scale);
-            i = w >> 31;
-            w = twiddle[(w ^ i) - i] ^ (i << 16);
-            for (i = r; i < n; i += p << 1) {
-                int32_t x = half(v[i]);
-                int32_t y = mult(w, v[i + p]);
-                v[i] = x - y;
-                v[i + p] = x + y;
-            }
-        }
-    }
-}
-
-void fixed_fft_real(int n, int32_t *v)
-{
-    int scale = LOG_FFT_SIZE, m = n >> 1, i;
-
-    fixed_fft(n, v);
-    for (i = 1; i <= n; i <<= 1, --scale);
-    v[0] = mult(~v[0], 0x80008000);
-    v[m] = half(v[m]);
-
-    for (i = 1; i < n >> 1; ++i) {
-        int32_t x = half(v[i]);
-        int32_t z = half(v[n - i]);
-        int32_t y = z - (x ^ 0xFFFF);
-        x = half(x + (z ^ 0xFFFF));
-        y = mult(y, twiddle[i << scale]);
-        v[i] = x - y;
-        v[n - i] = (x + y) ^ 0xFFFF;
-    }
-}
diff --git a/media/libmedia/mediametadataretriever.cpp b/media/libmedia/mediametadataretriever.cpp
index 88e269f..8d53357 100644
--- a/media/libmedia/mediametadataretriever.cpp
+++ b/media/libmedia/mediametadataretriever.cpp
@@ -35,7 +35,7 @@
 const sp<IMediaPlayerService>& MediaMetadataRetriever::getService()
 {
     Mutex::Autolock lock(sServiceLock);
-    if (sService.get() == 0) {
+    if (sService == 0) {
         sp<IServiceManager> sm = defaultServiceManager();
         sp<IBinder> binder;
         do {
diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp
index 2284927..f1c47dd 100644
--- a/media/libmedia/mediaplayer.cpp
+++ b/media/libmedia/mediaplayer.cpp
@@ -30,7 +30,7 @@
 #include <gui/SurfaceTextureClient.h>
 
 #include <media/mediaplayer.h>
-#include <media/AudioTrack.h>
+#include <media/AudioSystem.h>
 
 #include <surfaceflinger/Surface.h>
 
@@ -478,7 +478,7 @@
     return reset_l();
 }
 
-status_t MediaPlayer::setAudioStreamType(int type)
+status_t MediaPlayer::setAudioStreamType(audio_stream_type_t type)
 {
     ALOGV("MediaPlayer::setAudioStreamType");
     Mutex::Autolock _l(mLock);
@@ -709,7 +709,7 @@
     }
 }
 
-/*static*/ sp<IMemory> MediaPlayer::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
+/*static*/ sp<IMemory> MediaPlayer::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
 {
     ALOGV("decode(%s)", url);
     sp<IMemory> p;
@@ -729,7 +729,7 @@
     notify(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, 0);
 }
 
-/*static*/ sp<IMemory> MediaPlayer::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
+/*static*/ sp<IMemory> MediaPlayer::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
 {
     ALOGV("decode(%d, %lld, %lld)", fd, offset, length);
     sp<IMemory> p;
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index f5cb019..a0c20ae 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -1010,7 +1010,7 @@
     return p->reset();
 }
 
-status_t MediaPlayerService::Client::setAudioStreamType(int type)
+status_t MediaPlayerService::Client::setAudioStreamType(audio_stream_type_t type)
 {
     ALOGV("[%d] setAudioStreamType(%d)", mConnId, type);
     // TODO: for hardware output, call player instead
@@ -1149,7 +1149,7 @@
 
 static size_t kDefaultHeapSize = 1024 * 1024; // 1MB
 
-sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
+sp<IMemory> MediaPlayerService::decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
 {
     ALOGV("decode(%s)", url);
     sp<MemoryBase> mem;
@@ -1197,7 +1197,7 @@
     mem = new MemoryBase(cache->getHeap(), 0, cache->size());
     *pSampleRate = cache->sampleRate();
     *pNumChannels = cache->channelCount();
-    *pFormat = (int)cache->format();
+    *pFormat = cache->format();
     ALOGV("return memory @ %p, sampleRate=%u, channelCount = %d, format = %d", mem->pointer(), *pSampleRate, *pNumChannels, *pFormat);
 
 Exit:
@@ -1205,7 +1205,7 @@
     return mem;
 }
 
-sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat)
+sp<IMemory> MediaPlayerService::decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat)
 {
     ALOGV("decode(%d, %lld, %lld)", fd, offset, length);
     sp<MemoryBase> mem;
@@ -1339,7 +1339,7 @@
 }
 
 status_t MediaPlayerService::AudioOutput::open(
-        uint32_t sampleRate, int channelCount, int format, int bufferCount,
+        uint32_t sampleRate, int channelCount, audio_format_t format, int bufferCount,
         AudioCallback cb, void *cookie)
 {
     mCallback = cb;
@@ -1611,7 +1611,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 status_t MediaPlayerService::AudioCache::open(
-        uint32_t sampleRate, int channelCount, int format, int bufferCount,
+        uint32_t sampleRate, int channelCount, audio_format_t format, int bufferCount,
         AudioCallback cb, void *cookie)
 {
     ALOGV("open(%u, %d, %d, %d)", sampleRate, channelCount, format, bufferCount);
@@ -1621,7 +1621,7 @@
 
     mSampleRate = sampleRate;
     mChannelCount = (uint16_t)channelCount;
-    mFormat = (uint16_t)format;
+    mFormat = format;
     mMsecsPerFrame = 1.e3 / (float) sampleRate;
 
     if (cb != NULL) {
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index 04d9e28..fa71d11 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -34,6 +34,7 @@
 
 namespace android {
 
+class AudioTrack;
 class IMediaRecorder;
 class IMediaMetadataRetriever;
 class IOMX;
@@ -83,7 +84,7 @@
 
         virtual status_t        open(
                 uint32_t sampleRate, int channelCount,
-                int format, int bufferCount,
+                audio_format_t format, int bufferCount,
                 AudioCallback cb, void *cookie);
 
         virtual void            start();
@@ -92,7 +93,7 @@
         virtual void            flush();
         virtual void            pause();
         virtual void            close();
-                void            setAudioStreamType(int streamType) { mStreamType = streamType; }
+                void            setAudioStreamType(audio_stream_type_t streamType) { mStreamType = streamType; }
                 void            setVolume(float left, float right);
                 status_t        setAuxEffectSendLevel(float level);
                 status_t        attachAuxEffect(int effectId);
@@ -108,7 +109,7 @@
         AudioTrack*             mTrack;
         AudioCallback           mCallback;
         void *                  mCallbackCookie;
-        int                     mStreamType;
+        audio_stream_type_t     mStreamType;
         float                   mLeftVolume;
         float                   mRightVolume;
         float                   mMsecsPerFrame;
@@ -139,7 +140,7 @@
         virtual int             getSessionId();
 
         virtual status_t        open(
-                uint32_t sampleRate, int channelCount, int format,
+                uint32_t sampleRate, int channelCount, audio_format_t format,
                 int bufferCount = 1,
                 AudioCallback cb = NULL, void *cookie = NULL);
 
@@ -149,10 +150,10 @@
         virtual void            flush() {}
         virtual void            pause() {}
         virtual void            close() {}
-                void            setAudioStreamType(int streamType) {}
+                void            setAudioStreamType(audio_stream_type_t streamType) {}
                 void            setVolume(float left, float right) {}
                 uint32_t        sampleRate() const { return mSampleRate; }
-                uint32_t        format() const { return (uint32_t)mFormat; }
+                audio_format_t  format() const { return mFormat; }
                 size_t          size() const { return mSize; }
                 status_t        wait();
 
@@ -170,7 +171,7 @@
         sp<MemoryHeapBase>  mHeap;
         float               mMsecsPerFrame;
         uint16_t            mChannelCount;
-        uint16_t            mFormat;
+        audio_format_t      mFormat;
         ssize_t             mFrameCount;
         uint32_t            mSampleRate;
         uint32_t            mSize;
@@ -190,8 +191,8 @@
 
     virtual sp<IMediaPlayer>    create(pid_t pid, const sp<IMediaPlayerClient>& client, int audioSessionId);
 
-    virtual sp<IMemory>         decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
-    virtual sp<IMemory>         decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);
+    virtual sp<IMemory>         decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat);
+    virtual sp<IMemory>         decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, audio_format_t* pFormat);
     virtual sp<IOMX>            getOMX();
 
     virtual status_t            dump(int fd, const Vector<String16>& args);
@@ -259,7 +260,7 @@
         virtual status_t        getCurrentPosition(int* msec);
         virtual status_t        getDuration(int* msec);
         virtual status_t        reset();
-        virtual status_t        setAudioStreamType(int type);
+        virtual status_t        setAudioStreamType(audio_stream_type_t type);
         virtual status_t        setLooping(int loop);
         virtual status_t        setVolume(float leftVolume, float rightVolume);
         virtual status_t        invoke(const Parcel& request, Parcel *reply);
diff --git a/media/libmediaplayerservice/MediaRecorderClient.cpp b/media/libmediaplayerservice/MediaRecorderClient.cpp
index d219fc2..beda945 100644
--- a/media/libmediaplayerservice/MediaRecorderClient.cpp
+++ b/media/libmediaplayerservice/MediaRecorderClient.cpp
@@ -33,8 +33,6 @@
 
 #include <utils/String16.h>
 
-#include <media/AudioTrack.h>
-
 #include <system/audio.h>
 
 #include "MediaRecorderClient.h"
diff --git a/media/libmediaplayerservice/MidiFile.cpp b/media/libmediaplayerservice/MidiFile.cpp
index d89b5f4..7cb8c29 100644
--- a/media/libmediaplayerservice/MidiFile.cpp
+++ b/media/libmediaplayerservice/MidiFile.cpp
@@ -86,7 +86,8 @@
     // create playback thread
     {
         Mutex::Autolock l(mMutex);
-        createThreadEtc(renderThread, this, "midithread", ANDROID_PRIORITY_AUDIO);
+        mThread = new MidiFileThread(this);
+        mThread->run("midithread", ANDROID_PRIORITY_AUDIO);
         mCondition.wait(mMutex);
         ALOGV("thread started");
     }
@@ -427,11 +428,6 @@
     return NO_ERROR;
 }
 
-int MidiFile::renderThread(void* p) {
-
-    return ((MidiFile*)p)->render();
-}
-
 int MidiFile::render() {
     EAS_RESULT result = EAS_FAILURE;
     EAS_I32 count;
diff --git a/media/libmediaplayerservice/MidiFile.h b/media/libmediaplayerservice/MidiFile.h
index 3469389..f6f8f7b 100644
--- a/media/libmediaplayerservice/MidiFile.h
+++ b/media/libmediaplayerservice/MidiFile.h
@@ -19,11 +19,11 @@
 #define ANDROID_MIDIFILE_H
 
 #include <media/MediaPlayerInterface.h>
-#include <media/AudioTrack.h>
 #include <libsonivox/eas.h>
 
 namespace android {
 
+// Note that the name MidiFile is misleading; this actually represents a MIDI file player
 class MidiFile : public MediaPlayerInterface {
 public:
                         MidiFile();
@@ -65,7 +65,6 @@
 private:
             status_t    createOutputTrack();
             status_t    reset_nosync();
-    static  int         renderThread(void*);
             int         render();
             void        updateState(){ EAS_State(mEasData, mEasHandle, &mState); }
 
@@ -78,12 +77,35 @@
     EAS_I32             mDuration;
     EAS_STATE           mState;
     EAS_FILE            mFileLocator;
-    int                 mStreamType;
+    audio_stream_type_t mStreamType;
     bool                mLoop;
     volatile bool       mExit;
     bool                mPaused;
     volatile bool       mRender;
     pid_t               mTid;
+
+    class MidiFileThread : public Thread {
+    public:
+        MidiFileThread(MidiFile *midiPlayer) : mMidiFile(midiPlayer) {
+        }
+
+    protected:
+        virtual ~MidiFileThread() {}
+
+    private:
+        MidiFile *mMidiFile;
+
+        bool threadLoop() {
+            int result;
+            result = mMidiFile->render();
+            return false;
+        }
+
+        MidiFileThread(const MidiFileThread &);
+        MidiFileThread &operator=(const MidiFileThread &);
+    };
+
+    sp<MidiFileThread> mThread;
 };
 
 }; // namespace android
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index a00aaa5..b731d0f 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -480,7 +480,7 @@
                 // completed.
 
                 ALOGV("postponing reset mFlushingAudio=%d, mFlushingVideo=%d",
-                        mFlushingAudio, mFlushingVideo);
+                      mFlushingAudio, mFlushingVideo);
 
                 mResetPostponed = true;
                 break;
@@ -690,7 +690,7 @@
                 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
 
                 ALOGI("%s discontinuity (formatChange=%d, time=%d)",
-                      audio ? "audio" : "video", formatChange, timeChange);
+                     audio ? "audio" : "video", formatChange, timeChange);
 
                 if (audio) {
                     mSkipRenderingAudioUntilMediaTimeUs = -1;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
index 074cb4f..15259cb 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
@@ -376,7 +376,7 @@
     bool tooLate = (mVideoLateByUs > 40000);
 
     if (tooLate) {
-        ALOGV("video late by %lld us (%.2f secs)", lateByUs, lateByUs / 1E6);
+        ALOGV("video late by %lld us (%.2f secs)", mVideoLateByUs, mVideoLateByUs / 1E6);
     } else {
         ALOGV("rendering video at media time %.2f secs", mediaTimeUs / 1E6);
     }
@@ -629,7 +629,7 @@
     }
 
     ALOGV("now paused audio queue has %d entries, video has %d entries",
-         mAudioQueue.size(), mVideoQueue.size());
+          mAudioQueue.size(), mVideoQueue.size());
 
     mPaused = true;
 }
diff --git a/media/libstagefright/AACExtractor.cpp b/media/libstagefright/AACExtractor.cpp
index 52b1200..33f22f2 100644
--- a/media/libstagefright/AACExtractor.cpp
+++ b/media/libstagefright/AACExtractor.cpp
@@ -22,6 +22,7 @@
 #include "include/avc_utils.h"
 
 #include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/AMessage.h>
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/MediaBufferGroup.h>
 #include <media/stagefright/MediaDebug.h>
@@ -131,18 +132,28 @@
     return frameSize;
 }
 
-AACExtractor::AACExtractor(const sp<DataSource> &source)
+AACExtractor::AACExtractor(
+        const sp<DataSource> &source, const sp<AMessage> &_meta)
     : mDataSource(source),
       mInitCheck(NO_INIT),
       mFrameDurationUs(0) {
-    String8 mimeType;
-    float confidence;
-    if (!SniffAAC(mDataSource, &mimeType, &confidence, NULL)) {
-        return;
+    sp<AMessage> meta = _meta;
+
+    if (meta == NULL) {
+        String8 mimeType;
+        float confidence;
+        sp<AMessage> _meta;
+
+        if (!SniffAAC(mDataSource, &mimeType, &confidence, &meta)) {
+            return;
+        }
     }
 
+    int64_t offset;
+    CHECK(meta->findInt64("offset", &offset));
+
     uint8_t profile, sf_index, channel, header[2];
-    if (mDataSource->readAt(2, &header, 2) < 2) {
+    if (mDataSource->readAt(offset + 2, &header, 2) < 2) {
         return;
     }
 
@@ -156,7 +167,6 @@
 
     mMeta = MakeAACCodecSpecificData(profile, sf_index, channel);
 
-    off64_t offset = 0;
     off64_t streamSize, numFrames = 0;
     size_t frameSize = 0;
     int64_t duration = 0;
@@ -245,7 +255,12 @@
 status_t AACSource::start(MetaData *params) {
     CHECK(!mStarted);
 
-    mOffset = 0;
+    if (mOffsetVector.empty()) {
+        mOffset = 0;
+    } else {
+        mOffset = mOffsetVector.itemAt(0);
+    }
+
     mCurrentTimeUs = 0;
     mGroup = new MediaBufferGroup;
     mGroup->add_buffer(new MediaBuffer(kMaxFrameSize));
@@ -318,10 +333,39 @@
 
 bool SniffAAC(
         const sp<DataSource> &source, String8 *mimeType, float *confidence,
-        sp<AMessage> *) {
+        sp<AMessage> *meta) {
+    off64_t pos = 0;
+
+    for (;;) {
+        uint8_t id3header[10];
+        if (source->readAt(pos, id3header, sizeof(id3header))
+                < (ssize_t)sizeof(id3header)) {
+            return false;
+        }
+
+        if (memcmp("ID3", id3header, 3)) {
+            break;
+        }
+
+        // Skip the ID3v2 header.
+
+        size_t len =
+            ((id3header[6] & 0x7f) << 21)
+            | ((id3header[7] & 0x7f) << 14)
+            | ((id3header[8] & 0x7f) << 7)
+            | (id3header[9] & 0x7f);
+
+        len += 10;
+
+        pos += len;
+
+        ALOGV("skipped ID3 tag, new starting offset is %lld (0x%016llx)",
+             pos, pos);
+    }
+
     uint8_t header[2];
 
-    if (source->readAt(0, &header, 2) != 2) {
+    if (source->readAt(pos, &header, 2) != 2) {
         return false;
     }
 
@@ -329,6 +373,10 @@
     if ((header[0] == 0xff) && ((header[1] & 0xf6) == 0xf0)) {
         *mimeType = MEDIA_MIMETYPE_AUDIO_AAC_ADTS;
         *confidence = 0.2;
+
+        *meta = new AMessage;
+        (*meta)->setInt64("offset", pos);
+
         return true;
     }
 
diff --git a/media/libstagefright/AVIExtractor.cpp b/media/libstagefright/AVIExtractor.cpp
index a3187b7..5a6211e 100644
--- a/media/libstagefright/AVIExtractor.cpp
+++ b/media/libstagefright/AVIExtractor.cpp
@@ -577,6 +577,7 @@
         case FOURCC('a', 'v', 'c', '1'):
         case FOURCC('d', 'a', 'v', 'c'):
         case FOURCC('x', '2', '6', '4'):
+        case FOURCC('H', '2', '6', '4'):
         case FOURCC('v', 's', 's', 'h'):
             return MEDIA_MIMETYPE_VIDEO_AVC;
 
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index 690deac..0aeb515 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -9,6 +9,7 @@
         AACWriter.cpp                     \
         AMRExtractor.cpp                  \
         AMRWriter.cpp                     \
+        AVIExtractor.cpp                  \
         AudioPlayer.cpp                   \
         AudioSource.cpp                   \
         AwesomePlayer.cpp                 \
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index d0cb7ff..8480b6d 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -335,6 +335,14 @@
         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);
@@ -342,8 +350,6 @@
             notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
         }
     }
-
-    return setDataSource_l(extractor);
 }
 
 status_t AwesomePlayer::setDataSource_l(const sp<MediaExtractor> &extractor) {
@@ -2095,7 +2101,7 @@
         String8 mimeType;
         float confidence;
         sp<AMessage> dummy;
-        bool success = SniffDRM(dataSource, &mimeType, &confidence, &dummy);
+        bool success = SniffWVM(dataSource, &mimeType, &confidence, &dummy);
 
         if (!success
                 || strcasecmp(
@@ -2115,13 +2121,8 @@
         }
     }
 
-    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);
-        }
+    if (extractor->getDrmFlag()) {
+        checkDrmStatus(dataSource);
     }
 
     status_t err = setDataSource_l(extractor);
diff --git a/media/libstagefright/DRMExtractor.cpp b/media/libstagefright/DRMExtractor.cpp
index 9452ab1..afc4a80 100644
--- a/media/libstagefright/DRMExtractor.cpp
+++ b/media/libstagefright/DRMExtractor.cpp
@@ -282,13 +282,13 @@
     if (decryptHandle != NULL) {
         if (decryptHandle->decryptApiType == DecryptApiType::CONTAINER_BASED) {
             *mimeType = String8("drm+container_based+") + decryptHandle->mimeType;
+            *confidence = 10.0f;
         } else if (decryptHandle->decryptApiType == DecryptApiType::ELEMENTARY_STREAM_BASED) {
             *mimeType = String8("drm+es_based+") + decryptHandle->mimeType;
-        } else if (decryptHandle->decryptApiType == DecryptApiType::WV_BASED) {
-            *mimeType = MEDIA_MIMETYPE_CONTAINER_WVM;
-            ALOGW("SniffWVM: found match\n");
+            *confidence = 10.0f;
+        } else {
+            return false;
         }
-        *confidence = 10.0f;
 
         return true;
     }
diff --git a/media/libstagefright/DataSource.cpp b/media/libstagefright/DataSource.cpp
index 43539bb..d0a7880 100644
--- a/media/libstagefright/DataSource.cpp
+++ b/media/libstagefright/DataSource.cpp
@@ -15,6 +15,12 @@
  */
 
 #include "include/AMRExtractor.h"
+#include "include/AVIExtractor.h"
+
+#if CHROMIUM_AVAILABLE
+#include "include/DataUriSource.h"
+#endif
+
 #include "include/MP3Extractor.h"
 #include "include/MPEG4Extractor.h"
 #include "include/WAVExtractor.h"
@@ -26,6 +32,7 @@
 #include "include/DRMExtractor.h"
 #include "include/FLACExtractor.h"
 #include "include/AACExtractor.h"
+#include "include/WVMExtractor.h"
 
 #include "matroska/MatroskaExtractor.h"
 
@@ -112,7 +119,9 @@
     RegisterSniffer(SniffMPEG2TS);
     RegisterSniffer(SniffMP3);
     RegisterSniffer(SniffAAC);
+    RegisterSniffer(SniffAVI);
     RegisterSniffer(SniffMPEG2PS);
+    RegisterSniffer(SniffWVM);
 
     char value[PROPERTY_VALUE_MAX];
     if (property_get("drm.service.enabled", value, NULL)
@@ -134,6 +143,10 @@
             return NULL;
         }
         source = new NuCachedSource2(httpSource);
+# if CHROMIUM_AVAILABLE
+    } else if (!strncasecmp("data:", uri, 5)) {
+        source = new DataUriSource(uri);
+#endif
     } else {
         // Assume it's a filename.
         source = new FileSource(uri);
diff --git a/media/libstagefright/FileSource.cpp b/media/libstagefright/FileSource.cpp
index 73cb48c..01f53e4 100644
--- a/media/libstagefright/FileSource.cpp
+++ b/media/libstagefright/FileSource.cpp
@@ -127,7 +127,7 @@
     return OK;
 }
 
-sp<DecryptHandle> FileSource::DrmInitialization() {
+sp<DecryptHandle> FileSource::DrmInitialization(const char *mime) {
     if (mDrmManagerClient == NULL) {
         mDrmManagerClient = new DrmManagerClient();
     }
@@ -138,7 +138,7 @@
 
     if (mDecryptHandle == NULL) {
         mDecryptHandle = mDrmManagerClient->openDecryptSession(
-                mFd, mOffset, mLength);
+                mFd, mOffset, mLength, mime);
     }
 
     if (mDecryptHandle == NULL) {
diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/libstagefright/MPEG4Extractor.cpp
index 22bdd95..bc88015 100644
--- a/media/libstagefright/MPEG4Extractor.cpp
+++ b/media/libstagefright/MPEG4Extractor.cpp
@@ -1372,8 +1372,9 @@
 
             uint32_t type = ntohl(buffer);
             // For the 3GPP file format, the handler-type within the 'hdlr' box
-            // shall be 'text'
-            if (type == FOURCC('t', 'e', 'x', 't')) {
+            // shall be 'text'. We also want to support 'sbtl' handler type
+            // for a practical reason as various MPEG4 containers use it.
+            if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) {
                 mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP);
             }
 
diff --git a/media/libstagefright/MediaExtractor.cpp b/media/libstagefright/MediaExtractor.cpp
index 7b17d65..2171492 100644
--- a/media/libstagefright/MediaExtractor.cpp
+++ b/media/libstagefright/MediaExtractor.cpp
@@ -19,6 +19,7 @@
 #include <utils/Log.h>
 
 #include "include/AMRExtractor.h"
+#include "include/AVIExtractor.h"
 #include "include/MP3Extractor.h"
 #include "include/MPEG4Extractor.h"
 #include "include/WAVExtractor.h"
@@ -109,10 +110,12 @@
         ret = new MatroskaExtractor(source);
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2TS)) {
         ret = new MPEG2TSExtractor(source);
+    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_AVI)) {
+        ret = new AVIExtractor(source);
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WVM)) {
         ret = new WVMExtractor(source);
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC_ADTS)) {
-        ret = new AACExtractor(source);
+        ret = new AACExtractor(source, meta);
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2PS)) {
         ret = new MPEG2PSExtractor(source);
     }
diff --git a/media/libstagefright/NuCachedSource2.cpp b/media/libstagefright/NuCachedSource2.cpp
index 249c298..0957426 100644
--- a/media/libstagefright/NuCachedSource2.cpp
+++ b/media/libstagefright/NuCachedSource2.cpp
@@ -370,6 +370,7 @@
                     && (mSource->flags() & DataSource::kIsHTTPBasedSource)) {
                 ALOGV("Disconnecting at high watermark");
                 static_cast<HTTPBase *>(mSource.get())->disconnect();
+                mFinalStatus = -EAGAIN;
             }
         }
     } else {
@@ -549,7 +550,7 @@
 
     size_t delta = offset - mCacheOffset;
 
-    if (mFinalStatus != OK) {
+    if (mFinalStatus != OK && mNumRetriesLeft == 0) {
         if (delta >= mCache->totalSize()) {
             return mFinalStatus;
         }
@@ -591,7 +592,7 @@
     size_t totalSize = mCache->totalSize();
     CHECK_EQ(mCache->releaseFromStart(totalSize), totalSize);
 
-    mFinalStatus = OK;
+    mNumRetriesLeft = kMaxNumRetries;
     mFetching = true;
 
     return OK;
@@ -603,8 +604,8 @@
     restartPrefetcherIfNecessary_l(true /* ignore low water threshold */);
 }
 
-sp<DecryptHandle> NuCachedSource2::DrmInitialization() {
-    return mSource->DrmInitialization();
+sp<DecryptHandle> NuCachedSource2::DrmInitialization(const char* mime) {
+    return mSource->DrmInitialization(mime);
 }
 
 void NuCachedSource2::getDrmInfo(sp<DecryptHandle> &handle, DrmManagerClient **client) {
diff --git a/media/libstagefright/SampleTable.cpp b/media/libstagefright/SampleTable.cpp
index 8d80d63..d9858d7 100644
--- a/media/libstagefright/SampleTable.cpp
+++ b/media/libstagefright/SampleTable.cpp
@@ -618,26 +618,31 @@
     }
 
     uint32_t left = 0;
-    while (left < mNumSyncSamples) {
-        uint32_t x = mSyncSamples[left];
+    uint32_t right = mNumSyncSamples;
+    while (left < right) {
+        uint32_t center = left + (right - left) / 2;
+        uint32_t x = mSyncSamples[center];
 
-        if (x >= start_sample_index) {
+        if (start_sample_index < x) {
+            right = center;
+        } else if (start_sample_index > x) {
+            left = center + 1;
+        } else {
+            left = center;
             break;
         }
-
-        ++left;
     }
-
     if (left == mNumSyncSamples) {
         if (flags == kFlagAfter) {
             ALOGE("tried to find a sync frame after the last one: %d", left);
             return ERROR_OUT_OF_RANGE;
         }
+        left = left - 1;
     }
 
-    if (left > 0) {
-        --left;
-    }
+    // Now ssi[left] is the sync sample index just before (or at)
+    // start_sample_index.
+    // Also start_sample_index < ssi[left + 1], if left + 1 < mNumSyncSamples.
 
     uint32_t x = mSyncSamples[left];
 
@@ -682,7 +687,11 @@
 
                 x = mSyncSamples[left - 1];
 
-                CHECK(x <= start_sample_index);
+                if (x > start_sample_index) {
+                    // The table of sync sample indices was not sorted
+                    // properly.
+                    return ERROR_MALFORMED;
+                }
             }
             break;
         }
@@ -696,7 +705,11 @@
 
                 x = mSyncSamples[left + 1];
 
-                CHECK(x >= start_sample_index);
+                if (x < start_sample_index) {
+                    // The table of sync sample indices was not sorted
+                    // properly.
+                    return ERROR_MALFORMED;
+                }
             }
 
             break;
diff --git a/media/libstagefright/SurfaceMediaSource.cpp b/media/libstagefright/SurfaceMediaSource.cpp
index 48df058..2233d1b 100644
--- a/media/libstagefright/SurfaceMediaSource.cpp
+++ b/media/libstagefright/SurfaceMediaSource.cpp
@@ -32,6 +32,8 @@
 #include <utils/Log.h>
 #include <utils/String8.h>
 
+#include <private/gui/ComposerService.h>
+
 namespace android {
 
 SurfaceMediaSource::SurfaceMediaSource(uint32_t bufW, uint32_t bufH) :
diff --git a/media/libstagefright/WVMExtractor.cpp b/media/libstagefright/WVMExtractor.cpp
index 2092cb6..1e4e049 100644
--- a/media/libstagefright/WVMExtractor.cpp
+++ b/media/libstagefright/WVMExtractor.cpp
@@ -45,17 +45,12 @@
 static Mutex gWVMutex;
 
 WVMExtractor::WVMExtractor(const sp<DataSource> &source)
-    : mDataSource(source) {
-    {
-        Mutex::Autolock autoLock(gWVMutex);
-        if (gVendorLibHandle == NULL) {
-            gVendorLibHandle = dlopen("libwvm.so", RTLD_NOW);
-        }
+    : mDataSource(source)
+{
+    Mutex::Autolock autoLock(gWVMutex);
 
-        if (gVendorLibHandle == NULL) {
-            ALOGE("Failed to open libwvm.so");
-            return;
-        }
+    if (!getVendorLibHandle()) {
+        return;
     }
 
     typedef WVMLoadableExtractor *(*GetInstanceFunc)(sp<DataSource>);
@@ -64,13 +59,28 @@
                 "_ZN7android11GetInstanceENS_2spINS_10DataSourceEEE");
 
     if (getInstanceFunc) {
+        CHECK(source->DrmInitialization(MEDIA_MIMETYPE_CONTAINER_WVM) != NULL);
         mImpl = (*getInstanceFunc)(source);
         CHECK(mImpl != NULL);
+        setDrmFlag(true);
     } else {
         ALOGE("Failed to locate GetInstance in libwvm.so");
     }
 }
 
+bool WVMExtractor::getVendorLibHandle()
+{
+    if (gVendorLibHandle == NULL) {
+        gVendorLibHandle = dlopen("libwvm.so", RTLD_NOW);
+    }
+
+    if (gVendorLibHandle == NULL) {
+        ALOGE("Failed to open libwvm.so");
+    }
+
+    return gVendorLibHandle != NULL;
+}
+
 WVMExtractor::~WVMExtractor() {
 }
 
@@ -113,5 +123,33 @@
     }
 }
 
+bool SniffWVM(
+    const sp<DataSource> &source, String8 *mimeType, float *confidence,
+        sp<AMessage> *) {
+
+    Mutex::Autolock autoLock(gWVMutex);
+
+    if (!WVMExtractor::getVendorLibHandle()) {
+        return false;
+    }
+
+    typedef WVMLoadableExtractor *(*SnifferFunc)(const sp<DataSource>&);
+    SnifferFunc snifferFunc =
+        (SnifferFunc) dlsym(gVendorLibHandle,
+                            "_ZN7android15IsWidevineMediaERKNS_2spINS_10DataSourceEEE");
+
+    if (snifferFunc) {
+        if ((*snifferFunc)(source)) {
+            *mimeType = MEDIA_MIMETYPE_CONTAINER_WVM;
+            *confidence = 10.0f;
+            return true;
+        }
+    } else {
+        ALOGE("IsWidevineMedia not found in libwvm.so");
+    }
+
+    return false;
+}
+
 } //namespace android
 
diff --git a/media/libstagefright/chromium_http/Android.mk b/media/libstagefright/chromium_http/Android.mk
index 6573e3c..63775f1 100644
--- a/media/libstagefright/chromium_http/Android.mk
+++ b/media/libstagefright/chromium_http/Android.mk
@@ -3,8 +3,9 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:=       \
-        ChromiumHTTPDataSource.cpp        \
-        support.cpp                     \
+        DataUriSource.cpp \
+        ChromiumHTTPDataSource.cpp \
+        support.cpp
 
 LOCAL_C_INCLUDES:= \
         $(JNI_H_INCLUDE) \
diff --git a/media/libstagefright/chromium_http/ChromiumHTTPDataSource.cpp b/media/libstagefright/chromium_http/ChromiumHTTPDataSource.cpp
index 180460b..76f7946 100644
--- a/media/libstagefright/chromium_http/ChromiumHTTPDataSource.cpp
+++ b/media/libstagefright/chromium_http/ChromiumHTTPDataSource.cpp
@@ -259,7 +259,7 @@
     mCondition.broadcast();
 }
 
-sp<DecryptHandle> ChromiumHTTPDataSource::DrmInitialization() {
+sp<DecryptHandle> ChromiumHTTPDataSource::DrmInitialization(const char* mime) {
     Mutex::Autolock autoLock(mLock);
 
     if (mDrmManagerClient == NULL) {
@@ -275,7 +275,7 @@
          * original one
          */
         mDecryptHandle = mDrmManagerClient->openDecryptSession(
-                String8(mURI.c_str()));
+                String8(mURI.c_str()), mime);
     }
 
     if (mDecryptHandle == NULL) {
diff --git a/media/libstagefright/chromium_http/DataUriSource.cpp b/media/libstagefright/chromium_http/DataUriSource.cpp
new file mode 100644
index 0000000..ecf3fa1
--- /dev/null
+++ b/media/libstagefright/chromium_http/DataUriSource.cpp
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <include/DataUriSource.h>
+
+#include <net/base/data_url.h>
+#include <googleurl/src/gurl.h>
+
+
+namespace android {
+
+DataUriSource::DataUriSource(const char *uri) :
+    mDataUri(uri),
+    mInited(NO_INIT) {
+
+    // Copy1: const char *uri -> String8 mDataUri.
+    std::string mimeTypeStr, unusedCharsetStr, dataStr;
+    // Copy2: String8 mDataUri -> std::string
+    const bool ret = net::DataURL::Parse(
+            GURL(std::string(mDataUri.string())),
+            &mimeTypeStr, &unusedCharsetStr, &dataStr);
+    // Copy3: std::string dataStr -> AString mData
+    mData.setTo(dataStr.data(), dataStr.length());
+    mInited = ret ? OK : UNKNOWN_ERROR;
+
+    // The chromium data url implementation defaults to using "text/plain"
+    // if no mime type is specified. We prefer to leave this unspecified
+    // instead, since the mime type is sniffed in most cases.
+    if (mimeTypeStr != "text/plain") {
+        mMimeType = mimeTypeStr.c_str();
+    }
+}
+
+ssize_t DataUriSource::readAt(off64_t offset, void *out, size_t size) {
+    if (mInited != OK) {
+        return mInited;
+    }
+
+    const off64_t length = mData.size();
+    if (offset >= length) {
+        return UNKNOWN_ERROR;
+    }
+
+    const char *dataBuf = mData.c_str();
+    const size_t bytesToCopy =
+            offset + size >= length ? (length - offset) : size;
+
+    if (bytesToCopy > 0) {
+        memcpy(out, dataBuf + offset, bytesToCopy);
+    }
+
+    return bytesToCopy;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/httplive/LiveSession.cpp b/media/libstagefright/httplive/LiveSession.cpp
index 0df66f1..0cddd2e 100644
--- a/media/libstagefright/httplive/LiveSession.cpp
+++ b/media/libstagefright/httplive/LiveSession.cpp
@@ -215,7 +215,9 @@
     mDisconnectPending = false;
 }
 
-status_t LiveSession::fetchFile(const char *url, sp<ABuffer> *out) {
+status_t LiveSession::fetchFile(
+        const char *url, sp<ABuffer> *out,
+        int64_t range_offset, int64_t range_length) {
     *out = NULL;
 
     sp<DataSource> source;
@@ -234,8 +236,18 @@
             }
         }
 
-        status_t err = mHTTPDataSource->connect(
-                url, mExtraHeaders.isEmpty() ? NULL : &mExtraHeaders);
+        KeyedVector<String8, String8> headers = mExtraHeaders;
+        if (range_offset > 0 || range_length >= 0) {
+            headers.add(
+                    String8("Range"),
+                    String8(
+                        StringPrintf(
+                            "bytes=%lld-%s",
+                            range_offset,
+                            range_length < 0
+                                ? "" : StringPrintf("%lld", range_offset + range_length - 1).c_str()).c_str()));
+        }
+        status_t err = mHTTPDataSource->connect(url, &headers);
 
         if (err != OK) {
             return err;
@@ -270,9 +282,21 @@
             buffer = copy;
         }
 
+        size_t maxBytesToRead = bufferRemaining;
+        if (range_length >= 0) {
+            int64_t bytesLeftInRange = range_length - buffer->size();
+            if (bytesLeftInRange < maxBytesToRead) {
+                maxBytesToRead = bytesLeftInRange;
+
+                if (bytesLeftInRange == 0) {
+                    break;
+                }
+            }
+        }
+
         ssize_t n = source->readAt(
                 buffer->size(), buffer->data() + buffer->size(),
-                bufferRemaining);
+                maxBytesToRead);
 
         if (n < 0) {
             return n;
@@ -659,8 +683,15 @@
         explicitDiscontinuity = true;
     }
 
+    int64_t range_offset, range_length;
+    if (!itemMeta->findInt64("range-offset", &range_offset)
+            || !itemMeta->findInt64("range-length", &range_length)) {
+        range_offset = 0;
+        range_length = -1;
+    }
+
     sp<ABuffer> buffer;
-    status_t err = fetchFile(uri.c_str(), &buffer);
+    status_t err = fetchFile(uri.c_str(), &buffer, range_offset, range_length);
     if (err != OK) {
         ALOGE("failed to fetch .ts segment at url '%s'", uri.c_str());
         mDataSource->queueEOS(err);
diff --git a/media/libstagefright/httplive/M3UParser.cpp b/media/libstagefright/httplive/M3UParser.cpp
index 5e30488..7d3cf05 100644
--- a/media/libstagefright/httplive/M3UParser.cpp
+++ b/media/libstagefright/httplive/M3UParser.cpp
@@ -152,6 +152,7 @@
 
     const char *data = (const char *)_data;
     size_t offset = 0;
+    uint64_t segmentRangeOffset = 0;
     while (offset < size) {
         size_t offsetLF = offset;
         while (offsetLF < size && data[offsetLF] != '\n') {
@@ -218,6 +219,24 @@
                 }
                 mIsVariantPlaylist = true;
                 err = parseStreamInf(line, &itemMeta);
+            } else if (line.startsWith("#EXT-X-BYTERANGE")) {
+                if (mIsVariantPlaylist) {
+                    return ERROR_MALFORMED;
+                }
+
+                uint64_t length, offset;
+                err = parseByteRange(line, segmentRangeOffset, &length, &offset);
+
+                if (err == OK) {
+                    if (itemMeta == NULL) {
+                        itemMeta = new AMessage;
+                    }
+
+                    itemMeta->setInt64("range-offset", offset);
+                    itemMeta->setInt64("range-length", length);
+
+                    segmentRangeOffset = offset + length;
+                }
             }
 
             if (err != OK) {
@@ -447,6 +466,52 @@
 }
 
 // static
+status_t M3UParser::parseByteRange(
+        const AString &line, uint64_t curOffset,
+        uint64_t *length, uint64_t *offset) {
+    ssize_t colonPos = line.find(":");
+
+    if (colonPos < 0) {
+        return ERROR_MALFORMED;
+    }
+
+    ssize_t atPos = line.find("@", colonPos + 1);
+
+    AString lenStr;
+    if (atPos < 0) {
+        lenStr = AString(line, colonPos + 1, line.size() - colonPos - 1);
+    } else {
+        lenStr = AString(line, colonPos + 1, atPos - colonPos - 1);
+    }
+
+    lenStr.trim();
+
+    const char *s = lenStr.c_str();
+    char *end;
+    *length = strtoull(s, &end, 10);
+
+    if (s == end || *end != '\0') {
+        return ERROR_MALFORMED;
+    }
+
+    if (atPos >= 0) {
+        AString offStr = AString(line, atPos + 1, line.size() - atPos - 1);
+        offStr.trim();
+
+        const char *s = offStr.c_str();
+        *offset = strtoull(s, &end, 10);
+
+        if (s == end || *end != '\0') {
+            return ERROR_MALFORMED;
+        }
+    } else {
+        *offset = curOffset;
+    }
+
+    return OK;
+}
+
+// static
 status_t M3UParser::ParseInt32(const char *s, int32_t *x) {
     char *end;
     long lval = strtol(s, &end, 10);
diff --git a/media/libstagefright/include/AACExtractor.h b/media/libstagefright/include/AACExtractor.h
index 8e5657b..e98ca82 100644
--- a/media/libstagefright/include/AACExtractor.h
+++ b/media/libstagefright/include/AACExtractor.h
@@ -29,7 +29,7 @@
 
 class AACExtractor : public MediaExtractor {
 public:
-    AACExtractor(const sp<DataSource> &source);
+    AACExtractor(const sp<DataSource> &source, const sp<AMessage> &meta);
 
     virtual size_t countTracks();
     virtual sp<MediaSource> getTrack(size_t index);
diff --git a/media/libstagefright/include/AwesomePlayer.h b/media/libstagefright/include/AwesomePlayer.h
index 0985f47..82c6476 100644
--- a/media/libstagefright/include/AwesomePlayer.h
+++ b/media/libstagefright/include/AwesomePlayer.h
@@ -290,6 +290,7 @@
 
     bool isStreamingHTTP() const;
     void sendCacheStats();
+    void checkDrmStatus(const sp<DataSource>& dataSource);
 
     enum FlagMode {
         SET,
diff --git a/media/libstagefright/include/ChromiumHTTPDataSource.h b/media/libstagefright/include/ChromiumHTTPDataSource.h
index 18f8913..82e08fd 100644
--- a/media/libstagefright/include/ChromiumHTTPDataSource.h
+++ b/media/libstagefright/include/ChromiumHTTPDataSource.h
@@ -43,7 +43,7 @@
     virtual status_t getSize(off64_t *size);
     virtual uint32_t flags();
 
-    virtual sp<DecryptHandle> DrmInitialization();
+    virtual sp<DecryptHandle> DrmInitialization(const char *mime);
 
     virtual void getDrmInfo(sp<DecryptHandle> &handle, DrmManagerClient **client);
 
diff --git a/media/libstagefright/include/DataUriSource.h b/media/libstagefright/include/DataUriSource.h
new file mode 100644
index 0000000..d223c06
--- /dev/null
+++ b/media/libstagefright/include/DataUriSource.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2011 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 DATA_URI_SOURCE_H_
+
+#define DATA_URI_SOURCE_H_
+
+#include <stdio.h>
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/foundation/AString.h>
+
+namespace android {
+
+class DataUriSource : public DataSource {
+public:
+    DataUriSource(const char *uri);
+
+    virtual status_t initCheck() const {
+        return mInited;
+    }
+
+    virtual ssize_t readAt(off64_t offset, void *data, size_t size);
+
+    virtual status_t getSize(off64_t *size) {
+        if (mInited != OK) {
+            return mInited;
+        }
+
+        *size = mData.size();
+        return OK;
+    }
+
+    virtual String8 getUri() {
+        return mDataUri;
+    }
+
+    virtual String8 getMIMEType() const {
+        return mMimeType;
+    }
+
+protected:
+    virtual ~DataUriSource() {
+        // Nothing to delete.
+    }
+
+private:
+    const String8 mDataUri;
+
+    String8 mMimeType;
+    // Use AString because individual bytes may not be valid UTF8 chars.
+    AString mData;
+    status_t mInited;
+
+    // Disallow copy and assign.
+    DataUriSource(const DataUriSource &);
+    DataUriSource &operator=(const DataUriSource &);
+};
+
+}  // namespace android
+
+#endif  // DATA_URI_SOURCE_H_
diff --git a/media/libstagefright/include/LiveSession.h b/media/libstagefright/include/LiveSession.h
index 116ed0e..3a11612 100644
--- a/media/libstagefright/include/LiveSession.h
+++ b/media/libstagefright/include/LiveSession.h
@@ -120,7 +120,10 @@
     void onMonitorQueue();
     void onSeek(const sp<AMessage> &msg);
 
-    status_t fetchFile(const char *url, sp<ABuffer> *out);
+    status_t fetchFile(
+            const char *url, sp<ABuffer> *out,
+            int64_t range_offset = 0, int64_t range_length = -1);
+
     sp<M3UParser> fetchPlaylist(const char *url, bool *unchanged);
     size_t getBandwidthIndex();
 
diff --git a/media/libstagefright/include/M3UParser.h b/media/libstagefright/include/M3UParser.h
index 478582d..e30d6fd 100644
--- a/media/libstagefright/include/M3UParser.h
+++ b/media/libstagefright/include/M3UParser.h
@@ -72,6 +72,10 @@
     static status_t parseCipherInfo(
             const AString &line, sp<AMessage> *meta, const AString &baseURI);
 
+    static status_t parseByteRange(
+            const AString &line, uint64_t curOffset,
+            uint64_t *length, uint64_t *offset);
+
     static status_t ParseInt32(const char *s, int32_t *x);
     static status_t ParseDouble(const char *s, double *x);
 
diff --git a/media/libstagefright/include/NuCachedSource2.h b/media/libstagefright/include/NuCachedSource2.h
index 7a03e7e..c27a29b 100644
--- a/media/libstagefright/include/NuCachedSource2.h
+++ b/media/libstagefright/include/NuCachedSource2.h
@@ -40,7 +40,7 @@
     virtual status_t getSize(off64_t *size);
     virtual uint32_t flags();
 
-    virtual sp<DecryptHandle> DrmInitialization();
+    virtual sp<DecryptHandle> DrmInitialization(const char* mime);
     virtual void getDrmInfo(sp<DecryptHandle> &handle, DrmManagerClient **client);
     virtual String8 getUri();
 
diff --git a/media/libstagefright/include/ThrottledSource.h b/media/libstagefright/include/ThrottledSource.h
index 8928a4a..7fe7c06 100644
--- a/media/libstagefright/include/ThrottledSource.h
+++ b/media/libstagefright/include/ThrottledSource.h
@@ -35,6 +35,11 @@
     virtual status_t getSize(off64_t *size);
     virtual uint32_t flags();
 
+    virtual String8 getMIMEType() const {
+        return mSource->getMIMEType();
+    }
+
+
 private:
     Mutex mLock;
 
diff --git a/media/libstagefright/include/WVMExtractor.h b/media/libstagefright/include/WVMExtractor.h
index deecd25..9f763f9 100644
--- a/media/libstagefright/include/WVMExtractor.h
+++ b/media/libstagefright/include/WVMExtractor.h
@@ -23,6 +23,8 @@
 
 namespace android {
 
+struct AMessage;
+class String8;
 class DataSource;
 
 class WVMLoadableExtractor : public MediaExtractor {
@@ -58,6 +60,8 @@
     // is used.
     void setAdaptiveStreamingMode(bool adaptive);
 
+    static bool getVendorLibHandle();
+
 protected:
     virtual ~WVMExtractor();
 
@@ -69,6 +73,10 @@
     WVMExtractor &operator=(const WVMExtractor &);
 };
 
+bool SniffWVM(
+        const sp<DataSource> &source, String8 *mimeType, float *confidence,
+        sp<AMessage> *);
+
 }  // namespace android
 
 #endif  // DRM_EXTRACTOR_H_
diff --git a/media/libstagefright/rtsp/MyHandler.h b/media/libstagefright/rtsp/MyHandler.h
index 2391c5c..9a7dd70 100644
--- a/media/libstagefright/rtsp/MyHandler.h
+++ b/media/libstagefright/rtsp/MyHandler.h
@@ -122,6 +122,7 @@
           mSetupTracksSuccessful(false),
           mSeekPending(false),
           mFirstAccessUnit(true),
+          mAllTracksHaveTime(false),
           mNTPAnchorUs(-1),
           mMediaAnchorUs(-1),
           mLastMediaTimeUs(0),
@@ -723,6 +724,7 @@
                 mSetupTracksSuccessful = false;
                 mSeekPending = false;
                 mFirstAccessUnit = true;
+                mAllTracksHaveTime = false;
                 mNTPAnchorUs = -1;
                 mMediaAnchorUs = -1;
                 mNumAccessUnitsReceived = 0;
@@ -930,6 +932,7 @@
                     info->mNTPAnchorUs = -1;
                 }
 
+                mAllTracksHaveTime = false;
                 mNTPAnchorUs = -1;
 
                 int64_t timeUs;
@@ -1037,6 +1040,14 @@
                         ALOGW("Never received any data, disconnecting.");
                         (new AMessage('abor', id()))->post();
                     }
+                } else {
+                    if (!mAllTracksHaveTime) {
+                        ALOGW("We received some RTCP packets, but time "
+                              "could not be established on all tracks, now "
+                              "using fake timestamps");
+
+                        fakeTimestamps();
+                    }
                 }
                 break;
             }
@@ -1211,6 +1222,7 @@
     bool mSeekPending;
     bool mFirstAccessUnit;
 
+    bool mAllTracksHaveTime;
     int64_t mNTPAnchorUs;
     int64_t mMediaAnchorUs;
     int64_t mLastMediaTimeUs;
@@ -1357,6 +1369,7 @@
     }
 
     void fakeTimestamps() {
+        mNTPAnchorUs = -1ll;
         for (size_t i = 0; i < mTracks.size(); ++i) {
             onTimeUpdate(i, 0, 0ll);
         }
@@ -1377,6 +1390,21 @@
             mNTPAnchorUs = ntpTimeUs;
             mMediaAnchorUs = mLastMediaTimeUs;
         }
+
+        if (!mAllTracksHaveTime) {
+            bool allTracksHaveTime = true;
+            for (size_t i = 0; i < mTracks.size(); ++i) {
+                TrackInfo *track = &mTracks.editItemAt(i);
+                if (track->mNTPAnchorUs < 0) {
+                    allTracksHaveTime = false;
+                    break;
+                }
+            }
+            if (allTracksHaveTime) {
+                mAllTracksHaveTime = true;
+                ALOGI("Time now established for all tracks.");
+            }
+        }
     }
 
     void onAccessUnitComplete(
@@ -1403,7 +1431,7 @@
 
         TrackInfo *track = &mTracks.editItemAt(trackIndex);
 
-        if (mNTPAnchorUs < 0 || mMediaAnchorUs < 0 || track->mNTPAnchorUs < 0) {
+        if (!mAllTracksHaveTime) {
             ALOGV("storing accessUnit, no time established yet");
             track->mPackets.push_back(accessUnit);
             return;
diff --git a/media/libstagefright/timedtext/TimedTextParser.cpp b/media/libstagefright/timedtext/TimedTextParser.cpp
index 0bada16..caea0a4 100644
--- a/media/libstagefright/timedtext/TimedTextParser.cpp
+++ b/media/libstagefright/timedtext/TimedTextParser.cpp
@@ -128,7 +128,7 @@
  *  Subtitle number
  *  Start time --> End time
  *  Text of subtitle (one or more lines)
- *  Blank line
+ *  Blank lines
  *
  * .srt file example:
  *  1
@@ -143,15 +143,20 @@
         off64_t *offset, int64_t *startTimeUs, TextInfo *info) {
     AString data;
     status_t err;
+
+    // To skip blank lines.
+    do {
+        if ((err = readNextLine(offset, &data)) != OK) {
+            return err;
+        }
+        data.trim();
+    } while(data.empty());
+
+    // Just ignore the first non-blank line which is subtitle sequence number.
+
     if ((err = readNextLine(offset, &data)) != OK) {
         return err;
     }
-
-    // to skip the first line
-    if ((err = readNextLine(offset, &data)) != OK) {
-        return err;
-    }
-
     int hour1, hour2, min1, min2, sec1, sec2, msec1, msec2;
     // the start time format is: hours:minutes:seconds,milliseconds
     // 00:00:24,600 --> 00:00:27,800
diff --git a/media/mediaserver/main_mediaserver.cpp b/media/mediaserver/main_mediaserver.cpp
index f078192..1520c01 100644
--- a/media/mediaserver/main_mediaserver.cpp
+++ b/media/mediaserver/main_mediaserver.cpp
@@ -15,10 +15,7 @@
 ** limitations under the License.
 */
 
-// System headers required for setgroups, etc.
-#include <sys/types.h>
-#include <unistd.h>
-#include <grp.h>
+#define LOG_TAG "mediaserver"
 
 #include <binder/IPCThreadState.h>
 #include <binder/ProcessState.h>
@@ -29,7 +26,6 @@
 #include <CameraService.h>
 #include <MediaPlayerService.h>
 #include <AudioPolicyService.h>
-#include <private/android_filesystem_config.h>
 
 using namespace android;
 
diff --git a/media/mtp/Android.mk b/media/mtp/Android.mk
index e590bab..fc7fc4f 100644
--- a/media/mtp/Android.mk
+++ b/media/mtp/Android.mk
@@ -39,6 +39,9 @@
 
 LOCAL_CFLAGS := -DMTP_DEVICE -DMTP_HOST
 
+# Needed for <bionic_time.h>
+LOCAL_C_INCLUDES := bionic/libc/private
+
 LOCAL_SHARED_LIBRARIES := libutils libcutils libusbhost libbinder
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/services/audioflinger/Android.mk b/services/audioflinger/Android.mk
index fa49592..52834db 100644
--- a/services/audioflinger/Android.mk
+++ b/services/audioflinger/Android.mk
@@ -11,9 +11,11 @@
     AudioPolicyService.cpp
 
 LOCAL_C_INCLUDES := \
-    system/media/audio_effects/include
+    system/media/audio_effects/include \
+    system/media/audio_utils/include
 
 LOCAL_SHARED_LIBRARIES := \
+    libaudioutils \
     libcutils \
     libutils \
     libbinder \
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 697bcdf..c6a9c77 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -35,10 +35,12 @@
 
 #include <cutils/bitops.h>
 #include <cutils/properties.h>
+#include <cutils/compiler.h>
 
 #include <media/AudioTrack.h>
 #include <media/AudioRecord.h>
 #include <media/IMediaPlayerService.h>
+#include <media/IMediaDeathNotifier.h>
 
 #include <private/media/AudioTrackShared.h>
 #include <private/media/AudioEffectShared.h>
@@ -54,6 +56,8 @@
 #include <audio_effects/effect_ns.h>
 #include <audio_effects/effect_aec.h>
 
+#include <audio_utils/primitives.h>
+
 #include <cpustats/ThreadCpuUsage.h>
 #include <powermanager/PowerManager.h>
 // #define DEBUG_CPU_USAGE 10  // log statistics every n wall clock seconds
@@ -63,12 +67,12 @@
 
 namespace android {
 
-static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
-static const char* kHardwareLockedString = "Hardware lock is taken\n";
+static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
+static const char kHardwareLockedString[] = "Hardware lock is taken\n";
 
 //static const nsecs_t kStandbyTimeInNsecs = seconds(3);
 static const float MAX_GAIN = 4096.0f;
-static const float MAX_GAIN_INT = 0x1000;
+static const uint32_t MAX_GAIN_INT = 0x1000;
 
 // retry counts for buffer fill timeout
 // 50 * ~20msecs = 1 second
@@ -80,14 +84,16 @@
 static const int8_t kMaxTrackRetriesDirect = 2;
 
 static const int kDumpLockRetries = 50;
-static const int kDumpLockSleep = 20000;
+static const int kDumpLockSleepUs = 20000;
 
-static const nsecs_t kWarningThrottle = seconds(5);
+// don't warn about blocked writes or record buffer overflows more often than this
+static const nsecs_t kWarningThrottleNs = seconds(5);
 
 // RecordThread loop sleep time upon application overrun or audio HAL read error
 static const int kRecordThreadSleepUs = 5000;
 
-static const nsecs_t kSetParametersTimeout = seconds(2);
+// maximum time to wait for setParameters to complete
+static const nsecs_t kSetParametersTimeoutNs = seconds(2);
 
 // minimum sleep time for the mixer thread loop when tracks are active but in underrun
 static const uint32_t kMinThreadSleepTimeUs = 5000;
@@ -113,11 +119,9 @@
 
 // To collect the amplifier usage
 static void addBatteryData(uint32_t params) {
-    sp<IBinder> binder =
-        defaultServiceManager()->getService(String16("media.player"));
-    sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
-    if (service.get() == NULL) {
-        ALOGW("Cannot connect to the MediaPlayerService for battery tracking");
+    sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
+    if (service == NULL) {
+        // it already logged
         return;
     }
 
@@ -147,7 +151,7 @@
     return rc;
 }
 
-static const char *audio_interfaces[] = {
+static const char * const audio_interfaces[] = {
     "primary",
     "a2dp",
     "usb",
@@ -158,7 +162,7 @@
 
 AudioFlinger::AudioFlinger()
     : BnAudioFlinger(),
-        mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
+        mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
         mBtNrecIsOff(false)
 {
 }
@@ -290,7 +294,7 @@
     const size_t SIZE = 256;
     char buffer[SIZE];
     String8 result;
-    int hardwareStatus = mHardwareStatus;
+    hardware_call_state hardwareStatus = mHardwareStatus;
 
     snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
     result.append(buffer);
@@ -320,14 +324,14 @@
             locked = true;
             break;
         }
-        usleep(kDumpLockSleep);
+        usleep(kDumpLockSleepUs);
     }
     return locked;
 }
 
 status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
 {
-    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
+    if (!checkCallingPermission(String16("android.permission.DUMP"))) {
         dumpPermissionDenial(fd, args);
     } else {
         // get state of hardware lock
@@ -376,9 +380,9 @@
 
 sp<IAudioTrack> AudioFlinger::createTrack(
         pid_t pid,
-        int streamType,
+        audio_stream_type_t streamType,
         uint32_t sampleRate,
-        uint32_t format,
+        audio_format_t format,
         uint32_t channelMask,
         int frameCount,
         uint32_t flags,
@@ -394,8 +398,10 @@
     status_t lStatus;
     int lSessionId;
 
-    if (streamType >= AUDIO_STREAM_CNT) {
-        ALOGE("invalid stream type");
+    // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
+    // but if someone uses binder directly they could bypass that and cause us to crash
+    if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
+        ALOGE("createTrack() invalid stream type %d", streamType);
         lStatus = BAD_VALUE;
         goto Exit;
     }
@@ -427,6 +433,7 @@
                     // prevent same audio session on different output threads
                     uint32_t sessions = t->hasAudioSession(*sessionId);
                     if (sessions & PlaybackThread::TRACK_SESSION) {
+                        ALOGE("createTrack() session ID %d already in use", *sessionId);
                         lStatus = BAD_VALUE;
                         goto Exit;
                     }
@@ -495,13 +502,13 @@
     return thread->channelCount();
 }
 
-uint32_t AudioFlinger::format(int output) const
+audio_format_t AudioFlinger::format(int output) const
 {
     Mutex::Autolock _l(mLock);
     PlaybackThread *thread = checkPlaybackThread_l(output);
     if (thread == NULL) {
         ALOGW("format() unknown thread %d", output);
-        return 0;
+        return AUDIO_FORMAT_INVALID;
     }
     return thread->format();
 }
@@ -558,7 +565,7 @@
     return NO_ERROR;
 }
 
-status_t AudioFlinger::setMode(int mode)
+status_t AudioFlinger::setMode(audio_mode_t mode)
 {
     status_t ret = initCheck();
     if (ret != NO_ERROR) {
@@ -569,7 +576,7 @@
     if (!settingsAllowed()) {
         return PERMISSION_DENIED;
     }
-    if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
+    if (uint32_t(mode) >= AUDIO_MODE_CNT) {
         ALOGW("Illegal value: setMode(%d)", mode);
         return BAD_VALUE;
     }
@@ -641,22 +648,25 @@
 
 float AudioFlinger::masterVolume() const
 {
-    return mMasterVolume;
+    Mutex::Autolock _l(mLock);
+    return masterVolume_l();
 }
 
 bool AudioFlinger::masterMute() const
 {
-    return mMasterMute;
+    Mutex::Autolock _l(mLock);
+    return masterMute_l();
 }
 
-status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
+status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
 {
     // check calling permissions
     if (!settingsAllowed()) {
         return PERMISSION_DENIED;
     }
 
-    if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
+    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
+        ALOGE("setStreamVolume() invalid stream %d", stream);
         return BAD_VALUE;
     }
 
@@ -682,15 +692,16 @@
     return NO_ERROR;
 }
 
-status_t AudioFlinger::setStreamMute(int stream, bool muted)
+status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
 {
     // check calling permissions
     if (!settingsAllowed()) {
         return PERMISSION_DENIED;
     }
 
-    if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
+    if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
         uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
+        ALOGE("setStreamMute() invalid stream %d", stream);
         return BAD_VALUE;
     }
 
@@ -702,9 +713,9 @@
     return NO_ERROR;
 }
 
-float AudioFlinger::streamVolume(int stream, int output) const
+float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
 {
-    if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
+    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
         return 0.0f;
     }
 
@@ -723,9 +734,9 @@
     return volume;
 }
 
-bool AudioFlinger::streamMute(int stream) const
+bool AudioFlinger::streamMute(audio_stream_type_t stream) const
 {
-    if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
+    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
         return true;
     }
 
@@ -790,7 +801,7 @@
         thread = checkPlaybackThread_l(ioHandle);
         if (thread == NULL) {
             thread = checkRecordThread_l(ioHandle);
-        } else if (thread.get() == primaryPlaybackThread_l()) {
+        } else if (thread == primaryPlaybackThread_l()) {
             // indicate output device change to all input threads for pre processing
             AudioParameter param = AudioParameter(keyValuePairs);
             int value;
@@ -838,7 +849,7 @@
     return String8("");
 }
 
-size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
+size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
 {
     status_t ret = initCheck();
     if (ret != NO_ERROR) {
@@ -979,7 +990,7 @@
 AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
     :   Thread(false),
         mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
-        mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
+        mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID), mStandby(false), mId(id), mExiting(false),
         mDevice(device)
 {
     mDeathRecipient = new PMDeathRecipient(this);
@@ -988,7 +999,6 @@
 AudioFlinger::ThreadBase::~ThreadBase()
 {
     mParamCond.broadcast();
-    mNewParameters.clear();
     // do not lock the mutex in destructor
     releaseWakeLock_l();
     if (mPowerManager != 0) {
@@ -999,13 +1009,13 @@
 
 void AudioFlinger::ThreadBase::exit()
 {
-    // keep a strong ref on ourself so that we wont get
+    // keep a strong ref on ourself so that we won't get
     // destroyed in the middle of requestExitAndWait()
     sp <ThreadBase> strongMe = this;
 
     ALOGV("ThreadBase::exit");
     {
-        AutoMutex lock(&mLock);
+        AutoMutex lock(mLock);
         mExiting = true;
         requestExit();
         mWaitWorkCV.signal();
@@ -1023,7 +1033,7 @@
     return (int)mChannelCount;
 }
 
-uint32_t AudioFlinger::ThreadBase::format() const
+audio_format_t AudioFlinger::ThreadBase::format() const
 {
     return mFormat;
 }
@@ -1044,7 +1054,7 @@
     mWaitWorkCV.signal();
     // wait condition with timeout in case the thread loop has exited
     // before the request could be processed
-    if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
+    if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
         status = mParamStatus;
         mWaitWorkCV.signal();
     } else {
@@ -1062,9 +1072,9 @@
 // sendConfigEvent_l() must be called with ThreadBase::mLock held
 void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
 {
-    ConfigEvent *configEvent = new ConfigEvent();
-    configEvent->mEvent = event;
-    configEvent->mParam = param;
+    ConfigEvent configEvent;
+    configEvent.mEvent = event;
+    configEvent.mParam = param;
     mConfigEvents.add(configEvent);
     ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
     mWaitWorkCV.signal();
@@ -1075,15 +1085,14 @@
     mLock.lock();
     while(!mConfigEvents.isEmpty()) {
         ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
-        ConfigEvent *configEvent = mConfigEvents[0];
+        ConfigEvent configEvent = mConfigEvents[0];
         mConfigEvents.removeAt(0);
         // release mLock before locking AudioFlinger mLock: lock order is always
         // AudioFlinger then ThreadBase to avoid cross deadlock
         mLock.unlock();
         mAudioFlinger->mLock.lock();
-        audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
+        audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
         mAudioFlinger->mLock.unlock();
-        delete configEvent;
         mLock.lock();
     }
     mLock.unlock();
@@ -1113,7 +1122,7 @@
     result.append(buffer);
     snprintf(buffer, SIZE, "Format: %d\n", mFormat);
     result.append(buffer);
-    snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
+    snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
     result.append(buffer);
 
     snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
@@ -1130,7 +1139,7 @@
     snprintf(buffer, SIZE, " Index event param\n");
     result.append(buffer);
     for (size_t i = 0; i < mConfigEvents.size(); i++) {
-        snprintf(buffer, SIZE, " %02d    %02d    %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
+        snprintf(buffer, SIZE, " %02d    %02d    %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
         result.append(buffer);
     }
     result.append("\n");
@@ -1367,20 +1376,26 @@
                                              int id,
                                              uint32_t device)
     :   ThreadBase(audioFlinger, id, device),
-        mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
+        mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
         mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
 {
     snprintf(mName, kNameLength, "AudioOut_%d", id);
 
     readOutputParameters();
 
-    mMasterVolume = mAudioFlinger->masterVolume();
-    mMasterMute = mAudioFlinger->masterMute();
+    // Assumes constructor is called by AudioFlinger with it's mLock held,
+    // but it would be safer to explicitly pass these as parameters
+    mMasterVolume = mAudioFlinger->masterVolume_l();
+    mMasterMute = mAudioFlinger->masterMute_l();
 
-    for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
+    // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
+    // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
+    for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
+            stream = (audio_stream_type_t) (stream + 1)) {
         mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
         mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
-        mStreamTypes[stream].valid = true;
+        // initialized by stream_type_t default constructor
+        // mStreamTypes[stream].valid = true;
     }
 }
 
@@ -1478,9 +1493,9 @@
 // PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
 sp<AudioFlinger::PlaybackThread::Track>  AudioFlinger::PlaybackThread::createTrack_l(
         const sp<AudioFlinger::Client>& client,
-        int streamType,
+        audio_stream_type_t streamType,
         uint32_t sampleRate,
-        uint32_t format,
+        audio_format_t format,
         uint32_t channelMask,
         int frameCount,
         const sp<IMemory>& sharedBuffer,
@@ -1526,8 +1541,10 @@
         for (size_t i = 0; i < mTracks.size(); ++i) {
             sp<Track> t = mTracks[i];
             if (t != 0) {
-                if (sessionId == t->sessionId() &&
-                        strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
+                uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
+                if (sessionId == t->sessionId() && strategy != actual) {
+                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
+                            strategy, actual);
                     lStatus = BAD_VALUE;
                     goto Exit;
                 }
@@ -1599,24 +1616,24 @@
     return mMasterMute;
 }
 
-status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
+status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
 {
     mStreamTypes[stream].volume = value;
     return NO_ERROR;
 }
 
-status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
+status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
 {
     mStreamTypes[stream].mute = muted;
     return NO_ERROR;
 }
 
-float AudioFlinger::PlaybackThread::streamVolume(int stream) const
+float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
 {
     return mStreamTypes[stream].volume;
 }
 
-bool AudioFlinger::PlaybackThread::streamMute(int stream) const
+bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
 {
     return mStreamTypes[stream].mute;
 }
@@ -1720,7 +1737,7 @@
     mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
     mChannelCount = (uint16_t)popcount(mChannelMask);
     mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
-    mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
+    mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
     mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
 
     // FIXME - Current mixer implementation only supports stereo output: Always
@@ -1832,7 +1849,7 @@
 
 AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
     :   PlaybackThread(audioFlinger, output, id, device),
-        mAudioMixer(0), mPrevMixerStatus(MIXER_IDLE)
+        mAudioMixer(NULL), mPrevMixerStatus(MIXER_IDLE)
 {
     mType = ThreadBase::MIXER;
     mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
@@ -1923,8 +1940,8 @@
             const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
 
             // put audio hardware into standby after short delay
-            if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
-                        mSuspended) {
+            if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
+                        mSuspended)) {
                 if (!mStandby) {
                     ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
                     mOutput->stream->common.standby(&mOutput->stream->common);
@@ -1946,7 +1963,7 @@
                     acquireWakeLock_l();
 
                     mPrevMixerStatus = MIXER_IDLE;
-                    if (mMasterMute == false) {
+                    if (!mMasterMute) {
                         char value[PROPERTY_VALUE_MAX];
                         property_get("ro.audio.silent", value, "0");
                         if (atoi(value)) {
@@ -1968,9 +1985,9 @@
             // during mixing and effect process as the audio buffers could be deleted
             // or modified if an effect is created or deleted
             lockEffectChains_l(effectChains);
-       }
+        }
 
-        if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
+        if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
             // mix buffers...
             mAudioMixer->process();
             sleepTime = 0;
@@ -2013,11 +2030,11 @@
         }
         // sleepTime == 0 means we must write to audio hardware
         if (sleepTime == 0) {
-             for (size_t i = 0; i < effectChains.size(); i ++) {
-                 effectChains[i]->process_l();
-             }
-             // enable changes in effect chain
-             unlockEffectChains(effectChains);
+            for (size_t i = 0; i < effectChains.size(); i ++) {
+                effectChains[i]->process_l();
+            }
+            // enable changes in effect chain
+            unlockEffectChains(effectChains);
             mLastWriteTime = systemTime();
             mInWrite = true;
             mBytesWritten += mixBufferSize;
@@ -2030,7 +2047,7 @@
             nsecs_t delta = now - mLastWriteTime;
             if (!mStandby && delta > maxPeriod) {
                 mNumDelayedWrites++;
-                if ((now - lastWarning) > kWarningThrottle) {
+                if ((now - lastWarning) > kWarningThrottleNs) {
                     ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
                             ns2ms(delta), mNumDelayedWrites, this);
                     lastWarning = now;
@@ -2095,12 +2112,13 @@
         sp<Track> t = activeTracks[i].promote();
         if (t == 0) continue;
 
+        // this const just means the local variable doesn't change
         Track* const track = t.get();
         audio_track_cblk_t* cblk = track->cblk();
 
         // The first time a track is added we wait
         // for all its buffers to be filled before processing it
-        mAudioMixer->setActiveTrack(track->name());
+        int name = track->name();
         // make sure that we have enough frames to mix one full buffer.
         // enforce this condition only once to enable draining the buffer in case the client
         // app does not call stop() and relies on underrun to stop:
@@ -2120,13 +2138,13 @@
                 // the minimum track buffer size is normally twice the number of frames necessary
                 // to fill one buffer and the resampler should not leave more than one buffer worth
                 // of unreleased frames after each pass, but just in case...
-                LOG_ASSERT(minFrames <= cblk->frameCount);
+                ALOG_ASSERT(minFrames <= cblk->frameCount);
             }
         }
         if ((cblk->framesReady() >= minFrames) && track->isReady() &&
                 !track->isPaused() && !track->isTerminated())
         {
-            //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
+            //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
 
             mixedTracks++;
 
@@ -2139,8 +2157,8 @@
                 if (chain != 0) {
                     tracksWithEffect++;
                 } else {
-                    ALOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
-                            track->name(), track->sessionId());
+                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
+                            name, track->sessionId());
                 }
             }
 
@@ -2153,7 +2171,7 @@
                     track->mState = TrackBase::ACTIVE;
                     param = AudioMixer::RAMP_VOLUME;
                 }
-                mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
+                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
             } else if (cblk->server != 0) {
                 // If the track is stopped before the first frame was mixed,
                 // do not apply ramp
@@ -2173,10 +2191,31 @@
                 // read original volumes with volume control
                 float typeVolume = mStreamTypes[track->type()].volume;
                 float v = masterVolume * typeVolume;
-                vl = (uint32_t)(v * cblk->volume[0]) << 12;
-                vr = (uint32_t)(v * cblk->volume[1]) << 12;
+                uint32_t vlr = cblk->volumeLR;
+                vl = vlr & 0xFFFF;
+                vr = vlr >> 16;
+                // track volumes come from shared memory, so can't be trusted and must be clamped
+                if (vl > MAX_GAIN_INT) {
+                    ALOGV("Track left volume out of range: %04X", vl);
+                    vl = MAX_GAIN_INT;
+                }
+                if (vr > MAX_GAIN_INT) {
+                    ALOGV("Track right volume out of range: %04X", vr);
+                    vr = MAX_GAIN_INT;
+                }
+                // now apply the master volume and stream type volume
+                vl = (uint32_t)(v * vl) << 12;
+                vr = (uint32_t)(v * vr) << 12;
+                // assuming master volume and stream type volume each go up to 1.0,
+                // vl and vr are now in 8.24 format
 
-                va = (uint32_t)(v * cblk->sendLevel);
+                uint16_t sendLevel = cblk->getSendLevel_U4_12();
+                // send level comes from shared memory and so may be corrupt
+                if (sendLevel >= MAX_GAIN_INT) {
+                    ALOGV("Track send level out of range: %04X", sendLevel);
+                    sendLevel = MAX_GAIN_INT;
+                }
+                va = (uint32_t)(v * sendLevel);
             }
             // Delegate volume control to effect in track effect chain if needed
             if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
@@ -2194,6 +2233,7 @@
 
             // Convert volumes from 8.24 to 4.12 format
             int16_t left, right, aux;
+            // This additional clamping is needed in case chain->setVolume_l() overshot
             uint32_t v_clamped = (vl + (1 << 11)) >> 12;
             if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
             left = int16_t(v_clamped);
@@ -2205,26 +2245,31 @@
             aux = int16_t(va);
 
             // XXX: these things DON'T need to be done each time
-            mAudioMixer->setBufferProvider(track);
-            mAudioMixer->enable(AudioMixer::MIXING);
+            mAudioMixer->setBufferProvider(name, track);
+            mAudioMixer->enable(name);
 
-            mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
-            mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
-            mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
+            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
+            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
+            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
             mAudioMixer->setParameter(
+                name,
                 AudioMixer::TRACK,
                 AudioMixer::FORMAT, (void *)track->format());
             mAudioMixer->setParameter(
+                name,
                 AudioMixer::TRACK,
                 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
             mAudioMixer->setParameter(
+                name,
                 AudioMixer::RESAMPLE,
                 AudioMixer::SAMPLE_RATE,
                 (void *)(cblk->sampleRate));
             mAudioMixer->setParameter(
+                name,
                 AudioMixer::TRACK,
                 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
             mAudioMixer->setParameter(
+                name,
                 AudioMixer::TRACK,
                 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
 
@@ -2238,7 +2283,7 @@
                 mixerStatus = MIXER_TRACKS_READY;
             }
         } else {
-            //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
+            //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
             if (track->isStopped()) {
                 track->reset();
             }
@@ -2250,7 +2295,7 @@
                 // No buffers for this track. Give it a few chances to
                 // fill a buffer, then remove it from active list.
                 if (--(track->mRetryCount) <= 0) {
-                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
+                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
                     tracksToRemove->add(track);
                     // indicate to client process that the track was disabled because of underrun
                     android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
@@ -2262,13 +2307,13 @@
                     mixerStatus = MIXER_TRACKS_ENABLED;
                 }
             }
-            mAudioMixer->disable(AudioMixer::MIXING);
+            mAudioMixer->disable(name);
         }
     }
 
     // remove all the tracks that need to be...
     count = tracksToRemove->size();
-    if (UNLIKELY(count)) {
+    if (CC_UNLIKELY(count)) {
         for (size_t i=0 ; i<count ; i++) {
             const sp<Track>& track = tracksToRemove->itemAt(i);
             mActiveTracks.remove(track);
@@ -2296,7 +2341,7 @@
     return mixerStatus;
 }
 
-void AudioFlinger::MixerThread::invalidateTracks(int streamType)
+void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
 {
     ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
             this,  streamType, mTracks.size());
@@ -2312,7 +2357,7 @@
     }
 }
 
-void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
+void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
 {
     ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
             this,  streamType, valid);
@@ -2349,7 +2394,7 @@
             reconfig = true;
         }
         if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
-            if (value != AUDIO_FORMAT_PCM_16_BIT) {
+            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
                 status = BAD_VALUE;
             } else {
                 reconfig = true;
@@ -2364,7 +2409,7 @@
         }
         if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
             // do not accept frame count changes if tracks are open as the track buffer
-            // size depends on frame count and correct behavior would not be garantied
+            // size depends on frame count and correct behavior would not be guaranteed
             // if frame count is changed after track creation
             if (!mTracks.isEmpty()) {
                 status = INVALID_OPERATION;
@@ -2435,7 +2480,7 @@
         mParamCond.signal();
         // wait for condition with time out in case the thread calling ThreadBase::setParameters()
         // already timed out waiting for the status and will never signal the condition.
-        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
+        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
     }
     return reconfig;
 }
@@ -2475,14 +2520,6 @@
 {
 }
 
-
-static inline int16_t clamp16(int32_t sample)
-{
-    if ((sample>>15) ^ (sample>>31))
-        sample = 0x7FFF ^ (sample>>31);
-    return sample;
-}
-
 static inline
 int32_t mul(int16_t in, int16_t v)
 {
@@ -2612,8 +2649,8 @@
             }
 
             // put audio hardware into standby after short delay
-            if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
-                        mSuspended) {
+            if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
+                        mSuspended)) {
                 // wait until we have something to do...
                 if (!mStandby) {
                     ALOGV("Audio hardware entering standby, mixer %p\n", this);
@@ -2634,7 +2671,7 @@
                     ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
                     acquireWakeLock_l();
 
-                    if (mMasterMute == false) {
+                    if (!mMasterMute) {
                         char value[PROPERTY_VALUE_MAX];
                         property_get("ro.audio.silent", value, "0");
                         if (atoi(value)) {
@@ -2690,10 +2727,11 @@
                     } else {
                         float typeVolume = mStreamTypes[track->type()].volume;
                         float v = mMasterVolume * typeVolume;
-                        float v_clamped = v * cblk->volume[0];
+                        uint32_t vlr = cblk->volumeLR;
+                        float v_clamped = v * (vlr & 0xFFFF);
                         if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
                         left = v_clamped/MAX_GAIN;
-                        v_clamped = v * cblk->volume[1];
+                        v_clamped = v * (vlr >> 16);
                         if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
                         right = v_clamped/MAX_GAIN;
                     }
@@ -2763,7 +2801,7 @@
             }
 
             // remove all the tracks that need to be...
-            if (UNLIKELY(trackToRemove != 0)) {
+            if (CC_UNLIKELY(trackToRemove != 0)) {
                 mActiveTracks.remove(trackToRemove);
                 if (!effectChains.isEmpty()) {
                     ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
@@ -2778,7 +2816,7 @@
             lockEffectChains_l(effectChains);
        }
 
-        if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
+        if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
             AudioBufferProvider::Buffer buffer;
             size_t frameCount = mFrameCount;
             curBuf = (int8_t *)mMixBuffer;
@@ -2786,7 +2824,7 @@
             while (frameCount) {
                 buffer.frameCount = frameCount;
                 activeTrack->getNextBuffer(&buffer);
-                if (UNLIKELY(buffer.raw == 0)) {
+                if (CC_UNLIKELY(buffer.raw == NULL)) {
                     memset(curBuf, 0, frameCount * mFrameSize);
                     break;
                 }
@@ -2911,7 +2949,7 @@
         mParamCond.signal();
         // wait for condition with time out in case the thread calling ThreadBase::setParameters()
         // already timed out waiting for the status and will never signal the condition.
-        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
+        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
     }
     return reconfig;
 }
@@ -3005,8 +3043,8 @@
             }
 
             // put audio hardware into standby after short delay
-            if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
-                         mSuspended) {
+            if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
+                         mSuspended)) {
                 if (!mStandby) {
                     for (size_t i = 0; i < outputTracks.size(); i++) {
                         outputTracks[i]->stop();
@@ -3029,7 +3067,7 @@
                     acquireWakeLock_l();
 
                     mPrevMixerStatus = MIXER_IDLE;
-                    if (mMasterMute == false) {
+                    if (!mMasterMute) {
                         char value[PROPERTY_VALUE_MAX];
                         property_get("ro.audio.silent", value, "0");
                         if (atoi(value)) {
@@ -3052,7 +3090,7 @@
             lockEffectChains_l(effectChains);
         }
 
-        if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
+        if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
             // mix buffers...
             if (outputsReady(outputTracks)) {
                 mAudioMixer->process();
@@ -3195,7 +3233,7 @@
             const wp<ThreadBase>& thread,
             const sp<Client>& client,
             uint32_t sampleRate,
-            uint32_t format,
+            audio_format_t format,
             uint32_t channelMask,
             int frameCount,
             uint32_t flags,
@@ -3251,7 +3289,7 @@
         }
    } else {
        mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
-       if (mCblk) { // construct the shared structure in-place.
+           // construct the shared structure in-place.
            new(mCblk) audio_track_cblk_t();
            // clear all buffers
            mCblk->frameCount = frameCount;
@@ -3264,7 +3302,6 @@
            // written to buffer (other flags are cleared)
            mCblk->flags = CBLK_UNDERRUN_ON;
            mBufferEnd = (uint8_t *)mBuffer + bufferSize;
-       }
    }
 }
 
@@ -3285,7 +3322,7 @@
 
 void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
 {
-    buffer->raw = 0;
+    buffer->raw = NULL;
     mFrameCount = buffer->frameCount;
     step();
     buffer->frameCount = 0;
@@ -3333,12 +3370,13 @@
 
 void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
     audio_track_cblk_t* cblk = this->cblk();
-    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
-    int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
+    size_t frameSize = cblk->frameSize;
+    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
+    int8_t *bufferEnd = bufferStart + frames * frameSize;
 
     // Check validity of returned pointer in case the track control block would have been corrupted.
     if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
-        ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
+        ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
         ALOGE("TrackBase::getBuffer buffer out of range:\n    start: %p, end %p , mBuffer %p mBufferEnd %p\n    \
                 server %d, serverBase %d, user %d, userBase %d",
                 bufferStart, bufferEnd, mBuffer, mBufferEnd,
@@ -3355,9 +3393,9 @@
 AudioFlinger::PlaybackThread::Track::Track(
             const wp<ThreadBase>& thread,
             const sp<Client>& client,
-            int streamType,
+            audio_stream_type_t streamType,
             uint32_t sampleRate,
-            uint32_t format,
+            audio_format_t format,
             uint32_t channelMask,
             int frameCount,
             const sp<IMemory>& sharedBuffer,
@@ -3377,8 +3415,6 @@
         if (mName < 0) {
             ALOGE("no more track names available");
         }
-        mVolume[0] = 1.0f;
-        mVolume[1] = 1.0f;
         mStreamType = streamType;
         // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
         // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
@@ -3430,6 +3466,7 @@
 
 void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
 {
+    uint32_t vlr = mCblk->volumeLR;
     snprintf(buffer, size, "   %05d %05d %03u %03u 0x%08x %05u   %04u %1d %1d %1d %05u %05u %05u  0x%08x 0x%08x 0x%08x 0x%08x\n",
             mName - AudioMixer::TRACK0,
             (mClient == NULL) ? getpid() : mClient->pid(),
@@ -3442,8 +3479,8 @@
             mMute,
             mFillingUpStatus,
             mCblk->sampleRate,
-            mCblk->volume[0],
-            mCblk->volume[1],
+            vlr & 0xFFFF,
+            vlr >> 16,
             mCblk->server,
             mCblk->user,
             (int)mMainBuffer,
@@ -3465,7 +3502,7 @@
 
      framesReady = cblk->framesReady();
 
-     if (LIKELY(framesReady)) {
+     if (CC_LIKELY(framesReady)) {
         uint32_t s = cblk->server;
         uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
 
@@ -3478,14 +3515,14 @@
         }
 
          buffer->raw = getBuffer(s, framesReq);
-         if (buffer->raw == 0) goto getNextBuffer_exit;
+         if (buffer->raw == NULL) goto getNextBuffer_exit;
 
          buffer->frameCount = framesReq;
         return NO_ERROR;
      }
 
 getNextBuffer_exit:
-     buffer->raw = 0;
+     buffer->raw = NULL;
      buffer->frameCount = 0;
      ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
      return NOT_ENOUGH_DATA;
@@ -3640,12 +3677,6 @@
     mMute = muted;
 }
 
-void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
-{
-    mVolume[0] = left;
-    mVolume[1] = right;
-}
-
 status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
 {
     status_t status = DEAD_OBJECT;
@@ -3670,7 +3701,7 @@
             const wp<ThreadBase>& thread,
             const sp<Client>& client,
             uint32_t sampleRate,
-            uint32_t format,
+            audio_format_t format,
             uint32_t channelMask,
             int frameCount,
             uint32_t flags,
@@ -3714,7 +3745,7 @@
 
     framesAvail = cblk->framesAvailable_l();
 
-    if (LIKELY(framesAvail)) {
+    if (CC_LIKELY(framesAvail)) {
         uint32_t s = cblk->server;
         uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
 
@@ -3726,14 +3757,14 @@
         }
 
         buffer->raw = getBuffer(s, framesReq);
-        if (buffer->raw == 0) goto getNextBuffer_exit;
+        if (buffer->raw == NULL) goto getNextBuffer_exit;
 
         buffer->frameCount = framesReq;
         return NO_ERROR;
     }
 
 getNextBuffer_exit:
-    buffer->raw = 0;
+    buffer->raw = NULL;
     buffer->frameCount = 0;
     return NOT_ENOUGH_DATA;
 }
@@ -3783,7 +3814,7 @@
             const wp<ThreadBase>& thread,
             DuplicatingThread *sourceThread,
             uint32_t sampleRate,
-            uint32_t format,
+            audio_format_t format,
             uint32_t channelMask,
             int frameCount)
     :   Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
@@ -3794,7 +3825,7 @@
     if (mCblk != NULL) {
         mCblk->flags |= CBLK_DIRECTION_OUT;
         mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
-        mCblk->volume[0] = mCblk->volume[1] = 0x1000;
+        mCblk->volumeLR = (MAX_GAIN_INT << 16) | MAX_GAIN_INT;
         mOutBuffer.frameCount = 0;
         playbackThread->mTracks.add(this);
         ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
@@ -3967,7 +3998,7 @@
         goto start_loop_here;
         while (framesAvail == 0) {
             active = mActive;
-            if (UNLIKELY(!active)) {
+            if (CC_UNLIKELY(!active)) {
                 ALOGV("Not active and NO_MORE_BUFFERS");
                 return AudioTrack::NO_MORE_BUFFERS;
             }
@@ -4095,10 +4126,6 @@
     mTrack->pause();
 }
 
-void AudioFlinger::TrackHandle::setVolume(float left, float right) {
-    mTrack->setVolume(left, right);
-}
-
 sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
     return mTrack->getCblk();
 }
@@ -4120,7 +4147,7 @@
         pid_t pid,
         int input,
         uint32_t sampleRate,
-        uint32_t format,
+        audio_format_t format,
         uint32_t channelMask,
         int frameCount,
         uint32_t flags,
@@ -4238,7 +4265,7 @@
                                          int id,
                                          uint32_t device) :
     ThreadBase(audioFlinger, id, device),
-    mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
+    mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
 {
     mType = ThreadBase::RECORD;
 
@@ -4253,7 +4280,7 @@
 AudioFlinger::RecordThread::~RecordThread()
 {
     delete[] mRsmpInBuffer;
-    if (mResampler != 0) {
+    if (mResampler != NULL) {
         delete mResampler;
         delete[] mRsmpOutBuffer;
     }
@@ -4345,9 +4372,9 @@
             }
 
             buffer.frameCount = mFrameCount;
-            if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
+            if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
                 size_t framesOut = buffer.frameCount;
-                if (mResampler == 0) {
+                if (mResampler == NULL) {
                     // no resampling
                     while (framesOut) {
                         size_t framesIn = mFrameCount - mRsmpInIndex;
@@ -4412,7 +4439,7 @@
                     // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
                     // are 32 bit aligned which should be always true.
                     if (mChannelCount == 2 && mReqChannelCount == 1) {
-                        AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
+                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
                         // the resampler always outputs stereo samples: do post stereo to mono conversion
                         int16_t *src = (int16_t *)mRsmpOutBuffer;
                         int16_t *dst = buffer.i16;
@@ -4421,7 +4448,7 @@
                             src += 2;
                         }
                     } else {
-                        AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
+                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
                     }
 
                 }
@@ -4432,7 +4459,7 @@
             else {
                 if (!mActiveTrack->setOverflow()) {
                     nsecs_t now = systemTime();
-                    if ((now - lastWarning) > kWarningThrottle) {
+                    if ((now - lastWarning) > kWarningThrottleNs) {
                         ALOGW("RecordThread: buffer overflow");
                         lastWarning = now;
                     }
@@ -4465,7 +4492,7 @@
 sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
         const sp<AudioFlinger::Client>& client,
         uint32_t sampleRate,
-        int format,
+        audio_format_t format,
         int channelMask,
         int frameCount,
         uint32_t flags,
@@ -4514,7 +4541,7 @@
     sp <ThreadBase> strongMe = this;
     status_t status = NO_ERROR;
     {
-        AutoMutex lock(&mLock);
+        AutoMutex lock(mLock);
         if (mActiveTrack != 0) {
             if (recordTrack != mActiveTrack.get()) {
                 status = -EBUSY;
@@ -4566,7 +4593,7 @@
     ALOGV("RecordThread::stop");
     sp <ThreadBase> strongMe = this;
     {
-        AutoMutex lock(&mLock);
+        AutoMutex lock(mLock);
         if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
             mActiveTrack->mState = TrackBase::PAUSING;
             // do not wait for mStartStopCond if exiting
@@ -4605,7 +4632,7 @@
         result.append(buffer);
         snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
         result.append(buffer);
-        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
+        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
         result.append(buffer);
         snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
         result.append(buffer);
@@ -4640,7 +4667,7 @@
                 mInput->stream->common.standby(&mInput->stream->common);
                 usleep(kRecordThreadSleepUs);
             }
-            buffer->raw = 0;
+            buffer->raw = NULL;
             buffer->frameCount = 0;
             return NOT_ENOUGH_DATA;
         }
@@ -4677,7 +4704,7 @@
         String8 keyValuePair = mNewParameters[0];
         AudioParameter param = AudioParameter(keyValuePair);
         int value;
-        int reqFormat = mFormat;
+        audio_format_t reqFormat = mFormat;
         int reqSamplingRate = mReqSampleRate;
         int reqChannelCount = mReqChannelCount;
 
@@ -4686,7 +4713,7 @@
             reconfig = true;
         }
         if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
-            reqFormat = value;
+            reqFormat = (audio_format_t) value;
             reconfig = true;
         }
         if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
@@ -4755,7 +4782,7 @@
         mParamCond.signal();
         // wait for condition with time out in case the thread calling ThreadBase::setParameters()
         // already timed out waiting for the status and will never signal the condition.
-        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
+        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
     }
     return reconfig;
 }
@@ -4803,13 +4830,13 @@
     if (mRsmpInBuffer) delete mRsmpInBuffer;
     if (mRsmpOutBuffer) delete mRsmpOutBuffer;
     if (mResampler) delete mResampler;
-    mResampler = 0;
+    mResampler = NULL;
 
     mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
     mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
     mChannelCount = (uint16_t)popcount(mChannelMask);
     mFormat = mInput->stream->common.get_format(&mInput->stream->common);
-    mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
+    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
     mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
     mFrameCount = mInputBytes / mFrameSize;
     mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
@@ -4897,7 +4924,7 @@
 
 int AudioFlinger::openOutput(uint32_t *pDevices,
                                 uint32_t *pSamplingRate,
-                                uint32_t *pFormat,
+                                audio_format_t *pFormat,
                                 uint32_t *pChannels,
                                 uint32_t *pLatencyMs,
                                 uint32_t flags)
@@ -4906,7 +4933,7 @@
     PlaybackThread *thread = NULL;
     mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
     uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
-    uint32_t format = pFormat ? *pFormat : 0;
+    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
     uint32_t channels = pChannels ? *pChannels : 0;
     uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
     audio_stream_out_t *outStream;
@@ -4929,7 +4956,7 @@
     if (outHwDev == NULL)
         return 0;
 
-    status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
+    status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
                                           &channels, &samplingRate, &outStream);
     ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
             outStream,
@@ -5057,17 +5084,17 @@
 
 int AudioFlinger::openInput(uint32_t *pDevices,
                                 uint32_t *pSamplingRate,
-                                uint32_t *pFormat,
+                                audio_format_t *pFormat,
                                 uint32_t *pChannels,
                                 uint32_t acoustics)
 {
     status_t status;
     RecordThread *thread = NULL;
     uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
-    uint32_t format = pFormat ? *pFormat : 0;
+    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
     uint32_t channels = pChannels ? *pChannels : 0;
     uint32_t reqSamplingRate = samplingRate;
-    uint32_t reqFormat = format;
+    audio_format_t reqFormat = format;
     uint32_t reqChannels = channels;
     audio_stream_in_t *inStream;
     audio_hw_device_t *inHwDev;
@@ -5082,7 +5109,7 @@
     if (inHwDev == NULL)
         return 0;
 
-    status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
+    status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
                                         &channels, &samplingRate,
                                         (audio_in_acoustics_t)acoustics,
                                         &inStream);
@@ -5102,7 +5129,7 @@
         (samplingRate <= 2 * reqSamplingRate) &&
         (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
         ALOGV("openInput() reopening with proposed sampling rate and channels");
-        status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
+        status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
                                             &channels, &samplingRate,
                                             (audio_in_acoustics_t)acoustics,
                                             &inStream);
@@ -5165,7 +5192,7 @@
     return NO_ERROR;
 }
 
-status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
+status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
 {
     Mutex::Autolock _l(mLock);
     MixerThread *dstThread = checkMixerThread_l(output);
@@ -5733,7 +5760,7 @@
             effect = chain->getEffectFromDesc_l(desc);
         }
 
-        ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
+        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
 
         if (effect == 0) {
             int id = mAudioFlinger->nextUniqueId();
@@ -5892,7 +5919,7 @@
     return chain;
 }
 
-void AudioFlinger::ThreadBase::setMode(uint32_t mode)
+void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
 {
     Mutex::Autolock _l(mLock);
     size_t size = mEffectChains.size();
@@ -6292,7 +6319,7 @@
     if (isProcessEnabled()) {
         // do 32 bit to 16 bit conversion for auxiliary effect input buffer
         if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
-            AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
+            ditherAndClamp(mConfig.inputCfg.buffer.s32,
                                         mConfig.inputCfg.buffer.s32,
                                         mConfig.inputCfg.buffer.frameCount/2);
         }
@@ -6397,7 +6424,7 @@
     status_t cmdStatus;
     uint32_t size = sizeof(int);
     status_t status = (*mEffectInterface)->command(mEffectInterface,
-                                                   EFFECT_CMD_CONFIGURE,
+                                                   EFFECT_CMD_SET_CONFIG,
                                                    sizeof(effect_config_t),
                                                    &mConfig,
                                                    &size,
@@ -6690,7 +6717,7 @@
     return status;
 }
 
-status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
+status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
 {
     Mutex::Autolock _l(mLock);
     status_t status = NO_ERROR;
@@ -6699,7 +6726,7 @@
         uint32_t size = sizeof(status_t);
         status = (*mEffectInterface)->command(mEffectInterface,
                                               EFFECT_CMD_SET_AUDIO_MODE,
-                                              sizeof(int),
+                                              sizeof(audio_mode_t),
                                               &mode,
                                               &size,
                                               &cmdStatus);
@@ -6715,7 +6742,8 @@
     Mutex::Autolock _l(mLock);
     mSuspended = suspended;
 }
-bool AudioFlinger::EffectModule::suspended()
+
+bool AudioFlinger::EffectModule::suspended() const
 {
     Mutex::Autolock _l(mLock);
     return mSuspended;
@@ -7348,7 +7376,7 @@
 }
 
 // setMode_l() must be called with PlaybackThread::mLock held
-void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
+void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
 {
     size_t size = mEffects.size();
     for (size_t i = 0; i < size; i++) {
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index 9bd2c7f..d862c1d 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -55,12 +55,6 @@
 
 // ----------------------------------------------------------------------------
 
-#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
-#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
-
-
-// ----------------------------------------------------------------------------
-
 static const nsecs_t kStandbyTimeInNsecs = seconds(3);
 
 class AudioFlinger :
@@ -69,16 +63,16 @@
 {
     friend class BinderService<AudioFlinger>;
 public:
-    static char const* getServiceName() { return "media.audio_flinger"; }
+    static const char* getServiceName() { return "media.audio_flinger"; }
 
     virtual     status_t    dump(int fd, const Vector<String16>& args);
 
     // IAudioFlinger interface
     virtual sp<IAudioTrack> createTrack(
                                 pid_t pid,
-                                int streamType,
+                                audio_stream_type_t streamType,
                                 uint32_t sampleRate,
-                                uint32_t format,
+                                audio_format_t format,
                                 uint32_t channelMask,
                                 int frameCount,
                                 uint32_t flags,
@@ -89,7 +83,7 @@
 
     virtual     uint32_t    sampleRate(int output) const;
     virtual     int         channelCount(int output) const;
-    virtual     uint32_t    format(int output) const;
+    virtual     audio_format_t format(int output) const;
     virtual     size_t      frameCount(int output) const;
     virtual     uint32_t    latency(int output) const;
 
@@ -99,13 +93,13 @@
     virtual     float       masterVolume() const;
     virtual     bool        masterMute() const;
 
-    virtual     status_t    setStreamVolume(int stream, float value, int output);
-    virtual     status_t    setStreamMute(int stream, bool muted);
+    virtual     status_t    setStreamVolume(audio_stream_type_t stream, float value, int output);
+    virtual     status_t    setStreamMute(audio_stream_type_t stream, bool muted);
 
-    virtual     float       streamVolume(int stream, int output) const;
-    virtual     bool        streamMute(int stream) const;
+    virtual     float       streamVolume(audio_stream_type_t stream, int output) const;
+    virtual     bool        streamMute(audio_stream_type_t stream) const;
 
-    virtual     status_t    setMode(int mode);
+    virtual     status_t    setMode(audio_mode_t mode);
 
     virtual     status_t    setMicMute(bool state);
     virtual     bool        getMicMute() const;
@@ -115,12 +109,12 @@
 
     virtual     void        registerClient(const sp<IAudioFlingerClient>& client);
 
-    virtual     size_t      getInputBufferSize(uint32_t sampleRate, int format, int channelCount);
+    virtual     size_t      getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount);
     virtual     unsigned int  getInputFramesLost(int ioHandle);
 
     virtual int openOutput(uint32_t *pDevices,
                                     uint32_t *pSamplingRate,
-                                    uint32_t *pFormat,
+                                    audio_format_t *pFormat,
                                     uint32_t *pChannels,
                                     uint32_t *pLatencyMs,
                                     uint32_t flags);
@@ -135,13 +129,13 @@
 
     virtual int openInput(uint32_t *pDevices,
                             uint32_t *pSamplingRate,
-                            uint32_t *pFormat,
+                            audio_format_t *pFormat,
                             uint32_t *pChannels,
                             uint32_t acoustics);
 
     virtual status_t closeInput(int input);
 
-    virtual status_t setStreamOutput(uint32_t stream, int output);
+    virtual status_t setStreamOutput(audio_stream_type_t stream, int output);
 
     virtual status_t setVoiceVolume(float volume);
 
@@ -195,7 +189,7 @@
                                 pid_t pid,
                                 int input,
                                 uint32_t sampleRate,
-                                uint32_t format,
+                                audio_format_t format,
                                 uint32_t channelMask,
                                 int frameCount,
                                 uint32_t flags,
@@ -208,7 +202,7 @@
                                 Parcel* reply,
                                 uint32_t flags);
 
-                uint32_t    getMode() { return mMode; }
+               audio_mode_t getMode() const { return mMode; }
 
                 bool        btNrecIsOff() { return mBtNrecIsOff; }
 
@@ -321,7 +315,7 @@
                                 TrackBase(const wp<ThreadBase>& thread,
                                         const sp<Client>& client,
                                         uint32_t sampleRate,
-                                        uint32_t format,
+                                        audio_format_t format,
                                         uint32_t channelMask,
                                         int frameCount,
                                         uint32_t flags,
@@ -349,7 +343,7 @@
             virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) = 0;
             virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
 
-            uint32_t format() const {
+            audio_format_t format() const {
                 return mFormat;
             }
 
@@ -382,7 +376,7 @@
             // we don't really need a lock for these
             int                 mState;
             int                 mClientTid;
-            uint32_t            mFormat;
+            audio_format_t      mFormat;
             uint32_t            mFlags;
             int                 mSessionId;
             uint8_t             mChannelCount;
@@ -416,7 +410,7 @@
                     int         type() const { return mType; }
                     uint32_t    sampleRate() const;
                     int         channelCount() const;
-                    uint32_t    format() const;
+                    audio_format_t format() const;
                     size_t      frameCount() const;
                     void        wakeUp()    { mWaitWorkCV.broadcast(); }
                     void        exit();
@@ -467,7 +461,7 @@
                     // unlock effect chains after process
                     void unlockEffectChains(Vector<sp <EffectChain> >& effectChains);
                     // set audio mode to all effect chains
-                    void setMode(uint32_t mode);
+                    void setMode(audio_mode_t mode);
                     // get effect module with corresponding ID on specified audio session
                     sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
                     // add and effect module. Also creates the effect chain is none exists for
@@ -542,12 +536,12 @@
                     size_t                  mFrameCount;
                     uint32_t                mChannelMask;
                     uint16_t                mChannelCount;
-                    uint16_t                mFrameSize;
-                    uint32_t                mFormat;
+                    size_t                  mFrameSize;
+                    audio_format_t          mFormat;
                     Condition               mParamCond;
                     Vector<String8>         mNewParameters;
                     status_t                mParamStatus;
-                    Vector<ConfigEvent *>   mConfigEvents;
+                    Vector<ConfigEvent>     mConfigEvents;
                     bool                    mStandby;
                     int                     mId;
                     bool                    mExiting;
@@ -579,9 +573,9 @@
         public:
                                 Track(  const wp<ThreadBase>& thread,
                                         const sp<Client>& client,
-                                        int streamType,
+                                        audio_stream_type_t streamType,
                                         uint32_t sampleRate,
-                                        uint32_t format,
+                                        audio_format_t format,
                                         uint32_t channelMask,
                                         int frameCount,
                                         const sp<IMemory>& sharedBuffer,
@@ -596,12 +590,11 @@
                     void        flush();
                     void        destroy();
                     void        mute(bool);
-                    void        setVolume(float left, float right);
                     int name() const {
                         return mName;
                     }
 
-                    int type() const {
+                    audio_stream_type_t type() const {
                         return mStreamType;
                     }
                     status_t    attachAuxEffect(int EffectId);
@@ -639,7 +632,6 @@
             }
 
             // we don't really need a lock for these
-            float               mVolume[2];
             volatile bool       mMute;
             // FILLED state is used for suppressing volume ramp at begin of playing
             enum {FS_FILLING, FS_FILLED, FS_ACTIVE};
@@ -647,7 +639,7 @@
             int8_t              mRetryCount;
             sp<IMemory>         mSharedBuffer;
             bool                mResetDone;
-            int                 mStreamType;
+            audio_stream_type_t mStreamType;
             int                 mName;
             int16_t             *mMainBuffer;
             int32_t             *mAuxBuffer;
@@ -668,7 +660,7 @@
                                 OutputTrack(  const wp<ThreadBase>& thread,
                                         DuplicatingThread *sourceThread,
                                         uint32_t sampleRate,
-                                        uint32_t format,
+                                        audio_format_t format,
                                         uint32_t channelMask,
                                         int frameCount);
                                 ~OutputTrack();
@@ -703,7 +695,7 @@
         virtual     status_t    readyToRun();
         virtual     void        onFirstRef();
 
-        virtual     status_t    initCheck() const { return (mOutput == 0) ? NO_INIT : NO_ERROR; }
+        virtual     status_t    initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
 
         virtual     uint32_t    latency() const;
 
@@ -713,17 +705,17 @@
         virtual     float       masterVolume() const;
         virtual     bool        masterMute() const;
 
-        virtual     status_t    setStreamVolume(int stream, float value);
-        virtual     status_t    setStreamMute(int stream, bool muted);
+        virtual     status_t    setStreamVolume(audio_stream_type_t stream, float value);
+        virtual     status_t    setStreamMute(audio_stream_type_t stream, bool muted);
 
-        virtual     float       streamVolume(int stream) const;
-        virtual     bool        streamMute(int stream) const;
+        virtual     float       streamVolume(audio_stream_type_t stream) const;
+        virtual     bool        streamMute(audio_stream_type_t stream) const;
 
                     sp<Track>   createTrack_l(
                                     const sp<AudioFlinger::Client>& client,
-                                    int streamType,
+                                    audio_stream_type_t streamType,
                                     uint32_t sampleRate,
-                                    uint32_t format,
+                                    audio_format_t format,
                                     uint32_t channelMask,
                                     int frameCount,
                                     const sp<IMemory>& sharedBuffer,
@@ -736,7 +728,7 @@
 
                     void        suspend() { mSuspended++; }
                     void        restore() { if (mSuspended) mSuspended--; }
-                    bool        isSuspended() { return (mSuspended != 0); }
+                    bool        isSuspended() const { return (mSuspended != 0); }
         virtual     String8     getParameters(const String8& keys);
         virtual     void        audioConfigChanged_l(int event, int param = 0);
         virtual     status_t    getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
@@ -753,7 +745,7 @@
                     virtual uint32_t hasAudioSession(int sessionId);
                     virtual uint32_t getStrategyForSession_l(int sessionId);
 
-                            void setStreamValid(int streamType, bool valid);
+                            void setStreamValid(audio_stream_type_t streamType, bool valid);
 
         struct  stream_type_t {
             stream_type_t()
@@ -771,7 +763,9 @@
         int16_t*                        mMixBuffer;
         int                             mSuspended;
         int                             mBytesWritten;
+    private:
         bool                            mMasterMute;
+    protected:
         SortedVector< wp<Track> >       mActiveTracks;
 
         virtual int             getTrackName_l() = 0;
@@ -803,7 +797,7 @@
         status_t    dumpTracks(int fd, const Vector<String16>& args);
 
         SortedVector< sp<Track> >       mTracks;
-        // mStreamTypes[] uses 1 additionnal stream type internally for the OutputTrack used by DuplicatingThread
+        // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by DuplicatingThread
         stream_type_t                   mStreamTypes[AUDIO_STREAM_CNT + 1];
         AudioStreamOut*                 mOutput;
         float                           mMasterVolume;
@@ -824,7 +818,7 @@
         // Thread virtuals
         virtual     bool        threadLoop();
 
-                    void        invalidateTracks(int streamType);
+                    void        invalidateTracks(audio_stream_type_t streamType);
         virtual     bool        checkForNewParameters_l();
         virtual     status_t    dumpInternals(int fd, const Vector<String16>& args);
 
@@ -892,7 +886,7 @@
               PlaybackThread *checkPlaybackThread_l(int output) const;
               MixerThread *checkMixerThread_l(int output) const;
               RecordThread *checkRecordThread_l(int input) const;
-              float streamVolumeInternal(int stream) const { return mStreamTypes[stream].volume; }
+              float streamVolumeInternal(audio_stream_type_t stream) const { return mStreamTypes[stream].volume; }
               void audioConfigChanged_l(int event, int ioHandle, void *param2);
 
               uint32_t nextUniqueId();
@@ -914,7 +908,6 @@
         virtual void        flush();
         virtual void        mute(bool);
         virtual void        pause();
-        virtual void        setVolume(float left, float right);
         virtual sp<IMemory> getCblk() const;
         virtual status_t    attachAuxEffect(int effectId);
         virtual status_t onTransact(
@@ -942,7 +935,7 @@
                                 RecordTrack(const wp<ThreadBase>& thread,
                                         const sp<Client>& client,
                                         uint32_t sampleRate,
-                                        uint32_t format,
+                                        audio_format_t format,
                                         uint32_t channelMask,
                                         int frameCount,
                                         uint32_t flags,
@@ -982,11 +975,11 @@
         virtual status_t    readyToRun();
         virtual void        onFirstRef();
 
-        virtual status_t    initCheck() const { return (mInput == 0) ? NO_INIT : NO_ERROR; }
+        virtual status_t    initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
                 sp<AudioFlinger::RecordThread::RecordTrack>  createRecordTrack_l(
                         const sp<AudioFlinger::Client>& client,
                         uint32_t sampleRate,
-                        int format,
+                        audio_format_t format,
                         int channelMask,
                         int frameCount,
                         uint32_t flags,
@@ -1119,11 +1112,11 @@
 
         status_t         setDevice(uint32_t device);
         status_t         setVolume(uint32_t *left, uint32_t *right, bool controller);
-        status_t         setMode(uint32_t mode);
+        status_t         setMode(audio_mode_t mode);
         status_t         start();
         status_t         stop();
         void             setSuspended(bool suspended);
-        bool             suspended();
+        bool             suspended() const;
 
         sp<EffectHandle> controlHandle();
 
@@ -1146,7 +1139,7 @@
         status_t start_l();
         status_t stop_l();
 
-        Mutex               mLock;      // mutex for process, commands and handles list protection
+mutable Mutex               mLock;      // mutex for process, commands and handles list protection
         wp<ThreadBase>      mThread;    // parent thread
         wp<EffectChain>     mChain;     // parent effect chain
         int                 mId;        // this instance unique ID
@@ -1272,7 +1265,7 @@
         sp<EffectModule> getEffectFromType_l(const effect_uuid_t *type);
         bool setVolume_l(uint32_t *left, uint32_t *right);
         void setDevice_l(uint32_t device);
-        void setMode_l(uint32_t mode);
+        void setMode_l(audio_mode_t mode);
 
         void setInBuffer(int16_t *buffer, bool ownsBuffer = false) {
             mInBuffer = buffer;
@@ -1391,11 +1384,13 @@
                 mutable     Mutex                   mHardwareLock;
                 audio_hw_device_t*                  mPrimaryHardwareDev;
                 Vector<audio_hw_device_t*>          mAudioHwDevs;
-    mutable     int                                 mHardwareStatus;
+    mutable     hardware_call_state                 mHardwareStatus;    // for dump only
 
 
                 DefaultKeyedVector< int, sp<PlaybackThread> >  mPlaybackThreads;
                 PlaybackThread::stream_type_t       mStreamTypes[AUDIO_STREAM_CNT];
+
+                // both are protected by mLock
                 float                               mMasterVolume;
                 bool                                mMasterMute;
 
@@ -1403,10 +1398,13 @@
 
                 DefaultKeyedVector< pid_t, sp<NotificationClient> >    mNotificationClients;
                 volatile int32_t                    mNextUniqueId;
-                uint32_t                            mMode;
+                audio_mode_t                        mMode;
                 bool                                mBtNrecIsOff;
 
                 Vector<AudioSessionRef*> mAudioSessionRefs;
+
+                float       masterVolume_l() const  { return mMasterVolume; }
+                bool        masterMute_l() const    { return mMasterMute; }
 };
 
 
diff --git a/services/audioflinger/AudioMixer.cpp b/services/audioflinger/AudioMixer.cpp
index 9dda256..a8102e5 100644
--- a/services/audioflinger/AudioMixer.cpp
+++ b/services/audioflinger/AudioMixer.cpp
@@ -18,6 +18,7 @@
 #define LOG_TAG "AudioMixer"
 //#define LOG_NDEBUG 0
 
+#include <assert.h>
 #include <stdint.h>
 #include <string.h>
 #include <stdlib.h>
@@ -27,240 +28,227 @@
 #include <utils/Log.h>
 
 #include <cutils/bitops.h>
+#include <cutils/compiler.h>
 
 #include <system/audio.h>
 
+#include <audio_utils/primitives.h>
+
 #include "AudioMixer.h"
 
 namespace android {
-// ----------------------------------------------------------------------------
-
-static inline int16_t clamp16(int32_t sample)
-{
-    if ((sample>>15) ^ (sample>>31))
-        sample = 0x7FFF ^ (sample>>31);
-    return sample;
-}
 
 // ----------------------------------------------------------------------------
 
 AudioMixer::AudioMixer(size_t frameCount, uint32_t sampleRate)
-    :   mActiveTrack(0), mTrackNames(0), mSampleRate(sampleRate)
+    :   mTrackNames(0), mSampleRate(sampleRate)
 {
+    // AudioMixer is not yet capable of multi-channel beyond stereo
+    assert(2 == MAX_NUM_CHANNELS);
     mState.enabledTracks= 0;
     mState.needsChanged = 0;
     mState.frameCount   = frameCount;
-    mState.outputTemp   = 0;
-    mState.resampleTemp = 0;
+    mState.outputTemp   = NULL;
+    mState.resampleTemp = NULL;
     mState.hook         = process__nop;
     track_t* t = mState.tracks;
-    for (int i=0 ; i<32 ; i++) {
+    for (unsigned i=0 ; i < MAX_NUM_TRACKS ; i++) {
         t->needs = 0;
         t->volume[0] = UNITY_GAIN;
         t->volume[1] = UNITY_GAIN;
+        // no initialization needed
+        // t->prevVolume[0]
+        // t->prevVolume[1]
         t->volumeInc[0] = 0;
         t->volumeInc[1] = 0;
         t->auxLevel = 0;
         t->auxInc = 0;
+        // no initialization needed
+        // t->prevAuxLevel
+        // t->frameCount
         t->channelCount = 2;
         t->enabled = 0;
         t->format = 16;
         t->channelMask = AUDIO_CHANNEL_OUT_STEREO;
         t->buffer.raw = 0;
-        t->bufferProvider = 0;
-        t->hook = 0;
-        t->resampler = 0;
+        t->bufferProvider = NULL;
+        t->hook = NULL;
+        t->resampler = NULL;
         t->sampleRate = mSampleRate;
-        t->in = 0;
+        t->in = NULL;
         t->mainBuffer = NULL;
         t->auxBuffer = NULL;
         t++;
     }
 }
 
- AudioMixer::~AudioMixer()
- {
-     track_t* t = mState.tracks;
-     for (int i=0 ; i<32 ; i++) {
-         delete t->resampler;
-         t++;
-     }
-     delete [] mState.outputTemp;
-     delete [] mState.resampleTemp;
- }
-
- int AudioMixer::getTrackName()
- {
-    uint32_t names = mTrackNames;
-    uint32_t mask = 1;
-    int n = 0;
-    while (names & mask) {
-        mask <<= 1;
-        n++;
+AudioMixer::~AudioMixer()
+{
+    track_t* t = mState.tracks;
+    for (unsigned i=0 ; i < MAX_NUM_TRACKS ; i++) {
+        delete t->resampler;
+        t++;
     }
-    if (mask) {
+    delete [] mState.outputTemp;
+    delete [] mState.resampleTemp;
+}
+
+int AudioMixer::getTrackName()
+{
+    uint32_t names = ~mTrackNames;
+    if (names != 0) {
+        int n = __builtin_ctz(names);
         ALOGV("add track (%d)", n);
-        mTrackNames |= mask;
+        mTrackNames |= 1 << n;
         return TRACK0 + n;
     }
     return -1;
- }
+}
 
- void AudioMixer::invalidateState(uint32_t mask)
- {
+void AudioMixer::invalidateState(uint32_t mask)
+{
     if (mask) {
         mState.needsChanged |= mask;
         mState.hook = process__validate;
     }
  }
 
- void AudioMixer::deleteTrackName(int name)
- {
+void AudioMixer::deleteTrackName(int name)
+{
     name -= TRACK0;
-    if (uint32_t(name) < MAX_NUM_TRACKS) {
-        ALOGV("deleteTrackName(%d)", name);
-        track_t& track(mState.tracks[ name ]);
-        if (track.enabled != 0) {
-            track.enabled = 0;
-            invalidateState(1<<name);
-        }
-        if (track.resampler) {
-            // delete  the resampler
-            delete track.resampler;
-            track.resampler = 0;
-            track.sampleRate = mSampleRate;
-            invalidateState(1<<name);
-        }
-        track.volumeInc[0] = 0;
-        track.volumeInc[1] = 0;
-        mTrackNames &= ~(1<<name);
+    assert(uint32_t(name) < MAX_NUM_TRACKS);
+    ALOGV("deleteTrackName(%d)", name);
+    track_t& track(mState.tracks[ name ]);
+    if (track.enabled != 0) {
+        track.enabled = 0;
+        invalidateState(1<<name);
     }
- }
-
-status_t AudioMixer::enable(int name)
-{
-    switch (name) {
-        case MIXING: {
-            if (mState.tracks[ mActiveTrack ].enabled != 1) {
-                mState.tracks[ mActiveTrack ].enabled = 1;
-                ALOGV("enable(%d)", mActiveTrack);
-                invalidateState(1<<mActiveTrack);
-            }
-        } break;
-        default:
-            return NAME_NOT_FOUND;
+    if (track.resampler) {
+        // delete  the resampler
+        delete track.resampler;
+        track.resampler = NULL;
+        track.sampleRate = mSampleRate;
+        invalidateState(1<<name);
     }
-    return NO_ERROR;
+    track.volumeInc[0] = 0;
+    track.volumeInc[1] = 0;
+    mTrackNames &= ~(1<<name);
 }
 
-status_t AudioMixer::disable(int name)
+void AudioMixer::enable(int name)
 {
-    switch (name) {
-        case MIXING: {
-            if (mState.tracks[ mActiveTrack ].enabled != 0) {
-                mState.tracks[ mActiveTrack ].enabled = 0;
-                ALOGV("disable(%d)", mActiveTrack);
-                invalidateState(1<<mActiveTrack);
-            }
-        } break;
-        default:
-            return NAME_NOT_FOUND;
+    name -= TRACK0;
+    assert(uint32_t(name) < MAX_NUM_TRACKS);
+    track_t& track = mState.tracks[name];
+
+    if (track.enabled != 1) {
+        track.enabled = 1;
+        ALOGV("enable(%d)", name);
+        invalidateState(1 << name);
     }
-    return NO_ERROR;
 }
 
-status_t AudioMixer::setActiveTrack(int track)
+void AudioMixer::disable(int name)
 {
-    if (uint32_t(track-TRACK0) >= MAX_NUM_TRACKS) {
-        return BAD_VALUE;
+    name -= TRACK0;
+    assert(uint32_t(name) < MAX_NUM_TRACKS);
+    track_t& track = mState.tracks[name];
+
+    if (track.enabled != 0) {
+        track.enabled = 0;
+        ALOGV("disable(%d)", name);
+        invalidateState(1 << name);
     }
-    mActiveTrack = track - TRACK0;
-    return NO_ERROR;
 }
 
-status_t AudioMixer::setParameter(int target, int name, void *value)
+void AudioMixer::setParameter(int name, int target, int param, void *value)
 {
+    name -= TRACK0;
+    assert(uint32_t(name) < MAX_NUM_TRACKS);
+    track_t& track = mState.tracks[name];
+
     int valueInt = (int)value;
     int32_t *valueBuf = (int32_t *)value;
 
     switch (target) {
-    case TRACK:
-        if (name == CHANNEL_MASK) {
-            uint32_t mask = (uint32_t)value;
-            if (mState.tracks[ mActiveTrack ].channelMask != mask) {
-                uint8_t channelCount = popcount(mask);
-                if ((channelCount <= MAX_NUM_CHANNELS) && (channelCount)) {
-                    mState.tracks[ mActiveTrack ].channelMask = mask;
-                    mState.tracks[ mActiveTrack ].channelCount = channelCount;
-                    ALOGV("setParameter(TRACK, CHANNEL_MASK, %x)", mask);
-                    invalidateState(1<<mActiveTrack);
-                    return NO_ERROR;
-                }
-            } else {
-                return NO_ERROR;
-            }
-        }
-        if (name == MAIN_BUFFER) {
-            if (mState.tracks[ mActiveTrack ].mainBuffer != valueBuf) {
-                mState.tracks[ mActiveTrack ].mainBuffer = valueBuf;
-                ALOGV("setParameter(TRACK, MAIN_BUFFER, %p)", valueBuf);
-                invalidateState(1<<mActiveTrack);
-            }
-            return NO_ERROR;
-        }
-        if (name == AUX_BUFFER) {
-            if (mState.tracks[ mActiveTrack ].auxBuffer != valueBuf) {
-                mState.tracks[ mActiveTrack ].auxBuffer = valueBuf;
-                ALOGV("setParameter(TRACK, AUX_BUFFER, %p)", valueBuf);
-                invalidateState(1<<mActiveTrack);
-            }
-            return NO_ERROR;
-        }
 
-        break;
-    case RESAMPLE:
-        if (name == SAMPLE_RATE) {
-            if (valueInt > 0) {
-                track_t& track = mState.tracks[ mActiveTrack ];
-                if (track.setResampler(uint32_t(valueInt), mSampleRate)) {
-                    ALOGV("setParameter(RESAMPLE, SAMPLE_RATE, %u)",
-                            uint32_t(valueInt));
-                    invalidateState(1<<mActiveTrack);
-                }
-                return NO_ERROR;
+    case TRACK:
+        switch (param) {
+        case CHANNEL_MASK: {
+            uint32_t mask = (uint32_t)value;
+            if (track.channelMask != mask) {
+                uint8_t channelCount = popcount(mask);
+                assert((channelCount <= MAX_NUM_CHANNELS) && (channelCount));
+                track.channelMask = mask;
+                track.channelCount = channelCount;
+                ALOGV("setParameter(TRACK, CHANNEL_MASK, %x)", mask);
+                invalidateState(1 << name);
             }
-        }
-        if (name == RESET) {
-            track_t& track = mState.tracks[ mActiveTrack ];
-            track.resetResampler();
-            invalidateState(1<<mActiveTrack);
-            return NO_ERROR;
+            } break;
+        case MAIN_BUFFER:
+            if (track.mainBuffer != valueBuf) {
+                track.mainBuffer = valueBuf;
+                ALOGV("setParameter(TRACK, MAIN_BUFFER, %p)", valueBuf);
+                invalidateState(1 << name);
+            }
+            break;
+        case AUX_BUFFER:
+            if (track.auxBuffer != valueBuf) {
+                track.auxBuffer = valueBuf;
+                ALOGV("setParameter(TRACK, AUX_BUFFER, %p)", valueBuf);
+                invalidateState(1 << name);
+            }
+            break;
+        default:
+            // bad param
+            assert(false);
         }
         break;
+
+    case RESAMPLE:
+        switch (param) {
+        case SAMPLE_RATE:
+            assert(valueInt > 0);
+            if (track.setResampler(uint32_t(valueInt), mSampleRate)) {
+                ALOGV("setParameter(RESAMPLE, SAMPLE_RATE, %u)",
+                        uint32_t(valueInt));
+                invalidateState(1 << name);
+            }
+            break;
+        case RESET:
+            track.resetResampler();
+            invalidateState(1 << name);
+            break;
+        default:
+            // bad param
+            assert(false);
+        }
+        break;
+
     case RAMP_VOLUME:
     case VOLUME:
-        if ((uint32_t(name-VOLUME0) < MAX_NUM_CHANNELS)) {
-            track_t& track = mState.tracks[ mActiveTrack ];
-            if (track.volume[name-VOLUME0] != valueInt) {
+        switch (param) {
+        case VOLUME0:
+        case VOLUME1:
+            if (track.volume[param-VOLUME0] != valueInt) {
                 ALOGV("setParameter(VOLUME, VOLUME0/1: %04x)", valueInt);
-                track.prevVolume[name-VOLUME0] = track.volume[name-VOLUME0] << 16;
-                track.volume[name-VOLUME0] = valueInt;
+                track.prevVolume[param-VOLUME0] = track.volume[param-VOLUME0] << 16;
+                track.volume[param-VOLUME0] = valueInt;
                 if (target == VOLUME) {
-                    track.prevVolume[name-VOLUME0] = valueInt << 16;
-                    track.volumeInc[name-VOLUME0] = 0;
+                    track.prevVolume[param-VOLUME0] = valueInt << 16;
+                    track.volumeInc[param-VOLUME0] = 0;
                 } else {
-                    int32_t d = (valueInt<<16) - track.prevVolume[name-VOLUME0];
+                    int32_t d = (valueInt<<16) - track.prevVolume[param-VOLUME0];
                     int32_t volInc = d / int32_t(mState.frameCount);
-                    track.volumeInc[name-VOLUME0] = volInc;
+                    track.volumeInc[param-VOLUME0] = volInc;
                     if (volInc == 0) {
-                        track.prevVolume[name-VOLUME0] = valueInt << 16;
+                        track.prevVolume[param-VOLUME0] = valueInt << 16;
                     }
                 }
-                invalidateState(1<<mActiveTrack);
+                invalidateState(1 << name);
             }
-            return NO_ERROR;
-        } else if (name == AUXLEVEL) {
-            track_t& track = mState.tracks[ mActiveTrack ];
+            break;
+        case AUXLEVEL:
             if (track.auxLevel != valueInt) {
                 ALOGV("setParameter(VOLUME, AUXLEVEL: %04x)", valueInt);
                 track.prevAuxLevel = track.auxLevel << 16;
@@ -276,13 +264,19 @@
                         track.prevAuxLevel = valueInt << 16;
                     }
                 }
-                invalidateState(1<<mActiveTrack);
+                invalidateState(1 << name);
             }
-            return NO_ERROR;
+            break;
+        default:
+            // bad param
+            assert(false);
         }
         break;
+
+    default:
+        // bad target
+        assert(false);
     }
-    return BAD_VALUE;
 }
 
 bool AudioMixer::track_t::setResampler(uint32_t value, uint32_t devSampleRate)
@@ -290,7 +284,7 @@
     if (value!=devSampleRate || resampler) {
         if (sampleRate != value) {
             sampleRate = value;
-            if (resampler == 0) {
+            if (resampler == NULL) {
                 resampler = AudioResampler::create(
                         format, channelCount, devSampleRate);
             }
@@ -302,12 +296,12 @@
 
 bool AudioMixer::track_t::doesResample() const
 {
-    return resampler != 0;
+    return resampler != NULL;
 }
 
 void AudioMixer::track_t::resetResampler()
 {
-    if (resampler != 0) {
+    if (resampler != NULL) {
         resampler->reset();
     }
 }
@@ -315,7 +309,7 @@
 inline
 void AudioMixer::track_t::adjustVolumeRamp(bool aux)
 {
-    for (int i=0 ; i<2 ; i++) {
+    for (uint32_t i=0 ; i<MAX_NUM_CHANNELS ; i++) {
         if (((volumeInc[i]>0) && (((prevVolume[i]+volumeInc[i])>>16) >= volume[i])) ||
             ((volumeInc[i]<0) && (((prevVolume[i]+volumeInc[i])>>16) <= volume[i]))) {
             volumeInc[i] = 0;
@@ -349,10 +343,11 @@
     return 0;
 }
 
-status_t AudioMixer::setBufferProvider(AudioBufferProvider* buffer)
+void AudioMixer::setBufferProvider(int name, AudioBufferProvider* buffer)
 {
-    mState.tracks[ mActiveTrack ].bufferProvider = buffer;
-    return NO_ERROR;
+    name -= TRACK0;
+    assert(uint32_t(name) < MAX_NUM_TRACKS);
+    mState.tracks[name].bufferProvider = buffer;
 }
 
 
@@ -447,11 +442,11 @@
         } else {
             if (state->outputTemp) {
                 delete [] state->outputTemp;
-                state->outputTemp = 0;
+                state->outputTemp = NULL;
             }
             if (state->resampleTemp) {
                 delete [] state->resampleTemp;
-                state->resampleTemp = 0;
+                state->resampleTemp = NULL;
             }
             state->hook = process__genericNoResampling;
             if (all16BitsStereoNoResample && !volumeRamp) {
@@ -467,115 +462,33 @@
         countActiveTracks, state->enabledTracks,
         all16BitsStereoNoResample, resampling, volumeRamp);
 
-   state->hook(state);
+    state->hook(state);
 
-   // Now that the volume ramp has been done, set optimal state and
-   // track hooks for subsequent mixer process
-   if (countActiveTracks) {
-       int allMuted = 1;
-       uint32_t en = state->enabledTracks;
-       while (en) {
-           const int i = 31 - __builtin_clz(en);
-           en &= ~(1<<i);
-           track_t& t = state->tracks[i];
-           if (!t.doesResample() && t.volumeRL == 0)
-           {
-               t.needs |= NEEDS_MUTE_ENABLED;
-               t.hook = track__nop;
-           } else {
-               allMuted = 0;
-           }
-       }
-       if (allMuted) {
-           state->hook = process__nop;
-       } else if (all16BitsStereoNoResample) {
-           if (countActiveTracks == 1) {
-              state->hook = process__OneTrack16BitsStereoNoResampling;
-           }
-       }
-   }
-}
-
-static inline
-int32_t mulAdd(int16_t in, int16_t v, int32_t a)
-{
-#if defined(__arm__) && !defined(__thumb__)
-    int32_t out;
-    asm( "smlabb %[out], %[in], %[v], %[a] \n"
-         : [out]"=r"(out)
-         : [in]"%r"(in), [v]"r"(v), [a]"r"(a)
-         : );
-    return out;
-#else
-    return a + in * int32_t(v);
-#endif
-}
-
-static inline
-int32_t mul(int16_t in, int16_t v)
-{
-#if defined(__arm__) && !defined(__thumb__)
-    int32_t out;
-    asm( "smulbb %[out], %[in], %[v] \n"
-         : [out]"=r"(out)
-         : [in]"%r"(in), [v]"r"(v)
-         : );
-    return out;
-#else
-    return in * int32_t(v);
-#endif
-}
-
-static inline
-int32_t mulAddRL(int left, uint32_t inRL, uint32_t vRL, int32_t a)
-{
-#if defined(__arm__) && !defined(__thumb__)
-    int32_t out;
-    if (left) {
-        asm( "smlabb %[out], %[inRL], %[vRL], %[a] \n"
-             : [out]"=r"(out)
-             : [inRL]"%r"(inRL), [vRL]"r"(vRL), [a]"r"(a)
-             : );
-    } else {
-        asm( "smlatt %[out], %[inRL], %[vRL], %[a] \n"
-             : [out]"=r"(out)
-             : [inRL]"%r"(inRL), [vRL]"r"(vRL), [a]"r"(a)
-             : );
+    // Now that the volume ramp has been done, set optimal state and
+    // track hooks for subsequent mixer process
+    if (countActiveTracks) {
+        int allMuted = 1;
+        uint32_t en = state->enabledTracks;
+        while (en) {
+            const int i = 31 - __builtin_clz(en);
+            en &= ~(1<<i);
+            track_t& t = state->tracks[i];
+            if (!t.doesResample() && t.volumeRL == 0)
+            {
+                t.needs |= NEEDS_MUTE_ENABLED;
+                t.hook = track__nop;
+            } else {
+                allMuted = 0;
+            }
+        }
+        if (allMuted) {
+            state->hook = process__nop;
+        } else if (all16BitsStereoNoResample) {
+            if (countActiveTracks == 1) {
+                state->hook = process__OneTrack16BitsStereoNoResampling;
+            }
+        }
     }
-    return out;
-#else
-    if (left) {
-        return a + int16_t(inRL&0xFFFF) * int16_t(vRL&0xFFFF);
-    } else {
-        return a + int16_t(inRL>>16) * int16_t(vRL>>16);
-    }
-#endif
-}
-
-static inline
-int32_t mulRL(int left, uint32_t inRL, uint32_t vRL)
-{
-#if defined(__arm__) && !defined(__thumb__)
-    int32_t out;
-    if (left) {
-        asm( "smulbb %[out], %[inRL], %[vRL] \n"
-             : [out]"=r"(out)
-             : [inRL]"%r"(inRL), [vRL]"r"(vRL)
-             : );
-    } else {
-        asm( "smultt %[out], %[inRL], %[vRL] \n"
-             : [out]"=r"(out)
-             : [inRL]"%r"(inRL), [vRL]"r"(vRL)
-             : );
-    }
-    return out;
-#else
-    if (left) {
-        return int16_t(inRL&0xFFFF) * int16_t(vRL&0xFFFF);
-    } else {
-        return int16_t(inRL>>16) * int16_t(vRL>>16);
-    }
-#endif
 }
 
 
@@ -591,13 +504,13 @@
         t->resampler->setVolume(UNITY_GAIN, UNITY_GAIN);
         memset(temp, 0, outFrameCount * MAX_NUM_CHANNELS * sizeof(int32_t));
         t->resampler->resample(temp, outFrameCount, t->bufferProvider);
-        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc) {
+        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc)) {
             volumeRampStereo(t, out, outFrameCount, temp, aux);
         } else {
             volumeStereo(t, out, outFrameCount, temp, aux);
         }
     } else {
-        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]) {
+        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1])) {
             t->resampler->setVolume(UNITY_GAIN, UNITY_GAIN);
             memset(temp, 0, outFrameCount * MAX_NUM_CHANNELS * sizeof(int32_t));
             t->resampler->resample(temp, outFrameCount, t->bufferProvider);
@@ -628,7 +541,7 @@
     //       (vl + vlInc*frameCount)/65536.0f, frameCount);
 
     // ramp volume
-    if UNLIKELY(aux != NULL) {
+    if (CC_UNLIKELY(aux != NULL)) {
         int32_t va = t->prevAuxLevel;
         const int32_t vaInc = t->auxInc;
         int32_t l;
@@ -663,7 +576,7 @@
     const int16_t vl = t->volume[0];
     const int16_t vr = t->volume[1];
 
-    if UNLIKELY(aux != NULL) {
+    if (CC_UNLIKELY(aux != NULL)) {
         const int16_t va = (int16_t)t->auxLevel;
         do {
             int16_t l = (int16_t)(*temp++ >> 12);
@@ -688,13 +601,13 @@
 
 void AudioMixer::track__16BitsStereo(track_t* t, int32_t* out, size_t frameCount, int32_t* temp, int32_t* aux)
 {
-    int16_t const *in = static_cast<int16_t const *>(t->in);
+    const int16_t *in = static_cast<const int16_t *>(t->in);
 
-    if UNLIKELY(aux != NULL) {
+    if (CC_UNLIKELY(aux != NULL)) {
         int32_t l;
         int32_t r;
         // ramp gain
-        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc) {
+        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc)) {
             int32_t vl = t->prevVolume[0];
             int32_t vr = t->prevVolume[1];
             int32_t va = t->prevAuxLevel;
@@ -727,7 +640,7 @@
             const uint32_t vrl = t->volumeRL;
             const int16_t va = (int16_t)t->auxLevel;
             do {
-                uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
+                uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
                 int16_t a = (int16_t)(((int32_t)in[0] + in[1]) >> 1);
                 in += 2;
                 out[0] = mulAddRL(1, rl, vrl, out[0]);
@@ -739,7 +652,7 @@
         }
     } else {
         // ramp gain
-        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]) {
+        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1])) {
             int32_t vl = t->prevVolume[0];
             int32_t vr = t->prevVolume[1];
             const int32_t vlInc = t->volumeInc[0];
@@ -765,7 +678,7 @@
         else {
             const uint32_t vrl = t->volumeRL;
             do {
-                uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
+                uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
                 in += 2;
                 out[0] = mulAddRL(1, rl, vrl, out[0]);
                 out[1] = mulAddRL(0, rl, vrl, out[1]);
@@ -778,11 +691,11 @@
 
 void AudioMixer::track__16BitsMono(track_t* t, int32_t* out, size_t frameCount, int32_t* temp, int32_t* aux)
 {
-    int16_t const *in = static_cast<int16_t const *>(t->in);
+    const int16_t *in = static_cast<int16_t const *>(t->in);
 
-    if UNLIKELY(aux != NULL) {
+    if (CC_UNLIKELY(aux != NULL)) {
         // ramp gain
-        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc) {
+        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1]|t->auxInc)) {
             int32_t vl = t->prevVolume[0];
             int32_t vr = t->prevVolume[1];
             int32_t va = t->prevAuxLevel;
@@ -825,7 +738,7 @@
         }
     } else {
         // ramp gain
-        if UNLIKELY(t->volumeInc[0]|t->volumeInc[1]) {
+        if (CC_UNLIKELY(t->volumeInc[0]|t->volumeInc[1])) {
             int32_t vl = t->prevVolume[0];
             int32_t vr = t->prevVolume[1];
             const int32_t vlInc = t->volumeInc[0];
@@ -862,19 +775,6 @@
     t->in = in;
 }
 
-void AudioMixer::ditherAndClamp(int32_t* out, int32_t const *sums, size_t c)
-{
-    for (size_t i=0 ; i<c ; i++) {
-        int32_t l = *sums++;
-        int32_t r = *sums++;
-        int32_t nl = l >> 12;
-        int32_t nr = r >> 12;
-        l = clamp16(nl);
-        r = clamp16(nr);
-        *out++ = (r<<16) | (l & 0xFFFF);
-    }
-}
-
 // no-op case
 void AudioMixer::process__nop(state_t* state)
 {
@@ -891,7 +791,7 @@
             i = 31 - __builtin_clz(e2);
             e2 &= ~(1<<i);
             track_t& t2 = state->tracks[i];
-            if UNLIKELY(t2.mainBuffer != t1.mainBuffer) {
+            if (CC_UNLIKELY(t2.mainBuffer != t1.mainBuffer)) {
                 e1 &= ~(1<<i);
             }
         }
@@ -949,7 +849,7 @@
             j = 31 - __builtin_clz(e2);
             e2 &= ~(1<<j);
             track_t& t2 = state->tracks[j];
-            if UNLIKELY(t2.mainBuffer != t1.mainBuffer) {
+            if (CC_UNLIKELY(t2.mainBuffer != t1.mainBuffer)) {
                 e1 &= ~(1<<j);
             }
         }
@@ -966,7 +866,7 @@
                 track_t& t = state->tracks[i];
                 size_t outFrames = BLOCKSIZE;
                 int32_t *aux = NULL;
-                if UNLIKELY((t.needs & NEEDS_AUX__MASK) == NEEDS_AUX_ENABLED) {
+                if (CC_UNLIKELY((t.needs & NEEDS_AUX__MASK) == NEEDS_AUX_ENABLED)) {
                     aux = t.auxBuffer + numFrames;
                 }
                 while (outFrames) {
@@ -975,7 +875,7 @@
                         (t.hook)(&t, outTemp + (BLOCKSIZE-outFrames)*MAX_NUM_CHANNELS, inFrames, state->resampleTemp, aux);
                         t.frameCount -= inFrames;
                         outFrames -= inFrames;
-                        if UNLIKELY(aux != NULL) {
+                        if (CC_UNLIKELY(aux != NULL)) {
                             aux += inFrames;
                         }
                     }
@@ -1010,9 +910,10 @@
 }
 
 
-  // generic code with resampling
+// generic code with resampling
 void AudioMixer::process__genericResampling(state_t* state)
 {
+    // this const just means that local variable outTemp doesn't change
     int32_t* const outTemp = state->outputTemp;
     const size_t size = sizeof(int32_t) * MAX_NUM_CHANNELS * state->frameCount;
 
@@ -1030,7 +931,7 @@
             j = 31 - __builtin_clz(e2);
             e2 &= ~(1<<j);
             track_t& t2 = state->tracks[j];
-            if UNLIKELY(t2.mainBuffer != t1.mainBuffer) {
+            if (CC_UNLIKELY(t2.mainBuffer != t1.mainBuffer)) {
                 e1 &= ~(1<<j);
             }
         }
@@ -1042,7 +943,7 @@
             e1 &= ~(1<<i);
             track_t& t = state->tracks[i];
             int32_t *aux = NULL;
-            if UNLIKELY((t.needs & NEEDS_AUX__MASK) == NEEDS_AUX_ENABLED) {
+            if (CC_UNLIKELY((t.needs & NEEDS_AUX__MASK) == NEEDS_AUX_ENABLED)) {
                 aux = t.auxBuffer;
             }
 
@@ -1063,7 +964,7 @@
                     // been enabled for mixing.
                     if (t.in == NULL) break;
 
-                    if UNLIKELY(aux != NULL) {
+                    if (CC_UNLIKELY(aux != NULL)) {
                         aux += outFrames;
                     }
                     (t.hook)(&t, outTemp + outFrames*MAX_NUM_CHANNELS, t.buffer.frameCount, state->resampleTemp, aux);
@@ -1093,7 +994,7 @@
     while (numFrames) {
         b.frameCount = numFrames;
         t.bufferProvider->getNextBuffer(&b);
-        int16_t const *in = b.i16;
+        const int16_t *in = b.i16;
 
         // in == NULL can happen if the track was flushed just after having
         // been enabled for mixing.
@@ -1105,11 +1006,11 @@
         }
         size_t outFrames = b.frameCount;
 
-        if (UNLIKELY(uint32_t(vl) > UNITY_GAIN || uint32_t(vr) > UNITY_GAIN)) {
+        if (CC_UNLIKELY(uint32_t(vl) > UNITY_GAIN || uint32_t(vr) > UNITY_GAIN)) {
             // volume is boosted, so we might need to clamp even though
             // we process only one track.
             do {
-                uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
+                uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
                 in += 2;
                 int32_t l = mulRL(1, rl, vrl) >> 12;
                 int32_t r = mulRL(0, rl, vrl) >> 12;
@@ -1120,7 +1021,7 @@
             } while (--outFrames);
         } else {
             do {
-                uint32_t rl = *reinterpret_cast<uint32_t const *>(in);
+                uint32_t rl = *reinterpret_cast<const uint32_t *>(in);
                 in += 2;
                 int32_t l = mulRL(1, rl, vrl) >> 12;
                 int32_t r = mulRL(0, rl, vrl) >> 12;
@@ -1132,6 +1033,7 @@
     }
 }
 
+#if 0
 // 2 tracks is also a common case
 // NEVER used in current implementation of process__validate()
 // only use if the 2 tracks have the same output buffer
@@ -1149,12 +1051,12 @@
     const track_t& t1 = state->tracks[i];
     AudioBufferProvider::Buffer& b1(t1.buffer);
 
-    int16_t const *in0;
+    const int16_t *in0;
     const int16_t vl0 = t0.volume[0];
     const int16_t vr0 = t0.volume[1];
     size_t frameCount0 = 0;
 
-    int16_t const *in1;
+    const int16_t *in1;
     const int16_t vl1 = t1.volume[0];
     const int16_t vr1 = t1.volume[1];
     size_t frameCount1 = 0;
@@ -1162,7 +1064,7 @@
     //FIXME: only works if two tracks use same buffer
     int32_t* out = t0.mainBuffer;
     size_t numFrames = state->frameCount;
-    int16_t const *buff = NULL;
+    const int16_t *buff = NULL;
 
 
     while (numFrames) {
@@ -1190,7 +1092,7 @@
                 }
                 in1 = buff;
                 b1.frameCount = numFrames;
-               } else {
+            } else {
                 in1 = b1.i16;
             }
             frameCount1 = b1.frameCount;
@@ -1229,7 +1131,7 @@
         delete [] buff;
     }
 }
+#endif
 
 // ----------------------------------------------------------------------------
 }; // namespace android
-
diff --git a/services/audioflinger/AudioMixer.h b/services/audioflinger/AudioMixer.h
index 0137185..84f6330 100644
--- a/services/audioflinger/AudioMixer.h
+++ b/services/audioflinger/AudioMixer.h
@@ -28,11 +28,6 @@
 
 // ----------------------------------------------------------------------------
 
-#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
-#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
-
-// ----------------------------------------------------------------------------
-
 class AudioMixer
 {
 public:
@@ -47,11 +42,10 @@
 
     enum { // names
 
-        // track units (32 units)
+        // track names (MAX_NUM_TRACKS units)
         TRACK0          = 0x1000,
 
-        // enable/disable
-        MIXING          = 0x2000,
+        // 0x2000 is unused
 
         // setParameter targets
         TRACK           = 0x3000,
@@ -65,32 +59,30 @@
         FORMAT          = 0x4001,
         MAIN_BUFFER     = 0x4002,
         AUX_BUFFER      = 0x4003,
-        // for TARGET RESAMPLE
+        // for target RESAMPLE
         SAMPLE_RATE     = 0x4100,
         RESET           = 0x4101,
-        // for TARGET VOLUME (8 channels max)
+        // for target RAMP_VOLUME and VOLUME (8 channels max)
         VOLUME0         = 0x4200,
         VOLUME1         = 0x4201,
         AUXLEVEL        = 0x4210,
     };
 
 
+    // For all APIs with "name": TRACK0 <= name < TRACK0 + MAX_NUM_TRACKS
     int         getTrackName();
     void        deleteTrackName(int name);
 
-    status_t    enable(int name);
-    status_t    disable(int name);
+    void        enable(int name);
+    void        disable(int name);
 
-    status_t    setActiveTrack(int track);
-    status_t    setParameter(int target, int name, void *value);
+    void        setParameter(int name, int target, int param, void *value);
 
-    status_t    setBufferProvider(AudioBufferProvider* bufferProvider);
+    void        setBufferProvider(int name, AudioBufferProvider* bufferProvider);
     void        process();
 
     uint32_t    trackNames() const { return mTrackNames; }
 
-    static void ditherAndClamp(int32_t* out, int32_t const *sums, size_t c);
-
     size_t      getUnreleasedFrames(int name);
 
 private:
@@ -119,11 +111,6 @@
         NEEDS_AUX_ENABLED      = 0x00010000,
     };
 
-    static inline int32_t applyVolume(int32_t in, int32_t v) {
-        return in * v;
-    }
-
-
     struct state_t;
     struct track_t;
 
@@ -135,13 +122,13 @@
         uint32_t    needs;
 
         union {
-        int16_t     volume[2];      // [0]3.12 fixed point
+        int16_t     volume[MAX_NUM_CHANNELS]; // [0]3.12 fixed point
         int32_t     volumeRL;
         };
 
-        int32_t     prevVolume[2];
+        int32_t     prevVolume[MAX_NUM_CHANNELS];
 
-        int32_t     volumeInc[2];
+        int32_t     volumeInc[MAX_NUM_CHANNELS];
         int32_t     auxLevel;
         int32_t     auxInc;
         int32_t     prevAuxLevel;
@@ -158,7 +145,7 @@
         mutable AudioBufferProvider::Buffer buffer;
 
         hook_t      hook;
-        void const* in;             // current location in buffer
+        const void* in;             // current location in buffer
 
         AudioResampler*     resampler;
         uint32_t            sampleRate;
@@ -181,10 +168,10 @@
         int32_t         *outputTemp;
         int32_t         *resampleTemp;
         int32_t         reserved[2];
-        track_t         tracks[32]; __attribute__((aligned(32)));
+        track_t         tracks[MAX_NUM_TRACKS]; __attribute__((aligned(32)));
     };
 
-    int             mActiveTrack;
+    // bitmask of allocated track names, where bit 0 corresponds to TRACK0 etc.
     uint32_t        mTrackNames;
     const uint32_t  mSampleRate;
 
@@ -204,7 +191,9 @@
     static void process__genericNoResampling(state_t* state);
     static void process__genericResampling(state_t* state);
     static void process__OneTrack16BitsStereoNoResampling(state_t* state);
+#if 0
     static void process__TwoTracks16BitsStereoNoResampling(state_t* state);
+#endif
 };
 
 // ----------------------------------------------------------------------------
diff --git a/services/audioflinger/AudioPolicyService.cpp b/services/audioflinger/AudioPolicyService.cpp
index 6be669b..28b1c89 100644
--- a/services/audioflinger/AudioPolicyService.cpp
+++ b/services/audioflinger/AudioPolicyService.cpp
@@ -31,7 +31,6 @@
 #include <utils/threads.h>
 #include "AudioPolicyService.h"
 #include <cutils/properties.h>
-#include <dlfcn.h>
 #include <hardware_legacy/power.h>
 #include <media/AudioEffect.h>
 #include <media/EffectsFactoryApi.h>
@@ -44,11 +43,11 @@
 
 namespace android {
 
-static const char *kDeadlockedString = "AudioPolicyService may be deadlocked\n";
-static const char *kCmdDeadlockedString = "AudioPolicyService command thread may be deadlocked\n";
+static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
+static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
 
 static const int kDumpLockRetries = 50;
-static const int kDumpLockSleep = 20000;
+static const int kDumpLockSleepUs = 20000;
 
 static bool checkPermission() {
     if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
@@ -186,7 +185,7 @@
                                                       device_address);
 }
 
-status_t AudioPolicyService::setPhoneState(int state)
+status_t AudioPolicyService::setPhoneState(audio_mode_t state)
 {
     if (mpAudioPolicy == NULL) {
         return NO_INIT;
@@ -194,7 +193,7 @@
     if (!checkPermission()) {
         return PERMISSION_DENIED;
     }
-    if (state < 0 || state >= AUDIO_MODE_CNT) {
+    if (uint32_t(state) >= AUDIO_MODE_CNT) {
         return BAD_VALUE;
     }
 
@@ -208,19 +207,6 @@
     return NO_ERROR;
 }
 
-status_t AudioPolicyService::setRingerMode(uint32_t mode, uint32_t mask)
-{
-    if (mpAudioPolicy == NULL) {
-        return NO_INIT;
-    }
-    if (!checkPermission()) {
-        return PERMISSION_DENIED;
-    }
-
-    mpAudioPolicy->set_ringer_mode(mpAudioPolicy, mode, mask);
-    return NO_ERROR;
-}
-
 status_t AudioPolicyService::setForceUse(audio_policy_force_use_t usage,
                                          audio_policy_forced_cfg_t config)
 {
@@ -255,7 +241,7 @@
 
 audio_io_handle_t AudioPolicyService::getOutput(audio_stream_type_t stream,
                                     uint32_t samplingRate,
-                                    uint32_t format,
+                                    audio_format_t format,
                                     uint32_t channels,
                                     audio_policy_output_flags_t flags)
 {
@@ -303,7 +289,7 @@
 
 audio_io_handle_t AudioPolicyService::getInput(int inputSource,
                                     uint32_t samplingRate,
-                                    uint32_t format,
+                                    audio_format_t format,
                                     uint32_t channels,
                                     audio_in_acoustics_t acoustics,
                                     int audioSession)
@@ -401,14 +387,16 @@
     if (!checkPermission()) {
         return PERMISSION_DENIED;
     }
-    if (stream < 0 || stream >= AUDIO_STREAM_CNT) {
+    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
         return BAD_VALUE;
     }
     mpAudioPolicy->init_stream_volume(mpAudioPolicy, stream, indexMin, indexMax);
     return NO_ERROR;
 }
 
-status_t AudioPolicyService::setStreamVolumeIndex(audio_stream_type_t stream, int index)
+status_t AudioPolicyService::setStreamVolumeIndex(audio_stream_type_t stream,
+                                                  int index,
+                                                  audio_devices_t device)
 {
     if (mpAudioPolicy == NULL) {
         return NO_INIT;
@@ -416,22 +404,38 @@
     if (!checkPermission()) {
         return PERMISSION_DENIED;
     }
-    if (stream < 0 || stream >= AUDIO_STREAM_CNT) {
+    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
         return BAD_VALUE;
     }
 
-    return mpAudioPolicy->set_stream_volume_index(mpAudioPolicy, stream, index);
+    if (mpAudioPolicy->set_stream_volume_index_for_device) {
+        return mpAudioPolicy->set_stream_volume_index_for_device(mpAudioPolicy,
+                                                                stream,
+                                                                index,
+                                                                device);
+    } else {
+        return mpAudioPolicy->set_stream_volume_index(mpAudioPolicy, stream, index);
+    }
 }
 
-status_t AudioPolicyService::getStreamVolumeIndex(audio_stream_type_t stream, int *index)
+status_t AudioPolicyService::getStreamVolumeIndex(audio_stream_type_t stream,
+                                                  int *index,
+                                                  audio_devices_t device)
 {
     if (mpAudioPolicy == NULL) {
         return NO_INIT;
     }
-    if (stream < 0 || stream >= AUDIO_STREAM_CNT) {
+    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
         return BAD_VALUE;
     }
-    return mpAudioPolicy->get_stream_volume_index(mpAudioPolicy, stream, index);
+    if (mpAudioPolicy->get_stream_volume_index_for_device) {
+        return mpAudioPolicy->get_stream_volume_index_for_device(mpAudioPolicy,
+                                                                stream,
+                                                                index,
+                                                                device);
+    } else {
+        return mpAudioPolicy->get_stream_volume_index(mpAudioPolicy, stream, index);
+    }
 }
 
 uint32_t AudioPolicyService::getStrategyForStream(audio_stream_type_t stream)
@@ -487,7 +491,7 @@
     return mpAudioPolicy->set_effect_enabled(mpAudioPolicy, id, enabled);
 }
 
-bool AudioPolicyService::isStreamActive(int stream, uint32_t inPastMs) const
+bool AudioPolicyService::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
 {
     if (mpAudioPolicy == NULL) {
         return 0;
@@ -546,7 +550,7 @@
             locked = true;
             break;
         }
-        usleep(kDumpLockSleep);
+        usleep(kDumpLockSleepUs);
     }
     return locked;
 }
@@ -570,7 +574,7 @@
 
 status_t AudioPolicyService::dump(int fd, const Vector<String16>& args)
 {
-    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
+    if (!checkCallingPermission(String16("android.permission.DUMP"))) {
         dumpPermissionDenial(fd);
     } else {
         bool locked = tryLock(mLock);
@@ -782,7 +786,7 @@
     return NO_ERROR;
 }
 
-void AudioPolicyService::AudioCommandThread::startToneCommand(int type, int stream)
+void AudioPolicyService::AudioCommandThread::startToneCommand(int type, audio_stream_type_t stream)
 {
     AudioCommand *command = new AudioCommand();
     command->mCommand = START_TONE;
@@ -809,7 +813,7 @@
     mWaitWorkCV.signal();
 }
 
-status_t AudioPolicyService::AudioCommandThread::volumeCommand(int stream,
+status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
                                                                float volume,
                                                                int output,
                                                                int delayMs)
@@ -1020,7 +1024,7 @@
                                         audio_io_handle_t output,
                                         int delayMs)
 {
-    return (int)mAudioCommandThread->volumeCommand((int)stream, volume,
+    return (int)mAudioCommandThread->volumeCommand(stream, volume,
                                                    (int)output, delayMs);
 }
 
@@ -1052,7 +1056,7 @@
 // Audio pre-processing configuration
 // ----------------------------------------------------------------------------
 
-const char *AudioPolicyService::kInputSourceNames[AUDIO_SOURCE_CNT -1] = {
+/*static*/ const char * const AudioPolicyService::kInputSourceNames[AUDIO_SOURCE_CNT -1] = {
     MIC_SRC_TAG,
     VOICE_UL_SRC_TAG,
     VOICE_DL_SRC_TAG,
@@ -1348,7 +1352,7 @@
 static audio_io_handle_t aps_open_output(void *service,
                                              uint32_t *pDevices,
                                              uint32_t *pSamplingRate,
-                                             uint32_t *pFormat,
+                                             audio_format_t *pFormat,
                                              uint32_t *pChannels,
                                              uint32_t *pLatencyMs,
                                              audio_policy_output_flags_t flags)
@@ -1409,7 +1413,7 @@
 static audio_io_handle_t aps_open_input(void *service,
                                             uint32_t *pDevices,
                                             uint32_t *pSamplingRate,
-                                            uint32_t *pFormat,
+                                            audio_format_t *pFormat,
                                             uint32_t *pChannels,
                                             uint32_t acoustics)
 {
diff --git a/services/audioflinger/AudioPolicyService.h b/services/audioflinger/AudioPolicyService.h
index d898a53..9811670 100644
--- a/services/audioflinger/AudioPolicyService.h
+++ b/services/audioflinger/AudioPolicyService.h
@@ -19,6 +19,7 @@
 
 #include <cutils/misc.h>
 #include <cutils/config_utils.h>
+#include <utils/String8.h>
 #include <utils/Vector.h>
 #include <utils/SortedVector.h>
 #include <binder/BinderService.h>
@@ -31,8 +32,6 @@
 
 namespace android {
 
-class String8;
-
 // ----------------------------------------------------------------------------
 
 class AudioPolicyService :
@@ -59,13 +58,12 @@
     virtual audio_policy_dev_state_t getDeviceConnectionState(
                                                                 audio_devices_t device,
                                                                 const char *device_address);
-    virtual status_t setPhoneState(int state);
-    virtual status_t setRingerMode(uint32_t mode, uint32_t mask);
+    virtual status_t setPhoneState(audio_mode_t state);
     virtual status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config);
     virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage);
     virtual audio_io_handle_t getOutput(audio_stream_type_t stream,
                                         uint32_t samplingRate = 0,
-                                        uint32_t format = AUDIO_FORMAT_DEFAULT,
+                                        audio_format_t format = AUDIO_FORMAT_DEFAULT,
                                         uint32_t channels = 0,
                                         audio_policy_output_flags_t flags =
                                             AUDIO_POLICY_OUTPUT_FLAG_INDIRECT);
@@ -78,7 +76,7 @@
     virtual void releaseOutput(audio_io_handle_t output);
     virtual audio_io_handle_t getInput(int inputSource,
                                     uint32_t samplingRate = 0,
-                                    uint32_t format = AUDIO_FORMAT_DEFAULT,
+                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
                                     uint32_t channels = 0,
                                     audio_in_acoustics_t acoustics =
                                             (audio_in_acoustics_t)0,
@@ -89,8 +87,12 @@
     virtual status_t initStreamVolume(audio_stream_type_t stream,
                                       int indexMin,
                                       int indexMax);
-    virtual status_t setStreamVolumeIndex(audio_stream_type_t stream, int index);
-    virtual status_t getStreamVolumeIndex(audio_stream_type_t stream, int *index);
+    virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
+                                          int index,
+                                          audio_devices_t device);
+    virtual status_t getStreamVolumeIndex(audio_stream_type_t stream,
+                                          int *index,
+                                          audio_devices_t device);
 
     virtual uint32_t getStrategyForStream(audio_stream_type_t stream);
     virtual uint32_t getDevicesForStream(audio_stream_type_t stream);
@@ -103,7 +105,7 @@
                                     int id);
     virtual status_t unregisterEffect(int id);
     virtual status_t setEffectEnabled(int id, bool enabled);
-    virtual bool isStreamActive(int stream, uint32_t inPastMs = 0) const;
+    virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const;
 
     virtual status_t queryDefaultPreProcessing(int audioSession,
                                               effect_descriptor_t *descriptors,
@@ -169,9 +171,9 @@
         virtual     bool        threadLoop();
 
                     void        exit();
-                    void        startToneCommand(int type = 0, int stream = 0);
+                    void        startToneCommand(int type = 0, audio_stream_type_t stream = AUDIO_STREAM_VOICE_CALL);
                     void        stopToneCommand();
-                    status_t    volumeCommand(int stream, float volume, int output, int delayMs = 0);
+                    status_t    volumeCommand(audio_stream_type_t stream, float volume, int output, int delayMs = 0);
                     status_t    parametersCommand(int ioHandle, const char *keyValuePairs, int delayMs = 0);
                     status_t    voiceVolumeCommand(float volume, int delayMs = 0);
                     void        insertCommand_l(AudioCommand *command, int delayMs = 0);
@@ -197,12 +199,12 @@
         class ToneData {
         public:
             int mType;      // tone type (START_TONE only)
-            int mStream;    // stream type (START_TONE only)
+            audio_stream_type_t mStream;    // stream type (START_TONE only)
         };
 
         class VolumeData {
         public:
-            int mStream;
+            audio_stream_type_t mStream;
             float mVolume;
             int mIO;
         };
@@ -251,7 +253,7 @@
         Vector< sp<AudioEffect> >mEffects;
     };
 
-    static const char *kInputSourceNames[AUDIO_SOURCE_CNT -1];
+    static const char * const kInputSourceNames[AUDIO_SOURCE_CNT -1];
 
     void setPreProcessorEnabled(InputDesc *inputDesc, bool enabled);
     status_t loadPreProcessorConfig(const char *path);
diff --git a/services/audioflinger/AudioResampler.cpp b/services/audioflinger/AudioResampler.cpp
index 4586b54..feacd96 100644
--- a/services/audioflinger/AudioResampler.cpp
+++ b/services/audioflinger/AudioResampler.cpp
@@ -390,6 +390,7 @@
 *       phaseFraction : phase fraction for next interpolation
 *
 *******************************************************************/
+__attribute__((noinline))
 void AudioResamplerOrder1::AsmMono16Loop(int16_t *in, int32_t* maxOutPt, int32_t maxInIdx,
             size_t &outputIndex, int32_t* out, size_t &inputIndex, int32_t vl, int32_t vr,
             uint32_t &phaseFraction, uint32_t phaseIncrement)
@@ -500,6 +501,7 @@
 *       phaseFraction : phase fraction for next interpolation
 *
 *******************************************************************/
+__attribute__((noinline))
 void AudioResamplerOrder1::AsmStereo16Loop(int16_t *in, int32_t* maxOutPt, int32_t maxInIdx,
             size_t &outputIndex, int32_t* out, size_t &inputIndex, int32_t vl, int32_t vr,
             uint32_t &phaseFraction, uint32_t phaseIncrement)
@@ -600,6 +602,5 @@
 
 
 // ----------------------------------------------------------------------------
-}
-; // namespace android
 
+} // namespace android
diff --git a/services/audioflinger/AudioResamplerSinc.cpp b/services/audioflinger/AudioResamplerSinc.cpp
index 9e5e254..d012433 100644
--- a/services/audioflinger/AudioResamplerSinc.cpp
+++ b/services/audioflinger/AudioResamplerSinc.cpp
@@ -284,7 +284,7 @@
 **/
 void AudioResamplerSinc::read(
         int16_t*& impulse, uint32_t& phaseFraction,
-        int16_t const* in, size_t inputIndex)
+        const int16_t* in, size_t inputIndex)
 {
     const uint32_t phaseIndex = phaseFraction >> kNumPhaseBits;
     impulse += CHANNELS;
@@ -302,7 +302,7 @@
 
 template<int CHANNELS>
 void AudioResamplerSinc::filterCoefficient(
-        int32_t& l, int32_t& r, uint32_t phase, int16_t const *samples)
+        int32_t& l, int32_t& r, uint32_t phase, const int16_t *samples)
 {
     // compute the index of the coefficient on the positive side and
     // negative side
@@ -317,9 +317,9 @@
 
     l = 0;
     r = 0;
-    int32_t const* coefs = mFirCoefs;
-    int16_t const *sP = samples;
-    int16_t const *sN = samples+CHANNELS;
+    const int32_t* coefs = mFirCoefs;
+    const int16_t *sP = samples;
+    const int16_t *sN = samples+CHANNELS;
     for (unsigned int i=0 ; i<halfNumCoefs/4 ; i++) {
         interpolate<CHANNELS>(l, r, coefs+indexP, lerpP, sP);
         interpolate<CHANNELS>(l, r, coefs+indexN, lerpN, sN);
@@ -339,13 +339,13 @@
 template<int CHANNELS>
 void AudioResamplerSinc::interpolate(
         int32_t& l, int32_t& r,
-        int32_t const* coefs, int16_t lerp, int16_t const* samples)
+        const int32_t* coefs, int16_t lerp, const int16_t* samples)
 {
     int32_t c0 = coefs[0];
     int32_t c1 = coefs[1];
     int32_t sinc = mulAdd(lerp, (c1-c0)<<1, c0);
     if (CHANNELS == 2) {
-        uint32_t rl = *reinterpret_cast<uint32_t const*>(samples);
+        uint32_t rl = *reinterpret_cast<const uint32_t*>(samples);
         l = mulAddRL(1, rl, sinc, l);
         r = mulAddRL(0, rl, sinc, r);
     } else {
diff --git a/services/audioflinger/AudioResamplerSinc.h b/services/audioflinger/AudioResamplerSinc.h
index e6cb90b..0e1bc44 100644
--- a/services/audioflinger/AudioResamplerSinc.h
+++ b/services/audioflinger/AudioResamplerSinc.h
@@ -44,22 +44,22 @@
 
     template<int CHANNELS>
     inline void filterCoefficient(
-            int32_t& l, int32_t& r, uint32_t phase, int16_t const *samples);
+            int32_t& l, int32_t& r, uint32_t phase, const int16_t *samples);
 
     template<int CHANNELS>
     inline void interpolate(
             int32_t& l, int32_t& r,
-            int32_t const* coefs, int16_t lerp, int16_t const* samples);
+            const int32_t* coefs, int16_t lerp, const int16_t* samples);
 
     template<int CHANNELS>
     inline void read(int16_t*& impulse, uint32_t& phaseFraction,
-            int16_t const* in, size_t inputIndex);
+            const int16_t* in, size_t inputIndex);
 
     int16_t *mState;
     int16_t *mImpulse;
     int16_t *mRingFull;
 
-    int32_t const * mFirCoefs;
+    const int32_t * mFirCoefs;
     static const int32_t mFirCoefsDown[];
     static const int32_t mFirCoefsUp[];
 
diff --git a/services/camera/libcameraservice/CameraHardwareInterface.h b/services/camera/libcameraservice/CameraHardwareInterface.h
index 34087b5..2ac69f78 100644
--- a/services/camera/libcameraservice/CameraHardwareInterface.h
+++ b/services/camera/libcameraservice/CameraHardwareInterface.h
@@ -635,6 +635,12 @@
         return native_window_set_crop(a, &crop);
     }
 
+    static int __set_timestamp(struct preview_stream_ops *w,
+                               int64_t timestamp) {
+        ANativeWindow *a = anw(w);
+        return native_window_set_buffers_timestamp(a, timestamp);
+    }
+
     static int __set_usage(struct preview_stream_ops* w, int usage)
     {
         ANativeWindow *a = anw(w);
@@ -664,6 +670,7 @@
         mHalPreviewWindow.nw.set_buffer_count = __set_buffer_count;
         mHalPreviewWindow.nw.set_buffers_geometry = __set_buffers_geometry;
         mHalPreviewWindow.nw.set_crop = __set_crop;
+        mHalPreviewWindow.nw.set_timestamp = __set_timestamp;
         mHalPreviewWindow.nw.set_usage = __set_usage;
         mHalPreviewWindow.nw.set_swap_interval = __set_swap_interval;
 
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index 918f31e..06fc708 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -351,7 +351,7 @@
 
     // Enable zoom, error, focus, and metadata messages by default
     enableMsgType(CAMERA_MSG_ERROR | CAMERA_MSG_ZOOM | CAMERA_MSG_FOCUS |
-                  CAMERA_MSG_PREVIEW_METADATA);
+                  CAMERA_MSG_PREVIEW_METADATA | CAMERA_MSG_FOCUS_MOVE);
 
     // Callback is disabled by default
     mPreviewCallbackFlag = CAMERA_FRAME_CALLBACK_FLAG_NOOP;