Merge "Add MTP and PTP OS descriptors." into oc-mr1-dev am: 71113d84ea  -s ours
am: 58106d1954

Change-Id: Ic888672cb3a51e33edd18fef380be09cd20b868e
diff --git a/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp b/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp
index cb69f91..eaa3390 100644
--- a/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp
+++ b/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp
@@ -89,7 +89,7 @@
     // asset_id change. If it sends an EcmContainer with 2 Ecms with different
     // asset_ids (old and new) then it might be best to prefetch the Emm.
     if ((asset_.id() != 0) && (*asset_id != asset_.id())) {
-        ALOGW("Asset_id change from %" PRIu64 " to %" PRIu64, asset_.id(), *asset_id);
+        ALOGW("Asset_id change from %llu to %" PRIu64, asset_.id(), *asset_id);
         asset_.Clear();
     }
 
diff --git a/drm/mediacas/plugins/mock/MockCasPlugin.cpp b/drm/mediacas/plugins/mock/MockCasPlugin.cpp
index 18cd9a4..500208b 100644
--- a/drm/mediacas/plugins/mock/MockCasPlugin.cpp
+++ b/drm/mediacas/plugins/mock/MockCasPlugin.cpp
@@ -146,7 +146,7 @@
     if (session == NULL) {
         return BAD_VALUE;
     }
-    ALOGV("ECM: size=%d", ecm.size());
+    ALOGV("ECM: size=%zu", ecm.size());
     ALOGV("ECM: data=%s", arrayToString(ecm).string());
 
     return OK;
@@ -156,7 +156,7 @@
     ALOGV("processEmm");
     Mutex::Autolock lock(mLock);
 
-    ALOGV("EMM: size=%d", emm.size());
+    ALOGV("EMM: size=%zu", emm.size());
     ALOGV("EMM: data=%s", arrayToString(emm).string());
 
     return OK;
diff --git a/include/OWNERS b/include/OWNERS
index 3cb6d9c..d6bd998 100644
--- a/include/OWNERS
+++ b/include/OWNERS
@@ -1,5 +1,5 @@
 elaurent@google.com
-gkasten@android.com
+gkasten@google.com
 hunga@google.com
 jtinker@google.com
 lajos@google.com
diff --git a/include/common_time/OWNERS b/include/common_time/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/include/common_time/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/include/media/IAudioRecord.h b/include/media/IAudioRecord.h
deleted file mode 120000
index 7fbf8f2..0000000
--- a/include/media/IAudioRecord.h
+++ /dev/null
@@ -1 +0,0 @@
-../../media/libaudioclient/include/media/IAudioRecord.h
\ No newline at end of file
diff --git a/include/media/VolumeShaper.h b/include/media/VolumeShaper.h
index 302641f..a3aaece 100644
--- a/include/media/VolumeShaper.h
+++ b/include/media/VolumeShaper.h
@@ -37,6 +37,8 @@
 
 namespace android {
 
+namespace media {
+
 // The native VolumeShaper class mirrors the java VolumeShaper class;
 // in addition, the native class contains implementation for actual operation.
 //
@@ -101,7 +103,7 @@
      * See "frameworks/base/media/java/android/media/VolumeShaper.java" for
      * details on the Java implementation.
      */
-    class Configuration : public Interpolator<S, T>, public RefBase {
+    class Configuration : public Interpolator<S, T>, public RefBase, public Parcelable {
     public:
         // Must match with VolumeShaper.java in frameworks/base.
         enum Type : int32_t {
@@ -283,7 +285,7 @@
         }
 
         // The parcel layout must match VolumeShaper.java
-        status_t writeToParcel(Parcel *parcel) const {
+        status_t writeToParcel(Parcel *parcel) const override {
             if (parcel == nullptr) return BAD_VALUE;
             return parcel->writeInt32((int32_t)mType)
                     ?: parcel->writeInt32(mId)
@@ -294,17 +296,17 @@
                             ?: Interpolator<S, T>::writeToParcel(parcel);
         }
 
-        status_t readFromParcel(const Parcel &parcel) {
+        status_t readFromParcel(const Parcel *parcel) override {
             int32_t type, optionFlags;
-            return parcel.readInt32(&type)
+            return parcel->readInt32(&type)
                     ?: setType((Type)type)
-                    ?: parcel.readInt32(&mId)
+                    ?: parcel->readInt32(&mId)
                     ?: mType == TYPE_ID
                         ? NO_ERROR
-                        : parcel.readInt32(&optionFlags)
+                        : parcel->readInt32(&optionFlags)
                             ?: setOptionFlags((OptionFlag)optionFlags)
-                            ?: parcel.readDouble(&mDurationMs)
-                            ?: Interpolator<S, T>::readFromParcel(parcel)
+                            ?: parcel->readDouble(&mDurationMs)
+                            ?: Interpolator<S, T>::readFromParcel(*parcel)
                             ?: checkCurve();
         }
 
@@ -336,7 +338,7 @@
      * See "frameworks/base/media/java/android/media/VolumeShaper.java" for
      * details on the Java implementation.
      */
-    class Operation : public RefBase {
+    class Operation : public RefBase, public Parcelable {
     public:
         // Must match with VolumeShaper.java.
         enum Flag : int32_t {
@@ -418,18 +420,18 @@
             return NO_ERROR;
         }
 
-        status_t writeToParcel(Parcel *parcel) const {
+        status_t writeToParcel(Parcel *parcel) const override {
             if (parcel == nullptr) return BAD_VALUE;
             return parcel->writeInt32((int32_t)mFlags)
                     ?: parcel->writeInt32(mReplaceId)
                     ?: parcel->writeFloat(mXOffset);
         }
 
-        status_t readFromParcel(const Parcel &parcel) {
+        status_t readFromParcel(const Parcel *parcel) override {
             int32_t flags;
-            return parcel.readInt32(&flags)
-                    ?: parcel.readInt32(&mReplaceId)
-                    ?: parcel.readFloat(&mXOffset)
+            return parcel->readInt32(&flags)
+                    ?: parcel->readInt32(&mReplaceId)
+                    ?: parcel->readFloat(&mXOffset)
                     ?: setFlags((Flag)flags);
         }
 
@@ -455,7 +457,7 @@
      * See "frameworks/base/media/java/android/media/VolumeShaper.java" for
      * details on the Java implementation.
      */
-    class State : public RefBase {
+    class State : public RefBase, public Parcelable {
     public:
         State(T volume, S xOffset)
             : mVolume(volume)
@@ -481,15 +483,15 @@
             mXOffset = xOffset;
         }
 
-        status_t writeToParcel(Parcel *parcel) const {
+        status_t writeToParcel(Parcel *parcel) const override {
             if (parcel == nullptr) return BAD_VALUE;
             return parcel->writeFloat(mVolume)
                     ?: parcel->writeFloat(mXOffset);
         }
 
-        status_t readFromParcel(const Parcel &parcel) {
-            return parcel.readFloat(&mVolume)
-                     ?: parcel.readFloat(&mXOffset);
+        status_t readFromParcel(const Parcel *parcel) override {
+            return parcel->readFloat(&mVolume)
+                     ?: parcel->readFloat(&mXOffset);
         }
 
         std::string toString() const {
@@ -1020,6 +1022,8 @@
     std::list<VolumeShaper> mVolumeShapers; // list provides stable iterators on erase
 }; // VolumeHandler
 
+} // namespace media
+
 } // namespace android
 
 #pragma pop_macro("LOG_TAG")
diff --git a/include/media/nbaio/ReportPerformance.h b/include/media/nbaio/ReportPerformance.h
new file mode 120000
index 0000000..bd596e3
--- /dev/null
+++ b/include/media/nbaio/ReportPerformance.h
@@ -0,0 +1 @@
+../../../media/libnbaio/include/media/nbaio/ReportPerformance.h
\ No newline at end of file
diff --git a/include/private/media/OWNERS b/include/private/media/OWNERS
new file mode 100644
index 0000000..21723ba
--- /dev/null
+++ b/include/private/media/OWNERS
@@ -0,0 +1,3 @@
+elaurent@google.com
+gkasten@google.com
+hunga@google.com
diff --git a/include/soundtrigger/OWNERS b/include/soundtrigger/OWNERS
new file mode 100644
index 0000000..e83f6b9
--- /dev/null
+++ b/include/soundtrigger/OWNERS
@@ -0,0 +1,2 @@
+elaurent@google.com
+thorntonc@google.com
diff --git a/media/audioserver/Android.mk b/media/audioserver/Android.mk
index 3ee7494..0777890 100644
--- a/media/audioserver/Android.mk
+++ b/media/audioserver/Android.mk
@@ -3,7 +3,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := \
-	main_audioserver.cpp
+	main_audioserver.cpp \
+	../libaudioclient/aidl/android/media/IAudioRecord.aidl
 
 LOCAL_SHARED_LIBRARIES := \
 	libaaudioservice \
@@ -36,6 +37,9 @@
 	$(call include-path-for, audio-utils) \
 	external/sonic \
 
+LOCAL_AIDL_INCLUDES := \
+        frameworks/av/media/libaudioclient/aidl
+
 # If AUDIOSERVER_MULTILIB in device.mk is non-empty then it is used to control
 # the LOCAL_MULTILIB for all audioserver exclusive libraries.
 # This is relevant for 64 bit architectures where either or both
diff --git a/media/audioserver/OWNERS b/media/audioserver/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/media/audioserver/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/media/common_time/OWNERS b/media/common_time/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/media/common_time/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/media/libaaudio/src/Android.mk b/media/libaaudio/src/Android.mk
index cfcf27a..112a192 100644
--- a/media/libaaudio/src/Android.mk
+++ b/media/libaaudio/src/Android.mk
@@ -27,6 +27,8 @@
     $(LOCAL_PATH)/legacy \
     $(LOCAL_PATH)/utility
 
+LOCAL_AIDL_INCLUDES := frameworks/av/media/libaudioclient/aidl
+
 # If you add a file here then also add it below in the SHARED target
 LOCAL_SRC_FILES = \
     core/AudioStream.cpp \
@@ -57,7 +59,9 @@
     binding/IAAudioService.cpp \
     binding/RingBufferParcelable.cpp \
     binding/SharedMemoryParcelable.cpp \
-    binding/SharedRegionParcelable.cpp
+    binding/SharedRegionParcelable.cpp \
+    ../../libaudioclient/aidl/android/media/IAudioRecord.aidl \
+    ../../libaudioclient/aidl/android/media/IPlayer.aidl
 
 LOCAL_CFLAGS += -Wno-unused-parameter -Wall -Werror
 
diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp
index 61c946c..98e8d95 100644
--- a/media/libaudioclient/Android.bp
+++ b/media/libaudioclient/Android.bp
@@ -6,7 +6,22 @@
 
 cc_library_shared {
     name: "libaudioclient",
+
+    aidl: {
+        export_aidl_headers: true,
+        local_include_dirs: ["aidl"],
+        include_dirs: [
+            "frameworks/av/media/libaudioclient/aidl",
+        ],
+    },
+
     srcs: [
+        // AIDL files for audioclient interfaces
+        // The headers for these interfaces will be available to any modules that
+        // include libaudioclient, at the path "aidl/package/path/BnFoo.h"
+        "aidl/android/media/IAudioRecord.aidl",
+        "aidl/android/media/IPlayer.aidl",
+
         "AudioEffect.cpp",
         "AudioPolicy.cpp",
         "AudioRecord.cpp",
@@ -17,7 +32,6 @@
         "IAudioFlingerClient.cpp",
         "IAudioPolicyService.cpp",
         "IAudioPolicyServiceClient.cpp",
-        "IAudioRecord.cpp",
         "IAudioTrack.cpp",
         "IEffect.cpp",
         "IEffectClient.cpp",
@@ -36,7 +50,7 @@
     ],
     export_shared_lib_headers: ["libbinder"],
 
-    local_include_dirs: ["include/media"],
+    local_include_dirs: ["include/media", "aidl"],
     header_libs: ["libaudioclient_headers"],
     export_header_lib_headers: ["libaudioclient_headers"],
 
diff --git a/media/libaudioclient/AudioRecord.cpp b/media/libaudioclient/AudioRecord.cpp
index 611cde7..6402bbb 100644
--- a/media/libaudioclient/AudioRecord.cpp
+++ b/media/libaudioclient/AudioRecord.cpp
@@ -323,7 +323,7 @@
 
     status_t status = NO_ERROR;
     if (!(flags & CBLK_INVALID)) {
-        status = mAudioRecord->start(event, triggerSession);
+        status = mAudioRecord->start(event, triggerSession).transactionError();
         if (status == DEAD_OBJECT) {
             flags |= CBLK_INVALID;
         }
@@ -652,22 +652,22 @@
 
     sp<IMemory> iMem;           // for cblk
     sp<IMemory> bufferMem;
-    sp<IAudioRecord> record = audioFlinger->openRecord(input,
-                                                       mSampleRate,
-                                                       mFormat,
-                                                       mChannelMask,
-                                                       opPackageName,
-                                                       &temp,
-                                                       &flags,
-                                                       mClientPid,
-                                                       tid,
-                                                       mClientUid,
-                                                       &mSessionId,
-                                                       &notificationFrames,
-                                                       iMem,
-                                                       bufferMem,
-                                                       &status,
-                                                       mPortId);
+    sp<media::IAudioRecord> record = audioFlinger->openRecord(input,
+                                                              mSampleRate,
+                                                              mFormat,
+                                                              mChannelMask,
+                                                              opPackageName,
+                                                              &temp,
+                                                              &flags,
+                                                              mClientPid,
+                                                              tid,
+                                                              mClientUid,
+                                                              &mSessionId,
+                                                              &notificationFrames,
+                                                              iMem,
+                                                              bufferMem,
+                                                              &status,
+                                                              mPortId);
     ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
             "session ID changed from %d to %d", originalSessionId, mSessionId);
 
@@ -1219,7 +1219,8 @@
         if (mActive) {
             // callback thread or sync event hasn't changed
             // FIXME this fails if we have a new AudioFlinger instance
-            result = mAudioRecord->start(AudioSystem::SYNC_EVENT_SAME, AUDIO_SESSION_NONE);
+            result = mAudioRecord->start(
+                AudioSystem::SYNC_EVENT_SAME, AUDIO_SESSION_NONE).transactionError();
         }
         mFramesReadServerOffset = mFramesRead; // server resets to zero so we need an offset.
     }
diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp
index b99eaff..698384a 100644
--- a/media/libaudioclient/AudioTrack.cpp
+++ b/media/libaudioclient/AudioTrack.cpp
@@ -39,6 +39,8 @@
 namespace android {
 // ---------------------------------------------------------------------------
 
+using media::VolumeShaper;
+
 // TODO: Move to a separate .h
 
 template <typename T>
@@ -562,7 +564,7 @@
     mFramesWritten = 0;
     mFramesWrittenServerOffset = 0;
     mFramesWrittenAtRestore = -1; // -1 is a unique initializer.
-    mVolumeHandler = new VolumeHandler();
+    mVolumeHandler = new media::VolumeHandler();
     return NO_ERROR;
 }
 
diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp
index 14feada..fc8c11a 100644
--- a/media/libaudioclient/IAudioFlinger.cpp
+++ b/media/libaudioclient/IAudioFlinger.cpp
@@ -175,7 +175,7 @@
         return track;
     }
 
-    virtual sp<IAudioRecord> openRecord(
+    virtual sp<media::IAudioRecord> openRecord(
                                 audio_io_handle_t input,
                                 uint32_t sampleRate,
                                 audio_format_t format,
@@ -194,7 +194,7 @@
                                 audio_port_handle_t portId)
     {
         Parcel data, reply;
-        sp<IAudioRecord> record;
+        sp<media::IAudioRecord> record;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
         data.writeInt32((int32_t) input);
         data.writeInt32(sampleRate);
@@ -238,7 +238,7 @@
                 *notificationFrames = lNotificationFrames;
             }
             lStatus = reply.readInt32();
-            record = interface_cast<IAudioRecord>(reply.readStrongBinder());
+            record = interface_cast<media::IAudioRecord>(reply.readStrongBinder());
             cblk = interface_cast<IMemory>(reply.readStrongBinder());
             if (cblk != 0 && cblk->pointer() == NULL) {
                 cblk.clear();
@@ -1025,7 +1025,7 @@
             sp<IMemory> cblk;
             sp<IMemory> buffers;
             status_t status = NO_ERROR;
-            sp<IAudioRecord> record = openRecord(input,
+            sp<media::IAudioRecord> record = openRecord(input,
                     sampleRate, format, channelMask, opPackageName, &frameCount, &flags,
                     pid, tid, clientUid, &sessionId, &notificationFrames, cblk, buffers,
                     &status, portId);
diff --git a/media/libaudioclient/IAudioRecord.cpp b/media/libaudioclient/IAudioRecord.cpp
deleted file mode 100644
index 1331c0d..0000000
--- a/media/libaudioclient/IAudioRecord.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
-**
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#define LOG_TAG "IAudioRecord"
-//#define LOG_NDEBUG 0
-#include <utils/Log.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <binder/Parcel.h>
-
-#include <media/IAudioRecord.h>
-
-namespace android {
-
-enum {
-    UNUSED_WAS_GET_CBLK = IBinder::FIRST_CALL_TRANSACTION,
-    START,
-    STOP
-};
-
-class BpAudioRecord : public BpInterface<IAudioRecord>
-{
-public:
-    explicit BpAudioRecord(const sp<IBinder>& impl)
-        : BpInterface<IAudioRecord>(impl)
-    {
-    }
-
-    virtual status_t start(int /*AudioSystem::sync_event_t*/ event, audio_session_t triggerSession)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioRecord::getInterfaceDescriptor());
-        data.writeInt32(event);
-        data.writeInt32(triggerSession);
-        status_t status = remote()->transact(START, data, &reply);
-        if (status == NO_ERROR) {
-            status = reply.readInt32();
-        } else {
-            ALOGW("start() error: %s", strerror(-status));
-        }
-        return status;
-    }
-
-    virtual void stop()
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioRecord::getInterfaceDescriptor());
-        remote()->transact(STOP, data, &reply);
-    }
-
-};
-
-IMPLEMENT_META_INTERFACE(AudioRecord, "android.media.IAudioRecord");
-
-// ----------------------------------------------------------------------
-
-status_t BnAudioRecord::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    switch (code) {
-        case START: {
-            CHECK_INTERFACE(IAudioRecord, data, reply);
-            int /*AudioSystem::sync_event_t*/ event = data.readInt32();
-            audio_session_t triggerSession = (audio_session_t) data.readInt32();
-            reply->writeInt32(start(event, triggerSession));
-            return NO_ERROR;
-        } break;
-        case STOP: {
-            CHECK_INTERFACE(IAudioRecord, data, reply);
-            stop();
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-}
-
-} // namespace android
diff --git a/media/libaudioclient/IAudioTrack.cpp b/media/libaudioclient/IAudioTrack.cpp
index 79e864d..adff057 100644
--- a/media/libaudioclient/IAudioTrack.cpp
+++ b/media/libaudioclient/IAudioTrack.cpp
@@ -28,6 +28,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 enum {
     GET_CBLK = IBinder::FIRST_CALL_TRANSACTION,
     START,
@@ -185,7 +187,7 @@
             return nullptr;
         }
         sp<VolumeShaper::State> state = new VolumeShaper::State;
-        status = state->readFromParcel(reply);
+        status = state->readFromParcel(&reply);
         if (status != NO_ERROR) {
             return nullptr;
         }
@@ -263,12 +265,12 @@
             status_t status = data.readInt32(&present);
             if (status == NO_ERROR && present != 0) {
                 configuration = new VolumeShaper::Configuration();
-                status = configuration->readFromParcel(data);
+                status = configuration->readFromParcel(&data);
             }
             status = status ?: data.readInt32(&present);
             if (status == NO_ERROR && present != 0) {
                 operation = new VolumeShaper::Operation();
-                status = operation->readFromParcel(data);
+                status = operation->readFromParcel(&data);
             }
             if (status == NO_ERROR) {
                 status = (status_t)applyVolumeShaper(configuration, operation);
diff --git a/media/libaudioclient/PlayerBase.cpp b/media/libaudioclient/PlayerBase.cpp
index 7868318..b0c68e5 100644
--- a/media/libaudioclient/PlayerBase.cpp
+++ b/media/libaudioclient/PlayerBase.cpp
@@ -22,6 +22,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 //--------------------------------------------------------------------------------------------------
 PlayerBase::PlayerBase() : BnPlayer(),
         mPanMultiplierL(1.0f), mPanMultiplierR(1.0f),
@@ -117,23 +119,26 @@
 
 //------------------------------------------------------------------------------
 // Implementation of IPlayer
-void PlayerBase::start() {
+binder::Status PlayerBase::start() {
     ALOGD("PlayerBase::start() from IPlayer");
     (void)startWithStatus();
+    return binder::Status::ok();
 }
 
-void PlayerBase::pause() {
+binder::Status PlayerBase::pause() {
     ALOGD("PlayerBase::pause() from IPlayer");
     (void)pauseWithStatus();
+    return binder::Status::ok();
 }
 
 
-void PlayerBase::stop() {
+binder::Status PlayerBase::stop() {
     ALOGD("PlayerBase::stop() from IPlayer");
     (void)stopWithStatus();
+    return binder::Status::ok();
 }
 
-void PlayerBase::setVolume(float vol) {
+binder::Status PlayerBase::setVolume(float vol) {
     ALOGD("PlayerBase::setVolume() from IPlayer");
     {
         Mutex::Autolock _l(mSettingsLock);
@@ -144,9 +149,10 @@
     if (status != NO_ERROR) {
         ALOGW("PlayerBase::setVolume() error %d", status);
     }
+    return binder::Status::fromStatusT(status);
 }
 
-void PlayerBase::setPan(float pan) {
+binder::Status PlayerBase::setPan(float pan) {
     ALOGD("PlayerBase::setPan() from IPlayer");
     {
         Mutex::Autolock _l(mSettingsLock);
@@ -163,22 +169,19 @@
     if (status != NO_ERROR) {
         ALOGW("PlayerBase::setPan() error %d", status);
     }
+    return binder::Status::fromStatusT(status);
 }
 
-void PlayerBase::setStartDelayMs(int32_t delayMs __unused) {
+binder::Status PlayerBase::setStartDelayMs(int32_t delayMs __unused) {
     ALOGW("setStartDelay() is not supported");
+    return binder::Status::ok();
 }
 
-void PlayerBase::applyVolumeShaper(
-        const sp<VolumeShaper::Configuration>& configuration  __unused,
-        const sp<VolumeShaper::Operation>& operation __unused) {
+binder::Status PlayerBase::applyVolumeShaper(
+            const VolumeShaper::Configuration& configuration __unused,
+            const VolumeShaper::Operation& operation __unused) {
     ALOGW("applyVolumeShaper() is not supported");
-}
-
-status_t PlayerBase::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    return BnPlayer::onTransact(code, data, reply, flags);
+    return binder::Status::ok();
 }
 
 } // namespace android
diff --git a/media/libaudioclient/TrackPlayerBase.cpp b/media/libaudioclient/TrackPlayerBase.cpp
index 48cd803..0a914fc 100644
--- a/media/libaudioclient/TrackPlayerBase.cpp
+++ b/media/libaudioclient/TrackPlayerBase.cpp
@@ -18,6 +18,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 //--------------------------------------------------------------------------------------------------
 TrackPlayerBase::TrackPlayerBase() : PlayerBase(),
         mPlayerVolumeL(1.0f), mPlayerVolumeR(1.0f)
@@ -103,18 +105,24 @@
 }
 
 
-void TrackPlayerBase::applyVolumeShaper(
-        const sp<VolumeShaper::Configuration>& configuration,
-        const sp<VolumeShaper::Operation>& operation) {
+binder::Status TrackPlayerBase::applyVolumeShaper(
+        const VolumeShaper::Configuration& configuration,
+        const VolumeShaper::Operation& operation) {
+
+    sp<VolumeShaper::Configuration> spConfiguration = new VolumeShaper::Configuration(configuration);
+    sp<VolumeShaper::Operation> spOperation = new VolumeShaper::Operation(operation);
+
     if (mAudioTrack != 0) {
         ALOGD("TrackPlayerBase::applyVolumeShaper() from IPlayer");
-        VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(configuration, operation);
+        VolumeShaper::Status status = mAudioTrack->applyVolumeShaper(spConfiguration, spOperation);
         if (status < 0) { // a non-negative value is the volume shaper id.
             ALOGE("TrackPlayerBase::applyVolumeShaper() failed with status %d", status);
         }
+        return binder::Status::fromStatusT(status);
     } else {
         ALOGD("TrackPlayerBase::applyVolumeShaper()"
-                " no AudioTrack for volume control from IPlayer");
+              " no AudioTrack for volume control from IPlayer");
+        return binder::Status::ok();
     }
 }
 
diff --git a/media/libaudioclient/aidl/android/media/IAudioRecord.aidl b/media/libaudioclient/aidl/android/media/IAudioRecord.aidl
new file mode 100644
index 0000000..50ce78f
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/IAudioRecord.aidl
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media;
+
+interface IAudioRecord {
+
+  /* After it's created the track is not active. Call start() to
+   * make it active.
+   */
+  void start(int /*AudioSystem::sync_event_t*/ event,
+             int /*audio_session_t*/ triggerSession);
+
+  /* Stop a track. If set, the callback will cease being called and
+   * obtainBuffer will return an error. Buffers that are already released
+   * will be processed, unless flush() is called.
+   */
+  void stop();
+}
diff --git a/media/libaudioclient/aidl/android/media/IPlayer.aidl b/media/libaudioclient/aidl/android/media/IPlayer.aidl
new file mode 100644
index 0000000..a90fcdd
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/IPlayer.aidl
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media;
+
+import android.media.VolumeShaper.Configuration;
+import android.media.VolumeShaper.Operation;
+
+/**
+ * @hide
+ */
+interface IPlayer {
+    oneway void start();
+    oneway void pause();
+    oneway void stop();
+    oneway void setVolume(float vol);
+    oneway void setPan(float pan);
+    oneway void setStartDelayMs(int delayMs);
+    oneway void applyVolumeShaper(in Configuration configuration,
+                                  in Operation operation);
+}
diff --git a/media/libaudioclient/aidl/android/media/VolumeShaper/Configuration.aidl b/media/libaudioclient/aidl/android/media/VolumeShaper/Configuration.aidl
new file mode 100644
index 0000000..fd0e60f
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/VolumeShaper/Configuration.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.VolumeShaper;
+
+parcelable Configuration cpp_header "media/VolumeShaper.h";
diff --git a/media/libaudioclient/aidl/android/media/VolumeShaper/Operation.aidl b/media/libaudioclient/aidl/android/media/VolumeShaper/Operation.aidl
new file mode 100644
index 0000000..4290d9d
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/VolumeShaper/Operation.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.VolumeShaper;
+
+parcelable Operation cpp_header "media/VolumeShaper.h";
diff --git a/media/libaudioclient/aidl/android/media/VolumeShaper/State.aidl b/media/libaudioclient/aidl/android/media/VolumeShaper/State.aidl
new file mode 100644
index 0000000..f6a22b8
--- /dev/null
+++ b/media/libaudioclient/aidl/android/media/VolumeShaper/State.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media.VolumeShaper;
+
+parcelable State cpp_header "media/VolumeShaper.h";
diff --git a/media/libaudioclient/include/media/AudioRecord.h b/media/libaudioclient/include/media/AudioRecord.h
index e6a5efb..74a626e 100644
--- a/media/libaudioclient/include/media/AudioRecord.h
+++ b/media/libaudioclient/include/media/AudioRecord.h
@@ -17,13 +17,16 @@
 #ifndef ANDROID_AUDIORECORD_H
 #define ANDROID_AUDIORECORD_H
 
+#include <binder/IMemory.h>
 #include <cutils/sched_policy.h>
 #include <media/AudioSystem.h>
 #include <media/AudioTimestamp.h>
-#include <media/IAudioRecord.h>
 #include <media/Modulo.h>
+#include <utils/RefBase.h>
 #include <utils/threads.h>
 
+#include "android/media/IAudioRecord.h"
+
 namespace android {
 
 // ----------------------------------------------------------------------------
@@ -624,7 +627,7 @@
 
     // Next 5 fields may be changed if IAudioRecord is re-created, but always != 0
     // provided the initial set() was successful
-    sp<IAudioRecord>        mAudioRecord;
+    sp<media::IAudioRecord> mAudioRecord;
     sp<IMemory>             mCblkMemory;
     audio_track_cblk_t*     mCblk;              // re-load after mLock.unlock()
     sp<IMemory>             mBufferMemory;
diff --git a/media/libaudioclient/include/media/AudioTrack.h b/media/libaudioclient/include/media/AudioTrack.h
index 7ae8ec5..14afc9d 100644
--- a/media/libaudioclient/include/media/AudioTrack.h
+++ b/media/libaudioclient/include/media/AudioTrack.h
@@ -744,12 +744,12 @@
             status_t    setParameters(const String8& keyValuePairs);
 
     /* Sets the volume shaper object */
-            VolumeShaper::Status applyVolumeShaper(
-                    const sp<VolumeShaper::Configuration>& configuration,
-                    const sp<VolumeShaper::Operation>& operation);
+            media::VolumeShaper::Status applyVolumeShaper(
+                    const sp<media::VolumeShaper::Configuration>& configuration,
+                    const sp<media::VolumeShaper::Operation>& operation);
 
     /* Gets the volume shaper state */
-            sp<VolumeShaper::State> getVolumeShaperState(int id);
+            sp<media::VolumeShaper::State> getVolumeShaperState(int id);
 
     /* Get parameters */
             String8     getParameters(const String8& keys);
@@ -1148,7 +1148,7 @@
                                               // May not match the app selection depending on other
                                               // activity and connected devices.
 
-    sp<VolumeHandler>       mVolumeHandler;
+    sp<media::VolumeHandler>       mVolumeHandler;
 
 private:
     class DeathNotifier : public IBinder::DeathRecipient {
diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h
index 0ad4231..133d6c9 100644
--- a/media/libaudioclient/include/media/IAudioFlinger.h
+++ b/media/libaudioclient/include/media/IAudioFlinger.h
@@ -25,7 +25,6 @@
 #include <utils/Errors.h>
 #include <binder/IInterface.h>
 #include <media/IAudioTrack.h>
-#include <media/IAudioRecord.h>
 #include <media/IAudioFlingerClient.h>
 #include <system/audio.h>
 #include <system/audio_effect.h>
@@ -34,6 +33,8 @@
 #include <media/IEffectClient.h>
 #include <utils/String8.h>
 
+#include "android/media/IAudioRecord.h"
+
 namespace android {
 
 // ----------------------------------------------------------------------------
@@ -69,7 +70,7 @@
                                 status_t *status,
                                 audio_port_handle_t portId) = 0;
 
-    virtual sp<IAudioRecord> openRecord(
+    virtual sp<media::IAudioRecord> openRecord(
                                 // On successful return, AudioFlinger takes over the handle
                                 // reference and will release it when the track is destroyed.
                                 // However on failure, the client is responsible for release.
diff --git a/media/libaudioclient/include/media/IAudioRecord.h b/media/libaudioclient/include/media/IAudioRecord.h
deleted file mode 100644
index 7768176..0000000
--- a/media/libaudioclient/include/media/IAudioRecord.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef IAUDIORECORD_H_
-#define IAUDIORECORD_H_
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/RefBase.h>
-#include <utils/Errors.h>
-#include <binder/IInterface.h>
-#include <binder/IMemory.h>
-#include <system/audio.h>
-
-namespace android {
-
-// ----------------------------------------------------------------------------
-
-class IAudioRecord : public IInterface
-{
-public:
-    DECLARE_META_INTERFACE(AudioRecord);
-
-    /* After it's created the track is not active. Call start() to
-     * make it active.
-     */
-    virtual status_t    start(int /*AudioSystem::sync_event_t*/ event,
-                              audio_session_t triggerSession) = 0;
-
-    /* Stop a track. If set, the callback will cease being called and
-     * obtainBuffer will return an error. Buffers that are already released
-     * will be processed, unless flush() is called.
-     */
-    virtual void        stop() = 0;
-};
-
-// ----------------------------------------------------------------------------
-
-class BnAudioRecord : public BnInterface<IAudioRecord>
-{
-public:
-    virtual status_t    onTransact( uint32_t code,
-                                    const Parcel& data,
-                                    Parcel* reply,
-                                    uint32_t flags = 0);
-};
-
-// ----------------------------------------------------------------------------
-
-}; // namespace android
-
-#endif /*IAUDIORECORD_H_*/
diff --git a/media/libaudioclient/include/media/IAudioTrack.h b/media/libaudioclient/include/media/IAudioTrack.h
index 27a62d6..94afe3c 100644
--- a/media/libaudioclient/include/media/IAudioTrack.h
+++ b/media/libaudioclient/include/media/IAudioTrack.h
@@ -77,12 +77,12 @@
     virtual void        signal() = 0;
 
     /* Sets the volume shaper */
-    virtual VolumeShaper::Status applyVolumeShaper(
-            const sp<VolumeShaper::Configuration>& configuration,
-            const sp<VolumeShaper::Operation>& operation) = 0;
+    virtual media::VolumeShaper::Status applyVolumeShaper(
+            const sp<media::VolumeShaper::Configuration>& configuration,
+            const sp<media::VolumeShaper::Operation>& operation) = 0;
 
     /* gets the volume shaper state */
-    virtual sp<VolumeShaper::State> getVolumeShaperState(int id) = 0;
+    virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/media/libaudioclient/include/media/PlayerBase.h b/media/libaudioclient/include/media/PlayerBase.h
index e63090b..e7a8abc 100644
--- a/media/libaudioclient/include/media/PlayerBase.h
+++ b/media/libaudioclient/include/media/PlayerBase.h
@@ -17,35 +17,31 @@
 #ifndef __ANDROID_PLAYER_BASE_H__
 #define __ANDROID_PLAYER_BASE_H__
 
-#include <audiomanager/IPlayer.h>
 #include <audiomanager/AudioManager.h>
 #include <audiomanager/IAudioManager.h>
 
+#include "android/media/BnPlayer.h"
 
 namespace android {
 
-class PlayerBase : public BnPlayer
+class PlayerBase : public ::android::media::BnPlayer
 {
 public:
     explicit PlayerBase();
-    virtual ~PlayerBase();
+    virtual ~PlayerBase() override;
 
     virtual void destroy() = 0;
 
     //IPlayer implementation
-    virtual void start();
-    virtual void pause();
-    virtual void stop();
-    virtual void setVolume(float vol);
-    virtual void setPan(float pan);
-    virtual void setStartDelayMs(int32_t delayMs);
-    virtual void applyVolumeShaper(
-            const sp<VolumeShaper::Configuration>& configuration,
-            const sp<VolumeShaper::Operation>& operation) override;
-
-    virtual status_t onTransact(
-                uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
-
+    virtual binder::Status start() override;
+    virtual binder::Status pause() override;
+    virtual binder::Status stop() override;
+    virtual binder::Status setVolume(float vol) override;
+    virtual binder::Status setPan(float pan) override;
+    virtual binder::Status setStartDelayMs(int32_t delayMs) override;
+    virtual binder::Status applyVolumeShaper(
+            const media::VolumeShaper::Configuration& configuration,
+            const media::VolumeShaper::Operation& operation) override;
 
             status_t startWithStatus();
             status_t pauseWithStatus();
diff --git a/media/libaudioclient/include/media/TrackPlayerBase.h b/media/libaudioclient/include/media/TrackPlayerBase.h
index 2d113c0..66e9b3b 100644
--- a/media/libaudioclient/include/media/TrackPlayerBase.h
+++ b/media/libaudioclient/include/media/TrackPlayerBase.h
@@ -32,9 +32,9 @@
     virtual void destroy();
 
     //IPlayer implementation
-    virtual void applyVolumeShaper(
-            const sp<VolumeShaper::Configuration>& configuration,
-            const sp<VolumeShaper::Operation>& operation);
+    virtual binder::Status applyVolumeShaper(
+            const media::VolumeShaper::Configuration& configuration,
+            const media::VolumeShaper::Operation& operation);
 
     //FIXME move to protected field, so far made public to minimize changes to AudioTrack logic
     sp<AudioTrack> mAudioTrack;
diff --git a/media/libaudioprocessing/OWNERS b/media/libaudioprocessing/OWNERS
new file mode 100644
index 0000000..96d0ea0
--- /dev/null
+++ b/media/libaudioprocessing/OWNERS
@@ -0,0 +1,3 @@
+gkasten@google.com
+hunga@google.com
+rago@google.com
diff --git a/media/libcpustats/OWNERS b/media/libcpustats/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/media/libcpustats/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/media/libeffects/OWNERS b/media/libeffects/OWNERS
index 7e3de13..7f9ae81 100644
--- a/media/libeffects/OWNERS
+++ b/media/libeffects/OWNERS
@@ -1,3 +1,4 @@
+hunga@google.com
 krocard@google.com
 mnaganov@google.com
 rago@google.com
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h b/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
index f32ed30..4ecaf14 100644
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
@@ -534,246 +534,246 @@
 
  /* Coefficients for centre frequency 55Hz */
 #define HPF_Fs8000_Fc55_A0                        0.958849f
-#define HPF_Fs8000_Fc55_A1                        -1.917698f
+#define HPF_Fs8000_Fc55_A1                        (-1.917698f)
 #define HPF_Fs8000_Fc55_A2                        0.958849f
-#define HPF_Fs8000_Fc55_B1                        -1.939001f
+#define HPF_Fs8000_Fc55_B1                        (-1.939001f)
 #define HPF_Fs8000_Fc55_B2                        0.940807f
 #define HPF_Fs11025_Fc55_A0                       0.966909f
-#define HPF_Fs11025_Fc55_A1                       -1.933818f
+#define HPF_Fs11025_Fc55_A1                       (-1.933818f)
 #define HPF_Fs11025_Fc55_A2                       0.966909f
-#define HPF_Fs11025_Fc55_B1                       -1.955732f
+#define HPF_Fs11025_Fc55_B1                       (-1.955732f)
 #define HPF_Fs11025_Fc55_B2                       0.956690f
 #define HPF_Fs12000_Fc55_A0                       0.968650f
-#define HPF_Fs12000_Fc55_A1                       -1.937300f
+#define HPF_Fs12000_Fc55_A1                       (-1.937300f)
 #define HPF_Fs12000_Fc55_A2                       0.968650f
-#define HPF_Fs12000_Fc55_B1                       -1.959327f
+#define HPF_Fs12000_Fc55_B1                       (-1.959327f)
 #define HPF_Fs12000_Fc55_B2                       0.960138f
 #define HPF_Fs16000_Fc55_A0                       0.973588f
-#define HPF_Fs16000_Fc55_A1                       -1.947176f
+#define HPF_Fs16000_Fc55_A1                       (-1.947176f)
 #define HPF_Fs16000_Fc55_A2                       0.973588f
-#define HPF_Fs16000_Fc55_B1                       -1.969494f
+#define HPF_Fs16000_Fc55_B1                       (-1.969494f)
 #define HPF_Fs16000_Fc55_B2                       0.969952f
 #define HPF_Fs22050_Fc55_A0                       0.977671f
-#define HPF_Fs22050_Fc55_A1                       -1.955343f
+#define HPF_Fs22050_Fc55_A1                       (-1.955343f)
 #define HPF_Fs22050_Fc55_A2                       0.977671f
-#define HPF_Fs22050_Fc55_B1                       -1.977863f
+#define HPF_Fs22050_Fc55_B1                       (-1.977863f)
 #define HPF_Fs22050_Fc55_B2                       0.978105f
 #define HPF_Fs24000_Fc55_A0                       0.978551f
-#define HPF_Fs24000_Fc55_A1                       -1.957102f
+#define HPF_Fs24000_Fc55_A1                       (-1.957102f)
 #define HPF_Fs24000_Fc55_A2                       0.978551f
-#define HPF_Fs24000_Fc55_B1                       -1.979662f
+#define HPF_Fs24000_Fc55_B1                       (-1.979662f)
 #define HPF_Fs24000_Fc55_B2                       0.979866f
 #define HPF_Fs32000_Fc55_A0                       0.981042f
-#define HPF_Fs32000_Fc55_A1                       -1.962084f
+#define HPF_Fs32000_Fc55_A1                       (-1.962084f)
 #define HPF_Fs32000_Fc55_A2                       0.981042f
-#define HPF_Fs32000_Fc55_B1                       -1.984746f
+#define HPF_Fs32000_Fc55_B1                       (-1.984746f)
 #define HPF_Fs32000_Fc55_B2                       0.984861f
 #define HPF_Fs44100_Fc55_A0                       0.983097f
-#define HPF_Fs44100_Fc55_A1                       -1.966194f
+#define HPF_Fs44100_Fc55_A1                       (-1.966194f)
 #define HPF_Fs44100_Fc55_A2                       0.983097f
-#define HPF_Fs44100_Fc55_B1                       -1.988931f
+#define HPF_Fs44100_Fc55_B1                       (-1.988931f)
 #define HPF_Fs44100_Fc55_B2                       0.988992f
 #define HPF_Fs48000_Fc55_A0                       0.983539f
-#define HPF_Fs48000_Fc55_A1                       -1.967079f
+#define HPF_Fs48000_Fc55_A1                       (-1.967079f)
 #define HPF_Fs48000_Fc55_A2                       0.983539f
-#define HPF_Fs48000_Fc55_B1                       -1.989831f
+#define HPF_Fs48000_Fc55_B1                       (-1.989831f)
 #define HPF_Fs48000_Fc55_B2                       0.989882f
 
 #ifdef HIGHER_FS
 #define HPF_Fs96000_Fc55_A0                       0.986040f
-#define HPF_Fs96000_Fc55_A1                       -1.972080f
+#define HPF_Fs96000_Fc55_A1                       (-1.972080f)
 #define HPF_Fs96000_Fc55_A2                       0.986040f
-#define HPF_Fs96000_Fc55_B1                       -1.994915f
+#define HPF_Fs96000_Fc55_B1                       (-1.994915f)
 #define HPF_Fs96000_Fc55_B2                       0.994928f
 
 #define HPF_Fs192000_Fc55_A0                      0.987294f
-#define HPF_Fs192000_Fc55_A1                      -1.974588f
+#define HPF_Fs192000_Fc55_A1                      (-1.974588f)
 #define HPF_Fs192000_Fc55_A2                      0.987294f
-#define HPF_Fs192000_Fc55_B1                      -1.997458f
+#define HPF_Fs192000_Fc55_B1                      (-1.997458f)
 #define HPF_Fs192000_Fc55_B2                      0.997461f
 #endif
 
 
  /* Coefficients for centre frequency 66Hz */
 #define HPF_Fs8000_Fc66_A0                        0.953016f
-#define HPF_Fs8000_Fc66_A1                        -1.906032f
+#define HPF_Fs8000_Fc66_A1                        (-1.906032f)
 #define HPF_Fs8000_Fc66_A2                        0.953016f
-#define HPF_Fs8000_Fc66_B1                        -1.926810f
+#define HPF_Fs8000_Fc66_B1                        (-1.926810f)
 #define HPF_Fs8000_Fc66_B2                        0.929396f
 #define HPF_Fs11025_Fc66_A0                       0.962638f
-#define HPF_Fs11025_Fc66_A1                       -1.925275f
+#define HPF_Fs11025_Fc66_A1                       (-1.925275f)
 #define HPF_Fs11025_Fc66_A2                       0.962638f
-#define HPF_Fs11025_Fc66_B1                       -1.946881f
+#define HPF_Fs11025_Fc66_B1                       (-1.946881f)
 #define HPF_Fs11025_Fc66_B2                       0.948256f
 #define HPF_Fs12000_Fc66_A0                       0.964718f
-#define HPF_Fs12000_Fc66_A1                       -1.929435f
+#define HPF_Fs12000_Fc66_A1                       (-1.929435f)
 #define HPF_Fs12000_Fc66_A2                       0.964718f
-#define HPF_Fs12000_Fc66_B1                       -1.951196f
+#define HPF_Fs12000_Fc66_B1                       (-1.951196f)
 #define HPF_Fs12000_Fc66_B2                       0.952359f
 #define HPF_Fs16000_Fc66_A0                       0.970622f
-#define HPF_Fs16000_Fc66_A1                       -1.941244f
+#define HPF_Fs16000_Fc66_A1                       (-1.941244f)
 #define HPF_Fs16000_Fc66_A2                       0.970622f
-#define HPF_Fs16000_Fc66_B1                       -1.963394f
+#define HPF_Fs16000_Fc66_B1                       (-1.963394f)
 #define HPF_Fs16000_Fc66_B2                       0.964052f
 #define HPF_Fs22050_Fc66_A0                       0.975509f
-#define HPF_Fs22050_Fc66_A1                       -1.951019f
+#define HPF_Fs22050_Fc66_A1                       (-1.951019f)
 #define HPF_Fs22050_Fc66_A2                       0.975509f
-#define HPF_Fs22050_Fc66_B1                       -1.973436f
+#define HPF_Fs22050_Fc66_B1                       (-1.973436f)
 #define HPF_Fs22050_Fc66_B2                       0.973784f
 #define HPF_Fs24000_Fc66_A0                       0.976563f
-#define HPF_Fs24000_Fc66_A1                       -1.953125f
+#define HPF_Fs24000_Fc66_A1                       (-1.953125f)
 #define HPF_Fs24000_Fc66_A2                       0.976563f
-#define HPF_Fs24000_Fc66_B1                       -1.975594f
+#define HPF_Fs24000_Fc66_B1                       (-1.975594f)
 #define HPF_Fs24000_Fc66_B2                       0.975889f
 #define HPF_Fs32000_Fc66_A0                       0.979547f
-#define HPF_Fs32000_Fc66_A1                       -1.959093f
+#define HPF_Fs32000_Fc66_A1                       (-1.959093f)
 #define HPF_Fs32000_Fc66_A2                       0.979547f
-#define HPF_Fs32000_Fc66_B1                       -1.981695f
+#define HPF_Fs32000_Fc66_B1                       (-1.981695f)
 #define HPF_Fs32000_Fc66_B2                       0.981861f
 #define HPF_Fs44100_Fc66_A0                       0.982010f
-#define HPF_Fs44100_Fc66_A1                       -1.964019f
+#define HPF_Fs44100_Fc66_A1                       (-1.964019f)
 #define HPF_Fs44100_Fc66_A2                       0.982010f
-#define HPF_Fs44100_Fc66_B1                       -1.986718f
+#define HPF_Fs44100_Fc66_B1                       (-1.986718f)
 #define HPF_Fs44100_Fc66_B2                       0.986805f
 #define HPF_Fs48000_Fc66_A0                       0.982540f
-#define HPF_Fs48000_Fc66_A1                       -1.965079f
+#define HPF_Fs48000_Fc66_A1                       (-1.965079f)
 #define HPF_Fs48000_Fc66_A2                       0.982540f
-#define HPF_Fs48000_Fc66_B1                       -1.987797f
+#define HPF_Fs48000_Fc66_B1                       (-1.987797f)
 #define HPF_Fs48000_Fc66_B2                       0.987871f
 
 #ifdef HIGHER_FS
 #define HPF_Fs96000_Fc66_A0                       0.985539f
-#define HPF_Fs96000_Fc66_A1                       -1.971077f
+#define HPF_Fs96000_Fc66_A1                       (-1.971077f)
 #define HPF_Fs96000_Fc66_A2                       0.985539f
-#define HPF_Fs96000_Fc66_B1                       -1.993898f
+#define HPF_Fs96000_Fc66_B1                       (-1.993898f)
 #define HPF_Fs96000_Fc66_B2                       0.993917f
 
 #define HPF_Fs192000_Fc66_A0                      0.987043f
-#define HPF_Fs192000_Fc66_A1                      -1.974086f
+#define HPF_Fs192000_Fc66_A1                      (-1.974086f)
 #define HPF_Fs192000_Fc66_A2                      0.987043f
-#define HPF_Fs192000_Fc66_B1                      -1.996949f
+#define HPF_Fs192000_Fc66_B1                      (-1.996949f)
 #define HPF_Fs192000_Fc66_B2                      0.996954f
 #endif
 
 /* Coefficients for centre frequency 78Hz */
 #define HPF_Fs8000_Fc78_A0                        0.946693f
-#define HPF_Fs8000_Fc78_A1                        -1.893387f
+#define HPF_Fs8000_Fc78_A1                        (-1.893387f)
 #define HPF_Fs8000_Fc78_A2                        0.946693f
-#define HPF_Fs8000_Fc78_B1                        -1.913517f
+#define HPF_Fs8000_Fc78_B1                        (-1.913517f)
 #define HPF_Fs8000_Fc78_B2                        0.917105f
 #define HPF_Fs11025_Fc78_A0                       0.957999f
-#define HPF_Fs11025_Fc78_A1                       -1.915998f
+#define HPF_Fs11025_Fc78_A1                       (-1.915998f)
 #define HPF_Fs11025_Fc78_A2                       0.957999f
-#define HPF_Fs11025_Fc78_B1                       -1.937229f
+#define HPF_Fs11025_Fc78_B1                       (-1.937229f)
 #define HPF_Fs11025_Fc78_B2                       0.939140f
 #define HPF_Fs12000_Fc78_A0                       0.960446f
-#define HPF_Fs12000_Fc78_A1                       -1.920892f
+#define HPF_Fs12000_Fc78_A1                       (-1.920892f)
 #define HPF_Fs12000_Fc78_A2                       0.960446f
-#define HPF_Fs12000_Fc78_B1                       -1.942326f
+#define HPF_Fs12000_Fc78_B1                       (-1.942326f)
 #define HPF_Fs12000_Fc78_B2                       0.943944f
 #define HPF_Fs16000_Fc78_A0                       0.967397f
-#define HPF_Fs16000_Fc78_A1                       -1.934794f
+#define HPF_Fs16000_Fc78_A1                       (-1.934794f)
 #define HPF_Fs16000_Fc78_A2                       0.967397f
-#define HPF_Fs16000_Fc78_B1                       -1.956740f
+#define HPF_Fs16000_Fc78_B1                       (-1.956740f)
 #define HPF_Fs16000_Fc78_B2                       0.957656f
 #define HPF_Fs22050_Fc78_A0                       0.973156f
-#define HPF_Fs22050_Fc78_A1                       -1.946313f
+#define HPF_Fs22050_Fc78_A1                       (-1.946313f)
 #define HPF_Fs22050_Fc78_A2                       0.973156f
-#define HPF_Fs22050_Fc78_B1                       -1.968607f
+#define HPF_Fs22050_Fc78_B1                       (-1.968607f)
 #define HPF_Fs22050_Fc78_B2                       0.969092f
 #define HPF_Fs24000_Fc78_A0                       0.974398f
-#define HPF_Fs24000_Fc78_A1                       -1.948797f
+#define HPF_Fs24000_Fc78_A1                       (-1.948797f)
 #define HPF_Fs24000_Fc78_A2                       0.974398f
-#define HPF_Fs24000_Fc78_B1                       -1.971157f
+#define HPF_Fs24000_Fc78_B1                       (-1.971157f)
 #define HPF_Fs24000_Fc78_B2                       0.971568f
 #define HPF_Fs32000_Fc78_A0                       0.977918f
-#define HPF_Fs32000_Fc78_A1                       -1.955836f
+#define HPF_Fs32000_Fc78_A1                       (-1.955836f)
 #define HPF_Fs32000_Fc78_A2                       0.977918f
-#define HPF_Fs32000_Fc78_B1                       -1.978367f
+#define HPF_Fs32000_Fc78_B1                       (-1.978367f)
 #define HPF_Fs32000_Fc78_B2                       0.978599f
 #define HPF_Fs44100_Fc78_A0                       0.980824f
-#define HPF_Fs44100_Fc78_A1                       -1.961649f
+#define HPF_Fs44100_Fc78_A1                       (-1.961649f)
 #define HPF_Fs44100_Fc78_A2                       0.980824f
-#define HPF_Fs44100_Fc78_B1                       -1.984303f
+#define HPF_Fs44100_Fc78_B1                       (-1.984303f)
 #define HPF_Fs44100_Fc78_B2                       0.984425f
 #define HPF_Fs48000_Fc78_A0                       0.981450f
-#define HPF_Fs48000_Fc78_A1                       -1.962900f
+#define HPF_Fs48000_Fc78_A1                       (-1.962900f)
 #define HPF_Fs48000_Fc78_A2                       0.981450f
-#define HPF_Fs48000_Fc78_B1                       -1.985578f
+#define HPF_Fs48000_Fc78_B1                       (-1.985578f)
 #define HPF_Fs48000_Fc78_B2                       0.985681f
 
 #ifdef HIGHER_FS
 #define HPF_Fs96000_Fc78_A0                       0.984992f
-#define HPF_Fs96000_Fc78_A1                       -1.969984f
+#define HPF_Fs96000_Fc78_A1                       (-1.969984f)
 #define HPF_Fs96000_Fc78_A2                       0.984992f
-#define HPF_Fs96000_Fc78_B1                       -1.992789f
+#define HPF_Fs96000_Fc78_B1                       (-1.992789f)
 #define HPF_Fs96000_Fc78_B2                       0.992815f
 
 #define HPF_Fs192000_Fc78_A0                      0.986769f
-#define HPF_Fs192000_Fc78_A1                      -1.973539f
+#define HPF_Fs192000_Fc78_A1                      (-1.973539f)
 #define HPF_Fs192000_Fc78_A2                      0.986769f
-#define HPF_Fs192000_Fc78_B1                      -1.996394f
+#define HPF_Fs192000_Fc78_B1                      (-1.996394f)
 #define HPF_Fs192000_Fc78_B2                      0.996401f
 #endif
 
 /* Coefficients for centre frequency 90Hz */
 #define HPF_Fs8000_Fc90_A0                       0.940412f
-#define HPF_Fs8000_Fc90_A1                       -1.880825f
+#define HPF_Fs8000_Fc90_A1                       (-1.880825f)
 #define HPF_Fs8000_Fc90_A2                       0.940412f
-#define HPF_Fs8000_Fc90_B1                       -1.900231f
+#define HPF_Fs8000_Fc90_B1                       (-1.900231f)
 #define HPF_Fs8000_Fc90_B2                       0.904977f
 #define HPF_Fs11025_Fc90_A0                      0.953383f
-#define HPF_Fs11025_Fc90_A1                      -1.906766f
+#define HPF_Fs11025_Fc90_A1                      (-1.906766f)
 #define HPF_Fs11025_Fc90_A2                      0.953383f
-#define HPF_Fs11025_Fc90_B1                      -1.927579f
+#define HPF_Fs11025_Fc90_B1                      (-1.927579f)
 #define HPF_Fs11025_Fc90_B2                      0.930111f
 #define HPF_Fs12000_Fc90_A0                      0.956193f
-#define HPF_Fs12000_Fc90_A1                      -1.912387f
+#define HPF_Fs12000_Fc90_A1                      (-1.912387f)
 #define HPF_Fs12000_Fc90_A2                      0.956193f
-#define HPF_Fs12000_Fc90_B1                      -1.933459f
+#define HPF_Fs12000_Fc90_B1                      (-1.933459f)
 #define HPF_Fs12000_Fc90_B2                      0.935603f
 #define HPF_Fs16000_Fc90_A0                      0.964183f
-#define HPF_Fs16000_Fc90_A1                      -1.928365f
+#define HPF_Fs16000_Fc90_A1                      (-1.928365f)
 #define HPF_Fs16000_Fc90_A2                      0.964183f
-#define HPF_Fs16000_Fc90_B1                      -1.950087f
+#define HPF_Fs16000_Fc90_B1                      (-1.950087f)
 #define HPF_Fs16000_Fc90_B2                      0.951303f
 #define HPF_Fs22050_Fc90_A0                      0.970809f
-#define HPF_Fs22050_Fc90_A1                      -1.941618f
+#define HPF_Fs22050_Fc90_A1                      (-1.941618f)
 #define HPF_Fs22050_Fc90_A2                      0.970809f
-#define HPF_Fs22050_Fc90_B1                      -1.963778f
+#define HPF_Fs22050_Fc90_B1                      (-1.963778f)
 #define HPF_Fs22050_Fc90_B2                      0.964423f
 #define HPF_Fs24000_Fc90_A0                      0.972239f
-#define HPF_Fs24000_Fc90_A1                      -1.944477f
+#define HPF_Fs24000_Fc90_A1                      (-1.944477f)
 #define HPF_Fs24000_Fc90_A2                      0.972239f
-#define HPF_Fs24000_Fc90_B1                      -1.966721f
+#define HPF_Fs24000_Fc90_B1                      (-1.966721f)
 #define HPF_Fs24000_Fc90_B2                      0.967266f
 #define HPF_Fs32000_Fc90_A0                      0.976292f
-#define HPF_Fs32000_Fc90_A1                      -1.952584f
+#define HPF_Fs32000_Fc90_A1                      (-1.952584f)
 #define HPF_Fs32000_Fc90_A2                      0.976292f
-#define HPF_Fs32000_Fc90_B1                      -1.975040f
+#define HPF_Fs32000_Fc90_B1                      (-1.975040f)
 #define HPF_Fs32000_Fc90_B2                      0.975347f
 #define HPF_Fs44100_Fc90_A0                      0.979641f
-#define HPF_Fs44100_Fc90_A1                      -1.959282f
+#define HPF_Fs44100_Fc90_A1                      (-1.959282f)
 #define HPF_Fs44100_Fc90_A2                      0.979641f
-#define HPF_Fs44100_Fc90_B1                      -1.981888f
+#define HPF_Fs44100_Fc90_B1                      (-1.981888f)
 #define HPF_Fs44100_Fc90_B2                      0.982050f
 #define HPF_Fs48000_Fc90_A0                      0.980362f
-#define HPF_Fs48000_Fc90_A1                      -1.960724f
+#define HPF_Fs48000_Fc90_A1                      (-1.960724f)
 #define HPF_Fs48000_Fc90_A2                      0.980362f
-#define HPF_Fs48000_Fc90_B1                      -1.983359f
+#define HPF_Fs48000_Fc90_B1                      (-1.983359f)
 #define HPF_Fs48000_Fc90_B2                      0.983497f
 
 #ifdef HIGHER_FS
 #define HPF_Fs96000_Fc90_A0                       0.984446f
-#define HPF_Fs96000_Fc90_A1                       -1.968892f
+#define HPF_Fs96000_Fc90_A1                       (-1.968892f)
 #define HPF_Fs96000_Fc90_A2                       0.984446f
-#define HPF_Fs96000_Fc90_B1                       -1.991680f
+#define HPF_Fs96000_Fc90_B1                       (-1.991680f)
 #define HPF_Fs96000_Fc90_B2                       0.991714f
 
 #define HPF_Fs192000_Fc90_A0                      0.986496f
-#define HPF_Fs192000_Fc90_A1                      -1.972992f
+#define HPF_Fs192000_Fc90_A1                      (-1.972992f)
 #define HPF_Fs192000_Fc90_A2                      0.986496f
-#define HPF_Fs192000_Fc90_B1                      -1.995840f
+#define HPF_Fs192000_Fc90_B1                      (-1.995840f)
 #define HPF_Fs192000_Fc90_B2                      0.995848f
 #endif
 
@@ -786,244 +786,244 @@
 /* Coefficients for centre frequency 55Hz */
 #define BPF_Fs8000_Fc55_A0                       0.009197f
 #define BPF_Fs8000_Fc55_A1                       0.000000f
-#define BPF_Fs8000_Fc55_A2                       -0.009197f
-#define BPF_Fs8000_Fc55_B1                       -1.979545f
+#define BPF_Fs8000_Fc55_A2                       (-0.009197f)
+#define BPF_Fs8000_Fc55_B1                       (-1.979545f)
 #define BPF_Fs8000_Fc55_B2                       0.981393f
 #define BPF_Fs11025_Fc55_A0                      0.006691f
 #define BPF_Fs11025_Fc55_A1                      0.000000f
-#define BPF_Fs11025_Fc55_A2                      -0.006691f
-#define BPF_Fs11025_Fc55_B1                      -1.985488f
+#define BPF_Fs11025_Fc55_A2                      (-0.006691f)
+#define BPF_Fs11025_Fc55_B1                      (-1.985488f)
 #define BPF_Fs11025_Fc55_B2                      0.986464f
 #define BPF_Fs12000_Fc55_A0                      0.006150f
 #define BPF_Fs12000_Fc55_A1                      0.000000f
-#define BPF_Fs12000_Fc55_A2                      -0.006150f
-#define BPF_Fs12000_Fc55_B1                      -1.986733f
+#define BPF_Fs12000_Fc55_A2                      (-0.006150f)
+#define BPF_Fs12000_Fc55_B1                      (-1.986733f)
 #define BPF_Fs12000_Fc55_B2                      0.987557f
 #define BPF_Fs16000_Fc55_A0                      0.004620f
 #define BPF_Fs16000_Fc55_A1                      0.000000f
-#define BPF_Fs16000_Fc55_A2                      -0.004620f
-#define BPF_Fs16000_Fc55_B1                      -1.990189f
+#define BPF_Fs16000_Fc55_A2                      (-0.004620f)
+#define BPF_Fs16000_Fc55_B1                      (-1.990189f)
 #define BPF_Fs16000_Fc55_B2                      0.990653f
 #define BPF_Fs22050_Fc55_A0                      0.003357f
 #define BPF_Fs22050_Fc55_A1                      0.000000f
-#define BPF_Fs22050_Fc55_A2                      -0.003357f
-#define BPF_Fs22050_Fc55_B1                      -1.992964f
+#define BPF_Fs22050_Fc55_A2                      (-0.003357f)
+#define BPF_Fs22050_Fc55_B1                      (-1.992964f)
 #define BPF_Fs22050_Fc55_B2                      0.993209f
 #define BPF_Fs24000_Fc55_A0                      0.003085f
 #define BPF_Fs24000_Fc55_A1                      0.000000f
-#define BPF_Fs24000_Fc55_A2                      -0.003085f
-#define BPF_Fs24000_Fc55_B1                      -1.993552f
+#define BPF_Fs24000_Fc55_A2                      (-0.003085f)
+#define BPF_Fs24000_Fc55_B1                      (-1.993552f)
 #define BPF_Fs24000_Fc55_B2                      0.993759f
 #define BPF_Fs32000_Fc55_A0                      0.002315f
 #define BPF_Fs32000_Fc55_A1                      0.000000f
-#define BPF_Fs32000_Fc55_A2                      -0.002315f
-#define BPF_Fs32000_Fc55_B1                      -1.995199f
+#define BPF_Fs32000_Fc55_A2                      (-0.002315f)
+#define BPF_Fs32000_Fc55_B1                      (-1.995199f)
 #define BPF_Fs32000_Fc55_B2                      0.995316f
 #define BPF_Fs44100_Fc55_A0                      0.001681f
 #define BPF_Fs44100_Fc55_A1                      0.000000f
-#define BPF_Fs44100_Fc55_A2                      -0.001681f
-#define BPF_Fs44100_Fc55_B1                      -1.996537f
+#define BPF_Fs44100_Fc55_A2                      (-0.001681f)
+#define BPF_Fs44100_Fc55_B1                      (-1.996537f)
 #define BPF_Fs44100_Fc55_B2                      0.996599f
 #define BPF_Fs48000_Fc55_A0                      0.001545f
 #define BPF_Fs48000_Fc55_A1                      0.000000f
-#define BPF_Fs48000_Fc55_A2                      -0.001545f
-#define BPF_Fs48000_Fc55_B1                      -1.996823f
+#define BPF_Fs48000_Fc55_A2                      (-0.001545f)
+#define BPF_Fs48000_Fc55_B1                      (-1.996823f)
 #define BPF_Fs48000_Fc55_B2                      0.996875f
 
 #ifdef HIGHER_FS
 #define BPF_Fs96000_Fc55_A0                      0.000762f
 #define BPF_Fs96000_Fc55_A1                      0.000000f
-#define BPF_Fs96000_Fc55_A2                      -0.000762f
-#define BPF_Fs96000_Fc55_B1                      -1.998461f
+#define BPF_Fs96000_Fc55_A2                      (-0.000762f)
+#define BPF_Fs96000_Fc55_B1                      (-1.998461f)
 #define BPF_Fs96000_Fc55_B2                      0.998477f
 
 #define BPF_Fs192000_Fc55_A0                     0.000381f
 #define BPF_Fs192000_Fc55_A1                     0.000000f
-#define BPF_Fs192000_Fc55_A2                     -0.000381f
-#define BPF_Fs192000_Fc55_B1                     -1.999234f
+#define BPF_Fs192000_Fc55_A2                     (-0.000381f)
+#define BPF_Fs192000_Fc55_B1                     (-1.999234f)
 #define BPF_Fs192000_Fc55_B2                     0.999238f
 #endif
 
 /* Coefficients for centre frequency 66Hz */
 #define BPF_Fs8000_Fc66_A0                      0.012648f
 #define BPF_Fs8000_Fc66_A1                      0.000000f
-#define BPF_Fs8000_Fc66_A2                      -0.012648f
-#define BPF_Fs8000_Fc66_B1                      -1.971760f
+#define BPF_Fs8000_Fc66_A2                      (-0.012648f)
+#define BPF_Fs8000_Fc66_B1                      (-1.971760f)
 #define BPF_Fs8000_Fc66_B2                      0.974412f
 #define BPF_Fs11025_Fc66_A0                     0.009209f
 #define BPF_Fs11025_Fc66_A1                     0.000000f
-#define BPF_Fs11025_Fc66_A2                     -0.009209f
-#define BPF_Fs11025_Fc66_B1                     -1.979966f
+#define BPF_Fs11025_Fc66_A2                     (-0.009209f)
+#define BPF_Fs11025_Fc66_B1                     (-1.979966f)
 #define BPF_Fs11025_Fc66_B2                     0.981368f
 #define BPF_Fs12000_Fc66_A0                     0.008468f
 #define BPF_Fs12000_Fc66_A1                     0.000000f
-#define BPF_Fs12000_Fc66_A2                     -0.008468f
-#define BPF_Fs12000_Fc66_B1                     -1.981685f
+#define BPF_Fs12000_Fc66_A2                     (-0.008468f)
+#define BPF_Fs12000_Fc66_B1                     (-1.981685f)
 #define BPF_Fs12000_Fc66_B2                     0.982869f
 #define BPF_Fs16000_Fc66_A0                     0.006364f
 #define BPF_Fs16000_Fc66_A1                     0.000000f
-#define BPF_Fs16000_Fc66_A2                     -0.006364f
-#define BPF_Fs16000_Fc66_B1                     -1.986457f
+#define BPF_Fs16000_Fc66_A2                     (-0.006364f)
+#define BPF_Fs16000_Fc66_B1                     (-1.986457f)
 #define BPF_Fs16000_Fc66_B2                     0.987124f
 #define BPF_Fs22050_Fc66_A0                     0.004626f
 #define BPF_Fs22050_Fc66_A1                     0.000000f
-#define BPF_Fs22050_Fc66_A2                     -0.004626f
-#define BPF_Fs22050_Fc66_B1                     -1.990288f
+#define BPF_Fs22050_Fc66_A2                     (-0.004626f)
+#define BPF_Fs22050_Fc66_B1                     (-1.990288f)
 #define BPF_Fs22050_Fc66_B2                     0.990641f
 #define BPF_Fs24000_Fc66_A0                     0.004252f
 #define BPF_Fs24000_Fc66_A1                     0.000000f
-#define BPF_Fs24000_Fc66_A2                     -0.004252f
-#define BPF_Fs24000_Fc66_B1                     -1.991100f
+#define BPF_Fs24000_Fc66_A2                     (-0.004252f)
+#define BPF_Fs24000_Fc66_B1                     (-1.991100f)
 #define BPF_Fs24000_Fc66_B2                     0.991398f
 #define BPF_Fs32000_Fc66_A0                     0.003192f
 #define BPF_Fs32000_Fc66_A1                     0.000000f
-#define BPF_Fs32000_Fc66_A2                     -0.003192f
-#define BPF_Fs32000_Fc66_B1                     -1.993374f
+#define BPF_Fs32000_Fc66_A2                     (-0.003192f)
+#define BPF_Fs32000_Fc66_B1                     (-1.993374f)
 #define BPF_Fs32000_Fc66_B2                     0.993541f
 #define BPF_Fs44100_Fc66_A0                     0.002318f
 #define BPF_Fs44100_Fc66_A1                     0.000000f
-#define BPF_Fs44100_Fc66_A2                     -0.002318f
-#define BPF_Fs44100_Fc66_B1                     -1.995221f
+#define BPF_Fs44100_Fc66_A2                     (-0.002318f)
+#define BPF_Fs44100_Fc66_B1                     (-1.995221f)
 #define BPF_Fs44100_Fc66_B2                     0.995309f
 #define BPF_Fs48000_Fc66_A0                     0.002131f
 #define BPF_Fs48000_Fc66_A1                     0.000000f
-#define BPF_Fs48000_Fc66_A2                     -0.002131f
-#define BPF_Fs48000_Fc66_B1                     -1.995615f
+#define BPF_Fs48000_Fc66_A2                     (-0.002131f)
+#define BPF_Fs48000_Fc66_B1                     (-1.995615f)
 #define BPF_Fs48000_Fc66_B2                     0.995690f
 
 #ifdef HIGHER_FS
 #define BPF_Fs96000_Fc66_A0                     0.001055f
 #define BPF_Fs96000_Fc66_A1                     0.000000f
-#define BPF_Fs96000_Fc66_A2                     -0.001055f
-#define BPF_Fs96000_Fc66_B1                     -1.997868f
+#define BPF_Fs96000_Fc66_A2                     (-0.001055f)
+#define BPF_Fs96000_Fc66_B1                     (-1.997868f)
 #define BPF_Fs96000_Fc66_B2                     0.997891f
 
 #define BPF_Fs192000_Fc66_A0                    0.000528f
 #define BPF_Fs192000_Fc66_A1                    0.000000f
-#define BPF_Fs192000_Fc66_A2                   -0.000528f
-#define BPF_Fs192000_Fc66_B1                   -1.998939f
+#define BPF_Fs192000_Fc66_A2                   (-0.000528f)
+#define BPF_Fs192000_Fc66_B1                   (-1.998939f)
 #define BPF_Fs192000_Fc66_B2                    0.998945f
 #endif
 
 /* Coefficients for centre frequency 78Hz */
 #define BPF_Fs8000_Fc78_A0                      0.018572f
 #define BPF_Fs8000_Fc78_A1                      0.000000f
-#define BPF_Fs8000_Fc78_A2                      -0.018572f
-#define BPF_Fs8000_Fc78_B1                      -1.958745f
+#define BPF_Fs8000_Fc78_A2                      (-0.018572f)
+#define BPF_Fs8000_Fc78_B1                      (-1.958745f)
 #define BPF_Fs8000_Fc78_B2                      0.962427f
 #define BPF_Fs11025_Fc78_A0                     0.013545f
 #define BPF_Fs11025_Fc78_A1                     0.000000f
-#define BPF_Fs11025_Fc78_A2                     -0.013545f
-#define BPF_Fs11025_Fc78_B1                     -1.970647f
+#define BPF_Fs11025_Fc78_A2                     (-0.013545f)
+#define BPF_Fs11025_Fc78_B1                     (-1.970647f)
 #define BPF_Fs11025_Fc78_B2                     0.972596f
 #define BPF_Fs12000_Fc78_A0                     0.012458f
 #define BPF_Fs12000_Fc78_A1                     0.000000f
-#define BPF_Fs12000_Fc78_A2                     -0.012458f
-#define BPF_Fs12000_Fc78_B1                     -1.973148f
+#define BPF_Fs12000_Fc78_A2                     (-0.012458f)
+#define BPF_Fs12000_Fc78_B1                     (-1.973148f)
 #define BPF_Fs12000_Fc78_B2                     0.974795f
 #define BPF_Fs16000_Fc78_A0                     0.009373f
 #define BPF_Fs16000_Fc78_A1                     0.000000f
-#define BPF_Fs16000_Fc78_A2                     -0.009373f
-#define BPF_Fs16000_Fc78_B1                     -1.980108f
+#define BPF_Fs16000_Fc78_A2                     (-0.009373f)
+#define BPF_Fs16000_Fc78_B1                     (-1.980108f)
 #define BPF_Fs16000_Fc78_B2                     0.981037f
 #define BPF_Fs22050_Fc78_A0                     0.006819f
 #define BPF_Fs22050_Fc78_A1                     0.000000f
-#define BPF_Fs22050_Fc78_A2                     -0.006819f
-#define BPF_Fs22050_Fc78_B1                     -1.985714f
+#define BPF_Fs22050_Fc78_A2                     (-0.006819f)
+#define BPF_Fs22050_Fc78_B1                     (-1.985714f)
 #define BPF_Fs22050_Fc78_B2                     0.986204f
 #define BPF_Fs24000_Fc78_A0                     0.006268f
 #define BPF_Fs24000_Fc78_A1                     0.000000f
-#define BPF_Fs24000_Fc78_A2                     -0.006268f
-#define BPF_Fs24000_Fc78_B1                     -1.986904f
+#define BPF_Fs24000_Fc78_A2                     (-0.006268f)
+#define BPF_Fs24000_Fc78_B1                     (-1.986904f)
 #define BPF_Fs24000_Fc78_B2                     0.987318f
 #define BPF_Fs32000_Fc78_A0                     0.004709f
 #define BPF_Fs32000_Fc78_A1                     0.000000f
-#define BPF_Fs32000_Fc78_A2                     -0.004709f
-#define BPF_Fs32000_Fc78_B1                     -1.990240f
+#define BPF_Fs32000_Fc78_A2                     (-0.004709f)
+#define BPF_Fs32000_Fc78_B1                     (-1.990240f)
 #define BPF_Fs32000_Fc78_B2                     0.990473f
 #define BPF_Fs44100_Fc78_A0                     0.003421f
 #define BPF_Fs44100_Fc78_A1                     0.000000f
-#define BPF_Fs44100_Fc78_A2                     -0.003421f
-#define BPF_Fs44100_Fc78_B1                     -1.992955f
+#define BPF_Fs44100_Fc78_A2                     (-0.003421f)
+#define BPF_Fs44100_Fc78_B1                     (-1.992955f)
 #define BPF_Fs44100_Fc78_B2                     0.993078f
 #define BPF_Fs48000_Fc78_A0                     0.003144f
 #define BPF_Fs48000_Fc78_A1                     0.000000f
-#define BPF_Fs48000_Fc78_A2                     -0.003144f
-#define BPF_Fs48000_Fc78_B1                     -1.993535f
+#define BPF_Fs48000_Fc78_A2                     (-0.003144f)
+#define BPF_Fs48000_Fc78_B1                     (-1.993535f)
 #define BPF_Fs48000_Fc78_B2                     0.993639f
 
 #ifdef HIGHER_FS
 #define BPF_Fs96000_Fc78_A0                     0.001555f
 #define BPF_Fs96000_Fc78_A1                     0.000000f
-#define BPF_Fs96000_Fc78_A2                    -0.0015555f
-#define BPF_Fs96000_Fc78_B1                    -1.996860f
+#define BPF_Fs96000_Fc78_A2                    (-0.0015555f)
+#define BPF_Fs96000_Fc78_B1                    (-1.996860f)
 #define BPF_Fs96000_Fc78_B2                     0.996891f
 
 #define BPF_Fs192000_Fc78_A0                    0.000778f
 #define BPF_Fs192000_Fc78_A1                    0.000000f
-#define BPF_Fs192000_Fc78_A2                   -0.000778f
-#define BPF_Fs192000_Fc78_B1                   -1.998437f
+#define BPF_Fs192000_Fc78_A2                   (-0.000778f)
+#define BPF_Fs192000_Fc78_B1                   (-1.998437f)
 #define BPF_Fs192000_Fc78_B2                    0.998444f
 #endif
 
 /* Coefficients for centre frequency 90Hz */
 #define BPF_Fs8000_Fc90_A0                       0.022760f
 #define BPF_Fs8000_Fc90_A1                       0.000000f
-#define BPF_Fs8000_Fc90_A2                       -0.022760f
-#define BPF_Fs8000_Fc90_B1                       -1.949073f
+#define BPF_Fs8000_Fc90_A2                       (-0.022760f)
+#define BPF_Fs8000_Fc90_B1                       (-1.949073f)
 #define BPF_Fs8000_Fc90_B2                       0.953953f
 #define BPF_Fs11025_Fc90_A0                      0.016619f
 #define BPF_Fs11025_Fc90_A1                      0.000000f
-#define BPF_Fs11025_Fc90_A2                      -0.016619f
-#define BPF_Fs11025_Fc90_B1                      -1.963791f
+#define BPF_Fs11025_Fc90_A2                      (-0.016619f)
+#define BPF_Fs11025_Fc90_B1                      (-1.963791f)
 #define BPF_Fs11025_Fc90_B2                      0.966377f
 #define BPF_Fs12000_Fc90_A0                      0.015289f
 #define BPF_Fs12000_Fc90_A1                      0.000000f
-#define BPF_Fs12000_Fc90_A2                      -0.015289f
-#define BPF_Fs12000_Fc90_B1                      -1.966882f
+#define BPF_Fs12000_Fc90_A2                      (-0.015289f)
+#define BPF_Fs12000_Fc90_B1                      (-1.966882f)
 #define BPF_Fs12000_Fc90_B2                      0.969067f
 #define BPF_Fs16000_Fc90_A0                      0.011511f
 #define BPF_Fs16000_Fc90_A1                      0.000000f
-#define BPF_Fs16000_Fc90_A2                      -0.011511f
-#define BPF_Fs16000_Fc90_B1                      -1.975477f
+#define BPF_Fs16000_Fc90_A2                      (-0.011511f)
+#define BPF_Fs16000_Fc90_B1                      (-1.975477f)
 #define BPF_Fs16000_Fc90_B2                      0.976711f
 #define BPF_Fs22050_Fc90_A0                      0.008379f
 #define BPF_Fs22050_Fc90_A1                      0.000000f
-#define BPF_Fs22050_Fc90_A2                      -0.008379f
-#define BPF_Fs22050_Fc90_B1                      -1.982395f
+#define BPF_Fs22050_Fc90_A2                      (-0.008379f)
+#define BPF_Fs22050_Fc90_B1                      (-1.982395f)
 #define BPF_Fs22050_Fc90_B2                      0.983047f
 #define BPF_Fs24000_Fc90_A0                      0.007704f
 #define BPF_Fs24000_Fc90_A1                      0.000000f
-#define BPF_Fs24000_Fc90_A2                      -0.007704f
-#define BPF_Fs24000_Fc90_B1                      -1.983863f
+#define BPF_Fs24000_Fc90_A2                      (-0.007704f)
+#define BPF_Fs24000_Fc90_B1                      (-1.983863f)
 #define BPF_Fs24000_Fc90_B2                      0.984414f
 #define BPF_Fs32000_Fc90_A0                      0.005789f
 #define BPF_Fs32000_Fc90_A1                      0.000000f
-#define BPF_Fs32000_Fc90_A2                      -0.005789f
-#define BPF_Fs32000_Fc90_B1                      -1.987977f
+#define BPF_Fs32000_Fc90_A2                      (-0.005789f)
+#define BPF_Fs32000_Fc90_B1                      (-1.987977f)
 #define BPF_Fs32000_Fc90_B2                      0.988288f
 #define BPF_Fs44100_Fc90_A0                      0.004207f
 #define BPF_Fs44100_Fc90_A1                      0.000000f
-#define BPF_Fs44100_Fc90_A2                      -0.004207f
-#define BPF_Fs44100_Fc90_B1                      -1.991324f
+#define BPF_Fs44100_Fc90_A2                      (-0.004207f)
+#define BPF_Fs44100_Fc90_B1                      (-1.991324f)
 #define BPF_Fs44100_Fc90_B2                      0.991488f
 #define BPF_Fs48000_Fc90_A0                      0.003867f
 #define BPF_Fs48000_Fc90_A1                      0.000000f
-#define BPF_Fs48000_Fc90_A2                      -0.003867f
-#define BPF_Fs48000_Fc90_B1                      -1.992038f
+#define BPF_Fs48000_Fc90_A2                      (-0.003867f)
+#define BPF_Fs48000_Fc90_B1                      (-1.992038f)
 #define BPF_Fs48000_Fc90_B2                      0.992177f
 
 #ifdef HIGHER_FS
 #define BPF_Fs96000_Fc90_A0                      0.001913f
 #define BPF_Fs96000_Fc90_A1                      0.000000f
-#define BPF_Fs96000_Fc90_A2                     -0.001913f
-#define BPF_Fs96000_Fc90_B1                     -1.996134f
+#define BPF_Fs96000_Fc90_A2                     (-0.001913f)
+#define BPF_Fs96000_Fc90_B1                     (-1.996134f)
 #define BPF_Fs96000_Fc90_B2                      0.996174f
 
 #define BPF_Fs192000_Fc90_A0                     0.000958f
 #define BPF_Fs192000_Fc90_A1                     0.000000f
-#define BPF_Fs192000_Fc90_A2                    -0.000958f
-#define BPF_Fs192000_Fc90_B1                    -1.998075f
+#define BPF_Fs192000_Fc90_A2                    (-0.000958f)
+#define BPF_Fs192000_Fc90_B1                    (-1.998075f)
 #define BPF_Fs192000_Fc90_B2                     0.998085f
 #endif
 
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h b/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
index 353560c..8c04847 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
@@ -69,55 +69,55 @@
 #define HPF_Fs22050_Gain6_B2                            0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs22050_Gain7_A0                            1.390177
-#define HPF_Fs22050_Gain7_A1                            -0.020144
+#define HPF_Fs22050_Gain7_A1                            (-0.020144)
 #define HPF_Fs22050_Gain7_A2                            0.000000
 #define HPF_Fs22050_Gain7_B1                            0.370033
 #define HPF_Fs22050_Gain7_B2                            0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs22050_Gain8_A0                            1.476219
-#define HPF_Fs22050_Gain8_A1                            -0.106187
+#define HPF_Fs22050_Gain8_A1                            (-0.106187)
 #define HPF_Fs22050_Gain8_A2                            0.000000
 #define HPF_Fs22050_Gain8_B1                            0.370033
 #define HPF_Fs22050_Gain8_B2                            0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs22050_Gain9_A0                            1.572761
-#define HPF_Fs22050_Gain9_A1                            -0.202728
+#define HPF_Fs22050_Gain9_A1                            (-0.202728)
 #define HPF_Fs22050_Gain9_A2                            0.000000
 #define HPF_Fs22050_Gain9_B1                            0.370033
 #define HPF_Fs22050_Gain9_B2                            0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs22050_Gain10_A0                           1.681082
-#define HPF_Fs22050_Gain10_A1                           -0.311049
+#define HPF_Fs22050_Gain10_A1                           (-0.311049)
 #define HPF_Fs22050_Gain10_A2                           0.000000
 #define HPF_Fs22050_Gain10_B1                           0.370033
 #define HPF_Fs22050_Gain10_B2                           0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs22050_Gain11_A0                           1.802620
-#define HPF_Fs22050_Gain11_A1                           -0.432588
+#define HPF_Fs22050_Gain11_A1                           (-0.432588)
 #define HPF_Fs22050_Gain11_A2                           0.000000
 #define HPF_Fs22050_Gain11_B1                           0.370033
 #define HPF_Fs22050_Gain11_B2                           0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs22050_Gain12_A0                           1.938989
-#define HPF_Fs22050_Gain12_A1                           -0.568956
+#define HPF_Fs22050_Gain12_A1                           (-0.568956)
 #define HPF_Fs22050_Gain12_A2                           0.000000
 #define HPF_Fs22050_Gain12_B1                           0.370033
 #define HPF_Fs22050_Gain12_B2                           0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs22050_Gain13_A0                           2.091997
-#define HPF_Fs22050_Gain13_A1                           -0.721964
+#define HPF_Fs22050_Gain13_A1                           (-0.721964)
 #define HPF_Fs22050_Gain13_A2                           0.000000
 #define HPF_Fs22050_Gain13_B1                           0.370033
 #define HPF_Fs22050_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs22050_Gain14_A0                           2.263674
-#define HPF_Fs22050_Gain14_A1                           -0.893641
+#define HPF_Fs22050_Gain14_A1                           (-0.893641)
 #define HPF_Fs22050_Gain14_A2                           0.000000
 #define HPF_Fs22050_Gain14_B1                           0.370033
 #define HPF_Fs22050_Gain14_B2                           0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs22050_Gain15_A0                           2.456300
-#define HPF_Fs22050_Gain15_A1                           -1.086267
+#define HPF_Fs22050_Gain15_A1                           (-1.086267)
 #define HPF_Fs22050_Gain15_A2                           0.000000
 #define HPF_Fs22050_Gain15_B1                           0.370033
 #define HPF_Fs22050_Gain15_B2                           0.000000
@@ -148,342 +148,342 @@
 #define HPF_Fs24000_Gain4_B2                            0.000000
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs24000_Gain5_A0                            1.284870
-#define HPF_Fs24000_Gain5_A1                            -0.016921
+#define HPF_Fs24000_Gain5_A1                            (-0.016921)
 #define HPF_Fs24000_Gain5_A2                            0.000000
 #define HPF_Fs24000_Gain5_B1                            0.267949
 #define HPF_Fs24000_Gain5_B2                            0.000000
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs24000_Gain6_A0                           1.364291
-#define HPF_Fs24000_Gain6_A1                           -0.096342
+#define HPF_Fs24000_Gain6_A1                           (-0.096342)
 #define HPF_Fs24000_Gain6_A2                           0.000000
 #define HPF_Fs24000_Gain6_B1                           0.267949
 #define HPF_Fs24000_Gain6_B2                           0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs24000_Gain7_A0                            1.453403
-#define HPF_Fs24000_Gain7_A1                            -0.185454
+#define HPF_Fs24000_Gain7_A1                            (-0.185454)
 #define HPF_Fs24000_Gain7_A2                            0.000000
 #define HPF_Fs24000_Gain7_B1                            0.267949
 #define HPF_Fs24000_Gain7_B2                            0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs24000_Gain8_A0                            1.553389
-#define HPF_Fs24000_Gain8_A1                            -0.285440
+#define HPF_Fs24000_Gain8_A1                            (-0.285440)
 #define HPF_Fs24000_Gain8_A2                            0.000000
 #define HPF_Fs24000_Gain8_B1                            0.267949
 #define HPF_Fs24000_Gain8_B2                            0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs24000_Gain9_A0                            1.665574
-#define HPF_Fs24000_Gain9_A1                            -0.397625
+#define HPF_Fs24000_Gain9_A1                            (-0.397625)
 #define HPF_Fs24000_Gain9_A2                            0.000000
 #define HPF_Fs24000_Gain9_B1                            0.267949
 #define HPF_Fs24000_Gain9_B2                            0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs24000_Gain10_A0                           1.791449
-#define HPF_Fs24000_Gain10_A1                           -0.523499
+#define HPF_Fs24000_Gain10_A1                           (-0.523499)
 #define HPF_Fs24000_Gain10_A2                           0.000000
 #define HPF_Fs24000_Gain10_B1                           0.267949
 #define HPF_Fs24000_Gain10_B2                           0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs24000_Gain11_A0                           1.932682
-#define HPF_Fs24000_Gain11_A1                           -0.664733
+#define HPF_Fs24000_Gain11_A1                           (-0.664733)
 #define HPF_Fs24000_Gain11_A2                           0.000000
 #define HPF_Fs24000_Gain11_B1                           0.267949
 #define HPF_Fs24000_Gain11_B2                           0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs24000_Gain12_A0                           2.091148
-#define HPF_Fs24000_Gain12_A1                           -0.823199
+#define HPF_Fs24000_Gain12_A1                           (-0.823199)
 #define HPF_Fs24000_Gain12_A2                           0.000000
 #define HPF_Fs24000_Gain12_B1                           0.267949
 #define HPF_Fs24000_Gain12_B2                           0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs24000_Gain13_A0                           2.268950
-#define HPF_Fs24000_Gain13_A1                           -1.001001
+#define HPF_Fs24000_Gain13_A1                           (-1.001001)
 #define HPF_Fs24000_Gain13_A2                           0.000000
 #define HPF_Fs24000_Gain13_B1                           0.267949
 #define HPF_Fs24000_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs24000_Gain14_A0                           2.468447
-#define HPF_Fs24000_Gain14_A1                           -1.200498
+#define HPF_Fs24000_Gain14_A1                           (-1.200498)
 #define HPF_Fs24000_Gain14_A2                           0.000000
 #define HPF_Fs24000_Gain14_B1                           0.267949
 #define HPF_Fs24000_Gain14_B2                           0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs24000_Gain15_A0                           2.692287
-#define HPF_Fs24000_Gain15_A1                           -1.424338
+#define HPF_Fs24000_Gain15_A1                           (-1.424338)
 #define HPF_Fs24000_Gain15_A2                           0.000000
 #define HPF_Fs24000_Gain15_B1                           0.267949
 #define HPF_Fs24000_Gain15_B2                           0.000000
 /* Coefficients for sample rate 32000Hz */
                                                                     /* Gain =  1.000000 dB */
 #define HPF_Fs32000_Gain1_A0                            1.061009
-#define HPF_Fs32000_Gain1_A1                            -0.061009
+#define HPF_Fs32000_Gain1_A1                            (-0.061009)
 #define HPF_Fs32000_Gain1_A2                            0.000000
-#define HPF_Fs32000_Gain1_B1                            -0.000000
+#define HPF_Fs32000_Gain1_B1                            (-0.000000)
 #define HPF_Fs32000_Gain1_B2                            0.000000
                                                                     /* Gain =  2.000000 dB */
 #define HPF_Fs32000_Gain2_A0                             1.129463
-#define HPF_Fs32000_Gain2_A1                             -0.129463
+#define HPF_Fs32000_Gain2_A1                             (-0.129463)
 #define HPF_Fs32000_Gain2_A2                             0.000000
-#define HPF_Fs32000_Gain2_B1                             -0.000000
+#define HPF_Fs32000_Gain2_B1                             (-0.000000)
 #define HPF_Fs32000_Gain2_B2                             0.000000
                                                                     /* Gain =  3.000000 dB */
 #define HPF_Fs32000_Gain3_A0                             1.206267
-#define HPF_Fs32000_Gain3_A1                             -0.206267
+#define HPF_Fs32000_Gain3_A1                             (-0.206267)
 #define HPF_Fs32000_Gain3_A2                             0.000000
-#define HPF_Fs32000_Gain3_B1                             -0.000000
+#define HPF_Fs32000_Gain3_B1                             (-0.000000)
 #define HPF_Fs32000_Gain3_B2                             0.000000
                                                                     /* Gain =  4.000000 dB */
 #define HPF_Fs32000_Gain4_A0                            1.292447
-#define HPF_Fs32000_Gain4_A1                            -0.292447
+#define HPF_Fs32000_Gain4_A1                            (-0.292447)
 #define HPF_Fs32000_Gain4_A2                            0.000000
-#define HPF_Fs32000_Gain4_B1                            -0.000000
+#define HPF_Fs32000_Gain4_B1                            (-0.000000)
 #define HPF_Fs32000_Gain4_B2                            0.000000
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs32000_Gain5_A0                            1.389140
-#define HPF_Fs32000_Gain5_A1                            -0.389140
+#define HPF_Fs32000_Gain5_A1                            (-0.389140)
 #define HPF_Fs32000_Gain5_A2                            0.000000
-#define HPF_Fs32000_Gain5_B1                            -0.000000
+#define HPF_Fs32000_Gain5_B1                            (-0.000000)
 #define HPF_Fs32000_Gain5_B2                            0.000000
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs32000_Gain6_A0                             1.497631
-#define HPF_Fs32000_Gain6_A1                             -0.497631
+#define HPF_Fs32000_Gain6_A1                             (-0.497631)
 #define HPF_Fs32000_Gain6_A2                             0.000000
-#define HPF_Fs32000_Gain6_B1                             -0.000000
+#define HPF_Fs32000_Gain6_B1                             (-0.000000)
 #define HPF_Fs32000_Gain6_B2                             0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs32000_Gain7_A0                             1.619361
-#define HPF_Fs32000_Gain7_A1                             -0.619361
+#define HPF_Fs32000_Gain7_A1                             (-0.619361)
 #define HPF_Fs32000_Gain7_A2                             0.000000
-#define HPF_Fs32000_Gain7_B1                             -0.000000
+#define HPF_Fs32000_Gain7_B1                             (-0.000000)
 #define HPF_Fs32000_Gain7_B2                             0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs32000_Gain8_A0                             1.755943
-#define HPF_Fs32000_Gain8_A1                             -0.755943
+#define HPF_Fs32000_Gain8_A1                             (-0.755943)
 #define HPF_Fs32000_Gain8_A2                             0.000000
-#define HPF_Fs32000_Gain8_B1                             -0.000000
+#define HPF_Fs32000_Gain8_B1                             (-0.000000)
 #define HPF_Fs32000_Gain8_B2                             0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs32000_Gain9_A0                             1.909191
-#define HPF_Fs32000_Gain9_A1                             -0.909191
+#define HPF_Fs32000_Gain9_A1                             (-0.909191)
 #define HPF_Fs32000_Gain9_A2                             0.000000
-#define HPF_Fs32000_Gain9_B1                             -0.000000
+#define HPF_Fs32000_Gain9_B1                             (-0.000000)
 #define HPF_Fs32000_Gain9_B2                             0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs32000_Gain10_A0                            2.081139
-#define HPF_Fs32000_Gain10_A1                            -1.081139
+#define HPF_Fs32000_Gain10_A1                            (-1.081139)
 #define HPF_Fs32000_Gain10_A2                            0.000000
-#define HPF_Fs32000_Gain10_B1                            -0.000000
+#define HPF_Fs32000_Gain10_B1                            (-0.000000)
 #define HPF_Fs32000_Gain10_B2                            0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs32000_Gain11_A0                           2.274067
-#define HPF_Fs32000_Gain11_A1                           -1.274067
+#define HPF_Fs32000_Gain11_A1                           (-1.274067)
 #define HPF_Fs32000_Gain11_A2                           0.000000
-#define HPF_Fs32000_Gain11_B1                           -0.000000
+#define HPF_Fs32000_Gain11_B1                           (-0.000000)
 #define HPF_Fs32000_Gain11_B2                           0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs32000_Gain12_A0                          2.490536
-#define HPF_Fs32000_Gain12_A1                          -1.490536
+#define HPF_Fs32000_Gain12_A1                          (-1.490536)
 #define HPF_Fs32000_Gain12_A2                          0.000000
-#define HPF_Fs32000_Gain12_B1                          -0.000000
+#define HPF_Fs32000_Gain12_B1                          (-0.000000)
 #define HPF_Fs32000_Gain12_B2                          0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs32000_Gain13_A0                           2.733418
-#define HPF_Fs32000_Gain13_A1                           -1.733418
+#define HPF_Fs32000_Gain13_A1                           (-1.733418)
 #define HPF_Fs32000_Gain13_A2                           0.000000
-#define HPF_Fs32000_Gain13_B1                           -0.000000
+#define HPF_Fs32000_Gain13_B1                           (-0.000000)
 #define HPF_Fs32000_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs32000_Gain14_A0                           3.005936
-#define HPF_Fs32000_Gain14_A1                           -2.005936
+#define HPF_Fs32000_Gain14_A1                           (-2.005936)
 #define HPF_Fs32000_Gain14_A2                           0.000000
-#define HPF_Fs32000_Gain14_B1                           -0.000000
+#define HPF_Fs32000_Gain14_B1                           (-0.000000)
 #define HPF_Fs32000_Gain14_B2                           0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs32000_Gain15_A0                          3.311707
-#define HPF_Fs32000_Gain15_A1                          -2.311707
+#define HPF_Fs32000_Gain15_A1                          (-2.311707)
 #define HPF_Fs32000_Gain15_A2                          0.000000
-#define HPF_Fs32000_Gain15_B1                          -0.000000
+#define HPF_Fs32000_Gain15_B1                          (-0.000000)
 #define HPF_Fs32000_Gain15_B2                          0.000000
 /* Coefficients for sample rate 44100Hz */
                                                                     /* Gain =  1.000000 dB */
 #define HPF_Fs44100_Gain1_A0                            1.074364
-#define HPF_Fs44100_Gain1_A1                            -0.293257
+#define HPF_Fs44100_Gain1_A1                            (-0.293257)
 #define HPF_Fs44100_Gain1_A2                            0.000000
-#define HPF_Fs44100_Gain1_B1                            -0.218894
+#define HPF_Fs44100_Gain1_B1                            (-0.218894)
 #define HPF_Fs44100_Gain1_B2                            0.000000
                                                                     /* Gain =  2.000000 dB */
 #define HPF_Fs44100_Gain2_A0                            1.157801
-#define HPF_Fs44100_Gain2_A1                            -0.376695
+#define HPF_Fs44100_Gain2_A1                            (-0.376695)
 #define HPF_Fs44100_Gain2_A2                            0.000000
-#define HPF_Fs44100_Gain2_B1                            -0.218894
+#define HPF_Fs44100_Gain2_B1                            (-0.218894)
 #define HPF_Fs44100_Gain2_B2                            0.000000
                                                                     /* Gain =  3.000000 dB */
 #define HPF_Fs44100_Gain3_A0                           1.251420
-#define HPF_Fs44100_Gain3_A1                           -0.470313
+#define HPF_Fs44100_Gain3_A1                           (-0.470313)
 #define HPF_Fs44100_Gain3_A2                           0.000000
-#define HPF_Fs44100_Gain3_B1                           -0.218894
+#define HPF_Fs44100_Gain3_B1                           (-0.218894)
 #define HPF_Fs44100_Gain3_B2                           0.000000
                                                                     /* Gain =  4.000000 dB */
 #define HPF_Fs44100_Gain4_A0                            1.356461
-#define HPF_Fs44100_Gain4_A1                            -0.575355
+#define HPF_Fs44100_Gain4_A1                            (-0.575355)
 #define HPF_Fs44100_Gain4_A2                            0.000000
-#define HPF_Fs44100_Gain4_B1                            -0.218894
+#define HPF_Fs44100_Gain4_B1                            (-0.218894)
 #define HPF_Fs44100_Gain4_B2                            0.000000
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs44100_Gain5_A0                            1.474320
-#define HPF_Fs44100_Gain5_A1                            -0.693213
+#define HPF_Fs44100_Gain5_A1                            (-0.693213)
 #define HPF_Fs44100_Gain5_A2                            0.000000
-#define HPF_Fs44100_Gain5_B1                            -0.218894
+#define HPF_Fs44100_Gain5_B1                            (-0.218894)
 #define HPF_Fs44100_Gain5_B2                            0.000000
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs44100_Gain6_A0                           1.606559
-#define HPF_Fs44100_Gain6_A1                           -0.825453
+#define HPF_Fs44100_Gain6_A1                           (-0.825453)
 #define HPF_Fs44100_Gain6_A2                           0.000000
-#define HPF_Fs44100_Gain6_B1                           -0.218894
+#define HPF_Fs44100_Gain6_B1                           (-0.218894)
 #define HPF_Fs44100_Gain6_B2                           0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs44100_Gain7_A0                           1.754935
-#define HPF_Fs44100_Gain7_A1                           -0.973828
+#define HPF_Fs44100_Gain7_A1                           (-0.973828)
 #define HPF_Fs44100_Gain7_A2                           0.000000
-#define HPF_Fs44100_Gain7_B1                           -0.218894
+#define HPF_Fs44100_Gain7_B1                           (-0.218894)
 #define HPF_Fs44100_Gain7_B2                           0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs44100_Gain8_A0                            1.921414
-#define HPF_Fs44100_Gain8_A1                            -1.140308
+#define HPF_Fs44100_Gain8_A1                            (-1.140308)
 #define HPF_Fs44100_Gain8_A2                            0.000000
-#define HPF_Fs44100_Gain8_B1                            -0.218894
+#define HPF_Fs44100_Gain8_B1                            (-0.218894)
 #define HPF_Fs44100_Gain8_B2                            0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs44100_Gain9_A0                            2.108208
-#define HPF_Fs44100_Gain9_A1                            -1.327101
+#define HPF_Fs44100_Gain9_A1                            (-1.327101)
 #define HPF_Fs44100_Gain9_A2                            0.000000
-#define HPF_Fs44100_Gain9_B1                            -0.218894
+#define HPF_Fs44100_Gain9_B1                            (-0.218894)
 #define HPF_Fs44100_Gain9_B2                            0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs44100_Gain10_A0                          2.317793
-#define HPF_Fs44100_Gain10_A1                          -1.536687
+#define HPF_Fs44100_Gain10_A1                          (-1.536687)
 #define HPF_Fs44100_Gain10_A2                          0.000000
-#define HPF_Fs44100_Gain10_B1                          -0.218894
+#define HPF_Fs44100_Gain10_B1                          (-0.218894)
 #define HPF_Fs44100_Gain10_B2                          0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs44100_Gain11_A0                          2.552952
-#define HPF_Fs44100_Gain11_A1                          -1.771846
+#define HPF_Fs44100_Gain11_A1                          (-1.771846)
 #define HPF_Fs44100_Gain11_A2                          0.000000
-#define HPF_Fs44100_Gain11_B1                          -0.218894
+#define HPF_Fs44100_Gain11_B1                          (-0.218894)
 #define HPF_Fs44100_Gain11_B2                          0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs44100_Gain12_A0                          2.816805
-#define HPF_Fs44100_Gain12_A1                          -2.035698
+#define HPF_Fs44100_Gain12_A1                          (-2.035698)
 #define HPF_Fs44100_Gain12_A2                          0.000000
-#define HPF_Fs44100_Gain12_B1                          -0.218894
+#define HPF_Fs44100_Gain12_B1                          (-0.218894)
 #define HPF_Fs44100_Gain12_B2                          0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs44100_Gain13_A0                           3.112852
-#define HPF_Fs44100_Gain13_A1                           -2.331746
+#define HPF_Fs44100_Gain13_A1                           (-2.331746)
 #define HPF_Fs44100_Gain13_A2                           0.000000
-#define HPF_Fs44100_Gain13_B1                           -0.218894
+#define HPF_Fs44100_Gain13_B1                           (-0.218894)
 #define HPF_Fs44100_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs44100_Gain14_A0                          3.445023
-#define HPF_Fs44100_Gain14_A1                          -2.663916
+#define HPF_Fs44100_Gain14_A1                          (-2.663916)
 #define HPF_Fs44100_Gain14_A2                          0.000000
-#define HPF_Fs44100_Gain14_B1                          -0.218894
+#define HPF_Fs44100_Gain14_B1                          (-0.218894)
 #define HPF_Fs44100_Gain14_B2                          0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs44100_Gain15_A0                          3.817724
-#define HPF_Fs44100_Gain15_A1                          -3.036618
+#define HPF_Fs44100_Gain15_A1                          (-3.036618)
 #define HPF_Fs44100_Gain15_A2                          0.000000
-#define HPF_Fs44100_Gain15_B1                          -0.218894
+#define HPF_Fs44100_Gain15_B1                          (-0.218894)
 #define HPF_Fs44100_Gain15_B2                          0.000000
 /* Coefficients for sample rate 48000Hz */
                                                                     /* Gain =  1.000000 dB */
 #define HPF_Fs48000_Gain1_A0                          1.077357
-#define HPF_Fs48000_Gain1_A1                          -0.345306
+#define HPF_Fs48000_Gain1_A1                          (-0.345306)
 #define HPF_Fs48000_Gain1_A2                          0.000000
-#define HPF_Fs48000_Gain1_B1                          -0.267949
+#define HPF_Fs48000_Gain1_B1                          (-0.267949)
 #define HPF_Fs48000_Gain1_B2                          0.000000
                                                                     /* Gain =  2.000000 dB */
 #define HPF_Fs48000_Gain2_A0                          1.164152
-#define HPF_Fs48000_Gain2_A1                          -0.432101
+#define HPF_Fs48000_Gain2_A1                          (-0.432101)
 #define HPF_Fs48000_Gain2_A2                          0.000000
-#define HPF_Fs48000_Gain2_B1                          -0.267949
+#define HPF_Fs48000_Gain2_B1                          (-0.267949)
 #define HPF_Fs48000_Gain2_B2                          0.000000
                                                                     /* Gain =  3.000000 dB */
 #define HPF_Fs48000_Gain3_A0                          1.261538
-#define HPF_Fs48000_Gain3_A1                          -0.529488
+#define HPF_Fs48000_Gain3_A1                          (-0.529488)
 #define HPF_Fs48000_Gain3_A2                          0.000000
-#define HPF_Fs48000_Gain3_B1                          -0.267949
+#define HPF_Fs48000_Gain3_B1                          (-0.267949)
 #define HPF_Fs48000_Gain3_B2                          0.000000
                                                                     /* Gain =  4.000000 dB */
 #define HPF_Fs48000_Gain4_A0                           1.370807
-#define HPF_Fs48000_Gain4_A1                           -0.638757
+#define HPF_Fs48000_Gain4_A1                           (-0.638757)
 #define HPF_Fs48000_Gain4_A2                           0.000000
-#define HPF_Fs48000_Gain4_B1                           -0.267949
+#define HPF_Fs48000_Gain4_B1                           (-0.267949)
 #define HPF_Fs48000_Gain4_B2                           0.000000
                                                                     /* Gain =  5.000000 dB */
 #define HPF_Fs48000_Gain5_A0                           1.493409
-#define HPF_Fs48000_Gain5_A1                           -0.761359
+#define HPF_Fs48000_Gain5_A1                           (-0.761359)
 #define HPF_Fs48000_Gain5_A2                           0.000000
-#define HPF_Fs48000_Gain5_B1                           -0.267949
+#define HPF_Fs48000_Gain5_B1                           (-0.267949)
 #define HPF_Fs48000_Gain5_B2                           0.000000
                                                                     /* Gain =  6.000000 dB */
 #define HPF_Fs48000_Gain6_A0                            1.630971
-#define HPF_Fs48000_Gain6_A1                            -0.898920
+#define HPF_Fs48000_Gain6_A1                            (-0.898920)
 #define HPF_Fs48000_Gain6_A2                            0.000000
-#define HPF_Fs48000_Gain6_B1                            -0.267949
+#define HPF_Fs48000_Gain6_B1                            (-0.267949)
 #define HPF_Fs48000_Gain6_B2                            0.000000
                                                                     /* Gain =  7.000000 dB */
 #define HPF_Fs48000_Gain7_A0                            1.785318
-#define HPF_Fs48000_Gain7_A1                            -1.053267
+#define HPF_Fs48000_Gain7_A1                            (-1.053267)
 #define HPF_Fs48000_Gain7_A2                            0.000000
-#define HPF_Fs48000_Gain7_B1                            -0.267949
+#define HPF_Fs48000_Gain7_B1                            (-0.267949)
 #define HPF_Fs48000_Gain7_B2                            0.000000
                                                                     /* Gain =  8.000000 dB */
 #define HPF_Fs48000_Gain8_A0                           1.958498
-#define HPF_Fs48000_Gain8_A1                           -1.226447
+#define HPF_Fs48000_Gain8_A1                           (-1.226447)
 #define HPF_Fs48000_Gain8_A2                           0.000000
-#define HPF_Fs48000_Gain8_B1                           -0.267949
+#define HPF_Fs48000_Gain8_B1                           (-0.267949)
 #define HPF_Fs48000_Gain8_B2                           0.000000
                                                                     /* Gain =  9.000000 dB */
 #define HPF_Fs48000_Gain9_A0                          2.152809
-#define HPF_Fs48000_Gain9_A1                          -1.420758
+#define HPF_Fs48000_Gain9_A1                          (-1.420758)
 #define HPF_Fs48000_Gain9_A2                          0.000000
-#define HPF_Fs48000_Gain9_B1                          -0.267949
+#define HPF_Fs48000_Gain9_B1                          (-0.267949)
 #define HPF_Fs48000_Gain9_B2                          0.000000
                                                                     /* Gain =  10.000000 dB */
 #define HPF_Fs48000_Gain10_A0                         2.370829
-#define HPF_Fs48000_Gain10_A1                         -1.638778
+#define HPF_Fs48000_Gain10_A1                         (-1.638778)
 #define HPF_Fs48000_Gain10_A2                         0.000000
-#define HPF_Fs48000_Gain10_B1                         -0.267949
+#define HPF_Fs48000_Gain10_B1                         (-0.267949)
 #define HPF_Fs48000_Gain10_B2                         0.000000
                                                                     /* Gain =  11.000000 dB */
 #define HPF_Fs48000_Gain11_A0                          2.615452
-#define HPF_Fs48000_Gain11_A1                          -1.883401
+#define HPF_Fs48000_Gain11_A1                          (-1.883401)
 #define HPF_Fs48000_Gain11_A2                          0.000000
-#define HPF_Fs48000_Gain11_B1                          -0.267949
+#define HPF_Fs48000_Gain11_B1                          (-0.267949)
 #define HPF_Fs48000_Gain11_B2                          0.000000
                                                                     /* Gain =  12.000000 dB */
 #define HPF_Fs48000_Gain12_A0                          2.889924
-#define HPF_Fs48000_Gain12_A1                          -2.157873
+#define HPF_Fs48000_Gain12_A1                          (-2.157873)
 #define HPF_Fs48000_Gain12_A2                          0.000000
-#define HPF_Fs48000_Gain12_B1                          -0.267949
+#define HPF_Fs48000_Gain12_B1                          (-0.267949)
 #define HPF_Fs48000_Gain12_B2                          0.000000
                                                                     /* Gain =  13.000000 dB */
 #define HPF_Fs48000_Gain13_A0                           3.197886
-#define HPF_Fs48000_Gain13_A1                           -2.465835
+#define HPF_Fs48000_Gain13_A1                           (-2.465835)
 #define HPF_Fs48000_Gain13_A2                           0.000000
-#define HPF_Fs48000_Gain13_B1                           -0.267949
+#define HPF_Fs48000_Gain13_B1                           (-0.267949)
 #define HPF_Fs48000_Gain13_B2                           0.000000
                                                                     /* Gain =  14.000000 dB */
 #define HPF_Fs48000_Gain14_A0                          3.543425
-#define HPF_Fs48000_Gain14_A1                          -2.811374
+#define HPF_Fs48000_Gain14_A1                          (-2.811374)
 #define HPF_Fs48000_Gain14_A2                          0.000000
-#define HPF_Fs48000_Gain14_B1                          -0.267949
+#define HPF_Fs48000_Gain14_B1                          (-0.267949)
 #define HPF_Fs48000_Gain14_B2                          0.000000
                                                                     /* Gain =  15.000000 dB */
 #define HPF_Fs48000_Gain15_A0                         3.931127
-#define HPF_Fs48000_Gain15_A1                         -3.199076
+#define HPF_Fs48000_Gain15_A1                         (-3.199076)
 #define HPF_Fs48000_Gain15_A2                         0.000000
-#define HPF_Fs48000_Gain15_B1                         -0.267949
+#define HPF_Fs48000_Gain15_B1                         (-0.267949)
 #define HPF_Fs48000_Gain15_B2                         0.000000
 
 #ifdef HIGHER_FS
@@ -491,185 +491,185 @@
 /* Coefficients for sample rate 96000Hz */
                                                                  /* Gain =  1.000000 dB */
 #define HPF_Fs96000_Gain1_A0                          1.096233
-#define HPF_Fs96000_Gain1_A1                          -0.673583
+#define HPF_Fs96000_Gain1_A1                          (-0.673583)
 #define HPF_Fs96000_Gain1_A2                          0.000000
-#define HPF_Fs96000_Gain1_B1                          -0.577350
+#define HPF_Fs96000_Gain1_B1                          (-0.577350)
 #define HPF_Fs96000_Gain1_B2                          0.000000
                                                                  /* Gain =  2.000000 dB */
 #define HPF_Fs96000_Gain2_A0                          1.204208
-#define HPF_Fs96000_Gain2_A1                          -0.781558
+#define HPF_Fs96000_Gain2_A1                          (-0.781558)
 #define HPF_Fs96000_Gain2_A2                          0.000000
-#define HPF_Fs96000_Gain2_B1                          -0.577350
+#define HPF_Fs96000_Gain2_B1                          (-0.577350)
 #define HPF_Fs96000_Gain2_B2                          0.000000
                                                                  /* Gain =  3.000000 dB */
 #define HPF_Fs96000_Gain3_A0                          1.325358
-#define HPF_Fs96000_Gain3_A1                          -0.902708
+#define HPF_Fs96000_Gain3_A1                          (-0.902708)
 #define HPF_Fs96000_Gain3_A2                          0.000000
-#define HPF_Fs96000_Gain3_B1                          -0.577350
+#define HPF_Fs96000_Gain3_B1                          (-0.577350)
 #define HPF_Fs96000_Gain3_B2                          0.000000
                                                                  /* Gain =  4.000000 dB */
 #define HPF_Fs96000_Gain4_A0                           1.461291
-#define HPF_Fs96000_Gain4_A1                           -1.038641
+#define HPF_Fs96000_Gain4_A1                           (-1.038641)
 #define HPF_Fs96000_Gain4_A2                           0.000000
-#define HPF_Fs96000_Gain4_B1                           -0.577350
+#define HPF_Fs96000_Gain4_B1                           (-0.577350)
 #define HPF_Fs96000_Gain4_B2                           0.000000
                                                                  /* Gain =  5.000000 dB */
 #define HPF_Fs96000_Gain5_A0                           1.613810
-#define HPF_Fs96000_Gain5_A1                           -1.191160
+#define HPF_Fs96000_Gain5_A1                           (-1.191160)
 #define HPF_Fs96000_Gain5_A2                           0.000000
-#define HPF_Fs96000_Gain5_B1                           -0.577350
+#define HPF_Fs96000_Gain5_B1                           (-0.577350)
 #define HPF_Fs96000_Gain5_B2                           0.000000
                                                                  /* Gain =  6.000000 dB */
 #define HPF_Fs96000_Gain6_A0                            1.784939
-#define HPF_Fs96000_Gain6_A1                            -1.362289
+#define HPF_Fs96000_Gain6_A1                            (-1.362289)
 #define HPF_Fs96000_Gain6_A2                            0.000000
-#define HPF_Fs96000_Gain6_B1                            -0.577350
+#define HPF_Fs96000_Gain6_B1                            (-0.577350)
 #define HPF_Fs96000_Gain6_B2                            0.000000
                                                                 /* Gain =  7.000000 dB */
 #define HPF_Fs96000_Gain7_A0                            1.976949
-#define HPF_Fs96000_Gain7_A1                            -1.554299
+#define HPF_Fs96000_Gain7_A1                            (-1.554299)
 #define HPF_Fs96000_Gain7_A2                            0.000000
-#define HPF_Fs96000_Gain7_B1                            -0.577350
+#define HPF_Fs96000_Gain7_B1                            (-0.577350)
 #define HPF_Fs96000_Gain7_B2                            0.000000
                                                                  /* Gain =  8.000000 dB */
 #define HPF_Fs96000_Gain8_A0                           2.192387
-#define HPF_Fs96000_Gain8_A1                           -1.769738
+#define HPF_Fs96000_Gain8_A1                           (-1.769738)
 #define HPF_Fs96000_Gain8_A2                           0.000000
-#define HPF_Fs96000_Gain8_B1                           -0.577350
+#define HPF_Fs96000_Gain8_B1                           (-0.577350)
 #define HPF_Fs96000_Gain8_B2                           0.000000
                                                                 /* Gain =  9.000000 dB */
 #define HPF_Fs96000_Gain9_A0                          2.434113
-#define HPF_Fs96000_Gain9_A1                          -2.011464
+#define HPF_Fs96000_Gain9_A1                          (-2.011464)
 #define HPF_Fs96000_Gain9_A2                          0.000000
-#define HPF_Fs96000_Gain9_B1                          -0.577350
+#define HPF_Fs96000_Gain9_B1                          (-0.577350)
 #define HPF_Fs96000_Gain9_B2                          0.000000
                                                                /* Gain =  10.000000 dB */
 #define HPF_Fs96000_Gain10_A0                        2.705335
-#define HPF_Fs96000_Gain10_A1                        -2.282685
+#define HPF_Fs96000_Gain10_A1                        (-2.282685)
 #define HPF_Fs96000_Gain10_A2                         0.000000
-#define HPF_Fs96000_Gain10_B1                         -0.577350
+#define HPF_Fs96000_Gain10_B1                         (-0.577350)
 #define HPF_Fs96000_Gain10_B2                         0.000000
                                                               /* Gain =  11.000000 dB */
 #define HPF_Fs96000_Gain11_A0                          3.009650
-#define HPF_Fs96000_Gain11_A1                          -2.587000
+#define HPF_Fs96000_Gain11_A1                          (-2.587000)
 #define HPF_Fs96000_Gain11_A2                          0.000000
-#define HPF_Fs96000_Gain11_B1                          -0.577350
+#define HPF_Fs96000_Gain11_B1                          (-0.577350)
 #define HPF_Fs96000_Gain11_B2                          0.000000
                                                                   /* Gain =  12.000000 dB */
 #define HPF_Fs96000_Gain12_A0                          3.351097
-#define HPF_Fs96000_Gain12_A1                          -2.928447
+#define HPF_Fs96000_Gain12_A1                          (-2.928447)
 #define HPF_Fs96000_Gain12_A2                          0.000000
-#define HPF_Fs96000_Gain12_B1                          -0.577350
+#define HPF_Fs96000_Gain12_B1                          (-0.577350)
 #define HPF_Fs96000_Gain12_B2                          0.000000
                                                                 /* Gain =  13.000000 dB */
 #define HPF_Fs96000_Gain13_A0                           3.734207
-#define HPF_Fs96000_Gain13_A1                           -3.311558
+#define HPF_Fs96000_Gain13_A1                           (-3.311558)
 #define HPF_Fs96000_Gain13_A2                           0.000000
-#define HPF_Fs96000_Gain13_B1                           -0.577350
+#define HPF_Fs96000_Gain13_B1                           (-0.577350)
 #define HPF_Fs96000_Gain13_B2                           0.000000
                                                                  /* Gain =  14.000000 dB */
 #define HPF_Fs96000_Gain14_A0                         4.164064
-#define HPF_Fs96000_Gain14_A1                         -3.741414
+#define HPF_Fs96000_Gain14_A1                         (-3.741414)
 #define HPF_Fs96000_Gain14_A2                          0.000000
-#define HPF_Fs96000_Gain14_B1                          -0.577350
+#define HPF_Fs96000_Gain14_B1                          (-0.577350)
 #define HPF_Fs96000_Gain14_B2                          0.000000
                                                                  /* Gain =  15.000000 dB */
 #define HPF_Fs96000_Gain15_A0                         4.646371
-#define HPF_Fs96000_Gain15_A1                         -4.223721
+#define HPF_Fs96000_Gain15_A1                         (-4.223721)
 #define HPF_Fs96000_Gain15_A2                         0.000000
-#define HPF_Fs96000_Gain15_B1                         -0.577350
+#define HPF_Fs96000_Gain15_B1                         (-0.577350)
 #define HPF_Fs96000_Gain15_B2                         0.000000
 
 /* Coefficients for sample rate 192000Hz */
                                                                   /* Gain =  1.000000 dB */
 #define HPF_Fs192000_Gain1_A0                          1.107823
-#define HPF_Fs192000_Gain1_A1                          -0.875150
+#define HPF_Fs192000_Gain1_A1                          (-0.875150)
 #define HPF_Fs192000_Gain1_A2                          0.000000
-#define HPF_Fs192000_Gain1_B1                          -0.767327
+#define HPF_Fs192000_Gain1_B1                          (-0.767327)
 #define HPF_Fs192000_Gain1_B2                          0.000000
                                                                   /* Gain =  2.000000 dB */
 #define HPF_Fs192000_Gain2_A0                          1.228803
-#define HPF_Fs192000_Gain2_A1                          -0.996130
+#define HPF_Fs192000_Gain2_A1                          (-0.996130)
 #define HPF_Fs192000_Gain2_A2                          0.000000
-#define HPF_Fs192000_Gain2_B1                          -0.767327
+#define HPF_Fs192000_Gain2_B1                          (-0.767327)
 #define HPF_Fs192000_Gain2_B2                          0.000000
                                                                    /* Gain =  3.000000 dB */
 #define HPF_Fs192000_Gain3_A0                          1.364544
-#define HPF_Fs192000_Gain3_A1                          -1.131871
+#define HPF_Fs192000_Gain3_A1                          (-1.131871)
 #define HPF_Fs192000_Gain3_A2                          0.000000
-#define HPF_Fs192000_Gain3_B1                          -0.767327
+#define HPF_Fs192000_Gain3_B1                          (-0.767327)
 #define HPF_Fs192000_Gain3_B2                          0.000000
                                                                    /* Gain =  4.000000 dB */
 #define HPF_Fs192000_Gain4_A0                          1.516849
-#define HPF_Fs192000_Gain4_A1                          -1.284176
+#define HPF_Fs192000_Gain4_A1                          (-1.284176)
 #define HPF_Fs192000_Gain4_A2                           0.000000
-#define HPF_Fs192000_Gain4_B1                           -0.767327
+#define HPF_Fs192000_Gain4_B1                           (-0.767327)
 #define HPF_Fs192000_Gain4_B2                           0.000000
                                                                    /* Gain =  5.000000 dB */
 #define HPF_Fs192000_Gain5_A0                           1.687737
-#define HPF_Fs192000_Gain5_A1                           -1.455064
+#define HPF_Fs192000_Gain5_A1                           (-1.455064)
 #define HPF_Fs192000_Gain5_A2                           0.000000
-#define HPF_Fs192000_Gain5_B1                           -0.767327
+#define HPF_Fs192000_Gain5_B1                           (-0.767327)
 #define HPF_Fs192000_Gain5_B2                           0.000000
                                                                    /* Gain =  6.000000 dB */
 #define HPF_Fs192000_Gain6_A0                            1.879477
-#define HPF_Fs192000_Gain6_A1                            -1.646804
+#define HPF_Fs192000_Gain6_A1                            (-1.646804)
 #define HPF_Fs192000_Gain6_A2                            0.000000
-#define HPF_Fs192000_Gain6_B1                            -0.767327
+#define HPF_Fs192000_Gain6_B1                            (-0.767327)
 #define HPF_Fs192000_Gain6_B2                            0.000000
                                                                  /* Gain =  7.000000 dB */
 #define HPF_Fs192000_Gain7_A0                            2.094613
-#define HPF_Fs192000_Gain7_A1                            -1.861940
+#define HPF_Fs192000_Gain7_A1                            (-1.861940)
 #define HPF_Fs192000_Gain7_A2                            0.000000
-#define HPF_Fs192000_Gain7_B1                            -0.767327
+#define HPF_Fs192000_Gain7_B1                            (-0.767327)
 #define HPF_Fs192000_Gain7_B2                            0.000000
                                                                    /* Gain =  8.000000 dB */
 #define HPF_Fs192000_Gain8_A0                           2.335999
-#define HPF_Fs192000_Gain8_A1                           -2.103326
+#define HPF_Fs192000_Gain8_A1                           (-2.103326)
 #define HPF_Fs192000_Gain8_A2                           0.000000
-#define HPF_Fs192000_Gain8_B1                           -0.767327
+#define HPF_Fs192000_Gain8_B1                           (-0.767327)
 #define HPF_Fs192000_Gain8_B2                           0.000000
                                                                    /* Gain =  9.000000 dB */
 #define HPF_Fs192000_Gain9_A0                          2.606839
-#define HPF_Fs192000_Gain9_A1                          -2.374166
+#define HPF_Fs192000_Gain9_A1                          (-2.374166)
 #define HPF_Fs192000_Gain9_A2                          0.000000
-#define HPF_Fs192000_Gain9_B1                          -0.767327
+#define HPF_Fs192000_Gain9_B1                          (-0.767327)
 #define HPF_Fs192000_Gain9_B2                          0.000000
                                                                  /* Gain =  10.000000 dB */
 #define HPF_Fs192000_Gain10_A0                        2.910726
-#define HPF_Fs192000_Gain10_A1                        -2.678053
+#define HPF_Fs192000_Gain10_A1                        (-2.678053)
 #define HPF_Fs192000_Gain10_A2                         0.000000
-#define HPF_Fs192000_Gain10_B1                         -0.767327
+#define HPF_Fs192000_Gain10_B1                         (-0.767327)
 #define HPF_Fs192000_Gain10_B2                         0.000000
                                                                   /* Gain =  11.000000 dB */
 #define HPF_Fs192000_Gain11_A0                          3.251693
-#define HPF_Fs192000_Gain11_A1                          -3.019020
+#define HPF_Fs192000_Gain11_A1                          (-3.019020)
 #define HPF_Fs192000_Gain11_A2                          0.000000
-#define HPF_Fs192000_Gain11_B1                          -0.767327
+#define HPF_Fs192000_Gain11_B1                          (-0.767327)
 #define HPF_Fs192000_Gain11_B2                          0.000000
                                                                   /* Gain =  12.000000 dB */
 #define HPF_Fs192000_Gain12_A0                          3.634264
-#define HPF_Fs192000_Gain12_A1                          -3.401591
+#define HPF_Fs192000_Gain12_A1                          (-3.401591)
 #define HPF_Fs192000_Gain12_A2                          0.000000
-#define HPF_Fs192000_Gain12_B1                          -0.767327
+#define HPF_Fs192000_Gain12_B1                          (-0.767327)
 #define HPF_Fs192000_Gain12_B2                          0.000000
                                                                 /* Gain =  13.000000 dB */
 #define HPF_Fs192000_Gain13_A0                           4.063516
-#define HPF_Fs192000_Gain13_A1                           -3.830843
+#define HPF_Fs192000_Gain13_A1                           (-3.830843)
 #define HPF_Fs192000_Gain13_A2                           0.000000
-#define HPF_Fs192000_Gain13_B1                           -0.767327
+#define HPF_Fs192000_Gain13_B1                           (-0.767327)
 #define HPF_Fs192000_Gain13_B2                           0.000000
                                                                 /* Gain =  14.000000 dB */
 #define HPF_Fs192000_Gain14_A0                          4.545145
-#define HPF_Fs192000_Gain14_A1                          -4.312472
+#define HPF_Fs192000_Gain14_A1                          (-4.312472)
 #define HPF_Fs192000_Gain14_A2                          0.000000
-#define HPF_Fs192000_Gain14_B1                          -0.767327
+#define HPF_Fs192000_Gain14_B1                          (-0.767327)
 #define HPF_Fs192000_Gain14_B2                          0.000000
                                                                   /* Gain =  15.000000 dB */
 #define HPF_Fs192000_Gain15_A0                         5.085542
-#define HPF_Fs192000_Gain15_A1                         -4.852868
+#define HPF_Fs192000_Gain15_A1                         (-4.852868)
 #define HPF_Fs192000_Gain15_A2                         0.000000
-#define HPF_Fs192000_Gain15_B1                         -0.767327
+#define HPF_Fs192000_Gain15_B1                         (-0.767327)
 #define HPF_Fs192000_Gain15_B2                         0.000000
 
 #endif
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
index f0deb6c..42ea46f 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
@@ -26,21 +26,21 @@
 /*                                                                                  */
 /************************************************************************************/
 #ifdef BUILD_FLOAT
-#define LVEQNB_Gain_Neg15_dB                             -0.822172f
-#define LVEQNB_Gain_Neg14_dB                             -0.800474f
-#define LVEQNB_Gain_Neg13_dB                             -0.776128f
-#define LVEQNB_Gain_Neg12_dB                             -0.748811f
-#define LVEQNB_Gain_Neg11_dB                             -0.718162f
-#define LVEQNB_Gain_Neg10_dB                             -0.683772f
-#define LVEQNB_Gain_Neg9_dB                              -0.645187f
-#define LVEQNB_Gain_Neg8_dB                              -0.601893f
-#define LVEQNB_Gain_Neg7_dB                              -0.553316f
-#define LVEQNB_Gain_Neg6_dB                              -0.498813f
-#define LVEQNB_Gain_Neg5_dB                              -0.437659f
-#define LVEQNB_Gain_Neg4_dB                              -0.369043f
-#define LVEQNB_Gain_Neg3_dB                              -0.292054f
-#define LVEQNB_Gain_Neg2_dB                              -0.205672f
-#define LVEQNB_Gain_Neg1_dB                              -0.108749f
+#define LVEQNB_Gain_Neg15_dB                             (-0.822172f)
+#define LVEQNB_Gain_Neg14_dB                             (-0.800474f)
+#define LVEQNB_Gain_Neg13_dB                             (-0.776128f)
+#define LVEQNB_Gain_Neg12_dB                             (-0.748811f)
+#define LVEQNB_Gain_Neg11_dB                             (-0.718162f)
+#define LVEQNB_Gain_Neg10_dB                             (-0.683772f)
+#define LVEQNB_Gain_Neg9_dB                              (-0.645187f)
+#define LVEQNB_Gain_Neg8_dB                              (-0.601893f)
+#define LVEQNB_Gain_Neg7_dB                              (-0.553316f)
+#define LVEQNB_Gain_Neg6_dB                              (-0.498813f)
+#define LVEQNB_Gain_Neg5_dB                              (-0.437659f)
+#define LVEQNB_Gain_Neg4_dB                              (-0.369043f)
+#define LVEQNB_Gain_Neg3_dB                              (-0.292054f)
+#define LVEQNB_Gain_Neg2_dB                              (-0.205672f)
+#define LVEQNB_Gain_Neg1_dB                              (-0.108749f)
 #define LVEQNB_Gain_0_dB                                  0.000000f
 #define LVEQNB_Gain_1_dB                                  0.122018f
 #define LVEQNB_Gain_2_dB                                  0.258925f
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h
index 4f5221a..0c2fe53 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h
@@ -27,127 +27,127 @@
 #ifdef BUILD_FLOAT
 /* Stereo Enhancer coefficients for 8000 Hz sample rate, scaled with 0.161258 */
 #define CS_MIDDLE_8000_A0                           0.227720
-#define CS_MIDDLE_8000_A1                          -0.215125
+#define CS_MIDDLE_8000_A1                          (-0.215125)
 #define CS_MIDDLE_8000_A2                           0.000000
-#define CS_MIDDLE_8000_B1                          -0.921899
+#define CS_MIDDLE_8000_B1                          (-0.921899)
 #define CS_MIDDLE_8000_B2                           0.000000
 #define CS_MIDDLE_8000_SCALE                        15
 #define CS_SIDE_8000_A0                             0.611441
-#define CS_SIDE_8000_A1                            -0.380344
-#define CS_SIDE_8000_A2                            -0.231097
-#define CS_SIDE_8000_B1                            -0.622470
-#define CS_SIDE_8000_B2                            -0.130759
+#define CS_SIDE_8000_A1                            (-0.380344)
+#define CS_SIDE_8000_A2                            (-0.231097)
+#define CS_SIDE_8000_B1                            (-0.622470)
+#define CS_SIDE_8000_B2                            (-0.130759)
 #define CS_SIDE_8000_SCALE                         15
 
 /* Stereo Enhancer coefficients for 11025Hz sample rate, scaled with 0.162943 */
 #define CS_MIDDLE_11025_A0                       0.230838
-#define CS_MIDDLE_11025_A1                      -0.221559
+#define CS_MIDDLE_11025_A1                      (-0.221559)
 #define CS_MIDDLE_11025_A2                       0.000000
-#define CS_MIDDLE_11025_B1                      -0.943056
+#define CS_MIDDLE_11025_B1                      (-0.943056)
 #define CS_MIDDLE_11025_B2                       0.000000
 #define CS_MIDDLE_11025_SCALE                    15
 #define CS_SIDE_11025_A0                         0.557372
-#define CS_SIDE_11025_A1                        -0.391490
-#define CS_SIDE_11025_A2                        -0.165881
-#define CS_SIDE_11025_B1                        -0.880608
+#define CS_SIDE_11025_A1                        (-0.391490)
+#define CS_SIDE_11025_A2                        (-0.165881)
+#define CS_SIDE_11025_B1                        (-0.880608)
 #define CS_SIDE_11025_B2                         0.032397
 #define CS_SIDE_11025_SCALE                      15
 
 /* Stereo Enhancer coefficients for 12000Hz sample rate, scaled with 0.162191 */
 #define CS_MIDDLE_12000_A0                        0.229932
-#define CS_MIDDLE_12000_A1                       -0.221436
+#define CS_MIDDLE_12000_A1                       (-0.221436)
 #define CS_MIDDLE_12000_A2                        0.000000
-#define CS_MIDDLE_12000_B1                       -0.947616
+#define CS_MIDDLE_12000_B1                       (-0.947616)
 #define CS_MIDDLE_12000_B2                        0.000000
 #define CS_MIDDLE_12000_SCALE                        15
 #define CS_SIDE_12000_A0                         0.558398
-#define CS_SIDE_12000_A1                        -0.392211
-#define CS_SIDE_12000_A2                        -0.166187
-#define CS_SIDE_12000_B1                        -0.892550
+#define CS_SIDE_12000_A1                        (-0.392211)
+#define CS_SIDE_12000_A2                        (-0.166187)
+#define CS_SIDE_12000_B1                        (-0.892550)
 #define CS_SIDE_12000_B2                         0.032856
 #define CS_SIDE_12000_SCALE                          15
 
 /* Stereo Enhancer coefficients for 16000Hz sample rate, scaled with 0.162371 */
 #define CS_MIDDLE_16000_A0                       0.230638
-#define CS_MIDDLE_16000_A1                      -0.224232
+#define CS_MIDDLE_16000_A1                      (-0.224232)
 #define CS_MIDDLE_16000_A2                       0.000000
-#define CS_MIDDLE_16000_B1                      -0.960550
+#define CS_MIDDLE_16000_B1                      (-0.960550)
 #define CS_MIDDLE_16000_B2                       0.000000
 #define CS_MIDDLE_16000_SCALE                        15
 #define CS_SIDE_16000_A0                         0.499695
-#define CS_SIDE_16000_A1                        -0.355543
-#define CS_SIDE_16000_A2                        -0.144152
-#define CS_SIDE_16000_B1                        -1.050788
+#define CS_SIDE_16000_A1                        (-0.355543)
+#define CS_SIDE_16000_A2                        (-0.144152)
+#define CS_SIDE_16000_B1                        (-1.050788)
 #define CS_SIDE_16000_B2                         0.144104
 #define CS_SIDE_16000_SCALE                          14
 
 /* Stereo Enhancer coefficients for 22050Hz sample rate, scaled with 0.160781 */
 #define CS_MIDDLE_22050_A0                       0.228749
-#define CS_MIDDLE_22050_A1                      -0.224128
+#define CS_MIDDLE_22050_A1                      (-0.224128)
 #define CS_MIDDLE_22050_A2                       0.000000
-#define CS_MIDDLE_22050_B1                      -0.971262
+#define CS_MIDDLE_22050_B1                      (-0.971262)
 #define CS_MIDDLE_22050_B2                       0.000000
 #define CS_MIDDLE_22050_SCALE                        15
 #define CS_SIDE_22050_A0                          0.440112
-#define CS_SIDE_22050_A1                         -0.261096
-#define CS_SIDE_22050_A2                         -0.179016
-#define CS_SIDE_22050_B1                         -1.116786
+#define CS_SIDE_22050_A1                         (-0.261096)
+#define CS_SIDE_22050_A2                         (-0.179016)
+#define CS_SIDE_22050_B1                         (-1.116786)
 #define CS_SIDE_22050_B2                          0.182507
 #define CS_SIDE_22050_SCALE                          14
 
 /* Stereo Enhancer coefficients for 24000Hz sample rate, scaled with 0.161882 */
 #define CS_MIDDLE_24000_A0                         0.230395
-#define CS_MIDDLE_24000_A1                        -0.226117
+#define CS_MIDDLE_24000_A1                        (-0.226117)
 #define CS_MIDDLE_24000_A2                         0.000000
-#define CS_MIDDLE_24000_B1                        -0.973573
+#define CS_MIDDLE_24000_B1                        (-0.973573)
 #define CS_MIDDLE_24000_B2                         0.000000
 #define CS_MIDDLE_24000_SCALE                        15
 #define CS_SIDE_24000_A0                           0.414770
-#define CS_SIDE_24000_A1                          -0.287182
-#define CS_SIDE_24000_A2                          -0.127588
-#define CS_SIDE_24000_B1                          -1.229648
+#define CS_SIDE_24000_A1                          (-0.287182)
+#define CS_SIDE_24000_A2                          (-0.127588)
+#define CS_SIDE_24000_B1                          (-1.229648)
 #define CS_SIDE_24000_B2                           0.282177
 #define CS_SIDE_24000_SCALE                          14
 
 /* Stereo Enhancer coefficients for 32000Hz sample rate, scaled with 0.160322 */
 #define CS_MIDDLE_32000_A0                          0.228400
-#define CS_MIDDLE_32000_A1                         -0.225214
+#define CS_MIDDLE_32000_A1                         (-0.225214)
 #define CS_MIDDLE_32000_A2                          0.000000
-#define CS_MIDDLE_32000_B1                         -0.980126
+#define CS_MIDDLE_32000_B1                         (-0.980126)
 #define CS_MIDDLE_32000_B2                          0.000000
 #define CS_MIDDLE_32000_SCALE                        15
 #define CS_SIDE_32000_A0                            0.364579
-#define CS_SIDE_32000_A1                           -0.207355
-#define CS_SIDE_32000_A2                           -0.157224
-#define CS_SIDE_32000_B1                           -1.274231
+#define CS_SIDE_32000_A1                           (-0.207355)
+#define CS_SIDE_32000_A2                           (-0.157224)
+#define CS_SIDE_32000_B1                           (-1.274231)
 #define CS_SIDE_32000_B2                            0.312495
 #define CS_SIDE_32000_SCALE                          14
 
 /* Stereo Enhancer coefficients for 44100Hz sample rate, scaled with 0.163834 */
 #define CS_MIDDLE_44100_A0                     0.233593
-#define CS_MIDDLE_44100_A1                    -0.231225
+#define CS_MIDDLE_44100_A1                    (-0.231225)
 #define CS_MIDDLE_44100_A2                     0.000000
-#define CS_MIDDLE_44100_B1                    -0.985545
+#define CS_MIDDLE_44100_B1                    (-0.985545)
 #define CS_MIDDLE_44100_B2                     0.000000
 #define CS_MIDDLE_44100_SCALE                        15
 #define CS_SIDE_44100_A0                       0.284573
-#define CS_SIDE_44100_A1                      -0.258910
-#define CS_SIDE_44100_A2                      -0.025662
-#define CS_SIDE_44100_B1                      -1.572248
+#define CS_SIDE_44100_A1                      (-0.258910)
+#define CS_SIDE_44100_A2                      (-0.025662)
+#define CS_SIDE_44100_B1                      (-1.572248)
 #define CS_SIDE_44100_B2                       0.588399
 #define CS_SIDE_44100_SCALE                  14
 
 /* Stereo Enhancer coefficients for 48000Hz sample rate, scaled with 0.164402 */
 #define CS_MIDDLE_48000_A0                     0.234445
-#define CS_MIDDLE_48000_A1                    -0.232261
+#define CS_MIDDLE_48000_A1                    (-0.232261)
 #define CS_MIDDLE_48000_A2                     0.000000
-#define CS_MIDDLE_48000_B1                    -0.986713
+#define CS_MIDDLE_48000_B1                    (-0.986713)
 #define CS_MIDDLE_48000_B2                     0.000000
 #define CS_MIDDLE_48000_SCALE                        15
 #define CS_SIDE_48000_A0                     0.272606
-#define CS_SIDE_48000_A1                    -0.266952
-#define CS_SIDE_48000_A2                    -0.005654
-#define CS_SIDE_48000_B1                    -1.617141
+#define CS_SIDE_48000_A1                    (-0.266952)
+#define CS_SIDE_48000_A2                    (-0.005654)
+#define CS_SIDE_48000_B1                    (-1.617141)
 #define CS_SIDE_48000_B2                     0.630405
 #define CS_SIDE_48000_SCALE                          14
 
@@ -155,31 +155,31 @@
 /* Stereo Enhancer coefficients for 96000Hz sample rate, scaled with  0.165*/
 /* high pass filter with cutoff frequency 102.18 Hz*/
 #define CS_MIDDLE_96000_A0                     0.235532
-#define CS_MIDDLE_96000_A1                    -0.234432
+#define CS_MIDDLE_96000_A1                    (-0.234432)
 #define CS_MIDDLE_96000_A2                     0.000000
-#define CS_MIDDLE_96000_B1                    -0.993334
+#define CS_MIDDLE_96000_B1                    (-0.993334)
 #define CS_MIDDLE_96000_B2                     0.000000
 #define CS_MIDDLE_96000_SCALE                        15
 /* bandpass filter with fc1 270 and fc2 3703, designed using 2nd order butterworth */
 #define CS_SIDE_96000_A0                     0.016727
 #define CS_SIDE_96000_A1                     0.000000
-#define CS_SIDE_96000_A2                    -0.016727
-#define CS_SIDE_96000_B1                    -1.793372
+#define CS_SIDE_96000_A2                    (-0.016727)
+#define CS_SIDE_96000_B1                    (-1.793372)
 #define CS_SIDE_96000_B2                     0.797236
 #define CS_SIDE_96000_SCALE                        14
 
 /* Stereo Enhancer coefficients for 192000Hz sample rate, scaled with  0.1689*/
 #define CS_MIDDLE_192000_A0                     0.241219
-#define CS_MIDDLE_192000_A1                    -0.240656
+#define CS_MIDDLE_192000_A1                    (-0.240656)
 #define CS_MIDDLE_192000_A2                     0.000000
-#define CS_MIDDLE_192000_B1                    -0.996661
+#define CS_MIDDLE_192000_B1                    (-0.996661)
 #define CS_MIDDLE_192000_B2                     0.000000
 #define CS_MIDDLE_192000_SCALE                        15
 /* bandpass filter with fc1 270 and fc2 3703, designed using 2nd order butterworth */
 #define CS_SIDE_192000_A0                     0.008991
-#define CS_SIDE_192000_A1                    -0.000000
-#define CS_SIDE_192000_A2                    -0.008991
-#define CS_SIDE_192000_B1                    -1.892509
+#define CS_SIDE_192000_A1                    (-0.000000)
+#define CS_SIDE_192000_A2                    (-0.008991)
+#define CS_SIDE_192000_B1                    (-1.892509)
 #define CS_SIDE_192000_B2                     0.893524
 #define CS_SIDE_192000_SCALE                       14
 #endif
@@ -203,74 +203,74 @@
 
 /* Reverb coefficients for 8000 Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_8000_A0                          0.667271
-#define CS_REVERB_8000_A1                         -0.667271
+#define CS_REVERB_8000_A1                         (-0.667271)
 #define CS_REVERB_8000_A2                          0.000000
-#define CS_REVERB_8000_B1                         -0.668179
+#define CS_REVERB_8000_B1                         (-0.668179)
 #define CS_REVERB_8000_B2                          0.000000
 #define CS_REVERB_8000_SCALE                         15
 
 /* Reverb coefficients for 11025Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_11025_A0                     0.699638
-#define CS_REVERB_11025_A1                    -0.699638
+#define CS_REVERB_11025_A1                    (-0.699638)
 #define CS_REVERB_11025_A2                     0.000000
-#define CS_REVERB_11025_B1                    -0.749096
+#define CS_REVERB_11025_B1                    (-0.749096)
 #define CS_REVERB_11025_B2                     0.000000
 #define CS_REVERB_11025_SCALE                  15
 
 /* Reverb coefficients for 12000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_12000_A0                   0.706931
-#define CS_REVERB_12000_A1                  -0.706931
+#define CS_REVERB_12000_A1                  (-0.706931)
 #define CS_REVERB_12000_A2                   0.000000
-#define CS_REVERB_12000_B1                  -0.767327
+#define CS_REVERB_12000_B1                  (-0.767327)
 #define CS_REVERB_12000_B2                   0.000000
 #define CS_REVERB_12000_SCALE                15
 
 /* Reverb coefficients for 16000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_16000_A0                      0.728272
-#define CS_REVERB_16000_A1                     -0.728272
+#define CS_REVERB_16000_A1                     (-0.728272)
 #define CS_REVERB_16000_A2                      0.000000
-#define CS_REVERB_16000_B1                     -0.820679
+#define CS_REVERB_16000_B1                     (-0.820679)
 #define CS_REVERB_16000_B2                      0.000000
 #define CS_REVERB_16000_SCALE                        15
 
 /* Reverb coefficients for 22050Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_22050_A0                     0.516396
 #define CS_REVERB_22050_A1                     0.000000
-#define CS_REVERB_22050_A2                    -0.516396
-#define CS_REVERB_22050_B1                    -0.518512
-#define CS_REVERB_22050_B2                    -0.290990
+#define CS_REVERB_22050_A2                    (-0.516396)
+#define CS_REVERB_22050_B1                    (-0.518512)
+#define CS_REVERB_22050_B2                    (-0.290990)
 #define CS_REVERB_22050_SCALE                        15
 
 
 /* Reverb coefficients for 24000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_24000_A0                       0.479565
 #define CS_REVERB_24000_A1                       0.000000
-#define CS_REVERB_24000_A2                      -0.479565
-#define CS_REVERB_24000_B1                      -0.637745
-#define CS_REVERB_24000_B2                      -0.198912
+#define CS_REVERB_24000_A2                      (-0.479565)
+#define CS_REVERB_24000_B1                      (-0.637745)
+#define CS_REVERB_24000_B2                      (-0.198912)
 #define CS_REVERB_24000_SCALE                        15
 
 /* Reverb coefficients for 32000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_32000_A0                      0.380349
 #define CS_REVERB_32000_A1                      0.000000
-#define CS_REVERB_32000_A2                     -0.380349
-#define CS_REVERB_32000_B1                     -0.950873
+#define CS_REVERB_32000_A2                     (-0.380349)
+#define CS_REVERB_32000_B1                     (-0.950873)
 #define CS_REVERB_32000_B2                      0.049127
 #define CS_REVERB_32000_SCALE                        15
 
 /* Reverb coefficients for 44100Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_44100_A0                         0.297389
 #define CS_REVERB_44100_A1                         0.000000
-#define CS_REVERB_44100_A2                        -0.297389
-#define CS_REVERB_44100_B1                        -1.200423
+#define CS_REVERB_44100_A2                        (-0.297389)
+#define CS_REVERB_44100_B1                        (-1.200423)
 #define CS_REVERB_44100_B2                         0.256529
 #define CS_REVERB_44100_SCALE                        14
 
 /* Reverb coefficients for 48000Hz sample rate, scaled with 1.038030 */
 #define CS_REVERB_48000_A0                       0.278661
 #define CS_REVERB_48000_A1                       0.000000
-#define CS_REVERB_48000_A2                      -0.278661
-#define CS_REVERB_48000_B1                      -1.254993
+#define CS_REVERB_48000_A2                      (-0.278661)
+#define CS_REVERB_48000_B1                      (-1.254993)
 #define CS_REVERB_48000_B2                       0.303347
 #define CS_REVERB_48000_SCALE                        14
 
@@ -279,8 +279,8 @@
 /* Band pass filter with fc1=500 and fc2=8000*/
 #define CS_REVERB_96000_A0                       0.1602488
 #define CS_REVERB_96000_A1                       0.000000
-#define CS_REVERB_96000_A2                      -0.1602488
-#define CS_REVERB_96000_B1                      -1.585413
+#define CS_REVERB_96000_A2                      (-0.1602488)
+#define CS_REVERB_96000_B1                      (-1.585413)
 #define CS_REVERB_96000_B2                       0.599377
 #define CS_REVERB_96000_SCALE                        14
 
@@ -288,8 +288,8 @@
 /* Band pass filter with fc1=500 and fc2=8000*/
 #define CS_REVERB_192000_A0                       0.0878369
 #define CS_REVERB_192000_A1                       0.000000
-#define CS_REVERB_192000_A2                      -0.0878369
-#define CS_REVERB_192000_B1                      -1.7765764
+#define CS_REVERB_192000_A2                      (-0.0878369)
+#define CS_REVERB_192000_B1                      (-1.7765764)
 #define CS_REVERB_192000_B2                       0.7804076
 #define CS_REVERB_192000_SCALE                        14
 
@@ -312,163 +312,163 @@
 /* Equaliser coefficients for 8000 Hz sample rate, \
    CS scaled with 1.038497 and CSEX scaled with 0.775480 */
 #define CS_EQUALISER_8000_A0                     1.263312
-#define CS_EQUALISER_8000_A1                    -0.601748
-#define CS_EQUALISER_8000_A2                    -0.280681
-#define CS_EQUALISER_8000_B1                    -0.475865
-#define CS_EQUALISER_8000_B2                    -0.408154
+#define CS_EQUALISER_8000_A1                    (-0.601748)
+#define CS_EQUALISER_8000_A2                    (-0.280681)
+#define CS_EQUALISER_8000_B1                    (-0.475865)
+#define CS_EQUALISER_8000_B2                    (-0.408154)
 #define CS_EQUALISER_8000_SCALE                      14
 #define CSEX_EQUALISER_8000_A0                    0.943357
-#define CSEX_EQUALISER_8000_A1                   -0.449345
-#define CSEX_EQUALISER_8000_A2                   -0.209594
-#define CSEX_EQUALISER_8000_B1                   -0.475865
-#define CSEX_EQUALISER_8000_B2                   -0.408154
+#define CSEX_EQUALISER_8000_A1                   (-0.449345)
+#define CSEX_EQUALISER_8000_A2                   (-0.209594)
+#define CSEX_EQUALISER_8000_B1                   (-0.475865)
+#define CSEX_EQUALISER_8000_B2                   (-0.408154)
 #define CSEX_EQUALISER_8000_SCALE                    15
 
 /* Equaliser coefficients for 11025Hz sample rate, \
    CS scaled with 1.027761 and CSEX scaled with 0.767463 */
 #define CS_EQUALISER_11025_A0                    1.101145
 #define CS_EQUALISER_11025_A1                    0.139020
-#define CS_EQUALISER_11025_A2                   -0.864423
+#define CS_EQUALISER_11025_A2                   (-0.864423)
 #define CS_EQUALISER_11025_B1                    0.024541
-#define CS_EQUALISER_11025_B2                   -0.908930
+#define CS_EQUALISER_11025_B2                   (-0.908930)
 #define CS_EQUALISER_11025_SCALE                     14
 #define CSEX_EQUALISER_11025_A0                    0.976058
-#define CSEX_EQUALISER_11025_A1                   -0.695326
-#define CSEX_EQUALISER_11025_A2                   -0.090809
-#define CSEX_EQUALISER_11025_B1                   -0.610594
-#define CSEX_EQUALISER_11025_B2                   -0.311149
+#define CSEX_EQUALISER_11025_A1                   (-0.695326)
+#define CSEX_EQUALISER_11025_A2                   (-0.090809)
+#define CSEX_EQUALISER_11025_B1                   (-0.610594)
+#define CSEX_EQUALISER_11025_B2                   (-0.311149)
 #define CSEX_EQUALISER_11025_SCALE                   15
 
 /* Equaliser coefficients for 12000Hz sample rate, \
    CS scaled with 1.032521 and CSEX scaled with 0.771017 */
 #define CS_EQUALISER_12000_A0                      1.276661
-#define CS_EQUALISER_12000_A1                     -1.017519
-#define CS_EQUALISER_12000_A2                     -0.044128
-#define CS_EQUALISER_12000_B1                     -0.729616
-#define CS_EQUALISER_12000_B2                     -0.204532
+#define CS_EQUALISER_12000_A1                     (-1.017519)
+#define CS_EQUALISER_12000_A2                     (-0.044128)
+#define CS_EQUALISER_12000_B1                     (-0.729616)
+#define CS_EQUALISER_12000_B2                     (-0.204532)
 #define CS_EQUALISER_12000_SCALE                     14
 #define CSEX_EQUALISER_12000_A0                 1.007095
-#define CSEX_EQUALISER_12000_A1                -0.871912
+#define CSEX_EQUALISER_12000_A1                (-0.871912)
 #define CSEX_EQUALISER_12000_A2                 0.023232
-#define CSEX_EQUALISER_12000_B1                -0.745857
-#define CSEX_EQUALISER_12000_B2                -0.189171
+#define CSEX_EQUALISER_12000_B1                (-0.745857)
+#define CSEX_EQUALISER_12000_B2                (-0.189171)
 #define CSEX_EQUALISER_12000_SCALE                   14
 
 /* Equaliser coefficients for 16000Hz sample rate, \
    CS scaled with 1.031378 and CSEX scaled with 0.770164 */
 #define CS_EQUALISER_16000_A0                     1.281629
-#define CS_EQUALISER_16000_A1                    -1.075872
-#define CS_EQUALISER_16000_A2                    -0.041365
-#define CS_EQUALISER_16000_B1                    -0.725239
-#define CS_EQUALISER_16000_B2                    -0.224358
+#define CS_EQUALISER_16000_A1                    (-1.075872)
+#define CS_EQUALISER_16000_A2                    (-0.041365)
+#define CS_EQUALISER_16000_B1                    (-0.725239)
+#define CS_EQUALISER_16000_B2                    (-0.224358)
 #define CS_EQUALISER_16000_SCALE                     14
 #define CSEX_EQUALISER_16000_A0                  1.081091
-#define CSEX_EQUALISER_16000_A1                 -0.867183
-#define CSEX_EQUALISER_16000_A2                 -0.070247
-#define CSEX_EQUALISER_16000_B1                 -0.515121
-#define CSEX_EQUALISER_16000_B2                 -0.425893
+#define CSEX_EQUALISER_16000_A1                 (-0.867183)
+#define CSEX_EQUALISER_16000_A2                 (-0.070247)
+#define CSEX_EQUALISER_16000_B1                 (-0.515121)
+#define CSEX_EQUALISER_16000_B2                 (-0.425893)
 #define CSEX_EQUALISER_16000_SCALE                   14
 
 /* Equaliser coefficients for 22050Hz sample rate, \
    CS scaled with 1.041576 and CSEX scaled with 0.777779 */
 #define CS_EQUALISER_22050_A0                   1.388605
-#define CS_EQUALISER_22050_A1                  -1.305799
+#define CS_EQUALISER_22050_A1                  (-1.305799)
 #define CS_EQUALISER_22050_A2                   0.039922
-#define CS_EQUALISER_22050_B1                  -0.719494
-#define CS_EQUALISER_22050_B2                  -0.243245
+#define CS_EQUALISER_22050_B1                  (-0.719494)
+#define CS_EQUALISER_22050_B2                  (-0.243245)
 #define CS_EQUALISER_22050_SCALE                     14
 #define CSEX_EQUALISER_22050_A0                   1.272910
-#define CSEX_EQUALISER_22050_A1                  -1.341014
+#define CSEX_EQUALISER_22050_A1                  (-1.341014)
 #define CSEX_EQUALISER_22050_A2                   0.167462
-#define CSEX_EQUALISER_22050_B1                  -0.614219
-#define CSEX_EQUALISER_22050_B2                  -0.345384
+#define CSEX_EQUALISER_22050_B1                  (-0.614219)
+#define CSEX_EQUALISER_22050_B2                  (-0.345384)
 #define CSEX_EQUALISER_22050_SCALE                   14
 
 /* Equaliser coefficients for 24000Hz sample rate, \
    CS scaled with 1.034495 and CSEX scaled with 0.772491 */
 #define CS_EQUALISER_24000_A0                    1.409832
-#define CS_EQUALISER_24000_A1                   -1.456506
+#define CS_EQUALISER_24000_A1                   (-1.456506)
 #define CS_EQUALISER_24000_A2                    0.151410
-#define CS_EQUALISER_24000_B1                   -0.804201
-#define CS_EQUALISER_24000_B2                   -0.163783
+#define CS_EQUALISER_24000_B1                   (-0.804201)
+#define CS_EQUALISER_24000_B2                   (-0.163783)
 #define CS_EQUALISER_24000_SCALE                     14
 #define CSEX_EQUALISER_24000_A0                  1.299198
-#define CSEX_EQUALISER_24000_A1                 -1.452447
+#define CSEX_EQUALISER_24000_A1                 (-1.452447)
 #define CSEX_EQUALISER_24000_A2                  0.240489
-#define CSEX_EQUALISER_24000_B1                 -0.669303
-#define CSEX_EQUALISER_24000_B2                 -0.294984
+#define CSEX_EQUALISER_24000_B1                 (-0.669303)
+#define CSEX_EQUALISER_24000_B2                 (-0.294984)
 #define CSEX_EQUALISER_24000_SCALE                   14
 
 /* Equaliser coefficients for 32000Hz sample rate, \
    CS scaled with 1.044559 and CSEX scaled with 0.780006 */
 #define CS_EQUALISER_32000_A0                     1.560988
-#define CS_EQUALISER_32000_A1                    -1.877724
+#define CS_EQUALISER_32000_A1                    (-1.877724)
 #define CS_EQUALISER_32000_A2                     0.389741
-#define CS_EQUALISER_32000_B1                    -0.907410
-#define CS_EQUALISER_32000_B2                    -0.070489
+#define CS_EQUALISER_32000_B1                    (-0.907410)
+#define CS_EQUALISER_32000_B2                    (-0.070489)
 #define CS_EQUALISER_32000_SCALE                     14
 #define CSEX_EQUALISER_32000_A0                  1.785049
-#define CSEX_EQUALISER_32000_A1                 -2.233497
+#define CSEX_EQUALISER_32000_A1                 (-2.233497)
 #define CSEX_EQUALISER_32000_A2                  0.526431
-#define CSEX_EQUALISER_32000_B1                 -0.445939
-#define CSEX_EQUALISER_32000_B2                 -0.522446
+#define CSEX_EQUALISER_32000_B1                 (-0.445939)
+#define CSEX_EQUALISER_32000_B2                 (-0.522446)
 #define CSEX_EQUALISER_32000_SCALE                   13
 
 /* Equaliser coefficients for 44100Hz sample rate, \
    CS scaled with 1.022170 and CSEX scaled with 0.763288 */
 #define CS_EQUALISER_44100_A0                  1.623993
-#define CS_EQUALISER_44100_A1                 -2.270743
+#define CS_EQUALISER_44100_A1                 (-2.270743)
 #define CS_EQUALISER_44100_A2                  0.688829
-#define CS_EQUALISER_44100_B1                 -1.117190
+#define CS_EQUALISER_44100_B1                 (-1.117190)
 #define CS_EQUALISER_44100_B2                  0.130208
 #define CS_EQUALISER_44100_SCALE                     13
 #define CSEX_EQUALISER_44100_A0                   2.028315
-#define CSEX_EQUALISER_44100_A1                  -2.882459
+#define CSEX_EQUALISER_44100_A1                  (-2.882459)
 #define CSEX_EQUALISER_44100_A2                   0.904535
-#define CSEX_EQUALISER_44100_B1                  -0.593308
-#define CSEX_EQUALISER_44100_B2                  -0.385816
+#define CSEX_EQUALISER_44100_B1                  (-0.593308)
+#define CSEX_EQUALISER_44100_B2                  (-0.385816)
 #define CSEX_EQUALISER_44100_SCALE                   13
 
 /* Equaliser coefficients for 48000Hz sample rate, \
    CS scaled with 1.018635 and CSEX scaled with 0.760648 */
 #define CS_EQUALISER_48000_A0                    1.641177
-#define CS_EQUALISER_48000_A1                   -2.364687
+#define CS_EQUALISER_48000_A1                   (-2.364687)
 #define CS_EQUALISER_48000_A2                    0.759910
-#define CS_EQUALISER_48000_B1                   -1.166774
+#define CS_EQUALISER_48000_B1                   (-1.166774)
 #define CS_EQUALISER_48000_B2                    0.178074
 #define CS_EQUALISER_48000_SCALE                     13
 #define CSEX_EQUALISER_48000_A0                  2.099655
-#define CSEX_EQUALISER_48000_A1                 -3.065220
+#define CSEX_EQUALISER_48000_A1                 (-3.065220)
 #define CSEX_EQUALISER_48000_A2                  1.010417
-#define CSEX_EQUALISER_48000_B1                 -0.634021
-#define CSEX_EQUALISER_48000_B2                 -0.347332
+#define CSEX_EQUALISER_48000_B1                 (-0.634021)
+#define CSEX_EQUALISER_48000_B2                 (-0.347332)
 #define CSEX_EQUALISER_48000_SCALE                   13
 
 
 #ifdef HIGHER_FS
 #define CS_EQUALISER_96000_A0                    1.784497
-#define CS_EQUALISER_96000_A1                   -3.001435
+#define CS_EQUALISER_96000_A1                   (-3.001435)
 #define CS_EQUALISER_96000_A2                    1.228422
-#define CS_EQUALISER_96000_B1                   -1.477804
+#define CS_EQUALISER_96000_B1                   (-1.477804)
 #define CS_EQUALISER_96000_B2                    0.481369
 #define CS_EQUALISER_96000_SCALE                     13
 #define CSEX_EQUALISER_96000_A0                  2.7573
-#define CSEX_EQUALISER_96000_A1                 -4.6721
+#define CSEX_EQUALISER_96000_A1                 (-4.6721)
 #define CSEX_EQUALISER_96000_A2                  1.9317
-#define CSEX_EQUALISER_96000_B1                 -0.971718
-#define CSEX_EQUALISER_96000_B2                 -0.021216
+#define CSEX_EQUALISER_96000_B1                 (-0.971718)
+#define CSEX_EQUALISER_96000_B2                 (-0.021216)
 #define CSEX_EQUALISER_96000_SCALE                   13
 
 #define CS_EQUALISER_192000_A0                    1.889582
-#define CS_EQUALISER_192000_A1                   -3.456140
+#define CS_EQUALISER_192000_A1                   (-3.456140)
 #define CS_EQUALISER_192000_A2                    1.569864
-#define CS_EQUALISER_192000_B1                   -1.700798
+#define CS_EQUALISER_192000_B1                   (-1.700798)
 #define CS_EQUALISER_192000_B2                    0.701824
 #define CS_EQUALISER_192000_SCALE                     13
 #define CSEX_EQUALISER_192000_A0                  3.4273
-#define CSEX_EQUALISER_192000_A1                 -6.2936
+#define CSEX_EQUALISER_192000_A1                 (-6.2936)
 #define CSEX_EQUALISER_192000_A2                  2.8720
-#define CSEX_EQUALISER_192000_B1                 -1.31074
+#define CSEX_EQUALISER_192000_B1                 (-1.31074)
 #define CSEX_EQUALISER_192000_B2                 0.31312
 #define CSEX_EQUALISER_192000_SCALE                   13
 #endif
diff --git a/media/libmedia/Android.bp b/media/libmedia/Android.bp
index a462f3a..12242b3 100644
--- a/media/libmedia/Android.bp
+++ b/media/libmedia/Android.bp
@@ -204,6 +204,7 @@
     ],
 
     export_shared_lib_headers: [
+        "libaudioclient",
         "libbinder",
         "libicuuc",
         "libicui18n",
diff --git a/media/libmedia/IMediaPlayer.cpp b/media/libmedia/IMediaPlayer.cpp
index 3996227..cda3b3a 100644
--- a/media/libmedia/IMediaPlayer.cpp
+++ b/media/libmedia/IMediaPlayer.cpp
@@ -35,6 +35,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 enum {
     DISCONNECT = IBinder::FIRST_CALL_TRANSACTION,
     SET_DATA_SOURCE_URL,
@@ -509,7 +511,7 @@
             return nullptr;
         }
         sp<VolumeShaper::State> state = new VolumeShaper::State();
-        status = state->readFromParcel(reply);
+        status = state->readFromParcel(&reply);
         if (status != NO_ERROR) {
             return nullptr;
         }
@@ -851,14 +853,14 @@
             status_t status = data.readInt32(&present);
             if (status == NO_ERROR && present != 0) {
                 configuration = new VolumeShaper::Configuration();
-                status = configuration->readFromParcel(data);
+                status = configuration->readFromParcel(&data);
             }
             if (status == NO_ERROR) {
                 status = data.readInt32(&present);
             }
             if (status == NO_ERROR && present != 0) {
                 operation = new VolumeShaper::Operation();
-                status = operation->readFromParcel(data);
+                status = operation->readFromParcel(&data);
             }
             if (status == NO_ERROR) {
                 status = (status_t)applyVolumeShaper(configuration, operation);
diff --git a/media/libmedia/include/media/IMediaPlayer.h b/media/libmedia/include/media/IMediaPlayer.h
index e5a98dd..e657716 100644
--- a/media/libmedia/include/media/IMediaPlayer.h
+++ b/media/libmedia/include/media/IMediaPlayer.h
@@ -91,10 +91,10 @@
     virtual status_t        getRetransmitEndpoint(struct sockaddr_in* endpoint) = 0;
     virtual status_t        setNextPlayer(const sp<IMediaPlayer>& next) = 0;
 
-    virtual VolumeShaper::Status applyVolumeShaper(
-                                    const sp<VolumeShaper::Configuration>& configuration,
-                                    const sp<VolumeShaper::Operation>& operation) = 0;
-    virtual sp<VolumeShaper::State> getVolumeShaperState(int id) = 0;
+    virtual media::VolumeShaper::Status applyVolumeShaper(
+                                    const sp<media::VolumeShaper::Configuration>& configuration,
+                                    const sp<media::VolumeShaper::Operation>& operation) = 0;
+    virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) = 0;
 
     // Modular DRM
     virtual status_t        prepareDrm(const uint8_t uuid[16],
diff --git a/media/libmedia/include/media/mediaplayer.h b/media/libmedia/include/media/mediaplayer.h
index 623c374..cb0a99f 100644
--- a/media/libmedia/include/media/mediaplayer.h
+++ b/media/libmedia/include/media/mediaplayer.h
@@ -266,10 +266,10 @@
             status_t        setRetransmitEndpoint(const char* addrString, uint16_t port);
             status_t        setNextMediaPlayer(const sp<MediaPlayer>& player);
 
-            VolumeShaper::Status applyVolumeShaper(
-                                    const sp<VolumeShaper::Configuration>& configuration,
-                                    const sp<VolumeShaper::Operation>& operation);
-            sp<VolumeShaper::State> getVolumeShaperState(int id);
+            media::VolumeShaper::Status applyVolumeShaper(
+                                    const sp<media::VolumeShaper::Configuration>& configuration,
+                                    const sp<media::VolumeShaper::Operation>& operation);
+            sp<media::VolumeShaper::State> getVolumeShaperState(int id);
             // Modular DRM
             status_t        prepareDrm(const uint8_t uuid[16], const Vector<uint8_t>& drmSessionId);
             status_t        releaseDrm();
diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp
index b976721..49101d1 100644
--- a/media/libmedia/mediaplayer.cpp
+++ b/media/libmedia/mediaplayer.cpp
@@ -48,6 +48,8 @@
 
 namespace android {
 
+using media::VolumeShaper;
+
 MediaPlayer::MediaPlayer()
 {
     ALOGV("constructor");
@@ -649,8 +651,12 @@
 status_t MediaPlayer::reset()
 {
     ALOGV("reset");
+    mLockThreadId = getThreadId();
     Mutex::Autolock _l(mLock);
-    return reset_l();
+    status_t result = reset_l();
+    mLockThreadId = 0;
+
+    return result;
 }
 
 status_t MediaPlayer::setAudioStreamType(audio_stream_type_t type)
@@ -860,7 +866,7 @@
     // this will deadlock.
     //
     // The threadId hack below works around this for the care of prepare,
-    // seekTo and start within the same process.
+    // seekTo, start, and reset within the same process.
     // FIXME: Remember, this is a hack, it's not even a hack that is applied
     // consistently for all use-cases, this needs to be revisited.
     if (mLockThreadId != getThreadId()) {
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index 496db0d..ba98f18 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -93,6 +93,7 @@
 using android::BAD_VALUE;
 using android::NOT_ENOUGH_DATA;
 using android::Parcel;
+using android::media::VolumeShaper;
 
 // Max number of entries in the filter.
 const int kMaxFilterSize = 64;  // I pulled that out of thin air.
@@ -1577,7 +1578,7 @@
       mSendLevel(0.0),
       mAuxEffectId(0),
       mFlags(AUDIO_OUTPUT_FLAG_NONE),
-      mVolumeHandler(new VolumeHandler())
+      mVolumeHandler(new media::VolumeHandler())
 {
     ALOGV("AudioOutput(%d)", sessionId);
     if (attr != NULL) {
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index 06b9cad..25691f9 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -132,10 +132,10 @@
         virtual status_t        setParameters(const String8& keyValuePairs);
         virtual String8         getParameters(const String8& keys);
 
-        virtual VolumeShaper::Status applyVolumeShaper(
-                                        const sp<VolumeShaper::Configuration>& configuration,
-                                        const sp<VolumeShaper::Operation>& operation) override;
-        virtual sp<VolumeShaper::State> getVolumeShaperState(int id) override;
+        virtual media::VolumeShaper::Status applyVolumeShaper(
+                                        const sp<media::VolumeShaper::Configuration>& configuration,
+                                        const sp<media::VolumeShaper::Operation>& operation) override;
+        virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
 
     private:
         static void             setMinBufferCount();
@@ -165,7 +165,7 @@
         float                   mSendLevel;
         int                     mAuxEffectId;
         audio_output_flags_t    mFlags;
-        sp<VolumeHandler>       mVolumeHandler;
+        sp<media::VolumeHandler>       mVolumeHandler;
         mutable Mutex           mLock;
 
         // static variables below not protected by mutex
@@ -343,10 +343,10 @@
         virtual status_t        getRetransmitEndpoint(struct sockaddr_in* endpoint);
         virtual status_t        setNextPlayer(const sp<IMediaPlayer>& player);
 
-        virtual VolumeShaper::Status applyVolumeShaper(
-                                        const sp<VolumeShaper::Configuration>& configuration,
-                                        const sp<VolumeShaper::Operation>& operation) override;
-        virtual sp<VolumeShaper::State> getVolumeShaperState(int id) override;
+        virtual media::VolumeShaper::Status applyVolumeShaper(
+                                        const sp<media::VolumeShaper::Configuration>& configuration,
+                                        const sp<media::VolumeShaper::Operation>& operation) override;
+        virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
 
         sp<MediaPlayerBase>     createPlayer(player_type playerType);
 
diff --git a/media/libmediaplayerservice/include/MediaPlayerInterface.h b/media/libmediaplayerservice/include/MediaPlayerInterface.h
index e8d59a7..bcdca37 100644
--- a/media/libmediaplayerservice/include/MediaPlayerInterface.h
+++ b/media/libmediaplayerservice/include/MediaPlayerInterface.h
@@ -146,10 +146,10 @@
         virtual status_t    setParameters(const String8& /* keyValuePairs */) { return NO_ERROR; }
         virtual String8     getParameters(const String8& /* keys */) { return String8::empty(); }
 
-        virtual VolumeShaper::Status applyVolumeShaper(
-                                    const sp<VolumeShaper::Configuration>& configuration,
-                                    const sp<VolumeShaper::Operation>& operation);
-        virtual sp<VolumeShaper::State> getVolumeShaperState(int id);
+        virtual media::VolumeShaper::Status applyVolumeShaper(
+                                    const sp<media::VolumeShaper::Configuration>& configuration,
+                                    const sp<media::VolumeShaper::Operation>& operation);
+        virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id);
     };
 
                         MediaPlayerBase() : mCookie(0), mNotify(0) {}
diff --git a/media/libmediaplayerservice/nuplayer/GenericSource.cpp b/media/libmediaplayerservice/nuplayer/GenericSource.cpp
index aa21fff..e0d253d 100644
--- a/media/libmediaplayerservice/nuplayer/GenericSource.cpp
+++ b/media/libmediaplayerservice/nuplayer/GenericSource.cpp
@@ -847,10 +847,6 @@
 
 status_t NuPlayer::GenericSource::dequeueAccessUnit(
         bool audio, sp<ABuffer> *accessUnit) {
-    if (audio && !mStarted) {
-        return -EWOULDBLOCK;
-    }
-
     // If has gone through stop/releaseDrm sequence, we no longer send down any buffer b/c
     // the codec's crypto object has gone away (b/37960096).
     // Note: This will be unnecessary when stop() changes behavior and releases codec (b/35248283).
@@ -1238,7 +1234,7 @@
     }
 
     if (mAudioTrack.mSource != NULL) {
-        readBuffer(MEDIA_TRACK_TYPE_AUDIO, seekTimeUs);
+        readBuffer(MEDIA_TRACK_TYPE_AUDIO, seekTimeUs, MediaPlayerSeekMode::SEEK_CLOSEST);
         mAudioLastDequeueTimeUs = seekTimeUs;
     }
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index df36046..274f613 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -49,6 +49,7 @@
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/AMessage.h>
 #include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaClock.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/MetaData.h>
@@ -172,9 +173,10 @@
 
 ////////////////////////////////////////////////////////////////////////////////
 
-NuPlayer::NuPlayer(pid_t pid)
+NuPlayer::NuPlayer(pid_t pid, const sp<MediaClock> &mediaClock)
     : mUIDValid(false),
       mPID(pid),
+      mMediaClock(mediaClock),
       mSourceFlags(0),
       mOffloadAudio(false),
       mAudioDecoderGeneration(0),
@@ -204,6 +206,7 @@
       mPausedForBuffering(false),
       mIsDrmProtected(false),
       mDataSourceType(DATA_SOURCE_TYPE_NONE) {
+    CHECK(mediaClock != NULL);
     clearFlushComplete();
 }
 
@@ -1523,7 +1526,7 @@
     sp<AMessage> notify = new AMessage(kWhatRendererNotify, this);
     ++mRendererGeneration;
     notify->setInt32("generation", mRendererGeneration);
-    mRenderer = new Renderer(mAudioSink, notify, flags);
+    mRenderer = new Renderer(mAudioSink, mMediaClock, notify, flags);
     mRendererLooper = new ALooper;
     mRendererLooper->setName("NuPlayerRenderer");
     mRendererLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.h b/media/libmediaplayerservice/nuplayer/NuPlayer.h
index c69835f..5e3c48b 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.h
@@ -30,11 +30,12 @@
 struct AudioPlaybackRate;
 struct AVSyncSettings;
 class IDataSource;
+struct MediaClock;
 class MetaData;
 struct NuPlayerDriver;
 
 struct NuPlayer : public AHandler {
-    explicit NuPlayer(pid_t pid);
+    explicit NuPlayer(pid_t pid, const sp<MediaClock> &mediaClock);
 
     void setUID(uid_t uid);
 
@@ -157,6 +158,7 @@
     bool mUIDValid;
     uid_t mUID;
     pid_t mPID;
+    const sp<MediaClock> mMediaClock;
     Mutex mSourceLock;  // guard |mSource|.
     sp<Source> mSource;
     uint32_t mSourceFlags;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
index ac187cc..cd770b6 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
@@ -750,12 +750,20 @@
 
         buffer->meta()->setInt32("eos", true);
         reply->setInt32("eos", true);
-    } else if (mSkipRenderingUntilMediaTimeUs >= 0) {
+    }
+
+    if (mSkipRenderingUntilMediaTimeUs >= 0) {
         if (timeUs < mSkipRenderingUntilMediaTimeUs) {
             ALOGV("[%s] dropping buffer at time %lld as requested.",
                      mComponentName.c_str(), (long long)timeUs);
 
             reply->post();
+            if (eos) {
+                notifyResumeCompleteIfNecessary();
+                if (mRenderer != NULL && !isDiscontinuityPending()) {
+                    mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
+                }
+            }
             return true;
         }
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
index dc29761..209caeb 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
@@ -28,6 +28,7 @@
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/ALooper.h>
 #include <media/stagefright/foundation/AUtils.h>
+#include <media/stagefright/MediaClock.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/Utils.h>
 
@@ -66,7 +67,8 @@
       mSeekInProgress(false),
       mPlayingTimeUs(0),
       mLooper(new ALooper),
-      mPlayer(new NuPlayer(pid)),
+      mMediaClock(new MediaClock),
+      mPlayer(new NuPlayer(pid, mMediaClock)),
       mPlayerFlags(0),
       mAnalyticsItem(NULL),
       mClientUid(-1),
@@ -76,6 +78,8 @@
     ALOGD("NuPlayerDriver(%p) created, clientPid(%d)", this, pid);
     mLooper->setName("NuPlayerDriver Looper");
 
+    mMediaClock->init();
+
     // set up an analytics record
     mAnalyticsItem = new MediaAnalyticsItem(kKeyPlayer);
     mAnalyticsItem->generateSessionID();
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h
index d0cf1dd..b797ca1 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h
@@ -22,6 +22,7 @@
 namespace android {
 
 struct ALooper;
+struct MediaClock;
 struct NuPlayer;
 
 struct NuPlayerDriver : public MediaPlayerInterface {
@@ -127,6 +128,7 @@
     // <<<
 
     sp<ALooper> mLooper;
+    const sp<MediaClock> mMediaClock;
     const sp<NuPlayer> mPlayer;
     sp<AudioSink> mAudioSink;
     uint32_t mPlayerFlags;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
index bd866cb..dec17e2 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
@@ -89,6 +89,7 @@
 
 NuPlayer::Renderer::Renderer(
         const sp<MediaPlayerBase::AudioSink> &sink,
+        const sp<MediaClock> &mediaClock,
         const sp<AMessage> &notify,
         uint32_t flags)
     : mAudioSink(sink),
@@ -103,6 +104,7 @@
       mAudioDrainGeneration(0),
       mVideoDrainGeneration(0),
       mAudioEOSGeneration(0),
+      mMediaClock(mediaClock),
       mPlaybackSettings(AUDIO_PLAYBACK_RATE_DEFAULT),
       mAudioFirstAnchorTimeMediaUs(-1),
       mAnchorTimeMediaUs(-1),
@@ -130,7 +132,7 @@
       mLastAudioBufferDrained(0),
       mUseAudioCallback(false),
       mWakeLock(new AWakeLock()) {
-    mMediaClock = new MediaClock;
+    CHECK(mediaClock != NULL);
     mPlaybackRate = mPlaybackSettings.mSpeed;
     mMediaClock->setPlaybackRate(mPlaybackRate);
 }
@@ -149,7 +151,6 @@
         flushQueue(&mVideoQueue);
     }
     mWakeLock.clear();
-    mMediaClock.clear();
     mVideoScheduler.clear();
     mNotify.clear();
     mAudioSink.clear();
@@ -1440,6 +1441,7 @@
     if (audio) {
         // Video might outlive audio. Clear anchor to enable video only case.
         mAnchorTimeMediaUs = -1;
+        mHasAudio = false;
     }
 }
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
index f58b79c..567f8f1 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.h
@@ -36,6 +36,7 @@
         FLAG_OFFLOAD_AUDIO = 2,
     };
     Renderer(const sp<MediaPlayerBase::AudioSink> &sink,
+             const sp<MediaClock> &mediaClock,
              const sp<AMessage> &notify,
              uint32_t flags = 0);
 
@@ -165,7 +166,7 @@
     int32_t mVideoDrainGeneration;
     int32_t mAudioEOSGeneration;
 
-    sp<MediaClock> mMediaClock;
+    const sp<MediaClock> mMediaClock;
     float mPlaybackRate; // audio track rate
 
     AudioPlaybackRate mPlaybackSettings;
diff --git a/media/libnbaio/NBLog.cpp b/media/libnbaio/NBLog.cpp
index 2f639d2..ad38390 100644
--- a/media/libnbaio/NBLog.cpp
+++ b/media/libnbaio/NBLog.cpp
@@ -12,88 +12,16 @@
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
+ *
+ *
  */
 
-/*
-* Documentation: Workflow summary for histogram data processing:
-* For more details on FIFO, please see system/media/audio_utils; doxygen
-* TODO: add this documentation to doxygen once it is further developed
-* 1) Writing buffer period timestamp to the circular buffer
-* onWork()
-*     Called every period length (e.g., 4ms)
-*     Calls LOG_HIST_TS
-* LOG_HIST_TS
-*     Hashes file name and line number, and writes single timestamp to buffer
-*     calls NBLOG::Writer::logEventHistTS once
-* NBLOG::Writer::logEventHistTS
-*     calls NBLOG::Writer::log on hash and current timestamp
-*     time is in CLOCK_MONOTONIC converted to ns
-* NBLOG::Writer::log(Event, const void*, size_t)
-*     Initializes Entry, a struct containing one log entry
-*     Entry contains the event type (mEvent), data length (mLength),
-*     and data pointer (mData)
-*     TODO: why mLength (max length of buffer data)  must be <= kMaxLength = 255?
-*     calls NBLOG::Writer::log(Entry *, bool)
-* NBLog::Writer::log(Entry *, bool)
-*     Calls copyEntryDataAt to format data as follows in temp array:
-*     [type][length][data ... ][length]
-*     calls audio_utils_fifo_writer.write on temp
-* audio_utils_fifo_writer.write
-*     calls obtain(), memcpy (reference in doxygen)
-*     returns number of frames written
-* ssize_t audio_utils_fifo_reader::obtain
-*     Determines readable buffer section via pointer arithmetic on reader
-*     and writer pointers
-* Similarly, LOG_AUDIO_STATE() is called by onStateChange whenever audio is
-* turned on or off, and writes this notification to the FIFO.
-*
-* 2) reading the data from shared memory
-* Thread::threadloop()
-*     TODO: add description?
-* NBLog::MergeThread::threadLoop()
-*     calls NBLog::Merger::merge
-* NBLog::Merger::merge
-*     Merges snapshots sorted by timestamp
-*     for each reader in vector of class NamedReader,
-*     callsNamedReader::reader()->getSnapshot
-*     TODO: check whether the rest of this function is relevant
-* NBLog::Reader::getSnapshot
-*     copies snapshot of reader's fifo buffer into its own buffer
-*     calls mFifoReader->obtain to find readable data
-*     sets snapshot.begin() and .end() iterators to boundaries of valid entries
-*     moves the fifo reader index to after the last entry read
-*     in this case, the buffer is in shared memory. in (4), the buffer is private
-*
-* 3) reading the data from private buffer
-* MediaLogService::dump
-*     calls NBLog::Reader::dump(CONSOLE)
-*     The private buffer contains all logs for all readers in shared memory
-* NBLog::Reader::dump(int)
-*     calls getSnapshot on the current reader
-*     calls dump(int, size_t, Snapshot)
-* NBLog::Reader::dump(int, size, snapshot)
-*     iterates through snapshot's events and switches based on their type
-*     (string, timestamp, etc...)
-*     In the case of EVENT_HISTOGRAM_ENTRY_TS, adds a list of timestamp sequences
-*     (histogram entry) to NBLog::mHists
-*     TODO: add every HISTOGRAM_ENTRY_TS to two
-*     circular buffers: one short-term and one long-term (can add even longer-term
-*     structures in the future). When dump is called, print everything currently
-*     in the buffer.
-* NBLog::drawHistogram
-*     input: timestamp array
-*     buckets this to a histogram and prints
-*
-*/
-
 #define LOG_TAG "NBLog"
-// #define LOG_NDEBUG 0
 
 #include <algorithm>
 #include <climits>
 #include <deque>
 #include <fstream>
-// #include <inttypes.h>
 #include <iostream>
 #include <math.h>
 #include <numeric>
@@ -109,7 +37,7 @@
 #include <media/nbaio/NBLog.h>
 #include <media/nbaio/PerformanceAnalysis.h>
 #include <media/nbaio/ReportPerformance.h>
-// #include <utils/CallStack.h> // used to print callstack
+#include <utils/CallStack.h>
 #include <utils/Log.h>
 #include <utils/String8.h>
 
@@ -760,14 +688,15 @@
 // ---------------------------------------------------------------------------
 
 const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
-                                                           NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
+        NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
+        NBLog::Event::EVENT_AUDIO_STATE};
 const std::set<NBLog::Event> NBLog::Reader::endingTypes   {NBLog::Event::EVENT_END_FMT,
-                                                           NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
-                                                           NBLog::Event::EVENT_AUDIO_STATE};
+        NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
+        NBLog::Event::EVENT_AUDIO_STATE};
 
 NBLog::Reader::Reader(const void *shared, size_t size)
-    : mShared((/*const*/ Shared *) shared), /*mIMemory*/
-      mFd(-1), mIndent(0),
+    : mFd(-1), mIndent(0), mLost(0),
+      mShared((/*const*/ Shared *) shared), /*mIMemory*/
       mFifo(mShared != NULL ?
         new audio_utils_fifo(size, sizeof(uint8_t),
             mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
@@ -805,6 +734,9 @@
     return nullptr; // no entry found
 }
 
+// Copies content of a Reader FIFO into its Snapshot
+// The Snapshot has the same raw data, but represented as a sequence of entries
+// and an EntryIterator making it possible to process the data.
 std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
 {
     if (mFifoReader == NULL) {
@@ -870,24 +802,11 @@
 
 }
 
-// TODO: move this to PerformanceAnalysis
-// TODO: make call to dump periodic so that data in shared FIFO does not get overwritten
-void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
+// Takes raw content of the local merger FIFO, processes log entries, and
+// writes the data to a map of class PerformanceAnalysis, based on their thread ID.
+void NBLog::MergeReader::getAndProcessSnapshot(NBLog::Reader::Snapshot &snapshot)
 {
-    mFd = fd;
-    mIndent = indent;
     String8 timestamp, body;
-    // FIXME: this is not thread safe
-    // TODO: need a separate instance of performanceAnalysis for each thread
-    // used to store data and to call analysis functions
-    static ReportPerformance::PerformanceAnalysis performanceAnalysis;
-    size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
-    if (lost > 0) {
-        body.appendFormat("warning: lost %zu bytes worth of events", lost);
-        // TODO timestamp empty here, only other choice to wait for the first timestamp event in the
-        //      log to push it out.  Consider keeping the timestamp/body between calls to copyEntryDataAt().
-        dumpLine(timestamp, body);
-    }
 
     for (auto entry = snapshot.begin(); entry != snapshot.end();) {
         switch (entry->type) {
@@ -902,12 +821,22 @@
             memcpy(&hash, &(data->hash), sizeof(hash));
             int64_t ts;
             memcpy(&ts, &data->ts, sizeof(ts));
-            performanceAnalysis.logTsEntry(ts);
+            // TODO: hash for histogram ts and audio state need to match
+            // and correspond to audio production source file location
+            mThreadPerformanceAnalysis[data->author][0 /*hash*/].logTsEntry(ts);
             ++entry;
             break;
         }
         case EVENT_AUDIO_STATE: {
-            performanceAnalysis.handleStateChange();
+            HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
+            // TODO This memcpies are here to avoid unaligned memory access crash.
+            // There's probably a more efficient way to do it
+            log_hash_t hash;
+            memcpy(&hash, &(data->hash), sizeof(hash));
+            // TODO: remove ts if unused
+            int64_t ts;
+            memcpy(&ts, &data->ts, sizeof(ts));
+            mThreadPerformanceAnalysis[data->author][0 /*hash*/].handleStateChange();
             ++entry;
             break;
         }
@@ -922,19 +851,25 @@
             break;
         }
     }
-    performanceAnalysis.reportPerformance(&body);
+    // FIXME: decide whether to print the warnings here or elsewhere
     if (!body.isEmpty()) {
         dumpLine(timestamp, body);
     }
 }
 
-void NBLog::Reader::dump(int fd, size_t indent)
+void NBLog::MergeReader::getAndProcessSnapshot()
 {
-    // get a snapshot, dump it
+    // get a snapshot, process it
     std::unique_ptr<Snapshot> snap = getSnapshot();
-    dump(fd, indent, *snap);
+    getAndProcessSnapshot(*snap);
 }
 
+void NBLog::MergeReader::dump(int fd, int indent) {
+    // TODO: add a mutex around media.log dump
+    ReportPerformance::dump(fd, indent, mThreadPerformanceAnalysis);
+}
+
+// Writes a string to the console
 void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
 {
     if (mFd >= 0) {
@@ -1093,6 +1028,7 @@
       {}
 
 void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
+
     // FIXME This is called by binder thread in MediaLogService::registerWriter
     //       but the access to shared variable mNamedReaders is not yet protected by a lock.
     mNamedReaders.push_back(reader);
@@ -1116,7 +1052,7 @@
     return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
 }
 
-// Merge registered readers, sorted by timestamp
+// Merge registered readers, sorted by timestamp, and write data to a single FIFO in local memory
 void NBLog::Merger::merge() {
     // FIXME This is called by merge thread
     //       but the access to shared variable mNamedReaders is not yet protected by a lock.
@@ -1173,8 +1109,9 @@
 
 // ---------------------------------------------------------------------------
 
-NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
+NBLog::MergeThread::MergeThread(NBLog::Merger &merger, NBLog::MergeReader &mergeReader)
     : mMerger(merger),
+      mMergeReader(mergeReader),
       mTimeoutUs(0) {}
 
 NBLog::MergeThread::~MergeThread() {
@@ -1196,7 +1133,12 @@
         mTimeoutUs -= kThreadSleepPeriodUs;
     }
     if (doMerge) {
+        // Merge data from all the readers
         mMerger.merge();
+        // Process the data collected by mMerger and write it to PerformanceAnalysis
+        // FIXME: decide whether to call getAndProcessSnapshot every time
+        // or whether to have a separate thread that calls it with a lower frequency
+        mMergeReader.getAndProcessSnapshot();
     }
     return true;
 }
diff --git a/media/libnbaio/OWNERS b/media/libnbaio/OWNERS
index f9cb567..eece71f 100644
--- a/media/libnbaio/OWNERS
+++ b/media/libnbaio/OWNERS
@@ -1 +1,2 @@
 gkasten@google.com
+hunga@google.com
diff --git a/media/libnbaio/PerformanceAnalysis.cpp b/media/libnbaio/PerformanceAnalysis.cpp
index fb3bddc..9e0f84d 100644
--- a/media/libnbaio/PerformanceAnalysis.cpp
+++ b/media/libnbaio/PerformanceAnalysis.cpp
@@ -36,7 +36,6 @@
 #include <media/nbaio/NBLog.h>
 #include <media/nbaio/PerformanceAnalysis.h>
 #include <media/nbaio/ReportPerformance.h>
-// #include <utils/CallStack.h> // used to print callstack
 #include <utils/Log.h>
 #include <utils/String8.h>
 
@@ -47,246 +46,239 @@
 
 namespace ReportPerformance {
 
-PerformanceAnalysis::PerformanceAnalysis() {
-    // These variables will be (FIXME) learned from the data
-    kPeriodMs = 4; // typical buffer period (mode)
-    // average number of Ms spent processing buffer
-    kPeriodMsCPU = static_cast<int>(kPeriodMs * kRatio);
-}
-
-// converts a time series into a map. key: buffer period length. value: count
-static std::map<int, int> buildBuckets(const std::vector<int64_t> &samples) {
-    // TODO allow buckets of variable resolution
-    std::map<int, int> buckets;
-    for (size_t i = 1; i < samples.size(); ++i) {
-        ++buckets[deltaMs(samples[i - 1], samples[i])];
-    }
-    return buckets;
-}
-
-static int widthOf(int x) {
-    int width = 0;
-    while (x > 0) {
-        ++width;
-        x /= 10;
-    }
-    return width;
-}
-
-// Given a series of audio processing wakeup timestamps,
-// buckets the time intervals into a histogram, searches for
+// Given an audio processing wakeup timestamp, buckets the time interval
+// since the previous timestamp into a histogram, searches for
 // outliers, analyzes the outlier series for unexpectedly
-// small or large values and stores these as peaks, and flushes
-// the timestamp series from memory.
-void PerformanceAnalysis::processAndFlushTimeStampSeries() {
-    // 1) analyze the series to store all outliers and their exact timestamps:
-    storeOutlierData(mTimeStampSeries);
-
-    // 2) detect peaks in the outlier series
-    detectPeaks();
-
-    // 3) compute its histogram, append to mRecentHists and clear the time series
-    mRecentHists.emplace_back(static_cast<timestamp>(mTimeStampSeries[0]),
-                              buildBuckets(mTimeStampSeries));
-    // do not let mRecentHists exceed capacity
-    // ALOGD("mRecentHists size: %d", static_cast<int>(mRecentHists.size()));
-    if (mRecentHists.size() >= kRecentHistsCapacity) {
-        //  ALOGD("popped back mRecentHists");
-        mRecentHists.pop_front();
+// small or large values and stores these as peaks
+void PerformanceAnalysis::logTsEntry(timestamp ts) {
+    // after a state change, start a new series and do not
+    // record time intervals in-between
+    if (mBufferPeriod.mPrevTs == 0) {
+        mBufferPeriod.mPrevTs = ts;
+        return;
     }
-    mTimeStampSeries.clear();
+
+    // calculate time interval between current and previous timestamp
+    const msInterval diffMs = static_cast<msInterval>(
+        deltaMs(mBufferPeriod.mPrevTs, ts));
+
+    const int diffJiffy = deltaJiffy(mBufferPeriod.mPrevTs, ts);
+
+    // old versus new weight ratio when updating the buffer period mean
+    static constexpr double exponentialWeight = 0.999;
+    // update buffer period mean with exponential weighting
+    mBufferPeriod.mMean = (mBufferPeriod.mMean < 0) ? diffMs :
+            exponentialWeight * mBufferPeriod.mMean + (1.0 - exponentialWeight) * diffMs;
+    // set mOutlierFactor to a smaller value for the fastmixer thread
+    const int kFastMixerMax = 10;
+    // NormalMixer times vary much more than FastMixer times.
+    // TODO: mOutlierFactor values are set empirically based on what appears to be
+    // an outlier. Learn these values from the data.
+    mBufferPeriod.mOutlierFactor = mBufferPeriod.mMean < kFastMixerMax ? 1.8 : 2.0;
+    // set outlier threshold
+    mBufferPeriod.mOutlier = mBufferPeriod.mMean * mBufferPeriod.mOutlierFactor;
+
+    // Check whether the time interval between the current timestamp
+    // and the previous one is long enough to count as an outlier
+    const bool isOutlier = detectAndStoreOutlier(diffMs);
+    // If an outlier was found, check whether it was a peak
+    if (isOutlier) {
+        /*bool isPeak =*/ detectAndStorePeak(
+            mOutlierData[0].first, mOutlierData[0].second);
+        // TODO: decide whether to insert a new empty histogram if a peak
+        // TODO: remove isPeak if unused to avoid "unused variable" error
+        // occurred at the current timestamp
+    }
+
+    // Insert a histogram to mHists if it is empty, or
+    // close the current histogram and insert a new empty one if
+    // if the current histogram has spanned its maximum time interval.
+    if (mHists.empty() ||
+        deltaMs(mHists[0].first, ts) >= kMaxLength.HistTimespanMs) {
+        mHists.emplace_front(ts, std::map<int, int>());
+        // When memory is full, delete oldest histogram
+        // TODO: use a circular buffer
+        if (mHists.size() >= kMaxLength.Hists) {
+            mHists.resize(kMaxLength.Hists);
+        }
+    }
+    // add current time intervals to histogram
+    ++mHists[0].second[diffJiffy];
+    // update previous timestamp
+    mBufferPeriod.mPrevTs = ts;
 }
 
+
 // forces short-term histogram storage to avoid adding idle audio time interval
 // to buffer period data
 void PerformanceAnalysis::handleStateChange() {
-    ALOGD("handleStateChange");
-    processAndFlushTimeStampSeries();
+    mBufferPeriod.mPrevTs = 0;
     return;
 }
 
-// Takes a single buffer period timestamp entry information and stores it in a
-// temporary series of timestamps. Once the series is full, the data is analyzed,
-// stored, and emptied.
-void PerformanceAnalysis::logTsEntry(int64_t ts) {
-    // TODO might want to filter excessively high outliers, which are usually caused
-    // by the thread being inactive.
-    // Store time series data for each reader in order to bucket it once there
-    // is enough data. Then, write to recentHists as a histogram.
-    mTimeStampSeries.push_back(ts);
-    // if length of the time series has reached kShortHistSize samples,
-    // analyze the data and flush the timestamp series from memory
-    if (mTimeStampSeries.size() >= kShortHistSize) {
-        processAndFlushTimeStampSeries();
-    }
-}
 
-// When the short-term histogram array mRecentHists has reached capacity,
-// merge histograms for data compression and store them in mLongTermHists
-// clears mRecentHists
-// TODO: have logTsEntry write directly to mLongTermHists, discard mRecentHists,
-// start a new histogram when a peak occurs
-void PerformanceAnalysis::processAndFlushRecentHists() {
-
-    // Buckets is used to aggregate short-term histograms.
-    Histogram buckets;
-    timestamp startingTs = mRecentHists[0].first;
-
-    for (const auto &shortHist: mRecentHists) {
-        // If the time between starting and ending timestamps has reached the maximum,
-        // add the current histogram (buckets) to the long-term histogram buffer,
-        // clear buckets, and start a new long-term histogram aggregation process.
-        if (deltaMs(startingTs, shortHist.first) >= kMaxHistTimespanMs) {
-            mLongTermHists.emplace_back(startingTs, std::move(buckets));
-            buckets.clear();
-            startingTs = shortHist.first;
-            // When memory is full, delete oldest histogram
-            // TODO use a circular buffer
-            if (mLongTermHists.size() >= kLongTermHistsCapacity) {
-                mLongTermHists.pop_front();
-            }
-        }
-
-        // add current histogram to buckets
-        for (const auto &countPair : shortHist.second) {
-            buckets[countPair.first] += countPair.second;
-        }
-    }
-    mRecentHists.clear();
-    // TODO: decide when/where to call writeToFile
-    // TODO: add a thread-specific extension to the file name
-    static const char* const kName = (const char *) "/data/misc/audioserver/sample_results.txt";
-    writeToFile(mOutlierData, mLongTermHists, kName, false);
-}
-
-// Given a series of outlier intervals (mOutlier data),
+// Checks whether the time interval between two outliers is far enough from
+// a typical delta to be considered a peak.
 // looks for changes in distribution (peaks), which can be either positive or negative.
 // The function sets the mean to the starting value and sigma to 0, and updates
 // them as long as no peak is detected. When a value is more than 'threshold'
 // standard deviations from the mean, a peak is detected and the mean and sigma
 // are set to the peak value and 0.
-void PerformanceAnalysis::detectPeaks() {
+bool PerformanceAnalysis::detectAndStorePeak(msInterval diff, timestamp ts) {
+    bool isPeak = false;
     if (mOutlierData.empty()) {
-        return;
+        return false;
     }
+    // Update mean of the distribution
+    // TypicalDiff is used to check whether a value is unusually large
+    // when we cannot use standard deviations from the mean because the sd is set to 0.
+    mOutlierDistribution.mTypicalDiff = (mOutlierDistribution.mTypicalDiff *
+            (mOutlierData.size() - 1) + diff) / mOutlierData.size();
 
-    // compute mean of the distribution. Used to check whether a value is large
-    const double kTypicalDiff = std::accumulate(
-        mOutlierData.begin(), mOutlierData.end(), 0,
-        [](auto &a, auto &b){return a + b.first;}) / mOutlierData.size();
-    // ALOGD("typicalDiff %f", kTypicalDiff);
+    // Initialize short-term mean at start of program
+    if (mOutlierDistribution.mMean == 0) {
+        mOutlierDistribution.mMean = diff;
+    }
+    // Update length of current sequence of outliers
+    mOutlierDistribution.mN++;
 
-    // iterator at the beginning of a sequence, or updated to the most recent peak
-    std::deque<std::pair<uint64_t, uint64_t>>::iterator start = mOutlierData.begin();
-    // the mean and standard deviation are updated every time a peak is detected
-    // initialize first time. The mean from the previous sequence is stored
-    // for the next sequence. Here, they are initialized for the first time.
-    if (mPeakDetectorMean < 0) {
-        mPeakDetectorMean = static_cast<double>(start->first);
-        mPeakDetectorSd = 0;
-    }
-    auto sqr = [](auto x){ return x * x; };
-    for (auto it = mOutlierData.begin(); it != mOutlierData.end(); ++it) {
-        // no surprise occurred:
-        // the new element is a small number of standard deviations from the mean
-        if ((fabs(it->first - mPeakDetectorMean) < kStddevThreshold * mPeakDetectorSd) ||
-             // or: right after peak has been detected, the delta is smaller than average
-            (mPeakDetectorSd == 0 && fabs(it->first - mPeakDetectorMean) < kTypicalDiff)) {
-            // update the mean and sd:
-            // count number of elements (distance between start interator and current)
-            const int kN = std::distance(start, it) + 1;
-            // usual formulas for mean and sd
-            mPeakDetectorMean = std::accumulate(start, it + 1, 0.0,
-                                   [](auto &a, auto &b){return a + b.first;}) / kN;
-            mPeakDetectorSd = sqrt(std::accumulate(start, it + 1, 0.0,
-                      [=](auto &a, auto &b){ return a + sqr(b.first - mPeakDetectorMean);})) /
-                      ((kN > 1)? kN - 1 : kN); // kN - 1: mean is correlated with variance
+    // Check whether a large deviation from the mean occurred.
+    // If the standard deviation has been reset to zero, the comparison is
+    // instead to the mean of the full mOutlierInterval sequence.
+    if ((fabs(diff - mOutlierDistribution.mMean) <
+            mOutlierDistribution.kMaxDeviation * mOutlierDistribution.mSd) ||
+            (mOutlierDistribution.mSd == 0 &&
+            fabs(diff - mOutlierDistribution.mMean) <
+            mOutlierDistribution.mTypicalDiff)) {
+        // update the mean and sd using online algorithm
+        // https://en.wikipedia.org/wiki/
+        // Algorithms_for_calculating_variance#Online_algorithm
+        mOutlierDistribution.mN++;
+        const double kDelta = diff - mOutlierDistribution.mMean;
+        mOutlierDistribution.mMean += kDelta / mOutlierDistribution.mN;
+        const double kDelta2 = diff - mOutlierDistribution.mMean;
+        mOutlierDistribution.mM2 += kDelta * kDelta2;
+        mOutlierDistribution.mSd = (mOutlierDistribution.mN < 2) ? 0 :
+                sqrt(mOutlierDistribution.mM2 / (mOutlierDistribution.mN - 1));
+    } else {
+        // new value is far from the mean:
+        // store peak timestamp and reset mean, sd, and short-term sequence
+        isPeak = true;
+        mPeakTimestamps.emplace_front(ts);
+        // if mPeaks has reached capacity, delete oldest data
+        // Note: this means that mOutlierDistribution values do not exactly
+        // match the data we have in mPeakTimestamps, but this is not an issue
+        // in practice for estimating future peaks.
+        // TODO: turn this into a circular buffer
+        if (mPeakTimestamps.size() >= kMaxLength.Peaks) {
+            mPeakTimestamps.resize(kMaxLength.Peaks);
         }
-        // surprising value: store peak timestamp and reset mean, sd, and start iterator
-        else {
-            mPeakTimestamps.emplace_back(it->second);
-            // TODO: remove pop_front once a circular buffer is in place
-            if (mPeakTimestamps.size() >= kPeakSeriesSize) {
-                mPeakTimestamps.pop_front();
-            }
-            mPeakDetectorMean = static_cast<double>(it->first);
-            mPeakDetectorSd = 0;
-            start = it;
-        }
+        mOutlierDistribution.mMean = 0;
+        mOutlierDistribution.mSd = 0;
+        mOutlierDistribution.mN = 0;
+        mOutlierDistribution.mM2 = 0;
     }
-    return;
+    return isPeak;
 }
 
-// Called by LogTsEntry. The input is a vector of timestamps.
-// Finds outliers and writes to mOutlierdata.
-// Each value in mOutlierdata consists of: <outlier timestamp, time elapsed since previous outlier>.
+
+// Determines whether the difference between a timestamp and the previous
+// one is beyond a threshold. If yes, stores the timestamp as an outlier
+// and writes to mOutlierdata in the following format:
+// Time elapsed since previous outlier: Timestamp of start of outlier
 // e.g. timestamps (ms) 1, 4, 5, 16, 18, 28 will produce pairs (4, 5), (13, 18).
-// This function is applied to the time series before it is converted into a histogram.
-void PerformanceAnalysis::storeOutlierData(const std::vector<int64_t> &timestamps) {
-    if (timestamps.size() < 1) {
-        return;
-    }
-    // first pass: need to initialize
-    if (mElapsed == 0) {
-        mPrevNs = timestamps[0];
-    }
-    for (const auto &ts: timestamps) {
-        const uint64_t diffMs = static_cast<uint64_t>(deltaMs(mPrevNs, ts));
-        if (diffMs >= static_cast<uint64_t>(kOutlierMs)) {
-            mOutlierData.emplace_back(mElapsed, static_cast<uint64_t>(mPrevNs));
-            // Remove oldest value if the vector is full
-            // TODO: remove pop_front once circular buffer is in place
-            // FIXME: make sure kShortHistSize is large enough that that data will never be lost
-            // before being written to file or to a FIFO
-            if (mOutlierData.size() >= kOutlierSeriesSize) {
-                mOutlierData.pop_front();
-            }
-            mElapsed = 0;
+// TODO: learn what timestamp sequences correlate with glitches instead of
+// manually designing a heuristic.
+bool PerformanceAnalysis::detectAndStoreOutlier(const msInterval diffMs) {
+    bool isOutlier = false;
+    if (diffMs >= mBufferPeriod.mOutlier) {
+        isOutlier = true;
+        mOutlierData.emplace_front(
+                mOutlierDistribution.mElapsed, mBufferPeriod.mPrevTs);
+        // Remove oldest value if the vector is full
+        // TODO: turn this into a circular buffer
+        // TODO: make sure kShortHistSize is large enough that that data will never be lost
+        // before being written to file or to a FIFO
+        if (mOutlierData.size() >= kMaxLength.Outliers) {
+            mOutlierData.resize(kMaxLength.Outliers);
         }
-        mElapsed += diffMs;
-        mPrevNs = ts;
+        mOutlierDistribution.mElapsed = 0;
     }
+    mOutlierDistribution.mElapsed += diffMs;
+    return isOutlier;
 }
 
-
-// FIXME: delete this temporary test code, recycled for various new functions
-void PerformanceAnalysis::testFunction() {
-    // produces values (4: 5000000), (13: 18000000)
-    // ns timestamps of buffer periods
-    const std::vector<int64_t>kTempTestData = {1000000, 4000000, 5000000,
-                                               16000000, 18000000, 28000000};
-    PerformanceAnalysis::storeOutlierData(kTempTestData);
-    for (const auto &outlier: mOutlierData) {
-        ALOGE("PerformanceAnalysis test %lld: %lld",
-              static_cast<long long>(outlier.first), static_cast<long long>(outlier.second));
+static int widthOf(int x) {
+    int width = 0;
+    if (x < 0) {
+        width++;
+        x = x == INT_MIN ? INT_MAX : -x;
     }
-    detectPeaks();
+    // assert (x >= 0)
+    do {
+        ++width;
+        x /= 10;
+    } while (x > 0);
+    return width;
 }
 
-// TODO Make it return a std::string instead of modifying body --> is this still relevant?
-// TODO consider changing all ints to uint32_t or uint64_t
-// TODO: move this to ReportPerformance, probably make it a friend function of PerformanceAnalysis
-void PerformanceAnalysis::reportPerformance(String8 *body, int maxHeight) {
-    if (mRecentHists.size() < 1) {
-        ALOGD("reportPerformance: mRecentHists is empty");
+// computes the column width required for a specific histogram value
+inline int numberWidth(double number, int leftPadding) {
+    // Added values account for whitespaces needed around numbers, and for the
+    // dot and decimal digit not accounted for by widthOf
+    return std::max(std::max(widthOf(static_cast<int>(number)) + 3, 2), leftPadding + 1);
+}
+
+// rounds value to precision based on log-distance from mean
+inline double logRound(double x, double mean) {
+    // Larger values decrease range of high resolution and prevent overflow
+    // of a histogram on the console.
+    // The following formula adjusts kBase based on the buffer period length.
+    // Different threads have buffer periods ranging from 2 to 40. The
+    // formula below maps buffer period 2 to kBase = ~1, 4 to ~2, 20 to ~3, 40 to ~4.
+    // TODO: tighten this for higher means, the data still overflows
+    const double kBase = log(mean) / log(2.2);
+    const double power = floor(
+        log(abs(x - mean) / mean) / log(kBase)) + 2;
+    // do not round values close to the mean
+    if (power < 1) {
+        return x;
+    }
+    const int factor = static_cast<int>(pow(10, power));
+    return (static_cast<int>(x) * factor) / factor;
+}
+
+// TODO Make it return a std::string instead of modifying body
+// TODO: move this to ReportPerformance, probably make it a friend function
+// of PerformanceAnalysis
+void PerformanceAnalysis::reportPerformance(String8 *body, int author, log_hash_t hash,
+                                            int maxHeight) {
+    if (mHists.empty()) {
         return;
     }
-    ALOGD("reportPerformance: hists size %d", static_cast<int>(mRecentHists.size()));
-    // TODO: more elaborate data analysis
-    std::map<int, int> buckets;
-    for (const auto &shortHist: mRecentHists) {
+
+    // ms of active audio in displayed histogram
+    double elapsedMs = 0;
+    // starting timestamp of histogram
+    timestamp startingTs = mHists[0].first;
+
+    // histogram which stores .1 precision ms counts instead of Jiffy multiple counts
+    std::map<double, int> buckets;
+    for (const auto &shortHist: mHists) {
         for (const auto &countPair : shortHist.second) {
-            buckets[countPair.first] += countPair.second;
+            const double ms = static_cast<double>(countPair.first) / kJiffyPerMs;
+            buckets[logRound(ms, mBufferPeriod.mMean)] += countPair.second;
+            elapsedMs += ms * countPair.second;
         }
     }
 
     // underscores and spaces length corresponds to maximum width of histogram
-    static const int kLen = 40;
+    static const int kLen = 200;
     std::string underscores(kLen, '_');
     std::string spaces(kLen, ' ');
 
     auto it = buckets.begin();
-    int maxDelta = it->first;
+    double maxDelta = it->first;
     int maxCount = it->second;
     // Compute maximum values
     while (++it != buckets.end()) {
@@ -299,18 +291,23 @@
     }
     int height = log2(maxCount) + 1; // maxCount > 0, safe to call log2
     const int leftPadding = widthOf(1 << height);
-    const int colWidth = std::max(std::max(widthOf(maxDelta) + 1, 3), leftPadding + 2);
+    const int bucketWidth = numberWidth(maxDelta, leftPadding);
     int scalingFactor = 1;
     // scale data if it exceeds maximum height
     if (height > maxHeight) {
         scalingFactor = (height + maxHeight) / maxHeight;
         height /= scalingFactor;
     }
-    body->appendFormat("\n%*s", leftPadding + 11, "Occurrences");
+    body->appendFormat("\n%*s %3.2f %s", leftPadding + 11,
+            "Occurrences in", (elapsedMs / kMsPerSec), "seconds of audio:");
+    body->appendFormat("\n%*s%d, %lld, %lld\n", leftPadding + 11,
+            "Thread, hash, starting timestamp: ", author,
+            static_cast<long long int>(hash), static_cast<long long int>(startingTs));
     // write histogram label line with bucket values
     body->appendFormat("\n%s", " ");
     body->appendFormat("%*s", leftPadding, " ");
     for (auto const &x : buckets) {
+        const int colWidth = numberWidth(x.first, leftPadding);
         body->appendFormat("%*d", colWidth, x.second);
     }
     // write histogram ascii art
@@ -319,54 +316,60 @@
         const int value = 1 << row;
         body->appendFormat("%.*s", leftPadding, spaces.c_str());
         for (auto const &x : buckets) {
-          body->appendFormat("%.*s%s", colWidth - 1, spaces.c_str(), x.second < value ? " " : "|");
+            const int colWidth = numberWidth(x.first, leftPadding);
+            body->appendFormat("%.*s%s", colWidth - 1,
+                               spaces.c_str(), x.second < value ? " " : "|");
         }
         body->appendFormat("\n%s", " ");
     }
     // print x-axis
     const int columns = static_cast<int>(buckets.size());
     body->appendFormat("%*c", leftPadding, ' ');
-    body->appendFormat("%.*s", (columns + 1) * colWidth, underscores.c_str());
+    body->appendFormat("%.*s", (columns + 1) * bucketWidth, underscores.c_str());
     body->appendFormat("\n%s", " ");
 
     // write footer with bucket labels
     body->appendFormat("%*s", leftPadding, " ");
     for (auto const &x : buckets) {
-        body->appendFormat("%*d", colWidth, x.first);
+        const int colWidth = numberWidth(x.first, leftPadding);
+        body->appendFormat("%*.*f", colWidth, 1, x.first);
     }
-    body->appendFormat("%.*s%s", colWidth, spaces.c_str(), "ms\n");
+    body->appendFormat("%.*s%s", bucketWidth, spaces.c_str(), "ms\n");
 
     // Now report glitches
-    body->appendFormat("\ntime elapsed between glitches and glitch timestamps\n");
+    body->appendFormat("\ntime elapsed between glitches and glitch timestamps:\n");
     for (const auto &outlier: mOutlierData) {
         body->appendFormat("%lld: %lld\n", static_cast<long long>(outlier.first),
                            static_cast<long long>(outlier.second));
     }
+}
 
+//------------------------------------------------------------------------------
+
+// writes summary of performance into specified file descriptor
+void dump(int fd, int indent, PerformanceAnalysisMap &threadPerformanceAnalysis) {
+    String8 body;
+    const char* const kDirectory = "/data/misc/audioserver/";
+    for (auto & thread : threadPerformanceAnalysis) {
+        for (auto & hash: thread.second) {
+            PerformanceAnalysis& curr = hash.second;
+            // write performance data to console
+            curr.reportPerformance(&body, thread.first, hash.first);
+            if (!body.isEmpty()) {
+                dumpLine(fd, indent, body);
+                body.clear();
+            }
+            // write to file
+            writeToFile(curr.mHists, curr.mOutlierData, curr.mPeakTimestamps,
+                        kDirectory, false, thread.first, hash.first);
+        }
+    }
 }
 
 
-// Produces a log warning if the timing of recent buffer periods caused a glitch
-// Computes sum of running window of three buffer periods
-// Checks whether the buffer periods leave enough CPU time for the next one
-// e.g. if a buffer period is expected to be 4 ms and a buffer requires 3 ms of CPU time,
-// here are some glitch cases:
-// 4 + 4 + 6 ; 5 + 4 + 5; 2 + 2 + 10
-// TODO: develop this code to track changes in histogram distribution in addition
-// to / instead of glitches.
-void PerformanceAnalysis::alertIfGlitch(const std::vector<int64_t> &samples) {
-    std::deque<int> periods(kNumBuff, kPeriodMs);
-    for (size_t i = 2; i < samples.size(); ++i) { // skip first time entry
-        periods.push_front(deltaMs(samples[i - 1], samples[i]));
-        periods.pop_back();
-        // TODO: check that all glitch cases are covered
-        if (std::accumulate(periods.begin(), periods.end(), 0) > kNumBuff * kPeriodMs +
-            kPeriodMs - kPeriodMsCPU) {
-                ALOGW("A glitch occurred");
-                periods.assign(kNumBuff, kPeriodMs);
-        }
-    }
-    return;
+// Writes a string into specified file descriptor
+void dumpLine(int fd, int indent, const String8 &body) {
+    dprintf(fd, "%.*s%s \n", indent, "", body.string());
 }
 
 } // namespace ReportPerformance
diff --git a/media/libnbaio/ReportPerformance.cpp b/media/libnbaio/ReportPerformance.cpp
index dc50ada..efc1b84 100644
--- a/media/libnbaio/ReportPerformance.cpp
+++ b/media/libnbaio/ReportPerformance.cpp
@@ -23,12 +23,13 @@
 #include <stdint.h>
 #include <stdio.h>
 #include <string.h>
+#include <sstream>
 #include <sys/prctl.h>
+#include <sys/time.h>
 #include <utility>
 #include <media/nbaio/NBLog.h>
 #include <media/nbaio/PerformanceAnalysis.h>
 #include <media/nbaio/ReportPerformance.h>
-// #include <utils/CallStack.h> // used to print callstack
 #include <utils/Log.h>
 #include <utils/String8.h>
 
@@ -36,37 +37,95 @@
 
 namespace ReportPerformance {
 
-// Writes outlier intervals, timestamps, and histograms spanning long time intervals to a file.
-// TODO: format the data efficiently and write different types of data to different files
-void writeToFile(std::deque<std::pair<outlierInterval, timestamp>> &outlierData,
-                                    std::deque<std::pair<timestamp, Histogram>> &hists,
-                                    const char * kName,
-                                    bool append) {
-    ALOGD("writing performance data to file");
-    if (outlierData.empty() || hists.empty()) {
+
+// TODO: use a function like this to extract logic from writeToFile
+// https://stackoverflow.com/a/9279620
+
+// Writes outlier intervals, timestamps, and histograms spanning long time intervals to file.
+// TODO: write data in binary format
+void writeToFile(const std::deque<std::pair<timestamp, Histogram>> &hists,
+                 const std::deque<std::pair<msInterval, timestamp>> &outlierData,
+                 const std::deque<timestamp> &peakTimestamps,
+                 const char * directory, bool append, int author, log_hash_t hash) {
+
+    // TODO: remove old files, implement rotating files as in AudioFlinger.cpp
+
+    if (outlierData.empty() && hists.empty() && peakTimestamps.empty()) {
+        ALOGW("No data, returning.");
         return;
     }
 
-    std::ofstream ofs;
-    ofs.open(kName, append ? std::ios::app : std::ios::trunc);
-    if (!ofs.is_open()) {
-        ALOGW("couldn't open file %s", kName);
+    std::stringstream outlierName;
+    std::stringstream histogramName;
+    std::stringstream peakName;
+
+    // get current time
+    char currTime[16]; //YYYYMMDDHHMMSS + '\0' + one unused
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    struct tm tm;
+    localtime_r(&tv.tv_sec, &tm);
+    strftime(currTime, sizeof(currTime), "%Y%m%d%H%M%S", &tm);
+
+    // generate file names
+    std::stringstream common;
+    common << author << "_" << hash << "_" << currTime << ".csv";
+
+    histogramName << directory << "histograms_" << common.str();
+    outlierName << directory << "outliers_" << common.str();
+    peakName << directory << "peaks_" << common.str();
+
+    std::ofstream hfs;
+    hfs.open(histogramName.str(), append ? std::ios::app : std::ios::trunc);
+    if (!hfs.is_open()) {
+        ALOGW("couldn't open file %s", histogramName.str().c_str());
         return;
     }
-    ofs << "Outlier data: interval and timestamp\n";
-    for (const auto &outlier : outlierData) {
-        ofs << outlier.first << ": " << outlier.second << "\n";
-    }
-    ofs << "Histogram data\n";
-    for (const auto &hist : hists) {
-        ofs << "\ttimestamp\n";
-        ofs << hist.first << "\n";
-        ofs << "\tbuckets and counts\n";
-        for (const auto &bucket : hist.second) {
-            ofs << bucket.first << ": " << bucket.second << "\n";
+    // each histogram is written as a line where the first value is the timestamp and
+    // subsequent values are pairs of buckets and counts. Each value is separated
+    // by a comma, and each histogram is separated by a newline.
+    for (auto hist = hists.begin(); hist != hists.end(); ++hist) {
+        hfs << hist->first << ", ";
+        for (auto bucket = hist->second.begin(); bucket != hist->second.end(); ++bucket) {
+            hfs << bucket->first / static_cast<double>(kJiffyPerMs)
+                << ", " << bucket->second;
+            if (std::next(bucket) != end(hist->second)) {
+                hfs << ", ";
+            }
+        }
+        if (std::next(hist) != end(hists)) {
+            hfs << "\n";
         }
     }
+    hfs.close();
+
+    std::ofstream ofs;
+    ofs.open(outlierName.str(), append ? std::ios::app : std::ios::trunc);
+    if (!ofs.is_open()) {
+        ALOGW("couldn't open file %s", outlierName.str().c_str());
+        return;
+    }
+    // outliers are written as pairs separated by newlines, where each
+    // pair's values are separated by a comma
+    for (const auto &outlier : outlierData) {
+        ofs << outlier.first << ", " << outlier.second << "\n";
+    }
     ofs.close();
+
+    std::ofstream pfs;
+    pfs.open(peakName.str(), append ? std::ios::app : std::ios::trunc);
+    if (!pfs.is_open()) {
+        ALOGW("couldn't open file %s", peakName.str().c_str());
+        return;
+    }
+    // peaks are simply timestamps separated by commas
+    for (auto peak = peakTimestamps.begin(); peak != peakTimestamps.end(); ++peak) {
+        pfs << *peak;
+        if (std::next(peak) != end(peakTimestamps)) {
+            pfs << ", ";
+        }
+    }
+    pfs.close();
 }
 
 } // namespace ReportPerformance
diff --git a/media/libnbaio/include/media/nbaio/NBLog.h b/media/libnbaio/include/media/nbaio/NBLog.h
index 3e48ee1..2c00386 100644
--- a/media/libnbaio/include/media/nbaio/NBLog.h
+++ b/media/libnbaio/include/media/nbaio/NBLog.h
@@ -19,16 +19,18 @@
 #ifndef ANDROID_MEDIA_NBLOG_H
 #define ANDROID_MEDIA_NBLOG_H
 
-#include <binder/IMemory.h>
-#include <audio_utils/fifo.h>
-#include <utils/Mutex.h>
-#include <utils/threads.h>
-
-#include <map>
 #include <deque>
+#include <map>
 #include <set>
 #include <vector>
 
+#include <audio_utils/fifo.h>
+#include <binder/IMemory.h>
+#include <media/nbaio/PerformanceAnalysis.h>
+#include <media/nbaio/ReportPerformance.h>
+#include <utils/Mutex.h>
+#include <utils/threads.h>
+
 namespace android {
 
 class String8;
@@ -37,234 +39,233 @@
 
 public:
 
-typedef uint64_t log_hash_t;
+    using log_hash_t = ReportPerformance::log_hash_t;
 
-// FIXME Everything needed for client (writer API and registration) should be isolated
-//       from the rest of the implementation.
-class Writer;
-class Reader;
+    // FIXME Everything needed for client (writer API and registration) should be isolated
+    //       from the rest of the implementation.
+    class Writer;
+    class Reader;
 
-enum Event : uint8_t {
-    EVENT_RESERVED,
-    EVENT_STRING,               // ASCII string, not NUL-terminated
-    // TODO: make timestamp optional
-    EVENT_TIMESTAMP,            // clock_gettime(CLOCK_MONOTONIC)
-    EVENT_INTEGER,              // integer value entry
-    EVENT_FLOAT,                // floating point value entry
-    EVENT_PID,                  // process ID and process name
-    EVENT_AUTHOR,               // author index (present in merged logs) tracks entry's original log
-    EVENT_START_FMT,            // logFormat start event: entry includes format string, following
-                                // entries contain format arguments
-    EVENT_HASH,                 // unique HASH of log origin, originates from hash of file name
-                                // and line number
-    EVENT_HISTOGRAM_ENTRY_TS,   // single datum for timestamp histogram
-    EVENT_AUDIO_STATE,          // audio on/off event: logged upon FastMixer::onStateChange() call
-    EVENT_END_FMT,              // end of logFormat argument list
+    enum Event : uint8_t {
+        EVENT_RESERVED,
+        EVENT_STRING,               // ASCII string, not NUL-terminated
+                                    // TODO: make timestamp optional
+        EVENT_TIMESTAMP,            // clock_gettime(CLOCK_MONOTONIC)
+        EVENT_INTEGER,              // integer value entry
+        EVENT_FLOAT,                // floating point value entry
+        EVENT_PID,                  // process ID and process name
+        EVENT_AUTHOR,               // author index (present in merged logs) tracks entry's
+                                    // original log
+        EVENT_START_FMT,            // logFormat start event: entry includes format string,
+                                    // following entries contain format arguments
+        EVENT_HASH,                 // unique HASH of log origin, originates from hash of file name
+                                    // and line number
+        EVENT_HISTOGRAM_ENTRY_TS,   // single datum for timestamp histogram
+        EVENT_AUDIO_STATE,          // audio on/off event: logged on FastMixer::onStateChange call
+        EVENT_END_FMT,              // end of logFormat argument list
 
-    EVENT_UPPER_BOUND,          // to check for invalid events
-};
+        EVENT_UPPER_BOUND,          // to check for invalid events
+    };
 
 private:
 
-// ---------------------------------------------------------------------------
-// API for handling format entry operations
+    // ---------------------------------------------------------------------------
+    // API for handling format entry operations
 
-// a formatted entry has the following structure:
-//    * START_FMT entry, containing the format string
-//    * TIMESTAMP entry
-//    * HASH entry
-//    * author entry of the thread that generated it (optional, present in merged log)
-//    * format arg1
-//    * format arg2
-//    * ...
-//    * END_FMT entry
+    // a formatted entry has the following structure:
+    //    * START_FMT entry, containing the format string
+    //    * TIMESTAMP entry
+    //    * HASH entry
+    //    * author entry of the thread that generated it (optional, present in merged log)
+    //    * format arg1
+    //    * format arg2
+    //    * ...
+    //    * END_FMT entry
 
-// entry representation in memory
-struct entry {
-    const uint8_t type;
-    const uint8_t length;
-    const uint8_t data[0];
-};
+    // entry representation in memory
+    struct entry {
+        const uint8_t type;
+        const uint8_t length;
+        const uint8_t data[0];
+    };
 
-// entry tail representation (after data)
-struct ending {
-    uint8_t length;
-    uint8_t next[0];
-};
+    // entry tail representation (after data)
+    struct ending {
+        uint8_t length;
+        uint8_t next[0];
+    };
 
-// entry iterator
-class EntryIterator {
-public:
-    EntryIterator();
-    explicit EntryIterator(const uint8_t *entry);
-    EntryIterator(const EntryIterator &other);
+    // entry iterator
+    class EntryIterator {
+    public:
+        EntryIterator();
+        explicit EntryIterator(const uint8_t *entry);
+        EntryIterator(const EntryIterator &other);
 
-    // dereference underlying entry
-    const entry&    operator*() const;
-    const entry*    operator->() const;
-    // advance to next entry
-    EntryIterator&       operator++(); // ++i
-    // back to previous entry
-    EntryIterator&       operator--(); // --i
-    EntryIterator        next() const;
-    EntryIterator        prev() const;
-    bool            operator!=(const EntryIterator &other) const;
-    int             operator-(const EntryIterator &other) const;
+        // dereference underlying entry
+        const entry&    operator*() const;
+        const entry*    operator->() const;
+        // advance to next entry
+        EntryIterator&       operator++(); // ++i
+        // back to previous entry
+        EntryIterator&       operator--(); // --i
+        EntryIterator        next() const;
+        EntryIterator        prev() const;
+        bool            operator!=(const EntryIterator &other) const;
+        int             operator-(const EntryIterator &other) const;
 
-    bool            hasConsistentLength() const;
-    void            copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const;
-    void            copyData(uint8_t *dst) const;
+        bool            hasConsistentLength() const;
+        void            copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const;
+        void            copyData(uint8_t *dst) const;
 
-    template<typename T>
-    inline const T& payload() {
-        return *reinterpret_cast<const T *>(ptr + offsetof(entry, data));
-    }
+        template<typename T>
+        inline const T& payload() {
+            return *reinterpret_cast<const T *>(ptr + offsetof(entry, data));
+        }
 
-    inline operator const uint8_t*() const {
-        return ptr;
-    }
+        inline operator const uint8_t*() const {
+            return ptr;
+        }
 
-private:
-    const uint8_t  *ptr;
-};
+    private:
+        const uint8_t  *ptr;
+    };
 
-class AbstractEntry {
-public:
+    class AbstractEntry {
+    public:
 
-    // Entry starting in the given pointer
-    explicit AbstractEntry(const uint8_t *entry);
-    virtual ~AbstractEntry() {}
+        // Entry starting in the given pointer
+        explicit AbstractEntry(const uint8_t *entry);
+        virtual ~AbstractEntry() {}
 
-    // build concrete entry of appropriate class from pointer
-    static std::unique_ptr<AbstractEntry> buildEntry(const uint8_t *ptr);
+        // build concrete entry of appropriate class from pointer
+        static std::unique_ptr<AbstractEntry> buildEntry(const uint8_t *ptr);
 
-    // get format entry timestamp
-    // TODO consider changing to uint64_t
-    virtual int64_t      timestamp() const = 0;
+        // get format entry timestamp
+        virtual int64_t      timestamp() const = 0;
 
-    // get format entry's unique id
-    virtual log_hash_t   hash() const = 0;
+        // get format entry's unique id
+        virtual log_hash_t   hash() const = 0;
 
-    // entry's author index (-1 if none present)
-    // a Merger has a vector of Readers, author simply points to the index of the
-    // Reader that originated the entry
-    // TODO consider changing to uint32_t
-    virtual int          author() const = 0;
+        // entry's author index (-1 if none present)
+        // a Merger has a vector of Readers, author simply points to the index of the
+        // Reader that originated the entry
+        // TODO consider changing to uint32_t
+        virtual int          author() const = 0;
 
-    // copy entry, adding author before timestamp, returns iterator to end of entry
-    virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
-                                       int author) const = 0;
+        // copy entry, adding author before timestamp, returns iterator to end of entry
+        virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
+                                                int author) const = 0;
 
-protected:
-    // copies ordinary entry from src to dst, and returns length of entry
-    // size_t      copyEntry(audio_utils_fifo_writer *dst, const iterator &it);
-    const uint8_t  *mEntry;
-};
+    protected:
+        // copies ordinary entry from src to dst, and returns length of entry
+        // size_t      copyEntry(audio_utils_fifo_writer *dst, const iterator &it);
+        const uint8_t  *mEntry;
+    };
 
-class FormatEntry : public AbstractEntry {
-public:
-    // explicit FormatEntry(const EntryIterator &it);
-    explicit FormatEntry(const uint8_t *ptr) : AbstractEntry(ptr) {}
-    virtual ~FormatEntry() {}
+    class FormatEntry : public AbstractEntry {
+    public:
+        // explicit FormatEntry(const EntryIterator &it);
+        explicit FormatEntry(const uint8_t *ptr) : AbstractEntry(ptr) {}
+        virtual ~FormatEntry() {}
 
-    EntryIterator begin() const;
+        EntryIterator begin() const;
 
-    // Entry's format string
-    const   char* formatString() const;
+        // Entry's format string
+        const   char* formatString() const;
 
-    // Enrty's format string length
-            size_t      formatStringLength() const;
+        // Enrty's format string length
+        size_t      formatStringLength() const;
 
-    // Format arguments (excluding format string, timestamp and author)
-            EntryIterator    args() const;
+        // Format arguments (excluding format string, timestamp and author)
+        EntryIterator    args() const;
 
-    // get format entry timestamp
-    virtual int64_t     timestamp() const override;
+        // get format entry timestamp
+        virtual int64_t     timestamp() const override;
 
-    // get format entry's unique id
-    virtual log_hash_t  hash() const override;
+        // get format entry's unique id
+        virtual log_hash_t  hash() const override;
 
-    // entry's author index (-1 if none present)
-    // a Merger has a vector of Readers, author simply points to the index of the
-    // Reader that originated the entry
-    virtual int         author() const override;
+        // entry's author index (-1 if none present)
+        // a Merger has a vector of Readers, author simply points to the index of the
+        // Reader that originated the entry
+        virtual int         author() const override;
 
-    // copy entry, adding author before timestamp, returns size of original entry
-    virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
-                                       int author) const override;
+        // copy entry, adding author before timestamp, returns size of original entry
+        virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
+                                                int author) const override;
 
-};
+    };
 
-class HistogramEntry : public AbstractEntry {
-public:
-    explicit HistogramEntry(const uint8_t *ptr) : AbstractEntry(ptr) {
-    }
-    virtual ~HistogramEntry() {}
+    class HistogramEntry : public AbstractEntry {
+    public:
+        explicit HistogramEntry(const uint8_t *ptr) : AbstractEntry(ptr) {
+        }
+        virtual ~HistogramEntry() {}
 
-    virtual int64_t     timestamp() const override;
+        virtual int64_t     timestamp() const override;
 
-    virtual log_hash_t  hash() const override;
+        virtual log_hash_t  hash() const override;
 
-    virtual int         author() const override;
+        virtual int         author() const override;
 
-    virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
-                                       int author) const override;
+        virtual EntryIterator    copyWithAuthor(std::unique_ptr<audio_utils_fifo_writer> &dst,
+                                                int author) const override;
 
-};
+    };
 
-// ---------------------------------------------------------------------------
+    // ---------------------------------------------------------------------------
 
-// representation of a single log entry in private memory
-struct Entry {
-    Entry(Event event, const void *data, size_t length)
-        : mEvent(event), mLength(length), mData(data) { }
-    /*virtual*/ ~Entry() { }
+    // representation of a single log entry in private memory
+    struct Entry {
+        Entry(Event event, const void *data, size_t length)
+            : mEvent(event), mLength(length), mData(data) { }
+        /*virtual*/ ~Entry() { }
 
-    // used during writing to format Entry information as follows: [type][length][data ... ][length]
-    int     copyEntryDataAt(size_t offset) const;
+        // used during writing to format Entry information as follows:
+        // [type][length][data ... ][length]
+        int     copyEntryDataAt(size_t offset) const;
 
-private:
-    friend class Writer;
-    Event       mEvent;     // event type
-    uint8_t     mLength;    // length of additional data, 0 <= mLength <= kMaxLength
-    const void *mData;      // event type-specific data
-    static const size_t kMaxLength = 255;
-public:
-    // mEvent, mLength, mData[...], duplicate mLength
-    static const size_t kOverhead = sizeof(entry) + sizeof(ending);
-    // endind length of previous entry
-    static const size_t kPreviousLengthOffset = - sizeof(ending) +
-                                                offsetof(ending, length);
-};
+    private:
+        friend class Writer;
+        Event       mEvent;     // event type
+        uint8_t     mLength;    // length of additional data, 0 <= mLength <= kMaxLength
+        const void *mData;      // event type-specific data
+        static const size_t kMaxLength = 255;
+    public:
+        // mEvent, mLength, mData[...], duplicate mLength
+        static const size_t kOverhead = sizeof(entry) + sizeof(ending);
+        // endind length of previous entry
+        static const size_t kPreviousLengthOffset = - sizeof(ending) +
+            offsetof(ending, length);
+    };
 
-struct HistTsEntry {
-    log_hash_t hash;
-    int64_t ts;
-}; //TODO __attribute__((packed));
+    struct HistTsEntry {
+        log_hash_t hash;
+        int64_t ts;
+    }; //TODO __attribute__((packed));
 
-struct HistTsEntryWithAuthor {
-    log_hash_t hash;
-    int64_t ts;
-    int author;
-}; //TODO __attribute__((packed));
+    struct HistTsEntryWithAuthor {
+        log_hash_t hash;
+        int64_t ts;
+        int author;
+    }; //TODO __attribute__((packed));
 
-using StateTsEntryWithAuthor = HistTsEntryWithAuthor;
+    struct HistIntEntry {
+        log_hash_t hash;
+        int value;
+    }; //TODO __attribute__((packed));
 
-struct HistIntEntry {
-    log_hash_t hash;
-    int value;
-}; //TODO __attribute__((packed));
-
-// representation of a single log entry in shared memory
-//  byte[0]             mEvent
-//  byte[1]             mLength
-//  byte[2]             mData[0]
-//  ...
-//  byte[2+i]           mData[i]
-//  ...
-//  byte[2+mLength-1]   mData[mLength-1]
-//  byte[2+mLength]     duplicate copy of mLength to permit reverse scan
-//  byte[3+mLength]     start of next log entry
+    // representation of a single log entry in shared memory
+    //  byte[0]             mEvent
+    //  byte[1]             mLength
+    //  byte[2]             mData[0]
+    //  ...
+    //  byte[2+i]           mData[i]
+    //  ...
+    //  byte[2+mLength-1]   mData[mLength-1]
+    //  byte[2+mLength]     duplicate copy of mLength to permit reverse scan
+    //  byte[3+mLength]     start of next log entry
 
     static void    appendInt(String8 *body, const void *data);
     static void    appendFloat(String8 *body, const void *data);
@@ -275,309 +276,326 @@
     static String8 bufferDump(const EntryIterator &it);
 public:
 
-// Located in shared memory, must be POD.
-// Exactly one process must explicitly call the constructor or use placement new.
-// Since this is a POD, the destructor is empty and unnecessary to call it explicitly.
-struct Shared {
-    Shared() /* mRear initialized via default constructor */ { }
-    /*virtual*/ ~Shared() { }
+    // Located in shared memory, must be POD.
+    // Exactly one process must explicitly call the constructor or use placement new.
+    // Since this is a POD, the destructor is empty and unnecessary to call it explicitly.
+    struct Shared {
+        Shared() /* mRear initialized via default constructor */ { }
+        /*virtual*/ ~Shared() { }
 
-    audio_utils_fifo_index  mRear;  // index one byte past the end of most recent Entry
-    char    mBuffer[0];             // circular buffer for entries
-};
-
-public:
-
-// ---------------------------------------------------------------------------
-
-// FIXME Timeline was intended to wrap Writer and Reader, but isn't actually used yet.
-// For now it is just a namespace for sharedSize().
-class Timeline : public RefBase {
-public:
-#if 0
-    Timeline(size_t size, void *shared = NULL);
-    virtual ~Timeline();
-#endif
-
-    // Input parameter 'size' is the desired size of the timeline in byte units.
-    // Returns the size rounded up to a power-of-2, plus the constant size overhead for indices.
-    static size_t sharedSize(size_t size);
-
-#if 0
-private:
-    friend class    Writer;
-    friend class    Reader;
-
-    const size_t    mSize;      // circular buffer size in bytes, must be a power of 2
-    bool            mOwn;       // whether I own the memory at mShared
-    Shared* const   mShared;    // pointer to shared memory
-#endif
-};
-
-// ---------------------------------------------------------------------------
-
-// Writer is thread-safe with respect to Reader, but not with respect to multiple threads
-// calling Writer methods.  If you need multi-thread safety for writing, use LockedWriter.
-class Writer : public RefBase {
-public:
-    Writer();                   // dummy nop implementation without shared memory
-
-    // Input parameter 'size' is the desired size of the timeline in byte units.
-    // The size of the shared memory must be at least Timeline::sharedSize(size).
-    Writer(void *shared, size_t size);
-    Writer(const sp<IMemory>& iMemory, size_t size);
-
-    virtual ~Writer();
-
-    // FIXME needs comments, and some should be private
-    virtual void    log(const char *string);
-    virtual void    logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
-    virtual void    logvf(const char *fmt, va_list ap);
-    virtual void    logTimestamp();
-    virtual void    logTimestamp(const int64_t ts);
-    virtual void    logInteger(const int x);
-    virtual void    logFloat(const float x);
-    virtual void    logPID();
-    virtual void    logFormat(const char *fmt, log_hash_t hash, ...);
-    virtual void    logVFormat(const char *fmt, log_hash_t hash, va_list ap);
-    virtual void    logStart(const char *fmt);
-    virtual void    logEnd();
-    virtual void    logHash(log_hash_t hash);
-    virtual void    logEventHistTs(Event event, log_hash_t hash);
-
-    virtual bool    isEnabled() const;
-
-    // return value for all of these is the previous isEnabled()
-    virtual bool    setEnabled(bool enabled);   // but won't enable if no shared memory
-            bool    enable()    { return setEnabled(true); }
-            bool    disable()   { return setEnabled(false); }
-
-    sp<IMemory>     getIMemory() const  { return mIMemory; }
-
-private:
-    // 0 <= length <= kMaxLength
-    // writes a single Entry to the FIFO
-    void    log(Event event, const void *data, size_t length);
-    // checks validity of an event before calling log above this one
-    void    log(const Entry *entry, bool trusted = false);
-
-    Shared* const   mShared;    // raw pointer to shared memory
-    sp<IMemory>     mIMemory;   // ref-counted version, initialized in constructor and then const
-    audio_utils_fifo * const mFifo;                 // FIFO itself,
-                                                    // non-NULL unless constructor fails
-    audio_utils_fifo_writer * const mFifoWriter;    // used to write to FIFO,
-                                                    // non-NULL unless dummy constructor used
-    bool            mEnabled;   // whether to actually log
-
-    // cached pid and process name to use in %p format specifier
-    // total tag length is mPidTagSize and process name is not zero terminated
-    char   *mPidTag;
-    size_t  mPidTagSize;
-};
-
-// ---------------------------------------------------------------------------
-
-// Similar to Writer, but safe for multiple threads to call concurrently
-class LockedWriter : public Writer {
-public:
-    LockedWriter();
-    LockedWriter(void *shared, size_t size);
-
-    virtual void    log(const char *string);
-    virtual void    logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
-    virtual void    logvf(const char *fmt, va_list ap);
-    virtual void    logTimestamp();
-    virtual void    logTimestamp(const int64_t ts);
-    virtual void    logInteger(const int x);
-    virtual void    logFloat(const float x);
-    virtual void    logPID();
-    virtual void    logStart(const char *fmt);
-    virtual void    logEnd();
-    virtual void    logHash(log_hash_t hash);
-
-    virtual bool    isEnabled() const;
-    virtual bool    setEnabled(bool enabled);
-
-private:
-    mutable Mutex   mLock;
-};
-
-// ---------------------------------------------------------------------------
-
-class Reader : public RefBase {
-public:
-
-    // A snapshot of a readers buffer
-    // This is raw data. No analysis has been done on it
-    class Snapshot {
-    public:
-        Snapshot() : mData(NULL), mLost(0) {}
-
-        Snapshot(size_t bufferSize) : mData(new uint8_t[bufferSize]) {}
-
-        ~Snapshot() { delete[] mData; }
-
-        // copy of the buffer
-        uint8_t *data() const { return mData; }
-
-        // amount of data lost (given by audio_utils_fifo_reader)
-        size_t   lost() const { return mLost; }
-
-        // iterator to beginning of readable segment of snapshot
-        // data between begin and end has valid entries
-        EntryIterator begin() { return mBegin; }
-
-        // iterator to end of readable segment of snapshot
-        EntryIterator end() { return mEnd; }
-
-    private:
-        friend class Reader;
-        uint8_t              *mData;
-        size_t                mLost;
-        EntryIterator mBegin;
-        EntryIterator mEnd;
+        audio_utils_fifo_index  mRear;  // index one byte past the end of most recent Entry
+        char    mBuffer[0];             // circular buffer for entries
     };
 
-    // Input parameter 'size' is the desired size of the timeline in byte units.
-    // The size of the shared memory must be at least Timeline::sharedSize(size).
-    Reader(const void *shared, size_t size);
-    Reader(const sp<IMemory>& iMemory, size_t size);
-
-    virtual ~Reader();
-
-    // get snapshot of readers fifo buffer, effectively consuming the buffer
-    std::unique_ptr<Snapshot> getSnapshot();
-    // dump a particular snapshot of the reader
-    // TODO: move dump to PerformanceAnalysis. Model/view/controller design
-    void     dump(int fd, size_t indent, Snapshot & snap);
-    // dump the current content of the reader's buffer (call getSnapshot() and previous dump())
-    void     dump(int fd, size_t indent = 0);
-    bool     isIMemory(const sp<IMemory>& iMemory) const;
-
-private:
-
-    static const std::set<Event> startingTypes;
-    static const std::set<Event> endingTypes;
-    /*const*/ Shared* const mShared;    // raw pointer to shared memory, actually const but not
-                                        // declared as const because audio_utils_fifo() constructor
-    sp<IMemory> mIMemory;       // ref-counted version, assigned only in constructor
-    int     mFd;                // file descriptor
-    int     mIndent;            // indentation level
-    audio_utils_fifo * const mFifo;                 // FIFO itself,
-                                                    // non-NULL unless constructor fails
-    audio_utils_fifo_reader * const mFifoReader;    // used to read from FIFO,
-                                                    // non-NULL unless constructor fails
-
-    // TODO: it might be clearer, instead of a direct map from source location to vector of
-    // timestamps, if we instead first mapped from source location to an object that
-    // represented that location. And one_of its fields would be a vector of timestamps.
-    // That would allow us to record other information about the source location beyond timestamps.
-    void    dumpLine(const String8& timestamp, String8& body);
-
-    EntryIterator   handleFormat(const FormatEntry &fmtEntry,
-                                         String8 *timestamp,
-                                         String8 *body);
-    // dummy method for handling absent author entry
-    virtual void handleAuthor(const AbstractEntry& /*fmtEntry*/, String8* /*body*/) {}
-
-    // Searches for the last entry of type <type> in the range [front, back)
-    // back has to be entry-aligned. Returns nullptr if none enconuntered.
-    static const uint8_t *findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
-                                         const std::set<Event> &types);
-
-    static const size_t kSquashTimestamp = 5; // squash this many or more adjacent timestamps
-};
-
-// Wrapper for a reader with a name. Contains a pointer to the reader and a pointer to the name
-class NamedReader {
 public:
-    NamedReader() { mName[0] = '\0'; } // for Vector
-    NamedReader(const sp<NBLog::Reader>& reader, const char *name) :
-        mReader(reader)
-        { strlcpy(mName, name, sizeof(mName)); }
-    ~NamedReader() { }
-    const sp<NBLog::Reader>&  reader() const { return mReader; }
-    const char*               name() const { return mName; }
 
-private:
-    sp<NBLog::Reader>   mReader;
-    static const size_t kMaxName = 32;
-    char                mName[kMaxName];
-};
+    // ---------------------------------------------------------------------------
 
-// ---------------------------------------------------------------------------
+    // FIXME Timeline was intended to wrap Writer and Reader, but isn't actually used yet.
+    // For now it is just a namespace for sharedSize().
+    class Timeline : public RefBase {
+    public:
+#if 0
+        Timeline(size_t size, void *shared = NULL);
+        virtual ~Timeline();
+#endif
 
-class Merger : public RefBase {
-public:
-    Merger(const void *shared, size_t size);
+        // Input parameter 'size' is the desired size of the timeline in byte units.
+        // Returns the size rounded up to a power-of-2, plus the constant size overhead for indices.
+        static size_t sharedSize(size_t size);
 
-    virtual ~Merger() {}
+#if 0
+    private:
+        friend class    Writer;
+        friend class    Reader;
 
-    void addReader(const NamedReader &reader);
-    // TODO add removeReader
-    void merge();
-    // FIXME This is returning a reference to a shared variable that needs a lock
-    const std::vector<NamedReader>& getNamedReaders() const;
-private:
-    // vector of the readers the merger is supposed to merge from.
-    // every reader reads from a writer's buffer
-    // FIXME Needs to be protected by a lock
-    std::vector<NamedReader> mNamedReaders;
+        const size_t    mSize;      // circular buffer size in bytes, must be a power of 2
+        bool            mOwn;       // whether I own the memory at mShared
+        Shared* const   mShared;    // pointer to shared memory
+#endif
+    };
 
-    // TODO Need comments on all of these
-    Shared * const mShared;
-    std::unique_ptr<audio_utils_fifo> mFifo;
-    std::unique_ptr<audio_utils_fifo_writer> mFifoWriter;
-};
+    // ---------------------------------------------------------------------------
 
-class MergeReader : public Reader {
-public:
-    MergeReader(const void *shared, size_t size, Merger &merger);
-private:
-    // FIXME Needs to be protected by a lock,
-    //       because even though our use of it is read-only there may be asynchronous updates
-    const std::vector<NamedReader>& mNamedReaders;
-    // handle author entry by looking up the author's name and appending it to the body
-    // returns number of bytes read from fmtEntry
-    void handleAuthor(const AbstractEntry &fmtEntry, String8 *body);
-};
+    // Writer is thread-safe with respect to Reader, but not with respect to multiple threads
+    // calling Writer methods.  If you need multi-thread safety for writing, use LockedWriter.
+    class Writer : public RefBase {
+    public:
+        Writer();                   // dummy nop implementation without shared memory
 
-// MergeThread is a thread that contains a Merger. It works as a retriggerable one-shot:
-// when triggered, it awakes for a lapse of time, during which it periodically merges; if
-// retriggered, the timeout is reset.
-// The thread is triggered on AudioFlinger binder activity.
-class MergeThread : public Thread {
-public:
-    MergeThread(Merger &merger);
-    virtual ~MergeThread() override;
+        // Input parameter 'size' is the desired size of the timeline in byte units.
+        // The size of the shared memory must be at least Timeline::sharedSize(size).
+        Writer(void *shared, size_t size);
+        Writer(const sp<IMemory>& iMemory, size_t size);
 
-    // Reset timeout and activate thread to merge periodically if it's idle
-    void wakeup();
+        virtual ~Writer();
 
-    // Set timeout period until the merging thread goes idle again
-    void setTimeoutUs(int time);
+        // FIXME needs comments, and some should be private
+        virtual void    log(const char *string);
+        virtual void    logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
+        virtual void    logvf(const char *fmt, va_list ap);
+        virtual void    logTimestamp();
+        virtual void    logTimestamp(const int64_t ts);
+        virtual void    logInteger(const int x);
+        virtual void    logFloat(const float x);
+        virtual void    logPID();
+        virtual void    logFormat(const char *fmt, log_hash_t hash, ...);
+        virtual void    logVFormat(const char *fmt, log_hash_t hash, va_list ap);
+        virtual void    logStart(const char *fmt);
+        virtual void    logEnd();
+        virtual void    logHash(log_hash_t hash);
+        virtual void    logEventHistTs(Event event, log_hash_t hash);
 
-private:
-    virtual bool threadLoop() override;
+        virtual bool    isEnabled() const;
 
-    // the merger who actually does the work of merging the logs
-    Merger&     mMerger;
+        // return value for all of these is the previous isEnabled()
+        virtual bool    setEnabled(bool enabled);   // but won't enable if no shared memory
+        bool    enable()    { return setEnabled(true); }
+        bool    disable()   { return setEnabled(false); }
 
-    // mutex for the condition variable
-    Mutex       mMutex;
+        sp<IMemory>     getIMemory() const  { return mIMemory; }
 
-    // condition variable to activate merging on timeout >= 0
-    Condition   mCond;
+    private:
+        // 0 <= length <= kMaxLength
+        // writes a single Entry to the FIFO
+        void    log(Event event, const void *data, size_t length);
+        // checks validity of an event before calling log above this one
+        void    log(const Entry *entry, bool trusted = false);
 
-    // time left until the thread blocks again (in microseconds)
-    int         mTimeoutUs;
+        Shared* const   mShared;    // raw pointer to shared memory
+        sp<IMemory>     mIMemory;   // ref-counted version, initialized in constructor
+                                    // and then const
+        audio_utils_fifo * const mFifo;                 // FIFO itself, non-NULL
+                                                        // unless constructor fails
+        audio_utils_fifo_writer * const mFifoWriter;    // used to write to FIFO, non-NULL
+                                                        // unless dummy constructor used
+        bool            mEnabled;   // whether to actually log
 
-    // merging period when the thread is awake
-    static const int  kThreadSleepPeriodUs = 1000000 /*1s*/;
+        // cached pid and process name to use in %p format specifier
+        // total tag length is mPidTagSize and process name is not zero terminated
+        char   *mPidTag;
+        size_t  mPidTagSize;
+    };
 
-    // initial timeout value when triggered
-    static const int  kThreadWakeupPeriodUs = 3000000 /*3s*/;
-};
+    // ---------------------------------------------------------------------------
+
+    // Similar to Writer, but safe for multiple threads to call concurrently
+    class LockedWriter : public Writer {
+    public:
+        LockedWriter();
+        LockedWriter(void *shared, size_t size);
+
+        virtual void    log(const char *string);
+        virtual void    logf(const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
+        virtual void    logvf(const char *fmt, va_list ap);
+        virtual void    logTimestamp();
+        virtual void    logTimestamp(const int64_t ts);
+        virtual void    logInteger(const int x);
+        virtual void    logFloat(const float x);
+        virtual void    logPID();
+        virtual void    logStart(const char *fmt);
+        virtual void    logEnd();
+        virtual void    logHash(log_hash_t hash);
+
+        virtual bool    isEnabled() const;
+        virtual bool    setEnabled(bool enabled);
+
+    private:
+        mutable Mutex   mLock;
+    };
+
+    // ---------------------------------------------------------------------------
+
+    class Reader : public RefBase {
+    public:
+        // A snapshot of a readers buffer
+        // This is raw data. No analysis has been done on it
+        class Snapshot {
+        public:
+            Snapshot() : mData(NULL), mLost(0) {}
+
+            Snapshot(size_t bufferSize) : mData(new uint8_t[bufferSize]) {}
+
+            ~Snapshot() { delete[] mData; }
+
+            // copy of the buffer
+            uint8_t *data() const { return mData; }
+
+            // amount of data lost (given by audio_utils_fifo_reader)
+            size_t   lost() const { return mLost; }
+
+            // iterator to beginning of readable segment of snapshot
+            // data between begin and end has valid entries
+            EntryIterator begin() { return mBegin; }
+
+            // iterator to end of readable segment of snapshot
+            EntryIterator end() { return mEnd; }
+
+        private:
+            friend class MergeReader;
+            friend class Reader;
+            uint8_t              *mData;
+            size_t                mLost;
+            EntryIterator mBegin;
+            EntryIterator mEnd;
+        };
+
+        // Input parameter 'size' is the desired size of the timeline in byte units.
+        // The size of the shared memory must be at least Timeline::sharedSize(size).
+        Reader(const void *shared, size_t size);
+        Reader(const sp<IMemory>& iMemory, size_t size);
+
+        virtual ~Reader();
+
+        // get snapshot of readers fifo buffer, effectively consuming the buffer
+        std::unique_ptr<Snapshot> getSnapshot();
+
+        bool     isIMemory(const sp<IMemory>& iMemory) const;
+
+    protected:
+        // print a summary of the performance to the console
+        void    dumpLine(const String8& timestamp, String8& body);
+        EntryIterator   handleFormat(const FormatEntry &fmtEntry,
+                                     String8 *timestamp,
+                                     String8 *body);
+        int mFd;                // file descriptor
+        int mIndent;            // indentation level
+        int mLost;              // bytes of data lost before buffer was read
+
+    private:
+        static const std::set<Event> startingTypes;
+        static const std::set<Event> endingTypes;
+
+        // declared as const because audio_utils_fifo() constructor
+        sp<IMemory> mIMemory;       // ref-counted version, assigned only in constructor
+
+        /*const*/ Shared* const mShared;    // raw pointer to shared memory, actually const but not
+        audio_utils_fifo * const mFifo;                 // FIFO itself,
+        // non-NULL unless constructor fails
+        audio_utils_fifo_reader * const mFifoReader;    // used to read from FIFO,
+        // non-NULL unless constructor fails
+
+        // Searches for the last entry of type <type> in the range [front, back)
+        // back has to be entry-aligned. Returns nullptr if none enconuntered.
+        static const uint8_t *findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
+                                                   const std::set<Event> &types);
+
+        // dummy method for handling absent author entry
+        virtual void handleAuthor(const AbstractEntry& /*fmtEntry*/, String8* /*body*/) {}
+    };
+
+    // Wrapper for a reader with a name. Contains a pointer to the reader and a pointer to the name
+    class NamedReader {
+    public:
+        NamedReader() { mName[0] = '\0'; } // for Vector
+        NamedReader(const sp<NBLog::Reader>& reader, const char *name) :
+            mReader(reader)
+            { strlcpy(mName, name, sizeof(mName)); }
+        ~NamedReader() { }
+        const sp<NBLog::Reader>&  reader() const { return mReader; }
+        const char*               name() const { return mName; }
+
+    private:
+        sp<NBLog::Reader>   mReader;
+        static const size_t kMaxName = 32;
+        char                mName[kMaxName];
+    };
+
+    // ---------------------------------------------------------------------------
+
+    // This class is used to read data from each thread's individual FIFO in shared memory
+    // and write it to a single FIFO in local memory.
+    class Merger : public RefBase {
+    public:
+        Merger(const void *shared, size_t size);
+
+        virtual ~Merger() {}
+
+        void addReader(const NamedReader &reader);
+        // TODO add removeReader
+        void merge();
+
+        // FIXME This is returning a reference to a shared variable that needs a lock
+        const std::vector<NamedReader>& getNamedReaders() const;
+
+    private:
+        // vector of the readers the merger is supposed to merge from.
+        // every reader reads from a writer's buffer
+        // FIXME Needs to be protected by a lock
+        std::vector<NamedReader> mNamedReaders;
+
+        Shared * const mShared; // raw pointer to shared memory
+        std::unique_ptr<audio_utils_fifo> mFifo; // FIFO itself
+        std::unique_ptr<audio_utils_fifo_writer> mFifoWriter; // used to write to FIFO
+    };
+
+    // This class has a pointer to the FIFO in local memory which stores the merged
+    // data collected by NBLog::Merger from all NamedReaders. It is used to process
+    // this data and write the result to PerformanceAnalysis.
+    class MergeReader : public Reader {
+    public:
+        MergeReader(const void *shared, size_t size, Merger &merger);
+
+        void dump(int fd, int indent = 0);
+        // process a particular snapshot of the reader
+        void getAndProcessSnapshot(Snapshot & snap);
+        // call getSnapshot of the content of the reader's buffer and process the data
+        void getAndProcessSnapshot();
+
+    private:
+        // FIXME Needs to be protected by a lock,
+        //       because even though our use of it is read-only there may be asynchronous updates
+        const std::vector<NamedReader>& mNamedReaders;
+
+        // analyzes, compresses and stores the merged data
+        // contains a separate instance for every author (thread), and for every source file
+        // location within each author
+        ReportPerformance::PerformanceAnalysisMap mThreadPerformanceAnalysis;
+
+        // handle author entry by looking up the author's name and appending it to the body
+        // returns number of bytes read from fmtEntry
+        void handleAuthor(const AbstractEntry &fmtEntry, String8 *body);
+    };
+
+    // MergeThread is a thread that contains a Merger. It works as a retriggerable one-shot:
+    // when triggered, it awakes for a lapse of time, during which it periodically merges; if
+    // retriggered, the timeout is reset.
+    // The thread is triggered on AudioFlinger binder activity.
+    class MergeThread : public Thread {
+    public:
+        MergeThread(Merger &merger, MergeReader &mergeReader);
+        virtual ~MergeThread() override;
+
+        // Reset timeout and activate thread to merge periodically if it's idle
+        void wakeup();
+
+        // Set timeout period until the merging thread goes idle again
+        void setTimeoutUs(int time);
+
+    private:
+        virtual bool threadLoop() override;
+
+        // the merger who actually does the work of merging the logs
+        Merger&     mMerger;
+
+        // the mergereader used to process data merged by mMerger
+        MergeReader& mMergeReader;
+
+        // mutex for the condition variable
+        Mutex       mMutex;
+
+        // condition variable to activate merging on timeout >= 0
+        Condition   mCond;
+
+        // time left until the thread blocks again (in microseconds)
+        int         mTimeoutUs;
+
+        // merging period when the thread is awake
+        static const int  kThreadSleepPeriodUs = 1000000 /*1s*/;
+
+        // initial timeout value when triggered
+        static const int  kThreadWakeupPeriodUs = 3000000 /*3s*/;
+    };
 
 };  // class NBLog
 
diff --git a/media/libnbaio/include/media/nbaio/PerformanceAnalysis.h b/media/libnbaio/include/media/nbaio/PerformanceAnalysis.h
index b0dc148..50367be 100644
--- a/media/libnbaio/include/media/nbaio/PerformanceAnalysis.h
+++ b/media/libnbaio/include/media/nbaio/PerformanceAnalysis.h
@@ -14,131 +14,111 @@
  * limitations under the License.
  */
 
-// Non-blocking event logger intended for safe communication between processes via shared memory
-
 #ifndef ANDROID_MEDIA_PERFORMANCEANALYSIS_H
 #define ANDROID_MEDIA_PERFORMANCEANALYSIS_H
 
-#include <map>
 #include <deque>
+#include <map>
 #include <vector>
-#include "NBLog.h"
-#include "ReportPerformance.h"
+
+#include <media/nbaio/ReportPerformance.h>
 
 namespace android {
 
 namespace ReportPerformance {
 
+class PerformanceAnalysis;
+
+// a map of PerformanceAnalysis instances
+// The outer key is for the thread, the inner key for the source file location.
+using PerformanceAnalysisMap = std::map<int, std::map<log_hash_t, PerformanceAnalysis>>;
+
 class PerformanceAnalysis {
     // This class stores and analyzes audio processing wakeup timestamps from NBLog
-    // FIXME: currently, all performance data is stored in deques. Need to add a mutex.
-    // FIXME: continue this way until analysis is done in a separate thread. Then, use
-    // the fifo writer utilities.
+    // FIXME: currently, all performance data is stored in deques. Turn these into circular
+    // buffers.
+    // TODO: add a mutex.
 public:
 
-    PerformanceAnalysis();
+    PerformanceAnalysis() {};
 
-    // Given a series of audio processing wakeup timestamps,
-    // compresses and and analyzes the data, and flushes
-    // the timestamp series from memory.
-    void processAndFlushTimeStampSeries();
+    friend void dump(int fd, int indent,
+                     PerformanceAnalysisMap &threadPerformanceAnalysis);
 
-    // Called when an audio on/off event is read from the buffer,
-    // e.g. EVENT_AUDIO_STATE.
-    // calls flushTimeStampSeries on the data up to the event,
-    // effectively discarding the idle audio time interval
+    // Called in the case of an audio on/off event, e.g., EVENT_AUDIO_STATE.
+    // Used to discard idle time intervals
     void handleStateChange();
 
-    // When the short-term histogram array mRecentHists has reached capacity,
-    // merges histograms for data compression and stores them in mLongTermHists
-    void processAndFlushRecentHists();
-
     // Writes wakeup timestamp entry to log and runs analysis
-    // TODO: make this thread safe. Each thread should have its own instance
-    // of PerformanceAnalysis.
-    void logTsEntry(timestamp_raw ts);
+    void logTsEntry(timestamp ts);
 
     // FIXME: make peakdetector and storeOutlierData a single function
     // Input: mOutlierData. Looks at time elapsed between outliers
     // finds significant changes in the distribution
     // writes timestamps of significant changes to mPeakTimestamps
-    void detectPeaks();
+    bool detectAndStorePeak(msInterval delta, timestamp ts);
 
-    // runs analysis on timestamp series before it is converted to a histogram
-    // finds outliers
+    // stores timestamps of intervals above a threshold: these are assumed outliers.
     // writes to mOutlierData <time elapsed since previous outlier, outlier timestamp>
-    void storeOutlierData(const std::vector<timestamp_raw> &timestamps);
+    bool detectAndStoreOutlier(const msInterval diffMs);
 
-    // input: series of short histograms. Generates a string of analysis of the buffer periods
-    // TODO: WIP write more detailed analysis
+    // Generates a string of analysis of the buffer periods and prints to console
     // FIXME: move this data visualization to a separate class. Model/view/controller
-    void reportPerformance(String8 *body, int maxHeight = 10);
-
-    // TODO: delete this. temp for testing
-    void testFunction();
-
-    // This function used to detect glitches in a time series
-    // TODO incorporate this into the analysis (currently unused)
-    void alertIfGlitch(const std::vector<timestamp_raw> &samples);
+    void reportPerformance(String8 *body, int author, log_hash_t hash,
+                           int maxHeight = 10);
 
 private:
 
-    // stores outlier analysis: <elapsed time between outliers in ms, outlier timestamp>
-    std::deque<std::pair<outlierInterval, timestamp>> mOutlierData;
+    // TODO use a circular buffer for the deques and vectors below
+
+    // stores outlier analysis:
+    // <elapsed time between outliers in ms, outlier beginning timestamp>
+    std::deque<std::pair<msInterval, timestamp>> mOutlierData;
 
     // stores each timestamp at which a peak was detected
     // a peak is a moment at which the average outlier interval changed significantly
     std::deque<timestamp> mPeakTimestamps;
 
-    // TODO: turn these into circular buffers for better data flow
-    // FIFO of small histograms
-    // stores fixed-size short buffer period histograms with timestamp of first sample
-    std::deque<std::pair<timestamp, Histogram>> mRecentHists;
-
-    // FIFO of small histograms
-    // stores fixed-size long-term buffer period histograms with timestamp of first sample
-    std::deque<std::pair<timestamp, Histogram>> mLongTermHists;
-
-    // vector of timestamps, collected from NBLog for a (TODO) specific thread
-    // when a vector reaches its maximum size, the data is processed and flushed
-    std::vector<timestamp_raw> mTimeStampSeries;
-
-    static const int kMsPerSec = 1000;
+    // stores buffer period histograms with timestamp of first sample
+    std::deque<std::pair<timestamp, Histogram>> mHists;
 
     // Parameters used when detecting outliers
-    // TODO: learn some of these from the data, delete unused ones
-    // FIXME: decide whether to make kPeriodMs static.
-    static const int kNumBuff = 3; // number of buffers considered in local history
-    int kPeriodMs; // current period length is ideally 4 ms
-    static const int kOutlierMs = 7; // values greater or equal to this cause glitches
-    // DAC processing time for 4 ms buffer
-    static constexpr double kRatio = 0.75; // estimate of CPU time as ratio of period length
-    int kPeriodMsCPU; // compute based on kPeriodLen and kRatio
-
-    // Peak detection: number of standard deviations from mean considered a significant change
-    static const int kStddevThreshold = 5;
+    struct BufferPeriod {
+        double    mMean = -1;          // average time between audio processing wakeups
+        double    mOutlierFactor = -1; // values > mMean * mOutlierFactor are outliers
+        double    mOutlier = -1;       // this is set to mMean * mOutlierFactor
+        timestamp mPrevTs = -1;        // previous timestamp
+    } mBufferPeriod;
 
     // capacity allocated to data structures
-    // TODO: adjust all of these values
-    static const int kRecentHistsCapacity = 100; // number of short-term histograms stored in memory
-    static const int kShortHistSize = 50; // number of samples in a short-term histogram
-    static const int kOutlierSeriesSize = 100; // number of values stored in outlier array
-    static const int kPeakSeriesSize = 100; // number of values stored in peak array
-    static const int kLongTermHistsCapacity = 20; // number of long-term histogram stored in memory
-    // maximum elapsed time between first and last timestamp of a long-term histogram
-    static const int kMaxHistTimespanMs = 5 * kMsPerSec;
+    struct MaxLength {
+        size_t Hists; // number of histograms stored in memory
+        size_t Outliers; // number of values stored in outlier array
+        size_t Peaks; // number of values stored in peak array
+        int HistTimespanMs; // maximum histogram timespan
+    };
+    // These values allow for 10 hours of data allowing for a glitch and a peak
+    // as often as every 3 seconds
+    static constexpr MaxLength kMaxLength = {.Hists = 60, .Outliers = 12000,
+            .Peaks = 12000, .HistTimespanMs = 10 * kSecPerMin * kMsPerSec };
 
-    // these variables are stored in-class to ensure continuity while analyzing the timestamp
-    // series one short sequence at a time: the variables are not re-initialized every time.
-    // FIXME: create inner class for these variables and decide which other ones to add to it
-    double mPeakDetectorMean = -1;
-    double mPeakDetectorSd = -1;
-    // variables for storeOutlierData
-    uint64_t mElapsed = 0;
-    int64_t mPrevNs = -1;
-
+    // these variables ensure continuity while analyzing the timestamp
+    // series one sample at a time.
+    // TODO: change this to a running variance/mean class
+    struct OutlierDistribution {
+        msInterval mMean = 0;         // sample mean since previous peak
+        msInterval mSd = 0;           // sample sd since previous peak
+        msInterval mElapsed = 0;      // time since previous detected outlier
+        const int  kMaxDeviation = 5; // standard deviations from the mean threshold
+        msInterval mTypicalDiff = 0;  // global mean of outliers
+        double     mN = 0;            // length of sequence since the last peak
+        double     mM2 = 0;           // used to calculate sd
+    } mOutlierDistribution;
 };
 
+void dump(int fd, int indent, PerformanceAnalysisMap &threadPerformanceAnalysis);
+void dumpLine(int fd, int indent, const String8 &body);
+
 } // namespace ReportPerformance
 
 }   // namespace android
diff --git a/media/libnbaio/include/media/nbaio/ReportPerformance.h b/media/libnbaio/include/media/nbaio/ReportPerformance.h
index 27d2810..ec0842f 100644
--- a/media/libnbaio/include/media/nbaio/ReportPerformance.h
+++ b/media/libnbaio/include/media/nbaio/ReportPerformance.h
@@ -23,41 +23,44 @@
 
 namespace android {
 
-// This class is used by reportPerformance function
-// TODO move reportPerformance function to ReportPerformance.cpp
+// The String8 class is used by reportPerformance function
 class String8;
 
 namespace ReportPerformance {
 
-// stores a histogram: key: observed buffer period. value: count
-// TODO: unsigned, unsigned
+constexpr int kMsPerSec = 1000;
+constexpr int kSecPerMin = 60;
+
+constexpr int kJiffyPerMs = 10; // time unit for histogram as a multiple of milliseconds
+
+// stores a histogram: key: observed buffer period (multiple of jiffy). value: count
 using Histogram = std::map<int, int>;
 
-using outlierInterval = uint64_t;
-// int64_t timestamps are converted to uint64_t in PerformanceAnalysis::storeOutlierData,
-// and all analysis functions use uint64_t.
-using timestamp = uint64_t;
-using timestamp_raw = int64_t;
+using msInterval = double;
+using jiffyInterval = double;
 
-// FIXME: decide whether to use 64 or 32 bits
-// TODO: the code has a mix of typedef and using. Standardize to one or the other.
-typedef uint64_t log_hash_t;
+using timestamp = int64_t;
+
+using log_hash_t = uint64_t;
 
 static inline int deltaMs(int64_t ns1, int64_t ns2) {
     return (ns2 - ns1) / (1000 * 1000);
 }
 
+static inline int deltaJiffy(int64_t ns1, int64_t ns2) {
+    return (kJiffyPerMs * (ns2 - ns1)) / (1000 * 1000);
+}
+
 static inline uint32_t log2(uint32_t x) {
     // This works for x > 0
     return 31 - __builtin_clz(x);
 }
 
-// Writes outlier intervals, timestamps, and histograms spanning long time
-// intervals to a file.
-void writeToFile(std::deque<std::pair<outlierInterval, timestamp>> &outlierData,
-                 std::deque<std::pair<timestamp, Histogram>> &hists,
-                 const char * kName,
-                 bool append);
+// Writes outlier intervals, timestamps, peaks timestamps, and histograms to a file.
+void writeToFile(const std::deque<std::pair<timestamp, Histogram>> &hists,
+                 const std::deque<std::pair<msInterval, timestamp>> &outlierData,
+                 const std::deque<timestamp> &peakTimestamps,
+                 const char * kDirectory, bool append, int author, log_hash_t hash);
 
 } // namespace ReportPerformance
 
diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp
index c8d4e4a..9743f37 100644
--- a/media/libstagefright/Android.bp
+++ b/media/libstagefright/Android.bp
@@ -161,6 +161,7 @@
 }
 
 subdirs = [
+    "codec2",
     "codecs/*",
     "colorconversion",
     "filters",
diff --git a/media/libstagefright/MediaClock.cpp b/media/libstagefright/MediaClock.cpp
index 3aa0061..669e09b 100644
--- a/media/libstagefright/MediaClock.cpp
+++ b/media/libstagefright/MediaClock.cpp
@@ -21,7 +21,7 @@
 #include <media/stagefright/MediaClock.h>
 
 #include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/ALooper.h>
+#include <media/stagefright/foundation/AMessage.h>
 
 namespace android {
 
@@ -34,10 +34,41 @@
       mAnchorTimeRealUs(-1),
       mMaxTimeMediaUs(INT64_MAX),
       mStartingTimeMediaUs(-1),
-      mPlaybackRate(1.0) {
+      mPlaybackRate(1.0),
+      mGeneration(0) {
+    mLooper = new ALooper;
+    mLooper->setName("MediaClock");
+    mLooper->start(false /* runOnCallingThread */,
+                   false /* canCallJava */,
+                   ANDROID_PRIORITY_AUDIO);
+}
+
+void MediaClock::init() {
+    mLooper->registerHandler(this);
 }
 
 MediaClock::~MediaClock() {
+    reset();
+    if (mLooper != NULL) {
+        mLooper->unregisterHandler(id());
+        mLooper->stop();
+    }
+}
+
+void MediaClock::reset() {
+    Mutex::Autolock autoLock(mLock);
+    auto it = mTimers.begin();
+    while (it != mTimers.end()) {
+        it->second->setInt32("reason", TIMER_REASON_RESET);
+        it->second->post();
+        it = mTimers.erase(it);
+    }
+    mAnchorTimeMediaUs = -1;
+    mAnchorTimeRealUs = -1;
+    mMaxTimeMediaUs = INT64_MAX;
+    mStartingTimeMediaUs = -1;
+    mPlaybackRate = 1.0;
+    ++mGeneration;
 }
 
 void MediaClock::setStartingTimeMedia(int64_t startingTimeMediaUs) {
@@ -82,6 +113,9 @@
     }
     mAnchorTimeRealUs = nowUs;
     mAnchorTimeMediaUs = nowMediaUs;
+
+    ++mGeneration;
+    processTimers_l();
 }
 
 void MediaClock::updateMaxTimeMedia(int64_t maxTimeMediaUs) {
@@ -105,6 +139,11 @@
     }
     mAnchorTimeRealUs = nowUs;
     mPlaybackRate = rate;
+
+    if (rate > 0.0) {
+        ++mGeneration;
+        processTimers_l();
+    }
 }
 
 float MediaClock::getPlaybackRate() const {
@@ -165,4 +204,64 @@
     return OK;
 }
 
+void MediaClock::addTimer(const sp<AMessage> &notify, int64_t mediaTimeUs) {
+    Mutex::Autolock autoLock(mLock);
+    int64_t nextMediaTimeUs = INT64_MAX;
+    if (!mTimers.empty()) {
+        nextMediaTimeUs = mTimers.begin()->first;
+    }
+
+    mTimers.emplace(mediaTimeUs, notify);
+    if (mediaTimeUs < nextMediaTimeUs) {
+        ++mGeneration;
+        processTimers_l();
+    }
+}
+
+void MediaClock::onMessageReceived(const sp<AMessage> &msg) {
+    switch (msg->what()) {
+        case kWhatTimeIsUp:
+        {
+            int32_t generation;
+            CHECK(msg->findInt32("generation", &generation));
+
+            Mutex::Autolock autoLock(mLock);
+            if (generation != mGeneration) {
+                break;
+            }
+            processTimers_l();
+            break;
+        }
+
+        default:
+            TRESPASS();
+            break;
+    }
+}
+
+void MediaClock::processTimers_l() {
+    int64_t nowMediaTimeUs;
+    status_t status = getMediaTime_l(
+            ALooper::GetNowUs(), &nowMediaTimeUs, false /* allowPastMaxTime */);
+
+    if (status != OK) {
+        return;
+    }
+
+    auto it = mTimers.begin();
+    while (it != mTimers.end() && it->first <= nowMediaTimeUs) {
+        it->second->setInt32("reason", TIMER_REASON_REACHED);
+        it->second->post();
+        it = mTimers.erase(it);
+    }
+
+    if (it == mTimers.end() || mPlaybackRate == 0.0 || mAnchorTimeMediaUs < 0) {
+        return;
+    }
+
+    sp<AMessage> msg = new AMessage(kWhatTimeIsUp, this);
+    msg->setInt32("generation", mGeneration);
+    msg->post((it->first - nowMediaTimeUs) / (double)mPlaybackRate);
+}
+
 }  // namespace android
diff --git a/media/libstagefright/MediaSync.cpp b/media/libstagefright/MediaSync.cpp
index 9278381..ba14e5d 100644
--- a/media/libstagefright/MediaSync.cpp
+++ b/media/libstagefright/MediaSync.cpp
@@ -61,6 +61,7 @@
         mNextBufferItemMediaUs(-1),
         mPlaybackRate(0.0) {
     mMediaClock = new MediaClock;
+    mMediaClock->init();
 
     // initialize settings
     mPlaybackSettings = AUDIO_PLAYBACK_RATE_DEFAULT;
diff --git a/media/libstagefright/codec2/Android.bp b/media/libstagefright/codec2/Android.bp
new file mode 100644
index 0000000..f79e058
--- /dev/null
+++ b/media/libstagefright/codec2/Android.bp
@@ -0,0 +1,32 @@
+cc_library_shared {
+    name: "libstagefright_codec2",
+
+    tags: [
+        "optional",
+    ],
+
+    srcs: ["C2.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/native/include/media/hardware",
+    ],
+
+    sanitize: {
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+        diag: {
+            cfi: true,
+        },
+    },
+
+    ldflags: ["-Wl,-Bsymbolic"],
+}
+
+subdirs = [
+    "tests",
+    "vndk",
+]
diff --git a/media/libstagefright/codec2/Android.mk b/media/libstagefright/codec2/Android.mk
deleted file mode 100644
index ef06ed7..0000000
--- a/media/libstagefright/codec2/Android.mk
+++ /dev/null
@@ -1,21 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-        C2.cpp    \
-
-LOCAL_C_INCLUDES += \
-        $(TOP)/frameworks/av/media/libstagefright/codec2/include \
-        $(TOP)/frameworks/native/include/media/hardware \
-
-LOCAL_MODULE:= libstagefright_codec2
-LOCAL_CFLAGS += -Werror -Wall
-LOCAL_CLANG := true
-LOCAL_SANITIZE := unsigned-integer-overflow signed-integer-overflow cfi
-LOCAL_SANITIZE_DIAG := cfi
-
-include $(BUILD_SHARED_LIBRARY)
-
-################################################################################
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/media/libstagefright/codec2/include/C2Buffer.h b/media/libstagefright/codec2/include/C2Buffer.h
index 9f6b487..88f1db3 100644
--- a/media/libstagefright/codec2/include/C2Buffer.h
+++ b/media/libstagefright/codec2/include/C2Buffer.h
@@ -223,7 +223,11 @@
      *
      * \return acquired object potentially invalidated if waiting for the fence failed.
      */
-    T get();
+    T get() {
+        // TODO:
+        // wait();
+        return mT;
+    }
 
 protected:
     C2Acquirable(C2Error error, C2Fence fence, T t) : C2Fence(fence), mInitialError(error), mT(t) { }
@@ -268,7 +272,7 @@
         : mCapacity(parent == nullptr ? 0 : parent->capacity()) { }
 
 private:
-    const uint32_t mCapacity;
+    uint32_t mCapacity;
 /// @}
 };
 
@@ -429,7 +433,7 @@
     /**
      * \return pointer to the start of the block or nullptr on error.
      */
-    const uint8_t *data();
+    const uint8_t *data() const;
 
     /**
      * Returns a portion of this view.
@@ -447,6 +451,10 @@
      */
     C2Error error();
 
+protected:
+    C2ReadView(const _C2LinearCapacityAspect *parent, const uint8_t *data);
+    explicit C2ReadView(C2Error error);
+
 private:
     class Impl;
     std::shared_ptr<Impl> mImpl;
@@ -476,6 +484,10 @@
      */
     C2Error error();
 
+protected:
+    C2WriteView(const _C2LinearRangeAspect *parent, uint8_t *base);
+    explicit C2WriteView(C2Error error);
+
 private:
     class Impl;
     /// \todo should this be unique_ptr to make this movable only - to avoid inconsistent regions
@@ -516,7 +528,13 @@
      */
     C2Fence fence() const { return mFence; }
 
+protected:
+    C2ConstLinearBlock(std::shared_ptr<C2LinearAllocation> alloc);
+    C2ConstLinearBlock(std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size);
+
 private:
+    class Impl;
+    std::shared_ptr<Impl> mImpl;
     C2Fence mFence;
 };
 
@@ -544,6 +562,14 @@
      *    The block shall be modified only until firing the event for the fence.
      */
     C2ConstLinearBlock share(size_t offset, size_t size, C2Fence fence);
+
+protected:
+    C2LinearBlock(std::shared_ptr<C2LinearAllocation> alloc);
+    C2LinearBlock(std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size);
+
+private:
+    class Impl;
+    std::shared_ptr<Impl> mImpl;
 };
 
 /// @}
diff --git a/media/libstagefright/codec2/include/C2Component.h b/media/libstagefright/codec2/include/C2Component.h
index 1ee9302..f071423 100644
--- a/media/libstagefright/codec2/include/C2Component.h
+++ b/media/libstagefright/codec2/include/C2Component.h
@@ -282,7 +282,7 @@
      * fields in the same list?
      */
     virtual status_t getSupportedValues(
-            const std::vector<const C2ParamField> fields,
+            const std::vector<const C2ParamField> &fields,
             std::vector<C2FieldSupportedValues>* const values) const = 0;
 
     virtual ~C2ComponentInterface() = default;
@@ -543,6 +543,7 @@
 };
 
 class C2ComponentStore {
+public:
     /**
      * Creates a component.
      *
diff --git a/media/libstagefright/codec2/include/C2Config.h b/media/libstagefright/codec2/include/C2Config.h
index 30e9193..18e0a47 100644
--- a/media/libstagefright/codec2/include/C2Config.h
+++ b/media/libstagefright/codec2/include/C2Config.h
@@ -67,6 +67,7 @@
     kParamIndexStructStart = 0x1,
     kParamIndexVideoSize,
     kParamIndexMaxVideoSizeHint,
+    kParamIndexVideoSizeTuning,
 
     kParamIndexParamStart = 0x800,
 };
@@ -230,19 +231,22 @@
     int32_t mWidth;     ///< video width
     int32_t mHeight;    ///< video height
 
-    DEFINE_AND_DESCRIBE_C2STRUCT(VideoSize)
+    DEFINE_C2STRUCT_NO_BASE(VideoSize)
+} C2_PACK;
+
+DESCRIBE_C2STRUCT(VideoSize, {
     C2FIELD(mWidth, "width")
     C2FIELD(mHeight, "height")
-};
+})
 
 // video size for video decoder [OUT]
-typedef C2StreamParam<C2Info, C2VideoSizeStruct> C2VideoSizeStreamInfo;
+typedef C2StreamParam<C2Info, C2VideoSizeStruct, kParamIndexVideoSize> C2VideoSizeStreamInfo;
 
 // max video size for video decoder [IN]
 typedef C2PortParam<C2Setting, C2VideoSizeStruct, kParamIndexMaxVideoSizeHint> C2MaxVideoSizeHintPortSetting;
 
 // video encoder size [IN]
-typedef C2StreamParam<C2Tuning, C2VideoSizeStruct> C2VideoSizeStreamTuning;
+typedef C2StreamParam<C2Tuning, C2VideoSizeStruct, kParamIndexVideoSizeTuning> C2VideoSizeStreamTuning;
 
 /// @}
 
diff --git a/media/libstagefright/codec2/include/C2Param.h b/media/libstagefright/codec2/include/C2Param.h
index fd43061..aab0474 100644
--- a/media/libstagefright/codec2/include/C2Param.h
+++ b/media/libstagefright/codec2/include/C2Param.h
@@ -362,6 +362,17 @@
         return param;
     }
 
+    /// Returns managed clone of |orig| at heap.
+    inline static std::unique_ptr<C2Param> Copy(const C2Param &orig) {
+        if (orig.size() == 0) {
+            return nullptr;
+        }
+        void *mem = ::operator new (orig.size());
+        C2Param *param = new (mem) C2Param(orig.size(), orig._mIndex);
+        param->updateFrom(orig);
+        return std::unique_ptr<C2Param>(param);
+    }
+
 #if 0
     template<typename P, class=decltype(C2Param(P()))>
     P *As() { return P::From(this); }
@@ -661,11 +672,11 @@
     Primitive mValue;
 };
 
-template<> const int32_t &C2Value::Primitive::ref<int32_t>() const { return i32; }
-template<> const int64_t &C2Value::Primitive::ref<int64_t>() const { return i64; }
-template<> const uint32_t &C2Value::Primitive::ref<uint32_t>() const { return u32; }
-template<> const uint64_t &C2Value::Primitive::ref<uint64_t>() const { return u64; }
-template<> const float &C2Value::Primitive::ref<float>() const { return fp; }
+template<> inline const int32_t &C2Value::Primitive::ref<int32_t>() const { return i32; }
+template<> inline const int64_t &C2Value::Primitive::ref<int64_t>() const { return i64; }
+template<> inline const uint32_t &C2Value::Primitive::ref<uint32_t>() const { return u32; }
+template<> inline const uint64_t &C2Value::Primitive::ref<uint64_t>() const { return u64; }
+template<> inline const float &C2Value::Primitive::ref<float>() const { return fp; }
 
 template<> constexpr C2Value::Type C2Value::typeFor<int32_t>() { return INT32; }
 template<> constexpr C2Value::Type C2Value::typeFor<int64_t>() { return INT64; }
diff --git a/media/libstagefright/codec2/tests/Android.bp b/media/libstagefright/codec2/tests/Android.bp
new file mode 100644
index 0000000..fd89690
--- /dev/null
+++ b/media/libstagefright/codec2/tests/Android.bp
@@ -0,0 +1,80 @@
+cc_test {
+    name: "codec2_test",
+
+    tags: [
+        "tests",
+    ],
+
+    srcs: [
+        "vndk/C2BufferTest.cpp",
+        "vndk/C2UtilTest.cpp",
+        "C2_test.cpp",
+        "C2Param_test.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/av/media/libstagefright/codec2/vndk/include",
+        "frameworks/native/include/media/openmax",
+    ],
+
+    shared_libs: [
+        "libcutils",
+        "liblog",
+        "libcutils",
+        "libhidlbase",
+        "libion",
+        "liblog",
+        "libstagefright_codec2",
+        "libutils",
+    ],
+
+    static_libs: [
+        "libstagefright_codec2_vndk",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-std=c++14",
+    ],
+}
+
+cc_test {
+    name: "codec2_interface_test",
+
+    tags: [
+        "tests",
+    ],
+
+    srcs: [
+        "C2ComponentInterface_test.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/av/media/libstagefright/codec2/vndk/include",
+        "frameworks/native/include/media/openmax",
+    ],
+
+    shared_libs: [
+        "libcutils",
+        "liblog",
+        "libcutils",
+        "libhidlbase",
+        "libion",
+        "liblog",
+        "libstagefright_codec2",
+        "libutils",
+    ],
+
+    static_libs: [
+        "libstagefright_codec2_vndk",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-std=c++14",
+    ],
+}
diff --git a/media/libstagefright/codec2/tests/Android.mk b/media/libstagefright/codec2/tests/Android.mk
deleted file mode 100644
index 49c4253..0000000
--- a/media/libstagefright/codec2/tests/Android.mk
+++ /dev/null
@@ -1,37 +0,0 @@
-# Build the unit tests.
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-LOCAL_MODULE := codec2_test
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := \
-	vndk/C2UtilTest.cpp \
-	C2_test.cpp \
-	C2Param_test.cpp \
-
-LOCAL_SHARED_LIBRARIES := \
-	libcutils \
-	libstagefright_codec2 \
-	liblog
-
-LOCAL_C_INCLUDES := \
-	frameworks/av/media/libstagefright/codec2/include \
-	frameworks/av/media/libstagefright/codec2/vndk/include \
-	$(TOP)/frameworks/native/include/media/openmax \
-
-LOCAL_CFLAGS += -Werror -Wall -std=c++14
-LOCAL_CLANG := true
-
-include $(BUILD_NATIVE_TEST)
-
-# Include subdirectory makefiles
-# ============================================================
-
-# If we're building with ONE_SHOT_MAKEFILE (mm, mmm), then what the framework
-# team really wants is to build the stuff defined by this makefile.
-ifeq (,$(ONE_SHOT_MAKEFILE))
-include $(call first-makefiles-under,$(LOCAL_PATH))
-endif
diff --git a/media/libstagefright/codec2/tests/C2ComponentInterface_test.cpp b/media/libstagefright/codec2/tests/C2ComponentInterface_test.cpp
new file mode 100644
index 0000000..0c8ca3e
--- /dev/null
+++ b/media/libstagefright/codec2/tests/C2ComponentInterface_test.cpp
@@ -0,0 +1,708 @@
+/*
+ * Copyright 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "C2ComponentInterface_test"
+
+#include <dlfcn.h>
+#include <stdio.h>
+
+#include <gtest/gtest.h>
+#include <utils/Log.h>
+
+#include <C2Component.h>
+#include <C2Param.h>
+
+#if !defined(UNUSED)
+#define UNUSED(expr)                                                           \
+  do {                                                                         \
+      (void)(expr);                                                            \
+  } while (0)
+
+#endif //!defined(UNUSED)
+
+namespace android {
+
+template <class T> std::unique_ptr<T> alloc_unique_cstr(const char *cstr) {
+    size_t len = strlen(cstr);
+    std::unique_ptr<T> ptr = T::alloc_unique(len);
+    memcpy(ptr->m.mValue, cstr, len);
+    return ptr;
+}
+
+class C2CompIntfTest : public ::testing::Test {
+protected:
+    C2CompIntfTest() {}
+    ~C2CompIntfTest() override {}
+
+    void setComponent(std::shared_ptr<C2ComponentInterface> intf) {
+        mIntf = intf;
+    }
+
+    void resetResults() {
+        mIntf = nullptr;
+        mParamResults.clear();
+    }
+
+    template <typename T> void testUnsupportedParam();
+
+    template <typename T> void testSupportedParam();
+
+    // testReadOnlyParam() and testWritableParam() are the main functions for testing a parameter.
+    // A caller should find out if a tested parameter is read-only or writable before calling them
+    // and it must call one of the corresponded them.
+
+    // If a parameter is read-only this is called.
+    // Test read-only parameter |preParam|. The test expects failure while config() with |newParam|,
+    // and make sure |preParam| stay unchanged.
+    template <typename T>
+    void testReadOnlyParam(const T &preParam, const T &newParam);
+
+    // If a parameter is writable this is called.
+    // Test one filed |writableField| for given writable parameter |param|.
+    // |validValues| contains all values obtained from getSupportedValues() for |writableField|.
+    // The test checks validity for config() with each value, and make sure values are config-ed
+    // by query() them out. |invalidValues| contains some values which are not in |validValues|.
+    // The test expects C2_BAD_VALUE while config() with these values,
+    // and |param| should stay unchanged.
+    template <typename TParam, typename TRealField, typename TField>
+    void testWritableParam(TParam *const param, TRealField *const writableField,
+                           const std::vector<TField> &validValues,
+                           const std::vector<TField> &invalidValues);
+
+    // Test all the defined parameters in C2Param.h.
+    void testMain(std::shared_ptr<C2ComponentInterface> intf,
+                  const std::string &componentName);
+
+    // Check permission of parameter type |T| for testing interface.
+    // This should be called first of the testing per parameter type,
+    // therefore different testing process is applied according to the permission type.
+    template <typename T>
+    void checkParamPermission(
+            int *const writable,
+            const std::vector<std::shared_ptr<C2ParamDescriptor>> &supportedParams);
+
+private:
+    enum ParamPermission : int {
+        WRITABLE,
+        READONLY,
+        UNSUPPORTED,
+    };
+
+    struct paramTestInfo {
+        std::string name;
+        int result;
+        paramTestInfo(const char *name_, int result_)
+            : name(name_), result(result_) {}
+    };
+
+    // queryOnStack() and queryonHeap() both call an interface's query_nb() and
+    // check if a component has a parameter whose type is |T|.
+    // If a component has, the value should be copied into an argument, that is
+    // |p| in queryOnStack() and |heapParams| in queryOnHeap().
+    // The return value is status_t (e.g. C2_OK).
+    template <typename T> status_t queryOnStack(T *const p);
+
+    template <typename T>
+    status_t queryOnHeap(const T &p,
+                         std::vector<std::unique_ptr<C2Param>> *const heapParams);
+
+    // Get a value whose type is |T| in a component. The value is copied to |param|.
+    // This should be called only if a component has the parameter.
+    template <typename T> void getValue(T *const param);
+
+    // Check if the parameter's value in component is equal to |expected| and
+    // queryOnStack() and queryOnHeap() are succeeded. When this function called,
+    // it should be guaranteed a component has the parameter.
+    template <typename T> void queryParamAsExpected(const T &expected);
+
+    // Test if query functions works correctly for supported parameters.
+    // "Support" means here a component has the parameter.
+    template <typename T> void querySupportedParam();
+
+    // Test query functions works correctly for unsupported parameters.
+    // "Unsupport" means here a component doesn't have the parameter.
+    template <typename T> void queryUnsupportedParam();
+
+    // Execute an interface's config_nb(). |T| is a single parameter type, not std::vector.
+    // config() creates std::vector<C2Param *const> {p} and passes it to config_nb().
+    template <typename T>
+    status_t
+    config(T *const p,
+           std::vector<std::unique_ptr<C2SettingResult>> *const failures);
+
+    // Test if config works correctly for read-only parameters.
+    // Because the failure of config() is assumed, |newParam| doesn't matter.
+    template <typename T> void configReadOnlyParam(const T &newParam);
+
+    // Test if config works correctly for writable parameters.
+    // This changes the parameter's value to |newParam|.
+    // |stConfig| is a return value of config().
+    template <typename T> void configWritableParamValidValue(const T &newParam, status_t *stConfig);
+
+    // Test if config works correctly in the case an invalid value |newParam| is tried to write
+    // to an writable parameter.
+    template <typename T> void configWritableParamInvalidValue(const T &newParam);
+
+    // Create values for testing from |validValueInfos|. The values are returned as arguments.
+    // |validValues| : valid values, which can be written for the parameter.
+    // |InvalidValues| : invalid values, which cannot be written for the parameter.
+    //                   config() should be failed if these values are used as new values.
+    // This function should be called only for writable and supported parameters.
+    template <typename TField>
+    void getTestValues(const std::vector<C2FieldSupportedValues> &validValueInfos,
+                       std::vector<TField> *const validValues,
+                       std::vector<TField> *const invalidValues);
+
+    // Output the summary of test results. Categorizes parameters with their configuration.
+    void outputResults(const std::string &name);
+
+    std::shared_ptr<C2ComponentInterface> mIntf;
+    std::vector<paramTestInfo> mParamResults;
+    std::string mCurrentParamName;
+};
+
+// factory function
+// TODO(hiroh): Add factory functions for other types.
+template <typename T> std::unique_ptr<T> makeParam() {
+    return std::make_unique<T>();
+}
+
+template <> std::unique_ptr<C2PortMimeConfig::input> makeParam() {
+    // TODO(hiroh): Set more precise length.
+    return C2PortMimeConfig::input::alloc_unique(100);
+}
+
+#define TRACED_FAILURE(func)                            \
+    do {                                                \
+        SCOPED_TRACE(mCurrentParamName);             \
+        func;                                           \
+        if (::testing::Test::HasFatalFailure()) {       \
+            return;                                     \
+        }                                               \
+    } while (false)
+
+template <typename T> status_t C2CompIntfTest::queryOnStack(T *const p) {
+    std::vector<C2Param *const> stackParams{p};
+    return mIntf->query_nb(stackParams, {}, nullptr);
+}
+
+template <typename T>
+status_t C2CompIntfTest::queryOnHeap(
+        const T &p, std::vector<std::unique_ptr<C2Param>> *const heapParams) {
+    uint32_t index = p.type();
+    if (p.forStream()) {
+        index |= ((p.stream() << 17) & 0x01FE0000) | 0x02000000;
+    }
+    return mIntf->query_nb({}, {index}, heapParams);
+}
+
+template <typename T> void C2CompIntfTest::getValue(T *const param) {
+    // When getValue() is called, a component has to have the parameter.
+    ASSERT_EQ(C2_OK, queryOnStack(param));
+}
+
+template <typename T>
+void C2CompIntfTest::queryParamAsExpected(const T &expected) {
+    // TODO(hiroh): Don't create param on stack and call queryOnStack for flex params.
+    // Note that all the current supported parameters are non-flex params.
+    T stack;
+    std::unique_ptr<T> pHeap = makeParam<T>();
+    std::vector<std::unique_ptr<C2Param>> heapParams;
+
+    ASSERT_EQ(C2_OK, queryOnStack(&stack));
+
+    // |stack| is a parameter value. The parameter size shouldn't be 0.
+    EXPECT_NE(0u, stack.size());
+    EXPECT_EQ(stack, expected);
+
+    ASSERT_EQ(C2_OK, queryOnHeap(*pHeap, &heapParams));
+
+    // |*heapParams[0]| is a parameter value. The size of |heapParams| has to be one.
+    ASSERT_EQ(1u, heapParams.size());
+    EXPECT_TRUE(heapParams[0]);
+    EXPECT_EQ(*heapParams[0], expected);
+}
+
+template <typename T> void C2CompIntfTest::querySupportedParam() {
+    std::unique_ptr<T> param = makeParam<T>();
+    // The current parameter's value is acquired by getValue(), which should be succeeded.
+    getValue(param.get());
+    queryParamAsExpected(*param);
+}
+
+template <typename T> void C2CompIntfTest::queryUnsupportedParam() {
+    // TODO(hiroh): Don't create param on stack and call queryOnStack for flex params.
+    // Note that all the current supported parameters are non-flex params.
+    T stack;
+    std::unique_ptr<T> pHeap = makeParam<T>();
+    std::vector<std::unique_ptr<C2Param>> heapParams;
+    // If a component doesn't have the parameter, queryOnStack() and queryOnHeap()
+    // should return C2_BAD_INDEX.
+    ASSERT_EQ(C2_BAD_INDEX, queryOnStack(&stack));
+    EXPECT_FALSE(stack);
+    ASSERT_EQ(C2_BAD_INDEX, queryOnHeap(*pHeap, &heapParams));
+    EXPECT_EQ(0u, heapParams.size());
+}
+
+template <typename T>
+status_t C2CompIntfTest::config(
+        T *const p, std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
+    std::vector<C2Param *const> params{p};
+    return mIntf->config_nb(params, failures);
+}
+
+// Create a new parameter copied from |p|.
+template <typename T> std::unique_ptr<T> makeParamFrom(const T &p) {
+    std::unique_ptr<T> retP = makeParam<T>();
+    EXPECT_TRUE(retP->updateFrom(p));
+    EXPECT_TRUE(memcmp(retP.get(), &p, sizeof(T)) == 0);
+    return retP;
+}
+
+template <typename T>
+void C2CompIntfTest::configReadOnlyParam(const T &newParam) {
+    std::unique_ptr<T> p = makeParamFrom(newParam);
+
+    std::vector<C2Param *const> params{p.get()};
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+
+    // config_nb should be failed because a parameter is read-only.
+    ASSERT_EQ(C2_BAD_VALUE, mIntf->config_nb(params, &failures));
+    ASSERT_EQ(1u, failures.size());
+    EXPECT_EQ(C2SettingResult::READ_ONLY, failures[0]->failure);
+}
+
+template <typename T>
+void C2CompIntfTest::configWritableParamValidValue(const T &newParam, status_t *configResult) {
+    std::unique_ptr<T> p = makeParamFrom(newParam);
+
+    std::vector<C2Param *const> params{p.get()};
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+    // In most cases, config_nb return C2_OK and the parameter's value should be changed
+    // to |newParam|, which is confirmed in a caller of configWritableParamValueValue().
+    // However, this can return ~~~~ and the parameter's values is not changed,
+    // because there may be dependent limitations between fields or between parameters.
+    // TODO(hiroh): I have to fill the return value. Comments in C2Component.h doesn't mention
+    // about the return value when conflict happens. I set C2_BAD_VALUE to it temporarily now.
+    status_t stConfig = mIntf->config_nb(params, &failures);
+    if (stConfig == C2_OK) {
+        EXPECT_EQ(0u, failures.size());
+    } else {
+        ASSERT_EQ(C2_BAD_VALUE, stConfig);
+        EXPECT_EQ(1u, failures.size());
+        EXPECT_EQ(C2SettingResult::CONFLICT, failures[0]->failure);
+    }
+    *configResult = stConfig;
+}
+
+template <typename T>
+void C2CompIntfTest::configWritableParamInvalidValue(const T &newParam) {
+    std::unique_ptr<T> p = makeParamFrom(newParam);
+
+    std::vector<C2Param *const> params{p.get()};
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+    // Although a parameter is writable, config_nb should be failed,
+    // because a new value is invalid.
+    ASSERT_EQ(C2_BAD_VALUE, mIntf->config_nb(params, &failures));
+    ASSERT_EQ(1u, failures.size());
+    EXPECT_EQ(C2SettingResult::BAD_VALUE, failures[0]->failure);
+}
+
+// There is only used enum type for the field type, that is C2DomainKind.
+// If another field type is added, it is necessary to add function for that.
+template <>
+void C2CompIntfTest::getTestValues(
+        const std::vector<C2FieldSupportedValues> &validValueInfos,
+        std::vector<C2DomainKind> *const validValues,
+        std::vector<C2DomainKind> *const invalidValues) {
+    UNUSED(validValueInfos);
+    validValues->emplace_back(C2DomainVideo);
+    validValues->emplace_back(C2DomainAudio);
+    validValues->emplace_back(C2DomainOther);
+
+    // There is no invalid value.
+    UNUSED(invalidValues);
+}
+
+template <typename TField>
+void C2CompIntfTest::getTestValues(
+        const std::vector<C2FieldSupportedValues> &validValueInfos,
+        std::vector<TField> *const validValues,
+        std::vector<TField> *const invalidValues) {
+
+    // The supported values are represented by C2Values. C2Value::Primitive needs to
+    // be transformed to a primitive value. This function is one to do that.
+    auto prim2Value = [](const C2Value::Primitive &prim) -> TField {
+        if (std::is_same<TField, int32_t>::value) {
+            return prim.i32;
+        } else if (std::is_same<TField, uint32_t>::value) {
+            return prim.u32;
+        } else if (std::is_same<TField, int64_t>::value) {
+            return prim.i64;
+        } else if (std::is_same<TField, uint64_t>::value) {
+            return prim.u64;
+        } else if (std::is_same<TField, float>::value) {
+            return prim.fp;
+        }
+        static_assert(std::is_same<TField, int32_t>::value ||
+                      std::is_same<TField, uint32_t>::value ||
+                      std::is_same<TField, int64_t>::value ||
+                      std::is_same<TField, uint64_t>::value ||
+                      std::is_same<TField, float>::value, "Invalid TField type.");
+        return 0;
+    };
+
+    // The size of validValueInfos is one.
+    const auto &c2FSV = validValueInfos[0];
+
+    switch (c2FSV.type) {
+    case C2FieldSupportedValues::Type::RANGE: {
+        const auto &range = c2FSV.range;
+        auto rmin = prim2Value(range.min);
+        auto rmax = prim2Value(range.max);
+        auto rstep = prim2Value(range.step);
+
+        ASSERT_LE(rmin, rmax);
+
+        if (rstep != 0) {
+            // Increase linear
+            for (auto v = rmin; v <= rmax; v += rstep) {
+                validValues->emplace_back(v);
+            }
+            if (rmin > std::numeric_limits<TField>::min()) {
+                invalidValues->emplace_back(rmin - 1);
+            }
+            if (rmax < std::numeric_limits<TField>::max()) {
+                invalidValues->emplace_back(rmax + 1);
+            }
+            const unsigned int N = validValues->size();
+            if (N >= 2) {
+                if (std::is_same<TField, float>::value) {
+                    invalidValues->emplace_back((validValues->at(0) + validValues->at(1)) / 2);
+                    invalidValues->emplace_back((validValues->at(N - 2) + validValues->at(N - 1)) / 2);
+                } else {
+                    if (rstep > 1) {
+                        invalidValues->emplace_back(validValues->at(0) + 1);
+                        invalidValues->emplace_back(validValues->at(N - 1) - 1);
+                    }
+                }
+            }
+        } else {
+            // There should be two cases, except linear case.
+            // 1. integer geometric case
+            // 2. float geometric case
+
+            auto nom = prim2Value(range.nom);
+            auto denom = prim2Value(range.denom);
+
+            // If both range.nom and range.denom are 1 and step is 0, we should use
+            // VALUES, shouldn't we?
+            ASSERT_FALSE(nom == 1 && denom == 1);
+
+            // (nom / denom) is not less than 1.
+            ASSERT_FALSE(denom == 0);
+            ASSERT_LE(denom, nom);
+            for (auto v = rmin; v <= rmax; v = v * nom / denom) {
+                validValues->emplace_back(v);
+            }
+
+            if (rmin > std::numeric_limits<TField>::min()) {
+                invalidValues->emplace_back(rmin - 1);
+            }
+            if (rmax < std::numeric_limits<TField>::max()) {
+                invalidValues->emplace_back(rmax + 1);
+            }
+
+            const unsigned int N = validValues->size();
+            if (N >= 2) {
+                if (std::is_same<TField, float>::value) {
+                    invalidValues->emplace_back((validValues->at(0) + validValues->at(1)) / 2);
+                    invalidValues->emplace_back((validValues->at(N - 2) + validValues->at(N - 1)) / 2);
+                } else {
+                    if (validValues->at(1) - validValues->at(0) > 1) {
+                        invalidValues->emplace_back(validValues->at(0) + 1);
+                    }
+                    if (validValues->at(N - 1) - validValues->at(N - 2) > 1) {
+                        invalidValues->emplace_back(validValues->at(N - 1) - 1);
+                    }
+                }
+            }
+        }
+        break;
+    }
+    case C2FieldSupportedValues::Type::VALUES: {
+        for (const C2Value::Primitive &prim : c2FSV.values) {
+            validValues->emplace_back(prim2Value(prim));
+        }
+        auto minv = *std::min_element(validValues->begin(), validValues->end());
+        auto maxv = *std::max_element(validValues->begin(), validValues->end());
+        if (minv - 1 > std::numeric_limits<TField>::min()) {
+            invalidValues->emplace_back(minv - 1);
+        }
+        if (maxv + 1 < std::numeric_limits<TField>::max()) {
+            invalidValues->emplace_back(maxv + 1);
+        }
+        break;
+    }
+    case C2FieldSupportedValues::Type::FLAGS: {
+        // TODO(hiroh) : Implement the case that param.type is FLAGS.
+        break;
+    }
+    }
+}
+
+template <typename T>
+void C2CompIntfTest::testReadOnlyParam(const T &preParam, const T &newParam) {
+    TRACED_FAILURE(configReadOnlyParam(newParam));
+    // Parameter value must not be changed
+    TRACED_FAILURE(queryParamAsExpected(preParam));
+}
+
+template <typename TParam, typename TRealField, typename TField>
+void C2CompIntfTest::testWritableParam(
+        TParam *const param, TRealField *const writableField,
+        const std::vector<TField> &validValues,
+        const std::vector<TField> &invalidValues) {
+    status_t stConfig;
+
+    // Get the parameter's value in the beginning in order to reset the value at the end.
+    TRACED_FAILURE(getValue(param));
+    std::unique_ptr<TParam> defaultParam = makeParamFrom(*param);
+
+    // Test valid values
+    for (const auto &val : validValues) {
+        std::unique_ptr<TParam> preParam = makeParamFrom(*param);
+
+        // Param is try to be changed
+        *writableField = val;
+        TRACED_FAILURE(configWritableParamValidValue(*param, &stConfig));
+        if (stConfig == C2_OK) {
+            TRACED_FAILURE(queryParamAsExpected(*param));
+        } else {
+            // Param is unchanged because a field value conflicts with other field or parameter.
+            TRACED_FAILURE(queryParamAsExpected(*preParam));
+        }
+    }
+
+    // Store the current parameter in order to test |param| is unchanged
+    // after trying to write an invalid value.
+    std::unique_ptr<TParam> lastValidParam = makeParamFrom(*param);
+
+    // Test invalid values
+    for (const auto &val : invalidValues) {
+        // Param is changed
+        *writableField = val;
+        TRACED_FAILURE(configWritableParamInvalidValue(*param));
+        TRACED_FAILURE(queryParamAsExpected(*lastValidParam));
+    }
+    // Reset the parameter by config().
+    TRACED_FAILURE(configWritableParamValidValue(*defaultParam, &stConfig));
+}
+
+template <typename T> void C2CompIntfTest::testUnsupportedParam() {
+    TRACED_FAILURE(queryUnsupportedParam<T>());
+}
+
+template <typename T> void C2CompIntfTest::testSupportedParam() {
+    TRACED_FAILURE(querySupportedParam<T>());
+}
+
+bool isSupportedParam(
+        const C2Param &param,
+        const std::vector<std::shared_ptr<C2ParamDescriptor>> &sParams) {
+    for (const auto &pd : sParams) {
+        if (param.type() == pd->type().type()) {
+            return true;
+        }
+    }
+    return false;
+}
+
+template <typename T>
+void C2CompIntfTest::checkParamPermission(
+    int *const result,
+    const std::vector<std::shared_ptr<C2ParamDescriptor>> &supportedParams) {
+    std::unique_ptr<T> param = makeParam<T>();
+
+    if (!isSupportedParam(*param, supportedParams)) {
+        // If a parameter isn't supported, it just finish after calling testUnsupportedParam().
+        testUnsupportedParam<T>();
+        *result = ParamPermission::UNSUPPORTED;
+        return;
+    }
+
+    testSupportedParam<T>();
+
+    TRACED_FAILURE(getValue(param.get()));
+    std::vector<std::unique_ptr<C2SettingResult>> failures;
+    // Config does not change the parameter, because param is the present param.
+    // This config is executed to find out if a parameter is read-only or writable.
+    status_t stStack = config(param.get(), &failures);
+    if (stStack == C2_BAD_VALUE) {
+        // Read-only
+        std::unique_ptr<T> newParam = makeParam<T>();
+        testReadOnlyParam(*param, *newParam);
+        *result = ParamPermission::READONLY;
+    } else {
+        // Writable
+        EXPECT_EQ(stStack, C2_OK);
+        *result = ParamPermission::WRITABLE;
+    }
+}
+
+void C2CompIntfTest::outputResults(const std::string &name) {
+    std::vector<std::string> params[3];
+    for (const auto &testInfo : mParamResults) {
+        int result = testInfo.result;
+        ASSERT_TRUE(0 <= result && result <= 2);
+        params[result].emplace_back(testInfo.name);
+    }
+    const char *resultString[] = {"Writable", "Read-Only", "Unsupported"};
+    printf("\n----TEST RESULTS (%s)----\n\n", name.c_str());
+    for (int i = 0; i < 3; i++) {
+        printf("[ %s ]\n", resultString[i]);
+        for (const auto &t : params[i]) {
+            printf("%s\n", t.c_str());
+        }
+        printf("\n");
+    }
+}
+
+#define TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, field_name_) \
+    do {                                                                \
+        std::unique_ptr<TParam_> param = makeParam<TParam_>();          \
+        std::vector<C2FieldSupportedValues> validValueInfos;            \
+        ASSERT_EQ(C2_OK,                                                \
+                  mIntf->getSupportedValues(                            \
+                          {C2ParamField(param.get(), &field_type_name_::field_name_)}, \
+                          &validValueInfos));                           \
+        ASSERT_EQ(1u, validValueInfos.size());                          \
+        std::vector<decltype(param->field_name_)> validValues;          \
+        std::vector<decltype(param->field_name_)> invalidValues;        \
+        getTestValues(validValueInfos, &validValues, &invalidValues);   \
+        testWritableParam(param.get(), &param->field_name_, validValues,\
+                          invalidValues);                               \
+    } while (0)
+
+#define TEST_VSSTRUCT_WRITABLE_FIELD(TParam_, field_type_name_)         \
+    do {                                                                \
+        TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, mWidth); \
+        TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, mHeight);\
+    } while (0)
+
+#define TEST_U32_WRITABLE_FIELD(TParam_, field_type_name_)              \
+  TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, mValue)
+
+#define TEST_ENUM_WRITABLE_FIELD(TParam_, field_type_name_)             \
+  TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, mValue)
+
+// TODO(hiroh): Support parameters based on char[] and uint32_t[].
+//#define TEST_STRING_WRITABLE_FIELD(TParam_, field_type_name_)
+// TEST_GENERAL_WRITABLE_FIELD(TParam_, field_type_name_, m.mValue)
+//#define TEST_U32ARRAY_WRITABLE_FIELD(Tparam_, field_type_name_)
+// TEST_GENERAL_WRITABLE_FIELD(Tparam_, uint32_t[], field_type_name_, mValues)
+
+#define EACH_TEST(TParam_, field_type_name_, test_name)                 \
+    do {                                                                \
+      int result = 0;                                                   \
+      this->mCurrentParamName = #TParam_;                            \
+      checkParamPermission<TParam_>(&result, supportedParams);          \
+      if (result == ParamPermission::WRITABLE) {                        \
+          test_name(TParam_, field_type_name_);                         \
+      }                                                                 \
+      mParamResults.emplace_back(#TParam_, result);                      \
+  } while (0)
+
+#define EACH_TEST_SELF(type_, test_name) EACH_TEST(type_, type_, test_name)
+#define EACH_TEST_INPUT(type_, test_name) EACH_TEST(type_::input, type_, test_name)
+#define EACH_TEST_OUTPUT(type_, test_name) EACH_TEST(type_::output, type_, test_name)
+void C2CompIntfTest::testMain(std::shared_ptr<C2ComponentInterface> intf,
+                              const std::string &componentName) {
+    setComponent(intf);
+
+    std::vector<std::shared_ptr<C2ParamDescriptor>> supportedParams;
+    ASSERT_EQ(C2_OK, mIntf->getSupportedParams(&supportedParams));
+
+    EACH_TEST_SELF(C2ComponentLatencyInfo, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_SELF(C2ComponentTemporalInfo, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2PortLatencyInfo, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2PortLatencyInfo, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2StreamFormatConfig, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2StreamFormatConfig, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2PortStreamCountConfig, TEST_U32_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2PortStreamCountConfig, TEST_U32_WRITABLE_FIELD);
+
+    EACH_TEST_SELF(C2ComponentDomainInfo, TEST_ENUM_WRITABLE_FIELD);
+
+    // TODO(hiroh): Support parameters based on uint32_t[] and char[].
+    // EACH_TEST_INPUT(C2PortMimeConfig, TEST_STRING_WRITABLE_FIELD);
+    // EACH_TEST_OUTPUT(C2PortMimeConfig, TEST_STRING_WRITABLE_FIELD);
+    // EACH_TEST_INPUT(C2StreamMimeConfig, TEST_STRING_WRITABLE_FIELD);
+    // EACH_TEST_OUTPUT(C2StreamMimeConfig, TEST_STRING_WRITABLE_FIELD);
+
+    // EACH_TEST_SELF(C2SupportedParamsInfo, TEST_U32ARRAY_WRITABLE_FIELD);
+    // EACH_TEST_SELF(C2RequiredParamsInfo, TEST_U32ARRAY_WRITABLE_FIELD);
+    // EACH_TEST_SELF(C2ReadOnlyParamsInfo, TEST_U32ARRAY_WRITABLE_FIELD);
+    // EACH_TEST_SELF(C2RequestedInfosInfo, TEST_U32ARRAY_WRITABLE_FIELD);
+
+    EACH_TEST_INPUT(C2VideoSizeStreamInfo, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2VideoSizeStreamInfo, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2VideoSizeStreamTuning, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2VideoSizeStreamTuning, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_INPUT(C2MaxVideoSizeHintPortSetting, TEST_VSSTRUCT_WRITABLE_FIELD);
+    EACH_TEST_OUTPUT(C2MaxVideoSizeHintPortSetting, TEST_VSSTRUCT_WRITABLE_FIELD);
+
+    outputResults(componentName);
+    resetResults();
+}
+
+TEST_F(C2CompIntfTest, C2V4L2CodecIntf) {
+
+    // Read a shared object library.
+    void* compLib = dlopen("system/lib/libv4l2_codec2.so", RTLD_NOW);
+
+    if (!compLib) {
+        printf("Cannot open library: %s.\n", dlerror());
+        FAIL();
+        return;
+    }
+
+    typedef C2ComponentStore* create_t();
+    create_t* create_store= (create_t*) dlsym(compLib, "create_store");
+    const char* dlsym_error = dlerror();
+    if (dlsym_error) {
+        printf("Cannot load symbol create: %s.\n", dlsym_error);
+        FAIL();
+        return;
+    }
+
+    typedef void destroy_t(C2ComponentStore*);
+    destroy_t* destroy_store = (destroy_t*) dlsym(compLib, "destroy_store");
+    dlsym_error = dlerror();
+    if (dlsym_error) {
+        printf("Cannot load symbol destroy: %s.\n", dlsym_error);
+        FAIL();
+        return;
+    }
+
+    std::shared_ptr<C2ComponentStore> componentStore(create_store(), destroy_store);
+    std::shared_ptr<C2ComponentInterface> componentIntf;
+    componentStore->createInterface("v4l2.decoder", &componentIntf);
+    auto componentName = "C2V4L2Codec";
+    testMain(componentIntf, componentName);
+}
+
+} // namespace android
diff --git a/media/libstagefright/codec2/tests/C2Param_test.cpp b/media/libstagefright/codec2/tests/C2Param_test.cpp
index ec82c84..9165aad 100644
--- a/media/libstagefright/codec2/tests/C2Param_test.cpp
+++ b/media/libstagefright/codec2/tests/C2Param_test.cpp
@@ -968,6 +968,10 @@
         EXPECT_EQ(C2NumberStreamTuning::From(&tun), nullptr);
         EXPECT_EQ(C2NumberStreamTuning::input::From(&tun), nullptr);
         EXPECT_EQ(C2NumberStreamTuning::output::From(&tun), nullptr);
+
+        EXPECT_EQ(*(C2Param::Copy(btun)), btun);
+        btun.invalidate();
+        EXPECT_FALSE(C2Param::Copy(btun));
     }
 
     const C2NumberPortTuning outp1(true, 100), inp1(false, 100);
@@ -1171,6 +1175,11 @@
         EXPECT_EQ(C2NumberStreamTuning::output::From(&inp2), nullptr);
         EXPECT_EQ(C2NumberStreamTuning::output::From(&outp1), nullptr);
         EXPECT_EQ(C2NumberStreamTuning::output::From(&outp2), nullptr);
+
+        EXPECT_EQ(*(C2Param::Copy(inp1)), inp1);
+        EXPECT_EQ(*(C2Param::Copy(inp2)), inp2);
+        EXPECT_EQ(*(C2Param::Copy(outp1)), outp1);
+        EXPECT_EQ(*(C2Param::Copy(outp2)), outp2);
     }
 
     const C2NumberStreamTuning outs1(true, 1u, 100), ins1(false, 1u, 100);
@@ -1383,6 +1392,10 @@
         EXPECT_EQ(C2NumberStreamTuning::output::From(&outs1), (C2NumberStreamTuning::output*)&outs1);
         EXPECT_EQ(C2NumberStreamTuning::output::From(&outs2), &outs2);
 
+        EXPECT_EQ(*(C2Param::Copy(ins1)), ins1);
+        EXPECT_EQ(*(C2Param::Copy(ins2)), ins2);
+        EXPECT_EQ(*(C2Param::Copy(outs1)), outs1);
+        EXPECT_EQ(*(C2Param::Copy(outs2)), outs2);
     }
 
     {
@@ -1518,6 +1531,8 @@
         EXPECT_EQ(C2NumbersStreamTuning::From(tun.get()), nullptr);
         EXPECT_EQ(C2NumbersStreamTuning::input::From(tun.get()), nullptr);
         EXPECT_EQ(C2NumbersStreamTuning::output::From(tun.get()), nullptr);
+
+        EXPECT_EQ(*(C2Param::Copy(*tun)), *tun);
     }
 
     std::unique_ptr<C2NumbersPortTuning> outp1_(C2NumbersPortTuning::alloc_unique(1, true)),
@@ -1739,6 +1754,10 @@
         EXPECT_EQ(C2NumbersStreamTuning::output::From(outp1.get()), nullptr);
         EXPECT_EQ(C2NumbersStreamTuning::output::From(outp2.get()), nullptr);
 
+        EXPECT_EQ(*(C2Param::Copy(*inp1)), *inp1);
+        EXPECT_EQ(*(C2Param::Copy(*inp2)), *inp2);
+        EXPECT_EQ(*(C2Param::Copy(*outp1)), *outp1);
+        EXPECT_EQ(*(C2Param::Copy(*outp2)), *outp2);
     }
 
     std::unique_ptr<C2NumbersStreamTuning> outs1_(C2NumbersStreamTuning::alloc_unique(1, true, 1u));
@@ -1968,6 +1987,10 @@
         EXPECT_EQ(C2NumbersStreamTuning::output::From(outs1.get()), (C2NumbersStreamTuning::output*)outs1.get());
         EXPECT_EQ(C2NumbersStreamTuning::output::From(outs2.get()), outs2.get());
 
+        EXPECT_EQ(*(C2Param::Copy(*ins1)), *ins1);
+        EXPECT_EQ(*(C2Param::Copy(*ins2)), *ins2);
+        EXPECT_EQ(*(C2Param::Copy(*outs1)), *outs1);
+        EXPECT_EQ(*(C2Param::Copy(*outs2)), *outs2);
     }
 
     {
@@ -2262,7 +2285,7 @@
         for (const C2Param::Index index : heapParamIndices) {
             if (mMyParams.count(index)) {
                 C2Param & myParam = mMyParams.find(index)->second;
-                std::unique_ptr<C2Param> paramCopy(C2Param::From(&myParam, myParam.size()));
+                std::unique_ptr<C2Param> paramCopy(C2Param::Copy(myParam));
                 heapParams->push_back(std::move(paramCopy));
             }
         }
@@ -2303,7 +2326,7 @@
     };
 
     virtual status_t getSupportedValues(
-            const std::vector<const C2ParamField> fields,
+            const std::vector<const C2ParamField> &fields,
             std::vector<C2FieldSupportedValues>* const values) const {
         for (const C2ParamField &field : fields) {
             if (field == C2ParamField(&mDomainInfo, &C2ComponentDomainInfo::mValue)) {
diff --git a/media/libstagefright/codec2/tests/vndk/C2BufferTest.cpp b/media/libstagefright/codec2/tests/vndk/C2BufferTest.cpp
new file mode 100644
index 0000000..0ba3cad
--- /dev/null
+++ b/media/libstagefright/codec2/tests/vndk/C2BufferTest.cpp
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <C2Buffer.h>
+#include <C2BufferPriv.h>
+
+#include <system/graphics.h>
+
+namespace android {
+
+class C2BufferTest : public ::testing::Test {
+public:
+    C2BufferTest()
+        : mAllocator(std::make_shared<C2AllocatorIon>()),
+          mSize(0u),
+          mAddr(nullptr) {
+    }
+
+    ~C2BufferTest() = default;
+
+    void allocate(size_t capacity) {
+        C2Error err = mAllocator->allocateLinearBuffer(
+                capacity,
+                { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                &mAllocation);
+        if (err != C2_OK) {
+            mAllocation.reset();
+            FAIL() << "C2Allocator::allocateLinearBuffer() failed: " << err;
+        }
+    }
+
+    void map(size_t offset, size_t size, uint8_t **addr) {
+        ASSERT_TRUE(mAllocation);
+        C2Error err = mAllocation->map(
+                offset,
+                size,
+                { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                // TODO: fence
+                nullptr,
+                &mAddr);
+        if (err != C2_OK) {
+            mAddr = nullptr;
+            FAIL() << "C2LinearAllocation::map() failed: " << err;
+        }
+        ASSERT_NE(nullptr, mAddr);
+        mSize = size;
+        *addr = (uint8_t *)mAddr;
+    }
+
+    void unmap() {
+        ASSERT_TRUE(mAllocation);
+        ASSERT_NE(nullptr, mAddr);
+        ASSERT_NE(0u, mSize);
+
+        // TODO: fence
+        ASSERT_EQ(C2_OK, mAllocation->unmap(mAddr, mSize, nullptr));
+        mSize = 0u;
+        mAddr = nullptr;
+    }
+
+    std::shared_ptr<C2BlockAllocator> makeBlockAllocator() {
+        return std::make_shared<C2DefaultBlockAllocator>(mAllocator);
+    }
+
+private:
+    std::shared_ptr<C2Allocator> mAllocator;
+    std::shared_ptr<C2LinearAllocation> mAllocation;
+    size_t mSize;
+    void *mAddr;
+};
+
+TEST_F(C2BufferTest, LinearAllocationTest) {
+    constexpr size_t kCapacity = 1024u * 1024u;
+
+    allocate(kCapacity);
+
+    uint8_t *addr = nullptr;
+    map(0u, kCapacity, &addr);
+    ASSERT_NE(nullptr, addr);
+
+    for (size_t i = 0; i < kCapacity; ++i) {
+        addr[i] = i % 100u;
+    }
+
+    unmap();
+    addr = nullptr;
+
+    map(kCapacity / 3, kCapacity / 3, &addr);
+    ASSERT_NE(nullptr, addr);
+    for (size_t i = 0; i < kCapacity / 3; ++i) {
+        ASSERT_EQ((i + kCapacity / 3) % 100, addr[i]) << " at i = " << i;
+    }
+}
+
+TEST_F(C2BufferTest, BlockAllocatorTest) {
+    constexpr size_t kCapacity = 1024u * 1024u;
+
+    std::shared_ptr<C2BlockAllocator> blockAllocator(makeBlockAllocator());
+
+    std::shared_ptr<C2LinearBlock> block;
+    ASSERT_EQ(C2_OK, blockAllocator->allocateLinearBlock(
+            kCapacity,
+            { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+            &block));
+    ASSERT_TRUE(block);
+
+    C2Acquirable<C2WriteView> writeViewHolder = block->map();
+    C2WriteView writeView = writeViewHolder.get();
+    ASSERT_EQ(C2_OK, writeView.error());
+    ASSERT_EQ(kCapacity, writeView.capacity());
+    ASSERT_EQ(0u, writeView.offset());
+    ASSERT_EQ(kCapacity, writeView.size());
+
+    uint8_t *data = writeView.data();
+    ASSERT_NE(nullptr, data);
+    for (size_t i = 0; i < writeView.size(); ++i) {
+        data[i] = i % 100u;
+    }
+
+    C2Fence fence;
+    C2ConstLinearBlock constBlock = block->share(
+            kCapacity / 3, kCapacity / 3, fence);
+
+    C2Acquirable<C2ReadView> readViewHolder = constBlock.map();
+    C2ReadView readView = readViewHolder.get();
+    ASSERT_EQ(C2_OK, readView.error());
+    ASSERT_EQ(kCapacity / 3, readView.capacity());
+
+    // TODO: fence
+    const uint8_t *constData = readView.data();
+    ASSERT_NE(nullptr, constData);
+    for (size_t i = 0; i < readView.capacity(); ++i) {
+        ASSERT_EQ((i + kCapacity / 3) % 100u, constData[i]) << " at i = " << i
+                << "; data = " << static_cast<void *>(data)
+                << "; constData = " << static_cast<const void *>(constData);
+    }
+
+    readView = readView.subView(333u, 100u);
+    ASSERT_EQ(C2_OK, readView.error());
+    ASSERT_EQ(100u, readView.capacity());
+
+    constData = readView.data();
+    ASSERT_NE(nullptr, constData);
+    for (size_t i = 0; i < readView.capacity(); ++i) {
+        ASSERT_EQ((i + 333u + kCapacity / 3) % 100u, constData[i]) << " at i = " << i;
+    }
+}
+
+} // namespace android
diff --git a/media/libstagefright/codec2/vndk/Android.bp b/media/libstagefright/codec2/vndk/Android.bp
new file mode 100644
index 0000000..9426b4e
--- /dev/null
+++ b/media/libstagefright/codec2/vndk/Android.bp
@@ -0,0 +1,30 @@
+cc_library_static {
+    name: "libstagefright_codec2_vndk",
+
+    srcs: ["C2Buffer.cpp"],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright/codec2/include",
+        "frameworks/av/media/libstagefright/codec2/vndk/include",
+        "frameworks/native/include/media/hardware",
+    ],
+
+    shared_libs: [
+        "libbinder",
+        "libcutils",
+        "libdl",
+        "libhardware",
+        "libhidlbase",
+        "libion",
+        "liblog",
+        "libmedia",
+        "libstagefright_foundation",
+        "libutils",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-std=c++14",
+    ],
+}
diff --git a/media/libstagefright/codec2/vndk/C2Buffer.cpp b/media/libstagefright/codec2/vndk/C2Buffer.cpp
new file mode 100644
index 0000000..ffb6c2e
--- /dev/null
+++ b/media/libstagefright/codec2/vndk/C2Buffer.cpp
@@ -0,0 +1,720 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "C2Buffer"
+#include <utils/Log.h>
+
+#include <C2BufferPriv.h>
+
+#include <ion/ion.h>
+#include <sys/mman.h>
+
+namespace android {
+
+// standard ERRNO mappings
+template<int N> constexpr C2Error _c2_errno2error_impl();
+template<> constexpr C2Error _c2_errno2error_impl<0>()       { return C2_OK; }
+template<> constexpr C2Error _c2_errno2error_impl<EINVAL>()  { return C2_BAD_VALUE; }
+template<> constexpr C2Error _c2_errno2error_impl<EACCES>()  { return C2_NO_PERMISSION; }
+template<> constexpr C2Error _c2_errno2error_impl<EPERM>()   { return C2_NO_PERMISSION; }
+template<> constexpr C2Error _c2_errno2error_impl<ENOMEM>()  { return C2_NO_MEMORY; }
+
+// map standard errno-s to the equivalent C2Error
+template<int... N> struct _c2_map_errno_impl;
+template<int E, int ... N> struct _c2_map_errno_impl<E, N...> {
+    static C2Error map(int result) {
+        if (result == E) {
+            return _c2_errno2error_impl<E>();
+        } else {
+            return _c2_map_errno_impl<N...>::map(result);
+        }
+    }
+};
+template<> struct _c2_map_errno_impl<> {
+    static C2Error map(int result) {
+        return result == 0 ? C2_OK : C2_CORRUPTED;
+    }
+};
+
+template<int... N>
+C2Error c2_map_errno(int result) {
+    return _c2_map_errno_impl<N...>::map(result);
+}
+
+namespace {
+
+// Inherit from the parent, share with the friend.
+
+class DummyCapacityAspect : public _C2LinearCapacityAspect {
+    using _C2LinearCapacityAspect::_C2LinearCapacityAspect;
+    friend class ::android::C2ReadView;
+    friend class ::android::C2ConstLinearBlock;
+};
+
+class C2DefaultReadView : public C2ReadView {
+    using C2ReadView::C2ReadView;
+    friend class ::android::C2ConstLinearBlock;
+};
+
+class C2DefaultWriteView : public C2WriteView {
+    using C2WriteView::C2WriteView;
+    friend class ::android::C2LinearBlock;
+};
+
+class C2AcquirableReadView : public C2Acquirable<C2ReadView> {
+    using C2Acquirable::C2Acquirable;
+    friend class ::android::C2ConstLinearBlock;
+};
+
+class C2AcquirableWriteView : public C2Acquirable<C2WriteView> {
+    using C2Acquirable::C2Acquirable;
+    friend class ::android::C2LinearBlock;
+};
+
+class C2DefaultConstLinearBlock : public C2ConstLinearBlock {
+    using C2ConstLinearBlock::C2ConstLinearBlock;
+    friend class ::android::C2LinearBlock;
+};
+
+class C2DefaultLinearBlock : public C2LinearBlock {
+    using C2LinearBlock::C2LinearBlock;
+    friend class ::android::C2DefaultBlockAllocator;
+};
+
+}  // namespace
+
+/* ======================================= ION ALLOCATION ====================================== */
+
+/**
+ * ION handle
+ */
+struct C2HandleIon : public C2Handle {
+    C2HandleIon(int ionFd, ion_user_handle_t buffer) : C2Handle(cHeader),
+          mFds{ ionFd, buffer },
+          mInts{ kMagic } { }
+
+    static bool isValid(const C2Handle * const o);
+
+    int ionFd() const { return mFds.mIon; }
+    ion_user_handle_t buffer() const { return mFds.mBuffer; }
+
+    void setBuffer(ion_user_handle_t bufferFd) { mFds.mBuffer = bufferFd; }
+
+protected:
+    struct {
+        int mIon;
+        int mBuffer; // ion_user_handle_t
+    } mFds;
+    struct {
+        int mMagic;
+    } mInts;
+
+private:
+    typedef C2HandleIon _type;
+    enum {
+        kMagic = 'ion1',
+        numFds = sizeof(mFds) / sizeof(int),
+        numInts = sizeof(mInts) / sizeof(int),
+        version = sizeof(C2Handle) + sizeof(mFds) + sizeof(mInts)
+    };
+    //constexpr static C2Handle cHeader = { version, numFds, numInts, {} };
+    const static C2Handle cHeader;
+};
+
+const C2Handle C2HandleIon::cHeader = {
+    C2HandleIon::version,
+    C2HandleIon::numFds,
+    C2HandleIon::numInts,
+    {}
+};
+
+// static
+bool C2HandleIon::isValid(const C2Handle * const o) {
+    if (!o || memcmp(o, &cHeader, sizeof(cHeader))) {
+        return false;
+    }
+    const C2HandleIon *other = static_cast<const C2HandleIon*>(o);
+    return other->mInts.mMagic == kMagic;
+}
+
+// TODO: is the dup of an ion fd identical to ion_share?
+
+class C2AllocationIon : public C2LinearAllocation {
+public:
+    virtual C2Error map(
+        size_t offset, size_t size, C2MemoryUsage usage, int *fence,
+        void **addr /* nonnull */);
+    virtual C2Error unmap(void *addr, size_t size, int *fenceFd);
+    virtual bool isValid() const;
+    virtual ~C2AllocationIon();
+    virtual const C2Handle *handle() const;
+    virtual bool equals(const std::shared_ptr<C2LinearAllocation> &other) const;
+
+    // internal methods
+    C2AllocationIon(int ionFd, size_t size, size_t align, unsigned heapMask, unsigned flags);
+    C2AllocationIon(int ionFd, size_t size, int shareFd);
+    int dup() const;
+    C2Error status() const;
+
+protected:
+    class Impl;
+    Impl *mImpl;
+};
+
+class C2AllocationIon::Impl {
+public:
+    // NOTE: using constructor here instead of a factory method as we will need the
+    // error value and this simplifies the error handling by the wrapper.
+    Impl(int ionFd, size_t capacity, size_t align, unsigned heapMask, unsigned flags)
+        : mInit(C2_OK),
+          mHandle(ionFd, -1),
+          mMapFd(-1),
+          mCapacity(capacity) {
+        ion_user_handle_t buffer = -1;
+        int ret = ion_alloc(mHandle.ionFd(), mCapacity, align, heapMask, flags, &buffer);
+        if (ret == 0) {
+            mHandle.setBuffer(buffer);
+        } else {
+            mInit = c2_map_errno<ENOMEM, EACCES, EINVAL>(-ret);
+        }
+    }
+
+    Impl(int ionFd, size_t capacity, int shareFd)
+        : mHandle(ionFd, -1),
+          mMapFd(-1),
+          mCapacity(capacity) {
+        ion_user_handle_t buffer;
+        mInit = ion_import(mHandle.ionFd(), shareFd, &buffer);
+        if (mInit == 0) {
+            mHandle.setBuffer(buffer);
+        }
+        (void)mCapacity; // TODO
+    }
+
+    C2Error map(size_t offset, size_t size, C2MemoryUsage usage, int *fenceFd, void **addr) {
+        (void)fenceFd; // TODO: wait for fence
+        *addr = nullptr;
+        int prot = PROT_NONE;
+        int flags = MAP_PRIVATE;
+        if (usage.mConsumer & GRALLOC_USAGE_SW_READ_MASK) {
+            prot |= PROT_READ;
+        }
+        if (usage.mProducer & GRALLOC_USAGE_SW_WRITE_MASK) {
+            prot |= PROT_WRITE;
+            flags = MAP_SHARED;
+        }
+
+        size_t alignmentBytes = offset % PAGE_SIZE;
+        size_t mapOffset = offset - alignmentBytes;
+        size_t mapSize = size + alignmentBytes;
+
+        C2Error err = C2_OK;
+        if (mMapFd == -1) {
+            int ret = ion_map(mHandle.ionFd(), mHandle.buffer(), mapSize, prot,
+                              flags, mapOffset, (unsigned char**)&mMapAddr, &mMapFd);
+            if (ret) {
+                mMapFd = -1;
+                *addr = nullptr;
+                err = c2_map_errno<EINVAL>(-ret);
+            } else {
+                *addr = (uint8_t *)mMapAddr + alignmentBytes;
+                mMapAlignmentBytes = alignmentBytes;
+                mMapSize = mapSize;
+            }
+        } else {
+            mMapAddr = mmap(nullptr, mapSize, prot, flags, mMapFd, mapOffset);
+            if (mMapAddr == MAP_FAILED) {
+                mMapAddr = *addr = nullptr;
+                err = c2_map_errno<EINVAL>(errno);
+            } else {
+                *addr = (uint8_t *)mMapAddr + alignmentBytes;
+                mMapAlignmentBytes = alignmentBytes;
+                mMapSize = mapSize;
+            }
+        }
+        return err;
+    }
+
+    C2Error unmap(void *addr, size_t size, int *fenceFd) {
+        if (addr != (uint8_t *)mMapAddr + mMapAlignmentBytes ||
+                size + mMapAlignmentBytes != mMapSize) {
+            return C2_BAD_VALUE;
+        }
+        int err = munmap(mMapAddr, mMapSize);
+        if (err != 0) {
+            return c2_map_errno<EINVAL>(errno);
+        }
+        if (fenceFd) {
+            *fenceFd = -1;
+        }
+        return C2_OK;
+    }
+
+    ~Impl() {
+        if (mMapFd != -1) {
+            close(mMapFd);
+            mMapFd = -1;
+        }
+
+        (void)ion_free(mHandle.ionFd(), mHandle.buffer());
+    }
+
+    C2Error status() const {
+        return mInit;
+    }
+
+    const C2Handle * handle() const {
+        return &mHandle;
+    }
+
+    int dup() const {
+        int fd = -1;
+        if (mInit != 0 || ion_share(mHandle.ionFd(), mHandle.buffer(), &fd) != 0) {
+            fd = -1;
+        }
+        return fd;
+    }
+
+private:
+    C2Error mInit;
+    C2HandleIon mHandle;
+    int mMapFd; // only one for now
+    void *mMapAddr;
+    size_t mMapAlignmentBytes;
+    size_t mMapSize;
+    size_t mCapacity;
+};
+
+C2Error C2AllocationIon::map(
+    size_t offset, size_t size, C2MemoryUsage usage, int *fenceFd, void **addr) {
+    return mImpl->map(offset, size, usage, fenceFd, addr);
+}
+
+C2Error C2AllocationIon::unmap(void *addr, size_t size, int *fenceFd) {
+    return mImpl->unmap(addr, size, fenceFd);
+}
+
+bool C2AllocationIon::isValid() const {
+    return mImpl->status() == C2_OK;
+}
+
+C2Error C2AllocationIon::status() const {
+    return mImpl->status();
+}
+
+bool C2AllocationIon::equals(const std::shared_ptr<C2LinearAllocation> &other) const {
+    return other != nullptr &&
+        other->handle(); // TODO
+}
+
+const C2Handle *C2AllocationIon::handle() const {
+    return mImpl->handle();
+}
+
+C2AllocationIon::~C2AllocationIon() {
+    delete mImpl;
+}
+
+C2AllocationIon::C2AllocationIon(int ionFd, size_t size, size_t align, unsigned heapMask, unsigned flags)
+    : C2LinearAllocation(size),
+      mImpl(new Impl(ionFd, size, align, heapMask, flags)) { }
+
+C2AllocationIon::C2AllocationIon(int ionFd, size_t size, int shareFd)
+    : C2LinearAllocation(size),
+      mImpl(new Impl(ionFd, size, shareFd)) { }
+
+int C2AllocationIon::dup() const {
+    return mImpl->dup();
+}
+
+/* ======================================= ION ALLOCATOR ====================================== */
+
+C2AllocatorIon::C2AllocatorIon() : mInit(C2_OK), mIonFd(ion_open()) {
+    if (mIonFd < 0) {
+        switch (errno) {
+        case ENOENT:    mInit = C2_UNSUPPORTED; break;
+        default:        mInit = c2_map_errno<EACCES>(errno); break;
+        }
+    }
+}
+
+C2AllocatorIon::~C2AllocatorIon() {
+    if (mInit == C2_OK) {
+        ion_close(mIonFd);
+    }
+}
+
+/**
+ * Allocates a 1D allocation of given |capacity| and |usage|. If successful, the allocation is
+ * stored in |allocation|. Otherwise, |allocation| is set to 'nullptr'.
+ *
+ * \param capacity        the size of requested allocation (the allocation could be slightly
+ *                      larger, e.g. to account for any system-required alignment)
+ * \param usage           the memory usage info for the requested allocation. \note that the
+ *                      returned allocation may be later used/mapped with different usage.
+ *                      The allocator should layout the buffer to be optimized for this usage,
+ *                      but must support any usage. One exception: protected buffers can
+ *                      only be used in a protected scenario.
+ * \param allocation      pointer to where the allocation shall be stored on success. nullptr
+ *                      will be stored here on failure
+ *
+ * \retval C2_OK        the allocation was successful
+ * \retval C2_NO_MEMORY not enough memory to complete the allocation
+ * \retval C2_TIMED_OUT the allocation timed out
+ * \retval C2_NO_PERMISSION     no permission to complete the allocation
+ * \retval C2_BAD_VALUE capacity or usage are not supported (invalid) (caller error)
+ * \retval C2_UNSUPPORTED       this allocator does not support 1D allocations
+ * \retval C2_CORRUPTED some unknown, unrecoverable error occured during allocation (unexpected)
+ */
+C2Error C2AllocatorIon::allocateLinearBuffer(
+        uint32_t capacity, C2MemoryUsage usage, std::shared_ptr<C2LinearAllocation> *allocation) {
+    *allocation = nullptr;
+    if (mInit != C2_OK) {
+        return C2_UNSUPPORTED;
+    }
+
+    // get align, heapMask and flags
+    //size_t align = 1;
+    size_t align = 0;
+    unsigned heapMask = ~0;
+    unsigned flags = 0;
+    //TODO
+    (void) usage;
+#if 0
+    int err = mUsageMapper(usage, capacity, &align, &heapMask, &flags);
+    if (err < 0) {
+        return c2_map_errno<EINVAL, ENOMEM, EACCES>(-err);
+    }
+#endif
+
+    std::shared_ptr<C2AllocationIon> alloc
+        = std::make_shared<C2AllocationIon>(mIonFd, capacity, align, heapMask, flags);
+    C2Error ret = alloc->status();
+    if (ret == C2_OK) {
+        *allocation = alloc;
+    }
+    return ret;
+}
+
+/**
+ * (Re)creates a 1D allocation from a native |handle|. If successful, the allocation is stored
+ * in |allocation|. Otherwise, |allocation| is set to 'nullptr'.
+ *
+ * \param handle      the handle for the existing allocation
+ * \param allocation  pointer to where the allocation shall be stored on success. nullptr
+ *                  will be stored here on failure
+ *
+ * \retval C2_OK        the allocation was recreated successfully
+ * \retval C2_NO_MEMORY not enough memory to recreate the allocation
+ * \retval C2_TIMED_OUT the recreation timed out (unexpected)
+ * \retval C2_NO_PERMISSION     no permission to recreate the allocation
+ * \retval C2_BAD_VALUE invalid handle (caller error)
+ * \retval C2_UNSUPPORTED       this allocator does not support 1D allocations
+ * \retval C2_CORRUPTED some unknown, unrecoverable error occured during allocation (unexpected)
+ */
+C2Error C2AllocatorIon::recreateLinearBuffer(
+        const C2Handle *handle, std::shared_ptr<C2LinearAllocation> *allocation) {
+    *allocation = nullptr;
+    if (mInit != C2_OK) {
+        return C2_UNSUPPORTED;
+    }
+
+    if (!C2HandleIon::isValid(handle)) {
+        return C2_BAD_VALUE;
+    }
+
+    // TODO: get capacity and validate it
+    const C2HandleIon *h = static_cast<const C2HandleIon*>(handle);
+    std::shared_ptr<C2AllocationIon> alloc
+        = std::make_shared<C2AllocationIon>(mIonFd, 0 /* capacity */, h->buffer());
+    C2Error ret = alloc->status();
+    if (ret == C2_OK) {
+        *allocation = alloc;
+    }
+    return ret;
+}
+
+/* ========================================== 1D BLOCK ========================================= */
+
+class C2Block1D::Impl {
+public:
+    const C2Handle *handle() const {
+        return mAllocation->handle();
+    }
+
+    Impl(std::shared_ptr<C2LinearAllocation> alloc)
+        : mAllocation(alloc) {}
+
+private:
+    std::shared_ptr<C2LinearAllocation> mAllocation;
+};
+
+const C2Handle *C2Block1D::handle() const {
+    return mImpl->handle();
+};
+
+C2Block1D::C2Block1D(std::shared_ptr<C2LinearAllocation> alloc)
+    : _C2LinearRangeAspect(alloc.get()), mImpl(new Impl(alloc)) {
+}
+
+C2Block1D::C2Block1D(std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size)
+    : _C2LinearRangeAspect(alloc.get(), offset, size), mImpl(new Impl(alloc)) {
+}
+
+class C2ReadView::Impl {
+public:
+    explicit Impl(const uint8_t *data)
+        : mData(data), mError(C2_OK) {}
+
+    explicit Impl(C2Error error)
+        : mData(nullptr), mError(error) {}
+
+    const uint8_t *data() const {
+        return mData;
+    }
+
+    C2Error error() const {
+        return mError;
+    }
+
+private:
+    const uint8_t *mData;
+    C2Error mError;
+};
+
+C2ReadView::C2ReadView(const _C2LinearCapacityAspect *parent, const uint8_t *data)
+    : _C2LinearCapacityAspect(parent), mImpl(std::make_shared<Impl>(data)) {}
+
+C2ReadView::C2ReadView(C2Error error)
+    : _C2LinearCapacityAspect(0u), mImpl(std::make_shared<Impl>(error)) {}
+
+const uint8_t *C2ReadView::data() const {
+    return mImpl->data();
+}
+
+C2ReadView C2ReadView::subView(size_t offset, size_t size) const {
+    if (offset > capacity()) {
+        offset = capacity();
+    }
+    if (size > capacity() - offset) {
+        size = capacity() - offset;
+    }
+    // TRICKY: newCapacity will just be used to grab the size.
+    DummyCapacityAspect newCapacity((uint32_t)size);
+    return C2ReadView(&newCapacity, data() + offset);
+}
+
+C2Error C2ReadView::error() {
+    return mImpl->error();
+}
+
+class C2WriteView::Impl {
+public:
+    explicit Impl(uint8_t *base)
+        : mBase(base), mError(C2_OK) {}
+
+    explicit Impl(C2Error error)
+        : mBase(nullptr), mError(error) {}
+
+    uint8_t *base() const {
+        return mBase;
+    }
+
+    C2Error error() const {
+        return mError;
+    }
+
+private:
+    uint8_t *mBase;
+    C2Error mError;
+};
+
+C2WriteView::C2WriteView(const _C2LinearRangeAspect *parent, uint8_t *base)
+    : _C2EditableLinearRange(parent), mImpl(std::make_shared<Impl>(base)) {}
+
+C2WriteView::C2WriteView(C2Error error)
+    : _C2EditableLinearRange(nullptr), mImpl(std::make_shared<Impl>(error)) {}
+
+uint8_t *C2WriteView::base() { return mImpl->base(); }
+
+uint8_t *C2WriteView::data() { return mImpl->base() + offset(); }
+
+C2Error C2WriteView::error() { return mImpl->error(); }
+
+class C2ConstLinearBlock::Impl {
+public:
+    explicit Impl(std::shared_ptr<C2LinearAllocation> alloc)
+        : mAllocation(alloc), mBase(nullptr), mSize(0u), mError(C2_CORRUPTED) {}
+
+    ~Impl() {
+        if (mBase != nullptr) {
+            // TODO: fence
+            C2Error err = mAllocation->unmap(mBase, mSize, nullptr);
+            if (err != C2_OK) {
+                // TODO: Log?
+            }
+        }
+    }
+
+    C2ConstLinearBlock subBlock(size_t offset, size_t size) const {
+        return C2ConstLinearBlock(mAllocation, offset, size);
+    }
+
+    void map(size_t offset, size_t size) {
+        if (mBase == nullptr) {
+            void *base = nullptr;
+            mError = mAllocation->map(
+                    offset, size, { C2MemoryUsage::kSoftwareRead, 0 }, nullptr, &base);
+            // TODO: fence
+            if (mError == C2_OK) {
+                mBase = (uint8_t *)base;
+                mSize = size;
+            }
+        }
+    }
+
+    const uint8_t *base() const { return mBase; }
+
+    C2Error error() const { return mError; }
+
+private:
+    std::shared_ptr<C2LinearAllocation> mAllocation;
+    uint8_t *mBase;
+    size_t mSize;
+    C2Error mError;
+};
+
+C2ConstLinearBlock::C2ConstLinearBlock(std::shared_ptr<C2LinearAllocation> alloc)
+    : C2Block1D(alloc), mImpl(std::make_shared<Impl>(alloc)) {}
+
+C2ConstLinearBlock::C2ConstLinearBlock(
+        std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size)
+    : C2Block1D(alloc, offset, size), mImpl(std::make_shared<Impl>(alloc)) {}
+
+C2Acquirable<C2ReadView> C2ConstLinearBlock::map() const {
+    mImpl->map(offset(), size());
+    if (mImpl->base() == nullptr) {
+        C2DefaultReadView view(mImpl->error());
+        return C2AcquirableReadView(mImpl->error(), mFence, view);
+    }
+    DummyCapacityAspect newCapacity(size());
+    C2DefaultReadView view(&newCapacity, mImpl->base());
+    return C2AcquirableReadView(mImpl->error(), mFence, view);
+}
+
+C2ConstLinearBlock C2ConstLinearBlock::subBlock(size_t offset, size_t size) const {
+    return mImpl->subBlock(offset, size);
+}
+
+class C2LinearBlock::Impl {
+public:
+    Impl(std::shared_ptr<C2LinearAllocation> alloc)
+        : mAllocation(alloc), mBase(nullptr), mSize(0u), mError(C2_CORRUPTED) {}
+
+    ~Impl() {
+        if (mBase != nullptr) {
+            // TODO: fence
+            C2Error err = mAllocation->unmap(mBase, mSize, nullptr);
+            if (err != C2_OK) {
+                // TODO: Log?
+            }
+        }
+    }
+
+    void map(size_t capacity) {
+        if (mBase == nullptr) {
+            void *base = nullptr;
+            // TODO: fence
+            mError = mAllocation->map(
+                    0u,
+                    capacity,
+                    { C2MemoryUsage::kSoftwareRead, C2MemoryUsage::kSoftwareWrite },
+                    nullptr,
+                    &base);
+            if (mError == C2_OK) {
+                mBase = (uint8_t *)base;
+                mSize = capacity;
+            }
+        }
+    }
+
+    C2ConstLinearBlock share(size_t offset, size_t size, C2Fence &fence) {
+        // TODO
+        (void) fence;
+        return C2DefaultConstLinearBlock(mAllocation, offset, size);
+    }
+
+    uint8_t *base() const { return mBase; }
+
+    C2Error error() const { return mError; }
+
+    C2Fence fence() const { return mFence; }
+
+private:
+    std::shared_ptr<C2LinearAllocation> mAllocation;
+    uint8_t *mBase;
+    size_t mSize;
+    C2Error mError;
+    C2Fence mFence;
+};
+
+C2LinearBlock::C2LinearBlock(std::shared_ptr<C2LinearAllocation> alloc)
+    : C2Block1D(alloc),
+      mImpl(new Impl(alloc)) {}
+
+C2LinearBlock::C2LinearBlock(std::shared_ptr<C2LinearAllocation> alloc, size_t offset, size_t size)
+    : C2Block1D(alloc, offset, size),
+      mImpl(new Impl(alloc)) {}
+
+C2Acquirable<C2WriteView> C2LinearBlock::map() {
+    mImpl->map(capacity());
+    if (mImpl->base() == nullptr) {
+        C2DefaultWriteView view(mImpl->error());
+        return C2AcquirableWriteView(mImpl->error(), mImpl->fence(), view);
+    }
+    C2DefaultWriteView view(this, mImpl->base());
+    view.setOffset_be(offset());
+    view.setSize_be(size());
+    return C2AcquirableWriteView(mImpl->error(), mImpl->fence(), view);
+}
+
+C2ConstLinearBlock C2LinearBlock::share(size_t offset, size_t size, C2Fence fence) {
+    return mImpl->share(offset, size, fence);
+}
+
+C2DefaultBlockAllocator::C2DefaultBlockAllocator(
+        const std::shared_ptr<C2Allocator> &allocator)
+  : mAllocator(allocator) {}
+
+C2Error C2DefaultBlockAllocator::allocateLinearBlock(
+        uint32_t capacity,
+        C2MemoryUsage usage,
+        std::shared_ptr<C2LinearBlock> *block /* nonnull */) {
+    block->reset();
+
+    std::shared_ptr<C2LinearAllocation> alloc;
+    C2Error err = mAllocator->allocateLinearBuffer(capacity, usage, &alloc);
+    if (err != C2_OK) {
+        return err;
+    }
+
+    block->reset(new C2DefaultLinearBlock(alloc));
+
+    return C2_OK;
+}
+
+} // namespace android
diff --git a/media/libstagefright/codec2/vndk/include/C2BufferPriv.h b/media/libstagefright/codec2/vndk/include/C2BufferPriv.h
new file mode 100644
index 0000000..bfb069c
--- /dev/null
+++ b/media/libstagefright/codec2/vndk/include/C2BufferPriv.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef STAGEFRIGHT_CODEC2_BUFFER_PRIV_H_
+#define STAGEFRIGHT_CODEC2_BUFFER_PRIV_H_
+
+#include <functional>
+
+#include <C2Buffer.h>
+
+namespace android {
+
+class C2AllocatorIon : public C2Allocator {
+public:
+    // (usage, capacity) => (align, heapMask, flags)
+    typedef std::function<int (C2MemoryUsage, size_t,
+                      /* => */ size_t*, unsigned*, unsigned*)> usage_mapper_fn;
+
+    virtual C2Error allocateLinearBuffer(
+            uint32_t capacity, C2MemoryUsage usage,
+            std::shared_ptr<C2LinearAllocation> *allocation) override;
+
+    virtual C2Error recreateLinearBuffer(
+            const C2Handle *handle,
+            std::shared_ptr<C2LinearAllocation> *allocation) override;
+
+    C2AllocatorIon();
+
+    C2Error status() const { return mInit; }
+
+    virtual ~C2AllocatorIon();
+
+private:
+    C2Error mInit;
+    int mIonFd;
+    usage_mapper_fn mUsageMapper;
+};
+
+class C2DefaultBlockAllocator : public C2BlockAllocator {
+public:
+    explicit C2DefaultBlockAllocator(const std::shared_ptr<C2Allocator> &allocator);
+
+    virtual ~C2DefaultBlockAllocator() = default;
+
+    virtual C2Error allocateLinearBlock(
+            uint32_t capacity,
+            C2MemoryUsage usage,
+            std::shared_ptr<C2LinearBlock> *block /* nonnull */) override;
+
+    // TODO:
+private:
+    const std::shared_ptr<C2Allocator> mAllocator;
+};
+
+#if 0
+class C2Allocation::Impl {
+public:
+    Impl() : mMapped(false), mBase(nullptr) { }
+    uint8_t* base() { return mMapped ? mBase : nullptr; }
+
+    // TODO: call map...
+
+private:
+    bool mMapped;
+    uint8_t *mBase;
+};
+#endif
+
+} // namespace android
+
+#endif // STAGEFRIGHT_CODEC2_BUFFER_PRIV_H_
diff --git a/media/libstagefright/include/media/stagefright/MediaClock.h b/media/libstagefright/include/media/stagefright/MediaClock.h
index dd1a809..59f700a 100644
--- a/media/libstagefright/include/media/stagefright/MediaClock.h
+++ b/media/libstagefright/include/media/stagefright/MediaClock.h
@@ -18,7 +18,8 @@
 
 #define MEDIA_CLOCK_H_
 
-#include <media/stagefright/foundation/ABase.h>
+#include <map>
+#include <media/stagefright/foundation/AHandler.h>
 #include <utils/Mutex.h>
 #include <utils/RefBase.h>
 
@@ -26,8 +27,15 @@
 
 struct AMessage;
 
-struct MediaClock : public RefBase {
+struct MediaClock : public AHandler {
+    enum {
+        TIMER_REASON_REACHED = 0,
+        TIMER_REASON_NO_CLOCK = 1,
+        TIMER_REASON_RESET = 2,
+    };
+
     MediaClock();
+    void init();
 
     void setStartingTimeMedia(int64_t startingTimeMediaUs);
 
@@ -54,15 +62,28 @@
     // The result is saved in |outRealUs|.
     status_t getRealTimeFor(int64_t targetMediaUs, int64_t *outRealUs) const;
 
+    void addTimer(const sp<AMessage> &notify, int64_t mediaTimeUs);
+
+    void reset();
+
 protected:
     virtual ~MediaClock();
 
+    virtual void onMessageReceived(const sp<AMessage> &msg);
+
 private:
+    enum {
+        kWhatTimeIsUp = 'tIsU',
+    };
+
     status_t getMediaTime_l(
             int64_t realUs,
             int64_t *outMediaUs,
             bool allowPastMaxTime) const;
 
+    void processTimers_l();
+
+    sp<ALooper> mLooper;
     mutable Mutex mLock;
 
     int64_t mAnchorTimeMediaUs;
@@ -72,6 +93,9 @@
 
     float mPlaybackRate;
 
+    int32_t mGeneration;
+    std::multimap<int64_t, sp<AMessage> > mTimers;
+
     DISALLOW_EVIL_CONSTRUCTORS(MediaClock);
 };
 
diff --git a/media/libstagefright/omx/Android.bp b/media/libstagefright/omx/Android.bp
index d4cdf69..bec022a 100644
--- a/media/libstagefright/omx/Android.bp
+++ b/media/libstagefright/omx/Android.bp
@@ -57,6 +57,7 @@
         "libhidlmemory",
         "libhidltransport",
         "libnativewindow", // TODO(b/62923479): use header library
+        "libvndksupport",
         "android.hidl.memory@1.0",
         "android.hidl.token@1.0-utils",
         "android.hardware.media@1.0",
diff --git a/media/libstagefright/omx/OMXMaster.cpp b/media/libstagefright/omx/OMXMaster.cpp
index fd97fdc..0967b5f 100644
--- a/media/libstagefright/omx/OMXMaster.cpp
+++ b/media/libstagefright/omx/OMXMaster.cpp
@@ -22,6 +22,8 @@
 #include <media/stagefright/omx/SoftOMXPlugin.h>
 #include <media/stagefright/foundation/ADebug.h>
 
+#include <vndksupport/linker.h>
+
 #include <dlfcn.h>
 #include <fcntl.h>
 
@@ -67,7 +69,7 @@
 }
 
 void OMXMaster::addPlugin(const char *libname) {
-    mVendorLibHandle = dlopen(libname, RTLD_NOW);
+    mVendorLibHandle = android_load_sphal_library(libname, RTLD_NOW);
 
     if (mVendorLibHandle == NULL) {
         return;
diff --git a/media/mtp/MtpFfsHandle.cpp b/media/mtp/MtpFfsHandle.cpp
index 89b20e5..965985d 100644
--- a/media/mtp/MtpFfsHandle.cpp
+++ b/media/mtp/MtpFfsHandle.cpp
@@ -94,8 +94,11 @@
     __le32 fs_count;
     __le32 hs_count;
     __le32 ss_count;
+    __le32 os_count;
     struct func_desc fs_descs, hs_descs;
     struct ss_func_desc ss_descs;
+    struct usb_os_desc_header os_header;
+    struct usb_ext_compat_desc os_desc;
 } __attribute__((packed));
 
 const struct usb_interface_descriptor mtp_interface_desc = {
@@ -261,6 +264,31 @@
     },
 };
 
+struct usb_os_desc_header mtp_os_desc_header = {
+    .interface = htole32(1),
+    .dwLength = htole32(sizeof(usb_os_desc_header) + sizeof(usb_ext_compat_desc)),
+    .bcdVersion = htole16(1),
+    .wIndex = htole16(4),
+    .bCount = htole16(1),
+    .Reserved = htole16(0),
+};
+
+struct usb_ext_compat_desc mtp_os_desc_compat = {
+    .bFirstInterfaceNumber = 0,
+    .Reserved1 = htole32(1),
+    .CompatibleID = { 'M', 'T', 'P' },
+    .SubCompatibleID = {0},
+    .Reserved2 = {0},
+};
+
+struct usb_ext_compat_desc ptp_os_desc_compat = {
+    .bFirstInterfaceNumber = 0,
+    .Reserved1 = htole32(1),
+    .CompatibleID = { 'P', 'T', 'P' },
+    .SubCompatibleID = {0},
+    .Reserved2 = {0},
+};
+
 struct mtp_device_status {
     uint16_t  wLength;
     uint16_t  wCode;
@@ -336,13 +364,16 @@
     v2_descriptor.header.magic = htole32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2);
     v2_descriptor.header.length = htole32(sizeof(v2_descriptor));
     v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC |
-                                 FUNCTIONFS_HAS_SS_DESC;
+                                 FUNCTIONFS_HAS_SS_DESC | FUNCTIONFS_HAS_MS_OS_DESC;
     v2_descriptor.fs_count = 4;
     v2_descriptor.hs_count = 4;
     v2_descriptor.ss_count = 7;
+    v2_descriptor.os_count = 1;
     v2_descriptor.fs_descs = mPtp ? ptp_fs_descriptors : mtp_fs_descriptors;
     v2_descriptor.hs_descs = mPtp ? ptp_hs_descriptors : mtp_hs_descriptors;
     v2_descriptor.ss_descs = mPtp ? ptp_ss_descriptors : mtp_ss_descriptors;
+    v2_descriptor.os_header = mtp_os_desc_header;
+    v2_descriptor.os_desc = mPtp ? ptp_os_desc_compat : mtp_os_desc_compat;
 
     if (mControl < 0) { // might have already done this before
         mControl.reset(TEMP_FAILURE_RETRY(open(FFS_MTP_EP0, O_RDWR)));
diff --git a/media/ndk/OWNERS b/media/ndk/OWNERS
new file mode 100644
index 0000000..43e4bb3
--- /dev/null
+++ b/media/ndk/OWNERS
@@ -0,0 +1 @@
+marcone@google.com
diff --git a/media/utils/OWNERS b/media/utils/OWNERS
new file mode 100644
index 0000000..f9cb567
--- /dev/null
+++ b/media/utils/OWNERS
@@ -0,0 +1 @@
+gkasten@google.com
diff --git a/services/OWNERS b/services/OWNERS
index d500dce..d5d00da 100644
--- a/services/OWNERS
+++ b/services/OWNERS
@@ -1,4 +1,4 @@
 elaurent@google.com
 etalvala@google.com
-gkasten@android.com
+gkasten@google.com
 hunga@google.com
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 13522f5..f906b6f 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -1561,7 +1561,7 @@
 
 // ----------------------------------------------------------------------------
 
-sp<IAudioRecord> AudioFlinger::openRecord(
+sp<media::IAudioRecord> AudioFlinger::openRecord(
         audio_io_handle_t input,
         uint32_t sampleRate,
         audio_format_t format,
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index 63898a0..de617b9 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -33,7 +33,6 @@
 #include <media/IAudioFlinger.h>
 #include <media/IAudioFlingerClient.h>
 #include <media/IAudioTrack.h>
-#include <media/IAudioRecord.h>
 #include <media/AudioSystem.h>
 #include <media/AudioTrack.h>
 #include <media/MmapStreamInterface.h>
@@ -76,6 +75,8 @@
 #include <private/media/AudioEffectShared.h>
 #include <private/media/AudioTrackShared.h>
 
+#include "android/media/BnAudioRecord.h"
+
 namespace android {
 
 class AudioMixer;
@@ -129,7 +130,7 @@
                                 status_t *status /*non-NULL*/,
                                 audio_port_handle_t portId);
 
-    virtual sp<IAudioRecord> openRecord(
+    virtual sp<media::IAudioRecord> openRecord(
                                 audio_io_handle_t input,
                                 uint32_t sampleRate,
                                 audio_format_t format,
@@ -556,10 +557,10 @@
         virtual void        pause();
         virtual status_t    attachAuxEffect(int effectId);
         virtual status_t    setParameters(const String8& keyValuePairs);
-        virtual VolumeShaper::Status applyVolumeShaper(
-                const sp<VolumeShaper::Configuration>& configuration,
-                const sp<VolumeShaper::Operation>& operation) override;
-        virtual sp<VolumeShaper::State> getVolumeShaperState(int id) override;
+        virtual media::VolumeShaper::Status applyVolumeShaper(
+                const sp<media::VolumeShaper::Configuration>& configuration,
+                const sp<media::VolumeShaper::Operation>& operation) override;
+        virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
         virtual status_t    getTimestamp(AudioTimestamp& timestamp);
         virtual void        signal(); // signal playback thread for a change in control block
 
@@ -571,15 +572,13 @@
     };
 
     // server side of the client's IAudioRecord
-    class RecordHandle : public android::BnAudioRecord {
+    class RecordHandle : public android::media::BnAudioRecord {
     public:
         explicit RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
         virtual             ~RecordHandle();
-        virtual status_t    start(int /*AudioSystem::sync_event_t*/ event,
-                audio_session_t triggerSession);
-        virtual void        stop();
-        virtual status_t onTransact(
-            uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
+        virtual binder::Status    start(int /*AudioSystem::sync_event_t*/ event,
+                int /*audio_session_t*/ triggerSession);
+        virtual binder::Status   stop();
     private:
         const sp<RecordThread::RecordTrack> mRecordTrack;
 
diff --git a/services/audioflinger/FastMixer.cpp b/services/audioflinger/FastMixer.cpp
index c10fa05..ace586c 100644
--- a/services/audioflinger/FastMixer.cpp
+++ b/services/audioflinger/FastMixer.cpp
@@ -138,8 +138,6 @@
 
 void FastMixer::onStateChange()
 {
-    // log that audio was turned on/off
-    LOG_AUDIO_STATE();
     const FastMixerState * const current = (const FastMixerState *) mCurrent;
     const FastMixerState * const previous = (const FastMixerState *) mPrevious;
     FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
@@ -336,7 +334,13 @@
 
 void FastMixer::onWork()
 {
-    LOG_HIST_TS();
+    // TODO: pass an ID parameter to indicate which time series we want to write to in NBLog.cpp
+    // Or: pass both of these into a single call with a boolean
+    if (mIsWarm) {
+        LOG_HIST_TS();
+    } else {
+        LOG_AUDIO_STATE();
+    }
     const FastMixerState * const current = (const FastMixerState *) mCurrent;
     FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
     const FastMixerState::Command command = mCommand;
diff --git a/services/audioflinger/OWNERS b/services/audioflinger/OWNERS
index 703e4d2..d02d9e0 100644
--- a/services/audioflinger/OWNERS
+++ b/services/audioflinger/OWNERS
@@ -1,3 +1,4 @@
 hunga@google.com
 jmtrivi@google.com
 mnaganov@google.com
+gkasten@google.com
diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h
index 1c1a989..946d88f 100644
--- a/services/audioflinger/PlaybackTracks.h
+++ b/services/audioflinger/PlaybackTracks.h
@@ -82,11 +82,11 @@
     virtual bool        isFastTrack() const { return (mFlags & AUDIO_OUTPUT_FLAG_FAST) != 0; }
 
 // implement volume handling.
-   VolumeShaper::Status applyVolumeShaper(
-                                const sp<VolumeShaper::Configuration>& configuration,
-                                const sp<VolumeShaper::Operation>& operation);
-sp<VolumeShaper::State> getVolumeShaperState(int id);
-    sp<VolumeHandler>   getVolumeHandler() { return mVolumeHandler; }
+    media::VolumeShaper::Status applyVolumeShaper(
+                                const sp<media::VolumeShaper::Configuration>& configuration,
+                                const sp<media::VolumeShaper::Operation>& operation);
+    sp<media::VolumeShaper::State> getVolumeShaperState(int id);
+    sp<media::VolumeHandler>   getVolumeHandler() { return mVolumeHandler; }
 
 protected:
     // for numerous
@@ -163,7 +163,7 @@
 
     ExtendedTimestamp  mSinkTimestamp;
 
-    sp<VolumeHandler>  mVolumeHandler; // handles multiple VolumeShaper configs and operations
+    sp<media::VolumeHandler>  mVolumeHandler; // handles multiple VolumeShaper configs and operations
 
 private:
     // The following fields are only for fast tracks, and should be in a subclass
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index 297608c..ef94bc3 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -2636,6 +2636,7 @@
 // shared by MIXER and DIRECT, overridden by DUPLICATING
 ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
 {
+    LOG_HIST_TS();
     mInWrite = true;
     ssize_t bytesWritten;
     const size_t offset = mCurrentWriteLength - mBytesRemaining;
@@ -3114,6 +3115,10 @@
 
                     threadLoop_standby();
 
+                    // This is where we go into standby
+                    if (!mStandby) {
+                        LOG_AUDIO_STATE();
+                    }
                     mStandby = true;
                 }
 
@@ -5429,7 +5434,7 @@
         mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
         mOffloadUnderrunPosition(~0LL)
 {
-    //FIXME: mStandby should be set to true by ThreadBase constructor
+    //FIXME: mStandby should be set to true by ThreadBase constructo
     mStandby = true;
     mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
 }
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index 8d7bb1a..bfd9a3f 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -485,6 +485,7 @@
                 // Updated by updateSuspendedSessions_l() only.
                 KeyedVector< audio_session_t, KeyedVector< int, sp<SuspendedSessionDesc> > >
                                         mSuspendedSessions;
+                // TODO: add comment and adjust size as needed
                 static const size_t     kLogSize = 4 * 1024;
                 sp<NBLog::Writer>       mNBLogWriter;
                 bool                    mSystemReady;
@@ -984,6 +985,7 @@
     sp<NBAIO_Source>        mTeeSource;
 #endif
     uint32_t                mScreenState;   // cached copy of gScreenState
+    // TODO: add comment and adjust size as needed
     static const size_t     kFastMixerLogSize = 8 * 1024;
     sp<NBLog::Writer>       mFastMixerNBLogWriter;
 
@@ -1456,6 +1458,7 @@
             // If a fast capture is present, the Pipe as IMemory, otherwise clear
             sp<IMemory>                         mPipeMemory;
 
+            // TODO: add comment and adjust size as needed
             static const size_t                 kFastCaptureLogSize = 4 * 1024;
             sp<NBLog::Writer>                   mFastCaptureNBLogWriter;
 
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index 0f25153..50c0e23 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -52,6 +52,7 @@
 
 namespace android {
 
+using media::VolumeShaper;
 // ----------------------------------------------------------------------------
 //      TrackBase
 // ----------------------------------------------------------------------------
@@ -399,7 +400,7 @@
     mAuxEffectId(0), mHasVolumeController(false),
     mPresentationCompleteFrames(0),
     mFrameMap(16 /* sink-frame-to-track-frame map memory */),
-    mVolumeHandler(new VolumeHandler(sampleRate)),
+    mVolumeHandler(new media::VolumeHandler(sampleRate)),
     // mSinkTimestamp
     mFastIndex(-1),
     mCachedVolume(1.0),
@@ -1561,14 +1562,16 @@
     mRecordTrack->destroy();
 }
 
-status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
-        audio_session_t triggerSession) {
+binder::Status AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
+        int /*audio_session_t*/ triggerSession) {
     ALOGV("RecordHandle::start()");
-    return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
+    return binder::Status::fromStatusT(
+        mRecordTrack->start((AudioSystem::sync_event_t)event, (audio_session_t) triggerSession));
 }
 
-void AudioFlinger::RecordHandle::stop() {
+binder::Status AudioFlinger::RecordHandle::stop() {
     stop_nonvirtual();
+    return binder::Status::ok();
 }
 
 void AudioFlinger::RecordHandle::stop_nonvirtual() {
@@ -1576,12 +1579,6 @@
     mRecordTrack->stop();
 }
 
-status_t AudioFlinger::RecordHandle::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
-    return BnAudioRecord::onTransact(code, data, reply, flags);
-}
-
 // ----------------------------------------------------------------------------
 
 // RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
index 8593444..4d3c3b5 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
@@ -46,17 +46,17 @@
     for (int i = 0; i < NUM_STRATEGIES; i++) {
         mStrategyMutedByDevice[i] = false;
     }
-    if (port != NULL) {
-        port->pickAudioProfile(mSamplingRate, mChannelMask, mFormat);
-        if (port->mGains.size() > 0) {
-            port->mGains[0]->getDefaultConfig(&mGain);
+    if (mPort.get() != nullptr) {
+        mPort->pickAudioProfile(mSamplingRate, mChannelMask, mFormat);
+        if (mPort->mGains.size() > 0) {
+            mPort->mGains[0]->getDefaultConfig(&mGain);
         }
     }
 }
 
 audio_module_handle_t AudioOutputDescriptor::getModuleHandle() const
 {
-    return mPort->getModuleHandle();
+    return mPort.get() != nullptr ? mPort->getModuleHandle() : AUDIO_MODULE_HANDLE_NONE;
 }
 
 audio_port_handle_t AudioOutputDescriptor::getId() const
@@ -175,9 +175,9 @@
     dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
 }
 
-void AudioOutputDescriptor::toAudioPort(
-                                                    struct audio_port *port) const
+void AudioOutputDescriptor::toAudioPort(struct audio_port *port) const
 {
+    // Should not be called for duplicated ports, see SwAudioOutputDescriptor::toAudioPortConfig.
     mPort->toAudioPort(port);
     port->id = mId;
     port->ext.mix.hw_module = getModuleHandle();
diff --git a/services/audiopolicy/config/audio_policy_configuration.xml b/services/audiopolicy/config/audio_policy_configuration.xml
index 7af2f81..73efe8e 100644
--- a/services/audiopolicy/config/audio_policy_configuration.xml
+++ b/services/audiopolicy/config/audio_policy_configuration.xml
@@ -163,37 +163,16 @@
                        sources="primary output,deep_buffer,compressed_offload,BT SCO Headset Mic,Telephony Rx"/>
                 <route type="mix" sink="Wired Headphones"
                        sources="primary output,deep_buffer,compressed_offload,BT SCO Headset Mic,Telephony Rx"/>
-                <route type="mix" sink="Telephony Tx"
-                       sources="voice_tx"/>
                 <route type="mix" sink="primary input"
                        sources="Built-In Mic,Built-In Back Mic,Wired Headset Mic,BT SCO Headset Mic"/>
                 <route type="mix" sink="Telephony Tx"
-                       sources="Built-In Mic,Built-In Back Mic,Wired Headset Mic,BT SCO Headset Mic"/>
+                       sources="Built-In Mic,Built-In Back Mic,Wired Headset Mic,BT SCO Headset Mic, voice_tx"/>
                 <route type="mix" sink="voice_rx"
                        sources="Telephony Rx"/>
             </routes>
 
         </module>
 
-        <!-- HDMI Audio HAL -->
-        <module description="HDMI Audio HAL" name="hdmi" version="2.0">
-            <mixPorts>
-                <mixPort name="hdmi output" role="source">
-                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT" samplingRates="48000"/>
-                </mixPort>
-            </mixPorts>
-            <devicePorts>
-                <devicePort tagName="HDMI Out" type="AUDIO_DEVICE_OUT_AUX_DIGITAL" role="sink">
-                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
-                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
-                </devicePort>
-            </devicePorts>
-            <routes>
-                <route type="mix" sink="HDMI Out"
-                       sources="hdmi output"/>
-            </routes>
-        </module>
-
         <!-- A2dp Audio HAL -->
         <xi:include href="a2dp_audio_policy_configuration.xml"/>
 
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index e6ee6c9..d2a2855 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -874,48 +874,6 @@
     audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
     status_t status;
 
-#ifdef AUDIO_POLICY_TEST
-    if (mCurOutput != 0) {
-        ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
-                mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
-
-        if (mTestOutputs[mCurOutput] == 0) {
-            ALOGV("getOutput() opening test output");
-            sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
-                                                                               mpClientInterface);
-            outputDesc->mDevice = mTestDevice;
-            outputDesc->mLatency = mTestLatencyMs;
-            outputDesc->mFlags =
-                    (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
-            outputDesc->mRefCount[stream] = 0;
-            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
-            config.sample_rate = mTestSamplingRate;
-            config.channel_mask = mTestChannels;
-            config.format = mTestFormat;
-            if (offloadInfo != NULL) {
-                config.offload_info = *offloadInfo;
-            }
-            status = mpClientInterface->openOutput(0,
-                                                  &mTestOutputs[mCurOutput],
-                                                  &config,
-                                                  &outputDesc->mDevice,
-                                                  String8(""),
-                                                  &outputDesc->mLatency,
-                                                  outputDesc->mFlags);
-            if (status == NO_ERROR) {
-                outputDesc->mSamplingRate = config.sample_rate;
-                outputDesc->mFormat = config.format;
-                outputDesc->mChannelMask = config.channel_mask;
-                AudioParameter outputCmd = AudioParameter();
-                outputCmd.addInt(String8("set_id"),mCurOutput);
-                mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
-                addOutput(mTestOutputs[mCurOutput], outputDesc);
-            }
-        }
-        return mTestOutputs[mCurOutput];
-    }
-#endif //AUDIO_POLICY_TEST
-
     // open a direct output if required by specified parameters
     //force direct flag if offload flag is set: offloading implies a direct output stream
     // and all common behaviors are driven by checking only the direct flag
@@ -1094,7 +1052,7 @@
         flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
         output = selectOutput(outputs, flags, format);
     }
-    ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
+    ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d, "
             "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
 
     return output;
@@ -1454,19 +1412,6 @@
         return;
     }
 
-#ifdef AUDIO_POLICY_TEST
-    int testIndex = testOutputIndex(output);
-    if (testIndex != 0) {
-        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
-        if (outputDesc->isActive()) {
-            mpClientInterface->closeOutput(output);
-            removeOutput(output);
-            mTestOutputs[testIndex] = 0;
-        }
-        return;
-    }
-#endif //AUDIO_POLICY_TEST
-
     // Routing
     mOutputRoutes.removeRoute(session);
 
@@ -1673,7 +1618,7 @@
         } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
             profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
         } else { // fail
-            ALOGW("getInputForDevice() could not find profile for device 0x%X,"
+            ALOGW("getInputForDevice() could not find profile for device 0x%X, "
                   "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
                     device, samplingRate, format, channelMask, flags);
             return input;
@@ -3569,9 +3514,6 @@
 
 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
     :
-#ifdef AUDIO_POLICY_TEST
-    Thread(false),
-#endif //AUDIO_POLICY_TEST
     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
     mA2dpSuspended(false),
     mAudioPortGeneration(1),
@@ -3812,37 +3754,10 @@
     ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
 
     updateDevicesAndOutputs();
-
-#ifdef AUDIO_POLICY_TEST
-    if (mPrimaryOutput != 0) {
-        AudioParameter outputCmd = AudioParameter();
-        outputCmd.addInt(String8("set_id"), 0);
-        mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
-
-        mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
-        mTestSamplingRate = 44100;
-        mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
-        mTestChannels =  AUDIO_CHANNEL_OUT_STEREO;
-        mTestLatencyMs = 0;
-        mCurOutput = 0;
-        mDirectOutput = false;
-        for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
-            mTestOutputs[i] = 0;
-        }
-
-        const size_t SIZE = 256;
-        char buffer[SIZE];
-        snprintf(buffer, SIZE, "AudioPolicyManagerTest");
-        run(buffer, ANDROID_PRIORITY_AUDIO);
-    }
-#endif //AUDIO_POLICY_TEST
 }
 
 AudioPolicyManager::~AudioPolicyManager()
 {
-#ifdef AUDIO_POLICY_TEST
-    exit();
-#endif //AUDIO_POLICY_TEST
    for (size_t i = 0; i < mOutputs.size(); i++) {
         mpClientInterface->closeOutput(mOutputs.keyAt(i));
    }
@@ -3861,164 +3776,6 @@
     return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
 }
 
-#ifdef AUDIO_POLICY_TEST
-bool AudioPolicyManager::threadLoop()
-{
-    ALOGV("entering threadLoop()");
-    while (!exitPending())
-    {
-        String8 command;
-        int valueInt;
-        String8 value;
-
-        Mutex::Autolock _l(mLock);
-        mWaitWorkCV.waitRelative(mLock, milliseconds(50));
-
-        command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
-        AudioParameter param = AudioParameter(command);
-
-        if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
-            valueInt != 0) {
-            ALOGV("Test command %s received", command.string());
-            String8 target;
-            if (param.get(String8("target"), target) != NO_ERROR) {
-                target = "Manager";
-            }
-            if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_output"));
-                mCurOutput = valueInt;
-            }
-            if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_direct"));
-                if (value == "false") {
-                    mDirectOutput = false;
-                } else if (value == "true") {
-                    mDirectOutput = true;
-                }
-            }
-            if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_input"));
-                mTestInput = valueInt;
-            }
-
-            if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_format"));
-                int format = AUDIO_FORMAT_INVALID;
-                if (value == "PCM 16 bits") {
-                    format = AUDIO_FORMAT_PCM_16_BIT;
-                } else if (value == "PCM 8 bits") {
-                    format = AUDIO_FORMAT_PCM_8_BIT;
-                } else if (value == "Compressed MP3") {
-                    format = AUDIO_FORMAT_MP3;
-                }
-                if (format != AUDIO_FORMAT_INVALID) {
-                    if (target == "Manager") {
-                        mTestFormat = format;
-                    } else if (mTestOutputs[mCurOutput] != 0) {
-                        AudioParameter outputParam = AudioParameter();
-                        outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
-                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
-                    }
-                }
-            }
-            if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_channels"));
-                int channels = 0;
-
-                if (value == "Channels Stereo") {
-                    channels =  AUDIO_CHANNEL_OUT_STEREO;
-                } else if (value == "Channels Mono") {
-                    channels =  AUDIO_CHANNEL_OUT_MONO;
-                }
-                if (channels != 0) {
-                    if (target == "Manager") {
-                        mTestChannels = channels;
-                    } else if (mTestOutputs[mCurOutput] != 0) {
-                        AudioParameter outputParam = AudioParameter();
-                        outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
-                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
-                    }
-                }
-            }
-            if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_sampleRate"));
-                if (valueInt >= 0 && valueInt <= 96000) {
-                    int samplingRate = valueInt;
-                    if (target == "Manager") {
-                        mTestSamplingRate = samplingRate;
-                    } else if (mTestOutputs[mCurOutput] != 0) {
-                        AudioParameter outputParam = AudioParameter();
-                        outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
-                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
-                    }
-                }
-            }
-
-            if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
-                param.remove(String8("test_cmd_policy_reopen"));
-
-                mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
-
-                audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
-
-                removeOutput(mPrimaryOutput->mIoHandle);
-                sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
-                                                                               mpClientInterface);
-                outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
-                audio_config_t config = AUDIO_CONFIG_INITIALIZER;
-                config.sample_rate = outputDesc->mSamplingRate;
-                config.channel_mask = outputDesc->mChannelMask;
-                config.format = outputDesc->mFormat;
-                audio_io_handle_t handle;
-                status_t status = mpClientInterface->openOutput(moduleHandle,
-                                                                &handle,
-                                                                &config,
-                                                                &outputDesc->mDevice,
-                                                                String8(""),
-                                                                &outputDesc->mLatency,
-                                                                outputDesc->mFlags);
-                if (status != NO_ERROR) {
-                    ALOGE("Failed to reopen hardware output stream, "
-                        "samplingRate: %d, format %d, channels %d",
-                        outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
-                } else {
-                    outputDesc->mSamplingRate = config.sample_rate;
-                    outputDesc->mChannelMask = config.channel_mask;
-                    outputDesc->mFormat = config.format;
-                    mPrimaryOutput = outputDesc;
-                    AudioParameter outputCmd = AudioParameter();
-                    outputCmd.addInt(String8("set_id"), 0);
-                    mpClientInterface->setParameters(handle, outputCmd.toString());
-                    addOutput(handle, outputDesc);
-                }
-            }
-
-
-            mpClientInterface->setParameters(0, String8("test_cmd_policy="));
-        }
-    }
-    return false;
-}
-
-void AudioPolicyManager::exit()
-{
-    {
-        AutoMutex _l(mLock);
-        requestExit();
-        mWaitWorkCV.signal();
-    }
-    requestExitAndWait();
-}
-
-int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
-{
-    for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
-        if (output == mTestOutputs[i]) return i;
-    }
-    return 0;
-}
-#endif //AUDIO_POLICY_TEST
-
 // ---
 
 void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h
index 82c4c35..7ba0669 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.h
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h
@@ -76,10 +76,6 @@
 // ----------------------------------------------------------------------------
 
 class AudioPolicyManager : public AudioPolicyInterface, public AudioPolicyManagerObserver
-
-#ifdef AUDIO_POLICY_TEST
-    , public Thread
-#endif //AUDIO_POLICY_TEST
 {
 
 public:
@@ -419,11 +415,6 @@
         {
             return mEffects.getMaxEffectsMemory();
         }
-#ifdef AUDIO_POLICY_TEST
-        virtual     bool        threadLoop();
-                    void        exit();
-        int testOutputIndex(audio_io_handle_t output);
-#endif //AUDIO_POLICY_TEST
 
         SortedVector<audio_io_handle_t> getOutputsForDevice(audio_devices_t device,
                                                             const SwAudioOutputCollection& openOutputs);
@@ -574,22 +565,6 @@
         AudioPolicyMixCollection mPolicyMixes; // list of registered mixes
         audio_io_handle_t mMusicEffectOutput;     // output selected for music effects
 
-
-#ifdef AUDIO_POLICY_TEST
-        Mutex   mLock;
-        Condition mWaitWorkCV;
-
-        int             mCurOutput;
-        bool            mDirectOutput;
-        audio_io_handle_t mTestOutputs[NUM_TEST_OUTPUTS];
-        int             mTestInput;
-        uint32_t        mTestDevice;
-        uint32_t        mTestSamplingRate;
-        uint32_t        mTestFormat;
-        uint32_t        mTestChannels;
-        uint32_t        mTestLatencyMs;
-#endif //AUDIO_POLICY_TEST
-
         uint32_t nextAudioPortGeneration();
 
         // Audio Policy Engine Interface.
diff --git a/services/camera/libcameraservice/api1/client2/JpegProcessor.cpp b/services/camera/libcameraservice/api1/client2/JpegProcessor.cpp
old mode 100644
new mode 100755
index d8b7af2..d1bbdaf
--- a/services/camera/libcameraservice/api1/client2/JpegProcessor.cpp
+++ b/services/camera/libcameraservice/api1/client2/JpegProcessor.cpp
@@ -395,7 +395,7 @@
     }
 
     // Read JFIF segment markers, skip over segment data
-    size = 0;
+    size = MARKER_LENGTH; //jump SOI;
     while (size <= maxSize - MARKER_LENGTH) {
         segment_t *segment = (segment_t*)(jpegBuffer + size);
         uint8_t type = checkJpegMarker(segment->marker);
diff --git a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
index 6fd9263..29bc21c 100644
--- a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
+++ b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
@@ -193,7 +193,7 @@
          */
         SurfaceMap surfaceMap;
         Vector<int32_t> outputStreamIds;
-        for (sp<Surface> surface : request.mSurfaceList) {
+        for (const sp<Surface>& surface : request.mSurfaceList) {
             if (surface == 0) continue;
 
             sp<IGraphicBufferProducer> gbp = surface->getIGraphicBufferProducer();
diff --git a/services/camera/libcameraservice/device3/Camera3OutputStream.cpp b/services/camera/libcameraservice/device3/Camera3OutputStream.cpp
index dcaefe3..0a02a32 100644
--- a/services/camera/libcameraservice/device3/Camera3OutputStream.cpp
+++ b/services/camera/libcameraservice/device3/Camera3OutputStream.cpp
@@ -728,7 +728,7 @@
         const std::vector<sp<GraphicBuffer>>& removedBuffers) {
     sp<Camera3StreamBufferFreedListener> callback = mBufferFreedListener.promote();
     if (callback != nullptr) {
-        for (auto gb : removedBuffers) {
+        for (const auto& gb : removedBuffers) {
             callback->onBufferFreed(mId, gb->handle);
         }
     }
diff --git a/services/camera/libcameraservice/device3/Camera3SharedOutputStream.cpp b/services/camera/libcameraservice/device3/Camera3SharedOutputStream.cpp
index 5051711..fb7472b 100644
--- a/services/camera/libcameraservice/device3/Camera3SharedOutputStream.cpp
+++ b/services/camera/libcameraservice/device3/Camera3SharedOutputStream.cpp
@@ -200,7 +200,7 @@
         // Called before shared buffer queue is constructed.
         *usage = getPresetConsumerUsage();
 
-        for (auto surface : mSurfaces) {
+        for (const auto& surface : mSurfaces) {
             if (surface != nullptr) {
                 res = getEndpointUsageForSurface(&u, surface);
                 *usage |= u;
diff --git a/services/mediaanalytics/OWNERS b/services/mediaanalytics/OWNERS
new file mode 100644
index 0000000..9af258b
--- /dev/null
+++ b/services/mediaanalytics/OWNERS
@@ -0,0 +1 @@
+essick@google.com
diff --git a/services/medialog/MediaLogService.cpp b/services/medialog/MediaLogService.cpp
index a5512e1..fe19b6b 100644
--- a/services/medialog/MediaLogService.cpp
+++ b/services/medialog/MediaLogService.cpp
@@ -26,13 +26,19 @@
 
 namespace android {
 
- static const char kDeadlockedString[] = "MediaLogService may be deadlocked\n";
+static const char kDeadlockedString[] = "MediaLogService may be deadlocked\n";
+
+// mMerger, mMergeReader, and mMergeThread all point to the same location in memory
+// mMergerShared. This is the local memory FIFO containing data merged from all
+// individual thread FIFOs in shared memory. mMergeThread is used to periodically
+// call NBLog::Merger::merge() to collect the data and write it to the FIFO, and call
+// NBLog::MergeReader::getAndProcessSnapshot to process the merged data.
 MediaLogService::MediaLogService() :
     BnMediaLogService(),
     mMergerShared((NBLog::Shared*) malloc(NBLog::Timeline::sharedSize(kMergeBufferSize))),
     mMerger(mMergerShared, kMergeBufferSize),
     mMergeReader(mMergerShared, kMergeBufferSize, mMerger),
-    mMergeThread(new NBLog::MergeThread(mMerger))
+    mMergeThread(new NBLog::MergeThread(mMerger, mMergeReader))
 {
     mMergeThread->run("MergeThread");
 }
@@ -123,15 +129,10 @@
                 } else {
                     ALOGI("%s:", namedReader.name());
                 }
-                // TODO This code is for testing, remove it when done
-                // namedReader.reader()->dump(fd, 0 /*indent*/);
             }
-
             mLock.unlock();
         }
     }
-
-    // FIXME request merge to make sure log is up to date
     mMergeReader.dump(fd);
     return NO_ERROR;
 }
diff --git a/services/medialog/OWNERS b/services/medialog/OWNERS
index fb8b8ee..21723ba 100644
--- a/services/medialog/OWNERS
+++ b/services/medialog/OWNERS
@@ -1,3 +1,3 @@
 elaurent@google.com
-gkasten@android.com
+gkasten@google.com
 hunga@google.com
diff --git a/services/minijail/OWNERS b/services/minijail/OWNERS
new file mode 100644
index 0000000..19f4f9f
--- /dev/null
+++ b/services/minijail/OWNERS
@@ -0,0 +1,2 @@
+jorgelo@google.com
+marcone@google.com
diff --git a/services/oboeservice/AAudioClientTracker.cpp b/services/oboeservice/AAudioClientTracker.cpp
index 75392bd..a3d5ea1 100644
--- a/services/oboeservice/AAudioClientTracker.cpp
+++ b/services/oboeservice/AAudioClientTracker.cpp
@@ -172,12 +172,12 @@
 
         {
             std::lock_guard<std::mutex> lock(mLock);
-            for (auto serviceStream : mStreams) {
+            for (const auto& serviceStream : mStreams) {
                 streamsToClose.insert(serviceStream);
             }
         }
 
-        for (auto serviceStream : streamsToClose) {
+        for (const auto& serviceStream : streamsToClose) {
             aaudio_handle_t handle = serviceStream->getHandle();
             ALOGW("AAudioClientTracker::binderDied() close abandoned stream 0x%08X\n", handle);
             aaudioService->closeStream(handle);
@@ -200,7 +200,7 @@
     }
 
     result << "  client: pid = " << mProcessId << " has " << mStreams.size() << " streams\n";
-    for (auto serviceStream : mStreams) {
+    for (const auto& serviceStream : mStreams) {
         result << "     stream: 0x" << std::hex << serviceStream->getHandle() << std::dec << "\n";
     }
 
diff --git a/tools/OWNERS b/tools/OWNERS
index 6dcb035..f9cb567 100644
--- a/tools/OWNERS
+++ b/tools/OWNERS
@@ -1 +1 @@
-gkasten@android.com
+gkasten@google.com
diff --git a/tools/resampler_tools/OWNERS b/tools/resampler_tools/OWNERS
new file mode 100644
index 0000000..b4a6798
--- /dev/null
+++ b/tools/resampler_tools/OWNERS
@@ -0,0 +1 @@
+hunga@google.com