Merge "mediautils : TimeCheck: fix OOB access" into rvc-qpr-dev am: fe4cb2de15

Original change: https://googleplex-android-review.googlesource.com/c/platform/frameworks/av/+/13773950

MUST ONLY BE SUBMITTED BY AUTOMERGER

Change-Id: I71127c7a566e4a495152142d5b3bd2812a6981dd
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..9937b98
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,50 @@
+//
+// Copyright (C) 2021 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.
+
+// *** THIS PACKAGE HAS SPECIAL LICENSING CONDITIONS.  PLEASE
+//     CONSULT THE OWNERS AND opensource-licensing@google.com BEFORE
+//     DEPENDING ON IT IN YOUR PROJECT. ***
+package {
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-BSD",
+        "SPDX-license-identifier-MIT",
+        "SPDX-license-identifier-Unicode-DFS",
+        "legacy_by_exception_only", // by exception only
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
diff --git a/METADATA b/METADATA
new file mode 100644
index 0000000..aabda36
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,23 @@
+# *** THIS PACKAGE HAS SPECIAL LICENSING CONDITIONS.  PLEASE
+#     CONSULT THE OWNERS AND opensource-licensing@google.com BEFORE
+#     DEPENDING ON IT IN YOUR PROJECT. ***
+third_party {
+  # would be NOTICE save for Widevine Master License Agreement in:
+  #   drm/mediadrm/plugins/clearkey/hidl/DeviceFiles.cpp
+  #   drm/mediadrm/plugins/clearkey/hidl/MemoryFileSystem.cpp
+  #   drm/mediadrm/plugins/clearkey/hidl/include/DeviceFiles.h
+  #   drm/mediadrm/plugins/clearkey/hidl/protos/DeviceFiles.proto
+  #   drm/mediadrm/plugins/clearkey/hidl/include/MemoryFileSystem.h
+  # and patent disclaimers in:
+  #   media/codec2/components/aac/patent_disclaimer.txt
+  #   media/codec2/components/amr_nb_wb/patent_disclaimer.txt
+  #   media/codec2/components/mp3/patent_disclaimer.txt
+  #   media/codec2/components/mpeg4_h263/patent_disclaimer.txt
+  #   media/codecs/amrnb/patent_disclaimer.txt
+  #   media/codecs/amrwb/dec/patent_disclaimer.txt
+  #   media/codecs/amrwb/enc/patent_disclaimer.txt
+  #   media/codecs/m4v_h263/patent_disclaimer.txt
+  #   media/codecs/mp3dec/patent_disclaimer.txt
+  #   media/libstagefright/codecs/aacenc/patent_disclaimer.txt
+  license_type: BY_EXCEPTION_ONLY
+}
diff --git a/OWNERS b/OWNERS
index 8f405e9..7f523a2 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,4 +1,10 @@
+chz@google.com
 elaurent@google.com
 etalvala@google.com
+hkuang@google.com
 lajos@google.com
 marcone@google.com
+
+# LON
+olly@google.com
+andrewlewis@google.com
diff --git a/apex/Android.bp b/apex/Android.bp
index be6185e..4d194bd 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 apex_defaults {
     name: "com.android.media-defaults",
     updatable: true,
@@ -61,6 +70,15 @@
     name: "com.android.media",
     manifest: "manifest.json",
     defaults: ["com.android.media-defaults"],
+    prebuilts: [
+        "media-linker-config",
+    ],
+}
+
+linker_config {
+    name: "media-linker-config",
+    src: "linker.config.json",
+    installable: false,
 }
 
 filegroup {
diff --git a/apex/linker.config.json b/apex/linker.config.json
new file mode 100644
index 0000000..67c076e
--- /dev/null
+++ b/apex/linker.config.json
@@ -0,0 +1,3 @@
+{
+    "visible": true
+}
diff --git a/apex/manifest_codec.json b/apex/manifest_codec.json
index 2320fd7..1f05d2e 100644
--- a/apex/manifest_codec.json
+++ b/apex/manifest_codec.json
@@ -1,4 +1,7 @@
 {
   "name": "com.android.media.swcodec",
-  "version": 300000000
+  "version": 300000000,
+  "requireNativeLibs": [
+    ":sphal"
+  ]
 }
diff --git a/apex/testing/Android.bp b/apex/testing/Android.bp
index a04ab3f..4ff4d06 100644
--- a/apex/testing/Android.bp
+++ b/apex/testing/Android.bp
@@ -12,12 +12,26 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    //   SPDX-license-identifier-Unicode-DFS
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 apex_test {
     name: "test_com.android.media",
     manifest: "test_manifest.json",
     file_contexts: ":com.android.media-file_contexts",
     defaults: ["com.android.media-defaults"],
-    prebuilts: ["sdkinfo_45"],
+    prebuilts: [
+        "sdkinfo_45",
+        "media-linker-config",
+    ],
     installable: false,
 }
 
diff --git a/camera/Android.bp b/camera/Android.bp
index fa36bb3..93bc68d 100644
--- a/camera/Android.bp
+++ b/camera/Android.bp
@@ -12,6 +12,37 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["frameworks_av_camera_license"],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_camera_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-MIT",
+        "SPDX-license-identifier-Unicode-DFS",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libcamera_client",
 
@@ -50,6 +81,7 @@
     ],
 
     shared_libs: [
+        "libbase",
         "libcutils",
         "libutils",
         "liblog",
diff --git a/camera/CameraParameters.cpp b/camera/CameraParameters.cpp
index 68969cf..e95c91c 100644
--- a/camera/CameraParameters.cpp
+++ b/camera/CameraParameters.cpp
@@ -20,6 +20,7 @@
 
 #include <string.h>
 #include <stdlib.h>
+#include <unistd.h>
 #include <camera/CameraParameters.h>
 #include <system/graphics.h>
 
diff --git a/camera/CameraParameters2.cpp b/camera/CameraParameters2.cpp
index c29233c..a1cf355 100644
--- a/camera/CameraParameters2.cpp
+++ b/camera/CameraParameters2.cpp
@@ -21,6 +21,7 @@
 
 #include <string.h>
 #include <stdlib.h>
+#include <unistd.h>
 #include <camera/CameraParameters2.h>
 
 namespace android {
diff --git a/camera/CameraUtils.cpp b/camera/CameraUtils.cpp
index f9b1b37..af3c492 100644
--- a/camera/CameraUtils.cpp
+++ b/camera/CameraUtils.cpp
@@ -20,14 +20,16 @@
 #include <camera/CameraUtils.h>
 #include <media/hardware/HardwareAPI.h>
 
+#include <android-base/properties.h>
 #include <system/window.h>
 #include <system/graphics.h>
 
-#include <cutils/properties.h>
 #include <utils/Log.h>
 
 namespace android {
 
+const char *kCameraServiceDisabledProperty = "config.disable_cameraservice";
+
 status_t CameraUtils::getRotationTransform(const CameraMetadata& staticInfo,
                 /*out*/int32_t* transform) {
     ALOGV("%s", __FUNCTION__);
@@ -124,9 +126,7 @@
 }
 
 bool CameraUtils::isCameraServiceDisabled() {
-    char value[PROPERTY_VALUE_MAX];
-    property_get("config.disable_cameraservice", value, "0");
-    return (strncmp(value, "0", 2) != 0 && strncasecmp(value, "false", 6) != 0);
+    return base::GetBoolProperty(kCameraServiceDisabledProperty, false);
 }
 
 } /* namespace android */
diff --git a/camera/camera2/CaptureRequest.cpp b/camera/camera2/CaptureRequest.cpp
index 1843ec4..ebc09d7 100644
--- a/camera/camera2/CaptureRequest.cpp
+++ b/camera/camera2/CaptureRequest.cpp
@@ -94,12 +94,12 @@
     // Do not distinguish null arrays from 0-sized arrays.
     for (int32_t i = 0; i < size; ++i) {
         // Parcel.writeParcelableArray
-        size_t len;
-        const char16_t* className = parcel->readString16Inplace(&len);
+        std::optional<std::string> className;
+        parcel->readUtf8FromUtf16(&className);
         ALOGV("%s: Read surface class = %s", __FUNCTION__,
-              className != NULL ? String8(className).string() : "<null>");
+              className.value_or("<null>").c_str());
 
-        if (className == NULL) {
+        if (className == std::nullopt) {
             continue;
         }
 
diff --git a/camera/cameraserver/Android.bp b/camera/cameraserver/Android.bp
index dc7f88a..f58f20c 100644
--- a/camera/cameraserver/Android.bp
+++ b/camera/cameraserver/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_camera_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_camera_license"],
+}
+
 cc_binary {
     name: "cameraserver",
 
@@ -37,7 +46,7 @@
         "android.hardware.camera.device@3.2",
         "android.hardware.camera.device@3.4",
     ],
-    compile_multilib: "32",
+    compile_multilib: "prefer32",
     cflags: [
         "-Wall",
         "-Wextra",
diff --git a/camera/ndk/Android.bp b/camera/ndk/Android.bp
index 7ba82c1..24eaba6 100644
--- a/camera/ndk/Android.bp
+++ b/camera/ndk/Android.bp
@@ -16,6 +16,37 @@
 // to refer to headers in parent directories and the headers live in
 // frameworks/av/include.
 
+package {
+    default_applicable_licenses: ["frameworks_av_camera_ndk_license"],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_camera_ndk_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-MIT",
+        "SPDX-license-identifier-Unicode-DFS",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 ndk_library {
     name: "libcamera2ndk",
     symbol_file: "libcamera2ndk.map.txt",
diff --git a/camera/ndk/impl/ACameraManager.cpp b/camera/ndk/impl/ACameraManager.cpp
index 2cba665..73cabbf 100644
--- a/camera/ndk/impl/ACameraManager.cpp
+++ b/camera/ndk/impl/ACameraManager.cpp
@@ -738,7 +738,7 @@
     // No way to get package name from native.
     // Send a zero length package name and let camera service figure it out from UID
     binder::Status serviceRet = cs->connectDevice(
-            callbacks, String16(cameraId), String16(""), std::unique_ptr<String16>(),
+            callbacks, String16(cameraId), String16(""), {},
             hardware::ICameraService::USE_CALLING_UID, /*out*/&deviceRemote);
 
     if (!serviceRet.isOk()) {
diff --git a/camera/ndk/include/camera/NdkCameraCaptureSession.h b/camera/ndk/include/camera/NdkCameraCaptureSession.h
index 07176cf..6c1cf33 100644
--- a/camera/ndk/include/camera/NdkCameraCaptureSession.h
+++ b/camera/ndk/include/camera/NdkCameraCaptureSession.h
@@ -45,8 +45,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraCaptureSession is an opaque type that manages frame captures of a camera device.
  *
@@ -593,10 +591,6 @@
 camera_status_t ACameraCaptureSession_abortCaptures(ACameraCaptureSession* session)
         __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 28
-
 typedef struct ACaptureSessionOutput ACaptureSessionOutput;
 
 /**
@@ -641,9 +635,7 @@
  */
 camera_status_t ACameraCaptureSession_updateSharedOutput(ACameraCaptureSession* session,
         ACaptureSessionOutput* output) __INTRODUCED_IN(28);
-#endif /* __ANDROID_API__ >= 28 */
 
-#if __ANDROID_API__ >= 29
 /**
  * The definition of final capture result callback with logical multi-camera support.
  *
@@ -788,8 +780,6 @@
         int numRequests, ACaptureRequest** requests,
         /*optional*/int* captureSequenceId) __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_CAPTURE_SESSION_H */
diff --git a/camera/ndk/include/camera/NdkCameraDevice.h b/camera/ndk/include/camera/NdkCameraDevice.h
index 1537bde..f72fe8d 100644
--- a/camera/ndk/include/camera/NdkCameraDevice.h
+++ b/camera/ndk/include/camera/NdkCameraDevice.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraDevice is opaque type that provides access to a camera device.
  *
@@ -687,10 +685,6 @@
         const ACameraCaptureSession_stateCallbacks* callbacks,
         /*out*/ACameraCaptureSession** session) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 28
-
 /**
  * Create a shared ACaptureSessionOutput object.
  *
@@ -782,10 +776,6 @@
         const ACameraCaptureSession_stateCallbacks* callbacks,
         /*out*/ACameraCaptureSession** session) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Create a ACaptureSessionOutput object used for streaming from a physical
  * camera as part of a logical camera device.
@@ -890,8 +880,6 @@
         const ACameraDevice* device,
         const ACaptureSessionOutputContainer* sessionOutputContainer) __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_DEVICE_H */
diff --git a/camera/ndk/include/camera/NdkCameraError.h b/camera/ndk/include/camera/NdkCameraError.h
index fc618ee..9d77eb4 100644
--- a/camera/ndk/include/camera/NdkCameraError.h
+++ b/camera/ndk/include/camera/NdkCameraError.h
@@ -40,8 +40,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 typedef enum {
     ACAMERA_OK = 0,
 
@@ -138,8 +136,6 @@
     ACAMERA_ERROR_UNSUPPORTED_OPERATION = ACAMERA_ERROR_BASE - 14,
 } camera_status_t;
 
-#endif /* __ANDROID_API__ >= 24 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_ERROR_H */
diff --git a/camera/ndk/include/camera/NdkCameraManager.h b/camera/ndk/include/camera/NdkCameraManager.h
index 0a2ee57..be32b11 100644
--- a/camera/ndk/include/camera/NdkCameraManager.h
+++ b/camera/ndk/include/camera/NdkCameraManager.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraManager is opaque type that provides access to camera service.
  *
@@ -293,10 +291,6 @@
         ACameraDevice_StateCallbacks* callback,
         /*out*/ACameraDevice** device) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Definition of camera access permission change callback.
  *
@@ -419,8 +413,6 @@
         __INTRODUCED_IN(29);
 #endif
 
-#endif /* __ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_MANAGER_H */
diff --git a/camera/ndk/include/camera/NdkCameraMetadata.h b/camera/ndk/include/camera/NdkCameraMetadata.h
index 072bb02..0d5e6c4 100644
--- a/camera/ndk/include/camera/NdkCameraMetadata.h
+++ b/camera/ndk/include/camera/NdkCameraMetadata.h
@@ -36,13 +36,12 @@
 #ifndef _NDK_CAMERA_METADATA_H
 #define _NDK_CAMERA_METADATA_H
 
+#include <stdbool.h>
 #include <stdint.h>
 #include <sys/cdefs.h>
 
 #ifndef __ANDROID_VNDK__
-#if __ANDROID_API__ >= 30
 #include "jni.h"
-#endif  /* __ANDROID_API__ >= 30 */
 #endif  /* __ANDROID_VNDK__ */
 
 #include "NdkCameraError.h"
@@ -50,8 +49,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraMetadata is opaque type that provides access to read-only camera metadata like camera
  * characteristics (via {@link ACameraManager_getCameraCharacteristics}) or capture results (via
@@ -237,10 +234,6 @@
  */
 void ACameraMetadata_free(ACameraMetadata* metadata) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Helper function to check if a camera is logical multi-camera.
  *
@@ -259,10 +252,7 @@
         /*out*/size_t* numPhysicalCameras, /*out*/const char* const** physicalCameraIds)
         __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
 #ifndef __ANDROID_VNDK__
-#if __ANDROID_API__ >= 30
 
 /**
  * Return a {@link ACameraMetadata} that references the same data as
@@ -289,7 +279,6 @@
 ACameraMetadata* ACameraMetadata_fromCameraMetadata(JNIEnv* env, jobject cameraMetadata)
         __INTRODUCED_IN(30);
 
-#endif /* __ANDROID_API__ >= 30 */
 #endif  /* __ANDROID_VNDK__ */
 
 __END_DECLS
diff --git a/camera/ndk/include/camera/NdkCameraMetadataTags.h b/camera/ndk/include/camera/NdkCameraMetadataTags.h
index 5634982..bc33d6a 100644
--- a/camera/ndk/include/camera/NdkCameraMetadataTags.h
+++ b/camera/ndk/include/camera/NdkCameraMetadataTags.h
@@ -40,8 +40,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 typedef enum acamera_metadata_section {
     ACAMERA_COLOR_CORRECTION,
     ACAMERA_CONTROL,
@@ -8998,8 +8996,6 @@
 
 
 
-#endif /* __ANDROID_API__ >= 24 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_METADATA_TAGS_H */
diff --git a/camera/ndk/include/camera/NdkCaptureRequest.h b/camera/ndk/include/camera/NdkCaptureRequest.h
index d3f8826..a4dc374 100644
--- a/camera/ndk/include/camera/NdkCaptureRequest.h
+++ b/camera/ndk/include/camera/NdkCaptureRequest.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 // Container for output targets
 typedef struct ACameraOutputTargets ACameraOutputTargets;
 
@@ -304,10 +302,6 @@
  */
 void ACaptureRequest_free(ACaptureRequest* request) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 28
-
 /**
  * Associate an arbitrary user context pointer to the {@link ACaptureRequest}
  *
@@ -356,10 +350,6 @@
  */
 ACaptureRequest* ACaptureRequest_copy(const ACaptureRequest* src) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Get a metadata entry from input {@link ACaptureRequest} for
  * a physical camera backing a logical multi-camera device.
@@ -569,8 +559,6 @@
         ACaptureRequest* request, const char* physicalId, uint32_t tag,
         uint32_t count, const ACameraMetadata_rational* data) __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif /* _NDK_CAPTURE_REQUEST_H */
diff --git a/camera/tests/Android.mk b/camera/tests/Android.mk
index e5c1631..7f8078e 100644
--- a/camera/tests/Android.mk
+++ b/camera/tests/Android.mk
@@ -42,6 +42,9 @@
 LOCAL_CFLAGS += -Wall -Wextra -Werror
 
 LOCAL_MODULE:= camera_client_test
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/../NOTICE
 LOCAL_MODULE_TAGS := tests
 
 include $(BUILD_NATIVE_TEST)
diff --git a/camera/tests/CameraBinderTests.cpp b/camera/tests/CameraBinderTests.cpp
index 8ccded2..eee05ff 100644
--- a/camera/tests/CameraBinderTests.cpp
+++ b/camera/tests/CameraBinderTests.cpp
@@ -378,7 +378,7 @@
         sp<TestCameraDeviceCallbacks> callbacks(new TestCameraDeviceCallbacks());
         sp<hardware::camera2::ICameraDeviceUser> device;
         res = service->connectDevice(callbacks, cameraId, String16("meeeeeeeee!"),
-                std::unique_ptr<String16>(), hardware::ICameraService::USE_CALLING_UID,
+                {}, hardware::ICameraService::USE_CALLING_UID,
                 /*out*/&device);
         EXPECT_TRUE(res.isOk()) << res;
         ASSERT_NE(nullptr, device.get());
@@ -421,7 +421,7 @@
         {
             SCOPED_TRACE("openNewDevice");
             binder::Status res = service->connectDevice(callbacks, deviceId, String16("meeeeeeeee!"),
-                    std::unique_ptr<String16>(), hardware::ICameraService::USE_CALLING_UID,
+                    {}, hardware::ICameraService::USE_CALLING_UID,
                     /*out*/&device);
             EXPECT_TRUE(res.isOk()) << res;
         }
diff --git a/cmds/screenrecord/Android.bp b/cmds/screenrecord/Android.bp
index d7d905f..359a835 100644
--- a/cmds/screenrecord/Android.bp
+++ b/cmds/screenrecord/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_binary {
     name: "screenrecord",
 
diff --git a/cmds/stagefright/Android.mk b/cmds/stagefright/Android.mk
index 6470fb1..ef4c568 100644
--- a/cmds/stagefright/Android.mk
+++ b/cmds/stagefright/Android.mk
@@ -28,6 +28,9 @@
 
 LOCAL_SYSTEM_EXT_MODULE:= true
 LOCAL_MODULE:= stagefright
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE
 
 include $(BUILD_EXECUTABLE)
 
@@ -58,6 +61,9 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE:= record
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE
 
 include $(BUILD_EXECUTABLE)
 
@@ -86,6 +92,9 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE:= recordvideo
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE
 
 include $(BUILD_EXECUTABLE)
 
@@ -115,6 +124,9 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE:= audioloop
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE
 
 include $(BUILD_EXECUTABLE)
 
@@ -141,6 +153,9 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE:= stream
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE
 
 include $(BUILD_EXECUTABLE)
 
@@ -169,6 +184,9 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE:= codec
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE
 
 include $(BUILD_EXECUTABLE)
 
@@ -214,6 +232,9 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE:= mediafilter
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE
 
 LOCAL_SANITIZE := cfi
 
@@ -242,5 +263,8 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE:= muxer
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE
 
 include $(BUILD_EXECUTABLE)
diff --git a/cmds/stagefright/AudioPlayer.cpp b/cmds/stagefright/AudioPlayer.cpp
index eb76953..55427ca 100644
--- a/cmds/stagefright/AudioPlayer.cpp
+++ b/cmds/stagefright/AudioPlayer.cpp
@@ -134,15 +134,18 @@
     success = format->findInt32(kKeySampleRate, &mSampleRate);
     CHECK(success);
 
-    int32_t numChannels, channelMask;
+    int32_t numChannels;
     success = format->findInt32(kKeyChannelCount, &numChannels);
     CHECK(success);
 
-    if(!format->findInt32(kKeyChannelMask, &channelMask)) {
+    audio_channel_mask_t channelMask;
+    if (int32_t rawChannelMask; !format->findInt32(kKeyChannelMask, &rawChannelMask)) {
         // log only when there's a risk of ambiguity of channel mask selection
         ALOGI_IF(numChannels > 2,
                 "source format didn't specify channel mask, using (%d) channel order", numChannels);
         channelMask = CHANNEL_MASK_USE_CHANNEL_ORDER;
+    } else {
+        channelMask = static_cast<audio_channel_mask_t>(rawChannelMask);
     }
 
     audio_format_t audioFormat = AUDIO_FORMAT_PCM_16_BIT;
diff --git a/drm/common/Android.bp b/drm/common/Android.bp
index 248570e..76ee22e 100644
--- a/drm/common/Android.bp
+++ b/drm/common/Android.bp
@@ -14,6 +14,23 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["frameworks_av_drm_common_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_drm_common_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libdrmframeworkcommon",
 
diff --git a/drm/common/include/DrmEngineBase.h b/drm/common/include/DrmEngineBase.h
index 73f11a4..c0a5e3b 100644
--- a/drm/common/include/DrmEngineBase.h
+++ b/drm/common/include/DrmEngineBase.h
@@ -309,7 +309,7 @@
 
     /**
      * Removes all the rights information of each plug-in associated with
-     * DRM framework. Will be used in master reset
+     * DRM framework.
      *
      * @param[in] uniqueId Unique identifier for a session
      * @return status_t
diff --git a/drm/common/include/IDrmEngine.h b/drm/common/include/IDrmEngine.h
index 1837a11..a545941 100644
--- a/drm/common/include/IDrmEngine.h
+++ b/drm/common/include/IDrmEngine.h
@@ -250,7 +250,7 @@
 
     /**
      * Removes all the rights information of each plug-in associated with
-     * DRM framework. Will be used in master reset
+     * DRM framework.
      *
      * @param[in] uniqueId Unique identifier for a session
      * @return status_t
diff --git a/drm/drmserver/Android.bp b/drm/drmserver/Android.bp
index 141fe70..df3a6a2 100644
--- a/drm/drmserver/Android.bp
+++ b/drm/drmserver/Android.bp
@@ -14,6 +14,23 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["frameworks_av_drm_drmserver_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_drm_drmserver_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_binary {
     name: "drmserver",
 
@@ -42,7 +59,7 @@
         "-Werror",
     ],
 
-    compile_multilib: "32",
+    compile_multilib: "prefer32",
 
     init_rc: ["drmserver.rc"],
 }
diff --git a/drm/drmserver/DrmManager.cpp b/drm/drmserver/DrmManager.cpp
index 9a32cc5..74e3223 100644
--- a/drm/drmserver/DrmManager.cpp
+++ b/drm/drmserver/DrmManager.cpp
@@ -99,13 +99,13 @@
         }
         default:
         {
-            ALOGW("Unrecognized message type: %zd", msg->what());
+            ALOGW("Unrecognized message type: %u", msg->what());
         }
     }
 }
 
 int64_t DrmManager::getMetricsFlushPeriodUs() {
-    return 1000 * 1000 * std::max(1ll, property_get_int64("drmmanager.metrics.period", 86400));
+    return 1000 * 1000 * std::max(1ll, (long long)property_get_int64("drmmanager.metrics.period", 86400));
 }
 
 void DrmManager::recordEngineMetrics(
diff --git a/drm/libdrmframework/Android.bp b/drm/libdrmframework/Android.bp
index b4a7b25..dbce5ea 100644
--- a/drm/libdrmframework/Android.bp
+++ b/drm/libdrmframework/Android.bp
@@ -14,6 +14,23 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["frameworks_av_drm_libdrmframework_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_drm_libdrmframework_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libdrmframework",
 
@@ -37,4 +54,3 @@
 
     cflags: ["-Werror"],
 }
-
diff --git a/drm/libdrmframework/include/DrmManagerClientImpl.h b/drm/libdrmframework/include/DrmManagerClientImpl.h
index 3858675..8c8783b 100644
--- a/drm/libdrmframework/include/DrmManagerClientImpl.h
+++ b/drm/libdrmframework/include/DrmManagerClientImpl.h
@@ -230,7 +230,7 @@
 
     /**
      * Removes all the rights information of each plug-in associated with
-     * DRM framework. Will be used in master reset
+     * DRM framework.
      *
      * @param[in] uniqueId Unique identifier for a session
      * @return status_t
diff --git a/drm/libdrmframework/plugins/common/util/Android.bp b/drm/libdrmframework/plugins/common/util/Android.bp
index 7372eb7..a47b4a1 100644
--- a/drm/libdrmframework/plugins/common/util/Android.bp
+++ b/drm/libdrmframework/plugins/common/util/Android.bp
@@ -14,6 +14,25 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: [
+        "frameworks_av_drm_libdrmframework_plugins_common_util_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_drm_libdrmframework_plugins_common_util_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_static {
     name: "libdrmutility",
 
diff --git a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.bp b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.bp
index 9f52f7a..be2b546 100644
--- a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.bp
+++ b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.bp
@@ -14,6 +14,25 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: [
+        "frameworks_av_drm_libdrmframework_plugins_forward-lock_FwdLockEngine_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_drm_libdrmframework_plugins_forward-lock_FwdLockEngine_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libfwdlockengine",
 
diff --git a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/include/FwdLockEngine.h b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/include/FwdLockEngine.h
index b62ddb9..eb5b0f6 100644
--- a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/include/FwdLockEngine.h
+++ b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/include/FwdLockEngine.h
@@ -252,8 +252,7 @@
 
 /**
  * Removes all the rights information of each plug-in associated with
- * DRM framework. Will be used in master reset but does nothing for
- * Forward Lock Engine.
+ * DRM framework. Does nothing for Forward Lock Engine.
  *
  * @param uniqueId Unique identifier for a session
  * @return status_t
diff --git a/drm/libdrmframework/plugins/forward-lock/internal-format/common/Android.bp b/drm/libdrmframework/plugins/forward-lock/internal-format/common/Android.bp
index 3be327a..2e4070b 100644
--- a/drm/libdrmframework/plugins/forward-lock/internal-format/common/Android.bp
+++ b/drm/libdrmframework/plugins/forward-lock/internal-format/common/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_drm_libdrmframework_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_drm_libdrmframework_license"],
+}
+
 cc_library_static {
     name: "libfwdlock-common",
 
diff --git a/drm/libdrmframework/plugins/forward-lock/internal-format/converter/Android.bp b/drm/libdrmframework/plugins/forward-lock/internal-format/converter/Android.bp
index d4e04b8..51c778f 100644
--- a/drm/libdrmframework/plugins/forward-lock/internal-format/converter/Android.bp
+++ b/drm/libdrmframework/plugins/forward-lock/internal-format/converter/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_drm_libdrmframework_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_drm_libdrmframework_license"],
+}
+
 cc_library_static {
     name: "libfwdlock-converter",
 
diff --git a/drm/libdrmframework/plugins/forward-lock/internal-format/decoder/Android.bp b/drm/libdrmframework/plugins/forward-lock/internal-format/decoder/Android.bp
index 0bf2737..6773fe1 100644
--- a/drm/libdrmframework/plugins/forward-lock/internal-format/decoder/Android.bp
+++ b/drm/libdrmframework/plugins/forward-lock/internal-format/decoder/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_drm_libdrmframework_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_drm_libdrmframework_license"],
+}
+
 cc_library_static {
     name: "libfwdlock-decoder",
 
diff --git a/drm/libdrmframework/plugins/forward-lock/internal-format/doc/FwdLock.html b/drm/libdrmframework/plugins/forward-lock/internal-format/doc/FwdLock.html
index 8f95cd2..c1d5b3d 100644
--- a/drm/libdrmframework/plugins/forward-lock/internal-format/doc/FwdLock.html
+++ b/drm/libdrmframework/plugins/forward-lock/internal-format/doc/FwdLock.html
@@ -488,7 +488,7 @@
 <p class=MsoBodyText><b>Note:</b> The key-encryption key must be unique to each
 device; this is what makes the files forward lock–protected. Ideally, it should
 be derived from secret hardware parameters, but at the very least it should be
-persistent from one master reset to the next.</p>
+persistent from one factory reset to the next.</p>
 
 <div style='margin-bottom:24.0pt;border:solid windowtext 1.0pt;padding:1.0pt 4.0pt 1.0pt 4.0pt;
 background:#F2F2F2'>
diff --git a/drm/libdrmframework/plugins/passthru/Android.bp b/drm/libdrmframework/plugins/passthru/Android.bp
index 8045586..6dffd49 100644
--- a/drm/libdrmframework/plugins/passthru/Android.bp
+++ b/drm/libdrmframework/plugins/passthru/Android.bp
@@ -14,6 +14,25 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: [
+        "frameworks_av_drm_libdrmframework_plugins_passthru_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_drm_libdrmframework_plugins_passthru_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libdrmpassthruplugin",
 
diff --git a/drm/libmediadrm/Android.bp b/drm/libmediadrm/Android.bp
index 1700a95..a82a61d 100644
--- a/drm/libmediadrm/Android.bp
+++ b/drm/libmediadrm/Android.bp
@@ -2,6 +2,15 @@
 // libmediadrm
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libmediadrm_headers",
 
@@ -11,7 +20,7 @@
 
 }
 
-cc_library_shared {
+cc_library {
     name: "libmediadrm",
 
     srcs: [
diff --git a/drm/libmediadrm/DrmSessionManager.cpp b/drm/libmediadrm/DrmSessionManager.cpp
index 5292705..e31395d 100644
--- a/drm/libmediadrm/DrmSessionManager.cpp
+++ b/drm/libmediadrm/DrmSessionManager.cpp
@@ -66,7 +66,7 @@
     std::vector<MediaResourceParcel> resources;
     MediaResourceParcel resource{
             Type::kDrmSession, SubType::kUnspecifiedSubType,
-            toStdVec<int8_t>(sessionId), value};
+            toStdVec<>(sessionId), value};
     resources.push_back(resource);
     return resources;
 }
diff --git a/drm/libmediadrm/fuzzer/Android.bp b/drm/libmediadrm/fuzzer/Android.bp
new file mode 100644
index 0000000..2b04702
--- /dev/null
+++ b/drm/libmediadrm/fuzzer/Android.bp
@@ -0,0 +1,68 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_fuzz {
+    name: "mediadrm_fuzzer",
+    srcs: [
+        "mediadrm_fuzzer.cpp",
+    ],
+    static_libs: [
+        "libmediadrm",
+        "liblog",
+        "resourcemanager_aidl_interface-ndk_platform",
+    ],
+    header_libs: [
+        "libmedia_headers",
+        "libmediadrm_headers",
+    ],
+    shared_libs: [
+        "libbinder",
+        "libutils",
+        "libbinder_ndk",
+        "libcutils",
+        "libdl",
+        "libmedia",
+        "libmediadrmmetrics_lite",
+        "libmediametrics#1",
+        "libmediautils",
+        "libstagefright_foundation",
+        "android.hardware.drm@1.0",
+        "android.hardware.drm@1.1",
+        "android.hardware.drm@1.2",
+        "android.hardware.drm@1.3",
+        "libhidlallocatorutils",
+        "libhidlbase",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
diff --git a/drm/libmediadrm/fuzzer/README.md b/drm/libmediadrm/fuzzer/README.md
new file mode 100644
index 0000000..3c95cd7
--- /dev/null
+++ b/drm/libmediadrm/fuzzer/README.md
@@ -0,0 +1,56 @@
+# Fuzzer for libmediadrm
+
+## Plugin Design Considerations
+The fuzzer plugin for libmediadrm is designed based on the understanding of the
+library and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+libmediadrm supports the following parameters:
+1. Security Level (parameter name: `securityLevel`)
+2. Mime Type (parameter name: `mimeType`)
+3. Key Type (parameter name: `keyType`)
+4. Crypto Mode (parameter name: `cryptoMode`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `securityLevel` | 0.`DrmPlugin::kSecurityLevelUnknown` 1.`DrmPlugin::kSecurityLevelMax` 2.`DrmPlugin::kSecurityLevelSwSecureCrypto` 3.`DrmPlugin::kSecurityLevelSwSecureDecode`  4.`DrmPlugin::kSecurityLevelHwSecureCrypto` 5.`DrmPlugin::kSecurityLevelHwSecureDecode` 6.`DrmPlugin::kSecurityLevelHwSecureAll`| Value obtained from FuzzedDataProvider in the range 0 to 6|
+| `mimeType` | 0.`video/mp4` 1.`video/mpeg` 2.`video/x-flv` 3.`video/mj2` 4.`video/3gp2` 5.`video/3gpp` 6.`video/3gpp2` 7.`audio/mp4` 8.`audio/mpeg` 9.`audio/aac` 10.`audio/3gp2` 11.`audio/3gpp` 12.`audio/3gpp2` 13.`video/unknown`| Value obtained from FuzzedDataProvider in the range 0 to 13|
+| `keyType` | 0.`DrmPlugin::kKeyType_Offline` 1.`DrmPlugin::kKeyType_Streaming` 2.`DrmPlugin::kKeyType_Release` | Value obtained from FuzzedDataProvider in the range 0 to 2|
+| `cryptoMode` | 0.`CryptoPlugin::kMode_Unencrypted` 1.`CryptoPlugin::kMode_AES_CTR` 2.`CryptoPlugin::kMode_AES_WV` 3.`CryptoPlugin::kMode_AES_CBC` | Value obtained from FuzzedDataProvider in the range 0 to 3|
+
+This also ensures that the plugin is always deterministic for any given input.
+
+##### Maximize utilization of input data
+The plugin feeds the entire input data to the drm module.
+This ensures that the plugin tolerates any kind of input (empty, huge,
+malformed, etc) and doesnt `exit()` on any input and thereby increasing the
+chance of identifying vulnerabilities.
+
+## Build
+
+This describes steps to build mediadrm_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mediadrm_fuzzer
+```
+#### Steps to run
+Create a directory CORPUS_DIR
+```
+  $ adb shell mkdir CORPUS_DIR
+```
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/${TARGET_ARCH}/mediadrm_fuzzer/mediadrm_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/drm/libmediadrm/fuzzer/mediadrm_fuzzer.cpp b/drm/libmediadrm/fuzzer/mediadrm_fuzzer.cpp
new file mode 100644
index 0000000..8df0477
--- /dev/null
+++ b/drm/libmediadrm/fuzzer/mediadrm_fuzzer.cpp
@@ -0,0 +1,458 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include <binder/MemoryDealer.h>
+#include <hidlmemory/FrameworkUtils.h>
+#include <mediadrm/CryptoHal.h>
+#include <mediadrm/DrmHal.h>
+#include <utils/String8.h>
+#include "fuzzer/FuzzedDataProvider.h"
+
+#define AES_BLOCK_SIZE 16
+#define UNUSED_PARAM __attribute__((unused))
+
+using namespace std;
+using namespace android;
+using android::hardware::fromHeap;
+using ::android::os::PersistableBundle;
+using drm::V1_0::BufferType;
+
+enum {
+    INVALID_UUID = 0,
+    PSSH_BOX_UUID,
+    CLEARKEY_UUID,
+};
+
+static const uint8_t kInvalidUUID[16] = {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80,
+                                         0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80};
+
+static const uint8_t kCommonPsshBoxUUID[16] = {0x10, 0x77, 0xEF, 0xEC, 0xC0, 0xB2, 0x4D, 0x02,
+                                               0xAC, 0xE3, 0x3C, 0x1E, 0x52, 0xE2, 0xFB, 0x4B};
+
+static const uint8_t kClearKeyUUID[16] = {0xE2, 0x71, 0x9D, 0x58, 0xA9, 0x85, 0xB3, 0xC9,
+                                          0x78, 0x1A, 0xB0, 0x30, 0xAF, 0x78, 0xD3, 0x0E};
+
+static const uint32_t kUUID[] = {INVALID_UUID, PSSH_BOX_UUID, CLEARKEY_UUID};
+
+const DrmPlugin::SecurityLevel kSecurityLevel[] = {
+    DrmPlugin::kSecurityLevelUnknown,        DrmPlugin::kSecurityLevelMax,
+    DrmPlugin::kSecurityLevelSwSecureCrypto, DrmPlugin::kSecurityLevelSwSecureDecode,
+    DrmPlugin::kSecurityLevelHwSecureCrypto, DrmPlugin::kSecurityLevelHwSecureDecode,
+    DrmPlugin::kSecurityLevelHwSecureAll};
+
+const char *kMimeType[] = {"video/mp4",   "video/mpeg",    "video/x-flv",  "video/mj2",
+                           "video/3gp2",  "video/3gpp",    "video/3gpp2",  "audio/mp4",
+                           "audio/mpeg",  "audio/aac",     "audio/3gp2",   "audio/3gpp",
+                           "audio/3gpp2", "video/unknown", "audio/unknown"};
+
+const DrmPlugin::KeyType kKeyType[] = {DrmPlugin::kKeyType_Offline, DrmPlugin::kKeyType_Streaming,
+                                       DrmPlugin::kKeyType_Release};
+
+const CryptoPlugin::Mode kCryptoMode[] = {CryptoPlugin::kMode_Unencrypted,
+                                          CryptoPlugin::kMode_AES_CTR, CryptoPlugin::kMode_AES_WV,
+                                          CryptoPlugin::kMode_AES_CBC};
+
+const char *kCipherAlgorithm[] = {"AES/CBC/NoPadding", ""};
+const char *kMacAlgorithm[] = {"HmacSHA256", ""};
+const char *kRSAAlgorithm[] = {"RSASSA-PSS-SHA1", ""};
+const size_t kNumSecurityLevel = size(kSecurityLevel);
+const size_t kNumMimeType = size(kMimeType);
+const size_t kNumKeyType = size(kKeyType);
+const size_t kNumCryptoMode = size(kCryptoMode);
+const size_t kNumUUID = size(kUUID);
+const size_t kMaxStringLength = 100;
+const size_t kMaxSubSamples = 10;
+const size_t kMaxNumBytes = 1000;
+
+struct DrmListener : virtual public IDrmClient {
+   public:
+    void sendEvent(DrmPlugin::EventType eventType UNUSED_PARAM,
+                   const hardware::hidl_vec<uint8_t> &sessionId UNUSED_PARAM,
+                   const hardware::hidl_vec<uint8_t> &data UNUSED_PARAM) override {}
+
+    void sendExpirationUpdate(const hardware::hidl_vec<uint8_t> &sessionId UNUSED_PARAM,
+                              int64_t expiryTimeInMS UNUSED_PARAM) override {}
+
+    void sendKeysChange(const hardware::hidl_vec<uint8_t> &sessionId UNUSED_PARAM,
+                        const std::vector<DrmKeyStatus> &keyStatusList UNUSED_PARAM,
+                        bool hasNewUsableKey UNUSED_PARAM) override {}
+
+    void sendSessionLostState(const hardware::hidl_vec<uint8_t> &) override {}
+    DrmListener() {}
+
+   private:
+    DISALLOW_EVIL_CONSTRUCTORS(DrmListener);
+};
+
+class DrmFuzzer {
+   public:
+    void process(const uint8_t *data, size_t size);
+
+   private:
+    void invokeDrm(const uint8_t *data, size_t size);
+    bool initDrm();
+    void invokeDrmCreatePlugin();
+    void invokeDrmOpenSession();
+    void invokeDrmSetListener();
+    void invokeDrmSetAlgorithmAPI();
+    void invokeDrmPropertyAPI();
+    void invokeDrmDecryptEncryptAPI(const uint8_t *data, size_t size);
+    void invokeDrmSecureStopAPI();
+    void invokeDrmOfflineLicenseAPI();
+    void invokeDrmCloseSession();
+    void invokeDrmDestroyPlugin();
+    void invokeCrypto(const uint8_t *data);
+    bool initCrypto();
+    void invokeCryptoCreatePlugin();
+    void invokeCryptoDecrypt(const uint8_t *data);
+    void invokeCryptoDestroyPlugin();
+    sp<DrmHal> mDrm = nullptr;
+    sp<CryptoHal> mCrypto = nullptr;
+    Vector<uint8_t> mSessionId = {};
+    FuzzedDataProvider *mFuzzedDataProvider = nullptr;
+};
+
+bool DrmFuzzer::initDrm() {
+    mDrm = new DrmHal();
+    if (!mDrm) {
+        return false;
+    }
+    return true;
+}
+
+void DrmFuzzer::invokeDrmCreatePlugin() {
+    mDrm->initCheck();
+    String8 packageName(mFuzzedDataProvider->ConsumeRandomLengthString(kMaxStringLength).c_str());
+    uint32_t uuidEnum = kUUID[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(0, kNumUUID - 1)];
+    switch (uuidEnum) {
+        case INVALID_UUID:
+            mDrm->createPlugin(kInvalidUUID, packageName);
+            break;
+        case PSSH_BOX_UUID:
+            mDrm->createPlugin(kCommonPsshBoxUUID, packageName);
+            break;
+        case CLEARKEY_UUID:
+            mDrm->createPlugin(kClearKeyUUID, packageName);
+            break;
+        default:
+            break;
+    }
+}
+
+void DrmFuzzer::invokeDrmDestroyPlugin() { mDrm->destroyPlugin(); }
+
+void DrmFuzzer::invokeDrmOpenSession() {
+    DrmPlugin::SecurityLevel securityLevel;
+    bool shouldPassRandomSecurityLevel = mFuzzedDataProvider->ConsumeBool();
+    if (shouldPassRandomSecurityLevel) {
+        securityLevel =
+            static_cast<DrmPlugin::SecurityLevel>(mFuzzedDataProvider->ConsumeIntegral<size_t>());
+    } else {
+        securityLevel = kSecurityLevel[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(
+            0, kNumSecurityLevel - 1)];
+    }
+    mDrm->openSession(securityLevel, mSessionId);
+}
+
+void DrmFuzzer::invokeDrmCloseSession() { mDrm->closeSession(mSessionId); }
+
+void DrmFuzzer::invokeDrmSetListener() {
+    sp<DrmListener> listener = new DrmListener();
+    mDrm->setListener(listener);
+}
+
+void DrmFuzzer::invokeDrmSetAlgorithmAPI() {
+    mDrm->setCipherAlgorithm(mSessionId,
+                             String8(kCipherAlgorithm[mFuzzedDataProvider->ConsumeBool()]));
+    mDrm->setMacAlgorithm(mSessionId, String8(kMacAlgorithm[mFuzzedDataProvider->ConsumeBool()]));
+}
+
+void DrmFuzzer::invokeDrmPropertyAPI() {
+    mDrm->setPropertyString(String8("property"), String8("value"));
+    String8 stringValue;
+    mDrm->getPropertyString(String8("property"), stringValue);
+    Vector<uint8_t> value = {};
+    mDrm->setPropertyByteArray(String8("property"), value);
+    Vector<uint8_t> byteValue;
+    mDrm->getPropertyByteArray(String8("property"), byteValue);
+}
+
+void DrmFuzzer::invokeDrmDecryptEncryptAPI(const uint8_t *data, size_t size) {
+    uint32_t openSessions = 0;
+    uint32_t maxSessions = 0;
+    mDrm->getNumberOfSessions(&openSessions, &maxSessions);
+
+    DrmPlugin::HdcpLevel connected;
+    DrmPlugin::HdcpLevel max;
+    mDrm->getHdcpLevels(&connected, &max);
+
+    DrmPlugin::SecurityLevel securityLevel;
+    mDrm->getSecurityLevel(mSessionId, &securityLevel);
+
+    // isCryptoSchemeSupported() shall fill isSupported
+    bool isSupported;
+    String8 mimeType(
+        kMimeType[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(0, kNumMimeType - 1)]);
+    mDrm->isCryptoSchemeSupported(kClearKeyUUID, mimeType, securityLevel, &isSupported);
+
+    // getProvisionRequest() shall fill legacyRequest and legacyDefaultUrl
+    String8 certificateType(
+        mFuzzedDataProvider->ConsumeRandomLengthString(kMaxStringLength).c_str());
+    String8 certAuthority(mFuzzedDataProvider->ConsumeRandomLengthString(kMaxStringLength).c_str());
+    Vector<uint8_t> legacyRequest = {};
+    String8 legacyDefaultUrl;
+    mDrm->getProvisionRequest(certificateType, certAuthority, legacyRequest, legacyDefaultUrl);
+
+    // provideProvisionResponse() shall fill certificate and wrappedKey
+    Vector<uint8_t> provisionResponse = {};
+    Vector<uint8_t> certificate = {};
+    Vector<uint8_t> wrappedKey = {};
+    mDrm->provideProvisionResponse(provisionResponse, certificate, wrappedKey);
+
+    // getKeyRequest() shall fill keyRequest, defaultUrl and keyRequestType
+    Vector<uint8_t> initData = {};
+    initData.appendArray(data, size);
+    DrmPlugin::KeyType keyType;
+    bool shouldPassRandomKeyType = mFuzzedDataProvider->ConsumeBool();
+    if (shouldPassRandomKeyType) {
+        keyType = static_cast<DrmPlugin::KeyType>(mFuzzedDataProvider->ConsumeIntegral<size_t>());
+    } else {
+        keyType = kKeyType[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(0, kNumKeyType - 1)];
+    }
+    KeyedVector<String8, String8> mdOptionalParameters = {};
+    Vector<uint8_t> keyRequest = {};
+    String8 defaultUrl;
+    DrmPlugin::KeyRequestType keyRequestType;
+    mDrm->getKeyRequest(mSessionId, initData, mimeType, keyType, mdOptionalParameters, keyRequest,
+                        defaultUrl, &keyRequestType);
+
+    // provideKeyResponse() shall fill keySetId
+    Vector<uint8_t> keyResponse = {};
+    keyResponse.appendArray(data, size);
+    Vector<uint8_t> keySetId = {};
+    mDrm->provideKeyResponse(mSessionId, keyResponse, keySetId);
+
+    // restoreKeys
+    mDrm->restoreKeys(mSessionId, keySetId);
+
+    // queryKeyStatus() shall fill infoMap
+    KeyedVector<String8, String8> infoMap = {};
+    mDrm->queryKeyStatus(mSessionId, infoMap);
+
+    // decrypt() shall fill outputVec
+    Vector<uint8_t> keyIdVec = {};
+    keyIdVec.appendArray(data, size);
+
+    Vector<uint8_t> inputVec = {};
+    inputVec.appendArray(data, size);
+
+    Vector<uint8_t> ivVec = {};
+    ivVec.appendArray(data, size);
+
+    Vector<uint8_t> outputVec = {};
+    mDrm->decrypt(mSessionId, keyIdVec, inputVec, ivVec, outputVec);
+
+    // encrypt() shall fill outputVec
+    mDrm->encrypt(mSessionId, keyIdVec, inputVec, ivVec, outputVec);
+
+    // sign() shall fill signature
+    Vector<uint8_t> message = {};
+    message.appendArray(data, size);
+    Vector<uint8_t> signature = {};
+    mDrm->sign(mSessionId, keyIdVec, message, signature);
+
+    // verify() shall fill match
+    bool match;
+    mDrm->verify(mSessionId, keyIdVec, message, signature, match);
+
+    // signRSA() shall fill signature
+    mDrm->signRSA(mSessionId, String8(kRSAAlgorithm[mFuzzedDataProvider->ConsumeBool()]), message,
+                  wrappedKey, signature);
+
+    mDrm->removeKeys(mSessionId);
+}
+
+void DrmFuzzer::invokeDrmSecureStopAPI() {
+    // getSecureStops() shall fill secureStops
+    List<Vector<uint8_t>> secureStops = {};
+    mDrm->getSecureStops(secureStops);
+
+    // getSecureStopIds() shall fill secureStopIds
+    List<Vector<uint8_t>> secureStopIds = {};
+    mDrm->getSecureStopIds(secureStopIds);
+
+    // getSecureStop() shall fill secureStop
+    Vector<uint8_t> ssid = {};
+    Vector<uint8_t> secureStop = {};
+    mDrm->getSecureStop(ssid, secureStop);
+
+    mDrm->removeSecureStop(ssid);
+
+    mDrm->releaseSecureStops(ssid);
+
+    mDrm->removeAllSecureStops();
+}
+
+void DrmFuzzer::invokeDrmOfflineLicenseAPI() {
+    // getOfflineLicenseKeySetIds() shall keySetIds
+    List<Vector<uint8_t>> keySetIds = {};
+    mDrm->getOfflineLicenseKeySetIds(keySetIds);
+
+    // getOfflineLicenseState() shall fill state
+    Vector<uint8_t> const keySetIdOfflineLicense = {};
+    DrmPlugin::OfflineLicenseState state;
+    mDrm->getOfflineLicenseState(keySetIdOfflineLicense, &state);
+
+    mDrm->removeOfflineLicense(keySetIdOfflineLicense);
+}
+
+bool DrmFuzzer::initCrypto() {
+    mCrypto = new CryptoHal();
+    if (!mCrypto) {
+        return false;
+    }
+    return true;
+}
+
+void DrmFuzzer::invokeCryptoCreatePlugin() {
+    mCrypto->initCheck();
+
+    mCrypto->isCryptoSchemeSupported(kClearKeyUUID);
+    mCrypto->createPlugin(kClearKeyUUID, NULL, 0);
+}
+
+void DrmFuzzer::invokeCryptoDestroyPlugin() { mCrypto->destroyPlugin(); }
+
+void DrmFuzzer::invokeCryptoDecrypt(const uint8_t *data) {
+    mCrypto->requiresSecureDecoderComponent(
+        kMimeType[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(0, kNumMimeType - 1)]);
+
+    uint32_t width = mFuzzedDataProvider->ConsumeIntegral<uint32_t>();
+    uint32_t height = mFuzzedDataProvider->ConsumeIntegral<uint32_t>();
+    mCrypto->notifyResolution(width, height);
+
+    mCrypto->setMediaDrmSession(mSessionId);
+
+    const CryptoPlugin::Pattern pattern = {0, 0};
+
+    size_t totalSize = 0;
+    size_t numSubSamples = mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(1, kMaxSubSamples);
+
+    CryptoPlugin::SubSample subSamples[numSubSamples];
+
+    for (size_t i = 0; i < numSubSamples; ++i) {
+        uint32_t clearBytes =
+            mFuzzedDataProvider->ConsumeIntegralInRange<uint32_t>(1, kMaxNumBytes);
+        uint32_t encryptedBytes =
+            mFuzzedDataProvider->ConsumeIntegralInRange<uint32_t>(1, kMaxNumBytes);
+        subSamples[i].mNumBytesOfClearData = clearBytes;
+        subSamples[i].mNumBytesOfEncryptedData = encryptedBytes;
+        totalSize += subSamples[i].mNumBytesOfClearData;
+        totalSize += subSamples[i].mNumBytesOfEncryptedData;
+    }
+
+    size_t heapSize = totalSize * 2;
+    sp<MemoryDealer> dealer = new MemoryDealer(heapSize, "DrmFuzzerMemory");
+    if (!dealer) {
+        return;
+    }
+
+    sp<HidlMemory> heap = fromHeap(dealer->getMemoryHeap());
+    if (!heap) {
+        return;
+    }
+    int heapSeqNum = mCrypto->setHeap(heap);
+    if (heapSeqNum < 0) {
+        return;
+    }
+
+    const size_t segmentIndex = 0;
+    const uint8_t keyId[AES_BLOCK_SIZE] = {};
+    memcpy((void *)keyId, data, AES_BLOCK_SIZE);
+
+    const uint8_t iv[AES_BLOCK_SIZE] = {};
+    memset((void *)iv, 0, AES_BLOCK_SIZE);
+
+    const SharedBuffer sourceBuffer = {.bufferId = segmentIndex, .offset = 0, .size = totalSize};
+
+    const DestinationBuffer destBuffer = {
+        .type = BufferType::SHARED_MEMORY,
+        {.bufferId = segmentIndex, .offset = totalSize, .size = totalSize},
+        .secureMemory = nullptr};
+
+    const uint64_t offset = 0;
+    AString *errorDetailMsg = nullptr;
+    CryptoPlugin::Mode mode;
+    bool shouldPassRandomCryptoMode = mFuzzedDataProvider->ConsumeBool();
+    if (shouldPassRandomCryptoMode) {
+        mode = static_cast<CryptoPlugin::Mode>(mFuzzedDataProvider->ConsumeIntegral<size_t>());
+    } else {
+        mode =
+            kCryptoMode[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(0, kNumCryptoMode - 1)];
+    }
+    mCrypto->decrypt(keyId, iv, mode, pattern, sourceBuffer, offset, subSamples, numSubSamples,
+                     destBuffer, errorDetailMsg);
+
+    if (heapSeqNum >= 0) {
+        mCrypto->unsetHeap(heapSeqNum);
+    }
+    heap.clear();
+}
+
+void DrmFuzzer::invokeDrm(const uint8_t *data, size_t size) {
+    if (!initDrm()) {
+        return;
+    }
+    invokeDrmCreatePlugin();
+    invokeDrmOpenSession();
+    invokeDrmSetAlgorithmAPI();
+    invokeDrmSetListener();
+    invokeDrmPropertyAPI();
+    invokeDrmDecryptEncryptAPI(data, size);
+    invokeDrmSecureStopAPI();
+    invokeDrmOfflineLicenseAPI();
+    invokeDrmCloseSession();
+    invokeDrmDestroyPlugin();
+}
+
+void DrmFuzzer::invokeCrypto(const uint8_t *data) {
+    if (!initCrypto()) {
+        return;
+    }
+    invokeCryptoCreatePlugin();
+    invokeCryptoDecrypt(data);
+    invokeCryptoDestroyPlugin();
+}
+
+void DrmFuzzer::process(const uint8_t *data, size_t size) {
+    mFuzzedDataProvider = new FuzzedDataProvider(data, size);
+    invokeDrm(data, size);
+    invokeCrypto(data);
+    delete mFuzzedDataProvider;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    if (size < AES_BLOCK_SIZE) {
+        return 0;
+    }
+    DrmFuzzer drmFuzzer;
+    drmFuzzer.process(data, size);
+    return 0;
+}
diff --git a/drm/libmediadrm/include/mediadrm/DrmSessionManager.h b/drm/libmediadrm/include/mediadrm/DrmSessionManager.h
index 9e43504..c56bf01 100644
--- a/drm/libmediadrm/include/mediadrm/DrmSessionManager.h
+++ b/drm/libmediadrm/include/mediadrm/DrmSessionManager.h
@@ -62,7 +62,7 @@
     void removeSession(const Vector<uint8_t>& sessionId);
     bool reclaimSession(int callingPid);
 
-    // sanity check APIs
+    // inspection APIs
     size_t getSessionCount() const;
     bool containsSession(const Vector<uint8_t>& sessionId) const;
 
diff --git a/drm/libmediadrm/protos/Android.bp b/drm/libmediadrm/protos/Android.bp
new file mode 100644
index 0000000..f8d237a
--- /dev/null
+++ b/drm/libmediadrm/protos/Android.bp
@@ -0,0 +1,47 @@
+// Copyright (C) 2020 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.
+
+// This is the version of the drm metrics configured for protobuf full on host.
+// It is used by the metrics_dump tool.
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library_host_shared {
+    name: "libdrm_metrics_protos_full_host",
+    vendor_available: true,
+
+    include_dirs: ["external/protobuf/src"],
+
+    srcs: [
+        "metrics.proto",
+    ],
+
+    proto: {
+        export_proto_headers: true,
+        type: "full",
+    },
+
+    cflags: [
+        // Suppress unused parameter error. This error occurs
+        // when using the map type in a proto definition.
+        "-Wno-unused-parameter",
+    ],
+}
diff --git a/drm/libmediadrm/tests/Android.bp b/drm/libmediadrm/tests/Android.bp
index 6529387..9267e79 100644
--- a/drm/libmediadrm/tests/Android.bp
+++ b/drm/libmediadrm/tests/Android.bp
@@ -1,5 +1,14 @@
 // Build definitions for unit tests.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "CounterMetric_test",
     srcs: ["CounterMetric_test.cpp"],
diff --git a/drm/mediacas/plugins/clearkey/Android.bp b/drm/mediacas/plugins/clearkey/Android.bp
index 0113cb8..569cdbe 100644
--- a/drm/mediacas/plugins/clearkey/Android.bp
+++ b/drm/mediacas/plugins/clearkey/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libclearkeycasplugin",
 
diff --git a/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp b/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp
index cb69f91..466e571 100644
--- a/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp
+++ b/drm/mediacas/plugins/clearkey/ClearKeyFetcher.cpp
@@ -62,8 +62,8 @@
     }
     ALOGV("descriptor_size=%zu", container.descriptor_size());
 
-    // Sanity check to verify that the BroadcastEncryptor is sending a properly
-    // formed EcmContainer. If it contains two Ecms, the ids should have different
+    // Validate that the BroadcastEncryptor is sending a properly formed
+    // EcmContainer. If it contains two Ecms, the ids should have different
     // parity (one odd, one even). This does not necessarily affect decryption
     // but indicates a problem with Ecm generation.
     if (container.descriptor_size() == 2) {
diff --git a/drm/mediacas/plugins/clearkey/tests/Android.bp b/drm/mediacas/plugins/clearkey/tests/Android.bp
index 575863c..9ad8d1e 100644
--- a/drm/mediacas/plugins/clearkey/tests/Android.bp
+++ b/drm/mediacas/plugins/clearkey/tests/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "ClearKeyFetcherTest",
 
diff --git a/drm/mediacas/plugins/mock/Android.bp b/drm/mediacas/plugins/mock/Android.bp
index e8a3c6f..6f68c77 100644
--- a/drm/mediacas/plugins/mock/Android.bp
+++ b/drm/mediacas/plugins/mock/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libmockcasplugin",
 
diff --git a/drm/mediadrm/plugins/clearkey/common/Android.bp b/drm/mediadrm/plugins/clearkey/common/Android.bp
index 2c674e1..7ed8b88 100644
--- a/drm/mediadrm/plugins/clearkey/common/Android.bp
+++ b/drm/mediadrm/plugins/clearkey/common/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_static {
     name: "libclearkeycommon",
     vendor: true,
@@ -35,4 +44,3 @@
         integer_overflow: true,
     },
 }
-
diff --git a/drm/mediadrm/plugins/clearkey/default/Android.bp b/drm/mediadrm/plugins/clearkey/default/Android.bp
index 9803d32..4b5389a 100644
--- a/drm/mediadrm/plugins/clearkey/default/Android.bp
+++ b/drm/mediadrm/plugins/clearkey/default/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libdrmclearkeyplugin",
     vendor: true,
@@ -60,4 +69,3 @@
         integer_overflow: true,
     },
 }
-
diff --git a/drm/mediadrm/plugins/clearkey/default/tests/Android.bp b/drm/mediadrm/plugins/clearkey/default/tests/Android.bp
index 4419865..b97e924 100644
--- a/drm/mediadrm/plugins/clearkey/default/tests/Android.bp
+++ b/drm/mediadrm/plugins/clearkey/default/tests/Android.bp
@@ -17,6 +17,15 @@
 // Builds ClearKey Drm Tests
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "ClearKeyDrmUnitTest",
     vendor: true,
diff --git a/drm/mediadrm/plugins/clearkey/hidl/Android.bp b/drm/mediadrm/plugins/clearkey/hidl/Android.bp
index a194416..e6e1f80 100644
--- a/drm/mediadrm/plugins/clearkey/hidl/Android.bp
+++ b/drm/mediadrm/plugins/clearkey/hidl/Android.bp
@@ -14,6 +14,19 @@
 // limitations under the License.
 //
 
+// *** THIS PACKAGE HAS SPECIAL LICENSING CONDITIONS.  PLEASE
+//     CONSULT THE OWNERS AND opensource-licensing@google.com BEFORE
+//     DEPENDING ON IT IN YOUR PROJECT. ***
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   legacy_by_exception_only (by exception only)
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "clearkey_service_defaults",
     vendor: true,
diff --git a/drm/mediadrm/plugins/clearkey/hidl/MemoryFileSystem.cpp b/drm/mediadrm/plugins/clearkey/hidl/MemoryFileSystem.cpp
index 2dcd00f..051a968 100644
--- a/drm/mediadrm/plugins/clearkey/hidl/MemoryFileSystem.cpp
+++ b/drm/mediadrm/plugins/clearkey/hidl/MemoryFileSystem.cpp
@@ -15,7 +15,7 @@
 namespace clearkey {
 
 std::string MemoryFileSystem::GetFileName(const std::string& path) {
-    size_t index = path.find_last_of("/");
+    size_t index = path.find_last_of('/');
     if (index != std::string::npos) {
         return path.substr(index+1);
     } else {
diff --git a/drm/mediadrm/plugins/mock/Android.bp b/drm/mediadrm/plugins/mock/Android.bp
index dd2ad7b..20dfb4a 100644
--- a/drm/mediadrm/plugins/mock/Android.bp
+++ b/drm/mediadrm/plugins/mock/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libmockdrmcryptoplugin",
 
diff --git a/include/drm/DrmManagerClient.h b/include/drm/DrmManagerClient.h
index 866edac..a38aa9b 100644
--- a/include/drm/DrmManagerClient.h
+++ b/include/drm/DrmManagerClient.h
@@ -318,7 +318,7 @@
 
     /**
      * Removes all the rights information of each plug-in associated with
-     * DRM framework. Will be used in master reset
+     * DRM framework.
      *
      * @return status_t
      *     Returns DRM_NO_ERROR for success, DRM_ERROR_UNKNOWN for failure
diff --git a/include/media/MicrophoneInfo.h b/include/media/MicrophoneInfo.h
index 2287aca..0a24b02 100644
--- a/include/media/MicrophoneInfo.h
+++ b/include/media/MicrophoneInfo.h
@@ -205,11 +205,11 @@
 private:
     status_t readFloatVector(
             const Parcel* parcel, Vector<float> *vectorPtr, size_t defaultLength) {
-        std::unique_ptr<std::vector<float>> v;
+        std::optional<std::vector<float>> v;
         status_t result = parcel->readFloatVector(&v);
         if (result != OK) return result;
         vectorPtr->clear();
-        if (v.get() != nullptr) {
+        if (v) {
             for (const auto& iter : *v) {
                 vectorPtr->push_back(iter);
             }
diff --git a/media/OWNERS b/media/OWNERS
index 1afc253..3e194f0 100644
--- a/media/OWNERS
+++ b/media/OWNERS
@@ -8,13 +8,14 @@
 hunga@google.com
 jiabin@google.com
 jmtrivi@google.com
-krocard@google.com
 lajos@google.com
 marcone@google.com
 mnaganov@google.com
+nchalko@google.com
 pawin@google.com
 philburk@google.com
 pmclean@google.com
+quxiangfang@google.com
 rachad@google.com
 rago@google.com
 robertshih@google.com
diff --git a/media/audioserver/Android.mk b/media/audioserver/Android.mk
index cf1c14c..acc1b82 100644
--- a/media/audioserver/Android.mk
+++ b/media/audioserver/Android.mk
@@ -43,6 +43,9 @@
 	external/sonic \
 
 LOCAL_MODULE := audioserver
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/../../NOTICE
 
 LOCAL_INIT_RC := audioserver.rc
 
diff --git a/media/audioserver/main_audioserver.cpp b/media/audioserver/main_audioserver.cpp
index f9f4f31..17309dd 100644
--- a/media/audioserver/main_audioserver.cpp
+++ b/media/audioserver/main_audioserver.cpp
@@ -49,7 +49,12 @@
 
     signal(SIGPIPE, SIG_IGN);
 
+#if 1
+    // FIXME See bug 165702394 and bug 168511485
+    const bool doLog = false;
+#else
     bool doLog = (bool) property_get_bool("ro.test_harness", 0);
+#endif
 
     pid_t childPid;
     // FIXME The advantage of making the process containing media.log service the parent process of
diff --git a/media/bufferpool/1.0/Android.bp b/media/bufferpool/1.0/Android.bp
index f817c76..16cf920 100644
--- a/media/bufferpool/1.0/Android.bp
+++ b/media/bufferpool/1.0/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libstagefright_bufferpool@1.0",
     vendor_available: true,
diff --git a/media/bufferpool/1.0/vts/Android.bp b/media/bufferpool/1.0/vts/Android.bp
index ee5a757..b39871e 100644
--- a/media/bufferpool/1.0/vts/Android.bp
+++ b/media/bufferpool/1.0/vts/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "VtsVndkHidlBufferpoolV1_0TargetSingleTest",
     defaults: ["VtsHalTargetTestDefaults"],
diff --git a/media/bufferpool/1.0/vts/multi.cpp b/media/bufferpool/1.0/vts/multi.cpp
index 1796819..d8cc285 100644
--- a/media/bufferpool/1.0/vts/multi.cpp
+++ b/media/bufferpool/1.0/vts/multi.cpp
@@ -215,7 +215,7 @@
 }  // anonymous namespace
 
 int main(int argc, char** argv) {
-  setenv("TREBLE_TESTING_OVERRIDE", "true", true);
+  android::hardware::details::setTrebleTestingOverride(true);
   ::testing::InitGoogleTest(&argc, argv);
   int status = RUN_ALL_TESTS();
   LOG(INFO) << "Test result = " << status;
diff --git a/media/bufferpool/2.0/AccessorImpl.cpp b/media/bufferpool/2.0/AccessorImpl.cpp
index 6111fea..1d2562e 100644
--- a/media/bufferpool/2.0/AccessorImpl.cpp
+++ b/media/bufferpool/2.0/AccessorImpl.cpp
@@ -39,6 +39,8 @@
 
     static constexpr size_t kMinAllocBytesForEviction = 1024*1024*15;
     static constexpr size_t kMinBufferCountForEviction = 25;
+    static constexpr size_t kMaxUnusedBufferCount = 64;
+    static constexpr size_t kUnusedBufferCountTarget = kMaxUnusedBufferCount - 16;
 
     static constexpr nsecs_t kEvictGranularityNs = 1000000000; // 1 sec
     static constexpr nsecs_t kEvictDurationNs = 5000000000; // 5 secs
@@ -724,9 +726,11 @@
 }
 
 void Accessor::Impl::BufferPool::cleanUp(bool clearCache) {
-    if (clearCache || mTimestampUs > mLastCleanUpUs + kCleanUpDurationUs) {
+    if (clearCache || mTimestampUs > mLastCleanUpUs + kCleanUpDurationUs ||
+            mStats.buffersNotInUse() > kMaxUnusedBufferCount) {
         mLastCleanUpUs = mTimestampUs;
-        if (mTimestampUs > mLastLogUs + kLogDurationUs) {
+        if (mTimestampUs > mLastLogUs + kLogDurationUs ||
+                mStats.buffersNotInUse() > kMaxUnusedBufferCount) {
             mLastLogUs = mTimestampUs;
             ALOGD("bufferpool2 %p : %zu(%zu size) total buffers - "
                   "%zu(%zu size) used buffers - %zu/%zu (recycle/alloc) - "
@@ -737,8 +741,9 @@
                   mStats.mTotalFetches, mStats.mTotalTransfers);
         }
         for (auto freeIt = mFreeBuffers.begin(); freeIt != mFreeBuffers.end();) {
-            if (!clearCache && (mStats.mSizeCached < kMinAllocBytesForEviction
-                    || mBuffers.size() < kMinBufferCountForEviction)) {
+            if (!clearCache && mStats.buffersNotInUse() <= kUnusedBufferCountTarget &&
+                    (mStats.mSizeCached < kMinAllocBytesForEviction ||
+                     mBuffers.size() < kMinBufferCountForEviction)) {
                 break;
             }
             auto it = mBuffers.find(*freeIt);
diff --git a/media/bufferpool/2.0/AccessorImpl.h b/media/bufferpool/2.0/AccessorImpl.h
index cd1b4d0..3d39941 100644
--- a/media/bufferpool/2.0/AccessorImpl.h
+++ b/media/bufferpool/2.0/AccessorImpl.h
@@ -193,6 +193,12 @@
                 : mSizeCached(0), mBuffersCached(0), mSizeInUse(0), mBuffersInUse(0),
                   mTotalAllocations(0), mTotalRecycles(0), mTotalTransfers(0), mTotalFetches(0) {}
 
+            /// # of currently unused buffers
+            size_t buffersNotInUse() const {
+                ALOG_ASSERT(mBuffersCached >= mBuffersInUse);
+                return mBuffersCached - mBuffersInUse;
+            }
+
             /// A new buffer is allocated on an allocation request.
             void onBufferAllocated(size_t allocSize) {
                 mSizeCached += allocSize;
diff --git a/media/bufferpool/2.0/Android.bp b/media/bufferpool/2.0/Android.bp
index 536f75e..0d1fe27 100644
--- a/media/bufferpool/2.0/Android.bp
+++ b/media/bufferpool/2.0/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "libstagefright_bufferpool@2.0-default",
     srcs: [
@@ -49,4 +58,3 @@
         enabled: true,
     },
 }
-
diff --git a/media/bufferpool/2.0/BufferPoolClient.cpp b/media/bufferpool/2.0/BufferPoolClient.cpp
index 342fef6..9308b81 100644
--- a/media/bufferpool/2.0/BufferPoolClient.cpp
+++ b/media/bufferpool/2.0/BufferPoolClient.cpp
@@ -32,6 +32,8 @@
 static constexpr int64_t kReceiveTimeoutUs = 1000000; // 100ms
 static constexpr int kPostMaxRetry = 3;
 static constexpr int kCacheTtlUs = 1000000; // TODO: tune
+static constexpr size_t kMaxCachedBufferCount = 64;
+static constexpr size_t kCachedBufferCountTarget = kMaxCachedBufferCount - 16;
 
 class BufferPoolClient::Impl
         : public std::enable_shared_from_this<BufferPoolClient::Impl> {
@@ -136,6 +138,10 @@
             --mActive;
             mLastChangeUs = getTimestampNow();
         }
+
+        int cachedBufferCount() const {
+            return mBuffers.size() - mActive;
+        }
     } mCache;
 
     // FMQ - release notifier
@@ -668,10 +674,12 @@
 // should have mCache.mLock
 void BufferPoolClient::Impl::evictCaches(bool clearCache) {
     int64_t now = getTimestampNow();
-    if (now >= mLastEvictCacheUs + kCacheTtlUs || clearCache) {
+    if (now >= mLastEvictCacheUs + kCacheTtlUs ||
+            clearCache || mCache.cachedBufferCount() > kMaxCachedBufferCount) {
         size_t evicted = 0;
         for (auto it = mCache.mBuffers.begin(); it != mCache.mBuffers.end();) {
-            if (!it->second->hasCache() && (it->second->expire() || clearCache)) {
+            if (!it->second->hasCache() && (it->second->expire() ||
+                        clearCache || mCache.cachedBufferCount() > kCachedBufferCountTarget)) {
                 it = mCache.mBuffers.erase(it);
                 ++evicted;
             } else {
diff --git a/media/bufferpool/2.0/tests/Android.bp b/media/bufferpool/2.0/tests/Android.bp
index 8b44f61..d6db202 100644
--- a/media/bufferpool/2.0/tests/Android.bp
+++ b/media/bufferpool/2.0/tests/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "VtsVndkHidlBufferpoolV2_0TargetSingleTest",
     defaults: ["VtsHalTargetTestDefaults"],
diff --git a/media/bufferpool/2.0/tests/multi.cpp b/media/bufferpool/2.0/tests/multi.cpp
index 68b6992..b40838e 100644
--- a/media/bufferpool/2.0/tests/multi.cpp
+++ b/media/bufferpool/2.0/tests/multi.cpp
@@ -215,7 +215,7 @@
 }  // anonymous namespace
 
 int main(int argc, char** argv) {
-  setenv("TREBLE_TESTING_OVERRIDE", "true", true);
+  android::hardware::details::setTrebleTestingOverride(true);
   ::testing::InitGoogleTest(&argc, argv);
   int status = RUN_ALL_TESTS();
   LOG(INFO) << "Test result = " << status;
diff --git a/media/codec2/components/aac/Android.bp b/media/codec2/components/aac/Android.bp
index 9eca585..c547e85 100644
--- a/media/codec2/components/aac/Android.bp
+++ b/media/codec2/components/aac/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_aac_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_aac_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_aacdec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -15,7 +34,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_aacenc",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/aac/C2SoftAacDec.cpp b/media/codec2/components/aac/C2SoftAacDec.cpp
index 677f316..3e6b0ff 100644
--- a/media/codec2/components/aac/C2SoftAacDec.cpp
+++ b/media/codec2/components/aac/C2SoftAacDec.cpp
@@ -877,10 +877,14 @@
             work->worklets.front()->output.configUpdate.push_back(
                     C2Param::Copy(currentBoostFactor));
 
-            C2StreamDrcCompressionModeTuning::input currentCompressMode(0u,
-                    (C2Config::drc_compression_mode_t) compressMode);
-            work->worklets.front()->output.configUpdate.push_back(
-                    C2Param::Copy(currentCompressMode));
+            if (android_get_device_api_level() < __ANDROID_API_S__) {
+                // We used to report DRC compression mode in the output format
+                // in Q and R, but stopped doing that in S
+                C2StreamDrcCompressionModeTuning::input currentCompressMode(0u,
+                        (C2Config::drc_compression_mode_t) compressMode);
+                work->worklets.front()->output.configUpdate.push_back(
+                        C2Param::Copy(currentCompressMode));
+            }
 
             C2StreamDrcEncodedTargetLevelTuning::input currentEncodedTargetLevel(0u,
                     (C2FloatValue) (encTargetLevel*-0.25));
@@ -1061,11 +1065,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftAacDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/aac/C2SoftAacEnc.cpp b/media/codec2/components/aac/C2SoftAacEnc.cpp
index 2e85915..ea76cbb 100644
--- a/media/codec2/components/aac/C2SoftAacEnc.cpp
+++ b/media/codec2/components/aac/C2SoftAacEnc.cpp
@@ -692,11 +692,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftAacEncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/amr_nb_wb/Android.bp b/media/codec2/components/amr_nb_wb/Android.bp
index ce25bc9..1418ba5 100644
--- a/media/codec2/components/amr_nb_wb/Android.bp
+++ b/media/codec2/components/amr_nb_wb/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_amr_nb_wb_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_amr_nb_wb_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_amrnbdec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -21,7 +40,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_amrwbdec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -40,7 +59,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_amrnbenc",
     defaults: [
         "libcodec2_soft-defaults",
@@ -58,7 +77,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_amrwbenc",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/amr_nb_wb/C2SoftAmrDec.cpp b/media/codec2/components/amr_nb_wb/C2SoftAmrDec.cpp
index f7943be..c08e02b 100644
--- a/media/codec2/components/amr_nb_wb/C2SoftAmrDec.cpp
+++ b/media/codec2/components/amr_nb_wb/C2SoftAmrDec.cpp
@@ -420,11 +420,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftAMRDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/amr_nb_wb/C2SoftAmrNbEnc.cpp b/media/codec2/components/amr_nb_wb/C2SoftAmrNbEnc.cpp
index e2d8cb6..bb63e1f 100644
--- a/media/codec2/components/amr_nb_wb/C2SoftAmrNbEnc.cpp
+++ b/media/codec2/components/amr_nb_wb/C2SoftAmrNbEnc.cpp
@@ -337,11 +337,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftAmrNbEncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/amr_nb_wb/C2SoftAmrWbEnc.cpp b/media/codec2/components/amr_nb_wb/C2SoftAmrWbEnc.cpp
index 84ae4b7..84728ae 100644
--- a/media/codec2/components/amr_nb_wb/C2SoftAmrWbEnc.cpp
+++ b/media/codec2/components/amr_nb_wb/C2SoftAmrWbEnc.cpp
@@ -411,11 +411,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftAmrWbEncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/aom/Android.bp b/media/codec2/components/aom/Android.bp
index 61dbd4c..cb9837f 100644
--- a/media/codec2/components/aom/Android.bp
+++ b/media/codec2/components/aom/Android.bp
@@ -1,4 +1,13 @@
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libcodec2_soft_av1dec_aom",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/aom/C2SoftAomDec.cpp b/media/codec2/components/aom/C2SoftAomDec.cpp
index c7046cb..c08cd59 100644
--- a/media/codec2/components/aom/C2SoftAomDec.cpp
+++ b/media/codec2/components/aom/C2SoftAomDec.cpp
@@ -506,30 +506,28 @@
 }
 
 static void copyOutputBufferToYuvPlanarFrame(
-        uint8_t *dst, const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV,
+        uint8_t *dstY, uint8_t *dstU, uint8_t *dstV,
+        const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV,
         size_t srcYStride, size_t srcUStride, size_t srcVStride,
         size_t dstYStride, size_t dstUVStride,
         uint32_t width, uint32_t height) {
-    uint8_t* dstStart = dst;
 
     for (size_t i = 0; i < height; ++i) {
-        memcpy(dst, srcY, width);
+        memcpy(dstY, srcY, width);
         srcY += srcYStride;
-        dst += dstYStride;
+        dstY += dstYStride;
     }
 
-    dst = dstStart + dstYStride * height;
     for (size_t i = 0; i < height / 2; ++i) {
-         memcpy(dst, srcV, width / 2);
+        memcpy(dstV, srcV, width / 2);
         srcV += srcVStride;
-        dst += dstUVStride;
+        dstV += dstUVStride;
     }
 
-    dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
     for (size_t i = 0; i < height / 2; ++i) {
-         memcpy(dst, srcU, width / 2);
+        memcpy(dstU, srcU, width / 2);
         srcU += srcUStride;
-        dst += dstUVStride;
+        dstU += dstUVStride;
     }
 }
 
@@ -596,16 +594,12 @@
     return;
 }
 
-static void convertYUV420Planar16ToYUV420Planar(uint8_t *dst,
+static void convertYUV420Planar16ToYUV420Planar(
+        uint8_t *dstY, uint8_t *dstU, uint8_t *dstV,
         const uint16_t *srcY, const uint16_t *srcU, const uint16_t *srcV,
         size_t srcYStride, size_t srcUStride, size_t srcVStride,
-        size_t dstYStride, size_t dstUVStride, size_t width, size_t height) {
-
-    uint8_t *dstY = (uint8_t *)dst;
-    size_t dstYSize = dstYStride * height;
-    size_t dstUVSize = dstUVStride * height / 2;
-    uint8_t *dstV = dstY + dstYSize;
-    uint8_t *dstU = dstV + dstUVSize;
+        size_t dstYStride, size_t dstUVStride,
+        size_t width, size_t height) {
 
     for (size_t y = 0; y < height; ++y) {
         for (size_t x = 0; x < width; ++x) {
@@ -696,7 +690,9 @@
           block->width(), block->height(), mWidth, mHeight,
           (int)*(int64_t*)img->user_priv);
 
-    uint8_t* dst = const_cast<uint8_t*>(wView.data()[C2PlanarLayout::PLANE_Y]);
+    uint8_t* dstY = const_cast<uint8_t*>(wView.data()[C2PlanarLayout::PLANE_Y]);
+    uint8_t* dstU = const_cast<uint8_t*>(wView.data()[C2PlanarLayout::PLANE_U]);
+    uint8_t* dstV = const_cast<uint8_t*>(wView.data()[C2PlanarLayout::PLANE_V]);
     size_t srcYStride = img->stride[AOM_PLANE_Y];
     size_t srcUStride = img->stride[AOM_PLANE_U];
     size_t srcVStride = img->stride[AOM_PLANE_V];
@@ -710,13 +706,14 @@
         const uint16_t *srcV = (const uint16_t *)img->planes[AOM_PLANE_V];
 
         if (format == HAL_PIXEL_FORMAT_RGBA_1010102) {
-            convertYUV420Planar16ToY410((uint32_t *)dst, srcY, srcU, srcV, srcYStride / 2,
+            convertYUV420Planar16ToY410((uint32_t *)dstY, srcY, srcU, srcV, srcYStride / 2,
                                     srcUStride / 2, srcVStride / 2,
                                     dstYStride / sizeof(uint32_t),
                                     mWidth, mHeight);
         } else {
-            convertYUV420Planar16ToYUV420Planar(dst, srcY, srcU, srcV, srcYStride / 2,
-                                    srcUStride / 2, srcVStride / 2,
+            convertYUV420Planar16ToYUV420Planar(dstY, dstU, dstV,
+                                    srcY, srcU, srcV,
+                                    srcYStride / 2, srcUStride / 2, srcVStride / 2,
                                     dstYStride, dstUVStride,
                                     mWidth, mHeight);
         }
@@ -725,7 +722,7 @@
         const uint8_t *srcU = (const uint8_t *)img->planes[AOM_PLANE_U];
         const uint8_t *srcV = (const uint8_t *)img->planes[AOM_PLANE_V];
         copyOutputBufferToYuvPlanarFrame(
-                dst, srcY, srcU, srcV,
+                dstY, dstU, dstV, srcY, srcU, srcV,
                 srcYStride, srcUStride, srcVStride,
                 dstYStride, dstUVStride,
                 mWidth, mHeight);
@@ -803,11 +800,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftAomFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/avc/Android.bp b/media/codec2/components/avc/Android.bp
index 4021444..0be1bed 100644
--- a/media/codec2/components/avc/Android.bp
+++ b/media/codec2/components/avc/Android.bp
@@ -1,9 +1,19 @@
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libcodec2_soft_avcdec",
     defaults: [
         "libcodec2_soft-defaults",
         "libcodec2_soft_sanitize_signed-defaults",
-   ],
+        "libcodec2_soft_sanitize_cfi-defaults",
+    ],
 
     static_libs: ["libavcdec"],
 
@@ -15,12 +25,13 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_avcenc",
     defaults: [
         "libcodec2_soft-defaults",
         "libcodec2_soft_sanitize_signed-defaults",
-   ],
+        "libcodec2_soft_sanitize_cfi-defaults",
+    ],
 
     static_libs: ["libavcenc"],
 
diff --git a/media/codec2/components/avc/C2SoftAvcDec.cpp b/media/codec2/components/avc/C2SoftAvcDec.cpp
index d7b9e12..0207311 100644
--- a/media/codec2/components/avc/C2SoftAvcDec.cpp
+++ b/media/codec2/components/avc/C2SoftAvcDec.cpp
@@ -34,7 +34,11 @@
 constexpr size_t kMinInputBufferSize = 2 * 1024 * 1024;
 constexpr char COMPONENT_NAME[] = "c2.android.avc.decoder";
 constexpr uint32_t kDefaultOutputDelay = 8;
-constexpr uint32_t kMaxOutputDelay = 16;
+/* avc specification allows for a maximum delay of 16 frames.
+   As soft avc decoder supports interlaced, this delay would be 32 fields.
+   And avc decoder implementation has an additional delay of 2 decode calls.
+   So total maximum output delay is 34 */
+constexpr uint32_t kMaxOutputDelay = 34;
 constexpr uint32_t kMinInputBytes = 4;
 }  // namespace
 
@@ -1045,11 +1049,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftAvcDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/avc/C2SoftAvcEnc.cpp b/media/codec2/components/avc/C2SoftAvcEnc.cpp
index ab93ce3..cfaeb66 100644
--- a/media/codec2/components/avc/C2SoftAvcEnc.cpp
+++ b/media/codec2/components/avc/C2SoftAvcEnc.cpp
@@ -1756,11 +1756,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftAvcEncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/base/Android.bp b/media/codec2/components/base/Android.bp
index f10835f..160e250 100644
--- a/media/codec2/components/base/Android.bp
+++ b/media/codec2/components/base/Android.bp
@@ -1,6 +1,15 @@
 // DO NOT DEPEND ON THIS DIRECTLY
 // use libcodec2_soft-defaults instead
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libcodec2_soft_common",
     defaults: ["libcodec2-impl-defaults"],
     vendor_available: true,
@@ -20,7 +29,7 @@
 
     shared_libs: [
         "libcutils", // for properties
-        "liblog",    // for ALOG
+        "liblog", // for ALOG
         "libsfplugin_ccodec_utils", // for ImageCopy
         "libstagefright_foundation", // for Mutexed
     ],
@@ -38,7 +47,7 @@
 
 filegroup {
     name: "codec2_soft_exports",
-    srcs: [ "exports.lds" ],
+    srcs: ["exports.lds"],
 }
 
 // public dependency for software codec implementation
@@ -91,12 +100,22 @@
         misc_undefined: [
             "signed-integer-overflow",
         ],
+    },
+}
+
+cc_defaults {
+    name: "libcodec2_soft_sanitize_cfi-defaults",
+
+    sanitize: {
         cfi: true,
+        config: {
+            cfi_assembly_support: true,
+        },
     },
 }
 
 // TEMP: used by cheets2 project - remove when no longer used
-cc_library_shared {
+cc_library {
     name: "libcodec2_simple_component",
     vendor_available: true,
 
@@ -131,4 +150,3 @@
 
     ldflags: ["-Wl,-Bsymbolic"],
 }
-
diff --git a/media/codec2/components/cmds/Android.bp b/media/codec2/components/cmds/Android.bp
index a081e28..d6ffd12 100644
--- a/media/codec2/components/cmds/Android.bp
+++ b/media/codec2/components/cmds/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_binary {
     name: "codec2play",
     defaults: ["libcodec2-impl-defaults"],
diff --git a/media/codec2/components/cmds/codec2.cpp b/media/codec2/components/cmds/codec2.cpp
index d6025de..a17b04e 100644
--- a/media/codec2/components/cmds/codec2.cpp
+++ b/media/codec2/components/cmds/codec2.cpp
@@ -138,7 +138,7 @@
 
 SimplePlayer::SimplePlayer()
     : mListener(new Listener(this)),
-      mProducerListener(new DummyProducerListener),
+      mProducerListener(new StubProducerListener),
       mLinearPoolId(C2BlockPool::PLATFORM_START),
       mComposerClient(new SurfaceComposerClient) {
     CHECK_EQ(mComposerClient->initCheck(), (status_t)OK);
diff --git a/media/codec2/components/flac/Android.bp b/media/codec2/components/flac/Android.bp
index 48cc51b..1143bed 100644
--- a/media/codec2/components/flac/Android.bp
+++ b/media/codec2/components/flac/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_flac_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_flac_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_flacdec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -14,7 +33,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_flacenc",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/flac/C2SoftFlacDec.cpp b/media/codec2/components/flac/C2SoftFlacDec.cpp
index 4039b9b..e70c289 100644
--- a/media/codec2/components/flac/C2SoftFlacDec.cpp
+++ b/media/codec2/components/flac/C2SoftFlacDec.cpp
@@ -367,11 +367,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftFlacDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/flac/C2SoftFlacEnc.cpp b/media/codec2/components/flac/C2SoftFlacEnc.cpp
index 408db7e..1c0babd 100644
--- a/media/codec2/components/flac/C2SoftFlacEnc.cpp
+++ b/media/codec2/components/flac/C2SoftFlacEnc.cpp
@@ -481,11 +481,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftFlacEncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/g711/Android.bp b/media/codec2/components/g711/Android.bp
index 3ede68c..45e85a9 100644
--- a/media/codec2/components/g711/Android.bp
+++ b/media/codec2/components/g711/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_g711_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_g711_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_g711alawdec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -7,12 +26,14 @@
 
     srcs: ["C2SoftG711Dec.cpp"],
 
+    static_libs: ["codecs_g711dec"],
+
     cflags: [
         "-DALAW",
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_g711mlawdec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -20,4 +41,6 @@
     ],
 
     srcs: ["C2SoftG711Dec.cpp"],
+
+    static_libs: ["codecs_g711dec"],
 }
diff --git a/media/codec2/components/g711/C2SoftG711Dec.cpp b/media/codec2/components/g711/C2SoftG711Dec.cpp
index 4ff0793..f9299af 100644
--- a/media/codec2/components/g711/C2SoftG711Dec.cpp
+++ b/media/codec2/components/g711/C2SoftG711Dec.cpp
@@ -22,7 +22,7 @@
 
 #include <C2PlatformSupport.h>
 #include <SimpleC2Interface.h>
-
+#include <g711Dec.h>
 #include "C2SoftG711Dec.h"
 
 namespace android {
@@ -224,53 +224,6 @@
     return C2_OK;
 }
 
-#ifdef ALAW
-void C2SoftG711Dec::DecodeALaw(
-        int16_t *out, const uint8_t *in, size_t inSize) {
-    while (inSize > 0) {
-        inSize--;
-        int32_t x = *in++;
-
-        int32_t ix = x ^ 0x55;
-        ix &= 0x7f;
-
-        int32_t iexp = ix >> 4;
-        int32_t mant = ix & 0x0f;
-
-        if (iexp > 0) {
-            mant += 16;
-        }
-
-        mant = (mant << 4) + 8;
-
-        if (iexp > 1) {
-            mant = mant << (iexp - 1);
-        }
-
-        *out++ = (x > 127) ? mant : -mant;
-    }
-}
-#else
-void C2SoftG711Dec::DecodeMLaw(
-        int16_t *out, const uint8_t *in, size_t inSize) {
-    while (inSize > 0) {
-        inSize--;
-        int32_t x = *in++;
-
-        int32_t mantissa = ~x;
-        int32_t exponent = (mantissa >> 4) & 7;
-        int32_t segment = exponent + 1;
-        mantissa &= 0x0f;
-
-        int32_t step = 4 << segment;
-
-        int32_t abs = (0x80l << exponent) + step * mantissa + step / 2 - 4 * 33;
-
-        *out++ = (x < 0x80) ? -abs : abs;
-    }
-}
-#endif
-
 class C2SoftG711DecFactory : public C2ComponentFactory {
 public:
     C2SoftG711DecFactory() : mHelper(std::static_pointer_cast<C2ReflectorHelper>(
@@ -306,11 +259,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftG711DecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/g711/C2SoftG711Dec.h b/media/codec2/components/g711/C2SoftG711Dec.h
index 23e8ffc..f93840b 100644
--- a/media/codec2/components/g711/C2SoftG711Dec.h
+++ b/media/codec2/components/g711/C2SoftG711Dec.h
@@ -45,12 +45,6 @@
     std::shared_ptr<IntfImpl> mIntf;
     bool mSignalledOutputEos;
 
-#ifdef ALAW
-    void DecodeALaw(int16_t *out, const uint8_t *in, size_t inSize);
-#else
-    void DecodeMLaw(int16_t *out, const uint8_t *in, size_t inSize);
-#endif
-
     C2_DO_NOT_COPY(C2SoftG711Dec);
 };
 
diff --git a/media/codec2/components/gav1/Android.bp b/media/codec2/components/gav1/Android.bp
index f374089..7692d37 100644
--- a/media/codec2/components/gav1/Android.bp
+++ b/media/codec2/components/gav1/Android.bp
@@ -1,4 +1,13 @@
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libcodec2_soft_av1dec_gav1",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/gav1/C2SoftGav1Dec.cpp b/media/codec2/components/gav1/C2SoftGav1Dec.cpp
index 120ba7a..76345ae 100644
--- a/media/codec2/components/gav1/C2SoftGav1Dec.cpp
+++ b/media/codec2/components/gav1/C2SoftGav1Dec.cpp
@@ -458,32 +458,28 @@
   }
 }
 
-static void copyOutputBufferToYuvPlanarFrame(uint8_t *dst, const uint8_t *srcY,
-                                             const uint8_t *srcU,
-                                             const uint8_t *srcV, size_t srcYStride,
-                                             size_t srcUStride, size_t srcVStride,
-                                             size_t dstYStride, size_t dstUVStride,
-                                             uint32_t width, uint32_t height) {
-  uint8_t *const dstStart = dst;
+static void copyOutputBufferToYV12Frame(uint8_t *dstY, uint8_t *dstU, uint8_t *dstV,
+                                        const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV,
+                                        size_t srcYStride, size_t srcUStride, size_t srcVStride,
+                                        size_t dstYStride, size_t dstUVStride,
+                                        uint32_t width, uint32_t height) {
 
   for (size_t i = 0; i < height; ++i) {
-    memcpy(dst, srcY, width);
+    memcpy(dstY, srcY, width);
     srcY += srcYStride;
-    dst += dstYStride;
+    dstY += dstYStride;
   }
 
-  dst = dstStart + dstYStride * height;
   for (size_t i = 0; i < height / 2; ++i) {
-    memcpy(dst, srcV, width / 2);
+    memcpy(dstV, srcV, width / 2);
     srcV += srcVStride;
-    dst += dstUVStride;
+    dstV += dstUVStride;
   }
 
-  dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
   for (size_t i = 0; i < height / 2; ++i) {
-    memcpy(dst, srcU, width / 2);
+    memcpy(dstU, srcU, width / 2);
     srcU += srcUStride;
-    dst += dstUVStride;
+    dstU += dstUVStride;
   }
 }
 
@@ -555,15 +551,11 @@
 }
 
 static void convertYUV420Planar16ToYUV420Planar(
-    uint8_t *dst, const uint16_t *srcY, const uint16_t *srcU,
-    const uint16_t *srcV, size_t srcYStride, size_t srcUStride,
-    size_t srcVStride, size_t dstYStride, size_t dstUVStride,
+    uint8_t *dstY, uint8_t *dstU, uint8_t *dstV,
+    const uint16_t *srcY, const uint16_t *srcU, const uint16_t *srcV,
+    size_t srcYStride, size_t srcUStride, size_t srcVStride,
+    size_t dstYStride, size_t dstUVStride,
     size_t width, size_t height) {
-  uint8_t *dstY = (uint8_t *)dst;
-  size_t dstYSize = dstYStride * height;
-  size_t dstUVSize = dstUVStride * height / 2;
-  uint8_t *dstV = dstY + dstYSize;
-  uint8_t *dstU = dstV + dstUVSize;
 
   for (size_t y = 0; y < height; ++y) {
     for (size_t x = 0; x < width; ++x) {
@@ -667,10 +659,13 @@
   ALOGV("provided (%dx%d) required (%dx%d), out frameindex %d", block->width(),
         block->height(), mWidth, mHeight, (int)buffer->user_private_data);
 
-  uint8_t *dst = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
+  uint8_t *dstY = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
+  uint8_t *dstU = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_U]);
+  uint8_t *dstV = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_V]);
   size_t srcYStride = buffer->stride[0];
   size_t srcUStride = buffer->stride[1];
   size_t srcVStride = buffer->stride[2];
+
   C2PlanarLayout layout = wView.layout();
   size_t dstYStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
   size_t dstUVStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
@@ -682,20 +677,24 @@
 
     if (format == HAL_PIXEL_FORMAT_RGBA_1010102) {
       convertYUV420Planar16ToY410(
-          (uint32_t *)dst, srcY, srcU, srcV, srcYStride / 2, srcUStride / 2,
+          (uint32_t *)dstY, srcY, srcU, srcV, srcYStride / 2, srcUStride / 2,
           srcVStride / 2, dstYStride / sizeof(uint32_t), mWidth, mHeight);
     } else {
-      convertYUV420Planar16ToYUV420Planar(dst, srcY, srcU, srcV, srcYStride / 2,
-                                          srcUStride / 2, srcVStride / 2,
-                                          dstYStride, dstUVStride, mWidth, mHeight);
+      convertYUV420Planar16ToYUV420Planar(dstY, dstU, dstV,
+                                          srcY, srcU, srcV,
+                                          srcYStride / 2, srcUStride / 2, srcVStride / 2,
+                                          dstYStride, dstUVStride,
+                                          mWidth, mHeight);
     }
   } else {
     const uint8_t *srcY = (const uint8_t *)buffer->plane[0];
     const uint8_t *srcU = (const uint8_t *)buffer->plane[1];
     const uint8_t *srcV = (const uint8_t *)buffer->plane[2];
-    copyOutputBufferToYuvPlanarFrame(dst, srcY, srcU, srcV, srcYStride, srcUStride,
-                                     srcVStride, dstYStride, dstUVStride,
-                                     mWidth, mHeight);
+    copyOutputBufferToYV12Frame(dstY, dstU, dstV,
+                                srcY, srcU, srcV,
+                                srcYStride, srcUStride, srcVStride,
+                                dstYStride, dstUVStride,
+                                mWidth, mHeight);
   }
   finishWork(buffer->user_private_data, work, std::move(block));
   block = nullptr;
@@ -771,11 +770,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory *CreateCodec2Factory() {
   ALOGV("in %s", __func__);
   return new ::android::C2SoftGav1Factory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory *factory) {
   ALOGV("in %s", __func__);
   delete factory;
diff --git a/media/codec2/components/gsm/Android.bp b/media/codec2/components/gsm/Android.bp
index 9330c01..2d0976d 100644
--- a/media/codec2/components/gsm/Android.bp
+++ b/media/codec2/components/gsm/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_gsm_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_gsm_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_gsmdec",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/gsm/C2SoftGsmDec.cpp b/media/codec2/components/gsm/C2SoftGsmDec.cpp
index 287cfc6..977677d 100644
--- a/media/codec2/components/gsm/C2SoftGsmDec.cpp
+++ b/media/codec2/components/gsm/C2SoftGsmDec.cpp
@@ -294,11 +294,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftGSMDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/gsm/C2SoftGsmDec.h b/media/codec2/components/gsm/C2SoftGsmDec.h
index 2b209fe..edd273b 100644
--- a/media/codec2/components/gsm/C2SoftGsmDec.h
+++ b/media/codec2/components/gsm/C2SoftGsmDec.h
@@ -19,10 +19,7 @@
 
 #include <SimpleC2Component.h>
 
-
-extern "C" {
-    #include "gsm.h"
-}
+#include "gsm.h"
 
 namespace android {
 
diff --git a/media/codec2/components/hevc/Android.bp b/media/codec2/components/hevc/Android.bp
index 369bd78..d1388b9 100644
--- a/media/codec2/components/hevc/Android.bp
+++ b/media/codec2/components/hevc/Android.bp
@@ -1,8 +1,18 @@
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libcodec2_soft_hevcdec",
     defaults: [
         "libcodec2_soft-defaults",
         "libcodec2_soft_sanitize_signed-defaults",
+        "libcodec2_soft_sanitize_cfi-defaults",
     ],
 
     srcs: ["C2SoftHevcDec.cpp"],
@@ -11,11 +21,12 @@
 
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_hevcenc",
     defaults: [
         "libcodec2_soft-defaults",
         "libcodec2_soft_sanitize_signed-defaults",
+        "libcodec2_soft_sanitize_cfi-defaults",
     ],
 
     srcs: ["C2SoftHevcEnc.cpp"],
diff --git a/media/codec2/components/hevc/C2SoftHevcDec.cpp b/media/codec2/components/hevc/C2SoftHevcDec.cpp
index 23104dc..a374dfa 100644
--- a/media/codec2/components/hevc/C2SoftHevcDec.cpp
+++ b/media/codec2/components/hevc/C2SoftHevcDec.cpp
@@ -906,7 +906,6 @@
                 work->result = C2_CORRUPTED;
                 return;
             }
-            continue;
         }
         if (0 < s_decode_op.u4_pic_wd && 0 < s_decode_op.u4_pic_ht) {
             if (mHeaderDecoded == false) {
@@ -1048,11 +1047,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftHevcDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/hevc/C2SoftHevcEnc.cpp b/media/codec2/components/hevc/C2SoftHevcEnc.cpp
index c2d2540..436a2c4 100644
--- a/media/codec2/components/hevc/C2SoftHevcEnc.cpp
+++ b/media/codec2/components/hevc/C2SoftHevcEnc.cpp
@@ -1078,11 +1078,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftHevcEncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/mp3/Android.bp b/media/codec2/components/mp3/Android.bp
index 66665ed..437d34f 100644
--- a/media/codec2/components/mp3/Android.bp
+++ b/media/codec2/components/mp3/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_mp3_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_mp3_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_mp3dec",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/mp3/C2SoftMp3Dec.cpp b/media/codec2/components/mp3/C2SoftMp3Dec.cpp
index 5ba7e3d..7137767 100644
--- a/media/codec2/components/mp3/C2SoftMp3Dec.cpp
+++ b/media/codec2/components/mp3/C2SoftMp3Dec.cpp
@@ -539,11 +539,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftMp3DecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/mpeg2/Android.bp b/media/codec2/components/mpeg2/Android.bp
index 841f0a9..daa10ae 100644
--- a/media/codec2/components/mpeg2/Android.bp
+++ b/media/codec2/components/mpeg2/Android.bp
@@ -1,4 +1,13 @@
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libcodec2_soft_mpeg2dec",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp b/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp
index 55dd475..b1cf388 100644
--- a/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp
+++ b/media/codec2/components/mpeg2/C2SoftMpeg2Dec.cpp
@@ -30,6 +30,7 @@
 
 namespace android {
 constexpr size_t kMinInputBufferSize = 2 * 1024 * 1024;
+constexpr size_t kMaxDimension = 1920;
 constexpr char COMPONENT_NAME[] = "c2.android.mpeg2.decoder";
 
 class C2SoftMpeg2Dec::IntfImpl : public SimpleInterface<void>::BaseParams {
@@ -64,8 +65,8 @@
                 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
                 .withDefault(new C2StreamPictureSizeInfo::output(0u, 320, 240))
                 .withFields({
-                    C2F(mSize, width).inRange(16, 1920, 4),
-                    C2F(mSize, height).inRange(16, 1088, 4),
+                    C2F(mSize, width).inRange(16, kMaxDimension, 2),
+                    C2F(mSize, height).inRange(16, kMaxDimension, 2),
                 })
                 .withSetter(SizeSetter)
                 .build());
@@ -91,8 +92,8 @@
                 DefineParam(mMaxSize, C2_PARAMKEY_MAX_PICTURE_SIZE)
                 .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 320, 240))
                 .withFields({
-                    C2F(mSize, width).inRange(2, 1920, 2),
-                    C2F(mSize, height).inRange(2, 1088, 2),
+                    C2F(mSize, width).inRange(2, kMaxDimension, 2),
+                    C2F(mSize, height).inRange(2, kMaxDimension, 2),
                 })
                 .withSetter(MaxPictureSizeSetter, mSize)
                 .build());
@@ -204,8 +205,8 @@
                                     const C2P<C2StreamPictureSizeInfo::output> &size) {
         (void)mayBlock;
         // TODO: get max width/height from the size's field helpers vs. hardcoding
-        me.set().width = c2_min(c2_max(me.v.width, size.v.width), 1920u);
-        me.set().height = c2_min(c2_max(me.v.height, size.v.height), 1088u);
+        me.set().width = c2_min(c2_max(me.v.width, size.v.width), kMaxDimension);
+        me.set().height = c2_min(c2_max(me.v.height, size.v.height), kMaxDimension);
         return C2R::Ok();
     }
 
@@ -1113,11 +1114,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftMpeg2DecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/mpeg4_h263/Android.bp b/media/codec2/components/mpeg4_h263/Android.bp
index 41e4f44..e19fa45 100644
--- a/media/codec2/components/mpeg4_h263/Android.bp
+++ b/media/codec2/components/mpeg4_h263/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_mpeg4_h263_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_mpeg4_h263_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_mpeg4dec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -15,7 +34,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_h263dec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -31,7 +50,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_mpeg4enc",
     defaults: [
         "libcodec2_soft-defaults",
@@ -49,7 +68,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_h263enc",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp
index 61b286c..ddd312f 100644
--- a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp
+++ b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp
@@ -35,8 +35,10 @@
 namespace android {
 constexpr size_t kMinInputBufferSize = 2 * 1024 * 1024;
 #ifdef MPEG4
+constexpr size_t kMaxDimension = 1920;
 constexpr char COMPONENT_NAME[] = "c2.android.mpeg4.decoder";
 #else
+constexpr size_t kMaxDimension = 352;
 constexpr char COMPONENT_NAME[] = "c2.android.h263.decoder";
 #endif
 
@@ -75,13 +77,8 @@
                 DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE)
                 .withDefault(new C2StreamPictureSizeInfo::output(0u, 176, 144))
                 .withFields({
-#ifdef MPEG4
-                    C2F(mSize, width).inRange(2, 1920, 2),
-                    C2F(mSize, height).inRange(2, 1088, 2),
-#else
-                    C2F(mSize, width).inRange(2, 352, 2),
-                    C2F(mSize, height).inRange(2, 288, 2),
-#endif
+                    C2F(mSize, width).inRange(2, kMaxDimension, 2),
+                    C2F(mSize, height).inRange(2, kMaxDimension, 2),
                 })
                 .withSetter(SizeSetter)
                 .build());
@@ -130,19 +127,10 @@
 
         addParameter(
                 DefineParam(mMaxSize, C2_PARAMKEY_MAX_PICTURE_SIZE)
-#ifdef MPEG4
-                .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 1920, 1088))
-#else
                 .withDefault(new C2StreamMaxPictureSizeTuning::output(0u, 352, 288))
-#endif
                 .withFields({
-#ifdef MPEG4
-                    C2F(mSize, width).inRange(2, 1920, 2),
-                    C2F(mSize, height).inRange(2, 1088, 2),
-#else
-                    C2F(mSize, width).inRange(2, 352, 2),
-                    C2F(mSize, height).inRange(2, 288, 2),
-#endif
+                    C2F(mSize, width).inRange(2, kMaxDimension, 2),
+                    C2F(mSize, height).inRange(2, kMaxDimension, 2),
                 })
                 .withSetter(MaxPictureSizeSetter, mSize)
                 .build());
@@ -200,13 +188,8 @@
                                     const C2P<C2StreamPictureSizeInfo::output> &size) {
         (void)mayBlock;
         // TODO: get max width/height from the size's field helpers vs. hardcoding
-#ifdef MPEG4
-        me.set().width = c2_min(c2_max(me.v.width, size.v.width), 1920u);
-        me.set().height = c2_min(c2_max(me.v.height, size.v.height), 1088u);
-#else
-        me.set().width = c2_min(c2_max(me.v.width, size.v.width), 352u);
-        me.set().height = c2_min(c2_max(me.v.height, size.v.height), 288u);
-#endif
+        me.set().width = c2_min(c2_max(me.v.width, size.v.width), kMaxDimension);
+        me.set().height = c2_min(c2_max(me.v.height, size.v.height), kMaxDimension);
         return C2R::Ok();
     }
 
@@ -464,34 +447,34 @@
 /* TODO: can remove temporary copy after library supports writing to display
  * buffer Y, U and V plane pointers using stride info. */
 static void copyOutputBufferToYuvPlanarFrame(
-        uint8_t *dst, uint8_t *src,
+        uint8_t *dstY, uint8_t *dstU, uint8_t *dstV, uint8_t *src,
         size_t dstYStride, size_t dstUVStride,
         size_t srcYStride, uint32_t width,
         uint32_t height) {
     size_t srcUVStride = srcYStride / 2;
     uint8_t *srcStart = src;
-    uint8_t *dstStart = dst;
+
     size_t vStride = align(height, 16);
     for (size_t i = 0; i < height; ++i) {
-         memcpy(dst, src, width);
+         memcpy(dstY, src, width);
          src += srcYStride;
-         dst += dstYStride;
+         dstY += dstYStride;
     }
+
     /* U buffer */
     src = srcStart + vStride * srcYStride;
-    dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
     for (size_t i = 0; i < height / 2; ++i) {
-         memcpy(dst, src, width / 2);
+         memcpy(dstU, src, width / 2);
          src += srcUVStride;
-         dst += dstUVStride;
+         dstU += dstUVStride;
     }
+
     /* V buffer */
     src = srcStart + vStride * srcYStride * 5 / 4;
-    dst = dstStart + (dstYStride * height);
     for (size_t i = 0; i < height / 2; ++i) {
-         memcpy(dst, src, width / 2);
+         memcpy(dstV, src, width / 2);
          src += srcUVStride;
-         dst += dstUVStride;
+         dstV += dstUVStride;
     }
 }
 
@@ -672,11 +655,14 @@
         }
 
         uint8_t *outputBufferY = wView.data()[C2PlanarLayout::PLANE_Y];
+        uint8_t *outputBufferU = wView.data()[C2PlanarLayout::PLANE_U];
+        uint8_t *outputBufferV = wView.data()[C2PlanarLayout::PLANE_V];
+
         C2PlanarLayout layout = wView.layout();
         size_t dstYStride = layout.planes[C2PlanarLayout::PLANE_Y].rowInc;
         size_t dstUVStride = layout.planes[C2PlanarLayout::PLANE_U].rowInc;
         (void)copyOutputBufferToYuvPlanarFrame(
-                outputBufferY,
+                outputBufferY, outputBufferU, outputBufferV,
                 mOutputBuffer[mNumSamplesOutput & 1],
                 dstYStride, dstUVStride,
                 align(mWidth, 16), mWidth, mHeight);
@@ -744,11 +730,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftMpeg4DecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Enc.cpp b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Enc.cpp
index 54c8c47..e1cc6b3 100644
--- a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Enc.cpp
+++ b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Enc.cpp
@@ -652,11 +652,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftMpeg4EncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/mpeg4_h263/TEST_MAPPING b/media/codec2/components/mpeg4_h263/TEST_MAPPING
new file mode 100644
index 0000000..93fba22
--- /dev/null
+++ b/media/codec2/components/mpeg4_h263/TEST_MAPPING
@@ -0,0 +1,6 @@
+// mappings for frameworks/av/media/codec2/components/mpeg4_h263
+{
+  "presubmit": [
+    { "name": "C2SoftMpeg4DecTest" }
+  ]
+}
diff --git a/media/codec2/components/opus/Android.bp b/media/codec2/components/opus/Android.bp
index 0ed141b..bfba45c 100644
--- a/media/codec2/components/opus/Android.bp
+++ b/media/codec2/components/opus/Android.bp
@@ -1,4 +1,13 @@
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libcodec2_soft_opusdec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -9,7 +18,7 @@
 
     shared_libs: ["libopus"],
 }
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_opusenc",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/opus/C2SoftOpusDec.cpp b/media/codec2/components/opus/C2SoftOpusDec.cpp
index b7c1556..d4987c0 100644
--- a/media/codec2/components/opus/C2SoftOpusDec.cpp
+++ b/media/codec2/components/opus/C2SoftOpusDec.cpp
@@ -473,11 +473,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftOpusDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/opus/C2SoftOpusEnc.cpp b/media/codec2/components/opus/C2SoftOpusEnc.cpp
index 70d1965..b47275f 100644
--- a/media/codec2/components/opus/C2SoftOpusEnc.cpp
+++ b/media/codec2/components/opus/C2SoftOpusEnc.cpp
@@ -626,11 +626,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftOpusEncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/raw/Android.bp b/media/codec2/components/raw/Android.bp
index dc944da..c0b7613 100644
--- a/media/codec2/components/raw/Android.bp
+++ b/media/codec2/components/raw/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_raw_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_raw_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_rawdec",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/raw/C2SoftRawDec.cpp b/media/codec2/components/raw/C2SoftRawDec.cpp
index 7b6f21a..31ca705 100644
--- a/media/codec2/components/raw/C2SoftRawDec.cpp
+++ b/media/codec2/components/raw/C2SoftRawDec.cpp
@@ -215,11 +215,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftRawDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/tests/Android.bp b/media/codec2/components/tests/Android.bp
new file mode 100644
index 0000000..3c68eee
--- /dev/null
+++ b/media/codec2/components/tests/Android.bp
@@ -0,0 +1,68 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_defaults {
+    name: "C2SoftCodecTest-defaults",
+    gtest: true,
+    host_supported: false,
+    srcs: [
+        "C2SoftCodecTest.cpp",
+    ],
+
+    static_libs: [
+        "liblog",
+        "libion",
+        "libfmq",
+        "libbase",
+        "libutils",
+        "libcutils",
+        "libcodec2",
+        "libhidlbase",
+        "libdmabufheap",
+        "libcodec2_vndk",
+        "libnativewindow",
+        "libcodec2_soft_common",
+        "libsfplugin_ccodec_utils",
+        "libstagefright_foundation",
+        "libstagefright_bufferpool@2.0.1",
+        "android.hardware.graphics.mapper@2.0",
+        "android.hardware.graphics.mapper@3.0",
+        "android.hardware.media.bufferpool@2.0",
+        "android.hardware.graphics.allocator@2.0",
+        "android.hardware.graphics.allocator@3.0",
+        "android.hardware.graphics.bufferqueue@2.0",
+    ],
+
+    shared_libs: [
+        "libui",
+        "libdl",
+        "libhardware",
+        "libvndksupport",
+        "libprocessgroup",
+    ],
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+}
+
+cc_test {
+    name: "C2SoftMpeg4DecTest",
+    defaults: ["C2SoftCodecTest-defaults"],
+
+    static_libs: [
+        "libstagefright_m4vh263dec",
+        "libcodec2_soft_mpeg4dec",
+    ],
+
+    test_suites: [
+        "general-tests",
+    ],
+}
diff --git a/media/codec2/components/tests/C2SoftCodecTest.cpp b/media/codec2/components/tests/C2SoftCodecTest.cpp
new file mode 100644
index 0000000..84c2562
--- /dev/null
+++ b/media/codec2/components/tests/C2SoftCodecTest.cpp
@@ -0,0 +1,105 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2021 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+#include <C2Config.h>
+#include <C2ComponentFactory.h>
+#include <gtest/gtest.h>
+#include <log/log.h>
+
+using namespace android;
+extern "C" ::C2ComponentFactory* CreateCodec2Factory();
+extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory);
+
+class C2SoftCodecTest : public ::testing::Test {
+public:
+  void SetUp() override {
+    mFactory = CreateCodec2Factory();
+  }
+
+  void TearDown() override {
+    if (mFactory) {
+      DestroyCodec2Factory(mFactory);
+    }
+  }
+
+  c2_status_t createComponent(
+        std::shared_ptr<C2Component>* const comp) {
+    if (!mFactory) {
+      return C2_NO_INIT;
+    }
+    return mFactory->createComponent(
+        kPlaceholderId, comp, std::default_delete<C2Component>());
+  }
+
+  c2_status_t createInterface(
+      std::shared_ptr<C2ComponentInterface>* const intf) {
+    if (!mFactory) {
+      return C2_NO_INIT;
+    }
+    return mFactory->createInterface(
+        kPlaceholderId, intf, std::default_delete<C2ComponentInterface>());
+  }
+
+  ::C2ComponentFactory *getFactory() { return mFactory; }
+
+private:
+  static constexpr ::c2_node_id_t kPlaceholderId = 0;
+
+  ::C2ComponentFactory *mFactory;
+};
+
+TEST_F(C2SoftCodecTest, PictureSizeInfoTest) {
+  std::shared_ptr<C2ComponentInterface> interface;
+  c2_status_t status = createInterface(&interface);
+  ASSERT_EQ(status, C2_OK) << "Error in createInterface";
+  ASSERT_NE(interface, nullptr) << "interface is null";
+
+  std::unique_ptr<C2StreamPictureSizeInfo::output> param =
+      std::make_unique<C2StreamPictureSizeInfo::output>();
+  std::vector<C2FieldSupportedValuesQuery> validValueInfos = {
+      C2FieldSupportedValuesQuery::Current(
+          C2ParamField(param.get(), &C2StreamPictureSizeInfo::width)),
+      C2FieldSupportedValuesQuery::Current(
+          C2ParamField(param.get(), &C2StreamPictureSizeInfo::height))};
+  status = interface->querySupportedValues_vb(validValueInfos, C2_MAY_BLOCK);
+  ASSERT_EQ(status, C2_OK) << "Error in querySupportedValues_vb";
+  ASSERT_EQ(validValueInfos.size(), 2) << "querySupportedValues_vb didn't return 2 values";
+
+  ASSERT_EQ(validValueInfos[0].values.range.max.ref<uint32_t>(), 1920)
+      << "Incorrect maximum value for width";
+  ASSERT_EQ(validValueInfos[1].values.range.max.ref<uint32_t>(), 1920)
+      << "Incorrect maximum value for height";
+  ASSERT_EQ(validValueInfos[0].values.range.min.ref<uint32_t>(), 2)
+      << "Incorrect minimum value for width";
+  ASSERT_EQ(validValueInfos[1].values.range.min.ref<uint32_t>(), 2)
+      << "Incorrect minimum value for height";
+  ASSERT_EQ(validValueInfos[0].values.range.step.ref<uint32_t>(), 2)
+      << "Incorrect alignment value for width";
+  ASSERT_EQ(validValueInfos[1].values.range.step.ref<uint32_t>(), 2)
+      << "Incorrect alignment value for height";
+
+  return;
+}
+
+int main(int argc, char** argv) {
+  ::testing::InitGoogleTest(&argc, argv);
+  int status = RUN_ALL_TESTS();
+  ALOGV("Test result = %d\n", status);
+  return status;
+}
diff --git a/media/codec2/components/vorbis/Android.bp b/media/codec2/components/vorbis/Android.bp
index bc1c380..ccf6f20 100644
--- a/media/codec2/components/vorbis/Android.bp
+++ b/media/codec2/components/vorbis/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_vorbis_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_vorbis_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_vorbisdec",
     defaults: [
         "libcodec2_soft-defaults",
diff --git a/media/codec2/components/vorbis/C2SoftVorbisDec.cpp b/media/codec2/components/vorbis/C2SoftVorbisDec.cpp
index a8b5377..899fe9b 100644
--- a/media/codec2/components/vorbis/C2SoftVorbisDec.cpp
+++ b/media/codec2/components/vorbis/C2SoftVorbisDec.cpp
@@ -477,11 +477,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftVorbisDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/vpx/Android.bp b/media/codec2/components/vpx/Android.bp
index 34f5753..bb6a545 100644
--- a/media/codec2/components/vpx/Android.bp
+++ b/media/codec2/components/vpx/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codec2_components_vpx_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codec2_components_vpx_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libcodec2_soft_vp9dec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -14,7 +33,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_vp8dec",
     defaults: [
         "libcodec2_soft-defaults",
@@ -26,7 +45,7 @@
     shared_libs: ["libvpx"],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_vp9enc",
     defaults: [
         "libcodec2_soft-defaults",
@@ -43,7 +62,7 @@
     cflags: ["-DVP9"],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2_soft_vp8enc",
     defaults: [
         "libcodec2_soft-defaults",
@@ -57,4 +76,3 @@
 
     shared_libs: ["libvpx"],
 }
-
diff --git a/media/codec2/components/vpx/C2SoftVp8Enc.cpp b/media/codec2/components/vpx/C2SoftVp8Enc.cpp
index f18f5d0..049ec38 100644
--- a/media/codec2/components/vpx/C2SoftVp8Enc.cpp
+++ b/media/codec2/components/vpx/C2SoftVp8Enc.cpp
@@ -101,11 +101,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftVp8EncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/vpx/C2SoftVp9Enc.cpp b/media/codec2/components/vpx/C2SoftVp9Enc.cpp
index 740dbda..6401521 100644
--- a/media/codec2/components/vpx/C2SoftVp9Enc.cpp
+++ b/media/codec2/components/vpx/C2SoftVp9Enc.cpp
@@ -131,11 +131,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftVp9EncFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/vpx/C2SoftVpxDec.cpp b/media/codec2/components/vpx/C2SoftVpxDec.cpp
index 3eef1e3..2953d90 100644
--- a/media/codec2/components/vpx/C2SoftVpxDec.cpp
+++ b/media/codec2/components/vpx/C2SoftVpxDec.cpp
@@ -631,31 +631,30 @@
 }
 
 static void copyOutputBufferToYuvPlanarFrame(
-        uint8_t *dst, const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV,
+        uint8_t *dstY, uint8_t *dstU, uint8_t *dstV,
+        const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV,
         size_t srcYStride, size_t srcUStride, size_t srcVStride,
         size_t dstYStride, size_t dstUVStride,
         uint32_t width, uint32_t height) {
-    uint8_t *dstStart = dst;
 
     for (size_t i = 0; i < height; ++i) {
-         memcpy(dst, srcY, width);
+         memcpy(dstY, srcY, width);
          srcY += srcYStride;
-         dst += dstYStride;
+         dstY += dstYStride;
     }
 
-    dst = dstStart + dstYStride * height;
     for (size_t i = 0; i < height / 2; ++i) {
-         memcpy(dst, srcV, width / 2);
+         memcpy(dstV, srcV, width / 2);
          srcV += srcVStride;
-         dst += dstUVStride;
+         dstV += dstUVStride;
     }
 
-    dst = dstStart + (dstYStride * height) + (dstUVStride * height / 2);
     for (size_t i = 0; i < height / 2; ++i) {
-         memcpy(dst, srcU, width / 2);
+         memcpy(dstU, srcU, width / 2);
          srcU += srcUStride;
-         dst += dstUVStride;
+         dstU += dstUVStride;
     }
+
 }
 
 static void convertYUV420Planar16ToY410(uint32_t *dst,
@@ -721,16 +720,12 @@
     return;
 }
 
-static void convertYUV420Planar16ToYUV420Planar(uint8_t *dst,
+static void convertYUV420Planar16ToYUV420Planar(
+        uint8_t *dstY, uint8_t *dstU, uint8_t *dstV,
         const uint16_t *srcY, const uint16_t *srcU, const uint16_t *srcV,
         size_t srcYStride, size_t srcUStride, size_t srcVStride,
-        size_t dstYStride, size_t dstUVStride, size_t width, size_t height) {
-
-    uint8_t *dstY = (uint8_t *)dst;
-    size_t dstYSize = dstYStride * height;
-    size_t dstUVSize = dstUVStride * height / 2;
-    uint8_t *dstV = dstY + dstYSize;
-    uint8_t *dstU = dstV + dstUVSize;
+        size_t dstYStride, size_t dstUVStride,
+        size_t width, size_t height) {
 
     for (size_t y = 0; y < height; ++y) {
         for (size_t x = 0; x < width; ++x) {
@@ -823,7 +818,10 @@
            block->width(), block->height(), mWidth, mHeight,
            ((c2_cntr64_t *)img->user_priv)->peekll());
 
-    uint8_t *dst = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
+    uint8_t *dstY = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_Y]);
+    uint8_t *dstU = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_U]);
+    uint8_t *dstV = const_cast<uint8_t *>(wView.data()[C2PlanarLayout::PLANE_V]);
+
     size_t srcYStride = img->stride[VPX_PLANE_Y];
     size_t srcUStride = img->stride[VPX_PLANE_U];
     size_t srcVStride = img->stride[VPX_PLANE_V];
@@ -842,18 +840,18 @@
             constexpr size_t kHeight = 64;
             for (; i < mHeight; i += kHeight) {
                 queue->entries.push_back(
-                        [dst, srcY, srcU, srcV,
+                        [dstY, srcY, srcU, srcV,
                          srcYStride, srcUStride, srcVStride, dstYStride,
                          width = mWidth, height = std::min(mHeight - i, kHeight)] {
                             convertYUV420Planar16ToY410(
-                                    (uint32_t *)dst, srcY, srcU, srcV, srcYStride / 2,
+                                    (uint32_t *)dstY, srcY, srcU, srcV, srcYStride / 2,
                                     srcUStride / 2, srcVStride / 2, dstYStride / sizeof(uint32_t),
                                     width, height);
                         });
                 srcY += srcYStride / 2 * kHeight;
                 srcU += srcUStride / 2 * (kHeight / 2);
                 srcV += srcVStride / 2 * (kHeight / 2);
-                dst += dstYStride * kHeight;
+                dstY += dstYStride * kHeight;
             }
             CHECK_EQ(0u, queue->numPending);
             queue->numPending = queue->entries.size();
@@ -862,8 +860,9 @@
                 queue.waitForCondition(queue->cond);
             }
         } else {
-            convertYUV420Planar16ToYUV420Planar(dst, srcY, srcU, srcV, srcYStride / 2,
-                                                srcUStride / 2, srcVStride / 2,
+            convertYUV420Planar16ToYUV420Planar(dstY, dstU, dstV,
+                                                srcY, srcU, srcV,
+                                                srcYStride / 2, srcUStride / 2, srcVStride / 2,
                                                 dstYStride, dstUVStride,
                                                 mWidth, mHeight);
         }
@@ -871,8 +870,10 @@
         const uint8_t *srcY = (const uint8_t *)img->planes[VPX_PLANE_Y];
         const uint8_t *srcU = (const uint8_t *)img->planes[VPX_PLANE_U];
         const uint8_t *srcV = (const uint8_t *)img->planes[VPX_PLANE_V];
+
         copyOutputBufferToYuvPlanarFrame(
-                dst, srcY, srcU, srcV,
+                dstY, dstU, dstV,
+                srcY, srcU, srcV,
                 srcYStride, srcUStride, srcVStride,
                 dstYStride, dstUVStride,
                 mWidth, mHeight);
@@ -947,11 +948,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftVpxFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/components/xaac/Android.bp b/media/codec2/components/xaac/Android.bp
index 7795cc1..bb3efb5 100644
--- a/media/codec2/components/xaac/Android.bp
+++ b/media/codec2/components/xaac/Android.bp
@@ -1,8 +1,18 @@
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libcodec2_soft_xaacdec",
     defaults: [
         "libcodec2_soft-defaults",
         "libcodec2_soft_sanitize_all-defaults",
+	"libcodec2_soft_sanitize_cfi-defaults",
     ],
 
     srcs: ["C2SoftXaacDec.cpp"],
diff --git a/media/codec2/components/xaac/C2SoftXaacDec.cpp b/media/codec2/components/xaac/C2SoftXaacDec.cpp
index 951d058..6deafda 100644
--- a/media/codec2/components/xaac/C2SoftXaacDec.cpp
+++ b/media/codec2/components/xaac/C2SoftXaacDec.cpp
@@ -1600,11 +1600,13 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" ::C2ComponentFactory* CreateCodec2Factory() {
     ALOGV("in %s", __func__);
     return new ::android::C2SoftXaacDecFactory();
 }
 
+__attribute__((cfi_canonical_jump_table))
 extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory) {
     ALOGV("in %s", __func__);
     delete factory;
diff --git a/media/codec2/core/Android.bp b/media/codec2/core/Android.bp
index ce1c9ac..64999b7 100644
--- a/media/codec2/core/Android.bp
+++ b/media/codec2/core/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libcodec2_headers",
     vendor_available: true,
@@ -5,7 +14,7 @@
     export_include_dirs: ["include"],
 }
 
-cc_library_shared {
+cc_library {
     name: "libcodec2",
     vendor_available: true,
     min_sdk_version: "29",
@@ -21,6 +30,10 @@
         "-Werror",
     ],
 
+    header_abi_checker: {
+        check_all_apis: true,
+    },
+
     header_libs: [
         "libcodec2_headers",
         "libhardware_headers",
@@ -48,4 +61,3 @@
 
     ldflags: ["-Wl,-Bsymbolic"],
 }
-
diff --git a/media/codec2/core/include/C2Buffer.h b/media/codec2/core/include/C2Buffer.h
index 3d3587c..fe37b05 100644
--- a/media/codec2/core/include/C2Buffer.h
+++ b/media/codec2/core/include/C2Buffer.h
@@ -734,6 +734,22 @@
     }
 
     virtual ~C2Allocator() = default;
+
+    /**
+     * Returns a true if the handle looks valid for this allocator.
+     *
+     * It does not actually validate that the handle represents a valid allocation (by this
+     * allocator), only that the handle could have been returned by this allocator. As such,
+     * multiple allocators may return true for looksValid for the same handle.
+     *
+     * This method MUST be "non-blocking", MUST not access kernel and/or device drivers, and
+     * return within 1us.
+     *
+     * \param handle      the handle for an existing allocation (possibly from another
+     *                    allocator)
+     */
+    virtual bool checkHandle(const C2Handle *const handle) const = 0;
+
 protected:
     C2Allocator() = default;
 };
@@ -2156,9 +2172,12 @@
 };
 
 /**
- * An extension of C2Info objects that can contain arbitrary buffer data.
+ * A const metadata object that can contain arbitrary buffer data.
  *
- * \note This object is not describable and contains opaque data.
+ * This object is not an actual C2Info and is not attached to buffers (C2Buffer), but rather to
+ * frames (C2FrameData). It is not describable via C2ParamDescriptor.
+ *
+ * C2InfoBuffer is a const object that can be allocated on stack and is copiable.
  */
 class C2InfoBuffer {
 public:
@@ -2167,14 +2186,65 @@
      *
      * \return the parameter index.
      */
-    const C2Param::Index index() const;
+    const C2Param::Index index() const { return mIndex; }
 
     /**
      * Gets the buffer's data.
      *
      * \return the buffer's data.
      */
-    const C2BufferData data() const;
+    const C2BufferData data() const { return mData; }
+
+    /// Returns a clone of this as a global info buffer.
+    C2InfoBuffer asGlobal() const {
+        C2Param::Index index = mIndex;
+        index.convertToGlobal();
+        return C2InfoBuffer(index, mData);
+    }
+
+    /// Returns a clone of this as a port info buffer.
+    C2InfoBuffer asPort(bool output) const {
+        C2Param::Index index = mIndex;
+        index.convertToPort(output);
+        return C2InfoBuffer(index, mData);
+    }
+
+    /// Returns a clone of this as a stream info buffer.
+    C2InfoBuffer asStream(bool output, unsigned stream) const {
+        C2Param::Index index = mIndex;
+        index.convertToStream(output, stream);
+        return C2InfoBuffer(index, mData);
+    }
+
+    /**
+     * Creates a global info buffer containing a single linear block.
+     *
+     * \param index the core parameter index of this info buffer.
+     * \param block the content of the info buffer.
+     *
+     * \return shared pointer to the created info buffer.
+     */
+    static C2InfoBuffer CreateLinearBuffer(C2Param::CoreIndex index, const C2ConstLinearBlock &block);
+
+    /**
+     * Creates a global info buffer containing a single graphic block.
+     *
+     * \param index the core parameter index of this info buffer.
+     * \param block the content of the info buffer.
+     *
+     * \return shared pointer to the created info buffer.
+     */
+    static C2InfoBuffer CreateGraphicBuffer(C2Param::CoreIndex index, const C2ConstGraphicBlock &block);
+
+protected:
+    // no public constructor
+    explicit C2InfoBuffer(C2Param::Index index, const std::vector<C2ConstLinearBlock> &blocks);
+    explicit C2InfoBuffer(C2Param::Index index, const std::vector<C2ConstGraphicBlock> &blocks);
+
+private:
+    C2Param::Index mIndex;
+    C2BufferData mData;
+    explicit C2InfoBuffer(C2Param::Index index, const C2BufferData &data);
 };
 
 /// @}
diff --git a/media/codec2/core/include/C2Config.h b/media/codec2/core/include/C2Config.h
index 29bccd5..752140a 100644
--- a/media/codec2/core/include/C2Config.h
+++ b/media/codec2/core/include/C2Config.h
@@ -151,6 +151,7 @@
 
     /* protected content */
     kParamIndexSecureMode,
+    kParamIndexEncryptedBuffer, // info-buffer, used with SM_READ_PROTECTED_WITH_ENCRYPTED
 
     // deprecated
     kParamIndexDelayRequest = kParamIndexDelay | C2Param::CoreIndex::IS_REQUEST_FLAG,
@@ -221,6 +222,7 @@
     kParamIndexDrcEffectType, // drc, enum
     kParamIndexDrcOutputLoudness, // drc, float (dBFS)
     kParamIndexDrcAlbumMode, // drc, enum
+    kParamIndexAudioFrameSize, // int
 
     /* ============================== platform-defined parameters ============================== */
 
@@ -249,6 +251,13 @@
 
     // low latency mode
     kParamIndexLowLatencyMode, // bool
+
+    // tunneled codec
+    kParamIndexTunneledMode, // struct
+    kParamIndexTunnelHandle, // int32[]
+    kParamIndexTunnelSystemTime, // int64
+
+    kParamIndexStoreDmaBufUsage,  // store, struct
 };
 
 }
@@ -1137,6 +1146,8 @@
 C2ENUM(C2Config::secure_mode_t, uint32_t,
     SM_UNPROTECTED,    ///< no content protection
     SM_READ_PROTECTED, ///< input and output buffers shall be protected from reading
+    /// both read protected and readable encrypted buffers are used
+    SM_READ_PROTECTED_WITH_ENCRYPTED,
 )
 
 typedef C2GlobalParam<C2Tuning, C2SimpleValueStruct<C2Config::secure_mode_t>, kParamIndexSecureMode>
@@ -1962,9 +1973,20 @@
 /**
  * DRC output loudness in dBFS. Retrieved during decoding
  */
- typedef C2StreamParam<C2Info, C2FloatValue, kParamIndexDrcOutputLoudness>
+typedef C2StreamParam<C2Info, C2FloatValue, kParamIndexDrcOutputLoudness>
         C2StreamDrcOutputLoudnessTuning;
- constexpr char C2_PARAMKEY_DRC_OUTPUT_LOUDNESS[] = "output.drc.output-loudness";
+constexpr char C2_PARAMKEY_DRC_OUTPUT_LOUDNESS[] = "output.drc.output-loudness";
+
+/**
+ * Audio frame size in samples.
+ *
+ * Audio encoders can expose this parameter to signal the desired audio frame
+ * size that corresponds to a single coded access unit.
+ * Default value is 0, meaning that the encoder accepts input buffers of any size.
+ */
+typedef C2StreamParam<C2Info, C2Uint32Value, kParamIndexAudioFrameSize>
+        C2StreamAudioFrameSizeInfo;
+constexpr char C2_PARAMKEY_AUDIO_FRAME_SIZE[] = "raw.audio-frame-size";
 
 /* --------------------------------------- AAC components --------------------------------------- */
 
@@ -2036,6 +2058,33 @@
         C2StoreIonUsageInfo;
 
 /**
+ * This structure describes the preferred DMA-Buf allocation parameters for a given memory usage.
+ */
+struct C2StoreDmaBufUsageStruct {
+    inline C2StoreDmaBufUsageStruct() { memset(this, 0, sizeof(*this)); }
+
+    inline C2StoreDmaBufUsageStruct(size_t flexCount, uint64_t usage_, uint32_t capacity_)
+        : usage(usage_), capacity(capacity_), allocFlags(0) {
+        memset(heapName, 0, flexCount);
+    }
+
+    uint64_t usage;                         ///< C2MemoryUsage
+    uint32_t capacity;                      ///< capacity
+    int32_t allocFlags;                     ///< ion allocation flags
+    char heapName[];                        ///< dmabuf heap name
+
+    DEFINE_AND_DESCRIBE_FLEX_C2STRUCT(StoreDmaBufUsage, heapName)
+    C2FIELD(usage, "usage")
+    C2FIELD(capacity, "capacity")
+    C2FIELD(allocFlags, "alloc-flags")
+    C2FIELD(heapName, "heap-name")
+};
+
+// store, private
+typedef C2GlobalParam<C2Info, C2StoreDmaBufUsageStruct, kParamIndexStoreDmaBufUsage>
+        C2StoreDmaBufUsageInfo;
+
+/**
  * Flexible pixel format descriptors
  */
 struct C2FlexiblePixelFormatDescriptorStruct {
@@ -2182,6 +2231,79 @@
 typedef C2PortParam<C2Tuning, C2TimestampGapAdjustmentStruct> C2PortTimestampGapTuning;
 constexpr char C2_PARAMKEY_INPUT_SURFACE_TIMESTAMP_ADJUSTMENT[] = "input-surface.timestamp-adjustment";
 
+/* ===================================== TUNNELED CODEC ==================================== */
+
+/**
+ * Tunneled codec control.
+ */
+struct C2TunneledModeStruct {
+    /// mode
+    enum mode_t : uint32_t;
+    /// sync type
+    enum sync_type_t : uint32_t;
+
+    inline C2TunneledModeStruct() = default;
+
+    inline C2TunneledModeStruct(
+            size_t flexCount, mode_t mode_, sync_type_t type, std::vector<int32_t> id)
+        : mode(mode_), syncType(type) {
+        memcpy(&syncId, &id[0], c2_min(id.size(), flexCount) * FLEX_SIZE);
+    }
+
+    inline C2TunneledModeStruct(size_t flexCount, mode_t mode_, sync_type_t type, int32_t id)
+        : mode(mode_), syncType(type) {
+        if (flexCount >= 1) {
+            syncId[0] = id;
+        }
+    }
+
+    mode_t mode;          ///< tunneled mode
+    sync_type_t syncType; ///< type of sync used for tunneled mode
+    int32_t syncId[];     ///< sync id
+
+    DEFINE_AND_DESCRIBE_FLEX_C2STRUCT(TunneledMode, syncId)
+    C2FIELD(mode, "mode")
+    C2FIELD(syncType, "sync-type")
+    C2FIELD(syncId, "sync-id")
+
+};
+
+C2ENUM(C2TunneledModeStruct::mode_t, uint32_t,
+    NONE,
+    SIDEBAND,
+);
+
+
+C2ENUM(C2TunneledModeStruct::sync_type_t, uint32_t,
+    REALTIME,
+    AUDIO_HW_SYNC,
+    HW_AV_SYNC,
+);
+
+/**
+ * Configure tunneled mode
+ */
+typedef C2PortParam<C2Tuning, C2TunneledModeStruct, kParamIndexTunneledMode>
+        C2PortTunneledModeTuning;
+constexpr char C2_PARAMKEY_TUNNELED_RENDER[] = "output.tunneled-render";
+
+/**
+ * Tunneled mode handle. The meaning of this is depends on the
+ * tunneled mode. If the tunneled mode is SIDEBAND, this is the
+ * sideband handle.
+ */
+typedef C2PortParam<C2Tuning, C2Int32Array, kParamIndexTunnelHandle> C2PortTunnelHandleTuning;
+constexpr char C2_PARAMKEY_OUTPUT_TUNNEL_HANDLE[] = "output.tunnel-handle";
+
+/**
+ * The system time using CLOCK_MONOTONIC in nanoseconds at the tunnel endpoint.
+ * For decoders this is the render time for the output frame and
+ * this corresponds to the media timestamp of the output frame.
+ */
+typedef C2PortParam<C2Info, C2SimpleValueStruct<int64_t>, kParamIndexTunnelSystemTime>
+        C2PortTunnelSystemTime;
+constexpr char C2_PARAMKEY_OUTPUT_RENDER_TIME[] = "output.render-time";
+
 /// @}
 
 #endif  // C2CONFIG_H_
diff --git a/media/codec2/core/include/C2Enum.h b/media/codec2/core/include/C2Enum.h
index b0fad8f..da1f43b 100644
--- a/media/codec2/core/include/C2Enum.h
+++ b/media/codec2/core/include/C2Enum.h
@@ -54,7 +54,7 @@
 /// \note this will contain any initialization, which we will remove when converting to lower-case
 #define _C2_GET_ENUM_NAME(x, y) #x
 /// mapper to get value of enum
-#define _C2_GET_ENUM_VALUE(x, type) (_C2EnumConst<type>)x
+#define _C2_GET_ENUM_VALUE(x, type_) (_C2EnumConst<typename std::underlying_type<type_>::type>)type_::x
 
 /// \endcond
 
@@ -106,7 +106,7 @@
 template<> \
 C2FieldDescriptor::NamedValuesType C2FieldDescriptor::namedValuesFor(const name &r __unused) { \
     return _C2EnumUtils::sanitizeEnumValues( \
-            std::vector<C2Value::Primitive> { _C2_MAP(_C2_GET_ENUM_VALUE, type, __VA_ARGS__) }, \
+            std::vector<C2Value::Primitive> { _C2_MAP(_C2_GET_ENUM_VALUE, name, __VA_ARGS__) }, \
             { _C2_MAP(_C2_GET_ENUM_NAME, type, __VA_ARGS__) }, \
             prefix); \
 }
diff --git a/media/codec2/core/include/C2Param.h b/media/codec2/core/include/C2Param.h
index 51d417a..e938f96 100644
--- a/media/codec2/core/include/C2Param.h
+++ b/media/codec2/core/include/C2Param.h
@@ -317,7 +317,8 @@
         DEFINE_FIELD_BASED_COMPARISON_OPERATORS(Index, mIndex)
 
     private:
-        friend struct C2Param;           // for setStream, MakeStreamId, isValid
+        friend class C2InfoBuffer;       // for convertTo*
+        friend struct C2Param;           // for setStream, MakeStreamId, isValid, convertTo*
         friend struct _C2ParamInspector; // for testing
 
         /**
@@ -508,6 +509,14 @@
         return _mIndex.setPort(output);
     }
 
+    /// sets the size of this parameter.
+    inline void setSize(size_t size) {
+        if (size < sizeof(C2Param)) {
+            size = 0;
+        }
+        _mSize = c2_min(size, _mSize);
+    }
+
 public:
     /// invalidate this parameter. There is no recovery from this call; e.g. parameter
     /// cannot be 'corrected' to be valid.
diff --git a/media/codec2/core/include/C2ParamDef.h b/media/codec2/core/include/C2ParamDef.h
index 0a33283..d578820 100644
--- a/media/codec2/core/include/C2ParamDef.h
+++ b/media/codec2/core/include/C2ParamDef.h
@@ -97,6 +97,9 @@
         PARAM_TYPE = CoreIndex | TypeFlags
     };
 
+    // the underlying param struct type
+    typedef S Struct;
+
 protected:
     enum : uint32_t {
         FLEX_SIZE = 0,
@@ -270,6 +273,11 @@
         } \
         return 0; \
     } \
+    inline void setFlexCount(size_t count) { \
+        if (count < flexCount()) { \
+            this->setSize(sizeof(_Type) + _Type::FLEX_SIZE * count); \
+        } \
+    } \
 
 /// Mark flexible member variable and make structure flexible.
 #define FLEX(cls, m) \
diff --git a/media/codec2/core/include/C2Work.h b/media/codec2/core/include/C2Work.h
index 6923f3e..67084cc 100644
--- a/media/codec2/core/include/C2Work.h
+++ b/media/codec2/core/include/C2Work.h
@@ -161,7 +161,7 @@
     //< for initial work item, these may also come from the parser - if provided
     //< for output buffers, these are the responses to requestedInfos
     std::vector<std::unique_ptr<C2Param>>      configUpdate;
-    std::vector<std::shared_ptr<C2InfoBuffer>> infoBuffers;
+    std::vector<C2InfoBuffer> infoBuffers;
 };
 
 struct C2Worklet {
diff --git a/media/codec2/faultinjection/Android.bp b/media/codec2/faultinjection/Android.bp
index a0ad3ce..c04ecbe 100644
--- a/media/codec2/faultinjection/Android.bp
+++ b/media/codec2/faultinjection/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libcodec2_component_wrapper",
     vendor_available: true,
@@ -26,4 +35,3 @@
 
     ldflags: ["-Wl,-Bsymbolic"],
 }
-
diff --git a/media/codec2/fuzzer/Android.bp b/media/codec2/fuzzer/Android.bp
new file mode 100644
index 0000000..bd1fac6
--- /dev/null
+++ b/media/codec2/fuzzer/Android.bp
@@ -0,0 +1,342 @@
+/*
+ * Copyright (C) 2020 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.
+ *
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_defaults {
+    name: "C2Fuzzer-defaults",
+
+    srcs: [
+        "C2Fuzzer.cpp",
+    ],
+
+    static_libs: [
+        "liblog",
+        "libion",
+        "libfmq",
+        "libbase",
+        "libutils",
+        "libcutils",
+        "libcodec2",
+        "libhidlbase",
+        "libdmabufheap",
+        "libcodec2_vndk",
+        "libnativewindow",
+        "libcodec2_soft_common",
+        "libsfplugin_ccodec_utils",
+        "libstagefright_foundation",
+        "libstagefright_bufferpool@2.0.1",
+        "android.hardware.graphics.mapper@2.0",
+        "android.hardware.graphics.mapper@3.0",
+        "android.hardware.media.bufferpool@2.0",
+        "android.hardware.graphics.allocator@2.0",
+        "android.hardware.graphics.allocator@3.0",
+        "android.hardware.graphics.bufferqueue@2.0",
+    ],
+
+    shared_libs: [
+        "libui",
+        "libdl",
+        "libbinder",
+        "libhardware",
+        "libvndksupport",
+        "libprocessgroup",
+    ],
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerAvcDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.avc.decoder\"",
+    ],
+
+    static_libs: [
+        "libavcdec",
+        "libcodec2_soft_avcdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerHevcDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.hevc.decoder\"",
+    ],
+
+    static_libs: [
+        "libhevcdec",
+        "libcodec2_soft_hevcdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerMpeg2Dec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.mpeg2.decoder\"",
+    ],
+
+    static_libs: [
+        "libmpeg2dec",
+        "libcodec2_soft_mpeg2dec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerMpeg4Dec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.mpeg4.decoder\"",
+    ],
+
+    static_libs: [
+        "libstagefright_m4vh263dec",
+        "libcodec2_soft_mpeg4dec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerH263Dec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.h263.decoder\"",
+    ],
+
+    static_libs: [
+        "libstagefright_m4vh263dec",
+        "libcodec2_soft_h263dec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerVp8Dec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.vp8.decoder\"",
+    ],
+
+    static_libs: [
+        "libvpx",
+        "libcodec2_soft_vp8dec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerVp9Dec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.vp9.decoder\"",
+    ],
+
+    static_libs: [
+        "libvpx",
+        "libcodec2_soft_vp9dec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerAacDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.aac.decoder\"",
+    ],
+
+    static_libs: [
+        "libFraunhoferAAC",
+        "libcodec2_soft_aacdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerAmrnbDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.amrnb.decoder\"",
+    ],
+
+    static_libs: [
+        "libstagefright_amrnbdec",
+        "libstagefright_amrwbdec",
+        "libstagefright_amrnb_common",
+        "libcodec2_soft_amrnbdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerAmrwbDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.amrwb.decoder\"",
+    ],
+
+    static_libs: [
+        "libstagefright_amrnbdec",
+        "libstagefright_amrwbdec",
+        "libstagefright_amrnb_common",
+        "libcodec2_soft_amrwbdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerFlacDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.flac.decoder\"",
+    ],
+
+    static_libs: [
+        "libFLAC",
+        "libstagefright_flacdec",
+        "libcodec2_soft_flacdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerG711AlawDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.g711.alaw.decoder\"",
+    ],
+
+    static_libs: [
+        "codecs_g711dec",
+        "libcodec2_soft_g711alawdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerG711MlawDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.g711.mlaw.decoder\"",
+    ],
+
+    static_libs: [
+        "codecs_g711dec",
+        "libcodec2_soft_g711mlawdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerGsmDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.gsm.decoder\"",
+    ],
+
+    static_libs: [
+        "libgsm",
+        "libcodec2_soft_gsmdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerMp3Dec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.mp3.decoder\"",
+    ],
+
+    static_libs: [
+        "libstagefright_mp3dec",
+        "libcodec2_soft_mp3dec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerOpusDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.opus.decoder\"",
+    ],
+
+    static_libs: [
+        "libopus",
+        "libcodec2_soft_opusdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerRawDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.raw.decoder\"",
+    ],
+
+    static_libs: [
+        "libcodec2_soft_rawdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerVorbisDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.vorbis.decoder\"",
+    ],
+
+    static_libs: [
+        "libvorbisidec",
+        "libcodec2_soft_vorbisdec",
+    ],
+}
+
+cc_fuzz {
+    name: "C2FuzzerXaacDec",
+    defaults: ["C2Fuzzer-defaults"],
+
+    cflags: [
+        "-DC2COMPONENTNAME=\"c2.android.xaac.decoder\"",
+    ],
+
+    static_libs: [
+        "libxaacdec",
+        "libcodec2_soft_xaacdec",
+    ],
+}
diff --git a/media/codec2/fuzzer/C2Fuzzer.cpp b/media/codec2/fuzzer/C2Fuzzer.cpp
new file mode 100644
index 0000000..51e1013
--- /dev/null
+++ b/media/codec2/fuzzer/C2Fuzzer.cpp
@@ -0,0 +1,317 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+#include <stdio.h>
+
+#include <C2Fuzzer.h>
+
+using namespace android;
+
+class LinearBuffer : public C2Buffer {
+ public:
+  explicit LinearBuffer(const std::shared_ptr<C2LinearBlock>& block)
+      : C2Buffer({block->share(block->offset(), block->size(), ::C2Fence())}) {}
+
+  explicit LinearBuffer(const std::shared_ptr<C2LinearBlock>& block, size_t size)
+      : C2Buffer({block->share(block->offset(), size, ::C2Fence())}) {}
+};
+
+/**
+ * Handle Callback functions onWorkDone_nb(), onTripped_nb(), onError_nb() for C2 Components
+ */
+struct CodecListener : public C2Component::Listener {
+ public:
+  CodecListener(const std::function<void(std::weak_ptr<C2Component> comp,
+                                         std::list<std::unique_ptr<C2Work>>& workItems)>
+                    fn = nullptr)
+      : callBack(fn) {}
+  virtual void onWorkDone_nb(const std::weak_ptr<C2Component> comp,
+                             std::list<std::unique_ptr<C2Work>> workItems) {
+    if (callBack) {
+      callBack(comp, workItems);
+    }
+  }
+
+  virtual void onTripped_nb(const std::weak_ptr<C2Component> comp,
+                            const std::vector<std::shared_ptr<C2SettingResult>> settingResults) {
+    (void)comp;
+    (void)settingResults;
+  }
+
+  virtual void onError_nb(const std::weak_ptr<C2Component> comp, uint32_t errorCode) {
+    (void)comp;
+    (void)errorCode;
+  }
+
+  std::function<void(std::weak_ptr<C2Component> comp,
+                     std::list<std::unique_ptr<C2Work>>& workItems)> callBack;
+};
+
+/**
+ * Buffer source implementations to identify a frame and its size
+ */
+bool Codec2Fuzzer::BufferSource::searchForMarker() {
+  while (true) {
+    if (isMarker()) {
+      return true;
+    }
+    --mReadIndex;
+    if (mReadIndex > mSize) {
+      break;
+    }
+  }
+  return false;
+}
+
+void Codec2Fuzzer::BufferSource::parse() {
+  bool isFrameAvailable = true;
+  size_t bytesRemaining = mSize;
+  while (isFrameAvailable) {
+    isFrameAvailable = searchForMarker();
+    if (isFrameAvailable) {
+      size_t location = mReadIndex + kMarkerSize;
+      bool isCSD = isCSDMarker(location);
+      location += kMarkerSuffixSize;
+      uint8_t* framePtr = const_cast<uint8_t*>(&mData[location]);
+      size_t frameSize = bytesRemaining - location;
+      uint32_t flags = 0;
+      if (mFrameList.empty()) {
+        flags |= C2FrameData::FLAG_END_OF_STREAM;
+      } else if (isCSD) {
+        flags |= C2FrameData::FLAG_CODEC_CONFIG;
+      }
+      mFrameList.emplace_back(std::make_tuple(framePtr, frameSize, flags));
+      bytesRemaining -= (frameSize + kMarkerSize + kMarkerSuffixSize);
+      --mReadIndex;
+    }
+  }
+  if (mFrameList.empty()) {
+    /**
+     * Scenario where input data does not contain the custom frame markers.
+     * Hence feed the entire data as single frame.
+     */
+    mFrameList.emplace_back(
+        std::make_tuple(const_cast<uint8_t*>(mData), 0, C2FrameData::FLAG_END_OF_STREAM));
+    mFrameList.emplace_back(
+        std::make_tuple(const_cast<uint8_t*>(mData), mSize, C2FrameData::FLAG_CODEC_CONFIG));
+  }
+}
+
+FrameData Codec2Fuzzer::BufferSource::getFrame() {
+  FrameData frame = mFrameList.back();
+  mFrameList.pop_back();
+  return frame;
+}
+
+void Codec2Fuzzer::handleWorkDone(std::weak_ptr<C2Component> comp,
+                                  std::list<std::unique_ptr<C2Work>>& workItems) {
+  (void)comp;
+  for (std::unique_ptr<C2Work>& work : workItems) {
+    if (!work->worklets.empty()) {
+      if (work->worklets.front()->output.flags != C2FrameData::FLAG_INCOMPLETE) {
+        mEos = (work->worklets.front()->output.flags & C2FrameData::FLAG_END_OF_STREAM) != 0;
+        work->input.buffers.clear();
+        work->worklets.clear();
+        {
+          std::unique_lock<std::mutex> lock(mQueueLock);
+          mWorkQueue.push_back(std::move(work));
+          mQueueCondition.notify_all();
+        }
+        if (mEos) {
+          {
+            std::lock_guard<std::mutex> waitForDecodeComplete(mDecodeCompleteMutex);
+          }
+          mConditionalVariable.notify_one();
+        }
+      }
+    }
+  }
+}
+
+bool Codec2Fuzzer::initDecoder() {
+  std::vector<std::tuple<C2String, C2ComponentFactory::CreateCodec2FactoryFunc,
+        C2ComponentFactory::DestroyCodec2FactoryFunc>> codec2FactoryFunc;
+
+  codec2FactoryFunc.emplace_back(
+      std::make_tuple(C2COMPONENTNAME, &CreateCodec2Factory, &DestroyCodec2Factory));
+
+  std::shared_ptr<C2ComponentStore> componentStore = GetTestComponentStore(codec2FactoryFunc);
+  if (!componentStore) {
+    return false;
+  }
+
+  std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
+  if (!allocatorStore) {
+    return false;
+  }
+
+  c2_status_t status =
+      allocatorStore->fetchAllocator(C2AllocatorStore::DEFAULT_LINEAR, &mLinearAllocator);
+  if (status != C2_OK) {
+    return false;
+  }
+
+  mLinearPool = std::make_shared<C2PooledBlockPool>(mLinearAllocator, ++mBlockPoolId);
+  if (!mLinearPool) {
+    return false;
+  }
+
+  for (int32_t i = 0; i < kNumberOfC2WorkItems; ++i) {
+    mWorkQueue.emplace_back(new C2Work);
+  }
+
+  status = componentStore->createComponent(C2COMPONENTNAME, &mComponent);
+  if (status != C2_OK) {
+    return false;
+  }
+
+  status = componentStore->createInterface(C2COMPONENTNAME, &mInterface);
+  if (status != C2_OK) {
+    return false;
+  }
+
+  C2ComponentKindSetting kind;
+  C2ComponentDomainSetting domain;
+  status = mInterface->query_vb({&kind, &domain}, {}, C2_MAY_BLOCK, nullptr);
+  if (status != C2_OK) {
+    return false;
+  }
+
+  std::vector<C2Param*> configParams;
+  if (domain.value == DOMAIN_VIDEO) {
+    C2StreamPictureSizeInfo::input inputSize(0u, kWidthOfVideo, kHeightOfVideo);
+    configParams.push_back(&inputSize);
+  } else if (domain.value == DOMAIN_AUDIO) {
+    C2StreamSampleRateInfo::output sampleRateInfo(0u, kSamplingRateOfAudio);
+    C2StreamChannelCountInfo::output channelCountInfo(0u, kChannelsOfAudio);
+    configParams.push_back(&sampleRateInfo);
+    configParams.push_back(&channelCountInfo);
+  }
+
+  mListener.reset(new CodecListener(
+      [this](std::weak_ptr<C2Component> comp, std::list<std::unique_ptr<C2Work>>& workItems) {
+        handleWorkDone(comp, workItems);
+      }));
+  if (!mListener) {
+    return false;
+  }
+
+  status = mComponent->setListener_vb(mListener, C2_DONT_BLOCK);
+  if (status != C2_OK) {
+    return false;
+  }
+
+  std::vector<std::unique_ptr<C2SettingResult>> failures;
+  componentStore->config_sm(configParams, &failures);
+  if (failures.size() != 0) {
+    return false;
+  }
+
+  status = mComponent->start();
+  if (status != C2_OK) {
+    return false;
+  }
+
+  return true;
+}
+
+void Codec2Fuzzer::deInitDecoder() {
+  mComponent->stop();
+  mComponent->reset();
+  mComponent->release();
+  mComponent = nullptr;
+}
+
+void Codec2Fuzzer::decodeFrames(const uint8_t* data, size_t size) {
+  mBufferSource = new BufferSource(data, size);
+  if (!mBufferSource) {
+    return;
+  }
+  mBufferSource->parse();
+  c2_status_t status = C2_OK;
+  size_t numFrames = 0;
+  while (!mBufferSource->isEos()) {
+    uint8_t* frame = nullptr;
+    size_t frameSize = 0;
+    FrameData frameData = mBufferSource->getFrame();
+    frame = std::get<0>(frameData);
+    frameSize = std::get<1>(frameData);
+
+    std::unique_ptr<C2Work> work;
+    {
+      std::unique_lock<std::mutex> lock(mQueueLock);
+      if (mWorkQueue.empty()) mQueueCondition.wait_for(lock, kC2FuzzerTimeOut);
+      if (!mWorkQueue.empty()) {
+        work.swap(mWorkQueue.front());
+        mWorkQueue.pop_front();
+      } else {
+        return;
+      }
+    }
+
+    work->input.flags = (C2FrameData::flags_t)std::get<2>(frameData);
+    work->input.ordinal.timestamp = 0;
+    work->input.ordinal.frameIndex = ++numFrames;
+    work->input.buffers.clear();
+    int32_t alignedSize = C2FUZZER_ALIGN(frameSize, PAGE_SIZE);
+
+    std::shared_ptr<C2LinearBlock> block;
+    status = mLinearPool->fetchLinearBlock(
+        alignedSize, {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE}, &block);
+    if (status != C2_OK || block == nullptr) {
+      return;
+    }
+
+    C2WriteView view = block->map().get();
+    if (view.error() != C2_OK) {
+      return;
+    }
+    memcpy(view.base(), frame, frameSize);
+    work->input.buffers.emplace_back(new LinearBuffer(block, frameSize));
+    work->worklets.clear();
+    work->worklets.emplace_back(new C2Worklet);
+
+    std::list<std::unique_ptr<C2Work>> items;
+    items.push_back(std::move(work));
+    status = mComponent->queue_nb(&items);
+    if (status != C2_OK) {
+      return;
+    }
+  }
+  std::unique_lock<std::mutex> waitForDecodeComplete(mDecodeCompleteMutex);
+  mConditionalVariable.wait_for(waitForDecodeComplete, kC2FuzzerTimeOut, [this] { return mEos; });
+  std::list<std::unique_ptr<C2Work>> c2flushedWorks;
+  mComponent->flush_sm(C2Component::FLUSH_COMPONENT, &c2flushedWorks);
+  delete mBufferSource;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if (size < 1) {
+    return 0;
+  }
+  Codec2Fuzzer* codec = new Codec2Fuzzer();
+  if (!codec) {
+    return 0;
+  }
+  if (codec->initDecoder()) {
+    codec->decodeFrames(data, size);
+  }
+  delete codec;
+  return 0;
+}
diff --git a/media/codec2/fuzzer/C2Fuzzer.h b/media/codec2/fuzzer/C2Fuzzer.h
new file mode 100644
index 0000000..d5ac81a
--- /dev/null
+++ b/media/codec2/fuzzer/C2Fuzzer.h
@@ -0,0 +1,125 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+#ifndef __C2FUZZER_H__
+#define __C2FUZZER_H__
+
+#include <C2AllocatorIon.h>
+#include <C2Buffer.h>
+#include <C2BufferPriv.h>
+#include <C2Component.h>
+#include <C2Config.h>
+#include <C2PlatformSupport.h>
+
+using namespace std::chrono_literals;
+
+extern "C" ::C2ComponentFactory* CreateCodec2Factory();
+extern "C" void DestroyCodec2Factory(::C2ComponentFactory* factory);
+
+namespace android {
+
+#define C2FUZZER_ALIGN(_sz, _align) (((_sz) + ((_align)-1)) & ~((_align)-1))
+
+constexpr std::chrono::milliseconds kC2FuzzerTimeOut = 5000ms;
+constexpr int32_t kNumberOfC2WorkItems = 8;
+constexpr uint32_t kWidthOfVideo = 3840;
+constexpr uint32_t kHeightOfVideo = 2160;
+constexpr uint32_t kSamplingRateOfAudio = 48000;
+constexpr uint32_t kChannelsOfAudio = 8;
+
+typedef std::tuple<uint8_t*, size_t, uint32_t> FrameData;
+
+class Codec2Fuzzer {
+ public:
+  Codec2Fuzzer() = default;
+  ~Codec2Fuzzer() { deInitDecoder(); }
+  bool initDecoder();
+  void deInitDecoder();
+  void decodeFrames(const uint8_t* data, size_t size);
+
+  void handleWorkDone(std::weak_ptr<C2Component> comp,
+                      std::list<std::unique_ptr<C2Work>>& workItems);
+
+ private:
+  class BufferSource {
+   public:
+    BufferSource(const uint8_t* data, size_t size) : mData(data), mSize(size) {
+      mReadIndex = (size <= kMarkerSize) ? 0 : (size - kMarkerSize);
+    }
+    ~BufferSource() {
+      mData = nullptr;
+      mSize = 0;
+      mReadIndex = 0;
+      mFrameList.clear();
+    }
+    bool isEos() { return mFrameList.empty(); }
+    void parse();
+    FrameData getFrame();
+
+   private:
+    bool isMarker() {
+      if ((kMarkerSize < mSize) && (mReadIndex < mSize - kMarkerSize)) {
+        return (memcmp(&mData[mReadIndex], kMarker, kMarkerSize) == 0);
+      } else {
+        return false;
+      }
+    }
+
+    bool isCSDMarker(size_t position) {
+      if ((kMarkerSuffixSize < mSize) && (position < mSize - kMarkerSuffixSize)) {
+        return (memcmp(&mData[position], kCsdMarkerSuffix, kMarkerSuffixSize) == 0);
+      } else {
+        return false;
+      }
+    }
+
+    bool searchForMarker();
+
+    const uint8_t* mData = nullptr;
+    size_t mSize = 0;
+    size_t mReadIndex = 0;
+    std::vector<FrameData> mFrameList;
+    static constexpr uint8_t kMarker[] = "_MARK";
+    static constexpr uint8_t kCsdMarkerSuffix[] = "_H_";
+    static constexpr uint8_t kFrameMarkerSuffix[] = "_F_";
+    // All markers should be 5 bytes long ( sizeof '_MARK' which is 5)
+    static constexpr size_t kMarkerSize = (sizeof(kMarker) - 1);
+    // All marker types should be 3 bytes long ('_H_', '_F_')
+    static constexpr size_t kMarkerSuffixSize = 3;
+  };
+
+  BufferSource* mBufferSource;
+  bool mEos = false;
+  C2BlockPool::local_id_t mBlockPoolId;
+
+  std::shared_ptr<C2BlockPool> mLinearPool;
+  std::shared_ptr<C2Allocator> mLinearAllocator;
+  std::shared_ptr<C2Component::Listener> mListener;
+  std::shared_ptr<C2Component> mComponent;
+  std::shared_ptr<C2ComponentInterface> mInterface;
+  std::mutex mQueueLock;
+  std::condition_variable mQueueCondition;
+  std::list<std::unique_ptr<C2Work>> mWorkQueue;
+  std::mutex mDecodeCompleteMutex;
+  std::condition_variable mConditionalVariable;
+};
+
+}  // namespace android
+
+#endif  // __C2FUZZER_H__
diff --git a/media/codec2/hidl/1.0/utils/Android.bp b/media/codec2/hidl/1.0/utils/Android.bp
index 3b73350..008def8 100644
--- a/media/codec2/hidl/1.0/utils/Android.bp
+++ b/media/codec2/hidl/1.0/utils/Android.bp
@@ -1,5 +1,14 @@
 // DO NOT DEPEND ON THIS DIRECTLY
 // use libcodec2-hidl-client-defaults instead
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libcodec2_hidl_client@1.0",
 
@@ -80,6 +89,7 @@
         "libbase",
         "libcodec2",
         "libcodec2_vndk",
+        "libcodec2_hidl_plugin_stub",
         "libcutils",
         "libhidlbase",
         "liblog",
@@ -93,9 +103,17 @@
         vendor: {
             exclude_shared_libs: [
                 "libstagefright_bufferqueue_helper_novndk",
+                "libcodec2_hidl_plugin_stub",
             ],
             shared_libs: [
                 "libstagefright_bufferqueue_helper",
+                "libcodec2_hidl_plugin",
+            ],
+        },
+        apex: {
+            exclude_shared_libs: [
+                "libcodec2_hidl_plugin",
+                "libcodec2_hidl_plugin_stub",
             ],
         },
     },
diff --git a/media/codec2/hidl/1.0/utils/Component.cpp b/media/codec2/hidl/1.0/utils/Component.cpp
index 8a84601..082c5e3 100644
--- a/media/codec2/hidl/1.0/utils/Component.cpp
+++ b/media/codec2/hidl/1.0/utils/Component.cpp
@@ -22,6 +22,10 @@
 #include <codec2/hidl/1.0/ComponentStore.h>
 #include <codec2/hidl/1.0/InputBufferManager.h>
 
+#ifndef __ANDROID_APEX__
+#include <FilterWrapper.h>
+#endif
+
 #include <hidl/HidlBinderSupport.h>
 #include <utils/Timers.h>
 
@@ -390,10 +394,17 @@
         uint32_t allocatorId,
         createBlockPool_cb _hidl_cb) {
     std::shared_ptr<C2BlockPool> blockPool;
+#ifdef __ANDROID_APEX__
     c2_status_t status = CreateCodec2BlockPool(
             static_cast<C2PlatformAllocatorStore::id_t>(allocatorId),
             mComponent,
             &blockPool);
+#else
+    c2_status_t status = ComponentStore::GetFilterWrapper()->createBlockPool(
+            static_cast<C2PlatformAllocatorStore::id_t>(allocatorId),
+            mComponent,
+            &blockPool);
+#endif
     if (status != C2_OK) {
         blockPool = nullptr;
     }
diff --git a/media/codec2/hidl/1.0/utils/ComponentStore.cpp b/media/codec2/hidl/1.0/utils/ComponentStore.cpp
index 9b9d449..1c0d5b0 100644
--- a/media/codec2/hidl/1.0/utils/ComponentStore.cpp
+++ b/media/codec2/hidl/1.0/utils/ComponentStore.cpp
@@ -35,6 +35,14 @@
 #include <ostream>
 #include <sstream>
 
+#ifndef __ANDROID_APEX__
+#include <codec2/hidl/plugin/FilterPlugin.h>
+#include <dlfcn.h>
+#include <C2Config.h>
+#include <DefaultFilterPlugin.h>
+#include <FilterWrapper.h>
+#endif
+
 namespace android {
 namespace hardware {
 namespace media {
@@ -176,6 +184,16 @@
     return mParameterCache;
 }
 
+#ifndef __ANDROID_APEX__
+// static
+std::shared_ptr<FilterWrapper> ComponentStore::GetFilterWrapper() {
+    constexpr const char kPluginPath[] = "libc2filterplugin.so";
+    static std::shared_ptr<FilterWrapper> wrapper = FilterWrapper::Create(
+            std::make_unique<DefaultFilterPlugin>(kPluginPath));
+    return wrapper;
+}
+#endif
+
 // Methods from ::android::hardware::media::c2::V1_0::IComponentStore
 Return<void> ComponentStore::createComponent(
         const hidl_string& name,
@@ -189,6 +207,9 @@
             mStore->createComponent(name, &c2component));
 
     if (status == Status::OK) {
+#ifndef __ANDROID_APEX__
+        c2component = GetFilterWrapper()->maybeWrapComponent(c2component);
+#endif
         onInterfaceLoaded(c2component->intf());
         component = new Component(c2component, listener, this, pool);
         if (!component) {
@@ -214,8 +235,12 @@
         createInterface_cb _hidl_cb) {
     std::shared_ptr<C2ComponentInterface> c2interface;
     c2_status_t res = mStore->createInterface(name, &c2interface);
+
     sp<IComponentInterface> interface;
     if (res == C2_OK) {
+#ifndef __ANDROID_APEX__
+        c2interface = GetFilterWrapper()->maybeWrapInterface(c2interface);
+#endif
         onInterfaceLoaded(c2interface);
         interface = new ComponentInterface(c2interface, mParameterCache);
     }
@@ -458,7 +483,6 @@
     return Void();
 }
 
-
 }  // namespace utils
 }  // namespace V1_0
 }  // namespace c2
diff --git a/media/codec2/hidl/1.0/utils/include/codec2/hidl/1.0/ComponentStore.h b/media/codec2/hidl/1.0/utils/include/codec2/hidl/1.0/ComponentStore.h
index fe7d048..27e2a05 100644
--- a/media/codec2/hidl/1.0/utils/include/codec2/hidl/1.0/ComponentStore.h
+++ b/media/codec2/hidl/1.0/utils/include/codec2/hidl/1.0/ComponentStore.h
@@ -37,6 +37,8 @@
 #include <vector>
 
 namespace android {
+class FilterWrapper;
+
 namespace hardware {
 namespace media {
 namespace c2 {
@@ -74,6 +76,8 @@
      */
     std::shared_ptr<ParameterCache> getParameterCache() const;
 
+    static std::shared_ptr<FilterWrapper> GetFilterWrapper();
+
     // Methods from ::android::hardware::media::c2::V1_0::IComponentStore.
     virtual Return<void> createComponent(
             const hidl_string& name,
diff --git a/media/codec2/hidl/1.0/utils/types.cpp b/media/codec2/hidl/1.0/utils/types.cpp
index c73cb52..72f7c43 100644
--- a/media/codec2/hidl/1.0/utils/types.cpp
+++ b/media/codec2/hidl/1.0/utils/types.cpp
@@ -895,13 +895,12 @@
         BufferPoolSender* bufferPoolSender,
         std::list<BaseBlock>* baseBlocks,
         std::map<const void*, uint32_t>* baseBlockIndices) {
-    // TODO: C2InfoBuffer is not implemented.
-    (void)d;
-    (void)s;
-    (void)bufferPoolSender;
-    (void)baseBlocks;
-    (void)baseBlockIndices;
-    LOG(INFO) << "InfoBuffer not implemented.";
+    d->index = static_cast<ParamIndex>(s.index());
+    Buffer& dBuffer = d->buffer;
+    if (!objcpy(&dBuffer, s.data(), bufferPoolSender, baseBlocks, baseBlockIndices)) {
+        LOG(ERROR) << "Invalid C2InfoBuffer::data";
+        return false;
+    }
     return true;
 }
 
@@ -943,14 +942,9 @@
 
     d->infoBuffers.resize(s.infoBuffers.size());
     i = 0;
-    for (const std::shared_ptr<C2InfoBuffer>& sInfoBuffer : s.infoBuffers) {
+    for (const C2InfoBuffer& sInfoBuffer : s.infoBuffers) {
         InfoBuffer& dInfoBuffer = d->infoBuffers[i++];
-        if (!sInfoBuffer) {
-            LOG(ERROR) << "Null C2FrameData::infoBuffers["
-                       << i - 1 << "].";
-            return false;
-        }
-        if (!objcpy(&dInfoBuffer, *sInfoBuffer,
+        if (!objcpy(&dInfoBuffer, sInfoBuffer,
                 bufferPoolSender, baseBlocks, baseBlockIndices)) {
             LOG(ERROR) << "Invalid C2FrameData::infoBuffers["
                        << i - 1 << "].";
@@ -1341,6 +1335,68 @@
     return true;
 }
 
+// InfoBuffer -> C2InfoBuffer
+bool objcpy(std::vector<C2InfoBuffer> *d, const InfoBuffer& s,
+        const std::vector<C2BaseBlock>& baseBlocks) {
+
+    // Currently, a non-null C2InfoBufer must contain exactly 1 block.
+    if (s.buffer.blocks.size() == 0) {
+        return true;
+    } else if (s.buffer.blocks.size() != 1) {
+        LOG(ERROR) << "Invalid InfoBuffer::Buffer "
+                      "Currently, a C2InfoBuffer must contain exactly 1 block.";
+        return false;
+    }
+
+    const Block &sBlock = s.buffer.blocks[0];
+    if (sBlock.index >= baseBlocks.size()) {
+        LOG(ERROR) << "Invalid InfoBuffer::Buffer::blocks[0].index: "
+                      "Array index out of range.";
+        return false;
+    }
+    const C2BaseBlock &baseBlock = baseBlocks[sBlock.index];
+
+    // Parse meta.
+    std::vector<C2Param*> sBlockMeta;
+    if (!parseParamsBlob(&sBlockMeta, sBlock.meta)) {
+        LOG(ERROR) << "Invalid InfoBuffer::Buffer::blocks[0].meta.";
+        return false;
+    }
+
+    // Copy fence.
+    C2Fence dFence;
+    if (!objcpy(&dFence, sBlock.fence)) {
+        LOG(ERROR) << "Invalid InfoBuffer::Buffer::blocks[0].fence.";
+        return false;
+    }
+
+    // Construct a block.
+    switch (baseBlock.type) {
+    case C2BaseBlock::LINEAR:
+        if (sBlockMeta.size() == 1 && sBlockMeta[0] != nullptr &&
+            sBlockMeta[0]->size() == sizeof(C2Hidl_RangeInfo)) {
+            C2Hidl_RangeInfo *rangeInfo =
+                    reinterpret_cast<C2Hidl_RangeInfo*>(sBlockMeta[0]);
+            d->emplace_back(C2InfoBuffer::CreateLinearBuffer(
+                    s.index,
+                    baseBlock.linear->share(
+                            rangeInfo->offset, rangeInfo->length, dFence)));
+            return true;
+        }
+        LOG(ERROR) << "Invalid Meta for C2BaseBlock::Linear InfoBuffer.";
+        break;
+    case C2BaseBlock::GRAPHIC:
+        // It's not used now
+        LOG(ERROR) << "Non-Used C2BaseBlock::type for InfoBuffer.";
+        break;
+    default:
+        LOG(ERROR) << "Invalid C2BaseBlock::type for InfoBuffer.";
+        break;
+    }
+
+    return false;
+}
+
 // FrameData -> C2FrameData
 bool objcpy(C2FrameData* d, const FrameData& s,
         const std::vector<C2BaseBlock>& baseBlocks) {
@@ -1375,8 +1431,18 @@
         }
     }
 
-    // TODO: Implement this once C2InfoBuffer has constructors.
     d->infoBuffers.clear();
+    if (s.infoBuffers.size() == 0) {
+        // InfoBuffer is optional
+        return true;
+    }
+    d->infoBuffers.reserve(s.infoBuffers.size());
+    for (const InfoBuffer &sInfoBuffer: s.infoBuffers) {
+        if (!objcpy(&(d->infoBuffers), sInfoBuffer, baseBlocks)) {
+            LOG(ERROR) << "Invalid Framedata::infoBuffers.";
+            return false;
+        }
+    }
     return true;
 }
 
diff --git a/media/codec2/hidl/1.0/vts/functional/Android.bp b/media/codec2/hidl/1.0/vts/functional/Android.bp
index 5ea4825..0ae133c 100644
--- a/media/codec2/hidl/1.0/vts/functional/Android.bp
+++ b/media/codec2/hidl/1.0/vts/functional/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 filegroup {
     name: "media_c2_v1_audio_decode_res",
     path: "res",
@@ -108,4 +117,4 @@
     srcs: [
         "res/bbb_352x288_420p_30fps_32frames.yuv",
     ],
-}
\ No newline at end of file
+}
diff --git a/media/codec2/hidl/1.0/vts/functional/audio/Android.bp b/media/codec2/hidl/1.0/vts/functional/audio/Android.bp
index 014cbe9..624aad2 100644
--- a/media/codec2/hidl/1.0/vts/functional/audio/Android.bp
+++ b/media/codec2/hidl/1.0/vts/functional/audio/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "VtsHalMediaC2V1_0TargetAudioDecTest",
     stem: "vts_media_c2_v1_0_audio_dec_test",
diff --git a/media/codec2/hidl/1.0/vts/functional/common/Android.bp b/media/codec2/hidl/1.0/vts/functional/common/Android.bp
index f9ec5ae..4106be8 100644
--- a/media/codec2/hidl/1.0/vts/functional/common/Android.bp
+++ b/media/codec2/hidl/1.0/vts/functional/common/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_static {
     name: "VtsHalMediaC2V1_0CommonUtil",
     defaults: [
diff --git a/media/codec2/hidl/1.0/vts/functional/component/Android.bp b/media/codec2/hidl/1.0/vts/functional/component/Android.bp
index 7ec64ee..cc019da 100644
--- a/media/codec2/hidl/1.0/vts/functional/component/Android.bp
+++ b/media/codec2/hidl/1.0/vts/functional/component/Android.bp
@@ -14,9 +14,17 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "VtsHalMediaC2V1_0TargetComponentTest",
     defaults: ["VtsHalMediaC2V1_0Defaults"],
     srcs: ["VtsHalMediaC2V1_0TargetComponentTest.cpp"],
 }
-
diff --git a/media/codec2/hidl/1.0/vts/functional/master/Android.bp b/media/codec2/hidl/1.0/vts/functional/master/Android.bp
index 53e323e..40f5201 100644
--- a/media/codec2/hidl/1.0/vts/functional/master/Android.bp
+++ b/media/codec2/hidl/1.0/vts/functional/master/Android.bp
@@ -14,9 +14,17 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "VtsHalMediaC2V1_0TargetMasterTest",
     defaults: ["VtsHalMediaC2V1_0Defaults"],
     srcs: ["VtsHalMediaC2V1_0TargetMasterTest.cpp"],
 }
-
diff --git a/media/codec2/hidl/1.0/vts/functional/video/Android.bp b/media/codec2/hidl/1.0/vts/functional/video/Android.bp
index c7b0c12..f211ecf 100644
--- a/media/codec2/hidl/1.0/vts/functional/video/Android.bp
+++ b/media/codec2/hidl/1.0/vts/functional/video/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "VtsHalMediaC2V1_0TargetVideoDecTest",
     stem: "vts_media_c2_v1_0_video_dec_test",
@@ -40,4 +49,3 @@
     data: [":media_c2_v1_video_encode_res"],
     test_config: "VtsHalMediaC2V1_0TargetVideoEncTest.xml",
 }
-
diff --git a/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoDecTest.cpp b/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoDecTest.cpp
index 12ed725..b520c17 100644
--- a/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoDecTest.cpp
+++ b/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoDecTest.cpp
@@ -734,7 +734,7 @@
             }
             if (timestampMax < timestamp) timestampMax = timestamp;
         }
-        timestampOffset = timestampMax;
+        timestampOffset = timestampMax + 33333;
         eleInfo.close();
 
         // Reset Total frames before second decode loop
diff --git a/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoEncTest.cpp b/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoEncTest.cpp
index ecaf3a8..5bcea5b 100644
--- a/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoEncTest.cpp
+++ b/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoEncTest.cpp
@@ -107,6 +107,13 @@
         mOutputSize = 0u;
         mTimestampDevTest = false;
         if (mCompName == unknown_comp) mDisableTest = true;
+
+        C2SecureModeTuning secureModeTuning{};
+        mComponent->query({&secureModeTuning}, {}, C2_MAY_BLOCK, nullptr);
+        if (secureModeTuning.value == C2Config::SM_READ_PROTECTED) {
+            mDisableTest = true;
+        }
+
         if (mDisableTest) std::cout << "[   WARN   ] Test Disabled \n";
     }
 
diff --git a/media/codec2/hidl/1.1/utils/Android.bp b/media/codec2/hidl/1.1/utils/Android.bp
index 386f6e2..839a910 100644
--- a/media/codec2/hidl/1.1/utils/Android.bp
+++ b/media/codec2/hidl/1.1/utils/Android.bp
@@ -1,5 +1,14 @@
 // DO NOT DEPEND ON THIS DIRECTLY
 // use libcodec2-hidl-client-defaults instead
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libcodec2_hidl_client@1.1",
 
@@ -44,6 +53,12 @@
         "libstagefright_bufferpool@2.0.1",
         "libui",
     ],
+
+    // Device does not boot when global ThinLTO is enabled for this library.
+    // http://b/170595429
+    lto: {
+        never: true,
+    },
 }
 
 
@@ -85,6 +100,7 @@
         "libbase",
         "libcodec2",
         "libcodec2_hidl@1.0",
+        "libcodec2_hidl_plugin_stub",
         "libcodec2_vndk",
         "libcutils",
         "libhidlbase",
@@ -99,9 +115,17 @@
         vendor: {
             exclude_shared_libs: [
                 "libstagefright_bufferqueue_helper_novndk",
+                "libcodec2_hidl_plugin_stub",
             ],
             shared_libs: [
                 "libstagefright_bufferqueue_helper",
+                "libcodec2_hidl_plugin",
+            ],
+        },
+        apex: {
+            exclude_shared_libs: [
+                "libcodec2_hidl_plugin_stub",
+                "libcodec2_hidl_plugin",
             ],
         },
     },
diff --git a/media/codec2/hidl/1.1/utils/Component.cpp b/media/codec2/hidl/1.1/utils/Component.cpp
index ed281e6..1d7d3d8 100644
--- a/media/codec2/hidl/1.1/utils/Component.cpp
+++ b/media/codec2/hidl/1.1/utils/Component.cpp
@@ -22,6 +22,10 @@
 #include <codec2/hidl/1.1/ComponentStore.h>
 #include <codec2/hidl/1.1/InputBufferManager.h>
 
+#ifndef __ANDROID_APEX__
+#include <FilterWrapper.h>
+#endif
+
 #include <hidl/HidlBinderSupport.h>
 #include <utils/Timers.h>
 
@@ -390,10 +394,17 @@
         uint32_t allocatorId,
         createBlockPool_cb _hidl_cb) {
     std::shared_ptr<C2BlockPool> blockPool;
+#ifdef __ANDROID_APEX__
     c2_status_t status = CreateCodec2BlockPool(
             static_cast<C2PlatformAllocatorStore::id_t>(allocatorId),
             mComponent,
             &blockPool);
+#else
+    c2_status_t status = ComponentStore::GetFilterWrapper()->createBlockPool(
+            static_cast<C2PlatformAllocatorStore::id_t>(allocatorId),
+            mComponent,
+            &blockPool);
+#endif
     if (status != C2_OK) {
         blockPool = nullptr;
     }
diff --git a/media/codec2/hidl/1.1/utils/ComponentStore.cpp b/media/codec2/hidl/1.1/utils/ComponentStore.cpp
index 225cd09..163686d 100644
--- a/media/codec2/hidl/1.1/utils/ComponentStore.cpp
+++ b/media/codec2/hidl/1.1/utils/ComponentStore.cpp
@@ -35,6 +35,14 @@
 #include <ostream>
 #include <sstream>
 
+#ifndef __ANDROID_APEX__
+#include <codec2/hidl/plugin/FilterPlugin.h>
+#include <dlfcn.h>
+#include <C2Config.h>
+#include <DefaultFilterPlugin.h>
+#include <FilterWrapper.h>
+#endif
+
 namespace android {
 namespace hardware {
 namespace media {
@@ -176,6 +184,16 @@
     return mParameterCache;
 }
 
+#ifndef __ANDROID_APEX__
+// static
+std::shared_ptr<FilterWrapper> ComponentStore::GetFilterWrapper() {
+    constexpr const char kPluginPath[] = "libc2filterplugin.so";
+    static std::shared_ptr<FilterWrapper> wrapper = FilterWrapper::Create(
+            std::make_unique<DefaultFilterPlugin>(kPluginPath));
+    return wrapper;
+}
+#endif
+
 // Methods from ::android::hardware::media::c2::V1_0::IComponentStore
 Return<void> ComponentStore::createComponent(
         const hidl_string& name,
@@ -189,6 +207,9 @@
             mStore->createComponent(name, &c2component));
 
     if (status == Status::OK) {
+#ifndef __ANDROID_APEX__
+        c2component = GetFilterWrapper()->maybeWrapComponent(c2component);
+#endif
         onInterfaceLoaded(c2component->intf());
         component = new Component(c2component, listener, this, pool);
         if (!component) {
@@ -216,6 +237,9 @@
     c2_status_t res = mStore->createInterface(name, &c2interface);
     sp<IComponentInterface> interface;
     if (res == C2_OK) {
+#ifndef __ANDROID_APEX__
+        c2interface = GetFilterWrapper()->maybeWrapInterface(c2interface);
+#endif
         onInterfaceLoaded(c2interface);
         interface = new ComponentInterface(c2interface, mParameterCache);
     }
diff --git a/media/codec2/hidl/1.1/utils/include/codec2/hidl/1.1/ComponentStore.h b/media/codec2/hidl/1.1/utils/include/codec2/hidl/1.1/ComponentStore.h
index 1f04391..f6daee7 100644
--- a/media/codec2/hidl/1.1/utils/include/codec2/hidl/1.1/ComponentStore.h
+++ b/media/codec2/hidl/1.1/utils/include/codec2/hidl/1.1/ComponentStore.h
@@ -38,6 +38,8 @@
 #include <vector>
 
 namespace android {
+class FilterWrapper;
+
 namespace hardware {
 namespace media {
 namespace c2 {
@@ -75,6 +77,8 @@
      */
     std::shared_ptr<ParameterCache> getParameterCache() const;
 
+    static std::shared_ptr<FilterWrapper> GetFilterWrapper();
+
     // Methods from ::android::hardware::media::c2::V1_0::IComponentStore.
     virtual Return<void> createComponent(
             const hidl_string& name,
diff --git a/media/codec2/hidl/client/Android.bp b/media/codec2/hidl/client/Android.bp
index 3c37990..5a34c30 100644
--- a/media/codec2/hidl/client/Android.bp
+++ b/media/codec2/hidl/client/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libcodec2_client",
 
@@ -39,4 +48,3 @@
     ],
 
 }
-
diff --git a/media/codec2/hidl/client/client.cpp b/media/codec2/hidl/client/client.cpp
index 7e4352d..4650672 100644
--- a/media/codec2/hidl/client/client.cpp
+++ b/media/codec2/hidl/client/client.cpp
@@ -843,6 +843,11 @@
                             return;
                         }
                     });
+            if (!transStatus.isOk()) {
+                LOG(DEBUG) << "SimpleParamReflector -- transaction failed: "
+                           << transStatus.description();
+                descriptor.reset();
+            }
             return descriptor;
         }
 
diff --git a/media/codec2/hidl/plugin/Android.bp b/media/codec2/hidl/plugin/Android.bp
new file mode 100644
index 0000000..873bb02
--- /dev/null
+++ b/media/codec2/hidl/plugin/Android.bp
@@ -0,0 +1,75 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library_headers {
+    name: "libcodec2_hidl_plugin_headers",
+    vendor_available: true,
+    export_include_dirs: [
+        "include",
+    ],
+}
+
+cc_library {
+    name: "libcodec2_hidl_plugin_stub",
+
+    srcs: [
+        "DefaultFilterPlugin.cpp",
+        "FilterWrapperStub.cpp",
+    ],
+
+    header_libs: [
+        "libcodec2_internal", // private
+    ],
+
+    shared_libs: [
+        "libbase",
+        "libcodec2",
+        "libcodec2_vndk",
+        "liblog",
+        "libutils",
+    ],
+
+    export_include_dirs: [
+        "include",
+        "internal",
+    ],
+
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.media.swcodec",
+    ],
+    min_sdk_version: "29",
+}
+
+cc_library {
+    name: "libcodec2_hidl_plugin",
+    vendor: true,
+
+    srcs: [
+        "DefaultFilterPlugin.cpp",
+        "FilterWrapper.cpp",
+    ],
+
+    header_libs: [
+        "libcodec2_internal", // private
+    ],
+
+    shared_libs: [
+        "libbase",
+        "libcodec2",
+        "libcodec2_vndk",
+        "liblog",
+        "libutils",
+    ],
+
+    export_include_dirs: [
+        "include",
+        "internal",
+    ],
+}
diff --git a/media/codec2/hidl/plugin/DefaultFilterPlugin.cpp b/media/codec2/hidl/plugin/DefaultFilterPlugin.cpp
new file mode 100644
index 0000000..cd1bcb0
--- /dev/null
+++ b/media/codec2/hidl/plugin/DefaultFilterPlugin.cpp
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2020 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 "Codec2-DefaultFilterPlugin"
+#include <android-base/logging.h>
+
+#include <set>
+
+#include <dlfcn.h>
+
+#include <C2Config.h>
+#include <C2Debug.h>
+#include <C2ParamInternal.h>
+
+#include <codec2/hidl/plugin/FilterPlugin.h>
+
+#include <DefaultFilterPlugin.h>
+#include <FilterWrapper.h>
+
+namespace android {
+
+DefaultFilterPlugin::DefaultFilterPlugin(const char *pluginPath)
+    : mInit(NO_INIT),
+      mHandle(nullptr),
+      mDestroyPlugin(nullptr),
+      mPlugin(nullptr) {
+    mHandle = dlopen(pluginPath, RTLD_NOW | RTLD_NODELETE);
+    if (!mHandle) {
+        LOG(DEBUG) << "FilterPlugin: no plugin detected";
+        return;
+    }
+    GetFilterPluginVersionFunc getVersion =
+        (GetFilterPluginVersionFunc)dlsym(mHandle, "GetFilterPluginVersion");
+    if (!getVersion) {
+        LOG(WARNING) << "FilterPlugin: GetFilterPluginVersion undefined";
+        return;
+    }
+    int32_t version = getVersion();
+    if (version != FilterPlugin_V1::VERSION) {
+        LOG(WARNING) << "FilterPlugin: unrecognized version (" << version << ")";
+        return;
+    }
+    CreateFilterPluginFunc createPlugin =
+        (CreateFilterPluginFunc)dlsym(mHandle, "CreateFilterPlugin");
+    if (!createPlugin) {
+        LOG(WARNING) << "FilterPlugin: CreateFilterPlugin undefined";
+        return;
+    }
+    mDestroyPlugin =
+        (DestroyFilterPluginFunc)dlsym(mHandle, "DestroyFilterPlugin");
+    if (!mDestroyPlugin) {
+        LOG(WARNING) << "FilterPlugin: DestroyFilterPlugin undefined";
+        return;
+    }
+    mPlugin = (FilterPlugin_V1 *)createPlugin();
+    if (!mPlugin) {
+        LOG(WARNING) << "FilterPlugin: CreateFilterPlugin returned nullptr";
+        return;
+    }
+    mStore = mPlugin->getComponentStore();
+    if (!mStore) {
+        LOG(WARNING) << "FilterPlugin: FilterPlugin_V1::getComponentStore returned nullptr";
+        return;
+    }
+    mInit = OK;
+}
+
+DefaultFilterPlugin::~DefaultFilterPlugin() {
+    if (mHandle) {
+        if (mDestroyPlugin && mPlugin) {
+            mDestroyPlugin(mPlugin);
+            mPlugin = nullptr;
+        }
+        dlclose(mHandle);
+        mHandle = nullptr;
+        mDestroyPlugin = nullptr;
+    }
+}
+
+bool DefaultFilterPlugin::describe(C2String name, FilterWrapper::Descriptor *desc) {
+    if (mInit != OK) {
+        return false;
+    }
+    return mPlugin->describe(name, desc);
+}
+
+bool DefaultFilterPlugin::isFilteringEnabled(const std::shared_ptr<C2ComponentInterface> &intf) {
+    if (mInit != OK) {
+        return false;
+    }
+    return mPlugin->isFilteringEnabled(intf);
+}
+
+}  // namespace android
diff --git a/media/codec2/hidl/plugin/FilterWrapper.cpp b/media/codec2/hidl/plugin/FilterWrapper.cpp
new file mode 100644
index 0000000..0b38bc1
--- /dev/null
+++ b/media/codec2/hidl/plugin/FilterWrapper.cpp
@@ -0,0 +1,921 @@
+/*
+ * Copyright 2020 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 "Codec2-FilterWrapper"
+#include <android-base/logging.h>
+
+#include <set>
+#include <sstream>
+
+#include <dlfcn.h>
+
+#include <C2Config.h>
+#include <C2Debug.h>
+#include <C2ParamInternal.h>
+
+#include <codec2/hidl/plugin/FilterPlugin.h>
+
+#include <FilterWrapper.h>
+
+namespace android {
+
+namespace {
+
+// Indices that the last filter in the chain should consume.
+static constexpr uint32_t kTypesForLastFilter[] = {
+    // In case we have an output surface, we want to use the block pool
+    // backed by the output surface for the output buffer going to the client.
+    C2PortBlockPoolsTuning::output::PARAM_TYPE,
+};
+
+class WrappedDecoderInterface : public C2ComponentInterface {
+public:
+    WrappedDecoderInterface(
+            std::shared_ptr<C2ComponentInterface> intf,
+            std::vector<FilterWrapper::Component> &&filters)
+        : mIntf(intf) {
+        takeFilters(std::move(filters));
+    }
+
+    ~WrappedDecoderInterface() override = default;
+
+    void takeFilters(std::vector<FilterWrapper::Component> &&filters) {
+        std::unique_lock lock(mMutex);
+        std::vector<std::unique_ptr<C2Param>> lastFilterParams;
+        if (!mFilters.empty()) {
+            std::vector<C2Param::Index> indices;
+            std::vector<std::shared_ptr<C2ParamDescriptor>> paramDescs;
+            c2_status_t err = mFilters.back().intf->querySupportedParams_nb(&paramDescs);
+            if (err != C2_OK) {
+                LOG(WARNING) << "WrappedDecoderInterface: " << mFilters.back().traits.name
+                        << " returned error for querySupportedParams_nb; err=" << err;
+                paramDescs.clear();
+            }
+            for (const std::shared_ptr<C2ParamDescriptor> &paramDesc : paramDescs) {
+                C2Param::Index index = paramDesc->index();
+                if (std::count(
+                            std::begin(kTypesForLastFilter),
+                            std::end(kTypesForLastFilter),
+                            index.type()) != 0) {
+                    if (index.forStream()) {
+                        // querySupportedParams does not return per-stream params.
+                        // We only support stream-0 for now.
+                        index = index.withStream(0u);
+                    }
+                    indices.push_back(index);
+                }
+            }
+            if (!indices.empty()) {
+                mFilters.back().intf->query_vb({}, indices, C2_MAY_BLOCK, &lastFilterParams);
+            }
+        }
+
+        // TODO: documentation
+        mFilters = std::move(filters);
+        mTypeToIndexForQuery.clear();
+        mTypeToIndexForConfig.clear();
+        for (size_t i = 0; i < mFilters.size(); ++i) {
+            if (i == 0) {
+                transferParams_l(mIntf, mFilters[0].intf, C2_MAY_BLOCK);
+            } else {
+                transferParams_l(mFilters[i - 1].intf, mFilters[i].intf, C2_MAY_BLOCK);
+            }
+            for (C2Param::Type type : mFilters[i].desc.controlParams) {
+                mTypeToIndexForQuery[type.type()] = i;
+                mTypeToIndexForConfig[type.type() & ~C2Param::CoreIndex::IS_REQUEST_FLAG] = i;
+            }
+            for (C2Param::Type type : mFilters[i].desc.affectedParams) {
+                mTypeToIndexForQuery[type.type()] = i;
+            }
+        }
+        if (!mFilters.empty()) {
+            for (uint32_t type : kTypesForLastFilter) {
+                mTypeToIndexForQuery[type] = mFilters.size() - 1;
+                mTypeToIndexForConfig[type & ~C2Param::CoreIndex::IS_REQUEST_FLAG] =
+                    mFilters.size() - 1;
+            }
+            if (!lastFilterParams.empty()) {
+                std::vector<C2Param *> paramPtrs(lastFilterParams.size());
+                std::transform(
+                        lastFilterParams.begin(),
+                        lastFilterParams.end(),
+                        paramPtrs.begin(),
+                        [](const std::unique_ptr<C2Param> &param) {
+                            return param.get();
+                        });
+                std::vector<std::unique_ptr<C2SettingResult>> failures;
+                mFilters.back().intf->config_vb(paramPtrs, C2_MAY_BLOCK, &failures);
+            }
+        }
+    }
+
+    C2String getName() const override { return mIntf->getName(); }
+
+    c2_node_id_t getId() const override { return mIntf->getId(); }
+
+    c2_status_t query_vb(
+            const std::vector<C2Param *> &stackParams,
+            const std::vector<C2Param::Index> &heapParamIndices,
+            c2_blocking_t mayBlock,
+            std::vector<std::unique_ptr<C2Param>>* const heapParams) const override {
+        std::unique_lock lock(mMutex);
+        std::list<C2Param *> stackParamsList(stackParams.size());
+        std::copy_n(stackParams.begin(), stackParams.size(), stackParamsList.begin());
+        heapParams->clear();
+        c2_status_t result = C2_OK;
+        // TODO: loop optimization
+        for (size_t i = 0; i < mFilters.size(); ++i) {
+            // Filter stack params according to mTypeToIndexForQuery
+            std::vector<C2Param *> stackParamsForFilter;
+            for (auto it = stackParamsList.begin(); it != stackParamsList.end(); ) {
+                C2Param *param = *it;
+                uint32_t type = param->type().type();
+                auto it2 = mTypeToIndexForQuery.find(type);
+                if (it2 == mTypeToIndexForQuery.end() || it2->second != i) {
+                    ++it;
+                    continue;
+                }
+                stackParamsForFilter.push_back(param);
+                it = stackParamsList.erase(it);
+            }
+            // Filter heap params according to mTypeToIndexForQuery
+            std::vector<C2Param::Index> heapParamIndicesForFilter;
+            for (size_t j = 0; j < heapParamIndices.size(); ++j) {
+                uint32_t type = heapParamIndices[j].type();
+                auto it = mTypeToIndexForQuery.find(type);
+                if (it == mTypeToIndexForQuery.end() || it->second != i) {
+                    continue;
+                }
+                heapParamIndicesForFilter.push_back(heapParamIndices[j]);
+            }
+            std::vector<std::unique_ptr<C2Param>> heapParamsForFilter;
+            const std::shared_ptr<C2ComponentInterface> &filter = mFilters[i].intf;
+            c2_status_t err = filter->query_vb(
+                    stackParamsForFilter, heapParamIndicesForFilter, mayBlock,
+                    &heapParamsForFilter);
+            if (err != C2_OK && err != C2_BAD_INDEX) {
+                LOG(WARNING) << "WrappedDecoderInterface: " << filter->getName()
+                        << " returned error for query_vb; err=" << err;
+                result = err;
+                continue;
+            }
+            heapParams->insert(
+                    heapParams->end(),
+                    std::make_move_iterator(heapParamsForFilter.begin()),
+                    std::make_move_iterator(heapParamsForFilter.end()));
+        }
+
+        std::vector<C2Param *> stackParamsForIntf;
+        std::copy_n(stackParamsList.begin(), stackParamsList.size(), stackParamsForIntf.begin());
+
+        // Gather heap params that did not get queried from the filter interfaces above.
+        // These need to be queried from the decoder interface.
+        std::vector<C2Param::Index> heapParamIndicesForIntf;
+        for (size_t j = 0; j < heapParamIndices.size(); ++j) {
+            uint32_t type = heapParamIndices[j].type();
+            if (mTypeToIndexForQuery.find(type) != mTypeToIndexForQuery.end()) {
+                continue;
+            }
+            heapParamIndicesForIntf.push_back(heapParamIndices[j]);
+        }
+
+        std::vector<std::unique_ptr<C2Param>> heapParamsForIntf;
+        c2_status_t err = mIntf->query_vb(
+                stackParamsForIntf, heapParamIndicesForIntf, mayBlock, &heapParamsForIntf);
+        if (err != C2_OK) {
+            LOG(err == C2_BAD_INDEX ? VERBOSE : WARNING)
+                    << "WrappedDecoderInterface: " << mIntf->getName()
+                    << " returned error for query_vb; err=" << err;
+            result = err;
+        }
+
+        // TODO: params needs to preserve the order
+        heapParams->insert(
+                heapParams->end(),
+                std::make_move_iterator(heapParamsForIntf.begin()),
+                std::make_move_iterator(heapParamsForIntf.end()));
+
+        return result;
+    }
+
+    c2_status_t config_vb(
+            const std::vector<C2Param *> &params,
+            c2_blocking_t mayBlock,
+            std::vector<std::unique_ptr<C2SettingResult>>* const failures) override {
+        std::unique_lock lock(mMutex);
+        c2_status_t result = C2_OK;
+        std::vector<C2Param *> paramsForIntf;
+        for (C2Param* param : params) {
+            auto it = mTypeToIndexForConfig.find(param->type().type());
+            if (it != mTypeToIndexForConfig.end()) {
+                continue;
+            }
+            paramsForIntf.push_back(param);
+        }
+        c2_status_t err = mIntf->config_vb(paramsForIntf, mayBlock, failures);
+        if (err != C2_OK) {
+            LOG(err == C2_BAD_INDEX ? VERBOSE : WARNING)
+                    << "WrappedDecoderInterface: " << mIntf->getName()
+                    << " returned error for config_vb; err=" << err;
+            result = err;
+        }
+        for (size_t i = 0; i < mFilters.size(); ++i) {
+            if (i == 0) {
+                transferParams_l(mIntf, mFilters[0].intf, mayBlock);
+            } else {
+                transferParams_l(mFilters[i - 1].intf, mFilters[i].intf, mayBlock);
+            }
+            const std::shared_ptr<C2ComponentInterface> &filter = mFilters[i].intf;
+            std::vector<std::unique_ptr<C2SettingResult>> filterFailures;
+            std::vector<C2Param *> paramsForFilter;
+            for (C2Param* param : params) {
+                auto it = mTypeToIndexForConfig.find(param->type().type());
+                if (it != mTypeToIndexForConfig.end() && it->second != i) {
+                    continue;
+                }
+                paramsForFilter.push_back(param);
+            }
+            c2_status_t err = filter->config_vb(paramsForFilter, mayBlock, &filterFailures);
+            if (err != C2_OK) {
+                LOG(err == C2_BAD_INDEX ? VERBOSE : WARNING)
+                        << "WrappedDecoderInterface: " << filter->getName()
+                        << " returned error for config_vb; err=" << err;
+                result = err;
+            }
+        }
+
+        return result;
+    }
+
+    c2_status_t createTunnel_sm(c2_node_id_t) override { return C2_OMITTED; }
+    c2_status_t releaseTunnel_sm(c2_node_id_t) override { return C2_OMITTED; }
+
+    c2_status_t querySupportedParams_nb(
+            std::vector<std::shared_ptr<C2ParamDescriptor>> * const params) const override {
+        std::unique_lock lock(mMutex);
+        c2_status_t result = mIntf->querySupportedParams_nb(params);
+        if (result != C2_OK) {
+            LOG(WARNING) << "WrappedDecoderInterface: " << mIntf->getName()
+                    << " returned error for querySupportedParams_nb; err=" << result;
+            return result;
+        }
+        // TODO: optimization idea --- pre-compute at takeFilter().
+        for (const FilterWrapper::Component &filter : mFilters) {
+            std::vector<std::shared_ptr<C2ParamDescriptor>> filterParams;
+            c2_status_t err = filter.intf->querySupportedParams_nb(&filterParams);
+            if (err != C2_OK) {
+                LOG(WARNING) << "WrappedDecoderInterface: " << filter.intf->getName()
+                        << " returned error for querySupportedParams_nb; err=" << result;
+                result = err;
+                continue;
+            }
+            for (const std::shared_ptr<C2ParamDescriptor> &paramDesc : filterParams) {
+                if (std::count(
+                        filter.desc.controlParams.begin(),
+                        filter.desc.controlParams.end(),
+                        paramDesc->index().type()) == 0) {
+                    continue;
+                }
+                params->push_back(paramDesc);
+            }
+        }
+        return result;
+    }
+
+    c2_status_t querySupportedValues_vb(
+            std::vector<C2FieldSupportedValuesQuery> &fields,
+            c2_blocking_t mayBlock) const override {
+        std::unique_lock lock(mMutex);
+        c2_status_t result = mIntf->querySupportedValues_vb(fields, mayBlock);
+        if (result != C2_OK && result != C2_BAD_INDEX) {
+            LOG(WARNING) << "WrappedDecoderInterface: " << mIntf->getName()
+                    << " returned error for querySupportedParams_nb; err=" << result;
+            return result;
+        }
+        for (const FilterWrapper::Component &filter : mFilters) {
+            std::vector<C2FieldSupportedValuesQuery> filterFields;
+            std::vector<size_t> indices;
+            for (size_t i = 0; i < fields.size(); ++i) {
+                const C2FieldSupportedValuesQuery &field = fields[i];
+                uint32_t type = C2Param::Index(_C2ParamInspector::GetIndex(field.field())).type();
+                if (std::count(
+                        filter.desc.controlParams.begin(),
+                        filter.desc.controlParams.end(),
+                        type) == 0) {
+                    continue;
+                }
+                filterFields.push_back(field);
+                indices.push_back(i);
+            }
+            c2_status_t err = filter.intf->querySupportedValues_vb(filterFields, mayBlock);
+            if (err != C2_OK && err != C2_BAD_INDEX) {
+                LOG(WARNING) << "WrappedDecoderInterface: " << filter.intf->getName()
+                        << " returned error for querySupportedParams_nb; err=" << result;
+                result = err;
+                continue;
+            }
+            for (size_t i = 0; i < filterFields.size(); ++i) {
+                fields[indices[i]] = filterFields[i];
+            }
+        }
+        return result;
+    }
+
+private:
+    mutable std::mutex mMutex;
+    std::shared_ptr<C2ComponentInterface> mIntf;
+    std::vector<FilterWrapper::Component> mFilters;
+    std::map<uint32_t, size_t> mTypeToIndexForQuery;
+    std::map<uint32_t, size_t> mTypeToIndexForConfig;
+
+    c2_status_t transferParams_l(
+            const std::shared_ptr<C2ComponentInterface> &curr,
+            const std::shared_ptr<C2ComponentInterface> &next,
+            c2_blocking_t mayBlock) {
+        // NOTE: this implementation is preliminary --- it could change once
+        // we define what parameters needs to be propagated in component chaining.
+        std::vector<std::shared_ptr<C2ParamDescriptor>> paramDescs;
+        c2_status_t err = next->querySupportedParams_nb(&paramDescs);
+        if (err != C2_OK) {
+            LOG(DEBUG) << "WrappedDecoderInterface: " << next->getName()
+                    << " returned error for querySupportedParams_nb; err=" << err;
+            return err;
+        }
+        // Find supported input params from the next interface and flip direction
+        // so they become output params.
+        std::vector<C2Param::Index> indices;
+        for (const std::shared_ptr<C2ParamDescriptor> &paramDesc : paramDescs) {
+            C2Param::Index index = paramDesc->index();
+            if (!index.forInput() || paramDesc->isReadOnly()) {
+                continue;
+            }
+            if (index.forStream()) {
+                uint32_t stream = index.stream();
+                index = index.withPort(true /* output */).withStream(stream);
+            } else {
+                index = index.withPort(true /* output */);
+            }
+            indices.push_back(index);
+        }
+        // Query those output params from the current interface
+        std::vector<std::unique_ptr<C2Param>> heapParams;
+        err = curr->query_vb({}, indices, mayBlock, &heapParams);
+        if (err != C2_OK && err != C2_BAD_INDEX) {
+            LOG(DEBUG) << "WrappedDecoderInterface: " << curr->getName()
+                    << " returned error for query_vb; err=" << err;
+            return err;
+        }
+        // Flip the direction of the queried params, so they become input parameters.
+        // Configure the next interface with the params.
+        std::vector<C2Param *> configParams;
+        for (size_t i = 0; i < heapParams.size(); ++i) {
+            if (heapParams[i]->forStream()) {
+                heapParams[i] = C2Param::CopyAsStream(
+                        *heapParams[i], false /* output */, heapParams[i]->stream());
+            } else {
+                heapParams[i] = C2Param::CopyAsPort(*heapParams[i], false /* output */);
+            }
+            configParams.push_back(heapParams[i].get());
+        }
+        std::vector<std::unique_ptr<C2SettingResult>> failures;
+        err = next->config_vb(configParams, mayBlock, &failures);
+        if (err != C2_OK && err != C2_BAD_INDEX) {
+            LOG(DEBUG) << "WrappedDecoderInterface: " << next->getName()
+                    << " returned error for config_vb; err=" << err;
+            return err;
+        }
+        return C2_OK;
+    }
+};
+
+class WrappedDecoder : public C2Component, public std::enable_shared_from_this<WrappedDecoder> {
+public:
+    WrappedDecoder(
+            std::shared_ptr<C2Component> comp,
+            std::vector<FilterWrapper::Component> &&filters,
+            std::weak_ptr<FilterWrapper> filterWrapper)
+        : mComp(comp), mFilters(std::move(filters)), mFilterWrapper(filterWrapper) {
+        std::vector<FilterWrapper::Component> filtersDup(mFilters);
+        mIntf = std::make_shared<WrappedDecoderInterface>(
+                comp->intf(), std::move(filtersDup));
+    }
+
+    ~WrappedDecoder() override = default;
+
+    std::shared_ptr<C2ComponentInterface> intf() override { return mIntf; }
+
+    c2_status_t setListener_vb(
+            const std::shared_ptr<Listener> &listener, c2_blocking_t mayBlock) override {
+        if (listener) {
+            setListenerInternal(mFilters, listener, mayBlock);
+        } else {
+            mComp->setListener_vb(nullptr, mayBlock);
+            for (FilterWrapper::Component &filter : mFilters) {
+                filter.comp->setListener_vb(nullptr, mayBlock);
+            }
+        }
+        mListener = listener;
+        return C2_OK;
+    }
+
+    c2_status_t queue_nb(std::list<std::unique_ptr<C2Work>>* const items) override {
+        return mComp->queue_nb(items);
+    }
+
+    c2_status_t announce_nb(const std::vector<C2WorkOutline> &) override {
+        return C2_OMITTED;
+    }
+
+    c2_status_t flush_sm(
+            flush_mode_t mode, std::list<std::unique_ptr<C2Work>>* const flushedWork) override {
+        c2_status_t result = mComp->flush_sm(mode, flushedWork);
+        std::list<std::unique_ptr<C2Work>> filterFlushedWork;
+        for (FilterWrapper::Component filter : mRunningFilters) {
+            c2_status_t err = filter.comp->flush_sm(mode, &filterFlushedWork);
+            if (err != C2_OK) {
+                result = err;
+            }
+            flushedWork->splice(flushedWork->end(), filterFlushedWork);
+        }
+        return result;
+    }
+
+    c2_status_t drain_nb(drain_mode_t mode) override {
+        // TODO: simplify using comp->drain_nb(mode)
+        switch (mode) {
+        case DRAIN_COMPONENT_WITH_EOS: {
+            std::unique_ptr<C2Work> eosWork{new C2Work};
+            eosWork->input.flags = C2FrameData::FLAG_END_OF_STREAM;
+            eosWork->worklets.push_back(std::make_unique<C2Worklet>());
+            std::list<std::unique_ptr<C2Work>> items;
+            items.push_back(std::move(eosWork));
+            mComp->queue_nb(&items);
+            return C2_OK;
+        }
+        case DRAIN_COMPONENT_NO_EOS:
+        case DRAIN_CHAIN:
+        default:
+            return C2_BAD_VALUE;
+        }
+    }
+
+    c2_status_t start() override {
+        std::vector<FilterWrapper::Component> filters;
+        if (std::shared_ptr<FilterWrapper> filterWrapper = mFilterWrapper.lock()) {
+            // Let's check if we have filters that we can skip
+            for (FilterWrapper::Component &filter : mFilters) {
+                if (!filterWrapper->isFilteringEnabled(filter.intf)) {
+                    LOG(VERBOSE) << "filtering disabled for " << filter.traits.name;
+                    continue;
+                }
+                LOG(VERBOSE) << "filtering enabled for " << filter.traits.name;
+                filters.push_back(filter);
+            }
+            if (filters.size() < mFilters.size()) {
+                LOG(VERBOSE) << (mFilters.size() - filters.size()) << " filter(s) skipped";
+                setListenerInternal(filters, mListener, C2_MAY_BLOCK);
+                std::vector filtersCopy(filters);
+                mIntf->takeFilters(std::move(filtersCopy));
+            }
+        }
+
+        c2_status_t err = mComp->start();
+        if (err != C2_OK) {
+            return err;
+        }
+        for (FilterWrapper::Component &filter : filters) {
+            c2_status_t err = filter.comp->start();
+            if (err != C2_OK) {
+                // Previous components are already started successfully;
+                // we ended up in an incoherent state.
+                return C2_CORRUPTED;
+            }
+        }
+        mRunningFilters = std::move(filters);
+        return C2_OK;
+    }
+
+    c2_status_t stop() override {
+        c2_status_t err = mComp->stop();
+        if (err != C2_OK) {
+            return err;
+        }
+        for (FilterWrapper::Component filter : mRunningFilters) {
+            c2_status_t err = filter.comp->stop();
+            if (err != C2_OK) {
+                // Previous components are already stopped successfully;
+                // we ended up in an incoherent state.
+                return C2_CORRUPTED;
+            }
+        }
+        mRunningFilters.clear();
+        return C2_OK;
+    }
+
+    c2_status_t reset() override {
+        c2_status_t result = mComp->reset();
+        if (result != C2_OK) {
+            result = C2_CORRUPTED;
+        }
+        for (FilterWrapper::Component filter : mFilters) {
+            c2_status_t err = filter.comp->reset();
+            if (err != C2_OK) {
+                // Previous components are already reset successfully;
+                // we ended up in an incoherent state.
+                result = C2_CORRUPTED;
+                // continue for the rest of the chain
+            }
+        }
+        mRunningFilters.clear();
+        return result;
+    }
+
+    c2_status_t release() override {
+        c2_status_t result = mComp->release();
+        if (result != C2_OK) {
+            result = C2_CORRUPTED;
+        }
+        for (FilterWrapper::Component filter : mFilters) {
+            c2_status_t err = filter.comp->release();
+            if (err != C2_OK) {
+                // Previous components are already released successfully;
+                // we ended up in an incoherent state.
+                result = C2_CORRUPTED;
+                // continue for the rest of the chain
+            }
+        }
+        mRunningFilters.clear();
+        return result;
+    }
+
+private:
+    class PassingListener : public Listener {
+    public:
+        PassingListener(
+                std::shared_ptr<C2Component> wrappedComponent,
+                const std::shared_ptr<Listener> &wrappedComponentListener,
+                std::shared_ptr<C2Component> nextComponent)
+            : mWrappedComponent(wrappedComponent),
+              mWrappedComponentListener(wrappedComponentListener),
+              mNextComponent(nextComponent) {
+        }
+
+        void onWorkDone_nb(
+                std::weak_ptr<C2Component>,
+                std::list<std::unique_ptr<C2Work>> workItems) override {
+            std::shared_ptr<C2Component> nextComponent = mNextComponent.lock();
+            std::list<std::unique_ptr<C2Work>> failedWorkItems;
+            if (!nextComponent) {
+                for (std::unique_ptr<C2Work> &work : workItems) {
+                    // Next component unexpectedly released while the work is
+                    // in-flight. Report C2_CORRUPTED to the client.
+                    work->result = C2_CORRUPTED;
+                    failedWorkItems.push_back(std::move(work));
+                }
+                workItems.clear();
+            } else {
+                for (auto it = workItems.begin(); it != workItems.end(); ) {
+                    const std::unique_ptr<C2Work> &work = *it;
+                    if (work->result != C2_OK
+                            || work->worklets.size() != 1) {
+                        failedWorkItems.push_back(std::move(*it));
+                        it = workItems.erase(it);
+                        continue;
+                    }
+                    C2FrameData &output = work->worklets.front()->output;
+                    c2_cntr64_t customOrdinal = work->input.ordinal.customOrdinal;
+                    work->input = std::move(output);
+                    work->input.ordinal.customOrdinal = customOrdinal;
+                    output.flags = C2FrameData::flags_t(0);
+                    output.buffers.clear();
+                    output.configUpdate.clear();
+                    output.infoBuffers.clear();
+                    ++it;
+                }
+            }
+            if (!failedWorkItems.empty()) {
+                for (const std::unique_ptr<C2Work> &work : failedWorkItems) {
+                    LOG(VERBOSE) << "work #" << work->input.ordinal.frameIndex.peek()
+                            << " failed: err=" << work->result
+                            << " worklets.size()=" << work->worklets.size();
+                }
+                if (std::shared_ptr<Listener> wrappedComponentListener =
+                        mWrappedComponentListener.lock()) {
+                    wrappedComponentListener->onWorkDone_nb(
+                            mWrappedComponent, std::move(failedWorkItems));
+                }
+            }
+            if (!workItems.empty()) {
+                nextComponent->queue_nb(&workItems);
+            }
+        }
+
+        void onTripped_nb(
+                std::weak_ptr<C2Component>,
+                std::vector<std::shared_ptr<C2SettingResult>>) override {
+            // Trip not supported
+        }
+
+        void onError_nb(std::weak_ptr<C2Component>, uint32_t errorCode) {
+            if (std::shared_ptr<Listener> wrappedComponentListener =
+                    mWrappedComponentListener.lock()) {
+                wrappedComponentListener->onError_nb(mWrappedComponent, errorCode);
+            }
+        }
+
+    private:
+        std::weak_ptr<C2Component> mWrappedComponent;
+        std::weak_ptr<Listener> mWrappedComponentListener;
+        std::weak_ptr<C2Component> mNextComponent;
+    };
+
+    class LastListener : public Listener {
+    public:
+        LastListener(
+                std::shared_ptr<C2Component> wrappedComponent,
+                const std::shared_ptr<Listener> &wrappedComponentListener)
+            : mWrappedComponent(wrappedComponent),
+              mWrappedComponentListener(wrappedComponentListener) {
+        }
+
+        void onWorkDone_nb(
+                std::weak_ptr<C2Component>,
+                std::list<std::unique_ptr<C2Work>> workItems) override {
+            if (mWrappedComponent.expired()) {
+                return;
+            }
+            if (std::shared_ptr<Listener> wrappedComponentListener =
+                    mWrappedComponentListener.lock()) {
+                wrappedComponentListener->onWorkDone_nb(
+                        mWrappedComponent, std::move(workItems));
+            }
+        }
+
+        void onTripped_nb(
+                std::weak_ptr<C2Component>,
+                std::vector<std::shared_ptr<C2SettingResult>>) override {
+            // Trip not supported
+        }
+
+        void onError_nb(std::weak_ptr<C2Component>, uint32_t errorCode) {
+            if (mWrappedComponent.expired()) {
+                return;
+            }
+            if (std::shared_ptr<Listener> wrappedComponentListener =
+                    mWrappedComponentListener.lock()) {
+                wrappedComponentListener->onError_nb(mWrappedComponent, errorCode);
+            }
+        }
+
+    private:
+        std::weak_ptr<C2Component> mWrappedComponent;
+        std::weak_ptr<Listener> mWrappedComponentListener;
+    };
+
+    std::shared_ptr<C2Component> mComp;
+    std::shared_ptr<WrappedDecoderInterface> mIntf;
+    std::vector<FilterWrapper::Component> mFilters;
+    std::vector<FilterWrapper::Component> mRunningFilters;
+    std::weak_ptr<FilterWrapper> mFilterWrapper;
+    std::shared_ptr<Listener> mListener;
+#if defined(LOG_NDEBUG) && !LOG_NDEBUG
+    base::ScopedLogSeverity mScopedLogSeverity{base::VERBOSE};
+#endif
+
+    c2_status_t setListenerInternal(
+            const std::vector<FilterWrapper::Component> &filters,
+            const std::shared_ptr<Listener> &listener,
+            c2_blocking_t mayBlock) {
+        if (filters.empty()) {
+            return mComp->setListener_vb(listener, mayBlock);
+        }
+        std::shared_ptr passingListener = std::make_shared<PassingListener>(
+                shared_from_this(),
+                listener,
+                filters.front().comp);
+        mComp->setListener_vb(passingListener, mayBlock);
+        for (size_t i = 0; i < filters.size() - 1; ++i) {
+            filters[i].comp->setListener_vb(
+                    std::make_shared<PassingListener>(
+                            shared_from_this(),
+                            listener,
+                            filters[i + 1].comp),
+                    mayBlock);
+        }
+        filters.back().comp->setListener_vb(
+                std::make_shared<LastListener>(shared_from_this(), listener), mayBlock);
+        return C2_OK;
+    }
+};
+
+}  // anonymous namespace
+
+FilterWrapper::FilterWrapper(std::unique_ptr<Plugin> &&plugin)
+    : mInit(NO_INIT),
+      mPlugin(std::move(plugin)) {
+    if (mPlugin->status() != OK) {
+        LOG(ERROR) << "plugin not OK: " << mPlugin->status();
+        mPlugin.reset();
+        return;
+    }
+    mStore = mPlugin->getStore();
+    if (!mStore) {
+        LOG(ERROR) << "no store";
+        mPlugin.reset();
+        return;
+    }
+    std::vector<std::shared_ptr<const C2Component::Traits>> traits =
+        mStore->listComponents();
+    std::sort(
+            traits.begin(),
+            traits.end(),
+            [](std::shared_ptr<const C2Component::Traits> &a,
+                    std::shared_ptr<const C2Component::Traits> &b) {
+                return a->rank < b->rank;
+            });
+    for (size_t i = 0; i < traits.size(); ++i) {
+        const std::shared_ptr<const C2Component::Traits> &trait = traits[i];
+        if (trait->domain == C2Component::DOMAIN_OTHER
+                || trait->domain == C2Component::DOMAIN_AUDIO
+                || trait->kind != C2Component::KIND_OTHER) {
+            LOG(DEBUG) << trait->name << " is ignored because of domain/kind: "
+                << trait->domain << "/" << trait->kind;
+            continue;
+        }
+        Descriptor desc;
+        if (!mPlugin->describe(trait->name, &desc)) {
+            LOG(DEBUG) << trait->name << " is ignored because describe() failed";
+            continue;
+        }
+        mComponents.push_back({nullptr, nullptr, *trait, desc});
+    }
+    if (mComponents.empty()) {
+        LOG(DEBUG) << "FilterWrapper: no filter component found";
+        mPlugin.reset();
+        return;
+    }
+    mInit = OK;
+}
+
+FilterWrapper::~FilterWrapper() {
+}
+
+std::vector<FilterWrapper::Component> FilterWrapper::createFilters() {
+    std::vector<FilterWrapper::Component> filters;
+    for (const FilterWrapper::Component &filter : mComponents) {
+        std::shared_ptr<C2Component> comp;
+        std::shared_ptr<C2ComponentInterface> intf;
+        if (C2_OK != mStore->createComponent(filter.traits.name, &comp)) {
+            return {};
+        }
+        if (C2_OK != mStore->createInterface(filter.traits.name, &intf)) {
+            return {};
+        }
+        filters.push_back({comp, intf, filter.traits, filter.desc});
+    }
+    return filters;
+}
+
+C2Component::Traits FilterWrapper::getTraits(
+        const std::shared_ptr<C2ComponentInterface> &intf) {
+    {
+        std::unique_lock lock(mCacheMutex);
+        if (mCachedTraits.count(intf->getName())) {
+            return mCachedTraits.at(intf->getName());
+        }
+    }
+    C2ComponentDomainSetting domain;
+    C2ComponentKindSetting kind;
+    c2_status_t err = intf->query_vb({&domain, &kind}, {}, C2_MAY_BLOCK, nullptr);
+    C2Component::Traits traits = {
+        "query failed",  // name
+        C2Component::DOMAIN_OTHER,
+        C2Component::KIND_OTHER,
+        0,   // rank, unused
+        "",  // media type, unused
+        "",  // owner, unused
+        {},  // aliases, unused
+    };
+    if (err == C2_OK) {
+        traits = {
+            intf->getName(),
+            domain.value,
+            kind.value,
+            0,   // rank, unused
+            "",  // media type, unused
+            "",  // owner, unused
+            {},  // aliases, unused
+        };
+        std::unique_lock lock(mCacheMutex);
+        mCachedTraits[traits.name] = traits;
+    }
+    return traits;
+}
+
+std::shared_ptr<C2ComponentInterface> FilterWrapper::maybeWrapInterface(
+        const std::shared_ptr<C2ComponentInterface> intf) {
+    if (mInit != OK) {
+        LOG(VERBOSE) << "maybeWrapInterface: Wrapper not initialized: "
+                << intf->getName() << " is not wrapped.";
+        return intf;
+    }
+    C2Component::Traits traits = getTraits(intf);
+    if (traits.name != intf->getName()) {
+        LOG(INFO) << "maybeWrapInterface: Querying traits from " << intf->getName()
+                << " failed; not wrapping the interface";
+        return intf;
+    }
+    if ((traits.domain != C2Component::DOMAIN_VIDEO && traits.domain != C2Component::DOMAIN_IMAGE)
+            || traits.kind != C2Component::KIND_DECODER) {
+        LOG(VERBOSE) << "maybeWrapInterface: " << traits.name
+                << " is not video/image decoder; not wrapping the interface";
+        return intf;
+    }
+    return std::make_shared<WrappedDecoderInterface>(intf, createFilters());
+}
+
+std::shared_ptr<C2Component> FilterWrapper::maybeWrapComponent(
+        const std::shared_ptr<C2Component> comp) {
+    if (mInit != OK) {
+        LOG(VERBOSE) << "maybeWrapComponent: Wrapper not initialized: "
+                << comp->intf()->getName() << " is not wrapped.";
+        return comp;
+    }
+    C2Component::Traits traits = getTraits(comp->intf());
+    if (traits.name != comp->intf()->getName()) {
+        LOG(INFO) << "maybeWrapComponent: Querying traits from " << comp->intf()->getName()
+                << " failed; not wrapping the component";
+        return comp;
+    }
+    if ((traits.domain != C2Component::DOMAIN_VIDEO && traits.domain != C2Component::DOMAIN_IMAGE)
+            || traits.kind != C2Component::KIND_DECODER) {
+        LOG(VERBOSE) << "maybeWrapComponent: " << traits.name
+                << " is not video/image decoder; not wrapping the component";
+        return comp;
+    }
+    std::vector<Component> filters = createFilters();
+    std::shared_ptr wrapped = std::make_shared<WrappedDecoder>(
+            comp, std::move(filters), weak_from_this());
+    {
+        std::unique_lock lock(mWrappedComponentsMutex);
+        std::vector<std::weak_ptr<const C2Component>> &components =
+            mWrappedComponents.emplace_back();
+        components.push_back(wrapped);
+        components.push_back(comp);
+        for (const Component &filter : filters) {
+            components.push_back(filter.comp);
+        }
+    }
+    return wrapped;
+}
+
+bool FilterWrapper::isFilteringEnabled(const std::shared_ptr<C2ComponentInterface> &intf) {
+    if (mInit != OK) {
+        LOG(WARNING) << "isFilteringEnabled: Wrapper not initialized: ";
+        return false;
+    }
+    return mPlugin->isFilteringEnabled(intf);
+}
+
+c2_status_t FilterWrapper::createBlockPool(
+        C2PlatformAllocatorStore::id_t allocatorId,
+        std::shared_ptr<const C2Component> component,
+        std::shared_ptr<C2BlockPool> *pool) {
+    std::unique_lock lock(mWrappedComponentsMutex);
+    for (auto it = mWrappedComponents.begin(); it != mWrappedComponents.end(); ) {
+        std::shared_ptr<const C2Component> comp = it->front().lock();
+        if (!comp) {
+            it = mWrappedComponents.erase(it);
+            continue;
+        }
+        if (component == comp) {
+            std::vector<std::shared_ptr<const C2Component>> components(it->size());
+            std::transform(
+                    it->begin(), it->end(), components.begin(),
+                    [](const std::weak_ptr<const C2Component> &el) {
+                        return el.lock();
+                    });
+            if (C2_OK == CreateCodec2BlockPool(allocatorId, components, pool)) {
+                return C2_OK;
+            }
+        }
+        ++it;
+    }
+    return CreateCodec2BlockPool(allocatorId, component, pool);
+}
+
+}  // namespace android
diff --git a/media/codec2/hidl/plugin/FilterWrapperStub.cpp b/media/codec2/hidl/plugin/FilterWrapperStub.cpp
new file mode 100644
index 0000000..1b94a1a
--- /dev/null
+++ b/media/codec2/hidl/plugin/FilterWrapperStub.cpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2020 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 "Codec2-FilterWrapperStub"
+
+#include <FilterWrapper.h>
+
+namespace android {
+
+FilterWrapper::FilterWrapper(std::unique_ptr<Plugin> &&) {
+}
+
+FilterWrapper::~FilterWrapper() {
+}
+
+std::shared_ptr<C2ComponentInterface> FilterWrapper::maybeWrapInterface(
+        const std::shared_ptr<C2ComponentInterface> intf) {
+    return intf;
+}
+
+std::shared_ptr<C2Component> FilterWrapper::maybeWrapComponent(
+        const std::shared_ptr<C2Component> comp) {
+    return comp;
+}
+
+bool FilterWrapper::isFilteringEnabled(const std::shared_ptr<C2ComponentInterface> &) {
+    return false;
+}
+
+c2_status_t FilterWrapper::createBlockPool(
+        C2PlatformAllocatorStore::id_t,
+        std::shared_ptr<const C2Component>,
+        std::shared_ptr<C2BlockPool> *) {
+    return C2_OMITTED;
+}
+
+}  // namespace android
diff --git a/media/codec2/hidl/plugin/include/codec2/hidl/plugin/FilterPlugin.h b/media/codec2/hidl/plugin/include/codec2/hidl/plugin/FilterPlugin.h
new file mode 100644
index 0000000..6f1f907
--- /dev/null
+++ b/media/codec2/hidl/plugin/include/codec2/hidl/plugin/FilterPlugin.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2018, 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 CODEC2_HIDL_PLUGIN_FILTER_PLUGIN_H
+
+#define CODEC2_HIDL_PLUGIN_FILTER_PLUGIN_H
+
+#include <memory>
+
+#include <C2Component.h>
+
+namespace android {
+
+class FilterPlugin_V1 {
+public:
+    static constexpr int32_t VERSION = 1;
+
+    virtual ~FilterPlugin_V1() = default;
+
+    /**
+     * Returns a C2ComponentStore object with which clients can create
+     * filter components / interfaces.
+     */
+    virtual std::shared_ptr<C2ComponentStore> getComponentStore() = 0;
+    struct Descriptor {
+        // Parameters that client sets for filter control.
+        std::initializer_list<C2Param::Type> controlParams;
+        // Parameters that the component changes after filtering.
+        std::initializer_list<C2Param::Type> affectedParams;
+    };
+
+    /**
+     * Describe a filter component.
+     *
+     * @param name[in]  filter's name
+     * @param desc[out] pointer to filter descriptor to be populated
+     * @return  true if |name| is in the store and |desc| is populated;
+     *          false if |name| is not recognized
+     */
+    virtual bool describe(C2String name, Descriptor *desc) = 0;
+
+    /**
+     * Returns true if a component will apply filtering after all given the
+     * current configuration; false if it will be no-op.
+     */
+    virtual bool isFilteringEnabled(const std::shared_ptr<C2ComponentInterface> &intf) = 0;
+};
+
+}  // namespace android
+
+extern "C" {
+
+typedef int32_t (*GetFilterPluginVersionFunc)();
+int32_t GetFilterPluginVersion();
+
+typedef void* (*CreateFilterPluginFunc)();
+void *CreateFilterPlugin();
+
+typedef void (*DestroyFilterPluginFunc)(void *);
+void DestroyFilterPlugin(void *plugin);
+
+}  // extern "C"
+
+#endif  // CODEC2_HIDL_PLUGIN_FILTER_PLUGIN_H
diff --git a/media/codec2/hidl/plugin/internal/DefaultFilterPlugin.h b/media/codec2/hidl/plugin/internal/DefaultFilterPlugin.h
new file mode 100644
index 0000000..f856324
--- /dev/null
+++ b/media/codec2/hidl/plugin/internal/DefaultFilterPlugin.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2020, 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 CODEC2_HIDL_PLUGIN_DEFAULT_FILTER_PLUGIN_H
+
+#define CODEC2_HIDL_PLUGIN_DEFAULT_FILTER_PLUGIN_H
+
+#include <codec2/hidl/plugin/FilterPlugin.h>
+
+#include <FilterWrapper.h>
+
+namespace android {
+
+class DefaultFilterPlugin : public FilterWrapper::Plugin {
+public:
+    explicit DefaultFilterPlugin(const char *pluginPath);
+
+    ~DefaultFilterPlugin();
+
+    status_t status() const override { return mInit; }
+
+    std::shared_ptr<C2ComponentStore> getStore() override { return mStore; }
+    bool describe(C2String name, FilterWrapper::Descriptor *desc) override;
+    bool isFilteringEnabled(const std::shared_ptr<C2ComponentInterface> &intf) override;
+
+private:
+    status_t mInit;
+    void *mHandle;
+    DestroyFilterPluginFunc mDestroyPlugin;
+    FilterPlugin_V1 *mPlugin;
+    std::shared_ptr<C2ComponentStore> mStore;
+};
+
+}  // namespace android
+
+#endif  // CODEC2_HIDL_PLUGIN_DEFAULT_FILTER_PLUGIN_H
diff --git a/media/codec2/hidl/plugin/internal/FilterWrapper.h b/media/codec2/hidl/plugin/internal/FilterWrapper.h
new file mode 100644
index 0000000..5ced435
--- /dev/null
+++ b/media/codec2/hidl/plugin/internal/FilterWrapper.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2020, 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 CODEC2_HIDL_PLUGIN_FILTER_WRAPPER_H
+
+#define CODEC2_HIDL_PLUGIN_FILTER_WRAPPER_H
+
+#include <map>
+#include <memory>
+#include <mutex>
+
+#include <C2Component.h>
+#include <C2PlatformSupport.h>
+
+#include <codec2/hidl/plugin/FilterPlugin.h>
+#include <utils/Errors.h>
+
+namespace android {
+
+// TODO: documentation
+class FilterWrapper : public std::enable_shared_from_this<FilterWrapper> {
+public:
+    using Descriptor = FilterPlugin_V1::Descriptor;
+
+    class Plugin {
+    public:
+        Plugin() = default;
+        virtual ~Plugin() = default;
+        virtual status_t status() const = 0;
+        virtual std::shared_ptr<C2ComponentStore> getStore() = 0;
+        virtual bool describe(C2String name, Descriptor *desc) = 0;
+        virtual bool isFilteringEnabled(const std::shared_ptr<C2ComponentInterface> &intf) = 0;
+        C2_DO_NOT_COPY(Plugin);
+    };
+
+    struct Component {
+        const std::shared_ptr<C2Component> comp;
+        const std::shared_ptr<C2ComponentInterface> intf;
+        const C2Component::Traits traits;
+        const Descriptor desc;
+    };
+
+private:
+    explicit FilterWrapper(std::unique_ptr<Plugin> &&plugin);
+public:
+    static std::shared_ptr<FilterWrapper> Create(std::unique_ptr<Plugin> &&plugin) {
+        return std::shared_ptr<FilterWrapper>(new FilterWrapper(std::move(plugin)));
+    }
+    ~FilterWrapper();
+
+    /**
+     * Returns wrapped interface, or |intf| if wrapping is not possible / needed.
+     */
+    std::shared_ptr<C2ComponentInterface> maybeWrapInterface(
+            const std::shared_ptr<C2ComponentInterface> intf);
+
+    /**
+     * Returns wrapped component, or |comp| if wrapping is not possible / needed.
+     */
+    std::shared_ptr<C2Component> maybeWrapComponent(
+            const std::shared_ptr<C2Component> comp);
+
+    /**
+     * Returns ture iff the filtering will apply to the buffer in current configuration.
+     */
+    bool isFilteringEnabled(const std::shared_ptr<C2ComponentInterface> &intf);
+
+    c2_status_t createBlockPool(
+            C2PlatformAllocatorStore::id_t allocatorId,
+            std::shared_ptr<const C2Component> component,
+            std::shared_ptr<C2BlockPool> *pool);
+
+private:
+    status_t mInit;
+    std::unique_ptr<Plugin> mPlugin;
+    std::shared_ptr<C2ComponentStore> mStore;
+    std::list<FilterWrapper::Component> mComponents;
+
+    std::mutex mCacheMutex;
+    std::map<std::string, C2Component::Traits> mCachedTraits;
+
+    std::mutex mWrappedComponentsMutex;
+    std::list<std::vector<std::weak_ptr<const C2Component>>> mWrappedComponents;
+
+    std::vector<FilterWrapper::Component> createFilters();
+    C2Component::Traits getTraits(const std::shared_ptr<C2ComponentInterface> &intf);
+
+    C2_DO_NOT_COPY(FilterWrapper);
+};
+
+}  // namespace android
+
+#endif  // CODEC2_HIDL_PLUGIN_FILTER_WRAPPER_H
diff --git a/media/codec2/hidl/services/Android.bp b/media/codec2/hidl/services/Android.bp
index a16b106..5a23217 100644
--- a/media/codec2/hidl/services/Android.bp
+++ b/media/codec2/hidl/services/Android.bp
@@ -29,6 +29,15 @@
 // The seccomp_policy file name and its content can be modified, but note that
 // vendor.cpp also needs to be updated because it needs the absolute path to the
 // seccomp policy file on the device.
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_binary {
     name: "android.hardware.media.c2@1.1-default-service",
     vendor: true,
@@ -52,6 +61,9 @@
     // directly in the main device manifest.xml file or via vintf_fragments.
     // (Remove the line below if the entry is already in the main manifest.)
     vintf_fragments: ["manifest_media_c2_V1_1_default.xml"],
+
+    // Remove this line to enable this module.
+    enabled: false,
 }
 
 // seccomp policy file.
@@ -84,4 +96,3 @@
     // This may be removed.
     required: ["crash_dump.policy"],
 }
-
diff --git a/media/codec2/hidl/services/vendor.cpp b/media/codec2/hidl/services/vendor.cpp
index 81bffeb..3ddb039 100644
--- a/media/codec2/hidl/services/vendor.cpp
+++ b/media/codec2/hidl/services/vendor.cpp
@@ -122,6 +122,18 @@
                 })
                 .withSetter(SetIonUsage)
                 .build());
+
+            addParameter(
+                DefineParam(mDmaBufUsageInfo, "dmabuf-usage")
+                .withDefault(new C2StoreDmaBufUsageInfo())
+                .withFields({
+                    C2F(mDmaBufUsageInfo, usage).flags({C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE}),
+                    C2F(mDmaBufUsageInfo, capacity).inRange(0, UINT32_MAX, 1024),
+                    C2F(mDmaBufUsageInfo, heapName).any(),
+                    C2F(mDmaBufUsageInfo, allocFlags).flags({}),
+                })
+                .withSetter(SetDmaBufUsage)
+                .build());
         }
 
         virtual ~Interface() = default;
@@ -135,7 +147,16 @@
             return C2R::Ok();
         }
 
+        static C2R SetDmaBufUsage(bool /* mayBlock */, C2P<C2StoreDmaBufUsageInfo> &me) {
+            // Vendor's TODO: put appropriate mapping logic
+            strncpy(me.set().m.heapName, "system", me.v.flexCount());
+            me.set().m.allocFlags = 0;
+            return C2R::Ok();
+        }
+
+
         std::shared_ptr<C2StoreIonUsageInfo> mIonUsageInfo;
+        std::shared_ptr<C2StoreDmaBufUsageInfo> mDmaBufUsageInfo;
     };
     std::shared_ptr<C2ReflectorHelper> mReflectorHelper;
     Interface mInterface;
diff --git a/media/codec2/sfplugin/Android.bp b/media/codec2/sfplugin/Android.bp
index 94034b5..2bc748f 100644
--- a/media/codec2/sfplugin/Android.bp
+++ b/media/codec2/sfplugin/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libsfplugin_ccodec",
 
@@ -11,6 +20,7 @@
         "CCodecConfig.cpp",
         "Codec2Buffer.cpp",
         "Codec2InfoBuilder.cpp",
+        "FrameReassembler.cpp",
         "PipelineWatcher.cpp",
         "ReflectedParamUpdater.cpp",
     ],
diff --git a/media/codec2/sfplugin/C2OMXNode.cpp b/media/codec2/sfplugin/C2OMXNode.cpp
index c7588e9..ab73245 100644
--- a/media/codec2/sfplugin/C2OMXNode.cpp
+++ b/media/codec2/sfplugin/C2OMXNode.cpp
@@ -25,6 +25,7 @@
 #include <C2AllocatorGralloc.h>
 #include <C2BlockInternal.h>
 #include <C2Component.h>
+#include <C2Config.h>
 #include <C2PlatformSupport.h>
 
 #include <OMX_Component.h>
@@ -44,6 +45,8 @@
 
 namespace {
 
+constexpr OMX_U32 kPortIndexInput = 0;
+
 class Buffer2D : public C2Buffer {
 public:
     explicit Buffer2D(C2ConstGraphicBlock block) : C2Buffer({ block }) {}
@@ -200,11 +203,35 @@
                 return BAD_VALUE;
             }
             OMX_PARAM_PORTDEFINITIONTYPE *pDef = (OMX_PARAM_PORTDEFINITIONTYPE *)params;
-            // TODO: read these from intf()
+            if (pDef->nPortIndex != kPortIndexInput) {
+                break;
+            }
+
             pDef->nBufferCountActual = 16;
+
+            // WORKAROUND: having more slots improve performance while consuming
+            // more memory. This is a temporary workaround to reduce memory for
+            // larger-than-4K scenario.
+            if (mWidth * mHeight > 4096 * 2340) {
+                std::shared_ptr<Codec2Client::Component> comp = mComp.lock();
+                C2PortActualDelayTuning::input inputDelay(0);
+                C2ActualPipelineDelayTuning pipelineDelay(0);
+                c2_status_t c2err = C2_NOT_FOUND;
+                if (comp) {
+                    c2err = comp->query(
+                            {&inputDelay, &pipelineDelay}, {}, C2_DONT_BLOCK, nullptr);
+                }
+                if (c2err == C2_OK || c2err == C2_BAD_INDEX) {
+                    pDef->nBufferCountActual = 4;
+                    pDef->nBufferCountActual += (inputDelay ? inputDelay.value : 0u);
+                    pDef->nBufferCountActual += (pipelineDelay ? pipelineDelay.value : 0u);
+                }
+            }
+
             pDef->eDomain = OMX_PortDomainVideo;
             pDef->format.video.nFrameWidth = mWidth;
             pDef->format.video.nFrameHeight = mHeight;
+            pDef->format.video.eColorFormat = OMX_COLOR_FormatAndroidOpaque;
             err = OK;
             break;
         }
diff --git a/media/codec2/sfplugin/CCodec.cpp b/media/codec2/sfplugin/CCodec.cpp
index 54107bd..a23b9bd 100644
--- a/media/codec2/sfplugin/CCodec.cpp
+++ b/media/codec2/sfplugin/CCodec.cpp
@@ -246,8 +246,19 @@
         if (source == nullptr) {
             return NO_INIT;
         }
-        constexpr size_t kNumSlots = 16;
-        for (size_t i = 0; i < kNumSlots; ++i) {
+
+        size_t numSlots = 16;
+        constexpr OMX_U32 kPortIndexInput = 0;
+
+        OMX_PARAM_PORTDEFINITIONTYPE param;
+        param.nPortIndex = kPortIndexInput;
+        status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
+                                           &param, sizeof(param));
+        if (err == OK) {
+            numSlots = param.nBufferCountActual;
+        }
+
+        for (size_t i = 0; i < numSlots; ++i) {
             source->onInputBufferAdded(i);
         }
 
@@ -471,6 +482,34 @@
     }
 };
 
+void RevertOutputFormatIfNeeded(
+        const sp<AMessage> &oldFormat, sp<AMessage> &currentFormat) {
+    // We used to not report changes to these keys to the client.
+    const static std::set<std::string> sIgnoredKeys({
+            KEY_BIT_RATE,
+            KEY_FRAME_RATE,
+            KEY_MAX_BIT_RATE,
+            KEY_MAX_WIDTH,
+            KEY_MAX_HEIGHT,
+            "csd-0",
+            "csd-1",
+            "csd-2",
+    });
+    if (currentFormat == oldFormat) {
+        return;
+    }
+    sp<AMessage> diff = currentFormat->changesFrom(oldFormat);
+    AMessage::Type type;
+    for (size_t i = diff->countEntries(); i > 0; --i) {
+        if (sIgnoredKeys.count(diff->getEntryNameAt(i - 1, &type)) > 0) {
+            diff->removeEntryAt(i - 1);
+        }
+    }
+    if (diff->countEntries() == 0) {
+        currentFormat = oldFormat;
+    }
+}
+
 }  // namespace
 
 // CCodec::ClientListener
@@ -502,9 +541,26 @@
     virtual void onError(
             const std::weak_ptr<Codec2Client::Component>& component,
             uint32_t errorCode) override {
-        // TODO
-        (void)component;
-        (void)errorCode;
+        {
+            // Component is only used for reporting as we use a separate listener for each instance
+            std::shared_ptr<Codec2Client::Component> comp = component.lock();
+            if (!comp) {
+                ALOGD("Component died with error: 0x%x", errorCode);
+            } else {
+                ALOGD("Component \"%s\" returned error: 0x%x", comp->getName().c_str(), errorCode);
+            }
+        }
+
+        // Report to MediaCodec
+        // Note: for now we do not propagate the error code to MediaCodec
+        // except for C2_NO_MEMORY, as we would need to translate to a MediaCodec error.
+        sp<CCodec> codec(mCodec.promote());
+        if (!codec || !codec->mCallback) {
+            return;
+        }
+        codec->mCallback->onError(
+                errorCode == C2_NO_MEMORY ? NO_MEMORY : UNKNOWN_ERROR,
+                ACTION_CODE_FATAL);
     }
 
     virtual void onDeath(
@@ -773,12 +829,14 @@
                 return BAD_VALUE;
             }
         }
+        int32_t width = 0;
+        int32_t height = 0;
         if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
-            if (!msg->findInt32(KEY_WIDTH, &i32)) {
+            if (!msg->findInt32(KEY_WIDTH, &width)) {
                 ALOGD("width is missing, which is required for image/video components.");
                 return BAD_VALUE;
             }
-            if (!msg->findInt32(KEY_HEIGHT, &i32)) {
+            if (!msg->findInt32(KEY_HEIGHT, &height)) {
                 ALOGD("height is missing, which is required for image/video components.");
                 return BAD_VALUE;
             }
@@ -867,19 +925,84 @@
         /*
          * Handle desired color format.
          */
+        int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
         if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
-            int32_t format = -1;
+            int32_t format = 0;
+            // Query vendor format for Flexible YUV
+            std::vector<std::unique_ptr<C2Param>> heapParams;
+            C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
+            if (mClient->query(
+                        {},
+                        {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
+                        C2_MAY_BLOCK,
+                        &heapParams) == C2_OK
+                    && heapParams.size() == 1u) {
+                pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
+                        heapParams[0].get());
+            } else {
+                pixelFormatInfo = nullptr;
+            }
+            std::optional<uint32_t> flexPixelFormat{};
+            std::optional<uint32_t> flexPlanarPixelFormat{};
+            std::optional<uint32_t> flexSemiPlanarPixelFormat{};
+            if (pixelFormatInfo && *pixelFormatInfo) {
+                for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
+                    const C2FlexiblePixelFormatDescriptorStruct &desc =
+                        pixelFormatInfo->m.values[i];
+                    if (desc.bitDepth != 8
+                            || desc.subsampling != C2Color::YUV_420
+                            // TODO(b/180076105): some device report wrong layout
+                            // || desc.layout == C2Color::INTERLEAVED_PACKED
+                            // || desc.layout == C2Color::INTERLEAVED_ALIGNED
+                            || desc.layout == C2Color::UNKNOWN_LAYOUT) {
+                        continue;
+                    }
+                    if (!flexPixelFormat) {
+                        flexPixelFormat = desc.pixelFormat;
+                    }
+                    if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
+                        flexPlanarPixelFormat = desc.pixelFormat;
+                    }
+                    if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
+                        flexSemiPlanarPixelFormat = desc.pixelFormat;
+                    }
+                }
+            }
             if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
-                /*
-                 * Also handle default color format (encoders require color format, so this is only
-                 * needed for decoders.
-                 */
+                // Also handle default color format (encoders require color format, so this is only
+                // needed for decoders.
                 if (!(config->mDomain & Config::IS_ENCODER)) {
-                    format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
+                    if (surface == nullptr) {
+                        format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
+                    } else {
+                        format = COLOR_FormatSurface;
+                    }
+                    defaultColorFormat = format;
+                }
+            } else {
+                if ((config->mDomain & Config::IS_ENCODER) || !surface) {
+                    switch (format) {
+                        case COLOR_FormatYUV420Flexible:
+                            format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
+                            break;
+                        case COLOR_FormatYUV420Planar:
+                        case COLOR_FormatYUV420PackedPlanar:
+                            format = flexPlanarPixelFormat.value_or(
+                                    flexPixelFormat.value_or(format));
+                            break;
+                        case COLOR_FormatYUV420SemiPlanar:
+                        case COLOR_FormatYUV420PackedSemiPlanar:
+                            format = flexSemiPlanarPixelFormat.value_or(
+                                    flexPixelFormat.value_or(format));
+                            break;
+                        default:
+                            // No-op
+                            break;
+                    }
                 }
             }
 
-            if (format >= 0) {
+            if (format != 0) {
                 msg->setInt32("android._color-format", format);
             }
         }
@@ -932,7 +1055,10 @@
         C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
         C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
 
+        C2Param::Index colorAspectsRequestIndex =
+            C2StreamColorAspectsInfo::output::PARAM_TYPE | C2Param::CoreIndex::IS_REQUEST_FLAG;
         std::initializer_list<C2Param::Index> indices {
+            colorAspectsRequestIndex.withStream(0u),
         };
         c2_status_t c2err = comp->query(
                 { &usage, &maxInputSize, &prepend },
@@ -943,11 +1069,6 @@
             ALOGE("Failed to query component interface: %d", c2err);
             return UNKNOWN_ERROR;
         }
-        if (params.size() != indices.size()) {
-            ALOGE("Component returns wrong number of params: expected %zu actual %zu",
-                    indices.size(), params.size());
-            return UNKNOWN_ERROR;
-        }
         if (usage) {
             if (usage.value & C2MemoryUsage::CPU_READ) {
                 config->mInputFormat->setInt32("using-sw-read-often", true);
@@ -1019,6 +1140,7 @@
             return BAD_VALUE;
         }
 
+        int32_t componentColorFormat = 0;
         if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
             // propagate HDR static info to output format for both encoders and decoders
             // if component supports this info, we will update from component, but only the raw port,
@@ -1031,12 +1153,16 @@
 
             // Set desired color format from configuration parameter
             int32_t format;
-            if (msg->findInt32("android._color-format", &format)) {
-                if (config->mDomain & Config::IS_ENCODER) {
-                    config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
-                } else {
-                    config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
+            if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
+                format = defaultColorFormat;
+            }
+            if (config->mDomain & Config::IS_ENCODER) {
+                config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
+                if (msg->findInt32("android._color-format", &componentColorFormat)) {
+                    config->mInputFormat->setInt32("android._color-format", componentColorFormat);
                 }
+            } else {
+                config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
             }
         }
 
@@ -1064,8 +1190,86 @@
             }
         }
 
-        ALOGD("setup formats input: %s and output: %s",
-                config->mInputFormat->debugString().c_str(),
+        std::unique_ptr<C2Param> colorTransferRequestParam;
+        for (std::unique_ptr<C2Param> &param : params) {
+            if (param->index() == colorAspectsRequestIndex.withStream(0u)) {
+                ALOGI("found color transfer request param");
+                colorTransferRequestParam = std::move(param);
+            }
+        }
+        int32_t colorTransferRequest = 0;
+        if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)
+                && !sdkParams->findInt32("color-transfer-request", &colorTransferRequest)) {
+            colorTransferRequest = 0;
+        }
+
+        if (colorTransferRequest != 0) {
+            if (colorTransferRequestParam && *colorTransferRequestParam) {
+                C2StreamColorAspectsInfo::output *info =
+                    static_cast<C2StreamColorAspectsInfo::output *>(
+                            colorTransferRequestParam.get());
+                if (!C2Mapper::map(info->transfer, &colorTransferRequest)) {
+                    colorTransferRequest = 0;
+                }
+            } else {
+                colorTransferRequest = 0;
+            }
+            config->mInputFormat->setInt32("color-transfer-request", colorTransferRequest);
+        }
+
+        if (componentColorFormat != 0 && componentColorFormat != COLOR_FormatSurface) {
+            // Need to get stride/vstride
+            uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
+            if (C2Mapper::mapPixelFormatFrameworkToCodec(componentColorFormat, &pixelFormat)) {
+                // TODO: retrieve these values without allocating a buffer.
+                //       Currently allocating a buffer is necessary to retrieve the layout.
+                int64_t blockUsage =
+                    usage.value | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE;
+                std::shared_ptr<C2GraphicBlock> block = FetchGraphicBlock(
+                        width, height, pixelFormat, blockUsage, {comp->getName()});
+                sp<GraphicBlockBuffer> buffer;
+                if (block) {
+                    buffer = GraphicBlockBuffer::Allocate(
+                            config->mInputFormat,
+                            block,
+                            [](size_t size) -> sp<ABuffer> { return new ABuffer(size); });
+                } else {
+                    ALOGD("Failed to allocate a graphic block "
+                            "(width=%d height=%d pixelFormat=%u usage=%llx)",
+                            width, height, pixelFormat, (long long)blockUsage);
+                    // This means that byte buffer mode is not supported in this configuration
+                    // anyway. Skip setting stride/vstride to input format.
+                }
+                if (buffer) {
+                    sp<ABuffer> imageData = buffer->getImageData();
+                    MediaImage2 *img = nullptr;
+                    if (imageData && imageData->data()
+                            && imageData->size() >= sizeof(MediaImage2)) {
+                        img = (MediaImage2*)imageData->data();
+                    }
+                    if (img && img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
+                        int32_t stride = img->mPlane[0].mRowInc;
+                        config->mInputFormat->setInt32(KEY_STRIDE, stride);
+                        if (img->mNumPlanes > 1 && stride > 0) {
+                            int64_t offsetDelta =
+                                (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
+                            if (offsetDelta % stride == 0) {
+                                int32_t vstride = int32_t(offsetDelta / stride);
+                                config->mInputFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
+                            } else {
+                                ALOGD("Cannot report accurate slice height: "
+                                        "offsetDelta = %lld stride = %d",
+                                        (long long)offsetDelta, stride);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        ALOGD("setup formats input: %s",
+                config->mInputFormat->debugString().c_str());
+        ALOGD("setup formats output: %s",
                 config->mOutputFormat->debugString().c_str());
         return OK;
     };
@@ -1076,6 +1280,8 @@
     Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
     const std::unique_ptr<Config> &config = *configLocked;
 
+    config->queryConfiguration(comp);
+
     mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
 }
 
@@ -1581,7 +1787,9 @@
     {
         Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
         const std::unique_ptr<Config> &config = *configLocked;
+        sp<AMessage> outputFormat = config->mOutputFormat;
         config->queryConfiguration(comp);
+        RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
     }
 
     (void)mChannel->start(nullptr, nullptr, [&]{
@@ -1669,7 +1877,9 @@
                     || comp->getName().find("c2.android.") == 0)) {
         mChannel->setParameters(configUpdate);
     } else {
+        sp<AMessage> outputFormat = config->mOutputFormat;
         (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
+        RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
     }
 }
 
@@ -1794,7 +2004,6 @@
             // handle configuration changes in work done
             Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
             const std::unique_ptr<Config> &config = *configLocked;
-            bool changed = false;
             Config::Watcher<C2StreamInitDataInfo::output> initData =
                 config->watch<C2StreamInitDataInfo::output>();
             if (!work->worklets.empty()
@@ -1813,27 +2022,30 @@
                         // move all info into output-stream #0 domain
                         updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
                     }
-                    for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
+
+                    const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
+                    // for now only do the first block
+                    if (!blocks.empty()) {
                         // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
                         //      block.crop().left, block.crop().top,
                         //      block.crop().width, block.crop().height,
                         //      block.width(), block.height());
+                        const C2ConstGraphicBlock &block = blocks[0];
                         updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
                         updates.emplace_back(new C2StreamPictureSizeInfo::output(
                                 stream, block.crop().width, block.crop().height));
-                        break; // for now only do the first block
                     }
                     ++stream;
                 }
 
-                if (config->updateConfiguration(updates, config->mOutputDomain)) {
-                    changed = true;
-                }
+                sp<AMessage> outputFormat = config->mOutputFormat;
+                config->updateConfiguration(updates, config->mOutputDomain);
+                RevertOutputFormatIfNeeded(outputFormat, config->mOutputFormat);
 
                 // copy standard infos to graphic buffers if not already present (otherwise, we
                 // may overwrite the actual intermediate value with a final value)
                 stream = 0;
-                const static std::vector<C2Param::Index> stdGfxInfos = {
+                const static C2Param::Index stdGfxInfos[] = {
                     C2StreamRotationInfo::output::PARAM_TYPE,
                     C2StreamColorAspectsInfo::output::PARAM_TYPE,
                     C2StreamDataSpaceInfo::output::PARAM_TYPE,
@@ -1862,7 +2074,7 @@
                 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
             }
             mChannel->onWorkDone(
-                    std::move(work), changed ? config->mOutputFormat->dup() : nullptr,
+                    std::move(work), config->mOutputFormat,
                     initData.hasChanged() ? initData.update().get() : nullptr);
             break;
         }
@@ -1991,7 +2203,7 @@
             }
             if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
                 mInputAllocators.reset(
-                        C2PortAllocatorsTuning::input::From(params[0].get()));
+                        C2PortAllocatorsTuning::input::From(param));
             }
         }
         mInitStatus = OK;
diff --git a/media/codec2/sfplugin/CCodecBufferChannel.cpp b/media/codec2/sfplugin/CCodecBufferChannel.cpp
index 1654b11..4d2700a 100644
--- a/media/codec2/sfplugin/CCodecBufferChannel.cpp
+++ b/media/codec2/sfplugin/CCodecBufferChannel.cpp
@@ -30,6 +30,7 @@
 
 #include <android/hardware/cas/native/1.0/IDescrambler.h>
 #include <android/hardware/drm/1.0/types.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <binder/MemoryBase.h>
 #include <binder/MemoryDealer.h>
@@ -143,7 +144,8 @@
       mFrameIndex(0u),
       mFirstValidFrameIndex(0u),
       mMetaMode(MODE_NONE),
-      mInputMetEos(false) {
+      mInputMetEos(false),
+      mSendEncryptedInfoBuffer(false) {
     mOutputSurface.lock()->maxDequeueBuffers = kSmoothnessFactor + kRenderingDepth;
     {
         Mutexed<Input>::Locked input(mInput);
@@ -188,7 +190,10 @@
     return mInputSurface->signalEndOfInputStream();
 }
 
-status_t CCodecBufferChannel::queueInputBufferInternal(sp<MediaCodecBuffer> buffer) {
+status_t CCodecBufferChannel::queueInputBufferInternal(
+        sp<MediaCodecBuffer> buffer,
+        std::shared_ptr<C2LinearBlock> encryptedBlock,
+        size_t blockSize) {
     int64_t timeUs;
     CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
 
@@ -209,6 +214,7 @@
         flags |= C2FrameData::FLAG_CODEC_CONFIG;
     }
     ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
+    std::list<std::unique_ptr<C2Work>> items;
     std::unique_ptr<C2Work> work(new C2Work);
     work->input.ordinal.timestamp = timeUs;
     work->input.ordinal.frameIndex = mFrameIndex++;
@@ -218,9 +224,8 @@
     work->input.ordinal.customOrdinal = timeUs;
     work->input.buffers.clear();
 
-    uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
-    std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
     sp<Codec2Buffer> copy;
+    bool usesFrameReassembler = false;
 
     if (buffer->size() > 0u) {
         Mutexed<Input>::Locked input(mInput);
@@ -245,30 +250,48 @@
                       "buffer starvation on component.", mName);
             }
         }
-        work->input.buffers.push_back(c2buffer);
-        queuedBuffers.push_back(c2buffer);
+        if (input->frameReassembler) {
+            usesFrameReassembler = true;
+            input->frameReassembler.process(buffer, &items);
+        } else {
+            int32_t cvo = 0;
+            if (buffer->meta()->findInt32("cvo", &cvo)) {
+                int32_t rotation = cvo % 360;
+                // change rotation to counter-clock wise.
+                rotation = ((rotation <= 0) ? 0 : 360) - rotation;
+
+                Mutexed<OutputSurface>::Locked output(mOutputSurface);
+                uint64_t frameIndex = work->input.ordinal.frameIndex.peeku();
+                output->rotation[frameIndex] = rotation;
+            }
+            work->input.buffers.push_back(c2buffer);
+            if (encryptedBlock) {
+                work->input.infoBuffers.emplace_back(C2InfoBuffer::CreateLinearBuffer(
+                        kParamIndexEncryptedBuffer,
+                        encryptedBlock->share(0, blockSize, C2Fence())));
+            }
+        }
     } else if (eos) {
         flags |= C2FrameData::FLAG_END_OF_STREAM;
     }
-    work->input.flags = (C2FrameData::flags_t)flags;
-    // TODO: fill info's
+    if (usesFrameReassembler) {
+        if (!items.empty()) {
+            items.front()->input.configUpdate = std::move(mParamsToBeSet);
+            mFrameIndex = (items.back()->input.ordinal.frameIndex + 1).peek();
+        }
+    } else {
+        work->input.flags = (C2FrameData::flags_t)flags;
+        // TODO: fill info's
 
-    work->input.configUpdate = std::move(mParamsToBeSet);
-    work->worklets.clear();
-    work->worklets.emplace_back(new C2Worklet);
+        work->input.configUpdate = std::move(mParamsToBeSet);
+        work->worklets.clear();
+        work->worklets.emplace_back(new C2Worklet);
 
-    std::list<std::unique_ptr<C2Work>> items;
-    items.push_back(std::move(work));
-    mPipelineWatcher.lock()->onWorkQueued(
-            queuedFrameIndex,
-            std::move(queuedBuffers),
-            PipelineWatcher::Clock::now());
-    c2_status_t err = mComponent->queue(&items);
-    if (err != C2_OK) {
-        mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
+        items.push_back(std::move(work));
+
+        eos = eos && buffer->size() > 0u;
     }
-
-    if (err == C2_OK && eos && buffer->size() > 0u) {
+    if (eos) {
         work.reset(new C2Work);
         work->input.ordinal.timestamp = timeUs;
         work->input.ordinal.frameIndex = mFrameIndex++;
@@ -277,23 +300,28 @@
         work->input.buffers.clear();
         work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
         work->worklets.emplace_back(new C2Worklet);
-
-        queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
-        queuedBuffers.clear();
-
-        items.clear();
         items.push_back(std::move(work));
-
-        mPipelineWatcher.lock()->onWorkQueued(
-                queuedFrameIndex,
-                std::move(queuedBuffers),
-                PipelineWatcher::Clock::now());
-        err = mComponent->queue(&items);
-        if (err != C2_OK) {
-            mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
-        }
     }
-    if (err == C2_OK) {
+    c2_status_t err = C2_OK;
+    if (!items.empty()) {
+        {
+            Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
+            PipelineWatcher::Clock::time_point now = PipelineWatcher::Clock::now();
+            for (const std::unique_ptr<C2Work> &work : items) {
+                watcher->onWorkQueued(
+                        work->input.ordinal.frameIndex.peeku(),
+                        std::vector(work->input.buffers),
+                        now);
+            }
+        }
+        err = mComponent->queue(&items);
+    }
+    if (err != C2_OK) {
+        Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
+        for (const std::unique_ptr<C2Work> &work : items) {
+            watcher->onWorkDone(work->input.ordinal.frameIndex.peeku());
+        }
+    } else {
         Mutexed<Input>::Locked input(mInput);
         bool released = false;
         if (buffer) {
@@ -514,6 +542,40 @@
     }
     sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
 
+    std::shared_ptr<C2LinearBlock> block;
+    size_t allocSize = buffer->size();
+    size_t bufferSize = 0;
+    c2_status_t blockRes = C2_OK;
+    bool copied = false;
+    if (mSendEncryptedInfoBuffer) {
+        static const C2MemoryUsage kDefaultReadWriteUsage{
+            C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
+        constexpr int kAllocGranule0 = 1024 * 64;
+        constexpr int kAllocGranule1 = 1024 * 1024;
+        std::shared_ptr<C2BlockPool> pool = mBlockPools.lock()->inputPool;
+        // round up encrypted sizes to limit fragmentation and encourage buffer reuse
+        if (allocSize <= kAllocGranule1) {
+            bufferSize = align(allocSize, kAllocGranule0);
+        } else {
+            bufferSize = align(allocSize, kAllocGranule1);
+        }
+        blockRes = pool->fetchLinearBlock(
+                bufferSize, kDefaultReadWriteUsage, &block);
+
+        if (blockRes == C2_OK) {
+            C2WriteView view = block->map().get();
+            if (view.error() == C2_OK && view.size() == bufferSize) {
+                copied = true;
+                // TODO: only copy clear sections
+                memcpy(view.data(), buffer->data(), allocSize);
+            }
+        }
+    }
+
+    if (!copied) {
+        block.reset();
+    }
+
     ssize_t result = -1;
     ssize_t codecDataOffset = 0;
     if (numSubSamples == 1
@@ -605,7 +667,8 @@
     }
 
     buffer->setRange(codecDataOffset, result - codecDataOffset);
-    return queueInputBufferInternal(buffer);
+
+    return queueInputBufferInternal(buffer, block, bufferSize);
 }
 
 void CCodecBufferChannel::feedInputBufferIfAvailable() {
@@ -695,6 +758,22 @@
                 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
     bool flip = rotation && (rotation->flip & 1);
     uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
+
+    {
+        Mutexed<OutputSurface>::Locked output(mOutputSurface);
+        if (output->surface == nullptr) {
+            ALOGI("[%s] cannot render buffer without surface", mName);
+            return OK;
+        }
+        int64_t frameIndex;
+        buffer->meta()->findInt64("frameIndex", &frameIndex);
+        if (output->rotation.count(frameIndex) != 0) {
+            auto it = output->rotation.find(frameIndex);
+            quarters = (it->second / 90) & 3;
+            output->rotation.erase(it);
+        }
+    }
+
     uint32_t transform = 0;
     switch (quarters) {
         case 0: // no rotation
@@ -738,14 +817,6 @@
         hdr10PlusInfo.reset();
     }
 
-    {
-        Mutexed<OutputSurface>::Locked output(mOutputSurface);
-        if (output->surface == nullptr) {
-            ALOGI("[%s] cannot render buffer without surface", mName);
-            return OK;
-        }
-    }
-
     std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
     if (blocks.size() != 1u) {
         ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
@@ -816,9 +887,17 @@
     status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
     if (result != OK) {
         ALOGI("[%s] queueBuffer failed: %d", mName, result);
+        if (result == NO_INIT) {
+            mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
+        }
         return result;
     }
-    ALOGV("[%s] queue buffer successful", mName);
+
+    if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
+        ALOGD("[%s] queue buffer successful", mName);
+    } else {
+        ALOGV("[%s] queue buffer successful", mName);
+    }
 
     int64_t mediaTimeUs = 0;
     (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
@@ -879,27 +958,31 @@
         bool buffersBoundToCodec) {
     C2StreamBufferTypeSetting::input iStreamFormat(0u);
     C2StreamBufferTypeSetting::output oStreamFormat(0u);
+    C2ComponentKindSetting kind;
     C2PortReorderBufferDepthTuning::output reorderDepth;
     C2PortReorderKeySetting::output reorderKey;
     C2PortActualDelayTuning::input inputDelay(0);
     C2PortActualDelayTuning::output outputDelay(0);
     C2ActualPipelineDelayTuning pipelineDelay(0);
+    C2SecureModeTuning secureMode(C2Config::SM_UNPROTECTED);
 
     c2_status_t err = mComponent->query(
             {
                 &iStreamFormat,
                 &oStreamFormat,
+                &kind,
                 &reorderDepth,
                 &reorderKey,
                 &inputDelay,
                 &pipelineDelay,
                 &outputDelay,
+                &secureMode,
             },
             {},
             C2_DONT_BLOCK,
             nullptr);
     if (err == C2_BAD_INDEX) {
-        if (!iStreamFormat || !oStreamFormat) {
+        if (!iStreamFormat || !oStreamFormat || !kind) {
             return UNKNOWN_ERROR;
         }
     } else if (err != C2_OK) {
@@ -916,18 +999,26 @@
     // TODO: get this from input format
     bool secure = mComponent->getName().find(".secure") != std::string::npos;
 
+    // secure mode is a static parameter (shall not change in the executing state)
+    mSendEncryptedInfoBuffer = secureMode.value == C2Config::SM_READ_PROTECTED_WITH_ENCRYPTED;
+
     std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
     int poolMask = GetCodec2PoolMask();
     C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
 
     if (inputFormat != nullptr) {
         bool graphic = (iStreamFormat.value == C2BufferData::GRAPHIC);
+        bool audioEncoder = !graphic && (kind.value == C2Component::KIND_ENCODER);
         C2Config::api_feature_t apiFeatures = C2Config::api_feature_t(
                 API_REFLECTION |
                 API_VALUES |
                 API_CURRENT_VALUES |
                 API_DEPENDENCY |
                 API_SAME_INPUT_BUFFER);
+        C2StreamAudioFrameSizeInfo::input encoderFrameSize(0u);
+        C2StreamSampleRateInfo::input sampleRate(0u);
+        C2StreamChannelCountInfo::input channelCount(0u);
+        C2StreamPcmEncodingInfo::input pcmEncoding(0u);
         std::shared_ptr<C2BlockPool> pool;
         {
             Mutexed<BlockPools>::Locked pools(mBlockPools);
@@ -940,7 +1031,19 @@
             // from component, create the input block pool with given ID. Otherwise, use default IDs.
             std::vector<std::unique_ptr<C2Param>> params;
             C2ApiFeaturesSetting featuresSetting{apiFeatures};
-            err = mComponent->query({ &featuresSetting },
+            std::vector<C2Param *> stackParams({&featuresSetting});
+            if (audioEncoder) {
+                stackParams.push_back(&encoderFrameSize);
+                stackParams.push_back(&sampleRate);
+                stackParams.push_back(&channelCount);
+                stackParams.push_back(&pcmEncoding);
+            } else {
+                encoderFrameSize.invalidate();
+                sampleRate.invalidate();
+                channelCount.invalidate();
+                pcmEncoding.invalidate();
+            }
+            err = mComponent->query(stackParams,
                                     { C2PortAllocatorsTuning::input::PARAM_TYPE },
                                     C2_DONT_BLOCK,
                                     &params);
@@ -998,10 +1101,21 @@
         input->numSlots = numInputSlots;
         input->extraBuffers.flush();
         input->numExtraSlots = 0u;
+        if (audioEncoder && encoderFrameSize && sampleRate && channelCount) {
+            input->frameReassembler.init(
+                    pool,
+                    {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
+                    encoderFrameSize.value,
+                    sampleRate.value,
+                    channelCount.value,
+                    pcmEncoding ? pcmEncoding.value : C2Config::PCM_16);
+        }
         bool conforming = (apiFeatures & API_SAME_INPUT_BUFFER);
         // For encrypted content, framework decrypts source buffer (ashmem) into
         // C2Buffers. Thus non-conforming codecs can process these.
-        if (!buffersBoundToCodec && (hasCryptoOrDescrambler() || conforming)) {
+        if (!buffersBoundToCodec
+                && !input->frameReassembler
+                && (hasCryptoOrDescrambler() || conforming)) {
             input->buffers.reset(new SlotInputBuffers(mName));
         } else if (graphic) {
             if (mInputSurface) {
@@ -1063,9 +1177,6 @@
             Mutexed<OutputSurface>::Locked output(mOutputSurface);
             output->maxDequeueBuffers = numOutputSlots +
                     reorderDepth.value + kRenderingDepth;
-            if (!secure) {
-                output->maxDequeueBuffers += numInputSlots;
-            }
             outputSurface = output->surface ?
                     output->surface->getIGraphicBufferProducer() : nullptr;
             if (outputSurface) {
@@ -1300,54 +1411,30 @@
                 return a.capacity < b.capacity;
             });
 
-    {
-        Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
-        if (!configs->empty()) {
-            while (!configs->empty()) {
-                sp<ABuffer> config = configs->front();
-                configs->pop_front();
-                // Find the smallest input buffer that can fit the config.
-                auto i = std::find_if(
-                        clientInputBuffers.begin(),
-                        clientInputBuffers.end(),
-                        [cfgSize = config->size()](const ClientInputBuffer& b) {
-                            return b.capacity >= cfgSize;
-                        });
-                if (i == clientInputBuffers.end()) {
-                    ALOGW("[%s] no input buffer large enough for the config "
-                          "(%zu bytes)",
-                          mName, config->size());
-                    return NO_MEMORY;
-                }
-                sp<MediaCodecBuffer> buffer = i->buffer;
-                memcpy(buffer->base(), config->data(), config->size());
-                buffer->setRange(0, config->size());
-                buffer->meta()->clear();
-                buffer->meta()->setInt64("timeUs", 0);
-                buffer->meta()->setInt32("csd", 1);
-                if (queueInputBufferInternal(buffer) != OK) {
-                    ALOGW("[%s] Error while queueing a flushed config",
-                          mName);
-                    return UNKNOWN_ERROR;
-                }
-                clientInputBuffers.erase(i);
-            }
-        } else if (oStreamFormat.value == C2BufferData::LINEAR &&
-                   (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
-            sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
-            // WORKAROUND: Some apps expect CSD available without queueing
-            //             any input. Queue an empty buffer to get the CSD.
-            buffer->setRange(0, 0);
-            buffer->meta()->clear();
-            buffer->meta()->setInt64("timeUs", 0);
-            if (queueInputBufferInternal(buffer) != OK) {
-                ALOGW("[%s] Error while queueing an empty buffer to get CSD",
-                      mName);
-                return UNKNOWN_ERROR;
-            }
-            clientInputBuffers.pop_front();
+    std::list<std::unique_ptr<C2Work>> flushedConfigs;
+    mFlushedConfigs.lock()->swap(flushedConfigs);
+    if (!flushedConfigs.empty()) {
+        err = mComponent->queue(&flushedConfigs);
+        if (err != C2_OK) {
+            ALOGW("[%s] Error while queueing a flushed config", mName);
+            return UNKNOWN_ERROR;
         }
     }
+    if (oStreamFormat.value == C2BufferData::LINEAR &&
+            (!prepend || prepend.value == PREPEND_HEADER_TO_NONE)) {
+        sp<MediaCodecBuffer> buffer = clientInputBuffers.front().buffer;
+        // WORKAROUND: Some apps expect CSD available without queueing
+        //             any input. Queue an empty buffer to get the CSD.
+        buffer->setRange(0, 0);
+        buffer->meta()->clear();
+        buffer->meta()->setInt64("timeUs", 0);
+        if (queueInputBufferInternal(buffer) != OK) {
+            ALOGW("[%s] Error while queueing an empty buffer to get CSD",
+                  mName);
+            return UNKNOWN_ERROR;
+        }
+        clientInputBuffers.pop_front();
+    }
 
     for (const ClientInputBuffer& clientInputBuffer: clientInputBuffers) {
         mCallback->onInputBufferAvailable(
@@ -1396,27 +1483,36 @@
 
 void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
     ALOGV("[%s] flush", mName);
-    {
-        Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
-        for (const std::unique_ptr<C2Work> &work : flushedWork) {
-            if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
-                continue;
-            }
-            if (work->input.buffers.empty()
-                    || work->input.buffers.front()->data().linearBlocks().empty()) {
-                ALOGD("[%s] no linear codec config data found", mName);
-                continue;
-            }
-            C2ReadView view =
-                    work->input.buffers.front()->data().linearBlocks().front().map().get();
-            if (view.error() != C2_OK) {
-                ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
-                continue;
-            }
-            configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
-            ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
+    std::list<std::unique_ptr<C2Work>> configs;
+    for (const std::unique_ptr<C2Work> &work : flushedWork) {
+        if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
+            continue;
         }
+        if (work->input.buffers.empty()
+                || work->input.buffers.front() == nullptr
+                || work->input.buffers.front()->data().linearBlocks().empty()) {
+            ALOGD("[%s] no linear codec config data found", mName);
+            continue;
+        }
+        std::unique_ptr<C2Work> copy(new C2Work);
+        copy->input.flags = C2FrameData::flags_t(work->input.flags | C2FrameData::FLAG_DROP_FRAME);
+        copy->input.ordinal = work->input.ordinal;
+        copy->input.buffers.insert(
+                copy->input.buffers.begin(),
+                work->input.buffers.begin(),
+                work->input.buffers.end());
+        for (const std::unique_ptr<C2Param> &param : work->input.configUpdate) {
+            copy->input.configUpdate.push_back(C2Param::Copy(*param));
+        }
+        copy->input.infoBuffers.insert(
+                copy->input.infoBuffers.begin(),
+                work->input.infoBuffers.begin(),
+                work->input.infoBuffers.end());
+        copy->worklets.emplace_back(new C2Worklet);
+        configs.push_back(std::move(copy));
+        ALOGV("[%s] stashed flushed codec config data", mName);
     }
+    mFlushedConfigs.lock()->swap(configs);
     {
         Mutexed<Input>::Locked input(mInput);
         input->buffers->flush();
@@ -1526,6 +1622,7 @@
     }
 
     std::optional<uint32_t> newInputDelay, newPipelineDelay;
+    bool needMaxDequeueBufferCountUpdate = false;
     while (!worklet->output.configUpdate.empty()) {
         std::unique_ptr<C2Param> param;
         worklet->output.configUpdate.back().swap(param);
@@ -1534,24 +1631,10 @@
             case C2PortReorderBufferDepthTuning::CORE_INDEX: {
                 C2PortReorderBufferDepthTuning::output reorderDepth;
                 if (reorderDepth.updateFrom(*param)) {
-                    bool secure = mComponent->getName().find(".secure") !=
-                                  std::string::npos;
-                    mOutput.lock()->buffers->setReorderDepth(
-                            reorderDepth.value);
                     ALOGV("[%s] onWorkDone: updated reorder depth to %u",
                           mName, reorderDepth.value);
-                    size_t numOutputSlots = mOutput.lock()->numSlots;
-                    size_t numInputSlots = mInput.lock()->numSlots;
-                    Mutexed<OutputSurface>::Locked output(mOutputSurface);
-                    output->maxDequeueBuffers = numOutputSlots +
-                            reorderDepth.value + kRenderingDepth;
-                    if (!secure) {
-                        output->maxDequeueBuffers += numInputSlots;
-                    }
-                    if (output->surface) {
-                        output->surface->setMaxDequeuedBufferCount(
-                                output->maxDequeueBuffers);
-                    }
+                    mOutput.lock()->buffers->setReorderDepth(reorderDepth.value);
+                    needMaxDequeueBufferCountUpdate = true;
                 } else {
                     ALOGD("[%s] onWorkDone: failed to read reorder depth",
                           mName);
@@ -1595,14 +1678,11 @@
                     if (outputDelay.updateFrom(*param)) {
                         ALOGV("[%s] onWorkDone: updating output delay %u",
                               mName, outputDelay.value);
-                        bool secure = mComponent->getName().find(".secure") !=
-                                      std::string::npos;
-                        (void)mPipelineWatcher.lock()->outputDelay(
-                                outputDelay.value);
+                        (void)mPipelineWatcher.lock()->outputDelay(outputDelay.value);
+                        needMaxDequeueBufferCountUpdate = true;
 
                         bool outputBuffersChanged = false;
                         size_t numOutputSlots = 0;
-                        size_t numInputSlots = mInput.lock()->numSlots;
                         {
                             Mutexed<Output>::Locked output(mOutput);
                             if (!output->buffers) {
@@ -1628,16 +1708,6 @@
                         if (outputBuffersChanged) {
                             mCCodecCallback->onOutputBuffersChanged();
                         }
-
-                        uint32_t depth = mOutput.lock()->buffers->getReorderDepth();
-                        Mutexed<OutputSurface>::Locked output(mOutputSurface);
-                        output->maxDequeueBuffers = numOutputSlots + depth + kRenderingDepth;
-                        if (!secure) {
-                            output->maxDequeueBuffers += numInputSlots;
-                        }
-                        if (output->surface) {
-                            output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
-                        }
                     }
                 }
                 break;
@@ -1666,6 +1736,20 @@
             input->numSlots = newNumSlots;
         }
     }
+    if (needMaxDequeueBufferCountUpdate) {
+        size_t numOutputSlots = 0;
+        uint32_t reorderDepth = 0;
+        {
+            Mutexed<Output>::Locked output(mOutput);
+            numOutputSlots = output->numSlots;
+            reorderDepth = output->buffers->getReorderDepth();
+        }
+        Mutexed<OutputSurface>::Locked output(mOutputSurface);
+        output->maxDequeueBuffers = numOutputSlots + reorderDepth + kRenderingDepth;
+        if (output->surface) {
+            output->surface->setMaxDequeuedBufferCount(output->maxDequeueBuffers);
+        }
+    }
 
     int32_t flags = 0;
     if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
diff --git a/media/codec2/sfplugin/CCodecBufferChannel.h b/media/codec2/sfplugin/CCodecBufferChannel.h
index 046c5c3..45da003 100644
--- a/media/codec2/sfplugin/CCodecBufferChannel.h
+++ b/media/codec2/sfplugin/CCodecBufferChannel.h
@@ -31,6 +31,7 @@
 #include <media/stagefright/CodecBase.h>
 
 #include "CCodecBuffers.h"
+#include "FrameReassembler.h"
 #include "InputSurfaceWrapper.h"
 #include "PipelineWatcher.h"
 
@@ -238,7 +239,9 @@
 
     void feedInputBufferIfAvailable();
     void feedInputBufferIfAvailableInternal();
-    status_t queueInputBufferInternal(sp<MediaCodecBuffer> buffer);
+    status_t queueInputBufferInternal(sp<MediaCodecBuffer> buffer,
+                                      std::shared_ptr<C2LinearBlock> encryptedBlock = nullptr,
+                                      size_t blockSize = 0);
     bool handleWork(
             std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
             const C2StreamInitDataInfo::output *initData);
@@ -269,6 +272,8 @@
         size_t numExtraSlots;
         uint32_t inputDelay;
         uint32_t pipelineDelay;
+
+        FrameReassembler frameReassembler;
     };
     Mutexed<Input> mInput;
     struct Output {
@@ -277,7 +282,7 @@
         uint32_t outputDelay;
     };
     Mutexed<Output> mOutput;
-    Mutexed<std::list<sp<ABuffer>>> mFlushedConfigs;
+    Mutexed<std::list<std::unique_ptr<C2Work>>> mFlushedConfigs;
 
     std::atomic_uint64_t mFrameIndex;
     std::atomic_uint64_t mFirstValidFrameIndex;
@@ -288,6 +293,7 @@
         sp<Surface> surface;
         uint32_t generation;
         int maxDequeueBuffers;
+        std::map<uint64_t, int> rotation;
     };
     Mutexed<OutputSurface> mOutputSurface;
 
@@ -315,6 +321,7 @@
     inline bool hasCryptoOrDescrambler() {
         return mCrypto != nullptr || mDescrambler != nullptr;
     }
+    std::atomic_bool mSendEncryptedInfoBuffer;
 };
 
 // Conversion of a c2_status_t value to a status_t value may depend on the
diff --git a/media/codec2/sfplugin/CCodecBuffers.cpp b/media/codec2/sfplugin/CCodecBuffers.cpp
index bddaa9f..6825dc2 100644
--- a/media/codec2/sfplugin/CCodecBuffers.cpp
+++ b/media/codec2/sfplugin/CCodecBuffers.cpp
@@ -27,6 +27,7 @@
 #include <mediadrm/ICrypto.h>
 
 #include "CCodecBuffers.h"
+#include "Codec2Mapper.h"
 
 namespace android {
 
@@ -91,9 +92,14 @@
             newFormat->setInt32(KEY_STRIDE, stride);
             ALOGD("[%s] updating stride = %d", mName, stride);
             if (img->mNumPlanes > 1 && stride > 0) {
-                int32_t vstride = (img->mPlane[1].mOffset - img->mPlane[0].mOffset) / stride;
+                int64_t offsetDelta =
+                    (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
+                int32_t vstride = int32_t(offsetDelta / stride);
                 newFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
                 ALOGD("[%s] updating vstride = %d", mName, vstride);
+                buffer->setRange(
+                        img->mPlane[0].mOffset,
+                        buffer->size() - img->mPlane[0].mOffset);
             }
         }
         setFormat(newFormat);
@@ -156,8 +162,7 @@
     setSkipCutBuffer(delay, padding);
 }
 
-void OutputBuffers::updateSkipCutBuffer(
-        const sp<AMessage> &format, bool notify) {
+void OutputBuffers::updateSkipCutBuffer(const sp<AMessage> &format) {
     AString mediaType;
     if (format->findString(KEY_MIME, &mediaType)
             && mediaType == MIMETYPE_AUDIO_RAW) {
@@ -168,9 +173,6 @@
             updateSkipCutBuffer(sampleRate, channelCount);
         }
     }
-    if (notify) {
-        mUnreportedFormat = nullptr;
-    }
 }
 
 void OutputBuffers::submit(const sp<MediaCodecBuffer> &buffer) {
@@ -194,7 +196,6 @@
     mReorderStash.clear();
     mDepth = 0;
     mKey = C2Config::ORDINAL;
-    mUnreportedFormat = nullptr;
 }
 
 void OutputBuffers::flushStash() {
@@ -270,25 +271,25 @@
     *c2Buffer = entry.buffer;
     sp<AMessage> outputFormat = entry.format;
 
-    // The output format can be processed without a registered slot.
-    if (outputFormat) {
-        updateSkipCutBuffer(outputFormat, entry.notify);
-    }
-
-    if (entry.notify) {
-        if (outputFormat) {
-            setFormat(outputFormat);
-        } else if (mUnreportedFormat) {
-            outputFormat = mUnreportedFormat;
-            setFormat(outputFormat);
+    if (entry.notify && mFormat != outputFormat) {
+        updateSkipCutBuffer(outputFormat);
+        sp<ABuffer> imageData;
+        if (mFormat->findBuffer("image-data", &imageData)) {
+            outputFormat->setBuffer("image-data", imageData);
         }
-        mUnreportedFormat = nullptr;
-    } else {
-        if (outputFormat) {
-            mUnreportedFormat = outputFormat;
-        } else if (!mUnreportedFormat) {
-            mUnreportedFormat = mFormat;
+        int32_t stride;
+        if (mFormat->findInt32(KEY_STRIDE, &stride)) {
+            outputFormat->setInt32(KEY_STRIDE, stride);
         }
+        int32_t sliceHeight;
+        if (mFormat->findInt32(KEY_SLICE_HEIGHT, &sliceHeight)) {
+            outputFormat->setInt32(KEY_SLICE_HEIGHT, sliceHeight);
+        }
+        ALOGV("[%s] popFromStashAndRegister: output format reference changed: %p -> %p",
+                mName, mFormat.get(), outputFormat.get());
+        ALOGD("[%s] popFromStashAndRegister: output format changed to %s",
+                mName, outputFormat->debugString().c_str());
+        setFormat(outputFormat);
     }
 
     // Flushing mReorderStash because no other buffers should come after output
@@ -299,10 +300,6 @@
     }
 
     if (!entry.notify) {
-        if (outputFormat) {
-            ALOGD("[%s] popFromStashAndRegister: output format changed to %s",
-                    mName, outputFormat->debugString().c_str());
-        }
         mPending.pop_front();
         return DISCARD;
     }
@@ -319,10 +316,7 @@
     // Append information from the front stash entry to outBuffer.
     (*outBuffer)->meta()->setInt64("timeUs", entry.timestamp);
     (*outBuffer)->meta()->setInt32("flags", entry.flags);
-    if (outputFormat) {
-        ALOGD("[%s] popFromStashAndRegister: output format changed to %s",
-                mName, outputFormat->debugString().c_str());
-    }
+    (*outBuffer)->meta()->setInt64("frameIndex", entry.ordinal.frameIndex.peekll());
     ALOGV("[%s] popFromStashAndRegister: "
           "out buffer index = %zu [%p] => %p + %zu (%lld)",
           mName, *index, outBuffer->get(),
@@ -1014,18 +1008,32 @@
     // track of the flushed work.
 }
 
+static uint32_t extractPixelFormat(const sp<AMessage> &format) {
+    int32_t frameworkColorFormat = 0;
+    if (!format->findInt32("android._color-format", &frameworkColorFormat)) {
+        return PIXEL_FORMAT_UNKNOWN;
+    }
+    uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
+    if (C2Mapper::mapPixelFormatFrameworkToCodec(frameworkColorFormat, &pixelFormat)) {
+        return pixelFormat;
+    }
+    return PIXEL_FORMAT_UNKNOWN;
+}
+
 std::unique_ptr<InputBuffers> GraphicInputBuffers::toArrayMode(size_t size) {
     std::unique_ptr<InputBuffersArray> array(
             new InputBuffersArray(mComponentName.c_str(), "2D-BB-Input[N]"));
     array->setPool(mPool);
     array->setFormat(mFormat);
+    uint32_t pixelFormat = extractPixelFormat(mFormat);
     array->initialize(
             mImpl,
             size,
-            [pool = mPool, format = mFormat, lbp = mLocalBufferPool]() -> sp<Codec2Buffer> {
+            [pool = mPool, format = mFormat, lbp = mLocalBufferPool, pixelFormat]()
+                    -> sp<Codec2Buffer> {
                 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
                 return AllocateGraphicBuffer(
-                        pool, format, HAL_PIXEL_FORMAT_YV12, usage, lbp);
+                        pool, format, pixelFormat, usage, lbp);
             });
     return std::move(array);
 }
@@ -1038,7 +1046,7 @@
     // TODO: read usage from intf
     C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
     return AllocateGraphicBuffer(
-            mPool, mFormat, HAL_PIXEL_FORMAT_YV12, usage, mLocalBufferPool);
+            mPool, mFormat, extractPixelFormat(mFormat), usage, mLocalBufferPool);
 }
 
 // OutputBuffersArray
@@ -1174,7 +1182,6 @@
 void OutputBuffersArray::transferFrom(OutputBuffers* source) {
     mFormat = source->mFormat;
     mSkipCutBuffer = source->mSkipCutBuffer;
-    mUnreportedFormat = source->mUnreportedFormat;
     mPending = std::move(source->mPending);
     mReorderStash = std::move(source->mReorderStash);
     mDepth = source->mDepth;
diff --git a/media/codec2/sfplugin/CCodecBuffers.h b/media/codec2/sfplugin/CCodecBuffers.h
index 4772ab5..7c4e7b1 100644
--- a/media/codec2/sfplugin/CCodecBuffers.h
+++ b/media/codec2/sfplugin/CCodecBuffers.h
@@ -33,8 +33,8 @@
 class SkipCutBuffer;
 
 constexpr size_t kLinearBufferSize = 1048576;
-// This can fit 4K RGBA frame, and most likely client won't need more than this.
-constexpr size_t kMaxLinearBufferSize = 4096 * 2304 * 4;
+// This can fit an 8K frame.
+constexpr size_t kMaxLinearBufferSize = 7680 * 4320 * 2;
 
 /**
  * Base class for representation of buffers at one port.
@@ -215,10 +215,8 @@
 
     /**
      * Update SkipCutBuffer from format. The @p format must not be null.
-     * @p notify determines whether the format comes with a buffer that should
-     * be reported to the client or not.
      */
-    void updateSkipCutBuffer(const sp<AMessage> &format, bool notify = true);
+    void updateSkipCutBuffer(const sp<AMessage> &format);
 
     /**
      * Output Stash
@@ -392,9 +390,6 @@
 
     // Output stash
 
-    // Output format that has not been made available to the client.
-    sp<AMessage> mUnreportedFormat;
-
     // Struct for an entry in the output stash (mPending and mReorderStash)
     struct StashEntry {
         inline StashEntry()
diff --git a/media/codec2/sfplugin/CCodecConfig.cpp b/media/codec2/sfplugin/CCodecConfig.cpp
index 79c6227..d3814fb 100644
--- a/media/codec2/sfplugin/CCodecConfig.cpp
+++ b/media/codec2/sfplugin/CCodecConfig.cpp
@@ -415,19 +415,38 @@
     add(ConfigMapper("color-matrix",        C2_PARAMKEY_DEFAULT_COLOR_ASPECTS,   "matrix")
         .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::CODED & (D::CONFIG | D::PARAM)));
 
+    // read back default for decoders. This is needed in case the component does not support
+    // color aspects. In that case, these values get copied to color-* keys.
+    // TRICKY: We read these values at raw port, since that's where we want to read these.
+    add(ConfigMapper("default-color-range",     C2_PARAMKEY_DEFAULT_COLOR_ASPECTS,   "range")
+        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW & D::READ)
+        .withC2Mappers<C2Color::range_t>());
+    add(ConfigMapper("default-color-transfer",  C2_PARAMKEY_DEFAULT_COLOR_ASPECTS,   "transfer")
+        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW & D::READ)
+        .withC2Mappers<C2Color::transfer_t>());
+    add(ConfigMapper("default-color-primaries", C2_PARAMKEY_DEFAULT_COLOR_ASPECTS,   "primaries")
+        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW & D::READ));
+    add(ConfigMapper("default-color-matrix",    C2_PARAMKEY_DEFAULT_COLOR_ASPECTS,   "matrix")
+        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW & D::READ));
+
     // read back final for decoder output (also, configure final aspects as well. This should be
     // overwritten based on coded/default values if component supports color aspects, but is used
     // as final values if component does not support aspects at all)
     add(ConfigMapper(KEY_COLOR_RANGE,       C2_PARAMKEY_COLOR_ASPECTS,   "range")
-        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW)
+        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW & D::READ)
         .withC2Mappers<C2Color::range_t>());
     add(ConfigMapper(KEY_COLOR_TRANSFER,    C2_PARAMKEY_COLOR_ASPECTS,   "transfer")
-        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW)
+        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW & D::READ)
         .withC2Mappers<C2Color::transfer_t>());
     add(ConfigMapper("color-primaries",     C2_PARAMKEY_COLOR_ASPECTS,   "primaries")
-        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW));
+        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW & D::READ));
     add(ConfigMapper("color-matrix",        C2_PARAMKEY_COLOR_ASPECTS,   "matrix")
-        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW));
+        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW & D::READ));
+
+    // configure transfer request
+    add(ConfigMapper("color-transfer-request", C2_PARAMKEY_COLOR_ASPECTS, "transfer")
+        .limitTo((D::VIDEO | D::IMAGE) & D::DECODER  & D::RAW & D::CONFIG)
+        .withC2Mappers<C2Color::transfer_t>());
 
     // configure source aspects for encoders and read them back on the coded(!) port.
     // This is to ensure muxing the desired aspects into the container.
@@ -765,21 +784,13 @@
 
     // convert to compression type and add default
     add(ConfigMapper(KEY_AAC_DRC_HEAVY_COMPRESSION, C2_PARAMKEY_DRC_COMPRESSION_MODE, "value")
-        .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
-        .withMappers([](C2Value v) -> C2Value {
+        .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM))
+        .withMapper([](C2Value v) -> C2Value {
             int32_t value;
             if (!v.get(&value) || value < 0) {
                 value = property_get_int32(PROP_DRC_OVERRIDE_HEAVY, DRC_DEFAULT_MOBILE_DRC_HEAVY);
             }
             return value == 1 ? C2Config::DRC_COMPRESSION_HEAVY : C2Config::DRC_COMPRESSION_LIGHT;
-        },[](C2Value v) -> C2Value {
-            int32_t value;
-            if (v.get(&value)) {
-              return value;
-            }
-            else {
-              return C2Value();
-            }
         }));
 
     // convert to dBFS and add default
@@ -1009,11 +1020,14 @@
                     new C2StreamPixelAspectRatioInfo::output(0u, 1u, 1u),
                     C2_PARAMKEY_PIXEL_ASPECT_RATIO);
             addLocalParam(new C2StreamRotationInfo::output(0u, 0), C2_PARAMKEY_ROTATION);
-            addLocalParam(new C2StreamColorAspectsInfo::output(0u), C2_PARAMKEY_COLOR_ASPECTS);
+            addLocalParam(
+                    new C2StreamColorAspectsTuning::output(0u),
+                    C2_PARAMKEY_DEFAULT_COLOR_ASPECTS);
             addLocalParam<C2StreamDataSpaceInfo::output>(C2_PARAMKEY_DATA_SPACE);
             addLocalParam<C2StreamHdrStaticInfo::output>(C2_PARAMKEY_HDR_STATIC_INFO);
-            addLocalParam(new C2StreamSurfaceScalingInfo::output(0u, VIDEO_SCALING_MODE_SCALE_TO_FIT),
-                          C2_PARAMKEY_SURFACE_SCALING_MODE);
+            addLocalParam(
+                    new C2StreamSurfaceScalingInfo::output(0u, VIDEO_SCALING_MODE_SCALE_TO_FIT),
+                    C2_PARAMKEY_SURFACE_SCALING_MODE);
         } else {
             addLocalParam(new C2StreamColorAspectsInfo::input(0u), C2_PARAMKEY_COLOR_ASPECTS);
         }
@@ -1297,8 +1311,37 @@
     }
 
     { // convert color info
+        // move default color to color aspect if not read from the component
+        int32_t tmp;
+        int32_t range;
+        if (msg->findInt32("default-color-range", &range)) {
+            if (!msg->findInt32(KEY_COLOR_RANGE, &tmp)) {
+                msg->setInt32(KEY_COLOR_RANGE, range);
+            }
+            msg->removeEntryAt(msg->findEntryByName("default-color-range"));
+        }
+        int32_t transfer;
+        if (msg->findInt32("default-color-transfer", &transfer)) {
+            if (!msg->findInt32(KEY_COLOR_TRANSFER, &tmp)) {
+                msg->setInt32(KEY_COLOR_TRANSFER, transfer);
+            }
+            msg->removeEntryAt(msg->findEntryByName("default-color-transfer"));
+        }
         C2Color::primaries_t primaries;
+        if (msg->findInt32("default-color-primaries", (int32_t*)&primaries)) {
+            if (!msg->findInt32("color-primaries", &tmp)) {
+                msg->setInt32("color-primaries", primaries);
+            }
+            msg->removeEntryAt(msg->findEntryByName("default-color-primaries"));
+        }
         C2Color::matrix_t matrix;
+        if (msg->findInt32("default-color-matrix", (int32_t*)&matrix)) {
+            if (!msg->findInt32("color-matrix", &tmp)) {
+                msg->setInt32("color-matrix", matrix);
+            }
+            msg->removeEntryAt(msg->findEntryByName("default-color-matrix"));
+        }
+
         if (msg->findInt32("color-primaries", (int32_t*)&primaries)
                 && msg->findInt32("color-matrix", (int32_t*)&matrix)) {
             int32_t standard;
@@ -1390,22 +1433,22 @@
                 meta.sType1.mMinDisplayLuminance = hdr.mastering.minLuminance / 0.0001 + 0.5;
                 meta.sType1.mMaxContentLightLevel = hdr.maxCll + 0.5;
                 meta.sType1.mMaxFrameAverageLightLevel = hdr.maxFall + 0.5;
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.red.x"));
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.red.y"));
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.green.x"));
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.green.y"));
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.blue.x"));
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.blue.y"));
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.white.x"));
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.white.y"));
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.max-luminance"));
-                msg->removeEntryAt(msg->findEntryByName("smpte2086.min-luminance"));
-                msg->removeEntryAt(msg->findEntryByName("cta861.max-cll"));
-                msg->removeEntryAt(msg->findEntryByName("cta861.max-fall"));
                 msg->setBuffer(KEY_HDR_STATIC_INFO, ABuffer::CreateAsCopy(&meta, sizeof(meta)));
             } else {
                 ALOGD("found invalid HDR static metadata %s", msg->debugString(8).c_str());
             }
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.red.x"));
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.red.y"));
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.green.x"));
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.green.y"));
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.blue.x"));
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.blue.y"));
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.white.x"));
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.white.y"));
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.max-luminance"));
+            msg->removeEntryAt(msg->findEntryByName("smpte2086.min-luminance"));
+            msg->removeEntryAt(msg->findEntryByName("cta861.max-cll"));
+            msg->removeEntryAt(msg->findEntryByName("cta861.max-fall"));
         }
     }
 
@@ -1640,8 +1683,8 @@
             }
         }
     }
-    ALOGV("filtered %s to %s", params->debugString(4).c_str(),
-            filtered.debugString(4).c_str());
+    ALOGV("filter src msg %s", params->debugString(4).c_str());
+    ALOGV("filter dst params %s", filtered.debugString(4).c_str());
     return filtered;
 }
 
diff --git a/media/codec2/sfplugin/Codec2Buffer.cpp b/media/codec2/sfplugin/Codec2Buffer.cpp
index 25e7da9..fc4ee51 100644
--- a/media/codec2/sfplugin/Codec2Buffer.cpp
+++ b/media/codec2/sfplugin/Codec2Buffer.cpp
@@ -18,6 +18,7 @@
 #define LOG_TAG "Codec2Buffer"
 #include <utils/Log.h>
 
+#include <android-base/properties.h>
 #include <android/hardware/cas/native/1.0/types.h>
 #include <android/hardware/drm/1.0/types.h>
 #include <hidlmemory/FrameworkUtils.h>
@@ -211,21 +212,24 @@
      * Creates a C2GraphicView <=> MediaImage converter
      *
      * \param view C2GraphicView object
-     * \param colorFormat desired SDK color format for the MediaImage (if this is a flexible format,
-     *        an attempt is made to simply represent the graphic view as a flexible SDK format
-     *        without a memcpy)
+     * \param format buffer format
      * \param copy whether the converter is used for copy or not
      */
     GraphicView2MediaImageConverter(
-            const C2GraphicView &view, int32_t colorFormat, bool copy)
+            const C2GraphicView &view, const sp<AMessage> &format, bool copy)
         : mInitCheck(NO_INIT),
           mView(view),
           mWidth(view.width()),
           mHeight(view.height()),
-          mColorFormat(colorFormat),
           mAllocatedDepth(0),
           mBackBufferSize(0),
           mMediaImage(new ABuffer(sizeof(MediaImage2))) {
+        if (!format->findInt32(KEY_COLOR_FORMAT, &mClientColorFormat)) {
+            mClientColorFormat = COLOR_FormatYUV420Flexible;
+        }
+        if (!format->findInt32("android._color-format", &mComponentColorFormat)) {
+            mComponentColorFormat = COLOR_FormatYUV420Flexible;
+        }
         if (view.error() != C2_OK) {
             ALOGD("Converter: view.error() = %d", view.error());
             mInitCheck = BAD_VALUE;
@@ -246,68 +250,57 @@
         uint32_t stride = align(view.crop().width, 2) * divUp(layout.planes[0].allocatedDepth, 8u);
         uint32_t vStride = align(view.crop().height, 2);
 
+        bool tryWrapping = !copy;
+
         switch (layout.type) {
-            case C2PlanarLayout::TYPE_YUV:
+            case C2PlanarLayout::TYPE_YUV: {
                 mediaImage->mType = MediaImage2::MEDIA_IMAGE_TYPE_YUV;
                 if (layout.numPlanes != 3) {
                     ALOGD("Converter: %d planes for YUV layout", layout.numPlanes);
                     mInitCheck = BAD_VALUE;
                     return;
                 }
-                if (layout.planes[0].channel != C2PlaneInfo::CHANNEL_Y
-                        || layout.planes[1].channel != C2PlaneInfo::CHANNEL_CB
-                        || layout.planes[2].channel != C2PlaneInfo::CHANNEL_CR
-                        || layout.planes[0].colSampling != 1
-                        || layout.planes[0].rowSampling != 1
-                        || layout.planes[1].colSampling != 2
-                        || layout.planes[1].rowSampling != 2
-                        || layout.planes[2].colSampling != 2
-                        || layout.planes[2].rowSampling != 2) {
-                    ALOGD("Converter: not YUV420 for YUV layout");
+                C2PlaneInfo yPlane = layout.planes[C2PlanarLayout::PLANE_Y];
+                C2PlaneInfo uPlane = layout.planes[C2PlanarLayout::PLANE_U];
+                C2PlaneInfo vPlane = layout.planes[C2PlanarLayout::PLANE_V];
+                if (yPlane.channel != C2PlaneInfo::CHANNEL_Y
+                        || uPlane.channel != C2PlaneInfo::CHANNEL_CB
+                        || vPlane.channel != C2PlaneInfo::CHANNEL_CR) {
+                    ALOGD("Converter: not YUV layout");
                     mInitCheck = BAD_VALUE;
                     return;
                 }
-                switch (mColorFormat) {
-                    case COLOR_FormatYUV420Flexible:
-                        if (!copy) {
-                            // try to map directly. check if the planes are near one another
-                            const uint8_t *minPtr = mView.data()[0];
-                            const uint8_t *maxPtr = mView.data()[0];
-                            int32_t planeSize = 0;
-                            for (uint32_t i = 0; i < layout.numPlanes; ++i) {
-                                const C2PlaneInfo &plane = layout.planes[i];
-                                ssize_t minOffset = plane.minOffset(mWidth, mHeight);
-                                ssize_t maxOffset = plane.maxOffset(mWidth, mHeight);
-                                if (minPtr > mView.data()[i] + minOffset) {
-                                    minPtr = mView.data()[i] + minOffset;
-                                }
-                                if (maxPtr < mView.data()[i] + maxOffset) {
-                                    maxPtr = mView.data()[i] + maxOffset;
-                                }
-                                planeSize += std::abs(plane.rowInc) * align(mHeight, 64)
-                                        / plane.rowSampling / plane.colSampling
-                                        * divUp(mAllocatedDepth, 8u);
-                            }
-
-                            if ((maxPtr - minPtr + 1) <= planeSize) {
-                                // FIXME: this is risky as reading/writing data out of bound results
-                                //        in an undefined behavior, but gralloc does assume a
-                                //        contiguous mapping
-                                for (uint32_t i = 0; i < layout.numPlanes; ++i) {
-                                    const C2PlaneInfo &plane = layout.planes[i];
-                                    mediaImage->mPlane[i].mOffset = mView.data()[i] - minPtr;
-                                    mediaImage->mPlane[i].mColInc = plane.colInc;
-                                    mediaImage->mPlane[i].mRowInc = plane.rowInc;
-                                    mediaImage->mPlane[i].mHorizSubsampling = plane.colSampling;
-                                    mediaImage->mPlane[i].mVertSubsampling = plane.rowSampling;
-                                }
-                                mWrapped = new ABuffer(const_cast<uint8_t *>(minPtr),
-                                                       maxPtr - minPtr + 1);
-                                break;
-                            }
+                bool yuv420888 = yPlane.rowSampling == 1 && yPlane.colSampling == 1
+                        && uPlane.rowSampling == 2 && uPlane.colSampling == 2
+                        && vPlane.rowSampling == 2 && vPlane.colSampling == 2;
+                if (yuv420888) {
+                    for (uint32_t i = 0; i < 3; ++i) {
+                        const C2PlaneInfo &plane = layout.planes[i];
+                        if (plane.allocatedDepth != 8 || plane.bitDepth != 8) {
+                            yuv420888 = false;
+                            break;
                         }
-                        [[fallthrough]];
-
+                    }
+                    yuv420888 = yuv420888 && yPlane.colInc == 1 && uPlane.rowInc == vPlane.rowInc;
+                }
+                int32_t copyFormat = mClientColorFormat;
+                if (yuv420888 && mClientColorFormat == COLOR_FormatYUV420Flexible) {
+                    if (uPlane.colInc == 2 && vPlane.colInc == 2
+                            && yPlane.rowInc == uPlane.rowInc) {
+                        copyFormat = COLOR_FormatYUV420PackedSemiPlanar;
+                    } else if (uPlane.colInc == 1 && vPlane.colInc == 1
+                            && yPlane.rowInc == uPlane.rowInc * 2) {
+                        copyFormat = COLOR_FormatYUV420PackedPlanar;
+                    }
+                }
+                ALOGV("client_fmt=0x%x y:{colInc=%d rowInc=%d} u:{colInc=%d rowInc=%d} "
+                        "v:{colInc=%d rowInc=%d}",
+                        mClientColorFormat,
+                        yPlane.colInc, yPlane.rowInc,
+                        uPlane.colInc, uPlane.rowInc,
+                        vPlane.colInc, vPlane.rowInc);
+                switch (copyFormat) {
+                    case COLOR_FormatYUV420Flexible:
                     case COLOR_FormatYUV420Planar:
                     case COLOR_FormatYUV420PackedPlanar:
                         mediaImage->mPlane[mediaImage->Y].mOffset = 0;
@@ -327,6 +320,13 @@
                         mediaImage->mPlane[mediaImage->V].mRowInc = stride / 2;
                         mediaImage->mPlane[mediaImage->V].mHorizSubsampling = 2;
                         mediaImage->mPlane[mediaImage->V].mVertSubsampling = 2;
+
+                        if (tryWrapping && mClientColorFormat != COLOR_FormatYUV420Flexible) {
+                            tryWrapping = yuv420888 && uPlane.colInc == 1 && vPlane.colInc == 1
+                                    && yPlane.rowInc == uPlane.rowInc * 2
+                                    && view.data()[0] < view.data()[1]
+                                    && view.data()[1] < view.data()[2];
+                        }
                         break;
 
                     case COLOR_FormatYUV420SemiPlanar:
@@ -348,64 +348,165 @@
                         mediaImage->mPlane[mediaImage->V].mRowInc = stride;
                         mediaImage->mPlane[mediaImage->V].mHorizSubsampling = 2;
                         mediaImage->mPlane[mediaImage->V].mVertSubsampling = 2;
+
+                        if (tryWrapping && mClientColorFormat != COLOR_FormatYUV420Flexible) {
+                            tryWrapping = yuv420888 && uPlane.colInc == 2 && vPlane.colInc == 2
+                                    && yPlane.rowInc == uPlane.rowInc
+                                    && view.data()[0] < view.data()[1]
+                                    && view.data()[1] < view.data()[2];
+                        }
                         break;
 
-                    default:
-                        ALOGD("Converter: incompactible color format (%d) for YUV layout", mColorFormat);
-                        mInitCheck = BAD_VALUE;
-                        return;
+                    case COLOR_FormatYUVP010:
+                        mediaImage->mPlane[mediaImage->Y].mOffset = 0;
+                        mediaImage->mPlane[mediaImage->Y].mColInc = 2;
+                        mediaImage->mPlane[mediaImage->Y].mRowInc = stride * 2;
+                        mediaImage->mPlane[mediaImage->Y].mHorizSubsampling = 1;
+                        mediaImage->mPlane[mediaImage->Y].mVertSubsampling = 1;
+
+                        mediaImage->mPlane[mediaImage->U].mOffset = stride * vStride * 2;
+                        mediaImage->mPlane[mediaImage->U].mColInc = 4;
+                        mediaImage->mPlane[mediaImage->U].mRowInc = stride * 2;
+                        mediaImage->mPlane[mediaImage->U].mHorizSubsampling = 2;
+                        mediaImage->mPlane[mediaImage->U].mVertSubsampling = 2;
+
+                        mediaImage->mPlane[mediaImage->V].mOffset = stride * vStride * 2 + 2;
+                        mediaImage->mPlane[mediaImage->V].mColInc = 4;
+                        mediaImage->mPlane[mediaImage->V].mRowInc = stride * 2;
+                        mediaImage->mPlane[mediaImage->V].mHorizSubsampling = 2;
+                        mediaImage->mPlane[mediaImage->V].mVertSubsampling = 2;
+                        if (tryWrapping) {
+                            tryWrapping = yPlane.allocatedDepth == 16
+                                    && uPlane.allocatedDepth == 16
+                                    && vPlane.allocatedDepth == 16
+                                    && yPlane.bitDepth == 10
+                                    && uPlane.bitDepth == 10
+                                    && vPlane.bitDepth == 10
+                                    && yPlane.rightShift == 6
+                                    && uPlane.rightShift == 6
+                                    && vPlane.rightShift == 6
+                                    && yPlane.rowSampling == 1 && yPlane.colSampling == 1
+                                    && uPlane.rowSampling == 2 && uPlane.colSampling == 2
+                                    && vPlane.rowSampling == 2 && vPlane.colSampling == 2
+                                    && yPlane.colInc == 2
+                                    && uPlane.colInc == 4
+                                    && vPlane.colInc == 4
+                                    && yPlane.rowInc == uPlane.rowInc
+                                    && yPlane.rowInc == vPlane.rowInc;
+                        }
+                        break;
+
+                    default: {
+                        // default to fully planar format --- this will be overridden if wrapping
+                        // TODO: keep interleaved format
+                        int32_t colInc = divUp(mAllocatedDepth, 8u);
+                        int32_t rowInc = stride * colInc / yPlane.colSampling;
+                        mediaImage->mPlane[mediaImage->Y].mOffset = 0;
+                        mediaImage->mPlane[mediaImage->Y].mColInc = colInc;
+                        mediaImage->mPlane[mediaImage->Y].mRowInc = rowInc;
+                        mediaImage->mPlane[mediaImage->Y].mHorizSubsampling = yPlane.colSampling;
+                        mediaImage->mPlane[mediaImage->Y].mVertSubsampling = yPlane.rowSampling;
+                        int32_t offset = rowInc * vStride / yPlane.rowSampling;
+
+                        rowInc = stride * colInc / uPlane.colSampling;
+                        mediaImage->mPlane[mediaImage->U].mOffset = offset;
+                        mediaImage->mPlane[mediaImage->U].mColInc = colInc;
+                        mediaImage->mPlane[mediaImage->U].mRowInc = rowInc;
+                        mediaImage->mPlane[mediaImage->U].mHorizSubsampling = uPlane.colSampling;
+                        mediaImage->mPlane[mediaImage->U].mVertSubsampling = uPlane.rowSampling;
+                        offset += rowInc * vStride / uPlane.rowSampling;
+
+                        rowInc = stride * colInc / vPlane.colSampling;
+                        mediaImage->mPlane[mediaImage->V].mOffset = offset;
+                        mediaImage->mPlane[mediaImage->V].mColInc = colInc;
+                        mediaImage->mPlane[mediaImage->V].mRowInc = rowInc;
+                        mediaImage->mPlane[mediaImage->V].mHorizSubsampling = vPlane.colSampling;
+                        mediaImage->mPlane[mediaImage->V].mVertSubsampling = vPlane.rowSampling;
+                        break;
+                    }
                 }
                 break;
+            }
+
             case C2PlanarLayout::TYPE_YUVA:
-                mediaImage->mType = MediaImage2::MEDIA_IMAGE_TYPE_YUVA;
-                // We don't have an SDK YUVA format
-                ALOGD("Converter: incompactible color format (%d) for YUVA layout", mColorFormat);
-                mInitCheck = BAD_VALUE;
+                ALOGD("Converter: unrecognized color format "
+                        "(client %d component %d) for YUVA layout",
+                        mClientColorFormat, mComponentColorFormat);
+                mInitCheck = NO_INIT;
                 return;
             case C2PlanarLayout::TYPE_RGB:
-                mediaImage->mType = MediaImage2::MEDIA_IMAGE_TYPE_RGB;
-                switch (mColorFormat) {
-                    // TODO media image
-                    case COLOR_FormatRGBFlexible:
-                    case COLOR_Format24bitBGR888:
-                    case COLOR_Format24bitRGB888:
-                        break;
-                    default:
-                        ALOGD("Converter: incompactible color format (%d) for RGB layout", mColorFormat);
-                        mInitCheck = BAD_VALUE;
-                        return;
-                }
-                if (layout.numPlanes != 3) {
-                    ALOGD("Converter: %d planes for RGB layout", layout.numPlanes);
-                    mInitCheck = BAD_VALUE;
-                    return;
-                }
-                break;
+                ALOGD("Converter: unrecognized color format "
+                        "(client %d component %d) for RGB layout",
+                        mClientColorFormat, mComponentColorFormat);
+                mInitCheck = NO_INIT;
+                // TODO: support MediaImage layout
+                return;
             case C2PlanarLayout::TYPE_RGBA:
-                mediaImage->mType = MediaImage2::MEDIA_IMAGE_TYPE_RGBA;
-                switch (mColorFormat) {
-                    // TODO media image
-                    case COLOR_FormatRGBAFlexible:
-                    case COLOR_Format32bitABGR8888:
-                    case COLOR_Format32bitARGB8888:
-                    case COLOR_Format32bitBGRA8888:
-                        break;
-                    default:
-                        ALOGD("Incompactible color format (%d) for RGBA layout", mColorFormat);
-                        mInitCheck = BAD_VALUE;
-                        return;
-                }
-                if (layout.numPlanes != 4) {
-                    ALOGD("Converter: %d planes for RGBA layout", layout.numPlanes);
-                    mInitCheck = BAD_VALUE;
-                    return;
-                }
-                break;
+                ALOGD("Converter: unrecognized color format "
+                        "(client %d component %d) for RGBA layout",
+                        mClientColorFormat, mComponentColorFormat);
+                mInitCheck = NO_INIT;
+                // TODO: support MediaImage layout
+                return;
             default:
                 mediaImage->mType = MediaImage2::MEDIA_IMAGE_TYPE_UNKNOWN;
-                ALOGD("Unknown layout");
-                mInitCheck = BAD_VALUE;
-                return;
+                if (layout.numPlanes == 1) {
+                    const C2PlaneInfo &plane = layout.planes[0];
+                    if (plane.colInc < 0 || plane.rowInc < 0) {
+                        // Copy-only if we have negative colInc/rowInc
+                        tryWrapping = false;
+                    }
+                    mediaImage->mPlane[0].mOffset = 0;
+                    mediaImage->mPlane[0].mColInc = std::abs(plane.colInc);
+                    mediaImage->mPlane[0].mRowInc = std::abs(plane.rowInc);
+                    mediaImage->mPlane[0].mHorizSubsampling = plane.colSampling;
+                    mediaImage->mPlane[0].mVertSubsampling = plane.rowSampling;
+                } else {
+                    ALOGD("Converter: unrecognized layout: color format (client %d component %d)",
+                            mClientColorFormat, mComponentColorFormat);
+                    mInitCheck = NO_INIT;
+                    return;
+                }
+                break;
+        }
+        if (tryWrapping) {
+            // try to map directly. check if the planes are near one another
+            const uint8_t *minPtr = mView.data()[0];
+            const uint8_t *maxPtr = mView.data()[0];
+            int32_t planeSize = 0;
+            for (uint32_t i = 0; i < layout.numPlanes; ++i) {
+                const C2PlaneInfo &plane = layout.planes[i];
+                int64_t planeStride = std::abs(plane.rowInc / plane.colInc);
+                ssize_t minOffset = plane.minOffset(
+                        mWidth / plane.colSampling, mHeight / plane.rowSampling);
+                ssize_t maxOffset = plane.maxOffset(
+                        mWidth / plane.colSampling, mHeight / plane.rowSampling);
+                if (minPtr > mView.data()[i] + minOffset) {
+                    minPtr = mView.data()[i] + minOffset;
+                }
+                if (maxPtr < mView.data()[i] + maxOffset) {
+                    maxPtr = mView.data()[i] + maxOffset;
+                }
+                planeSize += planeStride * divUp(mAllocatedDepth, 8u)
+                        * align(mHeight, 64) / plane.rowSampling;
+            }
+
+            if ((maxPtr - minPtr + 1) <= planeSize) {
+                // FIXME: this is risky as reading/writing data out of bound results
+                //        in an undefined behavior, but gralloc does assume a
+                //        contiguous mapping
+                for (uint32_t i = 0; i < layout.numPlanes; ++i) {
+                    const C2PlaneInfo &plane = layout.planes[i];
+                    mediaImage->mPlane[i].mOffset = mView.data()[i] - minPtr;
+                    mediaImage->mPlane[i].mColInc = plane.colInc;
+                    mediaImage->mPlane[i].mRowInc = plane.rowInc;
+                    mediaImage->mPlane[i].mHorizSubsampling = plane.colSampling;
+                    mediaImage->mPlane[i].mVertSubsampling = plane.rowSampling;
+                }
+                mWrapped = new ABuffer(const_cast<uint8_t *>(minPtr),
+                                       maxPtr - minPtr + 1);
+                ALOGV("Converter: wrapped (capacity=%zu)", mWrapped->capacity());
+            }
         }
         mediaImage->mNumPlanes = layout.numPlanes;
         mediaImage->mWidth = view.crop().width;
@@ -428,12 +529,12 @@
                 return;
             }
             if (plane.allocatedDepth != mAllocatedDepth || plane.bitDepth != bitDepth) {
-                ALOGV("different allocatedDepth/bitDepth per plane unsupported");
+                ALOGD("different allocatedDepth/bitDepth per plane unsupported");
                 mInitCheck = BAD_VALUE;
                 return;
             }
             bufferSize += stride * vStride
-                    / plane.rowSampling / plane.colSampling;
+                    / plane.rowSampling / plane.colSampling * divUp(mAllocatedDepth, 8u);
         }
 
         mBackBufferSize = bufferSize;
@@ -488,7 +589,8 @@
     const C2GraphicView mView;
     uint32_t mWidth;
     uint32_t mHeight;
-    int32_t mColorFormat;  ///< SDK color format for MediaImage
+    int32_t mClientColorFormat;  ///< SDK color format for MediaImage
+    int32_t mComponentColorFormat;  ///< SDK color format from component
     sp<ABuffer> mWrapped;  ///< wrapped buffer (if we can map C2Buffer to an ABuffer)
     uint32_t mAllocatedDepth;
     uint32_t mBackBufferSize;
@@ -517,10 +619,7 @@
         return nullptr;
     }
 
-    int32_t colorFormat = COLOR_FormatYUV420Flexible;
-    (void)format->findInt32("color-format", &colorFormat);
-
-    GraphicView2MediaImageConverter converter(view, colorFormat, false /* copy */);
+    GraphicView2MediaImageConverter converter(view, format, false /* copy */);
     if (converter.initCheck() != OK) {
         ALOGD("Converter init failed: %d", converter.initCheck());
         return nullptr;
@@ -578,7 +677,23 @@
 }
 
 std::shared_ptr<C2Buffer> GraphicMetadataBuffer::asC2Buffer() {
-#ifndef __LP64__
+#ifdef __LP64__
+    static std::once_flag s_checkOnce;
+    static bool s_64bitonly {false};
+    std::call_once(s_checkOnce, [&](){
+        const std::string abi32list =
+        ::android::base::GetProperty("ro.product.cpu.abilist32", "");
+        if (abi32list.empty()) {
+            s_64bitonly = true;
+        }
+    });
+
+    if (!s_64bitonly) {
+        ALOGE("GraphicMetadataBuffer does not work in 32+64 system if compiled as 64-bit object");
+        return nullptr;
+    }
+#endif
+
     VideoNativeMetadata *meta = (VideoNativeMetadata *)base();
     ANativeWindowBuffer *buffer = (ANativeWindowBuffer *)meta->pBuffer;
     if (buffer == nullptr) {
@@ -611,10 +726,6 @@
     }
     return C2Buffer::CreateGraphicBuffer(
             block->share(C2Rect(buffer->width, buffer->height), C2Fence()));
-#else
-    ALOGE("GraphicMetadataBuffer does not work on 64-bit arch");
-    return nullptr;
-#endif
 }
 
 // ConstGraphicBlockBuffer
@@ -634,10 +745,7 @@
             buffer->data().graphicBlocks()[0].map().get()));
     std::unique_ptr<const C2GraphicView> holder;
 
-    int32_t colorFormat = COLOR_FormatYUV420Flexible;
-    (void)format->findInt32("color-format", &colorFormat);
-
-    GraphicView2MediaImageConverter converter(*view, colorFormat, false /* copy */);
+    GraphicView2MediaImageConverter converter(*view, format, false /* copy */);
     if (converter.initCheck() != OK) {
         ALOGD("Converter init failed: %d", converter.initCheck());
         return nullptr;
@@ -729,12 +837,11 @@
         return false;
     }
 
-    int32_t colorFormat = COLOR_FormatYUV420Flexible;
-    // FIXME: format() is not const, but we cannot change it, so do a const cast here
-    const_cast<ConstGraphicBlockBuffer *>(this)->format()->findInt32("color-format", &colorFormat);
-
     GraphicView2MediaImageConverter converter(
-            buffer->data().graphicBlocks()[0].map().get(), colorFormat, true /* copy */);
+            buffer->data().graphicBlocks()[0].map().get(),
+            // FIXME: format() is not const, but we cannot change it, so do a const cast here
+            const_cast<ConstGraphicBlockBuffer *>(this)->format(),
+            true /* copy */);
     if (converter.initCheck() != OK) {
         ALOGD("ConstGraphicBlockBuffer::canCopy: converter init failed: %d", converter.initCheck());
         return false;
@@ -752,11 +859,9 @@
         setRange(0, 0);
         return true;
     }
-    int32_t colorFormat = COLOR_FormatYUV420Flexible;
-    format()->findInt32("color-format", &colorFormat);
 
     GraphicView2MediaImageConverter converter(
-            buffer->data().graphicBlocks()[0].map().get(), colorFormat, true /* copy */);
+            buffer->data().graphicBlocks()[0].map().get(), format(), true /* copy */);
     if (converter.initCheck() != OK) {
         ALOGD("ConstGraphicBlockBuffer::copy: converter init failed: %d", converter.initCheck());
         return false;
diff --git a/media/codec2/sfplugin/Codec2InfoBuilder.cpp b/media/codec2/sfplugin/Codec2InfoBuilder.cpp
index b112249..a26f89e 100644
--- a/media/codec2/sfplugin/Codec2InfoBuilder.cpp
+++ b/media/codec2/sfplugin/Codec2InfoBuilder.cpp
@@ -103,11 +103,16 @@
     c2_status_t err1 = intf->querySupportedParams(&paramDescs);
     if (err1 == C2_OK) {
         for (const std::shared_ptr<C2ParamDescriptor> &desc : paramDescs) {
-            switch ((uint32_t)desc->index()) {
-            case C2StreamHdr10PlusInfo::output::PARAM_TYPE:
+            C2Param::Type type = desc->index();
+            // only consider supported parameters on raw ports
+            if (!(encoder ? type.forInput() : type.forOutput())) {
+                continue;
+            }
+            switch (type.coreIndex()) {
+            case C2StreamHdr10PlusInfo::CORE_INDEX:
                 supportsHdr10Plus = true;
                 break;
-            case C2StreamHdrStaticInfo::output::PARAM_TYPE:
+            case C2StreamHdrStaticInfo::CORE_INDEX:
                 supportsHdr = true;
                 break;
             default:
diff --git a/media/codec2/sfplugin/FrameReassembler.cpp b/media/codec2/sfplugin/FrameReassembler.cpp
new file mode 100644
index 0000000..f8e6937
--- /dev/null
+++ b/media/codec2/sfplugin/FrameReassembler.cpp
@@ -0,0 +1,226 @@
+/*
+ * Copyright 2019 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 "FrameReassembler"
+
+#include <log/log.h>
+
+#include <media/stagefright/foundation/AMessage.h>
+
+#include "FrameReassembler.h"
+
+namespace android {
+
+static constexpr uint64_t kToleranceUs = 1000;  // 1ms
+
+FrameReassembler::FrameReassembler()
+    : mUsage{0, 0},
+      mSampleRate(0u),
+      mChannelCount(0u),
+      mEncoding(C2Config::PCM_16),
+      mCurrentOrdinal({0, 0, 0}) {
+}
+
+void FrameReassembler::init(
+        const std::shared_ptr<C2BlockPool> &pool,
+        C2MemoryUsage usage,
+        uint32_t frameSize,
+        uint32_t sampleRate,
+        uint32_t channelCount,
+        C2Config::pcm_encoding_t encoding) {
+    mBlockPool = pool;
+    mUsage = usage;
+    mFrameSize = frameSize;
+    mSampleRate = sampleRate;
+    mChannelCount = channelCount;
+    mEncoding = encoding;
+}
+
+void FrameReassembler::updateFrameSize(uint32_t frameSize) {
+    finishCurrentBlock(&mPendingWork);
+    mFrameSize = frameSize;
+}
+
+void FrameReassembler::updateSampleRate(uint32_t sampleRate) {
+    finishCurrentBlock(&mPendingWork);
+    mSampleRate = sampleRate;
+}
+
+void FrameReassembler::updateChannelCount(uint32_t channelCount) {
+    finishCurrentBlock(&mPendingWork);
+    mChannelCount = channelCount;
+}
+
+void FrameReassembler::updatePcmEncoding(C2Config::pcm_encoding_t encoding) {
+    finishCurrentBlock(&mPendingWork);
+    mEncoding = encoding;
+}
+
+void FrameReassembler::reset() {
+    flush();
+    mCurrentOrdinal = {0, 0, 0};
+    mBlockPool.reset();
+    mFrameSize.reset();
+    mSampleRate = 0u;
+    mChannelCount = 0u;
+    mEncoding = C2Config::PCM_16;
+}
+
+FrameReassembler::operator bool() const {
+    return mFrameSize.has_value();
+}
+
+c2_status_t FrameReassembler::process(
+        const sp<MediaCodecBuffer> &buffer,
+        std::list<std::unique_ptr<C2Work>> *items) {
+    int64_t timeUs;
+    if (buffer->size() == 0u
+            || !buffer->meta()->findInt64("timeUs", &timeUs)) {
+        return C2_BAD_VALUE;
+    }
+
+    items->splice(items->end(), mPendingWork);
+
+    // Fill mCurrentBlock
+    if (mCurrentBlock) {
+        // First check the timestamp
+        c2_cntr64_t endTimestampUs = mCurrentOrdinal.timestamp;
+        endTimestampUs += bytesToSamples(mWriteView->size()) * 1000000 / mSampleRate;
+        if (timeUs < endTimestampUs.peek()) {
+            uint64_t diffUs = (endTimestampUs - timeUs).peeku();
+            if (diffUs > kToleranceUs) {
+                // The timestamp is going back in time in large amount.
+                // TODO: b/145702136
+                ALOGW("timestamp going back in time! from %lld to %lld",
+                        endTimestampUs.peekll(), (long long)timeUs);
+            }
+        } else {  // timeUs >= endTimestampUs.peek()
+            uint64_t diffUs = (timeUs - endTimestampUs).peeku();
+            if (diffUs > kToleranceUs) {
+                // The timestamp is going forward; add silence as necessary.
+                size_t gapSamples = usToSamples(diffUs);
+                size_t remainingSamples =
+                    (mWriteView->capacity() - mWriteView->size())
+                    / mChannelCount / bytesPerSample();
+                if (gapSamples < remainingSamples) {
+                    size_t gapBytes = gapSamples * mChannelCount * bytesPerSample();
+                    memset(mWriteView->base() + mWriteView->size(), 0u, gapBytes);
+                    mWriteView->setSize(mWriteView->size() + gapBytes);
+                } else {
+                    finishCurrentBlock(items);
+                }
+            }
+        }
+    }
+
+    if (mCurrentBlock) {
+        // Append the data at the end of the current block
+        size_t copySize = std::min(
+                buffer->size(),
+                size_t(mWriteView->capacity() - mWriteView->size()));
+        memcpy(mWriteView->base() + mWriteView->size(), buffer->data(), copySize);
+        buffer->setRange(buffer->offset() + copySize, buffer->size() - copySize);
+        mWriteView->setSize(mWriteView->size() + copySize);
+        if (mWriteView->size() == mWriteView->capacity()) {
+            finishCurrentBlock(items);
+        }
+        timeUs += bytesToSamples(copySize) * 1000000 / mSampleRate;
+    }
+
+    if (buffer->size() > 0) {
+        mCurrentOrdinal.timestamp = timeUs;
+    }
+
+    size_t frameSizeBytes = mFrameSize.value() * mChannelCount * bytesPerSample();
+    while (buffer->size() > 0) {
+        LOG_ALWAYS_FATAL_IF(
+                mCurrentBlock,
+                "There's remaining data but the pending block is not filled & finished");
+        std::unique_ptr<C2Work> work(new C2Work);
+        c2_status_t err = mBlockPool->fetchLinearBlock(frameSizeBytes, mUsage, &mCurrentBlock);
+        if (err != C2_OK) {
+            return err;
+        }
+        size_t copySize = std::min(buffer->size(), frameSizeBytes);
+        mWriteView = mCurrentBlock->map().get();
+        if (mWriteView->error() != C2_OK) {
+            return mWriteView->error();
+        }
+        ALOGV("buffer={offset=%zu size=%zu) copySize=%zu",
+                buffer->offset(), buffer->size(), copySize);
+        memcpy(mWriteView->base(), buffer->data(), copySize);
+        mWriteView->setOffset(0u);
+        mWriteView->setSize(copySize);
+        buffer->setRange(buffer->offset() + copySize, buffer->size() - copySize);
+        if (copySize == frameSizeBytes) {
+            finishCurrentBlock(items);
+        }
+    }
+
+    int32_t eos = 0;
+    if (buffer->meta()->findInt32("eos", &eos) && eos) {
+        finishCurrentBlock(items);
+    }
+
+    return C2_OK;
+}
+
+void FrameReassembler::flush() {
+    mPendingWork.clear();
+    mWriteView.reset();
+    mCurrentBlock.reset();
+}
+
+uint64_t FrameReassembler::bytesToSamples(size_t numBytes) const {
+    return numBytes / mChannelCount / bytesPerSample();
+}
+
+size_t FrameReassembler::usToSamples(uint64_t us) const {
+    return (us * mChannelCount * mSampleRate / 1000000);
+}
+
+uint32_t FrameReassembler::bytesPerSample() const {
+    return (mEncoding == C2Config::PCM_8) ? 1
+         : (mEncoding == C2Config::PCM_16) ? 2
+         : (mEncoding == C2Config::PCM_FLOAT) ? 4 : 0;
+}
+
+void FrameReassembler::finishCurrentBlock(std::list<std::unique_ptr<C2Work>> *items) {
+    if (!mCurrentBlock) {
+        // No-op
+        return;
+    }
+    if (mWriteView->size() < mWriteView->capacity()) {
+        memset(mWriteView->base() + mWriteView->size(), 0u,
+                mWriteView->capacity() - mWriteView->size());
+        mWriteView->setSize(mWriteView->capacity());
+    }
+    std::unique_ptr<C2Work> work{std::make_unique<C2Work>()};
+    work->input.ordinal = mCurrentOrdinal;
+    work->input.buffers.push_back(C2Buffer::CreateLinearBuffer(
+            mCurrentBlock->share(0, mCurrentBlock->capacity(), C2Fence())));
+    work->worklets.clear();
+    work->worklets.emplace_back(new C2Worklet);
+    items->push_back(std::move(work));
+
+    ++mCurrentOrdinal.frameIndex;
+    mCurrentOrdinal.timestamp += mFrameSize.value() * 1000000 / mSampleRate;
+    mCurrentBlock.reset();
+    mWriteView.reset();
+}
+
+}  // namespace android
diff --git a/media/codec2/sfplugin/FrameReassembler.h b/media/codec2/sfplugin/FrameReassembler.h
new file mode 100644
index 0000000..17ac06d
--- /dev/null
+++ b/media/codec2/sfplugin/FrameReassembler.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2019 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 FRAME_REASSEMBLER_H_
+#define FRAME_REASSEMBLER_H_
+
+#include <set>
+#include <memory>
+
+#include <media/MediaCodecBuffer.h>
+
+#include <C2Config.h>
+#include <C2Work.h>
+
+namespace android {
+
+class FrameReassembler {
+public:
+    FrameReassembler();
+
+    void init(
+            const std::shared_ptr<C2BlockPool> &pool,
+            C2MemoryUsage usage,
+            uint32_t frameSize,
+            uint32_t sampleRate,
+            uint32_t channelCount,
+            C2Config::pcm_encoding_t encoding);
+    void updateFrameSize(uint32_t frameSize);
+    void updateSampleRate(uint32_t sampleRate);
+    void updateChannelCount(uint32_t channelCount);
+    void updatePcmEncoding(C2Config::pcm_encoding_t encoding);
+    void reset();
+    void flush();
+
+    explicit operator bool() const;
+
+    c2_status_t process(
+            const sp<MediaCodecBuffer> &buffer,
+            std::list<std::unique_ptr<C2Work>> *items);
+
+private:
+    std::shared_ptr<C2BlockPool> mBlockPool;
+    C2MemoryUsage mUsage;
+    std::optional<uint32_t> mFrameSize;
+    uint32_t mSampleRate;
+    uint32_t mChannelCount;
+    C2Config::pcm_encoding_t mEncoding;
+    std::list<std::unique_ptr<C2Work>> mPendingWork;
+    C2WorkOrdinalStruct mCurrentOrdinal;
+    std::shared_ptr<C2LinearBlock> mCurrentBlock;
+    std::optional<C2WriteView> mWriteView;
+
+    uint64_t bytesToSamples(size_t numBytes) const;
+    size_t usToSamples(uint64_t us) const;
+    uint32_t bytesPerSample() const;
+
+    void finishCurrentBlock(std::list<std::unique_ptr<C2Work>> *items);
+};
+
+}  // namespace android
+
+#endif  // FRAME_REASSEMBLER_H_
diff --git a/media/codec2/sfplugin/tests/Android.bp b/media/codec2/sfplugin/tests/Android.bp
index 8d1a9c3..f9c7969 100644
--- a/media/codec2/sfplugin/tests/Android.bp
+++ b/media/codec2/sfplugin/tests/Android.bp
@@ -1,9 +1,19 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "ccodec_unit_test",
 
     srcs: [
         "CCodecBuffers_test.cpp",
         "CCodecConfig_test.cpp",
+        "FrameReassembler_test.cpp",
         "ReflectedParamUpdater_test.cpp",
     ],
 
diff --git a/media/codec2/sfplugin/tests/CCodecBuffers_test.cpp b/media/codec2/sfplugin/tests/CCodecBuffers_test.cpp
index 5bee605..66b7622 100644
--- a/media/codec2/sfplugin/tests/CCodecBuffers_test.cpp
+++ b/media/codec2/sfplugin/tests/CCodecBuffers_test.cpp
@@ -18,22 +18,32 @@
 
 #include <gtest/gtest.h>
 
+#include <codec2/hidl/client.h>
 #include <media/stagefright/MediaCodecConstants.h>
 
+#include <C2BlockInternal.h>
 #include <C2PlatformSupport.h>
+#include <Codec2Mapper.h>
 
 namespace android {
 
+static std::shared_ptr<RawGraphicOutputBuffers> GetRawGraphicOutputBuffers(
+        int32_t width, int32_t height) {
+    std::shared_ptr<RawGraphicOutputBuffers> buffers =
+        std::make_shared<RawGraphicOutputBuffers>("test");
+    sp<AMessage> format{new AMessage};
+    format->setInt32(KEY_WIDTH, width);
+    format->setInt32(KEY_HEIGHT, height);
+    buffers->setFormat(format);
+    return buffers;
+}
+
 TEST(RawGraphicOutputBuffersTest, ChangeNumSlots) {
     constexpr int32_t kWidth = 3840;
     constexpr int32_t kHeight = 2160;
 
     std::shared_ptr<RawGraphicOutputBuffers> buffers =
-        std::make_shared<RawGraphicOutputBuffers>("test");
-    sp<AMessage> format{new AMessage};
-    format->setInt32("width", kWidth);
-    format->setInt32("height", kHeight);
-    buffers->setFormat(format);
+        GetRawGraphicOutputBuffers(kWidth, kHeight);
 
     std::shared_ptr<C2BlockPool> pool;
     ASSERT_EQ(OK, GetCodec2BlockPool(C2BlockPool::BASIC_GRAPHIC, nullptr, &pool));
@@ -96,4 +106,746 @@
     }
 }
 
+TEST(RawGraphicOutputBuffersTest, FlexYuvColorFormat) {
+    constexpr int32_t kWidth = 320;
+    constexpr int32_t kHeight = 240;
+
+    std::vector<uint32_t> flexPixelFormats({HAL_PIXEL_FORMAT_YCbCr_420_888});
+    std::shared_ptr<Codec2Client> client = Codec2Client::CreateFromService("default");
+    if (client) {
+        // Query vendor format for Flexible YUV
+        std::vector<std::unique_ptr<C2Param>> heapParams;
+        C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
+        if (client->query(
+                    {},
+                    {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
+                    C2_MAY_BLOCK,
+                    &heapParams) == C2_OK
+                && heapParams.size() == 1u) {
+            pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
+                    heapParams[0].get());
+        } else {
+            pixelFormatInfo = nullptr;
+        }
+        if (pixelFormatInfo && *pixelFormatInfo) {
+            for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
+                const C2FlexiblePixelFormatDescriptorStruct &desc =
+                    pixelFormatInfo->m.values[i];
+                if (desc.bitDepth != 8
+                        || desc.subsampling != C2Color::YUV_420
+                        // TODO(b/180076105): some devices report wrong layouts
+                        // || desc.layout == C2Color::INTERLEAVED_PACKED
+                        // || desc.layout == C2Color::INTERLEAVED_ALIGNED
+                        || desc.layout == C2Color::UNKNOWN_LAYOUT) {
+                    continue;
+                }
+                flexPixelFormats.push_back(desc.pixelFormat);
+            }
+        }
+    }
+
+    for (uint32_t pixelFormat : flexPixelFormats) {
+        std::shared_ptr<RawGraphicOutputBuffers> buffers =
+            std::make_shared<RawGraphicOutputBuffers>(
+                    AStringPrintf("test pixel format 0x%x", pixelFormat).c_str());
+
+        sp<AMessage> format{new AMessage};
+        format->setInt32(KEY_WIDTH, kWidth);
+        format->setInt32(KEY_HEIGHT, kHeight);
+        format->setInt32(KEY_COLOR_FORMAT, COLOR_FormatYUV420Flexible);
+        int32_t fwkPixelFormat = 0;
+        if (C2Mapper::mapPixelFormatCodecToFramework(pixelFormat, &fwkPixelFormat)) {
+            format->setInt32("android._color-format", fwkPixelFormat);
+        }
+        buffers->setFormat(format);
+
+        std::shared_ptr<C2BlockPool> pool;
+        ASSERT_EQ(OK, GetCodec2BlockPool(C2BlockPool::BASIC_GRAPHIC, nullptr, &pool));
+
+        std::shared_ptr<C2GraphicBlock> block;
+        ASSERT_EQ(OK, pool->fetchGraphicBlock(
+                kWidth, kHeight, pixelFormat,
+                C2MemoryUsage{C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE}, &block));
+
+        {
+            C2GraphicView view = block->map().get();
+            C2PlanarLayout layout = view.layout();
+
+            // Verify the block is in YUV420 format
+            ASSERT_EQ(C2PlanarLayout::TYPE_YUV, layout.type);
+            ASSERT_EQ(3u, layout.numPlanes);
+            const C2PlaneInfo& yPlane = layout.planes[C2PlanarLayout::PLANE_Y];
+            const C2PlaneInfo& uPlane = layout.planes[C2PlanarLayout::PLANE_U];
+            const C2PlaneInfo& vPlane = layout.planes[C2PlanarLayout::PLANE_V];
+
+            // Y plane
+            ASSERT_EQ(1u, yPlane.colSampling);
+            ASSERT_EQ(1u, yPlane.rowSampling);
+            ASSERT_EQ(8u, yPlane.allocatedDepth);
+            ASSERT_EQ(8u, yPlane.bitDepth);
+            ASSERT_EQ(0u, yPlane.rightShift);
+
+            // U plane
+            ASSERT_EQ(2u, uPlane.colSampling);
+            ASSERT_EQ(2u, uPlane.rowSampling);
+            ASSERT_EQ(8u, uPlane.allocatedDepth);
+            ASSERT_EQ(8u, uPlane.bitDepth);
+            ASSERT_EQ(0u, uPlane.rightShift);
+
+            // V plane
+            ASSERT_EQ(2u, vPlane.colSampling);
+            ASSERT_EQ(2u, vPlane.rowSampling);
+            ASSERT_EQ(8u, vPlane.allocatedDepth);
+            ASSERT_EQ(8u, vPlane.bitDepth);
+            ASSERT_EQ(0u, vPlane.rightShift);
+
+            uint8_t *yRowPtr = view.data()[C2PlanarLayout::PLANE_Y];
+            uint8_t *uRowPtr = view.data()[C2PlanarLayout::PLANE_U];
+            uint8_t *vRowPtr = view.data()[C2PlanarLayout::PLANE_V];
+            for (int32_t row = 0; row < kHeight; ++row) {
+                uint8_t *yPtr = yRowPtr;
+                uint8_t *uPtr = uRowPtr;
+                uint8_t *vPtr = vRowPtr;
+                for (int32_t col = 0; col < kWidth; ++col) {
+                    *yPtr = ((row + col) & 0xFF);
+                    yPtr += yPlane.colInc;
+
+                    if (row < kHeight / 2 && col < kWidth / 2) {
+                        *uPtr = ((row + col + 1) & 0xFF);
+                        *vPtr = ((row + col + 2) & 0xFF);
+                        uPtr += uPlane.colInc;
+                        vPtr += vPlane.colInc;
+                    }
+                }
+                yRowPtr += yPlane.rowInc;
+                if (row < kHeight / 2) {
+                    uRowPtr += uPlane.rowInc;
+                    vRowPtr += vPlane.rowInc;
+                }
+            }
+        }
+
+        std::shared_ptr<C2Buffer> c2Buffer = C2Buffer::CreateGraphicBuffer(block->share(
+                block->crop(), C2Fence{}));
+        size_t index;
+        sp<MediaCodecBuffer> clientBuffer;
+        ASSERT_EQ(OK, buffers->registerBuffer(c2Buffer, &index, &clientBuffer));
+        ASSERT_NE(nullptr, clientBuffer);
+        sp<ABuffer> imageData;
+        ASSERT_TRUE(clientBuffer->format()->findBuffer("image-data", &imageData));
+        MediaImage2 *img = (MediaImage2 *)imageData->data();
+        ASSERT_EQ(MediaImage2::MEDIA_IMAGE_TYPE_YUV, img->mType);
+        ASSERT_EQ(3u, img->mNumPlanes);
+        ASSERT_EQ(kWidth, img->mWidth);
+        ASSERT_EQ(kHeight, img->mHeight);
+        ASSERT_EQ(8u, img->mBitDepth);
+        ASSERT_EQ(8u, img->mBitDepthAllocated);
+        const MediaImage2::PlaneInfo &yPlane = img->mPlane[MediaImage2::Y];
+        const MediaImage2::PlaneInfo &uPlane = img->mPlane[MediaImage2::U];
+        const MediaImage2::PlaneInfo &vPlane = img->mPlane[MediaImage2::V];
+        ASSERT_EQ(1u, yPlane.mHorizSubsampling);
+        ASSERT_EQ(1u, yPlane.mVertSubsampling);
+        ASSERT_EQ(2u, uPlane.mHorizSubsampling);
+        ASSERT_EQ(2u, uPlane.mVertSubsampling);
+        ASSERT_EQ(2u, vPlane.mHorizSubsampling);
+        ASSERT_EQ(2u, vPlane.mVertSubsampling);
+
+        uint8_t *yRowPtr = clientBuffer->data() + yPlane.mOffset;
+        uint8_t *uRowPtr = clientBuffer->data() + uPlane.mOffset;
+        uint8_t *vRowPtr = clientBuffer->data() + vPlane.mOffset;
+        for (int32_t row = 0; row < kHeight; ++row) {
+            uint8_t *yPtr = yRowPtr;
+            uint8_t *uPtr = uRowPtr;
+            uint8_t *vPtr = vRowPtr;
+            for (int32_t col = 0; col < kWidth; ++col) {
+                ASSERT_EQ((row + col) & 0xFF, *yPtr);
+                yPtr += yPlane.mColInc;
+                if (row < kHeight / 2 && col < kWidth / 2) {
+                    ASSERT_EQ((row + col + 1) & 0xFF, *uPtr);
+                    ASSERT_EQ((row + col + 2) & 0xFF, *vPtr);
+                    uPtr += uPlane.mColInc;
+                    vPtr += vPlane.mColInc;
+                }
+            }
+            yRowPtr += yPlane.mRowInc;
+            if (row < kHeight / 2) {
+                uRowPtr += uPlane.mRowInc;
+                vRowPtr += vPlane.mRowInc;
+            }
+        }
+    }
+}
+
+TEST(RawGraphicOutputBuffersTest, P010ColorFormat) {
+    constexpr int32_t kWidth = 320;
+    constexpr int32_t kHeight = 240;
+
+    std::shared_ptr<RawGraphicOutputBuffers> buffers =
+        std::make_shared<RawGraphicOutputBuffers>("test P010");
+
+    sp<AMessage> format{new AMessage};
+    format->setInt32(KEY_WIDTH, kWidth);
+    format->setInt32(KEY_HEIGHT, kHeight);
+    format->setInt32(KEY_COLOR_FORMAT, COLOR_FormatYUVP010);
+    int32_t fwkPixelFormat = 0;
+    if (C2Mapper::mapPixelFormatCodecToFramework(HAL_PIXEL_FORMAT_YCBCR_P010, &fwkPixelFormat)) {
+        format->setInt32("android._color-format", fwkPixelFormat);
+    }
+    buffers->setFormat(format);
+
+    std::shared_ptr<C2BlockPool> pool;
+    ASSERT_EQ(OK, GetCodec2BlockPool(C2BlockPool::BASIC_GRAPHIC, nullptr, &pool));
+
+    std::shared_ptr<C2GraphicBlock> block;
+    c2_status_t err = pool->fetchGraphicBlock(
+            kWidth, kHeight, HAL_PIXEL_FORMAT_YCBCR_P010,
+            C2MemoryUsage{C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE}, &block);
+    if (err != C2_OK) {
+        GTEST_SKIP();
+    }
+
+    {
+        C2GraphicView view = block->map().get();
+        C2PlanarLayout layout = view.layout();
+
+        // Verify the block is in YUV420 format
+        ASSERT_EQ(C2PlanarLayout::TYPE_YUV, layout.type);
+        ASSERT_EQ(3u, layout.numPlanes);
+        const C2PlaneInfo& yPlane = layout.planes[C2PlanarLayout::PLANE_Y];
+        const C2PlaneInfo& uPlane = layout.planes[C2PlanarLayout::PLANE_U];
+        const C2PlaneInfo& vPlane = layout.planes[C2PlanarLayout::PLANE_V];
+
+        // Y plane
+        ASSERT_EQ(1u, yPlane.colSampling);
+        ASSERT_EQ(1u, yPlane.rowSampling);
+        ASSERT_EQ(16u, yPlane.allocatedDepth);
+        ASSERT_EQ(10u, yPlane.bitDepth);
+        ASSERT_EQ(6u, yPlane.rightShift);
+
+        // U plane
+        ASSERT_EQ(2u, uPlane.colSampling);
+        ASSERT_EQ(2u, uPlane.rowSampling);
+        ASSERT_EQ(16u, uPlane.allocatedDepth);
+        ASSERT_EQ(10u, uPlane.bitDepth);
+        ASSERT_EQ(6u, uPlane.rightShift);
+
+        // V plane
+        ASSERT_EQ(2u, vPlane.colSampling);
+        ASSERT_EQ(2u, vPlane.rowSampling);
+        ASSERT_EQ(16u, vPlane.allocatedDepth);
+        ASSERT_EQ(10u, vPlane.bitDepth);
+        ASSERT_EQ(6u, vPlane.rightShift);
+
+        uint8_t *yRowPtr = view.data()[C2PlanarLayout::PLANE_Y];
+        uint8_t *uRowPtr = view.data()[C2PlanarLayout::PLANE_U];
+        uint8_t *vRowPtr = view.data()[C2PlanarLayout::PLANE_V];
+        for (int32_t row = 0; row < kHeight; ++row) {
+            uint8_t *yPtr = yRowPtr;
+            uint8_t *uPtr = uRowPtr;
+            uint8_t *vPtr = vRowPtr;
+            for (int32_t col = 0; col < kWidth; ++col) {
+                yPtr[0] = ((row + col) & 0x3) << 6;
+                yPtr[1] = ((row + col) & 0x3FC) >> 2;
+                yPtr += yPlane.colInc;
+
+                if (row < kHeight / 2 && col < kWidth / 2) {
+                    uPtr[0] = ((row + col + 1) & 0x3) << 6;
+                    uPtr[1] = ((row + col + 1) & 0x3FC) >> 2;
+                    vPtr[0] = ((row + col + 2) & 0x3) << 6;
+                    vPtr[1] = ((row + col + 2) & 0x3FC) >> 2;
+                    uPtr += uPlane.colInc;
+                    vPtr += vPlane.colInc;
+                }
+            }
+            yRowPtr += yPlane.rowInc;
+            if (row < kHeight / 2) {
+                uRowPtr += uPlane.rowInc;
+                vRowPtr += vPlane.rowInc;
+            }
+        }
+    }
+
+    std::shared_ptr<C2Buffer> c2Buffer = C2Buffer::CreateGraphicBuffer(block->share(
+            block->crop(), C2Fence{}));
+    size_t index;
+    sp<MediaCodecBuffer> clientBuffer;
+    ASSERT_EQ(OK, buffers->registerBuffer(c2Buffer, &index, &clientBuffer));
+    ASSERT_NE(nullptr, clientBuffer);
+    sp<ABuffer> imageData;
+    ASSERT_TRUE(clientBuffer->format()->findBuffer("image-data", &imageData));
+    MediaImage2 *img = (MediaImage2 *)imageData->data();
+    ASSERT_EQ(MediaImage2::MEDIA_IMAGE_TYPE_YUV, img->mType);
+    ASSERT_EQ(3u, img->mNumPlanes);
+    ASSERT_EQ(kWidth, img->mWidth);
+    ASSERT_EQ(kHeight, img->mHeight);
+    ASSERT_EQ(10u, img->mBitDepth);
+    ASSERT_EQ(16u, img->mBitDepthAllocated);
+    const MediaImage2::PlaneInfo &yPlane = img->mPlane[MediaImage2::Y];
+    const MediaImage2::PlaneInfo &uPlane = img->mPlane[MediaImage2::U];
+    const MediaImage2::PlaneInfo &vPlane = img->mPlane[MediaImage2::V];
+    ASSERT_EQ(1u, yPlane.mHorizSubsampling);
+    ASSERT_EQ(1u, yPlane.mVertSubsampling);
+    ASSERT_EQ(2u, uPlane.mHorizSubsampling);
+    ASSERT_EQ(2u, uPlane.mVertSubsampling);
+    ASSERT_EQ(2u, vPlane.mHorizSubsampling);
+    ASSERT_EQ(2u, vPlane.mVertSubsampling);
+
+    uint8_t *yRowPtr = clientBuffer->data() + yPlane.mOffset;
+    uint8_t *uRowPtr = clientBuffer->data() + uPlane.mOffset;
+    uint8_t *vRowPtr = clientBuffer->data() + vPlane.mOffset;
+    for (int32_t row = 0; row < kHeight; ++row) {
+        uint8_t *yPtr = yRowPtr;
+        uint8_t *uPtr = uRowPtr;
+        uint8_t *vPtr = vRowPtr;
+        for (int32_t col = 0; col < kWidth; ++col) {
+            ASSERT_EQ(((row + col) & 0x3) << 6, yPtr[0]);
+            ASSERT_EQ(((row + col) & 0x3FC) >> 2, yPtr[1]);
+            yPtr += yPlane.mColInc;
+            if (row < kHeight / 2 && col < kWidth / 2) {
+                ASSERT_EQ(((row + col + 1) & 0x3) << 6, uPtr[0]);
+                ASSERT_EQ(((row + col + 1) & 0x3FC) >> 2, uPtr[1]);
+                ASSERT_EQ(((row + col + 2) & 0x3) << 6, vPtr[0]);
+                ASSERT_EQ(((row + col + 2) & 0x3FC) >> 2, vPtr[1]);
+                uPtr += uPlane.mColInc;
+                vPtr += vPlane.mColInc;
+            }
+        }
+        yRowPtr += yPlane.mRowInc;
+        if (row < kHeight / 2) {
+            uRowPtr += uPlane.mRowInc;
+            vRowPtr += vPlane.mRowInc;
+        }
+    }
+}
+
+class TestGraphicAllocation : public C2GraphicAllocation {
+public:
+    TestGraphicAllocation(
+            uint32_t width,
+            uint32_t height,
+            const C2PlanarLayout &layout,
+            size_t capacity,
+            std::vector<size_t> offsets)
+        : C2GraphicAllocation(width, height),
+          mLayout(layout),
+          mMemory(capacity, 0xAA),
+          mOffsets(offsets) {
+    }
+
+    c2_status_t map(
+            C2Rect rect, C2MemoryUsage usage, C2Fence *fence,
+            C2PlanarLayout *layout, uint8_t **addr) override {
+        (void)rect;
+        (void)usage;
+        (void)fence;
+        *layout = mLayout;
+        for (size_t i = 0; i < mLayout.numPlanes; ++i) {
+            addr[i] = mMemory.data() + mOffsets[i];
+        }
+        return C2_OK;
+    }
+
+    c2_status_t unmap(uint8_t **, C2Rect, C2Fence *) override { return C2_OK; }
+
+    C2Allocator::id_t getAllocatorId() const override { return -1; }
+
+    const C2Handle *handle() const override { return nullptr; }
+
+    bool equals(const std::shared_ptr<const C2GraphicAllocation> &other) const override {
+        return other.get() == this;
+    }
+
+private:
+    C2PlanarLayout mLayout;
+    std::vector<uint8_t> mMemory;
+    std::vector<uint8_t *> mAddr;
+    std::vector<size_t> mOffsets;
+};
+
+class LayoutTest : public ::testing::TestWithParam<std::tuple<bool, std::string, bool, int32_t>> {
+private:
+    static C2PlanarLayout YUVPlanarLayout(int32_t stride) {
+        C2PlanarLayout layout = {
+            C2PlanarLayout::TYPE_YUV,
+            3,  /* numPlanes */
+            3,  /* rootPlanes */
+            {},  /* planes --- to be filled below */
+        };
+        layout.planes[C2PlanarLayout::PLANE_Y] = {
+            C2PlaneInfo::CHANNEL_Y,
+            1,  /* colInc */
+            stride,  /* rowInc */
+            1,  /* colSampling */
+            1,  /* rowSampling */
+            8,  /* allocatedDepth */
+            8,  /* bitDepth */
+            0,  /* rightShift */
+            C2PlaneInfo::NATIVE,
+            C2PlanarLayout::PLANE_Y,  /* rootIx */
+            0,  /* offset */
+        };
+        layout.planes[C2PlanarLayout::PLANE_U] = {
+            C2PlaneInfo::CHANNEL_CB,
+            1,  /* colInc */
+            stride / 2,  /* rowInc */
+            2,  /* colSampling */
+            2,  /* rowSampling */
+            8,  /* allocatedDepth */
+            8,  /* bitDepth */
+            0,  /* rightShift */
+            C2PlaneInfo::NATIVE,
+            C2PlanarLayout::PLANE_U,  /* rootIx */
+            0,  /* offset */
+        };
+        layout.planes[C2PlanarLayout::PLANE_V] = {
+            C2PlaneInfo::CHANNEL_CR,
+            1,  /* colInc */
+            stride / 2,  /* rowInc */
+            2,  /* colSampling */
+            2,  /* rowSampling */
+            8,  /* allocatedDepth */
+            8,  /* bitDepth */
+            0,  /* rightShift */
+            C2PlaneInfo::NATIVE,
+            C2PlanarLayout::PLANE_V,  /* rootIx */
+            0,  /* offset */
+        };
+        return layout;
+    }
+
+    static C2PlanarLayout YUVSemiPlanarLayout(int32_t stride) {
+        C2PlanarLayout layout = {
+            C2PlanarLayout::TYPE_YUV,
+            3,  /* numPlanes */
+            2,  /* rootPlanes */
+            {},  /* planes --- to be filled below */
+        };
+        layout.planes[C2PlanarLayout::PLANE_Y] = {
+            C2PlaneInfo::CHANNEL_Y,
+            1,  /* colInc */
+            stride,  /* rowInc */
+            1,  /* colSampling */
+            1,  /* rowSampling */
+            8,  /* allocatedDepth */
+            8,  /* bitDepth */
+            0,  /* rightShift */
+            C2PlaneInfo::NATIVE,
+            C2PlanarLayout::PLANE_Y,  /* rootIx */
+            0,  /* offset */
+        };
+        layout.planes[C2PlanarLayout::PLANE_U] = {
+            C2PlaneInfo::CHANNEL_CB,
+            2,  /* colInc */
+            stride,  /* rowInc */
+            2,  /* colSampling */
+            2,  /* rowSampling */
+            8,  /* allocatedDepth */
+            8,  /* bitDepth */
+            0,  /* rightShift */
+            C2PlaneInfo::NATIVE,
+            C2PlanarLayout::PLANE_U,  /* rootIx */
+            0,  /* offset */
+        };
+        layout.planes[C2PlanarLayout::PLANE_V] = {
+            C2PlaneInfo::CHANNEL_CR,
+            2,  /* colInc */
+            stride,  /* rowInc */
+            2,  /* colSampling */
+            2,  /* rowSampling */
+            8,  /* allocatedDepth */
+            8,  /* bitDepth */
+            0,  /* rightShift */
+            C2PlaneInfo::NATIVE,
+            C2PlanarLayout::PLANE_U,  /* rootIx */
+            1,  /* offset */
+        };
+        return layout;
+    }
+
+    static C2PlanarLayout YVUSemiPlanarLayout(int32_t stride) {
+        C2PlanarLayout layout = {
+            C2PlanarLayout::TYPE_YUV,
+            3,  /* numPlanes */
+            2,  /* rootPlanes */
+            {},  /* planes --- to be filled below */
+        };
+        layout.planes[C2PlanarLayout::PLANE_Y] = {
+            C2PlaneInfo::CHANNEL_Y,
+            1,  /* colInc */
+            stride,  /* rowInc */
+            1,  /* colSampling */
+            1,  /* rowSampling */
+            8,  /* allocatedDepth */
+            8,  /* bitDepth */
+            0,  /* rightShift */
+            C2PlaneInfo::NATIVE,
+            C2PlanarLayout::PLANE_Y,  /* rootIx */
+            0,  /* offset */
+        };
+        layout.planes[C2PlanarLayout::PLANE_U] = {
+            C2PlaneInfo::CHANNEL_CB,
+            2,  /* colInc */
+            stride,  /* rowInc */
+            2,  /* colSampling */
+            2,  /* rowSampling */
+            8,  /* allocatedDepth */
+            8,  /* bitDepth */
+            0,  /* rightShift */
+            C2PlaneInfo::NATIVE,
+            C2PlanarLayout::PLANE_V,  /* rootIx */
+            1,  /* offset */
+        };
+        layout.planes[C2PlanarLayout::PLANE_V] = {
+            C2PlaneInfo::CHANNEL_CR,
+            2,  /* colInc */
+            stride,  /* rowInc */
+            2,  /* colSampling */
+            2,  /* rowSampling */
+            8,  /* allocatedDepth */
+            8,  /* bitDepth */
+            0,  /* rightShift */
+            C2PlaneInfo::NATIVE,
+            C2PlanarLayout::PLANE_V,  /* rootIx */
+            0,  /* offset */
+        };
+        return layout;
+    }
+
+    static std::shared_ptr<C2GraphicBlock> CreateGraphicBlock(
+            uint32_t width,
+            uint32_t height,
+            const C2PlanarLayout &layout,
+            size_t capacity,
+            std::vector<size_t> offsets) {
+        std::shared_ptr<C2GraphicAllocation> alloc = std::make_shared<TestGraphicAllocation>(
+                width,
+                height,
+                layout,
+                capacity,
+                offsets);
+
+        return _C2BlockFactory::CreateGraphicBlock(alloc);
+    }
+
+    static constexpr uint8_t GetPixelValue(uint8_t value, uint32_t row, uint32_t col) {
+        return (uint32_t(value) * row + col) & 0xFF;
+    }
+
+    static void FillPlane(C2GraphicView &view, size_t index, uint8_t value) {
+        C2PlanarLayout layout = view.layout();
+
+        uint8_t *rowPtr = view.data()[index];
+        C2PlaneInfo plane = layout.planes[index];
+        for (uint32_t row = 0; row < view.height() / plane.rowSampling; ++row) {
+            uint8_t *colPtr = rowPtr;
+            for (uint32_t col = 0; col < view.width() / plane.colSampling; ++col) {
+                *colPtr = GetPixelValue(value, row, col);
+                colPtr += plane.colInc;
+            }
+            rowPtr += plane.rowInc;
+        }
+    }
+
+    static void FillBlock(const std::shared_ptr<C2GraphicBlock> &block) {
+        C2GraphicView view = block->map().get();
+
+        FillPlane(view, C2PlanarLayout::PLANE_Y, 'Y');
+        FillPlane(view, C2PlanarLayout::PLANE_U, 'U');
+        FillPlane(view, C2PlanarLayout::PLANE_V, 'V');
+    }
+
+    static bool VerifyPlane(
+            const MediaImage2 *mediaImage,
+            const uint8_t *base,
+            uint32_t index,
+            uint8_t value,
+            std::string *errorMsg) {
+        *errorMsg = "";
+        MediaImage2::PlaneInfo plane = mediaImage->mPlane[index];
+        const uint8_t *rowPtr = base + plane.mOffset;
+        for (uint32_t row = 0; row < mediaImage->mHeight / plane.mVertSubsampling; ++row) {
+            const uint8_t *colPtr = rowPtr;
+            for (uint32_t col = 0; col < mediaImage->mWidth / plane.mHorizSubsampling; ++col) {
+                if (GetPixelValue(value, row, col) != *colPtr) {
+                    *errorMsg = AStringPrintf("row=%u col=%u expected=%02x actual=%02x",
+                            row, col, GetPixelValue(value, row, col), *colPtr).c_str();
+                    return false;
+                }
+                colPtr += plane.mColInc;
+            }
+            rowPtr += plane.mRowInc;
+        }
+        return true;
+    }
+
+public:
+    static constexpr int32_t kWidth = 320;
+    static constexpr int32_t kHeight = 240;
+    static constexpr int32_t kGapLength = kWidth * kHeight * 10;
+
+    static std::shared_ptr<C2Buffer> CreateAndFillBufferFromParam(const ParamType &param) {
+        bool contiguous = std::get<0>(param);
+        std::string planeOrderStr = std::get<1>(param);
+        bool planar = std::get<2>(param);
+        int32_t stride = std::get<3>(param);
+
+        C2PlanarLayout::plane_index_t planeOrder[3];
+        C2PlanarLayout layout;
+
+        if (planeOrderStr.size() != 3) {
+            return nullptr;
+        }
+        for (size_t i = 0; i < 3; ++i) {
+            C2PlanarLayout::plane_index_t planeIndex;
+            switch (planeOrderStr[i]) {
+                case 'Y': planeIndex = C2PlanarLayout::PLANE_Y; break;
+                case 'U': planeIndex = C2PlanarLayout::PLANE_U; break;
+                case 'V': planeIndex = C2PlanarLayout::PLANE_V; break;
+                default:  return nullptr;
+            }
+            planeOrder[i] = planeIndex;
+        }
+
+        if (planar) {
+            layout = YUVPlanarLayout(stride);
+        } else {  // semi-planar
+            for (size_t i = 0; i < 3; ++i) {
+                if (planeOrder[i] == C2PlanarLayout::PLANE_U) {
+                    layout = YUVSemiPlanarLayout(stride);
+                    break;
+                }
+                if (planeOrder[i] == C2PlanarLayout::PLANE_V) {
+                    layout = YVUSemiPlanarLayout(stride);
+                    break;
+                }
+            }
+        }
+        size_t yPlaneSize = stride * kHeight;
+        size_t uvPlaneSize = stride * kHeight / 4;
+        size_t capacity = yPlaneSize + uvPlaneSize * 2;
+        std::vector<size_t> offsets(3);
+
+        if (!contiguous) {
+            if (planar) {
+                capacity += kGapLength * 2;
+            } else {  // semi-planar
+                capacity += kGapLength;
+            }
+        }
+
+        offsets[planeOrder[0]] = 0;
+        size_t planeSize = (planeOrder[0] == C2PlanarLayout::PLANE_Y) ? yPlaneSize : uvPlaneSize;
+        for (size_t i = 1; i < 3; ++i) {
+            offsets[planeOrder[i]] = offsets[planeOrder[i - 1]] + planeSize;
+            if (!contiguous) {
+                offsets[planeOrder[i]] += kGapLength;
+            }
+            planeSize = (planeOrder[i] == C2PlanarLayout::PLANE_Y) ? yPlaneSize : uvPlaneSize;
+            if (!planar  // semi-planar
+                    && planeOrder[i - 1] != C2PlanarLayout::PLANE_Y
+                    && planeOrder[i] != C2PlanarLayout::PLANE_Y) {
+                offsets[planeOrder[i]] = offsets[planeOrder[i - 1]] + 1;
+                planeSize = uvPlaneSize * 2 - 1;
+            }
+        }
+
+        std::shared_ptr<C2GraphicBlock> block = CreateGraphicBlock(
+                kWidth,
+                kHeight,
+                layout,
+                capacity,
+                offsets);
+        FillBlock(block);
+        return C2Buffer::CreateGraphicBuffer(
+                block->share(block->crop(), C2Fence()));
+    }
+
+    static bool VerifyClientBuffer(
+            const sp<MediaCodecBuffer> &buffer, std::string *errorMsg) {
+        *errorMsg = "";
+        sp<ABuffer> imageData;
+        if (!buffer->format()->findBuffer("image-data", &imageData)) {
+            *errorMsg = "Missing image data";
+            return false;
+        }
+        MediaImage2 *mediaImage = (MediaImage2 *)imageData->data();
+        if (mediaImage->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV) {
+            *errorMsg = AStringPrintf("Unexpected type: %d", mediaImage->mType).c_str();
+            return false;
+        }
+        std::string planeErrorMsg;
+        if (!VerifyPlane(mediaImage, buffer->base(), MediaImage2::Y, 'Y', &planeErrorMsg)) {
+            *errorMsg = "Y plane does not match: " + planeErrorMsg;
+            return false;
+        }
+        if (!VerifyPlane(mediaImage, buffer->base(), MediaImage2::U, 'U', &planeErrorMsg)) {
+            *errorMsg = "U plane does not match: " + planeErrorMsg;
+            return false;
+        }
+        if (!VerifyPlane(mediaImage, buffer->base(), MediaImage2::V, 'V', &planeErrorMsg)) {
+            *errorMsg = "V plane does not match: " + planeErrorMsg;
+            return false;
+        }
+
+        int32_t width, height, stride;
+        buffer->format()->findInt32(KEY_WIDTH, &width);
+        buffer->format()->findInt32(KEY_HEIGHT, &height);
+        buffer->format()->findInt32(KEY_STRIDE, &stride);
+
+        MediaImage2 legacyYLayout = {
+            MediaImage2::MEDIA_IMAGE_TYPE_Y,
+            1,  // mNumPlanes
+            uint32_t(width),
+            uint32_t(height),
+            8,
+            8,
+            {},  // mPlane
+        };
+        legacyYLayout.mPlane[MediaImage2::Y] = {
+            0,  // mOffset
+            1,  // mColInc
+            stride,  // mRowInc
+            1,  // mHorizSubsampling
+            1,  // mVertSubsampling
+        };
+        if (!VerifyPlane(&legacyYLayout, buffer->data(), MediaImage2::Y, 'Y', &planeErrorMsg)) {
+            *errorMsg = "Y plane by legacy layout does not match: " + planeErrorMsg;
+            return false;
+        }
+        return true;
+    }
+
+};
+
+TEST_P(LayoutTest, VerifyLayout) {
+    std::shared_ptr<RawGraphicOutputBuffers> buffers =
+        GetRawGraphicOutputBuffers(kWidth, kHeight);
+
+    std::shared_ptr<C2Buffer> c2Buffer = CreateAndFillBufferFromParam(GetParam());
+    ASSERT_NE(nullptr, c2Buffer);
+    sp<MediaCodecBuffer> clientBuffer;
+    size_t index;
+    ASSERT_EQ(OK, buffers->registerBuffer(c2Buffer, &index, &clientBuffer));
+    ASSERT_NE(nullptr, clientBuffer);
+    std::string errorMsg;
+    ASSERT_TRUE(VerifyClientBuffer(clientBuffer, &errorMsg)) << errorMsg;
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        RawGraphicOutputBuffersTest,
+        LayoutTest,
+        ::testing::Combine(
+            ::testing::Bool(),  /* contiguous */
+            ::testing::Values("YUV", "YVU", "UVY", "VUY"),
+            ::testing::Bool(),  /* planar */
+            ::testing::Values(320, 512)),
+        [](const ::testing::TestParamInfo<LayoutTest::ParamType> &info) {
+            std::string contiguous = std::get<0>(info.param) ? "Contiguous" : "Noncontiguous";
+            std::string planar = std::get<2>(info.param) ? "Planar" : "SemiPlanar";
+            return contiguous
+                    + std::get<1>(info.param)
+                    + planar
+                    + std::to_string(std::get<3>(info.param));
+        });
+
 } // namespace android
diff --git a/media/codec2/sfplugin/tests/FrameReassembler_test.cpp b/media/codec2/sfplugin/tests/FrameReassembler_test.cpp
new file mode 100644
index 0000000..6738ee7
--- /dev/null
+++ b/media/codec2/sfplugin/tests/FrameReassembler_test.cpp
@@ -0,0 +1,340 @@
+/*
+ * Copyright 2020 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 "FrameReassembler.h"
+
+#include <gtest/gtest.h>
+
+#include <C2PlatformSupport.h>
+
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/AMessage.h>
+
+namespace android {
+
+static size_t BytesPerSample(C2Config::pcm_encoding_t encoding) {
+    return encoding == PCM_8 ? 1
+         : encoding == PCM_16 ? 2
+         : encoding == PCM_FLOAT ? 4 : 0;
+}
+
+static uint64_t Diff(c2_cntr64_t a, c2_cntr64_t b) {
+    return std::abs((a - b).peek());
+}
+
+class FrameReassemblerTest : public ::testing::Test {
+public:
+    static const C2MemoryUsage kUsage;
+    static constexpr uint64_t kTimestampToleranceUs = 100;
+
+    FrameReassemblerTest() {
+        mInitStatus = GetCodec2BlockPool(C2BlockPool::BASIC_LINEAR, nullptr, &mPool);
+    }
+
+    status_t initStatus() const { return mInitStatus; }
+
+    void testPushSameSize(
+            size_t encoderFrameSize,
+            size_t sampleRate,
+            size_t channelCount,
+            C2Config::pcm_encoding_t encoding,
+            size_t inputFrameSizeInBytes,
+            size_t count,
+            size_t expectedOutputSize) {
+        FrameReassembler frameReassembler;
+        frameReassembler.init(
+                mPool,
+                kUsage,
+                encoderFrameSize,
+                sampleRate,
+                channelCount,
+                encoding);
+
+        ASSERT_TRUE(frameReassembler) << "FrameReassembler init failed";
+
+        size_t inputIndex = 0, outputIndex = 0;
+        size_t expectCount = 0;
+        for (size_t i = 0; i < count; ++i) {
+            sp<MediaCodecBuffer> buffer = new MediaCodecBuffer(
+                    new AMessage, new ABuffer(inputFrameSizeInBytes));
+            buffer->setRange(0, inputFrameSizeInBytes);
+            buffer->meta()->setInt64(
+                    "timeUs",
+                    inputIndex * 1000000 / sampleRate / channelCount / BytesPerSample(encoding));
+            if (i == count - 1) {
+                buffer->meta()->setInt32("eos", 1);
+            }
+            for (size_t j = 0; j < inputFrameSizeInBytes; ++j, ++inputIndex) {
+                buffer->base()[j] = (inputIndex & 0xFF);
+            }
+            std::list<std::unique_ptr<C2Work>> items;
+            ASSERT_EQ(C2_OK, frameReassembler.process(buffer, &items));
+            while (!items.empty()) {
+                std::unique_ptr<C2Work> work = std::move(*items.begin());
+                items.erase(items.begin());
+                // Verify timestamp
+                uint64_t expectedTimeUs =
+                    outputIndex * 1000000 / sampleRate / channelCount / BytesPerSample(encoding);
+                EXPECT_GE(
+                        kTimestampToleranceUs,
+                        Diff(expectedTimeUs, work->input.ordinal.timestamp))
+                    << "expected timestamp: " << expectedTimeUs
+                    << " actual timestamp: " << work->input.ordinal.timestamp.peeku()
+                    << " output index: " << outputIndex;
+
+                // Verify buffer
+                ASSERT_EQ(1u, work->input.buffers.size());
+                std::shared_ptr<C2Buffer> buffer = work->input.buffers.front();
+                ASSERT_EQ(C2BufferData::LINEAR, buffer->data().type());
+                ASSERT_EQ(1u, buffer->data().linearBlocks().size());
+                C2ReadView view = buffer->data().linearBlocks().front().map().get();
+                ASSERT_EQ(C2_OK, view.error());
+                ASSERT_EQ(encoderFrameSize * BytesPerSample(encoding), view.capacity());
+                for (size_t j = 0; j < view.capacity(); ++j, ++outputIndex) {
+                    ASSERT_TRUE(outputIndex < inputIndex
+                             || inputIndex == inputFrameSizeInBytes * count);
+                    uint8_t expected = outputIndex < inputIndex ? (outputIndex & 0xFF) : 0;
+                    if (expectCount < 10) {
+                        ++expectCount;
+                        EXPECT_EQ(expected, view.data()[j]) << "output index = " << outputIndex;
+                    }
+                }
+            }
+        }
+
+        ASSERT_EQ(inputFrameSizeInBytes * count, inputIndex);
+        size_t encoderFrameSizeInBytes =
+            encoderFrameSize * channelCount * BytesPerSample(encoding);
+        ASSERT_EQ(0, outputIndex % encoderFrameSizeInBytes)
+            << "output size must be multiple of frame size: output size = " << outputIndex
+            << " frame size = " << encoderFrameSizeInBytes;
+        ASSERT_EQ(expectedOutputSize, outputIndex)
+            << "output size must be smallest multiple of frame size, "
+            << "equal to or larger than input size. output size = " << outputIndex
+            << " input size = " << inputIndex << " frame size = " << encoderFrameSizeInBytes;
+    }
+
+private:
+    status_t mInitStatus;
+    std::shared_ptr<C2BlockPool> mPool;
+};
+
+const C2MemoryUsage FrameReassemblerTest::kUsage{C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
+
+// Push frames with exactly the same size as the encoder requested.
+TEST_F(FrameReassemblerTest, PushExactFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            1024 /* input frame size in bytes = 1024 samples * 1 channel * 1 bytes/sample */,
+            10 /* count */,
+            10240 /* expected output size = 10 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            2048 /* input frame size in bytes = 1024 samples * 1 channel * 2 bytes/sample */,
+            10 /* count */,
+            20480 /* expected output size = 10 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            4096 /* input frame size in bytes = 1024 samples * 1 channel * 4 bytes/sample */,
+            10 /* count */,
+            40960 /* expected output size = 10 * 4096 bytes/frame */);
+}
+
+// Push frames with half the size that the encoder requested.
+TEST_F(FrameReassemblerTest, PushHalfFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            512 /* input frame size in bytes = 512 samples * 1 channel * 1 bytes per sample */,
+            10 /* count */,
+            5120 /* expected output size = 5 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            1024 /* input frame size in bytes = 512 samples * 1 channel * 2 bytes per sample */,
+            10 /* count */,
+            10240 /* expected output size = 5 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            2048 /* input frame size in bytes = 512 samples * 1 channel * 4 bytes per sample */,
+            10 /* count */,
+            20480 /* expected output size = 5 * 4096 bytes/frame */);
+}
+
+// Push frames with twice the size that the encoder requested.
+TEST_F(FrameReassemblerTest, PushDoubleFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            2048 /* input frame size in bytes = 2048 samples * 1 channel * 1 bytes per sample */,
+            10 /* count */,
+            20480 /* expected output size = 20 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            4096 /* input frame size in bytes = 2048 samples * 1 channel * 2 bytes per sample */,
+            10 /* count */,
+            40960 /* expected output size = 20 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            8192 /* input frame size in bytes = 2048 samples * 1 channel * 4 bytes per sample */,
+            10 /* count */,
+            81920 /* expected output size = 20 * 4096 bytes/frame */);
+}
+
+// Push frames with a little bit larger (+5 samples) than the requested size.
+TEST_F(FrameReassemblerTest, PushLittleLargerFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            1029 /* input frame size in bytes = 1029 samples * 1 channel * 1 bytes per sample */,
+            10 /* count */,
+            11264 /* expected output size = 11 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            2058 /* input frame size in bytes = 1029 samples * 1 channel * 2 bytes per sample */,
+            10 /* count */,
+            22528 /* expected output size = 11 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            4116 /* input frame size in bytes = 1029 samples * 1 channel * 4 bytes per sample */,
+            10 /* count */,
+            45056 /* expected output size = 11 * 4096 bytes/frame */);
+}
+
+// Push frames with a little bit smaller (-5 samples) than the requested size.
+TEST_F(FrameReassemblerTest, PushLittleSmallerFrameSize) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            1019 /* input frame size in bytes = 1019 samples * 1 channel * 1 bytes per sample */,
+            10 /* count */,
+            10240 /* expected output size = 10 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            2038 /* input frame size in bytes = 1019 samples * 1 channel * 2 bytes per sample */,
+            10 /* count */,
+            20480 /* expected output size = 10 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            4076 /* input frame size in bytes = 1019 samples * 1 channel * 4 bytes per sample */,
+            10 /* count */,
+            40960 /* expected output size = 10 * 4096 bytes/frame */);
+}
+
+// Push single-byte frames
+TEST_F(FrameReassemblerTest, PushSingleByte) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            1 /* input frame size in bytes */,
+            100000 /* count */,
+            100352 /* expected output size = 98 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            1 /* input frame size in bytes */,
+            100000 /* count */,
+            100352 /* expected output size = 49 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            1 /* input frame size in bytes */,
+            100000 /* count */,
+            102400 /* expected output size = 25 * 4096 bytes/frame */);
+}
+
+// Push one big chunk.
+TEST_F(FrameReassemblerTest, PushBigChunk) {
+    ASSERT_EQ(OK, initStatus());
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_8,
+            100000 /* input frame size in bytes */,
+            1 /* count */,
+            100352 /* expected output size = 98 * 1024 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_16,
+            100000 /* input frame size in bytes */,
+            1 /* count */,
+            100352 /* expected output size = 49 * 2048 bytes/frame */);
+    testPushSameSize(
+            1024 /* frame size in samples */,
+            48000 /* sample rate */,
+            1 /* channel count */,
+            PCM_FLOAT,
+            100000 /* input frame size in bytes */,
+            1 /* count */,
+            102400 /* expected output size = 25 * 4096 bytes/frame */);
+}
+
+} // namespace android
diff --git a/media/codec2/sfplugin/utils/Android.bp b/media/codec2/sfplugin/utils/Android.bp
index 6287221..74e7ef1 100644
--- a/media/codec2/sfplugin/utils/Android.bp
+++ b/media/codec2/sfplugin/utils/Android.bp
@@ -1,4 +1,13 @@
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libsfplugin_ccodec_utils",
     vendor_available: true,
     min_sdk_version: "29",
diff --git a/media/codec2/sfplugin/utils/Codec2Mapper.cpp b/media/codec2/sfplugin/utils/Codec2Mapper.cpp
index 903db6c..1390642 100644
--- a/media/codec2/sfplugin/utils/Codec2Mapper.cpp
+++ b/media/codec2/sfplugin/utils/Codec2Mapper.cpp
@@ -958,17 +958,16 @@
             *c2Value = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
             return true;
         case COLOR_FormatYUV420Flexible:
-            *c2Value = HAL_PIXEL_FORMAT_YCBCR_420_888;
-            return true;
         case COLOR_FormatYUV420Planar:
         case COLOR_FormatYUV420SemiPlanar:
         case COLOR_FormatYUV420PackedPlanar:
         case COLOR_FormatYUV420PackedSemiPlanar:
-            *c2Value = HAL_PIXEL_FORMAT_YV12;
+            *c2Value = HAL_PIXEL_FORMAT_YCBCR_420_888;
             return true;
         default:
-            // TODO: support some sort of passthrough
-            return false;
+            // Passthrough
+            *c2Value = uint32_t(frameworkValue);
+            return true;
     }
 }
 
@@ -979,11 +978,16 @@
         case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
             *frameworkValue = COLOR_FormatSurface;
             return true;
-        case HAL_PIXEL_FORMAT_YV12:
+        case HAL_PIXEL_FORMAT_YCBCR_422_SP:
+        case HAL_PIXEL_FORMAT_YCRCB_420_SP:
+        case HAL_PIXEL_FORMAT_YCBCR_422_I:
         case HAL_PIXEL_FORMAT_YCBCR_420_888:
+        case HAL_PIXEL_FORMAT_YV12:
             *frameworkValue = COLOR_FormatYUV420Flexible;
             return true;
         default:
-            return false;
+            // Passthrough
+            *frameworkValue = int32_t(c2Value);
+            return true;
     }
 }
diff --git a/media/codec2/tests/Android.bp b/media/codec2/tests/Android.bp
index fce6e21..8ebb6c0 100644
--- a/media/codec2/tests/Android.bp
+++ b/media/codec2/tests/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "codec2_core_param_test",
 
diff --git a/media/codec2/tests/C2Param_test.cpp b/media/codec2/tests/C2Param_test.cpp
index 564d4d2..bb8130c 100644
--- a/media/codec2/tests/C2Param_test.cpp
+++ b/media/codec2/tests/C2Param_test.cpp
@@ -96,7 +96,7 @@
     const static std::vector<C2FieldDescriptor> _FIELD_LIST;
     static const std::vector<C2FieldDescriptor> FieldList();  // <= needed for C2FieldDescriptor
     const static FD::type_t TYPE = (FD::type_t)(CORE_INDEX | FD::STRUCT_FLAG);
-};
+} C2_PACK;
 
 DEFINE_NO_NAMED_VALUES_FOR(C2SizeStruct)
 
@@ -111,11 +111,13 @@
 
 struct C2TestStruct_A {
     int32_t signed32;
+    // 4-byte padding
     int64_t signed64[2];
     uint32_t unsigned32[1];
+    // 4-byte padding
     uint64_t unsigned64;
     float fp32;
-    C2SizeStruct sz[3];
+    C2SizeStruct sz[3]; // 8-byte structure, but 4-byte aligned
     uint8_t blob[100];
     char string[100];
     bool yesNo[100];
@@ -124,21 +126,21 @@
     static const std::vector<C2FieldDescriptor> FieldList();
     // enum : uint32_t { CORE_INDEX = kParamIndexTest };
     // typedef C2TestStruct_A _type;
-} __attribute__((packed));
+} __attribute__((aligned(4)));
 
 const std::vector<C2FieldDescriptor> C2TestStruct_A::FieldList() {
     return _FIELD_LIST;
 }
 const std::vector<C2FieldDescriptor> C2TestStruct_A::_FIELD_LIST =
     { { FD::INT32,    1, "s32",   0, 4 },
-      { FD::INT64,    2, "s64",   4, 8 },
-      { FD::UINT32,   1, "u32",  20, 4 },
-      { FD::UINT64,   1, "u64",  24, 8 },
-      { FD::FLOAT,    1, "fp",   32, 4 },
-      { C2SizeStruct::TYPE, 3, "size", 36, 8 },
-      { FD::BLOB,   100, "blob", 60, 1 },
-      { FD::STRING, 100, "str", 160, 1 },
-      { FD::BLOB,   100, "y-n", 260, 1 } };
+      { FD::INT64,    2, "s64",   8, 8 },
+      { FD::UINT32,   1, "u32",  24, 4 },
+      { FD::UINT64,   1, "u64",  32, 8 },
+      { FD::FLOAT,    1, "fp",   40, 4 },
+      { C2SizeStruct::TYPE, 3, "size", 44, 8 },
+      { FD::BLOB,   100, "blob", 68, 1 },
+      { FD::STRING, 100, "str", 168, 1 },
+      { FD::BLOB,   100, "y-n", 268, 1 } };
 
 TEST_P(C2ParamTest_ParamFieldList, VerifyStruct) {
     std::vector<C2FieldDescriptor> fields = GetParam(), expected = C2TestStruct_A::_FIELD_LIST;
@@ -198,11 +200,13 @@
 
 struct C2TestAStruct {
     int32_t signed32;
+    // 4-byte padding
     int64_t signed64[2];
     uint32_t unsigned32[1];
+    // 4-byte padding
     uint64_t unsigned64;
     float fp32;
-    C2SizeStruct sz[3];
+    C2SizeStruct sz[3]; // 8-byte structure, but 4-byte aligned
     uint8_t blob[100];
     char string[100];
     bool yesNo[100];
@@ -229,11 +233,13 @@
 
 struct C2TestBStruct {
     int32_t signed32;
+    // 4-byte padding
     int64_t signed64[2];
     uint32_t unsigned32[1];
+    // 4-byte padding
     uint64_t unsigned64;
     float fp32;
-    C2SizeStruct sz[3];
+    C2SizeStruct sz[3]; // 8-byte structure, but 4-byte aligned
     uint8_t blob[100];
     char string[100];
     bool yesNo[100];
@@ -286,7 +292,7 @@
         if (fields.size() > 1) {
             EXPECT_EQ(2u, fields.size());
             EXPECT_EQ(C2FieldDescriptor(FD::INT32, 1, "s32", 0, 4), fields[0]);
-            EXPECT_EQ(C2FieldDescriptor(this->FlexType, 0, "flex", 4, this->FLEX_SIZE),
+            EXPECT_EQ(C2FieldDescriptor(this->FlexType, 0, "flex", alignof(TypeParam) /* offset */, this->FLEX_SIZE),
                       fields[1]);
         } else {
             EXPECT_EQ(1u, fields.size());
@@ -392,6 +398,7 @@
 
 struct C2TestStruct_FlexEndS64 {
     int32_t signed32;
+    // 4-byte padding
     int64_t mSigned64Flex[];
 
     const static std::vector<C2FieldDescriptor> _FIELD_LIST;
@@ -406,7 +413,7 @@
 }
 const std::vector<C2FieldDescriptor> C2TestStruct_FlexEndS64::_FIELD_LIST = {
     { FD::INT32, 1, "s32", 0, 4 },
-    { FD::INT64, 0, "flex", 4, 8 },
+    { FD::INT64, 0, "flex", 8, 8 },
 };
 
 struct C2TestFlexS64Struct {
@@ -419,6 +426,7 @@
 
 struct C2TestFlexEndS64Struct {
     int32_t signed32;
+    // 4-byte padding
     int64_t mFlexSigned64[];
     C2TestFlexEndS64Struct() {}
 
@@ -468,7 +476,7 @@
     // enum : uint32_t { CORE_INDEX = C2TestStruct_FlexEndSize, FLEX_SIZE = 8 };
     // typedef C2TestStruct_FlexEndSize _type;
     // typedef C2SizeStruct FlexType;
-};
+} __attribute__((aligned(4)));
 
 const std::vector<C2FieldDescriptor> C2TestStruct_FlexEndSize::FieldList() {
     return _FIELD_LIST;
@@ -539,14 +547,14 @@
 TEST_F(C2ParamTest, FieldId) {
     // pointer constructor
     EXPECT_EQ(_C2FieldId(0, 4), _C2FieldId(&((C2TestStruct_A*)0)->signed32));
-    EXPECT_EQ(_C2FieldId(4, 8), _C2FieldId(&((C2TestStruct_A*)0)->signed64));
-    EXPECT_EQ(_C2FieldId(20, 4), _C2FieldId(&((C2TestStruct_A*)0)->unsigned32));
-    EXPECT_EQ(_C2FieldId(24, 8), _C2FieldId(&((C2TestStruct_A*)0)->unsigned64));
-    EXPECT_EQ(_C2FieldId(32, 4), _C2FieldId(&((C2TestStruct_A*)0)->fp32));
-    EXPECT_EQ(_C2FieldId(36, 8), _C2FieldId(&((C2TestStruct_A*)0)->sz));
-    EXPECT_EQ(_C2FieldId(60, 1), _C2FieldId(&((C2TestStruct_A*)0)->blob));
-    EXPECT_EQ(_C2FieldId(160, 1), _C2FieldId(&((C2TestStruct_A*)0)->string));
-    EXPECT_EQ(_C2FieldId(260, 1), _C2FieldId(&((C2TestStruct_A*)0)->yesNo));
+    EXPECT_EQ(_C2FieldId(8, 8), _C2FieldId(&((C2TestStruct_A*)0)->signed64));
+    EXPECT_EQ(_C2FieldId(24, 4), _C2FieldId(&((C2TestStruct_A*)0)->unsigned32));
+    EXPECT_EQ(_C2FieldId(32, 8), _C2FieldId(&((C2TestStruct_A*)0)->unsigned64));
+    EXPECT_EQ(_C2FieldId(40, 4), _C2FieldId(&((C2TestStruct_A*)0)->fp32));
+    EXPECT_EQ(_C2FieldId(44, 8), _C2FieldId(&((C2TestStruct_A*)0)->sz));
+    EXPECT_EQ(_C2FieldId(68, 1), _C2FieldId(&((C2TestStruct_A*)0)->blob));
+    EXPECT_EQ(_C2FieldId(168, 1), _C2FieldId(&((C2TestStruct_A*)0)->string));
+    EXPECT_EQ(_C2FieldId(268, 1), _C2FieldId(&((C2TestStruct_A*)0)->yesNo));
 
     EXPECT_EQ(_C2FieldId(0, 4), _C2FieldId(&((C2TestFlexEndSizeStruct*)0)->signed32));
     EXPECT_EQ(_C2FieldId(4, 8), _C2FieldId(&((C2TestFlexEndSizeStruct*)0)->mFlexSize));
@@ -556,14 +564,14 @@
 
     // member pointer constructor
     EXPECT_EQ(_C2FieldId(0, 4), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::signed32));
-    EXPECT_EQ(_C2FieldId(4, 8), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::signed64));
-    EXPECT_EQ(_C2FieldId(20, 4), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::unsigned32));
-    EXPECT_EQ(_C2FieldId(24, 8), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::unsigned64));
-    EXPECT_EQ(_C2FieldId(32, 4), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::fp32));
-    EXPECT_EQ(_C2FieldId(36, 8), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::sz));
-    EXPECT_EQ(_C2FieldId(60, 1), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::blob));
-    EXPECT_EQ(_C2FieldId(160, 1), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::string));
-    EXPECT_EQ(_C2FieldId(260, 1), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::yesNo));
+    EXPECT_EQ(_C2FieldId(8, 8), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::signed64));
+    EXPECT_EQ(_C2FieldId(24, 4), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::unsigned32));
+    EXPECT_EQ(_C2FieldId(32, 8), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::unsigned64));
+    EXPECT_EQ(_C2FieldId(40, 4), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::fp32));
+    EXPECT_EQ(_C2FieldId(44, 8), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::sz));
+    EXPECT_EQ(_C2FieldId(68, 1), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::blob));
+    EXPECT_EQ(_C2FieldId(168, 1), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::string));
+    EXPECT_EQ(_C2FieldId(268, 1), _C2FieldId((C2TestStruct_A*)0, &C2TestStruct_A::yesNo));
 
     EXPECT_EQ(_C2FieldId(0, 4), _C2FieldId((C2TestFlexEndSizeStruct*)0, &C2TestFlexEndSizeStruct::signed32));
     EXPECT_EQ(_C2FieldId(4, 8), _C2FieldId((C2TestFlexEndSizeStruct*)0, &C2TestFlexEndSizeStruct::mFlexSize));
@@ -573,14 +581,14 @@
 
     // member pointer sans type pointer
     EXPECT_EQ(_C2FieldId(0, 4), _C2FieldId(&C2TestStruct_A::signed32));
-    EXPECT_EQ(_C2FieldId(4, 8), _C2FieldId(&C2TestStruct_A::signed64));
-    EXPECT_EQ(_C2FieldId(20, 4), _C2FieldId(&C2TestStruct_A::unsigned32));
-    EXPECT_EQ(_C2FieldId(24, 8), _C2FieldId(&C2TestStruct_A::unsigned64));
-    EXPECT_EQ(_C2FieldId(32, 4), _C2FieldId(&C2TestStruct_A::fp32));
-    EXPECT_EQ(_C2FieldId(36, 8), _C2FieldId(&C2TestStruct_A::sz));
-    EXPECT_EQ(_C2FieldId(60, 1), _C2FieldId(&C2TestStruct_A::blob));
-    EXPECT_EQ(_C2FieldId(160, 1), _C2FieldId(&C2TestStruct_A::string));
-    EXPECT_EQ(_C2FieldId(260, 1), _C2FieldId(&C2TestStruct_A::yesNo));
+    EXPECT_EQ(_C2FieldId(8, 8), _C2FieldId(&C2TestStruct_A::signed64));
+    EXPECT_EQ(_C2FieldId(24, 4), _C2FieldId(&C2TestStruct_A::unsigned32));
+    EXPECT_EQ(_C2FieldId(32, 8), _C2FieldId(&C2TestStruct_A::unsigned64));
+    EXPECT_EQ(_C2FieldId(40, 4), _C2FieldId(&C2TestStruct_A::fp32));
+    EXPECT_EQ(_C2FieldId(44, 8), _C2FieldId(&C2TestStruct_A::sz));
+    EXPECT_EQ(_C2FieldId(68, 1), _C2FieldId(&C2TestStruct_A::blob));
+    EXPECT_EQ(_C2FieldId(168, 1), _C2FieldId(&C2TestStruct_A::string));
+    EXPECT_EQ(_C2FieldId(268, 1), _C2FieldId(&C2TestStruct_A::yesNo));
 
     EXPECT_EQ(_C2FieldId(0, 4), _C2FieldId(&C2TestFlexEndSizeStruct::signed32));
     EXPECT_EQ(_C2FieldId(4, 8), _C2FieldId(&C2TestFlexEndSizeStruct::mFlexSize));
@@ -594,14 +602,14 @@
 
     // pointer constructor in C2Param
     EXPECT_EQ(_C2FieldId(8, 4), _C2FieldId(&((C2TestAInfo*)0)->signed32));
-    EXPECT_EQ(_C2FieldId(12, 8), _C2FieldId(&((C2TestAInfo*)0)->signed64));
-    EXPECT_EQ(_C2FieldId(28, 4), _C2FieldId(&((C2TestAInfo*)0)->unsigned32));
-    EXPECT_EQ(_C2FieldId(32, 8), _C2FieldId(&((C2TestAInfo*)0)->unsigned64));
-    EXPECT_EQ(_C2FieldId(40, 4), _C2FieldId(&((C2TestAInfo*)0)->fp32));
-    EXPECT_EQ(_C2FieldId(44, 8), _C2FieldId(&((C2TestAInfo*)0)->sz));
-    EXPECT_EQ(_C2FieldId(68, 1), _C2FieldId(&((C2TestAInfo*)0)->blob));
-    EXPECT_EQ(_C2FieldId(168, 1), _C2FieldId(&((C2TestAInfo*)0)->string));
-    EXPECT_EQ(_C2FieldId(268, 1), _C2FieldId(&((C2TestAInfo*)0)->yesNo));
+    EXPECT_EQ(_C2FieldId(16, 8), _C2FieldId(&((C2TestAInfo*)0)->signed64));
+    EXPECT_EQ(_C2FieldId(32, 4), _C2FieldId(&((C2TestAInfo*)0)->unsigned32));
+    EXPECT_EQ(_C2FieldId(40, 8), _C2FieldId(&((C2TestAInfo*)0)->unsigned64));
+    EXPECT_EQ(_C2FieldId(48, 4), _C2FieldId(&((C2TestAInfo*)0)->fp32));
+    EXPECT_EQ(_C2FieldId(52, 8), _C2FieldId(&((C2TestAInfo*)0)->sz));
+    EXPECT_EQ(_C2FieldId(76, 1), _C2FieldId(&((C2TestAInfo*)0)->blob));
+    EXPECT_EQ(_C2FieldId(176, 1), _C2FieldId(&((C2TestAInfo*)0)->string));
+    EXPECT_EQ(_C2FieldId(276, 1), _C2FieldId(&((C2TestAInfo*)0)->yesNo));
 
     EXPECT_EQ(_C2FieldId(8, 4), _C2FieldId(&((C2TestFlexEndSizeInfo*)0)->m.signed32));
     EXPECT_EQ(_C2FieldId(12, 8), _C2FieldId(&((C2TestFlexEndSizeInfo*)0)->m.mFlexSize));
@@ -611,14 +619,14 @@
 
     // member pointer in C2Param
     EXPECT_EQ(_C2FieldId(8, 4), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::signed32));
-    EXPECT_EQ(_C2FieldId(12, 8), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::signed64));
-    EXPECT_EQ(_C2FieldId(28, 4), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::unsigned32));
-    EXPECT_EQ(_C2FieldId(32, 8), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::unsigned64));
-    EXPECT_EQ(_C2FieldId(40, 4), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::fp32));
-    EXPECT_EQ(_C2FieldId(44, 8), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::sz));
-    EXPECT_EQ(_C2FieldId(68, 1), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::blob));
-    EXPECT_EQ(_C2FieldId(168, 1), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::string));
-    EXPECT_EQ(_C2FieldId(268, 1), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::yesNo));
+    EXPECT_EQ(_C2FieldId(16, 8), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::signed64));
+    EXPECT_EQ(_C2FieldId(32, 4), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::unsigned32));
+    EXPECT_EQ(_C2FieldId(40, 8), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::unsigned64));
+    EXPECT_EQ(_C2FieldId(48, 4), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::fp32));
+    EXPECT_EQ(_C2FieldId(52, 8), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::sz));
+    EXPECT_EQ(_C2FieldId(76, 1), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::blob));
+    EXPECT_EQ(_C2FieldId(176, 1), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::string));
+    EXPECT_EQ(_C2FieldId(276, 1), _C2FieldId((C2TestAInfo*)0, &C2TestAInfo::yesNo));
 
     // NOTE: cannot use a member pointer for flex params due to introduction of 'm'
     // EXPECT_EQ(_C2FieldId(8, 4), _C2FieldId(&C2TestFlexEndSizeInfo::m.signed32));
@@ -2328,6 +2336,17 @@
         static_assert(std::is_same<decltype(blobValue->m.value), uint8_t[]>::value, "should be uint8_t[]");
         EXPECT_EQ(0, memcmp(blobValue->m.value, "ABCD\0", 6));
         EXPECT_EQ(6u, blobValue->flexCount());
+        blobValue->setFlexCount(7u); // increasing the count does not change it
+        EXPECT_EQ(6u, blobValue->flexCount());
+        blobValue->setFlexCount(2u); // decreasing the count changes it to it
+        EXPECT_EQ(2u, blobValue->flexCount());
+        blobValue->setFlexCount(0u); // can decrease to 0 and blob remains valid
+        EXPECT_EQ(0u, blobValue->flexCount());
+        EXPECT_TRUE(*blobValue);
+        blobValue->invalidate(); // flex params can be invalidated => results in 0 size
+        EXPECT_FALSE(*blobValue);
+        EXPECT_EQ(0u, blobValue->size());
+
         std::vector<C2FieldDescriptor> fields = blobValue->FieldList();
         EXPECT_EQ(1u, fields.size());
         EXPECT_EQ(FD::BLOB, fields.cbegin()->type());
diff --git a/media/codec2/tests/C2UtilTest.cpp b/media/codec2/tests/C2UtilTest.cpp
index 59cd313..2d66df1 100644
--- a/media/codec2/tests/C2UtilTest.cpp
+++ b/media/codec2/tests/C2UtilTest.cpp
@@ -78,7 +78,7 @@
       { "value2", Enum3Value2 },
       { "value4", Enum3Value4 },
       { "invalid", Invalid } });
-    Enum3 e3;
+    Enum3 e3(Invalid);
     C2FieldDescriptor::namedValuesFor(e3);
 
     // upper case
diff --git a/media/codec2/tests/vndk/C2BufferTest.cpp b/media/codec2/tests/vndk/C2BufferTest.cpp
index 780994a..a9f8e17 100644
--- a/media/codec2/tests/vndk/C2BufferTest.cpp
+++ b/media/codec2/tests/vndk/C2BufferTest.cpp
@@ -765,4 +765,54 @@
     }
 }
 
+TEST_F(C2BufferTest, InfoBufferTest) {
+    constexpr size_t kCapacity = 524288u;
+
+    // allocate a linear block
+    std::shared_ptr<C2BlockPool> linearPool(makeLinearBlockPool());
+    std::shared_ptr<C2LinearBlock> linearBlock;
+    ASSERT_EQ(C2_OK, linearPool->fetchLinearBlock(
+            kCapacity,
+            { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE },
+            &linearBlock));
+
+    C2InfoBuffer info = C2InfoBuffer::CreateLinearBuffer(
+            kParamIndexNumber1, linearBlock->share(1024, kCapacity / 2, C2Fence()));
+    std::shared_ptr<C2InfoBuffer> spInfo(new C2InfoBuffer(info));
+    ASSERT_EQ(kParamIndexNumber1, spInfo->index().coreIndex());
+    ASSERT_TRUE(spInfo->index().isGlobal());
+    ASSERT_EQ(C2Param::INFO, spInfo->index().kind());
+    ASSERT_EQ(C2BufferData::LINEAR, spInfo->data().type());
+    ASSERT_EQ(1024, spInfo->data().linearBlocks()[0].offset());
+    ASSERT_EQ(kCapacity / 2, spInfo->data().linearBlocks()[0].size());
+    // handles must actually be identical after sharing into an info buffer
+    ASSERT_EQ(linearBlock->handle(), spInfo->data().linearBlocks()[0].handle());
+    ASSERT_EQ(linearPool->getAllocatorId(), spInfo->data().linearBlocks()[0].getAllocatorId());
+
+    C2InfoBuffer streamInfo = info.asStream(false /* output */,  1u);
+    ASSERT_EQ(kParamIndexNumber1, streamInfo.index().coreIndex());
+    ASSERT_TRUE(streamInfo.index().forStream());
+    ASSERT_TRUE(streamInfo.index().forInput());
+    ASSERT_EQ(1u, streamInfo.index().stream());
+    ASSERT_EQ(C2Param::INFO, streamInfo.index().kind());
+    ASSERT_EQ(C2BufferData::LINEAR, streamInfo.data().type());
+    ASSERT_EQ(1024, streamInfo.data().linearBlocks()[0].offset());
+    ASSERT_EQ(kCapacity / 2, streamInfo.data().linearBlocks()[0].size());
+    // handles must actually be identical after sharing into an info buffer
+    ASSERT_EQ(linearBlock->handle(), streamInfo.data().linearBlocks()[0].handle());
+    ASSERT_EQ(linearPool->getAllocatorId(), streamInfo.data().linearBlocks()[0].getAllocatorId());
+
+    C2InfoBuffer portInfo = streamInfo.asPort(true /* output */);
+    ASSERT_EQ(kParamIndexNumber1, portInfo.index().coreIndex());
+    ASSERT_TRUE(portInfo.index().forPort());
+    ASSERT_TRUE(portInfo.index().forOutput());
+    ASSERT_EQ(C2Param::INFO, portInfo.index().kind());
+    ASSERT_EQ(C2BufferData::LINEAR, portInfo.data().type());
+    ASSERT_EQ(1024, portInfo.data().linearBlocks()[0].offset());
+    ASSERT_EQ(kCapacity / 2, portInfo.data().linearBlocks()[0].size());
+    // handles must actually be identical after sharing into an info buffer
+    ASSERT_EQ(linearBlock->handle(), portInfo.data().linearBlocks()[0].handle());
+    ASSERT_EQ(linearPool->getAllocatorId(), portInfo.data().linearBlocks()[0].getAllocatorId());
+}
+
 } // namespace android
diff --git a/media/codec2/vndk/Android.bp b/media/codec2/vndk/Android.bp
index 6f7acce..0401c1d 100644
--- a/media/codec2/vndk/Android.bp
+++ b/media/codec2/vndk/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libcodec2_internal",
 
@@ -13,7 +22,7 @@
 
 // !!!DO NOT DEPEND ON THIS SHARED LIBRARY DIRECTLY!!!
 // use libcodec2-impl-defaults instead
-cc_library_shared {
+cc_library {
     name: "libcodec2_vndk",
     vendor_available: true,
     min_sdk_version: "29",
@@ -26,6 +35,7 @@
         "C2AllocatorGralloc.cpp",
         "C2Buffer.cpp",
         "C2Config.cpp",
+        "C2DmaBufAllocator.cpp",
         "C2PlatformStorePluginLoader.cpp",
         "C2Store.cpp",
         "platform/C2BqBuffer.cpp",
@@ -64,6 +74,7 @@
         "libhardware",
         "libhidlbase",
         "libion",
+        "libdmabufheap",
         "libfmq",
         "liblog",
         "libnativewindow",
@@ -110,4 +121,3 @@
 
     // TODO: separate internal headers so they can be exposed here
 }
-
diff --git a/media/codec2/vndk/C2AllocatorBlob.cpp b/media/codec2/vndk/C2AllocatorBlob.cpp
index 50c9e59..6340cba 100644
--- a/media/codec2/vndk/C2AllocatorBlob.cpp
+++ b/media/codec2/vndk/C2AllocatorBlob.cpp
@@ -17,6 +17,8 @@
 // #define LOG_NDEBUG 0
 #define LOG_TAG "C2AllocatorBlob"
 
+#include <set>
+
 #include <C2AllocatorBlob.h>
 #include <C2PlatformSupport.h>
 
@@ -67,6 +69,10 @@
 private:
     const std::shared_ptr<C2GraphicAllocation> mGraphicAllocation;
     const C2Allocator::id_t mAllocatorId;
+
+    std::mutex mMapLock;
+    std::multiset<std::pair<size_t, size_t>> mMappedOffsetSize;
+    uint8_t *mMappedAddr;
 };
 
 C2AllocationBlob::C2AllocationBlob(
@@ -74,20 +80,74 @@
         C2Allocator::id_t allocatorId)
       : C2LinearAllocation(capacity),
         mGraphicAllocation(std::move(graphicAllocation)),
-        mAllocatorId(allocatorId) {}
+        mAllocatorId(allocatorId),
+        mMappedAddr(nullptr) {}
 
-C2AllocationBlob::~C2AllocationBlob() {}
+C2AllocationBlob::~C2AllocationBlob() {
+    if (mMappedAddr) {
+        C2Rect rect(capacity(), kLinearBufferHeight);
+        mGraphicAllocation->unmap(&mMappedAddr, rect, nullptr);
+    }
+}
 
 c2_status_t C2AllocationBlob::map(size_t offset, size_t size, C2MemoryUsage usage,
                                   C2Fence* fence, void** addr /* nonnull */) {
+    *addr = nullptr;
+    if (size > capacity() || offset > capacity() || offset > capacity() - size) {
+        ALOGV("C2AllocationBlob: map: bad offset / size: offset=%zu size=%zu capacity=%u",
+                offset, size, capacity());
+        return C2_BAD_VALUE;
+    }
+    std::unique_lock<std::mutex> lock(mMapLock);
+    if (mMappedAddr) {
+        *addr = mMappedAddr + offset;
+        mMappedOffsetSize.insert({offset, size});
+        ALOGV("C2AllocationBlob: mapped from existing mapping: offset=%zu size=%zu capacity=%u",
+                offset, size, capacity());
+        return C2_OK;
+    }
     C2PlanarLayout layout;
-    C2Rect rect = C2Rect(size, kLinearBufferHeight).at(offset, 0u);
-    return mGraphicAllocation->map(rect, usage, fence, &layout, reinterpret_cast<uint8_t**>(addr));
+    C2Rect rect = C2Rect(capacity(), kLinearBufferHeight);
+    c2_status_t err = mGraphicAllocation->map(rect, usage, fence, &layout, &mMappedAddr);
+    if (err != C2_OK) {
+        ALOGV("C2AllocationBlob: map failed: offset=%zu size=%zu capacity=%u err=%d",
+                offset, size, capacity(), err);
+        mMappedAddr = nullptr;
+        return err;
+    }
+    *addr = mMappedAddr + offset;
+    mMappedOffsetSize.insert({offset, size});
+    ALOGV("C2AllocationBlob: new map succeeded: offset=%zu size=%zu capacity=%u",
+            offset, size, capacity());
+    return C2_OK;
 }
 
 c2_status_t C2AllocationBlob::unmap(void* addr, size_t size, C2Fence* fenceFd) {
-    C2Rect rect(size, kLinearBufferHeight);
-    return mGraphicAllocation->unmap(reinterpret_cast<uint8_t**>(&addr), rect, fenceFd);
+    std::unique_lock<std::mutex> lock(mMapLock);
+    uint8_t *u8Addr = static_cast<uint8_t *>(addr);
+    if (u8Addr < mMappedAddr || mMappedAddr + capacity() < u8Addr + size) {
+        ALOGV("C2AllocationBlob: unmap: Bad addr / size: addr=%p size=%zu capacity=%u",
+                addr, size, capacity());
+        return C2_BAD_VALUE;
+    }
+    auto it = mMappedOffsetSize.find(std::make_pair(u8Addr - mMappedAddr, size));
+    if (it == mMappedOffsetSize.end()) {
+        ALOGV("C2AllocationBlob: unrecognized map: addr=%p size=%zu capacity=%u",
+                addr, size, capacity());
+        return C2_BAD_VALUE;
+    }
+    mMappedOffsetSize.erase(it);
+    if (!mMappedOffsetSize.empty()) {
+        ALOGV("C2AllocationBlob: still maintain mapping: addr=%p size=%zu capacity=%u",
+                addr, size, capacity());
+        return C2_OK;
+    }
+    C2Rect rect(capacity(), kLinearBufferHeight);
+    c2_status_t err = mGraphicAllocation->unmap(&mMappedAddr, rect, fenceFd);
+    ALOGV("C2AllocationBlob: last unmap: addr=%p size=%zu capacity=%u err=%d",
+            addr, size, capacity(), err);
+    mMappedAddr = nullptr;
+    return err;
 }
 
 /* ====================================== BLOB ALLOCATOR ====================================== */
@@ -175,12 +235,12 @@
 }
 
 // static
-bool C2AllocatorBlob::isValid(const C2Handle* const o) {
+bool C2AllocatorBlob::CheckHandle(const C2Handle* const o) {
     size_t capacity;
     // Distinguish C2Handle purely allocated by C2AllocatorGralloc, or one allocated through
     // C2AllocatorBlob, by checking the handle's height is 1, and its format is
     // PixelFormat::BLOB by GetCapacityFromHandle().
-    return C2AllocatorGralloc::isValid(o) && GetCapacityFromHandle(o, &capacity) == C2_OK;
+    return C2AllocatorGralloc::CheckHandle(o) && GetCapacityFromHandle(o, &capacity) == C2_OK;
 }
 
 }  // namespace android
diff --git a/media/codec2/vndk/C2AllocatorGralloc.cpp b/media/codec2/vndk/C2AllocatorGralloc.cpp
index e1e1377..bee6b7f 100644
--- a/media/codec2/vndk/C2AllocatorGralloc.cpp
+++ b/media/codec2/vndk/C2AllocatorGralloc.cpp
@@ -25,6 +25,7 @@
 #include <hardware/gralloc.h>
 #include <ui/GraphicBufferAllocator.h>
 #include <ui/GraphicBufferMapper.h>
+#include <ui/Rect.h>
 
 #include <C2AllocatorGralloc.h>
 #include <C2Buffer.h>
@@ -103,7 +104,7 @@
     const static uint32_t MAGIC = '\xc2gr\x00';
 
     static
-    const ExtraData* getExtraData(const C2Handle *const handle) {
+    const ExtraData* GetExtraData(const C2Handle *const handle) {
         if (handle == nullptr
                 || native_handle_is_invalid(handle)
                 || handle->numInts < NUM_INTS) {
@@ -114,23 +115,23 @@
     }
 
     static
-    ExtraData *getExtraData(C2Handle *const handle) {
-        return const_cast<ExtraData *>(getExtraData(const_cast<const C2Handle *const>(handle)));
+    ExtraData *GetExtraData(C2Handle *const handle) {
+        return const_cast<ExtraData *>(GetExtraData(const_cast<const C2Handle *const>(handle)));
     }
 
 public:
     void getIgbpData(uint32_t *generation, uint64_t *igbp_id, uint32_t *igbp_slot) const {
-        const ExtraData *ed = getExtraData(this);
+        const ExtraData *ed = GetExtraData(this);
         *generation = ed->generation;
         *igbp_id = unsigned(ed->igbp_id_lo) | uint64_t(unsigned(ed->igbp_id_hi)) << 32;
         *igbp_slot = ed->igbp_slot;
     }
 
-    static bool isValid(const C2Handle *const o) {
+    static bool IsValid(const C2Handle *const o) {
         if (o == nullptr) { // null handle is always valid
             return true;
         }
-        const ExtraData *xd = getExtraData(o);
+        const ExtraData *xd = GetExtraData(o);
         // we cannot validate width/height/format/usage without accessing gralloc driver
         return xd != nullptr && xd->magic == MAGIC;
     }
@@ -152,7 +153,7 @@
         native_handle_t *res = native_handle_create(handle->numFds, handle->numInts + NUM_INTS);
         if (res != nullptr) {
             memcpy(&res->data, &handle->data, sizeof(int) * (handle->numFds + handle->numInts));
-            *getExtraData(res) = xd;
+            *GetExtraData(res) = xd;
         }
         return reinterpret_cast<C2HandleGralloc *>(res);
     }
@@ -180,10 +181,10 @@
     static bool MigrateNativeHandle(
             native_handle_t *handle,
             uint32_t generation, uint64_t igbp_id, uint32_t igbp_slot) {
-        if (handle == nullptr || !isValid(handle)) {
+        if (handle == nullptr || !IsValid(handle)) {
             return false;
         }
-        ExtraData *ed = getExtraData(handle);
+        ExtraData *ed = GetExtraData(handle);
         if (!ed) return false;
         ed->generation = generation;
         ed->igbp_id_lo = uint32_t(igbp_id & 0xFFFFFFFF);
@@ -195,7 +196,7 @@
 
     static native_handle_t* UnwrapNativeHandle(
             const C2Handle *const handle) {
-        const ExtraData *xd = getExtraData(handle);
+        const ExtraData *xd = GetExtraData(handle);
         if (xd == nullptr || xd->magic != MAGIC) {
             return nullptr;
         }
@@ -211,7 +212,7 @@
             uint32_t *width, uint32_t *height, uint32_t *format,
             uint64_t *usage, uint32_t *stride,
             uint32_t *generation, uint64_t *igbp_id, uint32_t *igbp_slot) {
-        const ExtraData *xd = getExtraData(handle);
+        const ExtraData *xd = GetExtraData(handle);
         if (xd == nullptr) {
             return nullptr;
         }
@@ -253,7 +254,7 @@
     virtual ~C2AllocationGralloc() override;
 
     virtual c2_status_t map(
-            C2Rect rect, C2MemoryUsage usage, C2Fence *fence,
+            C2Rect c2Rect, C2MemoryUsage usage, C2Fence *fence,
             C2PlanarLayout *layout /* nonnull */, uint8_t **addr /* nonnull */) override;
     virtual c2_status_t unmap(
             uint8_t **addr /* nonnull */, C2Rect rect, C2Fence *fence /* nullable */) override;
@@ -336,8 +337,12 @@
 }
 
 c2_status_t C2AllocationGralloc::map(
-        C2Rect rect, C2MemoryUsage usage, C2Fence *fence,
+        C2Rect c2Rect, C2MemoryUsage usage, C2Fence *fence,
         C2PlanarLayout *layout /* nonnull */, uint8_t **addr /* nonnull */) {
+    const Rect rect{(int32_t)c2Rect.left, (int32_t)c2Rect.top,
+                    (int32_t)(c2Rect.left + c2Rect.width) /* right */,
+                    (int32_t)(c2Rect.top + c2Rect.height) /* bottom */};
+
     uint64_t grallocUsage = static_cast<C2AndroidMemoryUsage>(usage).asGrallocUsage();
     ALOGV("mapping buffer with usage %#llx => %#llx",
           (long long)usage.expected, (long long)grallocUsage);
@@ -386,10 +391,7 @@
             void *pointer = nullptr;
             // TODO: fence
             status_t err = GraphicBufferMapper::get().lock(
-                                const_cast<native_handle_t *>(mBuffer), grallocUsage,
-                                { (int32_t)rect.left, (int32_t)rect.top,
-                                  (int32_t)rect.width, (int32_t)rect.height },
-                                &pointer);
+                    const_cast<native_handle_t *>(mBuffer), grallocUsage, rect, &pointer);
             if (err) {
                 ALOGE("failed transaction: lock(RGBA_1010102)");
                 return C2_CORRUPTED;
@@ -464,10 +466,7 @@
             void *pointer = nullptr;
             // TODO: fence
             status_t err = GraphicBufferMapper::get().lock(
-                                const_cast<native_handle_t*>(mBuffer), grallocUsage,
-                                { (int32_t)rect.left, (int32_t)rect.top,
-                                  (int32_t)rect.width, (int32_t)rect.height },
-                                &pointer);
+                    const_cast<native_handle_t*>(mBuffer), grallocUsage, rect, &pointer);
             if (err) {
                 ALOGE("failed transaction: lock(RGBA_8888)");
                 return C2_CORRUPTED;
@@ -524,10 +523,7 @@
             void *pointer = nullptr;
             // TODO: fence
             status_t err = GraphicBufferMapper::get().lock(
-                                const_cast<native_handle_t*>(mBuffer), grallocUsage,
-                                { (int32_t)rect.left, (int32_t)rect.top,
-                                  (int32_t)rect.width, (int32_t)rect.height },
-                                &pointer);
+                    const_cast<native_handle_t*>(mBuffer), grallocUsage, rect, &pointer);
             if (err) {
                 ALOGE("failed transaction: lock(BLOB)");
                 return C2_CORRUPTED;
@@ -536,20 +532,33 @@
             break;
         }
 
+        case static_cast<uint32_t>(PixelFormat4::YCBCR_422_SP):
+            // fall-through
+        case static_cast<uint32_t>(PixelFormat4::YCRCB_420_SP):
+            // fall-through
+        case static_cast<uint32_t>(PixelFormat4::YCBCR_422_I):
+            // fall-through
         case static_cast<uint32_t>(PixelFormat4::YCBCR_420_888):
             // fall-through
-        case static_cast<uint32_t>(PixelFormat4::YV12):
-            // fall-through
-        default: {
+        case static_cast<uint32_t>(PixelFormat4::YV12): {
             android_ycbcr ycbcrLayout;
 
             status_t err = GraphicBufferMapper::get().lockYCbCr(
-                        const_cast<native_handle_t*>(mBuffer), grallocUsage,
-                        { (int32_t)rect.left, (int32_t)rect.top,
-                          (int32_t)rect.width, (int32_t)rect.height },
-                        &ycbcrLayout);
+                    const_cast<native_handle_t*>(mBuffer), grallocUsage, rect, &ycbcrLayout);
             if (err) {
-                ALOGE("failed transaction: lockYCbCr");
+                ALOGE("failed transaction: lockYCbCr (err=%d)", err);
+                return C2_CORRUPTED;
+            }
+            if (!ycbcrLayout.y || !ycbcrLayout.cb || !ycbcrLayout.cr
+                    || ycbcrLayout.ystride == 0
+                    || ycbcrLayout.cstride == 0
+                    || ycbcrLayout.chroma_step == 0) {
+                ALOGE("invalid layout: lockYCbCr (y=%s cb=%s cr=%s "
+                        "ystride=%zu cstride=%zu chroma_step=%zu)",
+                        ycbcrLayout.y ? "(non-null)" : "(null)",
+                        ycbcrLayout.cb ? "(non-null)" : "(null)",
+                        ycbcrLayout.cr ? "(non-null)" : "(null)",
+                        ycbcrLayout.ystride, ycbcrLayout.cstride, ycbcrLayout.chroma_step);
                 return C2_CORRUPTED;
             }
 
@@ -611,6 +620,161 @@
             }
             break;
         }
+
+        case static_cast<uint32_t>(PixelFormat4::YCBCR_P010): {
+            void *pointer = nullptr;
+            status_t err = GraphicBufferMapper::get().lock(
+                    const_cast<native_handle_t *>(mBuffer), grallocUsage, rect, &pointer);
+            if (err) {
+                ALOGE("failed transaction: lock(YCBCR_P010)");
+                return C2_CORRUPTED;
+            }
+            addr[C2PlanarLayout::PLANE_Y] = (uint8_t *)pointer;
+            addr[C2PlanarLayout::PLANE_U] = (uint8_t *)pointer + mStride * 2 * rect.height();
+            addr[C2PlanarLayout::PLANE_V] = addr[C2PlanarLayout::PLANE_U] + 2;
+            layout->type = C2PlanarLayout::TYPE_YUV;
+            layout->numPlanes = 3;
+            layout->rootPlanes = 2;
+            layout->planes[C2PlanarLayout::PLANE_Y] = {
+                C2PlaneInfo::CHANNEL_Y,         // channel
+                2,                              // colInc
+                static_cast<int32_t>(2 * mStride), // rowInc
+                1,                              // mColSampling
+                1,                              // mRowSampling
+                16,                             // allocatedDepth
+                10,                             // bitDepth
+                6,                              // rightShift
+                C2PlaneInfo::LITTLE_END,        // endianness
+                C2PlanarLayout::PLANE_Y,        // rootIx
+                0,                              // offset
+            };
+            layout->planes[C2PlanarLayout::PLANE_U] = {
+                C2PlaneInfo::CHANNEL_CB,        // channel
+                4,                              // colInc
+                static_cast<int32_t>(2 * mStride), // rowInc
+                2,                              // mColSampling
+                2,                              // mRowSampling
+                16,                             // allocatedDepth
+                10,                             // bitDepth
+                6,                              // rightShift
+                C2PlaneInfo::LITTLE_END,        // endianness
+                C2PlanarLayout::PLANE_U,        // rootIx
+                0,                              // offset
+            };
+            layout->planes[C2PlanarLayout::PLANE_V] = {
+                C2PlaneInfo::CHANNEL_CR,        // channel
+                4,                              // colInc
+                static_cast<int32_t>(2 * mStride), // rowInc
+                2,                              // mColSampling
+                2,                              // mRowSampling
+                16,                             // allocatedDepth
+                10,                             // bitDepth
+                6,                              // rightShift
+                C2PlaneInfo::LITTLE_END,        // endianness
+                C2PlanarLayout::PLANE_U,        // rootIx
+                2,                              // offset
+            };
+            break;
+        }
+
+        default: {
+            // We don't know what it is, but let's try to lock it.
+            android_ycbcr ycbcrLayout;
+
+            status_t err = GraphicBufferMapper::get().lockYCbCr(
+                    const_cast<native_handle_t*>(mBuffer), grallocUsage, rect, &ycbcrLayout);
+            if (err == OK && ycbcrLayout.y && ycbcrLayout.cb && ycbcrLayout.cr
+                    && ycbcrLayout.ystride > 0
+                    && ycbcrLayout.cstride > 0
+                    && ycbcrLayout.chroma_step > 0) {
+                addr[C2PlanarLayout::PLANE_Y] = (uint8_t *)ycbcrLayout.y;
+                addr[C2PlanarLayout::PLANE_U] = (uint8_t *)ycbcrLayout.cb;
+                addr[C2PlanarLayout::PLANE_V] = (uint8_t *)ycbcrLayout.cr;
+                layout->type = C2PlanarLayout::TYPE_YUV;
+                layout->numPlanes = 3;
+                layout->rootPlanes = 3;
+                layout->planes[C2PlanarLayout::PLANE_Y] = {
+                    C2PlaneInfo::CHANNEL_Y,         // channel
+                    1,                              // colInc
+                    (int32_t)ycbcrLayout.ystride,   // rowInc
+                    1,                              // mColSampling
+                    1,                              // mRowSampling
+                    8,                              // allocatedDepth
+                    8,                              // bitDepth
+                    0,                              // rightShift
+                    C2PlaneInfo::NATIVE,            // endianness
+                    C2PlanarLayout::PLANE_Y,        // rootIx
+                    0,                              // offset
+                };
+                layout->planes[C2PlanarLayout::PLANE_U] = {
+                    C2PlaneInfo::CHANNEL_CB,          // channel
+                    (int32_t)ycbcrLayout.chroma_step, // colInc
+                    (int32_t)ycbcrLayout.cstride,     // rowInc
+                    2,                                // mColSampling
+                    2,                                // mRowSampling
+                    8,                                // allocatedDepth
+                    8,                                // bitDepth
+                    0,                                // rightShift
+                    C2PlaneInfo::NATIVE,              // endianness
+                    C2PlanarLayout::PLANE_U,          // rootIx
+                    0,                                // offset
+                };
+                layout->planes[C2PlanarLayout::PLANE_V] = {
+                    C2PlaneInfo::CHANNEL_CR,          // channel
+                    (int32_t)ycbcrLayout.chroma_step, // colInc
+                    (int32_t)ycbcrLayout.cstride,     // rowInc
+                    2,                                // mColSampling
+                    2,                                // mRowSampling
+                    8,                                // allocatedDepth
+                    8,                                // bitDepth
+                    0,                                // rightShift
+                    C2PlaneInfo::NATIVE,              // endianness
+                    C2PlanarLayout::PLANE_V,          // rootIx
+                    0,                                // offset
+                };
+                // handle interleaved formats
+                intptr_t uvOffset = addr[C2PlanarLayout::PLANE_V] - addr[C2PlanarLayout::PLANE_U];
+                if (uvOffset > 0 && uvOffset < (intptr_t)ycbcrLayout.chroma_step) {
+                    layout->rootPlanes = 2;
+                    layout->planes[C2PlanarLayout::PLANE_V].rootIx = C2PlanarLayout::PLANE_U;
+                    layout->planes[C2PlanarLayout::PLANE_V].offset = uvOffset;
+                } else if (uvOffset < 0 && uvOffset > -(intptr_t)ycbcrLayout.chroma_step) {
+                    layout->rootPlanes = 2;
+                    layout->planes[C2PlanarLayout::PLANE_U].rootIx = C2PlanarLayout::PLANE_V;
+                    layout->planes[C2PlanarLayout::PLANE_U].offset = -uvOffset;
+                }
+                break;
+            }
+
+            // We really don't know what this is; lock the buffer and pass it through ---
+            // the client may know how to interpret it.
+            void *pointer = nullptr;
+            err = GraphicBufferMapper::get().lock(
+                    const_cast<native_handle_t *>(mBuffer), grallocUsage, rect, &pointer);
+            if (err) {
+                ALOGE("failed transaction: lock(??? %x)", mFormat);
+                return C2_CORRUPTED;
+            }
+            addr[0] = (uint8_t *)pointer;
+            layout->type = C2PlanarLayout::TYPE_UNKNOWN;
+            layout->numPlanes = 1;
+            layout->rootPlanes = 1;
+            layout->planes[0] = {
+                // TODO: CHANNEL_UNKNOWN?
+                C2PlaneInfo::channel_t(0xFF),   // channel
+                1,                              // colInc
+                int32_t(mStride),               // rowInc
+                1,                              // mColSampling
+                1,                              // mRowSampling
+                8,                              // allocatedDepth
+                8,                              // bitDepth
+                0,                              // rightShift
+                C2PlaneInfo::NATIVE,            // endianness
+                0,                              // rootIx
+                0,                              // offset
+            };
+            break;
+        }
     }
     mLocked = true;
 
@@ -784,8 +948,9 @@
     return mImpl->status();
 }
 
-bool C2AllocatorGralloc::isValid(const C2Handle* const o) {
-    return C2HandleGralloc::isValid(o);
+// static
+bool C2AllocatorGralloc::CheckHandle(const C2Handle* const o) {
+    return C2HandleGralloc::IsValid(o);
 }
 
 } // namespace android
diff --git a/media/codec2/vndk/C2AllocatorIon.cpp b/media/codec2/vndk/C2AllocatorIon.cpp
index 6d27a02..85623b8 100644
--- a/media/codec2/vndk/C2AllocatorIon.cpp
+++ b/media/codec2/vndk/C2AllocatorIon.cpp
@@ -73,7 +73,7 @@
 };
 
 // static
-bool C2HandleIon::isValid(const C2Handle * const o) {
+bool C2HandleIon::IsValid(const C2Handle * const o) {
     if (!o || memcmp(o, &cHeader, sizeof(cHeader))) {
         return false;
     }
@@ -579,7 +579,7 @@
         return mInit;
     }
 
-    if (!C2HandleIon::isValid(handle)) {
+    if (!C2HandleIon::IsValid(handle)) {
         return C2_BAD_VALUE;
     }
 
@@ -596,9 +596,8 @@
     return ret;
 }
 
-bool C2AllocatorIon::isValid(const C2Handle* const o) {
-    return C2HandleIon::isValid(o);
+bool C2AllocatorIon::CheckHandle(const C2Handle* const o) {
+    return C2HandleIon::IsValid(o);
 }
 
 } // namespace android
-
diff --git a/media/codec2/vndk/C2Buffer.cpp b/media/codec2/vndk/C2Buffer.cpp
index 0b08f31..143355f 100644
--- a/media/codec2/vndk/C2Buffer.cpp
+++ b/media/codec2/vndk/C2Buffer.cpp
@@ -106,6 +106,7 @@
 class BufferDataBuddy : public C2BufferData {
     using C2BufferData::C2BufferData;
     friend class ::C2Buffer;
+    friend class ::C2InfoBuffer;
 };
 
 }  // namespace
@@ -396,26 +397,18 @@
 std::shared_ptr<C2LinearBlock> _C2BlockFactory::CreateLinearBlock(
         const C2Handle *handle) {
     // TODO: get proper allocator? and mutex?
-    static std::unique_ptr<C2Allocator> sAllocator = []{
-        std::unique_ptr<C2Allocator> allocator;
-        if (android::GetPreferredLinearAllocatorId(android::GetCodec2PoolMask()) ==
-                android::C2PlatformAllocatorStore::BLOB) {
-            allocator = std::make_unique<C2AllocatorBlob>(android::C2PlatformAllocatorStore::BLOB);
-        } else {
-            allocator = std::make_unique<C2AllocatorIon>(android::C2PlatformAllocatorStore::ION);
-        }
+    static std::shared_ptr<C2Allocator> sAllocator = []{
+        std::shared_ptr<C2Allocator> allocator;
+        std::shared_ptr<C2AllocatorStore> allocatorStore = android::GetCodec2PlatformAllocatorStore();
+        allocatorStore->fetchAllocator(C2AllocatorStore::DEFAULT_LINEAR, &allocator);
+
         return allocator;
     }();
 
     if (sAllocator == nullptr)
         return nullptr;
 
-    bool isValidHandle = false;
-    if (sAllocator->getId() == android::C2PlatformAllocatorStore::BLOB) {
-        isValidHandle = C2AllocatorBlob::isValid(handle);
-    } else {
-        isValidHandle = C2AllocatorIon::isValid(handle);
-    }
+    bool isValidHandle = sAllocator->checkHandle(handle);
 
     std::shared_ptr<C2LinearAllocation> alloc;
     if (isValidHandle) {
@@ -431,26 +424,18 @@
 std::shared_ptr<C2LinearBlock> _C2BlockFactory::CreateLinearBlock(
         const C2Handle *cHandle, const std::shared_ptr<BufferPoolData> &data) {
     // TODO: get proper allocator? and mutex?
-    static std::unique_ptr<C2Allocator> sAllocator = []{
-        std::unique_ptr<C2Allocator> allocator;
-        if (android::GetPreferredLinearAllocatorId(android::GetCodec2PoolMask()) ==
-                android::C2PlatformAllocatorStore::BLOB) {
-            allocator = std::make_unique<C2AllocatorBlob>(android::C2PlatformAllocatorStore::BLOB);
-        } else {
-            allocator = std::make_unique<C2AllocatorIon>(android::C2PlatformAllocatorStore::ION);
-        }
+    static std::shared_ptr<C2Allocator> sAllocator = []{
+        std::shared_ptr<C2Allocator> allocator;
+        std::shared_ptr<C2AllocatorStore> allocatorStore = android::GetCodec2PlatformAllocatorStore();
+        allocatorStore->fetchAllocator(C2AllocatorStore::DEFAULT_LINEAR, &allocator);
+
         return allocator;
     }();
 
     if (sAllocator == nullptr)
         return nullptr;
 
-    bool isValidHandle = false;
-    if (sAllocator->getId() == android::C2PlatformAllocatorStore::BLOB) {
-        isValidHandle = C2AllocatorBlob::isValid(cHandle);
-    } else {
-        isValidHandle = C2AllocatorIon::isValid(cHandle);
-    }
+    bool isValidHandle = sAllocator->checkHandle(cHandle);
 
     std::shared_ptr<C2LinearAllocation> alloc;
     if (isValidHandle) {
@@ -1148,7 +1133,7 @@
     static std::unique_ptr<C2AllocatorGralloc> sAllocator = std::make_unique<C2AllocatorGralloc>(0);
 
     std::shared_ptr<C2GraphicAllocation> alloc;
-    if (C2AllocatorGralloc::isValid(cHandle)) {
+    if (sAllocator->isValid(cHandle)) {
         c2_status_t err = sAllocator->priorGraphicAllocation(cHandle, &alloc);
         const std::shared_ptr<C2PooledBlockPoolData> poolData =
                 std::make_shared<C2PooledBlockPoolData>(data);
@@ -1185,6 +1170,7 @@
     type_t mType;
     std::vector<C2ConstLinearBlock> mLinearBlocks;
     std::vector<C2ConstGraphicBlock> mGraphicBlocks;
+    friend class C2InfoBuffer;
 };
 
 C2BufferData::C2BufferData(const std::vector<C2ConstLinearBlock> &blocks) : mImpl(new Impl(blocks)) {}
@@ -1200,6 +1186,35 @@
     return mImpl->graphicBlocks();
 }
 
+C2InfoBuffer::C2InfoBuffer(
+    C2Param::Index index, const std::vector<C2ConstLinearBlock> &blocks)
+    : mIndex(index), mData(BufferDataBuddy(blocks)) {
+}
+
+C2InfoBuffer::C2InfoBuffer(
+    C2Param::Index index, const std::vector<C2ConstGraphicBlock> &blocks)
+    : mIndex(index), mData(BufferDataBuddy(blocks)) {
+}
+
+C2InfoBuffer::C2InfoBuffer(
+    C2Param::Index index, const C2BufferData &data)
+    : mIndex(index), mData(data) {
+}
+
+// static
+C2InfoBuffer C2InfoBuffer::CreateLinearBuffer(
+        C2Param::CoreIndex index, const C2ConstLinearBlock &block) {
+    return C2InfoBuffer(index.coreIndex() | C2Param::Index::KIND_INFO | C2Param::Index::DIR_GLOBAL,
+                        { block });
+}
+
+// static
+C2InfoBuffer C2InfoBuffer::CreateGraphicBuffer(
+        C2Param::CoreIndex index, const C2ConstGraphicBlock &block) {
+    return C2InfoBuffer(index.coreIndex() | C2Param::Index::KIND_INFO | C2Param::Index::DIR_GLOBAL,
+                        { block });
+}
+
 class C2Buffer::Impl {
 public:
     Impl(C2Buffer *thiz, const std::vector<C2ConstLinearBlock> &blocks)
@@ -1330,4 +1345,3 @@
 std::shared_ptr<C2Buffer> C2Buffer::CreateGraphicBuffer(const C2ConstGraphicBlock &block) {
     return std::shared_ptr<C2Buffer>(new C2Buffer({ block }));
 }
-
diff --git a/media/codec2/vndk/C2DmaBufAllocator.cpp b/media/codec2/vndk/C2DmaBufAllocator.cpp
new file mode 100644
index 0000000..750aa31
--- /dev/null
+++ b/media/codec2/vndk/C2DmaBufAllocator.cpp
@@ -0,0 +1,401 @@
+/*
+ * Copyright (C) 2020 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 "C2DmaBufAllocator"
+#include <BufferAllocator/BufferAllocator.h>
+#include <C2Buffer.h>
+#include <C2Debug.h>
+#include <C2DmaBufAllocator.h>
+#include <C2ErrnoUtils.h>
+#include <linux/ion.h>
+#include <sys/mman.h>
+#include <unistd.h>  // getpagesize, size_t, close, dup
+#include <utils/Log.h>
+
+#include <list>
+
+#ifdef __ANDROID_APEX__
+#include <android-base/properties.h>
+#endif
+
+namespace android {
+
+namespace {
+constexpr size_t USAGE_LRU_CACHE_SIZE = 1024;
+}
+
+/* =========================== BUFFER HANDLE =========================== */
+/**
+ * Buffer handle
+ *
+ * Stores dmabuf fd & metadata
+ *
+ * This handle will not capture mapped fd-s as updating that would require a
+ * global mutex.
+ */
+
+struct C2HandleBuf : public C2Handle {
+    C2HandleBuf(int bufferFd, size_t size)
+        : C2Handle(cHeader),
+          mFds{bufferFd},
+          mInts{int(size & 0xFFFFFFFF), int((uint64_t(size) >> 32) & 0xFFFFFFFF), kMagic} {}
+
+    static bool IsValid(const C2Handle* const o);
+
+    int bufferFd() const { return mFds.mBuffer; }
+    size_t size() const {
+        return size_t(unsigned(mInts.mSizeLo)) | size_t(uint64_t(unsigned(mInts.mSizeHi)) << 32);
+    }
+
+   protected:
+    struct {
+        int mBuffer;  // dmabuf fd
+    } mFds;
+    struct {
+        int mSizeLo;  // low 32-bits of size
+        int mSizeHi;  // high 32-bits of size
+        int mMagic;
+    } mInts;
+
+   private:
+    typedef C2HandleBuf _type;
+    enum {
+        kMagic = '\xc2io\x00',
+        numFds = sizeof(mFds) / sizeof(int),
+        numInts = sizeof(mInts) / sizeof(int),
+        version = sizeof(C2Handle)
+    };
+    // constexpr static C2Handle cHeader = { version, numFds, numInts, {} };
+    const static C2Handle cHeader;
+};
+
+const C2Handle C2HandleBuf::cHeader = {
+        C2HandleBuf::version, C2HandleBuf::numFds, C2HandleBuf::numInts, {}};
+
+// static
+bool C2HandleBuf::IsValid(const C2Handle* const o) {
+    if (!o || memcmp(o, &cHeader, sizeof(cHeader))) {
+        return false;
+    }
+    const C2HandleBuf* other = static_cast<const C2HandleBuf*>(o);
+    return other->mInts.mMagic == kMagic;
+}
+
+/* =========================== DMABUF ALLOCATION =========================== */
+class C2DmaBufAllocation : public C2LinearAllocation {
+   public:
+    /* Interface methods */
+    virtual c2_status_t map(size_t offset, size_t size, C2MemoryUsage usage, C2Fence* fence,
+                            void** addr /* nonnull */) override;
+    virtual c2_status_t unmap(void* addr, size_t size, C2Fence* fenceFd) override;
+    virtual ~C2DmaBufAllocation() override;
+    virtual const C2Handle* handle() const override;
+    virtual id_t getAllocatorId() const override;
+    virtual bool equals(const std::shared_ptr<C2LinearAllocation>& other) const override;
+
+    // internal methods
+    C2DmaBufAllocation(BufferAllocator& alloc, size_t size, C2String heap_name, unsigned flags,
+                       C2Allocator::id_t id);
+    C2DmaBufAllocation(size_t size, int shareFd, C2Allocator::id_t id);
+
+    c2_status_t status() const;
+
+   protected:
+    virtual c2_status_t mapInternal(size_t mapSize, size_t mapOffset, size_t alignmentBytes,
+                                    int prot, int flags, void** base, void** addr) {
+        c2_status_t err = C2_OK;
+        *base = mmap(nullptr, mapSize, prot, flags, mHandle.bufferFd(), mapOffset);
+        ALOGV("mmap(size = %zu, prot = %d, flags = %d, mapFd = %d, offset = %zu) "
+              "returned (%d)",
+              mapSize, prot, flags, mHandle.bufferFd(), mapOffset, errno);
+        if (*base == MAP_FAILED) {
+            *base = *addr = nullptr;
+            err = c2_map_errno<EINVAL>(errno);
+        } else {
+            *addr = (uint8_t*)*base + alignmentBytes;
+        }
+        return err;
+    }
+
+    C2Allocator::id_t mId;
+    C2HandleBuf mHandle;
+    c2_status_t mInit;
+    struct Mapping {
+        void* addr;
+        size_t alignmentBytes;
+        size_t size;
+    };
+    std::list<Mapping> mMappings;
+
+    // TODO: we could make this encapsulate shared_ptr and copiable
+    C2_DO_NOT_COPY(C2DmaBufAllocation);
+};
+
+c2_status_t C2DmaBufAllocation::map(size_t offset, size_t size, C2MemoryUsage usage, C2Fence* fence,
+                                    void** addr) {
+    (void)fence;  // TODO: wait for fence
+    *addr = nullptr;
+    if (!mMappings.empty()) {
+        ALOGV("multiple map");
+        // TODO: technically we should return DUPLICATE here, but our block views
+        // don't actually unmap, so we end up remapping the buffer multiple times.
+        //
+        // return C2_DUPLICATE;
+    }
+    if (size == 0) {
+        return C2_BAD_VALUE;
+    }
+
+    int prot = PROT_NONE;
+    int flags = MAP_SHARED;
+    if (usage.expected & C2MemoryUsage::CPU_READ) {
+        prot |= PROT_READ;
+    }
+    if (usage.expected & C2MemoryUsage::CPU_WRITE) {
+        prot |= PROT_WRITE;
+    }
+
+    size_t alignmentBytes = offset % PAGE_SIZE;
+    size_t mapOffset = offset - alignmentBytes;
+    size_t mapSize = size + alignmentBytes;
+    Mapping map = {nullptr, alignmentBytes, mapSize};
+
+    c2_status_t err =
+            mapInternal(mapSize, mapOffset, alignmentBytes, prot, flags, &(map.addr), addr);
+    if (map.addr) {
+        mMappings.push_back(map);
+    }
+    return err;
+}
+
+c2_status_t C2DmaBufAllocation::unmap(void* addr, size_t size, C2Fence* fence) {
+    if (mMappings.empty()) {
+        ALOGD("tried to unmap unmapped buffer");
+        return C2_NOT_FOUND;
+    }
+    for (auto it = mMappings.begin(); it != mMappings.end(); ++it) {
+        if (addr != (uint8_t*)it->addr + it->alignmentBytes ||
+            size + it->alignmentBytes != it->size) {
+            continue;
+        }
+        int err = munmap(it->addr, it->size);
+        if (err != 0) {
+            ALOGD("munmap failed");
+            return c2_map_errno<EINVAL>(errno);
+        }
+        if (fence) {
+            *fence = C2Fence();  // not using fences
+        }
+        (void)mMappings.erase(it);
+        ALOGV("successfully unmapped: %d", mHandle.bufferFd());
+        return C2_OK;
+    }
+    ALOGD("unmap failed to find specified map");
+    return C2_BAD_VALUE;
+}
+
+c2_status_t C2DmaBufAllocation::status() const {
+    return mInit;
+}
+
+C2Allocator::id_t C2DmaBufAllocation::getAllocatorId() const {
+    return mId;
+}
+
+bool C2DmaBufAllocation::equals(const std::shared_ptr<C2LinearAllocation>& other) const {
+    if (!other || other->getAllocatorId() != getAllocatorId()) {
+        return false;
+    }
+    // get user handle to compare objects
+    std::shared_ptr<C2DmaBufAllocation> otherAsBuf =
+            std::static_pointer_cast<C2DmaBufAllocation>(other);
+    return mHandle.bufferFd() == otherAsBuf->mHandle.bufferFd();
+}
+
+const C2Handle* C2DmaBufAllocation::handle() const {
+    return &mHandle;
+}
+
+C2DmaBufAllocation::~C2DmaBufAllocation() {
+    if (!mMappings.empty()) {
+        ALOGD("Dangling mappings!");
+        for (const Mapping& map : mMappings) {
+            int err = munmap(map.addr, map.size);
+            if (err) ALOGD("munmap failed");
+        }
+    }
+    if (mInit == C2_OK) {
+        native_handle_close(&mHandle);
+    }
+}
+
+C2DmaBufAllocation::C2DmaBufAllocation(BufferAllocator& alloc, size_t size, C2String heap_name,
+                                       unsigned flags, C2Allocator::id_t id)
+    : C2LinearAllocation(size), mHandle(-1, 0) {
+    int bufferFd = -1;
+    int ret = 0;
+
+    bufferFd = alloc.Alloc(heap_name, size, flags);
+    if (bufferFd < 0) ret = bufferFd;
+
+    mHandle = C2HandleBuf(bufferFd, size);
+    mId = id;
+    mInit = c2_status_t(c2_map_errno<ENOMEM, EACCES, EINVAL>(ret));
+}
+
+C2DmaBufAllocation::C2DmaBufAllocation(size_t size, int shareFd, C2Allocator::id_t id)
+    : C2LinearAllocation(size), mHandle(-1, 0) {
+    mHandle = C2HandleBuf(shareFd, size);
+    mId = id;
+    mInit = c2_status_t(c2_map_errno<ENOMEM, EACCES, EINVAL>(0));
+}
+
+/* =========================== DMABUF ALLOCATOR =========================== */
+C2DmaBufAllocator::C2DmaBufAllocator(id_t id) : mInit(C2_OK) {
+    C2MemoryUsage minUsage = {0, 0};
+    C2MemoryUsage maxUsage = {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE};
+    Traits traits = {"android.allocator.dmabuf", id, LINEAR, minUsage, maxUsage};
+    mTraits = std::make_shared<Traits>(traits);
+}
+
+C2Allocator::id_t C2DmaBufAllocator::getId() const {
+    std::lock_guard<std::mutex> lock(mUsageMapperLock);
+    return mTraits->id;
+}
+
+C2String C2DmaBufAllocator::getName() const {
+    std::lock_guard<std::mutex> lock(mUsageMapperLock);
+    return mTraits->name;
+}
+
+std::shared_ptr<const C2Allocator::Traits> C2DmaBufAllocator::getTraits() const {
+    std::lock_guard<std::mutex> lock(mUsageMapperLock);
+    return mTraits;
+}
+
+void C2DmaBufAllocator::setUsageMapper(const UsageMapperFn& mapper __unused, uint64_t minUsage,
+                                       uint64_t maxUsage, uint64_t blockSize) {
+    std::lock_guard<std::mutex> lock(mUsageMapperLock);
+    mUsageMapperCache.clear();
+    mUsageMapperLru.clear();
+    mUsageMapper = mapper;
+    Traits traits = {mTraits->name, mTraits->id, LINEAR, C2MemoryUsage(minUsage),
+                     C2MemoryUsage(maxUsage)};
+    mTraits = std::make_shared<Traits>(traits);
+    mBlockSize = blockSize;
+}
+
+std::size_t C2DmaBufAllocator::MapperKeyHash::operator()(const MapperKey& k) const {
+    return std::hash<uint64_t>{}(k.first) ^ std::hash<size_t>{}(k.second);
+}
+
+c2_status_t C2DmaBufAllocator::mapUsage(C2MemoryUsage usage, size_t capacity, C2String* heap_name,
+                                        unsigned* flags) {
+    std::lock_guard<std::mutex> lock(mUsageMapperLock);
+    c2_status_t res = C2_OK;
+    // align capacity
+    capacity = (capacity + mBlockSize - 1) & ~(mBlockSize - 1);
+    MapperKey key = std::make_pair(usage.expected, capacity);
+    auto entry = mUsageMapperCache.find(key);
+    if (entry == mUsageMapperCache.end()) {
+        if (mUsageMapper) {
+            res = mUsageMapper(usage, capacity, heap_name, flags);
+        } else {
+            if (C2DmaBufAllocator::system_uncached_supported() &&
+                !(usage.expected & (C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE)))
+                *heap_name = "system-uncached";
+            else
+                *heap_name = "system";
+            *flags = 0;
+            res = C2_NO_INIT;
+        }
+        // add usage to cache
+        MapperValue value = std::make_tuple(*heap_name, *flags, res);
+        mUsageMapperLru.emplace_front(key, value);
+        mUsageMapperCache.emplace(std::make_pair(key, mUsageMapperLru.begin()));
+        if (mUsageMapperCache.size() > USAGE_LRU_CACHE_SIZE) {
+            // remove LRU entry
+            MapperKey lruKey = mUsageMapperLru.front().first;
+            mUsageMapperCache.erase(lruKey);
+            mUsageMapperLru.pop_back();
+        }
+    } else {
+        // move entry to MRU
+        mUsageMapperLru.splice(mUsageMapperLru.begin(), mUsageMapperLru, entry->second);
+        const MapperValue& value = entry->second->second;
+        std::tie(*heap_name, *flags, res) = value;
+    }
+    return res;
+}
+
+c2_status_t C2DmaBufAllocator::newLinearAllocation(
+        uint32_t capacity, C2MemoryUsage usage, std::shared_ptr<C2LinearAllocation>* allocation) {
+    if (allocation == nullptr) {
+        return C2_BAD_VALUE;
+    }
+
+    allocation->reset();
+    if (mInit != C2_OK) {
+        return mInit;
+    }
+
+    C2String heap_name;
+    unsigned flags = 0;
+    c2_status_t ret = mapUsage(usage, capacity, &heap_name, &flags);
+    if (ret && ret != C2_NO_INIT) {
+        return ret;
+    }
+
+    std::shared_ptr<C2DmaBufAllocation> alloc = std::make_shared<C2DmaBufAllocation>(
+            mBufferAllocator, capacity, heap_name, flags, getId());
+    ret = alloc->status();
+    if (ret == C2_OK) {
+        *allocation = alloc;
+    }
+    return ret;
+}
+
+c2_status_t C2DmaBufAllocator::priorLinearAllocation(
+        const C2Handle* handle, std::shared_ptr<C2LinearAllocation>* allocation) {
+    *allocation = nullptr;
+    if (mInit != C2_OK) {
+        return mInit;
+    }
+
+    if (!C2HandleBuf::IsValid(handle)) {
+        return C2_BAD_VALUE;
+    }
+
+    // TODO: get capacity and validate it
+    const C2HandleBuf* h = static_cast<const C2HandleBuf*>(handle);
+    std::shared_ptr<C2DmaBufAllocation> alloc =
+            std::make_shared<C2DmaBufAllocation>(h->size(), h->bufferFd(), getId());
+    c2_status_t ret = alloc->status();
+    if (ret == C2_OK) {
+        *allocation = alloc;
+        native_handle_delete(
+                const_cast<native_handle_t*>(reinterpret_cast<const native_handle_t*>(handle)));
+    }
+    return ret;
+}
+
+// static
+bool C2DmaBufAllocator::CheckHandle(const C2Handle* const o) {
+    return C2HandleBuf::IsValid(o);
+}
+
+}  // namespace android
diff --git a/media/codec2/vndk/C2PlatformStorePluginLoader.cpp b/media/codec2/vndk/C2PlatformStorePluginLoader.cpp
index 4c330e5..bee028a 100644
--- a/media/codec2/vndk/C2PlatformStorePluginLoader.cpp
+++ b/media/codec2/vndk/C2PlatformStorePluginLoader.cpp
@@ -33,7 +33,8 @@
 }  // unnamed
 
 C2PlatformStorePluginLoader::C2PlatformStorePluginLoader(const char *libPath)
-    : mCreateBlockPool(nullptr) {
+    : mCreateBlockPool(nullptr),
+      mCreateAllocator(nullptr) {
     mLibHandle = dlopen(libPath, RTLD_NOW | RTLD_NODELETE);
     if (mLibHandle == nullptr) {
         ALOGD("Failed to load library: %s (%s)", libPath, dlerror());
diff --git a/media/codec2/vndk/C2Store.cpp b/media/codec2/vndk/C2Store.cpp
index d16527e..c07c09e 100644
--- a/media/codec2/vndk/C2Store.cpp
+++ b/media/codec2/vndk/C2Store.cpp
@@ -21,6 +21,7 @@
 #include <C2AllocatorBlob.h>
 #include <C2AllocatorGralloc.h>
 #include <C2AllocatorIon.h>
+#include <C2DmaBufAllocator.h>
 #include <C2BufferPriv.h>
 #include <C2BqBufferPriv.h>
 #include <C2Component.h>
@@ -82,6 +83,7 @@
 
     /// returns a shared-singleton ion allocator
     std::shared_ptr<C2Allocator> fetchIonAllocator();
+    std::shared_ptr<C2Allocator> fetchDmaBufAllocator();
 
     /// returns a shared-singleton gralloc allocator
     std::shared_ptr<C2Allocator> fetchGrallocAllocator();
@@ -99,6 +101,34 @@
 C2PlatformAllocatorStoreImpl::C2PlatformAllocatorStoreImpl() {
 }
 
+static bool using_ion(void) {
+    static int cached_result = []()->int {
+        struct stat buffer;
+        int ret = (stat("/dev/ion", &buffer) == 0);
+
+        if (property_get_int32("debug.c2.use_dmabufheaps", 0)) {
+            /*
+             * Double check that the system heap is present so we
+             * can gracefully fail back to ION if we cannot satisfy
+             * the override
+             */
+            ret = (stat("/dev/dma_heap/system", &buffer) != 0);
+            if (ret)
+                ALOGE("debug.c2.use_dmabufheaps set, but no system heap. Ignoring override!");
+            else
+                ALOGD("debug.c2.use_dmabufheaps set, forcing DMABUF Heaps");
+        }
+
+        if (ret)
+            ALOGD("Using ION\n");
+        else
+            ALOGD("Using DMABUF Heaps\n");
+        return ret;
+    }();
+
+    return (cached_result == 1);
+}
+
 c2_status_t C2PlatformAllocatorStoreImpl::fetchAllocator(
         id_t id, std::shared_ptr<C2Allocator> *const allocator) {
     allocator->reset();
@@ -107,8 +137,11 @@
     }
     switch (id) {
     // TODO: should we implement a generic registry for all, and use that?
-    case C2PlatformAllocatorStore::ION:
-        *allocator = fetchIonAllocator();
+    case C2PlatformAllocatorStore::ION: /* also ::DMABUFHEAP */
+        if (using_ion())
+            *allocator = fetchIonAllocator();
+        else
+            *allocator = fetchDmaBufAllocator();
         break;
 
     case C2PlatformAllocatorStore::GRALLOC:
@@ -142,7 +175,9 @@
 namespace {
 
 std::mutex gIonAllocatorMutex;
+std::mutex gDmaBufAllocatorMutex;
 std::weak_ptr<C2AllocatorIon> gIonAllocator;
+std::weak_ptr<C2DmaBufAllocator> gDmaBufAllocator;
 
 void UseComponentStoreForIonAllocator(
         const std::shared_ptr<C2AllocatorIon> allocator,
@@ -197,6 +232,65 @@
     allocator->setUsageMapper(mapper, minUsage, maxUsage, blockSize);
 }
 
+void UseComponentStoreForDmaBufAllocator(const std::shared_ptr<C2DmaBufAllocator> allocator,
+                                         std::shared_ptr<C2ComponentStore> store) {
+    C2DmaBufAllocator::UsageMapperFn mapper;
+    const size_t maxHeapNameLen = 128;
+    uint64_t minUsage = 0;
+    uint64_t maxUsage = C2MemoryUsage(C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE).expected;
+    size_t blockSize = getpagesize();
+
+    // query min and max usage as well as block size via supported values
+    std::unique_ptr<C2StoreDmaBufUsageInfo> usageInfo;
+    usageInfo = C2StoreDmaBufUsageInfo::AllocUnique(maxHeapNameLen);
+
+    std::vector<C2FieldSupportedValuesQuery> query = {
+            C2FieldSupportedValuesQuery::Possible(C2ParamField::Make(*usageInfo, usageInfo->m.usage)),
+            C2FieldSupportedValuesQuery::Possible(
+                    C2ParamField::Make(*usageInfo, usageInfo->m.capacity)),
+    };
+    c2_status_t res = store->querySupportedValues_sm(query);
+    if (res == C2_OK) {
+        if (query[0].status == C2_OK) {
+            const C2FieldSupportedValues& fsv = query[0].values;
+            if (fsv.type == C2FieldSupportedValues::FLAGS && !fsv.values.empty()) {
+                minUsage = fsv.values[0].u64;
+                maxUsage = 0;
+                for (C2Value::Primitive v : fsv.values) {
+                    maxUsage |= v.u64;
+                }
+            }
+        }
+        if (query[1].status == C2_OK) {
+            const C2FieldSupportedValues& fsv = query[1].values;
+            if (fsv.type == C2FieldSupportedValues::RANGE && fsv.range.step.u32 > 0) {
+                blockSize = fsv.range.step.u32;
+            }
+        }
+
+        mapper = [store](C2MemoryUsage usage, size_t capacity, C2String* heapName,
+                         unsigned* flags) -> c2_status_t {
+            if (capacity > UINT32_MAX) {
+                return C2_BAD_VALUE;
+            }
+
+            std::unique_ptr<C2StoreDmaBufUsageInfo> usageInfo;
+            usageInfo = C2StoreDmaBufUsageInfo::AllocUnique(maxHeapNameLen, usage.expected, capacity);
+            std::vector<std::unique_ptr<C2SettingResult>> failures;  // TODO: remove
+
+            c2_status_t res = store->config_sm({&*usageInfo}, &failures);
+            if (res == C2_OK) {
+                *heapName = C2String(usageInfo->m.heapName);
+                *flags = usageInfo->m.allocFlags;
+            }
+
+            return res;
+        };
+    }
+
+    allocator->setUsageMapper(mapper, minUsage, maxUsage, blockSize);
+}
+
 }
 
 void C2PlatformAllocatorStoreImpl::setComponentStore(std::shared_ptr<C2ComponentStore> store) {
@@ -233,6 +327,22 @@
     return allocator;
 }
 
+std::shared_ptr<C2Allocator> C2PlatformAllocatorStoreImpl::fetchDmaBufAllocator() {
+    std::lock_guard<std::mutex> lock(gDmaBufAllocatorMutex);
+    std::shared_ptr<C2DmaBufAllocator> allocator = gDmaBufAllocator.lock();
+    if (allocator == nullptr) {
+        std::shared_ptr<C2ComponentStore> componentStore;
+        {
+            std::lock_guard<std::mutex> lock(_mComponentStoreReadLock);
+            componentStore = _mComponentStore;
+        }
+        allocator = std::make_shared<C2DmaBufAllocator>(C2PlatformAllocatorStore::DMABUFHEAP);
+        UseComponentStoreForDmaBufAllocator(allocator, componentStore);
+        gDmaBufAllocator = allocator;
+    }
+    return allocator;
+}
+
 std::shared_ptr<C2Allocator> C2PlatformAllocatorStoreImpl::fetchBlobAllocator() {
     static std::mutex mutex;
     static std::weak_ptr<C2Allocator> blobAllocator;
@@ -335,7 +445,7 @@
 
     c2_status_t _createBlockPool(
             C2PlatformAllocatorStore::id_t allocatorId,
-            std::shared_ptr<const C2Component> component,
+            std::vector<std::shared_ptr<const C2Component>> components,
             C2BlockPool::local_id_t poolId,
             std::shared_ptr<C2BlockPool> *pool) {
         std::shared_ptr<C2AllocatorStore> allocatorStore =
@@ -347,7 +457,7 @@
             allocatorId = GetPreferredLinearAllocatorId(GetCodec2PoolMask());
         }
         switch(allocatorId) {
-            case C2PlatformAllocatorStore::ION:
+            case C2PlatformAllocatorStore::ION: /* also ::DMABUFHEAP */
                 res = allocatorStore->fetchAllocator(
                         C2PlatformAllocatorStore::ION, &allocator);
                 if (res == C2_OK) {
@@ -356,7 +466,9 @@
                                     allocator, poolId);
                     *pool = ptr;
                     mBlockPools[poolId] = ptr;
-                    mComponents[poolId] = component;
+                    mComponents[poolId].insert(
+                           mComponents[poolId].end(),
+                           components.begin(), components.end());
                 }
                 break;
             case C2PlatformAllocatorStore::BLOB:
@@ -368,7 +480,9 @@
                                     allocator, poolId);
                     *pool = ptr;
                     mBlockPools[poolId] = ptr;
-                    mComponents[poolId] = component;
+                    mComponents[poolId].insert(
+                           mComponents[poolId].end(),
+                           components.begin(), components.end());
                 }
                 break;
             case C2PlatformAllocatorStore::GRALLOC:
@@ -380,7 +494,9 @@
                         std::make_shared<C2PooledBlockPool>(allocator, poolId);
                     *pool = ptr;
                     mBlockPools[poolId] = ptr;
-                    mComponents[poolId] = component;
+                    mComponents[poolId].insert(
+                           mComponents[poolId].end(),
+                           components.begin(), components.end());
                 }
                 break;
             case C2PlatformAllocatorStore::BUFFERQUEUE:
@@ -392,7 +508,9 @@
                                     allocator, poolId);
                     *pool = ptr;
                     mBlockPools[poolId] = ptr;
-                    mComponents[poolId] = component;
+                    mComponents[poolId].insert(
+                           mComponents[poolId].end(),
+                           components.begin(), components.end());
                 }
                 break;
             default:
@@ -403,7 +521,9 @@
                 if (res == C2_OK) {
                     *pool = ptr;
                     mBlockPools[poolId] = ptr;
-                    mComponents[poolId] = component;
+                    mComponents[poolId].insert(
+                           mComponents[poolId].end(),
+                           components.begin(), components.end());
                 }
                 break;
         }
@@ -412,9 +532,9 @@
 
     c2_status_t createBlockPool(
             C2PlatformAllocatorStore::id_t allocatorId,
-            std::shared_ptr<const C2Component> component,
+            std::vector<std::shared_ptr<const C2Component>> components,
             std::shared_ptr<C2BlockPool> *pool) {
-        return _createBlockPool(allocatorId, component, mBlockPoolSeqId++, pool);
+        return _createBlockPool(allocatorId, components, mBlockPoolSeqId++, pool);
     }
 
     bool getBlockPool(
@@ -430,8 +550,13 @@
                 mBlockPools.erase(it);
                 mComponents.erase(blockPoolId);
             } else {
-                auto found = mComponents.find(blockPoolId);
-                if (component == found->second.lock()) {
+                auto found = std::find_if(
+                        mComponents[blockPoolId].begin(),
+                        mComponents[blockPoolId].end(),
+                        [component](const std::weak_ptr<const C2Component> &ptr) {
+                            return component == ptr.lock();
+                        });
+                if (found != mComponents[blockPoolId].end()) {
                     *pool = ptr;
                     return true;
                 }
@@ -444,7 +569,7 @@
     C2BlockPool::local_id_t mBlockPoolSeqId;
 
     std::map<C2BlockPool::local_id_t, std::weak_ptr<C2BlockPool>> mBlockPools;
-    std::map<C2BlockPool::local_id_t, std::weak_ptr<const C2Component>> mComponents;
+    std::map<C2BlockPool::local_id_t, std::vector<std::weak_ptr<const C2Component>>> mComponents;
 };
 
 static std::unique_ptr<_C2BlockPoolCache> sBlockPoolCache =
@@ -484,7 +609,7 @@
     // TODO: remove this. this is temporary
     case C2BlockPool::PLATFORM_START:
         res = sBlockPoolCache->_createBlockPool(
-                C2PlatformAllocatorStore::BUFFERQUEUE, component, id, pool);
+                C2PlatformAllocatorStore::BUFFERQUEUE, {component}, id, pool);
         break;
     default:
         break;
@@ -494,12 +619,22 @@
 
 c2_status_t CreateCodec2BlockPool(
         C2PlatformAllocatorStore::id_t allocatorId,
+        const std::vector<std::shared_ptr<const C2Component>> &components,
+        std::shared_ptr<C2BlockPool> *pool) {
+    pool->reset();
+
+    std::lock_guard<std::mutex> lock(sBlockPoolCacheMutex);
+    return sBlockPoolCache->createBlockPool(allocatorId, components, pool);
+}
+
+c2_status_t CreateCodec2BlockPool(
+        C2PlatformAllocatorStore::id_t allocatorId,
         std::shared_ptr<const C2Component> component,
         std::shared_ptr<C2BlockPool> *pool) {
     pool->reset();
 
     std::lock_guard<std::mutex> lock(sBlockPoolCacheMutex);
-    return sBlockPoolCache->createBlockPool(allocatorId, component, pool);
+    return sBlockPoolCache->createBlockPool(allocatorId, {component}, pool);
 }
 
 class C2PlatformComponentStore : public C2ComponentStore {
@@ -526,6 +661,12 @@
             std::vector<std::unique_ptr<C2SettingResult>> *const failures) override;
     C2PlatformComponentStore();
 
+    // For testing only
+    C2PlatformComponentStore(
+            std::vector<std::tuple<C2String,
+                                   C2ComponentFactory::CreateCodec2FactoryFunc,
+                                   C2ComponentFactory::DestroyCodec2FactoryFunc>>);
+
     virtual ~C2PlatformComponentStore() override = default;
 
 private:
@@ -566,6 +707,24 @@
         }
 
         /**
+         * Creates an uninitialized component module.
+         * NOTE: For testing only
+         *
+         * \param name[in]  component name.
+         *
+         * \note Only used by ComponentLoader.
+         */
+        ComponentModule(
+                C2ComponentFactory::CreateCodec2FactoryFunc createFactory,
+                C2ComponentFactory::DestroyCodec2FactoryFunc destroyFactory)
+            : mInit(C2_NO_INIT),
+              mLibHandle(nullptr),
+              createFactory(createFactory),
+              destroyFactory(destroyFactory),
+              mComponentFactory(nullptr) {
+        }
+
+        /**
          * Initializes a component module with a given library path. Must be called exactly once.
          *
          * \note Only used by ComponentLoader.
@@ -621,7 +780,13 @@
             std::lock_guard<std::mutex> lock(mMutex);
             std::shared_ptr<ComponentModule> localModule = mModule.lock();
             if (localModule == nullptr) {
-                localModule = std::make_shared<ComponentModule>();
+                if(mCreateFactory) {
+                    // For testing only
+                    localModule = std::make_shared<ComponentModule>(mCreateFactory,
+                                                                    mDestroyFactory);
+                } else {
+                    localModule = std::make_shared<ComponentModule>();
+                }
                 res = localModule->init(mLibPath);
                 if (res == C2_OK) {
                     mModule = localModule;
@@ -637,14 +802,27 @@
         ComponentLoader(std::string libPath)
             : mLibPath(libPath) {}
 
+        // For testing only
+        ComponentLoader(std::tuple<C2String,
+                          C2ComponentFactory::CreateCodec2FactoryFunc,
+                          C2ComponentFactory::DestroyCodec2FactoryFunc> func)
+            : mLibPath(std::get<0>(func)),
+              mCreateFactory(std::get<1>(func)),
+              mDestroyFactory(std::get<2>(func)) {}
+
     private:
         std::mutex mMutex; ///< mutex guarding the module
         std::weak_ptr<ComponentModule> mModule; ///< weak reference to the loaded module
         std::string mLibPath; ///< library path
+
+        // For testing only
+        C2ComponentFactory::CreateCodec2FactoryFunc mCreateFactory = nullptr;
+        C2ComponentFactory::DestroyCodec2FactoryFunc mDestroyFactory = nullptr;
     };
 
     struct Interface : public C2InterfaceHelper {
         std::shared_ptr<C2StoreIonUsageInfo> mIonUsageInfo;
+        std::shared_ptr<C2StoreDmaBufUsageInfo> mDmaBufUsageInfo;
 
         Interface(std::shared_ptr<C2ReflectorHelper> reflector)
             : C2InterfaceHelper(reflector) {
@@ -680,7 +858,19 @@
                     me.set().minAlignment = 0;
 #endif
                     return C2R::Ok();
-                }
+                };
+
+                static C2R setDmaBufUsage(bool /* mayBlock */, C2P<C2StoreDmaBufUsageInfo> &me) {
+                    long long usage = (long long)me.get().m.usage;
+                    if (C2DmaBufAllocator::system_uncached_supported() &&
+                        !(usage & (C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE))) {
+                        strncpy(me.set().m.heapName, "system-uncached", me.v.flexCount());
+                    } else {
+                        strncpy(me.set().m.heapName, "system", me.v.flexCount());
+                    }
+                    me.set().m.allocFlags = 0;
+                    return C2R::Ok();
+                };
             };
 
             addParameter(
@@ -695,6 +885,18 @@
                 })
                 .withSetter(Setter::setIonUsage)
                 .build());
+
+            addParameter(
+                DefineParam(mDmaBufUsageInfo, "dmabuf-usage")
+                .withDefault(C2StoreDmaBufUsageInfo::AllocShared(0))
+                .withFields({
+                    C2F(mDmaBufUsageInfo, m.usage).flags({C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE}),
+                    C2F(mDmaBufUsageInfo, m.capacity).inRange(0, UINT32_MAX, 1024),
+                    C2F(mDmaBufUsageInfo, m.allocFlags).flags({}),
+                    C2F(mDmaBufUsageInfo, m.heapName).any(),
+                })
+                .withSetter(Setter::setDmaBufUsage)
+                .build());
         }
     };
 
@@ -731,25 +933,33 @@
 
     std::shared_ptr<C2ReflectorHelper> mReflector;
     Interface mInterface;
+
+    // For testing only
+    std::vector<std::tuple<C2String,
+                          C2ComponentFactory::CreateCodec2FactoryFunc,
+                          C2ComponentFactory::DestroyCodec2FactoryFunc>> mCodec2FactoryFuncs;
 };
 
 c2_status_t C2PlatformComponentStore::ComponentModule::init(
         std::string libPath) {
     ALOGV("in %s", __func__);
     ALOGV("loading dll");
-    mLibHandle = dlopen(libPath.c_str(), RTLD_NOW|RTLD_NODELETE);
-    LOG_ALWAYS_FATAL_IF(mLibHandle == nullptr,
-            "could not dlopen %s: %s", libPath.c_str(), dlerror());
 
-    createFactory =
-        (C2ComponentFactory::CreateCodec2FactoryFunc)dlsym(mLibHandle, "CreateCodec2Factory");
-    LOG_ALWAYS_FATAL_IF(createFactory == nullptr,
-            "createFactory is null in %s", libPath.c_str());
+    if(!createFactory) {
+        mLibHandle = dlopen(libPath.c_str(), RTLD_NOW|RTLD_NODELETE);
+        LOG_ALWAYS_FATAL_IF(mLibHandle == nullptr,
+                "could not dlopen %s: %s", libPath.c_str(), dlerror());
 
-    destroyFactory =
-        (C2ComponentFactory::DestroyCodec2FactoryFunc)dlsym(mLibHandle, "DestroyCodec2Factory");
-    LOG_ALWAYS_FATAL_IF(destroyFactory == nullptr,
-            "destroyFactory is null in %s", libPath.c_str());
+        createFactory =
+            (C2ComponentFactory::CreateCodec2FactoryFunc)dlsym(mLibHandle, "CreateCodec2Factory");
+        LOG_ALWAYS_FATAL_IF(createFactory == nullptr,
+                "createFactory is null in %s", libPath.c_str());
+
+        destroyFactory =
+            (C2ComponentFactory::DestroyCodec2FactoryFunc)dlsym(mLibHandle, "DestroyCodec2Factory");
+        LOG_ALWAYS_FATAL_IF(destroyFactory == nullptr,
+                "destroyFactory is null in %s", libPath.c_str());
+    }
 
     mComponentFactory = createFactory();
     if (mComponentFactory == nullptr) {
@@ -772,58 +982,10 @@
 
     std::shared_ptr<C2Component::Traits> traits(new (std::nothrow) C2Component::Traits);
     if (traits) {
-        traits->name = intf->getName();
-
-        C2ComponentKindSetting kind;
-        C2ComponentDomainSetting domain;
-        res = intf->query_vb({ &kind, &domain }, {}, C2_MAY_BLOCK, nullptr);
-        bool fixDomain = res != C2_OK;
-        if (res == C2_OK) {
-            traits->kind = kind.value;
-            traits->domain = domain.value;
-        } else {
-            // TODO: remove this fall-back
-            ALOGD("failed to query interface for kind and domain: %d", res);
-
-            traits->kind =
-                (traits->name.find("encoder") != std::string::npos) ? C2Component::KIND_ENCODER :
-                (traits->name.find("decoder") != std::string::npos) ? C2Component::KIND_DECODER :
-                C2Component::KIND_OTHER;
-        }
-
-        uint32_t mediaTypeIndex =
-                traits->kind == C2Component::KIND_ENCODER ? C2PortMediaTypeSetting::output::PARAM_TYPE
-                : C2PortMediaTypeSetting::input::PARAM_TYPE;
-        std::vector<std::unique_ptr<C2Param>> params;
-        res = intf->query_vb({}, { mediaTypeIndex }, C2_MAY_BLOCK, &params);
-        if (res != C2_OK) {
-            ALOGD("failed to query interface: %d", res);
+        if (!C2InterfaceUtils::FillTraitsFromInterface(traits.get(), intf)) {
+            ALOGD("Failed to fill traits from interface");
             return mInit;
         }
-        if (params.size() != 1u) {
-            ALOGD("failed to query interface: unexpected vector size: %zu", params.size());
-            return mInit;
-        }
-        C2PortMediaTypeSetting *mediaTypeConfig = C2PortMediaTypeSetting::From(params[0].get());
-        if (mediaTypeConfig == nullptr) {
-            ALOGD("failed to query media type");
-            return mInit;
-        }
-        traits->mediaType =
-            std::string(mediaTypeConfig->m.value,
-                        strnlen(mediaTypeConfig->m.value, mediaTypeConfig->flexCount()));
-
-        if (fixDomain) {
-            if (strncmp(traits->mediaType.c_str(), "audio/", 6) == 0) {
-                traits->domain = C2Component::DOMAIN_AUDIO;
-            } else if (strncmp(traits->mediaType.c_str(), "video/", 6) == 0) {
-                traits->domain = C2Component::DOMAIN_VIDEO;
-            } else if (strncmp(traits->mediaType.c_str(), "image/", 6) == 0) {
-                traits->domain = C2Component::DOMAIN_IMAGE;
-            } else {
-                traits->domain = C2Component::DOMAIN_OTHER;
-            }
-        }
 
         // TODO: get this properly from the store during emplace
         switch (traits->domain) {
@@ -833,26 +995,6 @@
         default:
             traits->rank = 512;
         }
-
-        params.clear();
-        res = intf->query_vb({}, { C2ComponentAliasesSetting::PARAM_TYPE }, C2_MAY_BLOCK, &params);
-        if (res == C2_OK && params.size() == 1u) {
-            C2ComponentAliasesSetting *aliasesSetting =
-                C2ComponentAliasesSetting::From(params[0].get());
-            if (aliasesSetting) {
-                // Split aliases on ','
-                // This looks simpler in plain C and even std::string would still make a copy.
-                char *aliases = ::strndup(aliasesSetting->m.value, aliasesSetting->flexCount());
-                ALOGD("'%s' has aliases: '%s'", intf->getName().c_str(), aliases);
-
-                for (char *tok, *ptr, *str = aliases; (tok = ::strtok_r(str, ",", &ptr));
-                        str = nullptr) {
-                    traits->aliases.push_back(tok);
-                    ALOGD("adding alias: '%s'", tok);
-                }
-                free(aliases);
-            }
-        }
     }
     mTraits = traits;
 
@@ -950,6 +1092,22 @@
     emplace("libcodec2_soft_vp8enc.so");
     emplace("libcodec2_soft_vp9dec.so");
     emplace("libcodec2_soft_vp9enc.so");
+
+}
+
+// For testing only
+C2PlatformComponentStore::C2PlatformComponentStore(
+    std::vector<std::tuple<C2String,
+                C2ComponentFactory::CreateCodec2FactoryFunc,
+                C2ComponentFactory::DestroyCodec2FactoryFunc>> funcs)
+    : mVisited(false),
+      mReflector(std::make_shared<C2ReflectorHelper>()),
+      mInterface(mReflector),
+      mCodec2FactoryFuncs(funcs) {
+
+    for(auto const& func: mCodec2FactoryFuncs) {
+        mComponents.emplace(std::get<0>(func), func);
+    }
 }
 
 c2_status_t C2PlatformComponentStore::copyBuffer(
@@ -1069,4 +1227,11 @@
     return store;
 }
 
+// For testing only
+std::shared_ptr<C2ComponentStore> GetTestComponentStore(
+        std::vector<std::tuple<C2String,
+        C2ComponentFactory::CreateCodec2FactoryFunc,
+        C2ComponentFactory::DestroyCodec2FactoryFunc>> funcs) {
+    return std::shared_ptr<C2ComponentStore>(new C2PlatformComponentStore(funcs));
+}
 } // namespace android
diff --git a/media/codec2/vndk/include/C2AllocatorBlob.h b/media/codec2/vndk/include/C2AllocatorBlob.h
index 89ce949..fc67af7 100644
--- a/media/codec2/vndk/include/C2AllocatorBlob.h
+++ b/media/codec2/vndk/include/C2AllocatorBlob.h
@@ -44,7 +44,12 @@
 
     virtual ~C2AllocatorBlob() override;
 
-    static bool isValid(const C2Handle* const o);
+    virtual bool checkHandle(const C2Handle* const o) const override { return CheckHandle(o); }
+
+    static bool CheckHandle(const C2Handle* const o);
+
+    // deprecated
+    static bool isValid(const C2Handle* const o) { return CheckHandle(o); }
 
 private:
     std::shared_ptr<const Traits> mTraits;
diff --git a/media/codec2/vndk/include/C2AllocatorGralloc.h b/media/codec2/vndk/include/C2AllocatorGralloc.h
index ee7524e..578cf76 100644
--- a/media/codec2/vndk/include/C2AllocatorGralloc.h
+++ b/media/codec2/vndk/include/C2AllocatorGralloc.h
@@ -84,7 +84,12 @@
 
     virtual ~C2AllocatorGralloc() override;
 
-    static bool isValid(const C2Handle* const o);
+    virtual bool checkHandle(const C2Handle* const o) const override { return CheckHandle(o); }
+
+    static bool CheckHandle(const C2Handle* const o);
+
+    // deprecated
+    static bool isValid(const C2Handle* const o) { return CheckHandle(o); }
 
 private:
     class Impl;
diff --git a/media/codec2/vndk/include/C2AllocatorIon.h b/media/codec2/vndk/include/C2AllocatorIon.h
index 1b2051f..6a49b7d 100644
--- a/media/codec2/vndk/include/C2AllocatorIon.h
+++ b/media/codec2/vndk/include/C2AllocatorIon.h
@@ -57,7 +57,12 @@
 
     virtual ~C2AllocatorIon() override;
 
-    static bool isValid(const C2Handle* const o);
+    virtual bool checkHandle(const C2Handle* const o) const override { return CheckHandle(o); }
+
+    static bool CheckHandle(const C2Handle* const o);
+
+    // deprecated
+    static bool isValid(const C2Handle* const o) { return CheckHandle(o); }
 
     /**
      * Updates the usage mapper for subsequent new allocations, as well as the supported
diff --git a/media/codec2/vndk/include/C2DmaBufAllocator.h b/media/codec2/vndk/include/C2DmaBufAllocator.h
new file mode 100644
index 0000000..d84c8c6
--- /dev/null
+++ b/media/codec2/vndk/include/C2DmaBufAllocator.h
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2020 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_ALLOCATOR_BUF_H_
+#define STAGEFRIGHT_CODEC2_ALLOCATOR_BUF_H_
+
+#include <BufferAllocator/BufferAllocator.h>
+#include <C2Buffer.h>
+#include <sys/stat.h>  // stat
+
+#include <functional>
+#include <list>
+#include <mutex>
+#include <tuple>
+#include <unordered_map>
+
+namespace android {
+
+class C2DmaBufAllocator : public C2Allocator {
+   public:
+    virtual c2_status_t newLinearAllocation(
+            uint32_t capacity, C2MemoryUsage usage,
+            std::shared_ptr<C2LinearAllocation>* allocation) override;
+
+    virtual c2_status_t priorLinearAllocation(
+            const C2Handle* handle, std::shared_ptr<C2LinearAllocation>* allocation) override;
+
+    C2DmaBufAllocator(id_t id);
+
+    virtual c2_status_t status() const { return mInit; }
+
+    virtual bool checkHandle(const C2Handle* const o) const override { return CheckHandle(o); }
+
+    static bool CheckHandle(const C2Handle* const o);
+
+    virtual id_t getId() const override;
+
+    virtual C2String getName() const override;
+
+    virtual std::shared_ptr<const Traits> getTraits() const override;
+
+    // Usage mapper function used by the allocator
+    //   (usage, capacity) => (heapName, flags)
+    //
+    // capacity is aligned to the default block-size (defaults to page size) to
+    // reduce caching overhead
+    typedef std::function<c2_status_t(C2MemoryUsage, size_t,
+                                      /* => */ C2String*, unsigned*)>
+            UsageMapperFn;
+
+    /**
+     * Updates the usage mapper for subsequent new allocations, as well as the
+     * supported minimum and maximum usage masks and default block-size to use
+     * for the mapper.
+     *
+     * \param mapper          This method is called to map Codec 2.0 buffer usage
+     *                        to dmabuf heap name and flags required by the dma
+     *                        buf heap device
+     *
+     * \param minUsage        Minimum buffer usage required for supported
+     *                        allocations (defaults to 0)
+     *
+     * \param maxUsage        Maximum buffer usage supported by the ion allocator
+     *                        (defaults to SW_READ | SW_WRITE)
+     *
+     * \param blockSize       Alignment used prior to calling |mapper| for the
+     *                        buffer capacity. This also helps reduce the size of
+     *                        cache required for caching mapper results.
+     *                        (defaults to the page size)
+     */
+    void setUsageMapper(const UsageMapperFn& mapper, uint64_t minUsage, uint64_t maxUsage,
+                        uint64_t blockSize);
+
+    static bool system_uncached_supported(void) {
+        static int cached_result = -1;
+
+        if (cached_result == -1) {
+            struct stat buffer;
+            cached_result = (stat("/dev/dma_heap/system-uncached", &buffer) == 0);
+        }
+        return (cached_result == 1);
+    };
+
+   private:
+    c2_status_t mInit;
+    BufferAllocator mBufferAllocator;
+
+    c2_status_t mapUsage(C2MemoryUsage usage, size_t size,
+                         /* => */ C2String* heap_name, unsigned* flags);
+
+    // this locks mTraits, mBlockSize, mUsageMapper, mUsageMapperLru and
+    // mUsageMapperCache
+    mutable std::mutex mUsageMapperLock;
+    std::shared_ptr<const Traits> mTraits;
+    size_t mBlockSize;
+    UsageMapperFn mUsageMapper;
+    typedef std::pair<uint64_t, size_t> MapperKey;
+    struct MapperKeyHash {
+        std::size_t operator()(const MapperKey&) const;
+    };
+    typedef std::tuple<C2String, unsigned, c2_status_t> MapperValue;
+    typedef std::pair<MapperKey, MapperValue> MapperKeyValue;
+    typedef std::list<MapperKeyValue>::iterator MapperKeyValuePointer;
+    std::list<MapperKeyValue> mUsageMapperLru;
+    std::unordered_map<MapperKey, MapperKeyValuePointer, MapperKeyHash> mUsageMapperCache;
+};
+}  // namespace android
+
+#endif  // STAGEFRIGHT_CODEC2_ALLOCATOR_BUF_H_
diff --git a/media/codec2/vndk/include/C2PlatformSupport.h b/media/codec2/vndk/include/C2PlatformSupport.h
index a14e0d3..dc82e82 100644
--- a/media/codec2/vndk/include/C2PlatformSupport.h
+++ b/media/codec2/vndk/include/C2PlatformSupport.h
@@ -47,6 +47,17 @@
          */
         ION = PLATFORM_START,
 
+        /*
+         * ID of the DMA-Buf Heap (ion replacement) backed platform allocator.
+         *
+         * C2Handle consists of:
+         *   fd  shared dmabuf buffer handle
+         *   int size (lo 32 bits)
+         *   int size (hi 32 bits)
+         *   int magic '\xc2io\x00'
+         */
+        DMABUFHEAP = ION,
+
         /**
          * ID of the gralloc backed platform allocator.
          *
@@ -127,12 +138,38 @@
         std::shared_ptr<C2BlockPool> *pool);
 
 /**
+ * Creates a block pool.
+ * \param allocatorId  the allocator ID which is used to allocate blocks
+ * \param components    the components using the block pool
+ * \param pool          pointer to where the created block pool shall be store on success.
+ *                      nullptr will be stored here on failure
+ *
+ * \retval C2_OK        the operation was successful
+ * \retval C2_BAD_VALUE the component is null
+ * \retval C2_NOT_FOUND if the allocator does not exist
+ * \retval C2_NO_MEMORY not enough memory to create a block pool
+ */
+c2_status_t CreateCodec2BlockPool(
+        C2PlatformAllocatorStore::id_t allocatorId,
+        const std::vector<std::shared_ptr<const C2Component>> &components,
+        std::shared_ptr<C2BlockPool> *pool);
+
+/**
  * Returns the platform component store.
  * \retval nullptr if the platform component store could not be obtained
  */
 std::shared_ptr<C2ComponentStore> GetCodec2PlatformComponentStore();
 
 /**
+ * Returns the platform component store.
+ * NOTE: For testing only
+ * \retval nullptr if the platform component store could not be obtained
+ */
+std::shared_ptr<C2ComponentStore> GetTestComponentStore(
+        std::vector<std::tuple<C2String, C2ComponentFactory::CreateCodec2FactoryFunc,
+        C2ComponentFactory::DestroyCodec2FactoryFunc>>);
+
+/**
  * Sets the preferred component store in this process for the sole purpose of accessing its
  * interface. If this is not called, the default IComponentStore HAL (if exists) is the preferred
  * store for this purpose. If the default IComponentStore HAL is not present, the platform
diff --git a/media/codec2/vndk/include/util/C2InterfaceUtils.h b/media/codec2/vndk/include/util/C2InterfaceUtils.h
index e9037e5..13bdac3 100644
--- a/media/codec2/vndk/include/util/C2InterfaceUtils.h
+++ b/media/codec2/vndk/include/util/C2InterfaceUtils.h
@@ -17,6 +17,7 @@
 #ifndef C2UTILS_INTERFACE_UTILS_H_
 #define C2UTILS_INTERFACE_UTILS_H_
 
+#include <C2Component.h>
 #include <C2Param.h>
 #include <C2Work.h>
 
@@ -1130,6 +1131,19 @@
 
 };
 
+/**
+ * Utility class for C2ComponentInterface
+ */
+struct C2InterfaceUtils {
+    /**
+     * Create traits from C2ComponentInterface. Note that rank cannot be queried from interfaces,
+     * so left untouched.
+     */
+    static bool FillTraitsFromInterface(
+            C2Component::Traits *traits,
+            const std::shared_ptr<C2ComponentInterface> &intf);
+};
+
 #include <util/C2Debug-interface.h>
 
 #endif  // C2UTILS_INTERFACE_UTILS_H_
diff --git a/media/codec2/vndk/internal/C2HandleIonInternal.h b/media/codec2/vndk/internal/C2HandleIonInternal.h
index c0e1d83..c67698c 100644
--- a/media/codec2/vndk/internal/C2HandleIonInternal.h
+++ b/media/codec2/vndk/internal/C2HandleIonInternal.h
@@ -28,7 +28,10 @@
           mFds{ bufferFd },
           mInts{ int(size & 0xFFFFFFFF), int((uint64_t(size) >> 32) & 0xFFFFFFFF), kMagic } { }
 
-    static bool isValid(const C2Handle * const o);
+    static bool IsValid(const C2Handle * const o);
+
+    // deprecated
+    static bool isValid(const C2Handle * const o) { return IsValid(o); }
 
     int bufferFd() const { return mFds.mBuffer; }
     size_t size() const {
diff --git a/media/codec2/vndk/platform/C2BqBuffer.cpp b/media/codec2/vndk/platform/C2BqBuffer.cpp
index 62936f6..fff12c4 100644
--- a/media/codec2/vndk/platform/C2BqBuffer.cpp
+++ b/media/codec2/vndk/platform/C2BqBuffer.cpp
@@ -223,7 +223,7 @@
     static std::unique_ptr<C2AllocatorGralloc> sAllocator = std::make_unique<C2AllocatorGralloc>(0);
 
     std::shared_ptr<C2GraphicAllocation> alloc;
-    if (C2AllocatorGralloc::isValid(handle)) {
+    if (C2AllocatorGralloc::CheckHandle(handle)) {
         uint32_t width;
         uint32_t height;
         uint32_t format;
diff --git a/media/codec2/vndk/util/C2InterfaceHelper.cpp b/media/codec2/vndk/util/C2InterfaceHelper.cpp
index 9eb52d2..19d2295 100644
--- a/media/codec2/vndk/util/C2InterfaceHelper.cpp
+++ b/media/codec2/vndk/util/C2InterfaceHelper.cpp
@@ -645,6 +645,7 @@
                     lateReadParams.emplace_back(p);
                     std::unique_ptr<C2Param> request(C2Param::CopyAsRequest(*p));
                     p = request.get();
+                    paramIx = p->index();
                     paramRequests.emplace_back(std::move(request));
                 }
             }
diff --git a/media/codec2/vndk/util/C2InterfaceUtils.cpp b/media/codec2/vndk/util/C2InterfaceUtils.cpp
index 0c1729b..b5bc691 100644
--- a/media/codec2/vndk/util/C2InterfaceUtils.cpp
+++ b/media/codec2/vndk/util/C2InterfaceUtils.cpp
@@ -21,6 +21,7 @@
 
 #define C2_LOG_VERBOSE
 
+#include <C2Config.h>
 #include <C2Debug.h>
 #include <C2Param.h>
 #include <C2ParamDef.h>
@@ -30,6 +31,7 @@
 #include <cmath>
 #include <limits>
 #include <map>
+#include <sstream>
 #include <type_traits>
 
 #include <android-base/stringprintf.h>
@@ -1304,3 +1306,81 @@
     return std::vector<Info>(location.begin(), location.end());
 }
 
+//static
+bool C2InterfaceUtils::FillTraitsFromInterface(
+        C2Component::Traits *traits,
+        const std::shared_ptr<C2ComponentInterface> &intf) {
+    if (!traits) {
+        return false;
+    }
+    traits->name = intf->getName();
+
+    C2ComponentKindSetting kind;
+    C2ComponentDomainSetting domain;
+    c2_status_t res = intf->query_vb({ &kind, &domain }, {}, C2_MAY_BLOCK, nullptr);
+    bool fixDomain = res != C2_OK;
+    if (res == C2_OK) {
+        traits->kind = kind.value;
+        traits->domain = domain.value;
+    } else {
+        // TODO: remove this fall-back
+        C2_LOG(DEBUG) << "failed to query interface for kind and domain: " << res;
+
+        traits->kind =
+            (traits->name.find("encoder") != std::string::npos) ? C2Component::KIND_ENCODER :
+            (traits->name.find("decoder") != std::string::npos) ? C2Component::KIND_DECODER :
+            C2Component::KIND_OTHER;
+    }
+
+    uint32_t mediaTypeIndex = traits->kind == C2Component::KIND_ENCODER
+            ? C2PortMediaTypeSetting::output::PARAM_TYPE
+            : C2PortMediaTypeSetting::input::PARAM_TYPE;
+    std::vector<std::unique_ptr<C2Param>> params;
+    res = intf->query_vb({}, { mediaTypeIndex }, C2_MAY_BLOCK, &params);
+    if (res != C2_OK) {
+        C2_LOG(DEBUG) << "failed to query interface: " << res;
+        return false;
+    }
+    if (params.size() != 1u) {
+        C2_LOG(DEBUG) << "failed to query interface: unexpected vector size: " << params.size();
+        return false;
+    }
+    C2PortMediaTypeSetting *mediaTypeConfig = C2PortMediaTypeSetting::From(params[0].get());
+    if (mediaTypeConfig == nullptr) {
+        C2_LOG(DEBUG) << "failed to query media type";
+        return false;
+    }
+    traits->mediaType =
+        std::string(mediaTypeConfig->m.value,
+                    strnlen(mediaTypeConfig->m.value, mediaTypeConfig->flexCount()));
+
+    if (fixDomain) {
+        if (strncmp(traits->mediaType.c_str(), "audio/", 6) == 0) {
+            traits->domain = C2Component::DOMAIN_AUDIO;
+        } else if (strncmp(traits->mediaType.c_str(), "video/", 6) == 0) {
+            traits->domain = C2Component::DOMAIN_VIDEO;
+        } else if (strncmp(traits->mediaType.c_str(), "image/", 6) == 0) {
+            traits->domain = C2Component::DOMAIN_IMAGE;
+        } else {
+            traits->domain = C2Component::DOMAIN_OTHER;
+        }
+    }
+
+    params.clear();
+    res = intf->query_vb({}, { C2ComponentAliasesSetting::PARAM_TYPE }, C2_MAY_BLOCK, &params);
+    if (res == C2_OK && params.size() == 1u) {
+        C2ComponentAliasesSetting *aliasesSetting =
+            C2ComponentAliasesSetting::From(params[0].get());
+        if (aliasesSetting) {
+            std::istringstream iss(
+                    std::string(aliasesSetting->m.value, aliasesSetting->flexCount()));
+            C2_LOG(DEBUG) << intf->getName() << " has aliases: " << iss.str();
+
+            for (std::string tok; std::getline(iss, tok, ','); ) {
+                traits->aliases.push_back(tok);
+                C2_LOG(DEBUG) << "adding alias: " << tok;
+            }
+        }
+    }
+    return true;
+}
diff --git a/media/codecs/amrnb/TEST_MAPPING b/media/codecs/amrnb/TEST_MAPPING
new file mode 100644
index 0000000..343d08a
--- /dev/null
+++ b/media/codecs/amrnb/TEST_MAPPING
@@ -0,0 +1,10 @@
+// mappings for frameworks/av/media/libstagefright/codecs/amrnb
+{
+  // tests which require dynamic content
+  // invoke with: atest -- --enable-module-dynamic-download=true
+  // TODO(b/148094059): unit tests not allowed to download content
+  "dynamic-presubmit": [
+    { "name": "AmrnbDecoderTest"},
+    { "name": "AmrnbEncoderTest"}
+  ]
+}
diff --git a/media/libstagefright/codecs/amrnb/common/Android.bp b/media/codecs/amrnb/common/Android.bp
similarity index 83%
rename from media/libstagefright/codecs/amrnb/common/Android.bp
rename to media/codecs/amrnb/common/Android.bp
index 59a791d..bae65f3 100644
--- a/media/libstagefright/codecs/amrnb/common/Android.bp
+++ b/media/codecs/amrnb/common/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrnb_common_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codecs_amrnb_common_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libstagefright_amrnb_common",
     vendor_available: true,
diff --git a/media/libstagefright/codecs/amrnb/common/MODULE_LICENSE_APACHE2 b/media/codecs/amrnb/common/MODULE_LICENSE_APACHE2
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/MODULE_LICENSE_APACHE2
rename to media/codecs/amrnb/common/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/codecs/amrnb/common/NOTICE b/media/codecs/amrnb/common/NOTICE
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/NOTICE
rename to media/codecs/amrnb/common/NOTICE
diff --git a/media/libstagefright/codecs/amrnb/common/include/abs_s.h b/media/codecs/amrnb/common/include/abs_s.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/abs_s.h
rename to media/codecs/amrnb/common/include/abs_s.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/add.h b/media/codecs/amrnb/common/include/add.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/add.h
rename to media/codecs/amrnb/common/include/add.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/az_lsp.h b/media/codecs/amrnb/common/include/az_lsp.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/az_lsp.h
rename to media/codecs/amrnb/common/include/az_lsp.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/basic_op.h b/media/codecs/amrnb/common/include/basic_op.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/basic_op.h
rename to media/codecs/amrnb/common/include/basic_op.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/basic_op_arm_gcc_v5.h b/media/codecs/amrnb/common/include/basic_op_arm_gcc_v5.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/basic_op_arm_gcc_v5.h
rename to media/codecs/amrnb/common/include/basic_op_arm_gcc_v5.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/basic_op_arm_v5.h b/media/codecs/amrnb/common/include/basic_op_arm_v5.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/basic_op_arm_v5.h
rename to media/codecs/amrnb/common/include/basic_op_arm_v5.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/basic_op_c_equivalent.h b/media/codecs/amrnb/common/include/basic_op_c_equivalent.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/basic_op_c_equivalent.h
rename to media/codecs/amrnb/common/include/basic_op_c_equivalent.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/basicop_malloc.h b/media/codecs/amrnb/common/include/basicop_malloc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/basicop_malloc.h
rename to media/codecs/amrnb/common/include/basicop_malloc.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/bitno_tab.h b/media/codecs/amrnb/common/include/bitno_tab.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/bitno_tab.h
rename to media/codecs/amrnb/common/include/bitno_tab.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/bitreorder_tab.h b/media/codecs/amrnb/common/include/bitreorder_tab.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/bitreorder_tab.h
rename to media/codecs/amrnb/common/include/bitreorder_tab.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/bits2prm.h b/media/codecs/amrnb/common/include/bits2prm.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/bits2prm.h
rename to media/codecs/amrnb/common/include/bits2prm.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/cnst.h b/media/codecs/amrnb/common/include/cnst.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/cnst.h
rename to media/codecs/amrnb/common/include/cnst.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/cnst_vad.h b/media/codecs/amrnb/common/include/cnst_vad.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/cnst_vad.h
rename to media/codecs/amrnb/common/include/cnst_vad.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/copy.h b/media/codecs/amrnb/common/include/copy.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/copy.h
rename to media/codecs/amrnb/common/include/copy.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/d_gain_c.h b/media/codecs/amrnb/common/include/d_gain_c.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/d_gain_c.h
rename to media/codecs/amrnb/common/include/d_gain_c.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/d_gain_p.h b/media/codecs/amrnb/common/include/d_gain_p.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/d_gain_p.h
rename to media/codecs/amrnb/common/include/d_gain_p.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/d_plsf.h b/media/codecs/amrnb/common/include/d_plsf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/d_plsf.h
rename to media/codecs/amrnb/common/include/d_plsf.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/div_32.h b/media/codecs/amrnb/common/include/div_32.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/div_32.h
rename to media/codecs/amrnb/common/include/div_32.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/div_s.h b/media/codecs/amrnb/common/include/div_s.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/div_s.h
rename to media/codecs/amrnb/common/include/div_s.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/dtx_common_def.h b/media/codecs/amrnb/common/include/dtx_common_def.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/dtx_common_def.h
rename to media/codecs/amrnb/common/include/dtx_common_def.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/extract_h.h b/media/codecs/amrnb/common/include/extract_h.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/extract_h.h
rename to media/codecs/amrnb/common/include/extract_h.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/extract_l.h b/media/codecs/amrnb/common/include/extract_l.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/extract_l.h
rename to media/codecs/amrnb/common/include/extract_l.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/frame.h b/media/codecs/amrnb/common/include/frame.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/frame.h
rename to media/codecs/amrnb/common/include/frame.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/frame_type_3gpp.h b/media/codecs/amrnb/common/include/frame_type_3gpp.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/frame_type_3gpp.h
rename to media/codecs/amrnb/common/include/frame_type_3gpp.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/gc_pred.h b/media/codecs/amrnb/common/include/gc_pred.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/gc_pred.h
rename to media/codecs/amrnb/common/include/gc_pred.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/gmed_n.h b/media/codecs/amrnb/common/include/gmed_n.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/gmed_n.h
rename to media/codecs/amrnb/common/include/gmed_n.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/gsm_amr_typedefs.h b/media/codecs/amrnb/common/include/gsm_amr_typedefs.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/gsm_amr_typedefs.h
rename to media/codecs/amrnb/common/include/gsm_amr_typedefs.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/int_lpc.h b/media/codecs/amrnb/common/include/int_lpc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/int_lpc.h
rename to media/codecs/amrnb/common/include/int_lpc.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/int_lsf.h b/media/codecs/amrnb/common/include/int_lsf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/int_lsf.h
rename to media/codecs/amrnb/common/include/int_lsf.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/inv_sqrt.h b/media/codecs/amrnb/common/include/inv_sqrt.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/inv_sqrt.h
rename to media/codecs/amrnb/common/include/inv_sqrt.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_abs.h b/media/codecs/amrnb/common/include/l_abs.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_abs.h
rename to media/codecs/amrnb/common/include/l_abs.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_add.h b/media/codecs/amrnb/common/include/l_add.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_add.h
rename to media/codecs/amrnb/common/include/l_add.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_add_c.h b/media/codecs/amrnb/common/include/l_add_c.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_add_c.h
rename to media/codecs/amrnb/common/include/l_add_c.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_comp.h b/media/codecs/amrnb/common/include/l_comp.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_comp.h
rename to media/codecs/amrnb/common/include/l_comp.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_deposit_h.h b/media/codecs/amrnb/common/include/l_deposit_h.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_deposit_h.h
rename to media/codecs/amrnb/common/include/l_deposit_h.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_deposit_l.h b/media/codecs/amrnb/common/include/l_deposit_l.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_deposit_l.h
rename to media/codecs/amrnb/common/include/l_deposit_l.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_extract.h b/media/codecs/amrnb/common/include/l_extract.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_extract.h
rename to media/codecs/amrnb/common/include/l_extract.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_mac.h b/media/codecs/amrnb/common/include/l_mac.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_mac.h
rename to media/codecs/amrnb/common/include/l_mac.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_msu.h b/media/codecs/amrnb/common/include/l_msu.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_msu.h
rename to media/codecs/amrnb/common/include/l_msu.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_mult.h b/media/codecs/amrnb/common/include/l_mult.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_mult.h
rename to media/codecs/amrnb/common/include/l_mult.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_negate.h b/media/codecs/amrnb/common/include/l_negate.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_negate.h
rename to media/codecs/amrnb/common/include/l_negate.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_shl.h b/media/codecs/amrnb/common/include/l_shl.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_shl.h
rename to media/codecs/amrnb/common/include/l_shl.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_shr.h b/media/codecs/amrnb/common/include/l_shr.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_shr.h
rename to media/codecs/amrnb/common/include/l_shr.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_shr_r.h b/media/codecs/amrnb/common/include/l_shr_r.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_shr_r.h
rename to media/codecs/amrnb/common/include/l_shr_r.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_sub.h b/media/codecs/amrnb/common/include/l_sub.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/l_sub.h
rename to media/codecs/amrnb/common/include/l_sub.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/log2.h b/media/codecs/amrnb/common/include/log2.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/log2.h
rename to media/codecs/amrnb/common/include/log2.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/log2_norm.h b/media/codecs/amrnb/common/include/log2_norm.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/log2_norm.h
rename to media/codecs/amrnb/common/include/log2_norm.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsfwt.h b/media/codecs/amrnb/common/include/lsfwt.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/lsfwt.h
rename to media/codecs/amrnb/common/include/lsfwt.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsp.h b/media/codecs/amrnb/common/include/lsp.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/lsp.h
rename to media/codecs/amrnb/common/include/lsp.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsp_az.h b/media/codecs/amrnb/common/include/lsp_az.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/lsp_az.h
rename to media/codecs/amrnb/common/include/lsp_az.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsp_lsf.h b/media/codecs/amrnb/common/include/lsp_lsf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/lsp_lsf.h
rename to media/codecs/amrnb/common/include/lsp_lsf.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsp_tab.h b/media/codecs/amrnb/common/include/lsp_tab.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/lsp_tab.h
rename to media/codecs/amrnb/common/include/lsp_tab.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/mac_32.h b/media/codecs/amrnb/common/include/mac_32.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/mac_32.h
rename to media/codecs/amrnb/common/include/mac_32.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/mode.h b/media/codecs/amrnb/common/include/mode.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/mode.h
rename to media/codecs/amrnb/common/include/mode.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/mpy_32.h b/media/codecs/amrnb/common/include/mpy_32.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/mpy_32.h
rename to media/codecs/amrnb/common/include/mpy_32.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/mpy_32_16.h b/media/codecs/amrnb/common/include/mpy_32_16.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/mpy_32_16.h
rename to media/codecs/amrnb/common/include/mpy_32_16.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/mult.h b/media/codecs/amrnb/common/include/mult.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/mult.h
rename to media/codecs/amrnb/common/include/mult.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/mult_r.h b/media/codecs/amrnb/common/include/mult_r.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/mult_r.h
rename to media/codecs/amrnb/common/include/mult_r.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/n_proc.h b/media/codecs/amrnb/common/include/n_proc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/n_proc.h
rename to media/codecs/amrnb/common/include/n_proc.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/negate.h b/media/codecs/amrnb/common/include/negate.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/negate.h
rename to media/codecs/amrnb/common/include/negate.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/norm_l.h b/media/codecs/amrnb/common/include/norm_l.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/norm_l.h
rename to media/codecs/amrnb/common/include/norm_l.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/norm_s.h b/media/codecs/amrnb/common/include/norm_s.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/norm_s.h
rename to media/codecs/amrnb/common/include/norm_s.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/oper_32b.h b/media/codecs/amrnb/common/include/oper_32b.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/oper_32b.h
rename to media/codecs/amrnb/common/include/oper_32b.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/p_ol_wgh.h b/media/codecs/amrnb/common/include/p_ol_wgh.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/p_ol_wgh.h
rename to media/codecs/amrnb/common/include/p_ol_wgh.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/pow2.h b/media/codecs/amrnb/common/include/pow2.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/pow2.h
rename to media/codecs/amrnb/common/include/pow2.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/pred_lt.h b/media/codecs/amrnb/common/include/pred_lt.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/pred_lt.h
rename to media/codecs/amrnb/common/include/pred_lt.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/q_plsf.h b/media/codecs/amrnb/common/include/q_plsf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/q_plsf.h
rename to media/codecs/amrnb/common/include/q_plsf.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/q_plsf_3_tbl.h b/media/codecs/amrnb/common/include/q_plsf_3_tbl.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/q_plsf_3_tbl.h
rename to media/codecs/amrnb/common/include/q_plsf_3_tbl.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/q_plsf_5_tbl.h b/media/codecs/amrnb/common/include/q_plsf_5_tbl.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/q_plsf_5_tbl.h
rename to media/codecs/amrnb/common/include/q_plsf_5_tbl.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/qgain475_tab.h b/media/codecs/amrnb/common/include/qgain475_tab.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/qgain475_tab.h
rename to media/codecs/amrnb/common/include/qgain475_tab.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/qua_gain.h b/media/codecs/amrnb/common/include/qua_gain.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/qua_gain.h
rename to media/codecs/amrnb/common/include/qua_gain.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/qua_gain_tbl.h b/media/codecs/amrnb/common/include/qua_gain_tbl.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/qua_gain_tbl.h
rename to media/codecs/amrnb/common/include/qua_gain_tbl.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/reorder.h b/media/codecs/amrnb/common/include/reorder.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/reorder.h
rename to media/codecs/amrnb/common/include/reorder.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/residu.h b/media/codecs/amrnb/common/include/residu.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/residu.h
rename to media/codecs/amrnb/common/include/residu.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/reverse_bits.h b/media/codecs/amrnb/common/include/reverse_bits.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/reverse_bits.h
rename to media/codecs/amrnb/common/include/reverse_bits.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/round.h b/media/codecs/amrnb/common/include/round.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/round.h
rename to media/codecs/amrnb/common/include/round.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/set_zero.h b/media/codecs/amrnb/common/include/set_zero.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/set_zero.h
rename to media/codecs/amrnb/common/include/set_zero.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/shl.h b/media/codecs/amrnb/common/include/shl.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/shl.h
rename to media/codecs/amrnb/common/include/shl.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/shr.h b/media/codecs/amrnb/common/include/shr.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/shr.h
rename to media/codecs/amrnb/common/include/shr.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/shr_r.h b/media/codecs/amrnb/common/include/shr_r.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/shr_r.h
rename to media/codecs/amrnb/common/include/shr_r.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/sqrt_l.h b/media/codecs/amrnb/common/include/sqrt_l.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/sqrt_l.h
rename to media/codecs/amrnb/common/include/sqrt_l.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/sub.h b/media/codecs/amrnb/common/include/sub.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/sub.h
rename to media/codecs/amrnb/common/include/sub.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/syn_filt.h b/media/codecs/amrnb/common/include/syn_filt.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/syn_filt.h
rename to media/codecs/amrnb/common/include/syn_filt.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/typedef.h b/media/codecs/amrnb/common/include/typedef.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/typedef.h
rename to media/codecs/amrnb/common/include/typedef.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/vad.h b/media/codecs/amrnb/common/include/vad.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/vad.h
rename to media/codecs/amrnb/common/include/vad.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/vad1.h b/media/codecs/amrnb/common/include/vad1.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/vad1.h
rename to media/codecs/amrnb/common/include/vad1.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/vad2.h b/media/codecs/amrnb/common/include/vad2.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/vad2.h
rename to media/codecs/amrnb/common/include/vad2.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/weight_a.h b/media/codecs/amrnb/common/include/weight_a.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/weight_a.h
rename to media/codecs/amrnb/common/include/weight_a.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/window_tab.h b/media/codecs/amrnb/common/include/window_tab.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/window_tab.h
rename to media/codecs/amrnb/common/include/window_tab.h
diff --git a/media/libstagefright/codecs/amrnb/common/include/wmf_to_ets.h b/media/codecs/amrnb/common/include/wmf_to_ets.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/include/wmf_to_ets.h
rename to media/codecs/amrnb/common/include/wmf_to_ets.h
diff --git a/media/libstagefright/codecs/amrnb/common/src/add.cpp b/media/codecs/amrnb/common/src/add.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/add.cpp
rename to media/codecs/amrnb/common/src/add.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/az_lsp.cpp b/media/codecs/amrnb/common/src/az_lsp.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/az_lsp.cpp
rename to media/codecs/amrnb/common/src/az_lsp.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/bitno_tab.cpp b/media/codecs/amrnb/common/src/bitno_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/bitno_tab.cpp
rename to media/codecs/amrnb/common/src/bitno_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/bitreorder_tab.cpp b/media/codecs/amrnb/common/src/bitreorder_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/bitreorder_tab.cpp
rename to media/codecs/amrnb/common/src/bitreorder_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/bits2prm.cpp b/media/codecs/amrnb/common/src/bits2prm.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/bits2prm.cpp
rename to media/codecs/amrnb/common/src/bits2prm.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/c2_9pf_tab.cpp b/media/codecs/amrnb/common/src/c2_9pf_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/c2_9pf_tab.cpp
rename to media/codecs/amrnb/common/src/c2_9pf_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/copy.cpp b/media/codecs/amrnb/common/src/copy.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/copy.cpp
rename to media/codecs/amrnb/common/src/copy.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/div_32.cpp b/media/codecs/amrnb/common/src/div_32.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/div_32.cpp
rename to media/codecs/amrnb/common/src/div_32.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/div_s.cpp b/media/codecs/amrnb/common/src/div_s.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/div_s.cpp
rename to media/codecs/amrnb/common/src/div_s.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/extract_h.cpp b/media/codecs/amrnb/common/src/extract_h.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/extract_h.cpp
rename to media/codecs/amrnb/common/src/extract_h.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/extract_l.cpp b/media/codecs/amrnb/common/src/extract_l.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/extract_l.cpp
rename to media/codecs/amrnb/common/src/extract_l.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/gains_tbl.cpp b/media/codecs/amrnb/common/src/gains_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/gains_tbl.cpp
rename to media/codecs/amrnb/common/src/gains_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/gc_pred.cpp b/media/codecs/amrnb/common/src/gc_pred.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/gc_pred.cpp
rename to media/codecs/amrnb/common/src/gc_pred.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/gmed_n.cpp b/media/codecs/amrnb/common/src/gmed_n.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/gmed_n.cpp
rename to media/codecs/amrnb/common/src/gmed_n.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/gray_tbl.cpp b/media/codecs/amrnb/common/src/gray_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/gray_tbl.cpp
rename to media/codecs/amrnb/common/src/gray_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/grid_tbl.cpp b/media/codecs/amrnb/common/src/grid_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/grid_tbl.cpp
rename to media/codecs/amrnb/common/src/grid_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/int_lpc.cpp b/media/codecs/amrnb/common/src/int_lpc.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/int_lpc.cpp
rename to media/codecs/amrnb/common/src/int_lpc.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/inv_sqrt.cpp b/media/codecs/amrnb/common/src/inv_sqrt.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/inv_sqrt.cpp
rename to media/codecs/amrnb/common/src/inv_sqrt.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/inv_sqrt_tbl.cpp b/media/codecs/amrnb/common/src/inv_sqrt_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/inv_sqrt_tbl.cpp
rename to media/codecs/amrnb/common/src/inv_sqrt_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/l_abs.cpp b/media/codecs/amrnb/common/src/l_abs.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/l_abs.cpp
rename to media/codecs/amrnb/common/src/l_abs.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/l_deposit_h.cpp b/media/codecs/amrnb/common/src/l_deposit_h.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/l_deposit_h.cpp
rename to media/codecs/amrnb/common/src/l_deposit_h.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/l_deposit_l.cpp b/media/codecs/amrnb/common/src/l_deposit_l.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/l_deposit_l.cpp
rename to media/codecs/amrnb/common/src/l_deposit_l.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/l_shr_r.cpp b/media/codecs/amrnb/common/src/l_shr_r.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/l_shr_r.cpp
rename to media/codecs/amrnb/common/src/l_shr_r.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/log2.cpp b/media/codecs/amrnb/common/src/log2.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/log2.cpp
rename to media/codecs/amrnb/common/src/log2.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/log2_norm.cpp b/media/codecs/amrnb/common/src/log2_norm.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/log2_norm.cpp
rename to media/codecs/amrnb/common/src/log2_norm.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/log2_tbl.cpp b/media/codecs/amrnb/common/src/log2_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/log2_tbl.cpp
rename to media/codecs/amrnb/common/src/log2_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsfwt.cpp b/media/codecs/amrnb/common/src/lsfwt.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/lsfwt.cpp
rename to media/codecs/amrnb/common/src/lsfwt.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp.cpp b/media/codecs/amrnb/common/src/lsp.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/lsp.cpp
rename to media/codecs/amrnb/common/src/lsp.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp_az.cpp b/media/codecs/amrnb/common/src/lsp_az.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/lsp_az.cpp
rename to media/codecs/amrnb/common/src/lsp_az.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp_lsf.cpp b/media/codecs/amrnb/common/src/lsp_lsf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/lsp_lsf.cpp
rename to media/codecs/amrnb/common/src/lsp_lsf.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp_lsf_tbl.cpp b/media/codecs/amrnb/common/src/lsp_lsf_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/lsp_lsf_tbl.cpp
rename to media/codecs/amrnb/common/src/lsp_lsf_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp_tab.cpp b/media/codecs/amrnb/common/src/lsp_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/lsp_tab.cpp
rename to media/codecs/amrnb/common/src/lsp_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/mult_r.cpp b/media/codecs/amrnb/common/src/mult_r.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/mult_r.cpp
rename to media/codecs/amrnb/common/src/mult_r.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/negate.cpp b/media/codecs/amrnb/common/src/negate.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/negate.cpp
rename to media/codecs/amrnb/common/src/negate.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/norm_l.cpp b/media/codecs/amrnb/common/src/norm_l.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/norm_l.cpp
rename to media/codecs/amrnb/common/src/norm_l.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/norm_s.cpp b/media/codecs/amrnb/common/src/norm_s.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/norm_s.cpp
rename to media/codecs/amrnb/common/src/norm_s.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/ph_disp_tab.cpp b/media/codecs/amrnb/common/src/ph_disp_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/ph_disp_tab.cpp
rename to media/codecs/amrnb/common/src/ph_disp_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/pow2.cpp b/media/codecs/amrnb/common/src/pow2.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/pow2.cpp
rename to media/codecs/amrnb/common/src/pow2.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/pow2_tbl.cpp b/media/codecs/amrnb/common/src/pow2_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/pow2_tbl.cpp
rename to media/codecs/amrnb/common/src/pow2_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/pred_lt.cpp b/media/codecs/amrnb/common/src/pred_lt.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/pred_lt.cpp
rename to media/codecs/amrnb/common/src/pred_lt.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf.cpp b/media/codecs/amrnb/common/src/q_plsf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/q_plsf.cpp
rename to media/codecs/amrnb/common/src/q_plsf.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf_3.cpp b/media/codecs/amrnb/common/src/q_plsf_3.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/q_plsf_3.cpp
rename to media/codecs/amrnb/common/src/q_plsf_3.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf_3_tbl.cpp b/media/codecs/amrnb/common/src/q_plsf_3_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/q_plsf_3_tbl.cpp
rename to media/codecs/amrnb/common/src/q_plsf_3_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf_5.cpp b/media/codecs/amrnb/common/src/q_plsf_5.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/q_plsf_5.cpp
rename to media/codecs/amrnb/common/src/q_plsf_5.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf_5_tbl.cpp b/media/codecs/amrnb/common/src/q_plsf_5_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/q_plsf_5_tbl.cpp
rename to media/codecs/amrnb/common/src/q_plsf_5_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/qua_gain_tbl.cpp b/media/codecs/amrnb/common/src/qua_gain_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/qua_gain_tbl.cpp
rename to media/codecs/amrnb/common/src/qua_gain_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/reorder.cpp b/media/codecs/amrnb/common/src/reorder.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/reorder.cpp
rename to media/codecs/amrnb/common/src/reorder.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/residu.cpp b/media/codecs/amrnb/common/src/residu.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/residu.cpp
rename to media/codecs/amrnb/common/src/residu.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/round.cpp b/media/codecs/amrnb/common/src/round.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/round.cpp
rename to media/codecs/amrnb/common/src/round.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/set_zero.cpp b/media/codecs/amrnb/common/src/set_zero.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/set_zero.cpp
rename to media/codecs/amrnb/common/src/set_zero.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/shr.cpp b/media/codecs/amrnb/common/src/shr.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/shr.cpp
rename to media/codecs/amrnb/common/src/shr.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/shr_r.cpp b/media/codecs/amrnb/common/src/shr_r.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/shr_r.cpp
rename to media/codecs/amrnb/common/src/shr_r.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/sqrt_l.cpp b/media/codecs/amrnb/common/src/sqrt_l.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/sqrt_l.cpp
rename to media/codecs/amrnb/common/src/sqrt_l.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/sqrt_l_tbl.cpp b/media/codecs/amrnb/common/src/sqrt_l_tbl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/sqrt_l_tbl.cpp
rename to media/codecs/amrnb/common/src/sqrt_l_tbl.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/sub.cpp b/media/codecs/amrnb/common/src/sub.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/sub.cpp
rename to media/codecs/amrnb/common/src/sub.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/syn_filt.cpp b/media/codecs/amrnb/common/src/syn_filt.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/syn_filt.cpp
rename to media/codecs/amrnb/common/src/syn_filt.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/vad1.cpp b/media/codecs/amrnb/common/src/vad1.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/vad1.cpp
rename to media/codecs/amrnb/common/src/vad1.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/weight_a.cpp b/media/codecs/amrnb/common/src/weight_a.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/weight_a.cpp
rename to media/codecs/amrnb/common/src/weight_a.cpp
diff --git a/media/libstagefright/codecs/amrnb/common/src/window_tab.cpp b/media/codecs/amrnb/common/src/window_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/common/src/window_tab.cpp
rename to media/codecs/amrnb/common/src/window_tab.cpp
diff --git a/media/codecs/amrnb/dec/Android.bp b/media/codecs/amrnb/dec/Android.bp
new file mode 100644
index 0000000..1083b82
--- /dev/null
+++ b/media/codecs/amrnb/dec/Android.bp
@@ -0,0 +1,138 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrnb_dec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codecs_amrnb_dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-BSD",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library_static {
+    name: "libstagefright_amrnbdec",
+    vendor_available: true,
+    host_supported: true,
+    min_sdk_version: "29",
+
+    srcs: [
+        "src/a_refl.cpp",
+        "src/agc.cpp",
+        "src/amrdecode.cpp",
+        "src/b_cn_cod.cpp",
+        "src/bgnscd.cpp",
+        "src/c_g_aver.cpp",
+        "src/d1035pf.cpp",
+        "src/d2_11pf.cpp",
+        "src/d2_9pf.cpp",
+        "src/d3_14pf.cpp",
+        "src/d4_17pf.cpp",
+        "src/d8_31pf.cpp",
+        "src/d_gain_c.cpp",
+        "src/d_gain_p.cpp",
+        "src/d_plsf.cpp",
+        "src/d_plsf_3.cpp",
+        "src/d_plsf_5.cpp",
+        "src/dec_amr.cpp",
+        "src/dec_gain.cpp",
+        "src/dec_input_format_tab.cpp",
+        "src/dec_lag3.cpp",
+        "src/dec_lag6.cpp",
+        "src/dtx_dec.cpp",
+        "src/ec_gains.cpp",
+        "src/ex_ctrl.cpp",
+        "src/if2_to_ets.cpp",
+        "src/int_lsf.cpp",
+        "src/lsp_avg.cpp",
+        "src/ph_disp.cpp",
+        "src/post_pro.cpp",
+        "src/preemph.cpp",
+        "src/pstfilt.cpp",
+        "src/qgain475_tab.cpp",
+        "src/sp_dec.cpp",
+        "src/wmf_to_ets.cpp",
+    ],
+
+    export_include_dirs: ["src"],
+
+    cflags: [
+        "-DOSCL_UNUSED_ARG(x)=(void)(x)",
+        "-DOSCL_IMPORT_REF=",
+
+        "-Werror",
+    ],
+
+    //sanitize: {
+    //    misc_undefined: [
+    //        "signed-integer-overflow",
+    //    ],
+    //},
+
+    shared_libs: [
+        "libstagefright_amrnb_common",
+        "liblog",
+    ],
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+}
+
+//###############################################################################
+cc_test {
+    name: "libstagefright_amrnbdec_test",
+    gtest: false,
+    host_supported: true,
+
+    srcs: ["test/amrnbdec_test.cpp"],
+
+    cflags: ["-Wall", "-Werror"],
+
+    local_include_dirs: ["src"],
+
+    static_libs: [
+        "libstagefright_amrnbdec",
+        "libsndfile",
+    ],
+
+    shared_libs: [
+        "libstagefright_amrnb_common",
+        "libaudioutils",
+        "liblog",
+    ],
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+
+    //sanitize: {
+    //    misc_undefined: [
+    //        "signed-integer-overflow",
+    //    ],
+    //},
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/MODULE_LICENSE_APACHE2 b/media/codecs/amrnb/dec/MODULE_LICENSE_APACHE2
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/MODULE_LICENSE_APACHE2
rename to media/codecs/amrnb/dec/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/codecs/amrnb/dec/NOTICE b/media/codecs/amrnb/dec/NOTICE
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/NOTICE
rename to media/codecs/amrnb/dec/NOTICE
diff --git a/media/libstagefright/codecs/amrnb/dec/src/a_refl.cpp b/media/codecs/amrnb/dec/src/a_refl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/a_refl.cpp
rename to media/codecs/amrnb/dec/src/a_refl.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/a_refl.h b/media/codecs/amrnb/dec/src/a_refl.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/a_refl.h
rename to media/codecs/amrnb/dec/src/a_refl.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/agc.cpp b/media/codecs/amrnb/dec/src/agc.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/agc.cpp
rename to media/codecs/amrnb/dec/src/agc.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/agc.h b/media/codecs/amrnb/dec/src/agc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/agc.h
rename to media/codecs/amrnb/dec/src/agc.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/amrdecode.cpp b/media/codecs/amrnb/dec/src/amrdecode.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/amrdecode.cpp
rename to media/codecs/amrnb/dec/src/amrdecode.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/amrdecode.h b/media/codecs/amrnb/dec/src/amrdecode.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/amrdecode.h
rename to media/codecs/amrnb/dec/src/amrdecode.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.cpp b/media/codecs/amrnb/dec/src/b_cn_cod.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.cpp
rename to media/codecs/amrnb/dec/src/b_cn_cod.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.h b/media/codecs/amrnb/dec/src/b_cn_cod.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.h
rename to media/codecs/amrnb/dec/src/b_cn_cod.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/bgnscd.cpp b/media/codecs/amrnb/dec/src/bgnscd.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/bgnscd.cpp
rename to media/codecs/amrnb/dec/src/bgnscd.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/bgnscd.h b/media/codecs/amrnb/dec/src/bgnscd.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/bgnscd.h
rename to media/codecs/amrnb/dec/src/bgnscd.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/c_g_aver.cpp b/media/codecs/amrnb/dec/src/c_g_aver.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/c_g_aver.cpp
rename to media/codecs/amrnb/dec/src/c_g_aver.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/c_g_aver.h b/media/codecs/amrnb/dec/src/c_g_aver.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/c_g_aver.h
rename to media/codecs/amrnb/dec/src/c_g_aver.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d1035pf.cpp b/media/codecs/amrnb/dec/src/d1035pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d1035pf.cpp
rename to media/codecs/amrnb/dec/src/d1035pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d1035pf.h b/media/codecs/amrnb/dec/src/d1035pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d1035pf.h
rename to media/codecs/amrnb/dec/src/d1035pf.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d2_11pf.cpp b/media/codecs/amrnb/dec/src/d2_11pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d2_11pf.cpp
rename to media/codecs/amrnb/dec/src/d2_11pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d2_11pf.h b/media/codecs/amrnb/dec/src/d2_11pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d2_11pf.h
rename to media/codecs/amrnb/dec/src/d2_11pf.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d2_9pf.cpp b/media/codecs/amrnb/dec/src/d2_9pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d2_9pf.cpp
rename to media/codecs/amrnb/dec/src/d2_9pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d2_9pf.h b/media/codecs/amrnb/dec/src/d2_9pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d2_9pf.h
rename to media/codecs/amrnb/dec/src/d2_9pf.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d3_14pf.cpp b/media/codecs/amrnb/dec/src/d3_14pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d3_14pf.cpp
rename to media/codecs/amrnb/dec/src/d3_14pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d3_14pf.h b/media/codecs/amrnb/dec/src/d3_14pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d3_14pf.h
rename to media/codecs/amrnb/dec/src/d3_14pf.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d4_17pf.cpp b/media/codecs/amrnb/dec/src/d4_17pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d4_17pf.cpp
rename to media/codecs/amrnb/dec/src/d4_17pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d4_17pf.h b/media/codecs/amrnb/dec/src/d4_17pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d4_17pf.h
rename to media/codecs/amrnb/dec/src/d4_17pf.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d8_31pf.cpp b/media/codecs/amrnb/dec/src/d8_31pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d8_31pf.cpp
rename to media/codecs/amrnb/dec/src/d8_31pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d8_31pf.h b/media/codecs/amrnb/dec/src/d8_31pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d8_31pf.h
rename to media/codecs/amrnb/dec/src/d8_31pf.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_gain_c.cpp b/media/codecs/amrnb/dec/src/d_gain_c.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d_gain_c.cpp
rename to media/codecs/amrnb/dec/src/d_gain_c.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_gain_p.cpp b/media/codecs/amrnb/dec/src/d_gain_p.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d_gain_p.cpp
rename to media/codecs/amrnb/dec/src/d_gain_p.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_plsf.cpp b/media/codecs/amrnb/dec/src/d_plsf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d_plsf.cpp
rename to media/codecs/amrnb/dec/src/d_plsf.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_plsf_3.cpp b/media/codecs/amrnb/dec/src/d_plsf_3.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d_plsf_3.cpp
rename to media/codecs/amrnb/dec/src/d_plsf_3.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_plsf_5.cpp b/media/codecs/amrnb/dec/src/d_plsf_5.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/d_plsf_5.cpp
rename to media/codecs/amrnb/dec/src/d_plsf_5.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_amr.cpp b/media/codecs/amrnb/dec/src/dec_amr.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dec_amr.cpp
rename to media/codecs/amrnb/dec/src/dec_amr.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_amr.h b/media/codecs/amrnb/dec/src/dec_amr.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dec_amr.h
rename to media/codecs/amrnb/dec/src/dec_amr.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_gain.cpp b/media/codecs/amrnb/dec/src/dec_gain.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dec_gain.cpp
rename to media/codecs/amrnb/dec/src/dec_gain.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_gain.h b/media/codecs/amrnb/dec/src/dec_gain.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dec_gain.h
rename to media/codecs/amrnb/dec/src/dec_gain.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_input_format_tab.cpp b/media/codecs/amrnb/dec/src/dec_input_format_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dec_input_format_tab.cpp
rename to media/codecs/amrnb/dec/src/dec_input_format_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_lag3.cpp b/media/codecs/amrnb/dec/src/dec_lag3.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dec_lag3.cpp
rename to media/codecs/amrnb/dec/src/dec_lag3.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_lag3.h b/media/codecs/amrnb/dec/src/dec_lag3.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dec_lag3.h
rename to media/codecs/amrnb/dec/src/dec_lag3.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_lag6.cpp b/media/codecs/amrnb/dec/src/dec_lag6.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dec_lag6.cpp
rename to media/codecs/amrnb/dec/src/dec_lag6.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_lag6.h b/media/codecs/amrnb/dec/src/dec_lag6.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dec_lag6.h
rename to media/codecs/amrnb/dec/src/dec_lag6.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dtx_dec.cpp b/media/codecs/amrnb/dec/src/dtx_dec.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dtx_dec.cpp
rename to media/codecs/amrnb/dec/src/dtx_dec.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dtx_dec.h b/media/codecs/amrnb/dec/src/dtx_dec.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/dtx_dec.h
rename to media/codecs/amrnb/dec/src/dtx_dec.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ec_gains.cpp b/media/codecs/amrnb/dec/src/ec_gains.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/ec_gains.cpp
rename to media/codecs/amrnb/dec/src/ec_gains.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ec_gains.h b/media/codecs/amrnb/dec/src/ec_gains.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/ec_gains.h
rename to media/codecs/amrnb/dec/src/ec_gains.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.cpp b/media/codecs/amrnb/dec/src/ex_ctrl.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.cpp
rename to media/codecs/amrnb/dec/src/ex_ctrl.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.h b/media/codecs/amrnb/dec/src/ex_ctrl.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.h
rename to media/codecs/amrnb/dec/src/ex_ctrl.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/gsmamr_dec.h b/media/codecs/amrnb/dec/src/gsmamr_dec.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/gsmamr_dec.h
rename to media/codecs/amrnb/dec/src/gsmamr_dec.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.cpp b/media/codecs/amrnb/dec/src/if2_to_ets.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.cpp
rename to media/codecs/amrnb/dec/src/if2_to_ets.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.h b/media/codecs/amrnb/dec/src/if2_to_ets.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.h
rename to media/codecs/amrnb/dec/src/if2_to_ets.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/int_lsf.cpp b/media/codecs/amrnb/dec/src/int_lsf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/int_lsf.cpp
rename to media/codecs/amrnb/dec/src/int_lsf.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/lsp_avg.cpp b/media/codecs/amrnb/dec/src/lsp_avg.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/lsp_avg.cpp
rename to media/codecs/amrnb/dec/src/lsp_avg.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/lsp_avg.h b/media/codecs/amrnb/dec/src/lsp_avg.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/lsp_avg.h
rename to media/codecs/amrnb/dec/src/lsp_avg.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ph_disp.cpp b/media/codecs/amrnb/dec/src/ph_disp.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/ph_disp.cpp
rename to media/codecs/amrnb/dec/src/ph_disp.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ph_disp.h b/media/codecs/amrnb/dec/src/ph_disp.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/ph_disp.h
rename to media/codecs/amrnb/dec/src/ph_disp.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/post_pro.cpp b/media/codecs/amrnb/dec/src/post_pro.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/post_pro.cpp
rename to media/codecs/amrnb/dec/src/post_pro.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/post_pro.h b/media/codecs/amrnb/dec/src/post_pro.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/post_pro.h
rename to media/codecs/amrnb/dec/src/post_pro.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/preemph.cpp b/media/codecs/amrnb/dec/src/preemph.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/preemph.cpp
rename to media/codecs/amrnb/dec/src/preemph.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/preemph.h b/media/codecs/amrnb/dec/src/preemph.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/preemph.h
rename to media/codecs/amrnb/dec/src/preemph.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/pstfilt.cpp b/media/codecs/amrnb/dec/src/pstfilt.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/pstfilt.cpp
rename to media/codecs/amrnb/dec/src/pstfilt.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/pstfilt.h b/media/codecs/amrnb/dec/src/pstfilt.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/pstfilt.h
rename to media/codecs/amrnb/dec/src/pstfilt.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/qgain475_tab.cpp b/media/codecs/amrnb/dec/src/qgain475_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/qgain475_tab.cpp
rename to media/codecs/amrnb/dec/src/qgain475_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/sp_dec.cpp b/media/codecs/amrnb/dec/src/sp_dec.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/sp_dec.cpp
rename to media/codecs/amrnb/dec/src/sp_dec.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/src/sp_dec.h b/media/codecs/amrnb/dec/src/sp_dec.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/sp_dec.h
rename to media/codecs/amrnb/dec/src/sp_dec.h
diff --git a/media/libstagefright/codecs/amrnb/dec/src/wmf_to_ets.cpp b/media/codecs/amrnb/dec/src/wmf_to_ets.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/src/wmf_to_ets.cpp
rename to media/codecs/amrnb/dec/src/wmf_to_ets.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/test/AmrnbDecTestEnvironment.h b/media/codecs/amrnb/dec/test/AmrnbDecTestEnvironment.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/test/AmrnbDecTestEnvironment.h
rename to media/codecs/amrnb/dec/test/AmrnbDecTestEnvironment.h
diff --git a/media/libstagefright/codecs/amrnb/dec/test/AmrnbDecoderTest.cpp b/media/codecs/amrnb/dec/test/AmrnbDecoderTest.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/test/AmrnbDecoderTest.cpp
rename to media/codecs/amrnb/dec/test/AmrnbDecoderTest.cpp
diff --git a/media/libstagefright/codecs/amrnb/dec/test/Android.bp b/media/codecs/amrnb/dec/test/Android.bp
similarity index 72%
rename from media/libstagefright/codecs/amrnb/dec/test/Android.bp
rename to media/codecs/amrnb/dec/test/Android.bp
index 7a95cfa..b882481 100644
--- a/media/libstagefright/codecs/amrnb/dec/test/Android.bp
+++ b/media/codecs/amrnb/dec/test/Android.bp
@@ -14,6 +14,18 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_amrnb_dec_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-BSD
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrnb_dec_license",
+    ],
+}
+
 cc_test {
     name: "AmrnbDecoderTest",
     gtest: true,
diff --git a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml b/media/codecs/amrnb/dec/test/AndroidTest.xml
similarity index 70%
copy from media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
copy to media/codecs/amrnb/dec/test/AndroidTest.xml
index 7ff9732..1a9e678 100644
--- a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
+++ b/media/codecs/amrnb/dec/test/AndroidTest.xml
@@ -13,19 +13,19 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Test module config for Mp3 Decoder unit test">
-    <option name="test-suite-tag" value="Mp3DecoderTest" />
+<configuration description="Test module config for Amr-nb Decoder unit test">
+    <option name="test-suite-tag" value="AmrnbDecoderTest" />
     <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
         <option name="cleanup" value="true" />
-        <option name="push" value="Mp3DecoderTest->/data/local/tmp/Mp3DecoderTest" />
+        <option name="push" value="AmrnbDecoderTest->/data/local/tmp/AmrnbDecoderTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest.zip?unzip=true"
-            value="/data/local/tmp/Mp3DecoderTestRes/" />
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/codecs/amrnb/dec/test/AmrnbDecoderTest.zip?unzip=true"
+            value="/data/local/tmp/AmrnbDecoderTestRes/" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.GTest" >
         <option name="native-test-device-path" value="/data/local/tmp" />
-        <option name="module-name" value="Mp3DecoderTest" />
-        <option name="native-test-flag" value="-P /data/local/tmp/Mp3DecoderTestRes/" />
+        <option name="module-name" value="AmrnbDecoderTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/AmrnbDecoderTestRes/" />
     </test>
 </configuration>
diff --git a/media/codecs/amrnb/dec/test/README.md b/media/codecs/amrnb/dec/test/README.md
new file mode 100644
index 0000000..e9073e4
--- /dev/null
+++ b/media/codecs/amrnb/dec/test/README.md
@@ -0,0 +1,39 @@
+## Media Testing ##
+---
+#### AMR-NB Decoder :
+The Amr-Nb Decoder Test Suite validates the amrnb decoder available in libstagefright.
+
+Run the following steps to build the test suite:
+```
+m AmrnbDecoderTest
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+```
+adb push ${OUT}/data/nativetest64/AmrnbDecoderTest/AmrnbDecoderTest /data/local/tmp/
+```
+
+To test 32-bit binary push binaries from nativetest.
+```
+adb push ${OUT}/data/nativetest/AmrnbDecoderTest/AmrnbDecoderTest /data/local/tmp/
+```
+
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/codecs/amrnb/dec/test/AmrnbDecoderTest.zip). Download, unzip and push these files into device for testing.
+
+```
+adb push AmrnbDecoderTestRes/. /data/local/tmp/
+```
+
+usage: AmrnbDecoderTest -P \<path_to_folder\>
+```
+adb shell /data/local/tmp/AmrnbDecoderTest -P /data/local/tmp/AmrnbDecoderTestRes/
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest AmrnbDecoderTest -- --enable-module-dynamic-download=true
+```
diff --git a/media/libstagefright/codecs/amrnb/dec/test/amrnbdec_test.cpp b/media/codecs/amrnb/dec/test/amrnbdec_test.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/dec/test/amrnbdec_test.cpp
rename to media/codecs/amrnb/dec/test/amrnbdec_test.cpp
diff --git a/media/codecs/amrnb/enc/Android.bp b/media/codecs/amrnb/enc/Android.bp
new file mode 100644
index 0000000..9e947e9
--- /dev/null
+++ b/media/codecs/amrnb/enc/Android.bp
@@ -0,0 +1,145 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrnb_enc_license",
+    ],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codecs_amrnb_enc_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-BSD",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library_static {
+    name: "libstagefright_amrnbenc",
+    vendor_available: true,
+    min_sdk_version: "29",
+
+    srcs: [
+        "src/amrencode.cpp",
+        "src/autocorr.cpp",
+        "src/c1035pf.cpp",
+        "src/c2_11pf.cpp",
+        "src/c2_9pf.cpp",
+        "src/c3_14pf.cpp",
+        "src/c4_17pf.cpp",
+        "src/c8_31pf.cpp",
+        "src/calc_cor.cpp",
+        "src/calc_en.cpp",
+        "src/cbsearch.cpp",
+        "src/cl_ltp.cpp",
+        "src/cod_amr.cpp",
+        "src/convolve.cpp",
+        "src/cor_h.cpp",
+        "src/cor_h_x.cpp",
+        "src/cor_h_x2.cpp",
+        "src/corrwght_tab.cpp",
+        "src/dtx_enc.cpp",
+        "src/enc_lag3.cpp",
+        "src/enc_lag6.cpp",
+        "src/enc_output_format_tab.cpp",
+        "src/ets_to_if2.cpp",
+        "src/ets_to_wmf.cpp",
+        "src/g_adapt.cpp",
+        "src/g_code.cpp",
+        "src/g_pitch.cpp",
+        "src/gain_q.cpp",
+        "src/hp_max.cpp",
+        "src/inter_36.cpp",
+        "src/inter_36_tab.cpp",
+        "src/l_comp.cpp",
+        "src/l_extract.cpp",
+        "src/l_negate.cpp",
+        "src/lag_wind.cpp",
+        "src/lag_wind_tab.cpp",
+        "src/levinson.cpp",
+        "src/lpc.cpp",
+        "src/ol_ltp.cpp",
+        "src/p_ol_wgh.cpp",
+        "src/pitch_fr.cpp",
+        "src/pitch_ol.cpp",
+        "src/pre_big.cpp",
+        "src/pre_proc.cpp",
+        "src/prm2bits.cpp",
+        "src/q_gain_c.cpp",
+        "src/q_gain_p.cpp",
+        "src/qgain475.cpp",
+        "src/qgain795.cpp",
+        "src/qua_gain.cpp",
+        "src/s10_8pf.cpp",
+        "src/set_sign.cpp",
+        "src/sid_sync.cpp",
+        "src/sp_enc.cpp",
+        "src/spreproc.cpp",
+        "src/spstproc.cpp",
+        "src/ton_stab.cpp",
+    ],
+
+    header_libs: ["libstagefright_headers"],
+    export_include_dirs: ["src"],
+
+    cflags: [
+        "-DOSCL_UNUSED_ARG(x)=(void)(x)",
+        "-Werror",
+    ],
+
+    //addressing b/25409744
+    //sanitize: {
+    //    misc_undefined: [
+    //        "signed-integer-overflow",
+    //    ],
+    //},
+
+    shared_libs: ["libstagefright_amrnb_common"],
+
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+}
+
+//###############################################################################
+
+cc_test {
+    name: "libstagefright_amrnbenc_test",
+    gtest: false,
+
+    srcs: ["test/amrnb_enc_test.cpp"],
+
+    cflags: ["-Wall", "-Werror"],
+
+    local_include_dirs: ["src"],
+
+    static_libs: ["libstagefright_amrnbenc"],
+
+    shared_libs: ["libstagefright_amrnb_common"],
+
+    //addressing b/25409744
+    //sanitize: {
+    //    misc_undefined: [
+    //        "signed-integer-overflow",
+    //    ],
+    //},
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/MODULE_LICENSE_APACHE2 b/media/codecs/amrnb/enc/MODULE_LICENSE_APACHE2
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/MODULE_LICENSE_APACHE2
rename to media/codecs/amrnb/enc/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/codecs/amrnb/enc/NOTICE b/media/codecs/amrnb/enc/NOTICE
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/NOTICE
rename to media/codecs/amrnb/enc/NOTICE
diff --git a/media/libstagefright/codecs/amrnb/fuzzer/Android.bp b/media/codecs/amrnb/enc/fuzzer/Android.bp
similarity index 61%
copy from media/libstagefright/codecs/amrnb/fuzzer/Android.bp
copy to media/codecs/amrnb/enc/fuzzer/Android.bp
index 54de1cc..2c041b7 100644
--- a/media/libstagefright/codecs/amrnb/fuzzer/Android.bp
+++ b/media/codecs/amrnb/enc/fuzzer/Android.bp
@@ -18,20 +18,35 @@
  * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_amrnb_enc_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrnb_enc_license",
+    ],
+}
+
 cc_fuzz {
-    name: "amrnb_dec_fuzzer",
+    name: "amrnb_enc_fuzzer",
     host_supported: true,
+
     srcs: [
-        "amrnb_dec_fuzzer.cpp",
+        "amrnb_enc_fuzzer.cpp",
     ],
+
     static_libs: [
-        "libstagefright_amrnbdec",
-        "libstagefright_amrnb_common",
         "liblog",
+        "libstagefright_amrnbenc",
+        "libstagefright_amrnb_common",
     ],
-    target: {
-        darwin: {
-            enabled: false,
-        },
+
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
     },
 }
diff --git a/media/codecs/amrnb/enc/fuzzer/README.md b/media/codecs/amrnb/enc/fuzzer/README.md
new file mode 100644
index 0000000..239b4a8
--- /dev/null
+++ b/media/codecs/amrnb/enc/fuzzer/README.md
@@ -0,0 +1,60 @@
+# Fuzzer for libstagefright_amrnbenc encoder
+
+## Plugin Design Considerations
+The fuzzer plugin for AMR-NB is designed based on the understanding of the
+codec and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+AMR-WB supports the following parameters:
+1. Output Format (parameter name: `outputFormat`)
+2. Mode (parameter name: `mode`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `outputFormat` | 0. `AMR_TX_WMF` 1. `AMR_TX_IF2` 2. `AMR_TX_ETS` | Bits 0, 1 and 2 of 1st byte of data. |
+| `mode`   | 0. `MR475` 1. `MR515` 2. `MR59` 3. `MR67`  4. `MR74 ` 5. `MR795` 6. `MR102` 7. `MR122` 8. `MRDTX` | Bits 3, 4, 5 and 6 of 1st byte of data. |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+##### Maximize utilization of input data
+The plugin feeds the entire input data to the codec using a loop.
+If the encode operation was successful, the input is advanced by the frame size.
+If the encode operation was un-successful, the input is still advanced by frame size so
+that the fuzzer can proceed to feed the next frame.
+
+This ensures that the plugin tolerates any kind of input (empty, huge,
+malformed, etc) and doesnt `exit()` on any input and thereby increasing the
+chance of identifying vulnerabilities.
+
+## Build
+
+This describes steps to build amrnb_enc_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) amrnb_enc_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some pcm files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/amrnb_enc_fuzzer/amrnb_enc_fuzzer CORPUS_DIR
+```
+To run on host
+```
+  $ $ANDROID_HOST_OUT/fuzz/x86_64/amrnb_enc_fuzzer/amrnb_enc_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/media/codecs/amrnb/enc/fuzzer/amrnb_enc_fuzzer.cpp b/media/codecs/amrnb/enc/fuzzer/amrnb_enc_fuzzer.cpp
new file mode 100644
index 0000000..2fcbf24
--- /dev/null
+++ b/media/codecs/amrnb/enc/fuzzer/amrnb_enc_fuzzer.cpp
@@ -0,0 +1,105 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+#include <string.h>
+#include <utils/Log.h>
+#include <algorithm>
+#include "gsmamr_enc.h"
+
+// Constants for AMR-NB
+const int32_t kNumInputSamples = L_FRAME;  // 160 samples
+const int32_t kOutputBufferSize = 2 * kNumInputSamples * sizeof(Word16);
+const Mode kModes[9] = {MR475, /* 4.75 kbps */
+                        MR515, /* 5.15 kbps */
+                        MR59,  /* 5.90 kbps */
+                        MR67,  /* 6.70 kbps */
+                        MR74,  /* 7.40 kbps */
+                        MR795, /* 7.95 kbps */
+                        MR102, /* 10.2 kbps */
+                        MR122, /* 12.2 kbps */
+                        MRDTX, /* DTX       */};
+const Word16 kOutputFormat[3] = {AMR_TX_WMF, AMR_TX_IF2, AMR_TX_ETS};
+
+class Codec {
+   public:
+    Codec() = default;
+    ~Codec() { deInitEncoder(); }
+    Word16 initEncoder(const uint8_t *data);
+    void deInitEncoder();
+    void encodeFrames(const uint8_t *data, size_t size);
+
+   private:
+    void *mEncState = nullptr;
+    void *mSidState = nullptr;
+};
+
+Word16 Codec::initEncoder(const uint8_t *data) {
+    return AMREncodeInit(&mEncState, &mSidState, (*data >> 1) & 0x01 /* dtx_enable flag */);
+}
+
+void Codec::deInitEncoder() {
+    if (mEncState) {
+        AMREncodeExit(&mEncState, &mSidState);
+        mEncState = nullptr;
+        mSidState = nullptr;
+    }
+}
+
+void Codec::encodeFrames(const uint8_t *data, size_t size) {
+    AMREncodeReset(mEncState, mSidState);
+    uint8_t startByte = *data;
+    int modeIndex = ((startByte >> 3) % 9);
+    int outputFormatIndex = (startByte % 3);
+    Mode mode = kModes[modeIndex];
+    Word16 outputFormat = kOutputFormat[outputFormatIndex];
+
+    // Consume startByte
+    data++;
+    size--;
+
+    while (size > 0) {
+        Frame_Type_3GPP frameType = (Frame_Type_3GPP)mode;
+
+        Word16 inputBuf[kNumInputSamples] = {};
+        int32_t minSize = std::min(size, sizeof(inputBuf));
+
+        uint8_t outputBuf[kOutputBufferSize] = {};
+        memcpy(inputBuf, data, minSize);
+
+        AMREncode(mEncState, mSidState, mode, inputBuf, outputBuf, &frameType, outputFormat);
+
+        data += minSize;
+        size -= minSize;
+    }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    if (size < 1) {
+        return 0;
+    }
+    Codec *codec = new Codec();
+    if (!codec) {
+        return 0;
+    }
+    if (codec->initEncoder(data) == 0) {
+        codec->encodeFrames(data, size);
+    }
+    delete codec;
+    return 0;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/amrencode.cpp b/media/codecs/amrnb/enc/src/amrencode.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/amrencode.cpp
rename to media/codecs/amrnb/enc/src/amrencode.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/amrencode.h b/media/codecs/amrnb/enc/src/amrencode.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/amrencode.h
rename to media/codecs/amrnb/enc/src/amrencode.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/autocorr.cpp b/media/codecs/amrnb/enc/src/autocorr.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/autocorr.cpp
rename to media/codecs/amrnb/enc/src/autocorr.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/autocorr.h b/media/codecs/amrnb/enc/src/autocorr.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/autocorr.h
rename to media/codecs/amrnb/enc/src/autocorr.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c1035pf.cpp b/media/codecs/amrnb/enc/src/c1035pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c1035pf.cpp
rename to media/codecs/amrnb/enc/src/c1035pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c1035pf.h b/media/codecs/amrnb/enc/src/c1035pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c1035pf.h
rename to media/codecs/amrnb/enc/src/c1035pf.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c2_11pf.cpp b/media/codecs/amrnb/enc/src/c2_11pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c2_11pf.cpp
rename to media/codecs/amrnb/enc/src/c2_11pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c2_11pf.h b/media/codecs/amrnb/enc/src/c2_11pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c2_11pf.h
rename to media/codecs/amrnb/enc/src/c2_11pf.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c2_9pf.cpp b/media/codecs/amrnb/enc/src/c2_9pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c2_9pf.cpp
rename to media/codecs/amrnb/enc/src/c2_9pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c2_9pf.h b/media/codecs/amrnb/enc/src/c2_9pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c2_9pf.h
rename to media/codecs/amrnb/enc/src/c2_9pf.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c3_14pf.cpp b/media/codecs/amrnb/enc/src/c3_14pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c3_14pf.cpp
rename to media/codecs/amrnb/enc/src/c3_14pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c3_14pf.h b/media/codecs/amrnb/enc/src/c3_14pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c3_14pf.h
rename to media/codecs/amrnb/enc/src/c3_14pf.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c4_17pf.cpp b/media/codecs/amrnb/enc/src/c4_17pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c4_17pf.cpp
rename to media/codecs/amrnb/enc/src/c4_17pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c4_17pf.h b/media/codecs/amrnb/enc/src/c4_17pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c4_17pf.h
rename to media/codecs/amrnb/enc/src/c4_17pf.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c8_31pf.cpp b/media/codecs/amrnb/enc/src/c8_31pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c8_31pf.cpp
rename to media/codecs/amrnb/enc/src/c8_31pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c8_31pf.h b/media/codecs/amrnb/enc/src/c8_31pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/c8_31pf.h
rename to media/codecs/amrnb/enc/src/c8_31pf.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/calc_cor.cpp b/media/codecs/amrnb/enc/src/calc_cor.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/calc_cor.cpp
rename to media/codecs/amrnb/enc/src/calc_cor.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/calc_cor.h b/media/codecs/amrnb/enc/src/calc_cor.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/calc_cor.h
rename to media/codecs/amrnb/enc/src/calc_cor.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/calc_en.cpp b/media/codecs/amrnb/enc/src/calc_en.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/calc_en.cpp
rename to media/codecs/amrnb/enc/src/calc_en.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/calc_en.h b/media/codecs/amrnb/enc/src/calc_en.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/calc_en.h
rename to media/codecs/amrnb/enc/src/calc_en.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cbsearch.cpp b/media/codecs/amrnb/enc/src/cbsearch.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cbsearch.cpp
rename to media/codecs/amrnb/enc/src/cbsearch.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cbsearch.h b/media/codecs/amrnb/enc/src/cbsearch.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cbsearch.h
rename to media/codecs/amrnb/enc/src/cbsearch.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cl_ltp.cpp b/media/codecs/amrnb/enc/src/cl_ltp.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cl_ltp.cpp
rename to media/codecs/amrnb/enc/src/cl_ltp.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cl_ltp.h b/media/codecs/amrnb/enc/src/cl_ltp.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cl_ltp.h
rename to media/codecs/amrnb/enc/src/cl_ltp.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cod_amr.cpp b/media/codecs/amrnb/enc/src/cod_amr.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cod_amr.cpp
rename to media/codecs/amrnb/enc/src/cod_amr.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cod_amr.h b/media/codecs/amrnb/enc/src/cod_amr.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cod_amr.h
rename to media/codecs/amrnb/enc/src/cod_amr.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/convolve.cpp b/media/codecs/amrnb/enc/src/convolve.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/convolve.cpp
rename to media/codecs/amrnb/enc/src/convolve.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/convolve.h b/media/codecs/amrnb/enc/src/convolve.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/convolve.h
rename to media/codecs/amrnb/enc/src/convolve.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h.cpp b/media/codecs/amrnb/enc/src/cor_h.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cor_h.cpp
rename to media/codecs/amrnb/enc/src/cor_h.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h.h b/media/codecs/amrnb/enc/src/cor_h.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cor_h.h
rename to media/codecs/amrnb/enc/src/cor_h.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h_x.cpp b/media/codecs/amrnb/enc/src/cor_h_x.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cor_h_x.cpp
rename to media/codecs/amrnb/enc/src/cor_h_x.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h_x.h b/media/codecs/amrnb/enc/src/cor_h_x.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cor_h_x.h
rename to media/codecs/amrnb/enc/src/cor_h_x.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.cpp b/media/codecs/amrnb/enc/src/cor_h_x2.cpp
similarity index 99%
rename from media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.cpp
rename to media/codecs/amrnb/enc/src/cor_h_x2.cpp
index b4fd867..e32eb4a 100644
--- a/media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.cpp
+++ b/media/codecs/amrnb/enc/src/cor_h_x2.cpp
@@ -240,7 +240,7 @@
     Word16 j;
     Word16 k;
     Word32 s;
-    Word32 y32[L_CODE];
+    Word32 y32[L_CODE]{};
     Word32 max;
     Word32 tot;
 
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.h b/media/codecs/amrnb/enc/src/cor_h_x2.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.h
rename to media/codecs/amrnb/enc/src/cor_h_x2.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/corrwght_tab.cpp b/media/codecs/amrnb/enc/src/corrwght_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/corrwght_tab.cpp
rename to media/codecs/amrnb/enc/src/corrwght_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/dtx_enc.cpp b/media/codecs/amrnb/enc/src/dtx_enc.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/dtx_enc.cpp
rename to media/codecs/amrnb/enc/src/dtx_enc.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/dtx_enc.h b/media/codecs/amrnb/enc/src/dtx_enc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/dtx_enc.h
rename to media/codecs/amrnb/enc/src/dtx_enc.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_lag3.cpp b/media/codecs/amrnb/enc/src/enc_lag3.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/enc_lag3.cpp
rename to media/codecs/amrnb/enc/src/enc_lag3.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_lag3.h b/media/codecs/amrnb/enc/src/enc_lag3.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/enc_lag3.h
rename to media/codecs/amrnb/enc/src/enc_lag3.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_lag6.cpp b/media/codecs/amrnb/enc/src/enc_lag6.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/enc_lag6.cpp
rename to media/codecs/amrnb/enc/src/enc_lag6.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_lag6.h b/media/codecs/amrnb/enc/src/enc_lag6.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/enc_lag6.h
rename to media/codecs/amrnb/enc/src/enc_lag6.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_output_format_tab.cpp b/media/codecs/amrnb/enc/src/enc_output_format_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/enc_output_format_tab.cpp
rename to media/codecs/amrnb/enc/src/enc_output_format_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.cpp b/media/codecs/amrnb/enc/src/ets_to_if2.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.cpp
rename to media/codecs/amrnb/enc/src/ets_to_if2.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.h b/media/codecs/amrnb/enc/src/ets_to_if2.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.h
rename to media/codecs/amrnb/enc/src/ets_to_if2.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.cpp b/media/codecs/amrnb/enc/src/ets_to_wmf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.cpp
rename to media/codecs/amrnb/enc/src/ets_to_wmf.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.h b/media/codecs/amrnb/enc/src/ets_to_wmf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.h
rename to media/codecs/amrnb/enc/src/ets_to_wmf.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_adapt.cpp b/media/codecs/amrnb/enc/src/g_adapt.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/g_adapt.cpp
rename to media/codecs/amrnb/enc/src/g_adapt.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_adapt.h b/media/codecs/amrnb/enc/src/g_adapt.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/g_adapt.h
rename to media/codecs/amrnb/enc/src/g_adapt.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_code.cpp b/media/codecs/amrnb/enc/src/g_code.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/g_code.cpp
rename to media/codecs/amrnb/enc/src/g_code.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_code.h b/media/codecs/amrnb/enc/src/g_code.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/g_code.h
rename to media/codecs/amrnb/enc/src/g_code.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_pitch.cpp b/media/codecs/amrnb/enc/src/g_pitch.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/g_pitch.cpp
rename to media/codecs/amrnb/enc/src/g_pitch.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_pitch.h b/media/codecs/amrnb/enc/src/g_pitch.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/g_pitch.h
rename to media/codecs/amrnb/enc/src/g_pitch.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/gain_q.cpp b/media/codecs/amrnb/enc/src/gain_q.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/gain_q.cpp
rename to media/codecs/amrnb/enc/src/gain_q.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/gain_q.h b/media/codecs/amrnb/enc/src/gain_q.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/gain_q.h
rename to media/codecs/amrnb/enc/src/gain_q.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/gsmamr_enc.h b/media/codecs/amrnb/enc/src/gsmamr_enc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/gsmamr_enc.h
rename to media/codecs/amrnb/enc/src/gsmamr_enc.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/hp_max.cpp b/media/codecs/amrnb/enc/src/hp_max.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/hp_max.cpp
rename to media/codecs/amrnb/enc/src/hp_max.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/hp_max.h b/media/codecs/amrnb/enc/src/hp_max.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/hp_max.h
rename to media/codecs/amrnb/enc/src/hp_max.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/inter_36.cpp b/media/codecs/amrnb/enc/src/inter_36.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/inter_36.cpp
rename to media/codecs/amrnb/enc/src/inter_36.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/inter_36.h b/media/codecs/amrnb/enc/src/inter_36.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/inter_36.h
rename to media/codecs/amrnb/enc/src/inter_36.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.cpp b/media/codecs/amrnb/enc/src/inter_36_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.cpp
rename to media/codecs/amrnb/enc/src/inter_36_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.h b/media/codecs/amrnb/enc/src/inter_36_tab.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.h
rename to media/codecs/amrnb/enc/src/inter_36_tab.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/l_comp.cpp b/media/codecs/amrnb/enc/src/l_comp.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/l_comp.cpp
rename to media/codecs/amrnb/enc/src/l_comp.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/l_extract.cpp b/media/codecs/amrnb/enc/src/l_extract.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/l_extract.cpp
rename to media/codecs/amrnb/enc/src/l_extract.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/l_negate.cpp b/media/codecs/amrnb/enc/src/l_negate.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/l_negate.cpp
rename to media/codecs/amrnb/enc/src/l_negate.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lag_wind.cpp b/media/codecs/amrnb/enc/src/lag_wind.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/lag_wind.cpp
rename to media/codecs/amrnb/enc/src/lag_wind.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lag_wind.h b/media/codecs/amrnb/enc/src/lag_wind.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/lag_wind.h
rename to media/codecs/amrnb/enc/src/lag_wind.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.cpp b/media/codecs/amrnb/enc/src/lag_wind_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.cpp
rename to media/codecs/amrnb/enc/src/lag_wind_tab.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.h b/media/codecs/amrnb/enc/src/lag_wind_tab.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.h
rename to media/codecs/amrnb/enc/src/lag_wind_tab.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/levinson.cpp b/media/codecs/amrnb/enc/src/levinson.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/levinson.cpp
rename to media/codecs/amrnb/enc/src/levinson.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/levinson.h b/media/codecs/amrnb/enc/src/levinson.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/levinson.h
rename to media/codecs/amrnb/enc/src/levinson.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lpc.cpp b/media/codecs/amrnb/enc/src/lpc.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/lpc.cpp
rename to media/codecs/amrnb/enc/src/lpc.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lpc.h b/media/codecs/amrnb/enc/src/lpc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/lpc.h
rename to media/codecs/amrnb/enc/src/lpc.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ol_ltp.cpp b/media/codecs/amrnb/enc/src/ol_ltp.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/ol_ltp.cpp
rename to media/codecs/amrnb/enc/src/ol_ltp.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ol_ltp.h b/media/codecs/amrnb/enc/src/ol_ltp.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/ol_ltp.h
rename to media/codecs/amrnb/enc/src/ol_ltp.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/p_ol_wgh.cpp b/media/codecs/amrnb/enc/src/p_ol_wgh.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/p_ol_wgh.cpp
rename to media/codecs/amrnb/enc/src/p_ol_wgh.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pitch_fr.cpp b/media/codecs/amrnb/enc/src/pitch_fr.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/pitch_fr.cpp
rename to media/codecs/amrnb/enc/src/pitch_fr.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pitch_fr.h b/media/codecs/amrnb/enc/src/pitch_fr.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/pitch_fr.h
rename to media/codecs/amrnb/enc/src/pitch_fr.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pitch_ol.cpp b/media/codecs/amrnb/enc/src/pitch_ol.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/pitch_ol.cpp
rename to media/codecs/amrnb/enc/src/pitch_ol.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pitch_ol.h b/media/codecs/amrnb/enc/src/pitch_ol.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/pitch_ol.h
rename to media/codecs/amrnb/enc/src/pitch_ol.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pre_big.cpp b/media/codecs/amrnb/enc/src/pre_big.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/pre_big.cpp
rename to media/codecs/amrnb/enc/src/pre_big.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pre_big.h b/media/codecs/amrnb/enc/src/pre_big.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/pre_big.h
rename to media/codecs/amrnb/enc/src/pre_big.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pre_proc.cpp b/media/codecs/amrnb/enc/src/pre_proc.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/pre_proc.cpp
rename to media/codecs/amrnb/enc/src/pre_proc.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pre_proc.h b/media/codecs/amrnb/enc/src/pre_proc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/pre_proc.h
rename to media/codecs/amrnb/enc/src/pre_proc.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/prm2bits.cpp b/media/codecs/amrnb/enc/src/prm2bits.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/prm2bits.cpp
rename to media/codecs/amrnb/enc/src/prm2bits.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/prm2bits.h b/media/codecs/amrnb/enc/src/prm2bits.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/prm2bits.h
rename to media/codecs/amrnb/enc/src/prm2bits.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/q_gain_c.cpp b/media/codecs/amrnb/enc/src/q_gain_c.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/q_gain_c.cpp
rename to media/codecs/amrnb/enc/src/q_gain_c.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/q_gain_c.h b/media/codecs/amrnb/enc/src/q_gain_c.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/q_gain_c.h
rename to media/codecs/amrnb/enc/src/q_gain_c.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/q_gain_p.cpp b/media/codecs/amrnb/enc/src/q_gain_p.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/q_gain_p.cpp
rename to media/codecs/amrnb/enc/src/q_gain_p.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/q_gain_p.h b/media/codecs/amrnb/enc/src/q_gain_p.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/q_gain_p.h
rename to media/codecs/amrnb/enc/src/q_gain_p.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qgain475.cpp b/media/codecs/amrnb/enc/src/qgain475.cpp
similarity index 99%
rename from media/libstagefright/codecs/amrnb/enc/src/qgain475.cpp
rename to media/codecs/amrnb/enc/src/qgain475.cpp
index f8da589..08a5c15 100644
--- a/media/libstagefright/codecs/amrnb/enc/src/qgain475.cpp
+++ b/media/codecs/amrnb/enc/src/qgain475.cpp
@@ -1106,7 +1106,7 @@
     // the real, quantized gains)
     gc_pred(pred_st, MR475, sf1_code_nosharp,
             &sf1_exp_gcode0, &sf1_frac_gcode0,
-            &sf0_exp_gcode0, &sf0_gcode0); // last two args are dummy
+            &sf0_exp_gcode0, &sf0_gcode0); // last two args are unused
     sf1_gcode0 = extract_l(Pow2(14, sf1_frac_gcode0));
 
     tmp = add (tmp, 2);
@@ -1426,7 +1426,7 @@
        the real, quantized gains)                                   */
     gc_pred(pred_st, MR475, sf1_code_nosharp,
             &sf1_exp_gcode0, &sf1_frac_gcode0,
-            &sf0_exp_gcode0, &sf0_gcode0, /* dummy args */
+            &sf0_exp_gcode0, &sf0_gcode0, /* unused args */
             pOverflow);
 
     sf1_gcode0 = (Word16)(Pow2(14, sf1_frac_gcode0, pOverflow));
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qgain475.h b/media/codecs/amrnb/enc/src/qgain475.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/qgain475.h
rename to media/codecs/amrnb/enc/src/qgain475.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qgain795.cpp b/media/codecs/amrnb/enc/src/qgain795.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/qgain795.cpp
rename to media/codecs/amrnb/enc/src/qgain795.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qgain795.h b/media/codecs/amrnb/enc/src/qgain795.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/qgain795.h
rename to media/codecs/amrnb/enc/src/qgain795.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qua_gain.cpp b/media/codecs/amrnb/enc/src/qua_gain.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/qua_gain.cpp
rename to media/codecs/amrnb/enc/src/qua_gain.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/s10_8pf.cpp b/media/codecs/amrnb/enc/src/s10_8pf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/s10_8pf.cpp
rename to media/codecs/amrnb/enc/src/s10_8pf.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/s10_8pf.h b/media/codecs/amrnb/enc/src/s10_8pf.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/s10_8pf.h
rename to media/codecs/amrnb/enc/src/s10_8pf.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/set_sign.cpp b/media/codecs/amrnb/enc/src/set_sign.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/set_sign.cpp
rename to media/codecs/amrnb/enc/src/set_sign.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/set_sign.h b/media/codecs/amrnb/enc/src/set_sign.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/set_sign.h
rename to media/codecs/amrnb/enc/src/set_sign.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/sid_sync.cpp b/media/codecs/amrnb/enc/src/sid_sync.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/sid_sync.cpp
rename to media/codecs/amrnb/enc/src/sid_sync.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/sid_sync.h b/media/codecs/amrnb/enc/src/sid_sync.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/sid_sync.h
rename to media/codecs/amrnb/enc/src/sid_sync.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/sp_enc.cpp b/media/codecs/amrnb/enc/src/sp_enc.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/sp_enc.cpp
rename to media/codecs/amrnb/enc/src/sp_enc.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/sp_enc.h b/media/codecs/amrnb/enc/src/sp_enc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/sp_enc.h
rename to media/codecs/amrnb/enc/src/sp_enc.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/spreproc.cpp b/media/codecs/amrnb/enc/src/spreproc.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/spreproc.cpp
rename to media/codecs/amrnb/enc/src/spreproc.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/spreproc.h b/media/codecs/amrnb/enc/src/spreproc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/spreproc.h
rename to media/codecs/amrnb/enc/src/spreproc.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/spstproc.cpp b/media/codecs/amrnb/enc/src/spstproc.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/spstproc.cpp
rename to media/codecs/amrnb/enc/src/spstproc.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/spstproc.h b/media/codecs/amrnb/enc/src/spstproc.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/spstproc.h
rename to media/codecs/amrnb/enc/src/spstproc.h
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ton_stab.cpp b/media/codecs/amrnb/enc/src/ton_stab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/ton_stab.cpp
rename to media/codecs/amrnb/enc/src/ton_stab.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ton_stab.h b/media/codecs/amrnb/enc/src/ton_stab.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/src/ton_stab.h
rename to media/codecs/amrnb/enc/src/ton_stab.h
diff --git a/media/libstagefright/codecs/amrnb/enc/test/AmrnbEncTestEnvironment.h b/media/codecs/amrnb/enc/test/AmrnbEncTestEnvironment.h
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/test/AmrnbEncTestEnvironment.h
rename to media/codecs/amrnb/enc/test/AmrnbEncTestEnvironment.h
diff --git a/media/libstagefright/codecs/amrnb/enc/test/AmrnbEncoderTest.cpp b/media/codecs/amrnb/enc/test/AmrnbEncoderTest.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/test/AmrnbEncoderTest.cpp
rename to media/codecs/amrnb/enc/test/AmrnbEncoderTest.cpp
diff --git a/media/libstagefright/codecs/amrnb/enc/test/Android.bp b/media/codecs/amrnb/enc/test/Android.bp
similarity index 72%
rename from media/libstagefright/codecs/amrnb/enc/test/Android.bp
rename to media/codecs/amrnb/enc/test/Android.bp
index e8982fe..a94ffd4 100644
--- a/media/libstagefright/codecs/amrnb/enc/test/Android.bp
+++ b/media/codecs/amrnb/enc/test/Android.bp
@@ -14,6 +14,18 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_amrnb_enc_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-BSD
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrnb_enc_license",
+    ],
+}
+
 cc_test {
     name: "AmrnbEncoderTest",
     gtest: true,
diff --git a/media/libstagefright/codecs/amrnb/enc/test/AndroidTest.xml b/media/codecs/amrnb/enc/test/AndroidTest.xml
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/test/AndroidTest.xml
rename to media/codecs/amrnb/enc/test/AndroidTest.xml
diff --git a/media/libstagefright/codecs/amrnb/enc/test/README.md b/media/codecs/amrnb/enc/test/README.md
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/test/README.md
rename to media/codecs/amrnb/enc/test/README.md
diff --git a/media/libstagefright/codecs/amrnb/enc/test/amrnb_enc_test.cpp b/media/codecs/amrnb/enc/test/amrnb_enc_test.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrnb/enc/test/amrnb_enc_test.cpp
rename to media/codecs/amrnb/enc/test/amrnb_enc_test.cpp
diff --git a/media/libstagefright/codecs/amrnb/fuzzer/Android.bp b/media/codecs/amrnb/fuzzer/Android.bp
similarity index 71%
rename from media/libstagefright/codecs/amrnb/fuzzer/Android.bp
rename to media/codecs/amrnb/fuzzer/Android.bp
index 54de1cc..833a7ba 100644
--- a/media/libstagefright/codecs/amrnb/fuzzer/Android.bp
+++ b/media/codecs/amrnb/fuzzer/Android.bp
@@ -18,6 +18,15 @@
  * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_fuzz {
     name: "amrnb_dec_fuzzer",
     host_supported: true,
@@ -34,4 +43,10 @@
             enabled: false,
         },
     },
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
 }
diff --git a/media/libstagefright/codecs/amrnb/fuzzer/README.md b/media/codecs/amrnb/fuzzer/README.md
similarity index 100%
rename from media/libstagefright/codecs/amrnb/fuzzer/README.md
rename to media/codecs/amrnb/fuzzer/README.md
diff --git a/media/libstagefright/codecs/amrnb/fuzzer/amrnb_dec_fuzzer.cpp b/media/codecs/amrnb/fuzzer/amrnb_dec_fuzzer.cpp
similarity index 89%
rename from media/libstagefright/codecs/amrnb/fuzzer/amrnb_dec_fuzzer.cpp
rename to media/codecs/amrnb/fuzzer/amrnb_dec_fuzzer.cpp
index d4e7e5c..c7a7378 100644
--- a/media/libstagefright/codecs/amrnb/fuzzer/amrnb_dec_fuzzer.cpp
+++ b/media/codecs/amrnb/fuzzer/amrnb_dec_fuzzer.cpp
@@ -26,8 +26,10 @@
 constexpr int32_t kBitsPerSample = 16;
 constexpr int32_t kOutputBufferSize = kSamplesPerFrame * kBitsPerSample / 8;
 const bitstream_format kBitStreamFormats[2] = {MIME_IETF, IF2};
-const int32_t kLocalWmfDecBytesPerFrame[8] = {12, 13, 15, 17, 19, 20, 26, 31};
-const int32_t kLocalIf2DecBytesPerFrame[8] = {13, 14, 16, 18, 19, 21, 26, 31};
+const int32_t kLocalWmfDecBytesPerFrame[16] = {12, 13, 15, 17, 19, 20, 26, 31,
+                                               5,  6,  5,  5,  0,  0,  0,  0};
+const int32_t kLocalIf2DecBytesPerFrame[16] = {13, 14, 16, 18, 19, 21, 26, 31,
+                                               13, 14, 16, 18, 19, 21, 26, 31};
 
 class Codec {
  public:
@@ -52,7 +54,7 @@
     bitstream_format bitsreamFormat = kBitStreamFormats[bit];
     int32_t frameSize = 0;
     /* Find frame type */
-    Frame_Type_3GPP frameType = static_cast<Frame_Type_3GPP>((mode >> 3) & 0x07);
+    Frame_Type_3GPP frameType = static_cast<Frame_Type_3GPP>((mode >> 3) & 0x0f);
     ++data;
     --size;
     if (bit) {
diff --git a/media/libstagefright/codecs/amrnb/patent_disclaimer.txt b/media/codecs/amrnb/patent_disclaimer.txt
similarity index 100%
rename from media/libstagefright/codecs/amrnb/patent_disclaimer.txt
rename to media/codecs/amrnb/patent_disclaimer.txt
diff --git a/media/libstagefright/codecs/amrwb/Android.bp b/media/codecs/amrwb/dec/Android.bp
similarity index 67%
rename from media/libstagefright/codecs/amrwb/Android.bp
rename to media/codecs/amrwb/dec/Android.bp
index 204cbe3..228ea80 100644
--- a/media/libstagefright/codecs/amrwb/Android.bp
+++ b/media/codecs/amrwb/dec/Android.bp
@@ -1,3 +1,35 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrwb_dec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codecs_amrwb_dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-BSD",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_static {
     name: "libstagefright_amrwbdec",
     vendor_available: true,
diff --git a/media/libstagefright/codecs/amrnb/dec/MODULE_LICENSE_APACHE2 b/media/codecs/amrwb/dec/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/codecs/amrnb/dec/MODULE_LICENSE_APACHE2
copy to media/codecs/amrwb/dec/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/codecs/amrnb/dec/NOTICE b/media/codecs/amrwb/dec/NOTICE
similarity index 100%
copy from media/libstagefright/codecs/amrnb/dec/NOTICE
copy to media/codecs/amrwb/dec/NOTICE
diff --git a/media/codecs/amrwb/dec/TEST_MAPPING b/media/codecs/amrwb/dec/TEST_MAPPING
new file mode 100644
index 0000000..0278d26
--- /dev/null
+++ b/media/codecs/amrwb/dec/TEST_MAPPING
@@ -0,0 +1,10 @@
+// mappings for frameworks/av/media/libstagefright/codecs/amrwb
+{
+  // tests which require dynamic content
+  // invoke with: atest -- --enable-module-dynamic-download=true
+  // TODO(b/148094059): unit tests not allowed to download content
+  "dynamic-presubmit": [
+    { "name": "AmrwbDecoderTest"}
+
+  ]
+}
diff --git a/media/libstagefright/codecs/amrwb/fuzzer/Android.bp b/media/codecs/amrwb/dec/fuzzer/Android.bp
similarity index 67%
rename from media/libstagefright/codecs/amrwb/fuzzer/Android.bp
rename to media/codecs/amrwb/dec/fuzzer/Android.bp
index 46f77e3..16f08fa 100644
--- a/media/libstagefright/codecs/amrwb/fuzzer/Android.bp
+++ b/media/codecs/amrwb/dec/fuzzer/Android.bp
@@ -18,6 +18,17 @@
  * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_amrwb_dec_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrwb_dec_license",
+    ],
+}
+
 cc_fuzz {
     name: "amrwb_dec_fuzzer",
     host_supported: true,
@@ -32,4 +43,10 @@
             enabled: false,
         },
     },
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
 }
diff --git a/media/libstagefright/codecs/amrwb/fuzzer/README.md b/media/codecs/amrwb/dec/fuzzer/README.md
similarity index 100%
rename from media/libstagefright/codecs/amrwb/fuzzer/README.md
rename to media/codecs/amrwb/dec/fuzzer/README.md
diff --git a/media/libstagefright/codecs/amrwb/fuzzer/amrwb_dec_fuzzer.cpp b/media/codecs/amrwb/dec/fuzzer/amrwb_dec_fuzzer.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/fuzzer/amrwb_dec_fuzzer.cpp
rename to media/codecs/amrwb/dec/fuzzer/amrwb_dec_fuzzer.cpp
diff --git a/media/libstagefright/codecs/amrwb/include/pvamrwbdecoder_api.h b/media/codecs/amrwb/dec/include/pvamrwbdecoder_api.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/include/pvamrwbdecoder_api.h
rename to media/codecs/amrwb/dec/include/pvamrwbdecoder_api.h
diff --git a/media/libstagefright/codecs/mp3dec/patent_disclaimer.txt b/media/codecs/amrwb/dec/patent_disclaimer.txt
similarity index 100%
copy from media/libstagefright/codecs/mp3dec/patent_disclaimer.txt
copy to media/codecs/amrwb/dec/patent_disclaimer.txt
diff --git a/media/libstagefright/codecs/amrwb/src/agc2_amr_wb.cpp b/media/codecs/amrwb/dec/src/agc2_amr_wb.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/agc2_amr_wb.cpp
rename to media/codecs/amrwb/dec/src/agc2_amr_wb.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/band_pass_6k_7k.cpp b/media/codecs/amrwb/dec/src/band_pass_6k_7k.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/band_pass_6k_7k.cpp
rename to media/codecs/amrwb/dec/src/band_pass_6k_7k.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/dec_acelp_2p_in_64.cpp b/media/codecs/amrwb/dec/src/dec_acelp_2p_in_64.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/dec_acelp_2p_in_64.cpp
rename to media/codecs/amrwb/dec/src/dec_acelp_2p_in_64.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/dec_acelp_4p_in_64.cpp b/media/codecs/amrwb/dec/src/dec_acelp_4p_in_64.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/dec_acelp_4p_in_64.cpp
rename to media/codecs/amrwb/dec/src/dec_acelp_4p_in_64.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/dec_alg_codebook.cpp b/media/codecs/amrwb/dec/src/dec_alg_codebook.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/dec_alg_codebook.cpp
rename to media/codecs/amrwb/dec/src/dec_alg_codebook.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/dec_gain2_amr_wb.cpp b/media/codecs/amrwb/dec/src/dec_gain2_amr_wb.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/dec_gain2_amr_wb.cpp
rename to media/codecs/amrwb/dec/src/dec_gain2_amr_wb.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/deemphasis_32.cpp b/media/codecs/amrwb/dec/src/deemphasis_32.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/deemphasis_32.cpp
rename to media/codecs/amrwb/dec/src/deemphasis_32.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/dtx.h b/media/codecs/amrwb/dec/src/dtx.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/dtx.h
rename to media/codecs/amrwb/dec/src/dtx.h
diff --git a/media/libstagefright/codecs/amrwb/src/dtx_decoder_amr_wb.cpp b/media/codecs/amrwb/dec/src/dtx_decoder_amr_wb.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/dtx_decoder_amr_wb.cpp
rename to media/codecs/amrwb/dec/src/dtx_decoder_amr_wb.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/e_pv_amrwbdec.h b/media/codecs/amrwb/dec/src/e_pv_amrwbdec.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/e_pv_amrwbdec.h
rename to media/codecs/amrwb/dec/src/e_pv_amrwbdec.h
diff --git a/media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.cpp b/media/codecs/amrwb/dec/src/get_amr_wb_bits.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.cpp
rename to media/codecs/amrwb/dec/src/get_amr_wb_bits.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.h b/media/codecs/amrwb/dec/src/get_amr_wb_bits.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.h
rename to media/codecs/amrwb/dec/src/get_amr_wb_bits.h
diff --git a/media/libstagefright/codecs/amrwb/src/highpass_400hz_at_12k8.cpp b/media/codecs/amrwb/dec/src/highpass_400hz_at_12k8.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/highpass_400hz_at_12k8.cpp
rename to media/codecs/amrwb/dec/src/highpass_400hz_at_12k8.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/highpass_50hz_at_12k8.cpp b/media/codecs/amrwb/dec/src/highpass_50hz_at_12k8.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/highpass_50hz_at_12k8.cpp
rename to media/codecs/amrwb/dec/src/highpass_50hz_at_12k8.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/homing_amr_wb_dec.cpp b/media/codecs/amrwb/dec/src/homing_amr_wb_dec.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/homing_amr_wb_dec.cpp
rename to media/codecs/amrwb/dec/src/homing_amr_wb_dec.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/interpolate_isp.cpp b/media/codecs/amrwb/dec/src/interpolate_isp.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/interpolate_isp.cpp
rename to media/codecs/amrwb/dec/src/interpolate_isp.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/isf_extrapolation.cpp b/media/codecs/amrwb/dec/src/isf_extrapolation.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/isf_extrapolation.cpp
rename to media/codecs/amrwb/dec/src/isf_extrapolation.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/isp_az.cpp b/media/codecs/amrwb/dec/src/isp_az.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/isp_az.cpp
rename to media/codecs/amrwb/dec/src/isp_az.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/isp_isf.cpp b/media/codecs/amrwb/dec/src/isp_isf.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/isp_isf.cpp
rename to media/codecs/amrwb/dec/src/isp_isf.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/lagconceal.cpp b/media/codecs/amrwb/dec/src/lagconceal.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/lagconceal.cpp
rename to media/codecs/amrwb/dec/src/lagconceal.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/low_pass_filt_7k.cpp b/media/codecs/amrwb/dec/src/low_pass_filt_7k.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/low_pass_filt_7k.cpp
rename to media/codecs/amrwb/dec/src/low_pass_filt_7k.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/median5.cpp b/media/codecs/amrwb/dec/src/median5.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/median5.cpp
rename to media/codecs/amrwb/dec/src/median5.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/mime_io.cpp b/media/codecs/amrwb/dec/src/mime_io.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/mime_io.cpp
rename to media/codecs/amrwb/dec/src/mime_io.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/mime_io.h b/media/codecs/amrwb/dec/src/mime_io.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/mime_io.h
rename to media/codecs/amrwb/dec/src/mime_io.h
diff --git a/media/libstagefright/codecs/amrwb/src/noise_gen_amrwb.cpp b/media/codecs/amrwb/dec/src/noise_gen_amrwb.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/noise_gen_amrwb.cpp
rename to media/codecs/amrwb/dec/src/noise_gen_amrwb.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/normalize_amr_wb.cpp b/media/codecs/amrwb/dec/src/normalize_amr_wb.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/normalize_amr_wb.cpp
rename to media/codecs/amrwb/dec/src/normalize_amr_wb.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/normalize_amr_wb.h b/media/codecs/amrwb/dec/src/normalize_amr_wb.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/normalize_amr_wb.h
rename to media/codecs/amrwb/dec/src/normalize_amr_wb.h
diff --git a/media/libstagefright/codecs/amrwb/src/oversamp_12k8_to_16k.cpp b/media/codecs/amrwb/dec/src/oversamp_12k8_to_16k.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/oversamp_12k8_to_16k.cpp
rename to media/codecs/amrwb/dec/src/oversamp_12k8_to_16k.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/phase_dispersion.cpp b/media/codecs/amrwb/dec/src/phase_dispersion.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/phase_dispersion.cpp
rename to media/codecs/amrwb/dec/src/phase_dispersion.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/pit_shrp.cpp b/media/codecs/amrwb/dec/src/pit_shrp.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pit_shrp.cpp
rename to media/codecs/amrwb/dec/src/pit_shrp.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/pred_lt4.cpp b/media/codecs/amrwb/dec/src/pred_lt4.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pred_lt4.cpp
rename to media/codecs/amrwb/dec/src/pred_lt4.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/preemph_amrwb_dec.cpp b/media/codecs/amrwb/dec/src/preemph_amrwb_dec.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/preemph_amrwb_dec.cpp
rename to media/codecs/amrwb/dec/src/preemph_amrwb_dec.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/pv_amr_wb_type_defs.h b/media/codecs/amrwb/dec/src/pv_amr_wb_type_defs.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pv_amr_wb_type_defs.h
rename to media/codecs/amrwb/dec/src/pv_amr_wb_type_defs.h
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.cpp b/media/codecs/amrwb/dec/src/pvamrwb_math_op.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.cpp
rename to media/codecs/amrwb/dec/src/pvamrwb_math_op.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.h b/media/codecs/amrwb/dec/src/pvamrwb_math_op.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.h
rename to media/codecs/amrwb/dec/src/pvamrwb_math_op.h
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.cpp b/media/codecs/amrwb/dec/src/pvamrwbdecoder.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.cpp
rename to media/codecs/amrwb/dec/src/pvamrwbdecoder.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.h b/media/codecs/amrwb/dec/src/pvamrwbdecoder.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.h
rename to media/codecs/amrwb/dec/src/pvamrwbdecoder.h
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_acelp.h b/media/codecs/amrwb/dec/src/pvamrwbdecoder_acelp.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_acelp.h
rename to media/codecs/amrwb/dec/src/pvamrwbdecoder_acelp.h
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op.h b/media/codecs/amrwb/dec/src/pvamrwbdecoder_basic_op.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op.h
rename to media/codecs/amrwb/dec/src/pvamrwbdecoder_basic_op.h
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_armv5.h b/media/codecs/amrwb/dec/src/pvamrwbdecoder_basic_op_armv5.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_armv5.h
rename to media/codecs/amrwb/dec/src/pvamrwbdecoder_basic_op_armv5.h
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_cequivalent.h b/media/codecs/amrwb/dec/src/pvamrwbdecoder_basic_op_cequivalent.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_cequivalent.h
rename to media/codecs/amrwb/dec/src/pvamrwbdecoder_basic_op_cequivalent.h
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_gcc_armv5.h b/media/codecs/amrwb/dec/src/pvamrwbdecoder_basic_op_gcc_armv5.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_gcc_armv5.h
rename to media/codecs/amrwb/dec/src/pvamrwbdecoder_basic_op_gcc_armv5.h
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_cnst.h b/media/codecs/amrwb/dec/src/pvamrwbdecoder_cnst.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_cnst.h
rename to media/codecs/amrwb/dec/src/pvamrwbdecoder_cnst.h
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_mem_funcs.h b/media/codecs/amrwb/dec/src/pvamrwbdecoder_mem_funcs.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_mem_funcs.h
rename to media/codecs/amrwb/dec/src/pvamrwbdecoder_mem_funcs.h
diff --git a/media/libstagefright/codecs/amrwb/src/q_gain2_tab.cpp b/media/codecs/amrwb/dec/src/q_gain2_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/q_gain2_tab.cpp
rename to media/codecs/amrwb/dec/src/q_gain2_tab.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/q_pulse.h b/media/codecs/amrwb/dec/src/q_pulse.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/q_pulse.h
rename to media/codecs/amrwb/dec/src/q_pulse.h
diff --git a/media/libstagefright/codecs/amrwb/src/qisf_ns.cpp b/media/codecs/amrwb/dec/src/qisf_ns.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/qisf_ns.cpp
rename to media/codecs/amrwb/dec/src/qisf_ns.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/qisf_ns.h b/media/codecs/amrwb/dec/src/qisf_ns.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/qisf_ns.h
rename to media/codecs/amrwb/dec/src/qisf_ns.h
diff --git a/media/libstagefright/codecs/amrwb/src/qisf_ns_tab.cpp b/media/codecs/amrwb/dec/src/qisf_ns_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/qisf_ns_tab.cpp
rename to media/codecs/amrwb/dec/src/qisf_ns_tab.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/qpisf_2s.cpp b/media/codecs/amrwb/dec/src/qpisf_2s.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/qpisf_2s.cpp
rename to media/codecs/amrwb/dec/src/qpisf_2s.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/qpisf_2s.h b/media/codecs/amrwb/dec/src/qpisf_2s.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/qpisf_2s.h
rename to media/codecs/amrwb/dec/src/qpisf_2s.h
diff --git a/media/libstagefright/codecs/amrwb/src/qpisf_2s_tab.cpp b/media/codecs/amrwb/dec/src/qpisf_2s_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/qpisf_2s_tab.cpp
rename to media/codecs/amrwb/dec/src/qpisf_2s_tab.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/scale_signal.cpp b/media/codecs/amrwb/dec/src/scale_signal.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/scale_signal.cpp
rename to media/codecs/amrwb/dec/src/scale_signal.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.cpp b/media/codecs/amrwb/dec/src/synthesis_amr_wb.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.cpp
rename to media/codecs/amrwb/dec/src/synthesis_amr_wb.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.h b/media/codecs/amrwb/dec/src/synthesis_amr_wb.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.h
rename to media/codecs/amrwb/dec/src/synthesis_amr_wb.h
diff --git a/media/libstagefright/codecs/amrwb/src/voice_factor.cpp b/media/codecs/amrwb/dec/src/voice_factor.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/voice_factor.cpp
rename to media/codecs/amrwb/dec/src/voice_factor.cpp
diff --git a/media/libstagefright/codecs/amrwb/src/wb_syn_filt.cpp b/media/codecs/amrwb/dec/src/wb_syn_filt.cpp
similarity index 95%
rename from media/libstagefright/codecs/amrwb/src/wb_syn_filt.cpp
rename to media/codecs/amrwb/dec/src/wb_syn_filt.cpp
index e1af6d4..f12828d 100644
--- a/media/libstagefright/codecs/amrwb/src/wb_syn_filt.cpp
+++ b/media/codecs/amrwb/dec/src/wb_syn_filt.cpp
@@ -181,12 +181,14 @@
         L_tmp4  = fxp_mac_16by16(yy[(i<<2)+3  - j], a[j], L_tmp4);
 
         L_tmp1 = shl_int32(L_tmp1, 4);
+        L_tmp1 = L_tmp1 == INT32_MIN ? INT32_MIN + 1 : L_tmp1;
 
         y[(i<<2)] = yy[(i<<2)] = amr_wb_round(-L_tmp1);
 
         L_tmp2  = fxp_mac_16by16(yy[(i<<2)], a[1], L_tmp2);
 
         L_tmp2 = shl_int32(L_tmp2, 4);
+        L_tmp2 = L_tmp2 == INT32_MIN ? INT32_MIN + 1 : L_tmp2;
 
         y[(i<<2)+1] = yy[(i<<2)+1] = amr_wb_round(-L_tmp2);
 
@@ -197,12 +199,14 @@
         L_tmp3  = fxp_mac_16by16(yy[(i<<2) + 1], a[1], L_tmp3);
 
         L_tmp3 = shl_int32(L_tmp3, 4);
+        L_tmp3 = L_tmp3 == INT32_MIN ? INT32_MIN + 1 : L_tmp3;
 
         y[(i<<2)+2] = yy[(i<<2)+2] = amr_wb_round(-L_tmp3);
 
         L_tmp4  = fxp_mac_16by16(yy[(i<<2)+2], a[1], L_tmp4);
 
         L_tmp4 = shl_int32(L_tmp4, 4);
+        L_tmp4 = L_tmp4 == INT32_MIN ? INT32_MIN + 1 : L_tmp4;
 
         y[(i<<2)+3] = yy[(i<<2)+3] = amr_wb_round(-L_tmp4);
     }
@@ -273,9 +277,10 @@
 
         L_tmp1 >>= 11;      /* -4 : sig_lo[i] << 4 */
 
-        L_tmp1 += (int32)exc[(i<<1)] << a0;
+        int64 sig_tmp;
+        sig_tmp = (int64)L_tmp1 + (int32)(exc[(i<<1)] << a0);
+        L_tmp1 = (int32)(sig_tmp - (L_tmp2 << 1));
 
-        L_tmp1 -= (L_tmp2 << 1);
         /* sig_hi = bit16 to bit31 of synthesis */
         L_tmp1 = shl_int32(L_tmp1, 3);           /* ai in Q12 */
 
@@ -290,9 +295,8 @@
         L_tmp3 = fxp_mac_16by16(sig_lo[(i<<1)], a[1], L_tmp3);
         L_tmp3 = -L_tmp3 >> 11;
 
-        L_tmp3 += (int32)exc[(i<<1)+1] << a0;
-
-        L_tmp3 -= (L_tmp4 << 1);
+        sig_tmp = (int64)L_tmp3 + (int32)(exc[(i<<1)+1] << a0);
+        L_tmp3 = (int32)(sig_tmp - (L_tmp4 << 1));
         /* sig_hi = bit16 to bit31 of synthesis */
         L_tmp3 = shl_int32(L_tmp3, 3);           /* ai in Q12 */
         sig_hi[(i<<1)+1] = (int16)(L_tmp3 >> 16);
diff --git a/media/libstagefright/codecs/amrwb/src/weight_amrwb_lpc.cpp b/media/codecs/amrwb/dec/src/weight_amrwb_lpc.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/src/weight_amrwb_lpc.cpp
rename to media/codecs/amrwb/dec/src/weight_amrwb_lpc.cpp
diff --git a/media/libstagefright/codecs/amrwb/test/AmrwbDecTestEnvironment.h b/media/codecs/amrwb/dec/test/AmrwbDecTestEnvironment.h
similarity index 100%
rename from media/libstagefright/codecs/amrwb/test/AmrwbDecTestEnvironment.h
rename to media/codecs/amrwb/dec/test/AmrwbDecTestEnvironment.h
diff --git a/media/libstagefright/codecs/amrwb/test/AmrwbDecoderTest.cpp b/media/codecs/amrwb/dec/test/AmrwbDecoderTest.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/test/AmrwbDecoderTest.cpp
rename to media/codecs/amrwb/dec/test/AmrwbDecoderTest.cpp
diff --git a/media/libstagefright/codecs/amrwb/test/Android.bp b/media/codecs/amrwb/dec/test/Android.bp
similarity index 71%
rename from media/libstagefright/codecs/amrwb/test/Android.bp
rename to media/codecs/amrwb/dec/test/Android.bp
index 968215a..cc120d3 100644
--- a/media/libstagefright/codecs/amrwb/test/Android.bp
+++ b/media/codecs/amrwb/dec/test/Android.bp
@@ -14,6 +14,18 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_amrwb_dec_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-BSD
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrwb_dec_license",
+    ],
+}
+
 cc_test {
     name: "AmrwbDecoderTest",
     gtest: true,
diff --git a/media/libstagefright/codecs/amrwb/test/AndroidTest.xml b/media/codecs/amrwb/dec/test/AndroidTest.xml
similarity index 100%
rename from media/libstagefright/codecs/amrwb/test/AndroidTest.xml
rename to media/codecs/amrwb/dec/test/AndroidTest.xml
diff --git a/media/libstagefright/codecs/amrwb/test/README.md b/media/codecs/amrwb/dec/test/README.md
similarity index 100%
rename from media/libstagefright/codecs/amrwb/test/README.md
rename to media/codecs/amrwb/dec/test/README.md
diff --git a/media/libstagefright/codecs/amrwb/test/amrwbdec_test.cpp b/media/codecs/amrwb/dec/test/amrwbdec_test.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwb/test/amrwbdec_test.cpp
rename to media/codecs/amrwb/dec/test/amrwbdec_test.cpp
diff --git a/media/codecs/amrwb/enc/Android.bp b/media/codecs/amrwb/enc/Android.bp
new file mode 100644
index 0000000..cc72eb7
--- /dev/null
+++ b/media/codecs/amrwb/enc/Android.bp
@@ -0,0 +1,166 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrwb_enc_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codecs_amrwb_enc_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library_static {
+    name: "libstagefright_amrwbenc",
+    vendor_available: true,
+    min_sdk_version: "29",
+
+    srcs: [
+        "src/autocorr.c",
+        "src/az_isp.c",
+        "src/bits.c",
+        "src/c2t64fx.c",
+        "src/c4t64fx.c",
+        "src/convolve.c",
+        "src/cor_h_x.c",
+        "src/decim54.c",
+        "src/deemph.c",
+        "src/dtx.c",
+        "src/g_pitch.c",
+        "src/gpclip.c",
+        "src/homing.c",
+        "src/hp400.c",
+        "src/hp50.c",
+        "src/hp6k.c",
+        "src/hp_wsp.c",
+        "src/int_lpc.c",
+        "src/isp_az.c",
+        "src/isp_isf.c",
+        "src/lag_wind.c",
+        "src/levinson.c",
+        "src/log2.c",
+        "src/lp_dec2.c",
+        "src/math_op.c",
+        "src/oper_32b.c",
+        "src/p_med_ol.c",
+        "src/pit_shrp.c",
+        "src/pitch_f4.c",
+        "src/pred_lt4.c",
+        "src/preemph.c",
+        "src/q_gain2.c",
+        "src/q_pulse.c",
+        "src/qisf_ns.c",
+        "src/qpisf_2s.c",
+        "src/random.c",
+        "src/residu.c",
+        "src/scale.c",
+        "src/stream.c",
+        "src/syn_filt.c",
+        "src/updt_tar.c",
+        "src/util.c",
+        "src/voAMRWBEnc.c",
+        "src/voicefac.c",
+        "src/wb_vad.c",
+        "src/weight_a.c",
+        "src/mem_align.c",
+    ],
+
+    arch: {
+        arm: {
+            srcs: [
+                "src/asm/ARMV5E/convolve_opt.s",
+                "src/asm/ARMV5E/cor_h_vec_opt.s",
+                "src/asm/ARMV5E/Deemph_32_opt.s",
+                "src/asm/ARMV5E/Dot_p_opt.s",
+                "src/asm/ARMV5E/Filt_6k_7k_opt.s",
+                "src/asm/ARMV5E/Norm_Corr_opt.s",
+                "src/asm/ARMV5E/pred_lt4_1_opt.s",
+                "src/asm/ARMV5E/residu_asm_opt.s",
+                "src/asm/ARMV5E/scale_sig_opt.s",
+                "src/asm/ARMV5E/Syn_filt_32_opt.s",
+                "src/asm/ARMV5E/syn_filt_opt.s",
+            ],
+
+            cflags: [
+                "-DARM",
+                "-DASM_OPT",
+            ],
+            local_include_dirs: ["src/asm/ARMV5E"],
+
+            instruction_set: "arm",
+
+            neon: {
+                exclude_srcs: [
+                    "src/asm/ARMV5E/convolve_opt.s",
+                    "src/asm/ARMV5E/cor_h_vec_opt.s",
+                    "src/asm/ARMV5E/Deemph_32_opt.s",
+                    "src/asm/ARMV5E/Dot_p_opt.s",
+                    "src/asm/ARMV5E/Filt_6k_7k_opt.s",
+                    "src/asm/ARMV5E/Norm_Corr_opt.s",
+                    "src/asm/ARMV5E/pred_lt4_1_opt.s",
+                    "src/asm/ARMV5E/residu_asm_opt.s",
+                    "src/asm/ARMV5E/scale_sig_opt.s",
+                    "src/asm/ARMV5E/Syn_filt_32_opt.s",
+                    "src/asm/ARMV5E/syn_filt_opt.s",
+                ],
+
+                srcs: [
+                    "src/asm/ARMV7/convolve_neon.s",
+                    "src/asm/ARMV7/cor_h_vec_neon.s",
+                    "src/asm/ARMV7/Deemph_32_neon.s",
+                    "src/asm/ARMV7/Dot_p_neon.s",
+                    "src/asm/ARMV7/Filt_6k_7k_neon.s",
+                    "src/asm/ARMV7/Norm_Corr_neon.s",
+                    "src/asm/ARMV7/pred_lt4_1_neon.s",
+                    "src/asm/ARMV7/residu_asm_neon.s",
+                    "src/asm/ARMV7/scale_sig_neon.s",
+                    "src/asm/ARMV7/Syn_filt_32_neon.s",
+                    "src/asm/ARMV7/syn_filt_neon.s",
+                ],
+
+                // don't actually generate neon instructions, see bug 26932980
+                cflags: [
+                    "-DARMV7",
+                    "-mfpu=vfpv3",
+                ],
+                local_include_dirs: [
+                    "src/asm/ARMV5E",
+                    "src/asm/ARMV7",
+                ],
+            },
+
+        },
+    },
+
+    include_dirs: [
+        "frameworks/av/include",
+        "frameworks/av/media/libstagefright/include",
+    ],
+
+    local_include_dirs: ["src"],
+    export_include_dirs: ["inc"],
+
+    shared_libs: [
+        "libstagefright_enc_common",
+        "liblog",
+    ],
+
+    cflags: ["-Werror"],
+    sanitize: {
+        cfi: true,
+    },
+
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/MODULE_LICENSE_APACHE2 b/media/codecs/amrwb/enc/MODULE_LICENSE_APACHE2
similarity index 100%
copy from media/libstagefright/codecs/amrnb/enc/MODULE_LICENSE_APACHE2
copy to media/codecs/amrwb/enc/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/codecs/amrnb/enc/NOTICE b/media/codecs/amrwb/enc/NOTICE
similarity index 100%
copy from media/libstagefright/codecs/amrnb/enc/NOTICE
copy to media/codecs/amrwb/enc/NOTICE
diff --git a/media/libstagefright/codecs/amrwbenc/SampleCode/AMRWB_E_SAMPLE.c b/media/codecs/amrwb/enc/SampleCode/AMRWB_E_SAMPLE.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/SampleCode/AMRWB_E_SAMPLE.c
rename to media/codecs/amrwb/enc/SampleCode/AMRWB_E_SAMPLE.c
diff --git a/media/codecs/amrwb/enc/SampleCode/Android.bp b/media/codecs/amrwb/enc/SampleCode/Android.bp
new file mode 100644
index 0000000..1448364
--- /dev/null
+++ b/media/codecs/amrwb/enc/SampleCode/Android.bp
@@ -0,0 +1,47 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrwb_enc_SampleCode_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codecs_amrwb_enc_SampleCode_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_test {
+    name: "AMRWBEncTest",
+    gtest: false,
+
+    srcs: ["AMRWB_E_SAMPLE.c"],
+
+    cflags: ["-Wall", "-Werror"],
+
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
+
+    shared_libs: [
+        "libdl",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libstagefright_amrwbenc",
+        "libstagefright_enc_common",
+    ],
+
+    sanitize: {
+        cfi: true,
+    },
+}
diff --git a/media/libstagefright/codecs/amrwbenc/SampleCode/MODULE_LICENSE_APACHE2 b/media/codecs/amrwb/enc/SampleCode/MODULE_LICENSE_APACHE2
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/SampleCode/MODULE_LICENSE_APACHE2
rename to media/codecs/amrwb/enc/SampleCode/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/codecs/amrwbenc/SampleCode/NOTICE b/media/codecs/amrwb/enc/SampleCode/NOTICE
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/SampleCode/NOTICE
rename to media/codecs/amrwb/enc/SampleCode/NOTICE
diff --git a/media/codecs/amrwb/enc/TEST_MAPPING b/media/codecs/amrwb/enc/TEST_MAPPING
new file mode 100644
index 0000000..045e8b3
--- /dev/null
+++ b/media/codecs/amrwb/enc/TEST_MAPPING
@@ -0,0 +1,10 @@
+// mappings for frameworks/av/media/libstagefright/codecs/amrwbenc
+{
+  // tests which require dynamic content
+  // invoke with: atest -- --enable-module-dynamic-download=true
+  // TODO(b/148094059): unit tests not allowed to download content
+  "dynamic-presubmit": [
+    { "name": "AmrwbEncoderTest"}
+
+  ]
+}
diff --git a/media/libstagefright/codecs/amrwbenc/doc/voAMRWBEncoderSDK.pdf b/media/codecs/amrwb/enc/doc/voAMRWBEncoderSDK.pdf
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/doc/voAMRWBEncoderSDK.pdf
rename to media/codecs/amrwb/enc/doc/voAMRWBEncoderSDK.pdf
Binary files differ
diff --git a/media/codecs/amrwb/enc/fuzzer/Android.bp b/media/codecs/amrwb/enc/fuzzer/Android.bp
new file mode 100644
index 0000000..f74fa4f
--- /dev/null
+++ b/media/codecs/amrwb/enc/fuzzer/Android.bp
@@ -0,0 +1,52 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_amrwb_enc_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrwb_enc_license",
+    ],
+}
+
+cc_fuzz {
+    name: "amrwb_enc_fuzzer",
+    host_supported: true,
+
+    srcs: [
+        "amrwb_enc_fuzzer.cpp",
+    ],
+
+    static_libs: [
+        "liblog",
+        "libstagefright_amrwbenc",
+        "libstagefright_enc_common",
+    ],
+
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
diff --git a/media/codecs/amrwb/enc/fuzzer/README.md b/media/codecs/amrwb/enc/fuzzer/README.md
new file mode 100644
index 0000000..447fbfa
--- /dev/null
+++ b/media/codecs/amrwb/enc/fuzzer/README.md
@@ -0,0 +1,60 @@
+# Fuzzer for libstagefright_amrwbenc encoder
+
+## Plugin Design Considerations
+The fuzzer plugin for AMR-WB is designed based on the understanding of the
+codec and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+AMR-WB supports the following parameters:
+1. Frame Type (parameter name: `frameType`)
+2. Mode (parameter name: `mode`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `frameType` | 0. `VOAMRWB_DEFAULT` 1. `VOAMRWB_ITU` 2. `VOAMRWB_RFC3267` | Bits 0, 1 and 2 of 1st byte of data. |
+| `mode`   | 0. `VOAMRWB_MD66` 1. `VOAMRWB_MD885` 2. `VOAMRWB_MD1265` 3. `VOAMRWB_MD1425`  4. `VOAMRWB_MD1585 ` 5. `VOAMRWB_MD1825` 6. `VOAMRWB_MD1985` 7. `VOAMRWB_MD2305` 8. `VOAMRWB_MD2385` 9. `VOAMRWB_N_MODES` | Bits 4, 5, 6 and 7 of 1st byte of data. |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+##### Maximize utilization of input data
+The plugin feeds the entire input data to the codec using a loop.
+If the encode operation was successful, the input is advanced by the frame size.
+If the encode operation was un-successful, the input is still advanced by frame size so
+that the fuzzer can proceed to feed the next frame.
+
+This ensures that the plugin tolerates any kind of input (empty, huge,
+malformed, etc) and doesnt `exit()` on any input and thereby increasing the
+chance of identifying vulnerabilities.
+
+## Build
+
+This describes steps to build amrwb_enc_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) amrwb_enc_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some pcm files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/amrwb_enc_fuzzer/amrwb_enc_fuzzer CORPUS_DIR
+```
+To run on host
+```
+  $ $ANDROID_HOST_OUT/fuzz/x86_64/amrwb_enc_fuzzer/amrwb_enc_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/media/codecs/amrwb/enc/fuzzer/amrwb_enc_fuzzer.cpp b/media/codecs/amrwb/enc/fuzzer/amrwb_enc_fuzzer.cpp
new file mode 100644
index 0000000..4773a1f
--- /dev/null
+++ b/media/codecs/amrwb/enc/fuzzer/amrwb_enc_fuzzer.cpp
@@ -0,0 +1,142 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+#include <string.h>
+#include <utils/Log.h>
+#include <algorithm>
+#include "cmnMemory.h"
+#include "voAMRWB.h"
+#include "cnst.h"
+
+typedef int(VO_API *VOGETAUDIOENCAPI)(VO_AUDIO_CODECAPI *pEncHandle);
+const int32_t kInputBufferSize = L_FRAME16k * sizeof(int16_t) * 2;
+const int32_t kOutputBufferSize = 2 * kInputBufferSize;
+const int32_t kModes[] = {VOAMRWB_MD66 /* 6.60kbps */,    VOAMRWB_MD885 /* 8.85kbps */,
+                          VOAMRWB_MD1265 /* 12.65kbps */, VOAMRWB_MD1425 /* 14.25kbps */,
+                          VOAMRWB_MD1585 /* 15.85kbps */, VOAMRWB_MD1825 /* 18.25kbps */,
+                          VOAMRWB_MD1985 /* 19.85kbps */, VOAMRWB_MD2305 /* 23.05kbps */,
+                          VOAMRWB_MD2385 /* 23.85kbps */, VOAMRWB_N_MODES /* Invalid Mode */};
+const VOAMRWBFRAMETYPE kFrameTypes[] = {VOAMRWB_DEFAULT, VOAMRWB_ITU, VOAMRWB_RFC3267};
+
+class Codec {
+   public:
+    Codec() = default;
+    ~Codec() { deInitEncoder(); }
+    bool initEncoder(const uint8_t *data);
+    void deInitEncoder();
+    void encodeFrames(const uint8_t *data, size_t size);
+
+   private:
+    VO_AUDIO_CODECAPI *mApiHandle = nullptr;
+    VO_MEM_OPERATOR *mMemOperator = nullptr;
+    VO_HANDLE mEncoderHandle = nullptr;
+};
+
+bool Codec::initEncoder(const uint8_t *data) {
+    uint8_t startByte = *data;
+    int32_t mode = kModes[(startByte >> 4) % 10];
+    VOAMRWBFRAMETYPE frameType = kFrameTypes[startByte % 3];
+    mMemOperator = new VO_MEM_OPERATOR;
+    if (!mMemOperator) {
+        return false;
+    }
+
+    mMemOperator->Alloc = cmnMemAlloc;
+    mMemOperator->Copy = cmnMemCopy;
+    mMemOperator->Free = cmnMemFree;
+    mMemOperator->Set = cmnMemSet;
+    mMemOperator->Check = cmnMemCheck;
+
+    VO_CODEC_INIT_USERDATA userData;
+    memset(&userData, 0, sizeof(userData));
+    userData.memflag = VO_IMF_USERMEMOPERATOR;
+    userData.memData = (VO_PTR)mMemOperator;
+
+    mApiHandle = new VO_AUDIO_CODECAPI;
+    if (!mApiHandle) {
+        return false;
+    }
+    if (VO_ERR_NONE != voGetAMRWBEncAPI(mApiHandle)) {
+        // Failed to get api handle
+        return false;
+    }
+    if (VO_ERR_NONE != mApiHandle->Init(&mEncoderHandle, VO_AUDIO_CodingAMRWB, &userData)) {
+        // Failed to init AMRWB encoder
+        return false;
+    }
+    if (VO_ERR_NONE != mApiHandle->SetParam(mEncoderHandle, VO_PID_AMRWB_FRAMETYPE, &frameType)) {
+        // Failed to set AMRWB encoder frame type
+        return false;
+    }
+    if (VO_ERR_NONE != mApiHandle->SetParam(mEncoderHandle, VO_PID_AMRWB_MODE, &mode)) {
+        // Failed to set AMRWB encoder mode
+        return false;
+    }
+    return true;
+}
+
+void Codec::deInitEncoder() {
+    if (mEncoderHandle) {
+        mApiHandle->Uninit(mEncoderHandle);
+        mEncoderHandle = nullptr;
+    }
+    if (mApiHandle) {
+        delete mApiHandle;
+        mApiHandle = nullptr;
+    }
+    if (mMemOperator) {
+        delete mMemOperator;
+        mMemOperator = nullptr;
+    }
+}
+
+void Codec::encodeFrames(const uint8_t *data, size_t size) {
+    do {
+        int32_t minSize = std::min((int32_t)size, kInputBufferSize);
+        uint8_t outputBuf[kOutputBufferSize] = {};
+        VO_CODECBUFFER inData;
+        VO_CODECBUFFER outData;
+        VO_AUDIO_OUTPUTINFO outFormat;
+        inData.Buffer = (unsigned char *)data;
+        inData.Length = minSize;
+        outData.Buffer = outputBuf;
+        mApiHandle->SetInputData(mEncoderHandle, &inData);
+        mApiHandle->GetOutputData(mEncoderHandle, &outData, &outFormat);
+        data += minSize;
+        size -= minSize;
+    } while (size > 0);
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    if (size < 1) {
+        return 0;
+    }
+    Codec *codec = new Codec();
+    if (!codec) {
+        return 0;
+    }
+    if (codec->initEncoder(data)) {
+        // Consume first byte
+        ++data;
+        --size;
+        codec->encodeFrames(data, size);
+    }
+    delete codec;
+    return 0;
+}
diff --git a/media/libstagefright/codecs/amrwbenc/inc/acelp.h b/media/codecs/amrwb/enc/inc/acelp.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/acelp.h
rename to media/codecs/amrwb/enc/inc/acelp.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/basic_op.h b/media/codecs/amrwb/enc/inc/basic_op.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/basic_op.h
rename to media/codecs/amrwb/enc/inc/basic_op.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/bits.h b/media/codecs/amrwb/enc/inc/bits.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/bits.h
rename to media/codecs/amrwb/enc/inc/bits.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/cnst.h b/media/codecs/amrwb/enc/inc/cnst.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/cnst.h
rename to media/codecs/amrwb/enc/inc/cnst.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/cod_main.h b/media/codecs/amrwb/enc/inc/cod_main.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/cod_main.h
rename to media/codecs/amrwb/enc/inc/cod_main.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/dtx.h b/media/codecs/amrwb/enc/inc/dtx.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/dtx.h
rename to media/codecs/amrwb/enc/inc/dtx.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/grid100.tab b/media/codecs/amrwb/enc/inc/grid100.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/grid100.tab
rename to media/codecs/amrwb/enc/inc/grid100.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/ham_wind.tab b/media/codecs/amrwb/enc/inc/ham_wind.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/ham_wind.tab
rename to media/codecs/amrwb/enc/inc/ham_wind.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/homing.tab b/media/codecs/amrwb/enc/inc/homing.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/homing.tab
rename to media/codecs/amrwb/enc/inc/homing.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/isp_isf.tab b/media/codecs/amrwb/enc/inc/isp_isf.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/isp_isf.tab
rename to media/codecs/amrwb/enc/inc/isp_isf.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/lag_wind.tab b/media/codecs/amrwb/enc/inc/lag_wind.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/lag_wind.tab
rename to media/codecs/amrwb/enc/inc/lag_wind.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/log2.h b/media/codecs/amrwb/enc/inc/log2.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/log2.h
rename to media/codecs/amrwb/enc/inc/log2.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/log2_tab.h b/media/codecs/amrwb/enc/inc/log2_tab.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/log2_tab.h
rename to media/codecs/amrwb/enc/inc/log2_tab.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/main.h b/media/codecs/amrwb/enc/inc/main.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/main.h
rename to media/codecs/amrwb/enc/inc/main.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/math_op.h b/media/codecs/amrwb/enc/inc/math_op.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/math_op.h
rename to media/codecs/amrwb/enc/inc/math_op.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/mem_align.h b/media/codecs/amrwb/enc/inc/mem_align.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/mem_align.h
rename to media/codecs/amrwb/enc/inc/mem_align.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/mime_io.tab b/media/codecs/amrwb/enc/inc/mime_io.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/mime_io.tab
rename to media/codecs/amrwb/enc/inc/mime_io.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/oper_32b.h b/media/codecs/amrwb/enc/inc/oper_32b.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/oper_32b.h
rename to media/codecs/amrwb/enc/inc/oper_32b.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/p_med_o.h b/media/codecs/amrwb/enc/inc/p_med_o.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/p_med_o.h
rename to media/codecs/amrwb/enc/inc/p_med_o.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/p_med_ol.tab b/media/codecs/amrwb/enc/inc/p_med_ol.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/p_med_ol.tab
rename to media/codecs/amrwb/enc/inc/p_med_ol.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/q_gain2.tab b/media/codecs/amrwb/enc/inc/q_gain2.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/q_gain2.tab
rename to media/codecs/amrwb/enc/inc/q_gain2.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/q_pulse.h b/media/codecs/amrwb/enc/inc/q_pulse.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/q_pulse.h
rename to media/codecs/amrwb/enc/inc/q_pulse.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/qisf_ns.tab b/media/codecs/amrwb/enc/inc/qisf_ns.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/qisf_ns.tab
rename to media/codecs/amrwb/enc/inc/qisf_ns.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/qpisf_2s.tab b/media/codecs/amrwb/enc/inc/qpisf_2s.tab
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/qpisf_2s.tab
rename to media/codecs/amrwb/enc/inc/qpisf_2s.tab
diff --git a/media/libstagefright/codecs/amrwbenc/inc/stream.h b/media/codecs/amrwb/enc/inc/stream.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/stream.h
rename to media/codecs/amrwb/enc/inc/stream.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/typedef.h b/media/codecs/amrwb/enc/inc/typedef.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/typedef.h
rename to media/codecs/amrwb/enc/inc/typedef.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/typedefs.h b/media/codecs/amrwb/enc/inc/typedefs.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/typedefs.h
rename to media/codecs/amrwb/enc/inc/typedefs.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/wb_vad.h b/media/codecs/amrwb/enc/inc/wb_vad.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/wb_vad.h
rename to media/codecs/amrwb/enc/inc/wb_vad.h
diff --git a/media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h b/media/codecs/amrwb/enc/inc/wb_vad_c.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/inc/wb_vad_c.h
rename to media/codecs/amrwb/enc/inc/wb_vad_c.h
diff --git a/media/libstagefright/codecs/amrwbenc/patent_disclaimer.txt b/media/codecs/amrwb/enc/patent_disclaimer.txt
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/patent_disclaimer.txt
rename to media/codecs/amrwb/enc/patent_disclaimer.txt
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Deemph_32_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/Deemph_32_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Deemph_32_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/Deemph_32_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Dot_p_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/Dot_p_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Dot_p_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/Dot_p_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Filt_6k_7k_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/Filt_6k_7k_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Filt_6k_7k_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/Filt_6k_7k_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Norm_Corr_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/Norm_Corr_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Norm_Corr_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/Norm_Corr_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Syn_filt_32_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/Syn_filt_32_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/Syn_filt_32_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/Syn_filt_32_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/convolve_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/convolve_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/convolve_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/convolve_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/cor_h_vec_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/cor_h_vec_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/cor_h_vec_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/cor_h_vec_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/pred_lt4_1_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/pred_lt4_1_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/pred_lt4_1_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/pred_lt4_1_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/residu_asm_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/residu_asm_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/residu_asm_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/residu_asm_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/scale_sig_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/scale_sig_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/scale_sig_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/scale_sig_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/syn_filt_opt.s b/media/codecs/amrwb/enc/src/asm/ARMV5E/syn_filt_opt.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV5E/syn_filt_opt.s
rename to media/codecs/amrwb/enc/src/asm/ARMV5E/syn_filt_opt.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Deemph_32_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/Deemph_32_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Deemph_32_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/Deemph_32_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Dot_p_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/Dot_p_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Dot_p_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/Dot_p_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Filt_6k_7k_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/Filt_6k_7k_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Filt_6k_7k_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/Filt_6k_7k_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Norm_Corr_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/Norm_Corr_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Norm_Corr_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/Norm_Corr_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Syn_filt_32_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/Syn_filt_32_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/Syn_filt_32_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/Syn_filt_32_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/convolve_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/convolve_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/convolve_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/convolve_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/cor_h_vec_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/cor_h_vec_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/cor_h_vec_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/cor_h_vec_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/pred_lt4_1_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/pred_lt4_1_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/pred_lt4_1_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/pred_lt4_1_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/residu_asm_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/residu_asm_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/residu_asm_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/residu_asm_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/scale_sig_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/scale_sig_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/scale_sig_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/scale_sig_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/syn_filt_neon.s b/media/codecs/amrwb/enc/src/asm/ARMV7/syn_filt_neon.s
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/asm/ARMV7/syn_filt_neon.s
rename to media/codecs/amrwb/enc/src/asm/ARMV7/syn_filt_neon.s
diff --git a/media/libstagefright/codecs/amrwbenc/src/autocorr.c b/media/codecs/amrwb/enc/src/autocorr.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/autocorr.c
rename to media/codecs/amrwb/enc/src/autocorr.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/az_isp.c b/media/codecs/amrwb/enc/src/az_isp.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/az_isp.c
rename to media/codecs/amrwb/enc/src/az_isp.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/bits.c b/media/codecs/amrwb/enc/src/bits.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/bits.c
rename to media/codecs/amrwb/enc/src/bits.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/c2t64fx.c b/media/codecs/amrwb/enc/src/c2t64fx.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/c2t64fx.c
rename to media/codecs/amrwb/enc/src/c2t64fx.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/c4t64fx.c b/media/codecs/amrwb/enc/src/c4t64fx.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/c4t64fx.c
rename to media/codecs/amrwb/enc/src/c4t64fx.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/convolve.c b/media/codecs/amrwb/enc/src/convolve.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/convolve.c
rename to media/codecs/amrwb/enc/src/convolve.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/cor_h_x.c b/media/codecs/amrwb/enc/src/cor_h_x.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/cor_h_x.c
rename to media/codecs/amrwb/enc/src/cor_h_x.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/decim54.c b/media/codecs/amrwb/enc/src/decim54.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/decim54.c
rename to media/codecs/amrwb/enc/src/decim54.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/deemph.c b/media/codecs/amrwb/enc/src/deemph.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/deemph.c
rename to media/codecs/amrwb/enc/src/deemph.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/dtx.c b/media/codecs/amrwb/enc/src/dtx.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/dtx.c
rename to media/codecs/amrwb/enc/src/dtx.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/g_pitch.c b/media/codecs/amrwb/enc/src/g_pitch.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/g_pitch.c
rename to media/codecs/amrwb/enc/src/g_pitch.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/gpclip.c b/media/codecs/amrwb/enc/src/gpclip.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/gpclip.c
rename to media/codecs/amrwb/enc/src/gpclip.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/homing.c b/media/codecs/amrwb/enc/src/homing.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/homing.c
rename to media/codecs/amrwb/enc/src/homing.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp400.c b/media/codecs/amrwb/enc/src/hp400.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/hp400.c
rename to media/codecs/amrwb/enc/src/hp400.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp50.c b/media/codecs/amrwb/enc/src/hp50.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/hp50.c
rename to media/codecs/amrwb/enc/src/hp50.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp6k.c b/media/codecs/amrwb/enc/src/hp6k.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/hp6k.c
rename to media/codecs/amrwb/enc/src/hp6k.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/hp_wsp.c b/media/codecs/amrwb/enc/src/hp_wsp.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/hp_wsp.c
rename to media/codecs/amrwb/enc/src/hp_wsp.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/int_lpc.c b/media/codecs/amrwb/enc/src/int_lpc.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/int_lpc.c
rename to media/codecs/amrwb/enc/src/int_lpc.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/isp_az.c b/media/codecs/amrwb/enc/src/isp_az.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/isp_az.c
rename to media/codecs/amrwb/enc/src/isp_az.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/isp_isf.c b/media/codecs/amrwb/enc/src/isp_isf.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/isp_isf.c
rename to media/codecs/amrwb/enc/src/isp_isf.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/lag_wind.c b/media/codecs/amrwb/enc/src/lag_wind.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/lag_wind.c
rename to media/codecs/amrwb/enc/src/lag_wind.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/levinson.c b/media/codecs/amrwb/enc/src/levinson.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/levinson.c
rename to media/codecs/amrwb/enc/src/levinson.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/log2.c b/media/codecs/amrwb/enc/src/log2.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/log2.c
rename to media/codecs/amrwb/enc/src/log2.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/lp_dec2.c b/media/codecs/amrwb/enc/src/lp_dec2.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/lp_dec2.c
rename to media/codecs/amrwb/enc/src/lp_dec2.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/math_op.c b/media/codecs/amrwb/enc/src/math_op.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/math_op.c
rename to media/codecs/amrwb/enc/src/math_op.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/mem_align.c b/media/codecs/amrwb/enc/src/mem_align.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/mem_align.c
rename to media/codecs/amrwb/enc/src/mem_align.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/oper_32b.c b/media/codecs/amrwb/enc/src/oper_32b.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/oper_32b.c
rename to media/codecs/amrwb/enc/src/oper_32b.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/p_med_ol.c b/media/codecs/amrwb/enc/src/p_med_ol.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/p_med_ol.c
rename to media/codecs/amrwb/enc/src/p_med_ol.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/pit_shrp.c b/media/codecs/amrwb/enc/src/pit_shrp.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/pit_shrp.c
rename to media/codecs/amrwb/enc/src/pit_shrp.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c b/media/codecs/amrwb/enc/src/pitch_f4.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
rename to media/codecs/amrwb/enc/src/pitch_f4.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/pred_lt4.c b/media/codecs/amrwb/enc/src/pred_lt4.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/pred_lt4.c
rename to media/codecs/amrwb/enc/src/pred_lt4.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/preemph.c b/media/codecs/amrwb/enc/src/preemph.c
similarity index 98%
rename from media/libstagefright/codecs/amrwbenc/src/preemph.c
rename to media/codecs/amrwb/enc/src/preemph.c
index 70c8650..a43841a 100644
--- a/media/libstagefright/codecs/amrwbenc/src/preemph.c
+++ b/media/codecs/amrwb/enc/src/preemph.c
@@ -24,6 +24,7 @@
 
 #include "typedef.h"
 #include "basic_op.h"
+#include <stdint.h>
 
 void Preemph(
         Word16 x[],                           /* (i/o)   : input signal overwritten by the output */
diff --git a/media/libstagefright/codecs/amrwbenc/src/q_gain2.c b/media/codecs/amrwb/enc/src/q_gain2.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/q_gain2.c
rename to media/codecs/amrwb/enc/src/q_gain2.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/q_pulse.c b/media/codecs/amrwb/enc/src/q_pulse.c
similarity index 99%
rename from media/libstagefright/codecs/amrwbenc/src/q_pulse.c
rename to media/codecs/amrwb/enc/src/q_pulse.c
index fe0bdda..657b6fe 100644
--- a/media/libstagefright/codecs/amrwbenc/src/q_pulse.c
+++ b/media/codecs/amrwb/enc/src/q_pulse.c
@@ -27,6 +27,7 @@
 #include "q_pulse.h"
 
 #define NB_POS 16                          /* pos in track, mask for sign bit */
+#define UNUSED_VAR __attribute__((unused))
 
 Word32 quant_1p_N1(                        /* (o) return N+1 bits             */
         Word16 pos,                        /* (i) position of the pulse       */
@@ -188,7 +189,7 @@
         Word16 pos[],                         /* (i) position of the pulse 1..4  */
         Word16 N)                             /* (i) number of bits for position */
 {
-    Word16 nb_pos, mask __unused, n_1, tmp;
+    Word16 nb_pos, mask UNUSED_VAR, n_1, tmp;
     Word16 posA[4], posB[4];
     Word32 i, j, k, index;
 
diff --git a/media/libstagefright/codecs/amrwbenc/src/qisf_ns.c b/media/codecs/amrwb/enc/src/qisf_ns.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/qisf_ns.c
rename to media/codecs/amrwb/enc/src/qisf_ns.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c b/media/codecs/amrwb/enc/src/qpisf_2s.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/qpisf_2s.c
rename to media/codecs/amrwb/enc/src/qpisf_2s.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/random.c b/media/codecs/amrwb/enc/src/random.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/random.c
rename to media/codecs/amrwb/enc/src/random.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/residu.c b/media/codecs/amrwb/enc/src/residu.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/residu.c
rename to media/codecs/amrwb/enc/src/residu.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/scale.c b/media/codecs/amrwb/enc/src/scale.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/scale.c
rename to media/codecs/amrwb/enc/src/scale.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/stream.c b/media/codecs/amrwb/enc/src/stream.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/stream.c
rename to media/codecs/amrwb/enc/src/stream.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/syn_filt.c b/media/codecs/amrwb/enc/src/syn_filt.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/syn_filt.c
rename to media/codecs/amrwb/enc/src/syn_filt.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/updt_tar.c b/media/codecs/amrwb/enc/src/updt_tar.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/updt_tar.c
rename to media/codecs/amrwb/enc/src/updt_tar.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/util.c b/media/codecs/amrwb/enc/src/util.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/util.c
rename to media/codecs/amrwb/enc/src/util.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c b/media/codecs/amrwb/enc/src/voAMRWBEnc.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
rename to media/codecs/amrwb/enc/src/voAMRWBEnc.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/voicefac.c b/media/codecs/amrwb/enc/src/voicefac.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/voicefac.c
rename to media/codecs/amrwb/enc/src/voicefac.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/wb_vad.c b/media/codecs/amrwb/enc/src/wb_vad.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/wb_vad.c
rename to media/codecs/amrwb/enc/src/wb_vad.c
diff --git a/media/libstagefright/codecs/amrwbenc/src/weight_a.c b/media/codecs/amrwb/enc/src/weight_a.c
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/src/weight_a.c
rename to media/codecs/amrwb/enc/src/weight_a.c
diff --git a/media/libstagefright/codecs/amrwbenc/test/AmrwbEncTestEnvironment.h b/media/codecs/amrwb/enc/test/AmrwbEncTestEnvironment.h
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/test/AmrwbEncTestEnvironment.h
rename to media/codecs/amrwb/enc/test/AmrwbEncTestEnvironment.h
diff --git a/media/libstagefright/codecs/amrwbenc/test/AmrwbEncoderTest.cpp b/media/codecs/amrwb/enc/test/AmrwbEncoderTest.cpp
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/test/AmrwbEncoderTest.cpp
rename to media/codecs/amrwb/enc/test/AmrwbEncoderTest.cpp
diff --git a/media/libstagefright/codecs/amrwbenc/test/Android.bp b/media/codecs/amrwb/enc/test/Android.bp
similarity index 74%
rename from media/libstagefright/codecs/amrwbenc/test/Android.bp
rename to media/codecs/amrwb/enc/test/Android.bp
index 7042bc5..e4b7771 100644
--- a/media/libstagefright/codecs/amrwbenc/test/Android.bp
+++ b/media/codecs/amrwb/enc/test/Android.bp
@@ -14,6 +14,17 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_amrwb_enc_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_amrwb_enc_license",
+    ],
+}
+
 cc_test {
     name: "AmrwbEncoderTest",
     gtest: true,
diff --git a/media/libstagefright/codecs/amrwbenc/test/AndroidTest.xml b/media/codecs/amrwb/enc/test/AndroidTest.xml
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/test/AndroidTest.xml
rename to media/codecs/amrwb/enc/test/AndroidTest.xml
diff --git a/media/libstagefright/codecs/amrwbenc/test/README.md b/media/codecs/amrwb/enc/test/README.md
similarity index 100%
rename from media/libstagefright/codecs/amrwbenc/test/README.md
rename to media/codecs/amrwb/enc/test/README.md
diff --git a/media/codecs/g711/decoder/Android.bp b/media/codecs/g711/decoder/Android.bp
new file mode 100644
index 0000000..07f7ed4
--- /dev/null
+++ b/media/codecs/g711/decoder/Android.bp
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2020 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 {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library_static {
+    name: "codecs_g711dec",
+    vendor_available: true,
+    host_supported: true,
+
+    srcs: [
+        "g711DecAlaw.cpp",
+        "g711DecMlaw.cpp",
+    ],
+
+    export_include_dirs: ["."],
+
+    cflags: ["-Werror"],
+
+    sanitize: {
+        misc_undefined: [
+            "signed-integer-overflow",
+            "unsigned-integer-overflow",
+        ],
+        cfi: true,
+    },
+    apex_available: ["com.android.media.swcodec"],
+    min_sdk_version: "29",
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+}
diff --git a/media/codecs/g711/decoder/g711Dec.h b/media/codecs/g711/decoder/g711Dec.h
new file mode 100644
index 0000000..ca357a5
--- /dev/null
+++ b/media/codecs/g711/decoder/g711Dec.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2020 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 G711_DEC_H_
+#define G711_DEC_H_
+
+/**
+ * @file g711Dec.h
+ * @brief g711 Decoder API: DecodeALaw and DecodeMLaw
+ */
+
+/** Decodes input bytes of size inSize according to ALAW
+ *
+ * @param [in] out <tt>int16_t*</tt>: output buffer to be filled with decoded bytes.
+ * @param [in] in <tt>const uint8_t*</tt>: input buffer containing bytes to be decoded.
+ * @param [in] inSize <tt>size_t</tt>: size of the input buffer.
+ */
+void DecodeALaw(int16_t *out, const uint8_t *in, size_t inSize);
+
+/** Decodes input bytes of size inSize according to MLAW
+ *
+ * @param [in] out <tt>int16_t*</tt>: output buffer to be filled with decoded bytes.
+ * @param [in] in <tt>const uint8_t*</tt>: input buffer containing bytes to be decoded.
+ * @param [in] inSize <tt>size_t</tt>: size of the input buffer.
+ */
+void DecodeMLaw(int16_t *out, const uint8_t *in, size_t inSize);
+
+#endif  // G711_DECODER_H_
diff --git a/media/codecs/g711/decoder/g711DecAlaw.cpp b/media/codecs/g711/decoder/g711DecAlaw.cpp
new file mode 100644
index 0000000..e41a7b4
--- /dev/null
+++ b/media/codecs/g711/decoder/g711DecAlaw.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+
+void DecodeALaw(int16_t *out, const uint8_t *in, size_t inSize) {
+  if (out != nullptr && in != nullptr) {
+    while (inSize > 0) {
+      inSize--;
+      int32_t x = *in++;
+
+      int32_t ix = x ^ 0x55;
+      ix &= 0x7f;
+
+      int32_t iexp = ix >> 4;
+      int32_t mant = ix & 0x0f;
+
+      if (iexp > 0) {
+        mant += 16;
+      }
+
+      mant = (mant << 4) + 8;
+
+      if (iexp > 1) {
+        mant = mant << (iexp - 1);
+      }
+
+      *out++ = (x > 127) ? mant : -mant;
+    }
+  }
+}
diff --git a/media/codecs/g711/decoder/g711DecMlaw.cpp b/media/codecs/g711/decoder/g711DecMlaw.cpp
new file mode 100644
index 0000000..bb2caea
--- /dev/null
+++ b/media/codecs/g711/decoder/g711DecMlaw.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+
+void DecodeMLaw(int16_t *out, const uint8_t *in, size_t inSize) {
+  if (out != nullptr && in != nullptr) {
+    while (inSize > 0) {
+      inSize--;
+      int32_t x = *in++;
+
+      int32_t mantissa = ~x;
+      int32_t exponent = (mantissa >> 4) & 7;
+      int32_t segment = exponent + 1;
+      mantissa &= 0x0f;
+
+      int32_t step = 4 << segment;
+
+      int32_t abs = (0x80l << exponent) + step * mantissa + step / 2 - 4 * 33;
+
+      *out++ = (x < 0x80) ? -abs : abs;
+    }
+  }
+}
diff --git a/media/codecs/g711/fuzzer/Android.bp b/media/codecs/g711/fuzzer/Android.bp
new file mode 100644
index 0000000..376cce7
--- /dev/null
+++ b/media/codecs/g711/fuzzer/Android.bp
@@ -0,0 +1,65 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_fuzz {
+    name: "g711alaw_dec_fuzzer",
+    host_supported: true,
+    srcs: [
+        "g711_dec_fuzzer.cpp",
+    ],
+    static_libs: [
+        "codecs_g711dec",
+    ],
+    cflags: [
+        "-DALAW",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
+
+cc_fuzz {
+    name: "g711mlaw_dec_fuzzer",
+    host_supported: true,
+    srcs: [
+        "g711_dec_fuzzer.cpp",
+    ],
+    static_libs: [
+        "codecs_g711dec",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
diff --git a/media/codecs/g711/fuzzer/README.md b/media/codecs/g711/fuzzer/README.md
new file mode 100644
index 0000000..0c1c36b
--- /dev/null
+++ b/media/codecs/g711/fuzzer/README.md
@@ -0,0 +1,49 @@
+# Fuzzer for libstagefright_g711dec decoder
+
+## Plugin Design Considerations
+The fuzzer plugin for G711 is designed based on the understanding of the
+codec and tries to achieve the following:
+
+##### Maximize code coverage
+G711 supports two types of decoding:
+1. DecodeALaw
+2. DecodeMLaw
+
+These two decoder API's are fuzzed separately using g711alaw_dec_fuzzer and
+g711mlaw_dec_fuzzer respectively.
+
+##### Maximize utilization of input data
+The plugin feeds the entire input data to the codec as expected by decoder API.
+
+## Build
+
+This describes steps to build g711alaw_dec_fuzzer and g711mlaw_dec_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) g711alaw_dec_fuzzer
+  $ mm -j$(nproc) g711mlaw_dec_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some g711 files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/g711alaw_dec_fuzzer/g711alaw_dec_fuzzer CORPUS_DIR
+  $ adb shell /data/fuzz/arm64/g711mlaw_dec_fuzzer/g711mlaw_dec_fuzzer CORPUS_DIR
+```
+To run on host
+```
+  $ $ANDROID_HOST_OUT/fuzz/x86_64/g711alaw_dec_fuzzer/g711alaw_dec_fuzzer CORPUS_DIR
+  $ $ANDROID_HOST_OUT/fuzz/x86_64/g711mlaw_dec_fuzzer/g711mlaw_dec_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/media/codecs/g711/fuzzer/g711_dec_fuzzer.cpp b/media/codecs/g711/fuzzer/g711_dec_fuzzer.cpp
new file mode 100644
index 0000000..adfbcf5
--- /dev/null
+++ b/media/codecs/g711/fuzzer/g711_dec_fuzzer.cpp
@@ -0,0 +1,58 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include "g711Dec.h"
+
+class Codec {
+ public:
+  Codec() = default;
+  ~Codec() = default;
+  void decodeFrames(const uint8_t *data, size_t size);
+};
+
+void Codec::decodeFrames(const uint8_t *data, size_t size) {
+  size_t outputBufferSize = sizeof(int16_t) * size;
+  int16_t *out = new int16_t[outputBufferSize];
+  if (!out) {
+    return;
+  }
+#ifdef ALAW
+  DecodeALaw(out, data, size);
+#else
+  DecodeMLaw(out, data, size);
+#endif
+  delete[] out;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+  if (size < 1) {
+    return 0;
+  }
+  Codec *codec = new Codec();
+  if (!codec) {
+    return 0;
+  }
+  codec->decodeFrames(data, size);
+  delete codec;
+  return 0;
+}
diff --git a/media/codecs/m4v_h263/TEST_MAPPING b/media/codecs/m4v_h263/TEST_MAPPING
new file mode 100644
index 0000000..ba3ff1c
--- /dev/null
+++ b/media/codecs/m4v_h263/TEST_MAPPING
@@ -0,0 +1,18 @@
+// mappings for frameworks/av/media/libstagefright/codecs/m4v_h263
+{
+  // tests which require dynamic content
+  // invoke with: atest -- --enable-module-dynamic-download=true
+  // TODO(b/148094059): unit tests not allowed to download content
+  "dynamic-presubmit": [
+
+    // the decoder reports something bad about an unexpected newline in the *config file
+    // and the config file looks like the AndroidTest.xml file that we put in there.
+    // I don't get this from the Encoder -- and I don't see any substantive difference
+    // between decode and encode AndroidTest.xml files -- except that encode does NOT
+    // finish with a newline.
+    // strange.
+    { "name": "Mpeg4H263DecoderTest"},
+    { "name": "Mpeg4H263EncoderTest"}
+
+  ]
+}
diff --git a/media/codecs/m4v_h263/dec/Android.bp b/media/codecs/m4v_h263/dec/Android.bp
new file mode 100644
index 0000000..038d0e1
--- /dev/null
+++ b/media/codecs/m4v_h263/dec/Android.bp
@@ -0,0 +1,76 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_m4v_h263_dec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codecs_m4v_h263_dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library_static {
+    name: "libstagefright_m4vh263dec",
+    vendor_available: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.media.swcodec",
+    ],
+    min_sdk_version: "29",
+    host_supported: true,
+    shared_libs: ["liblog"],
+
+    srcs: [
+        "src/bitstream.cpp",
+        "src/block_idct.cpp",
+        "src/cal_dc_scaler.cpp",
+        "src/combined_decode.cpp",
+        "src/conceal.cpp",
+        "src/datapart_decode.cpp",
+        "src/dcac_prediction.cpp",
+        "src/dec_pred_intra_dc.cpp",
+        "src/get_pred_adv_b_add.cpp",
+        "src/get_pred_outside.cpp",
+        "src/idct.cpp",
+        "src/idct_vca.cpp",
+        "src/mb_motion_comp.cpp",
+        "src/mb_utils.cpp",
+        "src/packet_util.cpp",
+        "src/post_filter.cpp",
+        "src/pvdec_api.cpp",
+        "src/scaling_tab.cpp",
+        "src/vlc_decode.cpp",
+        "src/vlc_dequant.cpp",
+        "src/vlc_tab.cpp",
+        "src/vop.cpp",
+        "src/zigzag_tab.cpp",
+    ],
+
+    local_include_dirs: ["src"],
+    export_include_dirs: ["include"],
+
+    cflags: [
+        "-Werror",
+    ],
+
+    sanitize: {
+        misc_undefined: [
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+    },
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+}
diff --git a/media/libstagefright/codecs/m4v_h263/dec/MODULE_LICENSE_APACHE2 b/media/codecs/m4v_h263/dec/MODULE_LICENSE_APACHE2
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/MODULE_LICENSE_APACHE2
rename to media/codecs/m4v_h263/dec/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/codecs/m4v_h263/dec/NOTICE b/media/codecs/m4v_h263/dec/NOTICE
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/NOTICE
rename to media/codecs/m4v_h263/dec/NOTICE
diff --git a/media/libstagefright/codecs/m4v_h263/dec/include/m4vh263_decoder_pv_types.h b/media/codecs/m4v_h263/dec/include/m4vh263_decoder_pv_types.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/include/m4vh263_decoder_pv_types.h
rename to media/codecs/m4v_h263/dec/include/m4vh263_decoder_pv_types.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.h b/media/codecs/m4v_h263/dec/include/mp4dec_api.h
similarity index 97%
rename from media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.h
rename to media/codecs/m4v_h263/dec/include/mp4dec_api.h
index 1f404ce..06aee07 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.h
+++ b/media/codecs/m4v_h263/dec/include/mp4dec_api.h
@@ -42,13 +42,6 @@
 #define OSCL_EXPORT_REF /* empty */
 #endif
 
-/* flag for post-processing  4/25/00 */
-
-#ifdef DEC_NOPOSTPROC
-#undef PV_POSTPROC_ON   /* enable compilation of post-processing code */
-#else
-#define PV_POSTPROC_ON
-#endif
 
 #define PV_NO_POST_PROC 0
 #define PV_DEBLOCK 1
diff --git a/media/libstagefright/codecs/m4v_h263/dec/include/visual_header.h b/media/codecs/m4v_h263/dec/include/visual_header.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/include/visual_header.h
rename to media/codecs/m4v_h263/dec/include/visual_header.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/bitstream.cpp b/media/codecs/m4v_h263/dec/src/bitstream.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/bitstream.cpp
rename to media/codecs/m4v_h263/dec/src/bitstream.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/bitstream.h b/media/codecs/m4v_h263/dec/src/bitstream.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/bitstream.h
rename to media/codecs/m4v_h263/dec/src/bitstream.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/block_idct.cpp b/media/codecs/m4v_h263/dec/src/block_idct.cpp
similarity index 99%
rename from media/libstagefright/codecs/m4v_h263/dec/src/block_idct.cpp
rename to media/codecs/m4v_h263/dec/src/block_idct.cpp
index 3d10086..bc708e2 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/block_idct.cpp
+++ b/media/codecs/m4v_h263/dec/src/block_idct.cpp
@@ -506,6 +506,7 @@
 /*----------------------------------------------------------------------------
 ; Function Code FOR idctrow
 ----------------------------------------------------------------------------*/
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctrow(
     int16 *blk, uint8 *pred, uint8 *dst, int width
 )
@@ -828,6 +829,7 @@
 /*----------------------------------------------------------------------------
 ; Function Code FOR idctcol
 ----------------------------------------------------------------------------*/
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctcol(
     int16 *blk
 )
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/cal_dc_scaler.cpp b/media/codecs/m4v_h263/dec/src/cal_dc_scaler.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/cal_dc_scaler.cpp
rename to media/codecs/m4v_h263/dec/src/cal_dc_scaler.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/combined_decode.cpp b/media/codecs/m4v_h263/dec/src/combined_decode.cpp
similarity index 88%
rename from media/libstagefright/codecs/m4v_h263/dec/src/combined_decode.cpp
rename to media/codecs/m4v_h263/dec/src/combined_decode.cpp
index 6499233..72cbe83 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/combined_decode.cpp
+++ b/media/codecs/m4v_h263/dec/src/combined_decode.cpp
@@ -544,30 +544,12 @@
     int16 DC_coeff;
     PV_STATUS status;
 
-#ifdef PV_POSTPROC_ON
-    /* post-processing */
-    uint8 *pp_mod[6];
-    int TotalMB = video->nTotalMB;
-    int MB_in_width = video->nMBPerRow;
-#endif
     int y_pos = video->mbnum_row;
     int x_pos = video->mbnum_col;
     int32 offset = (int32)(y_pos << 4) * width + (x_pos << 4);
 
     /* Decode each 8-by-8 blocks. comp 0 ~ 3 are luminance blocks, 4 ~ 5 */
     /*  are chrominance blocks.   04/03/2000.                          */
-#ifdef PV_POSTPROC_ON
-    if (video->postFilterType != PV_NO_POST_PROC)
-    {
-        /** post-processing ***/
-        pp_mod[0] = video->pstprcTypCur + (y_pos << 1) * (MB_in_width << 1) + (x_pos << 1);
-        pp_mod[1] = pp_mod[0] + 1;
-        pp_mod[2] = pp_mod[0] + (MB_in_width << 1);
-        pp_mod[3] = pp_mod[2] + 1;
-        pp_mod[4] = video->pstprcTypCur + (TotalMB << 2) + mbnum;
-        pp_mod[5] = pp_mod[4] + TotalMB;
-    }
-#endif
 
     /*  oscl_memset(mblock->block, 0, sizeof(typeMBStore));    Aug 9,2005 */
 
@@ -645,10 +627,6 @@
             }
             no_coeff[comp] = ncoeffs[comp];
 
-#ifdef PV_POSTPROC_ON
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[comp] = (uint8) PostProcSemaphore(dataBlock);
-#endif
         }
         MBlockIDCT(video);
     }
@@ -677,20 +655,6 @@
                 BlockIDCT(c_comp + (comp&2)*(width << 2) + 8*(comp&1), mblock->pred_block + (comp&2)*64 + 8*(comp&1), mblock->block[comp], width, ncoeffs[comp],
                           mblock->bitmapcol[comp], mblock->bitmaprow[comp]);
 
-#ifdef PV_POSTPROC_ON
-                /* for inter just test for ringing */
-                if (video->postFilterType != PV_NO_POST_PROC)
-                    *pp_mod[comp] = (uint8)((ncoeffs[comp] > 3) ? 4 : 0);
-#endif
-            }
-            else
-            {
-                /* no IDCT for all zeros blocks  03/28/2002 */
-                /*              BlockIDCT();                */
-#ifdef PV_POSTPROC_ON
-                if (video->postFilterType != PV_NO_POST_PROC)
-                    *pp_mod[comp] = 0;
-#endif
             }
         }
 
@@ -707,20 +671,6 @@
             BlockIDCT(video->currVop->uChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 256, mblock->block[4], width >> 1, ncoeffs[4],
                       mblock->bitmapcol[4], mblock->bitmaprow[4]);
 
-#ifdef PV_POSTPROC_ON
-            /* for inter just test for ringing */
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[4] = (uint8)((ncoeffs[4] > 3) ? 4 : 0);
-#endif
-        }
-        else
-        {
-            /* no IDCT for all zeros blocks  03/28/2002 */
-            /*              BlockIDCT();                */
-#ifdef PV_POSTPROC_ON
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[4] = 0;
-#endif
         }
         (*DC)[5] = mid_gray;
         if (CBP & 1)
@@ -731,20 +681,6 @@
             BlockIDCT(video->currVop->vChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 264, mblock->block[5], width >> 1, ncoeffs[5],
                       mblock->bitmapcol[5], mblock->bitmaprow[5]);
 
-#ifdef PV_POSTPROC_ON
-            /* for inter just test for ringing */
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[5] = (uint8)((ncoeffs[5] > 3) ? 4 : 0);
-#endif
-        }
-        else
-        {
-            /* no IDCT for all zeros blocks  03/28/2002 */
-            /*              BlockIDCT();                */
-#ifdef PV_POSTPROC_ON
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[5] = 0;
-#endif
         }
         video->QPMB[mbnum] = QP;  /* restore the QP values  ANNEX_T*/
 #else
@@ -759,20 +695,6 @@
                 BlockIDCT(c_comp + (comp&2)*(width << 2) + 8*(comp&1), mblock->pred_block + (comp&2)*64 + 8*(comp&1), mblock->block[comp], width, ncoeffs[comp],
                           mblock->bitmapcol[comp], mblock->bitmaprow[comp]);
 
-#ifdef PV_POSTPROC_ON
-                /* for inter just test for ringing */
-                if (video->postFilterType != PV_NO_POST_PROC)
-                    *pp_mod[comp] = (uint8)((ncoeffs[comp] > 3) ? 4 : 0);
-#endif
-            }
-            else
-            {
-                /* no IDCT for all zeros blocks  03/28/2002 */
-                /*              BlockIDCT();                */
-#ifdef PV_POSTPROC_ON
-                if (video->postFilterType != PV_NO_POST_PROC)
-                    *pp_mod[comp] = 0;
-#endif
             }
         }
 
@@ -785,20 +707,11 @@
             BlockIDCT(video->currVop->uChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 256, mblock->block[4], width >> 1, ncoeffs[4],
                       mblock->bitmapcol[4], mblock->bitmaprow[4]);
 
-#ifdef PV_POSTPROC_ON
-            /* for inter just test for ringing */
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[4] = (uint8)((ncoeffs[4] > 3) ? 4 : 0);
-#endif
         }
         else
         {
             /* no IDCT for all zeros blocks  03/28/2002 */
             /*              BlockIDCT();                */
-#ifdef PV_POSTPROC_ON
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[4] = 0;
-#endif
         }
         (*DC)[5] = mid_gray;
         if (CBP & 1)
@@ -809,20 +722,11 @@
             BlockIDCT(video->currVop->vChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 264, mblock->block[5], width >> 1, ncoeffs[5],
                       mblock->bitmapcol[5], mblock->bitmaprow[5]);
 
-#ifdef PV_POSTPROC_ON
-            /* for inter just test for ringing */
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[5] = (uint8)((ncoeffs[5] > 3) ? 4 : 0);
-#endif
         }
         else
         {
             /* no IDCT for all zeros blocks  03/28/2002 */
             /*              BlockIDCT();                */
-#ifdef PV_POSTPROC_ON
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[5] = 0;
-#endif
 #endif  // PV_ANNEX_IJKT_SUPPORT
 
 
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/conceal.cpp b/media/codecs/m4v_h263/dec/src/conceal.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/conceal.cpp
rename to media/codecs/m4v_h263/dec/src/conceal.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/datapart_decode.cpp b/media/codecs/m4v_h263/dec/src/datapart_decode.cpp
similarity index 95%
rename from media/libstagefright/codecs/m4v_h263/dec/src/datapart_decode.cpp
rename to media/codecs/m4v_h263/dec/src/datapart_decode.cpp
index 00db04b..6071f40 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/datapart_decode.cpp
+++ b/media/codecs/m4v_h263/dec/src/datapart_decode.cpp
@@ -635,29 +635,9 @@
     int QP_tmp = QP;
 
     int y_pos = video->mbnum_row;
-#ifdef PV_POSTPROC_ON
-    uint8 *pp_mod[6];
-    int TotalMB = video->nTotalMB;
-    int MB_in_width = video->nMBPerRow;
-#endif
 
 
 
-    /*****
-    *     Decoding of the 6 blocks (depending on transparent pattern)
-    *****/
-#ifdef PV_POSTPROC_ON
-    if (video->postFilterType != PV_NO_POST_PROC)
-    {
-        /** post-processing ***/
-        pp_mod[0] = video->pstprcTypCur + (y_pos << 1) * (MB_in_width << 1) + (x_pos << 1);
-        pp_mod[1] = pp_mod[0] + 1;
-        pp_mod[2] = pp_mod[0] + (MB_in_width << 1);
-        pp_mod[3] = pp_mod[2] + 1;
-        pp_mod[4] = video->pstprcTypCur + (TotalMB << 2) + mbnum;
-        pp_mod[5] = pp_mod[4] + TotalMB;
-    }
-#endif
 
     /*  oscl_memset(mblock->block, 0, sizeof(typeMBStore));    Aug 9,2005 */
 
@@ -698,10 +678,6 @@
             /*  modified to new semaphore for post-proc */
             // Future work:: can be combined in the dequant function
             // @todo Deblocking Semaphore for INTRA block
-#ifdef PV_POSTPROC_ON
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[comp] = (uint8) PostProcSemaphore(dataBlock);
-#endif
         }
         MBlockIDCT(video);
     }
@@ -738,10 +714,6 @@
             }
 
             /*  @todo Deblocking Semaphore for INTRA block, for inter just test for ringing  */
-#ifdef PV_POSTPROC_ON
-            if (video->postFilterType != PV_NO_POST_PROC)
-                *pp_mod[comp] = (uint8)((ncoeffs[comp] > 3) ? 4 : 0);
-#endif
         }
 
         (*DC)[4] = mid_gray;
@@ -760,10 +732,6 @@
         {
             ncoeffs[4] = 0;
         }
-#ifdef PV_POSTPROC_ON
-        if (video->postFilterType != PV_NO_POST_PROC)
-            *pp_mod[4] = (uint8)((ncoeffs[4] > 3) ? 4 : 0);
-#endif
         (*DC)[5] = mid_gray;
         if (CBP & 1)
         {
@@ -780,10 +748,6 @@
         {
             ncoeffs[5] = 0;
         }
-#ifdef PV_POSTPROC_ON
-        if (video->postFilterType != PV_NO_POST_PROC)
-            *pp_mod[5] = (uint8)((ncoeffs[5] > 3) ? 4 : 0);
-#endif
 
 
 
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/dcac_prediction.cpp b/media/codecs/m4v_h263/dec/src/dcac_prediction.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/dcac_prediction.cpp
rename to media/codecs/m4v_h263/dec/src/dcac_prediction.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/dec_pred_intra_dc.cpp b/media/codecs/m4v_h263/dec/src/dec_pred_intra_dc.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/dec_pred_intra_dc.cpp
rename to media/codecs/m4v_h263/dec/src/dec_pred_intra_dc.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp b/media/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp
rename to media/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_outside.cpp b/media/codecs/m4v_h263/dec/src/get_pred_outside.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/get_pred_outside.cpp
rename to media/codecs/m4v_h263/dec/src/get_pred_outside.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/idct.cpp b/media/codecs/m4v_h263/dec/src/idct.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/idct.cpp
rename to media/codecs/m4v_h263/dec/src/idct.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/idct.h b/media/codecs/m4v_h263/dec/src/idct.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/idct.h
rename to media/codecs/m4v_h263/dec/src/idct.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/idct_vca.cpp b/media/codecs/m4v_h263/dec/src/idct_vca.cpp
similarity index 96%
rename from media/libstagefright/codecs/m4v_h263/dec/src/idct_vca.cpp
rename to media/codecs/m4v_h263/dec/src/idct_vca.cpp
index f35ce4f..dbaf5d1 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/idct_vca.cpp
+++ b/media/codecs/m4v_h263/dec/src/idct_vca.cpp
@@ -37,6 +37,7 @@
     return ;
 }
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctrow1(int16 *blk, uint8 *pred, uint8 *dst, int width)
 {
     /* shortcut */
@@ -94,6 +95,7 @@
     return;
 }
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctrow2(int16 *blk, uint8 *pred, uint8 *dst, int width)
 {
     int32 x0, x1, x2, x4, x5;
@@ -155,6 +157,7 @@
     return ;
 }
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctcol2(int16 *blk)
 {
     int32 x0, x1, x3, x5, x7;//, x8;
@@ -182,6 +185,7 @@
     return ;
 }
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctrow3(int16 *blk, uint8 *pred, uint8 *dst, int width)
 {
     int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
@@ -254,6 +258,7 @@
     return ;
 }
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctcol3(int16 *blk)
 {
     int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
@@ -291,6 +296,7 @@
 }
 
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctrow4(int16 *blk, uint8 *pred, uint8 *dst, int width)
 {
     int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
@@ -368,6 +374,7 @@
     return ;
 }
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctcol4(int16 *blk)
 {
     int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
@@ -445,6 +452,7 @@
     return;
 }
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctrow2_intra(int16 *blk, PIXEL *comp, int width)
 {
     int32 x0, x1, x2, x4, x5, temp;
@@ -502,6 +510,7 @@
     return ;
 }
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctrow3_intra(int16 *blk, PIXEL *comp, int width)
 {
     int32 x0, x1, x2, x3, x4, x5, x6, x7, x8, temp;
@@ -575,6 +584,7 @@
     return ;
 }
 
+__attribute__((no_sanitize("signed-integer-overflow")))
 void idctrow4_intra(int16 *blk, PIXEL *comp, int width)
 {
     int32 x0, x1, x2, x3, x4, x5, x6, x7, x8, temp;
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/max_level.h b/media/codecs/m4v_h263/dec/src/max_level.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/max_level.h
rename to media/codecs/m4v_h263/dec/src/max_level.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mb_motion_comp.cpp b/media/codecs/m4v_h263/dec/src/mb_motion_comp.cpp
similarity index 87%
rename from media/libstagefright/codecs/m4v_h263/dec/src/mb_motion_comp.cpp
rename to media/codecs/m4v_h263/dec/src/mb_motion_comp.cpp
index 877723d..79760f5 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/mb_motion_comp.cpp
+++ b/media/codecs/m4v_h263/dec/src/mb_motion_comp.cpp
@@ -154,14 +154,6 @@
     int xpred, ypred;
     int xsum;
     int round1;
-#ifdef PV_POSTPROC_ON // 2/14/2001      
-    /* Total number of pixels in the VOL */
-    int32 size = (int32) video->nTotalMB << 8;
-    uint8 *pp_dec_y, *pp_dec_u;
-    int ll[4];
-    int tmp = 0;
-    uint8 msk_deblock = 0;
-#endif
     /*----------------------------------------------------------------------------
     ; Function body here
     ----------------------------------------------------------------------------*/
@@ -404,43 +396,6 @@
     /* Call function to set de-blocking and de-ringing */
     /*   semaphores for luminance                      */
 
-#ifdef PV_POSTPROC_ON
-    if (video->postFilterType != PV_NO_POST_PROC)
-    {
-        if (mode&INTER_1VMASK)
-        {
-            pp_dec_y = video->pstprcTypCur + imv;
-            ll[0] = 1;
-            ll[1] = mvwidth - 1;
-            ll[2] = 1;
-            ll[3] = -mvwidth - 1;
-            msk_deblock = pp_semaphore_luma(xpred, ypred, pp_dec_y,
-                                            video->pstprcTypPrv, ll, &tmp, px[0], py[0], mvwidth,
-                                            width, height);
-
-            pp_dec_u = video->pstprcTypCur + (size >> 6) +
-                       ((imv + (xpos >> 3)) >> 2);
-
-            pp_semaphore_chroma_inter(xpred, ypred, pp_dec_u,
-                                      video->pstprcTypPrv, dx, dy, mvwidth, height, size,
-                                      tmp, msk_deblock);
-        }
-        else
-        {
-            /* Post-processing mode (MBM_INTER8) */
-            /* deblocking and deringing) */
-            pp_dec_y = video->pstprcTypCur + imv;
-            *pp_dec_y = 4;
-            *(pp_dec_y + 1) = 4;
-            *(pp_dec_y + mvwidth) = 4;
-            *(pp_dec_y + mvwidth + 1) = 4;
-            pp_dec_u = video->pstprcTypCur + (size >> 6) +
-                       ((imv + (xpos >> 3)) >> 2);
-            *pp_dec_u = 4;
-            pp_dec_u[size>>8] = 4;
-        }
-    }
-#endif
 
 
     /* xpred and ypred calculation for Chrominance is */
@@ -566,13 +521,6 @@
     PIXEL *cv_comp, *cv_prev;
     int width, width_uv;
     int32 offset;
-#ifdef PV_POSTPROC_ON // 2/14/2001      
-    int imv;
-    int32 size = (int32) video->nTotalMB << 8;
-    uint8 *pp_dec_y, *pp_dec_u;
-    uint8 *pp_prev1;
-    int mvwidth = video->nMBPerRow << 1;
-#endif
 
     width = video->width;
     width_uv  = width >> 1;
@@ -609,28 +557,6 @@
     PutSKIPPED_B(cv_comp, cv_prev, width_uv);
 
     /*  10/24/2000 post_processing semaphore generation */
-#ifdef PV_POSTPROC_ON // 2/14/2001
-    if (video->postFilterType != PV_NO_POST_PROC)
-    {
-        imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3);
-        /* Post-processing mode (copy previous MB) */
-        pp_prev1 = video->pstprcTypPrv + imv;
-        pp_dec_y = video->pstprcTypCur + imv;
-        *pp_dec_y = *pp_prev1;
-        *(pp_dec_y + 1) = *(pp_prev1 + 1);
-        *(pp_dec_y + mvwidth) = *(pp_prev1 + mvwidth);
-        *(pp_dec_y + mvwidth + 1) = *(pp_prev1 + mvwidth + 1);
-
-        /* chrominance */
-        /*4*MB_in_width*MB_in_height*/
-        pp_prev1 = video->pstprcTypPrv + (size >> 6) +
-                   ((imv + (xpos >> 3)) >> 2);
-        pp_dec_u = video->pstprcTypCur + (size >> 6) +
-                   ((imv + (xpos >> 3)) >> 2);
-        *pp_dec_u = *pp_prev1;
-        pp_dec_u[size>>8] = pp_prev1[size>>8];
-    }
-#endif
     /*----------------------------------------------------------------------------
     ; Return nothing or data or data pointer
     ----------------------------------------------------------------------------*/
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mb_utils.cpp b/media/codecs/m4v_h263/dec/src/mb_utils.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/mb_utils.cpp
rename to media/codecs/m4v_h263/dec/src/mb_utils.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mbtype_mode.h b/media/codecs/m4v_h263/dec/src/mbtype_mode.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/mbtype_mode.h
rename to media/codecs/m4v_h263/dec/src/mbtype_mode.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/motion_comp.h b/media/codecs/m4v_h263/dec/src/motion_comp.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/motion_comp.h
rename to media/codecs/m4v_h263/dec/src/motion_comp.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mp4dec_lib.h b/media/codecs/m4v_h263/dec/src/mp4dec_lib.h
similarity index 92%
rename from media/libstagefright/codecs/m4v_h263/dec/src/mp4dec_lib.h
rename to media/codecs/m4v_h263/dec/src/mp4dec_lib.h
index 9cd4edc..ce6f9c3 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/mp4dec_lib.h
+++ b/media/codecs/m4v_h263/dec/src/mp4dec_lib.h
@@ -170,37 +170,6 @@
 
     /*--------------------------------------------------------------------------*/
     /* defined in pp_semaphore_chroma_inter.c */
-#ifdef PV_POSTPROC_ON
-    void pp_semaphore_chroma_inter(
-        int xpred,      /* i */
-        int ypred,      /* i */
-        uint8   *pp_dec_u,  /* i/o */
-        uint8   *pstprcTypPrv,  /* i */
-        int dx,     /* i */
-        int dy,     /* i */
-        int mvwidth,    /* i */
-        int height,     /* i */
-        int32   size,       /* i */
-        int mv_loc,     /* i */
-        uint8   msk_deblock /* i */
-    );
-
-    /*--------------------------------------------------------------------------*/
-    /* defined in pp_semaphore_luma.c */
-    uint8 pp_semaphore_luma(
-        int xpred,      /* i */
-        int ypred,      /* i */
-        uint8   *pp_dec_y,  /* i/o */
-        uint8   *pstprcTypPrv,  /* i */
-        int *ll,        /* i */
-        int *mv_loc,    /* i/o */
-        int dx,     /* i */
-        int dy,     /* i */
-        int mvwidth,    /* i */
-        int width,      /* i */
-        int height      /* i */
-    );
-#endif
     /*--------------------------------------------------------------------------*/
     /* defined in get_pred_adv_mb_add.c */
     int GetPredAdvancedMB(
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mp4def.h b/media/codecs/m4v_h263/dec/src/mp4def.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/mp4def.h
rename to media/codecs/m4v_h263/dec/src/mp4def.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mp4lib_int.h b/media/codecs/m4v_h263/dec/src/mp4lib_int.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/mp4lib_int.h
rename to media/codecs/m4v_h263/dec/src/mp4lib_int.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/packet_util.cpp b/media/codecs/m4v_h263/dec/src/packet_util.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/packet_util.cpp
rename to media/codecs/m4v_h263/dec/src/packet_util.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/post_filter.cpp b/media/codecs/m4v_h263/dec/src/post_filter.cpp
similarity index 73%
rename from media/libstagefright/codecs/m4v_h263/dec/src/post_filter.cpp
rename to media/codecs/m4v_h263/dec/src/post_filter.cpp
index b36050c..37a03a0 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/post_filter.cpp
+++ b/media/codecs/m4v_h263/dec/src/post_filter.cpp
@@ -24,152 +24,6 @@
 const static int STRENGTH_tab[] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12};
 #endif
 
-#ifdef PV_POSTPROC_ON
-/*----------------------------------------------------------------------------
-; FUNCTION CODE
-----------------------------------------------------------------------------*/
-void PostFilter(
-    VideoDecData *video,
-    int filter_type,
-    uint8 *output)
-{
-    /*----------------------------------------------------------------------------
-    ; Define all local variables
-    ----------------------------------------------------------------------------*/
-    uint8 *pp_mod;
-    int16 *QP_store;
-    int combined_with_deblock_filter;
-    int nTotalMB = video->nTotalMB;
-    int width, height;
-    int32 size;
-    int softDeblocking;
-    uint8 *decodedFrame = video->videoDecControls->outputFrame;
-    /*----------------------------------------------------------------------------
-    ; Function body here
-    ----------------------------------------------------------------------------*/
-    width = video->width;
-    height = video->height;
-    size = (int32)width * height;
-
-    oscl_memcpy(output, decodedFrame, size);
-    oscl_memcpy(output + size, decodedFrame + size, (size >> 2));
-    oscl_memcpy(output + size + (size >> 2), decodedFrame + size + (size >> 2), (size >> 2));
-
-    if (filter_type == 0)
-        return;
-
-    /* The softDecoding cutoff corresponds to ~93000 bps for QCIF 15fps clip  */
-    if (PVGetDecBitrate(video->videoDecControls) > (100*video->frameRate*(size >> 12)))  // MC_sofDeblock
-        softDeblocking = FALSE;
-    else
-        softDeblocking = TRUE;
-
-    combined_with_deblock_filter = filter_type & PV_DEBLOCK;
-    QP_store = video->QPMB;
-
-    /* Luma */
-    pp_mod = video->pstprcTypCur;
-
-    if ((filter_type & PV_DEBLOCK) && (filter_type & PV_DERING))
-    {
-        CombinedHorzVertRingFilter(output, width, height, QP_store, 0, pp_mod);
-    }
-    else
-    {
-        if (filter_type & PV_DEBLOCK)
-        {
-            if (softDeblocking)
-            {
-                CombinedHorzVertFilter(output, width, height,
-                                       QP_store, 0, pp_mod);
-            }
-            else
-            {
-                CombinedHorzVertFilter_NoSoftDeblocking(output, width, height,
-                                                        QP_store, 0, pp_mod);
-            }
-        }
-        if (filter_type & PV_DERING)
-        {
-            Deringing_Luma(output, width, height, QP_store,
-                           combined_with_deblock_filter, pp_mod);
-
-        }
-    }
-
-    /* Chroma */
-
-    pp_mod += (nTotalMB << 2);
-    output += size;
-
-    if ((filter_type & PV_DEBLOCK) && (filter_type & PV_DERING))
-    {
-        CombinedHorzVertRingFilter(output, (int)(width >> 1), (int)(height >> 1), QP_store, (int) 1, pp_mod);
-    }
-    else
-    {
-        if (filter_type & PV_DEBLOCK)
-        {
-            if (softDeblocking)
-            {
-                CombinedHorzVertFilter(output, (int)(width >> 1),
-                                       (int)(height >> 1), QP_store, (int) 1, pp_mod);
-            }
-            else
-            {
-                CombinedHorzVertFilter_NoSoftDeblocking(output, (int)(width >> 1),
-                                                        (int)(height >> 1), QP_store, (int) 1, pp_mod);
-            }
-        }
-        if (filter_type & PV_DERING)
-        {
-            Deringing_Chroma(output, (int)(width >> 1),
-                             (int)(height >> 1), QP_store,
-                             combined_with_deblock_filter, pp_mod);
-        }
-    }
-
-    pp_mod += nTotalMB;
-    output += (size >> 2);
-
-    if ((filter_type & PV_DEBLOCK) && (filter_type & PV_DERING))
-    {
-        CombinedHorzVertRingFilter(output, (int)(width >> 1), (int)(height >> 1), QP_store, (int) 1, pp_mod);
-    }
-    else
-    {
-        if (filter_type & PV_DEBLOCK)
-        {
-            if (softDeblocking)
-            {
-                CombinedHorzVertFilter(output, (int)(width >> 1),
-                                       (int)(height >> 1), QP_store, (int) 1, pp_mod);
-            }
-            else
-            {
-                CombinedHorzVertFilter_NoSoftDeblocking(output, (int)(width >> 1),
-                                                        (int)(height >> 1), QP_store, (int) 1, pp_mod);
-            }
-        }
-        if (filter_type & PV_DERING)
-        {
-            Deringing_Chroma(output, (int)(width >> 1),
-                             (int)(height >> 1), QP_store,
-                             combined_with_deblock_filter, pp_mod);
-        }
-    }
-
-    /*  swap current pp_mod to prev_frame pp_mod */
-    pp_mod = video->pstprcTypCur;
-    video->pstprcTypCur = video->pstprcTypPrv;
-    video->pstprcTypPrv = pp_mod;
-
-    /*----------------------------------------------------------------------------
-    ; Return nothing or data or data pointer
-    ----------------------------------------------------------------------------*/
-    return;
-}
-#endif
 
 
 #ifdef PV_ANNEX_IJKT_SUPPORT
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/post_proc.h b/media/codecs/m4v_h263/dec/src/post_proc.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/post_proc.h
rename to media/codecs/m4v_h263/dec/src/post_proc.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/pvdec_api.cpp b/media/codecs/m4v_h263/dec/src/pvdec_api.cpp
similarity index 96%
rename from media/libstagefright/codecs/m4v_h263/dec/src/pvdec_api.cpp
rename to media/codecs/m4v_h263/dec/src/pvdec_api.cpp
index 9c0fcfa..b0828e4 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/pvdec_api.cpp
+++ b/media/codecs/m4v_h263/dec/src/pvdec_api.cpp
@@ -512,60 +512,6 @@
     video->memoryUsage += (sizeof(MOT) * 8 * nTotalMB);
 #endif
 
-#ifdef PV_POSTPROC_ON
-    /* Allocating space for post-processing Mode */
-#ifdef DEC_INTERNAL_MEMORY_OPT
-    video->pstprcTypCur = IMEM_pstprcTypCur;
-    video->memoryUsage += (nTotalMB * 6);
-    if (video->pstprcTypCur == NULL)
-    {
-        status = PV_FALSE;
-    }
-    else
-    {
-        oscl_memset(video->pstprcTypCur, 0, 4*nTotalMB + 2*nTotalMB);
-    }
-
-    video->pstprcTypPrv = IMEM_pstprcTypPrv;
-    video->memoryUsage += (nTotalMB * 6);
-    if (video->pstprcTypPrv == NULL)
-    {
-        status = PV_FALSE;
-    }
-    else
-    {
-        oscl_memset(video->pstprcTypPrv, 0, nTotalMB*6);
-    }
-
-#else
-    if (nTotalMB > INT32_MAX / 6) {
-        return PV_FALSE;
-    }
-    video->pstprcTypCur = (uint8 *) oscl_malloc(nTotalMB * 6);
-    video->memoryUsage += (nTotalMB * 6);
-    if (video->pstprcTypCur == NULL)
-    {
-        status = PV_FALSE;
-    }
-    else
-    {
-        oscl_memset(video->pstprcTypCur, 0, 4*nTotalMB + 2*nTotalMB);
-    }
-
-    video->pstprcTypPrv = (uint8 *) oscl_malloc(nTotalMB * 6);
-    video->memoryUsage += (nTotalMB * 6);
-    if (video->pstprcTypPrv == NULL)
-    {
-        status = PV_FALSE;
-    }
-    else
-    {
-        oscl_memset(video->pstprcTypPrv, 0, nTotalMB*6);
-    }
-
-#endif
-
-#endif
 
     /* initialize the decoder library */
     video->prevVop->predictionType = I_VOP;
@@ -631,10 +577,6 @@
 #ifdef DEC_INTERNAL_MEMORY_OPT
     if (video)
     {
-#ifdef PV_POSTPROC_ON
-        video->pstprcTypCur = NULL;
-        video->pstprcTypPrv = NULL;
-#endif
 
         video->acPredFlag       = NULL;
         video->sliceNo          = NULL;
@@ -699,10 +641,6 @@
 
     if (video)
     {
-#ifdef PV_POSTPROC_ON
-        if (video->pstprcTypCur) oscl_free(video->pstprcTypCur);
-        if (video->pstprcTypPrv) oscl_free(video->pstprcTypPrv);
-#endif
         if (video->predDC) oscl_free(video->predDC);
         video->predDCAC_row = NULL;
         if (video->predDCAC_col) oscl_free(video->predDCAC_col);
@@ -830,7 +768,10 @@
 OSCL_EXPORT_REF void PVSetPostProcType(VideoDecControls *decCtrl, int mode)
 {
     VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
-    video->postFilterType = mode;
+    if (mode != 0) {
+        ALOGE("Post processing filters are not supported");
+    }
+    video->postFilterType = 0;
 }
 
 
@@ -1621,43 +1562,8 @@
 void PVDecPostProcess(VideoDecControls *decCtrl, uint8 *outputYUV)
 {
     uint8 *outputBuffer;
-#ifdef PV_POSTPROC_ON
-    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
-    int32 tmpvar;
-    if (outputYUV)
-    {
-        outputBuffer = outputYUV;
-    }
-    else
-    {
-        if (video->postFilterType)
-        {
-            outputBuffer = video->currVop->yChan;
-        }
-        else
-        {
-            outputBuffer = decCtrl->outputFrame;
-        }
-    }
-
-    if (video->postFilterType)
-    {
-        /* Post-processing,  */
-        PostFilter(video, video->postFilterType, outputBuffer);
-    }
-    else
-    {
-        if (outputYUV)
-        {
-            /* Copy decoded frame to the output buffer. */
-            tmpvar = (int32)video->width * video->height;
-            oscl_memcpy(outputBuffer, decCtrl->outputFrame, tmpvar*3 / 2);           /*  3/3/01 */
-        }
-    }
-#else
     outputBuffer = decCtrl->outputFrame;
     outputYUV;
-#endif
     decCtrl->outputFrame = outputBuffer;
     return;
 }
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/scaling.h b/media/codecs/m4v_h263/dec/src/scaling.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/scaling.h
rename to media/codecs/m4v_h263/dec/src/scaling.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/scaling_tab.cpp b/media/codecs/m4v_h263/dec/src/scaling_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/scaling_tab.cpp
rename to media/codecs/m4v_h263/dec/src/scaling_tab.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_dec_tab.h b/media/codecs/m4v_h263/dec/src/vlc_dec_tab.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/vlc_dec_tab.h
rename to media/codecs/m4v_h263/dec/src/vlc_dec_tab.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.cpp b/media/codecs/m4v_h263/dec/src/vlc_decode.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.cpp
rename to media/codecs/m4v_h263/dec/src/vlc_decode.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.h b/media/codecs/m4v_h263/dec/src/vlc_decode.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.h
rename to media/codecs/m4v_h263/dec/src/vlc_decode.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_dequant.cpp b/media/codecs/m4v_h263/dec/src/vlc_dequant.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/vlc_dequant.cpp
rename to media/codecs/m4v_h263/dec/src/vlc_dequant.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_tab.cpp b/media/codecs/m4v_h263/dec/src/vlc_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/vlc_tab.cpp
rename to media/codecs/m4v_h263/dec/src/vlc_tab.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vop.cpp b/media/codecs/m4v_h263/dec/src/vop.cpp
similarity index 98%
rename from media/libstagefright/codecs/m4v_h263/dec/src/vop.cpp
rename to media/codecs/m4v_h263/dec/src/vop.cpp
index a11f55e..7b32498 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/vop.cpp
+++ b/media/codecs/m4v_h263/dec/src/vop.cpp
@@ -24,7 +24,6 @@
 
 #define OSCL_DISABLE_WARNING_CONV_POSSIBLE_LOSS_OF_DATA
 
-#ifdef PV_SUPPORT_MAIN_PROFILE
 /* INTRA */
 const static int mpeg_iqmat_def[NCOEFF_BLOCK] =
 {
@@ -50,7 +49,6 @@
     22, 23, 24, 26, 27, 28, 30, 31,
     23, 24, 25, 27, 28, 30, 31, 33
 };
-#endif
 
 /* ======================================================================== */
 /*  Function : CalcNumBits()                                                */
@@ -86,9 +84,7 @@
     BitstreamDecVideo *stream;
     uint32 tmpvar, vol_shape;
     uint32 startCode;
-#ifdef PV_SUPPORT_MAIN_PROFILE
     int *qmat, i, j;
-#endif
     int version_id = 1;
 #ifdef PV_TOLERATE_VOL_ERRORS
     uint32 profile = 0x01;
@@ -317,7 +313,8 @@
         }
         else
         {
-            if (tmpvar != 0x01) return PV_FAIL;
+            // Simple and advanced simple (for quant-type 1)
+            if (tmpvar != 0x01 && tmpvar != 0x11) return PV_FAIL;
         }
 
         /* version id specified? */
@@ -486,7 +483,6 @@
         currVol->quantType = BitstreamRead1Bits(stream);
         if (currVol->quantType)
         {
-#ifdef PV_SUPPORT_MAIN_PROFILE
             /* load quantization matrices.   5/22/2000 */
             /* load_intra_quant_mat (1 bit) */
             qmat = currVol->iqmat;
@@ -501,6 +497,13 @@
                 }
                 while ((qmat[*(zigzag_inv+i)] != 0) && (++i < 64));
 
+                /* qmatrix must have at least one non-zero value, which means
+                   i would be non-zero in valid cases */
+                if (i == 0)
+                {
+                    return PV_FAIL;
+                }
+
                 for (j = i; j < 64; j++)
                     qmat[*(zigzag_inv+j)] = qmat[*(zigzag_inv+i-1)];
             }
@@ -524,6 +527,13 @@
                 }
                 while ((qmat[*(zigzag_inv+i)] != 0) && (++i < 64));
 
+                /* qmatrix must have at least one non-zero value, which means
+                   i would be non-zero in valid cases */
+                if (i == 0)
+                {
+                    return PV_FAIL;
+                }
+
                 for (j = i; j < 64; j++)
                     qmat[*(zigzag_inv+j)] = qmat[*(zigzag_inv+i-1)];
             }
@@ -531,9 +541,6 @@
             {
                 oscl_memcpy(qmat, mpeg_nqmat_def, 64*sizeof(int));
             }
-#else
-            return PV_FAIL;
-#endif
         }
 
         if (version_id != 1)
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/zigzag.h b/media/codecs/m4v_h263/dec/src/zigzag.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/zigzag.h
rename to media/codecs/m4v_h263/dec/src/zigzag.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/zigzag_tab.cpp b/media/codecs/m4v_h263/dec/src/zigzag_tab.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/src/zigzag_tab.cpp
rename to media/codecs/m4v_h263/dec/src/zigzag_tab.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp b/media/codecs/m4v_h263/dec/test/Android.bp
similarity index 73%
rename from media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
rename to media/codecs/m4v_h263/dec/test/Android.bp
index 655491a..4ae5e73 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
+++ b/media/codecs/m4v_h263/dec/test/Android.bp
@@ -14,6 +14,17 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_m4v_h263_dec_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_m4v_h263_dec_license",
+    ],
+}
+
 cc_test {
     name: "Mpeg4H263DecoderTest",
     gtest: true,
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/AndroidTest.xml b/media/codecs/m4v_h263/dec/test/AndroidTest.xml
similarity index 97%
rename from media/libstagefright/codecs/m4v_h263/dec/test/AndroidTest.xml
rename to media/codecs/m4v_h263/dec/test/AndroidTest.xml
index 47e10ca..f572b0c 100755
--- a/media/libstagefright/codecs/m4v_h263/dec/test/AndroidTest.xml
+++ b/media/codecs/m4v_h263/dec/test/AndroidTest.xml
@@ -19,7 +19,7 @@
         <option name="cleanup" value="true" />
         <option name="push" value="Mpeg4H263DecoderTest->/data/local/tmp/Mpeg4H263DecoderTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/codecs/m4v_h263/dec/test/Mpeg4H263Decoder.zip?unzip=true"
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/codecs/m4v_h263/dec/test/Mpeg4H263Decoder-1.1.zip?unzip=true"
             value="/data/local/tmp/Mpeg4H263DecoderTestRes/" />
     </target_preparer>
 
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTest.cpp b/media/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTest.cpp
similarity index 97%
rename from media/libstagefright/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTest.cpp
rename to media/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTest.cpp
index 967c1ea..53d66ea 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTest.cpp
+++ b/media/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTest.cpp
@@ -404,6 +404,9 @@
                           make_tuple("swirl_352x288_h263.h263", "swirl_352x288_h263.info", false),
                           make_tuple("bbb_352x288_h263.h263", "bbb_352x288_h263.info", false),
                           make_tuple("bbb_352x288_mpeg4.m4v", "bbb_352x288_mpeg4.info", true),
+                          make_tuple("qtype0_mpeg4.m4v", "qtype0_mpeg4.info", true),
+                          make_tuple("qtype1_mpeg4.m4v", "qtype1_mpeg4.info", true),
+                          make_tuple("qtype1_qmatrix_mpeg4.m4v", "qtype1_qmatrix_mpeg4.info", true),
                           make_tuple("swirl_128x128_mpeg4.m4v", "swirl_128x128_mpeg4.info", true),
                           make_tuple("swirl_130x132_mpeg4.m4v", "swirl_130x132_mpeg4.info", true),
                           make_tuple("swirl_132x130_mpeg4.m4v", "swirl_132x130_mpeg4.info", true),
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTestEnvironment.h b/media/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTestEnvironment.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTestEnvironment.h
rename to media/codecs/m4v_h263/dec/test/Mpeg4H263DecoderTestEnvironment.h
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/README.md b/media/codecs/m4v_h263/dec/test/README.md
similarity index 90%
rename from media/libstagefright/codecs/m4v_h263/dec/test/README.md
rename to media/codecs/m4v_h263/dec/test/README.md
index 7e4aea1..38ac567 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/README.md
+++ b/media/codecs/m4v_h263/dec/test/README.md
@@ -22,7 +22,8 @@
 adb push ${OUT}/data/nativetest/Mpeg4H263DecoderTest/Mpeg4H263DecoderTest /data/local/tmp/
 ```
 
-The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/codecs/m4v_h263/dec/test/Mpeg4H263Decoder.zip). Download, unzip and push these files into device for testing.
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/codecs/m4v_h263/dec/test/Mpeg4H263Decoder-1.1.zip).
+Download, unzip and push these files into device for testing.
 
 ```
 adb push Mpeg4H263Decoder /data/local/tmp/
diff --git a/media/codecs/m4v_h263/enc/Android.bp b/media/codecs/m4v_h263/enc/Android.bp
new file mode 100644
index 0000000..e303404
--- /dev/null
+++ b/media/codecs/m4v_h263/enc/Android.bp
@@ -0,0 +1,107 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_m4v_h263_enc_license",
+    ],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codecs_m4v_h263_enc_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-BSD",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library_static {
+    name: "libstagefright_m4vh263enc",
+    vendor_available: true,
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.media.swcodec",
+    ],
+    min_sdk_version: "29",
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+
+    srcs: [
+        "src/bitstream_io.cpp",
+        "src/combined_encode.cpp", "src/datapart_encode.cpp",
+        "src/dct.cpp",
+        "src/findhalfpel.cpp",
+        "src/fastcodemb.cpp",
+        "src/fastidct.cpp",
+        "src/fastquant.cpp",
+        "src/me_utils.cpp",
+        "src/mp4enc_api.cpp",
+        "src/rate_control.cpp",
+        "src/motion_est.cpp",
+        "src/motion_comp.cpp",
+        "src/sad.cpp",
+        "src/sad_halfpel.cpp",
+        "src/vlc_encode.cpp",
+        "src/vop.cpp",
+    ],
+
+    cflags: [
+        "-DBX_RC",
+        "-Werror",
+    ],
+
+    local_include_dirs: ["src"],
+    export_include_dirs: ["include"],
+
+    sanitize: {
+        misc_undefined: [
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+    },
+}
+
+//###############################################################################
+
+cc_test {
+    name: "libstagefright_m4vh263enc_test",
+    gtest: false,
+
+    srcs: ["test/m4v_h263_enc_test.cpp"],
+
+    local_include_dirs: ["src"],
+
+    cflags: [
+        "-DBX_RC",
+        "-Wall",
+        "-Werror",
+    ],
+
+    sanitize: {
+        misc_undefined: [
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+    },
+
+    static_libs: ["libstagefright_m4vh263enc"],
+}
diff --git a/media/libstagefright/codecs/m4v_h263/enc/MODULE_LICENSE_APACHE2 b/media/codecs/m4v_h263/enc/MODULE_LICENSE_APACHE2
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/MODULE_LICENSE_APACHE2
rename to media/codecs/m4v_h263/enc/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/codecs/m4v_h263/enc/NOTICE b/media/codecs/m4v_h263/enc/NOTICE
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/NOTICE
rename to media/codecs/m4v_h263/enc/NOTICE
diff --git a/media/libstagefright/codecs/m4v_h263/enc/include/cvei.h b/media/codecs/m4v_h263/enc/include/cvei.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/include/cvei.h
rename to media/codecs/m4v_h263/enc/include/cvei.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/include/mp4enc_api.h b/media/codecs/m4v_h263/enc/include/mp4enc_api.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/include/mp4enc_api.h
rename to media/codecs/m4v_h263/enc/include/mp4enc_api.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/bitstream_io.cpp b/media/codecs/m4v_h263/enc/src/bitstream_io.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/bitstream_io.cpp
rename to media/codecs/m4v_h263/enc/src/bitstream_io.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/bitstream_io.h b/media/codecs/m4v_h263/enc/src/bitstream_io.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/bitstream_io.h
rename to media/codecs/m4v_h263/enc/src/bitstream_io.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/combined_encode.cpp b/media/codecs/m4v_h263/enc/src/combined_encode.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/combined_encode.cpp
rename to media/codecs/m4v_h263/enc/src/combined_encode.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/datapart_encode.cpp b/media/codecs/m4v_h263/enc/src/datapart_encode.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/datapart_encode.cpp
rename to media/codecs/m4v_h263/enc/src/datapart_encode.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/dct.cpp b/media/codecs/m4v_h263/enc/src/dct.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/dct.cpp
rename to media/codecs/m4v_h263/enc/src/dct.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/dct.h b/media/codecs/m4v_h263/enc/src/dct.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/dct.h
rename to media/codecs/m4v_h263/enc/src/dct.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/dct_inline.h b/media/codecs/m4v_h263/enc/src/dct_inline.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/dct_inline.h
rename to media/codecs/m4v_h263/enc/src/dct_inline.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp b/media/codecs/m4v_h263/enc/src/fastcodemb.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp
rename to media/codecs/m4v_h263/enc/src/fastcodemb.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.h b/media/codecs/m4v_h263/enc/src/fastcodemb.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.h
rename to media/codecs/m4v_h263/enc/src/fastcodemb.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/fastidct.cpp b/media/codecs/m4v_h263/enc/src/fastidct.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/fastidct.cpp
rename to media/codecs/m4v_h263/enc/src/fastidct.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/fastquant.cpp b/media/codecs/m4v_h263/enc/src/fastquant.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/fastquant.cpp
rename to media/codecs/m4v_h263/enc/src/fastquant.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/fastquant_inline.h b/media/codecs/m4v_h263/enc/src/fastquant_inline.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/fastquant_inline.h
rename to media/codecs/m4v_h263/enc/src/fastquant_inline.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/findhalfpel.cpp b/media/codecs/m4v_h263/enc/src/findhalfpel.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/findhalfpel.cpp
rename to media/codecs/m4v_h263/enc/src/findhalfpel.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/m4venc_oscl.h b/media/codecs/m4v_h263/enc/src/m4venc_oscl.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/m4venc_oscl.h
rename to media/codecs/m4v_h263/enc/src/m4venc_oscl.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/me_utils.cpp b/media/codecs/m4v_h263/enc/src/me_utils.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/me_utils.cpp
rename to media/codecs/m4v_h263/enc/src/me_utils.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/motion_comp.cpp b/media/codecs/m4v_h263/enc/src/motion_comp.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/motion_comp.cpp
rename to media/codecs/m4v_h263/enc/src/motion_comp.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/motion_est.cpp b/media/codecs/m4v_h263/enc/src/motion_est.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/motion_est.cpp
rename to media/codecs/m4v_h263/enc/src/motion_est.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/mp4def.h b/media/codecs/m4v_h263/enc/src/mp4def.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/mp4def.h
rename to media/codecs/m4v_h263/enc/src/mp4def.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/mp4enc_api.cpp b/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp
similarity index 99%
rename from media/libstagefright/codecs/m4v_h263/enc/src/mp4enc_api.cpp
rename to media/codecs/m4v_h263/enc/src/mp4enc_api.cpp
index 7ab8f45..d43156c 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/src/mp4enc_api.cpp
+++ b/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp
@@ -1579,7 +1579,7 @@
         if (currLayer == 0)
         {
             video->forwardRefVop = tempForwRefVop; /* For P-Vop base only */
-            video->forwardRefVop->refSelectCode = tempRefSelCode;
+            if (video->forwardRefVop != NULL) video->forwardRefVop->refSelectCode = tempRefSelCode;
         }
 
         return status;
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/mp4enc_lib.h b/media/codecs/m4v_h263/enc/src/mp4enc_lib.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/mp4enc_lib.h
rename to media/codecs/m4v_h263/enc/src/mp4enc_lib.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/mp4lib_int.h b/media/codecs/m4v_h263/enc/src/mp4lib_int.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/mp4lib_int.h
rename to media/codecs/m4v_h263/enc/src/mp4lib_int.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/rate_control.cpp b/media/codecs/m4v_h263/enc/src/rate_control.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/rate_control.cpp
rename to media/codecs/m4v_h263/enc/src/rate_control.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/rate_control.h b/media/codecs/m4v_h263/enc/src/rate_control.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/rate_control.h
rename to media/codecs/m4v_h263/enc/src/rate_control.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/sad.cpp b/media/codecs/m4v_h263/enc/src/sad.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/sad.cpp
rename to media/codecs/m4v_h263/enc/src/sad.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/sad_halfpel.cpp b/media/codecs/m4v_h263/enc/src/sad_halfpel.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/sad_halfpel.cpp
rename to media/codecs/m4v_h263/enc/src/sad_halfpel.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/sad_halfpel_inline.h b/media/codecs/m4v_h263/enc/src/sad_halfpel_inline.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/sad_halfpel_inline.h
rename to media/codecs/m4v_h263/enc/src/sad_halfpel_inline.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/sad_inline.h b/media/codecs/m4v_h263/enc/src/sad_inline.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/sad_inline.h
rename to media/codecs/m4v_h263/enc/src/sad_inline.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/sad_mb_offset.h b/media/codecs/m4v_h263/enc/src/sad_mb_offset.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/sad_mb_offset.h
rename to media/codecs/m4v_h263/enc/src/sad_mb_offset.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/vlc_enc_tab.h b/media/codecs/m4v_h263/enc/src/vlc_enc_tab.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/vlc_enc_tab.h
rename to media/codecs/m4v_h263/enc/src/vlc_enc_tab.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/vlc_encode.cpp b/media/codecs/m4v_h263/enc/src/vlc_encode.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/vlc_encode.cpp
rename to media/codecs/m4v_h263/enc/src/vlc_encode.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/vlc_encode.h b/media/codecs/m4v_h263/enc/src/vlc_encode.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/vlc_encode.h
rename to media/codecs/m4v_h263/enc/src/vlc_encode.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/vlc_encode_inline.h b/media/codecs/m4v_h263/enc/src/vlc_encode_inline.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/vlc_encode_inline.h
rename to media/codecs/m4v_h263/enc/src/vlc_encode_inline.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/vop.cpp b/media/codecs/m4v_h263/enc/src/vop.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/src/vop.cpp
rename to media/codecs/m4v_h263/enc/src/vop.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/test/Android.bp b/media/codecs/m4v_h263/enc/test/Android.bp
similarity index 71%
rename from media/libstagefright/codecs/m4v_h263/enc/test/Android.bp
rename to media/codecs/m4v_h263/enc/test/Android.bp
index b9a8117..e1ce4aa 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/test/Android.bp
+++ b/media/codecs/m4v_h263/enc/test/Android.bp
@@ -14,6 +14,18 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_m4v_h263_enc_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-BSD
+    default_applicable_licenses: [
+        "frameworks_av_media_codecs_m4v_h263_enc_license",
+    ],
+}
+
 cc_test {
     name: "Mpeg4H263EncoderTest",
     gtest: true,
diff --git a/media/libstagefright/codecs/m4v_h263/enc/test/AndroidTest.xml b/media/codecs/m4v_h263/enc/test/AndroidTest.xml
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/test/AndroidTest.xml
rename to media/codecs/m4v_h263/enc/test/AndroidTest.xml
diff --git a/media/libstagefright/codecs/m4v_h263/enc/test/Mpeg4H263EncoderTest.cpp b/media/codecs/m4v_h263/enc/test/Mpeg4H263EncoderTest.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/test/Mpeg4H263EncoderTest.cpp
rename to media/codecs/m4v_h263/enc/test/Mpeg4H263EncoderTest.cpp
diff --git a/media/libstagefright/codecs/m4v_h263/enc/test/Mpeg4H263EncoderTestEnvironment.h b/media/codecs/m4v_h263/enc/test/Mpeg4H263EncoderTestEnvironment.h
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/test/Mpeg4H263EncoderTestEnvironment.h
rename to media/codecs/m4v_h263/enc/test/Mpeg4H263EncoderTestEnvironment.h
diff --git a/media/libstagefright/codecs/m4v_h263/enc/test/README.md b/media/codecs/m4v_h263/enc/test/README.md
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/test/README.md
rename to media/codecs/m4v_h263/enc/test/README.md
diff --git a/media/libstagefright/codecs/m4v_h263/enc/test/m4v_h263_enc_test.cpp b/media/codecs/m4v_h263/enc/test/m4v_h263_enc_test.cpp
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/enc/test/m4v_h263_enc_test.cpp
rename to media/codecs/m4v_h263/enc/test/m4v_h263_enc_test.cpp
diff --git a/media/codecs/m4v_h263/fuzzer/Android.bp b/media/codecs/m4v_h263/fuzzer/Android.bp
new file mode 100644
index 0000000..a052c11
--- /dev/null
+++ b/media/codecs/m4v_h263/fuzzer/Android.bp
@@ -0,0 +1,120 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_defaults {
+    name: "mpeg4_h263_dec_fuzz_defaults",
+
+    host_supported: true,
+
+    srcs: [
+        "mpeg4_h263_dec_fuzzer.cpp",
+    ],
+
+    static_libs: [
+        "libstagefright_m4vh263dec",
+        "liblog",
+    ],
+
+    cflags: [
+        "-DOSCL_IMPORT_REF=",
+    ],
+
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
+
+cc_fuzz {
+    name: "mpeg4_dec_fuzzer",
+
+    defaults: [
+        "mpeg4_h263_dec_fuzz_defaults",
+    ],
+
+    cflags: [
+        "-DMPEG4",
+    ],
+}
+
+cc_fuzz {
+    name: "h263_dec_fuzzer",
+
+    defaults: [
+        "mpeg4_h263_dec_fuzz_defaults",
+    ],
+}
+
+cc_defaults {
+    name: "mpeg4_h263_enc_fuzz_defaults",
+
+    host_supported: true,
+
+    srcs: ["mpeg4_h263_enc_fuzzer.cpp"],
+
+    shared_libs: [
+        "libutils",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libstagefright_m4vh263enc",
+    ],
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
+
+cc_fuzz {
+    name: "mpeg4_enc_fuzzer",
+
+    defaults: [
+        "mpeg4_h263_enc_fuzz_defaults",
+    ],
+
+    cflags: ["-DMPEG4"],
+}
+
+cc_fuzz {
+    name: "h263_enc_fuzzer",
+
+    defaults: [
+        "mpeg4_h263_enc_fuzz_defaults",
+    ],
+}
diff --git a/media/codecs/m4v_h263/fuzzer/README.md b/media/codecs/m4v_h263/fuzzer/README.md
new file mode 100644
index 0000000..ad4ff97
--- /dev/null
+++ b/media/codecs/m4v_h263/fuzzer/README.md
@@ -0,0 +1,158 @@
+# Fuzzer for libstagefright_m4vh263dec decoder
+
+## Plugin Design Considerations
+The fuzzer plugin for MPEG4/H263 is designed based on the understanding of the
+codec and tries to achieve the following:
+
+##### Maximize code coverage
+Dict files (dictionary files) are created for MPEG4 and H263 to ensure that the required start
+bytes are present in every input file that goes to the fuzzer.
+This ensures that decoder does not reject any input file in the first check
+
+##### Maximize utilization of input data
+The plugin feeds the entire input data to the codec using a loop.
+ * If the decode operation was successful, the input is advanced by the number of bytes consumed
+   in the decode call.
+ * If the decode operation was un-successful, the input is advanced by 1 byte so that the fuzzer
+   can proceed to feed the next frame.
+
+This ensures that the plugin tolerates any kind of input (empty, huge, malformed, etc)
+and doesnt `exit()` on any input and thereby increasing the chance of identifying vulnerabilities.
+
+##### Other considerations
+ * Two fuzzer binaries - mpeg4_dec_fuzzer and h263_dec_fuzzer are generated based on the presence
+   of a flag - 'MPEG4'
+ * The number of decode calls are kept to a maximum of 100 so that the fuzzer does not timeout.
+
+## Build
+
+This describes steps to build mpeg4_dec_fuzzer and h263_dec_fuzzer binary.
+
+### Android
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mpeg4_dec_fuzzer
+  $ mm -j$(nproc) h263_dec_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some MPEG4 or H263 files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/mpeg4_dec_fuzzer/mpeg4_dec_fuzzer CORPUS_DIR
+  $ adb shell /data/fuzz/arm64/h263_dec_fuzzer/h263_dec_fuzzer CORPUS_DIR
+```
+To run on host
+```
+  $ $ANDROID_HOST_OUT/fuzz/x86_64/mpeg4_dec_fuzzer/mpeg4_dec_fuzzer CORPUS_DIR
+  $ $ANDROID_HOST_OUT/fuzz/x86_64/h263_dec_fuzzer/h263_dec_fuzzer CORPUS_DIR
+```
+
+# Fuzzer for libstagefright_m4vh263enc encoder
+
+## Plugin Design Considerations
+The fuzzer plugin for MPEG4/H263 is designed based on the understanding of the
+codec and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+MPEG4/H263 supports the following parameters:
+1. Frame Width (parameter name: `encWidth`)
+2. Frame Height (parameter name: `encHeight`)
+3. Rate control mode (parameter name: `rcType`)
+4. Number of bytes per packet (parameter name: `packetSize`)
+5. Qp for I-Vop(parameter name: `iQuant`)
+6. Qp for P-Vop (parameter name: `pQuant`)
+7. Enable RVLC mode (parameter name: `rvlcEnable`)
+8. Quantization mode (parameter name: `quantType`)
+9. Disable frame skipping (parameter name: `noFrameSkipped`)
+10. Enable scene change detection (parameter name: `sceneDetect`)
+11. Number of intra MBs in P-frame(parameter name: `numIntraMB`)
+12. Search range of ME (parameter name: `searchRange`)
+13. Enable 8x8 ME and MC (parameter name: `mv8x8Enable`)
+14. Enable AC prediction (parameter name: `useACPred`)
+15. Threshold for intra DC VLC (parameter name: `intraDCVlcTh`)
+16. Encoding Mode (parameter name: `encMode`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `rcType` | 0. `CONSTANT_Q` 1. `CBR_1` 2. `VBR_1` 3. `CBR_2` 4. `VBR_2` 5. `CBR_LOWDELAY` | All the bits of 6th byte of data modulus 6 |
+| `packetSize` | In the range `0 to 255` | All the bits of 7th byte of data |
+| `iQuant` | In the range `1 to 31` | All the bits of 8th byte of data |
+| `pQuant` | In the range `1 to 31` | All the bits of 9th byte of data |
+| `rvlcEnable` | 0. `PV_OFF` 1. `PV_ON` | bit 0 of 10th byte of data |
+| `quantType` | 0. `0` 1. `1` | bit 0 of 11th byte of data |
+| `noFrameSkipped` | 0. `PV_OFF` 1. `PV_ON` | bit 0 of 12th byte of data |
+| `sceneDetect` | 0. `PV_OFF` 1. `PV_ON` | bit 0 of 13th byte of data |
+| `numIntraMB` | In the range `0 to 7` | bit 0, 1 and 2 of 14th byte of data |
+| `searchRange` | In the range `0 to 31` | bit 0, 1, 2, 3 and 4 of 15th byte of data |
+| `mv8x8Enable` | 0. `PV_OFF` 1. `PV_ON` | bit 0 of 16th byte of data |
+| `useACPred` | 0. `PV_OFF` 1. `PV_ON` | bit 0 of 17th byte of data |
+| `intraDCVlcTh` | In the range `0 to 7` | bit 0, 1 and 2 of 18th byte of data |
+
+Following parameters are only for mpeg4_enc_fuzzer
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `encWidth` | In the range `0 to 10239` | All the bits of 1st and 2nd byte of data |
+| `encHeight` | In the range `0 to 10239` | All the bits of 3rd and 4th byte of data |
+| `encMode` | 0. `H263_MODE` 1. `H263_MODE_WITH_ERR_RES` 2. `DATA_PARTITIONING_MODE` 3. `COMBINE_MODE_NO_ERR_RES` 4. `COMBINE_MODE_WITH_ERR_RES` | All the bits of 19th byte of data modulus 5 |
+
+Following parameters are only for h263_enc_fuzzer
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `encWidth` | 0. `128` 1. `176` 2. `352` 3. `704` 4. `1408` | All the bits of 1st byte of data modulus 5|
+| `encHeight` | 0. `96` 1. `144` 2. `288` 3. `576` 4. `1152 ` | All the bits of 3rd byte of data modulus 5|
+| `encMode` | 0. `SHORT_HEADER` 1. `SHORT_HEADER_WITH_ERR_RES` | All the bits of 19th byte of data modulus 2 |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+##### Maximize utilization of input data
+The plugin feeds the entire input data to the codec using a loop.
+If the encode operation was successful, the input is advanced by the frame size.
+If the encode operation was un-successful, the input is still advanced by frame size so
+that the fuzzer can proceed to feed the next frame.
+
+This ensures that the plugin tolerates any kind of input (empty, huge,
+malformed, etc) and doesnt `exit()` on any input and thereby increasing the
+chance of identifying vulnerabilities.
+
+## Build
+
+This describes steps to build mpeg4_enc_fuzzer and h263_enc_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mpeg4_enc_fuzzer
+  $ mm -j$(nproc) h263_enc_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some yuv files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/m4v_h263_enc_fuzzer/m4v_h263_enc_fuzzer CORPUS_DIR
+  $ adb shell /data/fuzz/arm64/h263_enc_fuzzer/h263_enc_fuzzer CORPUS_DIR
+```
+To run on host
+```
+  $ $ANDROID_HOST_OUT/fuzz/x86_64/mpeg4_enc_fuzzer/mpeg4_enc_fuzzer CORPUS_DIR
+  $ $ANDROID_HOST_OUT/fuzz/x86_64/h263_enc_fuzzer/h263_enc_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/media/codecs/m4v_h263/fuzzer/h263_dec_fuzzer.dict b/media/codecs/m4v_h263/fuzzer/h263_dec_fuzzer.dict
new file mode 100644
index 0000000..591d37e
--- /dev/null
+++ b/media/codecs/m4v_h263/fuzzer/h263_dec_fuzzer.dict
@@ -0,0 +1,2 @@
+# Start code (bytes 0-3)
+kw1="\x00\x00\x80\x02"
diff --git a/media/codecs/m4v_h263/fuzzer/mpeg4_dec_fuzzer.dict b/media/codecs/m4v_h263/fuzzer/mpeg4_dec_fuzzer.dict
new file mode 100644
index 0000000..76241a6
--- /dev/null
+++ b/media/codecs/m4v_h263/fuzzer/mpeg4_dec_fuzzer.dict
@@ -0,0 +1,2 @@
+# Start code (bytes 0-3)
+kw1="\x00\x00\x01\xB0"
diff --git a/media/codecs/m4v_h263/fuzzer/mpeg4_h263_dec_fuzzer.cpp b/media/codecs/m4v_h263/fuzzer/mpeg4_h263_dec_fuzzer.cpp
new file mode 100644
index 0000000..912c821
--- /dev/null
+++ b/media/codecs/m4v_h263/fuzzer/mpeg4_h263_dec_fuzzer.cpp
@@ -0,0 +1,205 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+#include "mp4dec_api.h"
+#define MPEG4_MAX_WIDTH 1920
+#define MPEG4_MAX_HEIGHT 1080
+#define H263_MAX_WIDTH 352
+#define H263_MAX_HEIGHT 288
+#define DEFAULT_WIDTH 352
+#define DEFAULT_HEIGHT 288
+
+constexpr size_t kMaxNumDecodeCalls = 100;
+constexpr uint8_t kNumOutputBuffers = 2;
+constexpr int kLayer = 1;
+
+struct tagvideoDecControls;
+
+/* == ceil(num / den) * den. T must be integer type, alignment must be positive power of 2 */
+template <class T, class U>
+inline static const T align(const T &num, const U &den) {
+  return (num + (T)(den - 1)) & (T) ~(den - 1);
+}
+
+class Codec {
+ public:
+  Codec() = default;
+  ~Codec() { deInitDecoder(); }
+  bool initDecoder();
+  bool allocOutputBuffer(size_t outputBufferSize);
+  void freeOutputBuffer();
+  void handleResolutionChange();
+  void decodeFrames(const uint8_t *data, size_t size);
+  void deInitDecoder();
+
+ private:
+  tagvideoDecControls *mDecHandle = nullptr;
+  uint8_t *mOutputBuffer[kNumOutputBuffers];
+  bool mInitialized = false;
+  bool mFramesConfigured = false;
+#ifdef MPEG4
+  MP4DecodingMode mInputMode = MPEG4_MODE;
+  size_t mMaxWidth = MPEG4_MAX_WIDTH;
+  size_t mMaxHeight = MPEG4_MAX_HEIGHT;
+#else
+  MP4DecodingMode mInputMode = H263_MODE;
+  size_t mMaxWidth = H263_MAX_WIDTH;
+  size_t mMaxHeight = H263_MAX_HEIGHT;
+#endif
+  uint32_t mNumSamplesOutput = 0;
+  uint32_t mWidth = DEFAULT_WIDTH;
+  uint32_t mHeight = DEFAULT_HEIGHT;
+};
+
+bool Codec::initDecoder() {
+  mDecHandle = new tagvideoDecControls;
+  if (!mDecHandle) {
+    return false;
+  }
+  memset(mDecHandle, 0, sizeof(tagvideoDecControls));
+  return true;
+}
+
+bool Codec::allocOutputBuffer(size_t outputBufferSize) {
+  for (uint8_t i = 0; i < kNumOutputBuffers; ++i) {
+    if (!mOutputBuffer[i]) {
+      mOutputBuffer[i] = static_cast<uint8_t *>(malloc(outputBufferSize));
+      if (!mOutputBuffer[i]) {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+void Codec::freeOutputBuffer() {
+  for (uint8_t i = 0; i < kNumOutputBuffers; ++i) {
+    if (mOutputBuffer[i]) {
+      free(mOutputBuffer[i]);
+      mOutputBuffer[i] = nullptr;
+    }
+  }
+}
+
+void Codec::handleResolutionChange() {
+  int32_t dispWidth, dispHeight;
+  PVGetVideoDimensions(mDecHandle, &dispWidth, &dispHeight);
+
+  int32_t bufWidth, bufHeight;
+  PVGetBufferDimensions(mDecHandle, &bufWidth, &bufHeight);
+
+  if (dispWidth != mWidth || dispHeight != mHeight) {
+    mWidth = dispWidth;
+    mHeight = dispHeight;
+  }
+}
+
+void Codec::decodeFrames(const uint8_t *data, size_t size) {
+  size_t outputBufferSize = align(mMaxWidth, 16) * align(mMaxHeight, 16) * 3 / 2;
+  uint8_t *start_code = const_cast<uint8_t *>(data);
+  static const uint8_t volInfo[] = {0x00, 0x00, 0x01, 0xB0};
+  bool volHeader = memcmp(start_code, volInfo, 4) == 0;
+  if (volHeader) {
+    PVCleanUpVideoDecoder(mDecHandle);
+    mInitialized = false;
+  }
+
+  if (!mInitialized) {
+    uint8_t *volData[1]{};
+    int32_t volSize = 0;
+
+    if (volHeader) { /* removed some codec config part */
+      volData[0] = const_cast<uint8_t *>(data);
+      volSize = size;
+    }
+
+    if (!PVInitVideoDecoder(mDecHandle, volData, &volSize, kLayer, mMaxWidth, mMaxHeight,
+                            mInputMode)) {
+      return;
+    }
+    mInitialized = true;
+    MP4DecodingMode actualMode = PVGetDecBitstreamMode(mDecHandle);
+    if (mInputMode != actualMode) {
+      return;
+    }
+
+    PVSetPostProcType(mDecHandle, 0);
+  }
+  size_t yFrameSize = sizeof(uint8) * mDecHandle->size;
+  if (outputBufferSize < yFrameSize * 3 / 2) {
+    return;
+  }
+  if (!allocOutputBuffer(outputBufferSize)) {
+    return;
+  }
+  size_t numDecodeCalls = 0;
+  while ((size > 0) && (numDecodeCalls < kMaxNumDecodeCalls)) {
+    if (!mFramesConfigured) {
+      PVSetReferenceYUV(mDecHandle, mOutputBuffer[1]);
+      mFramesConfigured = true;
+    }
+
+    // Need to check if header contains new info, e.g., width/height, etc.
+    VopHeaderInfo header_info;
+    uint32_t useExtTimestamp = (numDecodeCalls == 0);
+    int32_t tempSize = (int32_t)size;
+    uint8_t *bitstreamTmp = const_cast<uint8_t *>(data);
+    uint32_t timestamp = 0;
+    if (PVDecodeVopHeader(mDecHandle, &bitstreamTmp, &timestamp, &tempSize, &header_info,
+                          &useExtTimestamp, mOutputBuffer[mNumSamplesOutput & 1]) != PV_TRUE) {
+      return;
+    }
+
+    handleResolutionChange();
+
+    PVDecodeVopBody(mDecHandle, &tempSize);
+    uint32_t bytesConsumed = 1;
+    if (size > tempSize) {
+      bytesConsumed = size - tempSize;
+    }
+    data += bytesConsumed;
+    size -= bytesConsumed;
+    ++mNumSamplesOutput;
+    ++numDecodeCalls;
+  }
+  freeOutputBuffer();
+}
+
+void Codec::deInitDecoder() {
+  PVCleanUpVideoDecoder(mDecHandle);
+  delete mDecHandle;
+  mDecHandle = nullptr;
+  mInitialized = false;
+  freeOutputBuffer();
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+  if (size < 4) {
+    return 0;
+  }
+  Codec *codec = new Codec();
+  if (!codec) {
+    return 0;
+  }
+  if (codec->initDecoder()) {
+    codec->decodeFrames(data, size);
+  }
+  delete codec;
+  return 0;
+}
diff --git a/media/codecs/m4v_h263/fuzzer/mpeg4_h263_enc_fuzzer.cpp b/media/codecs/m4v_h263/fuzzer/mpeg4_h263_enc_fuzzer.cpp
new file mode 100644
index 0000000..423325d
--- /dev/null
+++ b/media/codecs/m4v_h263/fuzzer/mpeg4_h263_enc_fuzzer.cpp
@@ -0,0 +1,192 @@
+/*
+ * Copyright (C) 2020 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 <algorithm>
+#include "mp4enc_api.h"
+
+constexpr int8_t kIDRFrameRefreshIntervalInSec = 1;
+constexpr MP4RateControlType krcType[] = {CONSTANT_Q, CBR_1, VBR_1, CBR_2, VBR_2, CBR_LOWDELAY};
+#ifdef MPEG4
+constexpr MP4EncodingMode kEncodingMode[] = {SHORT_HEADER, SHORT_HEADER_WITH_ERR_RES,
+                                             DATA_PARTITIONING_MODE, COMBINE_MODE_NO_ERR_RES,
+                                             COMBINE_MODE_WITH_ERR_RES};
+constexpr size_t kMaxWidth = 10240;
+constexpr size_t kMaxHeight = 10240;
+#else
+constexpr MP4EncodingMode kEncodingMode[] = {H263_MODE, H263_MODE_WITH_ERR_RES};
+constexpr int kWidth[] = {128, 176, 352, 704, 1408};
+constexpr int kHeight[] = {96, 144, 288, 576, 1152};
+constexpr size_t kWidthNum = std::size(kWidth);
+constexpr size_t kHeightNum = std::size(kHeight);
+#endif
+
+constexpr size_t krcTypeNum = std::size(krcType);
+constexpr size_t kEncodingModeNum = std::size(kEncodingMode);
+constexpr size_t kMaxQP = 51;
+
+enum {
+    IDX_WD_BYTE_1,
+    IDX_WD_BYTE_2,
+    IDX_HT_BYTE_1,
+    IDX_HT_BYTE_2,
+    IDX_FRAME_RATE,
+    IDX_RC_TYPE,
+    IDX_PACKET_SIZE,
+    IDX_I_FRAME_QP,
+    IDX_P_FRAME_QP,
+    IDX_ENABLE_RVLC,
+    IDX_QUANT_TYPE,
+    IDX_NO_FRAME_SKIPPED_FLAG,
+    IDX_ENABLE_SCENE_DETECT,
+    IDX_NUM_INTRA_MB,
+    IDX_SEARCH_RANGE,
+    IDX_ENABLE_MV_8x8,
+    IDX_USE_AC_PRED,
+    IDX_INTRA_DC_VLC_THRESHOLD,
+    IDX_ENC_MODE,
+    IDX_LAST
+};
+
+class Codec {
+   public:
+    Codec() = default;
+    ~Codec() { deInitEncoder(); }
+    bool initEncoder(const uint8_t *data);
+    void encodeFrames(const uint8_t *data, size_t size);
+    void deInitEncoder();
+
+   private:
+    int32_t mFrameWidth = 352;
+    int32_t mFrameHeight = 288;
+    float mFrameRate = 25.0f;
+    VideoEncOptions *mEncodeHandle = nullptr;
+    VideoEncControls *mEncodeControl = nullptr;
+};
+
+bool Codec::initEncoder(const uint8_t *data) {
+    mEncodeHandle = new VideoEncOptions;
+    if (!mEncodeHandle) {
+        return false;
+    }
+    memset(mEncodeHandle, 0, sizeof(VideoEncOptions));
+    mEncodeControl = new VideoEncControls;
+    if (!mEncodeControl) {
+        return false;
+    }
+    memset(mEncodeControl, 0, sizeof(VideoEncControls));
+    PVGetDefaultEncOption(mEncodeHandle, 0);
+
+#ifdef MPEG4
+    mFrameWidth = ((data[IDX_WD_BYTE_1] << 8) | data[IDX_WD_BYTE_2]) % kMaxWidth;
+    mFrameHeight = ((data[IDX_HT_BYTE_1] << 8) | data[IDX_HT_BYTE_2]) % kMaxHeight;
+#else
+    mFrameWidth = kWidth[data[IDX_WD_BYTE_1] % kWidthNum];
+    mFrameHeight = kHeight[data[IDX_HT_BYTE_1] % kHeightNum];
+#endif
+    mFrameRate = data[IDX_FRAME_RATE];
+    mEncodeHandle->rcType = krcType[data[IDX_RC_TYPE] % krcTypeNum];
+    mEncodeHandle->profile_level = CORE_PROFILE_LEVEL2;
+    mEncodeHandle->packetSize = data[IDX_PACKET_SIZE];
+    mEncodeHandle->iQuant[0] = (data[IDX_I_FRAME_QP] % kMaxQP) + 1;
+    mEncodeHandle->pQuant[0] = (data[IDX_P_FRAME_QP] % kMaxQP) + 1;
+    mEncodeHandle->rvlcEnable = (data[IDX_ENABLE_RVLC] & 0x01) ? PV_OFF : PV_ON;
+    mEncodeHandle->quantType[0] = (data[IDX_QUANT_TYPE] & 0x01) ? 0 : 1;
+    mEncodeHandle->noFrameSkipped = (data[IDX_NO_FRAME_SKIPPED_FLAG] & 0x01) ? PV_OFF : PV_ON;
+    mEncodeHandle->sceneDetect = (data[IDX_ENABLE_SCENE_DETECT] & 0x01) ? PV_OFF : PV_ON;
+    mEncodeHandle->numIntraMB = data[IDX_NUM_INTRA_MB] & 0x07;
+    mEncodeHandle->searchRange = data[IDX_SEARCH_RANGE] & 0x1F;
+    mEncodeHandle->mv8x8Enable = (data[IDX_ENABLE_MV_8x8] & 0x01) ? PV_OFF : PV_ON;
+    mEncodeHandle->useACPred = (data[IDX_USE_AC_PRED] & 0x01) ? PV_OFF : PV_ON;
+    mEncodeHandle->intraDCVlcTh = data[IDX_INTRA_DC_VLC_THRESHOLD] & 0x07;
+    mEncodeHandle->encMode = kEncodingMode[data[IDX_ENC_MODE] % kEncodingModeNum];
+    mEncodeHandle->encWidth[0] = mFrameWidth;
+    mEncodeHandle->encHeight[0] = mFrameHeight;
+    mEncodeHandle->encFrameRate[0] = mFrameRate;
+    mEncodeHandle->tickPerSrc = mEncodeHandle->timeIncRes / mFrameRate;
+    mEncodeHandle->intraPeriod = (kIDRFrameRefreshIntervalInSec * mFrameRate);
+    if (!PVInitVideoEncoder(mEncodeControl, mEncodeHandle)) {
+        return false;
+    }
+    return true;
+}
+
+void Codec::deInitEncoder() {
+    if (mEncodeControl) {
+        PVCleanUpVideoEncoder(mEncodeControl);
+        delete mEncodeControl;
+        mEncodeControl = nullptr;
+    }
+    if (mEncodeHandle) {
+        delete mEncodeHandle;
+        mEncodeHandle = nullptr;
+    }
+}
+
+void Codec::encodeFrames(const uint8_t *data, size_t size) {
+    size_t inputBufferSize = (mFrameWidth * mFrameHeight * 3) / 2;
+    size_t outputBufferSize = inputBufferSize * 2;
+    uint8_t *outputBuffer = new uint8_t[outputBufferSize];
+    uint8_t *inputBuffer = new uint8_t[inputBufferSize];
+
+    // Get VOL header.
+    int32_t sizeOutputBuffer = outputBufferSize;
+    PVGetVolHeader(mEncodeControl, outputBuffer, &sizeOutputBuffer, 0);
+
+    size_t numFrame = 0;
+    while (size > 0) {
+        size_t bytesConsumed = std::min(size, inputBufferSize);
+        memcpy(inputBuffer, data, bytesConsumed);
+        if (bytesConsumed < inputBufferSize) {
+            memset(inputBuffer + bytesConsumed, data[0], inputBufferSize - bytesConsumed);
+        }
+        VideoEncFrameIO videoIn{}, videoOut{};
+        videoIn.height = mFrameHeight;
+        videoIn.pitch = mFrameWidth;
+        videoIn.timestamp = (numFrame * 1000) / mFrameRate;
+        videoIn.yChan = inputBuffer;
+        videoIn.uChan = videoIn.yChan + videoIn.height * videoIn.pitch;
+        videoIn.vChan = videoIn.uChan + ((videoIn.height * videoIn.pitch) >> 2);
+        uint32_t modTimeMs = 0;
+        int32_t dataLength = outputBufferSize;
+        int32_t nLayer = 0;
+        PVEncodeVideoFrame(mEncodeControl, &videoIn, &videoOut, &modTimeMs, outputBuffer,
+                           &dataLength, &nLayer);
+        MP4HintTrack hintTrack;
+        PVGetHintTrack(mEncodeControl, &hintTrack);
+        PVGetOverrunBuffer(mEncodeControl);
+        ++numFrame;
+        data += bytesConsumed;
+        size -= bytesConsumed;
+    }
+    delete[] inputBuffer;
+    delete[] outputBuffer;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    if (size < IDX_LAST) {
+        return 0;
+    }
+    Codec *codec = new Codec();
+    if (!codec) {
+        return 0;
+    }
+    if (codec->initEncoder(data)) {
+        data += IDX_LAST;
+        size -= IDX_LAST;
+        codec->encodeFrames(data, size);
+    }
+    delete codec;
+    return 0;
+}
diff --git a/media/libstagefright/codecs/m4v_h263/patent_disclaimer.txt b/media/codecs/m4v_h263/patent_disclaimer.txt
similarity index 100%
rename from media/libstagefright/codecs/m4v_h263/patent_disclaimer.txt
rename to media/codecs/m4v_h263/patent_disclaimer.txt
diff --git a/media/codecs/mp3dec/Android.bp b/media/codecs/mp3dec/Android.bp
new file mode 100644
index 0000000..015b8b6
--- /dev/null
+++ b/media/codecs/mp3dec/Android.bp
@@ -0,0 +1,158 @@
+package {
+    default_applicable_licenses: ["frameworks_av_media_codecs_mp3dec_license"],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_codecs_mp3dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-BSD",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library_headers {
+    name: "libstagefright_mp3dec_headers",
+    vendor_available: true,
+    min_sdk_version: "29",
+    host_supported:true,
+    export_include_dirs: [
+        "include",
+        "src",
+    ],
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.media.swcodec",
+    ],
+}
+
+cc_library_static {
+    name: "libstagefright_mp3dec",
+    vendor_available: true,
+    min_sdk_version: "29",
+
+    host_supported:true,
+    srcs: [
+        "src/pvmp3_normalize.cpp",
+        "src/pvmp3_alias_reduction.cpp",
+        "src/pvmp3_crc.cpp",
+        "src/pvmp3_decode_header.cpp",
+        "src/pvmp3_decode_huff_cw.cpp",
+        "src/pvmp3_getbits.cpp",
+        "src/pvmp3_dequantize_sample.cpp",
+        "src/pvmp3_framedecoder.cpp",
+        "src/pvmp3_get_main_data_size.cpp",
+        "src/pvmp3_get_side_info.cpp",
+        "src/pvmp3_get_scale_factors.cpp",
+        "src/pvmp3_mpeg2_get_scale_data.cpp",
+        "src/pvmp3_mpeg2_get_scale_factors.cpp",
+        "src/pvmp3_mpeg2_stereo_proc.cpp",
+        "src/pvmp3_huffman_decoding.cpp",
+        "src/pvmp3_huffman_parsing.cpp",
+        "src/pvmp3_tables.cpp",
+        "src/pvmp3_imdct_synth.cpp",
+        "src/pvmp3_mdct_6.cpp",
+        "src/pvmp3_dct_6.cpp",
+        "src/pvmp3_poly_phase_synthesis.cpp",
+        "src/pvmp3_equalizer.cpp",
+        "src/pvmp3_seek_synch.cpp",
+        "src/pvmp3_stereo_proc.cpp",
+        "src/pvmp3_reorder.cpp",
+
+        "src/pvmp3_polyphase_filter_window.cpp",
+        "src/pvmp3_mdct_18.cpp",
+        "src/pvmp3_dct_9.cpp",
+        "src/pvmp3_dct_16.cpp",
+    ],
+
+    arch: {
+        arm: {
+            exclude_srcs: [
+                "src/pvmp3_polyphase_filter_window.cpp",
+                "src/pvmp3_mdct_18.cpp",
+                "src/pvmp3_dct_9.cpp",
+                "src/pvmp3_dct_16.cpp",
+            ],
+            srcs: [
+                "src/asm/pvmp3_polyphase_filter_window_gcc.s",
+                "src/asm/pvmp3_mdct_18_gcc.s",
+                "src/asm/pvmp3_dct_9_gcc.s",
+                "src/asm/pvmp3_dct_16_gcc.s",
+            ],
+
+            instruction_set: "arm",
+        },
+    },
+
+    sanitize: {
+        misc_undefined: [
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+    },
+
+    include_dirs: ["frameworks/av/media/libstagefright/include"],
+
+    header_libs: ["libstagefright_mp3dec_headers"],
+    export_header_lib_headers: ["libstagefright_mp3dec_headers"],
+
+    cflags: [
+        "-DOSCL_UNUSED_ARG(x)=(void)(x)",
+        "-Werror",
+    ],
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+}
+
+//###############################################################################
+cc_test {
+    name: "libstagefright_mp3dec_test",
+    gtest: false,
+
+    srcs: [
+        "test/mp3dec_test.cpp",
+        "test/mp3reader.cpp",
+    ],
+
+    cflags: ["-Wall", "-Werror"],
+
+    local_include_dirs: [
+        "src",
+        "include",
+    ],
+
+    sanitize: {
+        misc_undefined: [
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+    },
+
+    static_libs: [
+        "libstagefright_mp3dec",
+        "libsndfile",
+    ],
+
+    shared_libs: ["libaudioutils"],
+}
diff --git a/media/libstagefright/codecs/mp3dec/MODULE_LICENSE_APACHE2 b/media/codecs/mp3dec/MODULE_LICENSE_APACHE2
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/MODULE_LICENSE_APACHE2
rename to media/codecs/mp3dec/MODULE_LICENSE_APACHE2
diff --git a/media/libstagefright/codecs/mp3dec/NOTICE b/media/codecs/mp3dec/NOTICE
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/NOTICE
rename to media/codecs/mp3dec/NOTICE
diff --git a/media/codecs/mp3dec/TEST_MAPPING b/media/codecs/mp3dec/TEST_MAPPING
new file mode 100644
index 0000000..4ef4317
--- /dev/null
+++ b/media/codecs/mp3dec/TEST_MAPPING
@@ -0,0 +1,9 @@
+// mappings for frameworks/av/media/libstagefright/codecs/mp3dec
+{
+  // tests which require dynamic content
+  // invoke with: atest -- --enable-module-dynamic-download=true
+  // TODO(b/148094059): unit tests not allowed to download content
+  "dynamic-presubmit": [
+    { "name": "Mp3DecoderTest"}
+  ]
+}
diff --git a/media/libstagefright/codecs/amrnb/fuzzer/Android.bp b/media/codecs/mp3dec/fuzzer/Android.bp
similarity index 61%
copy from media/libstagefright/codecs/amrnb/fuzzer/Android.bp
copy to media/codecs/mp3dec/fuzzer/Android.bp
index 54de1cc..514a8a8 100644
--- a/media/libstagefright/codecs/amrnb/fuzzer/Android.bp
+++ b/media/codecs/mp3dec/fuzzer/Android.bp
@@ -18,20 +18,31 @@
  * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_mp3dec_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_codecs_mp3dec_license"],
+}
+
 cc_fuzz {
-    name: "amrnb_dec_fuzzer",
+    name: "mp3_dec_fuzzer",
     host_supported: true,
-    srcs: [
-        "amrnb_dec_fuzzer.cpp",
-    ],
+
     static_libs: [
-        "libstagefright_amrnbdec",
-        "libstagefright_amrnb_common",
-        "liblog",
+        "libstagefright_mp3dec",
     ],
-    target: {
-        darwin: {
-            enabled: false,
-        },
+
+    srcs: [
+        "mp3_dec_fuzzer.cpp",
+    ],
+
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
     },
 }
diff --git a/media/codecs/mp3dec/fuzzer/README.md b/media/codecs/mp3dec/fuzzer/README.md
new file mode 100644
index 0000000..09dd5c3
--- /dev/null
+++ b/media/codecs/mp3dec/fuzzer/README.md
@@ -0,0 +1,56 @@
+# Fuzzer for libstagefright_mp3dec decoder
+
+## Plugin Design Considerations
+The fuzzer plugin for mp3 decoder is designed based on the understanding of the
+codec and tries to achieve the following:
+
+##### Maximize code coverage
+
+This fuzzer makes use of the following config parameters:
+1. Equalizer type (parameter name: `equalizerType`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `equalizerType` | 0. `flat ` 1. `bass_boost ` 2. `rock ` 3. `pop ` 4. `jazz ` 5. `classical ` 6. `talk ` 7. `flat_ ` | Bits 0, 1 and 2 of first byte of input stream |
+| `crcEnabled` | 0. `false ` 1. `true `| Bit 0 of second byte of input stream |
+
+##### Maximize utilization of input data
+The plugin feeds the entire input data to the codec using a loop.
+ * If the decode operation was successful, the input is advanced by the number
+   of bytes used by the decoder.
+ * If the decode operation was un-successful, the input is advanced by 1 byte
+   till it reaches a valid frame or end of stream.
+
+This ensures that the plugin tolerates any kind of input (empty, huge,
+malformed, etc) and doesnt `exit()` on any input and thereby increasing the
+chance of identifying vulnerabilities.
+
+## Build
+
+This describes steps to build mp3_dec_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mp3_dec_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some mp3 files to that folder.
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/mp3_dec_fuzzer/mp3_dec_fuzzer CORPUS_DIR
+```
+To run on host
+```
+  $ $ANDROID_HOST_OUT/fuzz/x86_64/mp3_dec_fuzzer/mp3_dec_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/media/codecs/mp3dec/fuzzer/mp3_dec_fuzzer.cpp b/media/codecs/mp3dec/fuzzer/mp3_dec_fuzzer.cpp
new file mode 100644
index 0000000..847c8c4
--- /dev/null
+++ b/media/codecs/mp3dec/fuzzer/mp3_dec_fuzzer.cpp
@@ -0,0 +1,237 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include <stdlib.h>
+#include <algorithm>
+
+#include <pvmp3decoder_api.h>
+
+constexpr int kMaxFrameSamples = 4608;
+constexpr int kMaxChannels = 2;
+constexpr e_equalization kEqualizerTypes[] = {flat, bass_boost, rock, pop,
+                                              jazz, classical,  talk, flat_};
+
+static bool parseMp3Header(uint32_t header, size_t *frame_size,
+                           uint32_t *out_sampling_rate = nullptr, uint32_t *out_channels = nullptr,
+                           uint32_t *out_bitrate = nullptr, uint32_t *out_num_samples = nullptr) {
+  *frame_size = 0;
+  if (out_sampling_rate) *out_sampling_rate = 0;
+  if (out_channels) *out_channels = 0;
+  if (out_bitrate) *out_bitrate = 0;
+  if (out_num_samples) *out_num_samples = 0;
+
+  if ((header & 0xffe00000) != 0xffe00000) {
+    return false;
+  }
+  unsigned version = (header >> 19) & 3;
+  if (version == 0x01) {
+    return false;
+  }
+  unsigned layer = (header >> 17) & 3;
+  if (layer == 0x00) {
+    return false;
+  }
+  unsigned bitrate_index = (header >> 12) & 0x0f;
+  if (bitrate_index == 0 || bitrate_index == 0x0f) {
+    return false;
+  }
+  unsigned sampling_rate_index = (header >> 10) & 3;
+  if (sampling_rate_index == 3) {
+    return false;
+  }
+  static const int kSamplingRateV1[] = {44100, 48000, 32000};
+  int sampling_rate = kSamplingRateV1[sampling_rate_index];
+  if (version == 2 /* V2 */) {
+    sampling_rate /= 2;
+  } else if (version == 0 /* V2.5 */) {
+    sampling_rate /= 4;
+  }
+
+  unsigned padding = (header >> 9) & 1;
+
+  if (layer == 3) {  // layer I
+    static const int kBitrateV1[] = {32,  64,  96,  128, 160, 192, 224,
+                                     256, 288, 320, 352, 384, 416, 448};
+    static const int kBitrateV2[] = {32,  48,  56,  64,  80,  96,  112,
+                                     128, 144, 160, 176, 192, 224, 256};
+
+    int bitrate =
+        (version == 3 /* V1 */) ? kBitrateV1[bitrate_index - 1] : kBitrateV2[bitrate_index - 1];
+
+    if (out_bitrate) {
+      *out_bitrate = bitrate;
+    }
+    *frame_size = (12000 * bitrate / sampling_rate + padding) * 4;
+    if (out_num_samples) {
+      *out_num_samples = 384;
+    }
+  } else {  // layer II or III
+    static const int kBitrateV1L2[] = {32,  48,  56,  64,  80,  96,  112,
+                                       128, 160, 192, 224, 256, 320, 384};
+    static const int kBitrateV1L3[] = {32,  40,  48,  56,  64,  80,  96,
+                                       112, 128, 160, 192, 224, 256, 320};
+    static const int kBitrateV2[] = {8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160};
+    int bitrate;
+    if (version == 3 /* V1 */) {
+      bitrate =
+          (layer == 2 /* L2 */) ? kBitrateV1L2[bitrate_index - 1] : kBitrateV1L3[bitrate_index - 1];
+
+      if (out_num_samples) {
+        *out_num_samples = 1152;
+      }
+    } else {  // V2 (or 2.5)
+      bitrate = kBitrateV2[bitrate_index - 1];
+      if (out_num_samples) {
+        *out_num_samples = (layer == 1 /* L3 */) ? 576 : 1152;
+      }
+    }
+
+    if (out_bitrate) {
+      *out_bitrate = bitrate;
+    }
+
+    if (version == 3 /* V1 */) {
+      *frame_size = 144000 * bitrate / sampling_rate + padding;
+    } else {  // V2 or V2.5
+      size_t tmp = (layer == 1 /* L3 */) ? 72000 : 144000;
+      *frame_size = tmp * bitrate / sampling_rate + padding;
+    }
+  }
+
+  if (out_sampling_rate) {
+    *out_sampling_rate = sampling_rate;
+  }
+
+  if (out_channels) {
+    int channel_mode = (header >> 6) & 3;
+    *out_channels = (channel_mode == 3) ? 1 : 2;
+  }
+
+  return true;
+}
+
+static uint32_t U32_AT(const uint8_t *ptr) {
+  return ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
+}
+
+static bool checkHeader(uint8 *header, size_t inSize) {
+  size_t frameSize;
+  size_t totalInSize = 0;
+  bool isValidBuffer = false;
+
+  while (totalInSize + 4 < inSize) {
+    isValidBuffer = true;
+    uint32_t val = U32_AT(header + totalInSize);
+    if (!parseMp3Header(val, &frameSize, nullptr, nullptr, nullptr, nullptr)) {
+      return false;
+    }
+    totalInSize += frameSize;
+  }
+
+  return (isValidBuffer);
+}
+
+class Codec {
+ public:
+  Codec() = default;
+  ~Codec() { deInitDecoder(); }
+
+  bool initDecoder();
+  void decodeFrames(uint8_t *data, size_t size);
+  void deInitDecoder();
+
+ private:
+  tPVMP3DecoderExternal *mConfig = nullptr;
+  void *mDecoderBuf = nullptr;
+};
+
+bool Codec::initDecoder() {
+  mConfig = new tPVMP3DecoderExternal{};
+  if (!mConfig) {
+    return false;
+  }
+  size_t decoderBufSize = pvmp3_decoderMemRequirements();
+  mDecoderBuf = malloc(decoderBufSize);
+  if (!mDecoderBuf) {
+    return false;
+  }
+  memset(mDecoderBuf, 0x0, decoderBufSize);
+  pvmp3_InitDecoder(mConfig, mDecoderBuf);
+  return true;
+}
+
+void Codec::decodeFrames(uint8_t *data, size_t size) {
+  uint8_t equalizerTypeValue = (data[0] & 0x7);
+  mConfig->equalizerType = kEqualizerTypes[equalizerTypeValue];
+  mConfig->crcEnabled = data[1] & 0x1;
+
+  while (size > 0) {
+    bool status = checkHeader(data, size);
+    if (!status) {
+      size--;
+      data++;
+      continue;
+    }
+    size_t outBufSize = kMaxFrameSamples * kMaxChannels;
+    size_t usedBytes = 0;
+    int16_t outputBuf[outBufSize];
+    mConfig->inputBufferCurrentLength = size;
+    mConfig->inputBufferUsedLength = 0;
+    mConfig->inputBufferMaxLength = 0;
+    mConfig->pInputBuffer = data;
+    mConfig->pOutputBuffer = outputBuf;
+    mConfig->outputFrameSize = outBufSize / sizeof(int16_t);
+
+    ERROR_CODE decoderErr;
+    decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf);
+    if (decoderErr != NO_DECODING_ERROR) {
+      size--;
+      data++;
+    } else {
+      usedBytes = std::min((int32_t)size, mConfig->inputBufferUsedLength);
+      size -= usedBytes;
+      data += usedBytes;
+    }
+  }
+}
+
+void Codec::deInitDecoder() {
+  if (mDecoderBuf) {
+    free(mDecoderBuf);
+    mDecoderBuf = nullptr;
+  }
+  delete mConfig;
+  mConfig = nullptr;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+  if (size < 4) {
+    return 0;
+  }
+  Codec *codec = new Codec();
+  if (!codec) {
+    return 0;
+  }
+  if (codec->initDecoder()) {
+    codec->decodeFrames(const_cast<uint8_t *>(data), size);
+  }
+  delete codec;
+  return 0;
+}
diff --git a/media/libstagefright/codecs/mp3dec/include/mp3_decoder_selection.h b/media/codecs/mp3dec/include/mp3_decoder_selection.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/include/mp3_decoder_selection.h
rename to media/codecs/mp3dec/include/mp3_decoder_selection.h
diff --git a/media/libstagefright/codecs/mp3dec/include/pvmp3_audio_type_defs.h b/media/codecs/mp3dec/include/pvmp3_audio_type_defs.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/include/pvmp3_audio_type_defs.h
rename to media/codecs/mp3dec/include/pvmp3_audio_type_defs.h
diff --git a/media/libstagefright/codecs/mp3dec/include/pvmp3decoder_api.h b/media/codecs/mp3dec/include/pvmp3decoder_api.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/include/pvmp3decoder_api.h
rename to media/codecs/mp3dec/include/pvmp3decoder_api.h
diff --git a/media/libstagefright/codecs/mp3dec/patent_disclaimer.txt b/media/codecs/mp3dec/patent_disclaimer.txt
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/patent_disclaimer.txt
rename to media/codecs/mp3dec/patent_disclaimer.txt
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_16_gcc.s b/media/codecs/mp3dec/src/asm/pvmp3_dct_16_gcc.s
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_16_gcc.s
rename to media/codecs/mp3dec/src/asm/pvmp3_dct_16_gcc.s
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_9_gcc.s b/media/codecs/mp3dec/src/asm/pvmp3_dct_9_gcc.s
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_9_gcc.s
rename to media/codecs/mp3dec/src/asm/pvmp3_dct_9_gcc.s
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_gcc.s b/media/codecs/mp3dec/src/asm/pvmp3_mdct_18_gcc.s
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_gcc.s
rename to media/codecs/mp3dec/src/asm/pvmp3_mdct_18_gcc.s
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_gcc.s b/media/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_gcc.s
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_gcc.s
rename to media/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_gcc.s
diff --git a/media/libstagefright/codecs/mp3dec/src/mp3_mem_funcs.h b/media/codecs/mp3dec/src/mp3_mem_funcs.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/mp3_mem_funcs.h
rename to media/codecs/mp3dec/src/mp3_mem_funcs.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3_huffman.h b/media/codecs/mp3dec/src/pv_mp3_huffman.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pv_mp3_huffman.h
rename to media/codecs/mp3dec/src/pv_mp3_huffman.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op.h b/media/codecs/mp3dec/src/pv_mp3dec_fxd_op.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op.h
rename to media/codecs/mp3dec/src/pv_mp3dec_fxd_op.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm.h b/media/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm.h
rename to media/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm_gcc.h b/media/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm_gcc.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm_gcc.h
rename to media/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm_gcc.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h b/media/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h
rename to media/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_msc_evc.h b/media/codecs/mp3dec/src/pv_mp3dec_fxd_op_msc_evc.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_msc_evc.h
rename to media/codecs/mp3dec/src/pv_mp3dec_fxd_op_msc_evc.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.cpp b/media/codecs/mp3dec/src/pvmp3_alias_reduction.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.cpp
rename to media/codecs/mp3dec/src/pvmp3_alias_reduction.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.h b/media/codecs/mp3dec/src/pvmp3_alias_reduction.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.h
rename to media/codecs/mp3dec/src/pvmp3_alias_reduction.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_crc.cpp b/media/codecs/mp3dec/src/pvmp3_crc.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_crc.cpp
rename to media/codecs/mp3dec/src/pvmp3_crc.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_crc.h b/media/codecs/mp3dec/src/pvmp3_crc.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_crc.h
rename to media/codecs/mp3dec/src/pvmp3_crc.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.cpp b/media/codecs/mp3dec/src/pvmp3_dct_16.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.cpp
rename to media/codecs/mp3dec/src/pvmp3_dct_16.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.h b/media/codecs/mp3dec/src/pvmp3_dct_16.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.h
rename to media/codecs/mp3dec/src/pvmp3_dct_16.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp b/media/codecs/mp3dec/src/pvmp3_dct_6.cpp
similarity index 98%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp
rename to media/codecs/mp3dec/src/pvmp3_dct_6.cpp
index 1f8018a..c306873 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp
+++ b/media/codecs/mp3dec/src/pvmp3_dct_6.cpp
@@ -111,6 +111,7 @@
 ; FUNCTION CODE
 ----------------------------------------------------------------------------*/
 
+__attribute__((no_sanitize("integer")))
 void pvmp3_dct_6(int32 vec[])
 {
 
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_9.cpp b/media/codecs/mp3dec/src/pvmp3_dct_9.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_dct_9.cpp
rename to media/codecs/mp3dec/src/pvmp3_dct_9.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dec_defs.h b/media/codecs/mp3dec/src/pvmp3_dec_defs.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_dec_defs.h
rename to media/codecs/mp3dec/src/pvmp3_dec_defs.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.cpp b/media/codecs/mp3dec/src/pvmp3_decode_header.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.cpp
rename to media/codecs/mp3dec/src/pvmp3_decode_header.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.h b/media/codecs/mp3dec/src/pvmp3_decode_header.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.h
rename to media/codecs/mp3dec/src/pvmp3_decode_header.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.cpp b/media/codecs/mp3dec/src/pvmp3_decode_huff_cw.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.cpp
rename to media/codecs/mp3dec/src/pvmp3_decode_huff_cw.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.h b/media/codecs/mp3dec/src/pvmp3_decode_huff_cw.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.h
rename to media/codecs/mp3dec/src/pvmp3_decode_huff_cw.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp b/media/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp
rename to media/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.h b/media/codecs/mp3dec/src/pvmp3_dequantize_sample.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.h
rename to media/codecs/mp3dec/src/pvmp3_dequantize_sample.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.cpp b/media/codecs/mp3dec/src/pvmp3_equalizer.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.cpp
rename to media/codecs/mp3dec/src/pvmp3_equalizer.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.h b/media/codecs/mp3dec/src/pvmp3_equalizer.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.h
rename to media/codecs/mp3dec/src/pvmp3_equalizer.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.cpp b/media/codecs/mp3dec/src/pvmp3_framedecoder.cpp
similarity index 99%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.cpp
rename to media/codecs/mp3dec/src/pvmp3_framedecoder.cpp
index 15d2feb..a5c7f5e 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.cpp
+++ b/media/codecs/mp3dec/src/pvmp3_framedecoder.cpp
@@ -219,11 +219,6 @@
 
     if (info->error_protection)
     {
-        if (!bitsAvailable(&pVars->inputStream, 16))
-        {
-            return SIDE_INFO_ERROR;
-        }
-
         /*
          *  Get crc content
          */
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.h b/media/codecs/mp3dec/src/pvmp3_framedecoder.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.h
rename to media/codecs/mp3dec/src/pvmp3_framedecoder.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.cpp b/media/codecs/mp3dec/src/pvmp3_get_main_data_size.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.cpp
rename to media/codecs/mp3dec/src/pvmp3_get_main_data_size.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.h b/media/codecs/mp3dec/src/pvmp3_get_main_data_size.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.h
rename to media/codecs/mp3dec/src/pvmp3_get_main_data_size.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp b/media/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp
rename to media/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.h b/media/codecs/mp3dec/src/pvmp3_get_scale_factors.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.h
rename to media/codecs/mp3dec/src/pvmp3_get_scale_factors.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.cpp b/media/codecs/mp3dec/src/pvmp3_get_side_info.cpp
similarity index 87%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.cpp
rename to media/codecs/mp3dec/src/pvmp3_get_side_info.cpp
index 1a3fca5..d644207 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.cpp
+++ b/media/codecs/mp3dec/src/pvmp3_get_side_info.cpp
@@ -73,7 +73,6 @@
 
 #include "pvmp3_get_side_info.h"
 #include "pvmp3_crc.h"
-#include "pvmp3_getbits.h"
 
 
 /*----------------------------------------------------------------------------
@@ -126,22 +125,12 @@
     {
         if (stereo == 1)
         {
-            if (!bitsAvailable(inputStream, 14))
-            {
-                return SIDE_INFO_ERROR;
-            }
-
             tmp = getbits_crc(inputStream, 14, crc, info->error_protection);
             si->main_data_begin = (tmp << 18) >> 23;    /* 9 */
             si->private_bits    = (tmp << 27) >> 27;    /* 5 */
         }
         else
         {
-            if (!bitsAvailable(inputStream, 12))
-            {
-                return SIDE_INFO_ERROR;
-            }
-
             tmp = getbits_crc(inputStream, 12, crc, info->error_protection);
             si->main_data_begin = (tmp << 20) >> 23;    /* 9 */
             si->private_bits    = (tmp << 29) >> 29;    /* 3 */
@@ -150,11 +139,6 @@
 
         for (ch = 0; ch < stereo; ch++)
         {
-            if (!bitsAvailable(inputStream, 4))
-            {
-                return SIDE_INFO_ERROR;
-            }
-
             tmp = getbits_crc(inputStream, 4, crc, info->error_protection);
             si->ch[ch].scfsi[0] = (tmp << 28) >> 31;    /* 1 */
             si->ch[ch].scfsi[1] = (tmp << 29) >> 31;    /* 1 */
@@ -166,11 +150,6 @@
         {
             for (ch = 0; ch < stereo; ch++)
             {
-                if (!bitsAvailable(inputStream, 34))
-                {
-                    return SIDE_INFO_ERROR;
-                }
-
                 si->ch[ch].gran[gr].part2_3_length    = getbits_crc(inputStream, 12, crc, info->error_protection);
                 tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
 
@@ -181,11 +160,6 @@
 
                 if (si->ch[ch].gran[gr].window_switching_flag)
                 {
-                    if (!bitsAvailable(inputStream, 22))
-                    {
-                        return SIDE_INFO_ERROR;
-                    }
-
                     tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
 
                     si->ch[ch].gran[gr].block_type       = (tmp << 10) >> 30;   /* 2 */;
@@ -218,11 +192,6 @@
                 }
                 else
                 {
-                    if (!bitsAvailable(inputStream, 22))
-                    {
-                        return SIDE_INFO_ERROR;
-                    }
-
                     tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
 
                     si->ch[ch].gran[gr].table_select[0] = (tmp << 10) >> 27;   /* 5 */;
@@ -235,11 +204,6 @@
                     si->ch[ch].gran[gr].block_type      = 0;
                 }
 
-                if (!bitsAvailable(inputStream, 3))
-                {
-                    return SIDE_INFO_ERROR;
-                }
-
                 tmp = getbits_crc(inputStream, 3, crc, info->error_protection);
                 si->ch[ch].gran[gr].preflag            = (tmp << 29) >> 31;    /* 1 */
                 si->ch[ch].gran[gr].scalefac_scale     = (tmp << 30) >> 31;    /* 1 */
@@ -249,21 +213,11 @@
     }
     else /* Layer 3 LSF */
     {
-        if (!bitsAvailable(inputStream, 8 + stereo))
-        {
-            return SIDE_INFO_ERROR;
-        }
-
         si->main_data_begin = getbits_crc(inputStream,      8, crc, info->error_protection);
         si->private_bits    = getbits_crc(inputStream, stereo, crc, info->error_protection);
 
         for (ch = 0; ch < stereo; ch++)
         {
-            if (!bitsAvailable(inputStream, 39))
-            {
-                return SIDE_INFO_ERROR;
-            }
-
             tmp = getbits_crc(inputStream, 21, crc, info->error_protection);
             si->ch[ch].gran[0].part2_3_length    = (tmp << 11) >> 20;  /* 12 */
             si->ch[ch].gran[0].big_values        = (tmp << 23) >> 23;  /*  9 */
@@ -276,11 +230,6 @@
             if (si->ch[ch].gran[0].window_switching_flag)
             {
 
-                if (!bitsAvailable(inputStream, 22))
-                {
-                    return SIDE_INFO_ERROR;
-                }
-
                 tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
 
                 si->ch[ch].gran[0].block_type       = (tmp << 10) >> 30;   /* 2 */;
@@ -313,11 +262,6 @@
             }
             else
             {
-                if (!bitsAvailable(inputStream, 22))
-                {
-                    return SIDE_INFO_ERROR;
-                }
-
                 tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
 
                 si->ch[ch].gran[0].table_select[0] = (tmp << 10) >> 27;   /* 5 */;
@@ -330,11 +274,6 @@
                 si->ch[ch].gran[0].block_type      = 0;
             }
 
-            if (!bitsAvailable(inputStream, 2))
-            {
-                return SIDE_INFO_ERROR;
-            }
-
             tmp = getbits_crc(inputStream, 2, crc, info->error_protection);
             si->ch[ch].gran[0].scalefac_scale     =  tmp >> 1;  /* 1 */
             si->ch[ch].gran[0].count1table_select =  tmp & 1;  /* 1 */
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.h b/media/codecs/mp3dec/src/pvmp3_get_side_info.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.h
rename to media/codecs/mp3dec/src/pvmp3_get_side_info.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.cpp b/media/codecs/mp3dec/src/pvmp3_getbits.cpp
similarity index 79%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.cpp
rename to media/codecs/mp3dec/src/pvmp3_getbits.cpp
index 4d252ef..8ff7953 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.cpp
+++ b/media/codecs/mp3dec/src/pvmp3_getbits.cpp
@@ -113,11 +113,10 @@
 
     uint32    offset;
     uint32    bitIndex;
-    uint32    bytesToFetch;
-    uint8     Elem  = 0;         /* Needs to be same type as pInput->pBuffer */
-    uint8     Elem1 = 0;
-    uint8     Elem2 = 0;
-    uint8     Elem3 = 0;
+    uint8     Elem;         /* Needs to be same type as pInput->pBuffer */
+    uint8     Elem1;
+    uint8     Elem2;
+    uint8     Elem3;
     uint32   returnValue = 0;
 
     if (!neededBits)
@@ -127,25 +126,10 @@
 
     offset = (ptBitStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
 
-    /* Remove extra high bits by shifting up */
-    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
-
-    bytesToFetch = (bitIndex + neededBits + 7 ) >> 3 ;
-
-    switch (bytesToFetch)
-    {
-    case 4:
-        Elem3 = *(ptBitStream->pBuffer + module(offset + 3, BUFSIZE));
-        [[fallthrough]];
-    case 3:
-        Elem2 = *(ptBitStream->pBuffer + module(offset + 2, BUFSIZE));
-        [[fallthrough]];
-    case 2:
-        Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
-        [[fallthrough]];
-    case 1:
-        Elem = *(ptBitStream->pBuffer + module(offset, BUFSIZE));
-    }
+    Elem  = *(ptBitStream->pBuffer + module(offset  , BUFSIZE));
+    Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
+    Elem2 = *(ptBitStream->pBuffer + module(offset + 2, BUFSIZE));
+    Elem3 = *(ptBitStream->pBuffer + module(offset + 3, BUFSIZE));
 
 
     returnValue = (((uint32)(Elem)) << 24) |
@@ -153,6 +137,9 @@
                   (((uint32)(Elem2)) << 8) |
                   ((uint32)(Elem3));
 
+    /* Remove extra high bits by shifting up */
+    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
+
     /* This line is faster than to mask off the high bits. */
     returnValue <<= bitIndex;
 
@@ -174,32 +161,22 @@
 
     uint32    offset;
     uint32    bitIndex;
-    uint32    bytesToFetch;
-    uint8    Elem  = 0;         /* Needs to be same type as pInput->pBuffer */
-    uint8    Elem1 = 0;
+    uint8    Elem;         /* Needs to be same type as pInput->pBuffer */
+    uint8    Elem1;
     uint16   returnValue;
 
     offset = (ptBitStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
 
-    /* Remove extra high bits by shifting up */
-    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
-
-    bytesToFetch = (bitIndex + neededBits + 7 ) >> 3 ;
-
-    if (bytesToFetch > 1)
-    {
-        Elem = *(ptBitStream->pBuffer + module(offset, BUFSIZE));
-        Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
-    }
-    else if (bytesToFetch > 0)
-    {
-        Elem = *(ptBitStream->pBuffer + module(offset, BUFSIZE));
-    }
+    Elem  = *(ptBitStream->pBuffer + module(offset  , BUFSIZE));
+    Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
 
 
     returnValue = (((uint16)(Elem)) << 8) |
                   ((uint16)(Elem1));
 
+    /* Remove extra high bits by shifting up */
+    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
+
     ptBitStream->usedBits += neededBits;
     /* This line is faster than to mask off the high bits. */
     returnValue = (returnValue << (bitIndex));
@@ -220,40 +197,25 @@
 
     uint32    offset;
     uint32    bitIndex;
-    uint32    bytesToFetch;
-    uint8     Elem  = 0;         /* Needs to be same type as pInput->pBuffer */
-    uint8     Elem1 = 0;
-    uint8     Elem2 = 0;
+    uint8     Elem;         /* Needs to be same type as pInput->pBuffer */
+    uint8     Elem1;
+    uint8     Elem2;
     uint32   returnValue;
 
     offset = (ptBitStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
 
-    /* Remove extra high bits by shifting up */
-    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
-
-    bytesToFetch = (bitIndex + neededBits + 7 ) >> 3 ;
-
-    if (bytesToFetch > 2)
-    {
-        Elem  = *(ptBitStream->pBuffer + module(offset, BUFSIZE));
-        Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
-        Elem2 = *(ptBitStream->pBuffer + module(offset + 2, BUFSIZE));
-    }
-    else if (bytesToFetch > 1)
-    {
-        Elem  = *(ptBitStream->pBuffer + module(offset, BUFSIZE));
-        Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
-    }
-    else if (bytesToFetch > 0)
-    {
-        Elem = *(ptBitStream->pBuffer + module(offset, BUFSIZE));
-    }
+    Elem  = *(ptBitStream->pBuffer + module(offset  , BUFSIZE));
+    Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
+    Elem2 = *(ptBitStream->pBuffer + module(offset + 2, BUFSIZE));
 
 
     returnValue = (((uint32)(Elem)) << 16) |
                   (((uint32)(Elem1)) << 8) |
                   ((uint32)(Elem2));
 
+    /* Remove extra high bits by shifting up */
+    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
+
     ptBitStream->usedBits += neededBits;
     /* This line is faster than to mask off the high bits. */
     returnValue = 0xFFFFFF & (returnValue << (bitIndex));
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.h b/media/codecs/mp3dec/src/pvmp3_getbits.h
similarity index 95%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.h
rename to media/codecs/mp3dec/src/pvmp3_getbits.h
index b04fe6d..b058b00 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.h
+++ b/media/codecs/mp3dec/src/pvmp3_getbits.h
@@ -104,11 +104,6 @@
 ; Function Prototype declaration
 ----------------------------------------------------------------------------*/
 
-static inline bool bitsAvailable(tmp3Bits *inputStream, uint32 neededBits)
-{
-    return (inputStream->inputBufferCurrentLength << 3) >= (neededBits + inputStream->usedBits);
-}
-
 /*----------------------------------------------------------------------------
 ; END
 ----------------------------------------------------------------------------*/
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_decoding.cpp b/media/codecs/mp3dec/src/pvmp3_huffman_decoding.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_decoding.cpp
rename to media/codecs/mp3dec/src/pvmp3_huffman_decoding.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_parsing.cpp b/media/codecs/mp3dec/src/pvmp3_huffman_parsing.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_parsing.cpp
rename to media/codecs/mp3dec/src/pvmp3_huffman_parsing.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.cpp b/media/codecs/mp3dec/src/pvmp3_imdct_synth.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.cpp
rename to media/codecs/mp3dec/src/pvmp3_imdct_synth.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.h b/media/codecs/mp3dec/src/pvmp3_imdct_synth.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.h
rename to media/codecs/mp3dec/src/pvmp3_imdct_synth.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.cpp b/media/codecs/mp3dec/src/pvmp3_mdct_18.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.cpp
rename to media/codecs/mp3dec/src/pvmp3_mdct_18.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.h b/media/codecs/mp3dec/src/pvmp3_mdct_18.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.h
rename to media/codecs/mp3dec/src/pvmp3_mdct_18.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp b/media/codecs/mp3dec/src/pvmp3_mdct_6.cpp
similarity index 98%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp
rename to media/codecs/mp3dec/src/pvmp3_mdct_6.cpp
index 8d80e8f..1ba080d 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp
+++ b/media/codecs/mp3dec/src/pvmp3_mdct_6.cpp
@@ -118,7 +118,7 @@
 ; FUNCTION CODE
 ----------------------------------------------------------------------------*/
 
-
+__attribute__((no_sanitize("integer")))
 void pvmp3_mdct_6(int32 vec[], int32 *history)
 {
     int32 i;
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.h b/media/codecs/mp3dec/src/pvmp3_mdct_6.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.h
rename to media/codecs/mp3dec/src/pvmp3_mdct_6.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp b/media/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp
rename to media/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.h b/media/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.h
rename to media/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.cpp b/media/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.cpp
rename to media/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.h b/media/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.h
rename to media/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp b/media/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp
rename to media/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.h b/media/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.h
rename to media/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.cpp b/media/codecs/mp3dec/src/pvmp3_normalize.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.cpp
rename to media/codecs/mp3dec/src/pvmp3_normalize.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.h b/media/codecs/mp3dec/src/pvmp3_normalize.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.h
rename to media/codecs/mp3dec/src/pvmp3_normalize.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.cpp b/media/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.cpp
rename to media/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.h b/media/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.h
rename to media/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.cpp b/media/codecs/mp3dec/src/pvmp3_polyphase_filter_window.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.cpp
rename to media/codecs/mp3dec/src/pvmp3_polyphase_filter_window.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.h b/media/codecs/mp3dec/src/pvmp3_polyphase_filter_window.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.h
rename to media/codecs/mp3dec/src/pvmp3_polyphase_filter_window.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.cpp b/media/codecs/mp3dec/src/pvmp3_reorder.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.cpp
rename to media/codecs/mp3dec/src/pvmp3_reorder.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.h b/media/codecs/mp3dec/src/pvmp3_reorder.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.h
rename to media/codecs/mp3dec/src/pvmp3_reorder.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.cpp b/media/codecs/mp3dec/src/pvmp3_seek_synch.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.cpp
rename to media/codecs/mp3dec/src/pvmp3_seek_synch.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.h b/media/codecs/mp3dec/src/pvmp3_seek_synch.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.h
rename to media/codecs/mp3dec/src/pvmp3_seek_synch.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.cpp b/media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.cpp
rename to media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.h b/media/codecs/mp3dec/src/pvmp3_stereo_proc.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.h
rename to media/codecs/mp3dec/src/pvmp3_stereo_proc.h
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.cpp b/media/codecs/mp3dec/src/pvmp3_tables.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_tables.cpp
rename to media/codecs/mp3dec/src/pvmp3_tables.cpp
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.h b/media/codecs/mp3dec/src/pvmp3_tables.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/pvmp3_tables.h
rename to media/codecs/mp3dec/src/pvmp3_tables.h
diff --git a/media/libstagefright/codecs/mp3dec/src/s_huffcodetab.h b/media/codecs/mp3dec/src/s_huffcodetab.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/s_huffcodetab.h
rename to media/codecs/mp3dec/src/s_huffcodetab.h
diff --git a/media/libstagefright/codecs/mp3dec/src/s_mp3bits.h b/media/codecs/mp3dec/src/s_mp3bits.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/s_mp3bits.h
rename to media/codecs/mp3dec/src/s_mp3bits.h
diff --git a/media/libstagefright/codecs/mp3dec/src/s_tmp3dec_chan.h b/media/codecs/mp3dec/src/s_tmp3dec_chan.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/s_tmp3dec_chan.h
rename to media/codecs/mp3dec/src/s_tmp3dec_chan.h
diff --git a/media/libstagefright/codecs/mp3dec/src/s_tmp3dec_file.h b/media/codecs/mp3dec/src/s_tmp3dec_file.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/src/s_tmp3dec_file.h
rename to media/codecs/mp3dec/src/s_tmp3dec_file.h
diff --git a/media/libstagefright/codecs/mp3dec/test/Android.bp b/media/codecs/mp3dec/test/Android.bp
similarity index 73%
rename from media/libstagefright/codecs/mp3dec/test/Android.bp
rename to media/codecs/mp3dec/test/Android.bp
index 0ff8b12..8003068 100644
--- a/media/libstagefright/codecs/mp3dec/test/Android.bp
+++ b/media/codecs/mp3dec/test/Android.bp
@@ -14,6 +14,16 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_codecs_mp3dec_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-BSD
+    default_applicable_licenses: ["frameworks_av_media_codecs_mp3dec_license"],
+}
+
 cc_test {
     name: "Mp3DecoderTest",
     gtest: true,
diff --git a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml b/media/codecs/mp3dec/test/AndroidTest.xml
similarity index 94%
rename from media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
rename to media/codecs/mp3dec/test/AndroidTest.xml
index 7ff9732..29952eb 100644
--- a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
+++ b/media/codecs/mp3dec/test/AndroidTest.xml
@@ -19,7 +19,7 @@
         <option name="cleanup" value="true" />
         <option name="push" value="Mp3DecoderTest->/data/local/tmp/Mp3DecoderTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest.zip?unzip=true"
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest-1.2.zip?unzip=true"
             value="/data/local/tmp/Mp3DecoderTestRes/" />
     </target_preparer>
 
diff --git a/media/libstagefright/codecs/mp3dec/test/Mp3DecoderTest.cpp b/media/codecs/mp3dec/test/Mp3DecoderTest.cpp
similarity index 97%
rename from media/libstagefright/codecs/mp3dec/test/Mp3DecoderTest.cpp
rename to media/codecs/mp3dec/test/Mp3DecoderTest.cpp
index 99553ec..91326a8 100644
--- a/media/libstagefright/codecs/mp3dec/test/Mp3DecoderTest.cpp
+++ b/media/codecs/mp3dec/test/Mp3DecoderTest.cpp
@@ -185,6 +185,8 @@
 INSTANTIATE_TEST_SUITE_P(Mp3DecoderTestAll, Mp3DecoderTest,
                          ::testing::Values(("bbb_44100hz_2ch_128kbps_mp3_30sec.mp3"),
                                            ("bbb_44100hz_2ch_128kbps_mp3_5mins.mp3"),
+                                           ("bug_136053885.mp3"),
+                                           ("bbb_2ch_44kHz_lame_crc.mp3"),
                                            ("bbb_mp3_stereo_192kbps_48000hz.mp3")));
 
 int main(int argc, char **argv) {
diff --git a/media/libstagefright/codecs/mp3dec/test/Mp3DecoderTestEnvironment.h b/media/codecs/mp3dec/test/Mp3DecoderTestEnvironment.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/test/Mp3DecoderTestEnvironment.h
rename to media/codecs/mp3dec/test/Mp3DecoderTestEnvironment.h
diff --git a/media/libstagefright/codecs/mp3dec/test/README.md b/media/codecs/mp3dec/test/README.md
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/test/README.md
rename to media/codecs/mp3dec/test/README.md
diff --git a/media/libstagefright/codecs/mp3dec/test/mp3dec_test.cpp b/media/codecs/mp3dec/test/mp3dec_test.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/test/mp3dec_test.cpp
rename to media/codecs/mp3dec/test/mp3dec_test.cpp
diff --git a/media/libstagefright/codecs/mp3dec/test/mp3reader.cpp b/media/codecs/mp3dec/test/mp3reader.cpp
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/test/mp3reader.cpp
rename to media/codecs/mp3dec/test/mp3reader.cpp
diff --git a/media/libstagefright/codecs/mp3dec/test/mp3reader.h b/media/codecs/mp3dec/test/mp3reader.h
similarity index 100%
rename from media/libstagefright/codecs/mp3dec/test/mp3reader.h
rename to media/codecs/mp3dec/test/mp3reader.h
diff --git a/media/extractors/Android.bp b/media/extractors/Android.bp
index 7c4e62f..7513cb1 100644
--- a/media/extractors/Android.bp
+++ b/media/extractors/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "extractor-defaults",
 
@@ -21,7 +30,6 @@
 
     shared_libs: [
         "liblog",
-        "libmediandk#29",
     ],
 
     // extractors are supposed to work on Q(29)
@@ -39,6 +47,21 @@
 
     version_script: "exports.lds",
 
+    target: {
+        android: {
+            shared_libs: [
+                "libmediandk#29",
+            ],
+        },
+        host: {
+            static_libs: [
+                "libutils",
+                "libmediandk_format",
+                "libmedia_ndkformatpriv",
+            ],
+        },
+    },
+
     sanitize: {
         cfi: true,
         misc_undefined: [
@@ -46,4 +69,4 @@
             "signed-integer-overflow",
         ],
     },
-}
\ No newline at end of file
+}
diff --git a/media/extractors/aac/Android.bp b/media/extractors/aac/Android.bp
index 60d3ae1..7bf3a13 100644
--- a/media/extractors/aac/Android.bp
+++ b/media/extractors/aac/Android.bp
@@ -1,3 +1,20 @@
+package {
+    default_applicable_licenses: ["frameworks_av_media_extractors_aac_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_extractors_aac_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libaacextractor",
     defaults: ["extractor-defaults"],
@@ -10,4 +27,11 @@
         "libutils",
     ],
 
+    host_supported: true,
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
diff --git a/media/extractors/amr/Android.bp b/media/extractors/amr/Android.bp
index 49c9567..712360d 100644
--- a/media/extractors/amr/Android.bp
+++ b/media/extractors/amr/Android.bp
@@ -1,3 +1,20 @@
+package {
+    default_applicable_licenses: ["frameworks_av_media_extractors_amr_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_extractors_amr_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libamrextractor",
     defaults: ["extractor-defaults"],
@@ -8,4 +25,10 @@
         "libstagefright_foundation",
     ],
 
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    }
 }
diff --git a/media/extractors/flac/Android.bp b/media/extractors/flac/Android.bp
index 826c1a0..9a2a76b 100644
--- a/media/extractors/flac/Android.bp
+++ b/media/extractors/flac/Android.bp
@@ -1,6 +1,25 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_extractors_flac_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_extractors_flac_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libflacextractor",
-    defaults: ["extractor-defaults"],
+    defaults: ["extractor-defaults", "libbinder_ndk_host_user"],
 
     srcs: ["FLACExtractor.cpp"],
 
@@ -21,4 +40,12 @@
         "libutils",
     ],
 
+    host_supported: true,
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+
 }
diff --git a/media/extractors/fuzzers/Android.bp b/media/extractors/fuzzers/Android.bp
new file mode 100644
index 0000000..f9e82fb
--- /dev/null
+++ b/media/extractors/fuzzers/Android.bp
@@ -0,0 +1,321 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_defaults {
+    name: "extractor-fuzzerbase-defaults",
+
+    local_include_dirs: [
+        "include",
+    ],
+
+    export_include_dirs: [
+        "include",
+    ],
+
+    static_libs: [
+        "liblog",
+        "libstagefright_foundation",
+        "libmediandk_format",
+        "libmedia_ndkformatpriv",
+    ],
+
+    shared_libs: [
+        "libutils",
+        "libbinder",
+        "libbase",
+        "libcutils",
+    ],
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+}
+
+cc_defaults {
+    name: "extractor-fuzzer-defaults",
+    defaults: ["extractor-fuzzerbase-defaults"],
+
+    static_libs: [
+        "libextractorfuzzerbase",
+    ],
+
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
+
+cc_defaults {
+    name: "mpeg2-extractor-fuzzer-defaults",
+    defaults: ["extractor-fuzzer-defaults"],
+    host_supported: true,
+
+    include_dirs: [
+        "frameworks/av/media/extractors/mpeg2",
+        "frameworks/av/media/libstagefright",
+    ],
+
+    static_libs: [
+        "libstagefright_foundation_without_imemory",
+        "libstagefright_mpeg2support",
+        "libstagefright_mpeg2extractor",
+        "libstagefright_esds",
+        "libmpeg2extractor",
+        "libmedia_helper",
+    ],
+
+    shared_libs: [
+        "android.hardware.cas@1.0",
+        "android.hardware.cas.native@1.0",
+        "android.hidl.token@1.0-utils",
+        "android.hidl.allocator@1.0",
+        "libcrypto",
+        "libhidlmemory",
+        "libhidlbase",
+    ],
+}
+
+cc_library_static {
+    name: "libextractorfuzzerbase",
+    defaults: ["extractor-fuzzerbase-defaults"],
+    host_supported: true,
+
+    srcs: [
+        "ExtractorFuzzerBase.cpp",
+    ],
+}
+
+cc_fuzz {
+    name: "mp4_extractor_fuzzer",
+    defaults: ["extractor-fuzzer-defaults"],
+    host_supported: true,
+
+    srcs: [
+        "mp4_extractor_fuzzer.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/extractors/mp4",
+    ],
+
+    header_libs: [
+        "libaudioclient_headers",
+    ],
+
+    static_libs: [
+        "libstagefright_id3",
+        "libstagefright_esds",
+        "libmp4extractor",
+    ],
+
+    dictionary: "mp4_extractor_fuzzer.dict",
+}
+
+cc_fuzz {
+    name: "wav_extractor_fuzzer",
+    defaults: ["extractor-fuzzer-defaults"],
+    host_supported: true,
+
+    srcs: [
+        "wav_extractor_fuzzer.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/extractors/wav",
+    ],
+
+    static_libs: [
+        "libfifo",
+        "libwavextractor",
+    ],
+
+    shared_libs: [
+        "libbinder_ndk",
+    ],
+}
+
+cc_fuzz {
+    name: "amr_extractor_fuzzer",
+    defaults: ["extractor-fuzzer-defaults"],
+    host_supported: true,
+
+    srcs: [
+        "amr_extractor_fuzzer.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/extractors/amr",
+    ],
+
+    static_libs: [
+        "libamrextractor",
+    ],
+
+    dictionary: "amr_extractor_fuzzer.dict",
+}
+
+cc_fuzz {
+    name: "mkv_extractor_fuzzer",
+    defaults: ["extractor-fuzzer-defaults"],
+    host_supported: true,
+
+    srcs: [
+        "mkv_extractor_fuzzer.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/extractors/mkv",
+    ],
+
+    static_libs: [
+        "libwebm",
+        "libstagefright_flacdec",
+        "libstagefright_metadatautils",
+        "libmkvextractor",
+        "libFLAC",
+    ],
+
+    dictionary: "mkv_extractor_fuzzer.dict",
+}
+
+cc_fuzz {
+    name: "ogg_extractor_fuzzer",
+    defaults: ["extractor-fuzzer-defaults"],
+    host_supported: true,
+
+    srcs: [
+        "ogg_extractor_fuzzer.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/extractors/ogg",
+    ],
+
+    static_libs: [
+        "libstagefright_metadatautils",
+        "libvorbisidec",
+        "liboggextractor",
+    ],
+
+    dictionary: "ogg_extractor_fuzzer.dict",
+}
+
+cc_fuzz {
+    name: "mpeg2ps_extractor_fuzzer",
+    defaults: ["mpeg2-extractor-fuzzer-defaults"],
+
+    srcs: [
+        "mpeg2_extractor_fuzzer.cpp",
+    ],
+
+    cflags: [
+        "-DMPEG2PS",
+    ],
+
+    dictionary: "mpeg2ps_extractor_fuzzer.dict",
+}
+
+cc_fuzz {
+    name: "mpeg2ts_extractor_fuzzer",
+    defaults: ["mpeg2-extractor-fuzzer-defaults"],
+
+    srcs: [
+        "mpeg2_extractor_fuzzer.cpp",
+    ],
+
+    dictionary: "mpeg2ts_extractor_fuzzer.dict",
+}
+
+cc_fuzz {
+    name: "mp3_extractor_fuzzer",
+    defaults: ["extractor-fuzzer-defaults"],
+    host_supported: true,
+
+    srcs: [
+        "mp3_extractor_fuzzer.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/extractors/mp3",
+    ],
+
+    static_libs: [
+        "libfifo",
+        "libmp3extractor",
+        "libstagefright_id3",
+    ],
+}
+
+cc_fuzz {
+    name: "aac_extractor_fuzzer",
+    defaults: ["extractor-fuzzer-defaults"],
+    host_supported: true,
+
+    srcs: [
+        "aac_extractor_fuzzer.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/extractors/aac",
+    ],
+
+    static_libs: [
+        "libaacextractor",
+        "libstagefright_metadatautils",
+    ],
+}
+
+cc_fuzz {
+    name: "flac_extractor_fuzzer",
+    defaults: ["extractor-fuzzer-defaults"],
+    host_supported: true,
+
+    srcs: [
+        "flac_extractor_fuzzer.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/extractors/flac",
+    ],
+
+    static_libs: [
+        "libstagefright_metadatautils",
+        "libFLAC",
+        "libflacextractor",
+    ],
+
+    shared_libs: [
+        "libbinder_ndk",
+    ],
+
+    dictionary: "flac_extractor_fuzzer.dict",
+}
diff --git a/media/extractors/fuzzers/ExtractorFuzzerBase.cpp b/media/extractors/fuzzers/ExtractorFuzzerBase.cpp
new file mode 100644
index 0000000..1be8466
--- /dev/null
+++ b/media/extractors/fuzzers/ExtractorFuzzerBase.cpp
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2020 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 "ExtractorFuzzerBase"
+#include <utils/Log.h>
+
+#include "ExtractorFuzzerBase.h"
+
+using namespace android;
+
+bool ExtractorFuzzerBase::setDataSource(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return false;
+  }
+  mBufferSource = new BufferSource(data, size);
+  mDataSource = reinterpret_cast<DataSource*>(mBufferSource.get());
+  if (!mDataSource) {
+    return false;
+  }
+  return true;
+}
+
+void ExtractorFuzzerBase::getExtractorDef() {
+  float confidence;
+  void* meta = nullptr;
+  FreeMetaFunc freeMeta = nullptr;
+
+  ExtractorDef extractorDef = GETEXTRACTORDEF();
+  if (extractorDef.def_version == EXTRACTORDEF_VERSION_NDK_V1) {
+    extractorDef.u.v2.sniff(mDataSource->wrap(), &confidence, &meta, &freeMeta);
+  } else if (extractorDef.def_version == EXTRACTORDEF_VERSION_NDK_V2) {
+    extractorDef.u.v3.sniff(mDataSource->wrap(), &confidence, &meta, &freeMeta);
+  }
+
+  if (meta != nullptr && freeMeta != nullptr) {
+    freeMeta(meta);
+  }
+}
+
+void ExtractorFuzzerBase::extractTracks() {
+  MediaBufferGroup* bufferGroup = new MediaBufferGroup();
+  if (!bufferGroup) {
+    return;
+  }
+  size_t trackCount = mExtractor->countTracks();
+  for (size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
+    MediaTrackHelper* track = mExtractor->getTrack(trackIndex);
+    if (!track) {
+      continue;
+    }
+    extractTrack(track, bufferGroup);
+    delete track;
+  }
+  delete bufferGroup;
+}
+
+void ExtractorFuzzerBase::extractTrack(MediaTrackHelper* track, MediaBufferGroup* bufferGroup) {
+  CMediaTrack* cTrack = wrap(track);
+  if (!cTrack) {
+    return;
+  }
+
+  media_status_t status = cTrack->start(track, bufferGroup->wrap());
+  if (status != AMEDIA_OK) {
+    free(cTrack);
+    return;
+  }
+
+  do {
+    MediaBufferHelper* buffer = nullptr;
+    status = track->read(&buffer);
+    if (buffer) {
+      buffer->release();
+    }
+  } while (status == AMEDIA_OK);
+
+  cTrack->stop(track);
+  free(cTrack);
+}
+
+void ExtractorFuzzerBase::getTracksMetadata() {
+  AMediaFormat* format = AMediaFormat_new();
+  uint32_t flags = MediaExtractorPluginHelper::kIncludeExtensiveMetaData;
+
+  size_t trackCount = mExtractor->countTracks();
+  for (size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
+    mExtractor->getTrackMetaData(format, trackIndex, flags);
+  }
+
+  AMediaFormat_delete(format);
+}
+
+void ExtractorFuzzerBase::getMetadata() {
+  AMediaFormat* format = AMediaFormat_new();
+  mExtractor->getMetaData(format);
+  AMediaFormat_delete(format);
+}
+
+void ExtractorFuzzerBase::setDataSourceFlags(uint32_t flags) {
+  mBufferSource->setFlags(flags);
+}
+
+void ExtractorFuzzerBase::seekAndExtractTracks() {
+  MediaBufferGroup* bufferGroup = new MediaBufferGroup();
+  if (!bufferGroup) {
+    return;
+  }
+  size_t trackCount = mExtractor->countTracks();
+  for (size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
+    MediaTrackHelper* track = mExtractor->getTrack(trackIndex);
+    if (!track) {
+      continue;
+    }
+
+    AMediaFormat* trackMetaData = AMediaFormat_new();
+    int64_t trackDuration = 0;
+    uint32_t flags = MediaExtractorPluginHelper::kIncludeExtensiveMetaData;
+    mExtractor->getTrackMetaData(trackMetaData, trackIndex, flags);
+    AMediaFormat_getInt64(trackMetaData, AMEDIAFORMAT_KEY_DURATION, &trackDuration);
+
+    seekAndExtractTrack(track, bufferGroup, trackDuration);
+    AMediaFormat_delete(trackMetaData);
+    delete track;
+  }
+  delete bufferGroup;
+}
+
+void ExtractorFuzzerBase::seekAndExtractTrack(MediaTrackHelper* track,
+                                              MediaBufferGroup* bufferGroup,
+                                              int64_t trackDuration) {
+  CMediaTrack* cTrack = wrap(track);
+  if (!cTrack) {
+    return;
+  }
+
+  media_status_t status = cTrack->start(track, bufferGroup->wrap());
+  if (status != AMEDIA_OK) {
+    free(cTrack);
+    return;
+  }
+
+  int32_t seekCount = 0;
+  std::vector<int64_t> seekToTimeStamp;
+  while (seekCount <= kFuzzerMaxSeekPointsCount) {
+    /* This ensures kFuzzerMaxSeekPointsCount seek points are within the clipDuration and 1 seek
+     * point is outside of the clipDuration.
+     */
+    int64_t timeStamp = (seekCount * trackDuration) / (kFuzzerMaxSeekPointsCount - 1);
+    seekToTimeStamp.push_back(timeStamp);
+    seekCount++;
+  }
+
+  std::vector<uint32_t> seekOptions;
+  seekOptions.push_back(CMediaTrackReadOptions::SEEK | CMediaTrackReadOptions::SEEK_CLOSEST);
+  seekOptions.push_back(CMediaTrackReadOptions::SEEK | CMediaTrackReadOptions::SEEK_CLOSEST_SYNC);
+  seekOptions.push_back(CMediaTrackReadOptions::SEEK | CMediaTrackReadOptions::SEEK_PREVIOUS_SYNC);
+  seekOptions.push_back(CMediaTrackReadOptions::SEEK | CMediaTrackReadOptions::SEEK_NEXT_SYNC);
+  seekOptions.push_back(CMediaTrackReadOptions::SEEK | CMediaTrackReadOptions::SEEK_FRAME_INDEX);
+
+  for (uint32_t seekOption : seekOptions) {
+    for (int64_t seekPts : seekToTimeStamp) {
+      MediaTrackHelper::ReadOptions* options =
+          new MediaTrackHelper::ReadOptions(seekOption, seekPts);
+      MediaBufferHelper* buffer = nullptr;
+      track->read(&buffer, options);
+      if (buffer) {
+        buffer->release();
+      }
+      delete options;
+    }
+  }
+
+  cTrack->stop(track);
+  free(cTrack);
+}
+
+void ExtractorFuzzerBase::processData(const uint8_t* data, size_t size) {
+  if (setDataSource(data, size)) {
+    if (createExtractor()) {
+      getExtractorDef();
+      getMetadata();
+      extractTracks();
+      getTracksMetadata();
+      seekAndExtractTracks();
+    }
+  }
+}
diff --git a/media/extractors/fuzzers/README.md b/media/extractors/fuzzers/README.md
new file mode 100644
index 0000000..4223b5e
--- /dev/null
+++ b/media/extractors/fuzzers/README.md
@@ -0,0 +1,326 @@
+# Fuzzer for extractors
+
+## Table of contents
++ [libextractorfuzzerbase](#ExtractorFuzzerBase)
++ [libmp4extractor](#mp4ExtractorFuzzer)
++ [libwavextractor](#wavExtractorFuzzer)
++ [libamrextractor](#amrExtractorFuzzer)
++ [libmkvextractor](#mkvExtractorFuzzer)
++ [liboggextractor](#oggExtractorFuzzer)
++ [libmpeg2extractor](#mpeg2ExtractorFuzzer)
++ [libmp3extractor](#mp3ExtractorFuzzer)
++ [libaacextractor](#aacExtractorFuzzer)
++ [libflacextractor](#flacExtractor)
+
+# <a name="ExtractorFuzzerBase"></a> Fuzzer for libextractorfuzzerbase
+All the extractors have a common API - creating a data source, extraction
+of all the tracks, etc. These common APIs have been abstracted in a base class
+called `ExtractorFuzzerBase` to ensure code is reused between fuzzer plugins.
+
+Additionally, `ExtractorFuzzerBase` also has support for memory based buffer
+`BufferSource` since the fuzzing engine feeds data using memory buffers and
+usage of standard data source objects like FileSource, HTTPSource, etc. is
+not feasible.
+
+# <a name="mp4ExtractorFuzzer"></a> Fuzzer for libmp4extractor
+
+## Plugin Design Considerations
+The fuzzer plugin for MP4 extractor uses the `ExtractorFuzzerBase` class and
+implements only the `createExtractor` to create the MP4 extractor class.
+
+##### Maximize code coverage
+Dict file (dictionary file) is created for MP4 to ensure that the required MP4
+atoms are present in every input file that goes to the fuzzer.
+This ensures that larger code gets covered as a range of MP4 atoms will be
+present in the input data.
+
+
+## Build
+
+This describes steps to build mp4_extractor_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mp4_extractor_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some MP4 files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/mp4_extractor_fuzzer/mp4_extractor_fuzzer CORPUS_DIR
+```
+
+# <a name="wavExtractorFuzzer"></a> Fuzzer for libwavextractor
+
+## Plugin Design Considerations
+The fuzzer plugin for WAV extractor uses the `ExtractorFuzzerBase` class and
+implements only the `createExtractor` to create the WAV extractor class.
+
+
+## Build
+
+This describes steps to build wav_extractor_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) wav_extractor_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some wav files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/wav_extractor_fuzzer/wav_extractor_fuzzer CORPUS_DIR
+```
+
+# <a name="amrExtractorFuzzer"></a> Fuzzer for libamrextractor
+
+## Plugin Design Considerations
+The fuzzer plugin for AMR extractor uses the `ExtractorFuzzerBase` class and
+implements only the `createExtractor` to create the AMR extractor class.
+
+##### Maximize code coverage
+Dict file (dictionary file) is created for AMR to ensure that the required start
+bytes are present in every input file that goes to the fuzzer.
+This ensures that larger code gets covered.
+
+
+## Build
+
+This describes steps to build amr_extractor_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) amr_extractor_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some AMR files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/amr_extractor_fuzzer/amr_extractor_fuzzer CORPUS_DIR
+```
+
+# <a name="mkvExtractorFuzzer"></a> Fuzzer for libmkvextractor
+
+## Plugin Design Considerations
+The fuzzer plugin for MKV extractor uses the `ExtractorFuzzerBase` class and
+implements only the `createExtractor` to create the MKV extractor class.
+
+##### Maximize code coverage
+Dict file (dictionary file) is created for MKV to ensure that the required element
+ID's are present in every input file that goes to the fuzzer.
+This ensures that larger code gets covered.
+
+
+## Build
+
+This describes steps to build mkv_extractor_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mkv_extractor_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some mkv files to that folder.
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/mkv_extractor_fuzzer/mkv_extractor_fuzzer CORPUS_DIR
+```
+
+# <a name="oggExtractorFuzzer"></a> Fuzzer for liboggextractor
+
+## Plugin Design Considerations
+The fuzzer plugin for OGG extractor uses the `ExtractorFuzzerBase` class and
+implements only the `createExtractor` to create the OGG extractor object.
+
+##### Maximize code coverage
+Dict file (dictionary file) is created for OGG to ensure that the required start
+bytes are present in every input file that goes to the fuzzer.
+This ensures that larger code gets covered.
+
+
+## Build
+
+This describes steps to build ogg_extractor_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) ogg_extractor_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some ogg files to that folder.
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/ogg_extractor_fuzzer/ogg_extractor_fuzzer CORPUS_DIR
+```
+
+# <a name="mpeg2ExtractorFuzzer"></a> Fuzzer for libmpeg2extractor
+
+## Plugin Design Considerations
+The fuzzer plugins for MPEG2-PS and MPEG2-TS extractor use the `ExtractorFuzzerBase` class and
+implement only the `createExtractor` to create the MPEG2-PS or MPEG2-TS extractor
+object respectively.
+
+##### Maximize code coverage
+Dict files (dictionary files) are created for MPEG2-PS and MPEG2-TS to ensure that the
+required start bytes are present in every input file that goes to the fuzzer.
+This ensures that larger code gets covered.
+
+##### Other considerations
+Two fuzzer binaries - mpeg2ps_extractor_fuzzer and mpeg2ts_extractor_fuzzer are
+generated based on the presence of a flag - `MPEG2PS`
+
+
+## Build
+
+This describes steps to build mpeg2ps_extractor_fuzzer and mpeg2ts_extractor_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mpeg2ps_extractor_fuzzer
+  $ mm -j$(nproc) mpeg2ts_extractor_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some mpeg2 files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/mpeg2ps_extractor_fuzzer/mpeg2ps_extractor_fuzzer CORPUS_DIR
+  $ adb shell /data/fuzz/arm64/mpeg2ts_extractor_fuzzer/mpeg2ts_extractor_fuzzer CORPUS_DIR
+```
+
+# <a name="mp3ExtractorFuzzer"></a> Fuzzer for libmp3extractor
+
+## Plugin Design Considerations
+The fuzzer plugin for MP3 extractor uses the `ExtractorFuzzerBase` class and
+implements only the `createExtractor` to create the MP3 extractor class.
+
+
+## Build
+
+This describes steps to build mp3_extractor_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mp3_extractor_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some mp3 files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/mp3_extractor_fuzzer/mp3_extractor_fuzzer CORPUS_DIR
+```
+
+# <a name="aacExtractorFuzzer"></a> Fuzzer for libaacextractor
+
+## Plugin Design Considerations
+The fuzzer plugin for AAC extractor uses the `ExtractorFuzzerBase` class and
+implements only the `createExtractor` to create the AAC extractor class.
+
+
+## Build
+
+This describes steps to build aac_extractor_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) aac_extractor_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some aac files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/aac_extractor_fuzzer/aac_extractor_fuzzer CORPUS_DIR
+```
+
+# <a name="flacExtractor"></a> Fuzzer for libflacextractor
+
+## Plugin Design Considerations
+The fuzzer plugin for FLAC extractor uses the `ExtractorFuzzerBase` class and
+implements only the `createExtractor` to create the FLAC extractor object.
+
+##### Maximize code coverage
+Dict file (dictionary file) is created for FLAC to ensure that the required start
+bytes are present in every input file that goes to the fuzzer.
+This ensures that larger code gets covered.
+
+
+## Build
+
+This describes steps to build flac_extractor_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) flac_extractor_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some flac files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/flac_extractor_fuzzer/flac_extractor_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/media/extractors/fuzzers/aac_extractor_fuzzer.cpp b/media/extractors/fuzzers/aac_extractor_fuzzer.cpp
new file mode 100644
index 0000000..98a6cc9
--- /dev/null
+++ b/media/extractors/fuzzers/aac_extractor_fuzzer.cpp
@@ -0,0 +1,54 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "AACExtractor.h"
+
+#include "ExtractorFuzzerBase.h"
+
+using namespace android;
+
+class AacExtractor : public ExtractorFuzzerBase {
+ public:
+  AacExtractor() = default;
+  ~AacExtractor() = default;
+
+  bool createExtractor();
+};
+
+bool AacExtractor::createExtractor() {
+  mExtractor = new AACExtractor(new DataSourceHelper(mDataSource->wrap()), 0);
+  if (!mExtractor) {
+    return false;
+  }
+  mExtractor->name();
+  return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return 0;
+  }
+  AacExtractor* extractor = new AacExtractor();
+  if (extractor) {
+    extractor->processData(data, size);
+    delete extractor;
+  }
+  return 0;
+}
diff --git a/media/extractors/fuzzers/amr_extractor_fuzzer.cpp b/media/extractors/fuzzers/amr_extractor_fuzzer.cpp
new file mode 100644
index 0000000..6c9e1a5
--- /dev/null
+++ b/media/extractors/fuzzers/amr_extractor_fuzzer.cpp
@@ -0,0 +1,54 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "ExtractorFuzzerBase.h"
+
+#include "AMRExtractor.h"
+
+using namespace android;
+
+class AmrExtractor : public ExtractorFuzzerBase {
+ public:
+  AmrExtractor() = default;
+  ~AmrExtractor() = default;
+
+  bool createExtractor();
+};
+
+bool AmrExtractor::createExtractor() {
+  mExtractor = new AMRExtractor(new DataSourceHelper(mDataSource->wrap()));
+  if (!mExtractor) {
+    return false;
+  }
+  mExtractor->name();
+  return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return 0;
+  }
+  AmrExtractor* extractor = new AmrExtractor();
+  if (extractor) {
+    extractor->processData(data, size);
+    delete extractor;
+  }
+  return 0;
+}
diff --git a/media/extractors/fuzzers/amr_extractor_fuzzer.dict b/media/extractors/fuzzers/amr_extractor_fuzzer.dict
new file mode 100644
index 0000000..bc5726c
--- /dev/null
+++ b/media/extractors/fuzzers/amr_extractor_fuzzer.dict
@@ -0,0 +1,2 @@
+# Start code
+kw1="#!AMR"
diff --git a/media/extractors/fuzzers/flac_extractor_fuzzer.cpp b/media/extractors/fuzzers/flac_extractor_fuzzer.cpp
new file mode 100644
index 0000000..8734d45
--- /dev/null
+++ b/media/extractors/fuzzers/flac_extractor_fuzzer.cpp
@@ -0,0 +1,54 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "ExtractorFuzzerBase.h"
+
+#include "FLACExtractor.h"
+
+using namespace android;
+
+class FlacExtractor : public ExtractorFuzzerBase {
+ public:
+  FlacExtractor() = default;
+  ~FlacExtractor() = default;
+
+  bool createExtractor();
+};
+
+bool FlacExtractor::createExtractor() {
+  mExtractor = new FLACExtractor(new DataSourceHelper(mDataSource->wrap()));
+  if (!mExtractor) {
+    return false;
+  }
+  mExtractor->name();
+  return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return 0;
+  }
+  FlacExtractor* extractor = new FlacExtractor();
+  if (extractor) {
+    extractor->processData(data, size);
+    delete extractor;
+  }
+  return 0;
+}
diff --git a/media/extractors/fuzzers/flac_extractor_fuzzer.dict b/media/extractors/fuzzers/flac_extractor_fuzzer.dict
new file mode 100644
index 0000000..53ad44f
--- /dev/null
+++ b/media/extractors/fuzzers/flac_extractor_fuzzer.dict
@@ -0,0 +1,3 @@
+# Start code (bytes 0-3)
+# The below 4 bytes correspond to "fLaC" in ASCII
+kw1="\x66\x4C\x61\x43"
diff --git a/media/extractors/fuzzers/include/ExtractorFuzzerBase.h b/media/extractors/fuzzers/include/ExtractorFuzzerBase.h
new file mode 100644
index 0000000..6a2a1c1
--- /dev/null
+++ b/media/extractors/fuzzers/include/ExtractorFuzzerBase.h
@@ -0,0 +1,139 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#ifndef __EXTRACTOR_FUZZER_BASE_H__
+#define __EXTRACTOR_FUZZER_BASE_H__
+
+#include <media/DataSource.h>
+#include <media/MediaExtractorPluginHelper.h>
+#include <media/stagefright/MediaBufferGroup.h>
+#include <vector>
+
+extern "C" {
+android::ExtractorDef GETEXTRACTORDEF();
+}
+
+constexpr int32_t kFuzzerMaxSeekPointsCount = 5;
+
+namespace android {
+
+class ExtractorFuzzerBase {
+ public:
+  ExtractorFuzzerBase() = default;
+  virtual ~ExtractorFuzzerBase() {
+    if (mExtractor) {
+      delete mExtractor;
+      mExtractor = nullptr;
+    }
+    if (mBufferSource) {
+      mBufferSource.clear();
+      mBufferSource = nullptr;
+    }
+  }
+
+  /** Function to create the media extractor component.
+    * To be implemented by the derived class.
+    */
+  virtual bool createExtractor() = 0;
+
+  /** Parent class functions to be reused by derived class.
+    * These are common for all media extractor components.
+    */
+  bool setDataSource(const uint8_t* data, size_t size);
+
+  void getExtractorDef();
+
+  void extractTracks();
+
+  void getMetadata();
+
+  void getTracksMetadata();
+
+  void setDataSourceFlags(uint32_t flags);
+
+  void seekAndExtractTracks();
+
+  void processData(const uint8_t* data, size_t size);
+
+ protected:
+  class BufferSource : public DataSource {
+   public:
+    BufferSource(const uint8_t* data, size_t length) : mData(data), mLength(length) {}
+    virtual ~BufferSource() { mData = nullptr; }
+
+    void setFlags(uint32_t flags) { mFlags = flags; }
+
+    uint32_t flags() { return mFlags; }
+
+    status_t initCheck() const { return mData != nullptr ? OK : NO_INIT; }
+
+    ssize_t readAt(off64_t offset, void* data, size_t size) {
+      if (!mData) {
+        return NO_INIT;
+      }
+
+      Mutex::Autolock autoLock(mLock);
+      if ((offset >= static_cast<off64_t>(mLength)) || (offset < 0)) {
+        return 0;  // read beyond bounds.
+      }
+      size_t numAvailable = mLength - static_cast<size_t>(offset);
+      if (size > numAvailable) {
+        size = numAvailable;
+      }
+      return readAt_l(offset, data, size);
+    }
+
+    status_t getSize(off64_t* size) {
+      if (!mData) {
+        return NO_INIT;
+      }
+
+      Mutex::Autolock autoLock(mLock);
+      *size = static_cast<off64_t>(mLength);
+      return OK;
+    }
+
+   protected:
+    ssize_t readAt_l(off64_t offset, void* data, size_t size) {
+      void* result = memcpy(data, mData + offset, size);
+      return result != nullptr ? size : 0;
+    }
+
+    const uint8_t* mData = nullptr;
+    size_t mLength = 0;
+    Mutex mLock;
+    uint32_t mFlags = 0;
+
+   private:
+    DISALLOW_EVIL_CONSTRUCTORS(BufferSource);
+  };
+
+  sp<BufferSource> mBufferSource;
+  DataSource* mDataSource = nullptr;
+  MediaExtractorPluginHelper* mExtractor = nullptr;
+
+  virtual void extractTrack(MediaTrackHelper* track, MediaBufferGroup* bufferGroup);
+  virtual void seekAndExtractTrack(MediaTrackHelper* track, MediaBufferGroup* bufferGroup,
+                                   int64_t trackDuration);
+};
+
+}  // namespace android
+
+#endif  // __EXTRACTOR_FUZZER_BASE_H__
diff --git a/media/extractors/fuzzers/mkv_extractor_fuzzer.cpp b/media/extractors/fuzzers/mkv_extractor_fuzzer.cpp
new file mode 100644
index 0000000..eceb93f
--- /dev/null
+++ b/media/extractors/fuzzers/mkv_extractor_fuzzer.cpp
@@ -0,0 +1,54 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "ExtractorFuzzerBase.h"
+
+#include "MatroskaExtractor.h"
+
+using namespace android;
+
+class MKVExtractor : public ExtractorFuzzerBase {
+ public:
+  MKVExtractor() = default;
+  ~MKVExtractor() = default;
+
+  bool createExtractor();
+};
+
+bool MKVExtractor::createExtractor() {
+  mExtractor = new MatroskaExtractor(new DataSourceHelper(mDataSource->wrap()));
+  if (!mExtractor) {
+    return false;
+  }
+  mExtractor->name();
+  return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return 0;
+  }
+  MKVExtractor* extractor = new MKVExtractor();
+  if (extractor) {
+    extractor->processData(data, size);
+    delete extractor;
+  }
+  return 0;
+}
diff --git a/media/extractors/fuzzers/mkv_extractor_fuzzer.dict b/media/extractors/fuzzers/mkv_extractor_fuzzer.dict
new file mode 100644
index 0000000..b3815dc
--- /dev/null
+++ b/media/extractors/fuzzers/mkv_extractor_fuzzer.dict
@@ -0,0 +1,244 @@
+# Elements ID's
+kw1="\x42\x86"
+kw2="\x42\xF7"
+kw3="\x42\xF2"
+kw4="\x42\xF3"
+kw5="\x42\x87"
+kw6="\x42\x85"
+kw7="\x18\x53\x80\x67"
+kw8="\x11\x4D\x9B\x74"
+kw9="\x4D\xBB"
+kw10="\x53\xAB"
+kw11="\x53\xAC"
+kw12="\x15\x49\xA9\x66"
+kw13="\x73\xA4"
+kw14="\x73\x84"
+kw15="\x3C\xB9\x23"
+kw16="\x3C\x83\xAB"
+kw17="\x3C\xB9\x23"
+kw18="\x3E\x83\xBB"
+kw19="\x44\x44"
+kw20="\x69\x24"
+kw21="\x69\xFC"
+kw22="\x69\xBF"
+kw23="\x69\xA5"
+kw24="\x2A\xD7\xB1"
+kw25="\x44\x89"
+kw26="\x44\x61"
+kw27="\x7B\xA9"
+kw28="\x4D\x80"
+kw29="\x57\x41"
+kw30="\x1F\x43\xB6\x75"
+kw31="\xE7"
+kw32="\x58\x54"
+kw33="\x58\xD7"
+kw34="\xA7"
+kw35="\xAB"
+kw36="\xA3"
+kw37="\xA0"
+kw38="\xA1"
+kw39="\xA2"
+kw40="\x75\xA1"
+kw41="\x2A\xD7\xB1"
+kw42="\xA6"
+kw43="\xEE"
+kw44="\xA5"
+kw45="\x9A"
+kw46="\xFA"
+kw47="\xFB"
+kw48="\xFD"
+kw49="\xA4"
+kw50="\x75\xA2"
+kw51="\x8E"
+kw52="\xE8"
+kw53="\xCC"
+kw54="\xCD"
+kw55="\xCB"
+kw56="\xCE"
+kw57="\xCF"
+kw58="\xC8"
+kw59="\xC9"
+kw60="\xCA"
+kw61="\xAF"
+kw62="\x16\x54\xAE\x6B"
+kw63="\xAE"
+kw64="\xD7"
+kw65="\x73\xC5"
+kw66="\x83"
+kw67="\xB9"
+kw68="\x88"
+kw69="\x55\xAA"
+kw70="\x9C"
+kw71="\x6D\xE7"
+kw72="\x6D\xF8"
+kw73="\x23\xE3\x83"
+kw74="\x23\x4E\x7A"
+kw75="\x23\x31\x4F"
+kw76="\x53\x7F"
+kw77="\x55\xEE"
+kw78="\x53\x6E"
+kw79="\x22\xB5\x9C"
+kw80="\x22\xB5\x9D"
+kw81="\x86"
+kw82="\x63\xA2"
+kw83="\x25\x86\x88"
+kw84="\x26\xB2\x40"
+kw85="\xAA"
+kw86="\x6F\xAB"
+kw87="\x56\xAA"
+kw88="\x56\xBB"
+kw89="\x66\x24"
+kw90="\x66\xFC"
+kw91="\x66\xBF"
+kw92="\xE0"
+kw93="\x9A"
+kw94="\x9D"
+kw95="\x53\xB8"
+kw96="\x53\xC0"
+kw97="\x53\xB9"
+kw98="\xB0"
+kw99="\xBA"
+kw100="\x54\xAA"
+kw101="\x54\xBB"
+kw102="\x54\xCC"
+kw103="\x54\xDD"
+kw104="\x54\xB0"
+kw105="\x54\xBA"
+kw106="\x54\xB2"
+kw107="\x54\xB3"
+kw108="\x2E\xB5\x24"
+kw109="\x2F\xB5\x23"
+kw110="\x23\x83\xE3"
+kw111="\x55\xB0"
+kw112="\x55\xB1"
+kw113="\x55\xB2"
+kw114="\x55\xB3"
+kw115="\x55\xB4"
+kw116="\x55\xB5"
+kw117="\x55\xB6"
+kw118="\x55\xB7"
+kw119="\x55\xB8"
+kw120="\x55\xB9"
+kw121="\x55\xBA"
+kw122="\x55\xBB"
+kw123="\x55\xBC"
+kw124="\x55\xBD"
+kw125="\x55\xD0"
+kw126="\x55\xD1"
+kw127="\x55\xD2"
+kw128="\x55\xD3"
+kw129="\x55\xD4"
+kw130="\x55\xD5"
+kw131="\x55\xD6"
+kw132="\x55\xD7"
+kw133="\x55\xD8"
+kw134="\x55\xD9"
+kw135="\x55\xDA"
+kw136="\x76\x70"
+kw137="\x76\x71"
+kw138="\x76\x72"
+kw139="\x76\x73"
+kw140="\x76\x74"
+kw141="\x76\x75"
+kw142="\xE1"
+kw143="\xB5"
+kw144="\x78\xB5"
+kw145="\x9F"
+kw146="\x7D\x7B"
+kw147="\x62\x64"
+kw148="\xE2"
+kw149="\xE3"
+kw150="\xE4"
+kw151="\xE5"
+kw152="\xE6"
+kw153="\xE9"
+kw154="\xED"
+kw155="\xC0"
+kw156="\xC1"
+kw157="\xC6"
+kw158="\xC7"
+kw159="\xC4"
+kw160="\x6D\x80"
+kw161="\x62\x40"
+kw162="\x50\x31"
+kw163="\x50\x32"
+kw164="\x50\x33"
+kw165="\x50\x34"
+kw166="\x50\x35"
+kw167="\x42\x54"
+kw168="\x42\x55"
+kw169="\x47\xE1"
+kw170="\x47\xE2"
+kw171="\x47\xE7"
+kw172="\x47\xE8"
+kw173="\x47\xE3"
+kw174="\x47\xE4"
+kw175="\x47\xE5"
+kw176="\x47\xE6"
+kw177="\x1C\x53\xBB\x6B"
+kw178="\xBB"
+kw179="\xB3"
+kw180="\xB7"
+kw181="\xF7"
+kw182="\xF1"
+kw183="\xF0"
+kw184="\xB2"
+kw185="\x53\x78"
+kw186="\xEA"
+kw187="\xDB"
+kw188="\x96"
+kw189="\x97"
+kw190="\x53\x5F"
+kw191="\xEB"
+kw192="\x19\x41\xA4\x69"
+kw193="\x46\x7E"
+kw194="\x46\x6E"
+kw195="\x46\x60"
+kw196="\x46\x5C"
+kw197="\x46\xAE"
+kw198="\x46\x75"
+kw199="\x46\x61"
+kw200="\x46\x62"
+kw201="\x10\x43\xA7\x70"
+kw202="\x45\xB9"
+kw203="\x45\xBC"
+kw204="\x45\xBD"
+kw205="\x45\xDB"
+kw206="\x45\xDD"
+kw207="\xB6"
+kw208="\x73\xC4"
+kw209="\x56\x54"
+kw210="\x91"
+kw211="\x92"
+kw212="\x98"
+kw213="\x45\x98"
+kw214="\x6E\x67"
+kw215="\x6E\xBC"
+kw216="\x63\xC3"
+kw217="\x8F"
+kw218="\x89"
+kw219="\x80"
+kw220="\x85"
+kw221="\x43\x7C"
+kw222="\x43\x7D"
+kw223="\x43\x7E"
+kw224="\x69\x44"
+kw225="\x69\x55"
+kw226="\x45\x0D"
+kw227="\x69\x11"
+kw228="\x69\x22"
+kw229="\x69\x33"
+kw230="\x12\x54\xC3\x67"
+kw231="\x73\x73"
+kw232="\x63\xC0"
+kw233="\x68\xCA"
+kw234="\x63\xCA"
+kw235="\x63\xC5"
+kw236="\x63\xC9"
+kw237="\x67\xC8"
+kw238="\x45\xA3"
+kw239="\x44\x7A"
+kw240="\x44\x7B"
+kw241="\x44\x84"
+kw242="\x44\x87"
+kw243="\x44\x85"
diff --git a/media/extractors/fuzzers/mp3_extractor_fuzzer.cpp b/media/extractors/fuzzers/mp3_extractor_fuzzer.cpp
new file mode 100644
index 0000000..9a47c18
--- /dev/null
+++ b/media/extractors/fuzzers/mp3_extractor_fuzzer.cpp
@@ -0,0 +1,54 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "ExtractorFuzzerBase.h"
+
+#include "MP3Extractor.h"
+
+using namespace android;
+
+class Mp3Extractor : public ExtractorFuzzerBase {
+ public:
+  Mp3Extractor() = default;
+  ~Mp3Extractor() = default;
+
+  bool createExtractor();
+};
+
+bool Mp3Extractor::createExtractor() {
+  mExtractor = new MP3Extractor(new DataSourceHelper(mDataSource->wrap()), nullptr);
+  if (!mExtractor) {
+    return false;
+  }
+  mExtractor->name();
+  return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return 0;
+  }
+  Mp3Extractor* extractor = new Mp3Extractor();
+  if (extractor) {
+    extractor->processData(data, size);
+    delete extractor;
+  }
+  return 0;
+}
diff --git a/media/extractors/fuzzers/mp4_extractor_fuzzer.cpp b/media/extractors/fuzzers/mp4_extractor_fuzzer.cpp
new file mode 100644
index 0000000..3903519
--- /dev/null
+++ b/media/extractors/fuzzers/mp4_extractor_fuzzer.cpp
@@ -0,0 +1,56 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "ExtractorFuzzerBase.h"
+
+#include "MPEG4Extractor.h"
+#include "SampleTable.h"
+
+using namespace android;
+
+class MP4Extractor : public ExtractorFuzzerBase {
+ public:
+  MP4Extractor() = default;
+  ~MP4Extractor() = default;
+
+  bool createExtractor();
+};
+
+bool MP4Extractor::createExtractor() {
+  mExtractor = new MPEG4Extractor(new DataSourceHelper(mDataSource->wrap()));
+  if (!mExtractor) {
+    return false;
+  }
+  mExtractor->name();
+  setDataSourceFlags(DataSourceBase::kWantsPrefetching | DataSourceBase::kIsCachingDataSource);
+  return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return 0;
+  }
+  MP4Extractor* extractor = new MP4Extractor();
+  if (extractor) {
+    extractor->processData(data, size);
+    delete extractor;
+  }
+  return 0;
+}
diff --git a/media/extractors/fuzzers/mp4_extractor_fuzzer.dict b/media/extractors/fuzzers/mp4_extractor_fuzzer.dict
new file mode 100644
index 0000000..3683649
--- /dev/null
+++ b/media/extractors/fuzzers/mp4_extractor_fuzzer.dict
@@ -0,0 +1,248 @@
+# MP4 Atoms/Boxes
+kw1="ftyp"
+kw2="free"
+kw3="mdat"
+kw4="moov"
+kw5="mvhd"
+kw6="trak"
+kw7="tkhd"
+kw8="edts"
+kw9="elst"
+kw10="mdia"
+kw11="mdhd"
+kw12="hdlr"
+kw13="minf"
+kw14="vmhd"
+kw15="dinf"
+kw16="dref"
+kw17="url "
+kw18="stbl"
+kw19="stsd"
+kw20="avc1"
+kw21="avcC"
+kw22="stts"
+kw23="stss"
+kw24="ctts"
+kw25="stsc"
+kw26="stsz"
+kw27="stco"
+kw28="mp4a"
+kw29="esds"
+kw30="udta"
+kw31="meta"
+kw32="ilst"
+kw33="samr"
+kw34="sawb"
+kw35="ec-3"
+kw36="mp4v"
+kw37="s263"
+kw38="h263"
+kw39="H263"
+kw40="avc1"
+kw41="hvc1"
+kw42="hev1"
+kw43="ac-4"
+kw44="Opus"
+kw45="twos"
+kw46="sowt"
+kw47="alac"
+kw48="fLaC"
+kw49="av01"
+kw50=".mp3"
+kw51="keys"
+kw52="cprt"
+kw53="covr"
+kw54="mvex"
+kw55="moof"
+kw56="traf"
+kw57="mfra"
+kw58="sinf"
+kw59="schi"
+kw60="wave"
+kw61="schm"
+kw62="cbc1"
+kw63="cbcs"
+kw64="cenc"
+kw65="cens"
+kw66="frma"
+kw67="tenc"
+kw68="tref"
+kw69="thmb"
+kw70="pssh"
+kw71="mett"
+kw72="enca"
+kw73="encv"
+kw74="co64"
+kw75="stz2"
+kw76="\xA9xyz"
+kw77="btrt"
+kw78="hvcC"
+kw79="av1C"
+kw80="d263"
+kw81="iloc"
+kw82="iinf"
+kw83="iprp"
+kw84="pitm"
+kw85="idat"
+kw86="iref"
+kw87="ipro"
+kw88="mean"
+kw89="name"
+kw90="data"
+kw91="mehd"
+kw92="text"
+kw93="sbtl"
+kw94="trex"
+kw95="tx3g"
+kw96="colr"
+kw97="titl"
+kw98="perf"
+kw99="auth"
+kw100="gnre"
+kw101="albm"
+kw102="yrrc"
+kw103="ID32"
+kw104="----"
+kw105="sidx"
+kw106="ac-3"
+kw107="qt  "
+kw108="mif1"
+kw109="heic"
+kw110="dac4"
+kw111="dec3"
+kw112="dac3"
+kw113="\xA9alb"
+kw114="\xA9ART"
+kw115="aART"
+kw116="\xA9day"
+kw117="\xA9nam"
+kw118="\xA9wrt"
+kw119="\xA9gen"
+kw120="cpil"
+kw121="trkn"
+kw122="disk"
+kw123="nclx"
+kw124="nclc"
+kw125="tfhd"
+kw126="trun"
+kw127="saiz"
+kw128="saio"
+kw129="senc"
+kw130="isom"
+kw131="iso2"
+kw132="3gp4"
+kw133="mp41"
+kw134="mp42"
+kw135="dash"
+kw136="nvr1"
+kw137="MSNV"
+kw138="wmf "
+kw139="3g2a"
+kw140="3g2b"
+kw141="msf1"
+kw142="hevc"
+kw143="pdin"
+kw144="trgr"
+kw145="smhd"
+kw146="hmhd"
+kw147="nmhd"
+kw148="cslg"
+kw149="stsh"
+kw150="padb"
+kw151="stdp"
+kw152="sdtp"
+kw153="sbgp"
+kw154="sgpd"
+kw155="subs"
+kw156="leva"
+kw157="mfhd"
+kw158="tfdt"
+kw159="tfra"
+kw160="mfro"
+kw161="skip"
+kw162="tsel"
+kw163="strk"
+kw164="stri"
+kw165="strd"
+kw166="xml "
+kw167="bxml"
+kw168="fiin"
+kw169="paen"
+kw170="fire"
+kw171="fpar"
+kw172="fecr"
+kw173="segr"
+kw174="gitn"
+kw175="meco"
+kw176="mere"
+kw177="styp"
+kw178="ssix"
+kw179="prft"
+kw180="hint"
+kw181="cdsc"
+kw182="hind"
+kw183="vdep"
+kw184="vplx"
+kw185="msrc"
+kw186="urn "
+kw187="enct"
+kw188="encs"
+kw189="rinf"
+kw190="srpp"
+kw191="stsg"
+kw192="stvi"
+kw193="tims"
+kw194="tsro"
+kw195="snro"
+kw196="rtp "
+kw197="srtp"
+kw198="rtpo"
+kw199="hnti"
+kw200="sdp "
+kw201="trpy"
+kw202="nump"
+kw203="tpyl"
+kw204="totl"
+kw205="npck"
+kw206="tpay"
+kw207="maxr"
+kw208="dmed"
+kw209="dimm"
+kw210="drep"
+kw211="tmin"
+kw212="tmax"
+kw213="pmax"
+kw214="dmax"
+kw215="payt"
+kw216="fdp "
+kw217="fdsa"
+kw218="fdpa"
+kw219="extr"
+kw220="feci"
+kw221="rm2t"
+kw222="sm2t"
+kw223="tPAT"
+kw224="tPMT"
+kw225="tOD "
+kw226="tsti"
+kw227="istm"
+kw228="pm2t"
+kw229="rrtp"
+kw230="rssr"
+kw231="rscr"
+kw232="rsrp"
+kw233="rssr"
+kw234="ccid"
+kw235="sroc"
+kw236="prtp"
+kw237="roll"
+kw238="rash"
+kw239="alst"
+kw240="rap "
+kw241="tele"
+kw242="mp71"
+kw243="iso3"
+kw244="iso4"
+kw245="iso5"
+kw246="resv"
+kw247="iso6"
diff --git a/media/extractors/fuzzers/mpeg2_extractor_fuzzer.cpp b/media/extractors/fuzzers/mpeg2_extractor_fuzzer.cpp
new file mode 100644
index 0000000..240ef66
--- /dev/null
+++ b/media/extractors/fuzzers/mpeg2_extractor_fuzzer.cpp
@@ -0,0 +1,62 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "ExtractorFuzzerBase.h"
+
+#ifdef MPEG2PS
+#include "MPEG2PSExtractor.h"
+#else
+#include "MPEG2TSExtractor.h"
+#endif
+
+using namespace android;
+
+class MPEG2Extractor : public ExtractorFuzzerBase {
+ public:
+  MPEG2Extractor() = default;
+  ~MPEG2Extractor() = default;
+
+  bool createExtractor();
+};
+
+bool MPEG2Extractor::createExtractor() {
+#ifdef MPEG2PS
+  mExtractor = new MPEG2PSExtractor(new DataSourceHelper(mDataSource->wrap()));
+#else
+  mExtractor = new MPEG2TSExtractor(new DataSourceHelper(mDataSource->wrap()));
+#endif
+  if (!mExtractor) {
+    return false;
+  }
+  mExtractor->name();
+  return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return 0;
+  }
+  MPEG2Extractor* extractor = new MPEG2Extractor();
+  if (extractor) {
+    extractor->processData(data, size);
+    delete extractor;
+  }
+  return 0;
+}
diff --git a/media/extractors/fuzzers/mpeg2ps_extractor_fuzzer.dict b/media/extractors/fuzzers/mpeg2ps_extractor_fuzzer.dict
new file mode 100644
index 0000000..69d390a
--- /dev/null
+++ b/media/extractors/fuzzers/mpeg2ps_extractor_fuzzer.dict
@@ -0,0 +1,2 @@
+# Start code (bytes 0-3)
+kw1="\x00\x00\x01\xBA"
diff --git a/media/extractors/fuzzers/mpeg2ts_extractor_fuzzer.dict b/media/extractors/fuzzers/mpeg2ts_extractor_fuzzer.dict
new file mode 100644
index 0000000..006a1eb
--- /dev/null
+++ b/media/extractors/fuzzers/mpeg2ts_extractor_fuzzer.dict
@@ -0,0 +1,2 @@
+# Start byte
+kw1="\x47"
diff --git a/media/extractors/fuzzers/ogg_extractor_fuzzer.cpp b/media/extractors/fuzzers/ogg_extractor_fuzzer.cpp
new file mode 100644
index 0000000..bd2fcc5
--- /dev/null
+++ b/media/extractors/fuzzers/ogg_extractor_fuzzer.cpp
@@ -0,0 +1,54 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "ExtractorFuzzerBase.h"
+
+#include "OggExtractor.h"
+
+using namespace android;
+
+class OGGExtractor : public ExtractorFuzzerBase {
+ public:
+  OGGExtractor() = default;
+  ~OGGExtractor() = default;
+
+  bool createExtractor();
+};
+
+bool OGGExtractor::createExtractor() {
+  mExtractor = new OggExtractor(new DataSourceHelper(mDataSource->wrap()));
+  if (!mExtractor) {
+    return false;
+  }
+  mExtractor->name();
+  return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return 0;
+  }
+  OGGExtractor* extractor = new OGGExtractor();
+  if (extractor) {
+    extractor->processData(data, size);
+    delete extractor;
+  }
+  return 0;
+}
diff --git a/media/extractors/fuzzers/ogg_extractor_fuzzer.dict b/media/extractors/fuzzers/ogg_extractor_fuzzer.dict
new file mode 100644
index 0000000..df2fc38
--- /dev/null
+++ b/media/extractors/fuzzers/ogg_extractor_fuzzer.dict
@@ -0,0 +1,3 @@
+# Start code(bytes 0-3)
+# The below 4 bytes correspond to "OggS" in ASCII
+kw1="\x4F\x67\x67\x53"
diff --git a/media/extractors/fuzzers/wav_extractor_fuzzer.cpp b/media/extractors/fuzzers/wav_extractor_fuzzer.cpp
new file mode 100644
index 0000000..cb11ebd
--- /dev/null
+++ b/media/extractors/fuzzers/wav_extractor_fuzzer.cpp
@@ -0,0 +1,54 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "ExtractorFuzzerBase.h"
+
+#include "WAVExtractor.h"
+
+using namespace android;
+
+class wavExtractor : public ExtractorFuzzerBase {
+ public:
+  wavExtractor() = default;
+  ~wavExtractor() = default;
+
+  bool createExtractor();
+};
+
+bool wavExtractor::createExtractor() {
+  mExtractor = new WAVExtractor(new DataSourceHelper(mDataSource->wrap()));
+  if (!mExtractor) {
+    return false;
+  }
+  mExtractor->name();
+  return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+  if ((!data) || (size == 0)) {
+    return 0;
+  }
+  wavExtractor* extractor = new wavExtractor();
+  if (extractor) {
+    extractor->processData(data, size);
+    delete extractor;
+  }
+  return 0;
+}
diff --git a/media/extractors/midi/Android.bp b/media/extractors/midi/Android.bp
index b8255fc..f82fc41 100644
--- a/media/extractors/midi/Android.bp
+++ b/media/extractors/midi/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_extractors_midi_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_extractors_midi_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libmidiextractor",
     defaults: ["extractor-defaults"],
diff --git a/media/extractors/mkv/Android.bp b/media/extractors/mkv/Android.bp
index 7ad8cc1..840c9fc 100644
--- a/media/extractors/mkv/Android.bp
+++ b/media/extractors/mkv/Android.bp
@@ -1,3 +1,20 @@
+package {
+    default_applicable_licenses: ["frameworks_av_media_extractors_mkv_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_extractors_mkv_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libmkvextractor",
     defaults: ["extractor-defaults"],
@@ -21,4 +38,12 @@
         "libutils",
     ],
 
+    host_supported: true,
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+
 }
diff --git a/media/extractors/mkv/MatroskaExtractor.cpp b/media/extractors/mkv/MatroskaExtractor.cpp
index 27bd357..4fd3a56 100644
--- a/media/extractors/mkv/MatroskaExtractor.cpp
+++ b/media/extractors/mkv/MatroskaExtractor.cpp
@@ -1888,13 +1888,12 @@
 
     for(size_t i = 0; i < track->GetContentEncodingCount(); i++) {
         const mkvparser::ContentEncoding *encoding = track->GetContentEncodingByIndex(i);
-        for(size_t j = 0; j < encoding->GetEncryptionCount(); j++) {
+        if (encoding->GetEncryptionCount() > 0) {
             const mkvparser::ContentEncoding::ContentEncryption *encryption;
-            encryption = encoding->GetEncryptionByIndex(j);
+            encryption = encoding->GetEncryptionByIndex(0);
             AMediaFormat_setBuffer(trackInfo->mMeta,
                     AMEDIAFORMAT_KEY_CRYPTO_KEY, encryption->key_id, encryption->key_id_len);
             trackInfo->mEncrypted = true;
-            break;
         }
 
         for(size_t j = 0; j < encoding->GetCompressionCount(); j++) {
diff --git a/media/extractors/mp3/Android.bp b/media/extractors/mp3/Android.bp
index 102ac81..75b9b7b 100644
--- a/media/extractors/mp3/Android.bp
+++ b/media/extractors/mp3/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libmp3extractor",
     defaults: ["extractor-defaults"],
@@ -13,4 +22,11 @@
         "libstagefright_foundation",
     ],
 
+    host_supported: true,
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
diff --git a/media/extractors/mp4/Android.bp b/media/extractors/mp4/Android.bp
index e48e1b7..7fa6bfd 100644
--- a/media/extractors/mp4/Android.bp
+++ b/media/extractors/mp4/Android.bp
@@ -1,3 +1,20 @@
+package {
+    default_applicable_licenses: ["frameworks_av_media_extractors_mp4_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_extractors_mp4_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libmp4extractor",
     defaults: ["extractor-defaults"],
@@ -16,4 +33,12 @@
         "libstagefright_id3",
         "libutils",
     ],
+
+    host_supported: true,
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
diff --git a/media/extractors/mp4/ItemTable.cpp b/media/extractors/mp4/ItemTable.cpp
index 0773387..2599c2c 100644
--- a/media/extractors/mp4/ItemTable.cpp
+++ b/media/extractors/mp4/ItemTable.cpp
@@ -546,11 +546,11 @@
                 continue;
             }
             ALOGV("Image item id %d uses thumbnail item id %d", mRefs[i], mItemId);
-            ImageItem &masterImage = itemIdToItemMap.editValueAt(itemIndex);
-            if (!masterImage.thumbnails.empty()) {
+            ImageItem &imageItem = itemIdToItemMap.editValueAt(itemIndex);
+            if (!imageItem.thumbnails.empty()) {
                 ALOGW("already has thumbnails!");
             }
-            masterImage.thumbnails.push_back(mItemId);
+            imageItem.thumbnails.push_back(mItemId);
         }
         break;
     }
@@ -929,7 +929,7 @@
 
 status_t IpcoBox::parse(off64_t offset, size_t size) {
     ALOGV("%s: offset %lld, size %zu", __FUNCTION__, (long long)offset, size);
-    // push dummy as the index is 1-based
+    // push a placeholder as the index is 1-based
     mItemProperties->push_back(new ItemProperty());
     return parseChunks(offset, size);
 }
@@ -1614,17 +1614,17 @@
         return BAD_VALUE;
     }
 
-    uint32_t masterItemIndex = mDisplayables[imageIndex];
+    uint32_t imageItemIndex = mDisplayables[imageIndex];
 
-    const ImageItem &masterImage = mItemIdToItemMap[masterItemIndex];
-    if (masterImage.thumbnails.empty()) {
-        *itemIndex = masterItemIndex;
+    const ImageItem &imageItem = mItemIdToItemMap[imageItemIndex];
+    if (imageItem.thumbnails.empty()) {
+        *itemIndex = imageItemIndex;
         return OK;
     }
 
-    ssize_t thumbItemIndex = mItemIdToItemMap.indexOfKey(masterImage.thumbnails[0]);
+    ssize_t thumbItemIndex = mItemIdToItemMap.indexOfKey(imageItem.thumbnails[0]);
     if (thumbItemIndex < 0) {
-        // Do not return the master image in this case, fail it so that the
+        // Do not return the image item in this case, fail it so that the
         // thumbnail extraction code knows we really don't have it.
         return INVALID_OPERATION;
     }
diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp
old mode 100755
new mode 100644
index a976a2b..409fca1
--- a/media/extractors/mp4/MPEG4Extractor.cpp
+++ b/media/extractors/mp4/MPEG4Extractor.cpp
@@ -202,8 +202,8 @@
         uint32_t duration;
         int32_t compositionOffset;
         uint8_t iv[16];
-        Vector<size_t> clearsizes;
-        Vector<size_t> encryptedsizes;
+        Vector<uint32_t> clearsizes;
+        Vector<uint32_t> encryptedsizes;
     };
     Vector<Sample> mCurrentSamples;
     std::map<off64_t, uint32_t> mDrmOffsets;
@@ -372,6 +372,8 @@
             return MEDIA_MIMETYPE_AUDIO_FLAC;
         case FOURCC("av01"):
             return MEDIA_MIMETYPE_VIDEO_AV1;
+        case FOURCC("vp09"):
+            return MEDIA_MIMETYPE_VIDEO_VP9;
         case FOURCC(".mp3"):
         case 0x6D730055: // "ms U" mp3 audio
             return MEDIA_MIMETYPE_AUDIO_MPEG;
@@ -1149,7 +1151,7 @@
             } else if (chunk_type == FOURCC("moov")) {
                 mInitCheck = OK;
 
-                return UNKNOWN_ERROR;  // Return a dummy error.
+                return UNKNOWN_ERROR;  // Return a generic error.
             }
             break;
         }
@@ -1787,7 +1789,7 @@
                 return ERROR_IO;
             }
 
-            uint16_t data_ref_index __unused = U16_AT(&buffer[6]);
+            // we can get data_ref_index value from U16_AT(&buffer[6])
             uint16_t version = U16_AT(&buffer[8]);
             uint32_t num_channels = U16_AT(&buffer[16]);
 
@@ -1972,6 +1974,7 @@
         case FOURCC("dvh1"):
         case FOURCC("dav1"):
         case FOURCC("av01"):
+        case FOURCC("vp09"):
         {
             uint8_t buffer[78];
             if (chunk_data_size < (ssize_t)sizeof(buffer)) {
@@ -1984,7 +1987,7 @@
                 return ERROR_IO;
             }
 
-            uint16_t data_ref_index __unused = U16_AT(&buffer[6]);
+            // we can get data_ref_index value from U16_AT(&buffer[6])
             uint16_t width = U16_AT(&buffer[6 + 18]);
             uint16_t height = U16_AT(&buffer[6 + 20]);
 
@@ -2434,6 +2437,8 @@
             *offset += chunk_size;
             break;
         }
+
+        case FOURCC("vpcC"):
         case FOURCC("av1C"):
         {
             auto buffer = heapbuffer<uint8_t>(chunk_data_size);
@@ -3407,7 +3412,7 @@
     }
 
     // skip
-    unsigned bsmod __unused = br.getBits(3);
+    br.skipBits(3); // bsmod
 
     unsigned acmod = br.getBits(3);
     unsigned lfeon = br.getBits(1);
@@ -3718,19 +3723,18 @@
         return ERROR_IO;
     }
 
-    uint64_t ctime __unused, mtime __unused, duration __unused;
     int32_t id;
 
     if (version == 1) {
-        ctime = U64_AT(&buffer[4]);
-        mtime = U64_AT(&buffer[12]);
+        // we can get ctime value from U64_AT(&buffer[4])
+        // we can get mtime value from U64_AT(&buffer[12])
         id = U32_AT(&buffer[20]);
-        duration = U64_AT(&buffer[28]);
+        // we can get duration value from U64_AT(&buffer[28])
     } else if (version == 0) {
-        ctime = U32_AT(&buffer[4]);
-        mtime = U32_AT(&buffer[8]);
+        // we can get ctime value from U32_AT(&buffer[4])
+        // we can get mtime value from U32_AT(&buffer[8])
         id = U32_AT(&buffer[12]);
-        duration = U32_AT(&buffer[20]);
+        // we can get duration value from U32_AT(&buffer[20])
     } else {
         return ERROR_UNSUPPORTED;
     }
@@ -4337,6 +4341,18 @@
         if (size < 5 || ptr[0] != 0x81) {  // configurationVersion == 1
             return NULL;
         }
+    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_VP9)) {
+        void *data;
+        size_t size;
+        if (!AMediaFormat_getBuffer(track->meta, AMEDIAFORMAT_KEY_CSD_0, &data, &size)) {
+            return NULL;
+        }
+
+        const uint8_t *ptr = (const uint8_t *)data;
+
+        if (size < 5 || ptr[0] != 0x01) {  // configurationVersion == 1
+            return NULL;
+        }
     }
 
     ALOGV("track->elst_shift_start_ticks :%" PRIu64, track->elst_shift_start_ticks);
@@ -4391,6 +4407,10 @@
         if (!AMediaFormat_getBuffer(track->meta, AMEDIAFORMAT_KEY_CSD_0, &data, &size)) {
             return ERROR_MALFORMED;
         }
+    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_VP9)) {
+        if (!AMediaFormat_getBuffer(track->meta, AMEDIAFORMAT_KEY_CSD_0, &data, &size)) {
+            return ERROR_MALFORMED;
+        }
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4)
             || !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG2)
             || !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC)) {
@@ -4638,18 +4658,17 @@
     if (objectType == AOT_SBR || objectType == AOT_PS) {//SBR specific config per 14496-3 tbl 1.13
         if (br.numBitsLeft() < 4) return ERROR_MALFORMED;
         uint32_t extFreqIndex = br.getBits(4);
-        int32_t extSampleRate __unused;
         if (extFreqIndex == 15) {
             if (csd_size < 8) {
                 return ERROR_MALFORMED;
             }
             if (br.numBitsLeft() < 24) return ERROR_MALFORMED;
-            extSampleRate = br.getBits(24);
+            br.skipBits(24); // extSampleRate
         } else {
             if (extFreqIndex == 13 || extFreqIndex == 14) {
                 return ERROR_MALFORMED;
             }
-            extSampleRate = kSamplingRate[extFreqIndex];
+            //extSampleRate = kSamplingRate[extFreqIndex];
         }
         //TODO: save the extension sampling rate value in meta data =>
         //      AMediaFormat_setInt32(mLastTrack->meta, kKeyExtSampleRate, extSampleRate);
@@ -4692,13 +4711,13 @@
                 objectType == AOT_ER_AAC_LD || objectType == AOT_ER_AAC_SCAL ||
                 objectType == AOT_ER_BSAC) {
             if (br.numBitsLeft() < 2) return ERROR_MALFORMED;
-            const int32_t frameLengthFlag __unused = br.getBits(1);
+            br.skipBits(1); // frameLengthFlag
 
             const int32_t dependsOnCoreCoder = br.getBits(1);
 
             if (dependsOnCoreCoder ) {
                 if (br.numBitsLeft() < 14) return ERROR_MALFORMED;
-                const int32_t coreCoderDelay __unused = br.getBits(14);
+                br.skipBits(14); // coreCoderDelay
             }
 
             int32_t extensionFlag = -1;
@@ -4730,64 +4749,64 @@
                 if (br.numBitsLeft() < 32) {
                     return ERROR_MALFORMED;
                 }
-                const int32_t ElementInstanceTag __unused = br.getBits(4);
-                const int32_t Profile __unused = br.getBits(2);
-                const int32_t SamplingFrequencyIndex __unused = br.getBits(4);
+                br.skipBits(4); // ElementInstanceTag
+                br.skipBits(2); // Profile
+                br.skipBits(4); // SamplingFrequencyIndex
                 const int32_t NumFrontChannelElements = br.getBits(4);
                 const int32_t NumSideChannelElements = br.getBits(4);
                 const int32_t NumBackChannelElements = br.getBits(4);
                 const int32_t NumLfeChannelElements = br.getBits(2);
-                const int32_t NumAssocDataElements __unused = br.getBits(3);
-                const int32_t NumValidCcElements __unused = br.getBits(4);
+                br.skipBits(3); // NumAssocDataElements
+                br.skipBits(4); // NumValidCcElements
 
                 const int32_t MonoMixdownPresent = br.getBits(1);
 
                 if (MonoMixdownPresent != 0) {
                     if (br.numBitsLeft() < 4) return ERROR_MALFORMED;
-                    const int32_t MonoMixdownElementNumber __unused = br.getBits(4);
+                    br.skipBits(4); // MonoMixdownElementNumber
                 }
 
                 if (br.numBitsLeft() < 1) return ERROR_MALFORMED;
                 const int32_t StereoMixdownPresent = br.getBits(1);
                 if (StereoMixdownPresent != 0) {
                     if (br.numBitsLeft() < 4) return ERROR_MALFORMED;
-                    const int32_t StereoMixdownElementNumber __unused = br.getBits(4);
+                    br.skipBits(4); // StereoMixdownElementNumber
                 }
 
                 if (br.numBitsLeft() < 1) return ERROR_MALFORMED;
                 const int32_t MatrixMixdownIndexPresent = br.getBits(1);
                 if (MatrixMixdownIndexPresent != 0) {
                     if (br.numBitsLeft() < 3) return ERROR_MALFORMED;
-                    const int32_t MatrixMixdownIndex __unused = br.getBits(2);
-                    const int32_t PseudoSurroundEnable __unused = br.getBits(1);
+                    br.skipBits(2); // MatrixMixdownIndex
+                    br.skipBits(1); // PseudoSurroundEnable
                 }
 
                 int i;
                 for (i=0; i < NumFrontChannelElements; i++) {
                     if (br.numBitsLeft() < 5) return ERROR_MALFORMED;
                     const int32_t FrontElementIsCpe = br.getBits(1);
-                    const int32_t FrontElementTagSelect __unused = br.getBits(4);
+                    br.skipBits(4); // FrontElementTagSelect
                     channelsNum += FrontElementIsCpe ? 2 : 1;
                 }
 
                 for (i=0; i < NumSideChannelElements; i++) {
                     if (br.numBitsLeft() < 5) return ERROR_MALFORMED;
                     const int32_t SideElementIsCpe = br.getBits(1);
-                    const int32_t SideElementTagSelect __unused = br.getBits(4);
+                    br.skipBits(4); // SideElementTagSelect
                     channelsNum += SideElementIsCpe ? 2 : 1;
                 }
 
                 for (i=0; i < NumBackChannelElements; i++) {
                     if (br.numBitsLeft() < 5) return ERROR_MALFORMED;
                     const int32_t BackElementIsCpe = br.getBits(1);
-                    const int32_t BackElementTagSelect __unused = br.getBits(4);
+                    br.skipBits(4); // BackElementTagSelect
                     channelsNum += BackElementIsCpe ? 2 : 1;
                 }
                 channelsEffectiveNum = channelsNum;
 
                 for (i=0; i < NumLfeChannelElements; i++) {
                     if (br.numBitsLeft() < 4) return ERROR_MALFORMED;
-                    const int32_t LfeElementTagSelect __unused = br.getBits(4);
+                    br.skipBits(4); // LfeElementTagSelect
                     channelsNum += 1;
                 }
                 ALOGV("mpeg4 audio channelsNum = %d", channelsNum);
@@ -5766,7 +5785,7 @@
             return -EINVAL;
         }
 
-        // apply some sanity (vs strict legality) checks
+        // apply some quick (vs strict legality) checks
         //
         static constexpr uint32_t kMaxTrunSampleCount = 10000;
         if (sampleCount > kMaxTrunSampleCount) {
@@ -6485,9 +6504,9 @@
     if (smpl->encryptedsizes.size()) {
         // store clear/encrypted lengths in metadata
         AMediaFormat_setBuffer(bufmeta, AMEDIAFORMAT_KEY_CRYPTO_PLAIN_SIZES,
-                smpl->clearsizes.array(), smpl->clearsizes.size() * 4);
+                smpl->clearsizes.array(), smpl->clearsizes.size() * sizeof(uint32_t));
         AMediaFormat_setBuffer(bufmeta, AMEDIAFORMAT_KEY_CRYPTO_ENCRYPTED_SIZES,
-                smpl->encryptedsizes.array(), smpl->encryptedsizes.size() * 4);
+                smpl->encryptedsizes.array(), smpl->encryptedsizes.size() * sizeof(uint32_t));
         AMediaFormat_setInt32(bufmeta, AMEDIAFORMAT_KEY_CRYPTO_DEFAULT_IV_SIZE, mDefaultIVSize);
         AMediaFormat_setInt32(bufmeta, AMEDIAFORMAT_KEY_CRYPTO_MODE, mCryptoMode);
         AMediaFormat_setBuffer(bufmeta, AMEDIAFORMAT_KEY_CRYPTO_KEY, mCryptoKey, 16);
@@ -6713,6 +6732,7 @@
         FOURCC("hvc1"),
         FOURCC("hev1"),
         FOURCC("av01"),
+        FOURCC("vp09"),
         FOURCC("3gp4"),
         FOURCC("mp41"),
         FOURCC("mp42"),
diff --git a/media/extractors/mpeg2/Android.bp b/media/extractors/mpeg2/Android.bp
index bc8632c..7e6247b 100644
--- a/media/extractors/mpeg2/Android.bp
+++ b/media/extractors/mpeg2/Android.bp
@@ -1,6 +1,35 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_extractors_mpeg2_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_extractors_mpeg2_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libmpeg2extractor",
 
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+        android: {
+            shared_libs: ["libvndksupport#29"],
+        },
+    },
+
     defaults: ["extractor-defaults"],
 
     srcs: [
@@ -12,14 +41,13 @@
     shared_libs: [
         "libbase",
         "libcgrouprc#29",
-        "libvndksupport#29",
     ],
 
     header_libs: [
         "libaudioclient_headers",
         "libbase_headers",
         "libstagefright_headers",
-        "libmedia_headers",
+        "libmedia_datasource_headers",
     ],
 
     static_libs: [
@@ -37,7 +65,7 @@
         "libstagefright_esds",
         "libstagefright_foundation_without_imemory",
         "libstagefright_mpeg2extractor",
-        "libstagefright_mpeg2support",
+        "libstagefright_mpeg2support_nocrypto",
         "libutils",
     ],
 
diff --git a/media/extractors/ogg/Android.bp b/media/extractors/ogg/Android.bp
index 7aed683..d7540c4 100644
--- a/media/extractors/ogg/Android.bp
+++ b/media/extractors/ogg/Android.bp
@@ -1,3 +1,20 @@
+package {
+    default_applicable_licenses: ["frameworks_av_media_extractors_ogg_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_extractors_ogg_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "liboggextractor",
 
@@ -20,4 +37,11 @@
         "libvorbisidec",
     ],
 
+    host_supported: true,
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
diff --git a/media/extractors/ogg/OggExtractor.cpp b/media/extractors/ogg/OggExtractor.cpp
index 828bcd6..eb2246d 100644
--- a/media/extractors/ogg/OggExtractor.cpp
+++ b/media/extractors/ogg/OggExtractor.cpp
@@ -1304,8 +1304,8 @@
                 || audioChannelCount <= 0 || audioChannelCount > FCC_8) {
             ALOGE("Invalid haptic channel count found in metadata: %d", mHapticChannelCount);
         } else {
-            const audio_channel_mask_t channelMask = audio_channel_out_mask_from_count(
-                    audioChannelCount) | hapticChannelMask;
+            const audio_channel_mask_t channelMask = static_cast<audio_channel_mask_t>(
+                    audio_channel_out_mask_from_count(audioChannelCount) | hapticChannelMask);
             AMediaFormat_setInt32(mMeta, AMEDIAFORMAT_KEY_CHANNEL_MASK, channelMask);
             AMediaFormat_setInt32(
                     mMeta, AMEDIAFORMAT_KEY_HAPTIC_CHANNEL_COUNT, mHapticChannelCount);
diff --git a/media/extractors/tests/Android.bp b/media/extractors/tests/Android.bp
index b3afe2f..f46fa7b 100644
--- a/media/extractors/tests/Android.bp
+++ b/media/extractors/tests/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "ExtractorUnitTest",
     gtest: true,
diff --git a/media/extractors/tests/AndroidTest.xml b/media/extractors/tests/AndroidTest.xml
index 6bb2c8a..fc8152c 100644
--- a/media/extractors/tests/AndroidTest.xml
+++ b/media/extractors/tests/AndroidTest.xml
@@ -19,7 +19,7 @@
         <option name="cleanup" value="true" />
         <option name="push" value="ExtractorUnitTest->/data/local/tmp/ExtractorUnitTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/extractors/tests/extractor.zip?unzip=true"
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/extractors/tests/extractor-1.4.zip?unzip=true"
             value="/data/local/tmp/ExtractorUnitTestRes/" />
     </target_preparer>
 
diff --git a/media/extractors/tests/ExtractorUnitTest.cpp b/media/extractors/tests/ExtractorUnitTest.cpp
index 518166e..d91fffa 100644
--- a/media/extractors/tests/ExtractorUnitTest.cpp
+++ b/media/extractors/tests/ExtractorUnitTest.cpp
@@ -20,8 +20,10 @@
 
 #include <datasource/FileSource.h>
 #include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaCodecConstants.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaDataUtils.h>
+#include <media/stagefright/foundation/OpusHeader.h>
 
 #include "aac/AACExtractor.h"
 #include "amr/AMRExtractor.h"
@@ -43,11 +45,76 @@
 #define OUTPUT_DUMP_FILE "/data/local/tmp/extractorOutput"
 
 constexpr int32_t kMaxCount = 10;
-constexpr int32_t kOpusSeekPreRollUs = 80000;  // 80 ms;
+constexpr int32_t kAudioDefaultSampleDuration = 20000;                       // 20ms
+constexpr int32_t kRandomSeekToleranceUs = 2 * kAudioDefaultSampleDuration;  // 40 ms;
+constexpr int32_t kRandomSeed = 700;
+constexpr int32_t kUndefined = -1;
+
+enum inputID {
+    // audio streams
+    AAC_1,
+    AMR_NB_1,
+    AMR_WB_1,
+    FLAC_1,
+    GSM_1,
+    MIDI_1,
+    MP3_1,
+    OPUS_1,
+    VORBIS_1,
+    // video streams
+    HEVC_1,
+    HEVC_2,
+    MPEG2_PS_1,
+    MPEG2_TS_1,
+    MPEG4_1,
+    VP9_1,
+    UNKNOWN_ID,
+};
+
+// LookUpTable of clips and metadata for component testing
+static const struct InputData {
+    inputID inpId;
+    string mime;
+    string inputFile;
+    int32_t firstParam;
+    int32_t secondParam;
+    int32_t profile;
+    int32_t frameRate;
+} kInputData[] = {
+        {AAC_1, MEDIA_MIMETYPE_AUDIO_AAC, "test_mono_44100Hz_aac.aac", 44100, 1, AACObjectLC,
+         kUndefined},
+        {AMR_NB_1, MEDIA_MIMETYPE_AUDIO_AMR_NB, "bbb_mono_8kHz_amrnb.amr", 8000, 1, kUndefined,
+         kUndefined},
+        {AMR_WB_1, MEDIA_MIMETYPE_AUDIO_AMR_WB, "bbb_mono_16kHz_amrwb.amr", 16000, 1, kUndefined,
+         kUndefined},
+        {FLAC_1, MEDIA_MIMETYPE_AUDIO_RAW, "bbb_stereo_48kHz_flac.flac", 48000, 2, kUndefined,
+         kUndefined},
+        {GSM_1, MEDIA_MIMETYPE_AUDIO_MSGSM, "test_mono_8kHz_gsm.wav", 8000, 1, kUndefined,
+         kUndefined},
+        {MIDI_1, MEDIA_MIMETYPE_AUDIO_RAW, "midi_a.mid", 22050, 2, kUndefined, kUndefined},
+        {MP3_1, MEDIA_MIMETYPE_AUDIO_MPEG, "bbb_stereo_48kHz_mp3.mp3", 48000, 2, kUndefined,
+         kUndefined},
+        {OPUS_1, MEDIA_MIMETYPE_AUDIO_OPUS, "test_stereo_48kHz_opus.opus", 48000, 2, kUndefined,
+         kUndefined},
+        {VORBIS_1, MEDIA_MIMETYPE_AUDIO_VORBIS, "bbb_stereo_48kHz_vorbis.ogg", 48000, 2, kUndefined,
+         kUndefined},
+
+        // Test (b/151677264) for MP4 extractor
+        {HEVC_1, MEDIA_MIMETYPE_VIDEO_HEVC, "crowd_508x240_25fps_hevc.mp4", 508, 240,
+         HEVCProfileMain, 25},
+        {HEVC_2, MEDIA_MIMETYPE_IMAGE_ANDROID_HEIC, "test3.heic", 820, 460, kUndefined, kUndefined},
+        {MPEG2_PS_1, MEDIA_MIMETYPE_VIDEO_MPEG2, "swirl_144x136_mpeg2.mpg", 144, 136,
+         MPEG2ProfileMain, 12},
+        {MPEG2_TS_1, MEDIA_MIMETYPE_VIDEO_MPEG2, "bbb_cif_768kbps_30fps_mpeg2.ts", 352, 288,
+         MPEG2ProfileMain, 30},
+        {MPEG4_1, MEDIA_MIMETYPE_VIDEO_MPEG4, "bbb_cif_768kbps_30fps_mpeg4.mkv", 352, 288,
+         MPEG4ProfileSimple, 30},
+        {VP9_1, MEDIA_MIMETYPE_VIDEO_VP9, "bbb_340x280_30fps_vp9.webm", 340, 280, VP9Profile0, 30},
+};
 
 static ExtractorUnitTestEnvironment *gEnv = nullptr;
 
-class ExtractorUnitTest : public ::testing::TestWithParam<pair<string, string>> {
+class ExtractorUnitTest {
   public:
     ExtractorUnitTest() : mInputFp(nullptr), mDataSource(nullptr), mExtractor(nullptr) {}
 
@@ -66,16 +133,29 @@
         }
     }
 
-    virtual void SetUp() override {
+    void setupExtractor(string writerFormat) {
         mExtractorName = unknown_comp;
         mDisableTest = false;
 
         static const std::map<std::string, standardExtractors> mapExtractor = {
-                {"aac", AAC},     {"amr", AMR},         {"mp3", MP3},        {"ogg", OGG},
-                {"wav", WAV},     {"mkv", MKV},         {"flac", FLAC},      {"midi", MIDI},
-                {"mpeg4", MPEG4}, {"mpeg2ts", MPEG2TS}, {"mpeg2ps", MPEG2PS}};
+                {"aac", AAC},
+                {"amr", AMR},
+                {"flac", FLAC},
+                {"mid", MIDI},
+                {"midi", MIDI},
+                {"mkv", MKV},
+                {"mp3", MP3},
+                {"mp4", MPEG4},
+                {"mpeg2ps", MPEG2PS},
+                {"mpeg2ts", MPEG2TS},
+                {"mpeg4", MPEG4},
+                {"mpg", MPEG2PS},
+                {"ogg", OGG},
+                {"opus", OGG},
+                {"ts", MPEG2TS},
+                {"wav", WAV},
+                {"webm", MKV}};
         // Find the component type
-        string writerFormat = GetParam().first;
         if (mapExtractor.find(writerFormat) != mapExtractor.end()) {
             mExtractorName = mapExtractor.at(writerFormat);
         }
@@ -112,6 +192,39 @@
     MediaExtractorPluginHelper *mExtractor;
 };
 
+class ExtractorFunctionalityTest
+    : public ExtractorUnitTest,
+      public ::testing::TestWithParam<tuple<string /* container */, string /* InputFile */,
+                                            int32_t /* numTracks */, bool /* seekSupported */>> {
+  public:
+    virtual void SetUp() override {
+        tuple<string, string, int32_t, bool> params = GetParam();
+        mContainer = get<0>(params);
+        mNumTracks = get<2>(params);
+        setupExtractor(mContainer);
+    }
+    string mContainer;
+    int32_t mNumTracks;
+};
+
+class ConfigParamTest : public ExtractorUnitTest,
+                        public ::testing::TestWithParam<pair<string, inputID>> {
+  public:
+    virtual void SetUp() override { setupExtractor(GetParam().first); }
+
+    struct configFormat {
+        string mime;
+        int32_t width;
+        int32_t height;
+        int32_t sampleRate;
+        int32_t channelCount;
+        int32_t profile;
+        int32_t frameRate;
+    };
+
+    void getFileProperties(inputID inputId, string &inputFile, configFormat &configParam);
+};
+
 int32_t ExtractorUnitTest::setDataSource(string inputFileName) {
     mInputFp = fopen(inputFileName.c_str(), "rb");
     if (!mInputFp) {
@@ -168,6 +281,75 @@
     return 0;
 }
 
+void ConfigParamTest::getFileProperties(inputID inputId, string &inputFile,
+                                        configFormat &configParam) {
+    int32_t inputDataSize = sizeof(kInputData) / sizeof(kInputData[0]);
+    int32_t inputIdx = 0;
+    for (; inputIdx < inputDataSize; inputIdx++) {
+        if (inputId == kInputData[inputIdx].inpId) {
+            break;
+        }
+    }
+    if (inputIdx == inputDataSize) {
+        return;
+    }
+    inputFile += kInputData[inputIdx].inputFile;
+    configParam.mime = kInputData[inputIdx].mime;
+    size_t found = configParam.mime.find("audio/");
+    // Check if 'audio/' is present in the begininig of the mime type
+    if (found == 0) {
+        configParam.sampleRate = kInputData[inputIdx].firstParam;
+        configParam.channelCount = kInputData[inputIdx].secondParam;
+    } else {
+        configParam.width = kInputData[inputIdx].firstParam;
+        configParam.height = kInputData[inputIdx].secondParam;
+    }
+    configParam.profile = kInputData[inputIdx].profile;
+    configParam.frameRate = kInputData[inputIdx].frameRate;
+    return;
+}
+
+void randomSeekTest(MediaTrackHelper *track, int64_t clipDuration) {
+    int32_t status = 0;
+    int32_t seekCount = 0;
+    bool hasTimestamp = false;
+    vector<int64_t> seekToTimeStamp;
+    string seekPtsString;
+
+    srand(kRandomSeed);
+    while (seekCount < kMaxCount) {
+        int64_t timeStamp = ((double)rand() / RAND_MAX) * clipDuration;
+        seekToTimeStamp.push_back(timeStamp);
+        seekPtsString.append(to_string(timeStamp));
+        seekPtsString.append(", ");
+        seekCount++;
+    }
+
+    for (int64_t seekPts : seekToTimeStamp) {
+        MediaTrackHelper::ReadOptions *options = new MediaTrackHelper::ReadOptions(
+                CMediaTrackReadOptions::SEEK_CLOSEST | CMediaTrackReadOptions::SEEK, seekPts);
+        ASSERT_NE(options, nullptr) << "Cannot create read option";
+
+        MediaBufferHelper *buffer = nullptr;
+        status = track->read(&buffer, options);
+        if (buffer) {
+            AMediaFormat *metaData = buffer->meta_data();
+            int64_t timeStamp = 0;
+            hasTimestamp = AMediaFormat_getInt64(metaData, AMEDIAFORMAT_KEY_TIME_US, &timeStamp);
+            ASSERT_TRUE(hasTimestamp) << "Extractor didn't set timestamp for the given sample";
+
+            buffer->release();
+            EXPECT_LE(abs(timeStamp - seekPts), kRandomSeekToleranceUs)
+                    << "Seek unsuccessful. Expected timestamp range ["
+                    << seekPts - kRandomSeekToleranceUs << ", " << seekPts + kRandomSeekToleranceUs
+                    << "] "
+                    << "received " << timeStamp << ", list of input seek timestamps ["
+                    << seekPtsString << "]";
+        }
+        delete options;
+    }
+}
+
 void getSeekablePoints(vector<int64_t> &seekablePoints, MediaTrackHelper *track) {
     int32_t status = 0;
     if (!seekablePoints.empty()) {
@@ -190,20 +372,21 @@
     }
 }
 
-TEST_P(ExtractorUnitTest, CreateExtractorTest) {
+TEST_P(ExtractorFunctionalityTest, CreateExtractorTest) {
     if (mDisableTest) return;
 
     ALOGV("Checks if a valid extractor is created for a given input file");
-    string inputFileName = gEnv->getRes() + GetParam().second;
+    string inputFileName = gEnv->getRes() + get<1>(GetParam());
 
-    ASSERT_EQ(setDataSource(inputFileName), 0)
-            << "SetDataSource failed for" << GetParam().first << "extractor";
+    int32_t status = setDataSource(inputFileName);
+    ASSERT_EQ(status, 0) << "SetDataSource failed for" << mContainer << "extractor";
 
-    ASSERT_EQ(createExtractor(), 0)
-            << "Extractor creation failed for" << GetParam().first << "extractor";
+    status = createExtractor();
+    ASSERT_EQ(status, 0) << "Extractor creation failed for" << mContainer << "extractor";
 
-    // A valid extractor instace should return success for following calls
-    ASSERT_GT(mExtractor->countTracks(), 0);
+    int32_t numTracks = mExtractor->countTracks();
+    ASSERT_EQ(numTracks, mNumTracks)
+            << "Extractor reported wrong number of track for the given clip";
 
     AMediaFormat *format = AMediaFormat_new();
     ASSERT_NE(format, nullptr) << "AMediaFormat_new returned null AMediaformat";
@@ -212,20 +395,21 @@
     AMediaFormat_delete(format);
 }
 
-TEST_P(ExtractorUnitTest, ExtractorTest) {
+TEST_P(ExtractorFunctionalityTest, ExtractorTest) {
     if (mDisableTest) return;
 
-    ALOGV("Validates %s Extractor for a given input file", GetParam().first.c_str());
-    string inputFileName = gEnv->getRes() + GetParam().second;
+    ALOGV("Validates %s Extractor for a given input file", mContainer.c_str());
+    string inputFileName = gEnv->getRes() + get<1>(GetParam());
 
     int32_t status = setDataSource(inputFileName);
-    ASSERT_EQ(status, 0) << "SetDataSource failed for" << GetParam().first << "extractor";
+    ASSERT_EQ(status, 0) << "SetDataSource failed for" << mContainer << "extractor";
 
     status = createExtractor();
-    ASSERT_EQ(status, 0) << "Extractor creation failed for" << GetParam().first << "extractor";
+    ASSERT_EQ(status, 0) << "Extractor creation failed for" << mContainer << "extractor";
 
     int32_t numTracks = mExtractor->countTracks();
-    ASSERT_GT(numTracks, 0) << "Extractor didn't find any track for the given clip";
+    ASSERT_EQ(numTracks, mNumTracks)
+            << "Extractor reported wrong number of track for the given clip";
 
     for (int32_t idx = 0; idx < numTracks; idx++) {
         MediaTrackHelper *track = mExtractor->getTrack(idx);
@@ -262,20 +446,21 @@
     }
 }
 
-TEST_P(ExtractorUnitTest, MetaDataComparisonTest) {
+TEST_P(ExtractorFunctionalityTest, MetaDataComparisonTest) {
     if (mDisableTest) return;
 
     ALOGV("Validates Extractor's meta data for a given input file");
-    string inputFileName = gEnv->getRes() + GetParam().second;
+    string inputFileName = gEnv->getRes() + get<1>(GetParam());
 
     int32_t status = setDataSource(inputFileName);
-    ASSERT_EQ(status, 0) << "SetDataSource failed for" << GetParam().first << "extractor";
+    ASSERT_EQ(status, 0) << "SetDataSource failed for" << mContainer << "extractor";
 
     status = createExtractor();
-    ASSERT_EQ(status, 0) << "Extractor creation failed for" << GetParam().first << "extractor";
+    ASSERT_EQ(status, 0) << "Extractor creation failed for" << mContainer << "extractor";
 
     int32_t numTracks = mExtractor->countTracks();
-    ASSERT_GT(numTracks, 0) << "Extractor didn't find any track for the given clip";
+    ASSERT_EQ(numTracks, mNumTracks)
+            << "Extractor reported wrong number of track for the given clip";
 
     AMediaFormat *extractorFormat = AMediaFormat_new();
     ASSERT_NE(extractorFormat, nullptr) << "AMediaFormat_new returned null AMediaformat";
@@ -337,20 +522,21 @@
     AMediaFormat_delete(extractorFormat);
 }
 
-TEST_P(ExtractorUnitTest, MultipleStartStopTest) {
+TEST_P(ExtractorFunctionalityTest, MultipleStartStopTest) {
     if (mDisableTest) return;
 
-    ALOGV("Test %s extractor for multiple start and stop calls", GetParam().first.c_str());
-    string inputFileName = gEnv->getRes() + GetParam().second;
+    ALOGV("Test %s extractor for multiple start and stop calls", mContainer.c_str());
+    string inputFileName = gEnv->getRes() + get<1>(GetParam());
 
     int32_t status = setDataSource(inputFileName);
-    ASSERT_EQ(status, 0) << "SetDataSource failed for" << GetParam().first << "extractor";
+    ASSERT_EQ(status, 0) << "SetDataSource failed for" << mContainer << "extractor";
 
     status = createExtractor();
-    ASSERT_EQ(status, 0) << "Extractor creation failed for" << GetParam().first << "extractor";
+    ASSERT_EQ(status, 0) << "Extractor creation failed for" << mContainer << "extractor";
 
     int32_t numTracks = mExtractor->countTracks();
-    ASSERT_GT(numTracks, 0) << "Extractor didn't find any track for the given clip";
+    ASSERT_EQ(numTracks, mNumTracks)
+            << "Extractor reported wrong number of track for the given clip";
 
     // start/stop the tracks multiple times
     for (int32_t count = 0; count < kMaxCount; count++) {
@@ -379,27 +565,28 @@
     }
 }
 
-TEST_P(ExtractorUnitTest, SeekTest) {
-    // Both Flac and Wav extractor can give samples from any pts and mark the given sample as
-    // sync frame. So, this seek test is not applicable to FLAC and WAV extractors
-    if (mDisableTest || mExtractorName == FLAC || mExtractorName == WAV) return;
+TEST_P(ExtractorFunctionalityTest, SeekTest) {
+    if (mDisableTest) return;
 
-    ALOGV("Validates %s Extractor behaviour for different seek modes", GetParam().first.c_str());
-    string inputFileName = gEnv->getRes() + GetParam().second;
+    ALOGV("Validates %s Extractor behaviour for different seek modes", mContainer.c_str());
+    string inputFileName = gEnv->getRes() + get<1>(GetParam());
 
     int32_t status = setDataSource(inputFileName);
-    ASSERT_EQ(status, 0) << "SetDataSource failed for" << GetParam().first << "extractor";
+    ASSERT_EQ(status, 0) << "SetDataSource failed for" << mContainer << "extractor";
 
     status = createExtractor();
-    ASSERT_EQ(status, 0) << "Extractor creation failed for" << GetParam().first << "extractor";
+    ASSERT_EQ(status, 0) << "Extractor creation failed for" << mContainer << "extractor";
 
     int32_t numTracks = mExtractor->countTracks();
-    ASSERT_GT(numTracks, 0) << "Extractor didn't find any track for the given clip";
+    ASSERT_EQ(numTracks, mNumTracks)
+            << "Extractor reported wrong number of track for the given clip";
 
     uint32_t seekFlag = mExtractor->flags();
-    if (!(seekFlag & MediaExtractorPluginHelper::CAN_SEEK)) {
-        cout << "[   WARN   ] Test Skipped. " << GetParam().first
-             << " Extractor doesn't support seek\n";
+    bool seekSupported = get<3>(GetParam());
+    bool seekable = seekFlag & MediaExtractorPluginHelper::CAN_SEEK;
+    if (!seekable) {
+        ASSERT_FALSE(seekSupported) << mContainer << "Extractor is expected to support seek ";
+        cout << "[   WARN   ] Test Skipped. " << mContainer << " Extractor doesn't support seek\n";
         return;
     }
 
@@ -415,19 +602,73 @@
         MediaBufferGroup *bufferGroup = new MediaBufferGroup();
         status = cTrack->start(track, bufferGroup->wrap());
         ASSERT_EQ(OK, (media_status_t)status) << "Failed to start the track";
-        getSeekablePoints(seekablePoints, track);
-        ASSERT_GT(seekablePoints.size(), 0)
-                << "Failed to get seekable points for " << GetParam().first << " extractor";
+
+        // For Flac, Wav and Midi extractor, all samples are seek points.
+        // We cannot create list of all seekable points for these.
+        // This means that if we pass a seekToTimeStamp between two seek points, we may
+        // end up getting the timestamp of next sample as a seekable timestamp.
+        // This timestamp may/may not be a part of the seekable point vector thereby failing the
+        // test. So we test these extractors using random seek test.
+        if (mExtractorName == FLAC || mExtractorName == WAV || mExtractorName == MIDI) {
+            AMediaFormat *trackMeta = AMediaFormat_new();
+            ASSERT_NE(trackMeta, nullptr) << "AMediaFormat_new returned null AMediaformat";
+
+            status = mExtractor->getTrackMetaData(trackMeta, idx, 1);
+            ASSERT_EQ(OK, (media_status_t)status) << "Failed to get trackMetaData";
+
+            int64_t clipDuration = 0;
+            AMediaFormat_getInt64(trackMeta, AMEDIAFORMAT_KEY_DURATION, &clipDuration);
+            ASSERT_GT(clipDuration, 0) << "Invalid clip duration ";
+            randomSeekTest(track, clipDuration);
+            AMediaFormat_delete(trackMeta);
+            continue;
+        }
 
         AMediaFormat *trackFormat = AMediaFormat_new();
         ASSERT_NE(trackFormat, nullptr) << "AMediaFormat_new returned null format";
         status = track->getFormat(trackFormat);
         ASSERT_EQ(OK, (media_status_t)status) << "Failed to get track meta data";
 
-        bool isOpus = false;
         const char *mime;
-        AMediaFormat_getString(trackFormat, AMEDIAFORMAT_KEY_MIME, &mime);
-        if (!strcmp(mime, "audio/opus")) isOpus = true;
+        ASSERT_TRUE(AMediaFormat_getString(trackFormat, AMEDIAFORMAT_KEY_MIME, &mime))
+                << "Failed to get mime";
+
+        // Image formats are not expected to be seekable
+        if (!strncmp(mime, "image/", 6)) continue;
+
+        // Request seekable points for remaining extractors which will be used to validate the seek
+        // accuracy for the extractors. Depending on SEEK Mode, we expect the extractors to return
+        // the expected sync frame. We don't prefer random seek test for these extractors because
+        // they aren't expected to seek to random samples. MP4 for instance can seek to
+        // next/previous sync frames but not to samples between two sync frames.
+        getSeekablePoints(seekablePoints, track);
+        ASSERT_GT(seekablePoints.size(), 0)
+                << "Failed to get seekable points for " << mContainer << " extractor";
+
+        bool isOpus = false;
+        int64_t opusSeekPreRollUs = 0;
+        if (!strcmp(mime, "audio/opus")) {
+            isOpus = true;
+            void *seekPreRollBuf = nullptr;
+            size_t size = 0;
+            if (!AMediaFormat_getBuffer(trackFormat, "csd-2", &seekPreRollBuf, &size)) {
+                size_t opusHeadSize = 0;
+                size_t codecDelayBufSize = 0;
+                size_t seekPreRollBufSize = 0;
+                void *csdBuffer = nullptr;
+                void *opusHeadBuf = nullptr;
+                void *codecDelayBuf = nullptr;
+                AMediaFormat_getBuffer(trackFormat, "csd-0", &csdBuffer, &size);
+                ASSERT_NE(csdBuffer, nullptr);
+
+                GetOpusHeaderBuffers((uint8_t *)csdBuffer, size, &opusHeadBuf, &opusHeadSize,
+                                     &codecDelayBuf, &codecDelayBufSize, &seekPreRollBuf,
+                                     &seekPreRollBufSize);
+            }
+            ASSERT_NE(seekPreRollBuf, nullptr)
+                    << "Invalid track format. SeekPreRoll info missing for Opus file";
+            opusSeekPreRollUs = *((int64_t *)seekPreRollBuf);
+        }
         AMediaFormat_delete(trackFormat);
 
         int32_t seekIdx = 0;
@@ -448,7 +689,7 @@
                 // extractor is calculated based on (seekPts - seekPreRollUs).
                 // So we add the preRoll value to the timeStamp we want to seek to.
                 if (isOpus) {
-                    seekToTimeStamp += kOpusSeekPreRollUs;
+                    seekToTimeStamp += opusSeekPreRollUs;
                 }
 
                 MediaTrackHelper::ReadOptions *options = new MediaTrackHelper::ReadOptions(
@@ -496,24 +737,517 @@
     seekablePoints.clear();
 }
 
-// TODO: (b/145332185)
-// Add MIDI inputs
-INSTANTIATE_TEST_SUITE_P(ExtractorUnitTestAll, ExtractorUnitTest,
-                         ::testing::Values(make_pair("aac", "loudsoftaac.aac"),
-                                           make_pair("amr", "testamr.amr"),
-                                           make_pair("amr", "amrwb.wav"),
-                                           make_pair("ogg", "john_cage.ogg"),
-                                           make_pair("wav", "monotestgsm.wav"),
-                                           make_pair("mpeg2ts", "segment000001.ts"),
-                                           make_pair("flac", "sinesweepflac.flac"),
-                                           make_pair("ogg", "testopus.opus"),
-                                           make_pair("mkv", "sinesweepvorbis.mkv"),
-                                           make_pair("mpeg4", "sinesweepoggmp4.mp4"),
-                                           make_pair("mp3", "sinesweepmp3lame.mp3"),
-                                           make_pair("mkv", "swirl_144x136_vp9.webm"),
-                                           make_pair("mkv", "swirl_144x136_vp8.webm"),
-                                           make_pair("mpeg2ps", "swirl_144x136_mpeg2.mpg"),
-                                           make_pair("mpeg4", "swirl_132x130_mpeg4.mp4")));
+// Tests the extractors for seek beyond range : (0, ClipDuration)
+TEST_P(ExtractorFunctionalityTest, MonkeySeekTest) {
+    if (mDisableTest) return;
+    // TODO(b/155630778): Enable test for wav extractors
+    if (mExtractorName == WAV) return;
+
+    ALOGV("Validates %s Extractor behaviour for invalid seek points", mContainer.c_str());
+    string inputFileName = gEnv->getRes() + get<1>(GetParam());
+
+    int32_t status = setDataSource(inputFileName);
+    ASSERT_EQ(status, 0) << "SetDataSource failed for" << mContainer << "extractor";
+
+    status = createExtractor();
+    ASSERT_EQ(status, 0) << "Extractor creation failed for" << mContainer << "extractor";
+
+    int32_t numTracks = mExtractor->countTracks();
+    ASSERT_EQ(numTracks, mNumTracks)
+            << "Extractor reported wrong number of track for the given clip";
+
+    uint32_t seekFlag = mExtractor->flags();
+    bool seekSupported = get<3>(GetParam());
+    bool seekable = seekFlag & MediaExtractorPluginHelper::CAN_SEEK;
+    if (!seekable) {
+        ASSERT_FALSE(seekSupported) << mContainer << "Extractor is expected to support seek ";
+        cout << "[   WARN   ] Test Skipped. " << mContainer << " Extractor doesn't support seek\n";
+        return;
+    }
+
+    for (int32_t idx = 0; idx < numTracks; idx++) {
+        MediaTrackHelper *track = mExtractor->getTrack(idx);
+        ASSERT_NE(track, nullptr) << "Failed to get track for index " << idx;
+
+        CMediaTrack *cTrack = wrap(track);
+        ASSERT_NE(cTrack, nullptr) << "Failed to get track wrapper for index " << idx;
+
+        MediaBufferGroup *bufferGroup = new MediaBufferGroup();
+        status = cTrack->start(track, bufferGroup->wrap());
+        ASSERT_EQ(OK, (media_status_t)status) << "Failed to start the track";
+
+        AMediaFormat *trackMeta = AMediaFormat_new();
+        ASSERT_NE(trackMeta, nullptr) << "AMediaFormat_new returned null AMediaformat";
+
+        status = mExtractor->getTrackMetaData(
+                trackMeta, idx, MediaExtractorPluginHelper::kIncludeExtensiveMetaData);
+        ASSERT_EQ(OK, (media_status_t)status) << "Failed to get trackMetaData";
+
+        const char *mime;
+        ASSERT_TRUE(AMediaFormat_getString(trackMeta, AMEDIAFORMAT_KEY_MIME, &mime))
+                << "Failed to get mime";
+
+        int64_t clipDuration = 0;
+        AMediaFormat_getInt64(trackMeta, AMEDIAFORMAT_KEY_DURATION, &clipDuration);
+        // Image formats are not expected to have duration information
+        ASSERT_TRUE(clipDuration > 0 || !strncmp(mime, "image/", 6)) << "Invalid clip duration ";
+        AMediaFormat_delete(trackMeta);
+
+        int64_t seekToTimeStampUs[] = {-clipDuration, clipDuration / 2, clipDuration,
+                                       clipDuration * 2};
+        for (int32_t mode = CMediaTrackReadOptions::SEEK_PREVIOUS_SYNC;
+             mode <= CMediaTrackReadOptions::SEEK_CLOSEST; mode++) {
+            for (int64_t seekTimeUs : seekToTimeStampUs) {
+                MediaTrackHelper::ReadOptions *options = new MediaTrackHelper::ReadOptions(
+                        mode | CMediaTrackReadOptions::SEEK, seekTimeUs);
+                ASSERT_NE(options, nullptr) << "Cannot create read option";
+
+                MediaBufferHelper *buffer = nullptr;
+                status = track->read(&buffer, options);
+                if (status == AMEDIA_ERROR_END_OF_STREAM) {
+                    delete options;
+                    continue;
+                }
+                if (buffer) {
+                    AMediaFormat *metaData = buffer->meta_data();
+                    int64_t timeStamp;
+                    AMediaFormat_getInt64(metaData, AMEDIAFORMAT_KEY_TIME_US, &timeStamp);
+                    ALOGV("Seeked to timestamp : %lld, requested : %lld", (long long)timeStamp,
+                          (long long)seekTimeUs);
+                    buffer->release();
+                }
+                delete options;
+            }
+        }
+        status = cTrack->stop(track);
+        ASSERT_EQ(OK, status) << "Failed to stop the track";
+        delete bufferGroup;
+        delete track;
+    }
+}
+
+// Tests extractors for invalid tracks
+TEST_P(ExtractorFunctionalityTest, SanityTest) {
+    if (mDisableTest) return;
+    // TODO(b/155626946): Enable test for MPEG2 TS/PS extractors
+    if (mExtractorName == MPEG2TS || mExtractorName == MPEG2PS) return;
+
+    ALOGV("Validates %s Extractor behaviour for invalid tracks", mContainer.c_str());
+    string inputFileName = gEnv->getRes() + get<1>(GetParam());
+
+    int32_t status = setDataSource(inputFileName);
+    ASSERT_EQ(status, 0) << "SetDataSource failed for" << mContainer << "extractor";
+
+    status = createExtractor();
+    ASSERT_EQ(status, 0) << "Extractor creation failed for" << mContainer << "extractor";
+
+    int32_t numTracks = mExtractor->countTracks();
+    ASSERT_EQ(numTracks, mNumTracks)
+            << "Extractor reported wrong number of track for the given clip";
+
+    int32_t trackIdx[] = {-1, numTracks};
+    for (int32_t idx : trackIdx) {
+        MediaTrackHelper *track = mExtractor->getTrack(idx);
+        ASSERT_EQ(track, nullptr) << "Failed to get track for index " << idx << "\n";
+
+        AMediaFormat *extractorFormat = AMediaFormat_new();
+        ASSERT_NE(extractorFormat, nullptr) << "AMediaFormat_new returned null AMediaformat";
+
+        status = mExtractor->getTrackMetaData(
+                extractorFormat, idx, MediaExtractorPluginHelper::kIncludeExtensiveMetaData);
+        ASSERT_NE(OK, status) << "getTrackMetaData should return error for invalid index " << idx;
+        AMediaFormat_delete(extractorFormat);
+    }
+
+    // Validate Extractor's getTrackMetaData for null format
+    AMediaFormat *mediaFormat = nullptr;
+    status = mExtractor->getTrackMetaData(mediaFormat, 0,
+                                          MediaExtractorPluginHelper::kIncludeExtensiveMetaData);
+    ASSERT_NE(OK, status) << "getTrackMetaData should return error for null Media format";
+}
+
+// This test validates config params for a given input file.
+// For this test we only take single track files since the focus of this test is
+// to validate the file properties reported by Extractor and not multi-track behavior
+TEST_P(ConfigParamTest, ConfigParamValidation) {
+    if (mDisableTest) return;
+
+    string container = GetParam().first;
+    ALOGV("Validates %s Extractor for input's file properties", container.c_str());
+    string inputFileName = gEnv->getRes();
+    inputID inputFileId = GetParam().second;
+    configFormat configParam;
+    getFileProperties(inputFileId, inputFileName, configParam);
+
+    int32_t status = setDataSource(inputFileName);
+    ASSERT_EQ(status, 0) << "SetDataSource failed for " << container << "extractor";
+
+    status = createExtractor();
+    ASSERT_EQ(status, 0) << "Extractor creation failed for " << container << "extractor";
+
+    int32_t numTracks = mExtractor->countTracks();
+    ASSERT_GT(numTracks, 0) << "Extractor didn't find any track for the given clip";
+
+    MediaTrackHelper *track = mExtractor->getTrack(0);
+    ASSERT_NE(track, nullptr) << "Failed to get track for index 0";
+
+    AMediaFormat *trackFormat = AMediaFormat_new();
+    ASSERT_NE(trackFormat, nullptr) << "AMediaFormat_new returned null format";
+
+    status = track->getFormat(trackFormat);
+    ASSERT_EQ(OK, (media_status_t)status) << "Failed to get track meta data";
+
+    const char *trackMime;
+    bool valueFound = AMediaFormat_getString(trackFormat, AMEDIAFORMAT_KEY_MIME, &trackMime);
+    ASSERT_TRUE(valueFound) << "Mime type not set by extractor";
+    ASSERT_STREQ(configParam.mime.c_str(), trackMime) << "Invalid track format";
+
+    if (!strncmp(trackMime, "audio/", 6)) {
+        int32_t trackSampleRate, trackChannelCount;
+        ASSERT_TRUE(AMediaFormat_getInt32(trackFormat, AMEDIAFORMAT_KEY_CHANNEL_COUNT,
+                                          &trackChannelCount));
+        ASSERT_TRUE(
+                AMediaFormat_getInt32(trackFormat, AMEDIAFORMAT_KEY_SAMPLE_RATE, &trackSampleRate));
+        ASSERT_EQ(configParam.sampleRate, trackSampleRate) << "SampleRate not as expected";
+        ASSERT_EQ(configParam.channelCount, trackChannelCount) << "ChannelCount not as expected";
+    } else {
+        int32_t trackWidth, trackHeight;
+        ASSERT_TRUE(AMediaFormat_getInt32(trackFormat, AMEDIAFORMAT_KEY_WIDTH, &trackWidth));
+        ASSERT_TRUE(AMediaFormat_getInt32(trackFormat, AMEDIAFORMAT_KEY_HEIGHT, &trackHeight));
+        ASSERT_EQ(configParam.width, trackWidth) << "Width not as expected";
+        ASSERT_EQ(configParam.height, trackHeight) << "Height not as expected";
+
+        if (configParam.frameRate != kUndefined) {
+            int32_t frameRate;
+            ASSERT_TRUE(
+                    AMediaFormat_getInt32(trackFormat, AMEDIAFORMAT_KEY_FRAME_RATE, &frameRate));
+            ASSERT_EQ(configParam.frameRate, frameRate) << "frameRate not as expected";
+        }
+    }
+    // validate the profile for the input clip
+    int32_t profile;
+    if (configParam.profile != kUndefined) {
+        if (AMediaFormat_getInt32(trackFormat, AMEDIAFORMAT_KEY_PROFILE, &profile)) {
+            ASSERT_EQ(configParam.profile, profile) << "profile not as expected";
+        } else if (mExtractorName == AAC &&
+                   AMediaFormat_getInt32(trackFormat, AMEDIAFORMAT_KEY_AAC_PROFILE, &profile)) {
+            ASSERT_EQ(configParam.profile, profile) << "profile not as expected";
+        } else {
+            ASSERT_TRUE(false) << "profile not returned in extractor";
+        }
+    }
+
+    delete track;
+    AMediaFormat_delete(trackFormat);
+}
+
+class ExtractorComparison
+    : public ExtractorUnitTest,
+      public ::testing::TestWithParam<pair<string /* InputFile0 */, string /* InputFile1 */>> {
+  public:
+    ~ExtractorComparison() {
+        for (int8_t *extractorOp : mExtractorOutput) {
+            if (extractorOp != nullptr) {
+                free(extractorOp);
+            }
+        }
+    }
+
+    int8_t *mExtractorOutput[2]{};
+    size_t mExtractorOuputSize[2]{};
+};
+
+size_t allocateOutputBuffers(string inputFileName, AMediaFormat *extractorFormat) {
+    size_t bufferSize = 0u;
+    // allocating the buffer size as sampleRate * channelCount * clipDuration since
+    // some extractors like flac, midi and wav decodes the file. These extractors
+    // advertise the mime type as raw.
+    const char *mime;
+    AMediaFormat_getString(extractorFormat, AMEDIAFORMAT_KEY_MIME, &mime);
+    if (!strcmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) {
+        int64_t clipDurationUs = -1;
+        int32_t channelCount = -1;
+        int32_t sampleRate = -1;
+        int32_t bitsPerSampple = -1;
+        if (!AMediaFormat_getInt32(extractorFormat, AMEDIAFORMAT_KEY_CHANNEL_COUNT,
+                                   &channelCount) || channelCount <= 0) {
+            ALOGE("Invalid channelCount for input file : %s", inputFileName.c_str());
+            return 0;
+        }
+        if (!AMediaFormat_getInt32(extractorFormat, AMEDIAFORMAT_KEY_SAMPLE_RATE, &sampleRate) ||
+            sampleRate <= 0) {
+            ALOGE("Invalid sampleRate for input file : %s", inputFileName.c_str());
+            return 0;
+        }
+        if (!AMediaFormat_getInt64(extractorFormat, AMEDIAFORMAT_KEY_DURATION, &clipDurationUs) ||
+            clipDurationUs <= 0) {
+            ALOGE("Invalid clip duration for input file : %s", inputFileName.c_str());
+            return 0;
+        }
+        if (!AMediaFormat_getInt32(extractorFormat, AMEDIAFORMAT_KEY_PCM_ENCODING,
+                                   &bitsPerSampple) || bitsPerSampple <= 0) {
+            ALOGE("Invalid bits per sample for input file : %s", inputFileName.c_str());
+            return 0;
+        }
+        bufferSize = bitsPerSampple * channelCount * sampleRate * (clipDurationUs / 1000000 + 1);
+    } else {
+        struct stat buf;
+        int32_t status = stat(inputFileName.c_str(), &buf);
+        if (status != 0) {
+            ALOGE("Unable to get file properties for: %s", inputFileName.c_str());
+            return 0;
+        }
+        bufferSize = buf.st_size;
+    }
+    return bufferSize;
+}
+
+// Compare output of two extractors for identical content
+TEST_P(ExtractorComparison, ExtractorComparisonTest) {
+    vector<string> inputFileNames = {GetParam().first, GetParam().second};
+    size_t extractedOutputSize[2]{};
+    AMediaFormat *extractorFormat[2]{};
+    int32_t status = OK;
+
+    for (int32_t idx = 0; idx < inputFileNames.size(); idx++) {
+        string containerFormat = inputFileNames[idx].substr(inputFileNames[idx].find(".") + 1);
+        setupExtractor(containerFormat);
+        if (mDisableTest) {
+            ALOGV("Unknown extractor %s. Skipping the test", containerFormat.c_str());
+            return;
+        }
+
+        ALOGV("Validates %s Extractor for %s", containerFormat.c_str(),
+              inputFileNames[idx].c_str());
+        string inputFileName = gEnv->getRes() + inputFileNames[idx];
+
+        status = setDataSource(inputFileName);
+        ASSERT_EQ(status, 0) << "SetDataSource failed for" << containerFormat << "extractor";
+
+        status = createExtractor();
+        ASSERT_EQ(status, 0) << "Extractor creation failed for " << containerFormat << " extractor";
+
+        int32_t numTracks = mExtractor->countTracks();
+        ASSERT_EQ(numTracks, 1) << "This test expects inputs with one track only";
+
+        int32_t trackIdx = 0;
+        MediaTrackHelper *track = mExtractor->getTrack(trackIdx);
+        ASSERT_NE(track, nullptr) << "Failed to get track for index " << trackIdx;
+
+        extractorFormat[idx] = AMediaFormat_new();
+        ASSERT_NE(extractorFormat[idx], nullptr) << "AMediaFormat_new returned null AMediaformat";
+
+        status = track->getFormat(extractorFormat[idx]);
+        ASSERT_EQ(OK, (media_status_t)status) << "Failed to get track meta data";
+
+        CMediaTrack *cTrack = wrap(track);
+        ASSERT_NE(cTrack, nullptr) << "Failed to get track wrapper for index " << trackIdx;
+
+        mExtractorOuputSize[idx] = allocateOutputBuffers(inputFileName, extractorFormat[idx]);
+        ASSERT_GT(mExtractorOuputSize[idx], 0u) << " Invalid size for output buffers";
+
+        mExtractorOutput[idx] = (int8_t *)calloc(1, mExtractorOuputSize[idx]);
+        ASSERT_NE(mExtractorOutput[idx], nullptr)
+                << "Unable to allocate memory for writing extractor's output";
+
+        MediaBufferGroup *bufferGroup = new MediaBufferGroup();
+        status = cTrack->start(track, bufferGroup->wrap());
+        ASSERT_EQ(OK, (media_status_t)status) << "Failed to start the track";
+
+        int32_t offset = 0;
+        while (status != AMEDIA_ERROR_END_OF_STREAM) {
+            MediaBufferHelper *buffer = nullptr;
+            status = track->read(&buffer);
+            ALOGV("track->read Status = %d buffer %p", status, buffer);
+            if (buffer) {
+                ASSERT_LE(offset + buffer->range_length(), mExtractorOuputSize[idx])
+                        << "Memory overflow. Extracted output size more than expected";
+
+                memcpy(mExtractorOutput[idx] + offset, buffer->data(), buffer->range_length());
+                extractedOutputSize[idx] += buffer->range_length();
+                offset += buffer->range_length();
+                buffer->release();
+            }
+        }
+        status = cTrack->stop(track);
+        ASSERT_EQ(OK, status) << "Failed to stop the track";
+
+        fclose(mInputFp);
+        delete bufferGroup;
+        delete track;
+        mDataSource.clear();
+        delete mExtractor;
+        mInputFp = nullptr;
+        mExtractor = nullptr;
+    }
+
+    // Compare the meta data from both the extractors
+    const char *mime[2];
+    AMediaFormat_getString(extractorFormat[0], AMEDIAFORMAT_KEY_MIME, &mime[0]);
+    AMediaFormat_getString(extractorFormat[1], AMEDIAFORMAT_KEY_MIME, &mime[1]);
+    ASSERT_STREQ(mime[0], mime[1]) << "Mismatch between extractor's format";
+
+    if (!strncmp(mime[0], "audio/", 6)) {
+        int32_t channelCount0, channelCount1;
+        int32_t sampleRate0, sampleRate1;
+        ASSERT_TRUE(AMediaFormat_getInt32(extractorFormat[0], AMEDIAFORMAT_KEY_CHANNEL_COUNT,
+                                          &channelCount0));
+        ASSERT_TRUE(AMediaFormat_getInt32(extractorFormat[0], AMEDIAFORMAT_KEY_SAMPLE_RATE,
+                                          &sampleRate0));
+        ASSERT_TRUE(AMediaFormat_getInt32(extractorFormat[1], AMEDIAFORMAT_KEY_CHANNEL_COUNT,
+                                          &channelCount1));
+        ASSERT_TRUE(AMediaFormat_getInt32(extractorFormat[1], AMEDIAFORMAT_KEY_SAMPLE_RATE,
+                                          &sampleRate1));
+        ASSERT_EQ(channelCount0, channelCount1) << "Mismatch between extractor's channelCount";
+        ASSERT_EQ(sampleRate0, sampleRate1) << "Mismatch between extractor's sampleRate";
+    } else if (!strncmp(mime[0], "video/", 6)) {
+        int32_t width0, height0;
+        int32_t width1, height1;
+        ASSERT_TRUE(AMediaFormat_getInt32(extractorFormat[0], AMEDIAFORMAT_KEY_WIDTH, &width0));
+        ASSERT_TRUE(AMediaFormat_getInt32(extractorFormat[0], AMEDIAFORMAT_KEY_HEIGHT, &height0));
+        ASSERT_TRUE(AMediaFormat_getInt32(extractorFormat[1], AMEDIAFORMAT_KEY_WIDTH, &width1));
+        ASSERT_TRUE(AMediaFormat_getInt32(extractorFormat[1], AMEDIAFORMAT_KEY_HEIGHT, &height1));
+        ASSERT_EQ(width0, width1) << "Mismatch between extractor's width";
+        ASSERT_EQ(height0, height1) << "Mismatch between extractor's height";
+    } else {
+        ASSERT_TRUE(false) << "Invalid mime type " << mime[0];
+    }
+
+    for (AMediaFormat *exFormat : extractorFormat) {
+        AMediaFormat_delete(exFormat);
+    }
+
+    // Compare the extracted outputs of both extractor
+    ASSERT_EQ(extractedOutputSize[0], extractedOutputSize[1])
+            << "Extractor's output size doesn't match between " << inputFileNames[0] << "and "
+            << inputFileNames[1] << " extractors";
+    status = memcmp(mExtractorOutput[0], mExtractorOutput[1], extractedOutputSize[0]);
+    ASSERT_EQ(status, 0) << "Extracted content mismatch between " << inputFileNames[0] << "and "
+                         << inputFileNames[1] << " extractors";
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        ExtractorComparisonAll, ExtractorComparison,
+        ::testing::Values(make_pair("swirl_144x136_vp9.mp4", "swirl_144x136_vp9.webm"),
+                          make_pair("video_480x360_mp4_vp9_333kbps_25fps.mp4",
+                                    "video_480x360_webm_vp9_333kbps_25fps.webm"),
+                          make_pair("video_1280x720_av1_hdr_static_3mbps.mp4",
+                                    "video_1280x720_av1_hdr_static_3mbps.webm"),
+                          make_pair("swirl_132x130_mpeg4.3gp", "swirl_132x130_mpeg4.mkv"),
+                          make_pair("swirl_144x136_avc.mkv", "swirl_144x136_avc.mp4"),
+                          make_pair("swirl_132x130_mpeg4.mp4", "swirl_132x130_mpeg4.mkv"),
+                          make_pair("crowd_508x240_25fps_hevc.mp4","crowd_508x240_25fps_hevc.mkv"),
+                          make_pair("bbb_cif_768kbps_30fps_mpeg2.mp4",
+                                    "bbb_cif_768kbps_30fps_mpeg2.ts"),
+
+                          make_pair("loudsoftaac.aac", "loudsoftaac.mkv"),
+                          make_pair("sinesweepflacmkv.mkv", "sinesweepflacmp4.mp4"),
+                          make_pair("sinesweepmp3lame.mp3", "sinesweepmp3lame.mkv"),
+                          make_pair("sinesweepoggmp4.mp4", "sinesweepogg.ogg"),
+                          make_pair("sinesweepvorbis.mp4", "sinesweepvorbis.ogg"),
+                          make_pair("sinesweepvorbis.mkv", "sinesweepvorbis.ogg"),
+                          make_pair("testopus.mkv", "testopus.mp4"),
+                          make_pair("testopus.mp4", "testopus.opus"),
+
+                          make_pair("loudsoftaac.aac", "loudsoftaac.aac"),
+                          make_pair("testamr.amr", "testamr.amr"),
+                          make_pair("sinesweepflac.flac", "sinesweepflac.flac"),
+                          make_pair("midi_a.mid", "midi_a.mid"),
+                          make_pair("sinesweepvorbis.mkv", "sinesweepvorbis.mkv"),
+                          make_pair("sinesweepmp3lame.mp3", "sinesweepmp3lame.mp3"),
+                          make_pair("sinesweepoggmp4.mp4", "sinesweepoggmp4.mp4"),
+                          make_pair("testopus.opus", "testopus.opus"),
+                          make_pair("john_cage.ogg", "john_cage.ogg"),
+                          make_pair("monotestgsm.wav", "monotestgsm.wav"),
+
+                          make_pair("swirl_144x136_mpeg2.mpg", "swirl_144x136_mpeg2.mpg"),
+                          make_pair("swirl_132x130_mpeg4.mp4", "swirl_132x130_mpeg4.mp4"),
+                          make_pair("swirl_144x136_vp9.webm", "swirl_144x136_vp9.webm"),
+                          make_pair("swirl_144x136_vp8.webm", "swirl_144x136_vp8.webm")));
+
+INSTANTIATE_TEST_SUITE_P(ConfigParamTestAll, ConfigParamTest,
+                         ::testing::Values(make_pair("aac", AAC_1),
+                                           make_pair("amr", AMR_NB_1),
+                                           make_pair("amr", AMR_WB_1),
+                                           make_pair("flac", FLAC_1),
+                                           make_pair("wav", GSM_1),
+                                           make_pair("midi", MIDI_1),
+                                           make_pair("mp3", MP3_1),
+                                           make_pair("ogg", OPUS_1),
+                                           make_pair("ogg", VORBIS_1),
+
+                                           make_pair("mpeg4", HEVC_1),
+                                           make_pair("mpeg4", HEVC_2),
+                                           make_pair("mpeg2ps", MPEG2_PS_1),
+                                           make_pair("mpeg2ts", MPEG2_TS_1),
+                                           make_pair("mkv", MPEG4_1),
+                                           make_pair("mkv", VP9_1)));
+
+// Validate extractors for container format, input file, no. of tracks and supports seek flag
+INSTANTIATE_TEST_SUITE_P(
+        ExtractorUnitTestAll, ExtractorFunctionalityTest,
+        ::testing::Values(
+                make_tuple("aac", "loudsoftaac.aac", 1, true),
+                make_tuple("amr", "testamr.amr", 1, true),
+                make_tuple("amr", "amrwb.wav", 1, true),
+                make_tuple("flac", "sinesweepflac.flac", 1, true),
+                make_tuple("midi", "midi_a.mid", 1, true),
+                make_tuple("mkv", "sinesweepvorbis.mkv", 1, true),
+                make_tuple("mkv", "sinesweepmp3lame.mkv", 1, true),
+                make_tuple("mkv", "loudsoftaac.mkv", 1, true),
+                make_tuple("mp3", "sinesweepmp3lame.mp3", 1, true),
+                make_tuple("mp3", "id3test10.mp3", 1, true),
+                make_tuple("mpeg2ts", "segment000001.ts", 2, false),
+                make_tuple("mpeg2ts", "testac3ts.ts", 1, false),
+                make_tuple("mpeg2ts", "testac4ts.ts", 1, false),
+                make_tuple("mpeg2ts", "testeac3ts.ts", 1, false),
+                make_tuple("mpeg4", "audio_aac_mono_70kbs_44100hz.mp4", 2, true),
+                make_tuple("mpeg4", "multi0_ac4.mp4", 1, true),
+                make_tuple("mpeg4", "noise_6ch_44khz_aot5_dr_sbr_sig2_mp4.m4a", 1, true),
+                make_tuple("mpeg4", "sinesweepalac.mov", 1, true),
+                make_tuple("mpeg4", "sinesweepflacmp4.mp4", 1, true),
+                make_tuple("mpeg4", "sinesweepm4a.m4a", 1, true),
+                make_tuple("mpeg4", "sinesweepoggmp4.mp4", 1, true),
+                make_tuple("mpeg4", "sinesweepopusmp4.mp4", 1, true),
+                make_tuple("mpeg4", "testac3mp4.mp4", 1, true),
+                make_tuple("mpeg4", "testeac3mp4.mp4", 1, true),
+                make_tuple("ogg", "john_cage.ogg", 1, true),
+                make_tuple("ogg", "testopus.opus", 1, true),
+                make_tuple("ogg", "sinesweepoggalbumart.ogg", 1, true),
+                make_tuple("wav", "loudsoftwav.wav", 1, true),
+                make_tuple("wav", "monotestgsm.wav", 1, true),
+                make_tuple("wav", "noise_5ch_44khz_aot2_wave.wav", 1, true),
+                make_tuple("wav", "sine1khzm40db_alaw.wav", 1, true),
+                make_tuple("wav", "sine1khzm40db_f32le.wav", 1, true),
+                make_tuple("wav", "sine1khzm40db_mulaw.wav", 1, true),
+
+                make_tuple("mkv", "swirl_144x136_avc.mkv", 1, true),
+                make_tuple("mkv", "withoutcues.mkv", 2, true),
+                make_tuple("mkv", "swirl_144x136_vp9.webm", 1, true),
+                make_tuple("mkv", "swirl_144x136_vp8.webm", 1, true),
+                make_tuple("mpeg2ps", "swirl_144x136_mpeg2.mpg", 1, false),
+                make_tuple("mpeg2ps", "programstream.mpeg", 2, false),
+                make_tuple("mpeg4", "color_176x144_bt601_525_lr_sdr_h264.mp4", 1, true),
+                make_tuple("mpeg4", "heifwriter_input.heic", 4, false),
+                make_tuple("mpeg4", "psshtest.mp4", 1, true),
+                make_tuple("mpeg4", "swirl_132x130_mpeg4.mp4", 1, true),
+                make_tuple("mpeg4", "testvideo.3gp", 4, true),
+                make_tuple("mpeg4", "testvideo_with_2_timedtext_tracks.3gp", 4, true),
+                make_tuple("mpeg4",
+                           "video_176x144_3gp_h263_300kbps_25fps_aac_stereo_128kbps_11025hz_"
+                           "metadata_gyro_compliant.3gp",
+                           3, true),
+                make_tuple(
+                        "mpeg4",
+                        "video_1920x1080_mp4_mpeg2_12000kbps_30fps_aac_stereo_128kbps_48000hz.mp4",
+                        2, true),
+                make_tuple("mpeg4",
+                           "video_480x360_mp4_hevc_650kbps_30fps_aac_stereo_128kbps_48000hz.mp4", 2,
+                           true),
+                make_tuple(
+                        "mpeg4",
+                        "video_480x360_mp4_h264_1350kbps_30fps_aac_stereo_128kbps_44100hz_dash.mp4",
+                        2, true)));
 
 int main(int argc, char **argv) {
     gEnv = new ExtractorUnitTestEnvironment();
diff --git a/media/extractors/tests/README.md b/media/extractors/tests/README.md
index 69538b6..cff09ca 100644
--- a/media/extractors/tests/README.md
+++ b/media/extractors/tests/README.md
@@ -22,7 +22,7 @@
 adb push ${OUT}/data/nativetest/ExtractorUnitTest/ExtractorUnitTest /data/local/tmp/
 ```
 
-The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/extractors/tests/extractor.zip). Download, unzip and push these files into device for testing.
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/extractors/tests/extractor-1.4.zip). Download, unzip and push these files into device for testing.
 
 ```
 adb push extractor /data/local/tmp/
diff --git a/media/extractors/wav/Android.bp b/media/extractors/wav/Android.bp
index 5d38a81..cc5e1c7 100644
--- a/media/extractors/wav/Android.bp
+++ b/media/extractors/wav/Android.bp
@@ -1,7 +1,24 @@
+package {
+    default_applicable_licenses: ["frameworks_av_media_extractors_wav_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_extractors_wav_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libwavextractor",
 
-    defaults: ["extractor-defaults"],
+    defaults: ["extractor-defaults", "libbinder_ndk_host_user"],
 
     srcs: ["WAVExtractor.cpp"],
 
@@ -19,4 +36,11 @@
         "libfifo",
         "libstagefright_foundation",
     ],
+
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
diff --git a/media/img_utils/Android.bp b/media/img_utils/Android.bp
index 64530e1..237cd2b 100644
--- a/media/img_utils/Android.bp
+++ b/media/img_utils/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libimg_utils",
 
diff --git a/media/janitors/README b/media/janitors/README
new file mode 100644
index 0000000..9db8e0e
--- /dev/null
+++ b/media/janitors/README
@@ -0,0 +1,4 @@
+A collection of OWNERS files that we reference from other projects,
+such as the software codecs in directories like external/libavc.
+This is to simplify our owner/approver management across the multiple
+projects related to media.
diff --git a/media/janitors/codec_OWNERS b/media/janitors/codec_OWNERS
new file mode 100644
index 0000000..e201399
--- /dev/null
+++ b/media/janitors/codec_OWNERS
@@ -0,0 +1,5 @@
+# gerrit owner/approvers for the actual software codec libraries
+# differentiated from plugins connecting those codecs to either omx or codec2 infrastructure
+essick@google.com
+lajos@google.com
+marcone@google.com
diff --git a/media/libaaudio/Android.bp b/media/libaaudio/Android.bp
index 140052f..05c788c 100644
--- a/media/libaaudio/Android.bp
+++ b/media/libaaudio/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 ndk_headers {
     name: "libAAudio_headers",
     from: "include",
@@ -33,4 +42,3 @@
     name: "libaaudio_headers",
     export_include_dirs: ["include"],
 }
-
diff --git a/media/libaaudio/examples/Android.bp b/media/libaaudio/examples/Android.bp
index 49bd5ee..e2c1878 100644
--- a/media/libaaudio/examples/Android.bp
+++ b/media/libaaudio/examples/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libaaudio_example_utils",
     export_include_dirs: ["utils"],
diff --git a/media/libaaudio/examples/input_monitor/Android.bp b/media/libaaudio/examples/input_monitor/Android.bp
index d8c5843..72adfd7 100644
--- a/media/libaaudio/examples/input_monitor/Android.bp
+++ b/media/libaaudio/examples/input_monitor/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "input_monitor",
     gtest: false,
diff --git a/media/libaaudio/examples/loopback/Android.bp b/media/libaaudio/examples/loopback/Android.bp
index 5b7d956..8d86e95 100644
--- a/media/libaaudio/examples/loopback/Android.bp
+++ b/media/libaaudio/examples/loopback/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "aaudio_loopback",
     gtest: false,
diff --git a/media/libaaudio/examples/utils/dummy.cpp b/media/libaaudio/examples/utils/dummy.cpp
deleted file mode 100644
index 8ef7e36..0000000
--- a/media/libaaudio/examples/utils/dummy.cpp
+++ /dev/null
@@ -1,5 +0,0 @@
-/**
- * Dummy file needed to get Android Studio to scan this folder.
- */
-
-int g_DoNotUseThisVariable = 0;
diff --git a/media/libaaudio/examples/utils/unused.cpp b/media/libaaudio/examples/utils/unused.cpp
new file mode 100644
index 0000000..9a5205e
--- /dev/null
+++ b/media/libaaudio/examples/utils/unused.cpp
@@ -0,0 +1,5 @@
+/**
+ * Unused file required to get Android Studio to scan this folder.
+ */
+
+int g_DoNotUseThisVariable = 0;
diff --git a/media/libaaudio/examples/write_sine/Android.bp b/media/libaaudio/examples/write_sine/Android.bp
index aa25e67..1c7e0f1 100644
--- a/media/libaaudio/examples/write_sine/Android.bp
+++ b/media/libaaudio/examples/write_sine/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "write_sine",
     srcs: ["src/write_sine.cpp"],
diff --git a/media/libaaudio/include/aaudio/AAudio.h b/media/libaaudio/include/aaudio/AAudio.h
index cab8929..709c656 100644
--- a/media/libaaudio/include/aaudio/AAudio.h
+++ b/media/libaaudio/include/aaudio/AAudio.h
@@ -29,6 +29,8 @@
 #ifndef AAUDIO_AAUDIO_H
 #define AAUDIO_AAUDIO_H
 
+#include <stdbool.h>
+#include <stdint.h>
 #include <time.h>
 
 #ifdef __cplusplus
@@ -1022,7 +1024,6 @@
 // Stream Control
 // ============================================================
 
-#if __ANDROID_API__ >= 30
 /**
  * Free the audio resources associated with a stream created by
  * AAudioStreamBuilder_openStream().
@@ -1040,11 +1041,12 @@
  * On other "Legacy" streams some audio resources will still be in use
  * and some callbacks may still be in process after this call.
  *
+ * Available since API level 30.
+ *
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return {@link #AAUDIO_OK} or a negative error.
  */
 AAUDIO_API aaudio_result_t  AAudioStream_release(AAudioStream* stream) __INTRODUCED_IN(30);
-#endif // __ANDROID_API__
 
 /**
  * Delete the internal data structures associated with the stream created
@@ -1052,6 +1054,8 @@
  *
  * If AAudioStream_release() has not been called then it will be called automatically.
  *
+ * Available since API level 26.
+ *
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return {@link #AAUDIO_OK} or a negative error.
  */
diff --git a/media/libaaudio/src/Android.bp b/media/libaaudio/src/Android.bp
index 717f31a..fdbc9c5 100644
--- a/media/libaaudio/src/Android.bp
+++ b/media/libaaudio/src/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libaaudio",
 
diff --git a/media/libaaudio/src/binding/SharedMemoryParcelable.h b/media/libaaudio/src/binding/SharedMemoryParcelable.h
index 4ec38c5..3927f58 100644
--- a/media/libaaudio/src/binding/SharedMemoryParcelable.h
+++ b/media/libaaudio/src/binding/SharedMemoryParcelable.h
@@ -26,7 +26,7 @@
 
 namespace aaudio {
 
-// Arbitrary limits for sanity checks. TODO remove after debugging.
+// Arbitrary limits for range checks.
 #define MAX_SHARED_MEMORIES (32)
 #define MAX_MMAP_OFFSET_BYTES (32 * 1024 * 8)
 #define MAX_MMAP_SIZE_BYTES (32 * 1024 * 8)
diff --git a/media/libaaudio/src/flowgraph/AudioProcessorBase.h b/media/libaaudio/src/flowgraph/AudioProcessorBase.h
index eda46ae..972932f 100644
--- a/media/libaaudio/src/flowgraph/AudioProcessorBase.h
+++ b/media/libaaudio/src/flowgraph/AudioProcessorBase.h
@@ -267,7 +267,7 @@
     AudioFloatInputPort input;
 
     /**
-     * Dummy processor. The work happens in the read() method.
+     * Do nothing. The work happens in the read() method.
      *
      * @param framePosition index of first frame to be processed
      * @param numFrames
diff --git a/media/libaaudio/src/utility/AAudioUtilities.cpp b/media/libaaudio/src/utility/AAudioUtilities.cpp
index 9007b10..3dfb801 100644
--- a/media/libaaudio/src/utility/AAudioUtilities.cpp
+++ b/media/libaaudio/src/utility/AAudioUtilities.cpp
@@ -27,7 +27,7 @@
 #include "core/AudioGlobal.h"
 #include <aaudio/AAudioTesting.h>
 #include <math.h>
-#include <system/audio-base.h>
+#include <system/audio.h>
 #include <assert.h>
 
 #include "utility/AAudioUtilities.h"
@@ -231,7 +231,8 @@
         case AAUDIO_ALLOW_CAPTURE_BY_SYSTEM:
             return AUDIO_FLAG_NO_MEDIA_PROJECTION;
         case AAUDIO_ALLOW_CAPTURE_BY_NONE:
-            return AUDIO_FLAG_NO_MEDIA_PROJECTION | AUDIO_FLAG_NO_SYSTEM_CAPTURE;
+            return static_cast<audio_flags_mask_t>(
+                    AUDIO_FLAG_NO_MEDIA_PROJECTION | AUDIO_FLAG_NO_SYSTEM_CAPTURE);
         default:
             ALOGE("%s() 0x%08X unrecognized", __func__, policy);
             return AUDIO_FLAG_NONE; //
diff --git a/media/libaaudio/src/utility/AAudioUtilities.h b/media/libaaudio/src/utility/AAudioUtilities.h
index d2e4805..82eb77d 100644
--- a/media/libaaudio/src/utility/AAudioUtilities.h
+++ b/media/libaaudio/src/utility/AAudioUtilities.h
@@ -21,6 +21,7 @@
 #include <functional>
 #include <stdint.h>
 #include <sys/types.h>
+#include <unistd.h>
 
 #include <utils/Errors.h>
 #include <system/audio.h>
diff --git a/media/libaaudio/tests/Android.bp b/media/libaaudio/tests/Android.bp
index 8935d57..ccfbea3 100644
--- a/media/libaaudio/tests/Android.bp
+++ b/media/libaaudio/tests/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "libaaudio_tests_defaults",
     cflags: [
diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp
index fa2a159..0c11e0f 100644
--- a/media/libaudioclient/Android.bp
+++ b/media/libaudioclient/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libaudioclient_headers",
     vendor_available: true,
@@ -12,6 +21,12 @@
     export_header_lib_headers: [
         "libaudiofoundation_headers",
     ],
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
 
 cc_library_shared {
@@ -42,7 +57,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libaudioclient",
 
     aidl: {
diff --git a/media/libaudioclient/AudioAttributes.cpp b/media/libaudioclient/AudioAttributes.cpp
index 1ee6930..ff4ba06 100644
--- a/media/libaudioclient/AudioAttributes.cpp
+++ b/media/libaudioclient/AudioAttributes.cpp
@@ -57,7 +57,7 @@
         parcel->writeInt32(0);
     } else {
         parcel->writeInt32(1);
-        parcel->writeUtf8AsUtf16(mAttributes.tags);
+        parcel->writeUtf8AsUtf16(std::string(mAttributes.tags));
     }
     parcel->writeInt32(static_cast<int32_t>(mStreamType));
     parcel->writeUint32(static_cast<uint32_t>(mGroupId));
diff --git a/media/libaudioclient/AudioRecord.cpp b/media/libaudioclient/AudioRecord.cpp
index 9568e83..55b836f 100644
--- a/media/libaudioclient/AudioRecord.cpp
+++ b/media/libaudioclient/AudioRecord.cpp
@@ -279,7 +279,8 @@
         mAttributes.source = inputSource;
         if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION
                 || inputSource == AUDIO_SOURCE_CAMCORDER) {
-            mAttributes.flags |= AUDIO_FLAG_CAPTURE_PRIVATE;
+            mAttributes.flags = static_cast<audio_flags_mask_t>(
+                    mAttributes.flags | AUDIO_FLAG_CAPTURE_PRIVATE);
         }
     } else {
         // stream type shouldn't be looked at, this track has audio attributes
@@ -1103,7 +1104,7 @@
     }
 
     if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
-        // sanity-check. user is most-likely passing an error code, and it would
+        // Validation. user is most-likely passing an error code, and it would
         // make the return value ambiguous (actualSize vs error).
         ALOGE("%s(%d) (buffer=%p, size=%zu (%zu)",
                 __func__, mPortId, buffer, userSize, userSize);
@@ -1330,7 +1331,7 @@
         mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
         size_t readSize = audioBuffer.size;
 
-        // Sanity check on returned size
+        // Validate on returned size
         if (ssize_t(readSize) < 0 || readSize > reqSize) {
             ALOGE("%s(%d):  EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
                     __func__, mPortId, reqSize, ssize_t(readSize));
diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp
index e26a831..edb0889 100644
--- a/media/libaudioclient/AudioSystem.cpp
+++ b/media/libaudioclient/AudioSystem.cpp
@@ -582,7 +582,8 @@
         case AUDIO_INPUT_CONFIG_CHANGED: {
             sp<AudioIoDescriptor> oldDesc = getIoDescriptor_l(ioDesc->mIoHandle);
             if (oldDesc == 0) {
-                ALOGW("ioConfigChanged() modifying unknown output! %d", ioDesc->mIoHandle);
+                ALOGW("ioConfigChanged() modifying unknown %s! %d",
+                    event == AUDIO_OUTPUT_CONFIG_CHANGED ? "output" : "input", ioDesc->mIoHandle);
                 break;
             }
 
@@ -1362,7 +1363,7 @@
     return aps->registerPolicyMixes(mixes, registration);
 }
 
-status_t AudioSystem::setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices)
+status_t AudioSystem::setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAddrVector& devices)
 {
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
     if (aps == 0) return PERMISSION_DENIED;
@@ -1376,7 +1377,7 @@
 }
 
 status_t AudioSystem::setUserIdDeviceAffinities(int userId,
-                                                const Vector<AudioDeviceTypeAddr>& devices)
+                                                const AudioDeviceTypeAddrVector& devices)
 {
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
     if (aps == 0) return PERMISSION_DENIED;
@@ -1603,33 +1604,88 @@
     return aps->isCallScreenModeSupported();
 }
 
-status_t AudioSystem::setPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                    const AudioDeviceTypeAddr &device)
+status_t AudioSystem::setDevicesRoleForStrategy(product_strategy_t strategy,
+                                                device_role_t role,
+                                                const AudioDeviceTypeAddrVector &devices)
 {
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
     if (aps == 0) {
         return PERMISSION_DENIED;
     }
-    return aps->setPreferredDeviceForStrategy(strategy, device);
+    return aps->setDevicesRoleForStrategy(strategy, role, devices);
 }
 
-status_t AudioSystem::removePreferredDeviceForStrategy(product_strategy_t strategy)
+status_t AudioSystem::removeDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role)
 {
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
     if (aps == 0) {
         return PERMISSION_DENIED;
     }
-    return aps->removePreferredDeviceForStrategy(strategy);
+    return aps->removeDevicesRoleForStrategy(strategy, role);
 }
 
-status_t AudioSystem::getPreferredDeviceForStrategy(product_strategy_t strategy,
-        AudioDeviceTypeAddr &device)
+status_t AudioSystem::getDevicesForRoleAndStrategy(product_strategy_t strategy,
+                                                   device_role_t role,
+                                                   AudioDeviceTypeAddrVector &devices)
 {
     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
     if (aps == 0) {
         return PERMISSION_DENIED;
     }
-    return aps->getPreferredDeviceForStrategy(strategy, device);
+    return aps->getDevicesForRoleAndStrategy(strategy, role, devices);
+}
+
+status_t AudioSystem::setDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                     device_role_t role,
+                                                     const AudioDeviceTypeAddrVector &devices)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) {
+        return PERMISSION_DENIED;
+    }
+    return aps->setDevicesRoleForCapturePreset(audioSource, role, devices);
+}
+
+status_t AudioSystem::addDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                     device_role_t role,
+                                                     const AudioDeviceTypeAddrVector &devices)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) {
+        return PERMISSION_DENIED;
+    }
+    return aps->addDevicesRoleForCapturePreset(audioSource, role, devices);
+}
+
+status_t AudioSystem::removeDevicesRoleForCapturePreset(
+        audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) {
+        return PERMISSION_DENIED;
+    }
+    return aps->removeDevicesRoleForCapturePreset(audioSource, role, devices);
+}
+
+status_t AudioSystem::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                       device_role_t role)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) {
+        return PERMISSION_DENIED;
+    }
+    return aps->clearDevicesRoleForCapturePreset(audioSource, role);
+}
+
+status_t AudioSystem::getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+                                                        device_role_t role,
+                                                        AudioDeviceTypeAddrVector &devices)
+{
+    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
+    if (aps == 0) {
+        return PERMISSION_DENIED;
+    }
+    return aps->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
 }
 
 class CaptureStateListenerImpl : public media::BnCaptureStateListener,
diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp
index 68d11d4..19d1d1a 100644
--- a/media/libaudioclient/AudioTrack.cpp
+++ b/media/libaudioclient/AudioTrack.cpp
@@ -227,7 +227,7 @@
 {
     mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
     mAttributes.usage = AUDIO_USAGE_UNKNOWN;
-    mAttributes.flags = 0x0;
+    mAttributes.flags = AUDIO_FLAG_NONE;
     strcpy(mAttributes.tags, "");
 }
 
@@ -467,7 +467,7 @@
     if (format == AUDIO_FORMAT_DEFAULT) {
         format = AUDIO_FORMAT_PCM_16_BIT;
     } else if (format == AUDIO_FORMAT_IEC61937) { // HDMI pass-through?
-        mAttributes.flags |= AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO;
+        flags = static_cast<audio_output_flags_t>(flags | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
     }
 
     // validate parameters
@@ -644,6 +644,36 @@
     return status;
 }
 
+
+status_t AudioTrack::set(
+        audio_stream_type_t streamType,
+        uint32_t sampleRate,
+        audio_format_t format,
+        uint32_t channelMask,
+        size_t frameCount,
+        audio_output_flags_t flags,
+        callback_t cbf,
+        void* user,
+        int32_t notificationFrames,
+        const sp<IMemory>& sharedBuffer,
+        bool threadCanCallJava,
+        audio_session_t sessionId,
+        transfer_type transferType,
+        const audio_offload_info_t *offloadInfo,
+        uid_t uid,
+        pid_t pid,
+        const audio_attributes_t* pAttributes,
+        bool doNotReconnect,
+        float maxRequiredSpeed,
+        audio_port_handle_t selectedDeviceId)
+{
+    return set(streamType, sampleRate, format,
+            static_cast<audio_channel_mask_t>(channelMask),
+            frameCount, flags, cbf, user, notificationFrames, sharedBuffer,
+            threadCanCallJava, sessionId, transferType, offloadInfo, uid, pid,
+            pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId);
+}
+
 // -------------------------------------------------------------------------
 
 status_t AudioTrack::start()
@@ -1045,6 +1075,40 @@
     return mOriginalSampleRate;
 }
 
+status_t AudioTrack::setDualMonoMode(audio_dual_mono_mode_t mode)
+{
+    AutoMutex lock(mLock);
+    return setDualMonoMode_l(mode);
+}
+
+status_t AudioTrack::setDualMonoMode_l(audio_dual_mono_mode_t mode)
+{
+    return mAudioTrack->setDualMonoMode(mode);
+}
+
+status_t AudioTrack::getDualMonoMode(audio_dual_mono_mode_t* mode) const
+{
+    AutoMutex lock(mLock);
+    return mAudioTrack->getDualMonoMode(mode);
+}
+
+status_t AudioTrack::setAudioDescriptionMixLevel(float leveldB)
+{
+    AutoMutex lock(mLock);
+    return setAudioDescriptionMixLevel_l(leveldB);
+}
+
+status_t AudioTrack::setAudioDescriptionMixLevel_l(float leveldB)
+{
+    return mAudioTrack->setAudioDescriptionMixLevel(leveldB);
+}
+
+status_t AudioTrack::getAudioDescriptionMixLevel(float* leveldB) const
+{
+    AutoMutex lock(mLock);
+    return mAudioTrack->getAudioDescriptionMixLevel(leveldB);
+}
+
 status_t AudioTrack::setPlaybackRate(const AudioPlaybackRate &playbackRate)
 {
     AutoMutex lock(mLock);
@@ -1052,7 +1116,11 @@
         return NO_ERROR;
     }
     if (isOffloadedOrDirect_l()) {
-        return INVALID_OPERATION;
+        status_t status = mAudioTrack->setPlaybackRateParameters(playbackRate);
+        if (status == NO_ERROR) {
+            mPlaybackRate = playbackRate;
+        }
+        return status;
     }
     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
         return INVALID_OPERATION;
@@ -1117,9 +1185,16 @@
     return NO_ERROR;
 }
 
-const AudioPlaybackRate& AudioTrack::getPlaybackRate() const
+const AudioPlaybackRate& AudioTrack::getPlaybackRate()
 {
     AutoMutex lock(mLock);
+    if (isOffloadedOrDirect_l()) {
+        audio_playback_rate_t playbackRateTemp;
+        const status_t status = mAudioTrack->getPlaybackRateParameters(&playbackRateTemp);
+        if (status == NO_ERROR) { // update local version if changed.
+            mPlaybackRate = playbackRateTemp;
+        }
+    }
     return mPlaybackRate;
 }
 
@@ -1715,6 +1790,13 @@
     mProxy->setPlaybackRate(playbackRateTemp);
     mProxy->setMinimum(mNotificationFramesAct);
 
+    if (mDualMonoMode != AUDIO_DUAL_MONO_MODE_OFF) {
+        setDualMonoMode_l(mDualMonoMode);
+    }
+    if (mAudioDescriptionMixLeveldB != -std::numeric_limits<float>::infinity()) {
+        setAudioDescriptionMixLevel_l(mAudioDescriptionMixLeveldB);
+    }
+
     mDeathNotifier = new DeathNotifier(this);
     IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
 
@@ -1946,7 +2028,7 @@
     }
 
     if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
-        // Sanity-check: user is most-likely passing an error code, and it would
+        // Validation: user is most-likely passing an error code, and it would
         // make the return value ambiguous (actualSize vs error).
         ALOGE("%s(%d): AudioTrack::write(buffer=%p, size=%zu (%zd)",
                 __func__, mPortId, buffer, userSize, userSize);
@@ -2336,7 +2418,7 @@
                 mUserData, &audioBuffer);
         size_t writtenSize = audioBuffer.size;
 
-        // Sanity check on returned size
+        // Validate on returned size
         if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
             ALOGE("%s(%d): EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
                     __func__, mPortId, reqSize, ssize_t(writtenSize));
diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp
index d3a037c..08f307d 100644
--- a/media/libaudioclient/IAudioFlinger.cpp
+++ b/media/libaudioclient/IAudioFlinger.cpp
@@ -1002,7 +1002,7 @@
             break;
     }
 
-    // Whitelist of relevant events to trigger log merging.
+    // List of relevant events that trigger log merging.
     // Log merging should activate during audio activity of any kind. This are considered the
     // most relevant events.
     // TODO should select more wisely the items from the list
@@ -1211,7 +1211,7 @@
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             uint32_t sampleRate = data.readInt32();
             audio_format_t format = (audio_format_t) data.readInt32();
-            audio_channel_mask_t channelMask = data.readInt32();
+            audio_channel_mask_t channelMask = (audio_channel_mask_t) data.readInt32();
             reply->writeInt64( getInputBufferSize(sampleRate, format, channelMask) );
             return NO_ERROR;
         } break;
diff --git a/media/libaudioclient/IAudioPolicyService.cpp b/media/libaudioclient/IAudioPolicyService.cpp
index 43a5369..81f9dff 100644
--- a/media/libaudioclient/IAudioPolicyService.cpp
+++ b/media/libaudioclient/IAudioPolicyService.cpp
@@ -113,13 +113,18 @@
     MOVE_EFFECTS_TO_IO,
     SET_RTT_ENABLED,
     IS_CALL_SCREEN_MODE_SUPPORTED,
-    SET_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY,
-    REMOVE_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY,
-    GET_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY,
+    SET_DEVICES_ROLE_FOR_PRODUCT_STRATEGY,
+    REMOVE_DEVICES_ROLE_FOR_PRODUCT_STRATEGY,
+    GET_DEVICES_FOR_ROLE_AND_PRODUCT_STRATEGY,
     GET_DEVICES_FOR_ATTRIBUTES,
     AUDIO_MODULES_UPDATED,  // oneway
     SET_CURRENT_IME_UID,
     REGISTER_SOUNDTRIGGER_CAPTURE_STATE_LISTENER,
+    SET_DEVICES_ROLE_FOR_CAPTURE_PRESET,
+    ADD_DEVICES_ROLE_FOR_CAPTURE_PRESET,
+    REMOVE_DEVICES_ROLE_FOR_CAPTURE_PRESET,
+    CLEAR_DEVICES_ROLE_FOR_CAPTURE_PRESET,
+    GET_DEVICES_FOR_ROLE_AND_CAPTURE_PRESET,
 };
 
 #define MAX_ITEMS_PER_LIST 1024
@@ -1174,31 +1179,18 @@
         return reply.readBool();
     }
 
-    virtual status_t setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices)
+    virtual status_t setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAddrVector& devices)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
 
         data.writeInt32((int32_t) uid);
-        size_t size = devices.size();
-        size_t sizePosition = data.dataPosition();
-        data.writeInt32((int32_t) size);
-        size_t finalSize = size;
-        for (size_t i = 0; i < size; i++) {
-            size_t position = data.dataPosition();
-            if (devices[i].writeToParcel(&data) != NO_ERROR) {
-                data.setDataPosition(position);
-                finalSize--;
-            }
-        }
-        if (size != finalSize) {
-            size_t position = data.dataPosition();
-            data.setDataPosition(sizePosition);
-            data.writeInt32(finalSize);
-            data.setDataPosition(position);
+        status_t status = data.writeParcelableVector(devices);
+        if (status != NO_ERROR) {
+            return status;
         }
 
-        status_t status = remote()->transact(SET_UID_DEVICE_AFFINITY, data, &reply);
+        status = remote()->transact(SET_UID_DEVICE_AFFINITY, data, &reply);
         if (status == NO_ERROR) {
             status = (status_t)reply.readInt32();
         }
@@ -1219,51 +1211,37 @@
         return status;
     }
 
-        virtual status_t setUserIdDeviceAffinities(int userId,
-                const Vector<AudioDeviceTypeAddr>& devices)
-        {
-            Parcel data, reply;
-            data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+    virtual status_t setUserIdDeviceAffinities(int userId, const AudioDeviceTypeAddrVector& devices)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
 
-            data.writeInt32((int32_t) userId);
-            size_t size = devices.size();
-            size_t sizePosition = data.dataPosition();
-            data.writeInt32((int32_t) size);
-            size_t finalSize = size;
-            for (size_t i = 0; i < size; i++) {
-                size_t position = data.dataPosition();
-                if (devices[i].writeToParcel(&data) != NO_ERROR) {
-                    data.setDataPosition(position);
-                    finalSize--;
-                }
-            }
-            if (size != finalSize) {
-                size_t position = data.dataPosition();
-                data.setDataPosition(sizePosition);
-                data.writeInt32(finalSize);
-                data.setDataPosition(position);
-            }
-
-            status_t status = remote()->transact(SET_USERID_DEVICE_AFFINITY, data, &reply);
-            if (status == NO_ERROR) {
-                status = (status_t)reply.readInt32();
-            }
+        data.writeInt32((int32_t) userId);
+        status_t status = data.writeParcelableVector(devices);
+        if (status != NO_ERROR) {
             return status;
         }
 
-        virtual status_t removeUserIdDeviceAffinities(int userId) {
-            Parcel data, reply;
-            data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-
-            data.writeInt32((int32_t) userId);
-
-            status_t status =
-                remote()->transact(REMOVE_USERID_DEVICE_AFFINITY, data, &reply);
-            if (status == NO_ERROR) {
-                status = (status_t) reply.readInt32();
-            }
-            return status;
+        status = remote()->transact(SET_USERID_DEVICE_AFFINITY, data, &reply);
+        if (status == NO_ERROR) {
+            status = (status_t)reply.readInt32();
         }
+        return status;
+    }
+
+    virtual status_t removeUserIdDeviceAffinities(int userId) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+
+        data.writeInt32((int32_t) userId);
+
+        status_t status =
+            remote()->transact(REMOVE_USERID_DEVICE_AFFINITY, data, &reply);
+        if (status == NO_ERROR) {
+            status = (status_t) reply.readInt32();
+        }
+        return status;
+    }
 
     virtual status_t listAudioProductStrategies(AudioProductStrategyVector &strategies)
     {
@@ -1385,17 +1363,31 @@
         return reply.readBool();
     }
 
-    virtual status_t setPreferredDeviceForStrategy(product_strategy_t strategy,
-            const AudioDeviceTypeAddr &device)
+    virtual status_t setDevicesRoleForStrategy(product_strategy_t strategy,
+            device_role_t role, const AudioDeviceTypeAddrVector &devices)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
         data.writeUint32(static_cast<uint32_t>(strategy));
-        status_t status = device.writeToParcel(&data);
+        data.writeUint32(static_cast<uint32_t>(role));
+        status_t status = data.writeParcelableVector(devices);
         if (status != NO_ERROR) {
             return BAD_VALUE;
         }
-        status = remote()->transact(SET_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY,
+        status = remote()->transact(SET_DEVICES_ROLE_FOR_PRODUCT_STRATEGY, data, &reply);
+        if (status != NO_ERROR) {
+           return status;
+        }
+        return static_cast<status_t>(reply.readInt32());
+    }
+
+    virtual status_t removeDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeUint32(static_cast<uint32_t>(strategy));
+        data.writeUint32(static_cast<uint32_t>(role));
+        status_t status = remote()->transact(REMOVE_DEVICES_ROLE_FOR_PRODUCT_STRATEGY,
                 data, &reply);
         if (status != NO_ERROR) {
            return status;
@@ -1403,31 +1395,108 @@
         return static_cast<status_t>(reply.readInt32());
     }
 
-    virtual status_t removePreferredDeviceForStrategy(product_strategy_t strategy)
+    virtual status_t getDevicesForRoleAndStrategy(product_strategy_t strategy,
+            device_role_t role, AudioDeviceTypeAddrVector &devices)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
         data.writeUint32(static_cast<uint32_t>(strategy));
-        status_t status = remote()->transact(REMOVE_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY,
-                data, &reply);
-        if (status != NO_ERROR) {
-           return status;
-        }
-        return static_cast<status_t>(reply.readInt32());
-    }
-
-    virtual status_t getPreferredDeviceForStrategy(product_strategy_t strategy,
-            AudioDeviceTypeAddr &device)
-    {
-        Parcel data, reply;
-        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
-        data.writeUint32(static_cast<uint32_t>(strategy));
-        status_t status = remote()->transact(GET_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY,
+        data.writeUint32(static_cast<uint32_t>(role));
+        status_t status = remote()->transact(GET_DEVICES_FOR_ROLE_AND_PRODUCT_STRATEGY,
                 data, &reply);
         if (status != NO_ERROR) {
             return status;
         }
-        status = device.readFromParcel(&reply);
+        status = reply.readParcelableVector(&devices);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        return static_cast<status_t>(reply.readInt32());
+    }
+
+    virtual status_t setDevicesRoleForCapturePreset(audio_source_t audioSource,
+            device_role_t role, const AudioDeviceTypeAddrVector &devices) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeUint32(static_cast<uint32_t>(audioSource));
+        data.writeUint32(static_cast<uint32_t>(role));
+        status_t status = data.writeParcelableVector(devices);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        status = remote()->transact(SET_DEVICES_ROLE_FOR_CAPTURE_PRESET, data, &reply);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        return static_cast<status_t>(reply.readInt32());
+    }
+
+    virtual status_t addDevicesRoleForCapturePreset(audio_source_t audioSource,
+            device_role_t role, const AudioDeviceTypeAddrVector &devices)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeUint32(static_cast<uint32_t>(audioSource));
+        data.writeUint32(static_cast<uint32_t>(role));
+        status_t status = data.writeParcelableVector(devices);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        status = remote()->transact(ADD_DEVICES_ROLE_FOR_CAPTURE_PRESET, data, &reply);
+        if (status != NO_ERROR) {
+           return status;
+        }
+        return static_cast<status_t>(reply.readInt32());
+    }
+
+    virtual status_t removeDevicesRoleForCapturePreset(
+            audio_source_t audioSource, device_role_t role,
+            const AudioDeviceTypeAddrVector& devices)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeUint32(static_cast<uint32_t>(audioSource));
+        data.writeUint32(static_cast<uint32_t>(role));
+        status_t status = data.writeParcelableVector(devices);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        status = remote()->transact(REMOVE_DEVICES_ROLE_FOR_CAPTURE_PRESET,
+                data, &reply);
+        if (status != NO_ERROR) {
+           return status;
+        }
+        return static_cast<status_t>(reply.readInt32());
+    }
+
+    virtual status_t clearDevicesRoleForCapturePreset(
+            audio_source_t audioSource, device_role_t role)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeUint32(static_cast<uint32_t>(audioSource));
+        data.writeUint32(static_cast<uint32_t>(role));
+        status_t status = remote()->transact(CLEAR_DEVICES_ROLE_FOR_CAPTURE_PRESET,
+                data, &reply);
+        if (status != NO_ERROR) {
+           return status;
+        }
+        return static_cast<status_t>(reply.readInt32());
+    }
+
+    virtual status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+            device_role_t role, AudioDeviceTypeAddrVector &devices)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
+        data.writeUint32(static_cast<uint32_t>(audioSource));
+        data.writeUint32(static_cast<uint32_t>(role));
+        status_t status = remote()->transact(GET_DEVICES_FOR_ROLE_AND_CAPTURE_PRESET,
+                data, &reply);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        status = reply.readParcelableVector(&devices);
         if (status != NO_ERROR) {
             return status;
         }
@@ -1562,15 +1631,20 @@
         case RELEASE_SOUNDTRIGGER_SESSION:
         case SET_RTT_ENABLED:
         case IS_CALL_SCREEN_MODE_SUPPORTED:
-        case SET_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY:
+        case SET_DEVICES_ROLE_FOR_PRODUCT_STRATEGY:
         case SET_SUPPORTED_SYSTEM_USAGES:
-        case REMOVE_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY:
-        case GET_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY:
+        case REMOVE_DEVICES_ROLE_FOR_PRODUCT_STRATEGY:
+        case GET_DEVICES_FOR_ROLE_AND_PRODUCT_STRATEGY:
         case GET_DEVICES_FOR_ATTRIBUTES:
         case SET_ALLOWED_CAPTURE_POLICY:
         case AUDIO_MODULES_UPDATED:
         case SET_CURRENT_IME_UID:
-        case REGISTER_SOUNDTRIGGER_CAPTURE_STATE_LISTENER: {
+        case REGISTER_SOUNDTRIGGER_CAPTURE_STATE_LISTENER:
+        case SET_DEVICES_ROLE_FOR_CAPTURE_PRESET:
+        case ADD_DEVICES_ROLE_FOR_CAPTURE_PRESET:
+        case REMOVE_DEVICES_ROLE_FOR_CAPTURE_PRESET:
+        case CLEAR_DEVICES_ROLE_FOR_CAPTURE_PRESET:
+        case GET_DEVICES_FOR_ROLE_AND_CAPTURE_PRESET: {
             if (!isServiceUid(IPCThreadState::self()->getCallingUid())) {
                 ALOGW("%s: transaction %d received from PID %d unauthorized UID %d",
                       __func__, code, IPCThreadState::self()->getCallingPid(),
@@ -2522,15 +2596,12 @@
         case SET_UID_DEVICE_AFFINITY: {
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             const uid_t uid = (uid_t) data.readInt32();
-            Vector<AudioDeviceTypeAddr> devices;
-            size_t size = (size_t)data.readInt32();
-            for (size_t i = 0; i < size; i++) {
-                AudioDeviceTypeAddr device;
-                if (device.readFromParcel((Parcel*)&data) == NO_ERROR) {
-                    devices.add(device);
-                }
+            AudioDeviceTypeAddrVector devices;
+            status_t status = data.readParcelableVector(&devices);
+            if (status != NO_ERROR) {
+                return status;
             }
-            status_t status = setUidDeviceAffinities(uid, devices);
+            status = setUidDeviceAffinities(uid, devices);
             reply->writeInt32(status);
             return NO_ERROR;
         }
@@ -2546,15 +2617,12 @@
         case SET_USERID_DEVICE_AFFINITY: {
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             const int userId = (int) data.readInt32();
-            Vector<AudioDeviceTypeAddr> devices;
-            size_t size = (size_t)data.readInt32();
-            for (size_t i = 0; i < size; i++) {
-                AudioDeviceTypeAddr device;
-                if (device.readFromParcel((Parcel*)&data) == NO_ERROR) {
-                    devices.add(device);
-                }
+            AudioDeviceTypeAddrVector devices;
+            status_t status = data.readParcelableVector(&devices);
+            if (status != NO_ERROR) {
+                return status;
             }
-            status_t status = setUserIdDeviceAffinities(userId, devices);
+            status = setUserIdDeviceAffinities(userId, devices);
             reply->writeInt32(status);
             return NO_ERROR;
         }
@@ -2690,7 +2758,7 @@
         case SET_ALLOWED_CAPTURE_POLICY: {
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             uid_t uid = data.readInt32();
-            audio_flags_mask_t flags = data.readInt32();
+            audio_flags_mask_t flags = static_cast<audio_flags_mask_t>(data.readInt32());
             status_t status = setAllowedCapturePolicy(uid, flags);
             reply->writeInt32(status);
             return NO_ERROR;
@@ -2711,33 +2779,36 @@
             return NO_ERROR;
         }
 
-        case SET_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY: {
+        case SET_DEVICES_ROLE_FOR_PRODUCT_STRATEGY: {
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             product_strategy_t strategy = (product_strategy_t) data.readUint32();
-            AudioDeviceTypeAddr device;
-            status_t status = device.readFromParcel((Parcel*)&data);
+            device_role_t role = (device_role_t) data.readUint32();
+            AudioDeviceTypeAddrVector devices;
+            status_t status = data.readParcelableVector(&devices);
             if (status != NO_ERROR) {
                 return status;
             }
-            status = setPreferredDeviceForStrategy(strategy, device);
+            status = setDevicesRoleForStrategy(strategy, role, devices);
             reply->writeInt32(status);
             return NO_ERROR;
         }
 
-        case REMOVE_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY: {
+        case REMOVE_DEVICES_ROLE_FOR_PRODUCT_STRATEGY: {
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             product_strategy_t strategy = (product_strategy_t) data.readUint32();
-            status_t status = removePreferredDeviceForStrategy(strategy);
+            device_role_t role = (device_role_t) data.readUint32();
+            status_t status = removeDevicesRoleForStrategy(strategy, role);
             reply->writeInt32(status);
             return NO_ERROR;
         }
 
-        case GET_PREFERRED_DEVICE_FOR_PRODUCT_STRATEGY: {
+        case GET_DEVICES_FOR_ROLE_AND_PRODUCT_STRATEGY: {
             CHECK_INTERFACE(IAudioPolicyService, data, reply);
             product_strategy_t strategy = (product_strategy_t) data.readUint32();
-            AudioDeviceTypeAddr device;
-            status_t status = getPreferredDeviceForStrategy(strategy, device);
-            status_t marshall_status = device.writeToParcel(reply);
+            device_role_t role = (device_role_t) data.readUint32();
+            AudioDeviceTypeAddrVector devices;
+            status_t status = getDevicesForRoleAndStrategy(strategy, role, devices);
+            status_t marshall_status = reply->writeParcelableVector(devices);
             if (marshall_status != NO_ERROR) {
                 return marshall_status;
             }
@@ -2819,6 +2890,71 @@
             return NO_ERROR;
         } break;
 
+        case SET_DEVICES_ROLE_FOR_CAPTURE_PRESET: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_source_t audioSource = (audio_source_t) data.readUint32();
+            device_role_t role = (device_role_t) data.readUint32();
+            AudioDeviceTypeAddrVector devices;
+            status_t status = data.readParcelableVector(&devices);
+            if (status != NO_ERROR) {
+                return status;
+            }
+            status = setDevicesRoleForCapturePreset(audioSource, role, devices);
+            reply->writeInt32(status);
+            return NO_ERROR;
+        }
+
+        case ADD_DEVICES_ROLE_FOR_CAPTURE_PRESET: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_source_t audioSource = (audio_source_t) data.readUint32();
+            device_role_t role = (device_role_t) data.readUint32();
+            AudioDeviceTypeAddrVector devices;
+            status_t status = data.readParcelableVector(&devices);
+            if (status != NO_ERROR) {
+                return status;
+            }
+            status = addDevicesRoleForCapturePreset(audioSource, role, devices);
+            reply->writeInt32(status);
+            return NO_ERROR;
+        }
+
+        case REMOVE_DEVICES_ROLE_FOR_CAPTURE_PRESET: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_source_t audioSource = (audio_source_t) data.readUint32();
+            device_role_t role = (device_role_t) data.readUint32();
+            AudioDeviceTypeAddrVector devices;
+            status_t status = data.readParcelableVector(&devices);
+            if (status != NO_ERROR) {
+                return status;
+            }
+            status = removeDevicesRoleForCapturePreset(audioSource, role, devices);
+            reply->writeInt32(status);
+            return NO_ERROR;
+        }
+
+        case CLEAR_DEVICES_ROLE_FOR_CAPTURE_PRESET: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_source_t audioSource = (audio_source_t) data.readUint32();
+            device_role_t role = (device_role_t) data.readUint32();
+            status_t status = clearDevicesRoleForCapturePreset(audioSource, role);
+            reply->writeInt32(status);
+            return NO_ERROR;
+        }
+
+        case GET_DEVICES_FOR_ROLE_AND_CAPTURE_PRESET: {
+            CHECK_INTERFACE(IAudioPolicyService, data, reply);
+            audio_source_t audioSource = (audio_source_t) data.readUint32();
+            device_role_t role = (device_role_t) data.readUint32();
+            AudioDeviceTypeAddrVector devices;
+            status_t status = getDevicesForRoleAndCapturePreset(audioSource, role, devices);
+            status_t marshall_status = reply->writeParcelableVector(devices);
+            if (marshall_status != NO_ERROR) {
+                return marshall_status;
+            }
+            reply->writeInt32(status);
+            return NO_ERROR;
+        }
+
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/media/libaudioclient/IAudioTrack.cpp b/media/libaudioclient/IAudioTrack.cpp
index 6219e7a..6fcf300 100644
--- a/media/libaudioclient/IAudioTrack.cpp
+++ b/media/libaudioclient/IAudioTrack.cpp
@@ -44,6 +44,12 @@
     SIGNAL,
     APPLY_VOLUME_SHAPER,
     GET_VOLUME_SHAPER_STATE,
+    SET_DUAL_MONO_MODE,
+    GET_DUAL_MONO_MODE,
+    SET_AUDIO_DESCRIPTION_MIX_LEVEL,
+    GET_AUDIO_DESCRIPTION_MIX_LEVEL,
+    SET_PLAYBACK_RATE_PARAMETERS,
+    GET_PLAYBACK_RATE_PARAMETERS,
 };
 
 class BpAudioTrack : public BpInterface<IAudioTrack>
@@ -207,6 +213,92 @@
         }
         return state;
     }
+
+    status_t getDualMonoMode(audio_dual_mono_mode_t* mode) override {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
+        status_t status = remote()->transact(GET_DUAL_MONO_MODE, data, &reply);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        status = (status_t)reply.readInt32();
+        if (status != NO_ERROR) {
+            return status;
+        }
+        *mode = (audio_dual_mono_mode_t)reply.readInt32();
+        return NO_ERROR;
+    }
+
+    status_t setDualMonoMode(audio_dual_mono_mode_t mode) override {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
+        data.writeInt32((int32_t)mode);
+        status_t status = remote()->transact(SET_DUAL_MONO_MODE, data, &reply);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        return reply.readInt32();
+    }
+
+    status_t getAudioDescriptionMixLevel(float* leveldB) override {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
+        status_t status = remote()->transact(GET_AUDIO_DESCRIPTION_MIX_LEVEL, data, &reply);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        status = (status_t)reply.readInt32();
+        if (status != NO_ERROR) {
+            return status;
+        }
+        *leveldB = reply.readFloat();
+        return NO_ERROR;
+    }
+
+    status_t setAudioDescriptionMixLevel(float leveldB) override {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
+        data.writeFloat(leveldB);
+        status_t status = remote()->transact(SET_AUDIO_DESCRIPTION_MIX_LEVEL, data, &reply);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        return reply.readInt32();
+    }
+
+    status_t getPlaybackRateParameters(audio_playback_rate_t* playbackRate) override {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
+        status_t status = remote()->transact(GET_PLAYBACK_RATE_PARAMETERS, data, &reply);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        status = (status_t)reply.readInt32();
+        if (status != NO_ERROR) {
+            return status;
+        }
+        playbackRate->mSpeed = reply.readFloat();
+        playbackRate->mPitch = reply.readFloat();
+        playbackRate->mStretchMode =
+            static_cast<audio_timestretch_stretch_mode_t>(reply.readInt32());
+        playbackRate->mFallbackMode =
+            static_cast<audio_timestretch_fallback_mode_t>(reply.readInt32());
+        return NO_ERROR;
+    }
+
+    status_t setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) override {
+        Parcel data, reply;
+        data.writeInterfaceToken(IAudioTrack::getInterfaceDescriptor());
+        data.writeFloat(playbackRate.mSpeed);
+        data.writeFloat(playbackRate.mPitch);
+        data.writeInt32(playbackRate.mStretchMode);
+        data.writeInt32(playbackRate.mFallbackMode);
+        status_t status = remote()->transact(SET_PLAYBACK_RATE_PARAMETERS, data, &reply);
+        if (status != NO_ERROR) {
+            return status;
+        }
+        return reply.readInt32();
+    }
 };
 
 IMPLEMENT_META_INTERFACE(AudioTrack, "android.media.IAudioTrack");
@@ -309,6 +401,59 @@
             }
             return NO_ERROR;
         } break;
+        case SET_DUAL_MONO_MODE: {
+            CHECK_INTERFACE(IAudioTrack, data, reply);
+            reply->writeInt32( setDualMonoMode((audio_dual_mono_mode_t)data.readInt32()) );
+            return NO_ERROR;
+        } break;
+        case GET_DUAL_MONO_MODE: {
+            CHECK_INTERFACE(IAudioTrack, data, reply);
+            audio_dual_mono_mode_t mode;
+            const status_t status = getDualMonoMode(&mode);
+            reply->writeInt32((int32_t)status);
+            if (status == NO_ERROR) {
+                reply->writeInt32(mode);
+            }
+            return NO_ERROR;
+        } break;
+        case SET_AUDIO_DESCRIPTION_MIX_LEVEL: {
+            CHECK_INTERFACE(IAudioTrack, data, reply);
+            reply->writeInt32( setAudioDescriptionMixLevel(data.readFloat()) );
+            return NO_ERROR;
+        } break;
+        case GET_AUDIO_DESCRIPTION_MIX_LEVEL: {
+            CHECK_INTERFACE(IAudioTrack, data, reply);
+            float f;
+            const status_t status = getAudioDescriptionMixLevel(&f);
+            reply->writeInt32((int32_t)status);
+            if (status == NO_ERROR) {
+                reply->writeFloat(f);
+            }
+            return NO_ERROR;
+        } break;
+        case SET_PLAYBACK_RATE_PARAMETERS: {
+            CHECK_INTERFACE(IAudioTrack, data, reply);
+            audio_playback_rate_t playbackRate = {
+                data.readFloat(),
+                data.readFloat(),
+                static_cast<audio_timestretch_stretch_mode_t>(data.readInt32()),
+                static_cast<audio_timestretch_fallback_mode_t>(data.readInt32())};
+            reply->writeInt32( setPlaybackRateParameters(playbackRate) );
+            return NO_ERROR;
+        } break;
+        case GET_PLAYBACK_RATE_PARAMETERS: {
+            CHECK_INTERFACE(IAudioTrack, data, reply);
+            audio_playback_rate_t playbackRate;
+            const status_t status = getPlaybackRateParameters(&playbackRate);
+            reply->writeInt32((int32_t)status);
+            if (status == NO_ERROR) {
+                reply->writeFloat(playbackRate.mSpeed);
+                reply->writeFloat(playbackRate.mPitch);
+                reply->writeInt32(playbackRate.mStretchMode);
+                reply->writeInt32(playbackRate.mFallbackMode);
+            }
+            return NO_ERROR;
+        } break;
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/media/libaudioclient/OWNERS b/media/libaudioclient/OWNERS
index 482b9fb..034d161 100644
--- a/media/libaudioclient/OWNERS
+++ b/media/libaudioclient/OWNERS
@@ -1,3 +1,4 @@
 gkasten@google.com
+hunga@google.com
 jmtrivi@google.com
 mnaganov@google.com
diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h
index 19c2cbd..848743a 100644
--- a/media/libaudioclient/include/media/AudioSystem.h
+++ b/media/libaudioclient/include/media/AudioSystem.h
@@ -361,11 +361,11 @@
 
     static status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration);
 
-    static status_t setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices);
+    static status_t setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAddrVector& devices);
 
     static status_t removeUidDeviceAffinities(uid_t uid);
 
-    static status_t setUserIdDeviceAffinities(int userId, const Vector<AudioDeviceTypeAddr>& devices);
+    static status_t setUserIdDeviceAffinities(int userId, const AudioDeviceTypeAddrVector& devices);
 
     static status_t removeUserIdDeviceAffinities(int userId);
 
@@ -425,13 +425,29 @@
      */
     static status_t setAudioHalPids(const std::vector<pid_t>& pids);
 
-    static status_t setPreferredDeviceForStrategy(product_strategy_t strategy,
-            const AudioDeviceTypeAddr &device);
+    static status_t setDevicesRoleForStrategy(product_strategy_t strategy,
+            device_role_t role, const AudioDeviceTypeAddrVector &devices);
 
-    static status_t removePreferredDeviceForStrategy(product_strategy_t strategy);
+    static status_t removeDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role);
 
-    static status_t getPreferredDeviceForStrategy(product_strategy_t strategy,
-            AudioDeviceTypeAddr &device);
+    static status_t getDevicesForRoleAndStrategy(product_strategy_t strategy,
+            device_role_t role, AudioDeviceTypeAddrVector &devices);
+
+    static status_t setDevicesRoleForCapturePreset(audio_source_t audioSource,
+            device_role_t role, const AudioDeviceTypeAddrVector &devices);
+
+    static status_t addDevicesRoleForCapturePreset(audio_source_t audioSource,
+            device_role_t role, const AudioDeviceTypeAddrVector &devices);
+
+    static status_t removeDevicesRoleForCapturePreset(
+            audio_source_t audioSource, device_role_t role,
+            const AudioDeviceTypeAddrVector& devices);
+
+    static status_t clearDevicesRoleForCapturePreset(
+            audio_source_t audioSource, device_role_t role);
+
+    static status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+            device_role_t role, AudioDeviceTypeAddrVector &devices);
 
     static status_t getDeviceForStrategy(product_strategy_t strategy,
             AudioDeviceTypeAddr &device);
diff --git a/media/libaudioclient/include/media/AudioTrack.h b/media/libaudioclient/include/media/AudioTrack.h
index a9946da..fac4c83 100644
--- a/media/libaudioclient/include/media/AudioTrack.h
+++ b/media/libaudioclient/include/media/AudioTrack.h
@@ -344,6 +344,27 @@
                             bool doNotReconnect = false,
                             float maxRequiredSpeed = 1.0f,
                             audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE);
+    // FIXME(b/169889714): Vendor code depends on the old method signature at link time
+            status_t    set(audio_stream_type_t streamType,
+                            uint32_t sampleRate,
+                            audio_format_t format,
+                            uint32_t channelMask,
+                            size_t frameCount   = 0,
+                            audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
+                            callback_t cbf      = NULL,
+                            void* user          = NULL,
+                            int32_t notificationFrames = 0,
+                            const sp<IMemory>& sharedBuffer = 0,
+                            bool threadCanCallJava = false,
+                            audio_session_t sessionId  = AUDIO_SESSION_ALLOCATE,
+                            transfer_type transferType = TRANSFER_DEFAULT,
+                            const audio_offload_info_t *offloadInfo = NULL,
+                            uid_t uid = AUDIO_UID_INVALID,
+                            pid_t pid = -1,
+                            const audio_attributes_t* pAttributes = NULL,
+                            bool doNotReconnect = false,
+                            float maxRequiredSpeed = 1.0f,
+                            audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE);
 
     /* Result of constructing the AudioTrack. This must be checked for successful initialization
      * before using any AudioTrack API (except for set()), because using
@@ -492,6 +513,18 @@
      */
             uint32_t    getOriginalSampleRate() const;
 
+    /* Sets the Dual Mono mode presentation on the output device. */
+            status_t    setDualMonoMode(audio_dual_mono_mode_t mode);
+
+    /* Returns the Dual Mono mode presentation setting. */
+            status_t    getDualMonoMode(audio_dual_mono_mode_t* mode) const;
+
+    /* Sets the Audio Description Mix level in dB. */
+            status_t    setAudioDescriptionMixLevel(float leveldB);
+
+    /* Returns the Audio Description Mix level in dB. */
+            status_t    getAudioDescriptionMixLevel(float* leveldB) const;
+
     /* Set source playback rate for timestretch
      * 1.0 is normal speed: < 1.0 is slower, > 1.0 is faster
      * 1.0 is normal pitch: < 1.0 is lower pitch, > 1.0 is higher pitch
@@ -505,7 +538,7 @@
             status_t    setPlaybackRate(const AudioPlaybackRate &playbackRate);
 
     /* Return current playback rate */
-            const AudioPlaybackRate& getPlaybackRate() const;
+            const AudioPlaybackRate& getPlaybackRate();
 
     /* Enables looping and sets the start and end points of looping.
      * Only supported for static buffer mode.
@@ -1049,6 +1082,12 @@
 
             void     updateRoutedDeviceId_l();
 
+            /* Sets the Dual Mono mode presentation on the output device. */
+            status_t setDualMonoMode_l(audio_dual_mono_mode_t mode);
+
+            /* Sets the Audio Description Mix level in dB. */
+            status_t setAudioDescriptionMixLevel_l(float leveldB);
+
     // Next 4 fields may be changed if IAudioTrack is re-created, but always != 0
     sp<IAudioTrack>         mAudioTrack;
     sp<IMemory>             mCblkMemory;
@@ -1261,6 +1300,10 @@
 
     wp<AudioSystem::AudioDeviceCallback> mDeviceCallback;
 
+    // Cached values to restore along with the AudioTrack.
+    audio_dual_mono_mode_t mDualMonoMode = AUDIO_DUAL_MONO_MODE_OFF;
+    float mAudioDescriptionMixLeveldB = -std::numeric_limits<float>::infinity();
+
 private:
     class MediaMetrics {
       public:
diff --git a/media/libaudioclient/include/media/IAudioPolicyService.h b/media/libaudioclient/include/media/IAudioPolicyService.h
index 376c6eb..837375d 100644
--- a/media/libaudioclient/include/media/IAudioPolicyService.h
+++ b/media/libaudioclient/include/media/IAudioPolicyService.h
@@ -196,13 +196,13 @@
 
     virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration) = 0;
 
-    virtual status_t setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices)
+    virtual status_t setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAddrVector& devices)
             = 0;
 
     virtual status_t removeUidDeviceAffinities(uid_t uid) = 0;
 
     virtual status_t setUserIdDeviceAffinities(int userId,
-            const Vector<AudioDeviceTypeAddr>& devices) = 0;
+            const AudioDeviceTypeAddrVector& devices) = 0;
 
     virtual status_t removeUserIdDeviceAffinities(int userId) = 0;
 
@@ -241,13 +241,35 @@
 
     virtual bool     isCallScreenModeSupported() = 0;
 
-    virtual status_t setPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   const AudioDeviceTypeAddr &device) = 0;
+    virtual status_t setDevicesRoleForStrategy(product_strategy_t strategy,
+                                               device_role_t role,
+                                               const AudioDeviceTypeAddrVector &devices) = 0;
 
-    virtual status_t removePreferredDeviceForStrategy(product_strategy_t strategy) = 0;
+    virtual status_t removeDevicesRoleForStrategy(product_strategy_t strategy,
+                                                  device_role_t role) = 0;
 
-    virtual status_t getPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   AudioDeviceTypeAddr &device) = 0;
+    virtual status_t getDevicesForRoleAndStrategy(product_strategy_t strategy,
+                                                  device_role_t role,
+                                                  AudioDeviceTypeAddrVector &devices) = 0;
+
+    virtual status_t setDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                    device_role_t role,
+                                                    const AudioDeviceTypeAddrVector &devices) = 0;
+
+    virtual status_t addDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                    device_role_t role,
+                                                    const AudioDeviceTypeAddrVector &devices) = 0;
+
+    virtual status_t removeDevicesRoleForCapturePreset(
+            audio_source_t audioSource, device_role_t role,
+            const AudioDeviceTypeAddrVector& devices) = 0;
+
+    virtual status_t clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                      device_role_t role) = 0;
+
+    virtual status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+                                                       device_role_t role,
+                                                       AudioDeviceTypeAddrVector &devices) = 0;
 
     // The return code here is only intended to represent transport errors. The
     // actual server implementation should always return NO_ERROR.
diff --git a/media/libaudioclient/include/media/IAudioTrack.h b/media/libaudioclient/include/media/IAudioTrack.h
index 06e786d..dbbbf35 100644
--- a/media/libaudioclient/include/media/IAudioTrack.h
+++ b/media/libaudioclient/include/media/IAudioTrack.h
@@ -27,6 +27,7 @@
 #include <utils/String8.h>
 #include <media/AudioTimestamp.h>
 #include <media/VolumeShaper.h>
+#include <system/audio.h>
 
 namespace android {
 
@@ -86,6 +87,24 @@
 
     /* gets the volume shaper state */
     virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) = 0;
+
+    /* Returns the Dual Mono mode presentation setting. */
+    virtual status_t    getDualMonoMode(audio_dual_mono_mode_t* mode) = 0;
+
+    /* Sets the Dual Mono mode presentation on the output device. */
+    virtual status_t    setDualMonoMode(audio_dual_mono_mode_t mode) = 0;
+
+    /* Returns the Audio Description Mix level in dB. */
+    virtual status_t    getAudioDescriptionMixLevel(float* leveldB) = 0;
+
+    /* Sets the Audio Description Mix level in dB. */
+    virtual status_t    setAudioDescriptionMixLevel(float leveldB) = 0;
+
+    /* Retrieves current playback rate parameters. */
+    virtual status_t    getPlaybackRateParameters(audio_playback_rate_t* playbackRate) = 0;
+
+    /* Sets the playback rate parameters that control playback behavior. */
+    virtual status_t    setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/media/libaudioclient/tests/Android.bp b/media/libaudioclient/tests/Android.bp
index 350a780..92c6ec0 100644
--- a/media/libaudioclient/tests/Android.bp
+++ b/media/libaudioclient/tests/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "libaudioclient_tests_defaults",
     cflags: [
diff --git a/media/libaudiofoundation/Android.bp b/media/libaudiofoundation/Android.bp
index 548b080..b2fa007 100644
--- a/media/libaudiofoundation/Android.bp
+++ b/media/libaudiofoundation/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libaudiofoundation_headers",
     vendor_available: true,
@@ -12,6 +21,12 @@
         "libaudio_system_headers",
         "libmedia_helper_headers",
     ],
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
 
 cc_library {
diff --git a/media/libaudiofoundation/AudioDeviceTypeAddr.cpp b/media/libaudiofoundation/AudioDeviceTypeAddr.cpp
index b44043a..a47337b 100644
--- a/media/libaudiofoundation/AudioDeviceTypeAddr.cpp
+++ b/media/libaudiofoundation/AudioDeviceTypeAddr.cpp
@@ -16,12 +16,57 @@
 
 #include <media/AudioDeviceTypeAddr.h>
 
+#include <arpa/inet.h>
+#include <iostream>
+#include <regex>
+#include <set>
+#include <sstream>
+
 namespace android {
 
+namespace {
+
+static const std::string SUPPRESSED = "SUPPRESSED";
+static const std::regex MAC_ADDRESS_REGEX("([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}");
+
+bool isSenstiveAddress(const std::string &address) {
+    if (std::regex_match(address, MAC_ADDRESS_REGEX)) {
+        return true;
+    }
+
+    sockaddr_storage ss4;
+    if (inet_pton(AF_INET, address.c_str(), &ss4) > 0) {
+        return true;
+    }
+
+    sockaddr_storage ss6;
+    if (inet_pton(AF_INET6, address.c_str(), &ss6) > 0) {
+        return true;
+    }
+
+    return false;
+}
+
+} // namespace
+
+AudioDeviceTypeAddr::AudioDeviceTypeAddr(audio_devices_t type, const std::string &address) :
+        mType(type), mAddress(address) {
+    mIsAddressSensitive = isSenstiveAddress(mAddress);
+}
+
 const char* AudioDeviceTypeAddr::getAddress() const {
     return mAddress.c_str();
 }
 
+const std::string& AudioDeviceTypeAddr::address() const {
+    return mAddress;
+}
+
+void AudioDeviceTypeAddr::setAddress(const std::string& address) {
+    mAddress = address;
+    mIsAddressSensitive = isSenstiveAddress(mAddress);
+}
+
 bool AudioDeviceTypeAddr::equals(const AudioDeviceTypeAddr& other) const {
     return mType == other.mType && mAddress == other.mAddress;
 }
@@ -36,14 +81,34 @@
     return false;
 }
 
+bool AudioDeviceTypeAddr::operator==(const AudioDeviceTypeAddr &rhs) const {
+    return equals(rhs);
+}
+
+bool AudioDeviceTypeAddr::operator!=(const AudioDeviceTypeAddr &rhs) const {
+    return !operator==(rhs);
+}
+
 void AudioDeviceTypeAddr::reset() {
     mType = AUDIO_DEVICE_NONE;
-    mAddress = "";
+    setAddress("");
+}
+
+std::string AudioDeviceTypeAddr::toString(bool includeSensitiveInfo) const {
+    std::stringstream sstream;
+    sstream << "type:0x" << std::hex << mType;
+    // IP and MAC address are sensitive information. The sensitive information will be suppressed
+    // is `includeSensitiveInfo` is false.
+    sstream << ",@:"
+            << (!includeSensitiveInfo && mIsAddressSensitive ? SUPPRESSED : mAddress);
+    return sstream.str();
 }
 
 status_t AudioDeviceTypeAddr::readFromParcel(const Parcel *parcel) {
     status_t status;
-    if ((status = parcel->readUint32(&mType)) != NO_ERROR) return status;
+    uint32_t rawDeviceType;
+    if ((status = parcel->readUint32(&rawDeviceType)) != NO_ERROR) return status;
+    mType = static_cast<audio_devices_t>(rawDeviceType);
     status = parcel->readUtf8FromUtf16(&mAddress);
     return status;
 }
@@ -64,4 +129,30 @@
     return deviceTypes;
 }
 
-}
\ No newline at end of file
+AudioDeviceTypeAddrVector excludeDeviceTypeAddrsFrom(
+        const AudioDeviceTypeAddrVector& devices,
+        const AudioDeviceTypeAddrVector& devicesToExclude) {
+    std::set<AudioDeviceTypeAddr> devicesToExcludeSet(
+            devicesToExclude.begin(), devicesToExclude.end());
+    AudioDeviceTypeAddrVector remainedDevices;
+    for (const auto& device : devices) {
+        if (devicesToExcludeSet.count(device) == 0) {
+            remainedDevices.push_back(device);
+        }
+    }
+    return remainedDevices;
+}
+
+std::string dumpAudioDeviceTypeAddrVector(const AudioDeviceTypeAddrVector& deviceTypeAddrs,
+                                          bool includeSensitiveInfo) {
+    std::stringstream stream;
+    for (auto it = deviceTypeAddrs.begin(); it != deviceTypeAddrs.end(); ++it) {
+        if (it != deviceTypeAddrs.begin()) {
+            stream << " ";
+        }
+        stream << it->toString(includeSensitiveInfo);
+    }
+    return stream.str();
+}
+
+} // namespace android
diff --git a/media/libaudiofoundation/AudioGain.cpp b/media/libaudiofoundation/AudioGain.cpp
index 0d28335..759140e 100644
--- a/media/libaudiofoundation/AudioGain.cpp
+++ b/media/libaudiofoundation/AudioGain.cpp
@@ -152,8 +152,12 @@
     if ((status = parcel->readInt32(&mIndex)) != NO_ERROR) return status;
     if ((status = parcel->readBool(&mUseInChannelMask)) != NO_ERROR) return status;
     if ((status = parcel->readBool(&mUseForVolume)) != NO_ERROR) return status;
-    if ((status = parcel->readUint32(&mGain.mode)) != NO_ERROR) return status;
-    if ((status = parcel->readUint32(&mGain.channel_mask)) != NO_ERROR) return status;
+    uint32_t rawGainMode;
+    if ((status = parcel->readUint32(&rawGainMode)) != NO_ERROR) return status;
+    mGain.mode = static_cast<audio_gain_mode_t>(rawGainMode);
+    uint32_t rawChannelMask;
+    if ((status = parcel->readUint32(&rawChannelMask)) != NO_ERROR) return status;
+    mGain.channel_mask = static_cast<audio_channel_mask_t>(rawChannelMask);
     if ((status = parcel->readInt32(&mGain.min_value)) != NO_ERROR) return status;
     if ((status = parcel->readInt32(&mGain.max_value)) != NO_ERROR) return status;
     if ((status = parcel->readInt32(&mGain.default_value)) != NO_ERROR) return status;
diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp
index f988690..1846a6b 100644
--- a/media/libaudiofoundation/AudioPort.cpp
+++ b/media/libaudiofoundation/AudioPort.cpp
@@ -268,12 +268,17 @@
     if ((status = parcel->readUint32(reinterpret_cast<uint32_t*>(&mFormat))) != NO_ERROR) {
         return status;
     }
-    if ((status = parcel->readUint32(&mChannelMask)) != NO_ERROR) return status;
+    uint32_t rawChannelMask;
+    if ((status = parcel->readUint32(&rawChannelMask)) != NO_ERROR) return status;
+    mChannelMask = static_cast<audio_channel_mask_t>(rawChannelMask);
     if ((status = parcel->readInt32(&mId)) != NO_ERROR) return status;
     // Read mGain from parcel.
     if ((status = parcel->readInt32(&mGain.index)) != NO_ERROR) return status;
-    if ((status = parcel->readUint32(&mGain.mode)) != NO_ERROR) return status;
-    if ((status = parcel->readUint32(&mGain.channel_mask)) != NO_ERROR) return status;
+    uint32_t rawGainMode;
+    if ((status = parcel->readUint32(&rawGainMode)) != NO_ERROR) return status;
+    mGain.mode = static_cast<audio_gain_mode_t>(rawGainMode);
+    if ((status = parcel->readUint32(&rawChannelMask)) != NO_ERROR) return status;
+    mGain.channel_mask = static_cast<audio_channel_mask_t>(rawChannelMask);
     if ((status = parcel->readUint32(&mGain.ramp_duration_ms)) != NO_ERROR) return status;
     std::vector<int> values;
     if ((status = parcel->readInt32Vector(&values)) != NO_ERROR) return status;
diff --git a/media/libaudiofoundation/AudioProfile.cpp b/media/libaudiofoundation/AudioProfile.cpp
index 91be346..67b600e 100644
--- a/media/libaudiofoundation/AudioProfile.cpp
+++ b/media/libaudiofoundation/AudioProfile.cpp
@@ -157,7 +157,9 @@
     std::vector<int> values;
     if ((status = parcel->readInt32Vector(&values)) != NO_ERROR) return status;
     mChannelMasks.clear();
-    mChannelMasks.insert(values.begin(), values.end());
+    for (auto raw : values) {
+        mChannelMasks.insert(static_cast<audio_channel_mask_t>(raw));
+    }
     values.clear();
     if ((status = parcel->readInt32Vector(&values)) != NO_ERROR) return status;
     mSamplingRates.clear();
diff --git a/media/libaudiofoundation/DeviceDescriptorBase.cpp b/media/libaudiofoundation/DeviceDescriptorBase.cpp
index 3dbe37d..16cf71a 100644
--- a/media/libaudiofoundation/DeviceDescriptorBase.cpp
+++ b/media/libaudiofoundation/DeviceDescriptorBase.cpp
@@ -40,11 +40,15 @@
                                          AUDIO_PORT_ROLE_SOURCE),
         mDeviceTypeAddr(deviceTypeAddr)
 {
-    if (mDeviceTypeAddr.mAddress.empty() && audio_is_remote_submix_device(mDeviceTypeAddr.mType)) {
-        mDeviceTypeAddr.mAddress = "0";
+    if (mDeviceTypeAddr.address().empty() && audio_is_remote_submix_device(mDeviceTypeAddr.mType)) {
+        mDeviceTypeAddr.setAddress("0");
     }
 }
 
+void DeviceDescriptorBase::setAddress(const std::string &address) {
+    mDeviceTypeAddr.setAddress(address);
+}
+
 void DeviceDescriptorBase::toAudioPortConfig(struct audio_port_config *dstConfig,
                                              const struct audio_port_config *srcConfig) const
 {
@@ -123,18 +127,16 @@
             "%*s- supported encapsulation metadata types: %u",
             spaces, "", mEncapsulationMetadataTypes));
 
-    if (mDeviceTypeAddr.mAddress.size() != 0) {
+    if (mDeviceTypeAddr.address().size() != 0) {
         dst->append(base::StringPrintf(
                 "%*s- address: %-32s\n", spaces, "", mDeviceTypeAddr.getAddress()));
     }
     AudioPort::dump(dst, spaces, verbose);
 }
 
-std::string DeviceDescriptorBase::toString() const
+std::string DeviceDescriptorBase::toString(bool includeSensitiveInfo) const
 {
-    std::stringstream sstream;
-    sstream << "type:0x" << std::hex << type() << ",@:" << mDeviceTypeAddr.mAddress;
-    return sstream.str();
+    return mDeviceTypeAddr.toString(includeSensitiveInfo);
 }
 
 void DeviceDescriptorBase::log() const
diff --git a/media/libaudiofoundation/include/media/AudioContainers.h b/media/libaudiofoundation/include/media/AudioContainers.h
index 72fda49..aa7ca69 100644
--- a/media/libaudiofoundation/include/media/AudioContainers.h
+++ b/media/libaudiofoundation/include/media/AudioContainers.h
@@ -96,7 +96,7 @@
 static inline audio_devices_t deviceTypesToBitMask(const DeviceTypeSet& deviceTypes) {
     audio_devices_t types = AUDIO_DEVICE_NONE;
     for (auto deviceType : deviceTypes) {
-        types |= deviceType;
+        types = static_cast<audio_devices_t>(types | deviceType);
     }
     return types;
 }
@@ -131,4 +131,4 @@
 std::string toString(const DeviceTypeSet& deviceTypes);
 
 
-} // namespace android
\ No newline at end of file
+} // namespace android
diff --git a/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h b/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h
index 60ea78e..7497faf 100644
--- a/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h
+++ b/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h
@@ -27,28 +27,43 @@
 
 namespace android {
 
-struct AudioDeviceTypeAddr : public Parcelable {
+class AudioDeviceTypeAddr : public Parcelable {
+public:
     AudioDeviceTypeAddr() = default;
 
-    AudioDeviceTypeAddr(audio_devices_t type, const std::string& address) :
-            mType(type), mAddress(address) {}
+    AudioDeviceTypeAddr(audio_devices_t type, const std::string& address);
 
     const char* getAddress() const;
 
+    const std::string& address() const;
+
+    void setAddress(const std::string& address);
+
+    bool isAddressSensitive();
+
     bool equals(const AudioDeviceTypeAddr& other) const;
 
     AudioDeviceTypeAddr& operator= (const AudioDeviceTypeAddr&) = default;
 
     bool operator<(const AudioDeviceTypeAddr& other) const;
 
+    bool operator==(const AudioDeviceTypeAddr& rhs) const;
+
+    bool operator!=(const AudioDeviceTypeAddr& rhs) const;
+
     void reset();
 
+    std::string toString(bool includeSensitiveInfo=false) const;
+
     status_t readFromParcel(const Parcel *parcel) override;
 
     status_t writeToParcel(Parcel *parcel) const override;
 
     audio_devices_t mType = AUDIO_DEVICE_NONE;
+
+private:
     std::string mAddress;
+    bool mIsAddressSensitive;
 };
 
 using AudioDeviceTypeAddrVector = std::vector<AudioDeviceTypeAddr>;
@@ -58,4 +73,15 @@
  */
 DeviceTypeSet getAudioDeviceTypes(const AudioDeviceTypeAddrVector& deviceTypeAddrs);
 
-}
+/**
+ * Return a collection of AudioDeviceTypeAddrs that are shown in `devices` but not
+ * in `devicesToExclude`
+ */
+AudioDeviceTypeAddrVector excludeDeviceTypeAddrsFrom(
+        const AudioDeviceTypeAddrVector& devices,
+        const AudioDeviceTypeAddrVector& devicesToExclude);
+
+std::string dumpAudioDeviceTypeAddrVector(const AudioDeviceTypeAddrVector& deviceTypeAddrs,
+                                          bool includeSensitiveInfo=false);
+
+} // namespace android
diff --git a/media/libaudiofoundation/include/media/DeviceDescriptorBase.h b/media/libaudiofoundation/include/media/DeviceDescriptorBase.h
index af04721..0cbd1de 100644
--- a/media/libaudiofoundation/include/media/DeviceDescriptorBase.h
+++ b/media/libaudiofoundation/include/media/DeviceDescriptorBase.h
@@ -41,8 +41,8 @@
     virtual ~DeviceDescriptorBase() {}
 
     audio_devices_t type() const { return mDeviceTypeAddr.mType; }
-    std::string address() const { return mDeviceTypeAddr.mAddress; }
-    void setAddress(const std::string &address) { mDeviceTypeAddr.mAddress = address; }
+    const std::string& address() const { return mDeviceTypeAddr.address(); }
+    void setAddress(const std::string &address);
     const AudioDeviceTypeAddr& getDeviceTypeAddr() const { return mDeviceTypeAddr; }
 
     // AudioPortConfig
@@ -61,7 +61,14 @@
     void dump(std::string *dst, int spaces, int index,
               const char* extraInfo = nullptr, bool verbose = true) const;
     void log() const;
-    std::string toString() const;
+
+    /**
+     * Return a string to describe the DeviceDescriptor.
+     *
+     * @param includeSensitiveInfo sensitive information will be added when it is true.
+     * @return a string that can be used to describe the DeviceDescriptor.
+     */
+    std::string toString(bool includeSensitiveInfo = false) const;
 
     bool equals(const sp<DeviceDescriptorBase>& other) const;
 
diff --git a/media/libaudiofoundation/tests/Android.bp b/media/libaudiofoundation/tests/Android.bp
index f258b14..bb9a5f2 100644
--- a/media/libaudiofoundation/tests/Android.bp
+++ b/media/libaudiofoundation/tests/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "audiofoundation_parcelable_test",
 
diff --git a/media/libaudiohal/Android.bp b/media/libaudiohal/Android.bp
index 1709d1e..dbe342a 100644
--- a/media/libaudiohal/Android.bp
+++ b/media/libaudiohal/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libaudiohal",
 
@@ -14,10 +23,10 @@
     ],
 
     required: [
-        "libaudiohal@2.0",
         "libaudiohal@4.0",
         "libaudiohal@5.0",
         "libaudiohal@6.0",
+        "libaudiohal@7.0",
     ],
 
     shared_libs: [
diff --git a/media/libaudiohal/FactoryHalHidl.cpp b/media/libaudiohal/FactoryHalHidl.cpp
index 5985ef0..e420d07 100644
--- a/media/libaudiohal/FactoryHalHidl.cpp
+++ b/media/libaudiohal/FactoryHalHidl.cpp
@@ -31,10 +31,10 @@
 /** Supported HAL versions, in order of preference.
  */
 const char* sAudioHALVersions[] = {
+    "7.0",
     "6.0",
     "5.0",
     "4.0",
-    "2.0",
     nullptr
 };
 
diff --git a/media/libaudiohal/OWNERS b/media/libaudiohal/OWNERS
index 1456ab6..71b17e6 100644
--- a/media/libaudiohal/OWNERS
+++ b/media/libaudiohal/OWNERS
@@ -1,2 +1 @@
-krocard@google.com
 mnaganov@google.com
diff --git a/media/libaudiohal/impl/Android.bp b/media/libaudiohal/impl/Android.bp
index 967fba1..91a7a17 100644
--- a/media/libaudiohal/impl/Android.bp
+++ b/media/libaudiohal/impl/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "libaudiohal_default",
 
@@ -53,29 +62,15 @@
 }
 
 cc_library_shared {
-    name: "libaudiohal@2.0",
-    defaults: ["libaudiohal_default"],
-    shared_libs: [
-        "android.hardware.audio.common@2.0",
-        "android.hardware.audio.common@2.0-util",
-        "android.hardware.audio.effect@2.0",
-        "android.hardware.audio@2.0",
-    ],
-    cflags: [
-        "-DMAJOR_VERSION=2",
-        "-DMINOR_VERSION=0",
-        "-include common/all-versions/VersionMacro.h",
-    ]
-}
-
-cc_library_shared {
     name: "libaudiohal@4.0",
     defaults: ["libaudiohal_default"],
     shared_libs: [
         "android.hardware.audio.common@4.0",
         "android.hardware.audio.common@4.0-util",
         "android.hardware.audio.effect@4.0",
+        "android.hardware.audio.effect@4.0-util",
         "android.hardware.audio@4.0",
+        "android.hardware.audio@4.0-util",
     ],
     cflags: [
         "-DMAJOR_VERSION=4",
@@ -91,7 +86,9 @@
         "android.hardware.audio.common@5.0",
         "android.hardware.audio.common@5.0-util",
         "android.hardware.audio.effect@5.0",
+        "android.hardware.audio.effect@5.0-util",
         "android.hardware.audio@5.0",
+        "android.hardware.audio@5.0-util",
     ],
     cflags: [
         "-DMAJOR_VERSION=5",
@@ -107,7 +104,9 @@
         "android.hardware.audio.common@6.0",
         "android.hardware.audio.common@6.0-util",
         "android.hardware.audio.effect@6.0",
+        "android.hardware.audio.effect@6.0-util",
         "android.hardware.audio@6.0",
+        "android.hardware.audio@6.0-util",
     ],
     cflags: [
         "-DMAJOR_VERSION=6",
@@ -116,3 +115,20 @@
     ]
 }
 
+cc_library_shared {
+    name: "libaudiohal@7.0",
+    defaults: ["libaudiohal_default"],
+    shared_libs: [
+        "android.hardware.audio.common@7.0",
+        "android.hardware.audio.common@7.0-util",
+        "android.hardware.audio.effect@7.0",
+        "android.hardware.audio.effect@7.0-util",
+        "android.hardware.audio@7.0",
+        "android.hardware.audio@7.0-util",
+    ],
+    cflags: [
+        "-DMAJOR_VERSION=7",
+        "-DMINOR_VERSION=0",
+        "-include common/all-versions/VersionMacro.h",
+    ]
+}
diff --git a/media/libaudiohal/impl/ConversionHelperHidl.cpp b/media/libaudiohal/impl/ConversionHelperHidl.cpp
index ebed5fd..b6fee6d 100644
--- a/media/libaudiohal/impl/ConversionHelperHidl.cpp
+++ b/media/libaudiohal/impl/ConversionHelperHidl.cpp
@@ -50,12 +50,20 @@
             halKeys.get(String8(AUDIO_PARAMETER_DEVICE_SUP_ENCAPSULATION_METADATA_TYPES),
                         value) == NO_ERROR;
 
+    const bool keepDelayValue =
+            halKeys.get(String8(AUDIO_PARAMETER_DEVICE_ADDITIONAL_OUTPUT_DELAY),
+                        value) == NO_ERROR ||
+            halKeys.get(String8(AUDIO_PARAMETER_DEVICE_MAX_ADDITIONAL_OUTPUT_DELAY),
+                        value) == NO_ERROR;
+
     for (size_t i = 0; i < halKeys.size(); ++i) {
         String8 key;
         status_t status = halKeys.getAt(i, key);
         if (status != OK) return status;
         if ((keepFormatValue && key == AudioParameter::keyFormat) ||
-            (keepRoutingValue && key == AudioParameter::keyRouting)) {
+            (keepRoutingValue && key == AudioParameter::keyRouting) ||
+            (keepDelayValue && key == AUDIO_PARAMETER_DEVICE_ADDITIONAL_OUTPUT_DELAY) ||
+            (keepDelayValue && key == AUDIO_PARAMETER_DEVICE_MAX_ADDITIONAL_OUTPUT_DELAY)) {
             AudioParameter keepValueParam;
             halKeys.getAt(i, key, value);
             keepValueParam.add(key, value);
@@ -112,129 +120,5 @@
     ALOGE("%s %p %s: %s (from rpc)", mClassName, this, funcName, description);
 }
 
-#if MAJOR_VERSION >= 4
-// TODO: Use the same implementation in the hal when it moves to a util library.
-static std::string deviceAddressToHal(const DeviceAddress& address) {
-    // HAL assumes that the address is NUL-terminated.
-    char halAddress[AUDIO_DEVICE_MAX_ADDRESS_LEN];
-    memset(halAddress, 0, sizeof(halAddress));
-    audio_devices_t halDevice = static_cast<audio_devices_t>(address.device);
-    if (getAudioDeviceOutAllA2dpSet().count(halDevice) > 0 ||
-        halDevice == AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
-        snprintf(halAddress, sizeof(halAddress), "%02X:%02X:%02X:%02X:%02X:%02X",
-                 address.address.mac[0], address.address.mac[1], address.address.mac[2],
-                 address.address.mac[3], address.address.mac[4], address.address.mac[5]);
-    } else if (halDevice == AUDIO_DEVICE_OUT_IP || halDevice == AUDIO_DEVICE_IN_IP) {
-        snprintf(halAddress, sizeof(halAddress), "%d.%d.%d.%d", address.address.ipv4[0],
-                 address.address.ipv4[1], address.address.ipv4[2], address.address.ipv4[3]);
-    } else if (getAudioDeviceOutAllUsbSet().count(halDevice) > 0 ||
-               getAudioDeviceInAllUsbSet().count(halDevice) > 0) {
-        snprintf(halAddress, sizeof(halAddress), "card=%d;device=%d", address.address.alsa.card,
-                 address.address.alsa.device);
-    } else if (halDevice == AUDIO_DEVICE_OUT_BUS || halDevice == AUDIO_DEVICE_IN_BUS) {
-        snprintf(halAddress, sizeof(halAddress), "%s", address.busAddress.c_str());
-    } else if (halDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ||
-               halDevice == AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
-        snprintf(halAddress, sizeof(halAddress), "%s", address.rSubmixAddress.c_str());
-    } else {
-        snprintf(halAddress, sizeof(halAddress), "%s", address.busAddress.c_str());
-    }
-    return halAddress;
-}
-
-//local conversion helpers
-
-static audio_microphone_channel_mapping_t  channelMappingToHal(AudioMicrophoneChannelMapping mapping) {
-    switch (mapping) {
-        case AudioMicrophoneChannelMapping::UNUSED:
-            return AUDIO_MICROPHONE_CHANNEL_MAPPING_UNUSED;
-        case AudioMicrophoneChannelMapping::DIRECT:
-            return AUDIO_MICROPHONE_CHANNEL_MAPPING_DIRECT;
-        case AudioMicrophoneChannelMapping::PROCESSED:
-            return AUDIO_MICROPHONE_CHANNEL_MAPPING_PROCESSED;
-        default:
-            LOG_ALWAYS_FATAL("Unknown channelMappingToHal conversion %d", mapping);
-    }
-}
-
-static audio_microphone_location_t locationToHal(AudioMicrophoneLocation location) {
-    switch (location) {
-        case AudioMicrophoneLocation::UNKNOWN:
-            return AUDIO_MICROPHONE_LOCATION_UNKNOWN;
-        case AudioMicrophoneLocation::MAINBODY:
-            return AUDIO_MICROPHONE_LOCATION_MAINBODY;
-        case AudioMicrophoneLocation::MAINBODY_MOVABLE:
-            return AUDIO_MICROPHONE_LOCATION_MAINBODY_MOVABLE;
-        case AudioMicrophoneLocation::PERIPHERAL:
-            return AUDIO_MICROPHONE_LOCATION_PERIPHERAL;
-        default:
-            LOG_ALWAYS_FATAL("Unknown locationToHal conversion %d", location);
-    }
-}
-static audio_microphone_directionality_t directionalityToHal(AudioMicrophoneDirectionality dir) {
-    switch (dir) {
-        case AudioMicrophoneDirectionality::UNKNOWN:
-            return AUDIO_MICROPHONE_DIRECTIONALITY_UNKNOWN;
-        case AudioMicrophoneDirectionality::OMNI:
-            return AUDIO_MICROPHONE_DIRECTIONALITY_OMNI;
-        case AudioMicrophoneDirectionality::BI_DIRECTIONAL:
-            return AUDIO_MICROPHONE_DIRECTIONALITY_BI_DIRECTIONAL;
-        case AudioMicrophoneDirectionality::CARDIOID:
-            return AUDIO_MICROPHONE_DIRECTIONALITY_CARDIOID;
-        case AudioMicrophoneDirectionality::HYPER_CARDIOID:
-            return AUDIO_MICROPHONE_DIRECTIONALITY_HYPER_CARDIOID;
-        case AudioMicrophoneDirectionality::SUPER_CARDIOID:
-            return AUDIO_MICROPHONE_DIRECTIONALITY_SUPER_CARDIOID;
-        default:
-            LOG_ALWAYS_FATAL("Unknown directionalityToHal conversion %d", dir);
-    }
-}
-
-void microphoneInfoToHal(const MicrophoneInfo& src,
-                         audio_microphone_characteristic_t *pDst) {
-    if (pDst != NULL) {
-        snprintf(pDst->device_id, sizeof(pDst->device_id),
-                 "%s", src.deviceId.c_str());
-        pDst->device = static_cast<audio_devices_t>(src.deviceAddress.device);
-        snprintf(pDst->address, sizeof(pDst->address),
-                 "%s", deviceAddressToHal(src.deviceAddress).c_str());
-        if (src.channelMapping.size() > AUDIO_CHANNEL_COUNT_MAX) {
-            ALOGW("microphoneInfoToStruct found %zu channelMapping elements. Max expected is %d",
-                  src.channelMapping.size(), AUDIO_CHANNEL_COUNT_MAX);
-        }
-        size_t ch;
-        for (ch = 0; ch < src.channelMapping.size() && ch < AUDIO_CHANNEL_COUNT_MAX; ch++) {
-            pDst->channel_mapping[ch] = channelMappingToHal(src.channelMapping[ch]);
-        }
-        for (; ch < AUDIO_CHANNEL_COUNT_MAX; ch++) {
-            pDst->channel_mapping[ch] = AUDIO_MICROPHONE_CHANNEL_MAPPING_UNUSED;
-        }
-        pDst->location = locationToHal(src.location);
-        pDst->group = (audio_microphone_group_t)src.group;
-        pDst->index_in_the_group = (unsigned int)src.indexInTheGroup;
-        pDst->sensitivity = src.sensitivity;
-        pDst->max_spl = src.maxSpl;
-        pDst->min_spl = src.minSpl;
-        pDst->directionality = directionalityToHal(src.directionality);
-        pDst->num_frequency_responses = (unsigned int)src.frequencyResponse.size();
-        if (pDst->num_frequency_responses > AUDIO_MICROPHONE_MAX_FREQUENCY_RESPONSES) {
-            ALOGW("microphoneInfoToStruct found %d frequency responses. Max expected is %d",
-                  pDst->num_frequency_responses, AUDIO_MICROPHONE_MAX_FREQUENCY_RESPONSES);
-            pDst->num_frequency_responses = AUDIO_MICROPHONE_MAX_FREQUENCY_RESPONSES;
-        }
-        for (size_t k = 0; k < pDst->num_frequency_responses; k++) {
-            pDst->frequency_responses[0][k] = src.frequencyResponse[k].frequency;
-            pDst->frequency_responses[1][k] = src.frequencyResponse[k].level;
-        }
-        pDst->geometric_location.x = src.position.x;
-        pDst->geometric_location.y = src.position.y;
-        pDst->geometric_location.z = src.position.z;
-        pDst->orientation.x = src.orientation.x;
-        pDst->orientation.y = src.orientation.y;
-        pDst->orientation.z = src.orientation.z;
-    }
-}
-#endif
-
 }  // namespace CPP_VERSION
 }  // namespace android
diff --git a/media/libaudiohal/impl/ConversionHelperHidl.h b/media/libaudiohal/impl/ConversionHelperHidl.h
index fb3bb9d..59122c7 100644
--- a/media/libaudiohal/impl/ConversionHelperHidl.h
+++ b/media/libaudiohal/impl/ConversionHelperHidl.h
@@ -82,12 +82,6 @@
     void emitError(const char* funcName, const char* description);
 };
 
-#if MAJOR_VERSION >= 4
-using ::android::hardware::audio::CPP_VERSION::MicrophoneInfo;
-void microphoneInfoToHal(const MicrophoneInfo& src,
-                         audio_microphone_characteristic_t *pDst);
-#endif
-
 }  // namespace CPP_VERSION
 }  // namespace android
 
diff --git a/media/libaudiohal/impl/DeviceHalHidl.cpp b/media/libaudiohal/impl/DeviceHalHidl.cpp
index 7d0d83d..da16477 100644
--- a/media/libaudiohal/impl/DeviceHalHidl.cpp
+++ b/media/libaudiohal/impl/DeviceHalHidl.cpp
@@ -19,22 +19,24 @@
 #define LOG_TAG "DeviceHalHidl"
 //#define LOG_NDEBUG 0
 
-#include PATH(android/hardware/audio/FILE_VERSION/IPrimaryDevice.h)
 #include <cutils/native_handle.h>
 #include <hwbinder/IPCThreadState.h>
 #include <media/AudioContainers.h>
 #include <utils/Log.h>
 
+#include PATH(android/hardware/audio/FILE_VERSION/IPrimaryDevice.h)
+#include <HidlUtils.h>
 #include <common/all-versions/VersionUtils.h>
+#include <util/CoreUtils.h>
 
 #include "DeviceHalHidl.h"
 #include "EffectHalHidl.h"
-#include "HidlUtils.h"
+#include "ParameterUtils.h"
 #include "StreamHalHidl.h"
-#include "VersionUtils.h"
 
 using ::android::hardware::audio::common::CPP_VERSION::implementation::HidlUtils;
 using ::android::hardware::audio::common::utils::EnumBitfield;
+using ::android::hardware::audio::CPP_VERSION::implementation::CoreUtils;
 using ::android::hardware::hidl_string;
 using ::android::hardware::hidl_vec;
 
@@ -46,47 +48,6 @@
 
 using EffectHalHidl = ::android::effect::CPP_VERSION::EffectHalHidl;
 
-namespace {
-
-status_t deviceAddressFromHal(
-        audio_devices_t device, const char* halAddress, DeviceAddress* address) {
-    address->device = AudioDevice(device);
-
-    if (halAddress == nullptr || strnlen(halAddress, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
-        return OK;
-    }
-    if (getAudioDeviceOutAllA2dpSet().count(device) > 0
-            || device == AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
-        int status = sscanf(halAddress,
-                "%hhX:%hhX:%hhX:%hhX:%hhX:%hhX",
-                &address->address.mac[0], &address->address.mac[1], &address->address.mac[2],
-                &address->address.mac[3], &address->address.mac[4], &address->address.mac[5]);
-        return status == 6 ? OK : BAD_VALUE;
-    } else if (device == AUDIO_DEVICE_OUT_IP || device == AUDIO_DEVICE_IN_IP) {
-        int status = sscanf(halAddress,
-                "%hhu.%hhu.%hhu.%hhu",
-                &address->address.ipv4[0], &address->address.ipv4[1],
-                &address->address.ipv4[2], &address->address.ipv4[3]);
-        return status == 4 ? OK : BAD_VALUE;
-    } else if (getAudioDeviceOutAllUsbSet().count(device) > 0
-            || getAudioDeviceInAllUsbSet().count(device) > 0) {
-        int status = sscanf(halAddress,
-                "card=%d;device=%d",
-                &address->address.alsa.card, &address->address.alsa.device);
-        return status == 2 ? OK : BAD_VALUE;
-    } else if (device == AUDIO_DEVICE_OUT_BUS || device == AUDIO_DEVICE_IN_BUS) {
-        address->busAddress = halAddress;
-        return OK;
-    } else if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX
-            || device == AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
-        address->rSubmixAddress = halAddress;
-        return OK;
-    }
-    return OK;
-}
-
-}  // namespace
-
 DeviceHalHidl::DeviceHalHidl(const sp<IDevice>& device)
         : ConversionHelperHidl("Device"), mDevice(device),
           mPrimaryDevice(IPrimaryDevice::castFrom(device)) {
@@ -212,7 +173,7 @@
         const struct audio_config *config, size_t *size) {
     if (mDevice == 0) return NO_INIT;
     AudioConfig hidlConfig;
-    HidlUtils::audioConfigFromHal(*config, &hidlConfig);
+    HidlUtils::audioConfigFromHal(*config, true /*isInput*/, &hidlConfig);
     Result retval;
     Return<void> ret = mDevice->getInputBufferSize(
             hidlConfig,
@@ -234,16 +195,22 @@
         sp<StreamOutHalInterface> *outStream) {
     if (mDevice == 0) return NO_INIT;
     DeviceAddress hidlDevice;
-    status_t status = deviceAddressFromHal(deviceType, address, &hidlDevice);
-    if (status != OK) return status;
+    if (status_t status = CoreUtils::deviceAddressFromHal(deviceType, address, &hidlDevice);
+            status != OK) {
+        return status;
+    }
     AudioConfig hidlConfig;
-    HidlUtils::audioConfigFromHal(*config, &hidlConfig);
+    if (status_t status = HidlUtils::audioConfigFromHal(*config, false /*isInput*/, &hidlConfig);
+            status != OK) {
+        return status;
+    }
+    CoreUtils::AudioOutputFlags hidlFlags;
+    if (status_t status = CoreUtils::audioOutputFlagsFromHal(flags, &hidlFlags); status != OK) {
+        return status;
+    }
     Result retval = Result::NOT_INITIALIZED;
     Return<void> ret = mDevice->openOutputStream(
-            handle,
-            hidlDevice,
-            hidlConfig,
-            EnumBitfield<AudioOutputFlag>(flags),
+            handle, hidlDevice, hidlConfig, hidlFlags,
 #if MAJOR_VERSION >= 4
             {} /* metadata */,
 #endif
@@ -269,26 +236,45 @@
         sp<StreamInHalInterface> *inStream) {
     if (mDevice == 0) return NO_INIT;
     DeviceAddress hidlDevice;
-    status_t status = deviceAddressFromHal(devices, address, &hidlDevice);
-    if (status != OK) return status;
+    if (status_t status = CoreUtils::deviceAddressFromHal(devices, address, &hidlDevice);
+            status != OK) {
+        return status;
+    }
     AudioConfig hidlConfig;
-    HidlUtils::audioConfigFromHal(*config, &hidlConfig);
+    if (status_t status = HidlUtils::audioConfigFromHal(*config, true /*isInput*/, &hidlConfig);
+            status != OK) {
+        return status;
+    }
+    CoreUtils::AudioInputFlags hidlFlags;
+    if (status_t status = CoreUtils::audioInputFlagsFromHal(flags, &hidlFlags); status != OK) {
+        return status;
+    }
     Result retval = Result::NOT_INITIALIZED;
 #if MAJOR_VERSION == 2
     auto sinkMetadata = AudioSource(source);
 #elif MAJOR_VERSION >= 4
     // TODO: correctly propagate the tracks sources and volume
     //       for now, only send the main source at 1dbfs
-    SinkMetadata sinkMetadata = {{{ .source = AudioSource(source), .gain = 1 }}};
+    AudioSource hidlSource;
+    if (status_t status = HidlUtils::audioSourceFromHal(source, &hidlSource); status != OK) {
+        return status;
+    }
+    SinkMetadata sinkMetadata = {{{ .source = std::move(hidlSource), .gain = 1 }}};
 #endif
 #if MAJOR_VERSION < 5
     (void)outputDevice;
     (void)outputDeviceAddress;
 #else
+#if MAJOR_VERSION >= 7
+    (void)HidlUtils::audioChannelMaskFromHal(
+            AUDIO_CHANNEL_NONE, true /*isInput*/, &sinkMetadata.tracks[0].channelMask);
+#endif
     if (outputDevice != AUDIO_DEVICE_NONE) {
         DeviceAddress hidlOutputDevice;
-        status = deviceAddressFromHal(outputDevice, outputDeviceAddress, &hidlOutputDevice);
-        if (status != OK) return status;
+        if (status_t status = CoreUtils::deviceAddressFromHal(
+                        outputDevice, outputDeviceAddress, &hidlOutputDevice); status != OK) {
+            return status;
+        }
         sinkMetadata.tracks[0].destination.device(std::move(hidlOutputDevice));
     }
 #endif
@@ -297,11 +283,7 @@
     flags = static_cast<audio_input_flags_t>(flags & ~AUDIO_INPUT_FLAG_DIRECT);
 #endif
     Return<void> ret = mDevice->openInputStream(
-            handle,
-            hidlDevice,
-            hidlConfig,
-            EnumBitfield<AudioInputFlag>(flags),
-            sinkMetadata,
+            handle, hidlDevice, hidlConfig, hidlFlags, sinkMetadata,
             [&](Result r, const sp<IStreamIn>& result, const AudioConfig& suggestedConfig) {
                 retval = r;
                 if (retval == Result::OK) {
@@ -411,7 +393,7 @@
         for (size_t k = 0; k < micArrayHal.size(); k++) {
             audio_microphone_characteristic_t dst;
             //convert
-            microphoneInfoToHal(micArrayHal[k], &dst);
+            (void)CoreUtils::microphoneInfoToHal(micArrayHal[k], &dst);
             media::MicrophoneInfo microphone = media::MicrophoneInfo(dst);
             microphonesInfo->push_back(microphone);
         }
diff --git a/media/libaudiohal/impl/DeviceHalLocal.h b/media/libaudiohal/impl/DeviceHalLocal.h
index d85e2a7..b4eeba5 100644
--- a/media/libaudiohal/impl/DeviceHalLocal.h
+++ b/media/libaudiohal/impl/DeviceHalLocal.h
@@ -114,6 +114,8 @@
     void closeOutputStream(struct audio_stream_out *stream_out);
     void closeInputStream(struct audio_stream_in *stream_in);
 
+    uint32_t version() const { return mDev->common.version; }
+
   private:
     audio_hw_device_t *mDev;
 
@@ -124,8 +126,6 @@
 
     // The destructor automatically closes the device.
     virtual ~DeviceHalLocal();
-
-    uint32_t version() const { return mDev->common.version; }
 };
 
 } // namespace CPP_VERSION
diff --git a/media/libaudiohal/impl/EffectHalHidl.cpp b/media/libaudiohal/impl/EffectHalHidl.cpp
index caf575c..c589a48 100644
--- a/media/libaudiohal/impl/EffectHalHidl.cpp
+++ b/media/libaudiohal/impl/EffectHalHidl.cpp
@@ -23,12 +23,13 @@
 #include <media/EffectsFactoryApi.h>
 #include <utils/Log.h>
 
+#include <util/EffectUtils.h>
+
 #include "EffectBufferHalHidl.h"
 #include "EffectHalHidl.h"
-#include "HidlUtils.h"
 
-using ::android::hardware::audio::common::CPP_VERSION::implementation::HidlUtils;
 using ::android::hardware::audio::common::utils::EnumBitfield;
+using ::android::hardware::audio::effect::CPP_VERSION::implementation::EffectUtils;
 using ::android::hardware::hidl_vec;
 using ::android::hardware::MQDescriptorSync;
 using ::android::hardware::Return;
@@ -42,6 +43,10 @@
 
 EffectHalHidl::EffectHalHidl(const sp<IEffect>& effect, uint64_t effectId)
         : mEffect(effect), mEffectId(effectId), mBuffersChanged(true), mEfGroup(nullptr) {
+    effect_descriptor_t halDescriptor{};
+    if (EffectHalHidl::getDescriptor(&halDescriptor) == NO_ERROR) {
+        mIsInput = (halDescriptor.flags & EFFECT_FLAG_TYPE_PRE_PROC) == EFFECT_FLAG_TYPE_PRE_PROC;
+    }
 }
 
 EffectHalHidl::~EffectHalHidl() {
@@ -56,59 +61,6 @@
 }
 
 // static
-void EffectHalHidl::effectDescriptorToHal(
-        const EffectDescriptor& descriptor, effect_descriptor_t* halDescriptor) {
-    HidlUtils::uuidToHal(descriptor.type, &halDescriptor->type);
-    HidlUtils::uuidToHal(descriptor.uuid, &halDescriptor->uuid);
-    halDescriptor->flags = static_cast<uint32_t>(descriptor.flags);
-    halDescriptor->cpuLoad = descriptor.cpuLoad;
-    halDescriptor->memoryUsage = descriptor.memoryUsage;
-    memcpy(halDescriptor->name, descriptor.name.data(), descriptor.name.size());
-    memcpy(halDescriptor->implementor,
-            descriptor.implementor.data(), descriptor.implementor.size());
-}
-
-// TODO(mnaganov): These buffer conversion functions should be shared with Effect wrapper
-// via HidlUtils. Move them there when hardware/interfaces will get un-frozen again.
-
-// static
-void EffectHalHidl::effectBufferConfigFromHal(
-        const buffer_config_t& halConfig, EffectBufferConfig* config) {
-    config->samplingRateHz = halConfig.samplingRate;
-    config->channels = EnumBitfield<AudioChannelMask>(halConfig.channels);
-    config->format = AudioFormat(halConfig.format);
-    config->accessMode = EffectBufferAccess(halConfig.accessMode);
-    config->mask = EnumBitfield<EffectConfigParameters>(halConfig.mask);
-}
-
-// static
-void EffectHalHidl::effectBufferConfigToHal(
-        const EffectBufferConfig& config, buffer_config_t* halConfig) {
-    halConfig->buffer.frameCount = 0;
-    halConfig->buffer.raw = NULL;
-    halConfig->samplingRate = config.samplingRateHz;
-    halConfig->channels = static_cast<uint32_t>(config.channels);
-    halConfig->bufferProvider.cookie = NULL;
-    halConfig->bufferProvider.getBuffer = NULL;
-    halConfig->bufferProvider.releaseBuffer = NULL;
-    halConfig->format = static_cast<uint8_t>(config.format);
-    halConfig->accessMode = static_cast<uint8_t>(config.accessMode);
-    halConfig->mask = static_cast<uint8_t>(config.mask);
-}
-
-// static
-void EffectHalHidl::effectConfigFromHal(const effect_config_t& halConfig, EffectConfig* config) {
-    effectBufferConfigFromHal(halConfig.inputCfg, &config->inputCfg);
-    effectBufferConfigFromHal(halConfig.outputCfg, &config->outputCfg);
-}
-
-// static
-void EffectHalHidl::effectConfigToHal(const EffectConfig& config, effect_config_t* halConfig) {
-    effectBufferConfigToHal(config.inputCfg, &halConfig->inputCfg);
-    effectBufferConfigToHal(config.outputCfg, &halConfig->outputCfg);
-}
-
-// static
 status_t EffectHalHidl::analyzeResult(const Result& result) {
     switch (result) {
         case Result::OK: return OK;
@@ -269,7 +221,7 @@
             [&](Result r, const EffectDescriptor& result) {
                 retval = r;
                 if (retval == Result::OK) {
-                    effectDescriptorToHal(result, pDescriptor);
+                    EffectUtils::effectDescriptorToHal(result, pDescriptor);
                 }
             });
     return ret.isOk() ? analyzeResult(retval) : FAILED_TRANSACTION;
@@ -301,14 +253,16 @@
         ret = mEffect->getConfig([&] (Result r, const EffectConfig &hidlConfig) {
             result = analyzeResult(r);
             if (r == Result::OK) {
-                effectConfigToHal(hidlConfig, static_cast<effect_config_t*>(pReplyData));
+                EffectUtils::effectConfigToHal(
+                        hidlConfig, static_cast<effect_config_t*>(pReplyData));
             }
         });
     } else {
         ret = mEffect->getConfigReverse([&] (Result r, const EffectConfig &hidlConfig) {
             result = analyzeResult(r);
             if (r == Result::OK) {
-                effectConfigToHal(hidlConfig, static_cast<effect_config_t*>(pReplyData));
+                EffectUtils::effectConfigToHal(
+                        hidlConfig, static_cast<effect_config_t*>(pReplyData));
             }
         });
     }
@@ -332,7 +286,7 @@
         ALOGE("Buffer provider callbacks are not supported");
     }
     EffectConfig hidlConfig;
-    effectConfigFromHal(*halConfig, &hidlConfig);
+    EffectUtils::effectConfigFromHal(*halConfig, mIsInput, &hidlConfig);
     Return<Result> ret = cmdCode == EFFECT_CMD_SET_CONFIG ?
             mEffect->setConfig(hidlConfig, nullptr, nullptr) :
             mEffect->setConfigReverse(hidlConfig, nullptr, nullptr);
diff --git a/media/libaudiohal/impl/EffectHalHidl.h b/media/libaudiohal/impl/EffectHalHidl.h
index 1f238c0..8e46638 100644
--- a/media/libaudiohal/impl/EffectHalHidl.h
+++ b/media/libaudiohal/impl/EffectHalHidl.h
@@ -65,9 +65,6 @@
 
     uint64_t effectId() const { return mEffectId; }
 
-    static void effectDescriptorToHal(
-            const EffectDescriptor& descriptor, effect_descriptor_t* halDescriptor);
-
   private:
     friend class EffectsFactoryHalHidl;
     typedef MessageQueue<Result, hardware::kSynchronizedReadWrite> StatusMQ;
@@ -79,14 +76,9 @@
     bool mBuffersChanged;
     std::unique_ptr<StatusMQ> mStatusMQ;
     EventFlag* mEfGroup;
+    bool mIsInput = false;
 
     static status_t analyzeResult(const Result& result);
-    static void effectBufferConfigFromHal(
-            const buffer_config_t& halConfig, EffectBufferConfig* config);
-    static void effectBufferConfigToHal(
-            const EffectBufferConfig& config, buffer_config_t* halConfig);
-    static void effectConfigFromHal(const effect_config_t& halConfig, EffectConfig* config);
-    static void effectConfigToHal(const EffectConfig& config, effect_config_t* halConfig);
 
     // Can not be constructed directly by clients.
     EffectHalHidl(const sp<IEffect>& effect, uint64_t effectId);
diff --git a/media/libaudiohal/impl/EffectsFactoryHalHidl.cpp b/media/libaudiohal/impl/EffectsFactoryHalHidl.cpp
index 9192a31..8d15592 100644
--- a/media/libaudiohal/impl/EffectsFactoryHalHidl.cpp
+++ b/media/libaudiohal/impl/EffectsFactoryHalHidl.cpp
@@ -19,13 +19,16 @@
 
 #include <cutils/native_handle.h>
 
+#include <UuidUtils.h>
+#include <util/EffectUtils.h>
+
 #include "ConversionHelperHidl.h"
 #include "EffectBufferHalHidl.h"
 #include "EffectHalHidl.h"
 #include "EffectsFactoryHalHidl.h"
-#include "HidlUtils.h"
 
-using ::android::hardware::audio::common::CPP_VERSION::implementation::HidlUtils;
+using ::android::hardware::audio::common::CPP_VERSION::implementation::UuidUtils;
+using ::android::hardware::audio::effect::CPP_VERSION::implementation::EffectUtils;
 using ::android::hardware::Return;
 
 namespace android {
@@ -76,7 +79,7 @@
         if (queryResult != OK) return queryResult;
     }
     if (index >= mLastDescriptors.size()) return NAME_NOT_FOUND;
-    EffectHalHidl::effectDescriptorToHal(mLastDescriptors[index], pDescriptor);
+    EffectUtils::effectDescriptorToHal(mLastDescriptors[index], pDescriptor);
     return OK;
 }
 
@@ -85,13 +88,13 @@
     // TODO: check for nullptr
     if (mEffectsFactory == 0) return NO_INIT;
     Uuid hidlUuid;
-    HidlUtils::uuidFromHal(*pEffectUuid, &hidlUuid);
+    UuidUtils::uuidFromHal(*pEffectUuid, &hidlUuid);
     Result retval = Result::NOT_INITIALIZED;
     Return<void> ret = mEffectsFactory->getDescriptor(hidlUuid,
             [&](Result r, const EffectDescriptor& result) {
                 retval = r;
                 if (retval == Result::OK) {
-                    EffectHalHidl::effectDescriptorToHal(result, pDescriptor);
+                    EffectUtils::effectDescriptorToHal(result, pDescriptor);
                 }
             });
     if (ret.isOk()) {
@@ -107,7 +110,7 @@
         int32_t deviceId __unused, sp<EffectHalInterface> *effect) {
     if (mEffectsFactory == 0) return NO_INIT;
     Uuid hidlUuid;
-    HidlUtils::uuidFromHal(*pEffectUuid, &hidlUuid);
+    UuidUtils::uuidFromHal(*pEffectUuid, &hidlUuid);
     Result retval = Result::NOT_INITIALIZED;
     Return<void> ret;
 #if MAJOR_VERSION >= 6
diff --git a/media/libaudiohal/impl/VersionUtils.h b/media/libaudiohal/impl/ParameterUtils.h
similarity index 91%
rename from media/libaudiohal/impl/VersionUtils.h
rename to media/libaudiohal/impl/ParameterUtils.h
index eb0a42a..9cab72e 100644
--- a/media/libaudiohal/impl/VersionUtils.h
+++ b/media/libaudiohal/impl/ParameterUtils.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2018 The Android Open Source Project
+ * Copyright (C) 2021 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.
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef ANDROID_HARDWARE_VERSION_UTILS_H
-#define ANDROID_HARDWARE_VERSION_UTILS_H
+#pragma once
 
 #include PATH(android/hardware/audio/FILE_VERSION/types.h)
 #include <hidl/HidlSupport.h>
@@ -59,5 +58,3 @@
 } // namespace utils
 } // namespace CPP_VERSION
 } // namespace android
-
-#endif // ANDROID_HARDWARE_VERSION_UTILS_H
diff --git a/media/libaudiohal/impl/StreamHalHidl.cpp b/media/libaudiohal/impl/StreamHalHidl.cpp
index 2726e36..6da8bbd 100644
--- a/media/libaudiohal/impl/StreamHalHidl.cpp
+++ b/media/libaudiohal/impl/StreamHalHidl.cpp
@@ -17,17 +17,23 @@
 #define LOG_TAG "StreamHalHidl"
 //#define LOG_NDEBUG 0
 
-#include PATH(android/hardware/audio/FILE_VERSION/IStreamOutCallback.h)
+#include <android/hidl/manager/1.0/IServiceManager.h>
 #include <hwbinder/IPCThreadState.h>
 #include <media/AudioParameter.h>
 #include <mediautils/SchedulingPolicyService.h>
 #include <utils/Log.h>
 
+#include PATH(android/hardware/audio/FILE_VERSION/IStreamOutCallback.h)
+#include <HidlUtils.h>
+#include <util/CoreUtils.h>
+
 #include "DeviceHalHidl.h"
 #include "EffectHalHidl.h"
+#include "ParameterUtils.h"
 #include "StreamHalHidl.h"
-#include "VersionUtils.h"
 
+using ::android::hardware::audio::common::CPP_VERSION::implementation::HidlUtils;
+using ::android::hardware::audio::CPP_VERSION::implementation::CoreUtils;
 using ::android::hardware::MQDescriptorSync;
 using ::android::hardware::Return;
 using ::android::hardware::Void;
@@ -49,14 +55,11 @@
 
     // Instrument audio signal power logging.
     // Note: This assumes channel mask, format, and sample rate do not change after creation.
-    if (mStream != nullptr /* && mStreamPowerLog.isUserDebugOrEngBuild() */) {
-        // Obtain audio properties (see StreamHalHidl::getAudioProperties() below).
-        Return<void> ret = mStream->getAudioProperties(
-                [&](auto sr, auto m, auto f) {
-                mStreamPowerLog.init(sr,
-                        static_cast<audio_channel_mask_t>(m),
-                        static_cast<audio_format_t>(f));
-            });
+    audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
+    if (/* mStreamPowerLog.isUserDebugOrEngBuild() && */
+        StreamHalHidl::getAudioProperties(
+                &config.sample_rate, &config.channel_mask, &config.format) == NO_ERROR) {
+        mStreamPowerLog.init(config.sample_rate, config.channel_mask, config.format);
     }
 }
 
@@ -64,9 +67,12 @@
     mStream = nullptr;
 }
 
+// Note: this method will be removed
 status_t StreamHalHidl::getSampleRate(uint32_t *rate) {
-    if (!mStream) return NO_INIT;
-    return processReturn("getSampleRate", mStream->getSampleRate(), rate);
+    audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
+    status_t status = getAudioProperties(&config.sample_rate, &config.channel_mask, &config.format);
+    *rate = config.sample_rate;
+    return status;
 }
 
 status_t StreamHalHidl::getBufferSize(size_t *size) {
@@ -78,19 +84,26 @@
     return status;
 }
 
+// Note: this method will be removed
 status_t StreamHalHidl::getChannelMask(audio_channel_mask_t *mask) {
-    if (!mStream) return NO_INIT;
-    return processReturn("getChannelMask", mStream->getChannelMask(), mask);
+    audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
+    status_t status = getAudioProperties(&config.sample_rate, &config.channel_mask, &config.format);
+    *mask = config.channel_mask;
+    return status;
 }
 
+// Note: this method will be removed
 status_t StreamHalHidl::getFormat(audio_format_t *format) {
-    if (!mStream) return NO_INIT;
-    return processReturn("getFormat", mStream->getFormat(), format);
+    audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
+    status_t status = getAudioProperties(&config.sample_rate, &config.channel_mask, &config.format);
+    *format = config.format;
+    return status;
 }
 
 status_t StreamHalHidl::getAudioProperties(
         uint32_t *sampleRate, audio_channel_mask_t *mask, audio_format_t *format) {
     if (!mStream) return NO_INIT;
+#if MAJOR_VERSION <= 6
     Return<void> ret = mStream->getAudioProperties(
             [&](uint32_t sr, auto m, auto f) {
                 *sampleRate = sr;
@@ -98,6 +111,26 @@
                 *format = static_cast<audio_format_t>(f);
             });
     return processReturn("getAudioProperties", ret);
+#else
+    Result retval;
+    status_t conversionStatus = BAD_VALUE;
+    audio_config_base_t halConfig = AUDIO_CONFIG_BASE_INITIALIZER;
+    Return<void> ret = mStream->getAudioProperties(
+            [&](Result r, const AudioConfigBase& config) {
+                retval = r;
+                if (retval == Result::OK) {
+                    conversionStatus = HidlUtils::audioConfigBaseToHal(config, &halConfig);
+                }
+            });
+    if (status_t status = processReturn("getAudioProperties", ret, retval); status == NO_ERROR) {
+        *sampleRate = halConfig.sample_rate;
+        *mask = halConfig.channel_mask;
+        *format = halConfig.format;
+        return conversionStatus;
+    } else {
+        return status;
+    }
+#endif
 }
 
 status_t StreamHalHidl::setParameters(const String8& kvPairs) {
@@ -225,6 +258,24 @@
     return getBufferSize(size);
 }
 
+status_t StreamHalHidl::getHalPid(pid_t *pid) {
+    using ::android::hidl::base::V1_0::DebugInfo;
+    using ::android::hidl::manager::V1_0::IServiceManager;
+
+    DebugInfo debugInfo;
+    auto ret = mStream->getDebugInfo([&] (const auto &info) {
+        debugInfo = info;
+    });
+    if (!ret.isOk()) {
+        return INVALID_OPERATION;
+    }
+    if (debugInfo.pid != (int)IServiceManager::PidConstant::NO_PID) {
+        *pid = debugInfo.pid;
+        return NO_ERROR;
+    }
+    return NAME_NOT_FOUND;
+}
+
 bool StreamHalHidl::requestHalThreadPriority(pid_t threadPid, pid_t threadId) {
     if (mHalThreadPriority == HAL_THREAD_PRIORITY_DEFAULT) {
         return true;
@@ -453,7 +504,7 @@
                     const CommandMQ::Descriptor& commandMQ,
                     const DataMQ::Descriptor& dataMQ,
                     const StatusMQ::Descriptor& statusMQ,
-                    const ThreadInfo& halThreadInfo) {
+                    const auto& halThreadInfo) {
                 retval = r;
                 if (retval == Result::OK) {
                     tempCommandMQ.reset(new CommandMQ(commandMQ));
@@ -462,8 +513,12 @@
                     if (tempDataMQ->isValid() && tempDataMQ->getEventFlagWord()) {
                         EventFlag::createEventFlag(tempDataMQ->getEventFlagWord(), &mEfGroup);
                     }
+#if MAJOR_VERSION <= 6
                     halThreadPid = halThreadInfo.pid;
                     halThreadTid = halThreadInfo.tid;
+#else
+                    halThreadTid = halThreadInfo;
+#endif
                 }
             });
     if (!ret.isOk() || retval != Result::OK) {
@@ -484,6 +539,11 @@
         ALOGE_IF(!mEfGroup, "Event flag creation for writing failed");
         return NO_INIT;
     }
+#if MAJOR_VERSION >= 7
+    if (status_t status = getHalPid(&halThreadPid); status != NO_ERROR) {
+        return status;
+    }
+#endif
     requestHalThreadPriority(halThreadPid, halThreadTid);
 
     mCommandMQ = std::move(tempCommandMQ);
@@ -597,31 +657,45 @@
     return INVALID_OPERATION;
 }
 #elif MAJOR_VERSION >= 4
-/** Transform a standard collection to an HIDL vector. */
-template <class Values, class ElementConverter>
-static auto transformToHidlVec(const Values& values, ElementConverter converter) {
-    hidl_vec<decltype(converter(*values.begin()))> result{values.size()};
-    using namespace std;
-    transform(begin(values), end(values), begin(result), converter);
-    return result;
-}
-
 status_t StreamOutHalHidl::updateSourceMetadata(
         const StreamOutHalInterface::SourceMetadata& sourceMetadata) {
-    CPP_VERSION::SourceMetadata halMetadata = {
-        .tracks = transformToHidlVec(sourceMetadata.tracks,
-              [](const playback_track_metadata& metadata) -> PlaybackTrackMetadata {
-                  return {
-                    .usage=static_cast<AudioUsage>(metadata.usage),
-                    .contentType=static_cast<AudioContentType>(metadata.content_type),
-                    .gain=metadata.gain,
-                  };
-              })};
-    return processReturn("updateSourceMetadata", mStream->updateSourceMetadata(halMetadata));
+    CPP_VERSION::SourceMetadata hidlMetadata;
+    if (status_t status = CoreUtils::sourceMetadataFromHalV7(
+                    sourceMetadata.tracks, true /*ignoreNonVendorTags*/, &hidlMetadata);
+            status != OK) {
+        return status;
+    }
+    return processReturn("updateSourceMetadata", mStream->updateSourceMetadata(hidlMetadata));
 }
 #endif
 
 #if MAJOR_VERSION < 6
+status_t StreamOutHalHidl::getDualMonoMode(audio_dual_mono_mode_t* mode __unused) {
+    return INVALID_OPERATION;
+}
+
+status_t StreamOutHalHidl::setDualMonoMode(audio_dual_mono_mode_t mode __unused) {
+    return INVALID_OPERATION;
+}
+
+status_t StreamOutHalHidl::getAudioDescriptionMixLevel(float* leveldB __unused) {
+    return INVALID_OPERATION;
+}
+
+status_t StreamOutHalHidl::setAudioDescriptionMixLevel(float leveldB __unused) {
+    return INVALID_OPERATION;
+}
+
+status_t StreamOutHalHidl::getPlaybackRateParameters(
+        audio_playback_rate_t* playbackRate __unused) {
+    return INVALID_OPERATION;
+}
+
+status_t StreamOutHalHidl::setPlaybackRateParameters(
+        const audio_playback_rate_t& playbackRate __unused) {
+    return INVALID_OPERATION;
+}
+
 status_t StreamOutHalHidl::setEventCallback(
         const sp<StreamOutHalInterfaceEventCallback>& callback __unused) {
     // Codec format callback is supported starting from audio HAL V6.0
@@ -629,6 +703,73 @@
 }
 #else
 
+status_t StreamOutHalHidl::getDualMonoMode(audio_dual_mono_mode_t* mode) {
+    if (mStream == 0) return NO_INIT;
+    Result retval;
+    Return<void> ret = mStream->getDualMonoMode(
+            [&](Result r, DualMonoMode hidlMode) {
+                retval = r;
+                if (retval == Result::OK) {
+                    *mode = static_cast<audio_dual_mono_mode_t>(hidlMode);
+                }
+            });
+    return processReturn("getDualMonoMode", ret, retval);
+}
+
+status_t StreamOutHalHidl::setDualMonoMode(audio_dual_mono_mode_t mode) {
+    if (mStream == 0) return NO_INIT;
+    return processReturn(
+            "setDualMonoMode", mStream->setDualMonoMode(static_cast<DualMonoMode>(mode)));
+}
+
+status_t StreamOutHalHidl::getAudioDescriptionMixLevel(float* leveldB) {
+    if (mStream == 0) return NO_INIT;
+    Result retval;
+    Return<void> ret = mStream->getAudioDescriptionMixLevel(
+            [&](Result r, float hidlLeveldB) {
+                retval = r;
+                if (retval == Result::OK) {
+                    *leveldB = hidlLeveldB;
+                }
+            });
+    return processReturn("getAudioDescriptionMixLevel", ret, retval);
+}
+
+status_t StreamOutHalHidl::setAudioDescriptionMixLevel(float leveldB) {
+    if (mStream == 0) return NO_INIT;
+    return processReturn(
+            "setAudioDescriptionMixLevel", mStream->setAudioDescriptionMixLevel(leveldB));
+}
+
+status_t StreamOutHalHidl::getPlaybackRateParameters(audio_playback_rate_t* playbackRate) {
+    if (mStream == 0) return NO_INIT;
+    Result retval;
+    Return<void> ret = mStream->getPlaybackRateParameters(
+            [&](Result r, PlaybackRate hidlPlaybackRate) {
+                retval = r;
+                if (retval == Result::OK) {
+                    playbackRate->mSpeed = hidlPlaybackRate.speed;
+                    playbackRate->mPitch = hidlPlaybackRate.pitch;
+                    playbackRate->mStretchMode =
+                        static_cast<audio_timestretch_stretch_mode_t>(
+                            hidlPlaybackRate.timestretchMode);
+                    playbackRate->mFallbackMode =
+                        static_cast<audio_timestretch_fallback_mode_t>(
+                            hidlPlaybackRate.fallbackMode);
+                }
+            });
+    return processReturn("getPlaybackRateParameters", ret, retval);
+}
+
+status_t StreamOutHalHidl::setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) {
+    if (mStream == 0) return NO_INIT;
+    return processReturn(
+            "setPlaybackRateParameters", mStream->setPlaybackRateParameters(
+                PlaybackRate{playbackRate.mSpeed, playbackRate.mPitch,
+                    static_cast<TimestretchMode>(playbackRate.mStretchMode),
+                    static_cast<TimestretchFallbackMode>(playbackRate.mFallbackMode)}));
+}
+
 #include PATH(android/hardware/audio/FILE_VERSION/IStreamOutEventCallback.h)
 
 namespace {
@@ -797,7 +938,7 @@
                     const CommandMQ::Descriptor& commandMQ,
                     const DataMQ::Descriptor& dataMQ,
                     const StatusMQ::Descriptor& statusMQ,
-                    const ThreadInfo& halThreadInfo) {
+                    const auto& halThreadInfo) {
                 retval = r;
                 if (retval == Result::OK) {
                     tempCommandMQ.reset(new CommandMQ(commandMQ));
@@ -806,8 +947,12 @@
                     if (tempDataMQ->isValid() && tempDataMQ->getEventFlagWord()) {
                         EventFlag::createEventFlag(tempDataMQ->getEventFlagWord(), &mEfGroup);
                     }
+#if MAJOR_VERSION <= 6
                     halThreadPid = halThreadInfo.pid;
                     halThreadTid = halThreadInfo.tid;
+#else
+                    halThreadTid = halThreadInfo;
+#endif
                 }
             });
     if (!ret.isOk() || retval != Result::OK) {
@@ -828,6 +973,11 @@
         ALOGE_IF(!mEfGroup, "Event flag creation for reading failed");
         return NO_INIT;
     }
+#if MAJOR_VERSION >= 7
+    if (status_t status = getHalPid(&halThreadPid); status != NO_ERROR) {
+        return status;
+    }
+#endif
     requestHalThreadPriority(halThreadPid, halThreadTid);
 
     mCommandMQ = std::move(tempCommandMQ);
@@ -890,7 +1040,7 @@
         for (size_t k = 0; k < micArrayHal.size(); k++) {
             audio_microphone_characteristic_t dst;
             // convert
-            microphoneInfoToHal(micArrayHal[k], &dst);
+            (void)CoreUtils::microphoneInfoToHal(micArrayHal[k], &dst);
             media::MicrophoneInfo microphone = media::MicrophoneInfo(dst);
             microphonesInfo->push_back(microphone);
         }
@@ -900,15 +1050,13 @@
 
 status_t StreamInHalHidl::updateSinkMetadata(const
         StreamInHalInterface::SinkMetadata& sinkMetadata) {
-    CPP_VERSION::SinkMetadata halMetadata = {
-        .tracks = transformToHidlVec(sinkMetadata.tracks,
-              [](const record_track_metadata& metadata) -> RecordTrackMetadata {
-                  return {
-                    .source=static_cast<AudioSource>(metadata.source),
-                    .gain=metadata.gain,
-                  };
-              })};
-    return processReturn("updateSinkMetadata", mStream->updateSinkMetadata(halMetadata));
+    CPP_VERSION::SinkMetadata hidlMetadata;
+    if (status_t status = CoreUtils::sinkMetadataFromHalV7(
+                    sinkMetadata.tracks, true /*ignoreNonVendorTags*/, &hidlMetadata);
+            status != OK) {
+        return status;
+    }
+    return processReturn("updateSinkMetadata", mStream->updateSinkMetadata(hidlMetadata));
 }
 #endif
 
diff --git a/media/libaudiohal/impl/StreamHalHidl.h b/media/libaudiohal/impl/StreamHalHidl.h
index 88f8587..72ce60b 100644
--- a/media/libaudiohal/impl/StreamHalHidl.h
+++ b/media/libaudiohal/impl/StreamHalHidl.h
@@ -105,6 +105,8 @@
 
     status_t getCachedBufferSize(size_t *size);
 
+    status_t getHalPid(pid_t *pid);
+
     bool requestHalThreadPriority(pid_t threadPid, pid_t threadId);
 
     // mStreamPowerLog is used for audio signal power logging.
@@ -173,6 +175,24 @@
     void onDrainReady();
     void onError();
 
+    // Returns the Dual Mono mode presentation setting.
+    status_t getDualMonoMode(audio_dual_mono_mode_t* mode) override;
+
+    // Sets the Dual Mono mode presentation on the output device.
+    status_t setDualMonoMode(audio_dual_mono_mode_t mode) override;
+
+    // Returns the Audio Description Mix level in dB.
+    status_t getAudioDescriptionMixLevel(float* leveldB) override;
+
+    // Sets the Audio Description Mix level in dB.
+    status_t setAudioDescriptionMixLevel(float leveldB) override;
+
+    // Retrieves current playback rate parameters.
+    status_t getPlaybackRateParameters(audio_playback_rate_t* playbackRate) override;
+
+    // Sets the playback rate parameters that control playback behavior.
+    status_t setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) override;
+
     status_t setEventCallback(const sp<StreamOutHalInterfaceEventCallback>& callback) override;
 
     // Methods used by StreamCodecFormatCallback (HIDL).
diff --git a/media/libaudiohal/impl/StreamHalLocal.cpp b/media/libaudiohal/impl/StreamHalLocal.cpp
index 69be303..e89b288 100644
--- a/media/libaudiohal/impl/StreamHalLocal.cpp
+++ b/media/libaudiohal/impl/StreamHalLocal.cpp
@@ -22,8 +22,8 @@
 #include <utils/Log.h>
 
 #include "DeviceHalLocal.h"
+#include "ParameterUtils.h"
 #include "StreamHalLocal.h"
-#include "VersionUtils.h"
 
 namespace android {
 namespace CPP_VERSION {
@@ -241,19 +241,55 @@
     return mStream->get_presentation_position(mStream, frames, timestamp);
 }
 
+void StreamOutHalLocal::doUpdateSourceMetadata(const SourceMetadata& sourceMetadata) {
+    std::vector<playback_track_metadata> halTracks;
+    halTracks.reserve(sourceMetadata.tracks.size());
+    for (auto& metadata : sourceMetadata.tracks) {
+        playback_track_metadata halTrackMetadata;
+        playback_track_metadata_from_v7(&halTrackMetadata, &metadata);
+        halTracks.push_back(halTrackMetadata);
+    }
+    const source_metadata_t halMetadata = {
+        .track_count = halTracks.size(),
+        .tracks = halTracks.data(),
+    };
+    mStream->update_source_metadata(mStream, &halMetadata);
+}
+
+#if MAJOR_VERSION >= 7
+void StreamOutHalLocal::doUpdateSourceMetadataV7(const SourceMetadata& sourceMetadata) {
+    const source_metadata_v7_t metadata {
+        .track_count = sourceMetadata.tracks.size(),
+        // const cast is fine as it is in a const structure
+        .tracks = const_cast<playback_track_metadata_v7*>(sourceMetadata.tracks.data()),
+    };
+    mStream->update_source_metadata_v7(mStream, &metadata);
+}
+#endif
+
 status_t StreamOutHalLocal::updateSourceMetadata(const SourceMetadata& sourceMetadata) {
+#if MAJOR_VERSION < 7
     if (mStream->update_source_metadata == nullptr) {
         return INVALID_OPERATION;
     }
-    const source_metadata_t metadata {
-        .track_count = sourceMetadata.tracks.size(),
-        // const cast is fine as it is in a const structure
-        .tracks = const_cast<playback_track_metadata*>(sourceMetadata.tracks.data()),
-    };
-    mStream->update_source_metadata(mStream, &metadata);
+    doUpdateSourceMetadata(sourceMetadata);
+#else
+    if (mDevice->version() < AUDIO_DEVICE_API_VERSION_3_2) {
+        if (mStream->update_source_metadata == nullptr) {
+            return INVALID_OPERATION;
+        }
+        doUpdateSourceMetadata(sourceMetadata);
+    } else {
+        if (mStream->update_source_metadata_v7 == nullptr) {
+            return INVALID_OPERATION;
+        }
+        doUpdateSourceMetadataV7(sourceMetadata);
+    }
+#endif
     return OK;
 }
 
+
 status_t StreamOutHalLocal::start() {
     if (mStream->start == NULL) return INVALID_OPERATION;
     return mStream->start(mStream);
@@ -275,6 +311,36 @@
     return mStream->get_mmap_position(mStream, position);
 }
 
+status_t StreamOutHalLocal::getDualMonoMode(audio_dual_mono_mode_t* mode) {
+    if (mStream->get_dual_mono_mode == nullptr) return INVALID_OPERATION;
+    return mStream->get_dual_mono_mode(mStream, mode);
+}
+
+status_t StreamOutHalLocal::setDualMonoMode(audio_dual_mono_mode_t mode) {
+    if (mStream->set_dual_mono_mode == nullptr) return INVALID_OPERATION;
+    return mStream->set_dual_mono_mode(mStream, mode);
+}
+
+status_t StreamOutHalLocal::getAudioDescriptionMixLevel(float* leveldB) {
+    if (mStream->get_audio_description_mix_level == nullptr) return INVALID_OPERATION;
+    return mStream->get_audio_description_mix_level(mStream, leveldB);
+}
+
+status_t StreamOutHalLocal::setAudioDescriptionMixLevel(float leveldB) {
+    if (mStream->set_audio_description_mix_level == nullptr) return INVALID_OPERATION;
+    return mStream->set_audio_description_mix_level(mStream, leveldB);
+}
+
+status_t StreamOutHalLocal::getPlaybackRateParameters(audio_playback_rate_t* playbackRate) {
+    if (mStream->get_playback_rate_parameters == nullptr) return INVALID_OPERATION;
+    return mStream->get_playback_rate_parameters(mStream, playbackRate);
+}
+
+status_t StreamOutHalLocal::setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) {
+    if (mStream->set_playback_rate_parameters == nullptr) return INVALID_OPERATION;
+    return mStream->set_playback_rate_parameters(mStream, &playbackRate);
+}
+
 status_t StreamOutHalLocal::setEventCallback(
         const sp<StreamOutHalInterfaceEventCallback>& callback) {
     if (mStream->set_event_callback == nullptr) {
@@ -352,16 +418,51 @@
     return mStream->get_capture_position(mStream, frames, time);
 }
 
-status_t StreamInHalLocal::updateSinkMetadata(const SinkMetadata& sinkMetadata) {
-    if (mStream->update_sink_metadata == nullptr) {
-        return INVALID_OPERATION;
+void StreamInHalLocal::doUpdateSinkMetadata(const SinkMetadata& sinkMetadata) {
+    std::vector<record_track_metadata> halTracks;
+    halTracks.reserve(sinkMetadata.tracks.size());
+    for (auto& metadata : sinkMetadata.tracks) {
+        record_track_metadata halTrackMetadata;
+        record_track_metadata_from_v7(&halTrackMetadata, &metadata);
+        halTracks.push_back(halTrackMetadata);
     }
-    const sink_metadata_t metadata {
+    const sink_metadata_t halMetadata = {
+        .track_count = halTracks.size(),
+        .tracks = halTracks.data(),
+    };
+    mStream->update_sink_metadata(mStream, &halMetadata);
+}
+
+#if MAJOR_VERSION >= 7
+void StreamInHalLocal::doUpdateSinkMetadataV7(const SinkMetadata& sinkMetadata) {
+    const sink_metadata_v7_t halMetadata {
         .track_count = sinkMetadata.tracks.size(),
         // const cast is fine as it is in a const structure
-        .tracks = const_cast<record_track_metadata*>(sinkMetadata.tracks.data()),
+        .tracks = const_cast<record_track_metadata_v7*>(sinkMetadata.tracks.data()),
     };
-    mStream->update_sink_metadata(mStream, &metadata);
+    mStream->update_sink_metadata_v7(mStream, &halMetadata);
+}
+#endif
+
+status_t StreamInHalLocal::updateSinkMetadata(const SinkMetadata& sinkMetadata) {
+#if MAJOR_VERSION < 7
+    if (mStream->update_sink_metadata == nullptr) {
+        return INVALID_OPERATION;  // not supported by the HAL
+    }
+    doUpdateSinkMetadata(sinkMetadata);
+#else
+    if (mDevice->version() < AUDIO_DEVICE_API_VERSION_3_2) {
+        if (mStream->update_sink_metadata == nullptr) {
+            return INVALID_OPERATION;  // not supported by the HAL
+        }
+        doUpdateSinkMetadata(sinkMetadata);
+    } else {
+        if (mStream->update_sink_metadata_v7 == nullptr) {
+            return INVALID_OPERATION;  // not supported by the HAL
+        }
+        doUpdateSinkMetadataV7(sinkMetadata);
+    }
+#endif
     return OK;
 }
 
diff --git a/media/libaudiohal/impl/StreamHalLocal.h b/media/libaudiohal/impl/StreamHalLocal.h
index d17f9f3..e228104 100644
--- a/media/libaudiohal/impl/StreamHalLocal.h
+++ b/media/libaudiohal/impl/StreamHalLocal.h
@@ -156,6 +156,24 @@
     // Called when the metadata of the stream's source has been changed.
     status_t updateSourceMetadata(const SourceMetadata& sourceMetadata) override;
 
+    // Returns the Dual Mono mode presentation setting.
+    status_t getDualMonoMode(audio_dual_mono_mode_t* mode) override;
+
+    // Sets the Dual Mono mode presentation on the output device.
+    status_t setDualMonoMode(audio_dual_mono_mode_t mode) override;
+
+    // Returns the Audio Description Mix level in dB.
+    status_t getAudioDescriptionMixLevel(float* leveldB) override;
+
+    // Sets the Audio Description Mix level in dB.
+    status_t setAudioDescriptionMixLevel(float leveldB) override;
+
+    // Retrieves current playback rate parameters.
+    status_t getPlaybackRateParameters(audio_playback_rate_t* playbackRate) override;
+
+    // Sets the playback rate parameters that control playback behavior.
+    status_t setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) override;
+
     status_t setEventCallback(const sp<StreamOutHalInterfaceEventCallback>& callback) override;
 
   private:
@@ -173,6 +191,9 @@
     static int asyncCallback(stream_callback_event_t event, void *param, void *cookie);
 
     static int asyncEventCallback(stream_event_callback_type_t event, void *param, void *cookie);
+
+    void doUpdateSourceMetadataV7(const SourceMetadata& sourceMetadata);
+    void doUpdateSourceMetadata(const SourceMetadata& sourceMetadata);
 };
 
 class StreamInHalLocal : public StreamInHalInterface, public StreamHalLocal {
@@ -227,6 +248,9 @@
     StreamInHalLocal(audio_stream_in_t *stream, sp<DeviceHalLocal> device);
 
     virtual ~StreamInHalLocal();
+
+    void doUpdateSinkMetadata(const SinkMetadata& sinkMetadata);
+    void doUpdateSinkMetadataV7(const SinkMetadata& sinkMetadata);
 };
 
 } // namespace CPP_VERSION
diff --git a/media/libaudiohal/impl/StreamPowerLog.h b/media/libaudiohal/impl/StreamPowerLog.h
index 5fd3912..f6a554b 100644
--- a/media/libaudiohal/impl/StreamPowerLog.h
+++ b/media/libaudiohal/impl/StreamPowerLog.h
@@ -19,6 +19,7 @@
 
 #include <audio_utils/clock.h>
 #include <audio_utils/PowerLog.h>
+#include <cutils/bitops.h>
 #include <cutils/properties.h>
 #include <system/audio.h>
 
diff --git a/media/libaudiohal/include/media/audiohal/StreamHalInterface.h b/media/libaudiohal/include/media/audiohal/StreamHalInterface.h
index e30cb72..b47f536 100644
--- a/media/libaudiohal/include/media/audiohal/StreamHalInterface.h
+++ b/media/libaudiohal/include/media/audiohal/StreamHalInterface.h
@@ -31,18 +31,22 @@
 class StreamHalInterface : public virtual RefBase
 {
   public:
+    // TODO(mnaganov): Remove
     // Return the sampling rate in Hz - eg. 44100.
     virtual status_t getSampleRate(uint32_t *rate) = 0;
 
     // Return size of input/output buffer in bytes for this stream - eg. 4800.
     virtual status_t getBufferSize(size_t *size) = 0;
 
+    // TODO(mnaganov): Remove
     // Return the channel mask.
     virtual status_t getChannelMask(audio_channel_mask_t *mask) = 0;
 
+    // TODO(mnaganov): Remove
     // Return the audio format - e.g. AUDIO_FORMAT_PCM_16_BIT.
     virtual status_t getFormat(audio_format_t *format) = 0;
 
+    // TODO(mnaganov): Change to use audio_config_base_t
     // Convenience method.
     virtual status_t getAudioProperties(
             uint32_t *sampleRate, audio_channel_mask_t *mask, audio_format_t *format) = 0;
@@ -158,14 +162,33 @@
     virtual status_t getPresentationPosition(uint64_t *frames, struct timespec *timestamp) = 0;
 
     struct SourceMetadata {
-        std::vector<playback_track_metadata_t> tracks;
+        std::vector<playback_track_metadata_v7_t> tracks;
     };
+
     /**
      * Called when the metadata of the stream's source has been changed.
      * @param sourceMetadata Description of the audio that is played by the clients.
      */
     virtual status_t updateSourceMetadata(const SourceMetadata& sourceMetadata) = 0;
 
+    // Returns the Dual Mono mode presentation setting.
+    virtual status_t getDualMonoMode(audio_dual_mono_mode_t* mode) = 0;
+
+    // Sets the Dual Mono mode presentation on the output device.
+    virtual status_t setDualMonoMode(audio_dual_mono_mode_t mode) = 0;
+
+    // Returns the Audio Description Mix level in dB.
+    virtual status_t getAudioDescriptionMixLevel(float* leveldB) = 0;
+
+    // Sets the Audio Description Mix level in dB.
+    virtual status_t setAudioDescriptionMixLevel(float leveldB) = 0;
+
+    // Retrieves current playback rate parameters.
+    virtual status_t getPlaybackRateParameters(audio_playback_rate_t* playbackRate) = 0;
+
+    // Sets the playback rate parameters that control playback behavior.
+    virtual status_t setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) = 0;
+
     virtual status_t setEventCallback(const sp<StreamOutHalInterfaceEventCallback>& callback) = 0;
 
   protected:
@@ -197,7 +220,7 @@
     virtual status_t setPreferredMicrophoneFieldDimension(float zoom) = 0;
 
     struct SinkMetadata {
-        std::vector<record_track_metadata_t> tracks;
+        std::vector<record_track_metadata_v7_t> tracks;
     };
     /**
      * Called when the metadata of the stream's sink has been changed.
diff --git a/media/libaudioprocessing/Android.bp b/media/libaudioprocessing/Android.bp
index 39b0ceb..309765a 100644
--- a/media/libaudioprocessing/Android.bp
+++ b/media/libaudioprocessing/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "libaudioprocessing_defaults",
 
diff --git a/media/libaudioprocessing/AudioMixer.cpp b/media/libaudioprocessing/AudioMixer.cpp
index 1a31420..00baea2 100644
--- a/media/libaudioprocessing/AudioMixer.cpp
+++ b/media/libaudioprocessing/AudioMixer.cpp
@@ -79,10 +79,14 @@
             && mixerChannelMask == (track->mMixerChannelMask | track->mMixerHapticChannelMask)) {
         return false;  // no need to change
     }
-    const audio_channel_mask_t hapticChannelMask = trackChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
-    trackChannelMask &= ~AUDIO_CHANNEL_HAPTIC_ALL;
-    const audio_channel_mask_t mixerHapticChannelMask = mixerChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
-    mixerChannelMask &= ~AUDIO_CHANNEL_HAPTIC_ALL;
+    const audio_channel_mask_t hapticChannelMask =
+            static_cast<audio_channel_mask_t>(trackChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
+    trackChannelMask = static_cast<audio_channel_mask_t>(
+            trackChannelMask & ~AUDIO_CHANNEL_HAPTIC_ALL);
+    const audio_channel_mask_t mixerHapticChannelMask = static_cast<audio_channel_mask_t>(
+            mixerChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
+    mixerChannelMask = static_cast<audio_channel_mask_t>(
+            mixerChannelMask & ~AUDIO_CHANNEL_HAPTIC_ALL);
     // always recompute for both channel masks even if only one has changed.
     const uint32_t trackChannelCount = audio_channel_count_from_out_mask(trackChannelMask);
     const uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mixerChannelMask);
@@ -362,7 +366,8 @@
             const audio_channel_mask_t trackChannelMask =
                 static_cast<audio_channel_mask_t>(valueInt);
             if (setChannelMasks(name, trackChannelMask,
-                    (track->mMixerChannelMask | track->mMixerHapticChannelMask))) {
+                    static_cast<audio_channel_mask_t>(
+                            track->mMixerChannelMask | track->mMixerHapticChannelMask))) {
                 ALOGV("setParameter(TRACK, CHANNEL_MASK, %x)", trackChannelMask);
                 invalidate();
             }
@@ -407,7 +412,8 @@
         case MIXER_CHANNEL_MASK: {
             const audio_channel_mask_t mixerChannelMask =
                     static_cast<audio_channel_mask_t>(valueInt);
-            if (setChannelMasks(name, track->channelMask | track->mHapticChannelMask,
+            if (setChannelMasks(name, static_cast<audio_channel_mask_t>(
+                                    track->channelMask | track->mHapticChannelMask),
                     mixerChannelMask)) {
                 ALOGV("setParameter(TRACK, MIXER_CHANNEL_MASK, %#x)", mixerChannelMask);
                 invalidate();
@@ -533,9 +539,10 @@
     Track* t = static_cast<Track*>(track);
 
     audio_channel_mask_t channelMask = t->channelMask;
-    t->mHapticChannelMask = channelMask & AUDIO_CHANNEL_HAPTIC_ALL;
+    t->mHapticChannelMask = static_cast<audio_channel_mask_t>(
+            channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
     t->mHapticChannelCount = audio_channel_count_from_out_mask(t->mHapticChannelMask);
-    channelMask &= ~AUDIO_CHANNEL_HAPTIC_ALL;
+    channelMask = static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL);
     t->channelCount = audio_channel_count_from_out_mask(channelMask);
     ALOGV_IF(audio_channel_mask_get_bits(channelMask) != AUDIO_CHANNEL_OUT_STEREO,
             "Non-stereo channel mask: %d\n", channelMask);
diff --git a/media/libaudioprocessing/AudioResamplerDyn.cpp b/media/libaudioprocessing/AudioResamplerDyn.cpp
index ec56b00..1aacfd1 100644
--- a/media/libaudioprocessing/AudioResamplerDyn.cpp
+++ b/media/libaudioprocessing/AudioResamplerDyn.cpp
@@ -25,7 +25,6 @@
 
 #include <cutils/compiler.h>
 #include <cutils/properties.h>
-#include <utils/Debug.h>
 #include <utils/Log.h>
 #include <audio_utils/primitives.h>
 
@@ -636,7 +635,7 @@
     const uint32_t phaseWrapLimit = c.mL << c.mShift;
     size_t inFrameCount = (phaseIncrement * (uint64_t)outFrameCount + phaseFraction)
             / phaseWrapLimit;
-    // sanity check that inFrameCount is in signed 32 bit integer range.
+    // validate that inFrameCount is in signed 32 bit integer range.
     ALOG_ASSERT(0 <= inFrameCount && inFrameCount < (1U << 31));
 
     //ALOGV("inFrameCount:%d  outFrameCount:%d"
@@ -646,7 +645,7 @@
     // NOTE: be very careful when modifying the code here. register
     // pressure is very high and a small change might cause the compiler
     // to generate far less efficient code.
-    // Always sanity check the result with objdump or test-resample.
+    // Always validate the result with objdump or test-resample.
 
     // the following logic is a bit convoluted to keep the main processing loop
     // as tight as possible with register allocation.
diff --git a/media/libaudioprocessing/AudioResamplerFirProcess.h b/media/libaudioprocessing/AudioResamplerFirProcess.h
index 9b70a1c..1fcffcc 100644
--- a/media/libaudioprocessing/AudioResamplerFirProcess.h
+++ b/media/libaudioprocessing/AudioResamplerFirProcess.h
@@ -381,7 +381,7 @@
     // NOTE: be very careful when modifying the code here. register
     // pressure is very high and a small change might cause the compiler
     // to generate far less efficient code.
-    // Always sanity check the result with objdump or test-resample.
+    // Always validate the result with objdump or test-resample.
 
     if (LOCKED) {
         // locked polyphase (no interpolation)
diff --git a/media/libaudioprocessing/AudioResamplerSinc.cpp b/media/libaudioprocessing/AudioResamplerSinc.cpp
index 5a03a0d..f2c386d 100644
--- a/media/libaudioprocessing/AudioResamplerSinc.cpp
+++ b/media/libaudioprocessing/AudioResamplerSinc.cpp
@@ -404,7 +404,7 @@
     // NOTE: be very careful when modifying the code here. register
     // pressure is very high and a small change might cause the compiler
     // to generate far less efficient code.
-    // Always sanity check the result with objdump or test-resample.
+    // Always validate the result with objdump or test-resample.
 
     // compute the index of the coefficient on the positive side and
     // negative side
diff --git a/media/libaudioprocessing/audio-resampler/Android.bp b/media/libaudioprocessing/audio-resampler/Android.bp
index dc70310..4ea75e7 100644
--- a/media/libaudioprocessing/audio-resampler/Android.bp
+++ b/media/libaudioprocessing/audio-resampler/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libaudio-resampler",
 
diff --git a/media/libaudioprocessing/include/media/AudioResamplerPublic.h b/media/libaudioprocessing/include/media/AudioResamplerPublic.h
index 1b39067..200a4c8 100644
--- a/media/libaudioprocessing/include/media/AudioResamplerPublic.h
+++ b/media/libaudioprocessing/include/media/AudioResamplerPublic.h
@@ -59,7 +59,7 @@
 
 static inline bool isAudioPlaybackRateValid(const AudioPlaybackRate &playbackRate) {
     if (playbackRate.mFallbackMode == AUDIO_TIMESTRETCH_FALLBACK_FAIL &&
-            (playbackRate.mStretchMode == AUDIO_TIMESTRETCH_STRETCH_SPEECH ||
+            (playbackRate.mStretchMode == AUDIO_TIMESTRETCH_STRETCH_VOICE ||
                     playbackRate.mStretchMode == AUDIO_TIMESTRETCH_STRETCH_DEFAULT)) {
         //test sonic specific constraints
         return playbackRate.mSpeed >= TIMESTRETCH_SONIC_SPEED_MIN &&
diff --git a/media/libaudioprocessing/tests/Android.bp b/media/libaudioprocessing/tests/Android.bp
index 18acef7..3856817 100644
--- a/media/libaudioprocessing/tests/Android.bp
+++ b/media/libaudioprocessing/tests/Android.bp
@@ -1,5 +1,14 @@
 // Build the unit tests for libaudioprocessing
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "libaudioprocessing_test_defaults",
 
diff --git a/media/libaudioprocessing/tests/fuzzer/Android.bp b/media/libaudioprocessing/tests/fuzzer/Android.bp
index 1df47b7..8fb6fff 100644
--- a/media/libaudioprocessing/tests/fuzzer/Android.bp
+++ b/media/libaudioprocessing/tests/fuzzer/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_fuzz {
   name: "libaudioprocessing_resampler_fuzzer",
   srcs: [
@@ -8,3 +17,14 @@
     "libsndfile",
   ],
 }
+
+cc_fuzz {
+  name: "libaudioprocessing_record_buffer_converter_fuzzer",
+  srcs: [
+    "libaudioprocessing_record_buffer_converter_fuzzer.cpp",
+  ],
+  defaults: ["libaudioprocessing_test_defaults"],
+  static_libs: [
+    "libsndfile",
+  ],
+}
diff --git a/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_fuzz_utils.h b/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_fuzz_utils.h
new file mode 100644
index 0000000..5165925
--- /dev/null
+++ b/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_fuzz_utils.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_LIBAUDIOPROCESSING_FUZZ_UTILS_H
+#define ANDROID_LIBAUDIOPROCESSING_FUZZ_UTILS_H
+
+#include <media/AudioBufferProvider.h>
+#include <system/audio.h>
+
+namespace android {
+
+class Provider : public AudioBufferProvider {
+  const void* mAddr;        // base address
+  const size_t mNumFrames;  // total frames
+  const size_t mFrameSize;  // size of each frame in bytes
+  size_t mNextFrame;        // index of next frame to provide
+  size_t mUnrel;            // number of frames not yet released
+ public:
+  Provider(const void* addr, size_t frames, size_t frameSize)
+      : mAddr(addr),
+        mNumFrames(frames),
+        mFrameSize(frameSize),
+        mNextFrame(0),
+        mUnrel(0) {}
+  status_t getNextBuffer(Buffer* buffer) override {
+    if (buffer->frameCount > mNumFrames - mNextFrame) {
+      buffer->frameCount = mNumFrames - mNextFrame;
+    }
+    mUnrel = buffer->frameCount;
+    if (buffer->frameCount > 0) {
+      buffer->raw = (char*)mAddr + mFrameSize * mNextFrame;
+      return NO_ERROR;
+    } else {
+      buffer->raw = nullptr;
+      return NOT_ENOUGH_DATA;
+    }
+  }
+  void releaseBuffer(Buffer* buffer) override {
+    if (buffer->frameCount > mUnrel) {
+      mNextFrame += mUnrel;
+      mUnrel = 0;
+    } else {
+      mNextFrame += buffer->frameCount;
+      mUnrel -= buffer->frameCount;
+    }
+    buffer->frameCount = 0;
+    buffer->raw = nullptr;
+  }
+  void reset() { mNextFrame = 0; }
+};
+
+} // namespace android
+
+#endif // ANDROID_LIBAUDIOPROCESSING_FUZZ_UTILS_H
diff --git a/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_record_buffer_converter_fuzzer.cpp b/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_record_buffer_converter_fuzzer.cpp
new file mode 100644
index 0000000..017598c
--- /dev/null
+++ b/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_record_buffer_converter_fuzzer.cpp
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2020 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 "libaudioprocessing_fuzz_utils.h"
+#include "fuzzer/FuzzedDataProvider.h"
+#include <media/AudioResampler.h>
+#include <media/RecordBufferConverter.h>
+#include <stddef.h>
+#include <stdint.h>
+
+using namespace android;
+
+constexpr int MAX_FRAMES = 1024;
+
+#define AUDIO_FORMAT_PCM_MAIN 0
+
+// Copied and simplified from audio-hal-enums.h?l=571
+constexpr uint32_t FUZZ_AUDIO_FORMATS[] = {
+  AUDIO_FORMAT_PCM_MAIN | AUDIO_FORMAT_PCM_SUB_16_BIT,
+  AUDIO_FORMAT_PCM_MAIN | AUDIO_FORMAT_PCM_SUB_8_BIT,
+  AUDIO_FORMAT_PCM_MAIN | AUDIO_FORMAT_PCM_SUB_32_BIT,
+  AUDIO_FORMAT_PCM_MAIN | AUDIO_FORMAT_PCM_SUB_8_24_BIT,
+  AUDIO_FORMAT_PCM_MAIN | AUDIO_FORMAT_PCM_SUB_FLOAT,
+  AUDIO_FORMAT_PCM_MAIN | AUDIO_FORMAT_PCM_SUB_24_BIT_PACKED,
+  0x01000000u,
+  0x02000000u,
+  0x03000000u,
+  0x04000000u,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_MAIN,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_LC,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_SSR,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_LTP,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_HE_V1,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_SCALABLE,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_ERLC,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_LD,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_HE_V2,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_ELD,
+  AUDIO_FORMAT_AAC | AUDIO_FORMAT_AAC_SUB_XHE,
+  0x05000000u,
+  0x06000000u,
+  0x07000000u,
+  0x08000000u,
+  0x09000000u,
+  0x0A000000u,
+  AUDIO_FORMAT_E_AC3 | AUDIO_FORMAT_E_AC3_SUB_JOC,
+  0x0B000000u,
+  0x0C000000u,
+  0x0D000000u,
+  0x0E000000u,
+  0x10000000u,
+  0x11000000u,
+  0x12000000u,
+  0x13000000u,
+  0x14000000u,
+  0x15000000u,
+  0x16000000u,
+  0x17000000u,
+  0x18000000u,
+  0x19000000u,
+  0x1A000000u,
+  0x1B000000u,
+  0x1C000000u,
+  0x1D000000u,
+  0x1E000000u,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_MAIN,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_LC,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_SSR,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_LTP,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_HE_V1,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_SCALABLE,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_ERLC,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_LD,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_HE_V2,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_ELD,
+  AUDIO_FORMAT_AAC_ADTS | AUDIO_FORMAT_AAC_SUB_XHE,
+  0x1F000000u,
+  0x20000000u,
+  0x21000000u,
+  0x22000000u,
+  0x23000000u,
+  0x24000000u,
+  AUDIO_FORMAT_MAT | AUDIO_FORMAT_MAT_SUB_1_0,
+  AUDIO_FORMAT_MAT | AUDIO_FORMAT_MAT_SUB_2_0,
+  AUDIO_FORMAT_MAT | AUDIO_FORMAT_MAT_SUB_2_1,
+  0x25000000u,
+  AUDIO_FORMAT_AAC_LATM | AUDIO_FORMAT_AAC_SUB_LC,
+  AUDIO_FORMAT_AAC_LATM | AUDIO_FORMAT_AAC_SUB_HE_V1,
+  AUDIO_FORMAT_AAC_LATM | AUDIO_FORMAT_AAC_SUB_HE_V2,
+  0x26000000u,
+  0x27000000u,
+  0x28000000u,
+  0x29000000u,
+  0x2A000000u,
+  0x2B000000u,
+  0xFFFFFFFFu,
+  AUDIO_FORMAT_PCM_MAIN,
+  AUDIO_FORMAT_PCM,
+};
+constexpr size_t NUM_AUDIO_FORMATS = std::size(FUZZ_AUDIO_FORMATS);
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+  FuzzedDataProvider fdp(data, size);
+  fdp.ConsumeIntegral<int>();
+
+  const audio_channel_mask_t srcChannelMask = (audio_channel_mask_t)fdp.ConsumeIntegral<int>();
+  const audio_format_t srcFormat =
+      (audio_format_t)FUZZ_AUDIO_FORMATS[fdp.ConsumeIntegralInRange<int>(0, NUM_AUDIO_FORMATS - 1)];
+  const uint32_t srcSampleRate = fdp.ConsumeIntegralInRange<int>(1, 0x7fffffff);
+  const audio_channel_mask_t dstChannelMask = (audio_channel_mask_t)fdp.ConsumeIntegral<int>();
+  const audio_format_t dstFormat =
+      (audio_format_t)FUZZ_AUDIO_FORMATS[fdp.ConsumeIntegralInRange<int>(0, NUM_AUDIO_FORMATS - 1)];
+  const uint32_t dstSampleRate = fdp.ConsumeIntegralInRange<int>(1, 0x7fffffff);
+
+  // Certain formats will result in LOG_ALWAYS_FATAL errors that aren't interesting crashes
+  // for fuzzing.  Don't use those ones.
+  const uint32_t dstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
+  constexpr android::AudioResampler::src_quality quality =
+      android::AudioResampler::DEFAULT_QUALITY;
+  const int maxChannels =
+      quality < android::AudioResampler::DYN_LOW_QUALITY ? 2 : 8;
+  if (dstChannelCount < 1 || dstChannelCount > maxChannels) {
+    return 0;
+  }
+
+  const uint32_t srcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
+  if (srcChannelCount < 1 || srcChannelCount > maxChannels) {
+    return 0;
+  }
+
+  RecordBufferConverter converter(srcChannelMask, srcFormat, srcSampleRate,
+                                  dstChannelMask, dstFormat, dstSampleRate);
+  if (converter.initCheck() != NO_ERROR) {
+    return 0;
+  }
+
+  const uint32_t srcFrameSize = srcChannelCount * audio_bytes_per_sample(srcFormat);
+  const int srcNumFrames = fdp.ConsumeIntegralInRange<int>(0, MAX_FRAMES);
+  constexpr size_t metadataSize = 2 + 3 * sizeof(int) + 2 * sizeof(float);
+  std::vector<uint8_t> inputData = fdp.ConsumeBytes<uint8_t>(
+      metadataSize + (srcFrameSize * srcNumFrames));
+  Provider provider(inputData.data(), srcNumFrames, srcFrameSize);
+
+  const uint32_t dstFrameSize = dstChannelCount * audio_bytes_per_sample(dstFormat);
+  const size_t frames = fdp.ConsumeIntegralInRange<size_t>(0, MAX_FRAMES + 1);
+  int8_t dst[dstFrameSize * frames];
+  memset(dst, 0, sizeof(int8_t) * dstFrameSize * frames);
+
+  // Add a small number of loops to see if repeated calls to convert cause
+  // any change in behavior.
+  const int numLoops = fdp.ConsumeIntegralInRange<int>(1, 3);
+  for (int loop = 0; loop < numLoops; ++loop) {
+    switch (fdp.ConsumeIntegralInRange<int>(0, 1)) {
+      case 0:
+        converter.reset();
+        FALLTHROUGH_INTENDED;
+      case 1:
+        converter.convert(dst, &provider, frames);
+        break;
+    }
+  }
+
+  return 0;
+}
diff --git a/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_resampler_fuzzer.cpp b/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_resampler_fuzzer.cpp
index 938c610..65c9a3c 100644
--- a/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_resampler_fuzzer.cpp
+++ b/media/libaudioprocessing/tests/fuzzer/libaudioprocessing_resampler_fuzzer.cpp
@@ -34,6 +34,8 @@
 #include <unistd.h>
 #include <utils/Vector.h>
 
+#include "libaudioprocessing_fuzz_utils.h"
+
 #include <memory>
 
 using namespace android;
@@ -53,46 +55,6 @@
     AudioResampler::DYN_HIGH_QUALITY,
 };
 
-class Provider : public AudioBufferProvider {
-  const void* mAddr;        // base address
-  const size_t mNumFrames;  // total frames
-  const size_t mFrameSize;  // size of each frame in bytes
-  size_t mNextFrame;        // index of next frame to provide
-  size_t mUnrel;            // number of frames not yet released
- public:
-  Provider(const void* addr, size_t frames, size_t frameSize)
-      : mAddr(addr),
-        mNumFrames(frames),
-        mFrameSize(frameSize),
-        mNextFrame(0),
-        mUnrel(0) {}
-  status_t getNextBuffer(Buffer* buffer) override {
-    if (buffer->frameCount > mNumFrames - mNextFrame) {
-      buffer->frameCount = mNumFrames - mNextFrame;
-    }
-    mUnrel = buffer->frameCount;
-    if (buffer->frameCount > 0) {
-      buffer->raw = (char*)mAddr + mFrameSize * mNextFrame;
-      return NO_ERROR;
-    } else {
-      buffer->raw = nullptr;
-      return NOT_ENOUGH_DATA;
-    }
-  }
-  virtual void releaseBuffer(Buffer* buffer) {
-    if (buffer->frameCount > mUnrel) {
-      mNextFrame += mUnrel;
-      mUnrel = 0;
-    } else {
-      mNextFrame += buffer->frameCount;
-      mUnrel -= buffer->frameCount;
-    }
-    buffer->frameCount = 0;
-    buffer->raw = nullptr;
-  }
-  void reset() { mNextFrame = 0; }
-};
-
 audio_format_t chooseFormat(AudioResampler::src_quality quality,
                             uint8_t input_byte) {
   switch (quality) {
diff --git a/media/libaudioprocessing/tests/test-mixer.cpp b/media/libaudioprocessing/tests/test-mixer.cpp
index bc9d2a6..1bbb863 100644
--- a/media/libaudioprocessing/tests/test-mixer.cpp
+++ b/media/libaudioprocessing/tests/test-mixer.cpp
@@ -241,7 +241,8 @@
     // set up the tracks.
     for (size_t i = 0; i < providers.size(); ++i) {
         //printf("track %d out of %d\n", i, providers.size());
-        uint32_t channelMask = audio_channel_out_mask_from_count(providers[i].getNumChannels());
+        audio_channel_mask_t channelMask =
+                audio_channel_out_mask_from_count(providers[i].getNumChannels());
         const int name = i;
         const status_t status = mixer->create(
                 name, channelMask, formats[i], AUDIO_SESSION_OUTPUT_MIX);
diff --git a/media/libcpustats/Android.bp b/media/libcpustats/Android.bp
index 6e8ca1d..1ab1de0 100644
--- a/media/libcpustats/Android.bp
+++ b/media/libcpustats/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_static {
     name: "libcpustats",
 
diff --git a/media/libcpustats/ThreadCpuUsage.cpp b/media/libcpustats/ThreadCpuUsage.cpp
index 4b7549f..e71a7db 100644
--- a/media/libcpustats/ThreadCpuUsage.cpp
+++ b/media/libcpustats/ThreadCpuUsage.cpp
@@ -21,6 +21,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
+#include <unistd.h>
 
 #include <utils/Log.h>
 
diff --git a/media/libdatasource/Android.bp b/media/libdatasource/Android.bp
index f191c21..e0c6808 100644
--- a/media/libdatasource/Android.bp
+++ b/media/libdatasource/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libdatasource",
 
diff --git a/media/libeffects/OWNERS b/media/libeffects/OWNERS
index 7f9ae81..b7832ea 100644
--- a/media/libeffects/OWNERS
+++ b/media/libeffects/OWNERS
@@ -1,4 +1,3 @@
 hunga@google.com
-krocard@google.com
 mnaganov@google.com
 rago@google.com
diff --git a/media/libeffects/config/Android.bp b/media/libeffects/config/Android.bp
index 8493e30..b02dcb6 100644
--- a/media/libeffects/config/Android.bp
+++ b/media/libeffects/config/Android.bp
@@ -1,4 +1,13 @@
 // Effect configuration
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libeffectsconfig",
     vendor_available: true,
diff --git a/media/libeffects/config/src/EffectsConfig.cpp b/media/libeffects/config/src/EffectsConfig.cpp
index 26eaaf8..1696233 100644
--- a/media/libeffects/config/src/EffectsConfig.cpp
+++ b/media/libeffects/config/src/EffectsConfig.cpp
@@ -138,7 +138,7 @@
 
 template <>
 bool stringToStreamType(const char *streamName, audio_devices_t* type) {
-    return deviceFromString(streamName, *type);
+    return DeviceConverter::fromString(streamName, *type);
 }
 
 /** Parse a library xml note and push the result in libraries or return false on failure. */
diff --git a/media/libeffects/downmix/Android.bp b/media/libeffects/downmix/Android.bp
index 2a2f36e..b40317f 100644
--- a/media/libeffects/downmix/Android.bp
+++ b/media/libeffects/downmix/Android.bp
@@ -1,4 +1,23 @@
 // Multichannel downmix effect library
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libeffects_downmix_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libeffects_downmix_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libdownmix",
 
diff --git a/media/libeffects/downmix/tests/Android.bp b/media/libeffects/downmix/tests/Android.bp
index 63afc54..4077312 100644
--- a/media/libeffects/downmix/tests/Android.bp
+++ b/media/libeffects/downmix/tests/Android.bp
@@ -1,4 +1,15 @@
 // Build testbench for downmix module.
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libeffects_downmix_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libeffects_downmix_license",
+    ],
+}
+
 cc_test {
     name:"downmixtest",
     host_supported: false,
diff --git a/media/libeffects/downmix/tests/build_and_run_all_unit_tests.sh b/media/libeffects/downmix/tests/build_and_run_all_unit_tests.sh
index d0faebe..8aadfbf 100755
--- a/media/libeffects/downmix/tests/build_and_run_all_unit_tests.sh
+++ b/media/libeffects/downmix/tests/build_and_run_all_unit_tests.sh
@@ -39,8 +39,7 @@
 echo "testing Downmix"
 adb shell mkdir $testdir
 
-adb push $ANDROID_BUILD_TOP/cts/tests/tests/media/res/raw/sinesweepraw.raw \
-$testdir
+adb push $ANDROID_BUILD_TOP/frameworks/av/media/libeffects/res/raw/sinesweepraw.raw $testdir
 adb push $OUT/testcases/downmixtest/arm64/downmixtest $testdir
 
 #run the downmix test application for test.
diff --git a/media/libeffects/dynamicsproc/Android.bp b/media/libeffects/dynamicsproc/Android.bp
index eafc483..84131a4 100644
--- a/media/libeffects/dynamicsproc/Android.bp
+++ b/media/libeffects/dynamicsproc/Android.bp
@@ -13,6 +13,25 @@
 // limitations under the License.
 
 // DynamicsProcessing library
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libeffects_dynamicsproc_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libeffects_dynamicsproc_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libdynproc",
 
diff --git a/media/libeffects/factory/Android.bp b/media/libeffects/factory/Android.bp
index ddbfdd8..22838a3 100644
--- a/media/libeffects/factory/Android.bp
+++ b/media/libeffects/factory/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libeffects_headers",
     vendor_available: true,
diff --git a/media/libeffects/factory/EffectsConfigLoader.c b/media/libeffects/factory/EffectsConfigLoader.c
index fcef36f..e23530e 100644
--- a/media/libeffects/factory/EffectsConfigLoader.c
+++ b/media/libeffects/factory/EffectsConfigLoader.c
@@ -394,7 +394,7 @@
        }
        sub_effect_entry_t *subEntry = (sub_effect_entry_t*)gSubEffectList->sub_elem->object;
        effect_descriptor_t *subEffectDesc = (effect_descriptor_t*)(subEntry->object);
-       // Since we return a dummy descriptor for the proxy during
+       // Since we return a stub descriptor for the proxy during
        // get_descriptor call,we replace it with the correspoding
        // sw effect descriptor, but with Proxy UUID
        // check for Sw desc
diff --git a/media/libeffects/factory/EffectsXmlConfigLoader.cpp b/media/libeffects/factory/EffectsXmlConfigLoader.cpp
index 505be7c..30a9007 100644
--- a/media/libeffects/factory/EffectsXmlConfigLoader.cpp
+++ b/media/libeffects/factory/EffectsXmlConfigLoader.cpp
@@ -283,7 +283,7 @@
             }
             listPush(effectLoadResult.effectDesc.get(), subEffectList);
 
-            // Since we return a dummy descriptor for the proxy during
+            // Since we return a stub descriptor for the proxy during
             // get_descriptor call, we replace it with the corresponding
             // sw effect descriptor, but keep the Proxy UUID
             *effectLoadResult.effectDesc = *swEffectLoadResult.effectDesc;
diff --git a/media/libeffects/loudness/Android.bp b/media/libeffects/loudness/Android.bp
index 5a13af6..bcd6947 100644
--- a/media/libeffects/loudness/Android.bp
+++ b/media/libeffects/loudness/Android.bp
@@ -1,4 +1,23 @@
 // LoudnessEnhancer library
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libeffects_loudness_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libeffects_loudness_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libldnhncr",
 
diff --git a/media/libeffects/lvm/.clang-format b/media/libeffects/lvm/.clang-format
new file mode 100644
index 0000000..6f4b13e
--- /dev/null
+++ b/media/libeffects/lvm/.clang-format
@@ -0,0 +1,15 @@
+BasedOnStyle: Google
+Standard: Cpp11
+AccessModifierOffset: -2
+AllowShortFunctionsOnASingleLine: Inline
+ColumnLimit: 100
+CommentPragmas: NOLINT:.*
+DerivePointerAlignment: false
+IncludeBlocks: Preserve
+IndentWidth: 4
+ContinuationIndentWidth: 8
+PointerAlignment: Left
+TabWidth: 4
+UseTab: Never
+# Following are specific to libeffects/lvm
+SortIncludes: false
diff --git a/media/libeffects/lvm/benchmarks/Android.bp b/media/libeffects/lvm/benchmarks/Android.bp
new file mode 100644
index 0000000..8a25b85
--- /dev/null
+++ b/media/libeffects/lvm/benchmarks/Android.bp
@@ -0,0 +1,48 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_benchmark {
+    name: "lvm_benchmark",
+    vendor: true,
+    host_supported: true,
+    srcs: ["lvm_benchmark.cpp"],
+    static_libs: [
+        "libbundlewrapper",
+        "libmusicbundle",
+    ],
+    shared_libs: [
+        "libaudioutils",
+        "liblog",
+    ],
+    header_libs: [
+        "libhardware_headers",
+    ],
+}
+
+cc_benchmark {
+    name: "reverb_benchmark",
+    vendor: true,
+    host_supported: true,
+    include_dirs: [
+        "frameworks/av/media/libeffects/lvm/wrapper/Reverb",
+    ],
+    srcs: ["reverb_benchmark.cpp"],
+    static_libs: [
+        "libreverb",
+        "libreverbwrapper",
+    ],
+    shared_libs: [
+        "libaudioutils",
+        "liblog",
+    ],
+    header_libs: [
+        "libaudioeffects",
+        "libhardware_headers",
+    ],
+}
diff --git a/media/libeffects/lvm/benchmarks/lvm_benchmark.cpp b/media/libeffects/lvm/benchmarks/lvm_benchmark.cpp
new file mode 100644
index 0000000..bdb66d8
--- /dev/null
+++ b/media/libeffects/lvm/benchmarks/lvm_benchmark.cpp
@@ -0,0 +1,238 @@
+/*
+ * Copyright 2020 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 <array>
+#include <climits>
+#include <cstdlib>
+#include <random>
+#include <vector>
+#include <log/log.h>
+#include <benchmark/benchmark.h>
+#include <hardware/audio_effect.h>
+#include <system/audio.h>
+
+extern audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM;
+constexpr effect_uuid_t kEffectUuids[] = {
+        // NXP SW BassBoost
+        {0x8631f300, 0x72e2, 0x11df, 0xb57e, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // NXP SW Virtualizer
+        {0x1d4033c0, 0x8557, 0x11df, 0x9f2d, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // NXP SW Equalizer
+        {0xce772f20, 0x847d, 0x11df, 0xbb17, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // NXP SW Volume
+        {0x119341a0, 0x8469, 0x11df, 0x81f9, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+};
+
+constexpr size_t kNumEffectUuids = std::size(kEffectUuids);
+
+constexpr size_t kFrameCount = 2048;
+
+constexpr audio_channel_mask_t kChMasks[] = {
+        AUDIO_CHANNEL_INDEX_MASK_1,  AUDIO_CHANNEL_INDEX_MASK_2,  AUDIO_CHANNEL_INDEX_MASK_3,
+        AUDIO_CHANNEL_INDEX_MASK_4,  AUDIO_CHANNEL_INDEX_MASK_5,  AUDIO_CHANNEL_INDEX_MASK_6,
+        AUDIO_CHANNEL_INDEX_MASK_7,  AUDIO_CHANNEL_INDEX_MASK_8,  AUDIO_CHANNEL_INDEX_MASK_9,
+        AUDIO_CHANNEL_INDEX_MASK_10, AUDIO_CHANNEL_INDEX_MASK_11, AUDIO_CHANNEL_INDEX_MASK_12,
+        AUDIO_CHANNEL_INDEX_MASK_13, AUDIO_CHANNEL_INDEX_MASK_14, AUDIO_CHANNEL_INDEX_MASK_15,
+        AUDIO_CHANNEL_INDEX_MASK_16, AUDIO_CHANNEL_INDEX_MASK_17, AUDIO_CHANNEL_INDEX_MASK_18,
+        AUDIO_CHANNEL_INDEX_MASK_19, AUDIO_CHANNEL_INDEX_MASK_20, AUDIO_CHANNEL_INDEX_MASK_21,
+        AUDIO_CHANNEL_INDEX_MASK_22, AUDIO_CHANNEL_INDEX_MASK_23, AUDIO_CHANNEL_INDEX_MASK_24,
+};
+
+constexpr size_t kNumChMasks = std::size(kChMasks);
+constexpr int kSampleRate = 44100;
+
+/*******************************************************************
+ * A test result running on Pixel 3 for comparison.
+ * The first parameter indicates the number of channels.
+ * The second parameter indicates the effect.
+ * 0: Bass Boost, 1: Virtualizer, 2: Equalizer, 3: Volume
+ * -----------------------------------------------------
+ * Benchmark           Time             CPU   Iterations
+ * -----------------------------------------------------
+ * BM_LVM/1/0       52123 ns        51971 ns        13437
+ * BM_LVM/1/1       75397 ns        75175 ns         9382
+ * BM_LVM/1/2       40253 ns        40140 ns        17418
+ * BM_LVM/1/3       19918 ns        19860 ns        35230
+ * BM_LVM/2/0       62455 ns        62283 ns        11214
+ * BM_LVM/2/1      110086 ns       109751 ns         6350
+ * BM_LVM/2/2       44017 ns        43890 ns        15982
+ * BM_LVM/2/3       21660 ns        21596 ns        32568
+ * BM_LVM/3/0       71925 ns        71698 ns         9745
+ * BM_LVM/3/1      117043 ns       116754 ns         6007
+ * BM_LVM/3/2       48899 ns        48781 ns        14334
+ * BM_LVM/3/3       23607 ns        23540 ns        29739
+ * BM_LVM/4/0       81296 ns        81095 ns         8632
+ * BM_LVM/4/1      122435 ns       122132 ns         5733
+ * BM_LVM/4/2       53744 ns        53612 ns        13068
+ * BM_LVM/4/3       25846 ns        25783 ns        27188
+ * BM_LVM/5/0       98557 ns        98311 ns         7120
+ * BM_LVM/5/1      131626 ns       131269 ns         5296
+ * BM_LVM/5/2       66892 ns        66732 ns        10458
+ * BM_LVM/5/3       31797 ns        31721 ns        22092
+ * BM_LVM/6/0      111880 ns       111596 ns         6278
+ * BM_LVM/6/1      140207 ns       139846 ns         5000
+ * BM_LVM/6/2       75683 ns        75496 ns         9253
+ * BM_LVM/6/3       37669 ns        37571 ns        18663
+ * BM_LVM/7/0      128265 ns       127957 ns         5470
+ * BM_LVM/7/1      149522 ns       149159 ns         4699
+ * BM_LVM/7/2       92024 ns        91798 ns         7631
+ * BM_LVM/7/3       43372 ns        43268 ns        16181
+ * BM_LVM/8/0      141897 ns       141548 ns         4945
+ * BM_LVM/8/1      158062 ns       157661 ns         4438
+ * BM_LVM/8/2       98042 ns        97801 ns         7151
+ * BM_LVM/8/3       49044 ns        48923 ns        14314
+ * BM_LVM/9/0      174692 ns       174228 ns         4026
+ * BM_LVM/9/1      183048 ns       182560 ns         3834
+ * BM_LVM/9/2      131020 ns       130675 ns         5347
+ * BM_LVM/9/3       71102 ns        70915 ns         9801
+ * BM_LVM/10/0     189079 ns       188576 ns         3699
+ * BM_LVM/10/1     187989 ns       187472 ns         3737
+ * BM_LVM/10/2     140093 ns       139717 ns         5007
+ * BM_LVM/10/3      78175 ns        77963 ns         8919
+ * BM_LVM/11/0     207577 ns       207007 ns         3371
+ * BM_LVM/11/1     198186 ns       197640 ns         3535
+ * BM_LVM/11/2     157214 ns       156786 ns         4459
+ * BM_LVM/11/3      85912 ns        85681 ns         8153
+ * BM_LVM/12/0     220861 ns       220265 ns         3169
+ * BM_LVM/12/1     208759 ns       208184 ns         3355
+ * BM_LVM/12/2     165533 ns       165088 ns         4234
+ * BM_LVM/12/3      92616 ns        92364 ns         7528
+ * BM_LVM/13/0     238573 ns       237920 ns         2945
+ * BM_LVM/13/1     219130 ns       218520 ns         3209
+ * BM_LVM/13/2     183193 ns       182692 ns         3830
+ * BM_LVM/13/3     100546 ns       100274 ns         7005
+ * BM_LVM/14/0     254820 ns       254135 ns         2748
+ * BM_LVM/14/1     230161 ns       229530 ns         3049
+ * BM_LVM/14/2     192195 ns       191671 ns         3635
+ * BM_LVM/14/3     107770 ns       107477 ns         6502
+ * BM_LVM/15/0     273695 ns       272954 ns         2531
+ * BM_LVM/15/1     240718 ns       240049 ns         2801
+ * BM_LVM/15/2     220914 ns       220309 ns         3191
+ * BM_LVM/15/3     124321 ns       123978 ns         5664
+ * BM_LVM/16/0     285769 ns       284969 ns         2459
+ * BM_LVM/16/1     251692 ns       250983 ns         2789
+ * BM_LVM/16/2     224554 ns       223917 ns         3132
+ * BM_LVM/16/3     122048 ns       121706 ns         5753
+ * BM_LVM/17/0     310027 ns       309154 ns         2266
+ * BM_LVM/17/1     262008 ns       261259 ns         2681
+ * BM_LVM/17/2     247530 ns       246827 ns         2842
+ * BM_LVM/17/3     129513 ns       129146 ns         5418
+ * BM_LVM/18/0     322755 ns       321844 ns         2173
+ * BM_LVM/18/1     263266 ns       262514 ns         2671
+ * BM_LVM/18/2     257606 ns       256875 ns         2731
+ * BM_LVM/18/3     136550 ns       136164 ns         5129
+ * BM_LVM/19/0     338551 ns       337591 ns         2069
+ * BM_LVM/19/1     275929 ns       275134 ns         2535
+ * BM_LVM/19/2     270331 ns       269554 ns         2596
+ * BM_LVM/19/3     144551 ns       144138 ns         4838
+ * BM_LVM/20/0     352633 ns       351617 ns         1993
+ * BM_LVM/20/1     286607 ns       285713 ns         2371
+ * BM_LVM/20/2     283541 ns       282689 ns         2407
+ * BM_LVM/20/3     152355 ns       151904 ns         4604
+ * BM_LVM/21/0     370557 ns       369456 ns         1889
+ * BM_LVM/21/1     298251 ns       297351 ns         2352
+ * BM_LVM/21/2     296806 ns       295917 ns         2364
+ * BM_LVM/21/3     160212 ns       159735 ns         4330
+ * BM_LVM/22/0     386431 ns       385224 ns         1826
+ * BM_LVM/22/1     308901 ns       307925 ns         2273
+ * BM_LVM/22/2     309077 ns       308140 ns         2274
+ * BM_LVM/22/3     167492 ns       166987 ns         4194
+ * BM_LVM/23/0     404455 ns       403218 ns         1729
+ * BM_LVM/23/1     322026 ns       321014 ns         2187
+ * BM_LVM/23/2     326616 ns       325623 ns         2152
+ * BM_LVM/23/3     175873 ns       175328 ns         4007
+ * BM_LVM/24/0     416949 ns       415676 ns         1684
+ * BM_LVM/24/1     329803 ns       328779 ns         2128
+ * BM_LVM/24/2     337648 ns       336626 ns         2080
+ * BM_LVM/24/3     183192 ns       182634 ns         3824
+ *******************************************************************/
+
+static void BM_LVM(benchmark::State& state) {
+    const size_t chMask = kChMasks[state.range(0) - 1];
+    const effect_uuid_t uuid = kEffectUuids[state.range(1)];
+    const size_t channelCount = audio_channel_count_from_out_mask(chMask);
+
+    // Initialize input buffer with deterministic pseudo-random values
+    std::minstd_rand gen(chMask);
+    std::uniform_real_distribution<> dis(-1.0f, 1.0f);
+    std::vector<float> input(kFrameCount * channelCount);
+    for (auto& in : input) {
+        in = dis(gen);
+    }
+
+    effect_handle_t effectHandle = nullptr;
+    if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.create_effect(&uuid, 1, 1, &effectHandle);
+        status != 0) {
+        ALOGE("create_effect returned an error = %d\n", status);
+        return;
+    }
+
+    effect_config_t config{};
+    config.inputCfg.samplingRate = config.outputCfg.samplingRate = kSampleRate;
+    config.inputCfg.channels = config.outputCfg.channels = chMask;
+    config.inputCfg.format = config.outputCfg.format = AUDIO_FORMAT_PCM_FLOAT;
+
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    if (int status = (*effectHandle)
+                             ->command(effectHandle, EFFECT_CMD_SET_CONFIG, sizeof(effect_config_t),
+                                       &config, &replySize, &reply);
+        status != 0) {
+        ALOGE("command returned an error = %d\n", status);
+        return;
+    }
+
+    if (int status =
+                (*effectHandle)
+                        ->command(effectHandle, EFFECT_CMD_ENABLE, 0, nullptr, &replySize, &reply);
+        status != 0) {
+        ALOGE("Command enable call returned error %d\n", reply);
+        return;
+    }
+
+    // Run the test
+    for (auto _ : state) {
+        std::vector<float> output(kFrameCount * channelCount);
+
+        benchmark::DoNotOptimize(input.data());
+        benchmark::DoNotOptimize(output.data());
+
+        audio_buffer_t inBuffer = {.frameCount = kFrameCount, .f32 = input.data()};
+        audio_buffer_t outBuffer = {.frameCount = kFrameCount, .f32 = output.data()};
+        (*effectHandle)->process(effectHandle, &inBuffer, &outBuffer);
+
+        benchmark::ClobberMemory();
+    }
+
+    state.SetComplexityN(state.range(0));
+
+    if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.release_effect(effectHandle); status != 0) {
+        ALOGE("release_effect returned an error = %d\n", status);
+        return;
+    }
+}
+
+static void LVMArgs(benchmark::internal::Benchmark* b) {
+    for (int i = FCC_1; i <= kNumChMasks; i++) {
+        for (int j = 0; j < kNumEffectUuids; ++j) {
+            b->Args({i, j});
+        }
+    }
+}
+
+BENCHMARK(BM_LVM)->Apply(LVMArgs);
+
+BENCHMARK_MAIN();
diff --git a/media/libeffects/lvm/benchmarks/reverb_benchmark.cpp b/media/libeffects/lvm/benchmarks/reverb_benchmark.cpp
new file mode 100644
index 0000000..00a7ff2
--- /dev/null
+++ b/media/libeffects/lvm/benchmarks/reverb_benchmark.cpp
@@ -0,0 +1,180 @@
+/*
+ * Copyright 2020 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 <array>
+#include <climits>
+#include <cstdlib>
+#include <random>
+#include <vector>
+#include <log/log.h>
+#include <benchmark/benchmark.h>
+#include <hardware/audio_effect.h>
+#include <system/audio.h>
+#include "EffectReverb.h"
+
+extern audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM;
+constexpr effect_uuid_t kEffectUuids[] = {
+        {0x172cdf00,
+         0xa3bc,
+         0x11df,
+         0xa72f,
+         {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // preset-insert mode
+        {0xf29a1400,
+         0xa3bb,
+         0x11df,
+         0x8ddc,
+         {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // preset-aux mode
+};
+
+constexpr size_t kNumEffectUuids = std::size(kEffectUuids);
+
+constexpr size_t kFrameCount = 2048;
+
+constexpr int kPresets[] = {
+        REVERB_PRESET_NONE,      REVERB_PRESET_SMALLROOM,  REVERB_PRESET_MEDIUMROOM,
+        REVERB_PRESET_LARGEROOM, REVERB_PRESET_MEDIUMHALL, REVERB_PRESET_LARGEHALL,
+        REVERB_PRESET_PLATE,
+};
+
+constexpr size_t kNumPresets = std::size(kPresets);
+
+constexpr int kSampleRate = 44100;
+
+int reverbSetConfigParam(uint32_t paramType, uint32_t paramValue, effect_handle_t effectHandle) {
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    uint32_t paramData[2] = {paramType, paramValue};
+    auto effectParam = (effect_param_t*)malloc(sizeof(effect_param_t) + sizeof(paramData));
+    memcpy(&effectParam->data[0], &paramData[0], sizeof(paramData));
+    effectParam->psize = sizeof(paramData[0]);
+    effectParam->vsize = sizeof(paramData[1]);
+    int status = (*effectHandle)
+                         ->command(effectHandle, EFFECT_CMD_SET_PARAM,
+                                   sizeof(effect_param_t) + sizeof(paramData), effectParam,
+                                   &replySize, &reply);
+    free(effectParam);
+    if (status != 0) {
+        ALOGE("Reverb set config returned an error = %d\n", status);
+        return status;
+    }
+    return reply;
+}
+
+/*******************************************************************
+ * A test result running on Pixel 3 with for comparison.
+ * The first parameter indicates the preset level id.
+ * The second parameter indicates the effect.
+ * 0: preset-insert mode, 1: preset-aux mode
+ * --------------------------------------------------------
+ * Benchmark              Time             CPU   Iterations
+ * --------------------------------------------------------
+ * BM_REVERB/0/0      19312 ns        19249 ns        36282
+ * BM_REVERB/0/1       5613 ns         5596 ns       125032
+ * BM_REVERB/1/0     605453 ns       603714 ns         1131
+ * BM_REVERB/1/1     589421 ns       587758 ns         1161
+ * BM_REVERB/2/0     605760 ns       604006 ns         1131
+ * BM_REVERB/2/1     589434 ns       587777 ns         1161
+ * BM_REVERB/3/0     605574 ns       603828 ns         1131
+ * BM_REVERB/3/1     589566 ns       587862 ns         1162
+ * BM_REVERB/4/0     605634 ns       603894 ns         1131
+ * BM_REVERB/4/1     589506 ns       587856 ns         1161
+ * BM_REVERB/5/0     605644 ns       603929 ns         1131
+ * BM_REVERB/5/1     589592 ns       587863 ns         1161
+ * BM_REVERB/6/0     610544 ns       608561 ns         1131
+ * BM_REVERB/6/1     589686 ns       587871 ns         1161
+ *******************************************************************/
+
+static void BM_REVERB(benchmark::State& state) {
+    const size_t chMask = AUDIO_CHANNEL_OUT_STEREO;
+    const size_t preset = kPresets[state.range(0)];
+    const effect_uuid_t uuid = kEffectUuids[state.range(1)];
+    const size_t channelCount = audio_channel_count_from_out_mask(chMask);
+
+    // Initialize input buffer with deterministic pseudo-random values
+    std::minstd_rand gen(chMask);
+    std::uniform_real_distribution<> dis(-1.0f, 1.0f);
+    std::vector<float> input(kFrameCount * channelCount);
+    std::vector<float> output(kFrameCount * channelCount);
+    for (auto& in : input) {
+        in = dis(gen);
+    }
+
+    effect_handle_t effectHandle = nullptr;
+    if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.create_effect(&uuid, 1, 1, &effectHandle);
+        status != 0) {
+        ALOGE("create_effect returned an error = %d\n", status);
+        return;
+    }
+
+    effect_config_t config{};
+    config.inputCfg.samplingRate = config.outputCfg.samplingRate = kSampleRate;
+    config.inputCfg.channels = config.outputCfg.channels = chMask;
+    config.inputCfg.format = config.outputCfg.format = AUDIO_FORMAT_PCM_FLOAT;
+
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    if (int status = (*effectHandle)
+                             ->command(effectHandle, EFFECT_CMD_SET_CONFIG, sizeof(effect_config_t),
+                                       &config, &replySize, &reply);
+        status != 0) {
+        ALOGE("command returned an error = %d\n", status);
+        return;
+    }
+
+    if (int status =
+                (*effectHandle)
+                        ->command(effectHandle, EFFECT_CMD_ENABLE, 0, nullptr, &replySize, &reply);
+        status != 0) {
+        ALOGE("Command enable call returned error %d\n", reply);
+        return;
+    }
+
+    if (int status = reverbSetConfigParam(REVERB_PARAM_PRESET, preset, effectHandle); status != 0) {
+        ALOGE("Invalid reverb preset. Error %d\n", status);
+        return;
+    }
+
+    // Run the test
+    for (auto _ : state) {
+        benchmark::DoNotOptimize(input.data());
+        benchmark::DoNotOptimize(output.data());
+
+        audio_buffer_t inBuffer = {.frameCount = kFrameCount, .f32 = input.data()};
+        audio_buffer_t outBuffer = {.frameCount = kFrameCount, .f32 = output.data()};
+        (*effectHandle)->process(effectHandle, &inBuffer, &outBuffer);
+
+        benchmark::ClobberMemory();
+    }
+
+    state.SetComplexityN(state.range(0));
+
+    if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.release_effect(effectHandle); status != 0) {
+        ALOGE("release_effect returned an error = %d\n", status);
+        return;
+    }
+}
+
+static void REVERBArgs(benchmark::internal::Benchmark* b) {
+    for (int i = 0; i < kNumPresets; i++) {
+        for (int j = 0; j < kNumEffectUuids; ++j) {
+            b->Args({i, j});
+        }
+    }
+}
+
+BENCHMARK(BM_REVERB)->Apply(REVERBArgs);
+
+BENCHMARK_MAIN();
diff --git a/media/libeffects/lvm/lib/Android.bp b/media/libeffects/lvm/lib/Android.bp
index 1f2a5e1..a044295 100644
--- a/media/libeffects/lvm/lib/Android.bp
+++ b/media/libeffects/lvm/lib/Android.bp
@@ -1,4 +1,23 @@
 // Music bundle
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libeffects_lvm_lib_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libeffects_lvm_lib_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_static {
     name: "libmusicbundle",
 
@@ -9,6 +28,7 @@
     },
 
     vendor: true,
+    host_supported: true,
     srcs: [
         "StereoWidening/src/LVCS_BypassMix.cpp",
         "StereoWidening/src/LVCS_Control.cpp",
@@ -30,7 +50,6 @@
         "Bundle/src/LVM_Control.cpp",
         "SpectrumAnalyzer/src/LVPSA_Control.cpp",
         "SpectrumAnalyzer/src/LVPSA_Init.cpp",
-        "SpectrumAnalyzer/src/LVPSA_Memory.cpp",
         "SpectrumAnalyzer/src/LVPSA_Process.cpp",
         "SpectrumAnalyzer/src/LVPSA_QPD_Init.cpp",
         "SpectrumAnalyzer/src/LVPSA_QPD_Process.cpp",
@@ -43,55 +62,19 @@
         "Common/src/InstAlloc.cpp",
         "Common/src/DC_2I_D16_TRC_WRA_01.cpp",
         "Common/src/DC_2I_D16_TRC_WRA_01_Init.cpp",
-        "Common/src/FO_2I_D16F32C15_LShx_TRC_WRA_01.cpp",
-        "Common/src/FO_2I_D16F32Css_LShx_TRC_WRA_01_Init.cpp",
-        "Common/src/FO_1I_D16F16C15_TRC_WRA_01.cpp",
-        "Common/src/FO_1I_D16F16Css_TRC_WRA_01_Init.cpp",
-        "Common/src/BP_1I_D16F32C30_TRC_WRA_01.cpp",
-        "Common/src/BP_1I_D16F16C14_TRC_WRA_01.cpp",
-        "Common/src/BP_1I_D32F32C30_TRC_WRA_02.cpp",
-        "Common/src/BP_1I_D16F16Css_TRC_WRA_01_Init.cpp",
-        "Common/src/BP_1I_D16F32Cll_TRC_WRA_01_Init.cpp",
-        "Common/src/BP_1I_D32F32Cll_TRC_WRA_02_Init.cpp",
-        "Common/src/BQ_2I_D32F32Cll_TRC_WRA_01_Init.cpp",
-        "Common/src/BQ_2I_D32F32C30_TRC_WRA_01.cpp",
-        "Common/src/BQ_2I_D16F32C15_TRC_WRA_01.cpp",
-        "Common/src/BQ_2I_D16F32C14_TRC_WRA_01.cpp",
-        "Common/src/BQ_2I_D16F32C13_TRC_WRA_01.cpp",
-        "Common/src/BQ_2I_D16F32Css_TRC_WRA_01_init.cpp",
-        "Common/src/BQ_2I_D16F16C15_TRC_WRA_01.cpp",
-        "Common/src/BQ_2I_D16F16C14_TRC_WRA_01.cpp",
-        "Common/src/BQ_2I_D16F16Css_TRC_WRA_01_Init.cpp",
-        "Common/src/BQ_1I_D16F16C15_TRC_WRA_01.cpp",
-        "Common/src/BQ_1I_D16F16Css_TRC_WRA_01_Init.cpp",
-        "Common/src/BQ_1I_D16F32C14_TRC_WRA_01.cpp",
-        "Common/src/BQ_1I_D16F32Css_TRC_WRA_01_init.cpp",
-        "Common/src/PK_2I_D32F32C30G11_TRC_WRA_01.cpp",
-        "Common/src/PK_2I_D32F32C14G11_TRC_WRA_01.cpp",
-        "Common/src/PK_2I_D32F32CssGss_TRC_WRA_01_Init.cpp",
-        "Common/src/PK_2I_D32F32CllGss_TRC_WRA_01_Init.cpp",
-        "Common/src/Int16LShiftToInt32_16x32.cpp",
-        "Common/src/From2iToMono_16.cpp",
         "Common/src/Copy_16.cpp",
-        "Common/src/MonoTo2I_16.cpp",
         "Common/src/MonoTo2I_32.cpp",
-        "Common/src/LoadConst_16.cpp",
         "Common/src/LoadConst_32.cpp",
         "Common/src/dB_to_Lin32.cpp",
         "Common/src/Shift_Sat_v16xv16.cpp",
         "Common/src/Shift_Sat_v32xv32.cpp",
-        "Common/src/Abs_32.cpp",
-        "Common/src/Int32RShiftToInt16_Sat_32x16.cpp",
         "Common/src/From2iToMono_32.cpp",
-        "Common/src/mult3s_16x16.cpp",
         "Common/src/Mult3s_32x16.cpp",
         "Common/src/NonLinComp_D16.cpp",
         "Common/src/DelayMix_16x16.cpp",
         "Common/src/MSTo2i_Sat_16x16.cpp",
         "Common/src/From2iToMS_16x16.cpp",
-        "Common/src/Mac3s_Sat_16x16.cpp",
         "Common/src/Mac3s_Sat_32x16.cpp",
-        "Common/src/Add2_Sat_16x16.cpp",
         "Common/src/Add2_Sat_32x32.cpp",
         "Common/src/LVC_MixSoft_1St_2i_D16C31_SAT.cpp",
         "Common/src/LVC_MixSoft_1St_D16C31_SAT.cpp",
@@ -132,13 +115,14 @@
     shared_libs: [
         "liblog",
     ],
+    static_libs: [
+        "libaudioutils",
+    ],
     header_libs: [
-        "libhardware_headers"
+        "libhardware_headers",
     ],
     cppflags: [
         "-fvisibility=hidden",
-        "-DSUPPORT_MC",
-
         "-Wall",
         "-Werror",
     ],
@@ -156,6 +140,7 @@
     },
 
     vendor: true,
+    host_supported: true,
     srcs: [
         "Reverb/src/LVREV_ApplyNewSettings.cpp",
         "Reverb/src/LVREV_ClearAudioBuffers.cpp",
@@ -165,18 +150,12 @@
         "Reverb/src/LVREV_Process.cpp",
         "Reverb/src/LVREV_SetControlParameters.cpp",
         "Reverb/src/LVREV_Tables.cpp",
-        "Common/src/Abs_32.cpp",
         "Common/src/InstAlloc.cpp",
-        "Common/src/LoadConst_16.cpp",
         "Common/src/LoadConst_32.cpp",
         "Common/src/From2iToMono_32.cpp",
         "Common/src/Mult3s_32x16.cpp",
-        "Common/src/FO_1I_D32F32C31_TRC_WRA_01.cpp",
-        "Common/src/FO_1I_D32F32Cll_TRC_WRA_01_Init.cpp",
-        "Common/src/DelayAllPass_Sat_32x16To32.cpp",
         "Common/src/Copy_16.cpp",
         "Common/src/Mac3s_Sat_32x16.cpp",
-        "Common/src/DelayWrite_32.cpp",
         "Common/src/Shift_Sat_v32xv32.cpp",
         "Common/src/Add2_Sat_32x32.cpp",
         "Common/src/JoinTo2i_32x32.cpp",
@@ -203,10 +182,11 @@
         "Reverb/lib",
         "Common/lib",
     ],
-
+    static_libs: [
+        "libaudioutils",
+    ],
     cppflags: [
         "-fvisibility=hidden",
-
         "-Wall",
         "-Werror",
     ],
diff --git a/media/libeffects/lvm/lib/Bass/lib/LVDBE.h b/media/libeffects/lvm/lib/Bass/lib/LVDBE.h
index 948d79c..e60ad07 100644
--- a/media/libeffects/lvm/lib/Bass/lib/LVDBE.h
+++ b/media/libeffects/lvm/lib/Bass/lib/LVDBE.h
@@ -69,15 +69,12 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/* Memory table*/
-#define LVDBE_NR_MEMORY_REGIONS        4                            /* Number of memory regions */
-
 /* Bass Enhancement effect level */
-#define LVDBE_EFFECT_03DB            3                              /* Effect defines for backwards compatibility */
-#define LVDBE_EFFECT_06DB            6
-#define LVDBE_EFFECT_09DB            9
-#define LVDBE_EFFECT_12DB            12
-#define LVDBE_EFFECT_15DB            15
+#define LVDBE_EFFECT_03DB 3 /* Effect defines for backwards compatibility */
+#define LVDBE_EFFECT_06DB 6
+#define LVDBE_EFFECT_09DB 9
+#define LVDBE_EFFECT_12DB 12
+#define LVDBE_EFFECT_15DB 15
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -86,52 +83,31 @@
 /****************************************************************************************/
 
 /* Instance handle */
-typedef void    *LVDBE_Handle_t;
+typedef void* LVDBE_Handle_t;
 
 /* Operating modes */
-typedef enum
-{
-    LVDBE_OFF      = 0,
-    LVDBE_ON       = 1,
-    LVDBE_MODE_MAX = LVM_MAXINT_32
-} LVDBE_Mode_en;
+typedef enum { LVDBE_OFF = 0, LVDBE_ON = 1, LVDBE_MODE_MAX = LVM_MAXINT_32 } LVDBE_Mode_en;
 
 /* High pass filter */
-typedef enum
-{
+typedef enum {
     LVDBE_HPF_OFF = 0,
-    LVDBE_HPF_ON  = 1,
+    LVDBE_HPF_ON = 1,
     LVDBE_HPF_MAX = LVM_MAXINT_32
 } LVDBE_FilterSelect_en;
 
 /* Volume control */
-typedef enum
-{
+typedef enum {
     LVDBE_VOLUME_OFF = 0,
-    LVDBE_VOLUME_ON  = 1,
+    LVDBE_VOLUME_ON = 1,
     LVDBE_VOLUME_MAX = LVM_MAXINT_32
 } LVDBE_Volume_en;
 
-/* Memory Types */
-typedef enum
-{
-    LVDBE_PERSISTENT      = 0,
-    LVDBE_PERSISTENT_DATA = 1,
-    LVDBE_PERSISTENT_COEF = 2,
-    LVDBE_SCRATCH         = 3,
-    LVDBE_MEMORY_MAX      = LVM_MAXINT_32
-
-} LVDBE_MemoryTypes_en;
-
 /* Function return status */
-typedef enum
-{
-    LVDBE_SUCCESS        = 0,                        /* Successful return from a routine */
-    LVDBE_ALIGNMENTERROR = 1,                        /* Memory alignment error */
-    LVDBE_NULLADDRESS    = 2,                        /* NULL allocation address */
-    LVDBE_TOOMANYSAMPLES = 3,                        /* Maximum block size exceeded */
-    LVDBE_SIZEERROR      = 4,                        /* Incorrect structure size */
-    LVDBE_STATUS_MAX     = LVM_MAXINT_32
+typedef enum {
+    LVDBE_SUCCESS = 0,        /* Successful return from a routine */
+    LVDBE_NULLADDRESS = 1,    /* NULL allocation address */
+    LVDBE_TOOMANYSAMPLES = 2, /* Maximum block size exceeded */
+    LVDBE_STATUS_MAX = LVM_MAXINT_32
 } LVDBE_ReturnStatus_en;
 
 /****************************************************************************************/
@@ -158,40 +134,38 @@
 /*
  * Bass Enhancement centre frequency
  */
-#define LVDBE_CAP_CENTRE_55Hz       1
-#define LVDBE_CAP_CENTRE_66Hz       2
-#define LVDBE_CAP_CENTRE_78Hz       4
-#define LVDBE_CAP_CENTRE_90Hz       8
+#define LVDBE_CAP_CENTRE_55Hz 1
+#define LVDBE_CAP_CENTRE_66Hz 2
+#define LVDBE_CAP_CENTRE_78Hz 4
+#define LVDBE_CAP_CENTRE_90Hz 8
 
-typedef enum
-{
+typedef enum {
     LVDBE_CENTRE_55HZ = 0,
     LVDBE_CENTRE_66HZ = 1,
     LVDBE_CENTRE_78HZ = 2,
     LVDBE_CENTRE_90HZ = 3,
-    LVDBE_CENTRE_MAX  = LVM_MAXINT_32
+    LVDBE_CENTRE_MAX = LVM_MAXINT_32
 } LVDBE_CentreFreq_en;
 
 /*
  * Supported sample rates in samples per second
  */
-#define LVDBE_CAP_FS_8000                1
-#define LVDBE_CAP_FS_11025               2
-#define LVDBE_CAP_FS_12000               4
-#define LVDBE_CAP_FS_16000               8
-#define LVDBE_CAP_FS_22050               16
-#define LVDBE_CAP_FS_24000               32
-#define LVDBE_CAP_FS_32000               64
-#define LVDBE_CAP_FS_44100               128
-#define LVDBE_CAP_FS_48000               256
-#define LVDBE_CAP_FS_88200               512
-#define LVDBE_CAP_FS_96000               1024
-#define LVDBE_CAP_FS_176400              2048
-#define LVDBE_CAP_FS_192000              4096
+#define LVDBE_CAP_FS_8000 1
+#define LVDBE_CAP_FS_11025 2
+#define LVDBE_CAP_FS_12000 4
+#define LVDBE_CAP_FS_16000 8
+#define LVDBE_CAP_FS_22050 16
+#define LVDBE_CAP_FS_24000 32
+#define LVDBE_CAP_FS_32000 64
+#define LVDBE_CAP_FS_44100 128
+#define LVDBE_CAP_FS_48000 256
+#define LVDBE_CAP_FS_88200 512
+#define LVDBE_CAP_FS_96000 1024
+#define LVDBE_CAP_FS_176400 2048
+#define LVDBE_CAP_FS_192000 4096
 
-typedef enum
-{
-    LVDBE_FS_8000  = 0,
+typedef enum {
+    LVDBE_FS_8000 = 0,
     LVDBE_FS_11025 = 1,
     LVDBE_FS_12000 = 2,
     LVDBE_FS_16000 = 3,
@@ -204,7 +178,7 @@
     LVDBE_FS_96000 = 10,
     LVDBE_FS_176400 = 11,
     LVDBE_FS_192000 = 12,
-    LVDBE_FS_MAX   = LVM_MAXINT_32
+    LVDBE_FS_MAX = LVM_MAXINT_32
 } LVDBE_Fs_en;
 
 /****************************************************************************************/
@@ -213,44 +187,25 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/* Memory region definition */
-typedef struct
-{
-    LVM_UINT32                Size;                        /* Region size in bytes */
-    LVM_UINT16                Alignment;                  /* Region alignment in bytes */
-    LVDBE_MemoryTypes_en      Type;                       /* Region type */
-    void                      *pBaseAddress;              /* Pointer to the region base address */
-} LVDBE_MemoryRegion_t;
-
-/* Memory table containing the region definitions */
-typedef struct
-{
-    LVDBE_MemoryRegion_t    Region[LVDBE_NR_MEMORY_REGIONS];  /* One definition for each region */
-} LVDBE_MemTab_t;
-
 /* Parameter structure */
-typedef struct
-{
-    LVDBE_Mode_en           OperatingMode;
-    LVDBE_Fs_en             SampleRate;
-    LVM_INT16               EffectLevel;
-    LVDBE_CentreFreq_en     CentreFrequency;
-    LVDBE_FilterSelect_en   HPFSelect;
-    LVDBE_Volume_en         VolumeControl;
-    LVM_INT16               VolumedB;
-    LVM_INT16               HeadroomdB;
-#ifdef SUPPORT_MC
-    LVM_INT16               NrChannels;
-#endif
+typedef struct {
+    LVDBE_Mode_en OperatingMode;
+    LVDBE_Fs_en SampleRate;
+    LVM_INT16 EffectLevel;
+    LVDBE_CentreFreq_en CentreFrequency;
+    LVDBE_FilterSelect_en HPFSelect;
+    LVDBE_Volume_en VolumeControl;
+    LVM_INT16 VolumedB;
+    LVM_INT16 HeadroomdB;
+    LVM_INT16 NrChannels;
 
 } LVDBE_Params_t;
 
 /* Capability structure */
-typedef struct
-{
-      LVM_UINT16              SampleRate;               /* Sampling rate capabilities */
-      LVM_UINT16              CentreFrequency;          /* Centre frequency capabilities */
-      LVM_UINT16              MaxBlockSize;             /* Maximum block size in sample pairs */
+typedef struct {
+    LVM_UINT16 SampleRate;      /* Sampling rate capabilities */
+    LVM_UINT16 CentreFrequency; /* Centre frequency capabilities */
+    LVM_UINT16 MaxBlockSize;    /* Maximum block size in sample pairs */
 } LVDBE_Capabilities_t;
 
 /****************************************************************************************/
@@ -261,75 +216,39 @@
 
 /****************************************************************************************/
 /*                                                                                      */
-/* FUNCTION:                 LVDBE_Memory                                               */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*    This function is used for memory allocation and free. It can be called in         */
-/*    two ways:                                                                         */
-/*                                                                                      */
-/*        hInstance = NULL                Returns the memory requirements               */
-/*        hInstance = Instance handle        Returns the memory requirements and        */
-/*                                        allocated base addresses for the instance     */
-/*                                                                                      */
-/*    When this function is called for memory allocation (hInstance=NULL) the memory    */
-/*  base address pointers are NULL on return.                                           */
-/*                                                                                      */
-/*    When the function is called for free (hInstance = Instance Handle) the memory     */
-/*  table returns the allocated memory and base addresses used during initialisation.   */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance                Instance Handle                                            */
-/*  pMemoryTable             Pointer to an empty memory definition table                */
-/*    pCapabilities            Pointer to the default capabilites                       */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVDBE_SUCCESS            Succeeded                                                  */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*    1.    This function may be interrupted by the LVDBE_Process function              */
-/*                                                                                      */
-/****************************************************************************************/
-
-LVDBE_ReturnStatus_en LVDBE_Memory(LVDBE_Handle_t           hInstance,
-                                   LVDBE_MemTab_t           *pMemoryTable,
-                                   LVDBE_Capabilities_t     *pCapabilities);
-
-/****************************************************************************************/
-/*                                                                                      */
 /* FUNCTION:                 LVDBE_Init                                                 */
 /*                                                                                      */
 /* DESCRIPTION:                                                                         */
 /*    Create and initialisation function for the Bass Enhancement module                */
 /*                                                                                      */
-/*    This function can be used to create an algorithm instance by calling with         */
-/*    hInstance set to NULL. In this case the algorithm returns the new instance        */
-/*    handle.                                                                           */
-/*                                                                                      */
-/*    This function can be used to force a full re-initialisation of the algorithm      */
-/*    by calling with hInstance = Instance Handle. In this case the memory table        */
-/*    should be correct for the instance, this can be ensured by calling the function   */
-/*    LVDBE_Memory before calling this function.                                        */
-/*                                                                                      */
 /* PARAMETERS:                                                                          */
-/*  hInstance                  Instance handle                                          */
-/*  pMemoryTable             Pointer to the memory definition table                     */
+/*  phInstance               Pointer to instance handle                                 */
 /*  pCapabilities            Pointer to the initialisation capabilities                 */
+/*  pScratch                 Pointer to the bundle scratch buffer                       */
 /*                                                                                      */
 /* RETURNS:                                                                             */
-/*  LVDBE_SUCCESS                Initialisation succeeded                               */
-/*  LVDBE_ALIGNMENTERROR        Instance or scratch memory on incorrect alignment       */
-/*    LVDBE_NULLADDRESS            One or more memory has a NULL pointer                */
+/*  LVDBE_SUCCESS            Initialisation succeeded                                   */
+/*  LVDBE_NULLADDRESS        One or more memory has a NULL pointer - malloc failure     */
 /*                                                                                      */
 /* NOTES:                                                                               */
-/*  1.     The instance handle is the pointer to the base address of the first memory   */
-/*        region.                                                                       */
-/*    2.    This function must not be interrupted by the LVDBE_Process function         */
+/*  1.    This function must not be interrupted by the LVDBE_Process function           */
 /*                                                                                      */
 /****************************************************************************************/
+LVDBE_ReturnStatus_en LVDBE_Init(LVDBE_Handle_t* phInstance, LVDBE_Capabilities_t* pCapabilities,
+                                 void* pScratch);
 
-LVDBE_ReturnStatus_en LVDBE_Init(LVDBE_Handle_t             *phInstance,
-                                   LVDBE_MemTab_t           *pMemoryTable,
-                                   LVDBE_Capabilities_t     *pCapabilities);
+/****************************************************************************************/
+/*                                                                                      */
+/* FUNCTION:                 LVDBE_DeInit                                               */
+/*                                                                                      */
+/* DESCRIPTION:                                                                         */
+/*    Free the memories created during LVDBE_Init including instance handle             */
+/*                                                                                      */
+/* PARAMETERS:                                                                          */
+/*  phInstance               Pointer to instance handle                                 */
+/*                                                                                      */
+/****************************************************************************************/
+void LVDBE_DeInit(LVDBE_Handle_t* phInstance);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -351,8 +270,7 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVDBE_ReturnStatus_en LVDBE_GetParameters(LVDBE_Handle_t        hInstance,
-                                            LVDBE_Params_t      *pParams);
+LVDBE_ReturnStatus_en LVDBE_GetParameters(LVDBE_Handle_t hInstance, LVDBE_Params_t* pParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -374,8 +292,8 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVDBE_ReturnStatus_en LVDBE_GetCapabilities(LVDBE_Handle_t            hInstance,
-                                              LVDBE_Capabilities_t    *pCapabilities);
+LVDBE_ReturnStatus_en LVDBE_GetCapabilities(LVDBE_Handle_t hInstance,
+                                            LVDBE_Capabilities_t* pCapabilities);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -414,8 +332,7 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVDBE_ReturnStatus_en LVDBE_Control(LVDBE_Handle_t      hInstance,
-                                      LVDBE_Params_t    *pParams);
+LVDBE_ReturnStatus_en LVDBE_Control(LVDBE_Handle_t hInstance, LVDBE_Params_t* pParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -437,9 +354,7 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-LVDBE_ReturnStatus_en LVDBE_Process(LVDBE_Handle_t          hInstance,
-                                       const LVM_FLOAT      *pInData,
-                                       LVM_FLOAT            *pOutData,
-                                       LVM_UINT16           NumSamples);
+LVDBE_ReturnStatus_en LVDBE_Process(LVDBE_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                    LVM_FLOAT* pOutData, LVM_UINT16 NumSamples);
 
 #endif /* __LVDBE_H__ */
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h b/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
index b364dae..30e1692 100644
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Coeffs.h
@@ -24,7 +24,7 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#define LVDBE_SCALESHIFT                                    10         /* As a power of 2 */
+#define LVDBE_SCALESHIFT 10 /* As a power of 2 */
 
 /************************************************************************************/
 /*                                                                                  */
@@ -32,289 +32,289 @@
 /*                                                                                  */
 /************************************************************************************/
 
- /* Coefficients for centre frequency 55Hz */
-#define HPF_Fs8000_Fc55_A0                        0.958849f
-#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_B2                        0.940807f
-#define HPF_Fs11025_Fc55_A0                       0.966909f
-#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_B2                       0.956690f
-#define HPF_Fs12000_Fc55_A0                       0.968650f
-#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_B2                       0.960138f
-#define HPF_Fs16000_Fc55_A0                       0.973588f
-#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_B2                       0.969952f
-#define HPF_Fs22050_Fc55_A0                       0.977671f
-#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_B2                       0.978105f
-#define HPF_Fs24000_Fc55_A0                       0.978551f
-#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_B2                       0.979866f
-#define HPF_Fs32000_Fc55_A0                       0.981042f
-#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_B2                       0.984861f
-#define HPF_Fs44100_Fc55_A0                       0.983097f
-#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_B2                       0.988992f
-#define HPF_Fs48000_Fc55_A0                       0.983539f
-#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_B2                       0.989882f
+/* Coefficients for centre frequency 55Hz */
+#define HPF_Fs8000_Fc55_A0 0.958849f
+#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_B2 0.940807f
+#define HPF_Fs11025_Fc55_A0 0.966909f
+#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_B2 0.956690f
+#define HPF_Fs12000_Fc55_A0 0.968650f
+#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_B2 0.960138f
+#define HPF_Fs16000_Fc55_A0 0.973588f
+#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_B2 0.969952f
+#define HPF_Fs22050_Fc55_A0 0.977671f
+#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_B2 0.978105f
+#define HPF_Fs24000_Fc55_A0 0.978551f
+#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_B2 0.979866f
+#define HPF_Fs32000_Fc55_A0 0.981042f
+#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_B2 0.984861f
+#define HPF_Fs44100_Fc55_A0 0.983097f
+#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_B2 0.988992f
+#define HPF_Fs48000_Fc55_A0 0.983539f
+#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_B2 0.989882f
 
-#define HPF_Fs88200_Fc55_A0                       0.985818f
-#define HPF_Fs88200_Fc55_A1                       (-1.971636f)
-#define HPF_Fs88200_Fc55_A2                       0.985818f
-#define HPF_Fs88200_Fc55_B1                       (-1.994466f)
-#define HPF_Fs88200_Fc55_B2                       0.994481f
+#define HPF_Fs88200_Fc55_A0 0.985818f
+#define HPF_Fs88200_Fc55_A1 (-1.971636f)
+#define HPF_Fs88200_Fc55_A2 0.985818f
+#define HPF_Fs88200_Fc55_B1 (-1.994466f)
+#define HPF_Fs88200_Fc55_B2 0.994481f
 
-#define HPF_Fs96000_Fc55_A0                       0.986040f
-#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_B2                       0.994928f
+#define HPF_Fs96000_Fc55_A0 0.986040f
+#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_B2 0.994928f
 
-#define HPF_Fs176400_Fc55_A0                      0.987183f
-#define HPF_Fs176400_Fc55_A1                      (-1.974366f)
-#define HPF_Fs176400_Fc55_A2                      0.987183f
-#define HPF_Fs176400_Fc55_B1                      (-1.997233f)
-#define HPF_Fs176400_Fc55_B2                      0.997237f
+#define HPF_Fs176400_Fc55_A0 0.987183f
+#define HPF_Fs176400_Fc55_A1 (-1.974366f)
+#define HPF_Fs176400_Fc55_A2 0.987183f
+#define HPF_Fs176400_Fc55_B1 (-1.997233f)
+#define HPF_Fs176400_Fc55_B2 0.997237f
 
-#define HPF_Fs192000_Fc55_A0                      0.987294f
-#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_B2                      0.997461f
+#define HPF_Fs192000_Fc55_A0 0.987294f
+#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_B2 0.997461f
 
- /* Coefficients for centre frequency 66Hz */
-#define HPF_Fs8000_Fc66_A0                        0.953016f
-#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_B2                        0.929396f
-#define HPF_Fs11025_Fc66_A0                       0.962638f
-#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_B2                       0.948256f
-#define HPF_Fs12000_Fc66_A0                       0.964718f
-#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_B2                       0.952359f
-#define HPF_Fs16000_Fc66_A0                       0.970622f
-#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_B2                       0.964052f
-#define HPF_Fs22050_Fc66_A0                       0.975509f
-#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_B2                       0.973784f
-#define HPF_Fs24000_Fc66_A0                       0.976563f
-#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_B2                       0.975889f
-#define HPF_Fs32000_Fc66_A0                       0.979547f
-#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_B2                       0.981861f
-#define HPF_Fs44100_Fc66_A0                       0.982010f
-#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_B2                       0.986805f
-#define HPF_Fs48000_Fc66_A0                       0.982540f
-#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_B2                       0.987871f
+/* Coefficients for centre frequency 66Hz */
+#define HPF_Fs8000_Fc66_A0 0.953016f
+#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_B2 0.929396f
+#define HPF_Fs11025_Fc66_A0 0.962638f
+#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_B2 0.948256f
+#define HPF_Fs12000_Fc66_A0 0.964718f
+#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_B2 0.952359f
+#define HPF_Fs16000_Fc66_A0 0.970622f
+#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_B2 0.964052f
+#define HPF_Fs22050_Fc66_A0 0.975509f
+#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_B2 0.973784f
+#define HPF_Fs24000_Fc66_A0 0.976563f
+#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_B2 0.975889f
+#define HPF_Fs32000_Fc66_A0 0.979547f
+#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_B2 0.981861f
+#define HPF_Fs44100_Fc66_A0 0.982010f
+#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_B2 0.986805f
+#define HPF_Fs48000_Fc66_A0 0.982540f
+#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_B2 0.987871f
 
-#define HPF_Fs88200_Fc66_A0                       0.985273f
-#define HPF_Fs88200_Fc66_A1                       (-1.970546f)
-#define HPF_Fs88200_Fc66_A2                       0.985273f
-#define HPF_Fs88200_Fc66_B1                       (-1.993359f)
-#define HPF_Fs88200_Fc66_B2                       0.993381f
+#define HPF_Fs88200_Fc66_A0 0.985273f
+#define HPF_Fs88200_Fc66_A1 (-1.970546f)
+#define HPF_Fs88200_Fc66_A2 0.985273f
+#define HPF_Fs88200_Fc66_B1 (-1.993359f)
+#define HPF_Fs88200_Fc66_B2 0.993381f
 
-#define HPF_Fs96000_Fc66_A0                       0.985539f
-#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_B2                       0.993917f
+#define HPF_Fs96000_Fc66_A0 0.985539f
+#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_B2 0.993917f
 
-#define HPF_Fs176400_Fc66_A0                      0.986910f
-#define HPF_Fs176400_Fc66_A1                      (-1.973820f)
-#define HPF_Fs176400_Fc66_A2                      0.986910f
-#define HPF_Fs176400_Fc66_B1                      (-1.996679f)
-#define HPF_Fs176400_Fc66_B2                      0.996685f
+#define HPF_Fs176400_Fc66_A0 0.986910f
+#define HPF_Fs176400_Fc66_A1 (-1.973820f)
+#define HPF_Fs176400_Fc66_A2 0.986910f
+#define HPF_Fs176400_Fc66_B1 (-1.996679f)
+#define HPF_Fs176400_Fc66_B2 0.996685f
 
-#define HPF_Fs192000_Fc66_A0                      0.987043f
-#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_B2                      0.996954f
+#define HPF_Fs192000_Fc66_A0 0.987043f
+#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_B2 0.996954f
 
 /* Coefficients for centre frequency 78Hz */
-#define HPF_Fs8000_Fc78_A0                        0.946693f
-#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_B2                        0.917105f
-#define HPF_Fs11025_Fc78_A0                       0.957999f
-#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_B2                       0.939140f
-#define HPF_Fs12000_Fc78_A0                       0.960446f
-#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_B2                       0.943944f
-#define HPF_Fs16000_Fc78_A0                       0.967397f
-#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_B2                       0.957656f
-#define HPF_Fs22050_Fc78_A0                       0.973156f
-#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_B2                       0.969092f
-#define HPF_Fs24000_Fc78_A0                       0.974398f
-#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_B2                       0.971568f
-#define HPF_Fs32000_Fc78_A0                       0.977918f
-#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_B2                       0.978599f
-#define HPF_Fs44100_Fc78_A0                       0.980824f
-#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_B2                       0.984425f
-#define HPF_Fs48000_Fc78_A0                       0.981450f
-#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_B2                       0.985681f
+#define HPF_Fs8000_Fc78_A0 0.946693f
+#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_B2 0.917105f
+#define HPF_Fs11025_Fc78_A0 0.957999f
+#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_B2 0.939140f
+#define HPF_Fs12000_Fc78_A0 0.960446f
+#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_B2 0.943944f
+#define HPF_Fs16000_Fc78_A0 0.967397f
+#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_B2 0.957656f
+#define HPF_Fs22050_Fc78_A0 0.973156f
+#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_B2 0.969092f
+#define HPF_Fs24000_Fc78_A0 0.974398f
+#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_B2 0.971568f
+#define HPF_Fs32000_Fc78_A0 0.977918f
+#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_B2 0.978599f
+#define HPF_Fs44100_Fc78_A0 0.980824f
+#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_B2 0.984425f
+#define HPF_Fs48000_Fc78_A0 0.981450f
+#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_B2 0.985681f
 
-#define HPF_Fs88200_Fc78_A0                       0.984678f
-#define HPF_Fs88200_Fc78_A1                       (-1.969356f)
-#define HPF_Fs88200_Fc78_A2                       0.984678f
-#define HPF_Fs88200_Fc78_B1                       (-1.992151f)
-#define HPF_Fs88200_Fc78_B2                       0.992182f
+#define HPF_Fs88200_Fc78_A0 0.984678f
+#define HPF_Fs88200_Fc78_A1 (-1.969356f)
+#define HPF_Fs88200_Fc78_A2 0.984678f
+#define HPF_Fs88200_Fc78_B1 (-1.992151f)
+#define HPF_Fs88200_Fc78_B2 0.992182f
 
-#define HPF_Fs96000_Fc78_A0                       0.984992f
-#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_B2                       0.992815f
+#define HPF_Fs96000_Fc78_A0 0.984992f
+#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_B2 0.992815f
 
-#define HPF_Fs176400_Fc78_A0                      0.986612f
-#define HPF_Fs176400_Fc78_A1                      (-1.973224f)
-#define HPF_Fs176400_Fc78_A2                      0.986612f
-#define HPF_Fs176400_Fc78_B1                      (-1.996076f)
-#define HPF_Fs176400_Fc78_B2                      0.996083f
+#define HPF_Fs176400_Fc78_A0 0.986612f
+#define HPF_Fs176400_Fc78_A1 (-1.973224f)
+#define HPF_Fs176400_Fc78_A2 0.986612f
+#define HPF_Fs176400_Fc78_B1 (-1.996076f)
+#define HPF_Fs176400_Fc78_B2 0.996083f
 
-#define HPF_Fs192000_Fc78_A0                      0.986769f
-#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_B2                      0.996401f
+#define HPF_Fs192000_Fc78_A0 0.986769f
+#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_B2 0.996401f
 
 /* Coefficients for centre frequency 90Hz */
-#define HPF_Fs8000_Fc90_A0                       0.940412f
-#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_B2                       0.904977f
-#define HPF_Fs11025_Fc90_A0                      0.953383f
-#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_B2                      0.930111f
-#define HPF_Fs12000_Fc90_A0                      0.956193f
-#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_B2                      0.935603f
-#define HPF_Fs16000_Fc90_A0                      0.964183f
-#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_B2                      0.951303f
-#define HPF_Fs22050_Fc90_A0                      0.970809f
-#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_B2                      0.964423f
-#define HPF_Fs24000_Fc90_A0                      0.972239f
-#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_B2                      0.967266f
-#define HPF_Fs32000_Fc90_A0                      0.976292f
-#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_B2                      0.975347f
-#define HPF_Fs44100_Fc90_A0                      0.979641f
-#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_B2                      0.982050f
-#define HPF_Fs48000_Fc90_A0                      0.980362f
-#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_B2                      0.983497f
+#define HPF_Fs8000_Fc90_A0 0.940412f
+#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_B2 0.904977f
+#define HPF_Fs11025_Fc90_A0 0.953383f
+#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_B2 0.930111f
+#define HPF_Fs12000_Fc90_A0 0.956193f
+#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_B2 0.935603f
+#define HPF_Fs16000_Fc90_A0 0.964183f
+#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_B2 0.951303f
+#define HPF_Fs22050_Fc90_A0 0.970809f
+#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_B2 0.964423f
+#define HPF_Fs24000_Fc90_A0 0.972239f
+#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_B2 0.967266f
+#define HPF_Fs32000_Fc90_A0 0.976292f
+#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_B2 0.975347f
+#define HPF_Fs44100_Fc90_A0 0.979641f
+#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_B2 0.982050f
+#define HPF_Fs48000_Fc90_A0 0.980362f
+#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_B2 0.983497f
 
-#define HPF_Fs88200_Fc90_A0                       0.984084f
-#define HPF_Fs88200_Fc90_A1                       (-1.968168f)
-#define HPF_Fs88200_Fc90_A2                       0.984084f
-#define HPF_Fs88200_Fc90_B1                       (-1.990944f)
-#define HPF_Fs88200_Fc90_B2                       0.990985f
+#define HPF_Fs88200_Fc90_A0 0.984084f
+#define HPF_Fs88200_Fc90_A1 (-1.968168f)
+#define HPF_Fs88200_Fc90_A2 0.984084f
+#define HPF_Fs88200_Fc90_B1 (-1.990944f)
+#define HPF_Fs88200_Fc90_B2 0.990985f
 
-#define HPF_Fs96000_Fc90_A0                       0.984446f
-#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_B2                       0.991714f
+#define HPF_Fs96000_Fc90_A0 0.984446f
+#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_B2 0.991714f
 
-#define HPF_Fs176400_Fc90_A0                      0.986314f
-#define HPF_Fs176400_Fc90_A1                      (-1.972629f)
-#define HPF_Fs176400_Fc90_A2                      0.986314f
-#define HPF_Fs176400_Fc90_B1                      (-1.995472f)
-#define HPF_Fs176400_Fc90_B2                      0.995482f
+#define HPF_Fs176400_Fc90_A0 0.986314f
+#define HPF_Fs176400_Fc90_A1 (-1.972629f)
+#define HPF_Fs176400_Fc90_A2 0.986314f
+#define HPF_Fs176400_Fc90_B1 (-1.995472f)
+#define HPF_Fs176400_Fc90_B2 0.995482f
 
-#define HPF_Fs192000_Fc90_A0                      0.986496f
-#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_B2                      0.995848f
+#define HPF_Fs192000_Fc90_A0 0.986496f
+#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_B2 0.995848f
 
 /************************************************************************************/
 /*                                                                                  */
@@ -323,288 +323,288 @@
 /************************************************************************************/
 
 /* 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_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_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_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_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_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_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_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_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_B2                      0.996875f
+#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_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_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_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_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_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_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_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_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_B2 0.996875f
 
-#define BPF_Fs88200_Fc55_A0                      0.000831f
-#define BPF_Fs88200_Fc55_A1                      0.000000f
-#define BPF_Fs88200_Fc55_A2                      (-0.000831f)
-#define BPF_Fs88200_Fc55_B1                      (-1.998321f)
-#define BPF_Fs88200_Fc55_B2                      0.998338f
+#define BPF_Fs88200_Fc55_A0 0.000831f
+#define BPF_Fs88200_Fc55_A1 0.000000f
+#define BPF_Fs88200_Fc55_A2 (-0.000831f)
+#define BPF_Fs88200_Fc55_B1 (-1.998321f)
+#define BPF_Fs88200_Fc55_B2 0.998338f
 
-#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_B2                      0.998477f
+#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_B2 0.998477f
 
-#define BPF_Fs176400_Fc55_A0                     0.000416f
-#define BPF_Fs176400_Fc55_A1                     0.000000f
-#define BPF_Fs176400_Fc55_A2                     (-0.000416f)
-#define BPF_Fs176400_Fc55_B1                     (-1.999164f)
-#define BPF_Fs176400_Fc55_B2                     0.999169f
+#define BPF_Fs176400_Fc55_A0 0.000416f
+#define BPF_Fs176400_Fc55_A1 0.000000f
+#define BPF_Fs176400_Fc55_A2 (-0.000416f)
+#define BPF_Fs176400_Fc55_B1 (-1.999164f)
+#define BPF_Fs176400_Fc55_B2 0.999169f
 
-#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_B2                     0.999238f
+#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_B2 0.999238f
 
 /* 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_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_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_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_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_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_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_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_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_B2                     0.995690f
+#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_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_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_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_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_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_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_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_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_B2 0.995690f
 
-#define BPF_Fs88200_Fc66_A0                     0.001146f
-#define BPF_Fs88200_Fc66_A1                     0.000000f
-#define BPF_Fs88200_Fc66_A2                     (-0.001146f)
-#define BPF_Fs88200_Fc66_B1                     (-1.997684f)
-#define BPF_Fs88200_Fc66_B2                     0.997708f
+#define BPF_Fs88200_Fc66_A0 0.001146f
+#define BPF_Fs88200_Fc66_A1 0.000000f
+#define BPF_Fs88200_Fc66_A2 (-0.001146f)
+#define BPF_Fs88200_Fc66_B1 (-1.997684f)
+#define BPF_Fs88200_Fc66_B2 0.997708f
 
-#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_B2                     0.997891f
+#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_B2 0.997891f
 
-#define BPF_Fs176400_Fc66_A0                    0.000573f
-#define BPF_Fs176400_Fc66_A1                    0.000000f
-#define BPF_Fs176400_Fc66_A2                    (-0.000573f)
-#define BPF_Fs176400_Fc66_B1                    (-1.998847f)
-#define BPF_Fs176400_Fc66_B2                    0.998853f
+#define BPF_Fs176400_Fc66_A0 0.000573f
+#define BPF_Fs176400_Fc66_A1 0.000000f
+#define BPF_Fs176400_Fc66_A2 (-0.000573f)
+#define BPF_Fs176400_Fc66_B1 (-1.998847f)
+#define BPF_Fs176400_Fc66_B2 0.998853f
 
-#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_B2                    0.998945f
+#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_B2 0.998945f
 
 /* 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_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_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_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_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_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_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_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_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_B2                     0.993639f
+#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_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_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_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_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_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_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_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_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_B2 0.993639f
 
-#define BPF_Fs88200_Fc78_A0                    0.001693f
-#define BPF_Fs88200_Fc78_A1                    0.000000f
-#define BPF_Fs88200_Fc78_A2                    (-0.001693f)
-#define BPF_Fs88200_Fc78_B1                    (-1.996582f)
-#define BPF_Fs88200_Fc78_B2                    0.996615f
+#define BPF_Fs88200_Fc78_A0 0.001693f
+#define BPF_Fs88200_Fc78_A1 0.000000f
+#define BPF_Fs88200_Fc78_A2 (-0.001693f)
+#define BPF_Fs88200_Fc78_B1 (-1.996582f)
+#define BPF_Fs88200_Fc78_B2 0.996615f
 
-#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_B2                     0.996891f
+#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_B2 0.996891f
 
-#define BPF_Fs176400_Fc78_A0                    0.000847f
-#define BPF_Fs176400_Fc78_A1                    0.000000f
-#define BPF_Fs176400_Fc78_A2                    (-0.000847f)
-#define BPF_Fs176400_Fc78_B1                    (-1.998298f)
-#define BPF_Fs176400_Fc78_B2                    0.998306f
+#define BPF_Fs176400_Fc78_A0 0.000847f
+#define BPF_Fs176400_Fc78_A1 0.000000f
+#define BPF_Fs176400_Fc78_A2 (-0.000847f)
+#define BPF_Fs176400_Fc78_B1 (-1.998298f)
+#define BPF_Fs176400_Fc78_B2 0.998306f
 
-#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_B2                    0.998444f
+#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_B2 0.998444f
 
 /* 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_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_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_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_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_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_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_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_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_B2                      0.992177f
+#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_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_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_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_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_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_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_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_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_B2 0.992177f
 
-#define BPF_Fs88200_Fc90_A0                      0.002083f
-#define BPF_Fs88200_Fc90_A1                      0.000000f
-#define BPF_Fs88200_Fc90_A2                      (-0.002083f)
-#define BPF_Fs88200_Fc90_B1                      (-1.995791f)
-#define BPF_Fs88200_Fc90_B2                      0.995835f
+#define BPF_Fs88200_Fc90_A0 0.002083f
+#define BPF_Fs88200_Fc90_A1 0.000000f
+#define BPF_Fs88200_Fc90_A2 (-0.002083f)
+#define BPF_Fs88200_Fc90_B1 (-1.995791f)
+#define BPF_Fs88200_Fc90_B2 0.995835f
 
-#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_B2                      0.996174f
+#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_B2 0.996174f
 
-#define BPF_Fs176400_Fc90_A0                     0.001042f
-#define BPF_Fs176400_Fc90_A1                     0.000000f
-#define BPF_Fs176400_Fc90_A2                     (-0.001042f)
-#define BPF_Fs176400_Fc90_B1                     (-1.997904f)
-#define BPF_Fs176400_Fc90_B2                     0.997915f
+#define BPF_Fs176400_Fc90_A0 0.001042f
+#define BPF_Fs176400_Fc90_A1 0.000000f
+#define BPF_Fs176400_Fc90_A2 (-0.001042f)
+#define BPF_Fs176400_Fc90_B1 (-1.997904f)
+#define BPF_Fs176400_Fc90_B2 0.997915f
 
-#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_B2                     0.998085f
+#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_B2 0.998085f
 
 /************************************************************************************/
 /*                                                                                  */
@@ -613,74 +613,74 @@
 /************************************************************************************/
 
 /* AGC Time constants */
-#define AGC_ATTACK_Fs8000                             0.841395f
-#define AGC_ATTACK_Fs11025                            0.882223f
-#define AGC_ATTACK_Fs12000                            0.891251f
-#define AGC_ATTACK_Fs16000                            0.917276f
-#define AGC_ATTACK_Fs22050                            0.939267f
-#define AGC_ATTACK_Fs24000                            0.944061f
-#define AGC_ATTACK_Fs32000                            0.957745f
-#define AGC_ATTACK_Fs44100                            0.969158f
-#define AGC_ATTACK_Fs48000                            0.971628f
+#define AGC_ATTACK_Fs8000 0.841395f
+#define AGC_ATTACK_Fs11025 0.882223f
+#define AGC_ATTACK_Fs12000 0.891251f
+#define AGC_ATTACK_Fs16000 0.917276f
+#define AGC_ATTACK_Fs22050 0.939267f
+#define AGC_ATTACK_Fs24000 0.944061f
+#define AGC_ATTACK_Fs32000 0.957745f
+#define AGC_ATTACK_Fs44100 0.969158f
+#define AGC_ATTACK_Fs48000 0.971628f
 
-#define AGC_ATTACK_Fs88200                             0.984458f
-#define AGC_ATTACK_Fs96000                             0.985712f
-#define AGC_ATTACK_Fs176400                            0.992199f
-#define AGC_ATTACK_Fs192000                            0.992830f
+#define AGC_ATTACK_Fs88200 0.984458f
+#define AGC_ATTACK_Fs96000 0.985712f
+#define AGC_ATTACK_Fs176400 0.992199f
+#define AGC_ATTACK_Fs192000 0.992830f
 
-#define DECAY_SHIFT                                   10
+#define DECAY_SHIFT 10
 
-#define AGC_DECAY_Fs8000                              0.000042f
-#define AGC_DECAY_Fs11025                             0.000030f
-#define AGC_DECAY_Fs12000                             0.000028f
-#define AGC_DECAY_Fs16000                             0.000021f
-#define AGC_DECAY_Fs22050                             0.000015f
-#define AGC_DECAY_Fs24000                             0.000014f
-#define AGC_DECAY_Fs32000                             0.000010f
-#define AGC_DECAY_Fs44100                             0.000008f
-#define AGC_DECAY_Fs48000                             0.000007f
+#define AGC_DECAY_Fs8000 0.000042f
+#define AGC_DECAY_Fs11025 0.000030f
+#define AGC_DECAY_Fs12000 0.000028f
+#define AGC_DECAY_Fs16000 0.000021f
+#define AGC_DECAY_Fs22050 0.000015f
+#define AGC_DECAY_Fs24000 0.000014f
+#define AGC_DECAY_Fs32000 0.000010f
+#define AGC_DECAY_Fs44100 0.000008f
+#define AGC_DECAY_Fs48000 0.000007f
 
-#define AGC_DECAY_Fs88200                            0.0000038f
-#define AGC_DECAY_FS96000                            0.0000035f
-#define AGC_DECAY_Fs176400                          0.00000188f
-#define AGC_DECAY_FS192000                          0.00000175f
+#define AGC_DECAY_Fs88200 0.0000038f
+#define AGC_DECAY_FS96000 0.0000035f
+#define AGC_DECAY_Fs176400 0.00000188f
+#define AGC_DECAY_FS192000 0.00000175f
 
 /* AGC Gain settings */
-#define AGC_GAIN_SCALE                                        31         /* As a power of 2 */
-#define AGC_GAIN_SHIFT                                         4         /* As a power of 2 */
-#define AGC_TARGETLEVEL                            0.988553f
-#define AGC_HPFGAIN_0dB                            0.412538f
-#define AGC_GAIN_0dB                               0.000000f
-#define AGC_HPFGAIN_1dB                            0.584893f
-#define AGC_GAIN_1dB                               0.122018f
-#define AGC_HPFGAIN_2dB                            0.778279f
-#define AGC_GAIN_2dB                               0.258925f
-#define AGC_HPFGAIN_3dB                            0.995262f
-#define AGC_GAIN_3dB                               0.412538f
-#define AGC_HPFGAIN_4dB                            1.238721f
-#define AGC_GAIN_4dB                               0.584893f
-#define AGC_HPFGAIN_5dB                            1.511886f
-#define AGC_GAIN_5dB                               0.778279f
-#define AGC_HPFGAIN_6dB                            1.818383f
-#define AGC_GAIN_6dB                               0.995262f
-#define AGC_HPFGAIN_7dB                            2.162278f
-#define AGC_GAIN_7dB                               1.238721f
-#define AGC_HPFGAIN_8dB                            2.548134f
-#define AGC_GAIN_8dB                               1.511886f
-#define AGC_HPFGAIN_9dB                            2.981072f
-#define AGC_GAIN_9dB                               1.818383f
-#define AGC_HPFGAIN_10dB                           3.466836f
-#define AGC_GAIN_10dB                              2.162278f
-#define AGC_HPFGAIN_11dB                           4.011872f
-#define AGC_GAIN_11dB                              2.548134f
-#define AGC_HPFGAIN_12dB                           4.623413f
-#define AGC_GAIN_12dB                              2.981072f
-#define AGC_HPFGAIN_13dB                           5.309573f
-#define AGC_GAIN_13dB                              3.466836f
-#define AGC_HPFGAIN_14dB                           6.079458f
-#define AGC_GAIN_14dB                              4.011872f
-#define AGC_HPFGAIN_15dB                           6.943282f
-#define AGC_GAIN_15dB                              4.623413f
+#define AGC_GAIN_SCALE 31 /* As a power of 2 */
+#define AGC_GAIN_SHIFT 4  /* As a power of 2 */
+#define AGC_TARGETLEVEL 0.988553f
+#define AGC_HPFGAIN_0dB 0.412538f
+#define AGC_GAIN_0dB 0.000000f
+#define AGC_HPFGAIN_1dB 0.584893f
+#define AGC_GAIN_1dB 0.122018f
+#define AGC_HPFGAIN_2dB 0.778279f
+#define AGC_GAIN_2dB 0.258925f
+#define AGC_HPFGAIN_3dB 0.995262f
+#define AGC_GAIN_3dB 0.412538f
+#define AGC_HPFGAIN_4dB 1.238721f
+#define AGC_GAIN_4dB 0.584893f
+#define AGC_HPFGAIN_5dB 1.511886f
+#define AGC_GAIN_5dB 0.778279f
+#define AGC_HPFGAIN_6dB 1.818383f
+#define AGC_GAIN_6dB 0.995262f
+#define AGC_HPFGAIN_7dB 2.162278f
+#define AGC_GAIN_7dB 1.238721f
+#define AGC_HPFGAIN_8dB 2.548134f
+#define AGC_GAIN_8dB 1.511886f
+#define AGC_HPFGAIN_9dB 2.981072f
+#define AGC_GAIN_9dB 1.818383f
+#define AGC_HPFGAIN_10dB 3.466836f
+#define AGC_GAIN_10dB 2.162278f
+#define AGC_HPFGAIN_11dB 4.011872f
+#define AGC_GAIN_11dB 2.548134f
+#define AGC_HPFGAIN_12dB 4.623413f
+#define AGC_GAIN_12dB 2.981072f
+#define AGC_HPFGAIN_13dB 5.309573f
+#define AGC_GAIN_13dB 3.466836f
+#define AGC_HPFGAIN_14dB 6.079458f
+#define AGC_GAIN_14dB 4.011872f
+#define AGC_HPFGAIN_15dB 6.943282f
+#define AGC_GAIN_15dB 4.623413f
 
 /************************************************************************************/
 /*                                                                                  */
@@ -689,38 +689,38 @@
 /************************************************************************************/
 
 /* Volume control gain */
-#define VOLUME_MAX                                          0         /* In dBs */
-#define VOLUME_SHIFT                                        0         /* In dBs */
+#define VOLUME_MAX 0   /* In dBs */
+#define VOLUME_SHIFT 0 /* In dBs */
 
 /* Volume control time constants */
-#define VOL_TC_SHIFT                                       21         /* As a power of 2 */
-#define VOL_TC_Fs8000                                   0.024690f
-#define VOL_TC_Fs11025                                  0.017977f
-#define VOL_TC_Fs12000                                  0.016529f
-#define VOL_TC_Fs16000                                  0.012422f
-#define VOL_TC_Fs22050                                  0.009029f
-#define VOL_TC_Fs24000                                  0.008299f
-#define VOL_TC_Fs32000                                  0.006231f
-#define VOL_TC_Fs44100                                  0.004525f
-#define VOL_TC_Fs48000                                  0.004158f
-#define VOL_TC_Fs88200                                  0.002263f
-#define VOL_TC_Fs96000                                  0.002079f
-#define VOL_TC_Fs176400                                 0.001131f
-#define VOL_TC_Fs192000                                 0.001039f
-#define MIX_TC_Fs8000                                   29365         /* Floating point value 0.896151 */
-#define MIX_TC_Fs11025                                  30230         /* Floating point value 0.922548 */
-#define MIX_TC_Fs12000                                  30422         /* Floating point value 0.928415 */
-#define MIX_TC_Fs16000                                  30978         /* Floating point value 0.945387 */
-#define MIX_TC_Fs22050                                  31451         /* Floating point value 0.959804 */
-#define MIX_TC_Fs24000                                  31554         /* Floating point value 0.962956 */
-#define MIX_TC_Fs32000                                  31850         /* Floating point value 0.971973 */
-#define MIX_TC_Fs44100                                  32097         /* Floating point value 0.979515 */
-#define MIX_TC_Fs48000                                  32150         /* Floating point value 0.981150 */
+#define VOL_TC_SHIFT 21 /* As a power of 2 */
+#define VOL_TC_Fs8000 0.024690f
+#define VOL_TC_Fs11025 0.017977f
+#define VOL_TC_Fs12000 0.016529f
+#define VOL_TC_Fs16000 0.012422f
+#define VOL_TC_Fs22050 0.009029f
+#define VOL_TC_Fs24000 0.008299f
+#define VOL_TC_Fs32000 0.006231f
+#define VOL_TC_Fs44100 0.004525f
+#define VOL_TC_Fs48000 0.004158f
+#define VOL_TC_Fs88200 0.002263f
+#define VOL_TC_Fs96000 0.002079f
+#define VOL_TC_Fs176400 0.001131f
+#define VOL_TC_Fs192000 0.001039f
+#define MIX_TC_Fs8000 29365  /* Floating point value 0.896151 */
+#define MIX_TC_Fs11025 30230 /* Floating point value 0.922548 */
+#define MIX_TC_Fs12000 30422 /* Floating point value 0.928415 */
+#define MIX_TC_Fs16000 30978 /* Floating point value 0.945387 */
+#define MIX_TC_Fs22050 31451 /* Floating point value 0.959804 */
+#define MIX_TC_Fs24000 31554 /* Floating point value 0.962956 */
+#define MIX_TC_Fs32000 31850 /* Floating point value 0.971973 */
+#define MIX_TC_Fs44100 32097 /* Floating point value 0.979515 */
+#define MIX_TC_Fs48000 32150 /* Floating point value 0.981150 */
 /* Floating point value 0.989704 */
-#define MIX_TC_Fs88200                                  32430
-#define MIX_TC_Fs96000                                  32456         /* Floating point value 0.990530 */
+#define MIX_TC_Fs88200 32430
+#define MIX_TC_Fs96000 32456 /* Floating point value 0.990530 */
 /* Floating point value 0.994838 */
-#define MIX_TC_Fs176400                                 32598
-#define MIX_TC_Fs192000                                 32611         /* Floating point value 0.992524 */
+#define MIX_TC_Fs176400 32598
+#define MIX_TC_Fs192000 32611 /* Floating point value 0.992524 */
 
 #endif
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Control.cpp b/media/libeffects/lvm/lib/Bass/src/LVDBE_Control.cpp
index 53feae8..3fc9e95 100644
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Control.cpp
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Control.cpp
@@ -21,6 +21,8 @@
 /*                                                                                      */
 /****************************************************************************************/
 
+#include <audio_utils/BiquadFilter.h>
+#include <system/audio.h>
 #include "LVDBE.h"
 #include "LVDBE_Private.h"
 #include "VectorArithmetic.h"
@@ -47,15 +49,12 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVDBE_ReturnStatus_en LVDBE_GetParameters(LVDBE_Handle_t        hInstance,
-                                            LVDBE_Params_t        *pParams)
-{
-
-    LVDBE_Instance_t    *pInstance =(LVDBE_Instance_t  *)hInstance;
+LVDBE_ReturnStatus_en LVDBE_GetParameters(LVDBE_Handle_t hInstance, LVDBE_Params_t* pParams) {
+    LVDBE_Instance_t* pInstance = (LVDBE_Instance_t*)hInstance;
 
     *pParams = pInstance->Params;
 
-    return(LVDBE_SUCCESS);
+    return (LVDBE_SUCCESS);
 }
 
 /************************************************************************************/
@@ -77,15 +76,13 @@
 /*                                                                                  */
 /************************************************************************************/
 
-LVDBE_ReturnStatus_en LVDBE_GetCapabilities(LVDBE_Handle_t            hInstance,
-                                              LVDBE_Capabilities_t    *pCapabilities)
-{
-
-    LVDBE_Instance_t    *pInstance =(LVDBE_Instance_t  *)hInstance;
+LVDBE_ReturnStatus_en LVDBE_GetCapabilities(LVDBE_Handle_t hInstance,
+                                            LVDBE_Capabilities_t* pCapabilities) {
+    LVDBE_Instance_t* pInstance = (LVDBE_Instance_t*)hInstance;
 
     *pCapabilities = pInstance->Capabilities;
 
-    return(LVDBE_SUCCESS);
+    return (LVDBE_SUCCESS);
 }
 
 /************************************************************************************/
@@ -101,35 +98,30 @@
 /*                                                                                  */
 /************************************************************************************/
 
-void    LVDBE_SetFilters(LVDBE_Instance_t     *pInstance,
-                         LVDBE_Params_t       *pParams)
-{
-
+void LVDBE_SetFilters(LVDBE_Instance_t* pInstance, LVDBE_Params_t* pParams) {
     /*
      * Calculate the table offsets
      */
-    LVM_UINT16 Offset = (LVM_UINT16)((LVM_UINT16)pParams->SampleRate + \
-                                    (LVM_UINT16)(pParams->CentreFrequency * (1+LVDBE_FS_192000)));
+    LVM_UINT16 Offset =
+            (LVM_UINT16)((LVM_UINT16)pParams->SampleRate +
+                         (LVM_UINT16)(pParams->CentreFrequency * (1 + LVDBE_FS_192000)));
 
     /*
      * Setup the high pass filter
      */
-    LoadConst_Float(0,                                          /* Clear the history, value 0 */
-                   (LVM_FLOAT *)&pInstance->pData->HPFTaps,     /* Destination */
-                    sizeof(pInstance->pData->HPFTaps) / sizeof(LVM_FLOAT)); /* Number of words */
-    BQ_2I_D32F32Cll_TRC_WRA_01_Init(&pInstance->pCoef->HPFInstance,    /* Initialise the filter */
-                                    &pInstance->pData->HPFTaps,
-                                    (BQ_FLOAT_Coefs_t *)&LVDBE_HPF_Table[Offset]);
+    std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+            LVDBE_HPF_Table[Offset].A0, LVDBE_HPF_Table[Offset].A1, LVDBE_HPF_Table[Offset].A2,
+            -(LVDBE_HPF_Table[Offset].B1), -(LVDBE_HPF_Table[Offset].B2)};
+    pInstance->pHPFBiquad
+            ->setCoefficients<std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs>>(coefs);
 
     /*
      * Setup the band pass filter
      */
-    LoadConst_Float(0,                                           /* Clear the history, value 0 */
-                 (LVM_FLOAT *)&pInstance->pData->BPFTaps,        /* Destination */
-                 sizeof(pInstance->pData->BPFTaps) / sizeof(LVM_FLOAT));   /* Number of words */
-    BP_1I_D32F32Cll_TRC_WRA_02_Init(&pInstance->pCoef->BPFInstance,    /* Initialise the filter */
-                                    &pInstance->pData->BPFTaps,
-                                    (BP_FLOAT_Coefs_t *)&LVDBE_BPF_Table[Offset]);
+    coefs = {LVDBE_BPF_Table[Offset].A0, 0.0, -(LVDBE_BPF_Table[Offset].A0),
+             -(LVDBE_BPF_Table[Offset].B1), -(LVDBE_BPF_Table[Offset].B2)};
+    pInstance->pBPFBiquad
+            ->setCoefficients<std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs>>(coefs);
 }
 
 /************************************************************************************/
@@ -145,29 +137,26 @@
 /*                                                                                  */
 /************************************************************************************/
 
-void    LVDBE_SetAGC(LVDBE_Instance_t     *pInstance,
-                     LVDBE_Params_t       *pParams)
-{
-
+void LVDBE_SetAGC(LVDBE_Instance_t* pInstance, LVDBE_Params_t* pParams) {
     /*
      * Get the attack and decay time constants
      */
-    pInstance->pData->AGCInstance.AGC_Attack = LVDBE_AGC_ATTACK_Table[(LVM_UINT16)pParams->SampleRate];  /* Attack multiplier */
-    pInstance->pData->AGCInstance.AGC_Decay  = LVDBE_AGC_DECAY_Table[(LVM_UINT16)pParams->SampleRate];   /* Decay multipler */
+    pInstance->pData->AGCInstance.AGC_Attack =
+            LVDBE_AGC_ATTACK_Table[(LVM_UINT16)pParams->SampleRate]; /* Attack multiplier */
+    pInstance->pData->AGCInstance.AGC_Decay =
+            LVDBE_AGC_DECAY_Table[(LVM_UINT16)pParams->SampleRate]; /* Decay multipler */
 
     /*
      * Get the boost gain
      */
-    if (pParams->HPFSelect == LVDBE_HPF_ON)
-    {
-        pInstance->pData->AGCInstance.AGC_MaxGain   = LVDBE_AGC_HPFGAIN_Table[(LVM_UINT16)pParams->EffectLevel];  /* High pass filter on */
-    }
-    else
-    {
-        pInstance->pData->AGCInstance.AGC_MaxGain   = LVDBE_AGC_GAIN_Table[(LVM_UINT16)pParams->EffectLevel];     /* High pass filter off */
+    if (pParams->HPFSelect == LVDBE_HPF_ON) {
+        pInstance->pData->AGCInstance.AGC_MaxGain =
+                LVDBE_AGC_HPFGAIN_Table[(LVM_UINT16)pParams->EffectLevel]; /* High pass filter on */
+    } else {
+        pInstance->pData->AGCInstance.AGC_MaxGain =
+                LVDBE_AGC_GAIN_Table[(LVM_UINT16)pParams->EffectLevel]; /* High pass filter off */
     }
     pInstance->pData->AGCInstance.AGC_Target = AGC_TARGETLEVEL;
-
 }
 
 /************************************************************************************/
@@ -193,29 +182,22 @@
 /*                                                                                  */
 /************************************************************************************/
 
-void    LVDBE_SetVolume(LVDBE_Instance_t     *pInstance,
-                        LVDBE_Params_t       *pParams)
-{
+void LVDBE_SetVolume(LVDBE_Instance_t* pInstance, LVDBE_Params_t* pParams) {
+    LVM_UINT16 dBShifts;  /* 6dB shifts */
+    LVM_UINT16 dBOffset;  /* Table offset */
+    LVM_INT16 Volume = 0; /* Required volume in dBs */
 
-    LVM_UINT16      dBShifts;                                   /* 6dB shifts */
-    LVM_UINT16      dBOffset;                                   /* Table offset */
-    LVM_INT16       Volume = 0;                                 /* Required volume in dBs */
-
-    LVM_FLOAT        dBShifts_fac;
+    LVM_FLOAT dBShifts_fac;
     /*
      * Apply the volume if enabled
      */
-    if (pParams->VolumeControl == LVDBE_VOLUME_ON)
-    {
+    if (pParams->VolumeControl == LVDBE_VOLUME_ON) {
         /*
          * Limit the gain to the maximum allowed
          */
-        if  (pParams->VolumedB > VOLUME_MAX)
-        {
+        if (pParams->VolumedB > VOLUME_MAX) {
             Volume = VOLUME_MAX;
-        }
-        else
-        {
+        } else {
             Volume = pParams->VolumedB;
         }
     }
@@ -223,8 +205,8 @@
     /*
      * Calculate the required gain and shifts
      */
-    dBOffset = (LVM_UINT16)(6 + Volume % 6);                    /* Get the dBs 0-5 */
-    dBShifts = (LVM_UINT16)(Volume / -6);                       /* Get the 6dB shifts */
+    dBOffset = (LVM_UINT16)(6 + Volume % 6); /* Get the dBs 0-5 */
+    dBShifts = (LVM_UINT16)(Volume / -6);    /* Get the 6dB shifts */
 
     dBShifts_fac = (LVM_FLOAT)(1 << dBShifts);
     /*
@@ -232,27 +214,23 @@
      */
     pInstance->pData->AGCInstance.Target = (LVDBE_VolumeTable[dBOffset]);
     pInstance->pData->AGCInstance.Target = pInstance->pData->AGCInstance.Target / dBShifts_fac;
-    pInstance->pData->AGCInstance.VolumeTC    = LVDBE_VolumeTCTable[(LVM_UINT16)pParams->SampleRate];   /* Volume update time constant */
+    pInstance->pData->AGCInstance.VolumeTC =
+            LVDBE_VolumeTCTable[(LVM_UINT16)pParams->SampleRate]; /* Volume update time constant */
 
     /*
      * When DBE is disabled use the bypass volume control
      */
-    if(dBShifts > 0)
-    {
+    if (dBShifts > 0) {
         LVC_Mixer_SetTarget(&pInstance->pData->BypassVolume.MixerStream[0],
                             LVDBE_VolumeTable[dBOffset] / dBShifts_fac);
-    }
-    else
-    {
+    } else {
         LVC_Mixer_SetTarget(&pInstance->pData->BypassVolume.MixerStream[0],
                             LVDBE_VolumeTable[dBOffset]);
     }
 
     pInstance->pData->BypassVolume.MixerStream[0].CallbackSet = 1;
     LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->pData->BypassVolume.MixerStream[0],
-                                LVDBE_MIXER_TC,
-                                (LVM_Fs_en)pInstance->Params.SampleRate,
-                                2);
+                                       LVDBE_MIXER_TC, (LVM_Fs_en)pInstance->Params.SampleRate, 2);
 }
 
 /****************************************************************************************/
@@ -292,21 +270,23 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVDBE_ReturnStatus_en LVDBE_Control(LVDBE_Handle_t         hInstance,
-                                      LVDBE_Params_t         *pParams)
-{
+LVDBE_ReturnStatus_en LVDBE_Control(LVDBE_Handle_t hInstance, LVDBE_Params_t* pParams) {
+    LVDBE_Instance_t* pInstance = (LVDBE_Instance_t*)hInstance;
+    LVMixer3_2St_FLOAT_st* pBypassMixer_Instance = &pInstance->pData->BypassMixer;
 
-    LVDBE_Instance_t    *pInstance =(LVDBE_Instance_t  *)hInstance;
-    LVMixer3_2St_FLOAT_st     *pBypassMixer_Instance = &pInstance->pData->BypassMixer;
+    /*
+     * Create biquad instance
+     */
+    pInstance->pHPFBiquad.reset(
+            new android::audio_utils::BiquadFilter<LVM_FLOAT>(pParams->NrChannels));
 
     /*
      * Update the filters
      */
     if ((pInstance->Params.SampleRate != pParams->SampleRate) ||
-        (pInstance->Params.CentreFrequency != pParams->CentreFrequency))
-    {
-        LVDBE_SetFilters(pInstance,                     /* Instance pointer */
-                         pParams);                      /* New parameters */
+        (pInstance->Params.CentreFrequency != pParams->CentreFrequency)) {
+        LVDBE_SetFilters(pInstance, /* Instance pointer */
+                         pParams);  /* New parameters */
     }
 
     /*
@@ -314,16 +294,14 @@
      */
     if ((pInstance->Params.SampleRate != pParams->SampleRate) ||
         (pInstance->Params.EffectLevel != pParams->EffectLevel) ||
-        (pInstance->Params.HPFSelect != pParams->HPFSelect))
-    {
-        LVDBE_SetAGC(pInstance,                         /* Instance pointer */
-                     pParams);                          /* New parameters */
-        LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[0],
-            LVDBE_BYPASS_MIXER_TC,(LVM_Fs_en)pParams->SampleRate, 2);
+        (pInstance->Params.HPFSelect != pParams->HPFSelect)) {
+        LVDBE_SetAGC(pInstance, /* Instance pointer */
+                     pParams);  /* New parameters */
+        LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[0], LVDBE_BYPASS_MIXER_TC,
+                                  (LVM_Fs_en)pParams->SampleRate, 2);
 
-        LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[1],
-            LVDBE_BYPASS_MIXER_TC,(LVM_Fs_en)pParams->SampleRate, 2);
-
+        LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[1], LVDBE_BYPASS_MIXER_TC,
+                                  (LVM_Fs_en)pParams->SampleRate, 2);
     }
 
     /*
@@ -332,19 +310,16 @@
     if ((pInstance->Params.VolumedB != pParams->VolumedB) ||
         (pInstance->Params.SampleRate != pParams->SampleRate) ||
         (pInstance->Params.HeadroomdB != pParams->HeadroomdB) ||
-        (pInstance->Params.VolumeControl != pParams->VolumeControl))
-    {
-        LVDBE_SetVolume(pInstance,                      /* Instance pointer */
-                       pParams);                        /* New parameters */
+        (pInstance->Params.VolumeControl != pParams->VolumeControl)) {
+        LVDBE_SetVolume(pInstance, /* Instance pointer */
+                        pParams);  /* New parameters */
     }
 
-    if (pInstance->Params.OperatingMode==LVDBE_ON && pParams->OperatingMode==LVDBE_OFF)
-    {
+    if (pInstance->Params.OperatingMode == LVDBE_ON && pParams->OperatingMode == LVDBE_OFF) {
         LVC_Mixer_SetTarget(&pInstance->pData->BypassMixer.MixerStream[0], 0);
         LVC_Mixer_SetTarget(&pInstance->pData->BypassMixer.MixerStream[1], 1.0f);
     }
-    if (pInstance->Params.OperatingMode==LVDBE_OFF && pParams->OperatingMode==LVDBE_ON)
-    {
+    if (pInstance->Params.OperatingMode == LVDBE_OFF && pParams->OperatingMode == LVDBE_ON) {
         LVC_Mixer_SetTarget(&pInstance->pData->BypassMixer.MixerStream[0], 1.0f);
         LVC_Mixer_SetTarget(&pInstance->pData->BypassMixer.MixerStream[1], 0);
     }
@@ -354,5 +329,5 @@
      */
     pInstance->Params = *pParams;
 
-    return(LVDBE_SUCCESS);
+    return (LVDBE_SUCCESS);
 }
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Init.cpp b/media/libeffects/lvm/lib/Bass/src/LVDBE_Init.cpp
index ad77696..bbe7de0 100644
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Init.cpp
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Init.cpp
@@ -21,209 +21,92 @@
 /*                                                                                      */
 /****************************************************************************************/
 
+#include <system/audio.h>
+#include <stdlib.h>
 #include "LVDBE.h"
 #include "LVDBE_Private.h"
 
 /****************************************************************************************/
 /*                                                                                      */
-/* FUNCTION:                 LVDBE_Memory                                               */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*    This function is used for memory allocation and free. It can be called in         */
-/*    two ways:                                                                         */
-/*                                                                                      */
-/*        hInstance = NULL                Returns the memory requirements               */
-/*        hInstance = Instance handle        Returns the memory requirements and        */
-/*                                        allocated base addresses for the instance     */
-/*                                                                                      */
-/*    When this function is called for memory allocation (hInstance=NULL) the memory    */
-/*  base address pointers are NULL on return.                                           */
-/*                                                                                      */
-/*    When the function is called for free (hInstance = Instance Handle) the memory     */
-/*  table returns the allocated memory and base addresses used during initialisation.   */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance                Instance Handle                                            */
-/*  pMemoryTable             Pointer to an empty memory definition table                */
-/*    pCapabilities           Pointer to the instance capabilities                      */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVDBE_SUCCESS            Succeeded                                                  */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*    1.    This function may be interrupted by the LVDBE_Process function              */
-/*                                                                                      */
-/****************************************************************************************/
-
-LVDBE_ReturnStatus_en LVDBE_Memory(LVDBE_Handle_t            hInstance,
-                                   LVDBE_MemTab_t            *pMemoryTable,
-                                   LVDBE_Capabilities_t      *pCapabilities)
-{
-
-    LVM_UINT32          ScratchSize;
-    LVDBE_Instance_t    *pInstance = (LVDBE_Instance_t *)hInstance;
-
-    /*
-     * Fill in the memory table
-     */
-    if (hInstance == LVM_NULL)
-    {
-        /*
-         * Instance memory
-         */
-        pMemoryTable->Region[LVDBE_MEMREGION_INSTANCE].Size         = sizeof(LVDBE_Instance_t);
-        pMemoryTable->Region[LVDBE_MEMREGION_INSTANCE].Alignment    = LVDBE_INSTANCE_ALIGN;
-        pMemoryTable->Region[LVDBE_MEMREGION_INSTANCE].Type         = LVDBE_PERSISTENT;
-        pMemoryTable->Region[LVDBE_MEMREGION_INSTANCE].pBaseAddress = LVM_NULL;
-
-        /*
-         * Data memory
-         */
-        pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_DATA].Size   = sizeof(LVDBE_Data_FLOAT_t);
-        pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_DATA].Alignment    = LVDBE_PERSISTENT_DATA_ALIGN;
-        pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_DATA].Type         = LVDBE_PERSISTENT_DATA;
-        pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_DATA].pBaseAddress = LVM_NULL;
-
-        /*
-         * Coef memory
-         */
-        pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_COEF].Size   = sizeof(LVDBE_Coef_FLOAT_t);
-        pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_COEF].Alignment    = LVDBE_PERSISTENT_COEF_ALIGN;
-        pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_COEF].Type         = LVDBE_PERSISTENT_COEF;
-        pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_COEF].pBaseAddress = LVM_NULL;
-
-        /*
-         * Scratch memory
-         */
-        ScratchSize = (LVM_UINT32)(LVDBE_SCRATCHBUFFERS_INPLACE*sizeof(LVM_FLOAT) * \
-                                        pCapabilities->MaxBlockSize);
-        pMemoryTable->Region[LVDBE_MEMREGION_SCRATCH].Size         = ScratchSize;
-        pMemoryTable->Region[LVDBE_MEMREGION_SCRATCH].Alignment    = LVDBE_SCRATCH_ALIGN;
-        pMemoryTable->Region[LVDBE_MEMREGION_SCRATCH].Type         = LVDBE_SCRATCH;
-        pMemoryTable->Region[LVDBE_MEMREGION_SCRATCH].pBaseAddress = LVM_NULL;
-    }
-    else
-    {
-        /* Read back memory allocation table */
-        *pMemoryTable = pInstance->MemoryTable;
-    }
-
-    return(LVDBE_SUCCESS);
-}
-
-/****************************************************************************************/
-/*                                                                                      */
 /* FUNCTION:                 LVDBE_Init                                                 */
 /*                                                                                      */
 /* DESCRIPTION:                                                                         */
-/*    Create and initialisation function for the Dynamic Bass Enhancement module        */
-/*                                                                                      */
-/*    This function can be used to create an algorithm instance by calling with         */
-/*    hInstance set to NULL. In this case the algorithm returns the new instance        */
-/*    handle.                                                                           */
-/*                                                                                      */
-/*    This function can be used to force a full re-initialisation of the algorithm      */
-/*    by calling with hInstance = Instance Handle. In this case the memory table        */
-/*    should be correct for the instance, this can be ensured by calling the function   */
-/*    DBE_Memory before calling this function.                                          */
+/*    Create and initialisation function for the Bass Enhancement module                */
 /*                                                                                      */
 /* PARAMETERS:                                                                          */
-/*  hInstance                  Instance handle                                          */
-/*  pMemoryTable             Pointer to the memory definition table                     */
-/*  pCapabilities              Pointer to the instance capabilities                     */
+/*  phInstance               Pointer to instance handle                                 */
+/*  pCapabilities            Pointer to the initialisation capabilities                 */
+/*  pScratch                 Pointer to the bundle scratch buffer                       */
 /*                                                                                      */
 /* RETURNS:                                                                             */
 /*  LVDBE_SUCCESS            Initialisation succeeded                                   */
-/*  LVDBE_ALIGNMENTERROR    Instance or scratch memory on incorrect alignment           */
-/*    LVDBE_NULLADDRESS        Instance or scratch memory has a NULL pointer            */
+/*  LVDBE_NULLADDRESS        One or more memory has a NULL pointer - malloc failure     */
 /*                                                                                      */
 /* NOTES:                                                                               */
-/*  1.     The instance handle is the pointer to the base address of the first memory   */
-/*        region.                                                                       */
-/*    2.    This function must not be interrupted by the LVDBE_Process function         */
+/*  1.    This function must not be interrupted by the LVDBE_Process function           */
 /*                                                                                      */
 /****************************************************************************************/
-
-LVDBE_ReturnStatus_en LVDBE_Init(LVDBE_Handle_t         *phInstance,
-                                   LVDBE_MemTab_t       *pMemoryTable,
-                                   LVDBE_Capabilities_t *pCapabilities)
-{
-
-    LVDBE_Instance_t      *pInstance;
-    LVMixer3_1St_FLOAT_st       *pMixer_Instance;
-    LVMixer3_2St_FLOAT_st       *pBypassMixer_Instance;
-    LVM_FLOAT             MixGain;
-    LVM_INT16             i;
+LVDBE_ReturnStatus_en LVDBE_Init(LVDBE_Handle_t* phInstance, LVDBE_Capabilities_t* pCapabilities,
+                                 void* pScratch) {
+    LVDBE_Instance_t* pInstance;
+    LVMixer3_1St_FLOAT_st* pMixer_Instance;
+    LVMixer3_2St_FLOAT_st* pBypassMixer_Instance;
+    LVM_FLOAT MixGain;
 
     /*
-     * Set the instance handle if not already initialised
+     * Create the instance handle if not already initialised
      */
-    if (*phInstance == LVM_NULL)
-    {
-        *phInstance = (LVDBE_Handle_t)pMemoryTable->Region[LVDBE_MEMREGION_INSTANCE].pBaseAddress;
+    if (*phInstance == LVM_NULL) {
+        *phInstance = new LVDBE_Instance_t{};
     }
-    pInstance =(LVDBE_Instance_t  *)*phInstance;
-
-    /*
-     * Check the memory table for NULL pointers and incorrectly aligned data
-     */
-    for (i=0; i<LVDBE_NR_MEMORY_REGIONS; i++)
-    {
-        if (pMemoryTable->Region[i].Size!=0)
-        {
-            if (pMemoryTable->Region[i].pBaseAddress==LVM_NULL)
-            {
-                return(LVDBE_NULLADDRESS);
-            }
-            if (((uintptr_t)pMemoryTable->Region[i].pBaseAddress % pMemoryTable->Region[i].Alignment)!=0){
-                return(LVDBE_ALIGNMENTERROR);
-            }
-        }
-    }
+    pInstance = (LVDBE_Instance_t*)*phInstance;
 
     /*
      * Save the memory table in the instance structure
      */
     pInstance->Capabilities = *pCapabilities;
 
-    /*
-     * Save the memory table in the instance structure
-     */
-    pInstance->MemoryTable = *pMemoryTable;
+    pInstance->pScratch = pScratch;
 
     /*
      * Set the default instance parameters
      */
-    pInstance->Params.CentreFrequency   =    LVDBE_CENTRE_55HZ;
-    pInstance->Params.EffectLevel       =    0;
-    pInstance->Params.HeadroomdB        =    0;
-    pInstance->Params.HPFSelect         =    LVDBE_HPF_OFF;
-    pInstance->Params.OperatingMode     =    LVDBE_OFF;
-    pInstance->Params.SampleRate        =    LVDBE_FS_8000;
-    pInstance->Params.VolumeControl     =    LVDBE_VOLUME_OFF;
-    pInstance->Params.VolumedB          =    0;
+    pInstance->Params.CentreFrequency = LVDBE_CENTRE_55HZ;
+    pInstance->Params.EffectLevel = 0;
+    pInstance->Params.HeadroomdB = 0;
+    pInstance->Params.HPFSelect = LVDBE_HPF_OFF;
+    pInstance->Params.OperatingMode = LVDBE_OFF;
+    pInstance->Params.SampleRate = LVDBE_FS_8000;
+    pInstance->Params.VolumeControl = LVDBE_VOLUME_OFF;
+    pInstance->Params.VolumedB = 0;
 
     /*
-     * Set pointer to data and coef memory
+     * Create pointer to data and coef memory
      */
-    pInstance->pData =
-         (LVDBE_Data_FLOAT_t *)pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_DATA].pBaseAddress;
-    pInstance->pCoef =
-         (LVDBE_Coef_FLOAT_t *)pMemoryTable->Region[LVDBE_MEMREGION_PERSISTENT_COEF].pBaseAddress;
+    pInstance->pData = (LVDBE_Data_FLOAT_t*)calloc(1, sizeof(*(pInstance->pData)));
+    if (pInstance->pData == NULL) {
+        return LVDBE_NULLADDRESS;
+    }
+    /*
+     * Create biquad instance
+     */
+    pInstance->pHPFBiquad.reset(
+            new android::audio_utils::BiquadFilter<LVM_FLOAT>(LVM_MAX_CHANNELS));
+    pInstance->pBPFBiquad.reset(new android::audio_utils::BiquadFilter<LVM_FLOAT>(FCC_1));
 
     /*
      * Initialise the filters
      */
-    LVDBE_SetFilters(pInstance,                 /* Set the filter taps and coefficients */
+    LVDBE_SetFilters(pInstance, /* Set the filter taps and coefficients */
                      &pInstance->Params);
 
     /*
      * Initialise the AGC
      */
-    LVDBE_SetAGC(pInstance,                                     /* Set the AGC gain */
+    LVDBE_SetAGC(pInstance, /* Set the AGC gain */
                  &pInstance->Params);
     pInstance->pData->AGCInstance.AGC_Gain = pInstance->pData->AGCInstance.AGC_MaxGain;
-                                                /* Default to the bass boost setting */
+    /* Default to the bass boost setting */
 
     // initialize the mixer with some fixes values since otherwise LVDBE_SetVolume ends up
     // reading uninitialized data
@@ -233,11 +116,11 @@
     /*
      * Initialise the volume
      */
-    LVDBE_SetVolume(pInstance,                                         /* Set the Volume */
+    LVDBE_SetVolume(pInstance, /* Set the Volume */
                     &pInstance->Params);
 
     pInstance->pData->AGCInstance.Volume = pInstance->pData->AGCInstance.Target;
-                                                /* Initialise as the target */
+    /* Initialise as the target */
     MixGain = LVC_Mixer_GetTarget(&pMixer_Instance->MixerStream[0]);
     LVC_Mixer_Init(&pMixer_Instance->MixerStream[0], MixGain, MixGain);
 
@@ -259,11 +142,11 @@
     pBypassMixer_Instance->MixerStream[0].CallbackParam = 0;
     pBypassMixer_Instance->MixerStream[0].pCallbackHandle = LVM_NULL;
     pBypassMixer_Instance->MixerStream[0].pCallBack = LVM_NULL;
-    pBypassMixer_Instance->MixerStream[0].CallbackSet=0;
+    pBypassMixer_Instance->MixerStream[0].CallbackSet = 0;
 
-    LVC_Mixer_Init(&pBypassMixer_Instance->MixerStream[0],0,0);
-    LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[0],
-        LVDBE_BYPASS_MIXER_TC,(LVM_Fs_en)pInstance->Params.SampleRate,2);
+    LVC_Mixer_Init(&pBypassMixer_Instance->MixerStream[0], 0, 0);
+    LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[0], LVDBE_BYPASS_MIXER_TC,
+                              (LVM_Fs_en)pInstance->Params.SampleRate, 2);
 
     /*
      * Setup the mixer gain for the unprocessed path
@@ -271,10 +154,34 @@
     pBypassMixer_Instance->MixerStream[1].CallbackParam = 0;
     pBypassMixer_Instance->MixerStream[1].pCallbackHandle = LVM_NULL;
     pBypassMixer_Instance->MixerStream[1].pCallBack = LVM_NULL;
-    pBypassMixer_Instance->MixerStream[1].CallbackSet=0;
+    pBypassMixer_Instance->MixerStream[1].CallbackSet = 0;
     LVC_Mixer_Init(&pBypassMixer_Instance->MixerStream[1], 1.0, 1.0);
-    LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[1],
-        LVDBE_BYPASS_MIXER_TC,(LVM_Fs_en)pInstance->Params.SampleRate, 2);
+    LVC_Mixer_SetTimeConstant(&pBypassMixer_Instance->MixerStream[1], LVDBE_BYPASS_MIXER_TC,
+                              (LVM_Fs_en)pInstance->Params.SampleRate, 2);
 
-    return(LVDBE_SUCCESS);
+    return (LVDBE_SUCCESS);
+}
+
+/****************************************************************************************/
+/*                                                                                      */
+/* FUNCTION:                 LVDBE_DeInit                                               */
+/*                                                                                      */
+/* DESCRIPTION:                                                                         */
+/*    Free the memories created during LVDBE_Init including instance handle             */
+/*                                                                                      */
+/* PARAMETERS:                                                                          */
+/*  phInstance               Pointer to instance handle                                 */
+/*                                                                                      */
+/****************************************************************************************/
+void LVDBE_DeInit(LVDBE_Handle_t* phInstance) {
+    LVDBE_Instance_t* pInstance = (LVDBE_Instance_t*)*phInstance;
+    if (pInstance == LVM_NULL) {
+        return;
+    }
+    if (pInstance->pData != LVM_NULL) {
+        free(pInstance->pData);
+        pInstance->pData = LVM_NULL;
+    }
+    delete pInstance;
+    *phInstance = LVM_NULL;
 }
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Private.h b/media/libeffects/lvm/lib/Bass/src/LVDBE_Private.h
index f3faaed..7ac5db3 100644
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Private.h
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Private.h
@@ -33,7 +33,8 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-#include "LVDBE.h"                                /* Calling or Application layer definitions */
+#include <audio_utils/BiquadFilter.h>
+#include "LVDBE.h" /* Calling or Application layer definitions */
 #include "BIQUAD.h"
 #include "LVC_Mixer.h"
 #include "AGC.h"
@@ -45,28 +46,10 @@
 /****************************************************************************************/
 
 /* General */
-#define    LVDBE_INVALID            0xFFFF        /* Invalid init parameter */
+#define LVDBE_INVALID 0xFFFF /* Invalid init parameter */
 
-/* Memory */
-#define LVDBE_MEMREGION_INSTANCE         0       /* Offset to the instance memory region */
-#define LVDBE_MEMREGION_PERSISTENT_DATA  1       /* Offset to persistent data memory region */
-#define LVDBE_MEMREGION_PERSISTENT_COEF  2       /* Offset to persistent coefficient region */
-#define LVDBE_MEMREGION_SCRATCH          3       /* Offset to data scratch memory region */
-
-#define LVDBE_INSTANCE_ALIGN             4       /* 32-bit alignment for structures */
-#define LVDBE_PERSISTENT_DATA_ALIGN      4       /* 32-bit alignment for data */
-#define LVDBE_PERSISTENT_COEF_ALIGN      4       /* 32-bit alignment for coef */
-#define LVDBE_SCRATCH_ALIGN              4       /* 32-bit alignment for long data */
-
-#ifdef SUPPORT_MC
-/* Number of buffers required for inplace processing */
-#define LVDBE_SCRATCHBUFFERS_INPLACE     (LVM_MAX_CHANNELS * 3)
-#else
-#define LVDBE_SCRATCHBUFFERS_INPLACE     6       /* Number of buffers required for inplace processing */
-#endif
-
-#define LVDBE_MIXER_TC                   5       /* Mixer time  */
-#define LVDBE_BYPASS_MIXER_TC            100     /* Bypass mixer time */
+#define LVDBE_MIXER_TC 5          /* Mixer time  */
+#define LVDBE_BYPASS_MIXER_TC 100 /* Bypass mixer time */
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -76,37 +59,30 @@
 
 /* Data structure */
 /* Data structure */
-typedef struct
-{
+typedef struct {
     /* AGC parameters */
-    AGC_MIX_VOL_2St1Mon_FLOAT_t   AGCInstance;        /* AGC instance parameters */
+    AGC_MIX_VOL_2St1Mon_FLOAT_t AGCInstance; /* AGC instance parameters */
 
     /* Process variables */
-    Biquad_2I_Order2_FLOAT_Taps_t     HPFTaps;            /* High pass filter taps */
-    Biquad_1I_Order2_FLOAT_Taps_t     BPFTaps;            /* Band pass filter taps */
-    LVMixer3_1St_FLOAT_st             BypassVolume;       /* Bypass volume scaler */
-    LVMixer3_2St_FLOAT_st             BypassMixer;        /* Bypass Mixer for Click Removal */
+    LVMixer3_1St_FLOAT_st BypassVolume;    /* Bypass volume scaler */
+    LVMixer3_2St_FLOAT_st BypassMixer;     /* Bypass Mixer for Click Removal */
 
 } LVDBE_Data_FLOAT_t;
 
-/* Coefs structure */
-typedef struct
-{
-    /* Process variables */
-    Biquad_FLOAT_Instance_t           HPFInstance;        /* High pass filter instance */
-    Biquad_FLOAT_Instance_t           BPFInstance;        /* Band pass filter instance */
-} LVDBE_Coef_FLOAT_t;
+
 /* Instance structure */
-typedef struct
-{
+typedef struct {
     /* Public parameters */
-    LVDBE_MemTab_t                MemoryTable;        /* Instance memory allocation table */
-    LVDBE_Params_t                Params;             /* Instance parameters */
-    LVDBE_Capabilities_t        Capabilities;         /* Instance capabilities */
+    LVDBE_Params_t Params;             /* Instance parameters */
+    LVDBE_Capabilities_t Capabilities; /* Instance capabilities */
 
     /* Data and coefficient pointers */
-    LVDBE_Data_FLOAT_t                *pData;                /* Instance data */
-    LVDBE_Coef_FLOAT_t                *pCoef;                /* Instance coefficients */
+    LVDBE_Data_FLOAT_t* pData; /* Instance data */
+    void* pScratch;            /* scratch pointer */
+    std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            pHPFBiquad; /* Biquad filter instance for HPF */
+    std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            pBPFBiquad; /* Biquad filter instance for BPF */
 } LVDBE_Instance_t;
 
 /****************************************************************************************/
@@ -115,13 +91,10 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-void    LVDBE_SetAGC(LVDBE_Instance_t       *pInstance,
-                     LVDBE_Params_t         *pParams);
+void LVDBE_SetAGC(LVDBE_Instance_t* pInstance, LVDBE_Params_t* pParams);
 
-void    LVDBE_SetVolume(LVDBE_Instance_t    *pInstance,
-                        LVDBE_Params_t      *pParams);
+void LVDBE_SetVolume(LVDBE_Instance_t* pInstance, LVDBE_Params_t* pParams);
 
-void    LVDBE_SetFilters(LVDBE_Instance_t   *pInstance,
-                         LVDBE_Params_t     *pParams);
+void LVDBE_SetFilters(LVDBE_Instance_t* pInstance, LVDBE_Params_t* pParams);
 
-#endif      /* __LVDBE_PRIVATE_H__ */
+#endif /* __LVDBE_PRIVATE_H__ */
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Process.cpp b/media/libeffects/lvm/lib/Bass/src/LVDBE_Process.cpp
index b4a71c7..0969053 100644
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Process.cpp
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Process.cpp
@@ -20,13 +20,14 @@
 /*    Includes                                                                          */
 /*                                                                                      */
 /****************************************************************************************/
+#include <audio_utils/BiquadFilter.h>
 
-#include <string.h> // memset
+#include <string.h>  // memset
 #include "LVDBE.h"
 #include "LVDBE_Private.h"
 #include "VectorArithmetic.h"
 #include "AGC.h"
-#include "LVDBE_Coeffs.h"               /* Filter coefficients */
+#include "LVDBE_Coeffs.h" /* Filter coefficients */
 #include <log/log.h>
 
 /********************************************************************************************/
@@ -73,179 +74,103 @@
 /*     overall end to end gain is odB.                                                      */
 /*                                                                                          */
 /********************************************************************************************/
-LVDBE_ReturnStatus_en LVDBE_Process(LVDBE_Handle_t hInstance,
-    const LVM_FLOAT *pInData,
-    LVM_FLOAT *pOutData,
-    const LVM_UINT16 NrFrames) // updated to use samples = frames * channels.
+LVDBE_ReturnStatus_en LVDBE_Process(
+        LVDBE_Handle_t hInstance, const LVM_FLOAT* pInData, LVM_FLOAT* pOutData,
+        const LVM_UINT16 NrFrames)  // updated to use samples = frames * channels.
 {
-  LVDBE_Instance_t *pInstance =(LVDBE_Instance_t *)hInstance;
+    LVDBE_Instance_t* pInstance = (LVDBE_Instance_t*)hInstance;
+    const LVM_INT32 NrChannels = pInstance->Params.NrChannels;
+    const LVM_INT32 NrSamples = NrChannels * NrFrames;
 
-  /*Extract number of Channels info*/
-#ifdef SUPPORT_MC
-  // Mono passed in as stereo
-  const LVM_INT32 NrChannels = pInstance->Params.NrChannels == 1
-      ? 2 : pInstance->Params.NrChannels;
-#else
-  const LVM_INT32 NrChannels = 2; // FCC_2
-#endif
-  const LVM_INT32 NrSamples = NrChannels * NrFrames;
-
-  /* Space to store DBE path computation */
-  LVM_FLOAT * const pScratch =
-          (LVM_FLOAT *)pInstance->MemoryTable.Region[LVDBE_MEMREGION_SCRATCH].pBaseAddress;
-
-  /*
-   * Scratch for Mono path starts at offset of
-   * NrSamples float values from pScratch.
-   */
-  LVM_FLOAT * const pMono = pScratch + NrSamples;
-
-  /*
-   * TRICKY: pMono is used and discarded by the DBE path.
-   *         so it is available for use for the pScratchVol
-   *         path which is computed afterwards.
-   *
-   * Space to store Volume Control path computation.
-   * This is identical to pMono (see TRICKY comment).
-   */
-  LVM_FLOAT * const pScratchVol = pMono;
-
-  /*
-   * Check the number of frames is not too large
-   */
-  if (NrFrames > pInstance->Capabilities.MaxBlockSize)
-  {
-    return LVDBE_TOOMANYSAMPLES;
-  }
-
-  /*
-   * Check if the algorithm is enabled
-   */
-  /* DBE path is processed when DBE is ON or during On/Off transitions */
-  if ((pInstance->Params.OperatingMode == LVDBE_ON)||
-      (LVC_Mixer_GetCurrent(&pInstance->pData->BypassMixer.MixerStream[0])
-          !=LVC_Mixer_GetTarget(&pInstance->pData->BypassMixer.MixerStream[0])))
-  {
-    // make copy of input data
-    Copy_Float(pInData,
-        pScratch,
-        (LVM_INT16)NrSamples);
+    /* Space to store DBE path computation */
+    LVM_FLOAT* const pScratch = (LVM_FLOAT*)pInstance->pScratch;
 
     /*
-     * Apply the high pass filter if selected
+     * Scratch for Mono path starts at offset of
+     * NrSamples float values from pScratch.
      */
-    if (pInstance->Params.HPFSelect == LVDBE_HPF_ON)
-    {
-#ifdef SUPPORT_MC
-      BQ_MC_D32F32C30_TRC_WRA_01(&pInstance->pCoef->HPFInstance, /* Filter instance      */
-          pScratch, /* Source               */
-          pScratch, /* Destination          */
-          (LVM_INT16)NrFrames,
-          (LVM_INT16)NrChannels);
-#else
-      BQ_2I_D32F32C30_TRC_WRA_01(&pInstance->pCoef->HPFInstance,/* Filter instance      */
-          pScratch, /* Source               */
-          pScratch, /* Destination          */
-          (LVM_INT16)NrFrames);
-#endif
+    LVM_FLOAT* const pMono = pScratch + NrSamples;
+
+    /*
+     * TRICKY: pMono is used and discarded by the DBE path.
+     *         so it is available for use for the pScratchVol
+     *         path which is computed afterwards.
+     *
+     * Space to store Volume Control path computation.
+     * This is identical to pMono (see TRICKY comment).
+     */
+    LVM_FLOAT* const pScratchVol = pMono;
+
+    /*
+     * Check the number of frames is not too large
+     */
+    if (NrFrames > pInstance->Capabilities.MaxBlockSize) {
+        return LVDBE_TOOMANYSAMPLES;
     }
 
     /*
-     * Create the mono stream
+     * Check if the algorithm is enabled
      */
-#ifdef SUPPORT_MC
-    FromMcToMono_Float(pScratch, /* Source */
-        pMono, /* Mono destination */
-        (LVM_INT16)NrFrames,  /* Number of frames */
-        (LVM_INT16)NrChannels);
-#else
-    From2iToMono_Float(pScratch, /* Stereo source         */
-        pMono, /* Mono destination      */
-        (LVM_INT16)NrFrames);
-#endif
+    /* DBE path is processed when DBE is ON or during On/Off transitions */
+    if ((pInstance->Params.OperatingMode == LVDBE_ON) ||
+        (LVC_Mixer_GetCurrent(&pInstance->pData->BypassMixer.MixerStream[0]) !=
+         LVC_Mixer_GetTarget(&pInstance->pData->BypassMixer.MixerStream[0]))) {
+        // make copy of input data
+        Copy_Float(pInData, pScratch, (LVM_INT16)NrSamples);
 
-    /*
-     * Apply the band pass filter
-     */
-    BP_1I_D32F32C30_TRC_WRA_02(&pInstance->pCoef->BPFInstance, /* Filter instance       */
-        pMono, /* Source                */
-        pMono, /* Destination           */
-        (LVM_INT16)NrFrames);
+        /*
+         * Apply the high pass filter if selected
+         */
+        if (pInstance->Params.HPFSelect == LVDBE_HPF_ON) {
+            pInstance->pHPFBiquad->process(pScratch, pScratch, NrFrames);
+        }
 
-    /*
-     * Apply the AGC and mix
-     */
-#ifdef SUPPORT_MC
-    AGC_MIX_VOL_Mc1Mon_D32_WRA(&pInstance->pData->AGCInstance, /* Instance pointer      */
-        pScratch, /* Source         */
-        pMono, /* Mono band pass source */
-        pScratch, /* Destination    */
-        NrFrames, /* Number of frames     */
-        NrChannels); /* Number of channels     */
-#else
-    AGC_MIX_VOL_2St1Mon_D32_WRA(&pInstance->pData->AGCInstance, /* Instance pointer      */
-        pScratch, /* Stereo source         */
-        pMono, /* Mono band pass source */
-        pScratch, /* Stereo destination    */
-        NrFrames);
-#endif
+        /*
+         * Create the mono stream
+         */
+        FromMcToMono_Float(pScratch,            /* Source */
+                           pMono,               /* Mono destination */
+                           (LVM_INT16)NrFrames, /* Number of frames */
+                           (LVM_INT16)NrChannels);
 
-    for (LVM_INT32 ii = 0; ii < NrSamples; ++ii) {
-      //TODO: replace with existing clamping function
-      if (pScratch[ii] < -1.0) {
-        pScratch[ii] = -1.0;
-      } else if (pScratch[ii] > 1.0) {
-        pScratch[ii] = 1.0;
-      }
+        /*
+         * Apply the band pass filter
+         */
+        pInstance->pBPFBiquad->process(pMono, pMono, NrFrames);
+
+        /*
+         * Apply the AGC and mix
+         */
+        AGC_MIX_VOL_Mc1Mon_D32_WRA(&pInstance->pData->AGCInstance, /* Instance pointer      */
+                                   pScratch,                       /* Source         */
+                                   pMono,                          /* Mono band pass source */
+                                   pScratch,                       /* Destination    */
+                                   NrFrames,                       /* Number of frames     */
+                                   NrChannels);                    /* Number of channels     */
+    } else {
+        // clear DBE processed path
+        memset(pScratch, 0, sizeof(*pScratch) * NrSamples);
     }
-  } else {
-    // clear DBE processed path
-    memset(pScratch, 0, sizeof(*pScratch) * NrSamples);
-  }
 
-  /* Bypass Volume path is processed when DBE is OFF or during On/Off transitions */
-  if ((pInstance->Params.OperatingMode == LVDBE_OFF)||
-      (LVC_Mixer_GetCurrent(&pInstance->pData->BypassMixer.MixerStream[1])
-          !=LVC_Mixer_GetTarget(&pInstance->pData->BypassMixer.MixerStream[1])))
-  {
+    /* Bypass Volume path is processed when DBE is OFF or during On/Off transitions */
+    if ((pInstance->Params.OperatingMode == LVDBE_OFF) ||
+        (LVC_Mixer_GetCurrent(&pInstance->pData->BypassMixer.MixerStream[1]) !=
+         LVC_Mixer_GetTarget(&pInstance->pData->BypassMixer.MixerStream[1]))) {
+        /*
+         * The algorithm is disabled but volume management is required to compensate for
+         * headroom and volume (if enabled)
+         */
+        LVC_MixSoft_Mc_D16C31_SAT(&pInstance->pData->BypassVolume, pInData, pScratchVol,
+                                  (LVM_INT16)NrFrames, (LVM_INT16)NrChannels);
+    } else {
+        // clear bypass volume path
+        memset(pScratchVol, 0, sizeof(*pScratchVol) * NrSamples);
+    }
 
     /*
-     * The algorithm is disabled but volume management is required to compensate for
-     * headroom and volume (if enabled)
+     * Mix DBE processed path and bypass volume path
      */
-#ifdef SUPPORT_MC
-    LVC_MixSoft_Mc_D16C31_SAT(&pInstance->pData->BypassVolume,
-        pInData,
-        pScratchVol,
-        (LVM_INT16)NrFrames,
-        (LVM_INT16)NrChannels);
-#else
-    LVC_MixSoft_1St_D16C31_SAT(&pInstance->pData->BypassVolume,
-        pInData,
-        pScratchVol,
-        (LVM_INT16)NrSamples); /* Left and right, really # samples */
-#endif
-  } else {
-    // clear bypass volume path
-    memset(pScratchVol, 0, sizeof(*pScratchVol) * NrSamples);
-  }
-
-  /*
-   * Mix DBE processed path and bypass volume path
-   */
-#ifdef SUPPORT_MC
-  LVC_MixSoft_2Mc_D16C31_SAT(&pInstance->pData->BypassMixer,
-      pScratch,
-      pScratchVol,
-      pOutData,
-      (LVM_INT16)NrFrames,
-      (LVM_INT16)NrChannels);
-#else
-  LVC_MixSoft_2St_D16C31_SAT(&pInstance->pData->BypassMixer,
-      pScratch,
-      pScratchVol,
-      pOutData,
-      (LVM_INT16)NrSamples);
-#endif
-  return LVDBE_SUCCESS;
+    LVC_MixSoft_2Mc_D16C31_SAT(&pInstance->pData->BypassMixer, pScratch, pScratchVol, pOutData,
+                               (LVM_INT16)NrFrames, (LVM_INT16)NrChannels);
+    return LVDBE_SUCCESS;
 }
diff --git a/media/libeffects/lvm/lib/Bass/src/LVDBE_Tables.cpp b/media/libeffects/lvm/lib/Bass/src/LVDBE_Tables.cpp
index 728575c..1b95812 100644
--- a/media/libeffects/lvm/lib/Bass/src/LVDBE_Tables.cpp
+++ b/media/libeffects/lvm/lib/Bass/src/LVDBE_Tables.cpp
@@ -22,7 +22,7 @@
 /************************************************************************************/
 
 #include "LVDBE.h"
-#include "LVDBE_Coeffs.h"               /* Filter coefficients */
+#include "LVDBE_Coeffs.h" /* Filter coefficients */
 #include "LVDBE_Tables.h"
 #include "BIQUAD.h"
 
@@ -36,275 +36,119 @@
  * High Pass Filter Coefficient table
  */
 const BQ_FLOAT_Coefs_t LVDBE_HPF_Table[] = {
-    /* Coefficients for 55Hz centre frequency */
-    {HPF_Fs8000_Fc55_A2,                /* 8kS/s coefficients */
-     HPF_Fs8000_Fc55_A1,
-     HPF_Fs8000_Fc55_A0,
-     -HPF_Fs8000_Fc55_B2,
-     -HPF_Fs8000_Fc55_B1},
-    {HPF_Fs11025_Fc55_A2,                /* 11kS/s coefficients */
-     HPF_Fs11025_Fc55_A1,
-     HPF_Fs11025_Fc55_A0,
-     -HPF_Fs11025_Fc55_B2,
-     -HPF_Fs11025_Fc55_B1},
-    {HPF_Fs12000_Fc55_A2,                /* 12kS/s coefficients */
-     HPF_Fs12000_Fc55_A1,
-     HPF_Fs12000_Fc55_A0,
-     -HPF_Fs12000_Fc55_B2,
-     -HPF_Fs12000_Fc55_B1},
-    {HPF_Fs16000_Fc55_A2,                /* 16kS/s coefficients */
-     HPF_Fs16000_Fc55_A1,
-     HPF_Fs16000_Fc55_A0,
-     -HPF_Fs16000_Fc55_B2,
-     -HPF_Fs16000_Fc55_B1},
-    {HPF_Fs22050_Fc55_A2,                /* 22kS/s coefficients */
-     HPF_Fs22050_Fc55_A1,
-     HPF_Fs22050_Fc55_A0,
-     -HPF_Fs22050_Fc55_B2,
-     -HPF_Fs22050_Fc55_B1},
-    {HPF_Fs24000_Fc55_A2,                /* 24kS/s coefficients */
-     HPF_Fs24000_Fc55_A1,
-     HPF_Fs24000_Fc55_A0,
-     -HPF_Fs24000_Fc55_B2,
-     -HPF_Fs24000_Fc55_B1},
-    {HPF_Fs32000_Fc55_A2,                /* 32kS/s coefficients */
-     HPF_Fs32000_Fc55_A1,
-     HPF_Fs32000_Fc55_A0,
-     -HPF_Fs32000_Fc55_B2,
-     -HPF_Fs32000_Fc55_B1},
-    {HPF_Fs44100_Fc55_A2,                /* 44kS/s coefficients */
-     HPF_Fs44100_Fc55_A1,
-     HPF_Fs44100_Fc55_A0,
-     -HPF_Fs44100_Fc55_B2,
-     -HPF_Fs44100_Fc55_B1},
-    {HPF_Fs48000_Fc55_A2,                /* 48kS/s coefficients */
-     HPF_Fs48000_Fc55_A1,
-     HPF_Fs48000_Fc55_A0,
-     -HPF_Fs48000_Fc55_B2,
-     -HPF_Fs48000_Fc55_B1},
-    {HPF_Fs88200_Fc55_A2,                /* 88kS/s coefficients */
-     HPF_Fs88200_Fc55_A1,
-     HPF_Fs88200_Fc55_A0,
-     -HPF_Fs88200_Fc55_B2,
-     -HPF_Fs88200_Fc55_B1},
-    {HPF_Fs96000_Fc55_A2,                /* 96kS/s coefficients */
-     HPF_Fs96000_Fc55_A1,
-     HPF_Fs96000_Fc55_A0,
-     -HPF_Fs96000_Fc55_B2,
-     -HPF_Fs96000_Fc55_B1},
-    {HPF_Fs176400_Fc55_A2,                /* 176kS/s coefficients */
-     HPF_Fs176400_Fc55_A1,
-     HPF_Fs176400_Fc55_A0,
-     -HPF_Fs176400_Fc55_B2,
-     -HPF_Fs176400_Fc55_B1},
-    {HPF_Fs192000_Fc55_A2,                /* 192kS/s coefficients */
-     HPF_Fs192000_Fc55_A1,
-     HPF_Fs192000_Fc55_A0,
-     -HPF_Fs192000_Fc55_B2,
-     -HPF_Fs192000_Fc55_B1},
+        /* Coefficients for 55Hz centre frequency */
+        {HPF_Fs8000_Fc55_A2, /* 8kS/s coefficients */
+         HPF_Fs8000_Fc55_A1, HPF_Fs8000_Fc55_A0, -HPF_Fs8000_Fc55_B2, -HPF_Fs8000_Fc55_B1},
+        {HPF_Fs11025_Fc55_A2, /* 11kS/s coefficients */
+         HPF_Fs11025_Fc55_A1, HPF_Fs11025_Fc55_A0, -HPF_Fs11025_Fc55_B2, -HPF_Fs11025_Fc55_B1},
+        {HPF_Fs12000_Fc55_A2, /* 12kS/s coefficients */
+         HPF_Fs12000_Fc55_A1, HPF_Fs12000_Fc55_A0, -HPF_Fs12000_Fc55_B2, -HPF_Fs12000_Fc55_B1},
+        {HPF_Fs16000_Fc55_A2, /* 16kS/s coefficients */
+         HPF_Fs16000_Fc55_A1, HPF_Fs16000_Fc55_A0, -HPF_Fs16000_Fc55_B2, -HPF_Fs16000_Fc55_B1},
+        {HPF_Fs22050_Fc55_A2, /* 22kS/s coefficients */
+         HPF_Fs22050_Fc55_A1, HPF_Fs22050_Fc55_A0, -HPF_Fs22050_Fc55_B2, -HPF_Fs22050_Fc55_B1},
+        {HPF_Fs24000_Fc55_A2, /* 24kS/s coefficients */
+         HPF_Fs24000_Fc55_A1, HPF_Fs24000_Fc55_A0, -HPF_Fs24000_Fc55_B2, -HPF_Fs24000_Fc55_B1},
+        {HPF_Fs32000_Fc55_A2, /* 32kS/s coefficients */
+         HPF_Fs32000_Fc55_A1, HPF_Fs32000_Fc55_A0, -HPF_Fs32000_Fc55_B2, -HPF_Fs32000_Fc55_B1},
+        {HPF_Fs44100_Fc55_A2, /* 44kS/s coefficients */
+         HPF_Fs44100_Fc55_A1, HPF_Fs44100_Fc55_A0, -HPF_Fs44100_Fc55_B2, -HPF_Fs44100_Fc55_B1},
+        {HPF_Fs48000_Fc55_A2, /* 48kS/s coefficients */
+         HPF_Fs48000_Fc55_A1, HPF_Fs48000_Fc55_A0, -HPF_Fs48000_Fc55_B2, -HPF_Fs48000_Fc55_B1},
+        {HPF_Fs88200_Fc55_A2, /* 88kS/s coefficients */
+         HPF_Fs88200_Fc55_A1, HPF_Fs88200_Fc55_A0, -HPF_Fs88200_Fc55_B2, -HPF_Fs88200_Fc55_B1},
+        {HPF_Fs96000_Fc55_A2, /* 96kS/s coefficients */
+         HPF_Fs96000_Fc55_A1, HPF_Fs96000_Fc55_A0, -HPF_Fs96000_Fc55_B2, -HPF_Fs96000_Fc55_B1},
+        {HPF_Fs176400_Fc55_A2, /* 176kS/s coefficients */
+         HPF_Fs176400_Fc55_A1, HPF_Fs176400_Fc55_A0, -HPF_Fs176400_Fc55_B2, -HPF_Fs176400_Fc55_B1},
+        {HPF_Fs192000_Fc55_A2, /* 192kS/s coefficients */
+         HPF_Fs192000_Fc55_A1, HPF_Fs192000_Fc55_A0, -HPF_Fs192000_Fc55_B2, -HPF_Fs192000_Fc55_B1},
 
-    /* Coefficients for 66Hz centre frequency */
-    {HPF_Fs8000_Fc66_A2,                /* 8kS/s coefficients */
-     HPF_Fs8000_Fc66_A1,
-     HPF_Fs8000_Fc66_A0,
-     -HPF_Fs8000_Fc66_B2,
-     -HPF_Fs8000_Fc66_B1},
-    {HPF_Fs11025_Fc66_A2,                /* 11kS/s coefficients */
-     HPF_Fs11025_Fc66_A1,
-     HPF_Fs11025_Fc66_A0,
-     -HPF_Fs11025_Fc66_B2,
-     -HPF_Fs11025_Fc66_B1},
-    {HPF_Fs12000_Fc66_A2,                /* 12kS/s coefficients */
-     HPF_Fs12000_Fc66_A1,
-     HPF_Fs12000_Fc66_A0,
-     -HPF_Fs12000_Fc66_B2,
-     -HPF_Fs12000_Fc66_B1},
-    {HPF_Fs16000_Fc66_A2,                /* 16kS/s coefficients */
-     HPF_Fs16000_Fc66_A1,
-     HPF_Fs16000_Fc66_A0,
-     -HPF_Fs16000_Fc66_B2,
-     -HPF_Fs16000_Fc66_B1},
-    {HPF_Fs22050_Fc66_A2,                /* 22kS/s coefficients */
-     HPF_Fs22050_Fc66_A1,
-     HPF_Fs22050_Fc66_A0,
-     -HPF_Fs22050_Fc66_B2,
-     -HPF_Fs22050_Fc66_B1},
-    {HPF_Fs24000_Fc66_A2,                /* 24kS/s coefficients */
-     HPF_Fs24000_Fc66_A1,
-     HPF_Fs24000_Fc66_A0,
-     -HPF_Fs24000_Fc66_B2,
-     -HPF_Fs24000_Fc66_B1},
-    {HPF_Fs32000_Fc66_A2,                /* 32kS/s coefficients */
-     HPF_Fs32000_Fc66_A1,
-     HPF_Fs32000_Fc66_A0,
-     -HPF_Fs32000_Fc66_B2,
-     -HPF_Fs32000_Fc66_B1},
-    {HPF_Fs44100_Fc66_A2,                /* 44kS/s coefficients */
-     HPF_Fs44100_Fc66_A1,
-     HPF_Fs44100_Fc66_A0,
-     -HPF_Fs44100_Fc66_B2,
-     -HPF_Fs44100_Fc66_B1},
-    {HPF_Fs48000_Fc66_A2,                /* 48kS/s coefficients */
-     HPF_Fs48000_Fc66_A1,
-     HPF_Fs48000_Fc66_A0,
-     -HPF_Fs48000_Fc66_B2,
-     -HPF_Fs48000_Fc66_B1},
-    {HPF_Fs88200_Fc66_A2,                /* 88kS/s coefficients */
-     HPF_Fs88200_Fc66_A1,
-     HPF_Fs88200_Fc66_A0,
-     -HPF_Fs88200_Fc66_B2,
-     -HPF_Fs88200_Fc66_B1},
-    {HPF_Fs96000_Fc66_A2,                /* 96kS/s coefficients */
-     HPF_Fs96000_Fc66_A1,
-     HPF_Fs96000_Fc66_A0,
-     -HPF_Fs96000_Fc66_B2,
-     -HPF_Fs96000_Fc66_B1},
-    {HPF_Fs176400_Fc66_A2,                /* 176kS/s coefficients */
-     HPF_Fs176400_Fc66_A1,
-     HPF_Fs176400_Fc66_A0,
-     -HPF_Fs176400_Fc66_B2,
-     -HPF_Fs176400_Fc66_B1},
-    {HPF_Fs192000_Fc66_A2,                /* 192kS/s coefficients */
-     HPF_Fs192000_Fc66_A1,
-     HPF_Fs192000_Fc66_A0,
-     -HPF_Fs192000_Fc66_B2,
-     -HPF_Fs192000_Fc66_B1},
+        /* Coefficients for 66Hz centre frequency */
+        {HPF_Fs8000_Fc66_A2, /* 8kS/s coefficients */
+         HPF_Fs8000_Fc66_A1, HPF_Fs8000_Fc66_A0, -HPF_Fs8000_Fc66_B2, -HPF_Fs8000_Fc66_B1},
+        {HPF_Fs11025_Fc66_A2, /* 11kS/s coefficients */
+         HPF_Fs11025_Fc66_A1, HPF_Fs11025_Fc66_A0, -HPF_Fs11025_Fc66_B2, -HPF_Fs11025_Fc66_B1},
+        {HPF_Fs12000_Fc66_A2, /* 12kS/s coefficients */
+         HPF_Fs12000_Fc66_A1, HPF_Fs12000_Fc66_A0, -HPF_Fs12000_Fc66_B2, -HPF_Fs12000_Fc66_B1},
+        {HPF_Fs16000_Fc66_A2, /* 16kS/s coefficients */
+         HPF_Fs16000_Fc66_A1, HPF_Fs16000_Fc66_A0, -HPF_Fs16000_Fc66_B2, -HPF_Fs16000_Fc66_B1},
+        {HPF_Fs22050_Fc66_A2, /* 22kS/s coefficients */
+         HPF_Fs22050_Fc66_A1, HPF_Fs22050_Fc66_A0, -HPF_Fs22050_Fc66_B2, -HPF_Fs22050_Fc66_B1},
+        {HPF_Fs24000_Fc66_A2, /* 24kS/s coefficients */
+         HPF_Fs24000_Fc66_A1, HPF_Fs24000_Fc66_A0, -HPF_Fs24000_Fc66_B2, -HPF_Fs24000_Fc66_B1},
+        {HPF_Fs32000_Fc66_A2, /* 32kS/s coefficients */
+         HPF_Fs32000_Fc66_A1, HPF_Fs32000_Fc66_A0, -HPF_Fs32000_Fc66_B2, -HPF_Fs32000_Fc66_B1},
+        {HPF_Fs44100_Fc66_A2, /* 44kS/s coefficients */
+         HPF_Fs44100_Fc66_A1, HPF_Fs44100_Fc66_A0, -HPF_Fs44100_Fc66_B2, -HPF_Fs44100_Fc66_B1},
+        {HPF_Fs48000_Fc66_A2, /* 48kS/s coefficients */
+         HPF_Fs48000_Fc66_A1, HPF_Fs48000_Fc66_A0, -HPF_Fs48000_Fc66_B2, -HPF_Fs48000_Fc66_B1},
+        {HPF_Fs88200_Fc66_A2, /* 88kS/s coefficients */
+         HPF_Fs88200_Fc66_A1, HPF_Fs88200_Fc66_A0, -HPF_Fs88200_Fc66_B2, -HPF_Fs88200_Fc66_B1},
+        {HPF_Fs96000_Fc66_A2, /* 96kS/s coefficients */
+         HPF_Fs96000_Fc66_A1, HPF_Fs96000_Fc66_A0, -HPF_Fs96000_Fc66_B2, -HPF_Fs96000_Fc66_B1},
+        {HPF_Fs176400_Fc66_A2, /* 176kS/s coefficients */
+         HPF_Fs176400_Fc66_A1, HPF_Fs176400_Fc66_A0, -HPF_Fs176400_Fc66_B2, -HPF_Fs176400_Fc66_B1},
+        {HPF_Fs192000_Fc66_A2, /* 192kS/s coefficients */
+         HPF_Fs192000_Fc66_A1, HPF_Fs192000_Fc66_A0, -HPF_Fs192000_Fc66_B2, -HPF_Fs192000_Fc66_B1},
 
-    /* Coefficients for 78Hz centre frequency */
-    {HPF_Fs8000_Fc78_A2,                /* 8kS/s coefficients */
-     HPF_Fs8000_Fc78_A1,
-     HPF_Fs8000_Fc78_A0,
-     -HPF_Fs8000_Fc78_B2,
-     -HPF_Fs8000_Fc78_B1},
-    {HPF_Fs11025_Fc78_A2,                /* 11kS/s coefficients */
-     HPF_Fs11025_Fc78_A1,
-     HPF_Fs11025_Fc78_A0,
-     -HPF_Fs11025_Fc78_B2,
-     -HPF_Fs11025_Fc78_B1},
-    {HPF_Fs12000_Fc78_A2,                /* 12kS/s coefficients */
-     HPF_Fs12000_Fc78_A1,
-     HPF_Fs12000_Fc78_A0,
-     -HPF_Fs12000_Fc78_B2,
-     -HPF_Fs12000_Fc78_B1},
-    {HPF_Fs16000_Fc78_A2,                /* 16kS/s coefficients */
-     HPF_Fs16000_Fc78_A1,
-     HPF_Fs16000_Fc78_A0,
-     -HPF_Fs16000_Fc78_B2,
-     -HPF_Fs16000_Fc78_B1},
-    {HPF_Fs22050_Fc78_A2,                /* 22kS/s coefficients */
-     HPF_Fs22050_Fc78_A1,
-     HPF_Fs22050_Fc78_A0,
-     -HPF_Fs22050_Fc78_B2,
-     -HPF_Fs22050_Fc78_B1},
-    {HPF_Fs24000_Fc78_A2,                /* 24kS/s coefficients */
-     HPF_Fs24000_Fc78_A1,
-     HPF_Fs24000_Fc78_A0,
-     -HPF_Fs24000_Fc78_B2,
-     -HPF_Fs24000_Fc78_B1},
-    {HPF_Fs32000_Fc78_A2,                /* 32kS/s coefficients */
-     HPF_Fs32000_Fc78_A1,
-     HPF_Fs32000_Fc78_A0,
-     -HPF_Fs32000_Fc78_B2,
-     -HPF_Fs32000_Fc78_B1},
-    {HPF_Fs44100_Fc78_A2,                /* 44kS/s coefficients */
-     HPF_Fs44100_Fc78_A1,
-     HPF_Fs44100_Fc78_A0,
-     -HPF_Fs44100_Fc78_B2,
-     -HPF_Fs44100_Fc78_B1},
-    {HPF_Fs48000_Fc78_A2,                /* 48kS/s coefficients */
-     HPF_Fs48000_Fc78_A1,
-     HPF_Fs48000_Fc78_A0,
-     -HPF_Fs48000_Fc78_B2,
-     -HPF_Fs48000_Fc78_B1},
-    {HPF_Fs88200_Fc78_A2,                /* 88kS/s coefficients */
-     HPF_Fs88200_Fc78_A1,
-     HPF_Fs88200_Fc78_A0,
-     -HPF_Fs88200_Fc78_B2,
-     -HPF_Fs88200_Fc78_B1},
-    {HPF_Fs96000_Fc78_A2,                /* 96kS/s coefficients */
-     HPF_Fs96000_Fc78_A1,
-     HPF_Fs96000_Fc78_A0,
-     -HPF_Fs96000_Fc78_B2,
-     -HPF_Fs96000_Fc78_B1},
-    {HPF_Fs176400_Fc78_A2,                /* 176kS/s coefficients */
-     HPF_Fs176400_Fc78_A1,
-     HPF_Fs176400_Fc78_A0,
-     -HPF_Fs176400_Fc78_B2,
-     -HPF_Fs176400_Fc78_B1},
-    {HPF_Fs192000_Fc78_A2,                /* 192kS/s coefficients */
-     HPF_Fs192000_Fc78_A1,
-     HPF_Fs192000_Fc78_A0,
-     -HPF_Fs192000_Fc78_B2,
-     -HPF_Fs192000_Fc78_B1},
+        /* Coefficients for 78Hz centre frequency */
+        {HPF_Fs8000_Fc78_A2, /* 8kS/s coefficients */
+         HPF_Fs8000_Fc78_A1, HPF_Fs8000_Fc78_A0, -HPF_Fs8000_Fc78_B2, -HPF_Fs8000_Fc78_B1},
+        {HPF_Fs11025_Fc78_A2, /* 11kS/s coefficients */
+         HPF_Fs11025_Fc78_A1, HPF_Fs11025_Fc78_A0, -HPF_Fs11025_Fc78_B2, -HPF_Fs11025_Fc78_B1},
+        {HPF_Fs12000_Fc78_A2, /* 12kS/s coefficients */
+         HPF_Fs12000_Fc78_A1, HPF_Fs12000_Fc78_A0, -HPF_Fs12000_Fc78_B2, -HPF_Fs12000_Fc78_B1},
+        {HPF_Fs16000_Fc78_A2, /* 16kS/s coefficients */
+         HPF_Fs16000_Fc78_A1, HPF_Fs16000_Fc78_A0, -HPF_Fs16000_Fc78_B2, -HPF_Fs16000_Fc78_B1},
+        {HPF_Fs22050_Fc78_A2, /* 22kS/s coefficients */
+         HPF_Fs22050_Fc78_A1, HPF_Fs22050_Fc78_A0, -HPF_Fs22050_Fc78_B2, -HPF_Fs22050_Fc78_B1},
+        {HPF_Fs24000_Fc78_A2, /* 24kS/s coefficients */
+         HPF_Fs24000_Fc78_A1, HPF_Fs24000_Fc78_A0, -HPF_Fs24000_Fc78_B2, -HPF_Fs24000_Fc78_B1},
+        {HPF_Fs32000_Fc78_A2, /* 32kS/s coefficients */
+         HPF_Fs32000_Fc78_A1, HPF_Fs32000_Fc78_A0, -HPF_Fs32000_Fc78_B2, -HPF_Fs32000_Fc78_B1},
+        {HPF_Fs44100_Fc78_A2, /* 44kS/s coefficients */
+         HPF_Fs44100_Fc78_A1, HPF_Fs44100_Fc78_A0, -HPF_Fs44100_Fc78_B2, -HPF_Fs44100_Fc78_B1},
+        {HPF_Fs48000_Fc78_A2, /* 48kS/s coefficients */
+         HPF_Fs48000_Fc78_A1, HPF_Fs48000_Fc78_A0, -HPF_Fs48000_Fc78_B2, -HPF_Fs48000_Fc78_B1},
+        {HPF_Fs88200_Fc78_A2, /* 88kS/s coefficients */
+         HPF_Fs88200_Fc78_A1, HPF_Fs88200_Fc78_A0, -HPF_Fs88200_Fc78_B2, -HPF_Fs88200_Fc78_B1},
+        {HPF_Fs96000_Fc78_A2, /* 96kS/s coefficients */
+         HPF_Fs96000_Fc78_A1, HPF_Fs96000_Fc78_A0, -HPF_Fs96000_Fc78_B2, -HPF_Fs96000_Fc78_B1},
+        {HPF_Fs176400_Fc78_A2, /* 176kS/s coefficients */
+         HPF_Fs176400_Fc78_A1, HPF_Fs176400_Fc78_A0, -HPF_Fs176400_Fc78_B2, -HPF_Fs176400_Fc78_B1},
+        {HPF_Fs192000_Fc78_A2, /* 192kS/s coefficients */
+         HPF_Fs192000_Fc78_A1, HPF_Fs192000_Fc78_A0, -HPF_Fs192000_Fc78_B2, -HPF_Fs192000_Fc78_B1},
 
-    /* Coefficients for 90Hz centre frequency */
-    {HPF_Fs8000_Fc90_A2,                /* 8kS/s coefficients */
-     HPF_Fs8000_Fc90_A1,
-     HPF_Fs8000_Fc90_A0,
-     -HPF_Fs8000_Fc90_B2,
-     -HPF_Fs8000_Fc90_B1},
-    {HPF_Fs11025_Fc90_A2,                /* 11kS/s coefficients */
-     HPF_Fs11025_Fc90_A1,
-     HPF_Fs11025_Fc90_A0,
-     -HPF_Fs11025_Fc90_B2,
-     -HPF_Fs11025_Fc90_B1},
-    {HPF_Fs12000_Fc90_A2,                /* 12kS/s coefficients */
-     HPF_Fs12000_Fc90_A1,
-     HPF_Fs12000_Fc90_A0,
-     -HPF_Fs12000_Fc90_B2,
-     -HPF_Fs12000_Fc90_B1},
-    {HPF_Fs16000_Fc90_A2,                /* 16kS/s coefficients */
-     HPF_Fs16000_Fc90_A1,
-     HPF_Fs16000_Fc90_A0,
-     -HPF_Fs16000_Fc90_B2,
-     -HPF_Fs16000_Fc90_B1},
-    {HPF_Fs22050_Fc90_A2,                /* 22kS/s coefficients */
-     HPF_Fs22050_Fc90_A1,
-     HPF_Fs22050_Fc90_A0,
-     -HPF_Fs22050_Fc90_B2,
-     -HPF_Fs22050_Fc90_B1},
-    {HPF_Fs24000_Fc90_A2,                /* 24kS/s coefficients */
-     HPF_Fs24000_Fc90_A1,
-     HPF_Fs24000_Fc90_A0,
-     -HPF_Fs24000_Fc90_B2,
-     -HPF_Fs24000_Fc90_B1},
-    {HPF_Fs32000_Fc90_A2,                /* 32kS/s coefficients */
-     HPF_Fs32000_Fc90_A1,
-     HPF_Fs32000_Fc90_A0,
-     -HPF_Fs32000_Fc90_B2,
-     -HPF_Fs32000_Fc90_B1},
-    {HPF_Fs44100_Fc90_A2,                /* 44kS/s coefficients */
-     HPF_Fs44100_Fc90_A1,
-     HPF_Fs44100_Fc90_A0,
-     -HPF_Fs44100_Fc90_B2,
-     -HPF_Fs44100_Fc90_B1},
-    {HPF_Fs48000_Fc90_A2,                /* 48kS/s coefficients */
-     HPF_Fs48000_Fc90_A1,
-     HPF_Fs48000_Fc90_A0,
-     -HPF_Fs48000_Fc90_B2,
-     -HPF_Fs48000_Fc90_B1}
+        /* Coefficients for 90Hz centre frequency */
+        {HPF_Fs8000_Fc90_A2, /* 8kS/s coefficients */
+         HPF_Fs8000_Fc90_A1, HPF_Fs8000_Fc90_A0, -HPF_Fs8000_Fc90_B2, -HPF_Fs8000_Fc90_B1},
+        {HPF_Fs11025_Fc90_A2, /* 11kS/s coefficients */
+         HPF_Fs11025_Fc90_A1, HPF_Fs11025_Fc90_A0, -HPF_Fs11025_Fc90_B2, -HPF_Fs11025_Fc90_B1},
+        {HPF_Fs12000_Fc90_A2, /* 12kS/s coefficients */
+         HPF_Fs12000_Fc90_A1, HPF_Fs12000_Fc90_A0, -HPF_Fs12000_Fc90_B2, -HPF_Fs12000_Fc90_B1},
+        {HPF_Fs16000_Fc90_A2, /* 16kS/s coefficients */
+         HPF_Fs16000_Fc90_A1, HPF_Fs16000_Fc90_A0, -HPF_Fs16000_Fc90_B2, -HPF_Fs16000_Fc90_B1},
+        {HPF_Fs22050_Fc90_A2, /* 22kS/s coefficients */
+         HPF_Fs22050_Fc90_A1, HPF_Fs22050_Fc90_A0, -HPF_Fs22050_Fc90_B2, -HPF_Fs22050_Fc90_B1},
+        {HPF_Fs24000_Fc90_A2, /* 24kS/s coefficients */
+         HPF_Fs24000_Fc90_A1, HPF_Fs24000_Fc90_A0, -HPF_Fs24000_Fc90_B2, -HPF_Fs24000_Fc90_B1},
+        {HPF_Fs32000_Fc90_A2, /* 32kS/s coefficients */
+         HPF_Fs32000_Fc90_A1, HPF_Fs32000_Fc90_A0, -HPF_Fs32000_Fc90_B2, -HPF_Fs32000_Fc90_B1},
+        {HPF_Fs44100_Fc90_A2, /* 44kS/s coefficients */
+         HPF_Fs44100_Fc90_A1, HPF_Fs44100_Fc90_A0, -HPF_Fs44100_Fc90_B2, -HPF_Fs44100_Fc90_B1},
+        {HPF_Fs48000_Fc90_A2, /* 48kS/s coefficients */
+         HPF_Fs48000_Fc90_A1, HPF_Fs48000_Fc90_A0, -HPF_Fs48000_Fc90_B2, -HPF_Fs48000_Fc90_B1}
 
-    ,
-    {HPF_Fs88200_Fc90_A2,                /* 88kS/s coefficients */
-     HPF_Fs88200_Fc90_A1,
-     HPF_Fs88200_Fc90_A0,
-     -HPF_Fs88200_Fc90_B2,
-     -HPF_Fs88200_Fc90_B1},
-    {HPF_Fs96000_Fc90_A2,                /* 96kS/s coefficients */
-     HPF_Fs96000_Fc90_A1,
-     HPF_Fs96000_Fc90_A0,
-     -HPF_Fs96000_Fc90_B2,
-     -HPF_Fs96000_Fc90_B1},
-    {HPF_Fs176400_Fc90_A2,                /* 176kS/s coefficients */
-     HPF_Fs176400_Fc90_A1,
-     HPF_Fs176400_Fc90_A0,
-     -HPF_Fs176400_Fc90_B2,
-     -HPF_Fs176400_Fc90_B1},
-    {HPF_Fs192000_Fc90_A2,                /* 192kS/s coefficients */
-     HPF_Fs192000_Fc90_A1,
-     HPF_Fs192000_Fc90_A0,
-     -HPF_Fs192000_Fc90_B2,
-     -HPF_Fs192000_Fc90_B1}
+        ,
+        {HPF_Fs88200_Fc90_A2, /* 88kS/s coefficients */
+         HPF_Fs88200_Fc90_A1, HPF_Fs88200_Fc90_A0, -HPF_Fs88200_Fc90_B2, -HPF_Fs88200_Fc90_B1},
+        {HPF_Fs96000_Fc90_A2, /* 96kS/s coefficients */
+         HPF_Fs96000_Fc90_A1, HPF_Fs96000_Fc90_A0, -HPF_Fs96000_Fc90_B2, -HPF_Fs96000_Fc90_B1},
+        {HPF_Fs176400_Fc90_A2, /* 176kS/s coefficients */
+         HPF_Fs176400_Fc90_A1, HPF_Fs176400_Fc90_A0, -HPF_Fs176400_Fc90_B2, -HPF_Fs176400_Fc90_B1},
+        {HPF_Fs192000_Fc90_A2, /* 192kS/s coefficients */
+         HPF_Fs192000_Fc90_A1, HPF_Fs192000_Fc90_A0, -HPF_Fs192000_Fc90_B2, -HPF_Fs192000_Fc90_B1}
 
 };
 
@@ -312,170 +156,117 @@
  * Band Pass Filter coefficient table
  */
 const BP_FLOAT_Coefs_t LVDBE_BPF_Table[] = {
-    /* Coefficients for 55Hz centre frequency */
-    {BPF_Fs8000_Fc55_A0,                /* 8kS/s coefficients */
-     -BPF_Fs8000_Fc55_B2,
-     -BPF_Fs8000_Fc55_B1},
-    {BPF_Fs11025_Fc55_A0,                /* 11kS/s coefficients */
-     -BPF_Fs11025_Fc55_B2,
-     -BPF_Fs11025_Fc55_B1},
-    {BPF_Fs12000_Fc55_A0,                /* 12kS/s coefficients */
-     -BPF_Fs12000_Fc55_B2,
-     -BPF_Fs12000_Fc55_B1},
-    {BPF_Fs16000_Fc55_A0,                /* 16kS/s coefficients */
-     -BPF_Fs16000_Fc55_B2,
-     -BPF_Fs16000_Fc55_B1},
-    {BPF_Fs22050_Fc55_A0,                /* 22kS/s coefficients */
-     -BPF_Fs22050_Fc55_B2,
-     -BPF_Fs22050_Fc55_B1},
-    {BPF_Fs24000_Fc55_A0,                /* 24kS/s coefficients */
-     -BPF_Fs24000_Fc55_B2,
-     -BPF_Fs24000_Fc55_B1},
-    {BPF_Fs32000_Fc55_A0,                /* 32kS/s coefficients */
-     -BPF_Fs32000_Fc55_B2,
-     -BPF_Fs32000_Fc55_B1},
-    {BPF_Fs44100_Fc55_A0,                /* 44kS/s coefficients */
-     -BPF_Fs44100_Fc55_B2,
-     -BPF_Fs44100_Fc55_B1},
-    {BPF_Fs48000_Fc55_A0,                /* 48kS/s coefficients */
-     -BPF_Fs48000_Fc55_B2,
-     -BPF_Fs48000_Fc55_B1},
-     {BPF_Fs88200_Fc55_A0,                /* 88kS/s coefficients */
-      -BPF_Fs88200_Fc55_B2,
-      -BPF_Fs88200_Fc55_B1},
-     {BPF_Fs96000_Fc55_A0,                /* 96kS/s coefficients */
-     -BPF_Fs96000_Fc55_B2,
-     -BPF_Fs96000_Fc55_B1},
-     {BPF_Fs176400_Fc55_A0,                /* 176kS/s coefficients */
-      -BPF_Fs176400_Fc55_B2,
-      -BPF_Fs176400_Fc55_B1},
-     {BPF_Fs192000_Fc55_A0,                /* 192kS/s coefficients */
-     -BPF_Fs192000_Fc55_B2,
-     -BPF_Fs192000_Fc55_B1},
+        /* Coefficients for 55Hz centre frequency */
+        {BPF_Fs8000_Fc55_A0, /* 8kS/s coefficients */
+         -BPF_Fs8000_Fc55_B2, -BPF_Fs8000_Fc55_B1},
+        {BPF_Fs11025_Fc55_A0, /* 11kS/s coefficients */
+         -BPF_Fs11025_Fc55_B2, -BPF_Fs11025_Fc55_B1},
+        {BPF_Fs12000_Fc55_A0, /* 12kS/s coefficients */
+         -BPF_Fs12000_Fc55_B2, -BPF_Fs12000_Fc55_B1},
+        {BPF_Fs16000_Fc55_A0, /* 16kS/s coefficients */
+         -BPF_Fs16000_Fc55_B2, -BPF_Fs16000_Fc55_B1},
+        {BPF_Fs22050_Fc55_A0, /* 22kS/s coefficients */
+         -BPF_Fs22050_Fc55_B2, -BPF_Fs22050_Fc55_B1},
+        {BPF_Fs24000_Fc55_A0, /* 24kS/s coefficients */
+         -BPF_Fs24000_Fc55_B2, -BPF_Fs24000_Fc55_B1},
+        {BPF_Fs32000_Fc55_A0, /* 32kS/s coefficients */
+         -BPF_Fs32000_Fc55_B2, -BPF_Fs32000_Fc55_B1},
+        {BPF_Fs44100_Fc55_A0, /* 44kS/s coefficients */
+         -BPF_Fs44100_Fc55_B2, -BPF_Fs44100_Fc55_B1},
+        {BPF_Fs48000_Fc55_A0, /* 48kS/s coefficients */
+         -BPF_Fs48000_Fc55_B2, -BPF_Fs48000_Fc55_B1},
+        {BPF_Fs88200_Fc55_A0, /* 88kS/s coefficients */
+         -BPF_Fs88200_Fc55_B2, -BPF_Fs88200_Fc55_B1},
+        {BPF_Fs96000_Fc55_A0, /* 96kS/s coefficients */
+         -BPF_Fs96000_Fc55_B2, -BPF_Fs96000_Fc55_B1},
+        {BPF_Fs176400_Fc55_A0, /* 176kS/s coefficients */
+         -BPF_Fs176400_Fc55_B2, -BPF_Fs176400_Fc55_B1},
+        {BPF_Fs192000_Fc55_A0, /* 192kS/s coefficients */
+         -BPF_Fs192000_Fc55_B2, -BPF_Fs192000_Fc55_B1},
 
-    /* Coefficients for 66Hz centre frequency */
-    {BPF_Fs8000_Fc66_A0,                /* 8kS/s coefficients */
-     -BPF_Fs8000_Fc66_B2,
-     -BPF_Fs8000_Fc66_B1},
-    {BPF_Fs11025_Fc66_A0,                /* 11kS/s coefficients */
-     -BPF_Fs11025_Fc66_B2,
-     -BPF_Fs11025_Fc66_B1},
-    {BPF_Fs12000_Fc66_A0,                /* 12kS/s coefficients */
-     -BPF_Fs12000_Fc66_B2,
-     -BPF_Fs12000_Fc66_B1},
-    {BPF_Fs16000_Fc66_A0,                /* 16kS/s coefficients */
-     -BPF_Fs16000_Fc66_B2,
-     -BPF_Fs16000_Fc66_B1},
-    {BPF_Fs22050_Fc66_A0,                /* 22kS/s coefficients */
-     -BPF_Fs22050_Fc66_B2,
-     -BPF_Fs22050_Fc66_B1},
-    {BPF_Fs24000_Fc66_A0,                /* 24kS/s coefficients */
-     -BPF_Fs24000_Fc66_B2,
-     -BPF_Fs24000_Fc66_B1},
-    {BPF_Fs32000_Fc66_A0,                /* 32kS/s coefficients */
-     -BPF_Fs32000_Fc66_B2,
-     -BPF_Fs32000_Fc66_B1},
-    {BPF_Fs44100_Fc66_A0,                /* 44kS/s coefficients */
-     -BPF_Fs44100_Fc66_B2,
-     -BPF_Fs44100_Fc66_B1},
-    {BPF_Fs48000_Fc66_A0,                /* 48kS/s coefficients */
-     -BPF_Fs48000_Fc66_B2,
-     -BPF_Fs48000_Fc66_B1},
-    {BPF_Fs88200_Fc66_A0,                /* 88kS/s coefficients */
-     -BPF_Fs88200_Fc66_B2,
-     -BPF_Fs88200_Fc66_B1},
-    {BPF_Fs96000_Fc66_A0,                /* 96kS/s coefficients */
-     -BPF_Fs96000_Fc66_B2,
-     -BPF_Fs96000_Fc66_B1},
-    {BPF_Fs176400_Fc66_A0,                /* 176kS/s coefficients */
-     -BPF_Fs176400_Fc66_B2,
-     -BPF_Fs176400_Fc66_B1},
-    {BPF_Fs192000_Fc66_A0,                /* 192kS/s coefficients */
-     -BPF_Fs192000_Fc66_B2,
-     -BPF_Fs192000_Fc66_B1},
+        /* Coefficients for 66Hz centre frequency */
+        {BPF_Fs8000_Fc66_A0, /* 8kS/s coefficients */
+         -BPF_Fs8000_Fc66_B2, -BPF_Fs8000_Fc66_B1},
+        {BPF_Fs11025_Fc66_A0, /* 11kS/s coefficients */
+         -BPF_Fs11025_Fc66_B2, -BPF_Fs11025_Fc66_B1},
+        {BPF_Fs12000_Fc66_A0, /* 12kS/s coefficients */
+         -BPF_Fs12000_Fc66_B2, -BPF_Fs12000_Fc66_B1},
+        {BPF_Fs16000_Fc66_A0, /* 16kS/s coefficients */
+         -BPF_Fs16000_Fc66_B2, -BPF_Fs16000_Fc66_B1},
+        {BPF_Fs22050_Fc66_A0, /* 22kS/s coefficients */
+         -BPF_Fs22050_Fc66_B2, -BPF_Fs22050_Fc66_B1},
+        {BPF_Fs24000_Fc66_A0, /* 24kS/s coefficients */
+         -BPF_Fs24000_Fc66_B2, -BPF_Fs24000_Fc66_B1},
+        {BPF_Fs32000_Fc66_A0, /* 32kS/s coefficients */
+         -BPF_Fs32000_Fc66_B2, -BPF_Fs32000_Fc66_B1},
+        {BPF_Fs44100_Fc66_A0, /* 44kS/s coefficients */
+         -BPF_Fs44100_Fc66_B2, -BPF_Fs44100_Fc66_B1},
+        {BPF_Fs48000_Fc66_A0, /* 48kS/s coefficients */
+         -BPF_Fs48000_Fc66_B2, -BPF_Fs48000_Fc66_B1},
+        {BPF_Fs88200_Fc66_A0, /* 88kS/s coefficients */
+         -BPF_Fs88200_Fc66_B2, -BPF_Fs88200_Fc66_B1},
+        {BPF_Fs96000_Fc66_A0, /* 96kS/s coefficients */
+         -BPF_Fs96000_Fc66_B2, -BPF_Fs96000_Fc66_B1},
+        {BPF_Fs176400_Fc66_A0, /* 176kS/s coefficients */
+         -BPF_Fs176400_Fc66_B2, -BPF_Fs176400_Fc66_B1},
+        {BPF_Fs192000_Fc66_A0, /* 192kS/s coefficients */
+         -BPF_Fs192000_Fc66_B2, -BPF_Fs192000_Fc66_B1},
 
-    /* Coefficients for 78Hz centre frequency */
-    {BPF_Fs8000_Fc78_A0,                /* 8kS/s coefficients */
-     -BPF_Fs8000_Fc78_B2,
-     -BPF_Fs8000_Fc78_B1},
-    {BPF_Fs11025_Fc78_A0,                /* 11kS/s coefficients */
-     -BPF_Fs11025_Fc78_B2,
-     -BPF_Fs11025_Fc78_B1},
-    {BPF_Fs12000_Fc78_A0,                /* 12kS/s coefficients */
-     -BPF_Fs12000_Fc78_B2,
-     -BPF_Fs12000_Fc78_B1},
-    {BPF_Fs16000_Fc78_A0,                /* 16kS/s coefficients */
-     -BPF_Fs16000_Fc78_B2,
-     -BPF_Fs16000_Fc78_B1},
-    {BPF_Fs22050_Fc78_A0,                /* 22kS/s coefficients */
-     -BPF_Fs22050_Fc78_B2,
-     -BPF_Fs22050_Fc78_B1},
-    {BPF_Fs24000_Fc78_A0,                /* 24kS/s coefficients */
-     -BPF_Fs24000_Fc78_B2,
-     -BPF_Fs24000_Fc78_B1},
-    {BPF_Fs32000_Fc78_A0,                /* 32kS/s coefficients */
-     -BPF_Fs32000_Fc78_B2,
-     -BPF_Fs32000_Fc78_B1},
-    {BPF_Fs44100_Fc78_A0,                /* 44kS/s coefficients */
-     -BPF_Fs44100_Fc78_B2,
-     -BPF_Fs44100_Fc78_B1},
-    {BPF_Fs48000_Fc78_A0,                /* 48kS/s coefficients */
-     -BPF_Fs48000_Fc78_B2,
-     -BPF_Fs48000_Fc78_B1},
-    {BPF_Fs88200_Fc66_A0,                /* 88kS/s coefficients */
-     -BPF_Fs88200_Fc66_B2,
-     -BPF_Fs88200_Fc66_B1},
-    {BPF_Fs96000_Fc78_A0,                /* 96kS/s coefficients */
-     -BPF_Fs96000_Fc78_B2,
-     -BPF_Fs96000_Fc78_B1},
-    {BPF_Fs176400_Fc66_A0,                /* 176kS/s coefficients */
-     -BPF_Fs176400_Fc66_B2,
-     -BPF_Fs176400_Fc66_B1},
-    {BPF_Fs192000_Fc78_A0,                /* 192kS/s coefficients */
-     -BPF_Fs192000_Fc78_B2,
-     -BPF_Fs192000_Fc78_B1},
+        /* Coefficients for 78Hz centre frequency */
+        {BPF_Fs8000_Fc78_A0, /* 8kS/s coefficients */
+         -BPF_Fs8000_Fc78_B2, -BPF_Fs8000_Fc78_B1},
+        {BPF_Fs11025_Fc78_A0, /* 11kS/s coefficients */
+         -BPF_Fs11025_Fc78_B2, -BPF_Fs11025_Fc78_B1},
+        {BPF_Fs12000_Fc78_A0, /* 12kS/s coefficients */
+         -BPF_Fs12000_Fc78_B2, -BPF_Fs12000_Fc78_B1},
+        {BPF_Fs16000_Fc78_A0, /* 16kS/s coefficients */
+         -BPF_Fs16000_Fc78_B2, -BPF_Fs16000_Fc78_B1},
+        {BPF_Fs22050_Fc78_A0, /* 22kS/s coefficients */
+         -BPF_Fs22050_Fc78_B2, -BPF_Fs22050_Fc78_B1},
+        {BPF_Fs24000_Fc78_A0, /* 24kS/s coefficients */
+         -BPF_Fs24000_Fc78_B2, -BPF_Fs24000_Fc78_B1},
+        {BPF_Fs32000_Fc78_A0, /* 32kS/s coefficients */
+         -BPF_Fs32000_Fc78_B2, -BPF_Fs32000_Fc78_B1},
+        {BPF_Fs44100_Fc78_A0, /* 44kS/s coefficients */
+         -BPF_Fs44100_Fc78_B2, -BPF_Fs44100_Fc78_B1},
+        {BPF_Fs48000_Fc78_A0, /* 48kS/s coefficients */
+         -BPF_Fs48000_Fc78_B2, -BPF_Fs48000_Fc78_B1},
+        {BPF_Fs88200_Fc66_A0, /* 88kS/s coefficients */
+         -BPF_Fs88200_Fc66_B2, -BPF_Fs88200_Fc66_B1},
+        {BPF_Fs96000_Fc78_A0, /* 96kS/s coefficients */
+         -BPF_Fs96000_Fc78_B2, -BPF_Fs96000_Fc78_B1},
+        {BPF_Fs176400_Fc66_A0, /* 176kS/s coefficients */
+         -BPF_Fs176400_Fc66_B2, -BPF_Fs176400_Fc66_B1},
+        {BPF_Fs192000_Fc78_A0, /* 192kS/s coefficients */
+         -BPF_Fs192000_Fc78_B2, -BPF_Fs192000_Fc78_B1},
 
-    /* Coefficients for 90Hz centre frequency */
-    {BPF_Fs8000_Fc90_A0,                /* 8kS/s coefficients */
-     -BPF_Fs8000_Fc90_B2,
-     -BPF_Fs8000_Fc90_B1},
-    {BPF_Fs11025_Fc90_A0,                /* 11kS/s coefficients */
-     -BPF_Fs11025_Fc90_B2,
-     -BPF_Fs11025_Fc90_B1},
-    {BPF_Fs12000_Fc90_A0,                /* 12kS/s coefficients */
-     -BPF_Fs12000_Fc90_B2,
-     -BPF_Fs12000_Fc90_B1},
-    {BPF_Fs16000_Fc90_A0,                /* 16kS/s coefficients */
-     -BPF_Fs16000_Fc90_B2,
-     -BPF_Fs16000_Fc90_B1},
-    {BPF_Fs22050_Fc90_A0,                /* 22kS/s coefficients */
-     -BPF_Fs22050_Fc90_B2,
-     -BPF_Fs22050_Fc90_B1},
-    {BPF_Fs24000_Fc90_A0,                /* 24kS/s coefficients */
-     -BPF_Fs24000_Fc90_B2,
-     -BPF_Fs24000_Fc90_B1},
-    {BPF_Fs32000_Fc90_A0,                /* 32kS/s coefficients */
-     -BPF_Fs32000_Fc90_B2,
-     -BPF_Fs32000_Fc90_B1},
-    {BPF_Fs44100_Fc90_A0,                /* 44kS/s coefficients */
-     -BPF_Fs44100_Fc90_B2,
-     -BPF_Fs44100_Fc90_B1},
-    {BPF_Fs48000_Fc90_A0,                /* 48kS/s coefficients */
-     -BPF_Fs48000_Fc90_B2,
-     -BPF_Fs48000_Fc90_B1}
-    ,
-    {BPF_Fs88200_Fc90_A0,                /* 88kS/s coefficients */
-     -BPF_Fs88200_Fc90_B2,
-     -BPF_Fs88200_Fc90_B1},
-    {BPF_Fs96000_Fc90_A0,                /* 96kS/s coefficients */
-     -BPF_Fs96000_Fc90_B2,
-     -BPF_Fs96000_Fc90_B1},
-    {BPF_Fs176400_Fc90_A0,                /* 176kS/s coefficients */
-     -BPF_Fs176400_Fc90_B2,
-     -BPF_Fs176400_Fc90_B1},
-    {BPF_Fs192000_Fc90_A0,                /* 192kS/s coefficients */
-     -BPF_Fs192000_Fc90_B2,
-     -BPF_Fs192000_Fc90_B1}
+        /* Coefficients for 90Hz centre frequency */
+        {BPF_Fs8000_Fc90_A0, /* 8kS/s coefficients */
+         -BPF_Fs8000_Fc90_B2, -BPF_Fs8000_Fc90_B1},
+        {BPF_Fs11025_Fc90_A0, /* 11kS/s coefficients */
+         -BPF_Fs11025_Fc90_B2, -BPF_Fs11025_Fc90_B1},
+        {BPF_Fs12000_Fc90_A0, /* 12kS/s coefficients */
+         -BPF_Fs12000_Fc90_B2, -BPF_Fs12000_Fc90_B1},
+        {BPF_Fs16000_Fc90_A0, /* 16kS/s coefficients */
+         -BPF_Fs16000_Fc90_B2, -BPF_Fs16000_Fc90_B1},
+        {BPF_Fs22050_Fc90_A0, /* 22kS/s coefficients */
+         -BPF_Fs22050_Fc90_B2, -BPF_Fs22050_Fc90_B1},
+        {BPF_Fs24000_Fc90_A0, /* 24kS/s coefficients */
+         -BPF_Fs24000_Fc90_B2, -BPF_Fs24000_Fc90_B1},
+        {BPF_Fs32000_Fc90_A0, /* 32kS/s coefficients */
+         -BPF_Fs32000_Fc90_B2, -BPF_Fs32000_Fc90_B1},
+        {BPF_Fs44100_Fc90_A0, /* 44kS/s coefficients */
+         -BPF_Fs44100_Fc90_B2, -BPF_Fs44100_Fc90_B1},
+        {BPF_Fs48000_Fc90_A0, /* 48kS/s coefficients */
+         -BPF_Fs48000_Fc90_B2, -BPF_Fs48000_Fc90_B1},
+        {BPF_Fs88200_Fc90_A0, /* 88kS/s coefficients */
+         -BPF_Fs88200_Fc90_B2, -BPF_Fs88200_Fc90_B1},
+        {BPF_Fs96000_Fc90_A0, /* 96kS/s coefficients */
+         -BPF_Fs96000_Fc90_B2, -BPF_Fs96000_Fc90_B1},
+        {BPF_Fs176400_Fc90_A0, /* 176kS/s coefficients */
+         -BPF_Fs176400_Fc90_B2, -BPF_Fs176400_Fc90_B1},
+        {BPF_Fs192000_Fc90_A0, /* 192kS/s coefficients */
+         -BPF_Fs192000_Fc90_B2, -BPF_Fs192000_Fc90_B1}
 
 };
 
@@ -487,77 +278,34 @@
 
 /* Attack time (signal too large) */
 const LVM_FLOAT LVDBE_AGC_ATTACK_Table[] = {
-    AGC_ATTACK_Fs8000,
-    AGC_ATTACK_Fs11025,
-    AGC_ATTACK_Fs12000,
-    AGC_ATTACK_Fs16000,
-    AGC_ATTACK_Fs22050,
-    AGC_ATTACK_Fs24000,
-    AGC_ATTACK_Fs32000,
-    AGC_ATTACK_Fs44100,
-    AGC_ATTACK_Fs48000
-    ,AGC_ATTACK_Fs88200
-    ,AGC_ATTACK_Fs96000
-    ,AGC_ATTACK_Fs176400
-    ,AGC_ATTACK_Fs192000
+        AGC_ATTACK_Fs8000,  AGC_ATTACK_Fs11025, AGC_ATTACK_Fs12000, AGC_ATTACK_Fs16000,
+        AGC_ATTACK_Fs22050, AGC_ATTACK_Fs24000, AGC_ATTACK_Fs32000, AGC_ATTACK_Fs44100,
+        AGC_ATTACK_Fs48000, AGC_ATTACK_Fs88200, AGC_ATTACK_Fs96000, AGC_ATTACK_Fs176400,
+        AGC_ATTACK_Fs192000
 
 };
 
 /* Decay time (signal too small) */
-const LVM_FLOAT LVDBE_AGC_DECAY_Table[] = {
-    AGC_DECAY_Fs8000,
-    AGC_DECAY_Fs11025,
-    AGC_DECAY_Fs12000,
-    AGC_DECAY_Fs16000,
-    AGC_DECAY_Fs22050,
-    AGC_DECAY_Fs24000,
-    AGC_DECAY_Fs32000,
-    AGC_DECAY_Fs44100,
-    AGC_DECAY_Fs48000
-    ,AGC_DECAY_Fs88200
-    ,AGC_DECAY_FS96000
-    ,AGC_DECAY_Fs176400
-    ,AGC_DECAY_FS192000
+const LVM_FLOAT LVDBE_AGC_DECAY_Table[] = {AGC_DECAY_Fs8000,  AGC_DECAY_Fs11025, AGC_DECAY_Fs12000,
+                                           AGC_DECAY_Fs16000, AGC_DECAY_Fs22050, AGC_DECAY_Fs24000,
+                                           AGC_DECAY_Fs32000, AGC_DECAY_Fs44100, AGC_DECAY_Fs48000,
+                                           AGC_DECAY_Fs88200, AGC_DECAY_FS96000, AGC_DECAY_Fs176400,
+                                           AGC_DECAY_FS192000
 
 };
 
 /* Gain for use without the high pass filter */
 const LVM_FLOAT LVDBE_AGC_GAIN_Table[] = {
-    AGC_GAIN_0dB,
-    AGC_GAIN_1dB,
-    AGC_GAIN_2dB,
-    AGC_GAIN_3dB,
-    AGC_GAIN_4dB,
-    AGC_GAIN_5dB,
-    AGC_GAIN_6dB,
-    AGC_GAIN_7dB,
-    AGC_GAIN_8dB,
-    AGC_GAIN_9dB,
-    AGC_GAIN_10dB,
-    AGC_GAIN_11dB,
-    AGC_GAIN_12dB,
-    AGC_GAIN_13dB,
-    AGC_GAIN_14dB,
-    AGC_GAIN_15dB};
+        AGC_GAIN_0dB,  AGC_GAIN_1dB,  AGC_GAIN_2dB,  AGC_GAIN_3dB, AGC_GAIN_4dB,  AGC_GAIN_5dB,
+        AGC_GAIN_6dB,  AGC_GAIN_7dB,  AGC_GAIN_8dB,  AGC_GAIN_9dB, AGC_GAIN_10dB, AGC_GAIN_11dB,
+        AGC_GAIN_12dB, AGC_GAIN_13dB, AGC_GAIN_14dB, AGC_GAIN_15dB};
 
 /* Gain for use with the high pass filter */
 const LVM_FLOAT LVDBE_AGC_HPFGAIN_Table[] = {
-    AGC_HPFGAIN_0dB,
-    AGC_HPFGAIN_1dB,
-    AGC_HPFGAIN_2dB,
-    AGC_HPFGAIN_3dB,
-    AGC_HPFGAIN_4dB,
-    AGC_HPFGAIN_5dB,
-    AGC_HPFGAIN_6dB,
-    AGC_HPFGAIN_7dB,
-    AGC_HPFGAIN_8dB,
-    AGC_HPFGAIN_9dB,
-    AGC_HPFGAIN_10dB,
-    AGC_HPFGAIN_11dB,
-    AGC_HPFGAIN_12dB,
-    AGC_HPFGAIN_13dB,
-    AGC_HPFGAIN_14dB,
-    AGC_HPFGAIN_15dB};
+        AGC_HPFGAIN_0dB,  AGC_HPFGAIN_1dB,  AGC_HPFGAIN_2dB,  AGC_HPFGAIN_3dB,
+        AGC_HPFGAIN_4dB,  AGC_HPFGAIN_5dB,  AGC_HPFGAIN_6dB,  AGC_HPFGAIN_7dB,
+        AGC_HPFGAIN_8dB,  AGC_HPFGAIN_9dB,  AGC_HPFGAIN_10dB, AGC_HPFGAIN_11dB,
+        AGC_HPFGAIN_12dB, AGC_HPFGAIN_13dB, AGC_HPFGAIN_14dB, AGC_HPFGAIN_15dB};
 
 /************************************************************************************/
 /*                                                                                  */
@@ -566,45 +314,23 @@
 /************************************************************************************/
 
 /* dB to linear conversion table */
-const LVM_FLOAT LVDBE_VolumeTable[] = {
-    0.500000f,         /* -6dB */
-    0.562341f,         /* -5dB */
-    0.630957f,         /* -4dB */
-    0.707946f,         /* -3dB */
-    0.794328f,         /* -2dB */
-    0.891251f,         /* -1dB */
-    1.000000f};        /*  0dB */
+const LVM_FLOAT LVDBE_VolumeTable[] = {0.500000f,  /* -6dB */
+                                       0.562341f,  /* -5dB */
+                                       0.630957f,  /* -4dB */
+                                       0.707946f,  /* -3dB */
+                                       0.794328f,  /* -2dB */
+                                       0.891251f,  /* -1dB */
+                                       1.000000f}; /*  0dB */
 
 const LVM_FLOAT LVDBE_VolumeTCTable[] = {
-    VOL_TC_Fs8000,
-    VOL_TC_Fs11025,
-    VOL_TC_Fs12000,
-    VOL_TC_Fs16000,
-    VOL_TC_Fs22050,
-    VOL_TC_Fs24000,
-    VOL_TC_Fs32000,
-    VOL_TC_Fs44100,
-    VOL_TC_Fs48000
-    ,VOL_TC_Fs88200
-    ,VOL_TC_Fs96000
-    ,VOL_TC_Fs176400
-    ,VOL_TC_Fs192000
-};
+        VOL_TC_Fs8000,  VOL_TC_Fs11025,  VOL_TC_Fs12000, VOL_TC_Fs16000, VOL_TC_Fs22050,
+        VOL_TC_Fs24000, VOL_TC_Fs32000,  VOL_TC_Fs44100, VOL_TC_Fs48000, VOL_TC_Fs88200,
+        VOL_TC_Fs96000, VOL_TC_Fs176400, VOL_TC_Fs192000};
 
 const LVM_INT16 LVDBE_MixerTCTable[] = {
 
-    MIX_TC_Fs8000,
-    MIX_TC_Fs11025,
-    MIX_TC_Fs12000,
-    MIX_TC_Fs16000,
-    MIX_TC_Fs22050,
-    MIX_TC_Fs24000,
-    MIX_TC_Fs32000,
-    MIX_TC_Fs44100,
-    MIX_TC_Fs48000
-    ,MIX_TC_Fs88200
-    ,MIX_TC_Fs96000
-    ,MIX_TC_Fs176400
-    ,MIX_TC_Fs192000
+        MIX_TC_Fs8000,  MIX_TC_Fs11025,  MIX_TC_Fs12000, MIX_TC_Fs16000, MIX_TC_Fs22050,
+        MIX_TC_Fs24000, MIX_TC_Fs32000,  MIX_TC_Fs44100, MIX_TC_Fs48000, MIX_TC_Fs88200,
+        MIX_TC_Fs96000, MIX_TC_Fs176400, MIX_TC_Fs192000
 
 };
diff --git a/media/libeffects/lvm/lib/Bundle/lib/LVM.h b/media/libeffects/lvm/lib/Bundle/lib/LVM.h
index e4e8450..c90c5cc 100644
--- a/media/libeffects/lvm/lib/Bundle/lib/LVM.h
+++ b/media/libeffects/lvm/lib/Bundle/lib/LVM.h
@@ -67,31 +67,28 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/* Memory table*/
-#define LVM_NR_MEMORY_REGIONS                 4     /* Number of memory regions */
-
 /* Concert Sound effect level presets */
-#define LVM_CS_EFFECT_NONE                    0     /* 0% effect, minimum value */
-#define LVM_CS_EFFECT_LOW                 16384     /* 50% effect */
-#define LVM_CS_EFFECT_MED                 24576     /* 75% effect */
-#define LVM_CS_EFFECT_HIGH                32767     /* 100% effect, maximum value */
+#define LVM_CS_EFFECT_NONE 0     /* 0% effect, minimum value */
+#define LVM_CS_EFFECT_LOW 16384  /* 50% effect */
+#define LVM_CS_EFFECT_MED 24576  /* 75% effect */
+#define LVM_CS_EFFECT_HIGH 32767 /* 100% effect, maximum value */
 
 /* Treble enhancement */
-#define LVM_TE_LOW_MIPS                   32767
+#define LVM_TE_LOW_MIPS 32767
 
 /* Bass enhancement effect level presets */
-#define LVM_BE_0DB                            0     /* 0dB boost, no effect */
-#define LVM_BE_3DB                            3     /* +3dB boost */
-#define LVM_BE_6DB                            6     /* +6dB boost */
-#define LVM_BE_9DB                            9     /* +9dB boost */
-#define LVM_BE_12DB                          12     /* +12dB boost */
-#define LVM_BE_15DB                          15     /* +15dB boost */
+#define LVM_BE_0DB 0   /* 0dB boost, no effect */
+#define LVM_BE_3DB 3   /* +3dB boost */
+#define LVM_BE_6DB 6   /* +6dB boost */
+#define LVM_BE_9DB 9   /* +9dB boost */
+#define LVM_BE_12DB 12 /* +12dB boost */
+#define LVM_BE_15DB 15 /* +15dB boost */
 
 /* N-Band Equalizer */
-#define LVM_EQ_NBANDS                         5    /* Number of bands for equalizer */
+#define LVM_EQ_NBANDS 5 /* Number of bands for equalizer */
 
 /* Headroom management */
-#define LVM_HEADROOM_MAX_NBANDS               5
+#define LVM_HEADROOM_MAX_NBANDS 5
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -100,123 +97,89 @@
 /****************************************************************************************/
 
 /* Instance handle */
-typedef void *LVM_Handle_t;
+typedef void* LVM_Handle_t;
 
 /* Status return values */
-typedef enum
-{
-    LVM_SUCCESS            = 0,                     /* Successful return from a routine */
-    LVM_ALIGNMENTERROR     = 1,                     /* Memory alignment error */
-    LVM_NULLADDRESS        = 2,                     /* NULL allocation address */
-    LVM_OUTOFRANGE         = 3,                     /* Out of range control parameter */
-    LVM_INVALIDNUMSAMPLES  = 4,                     /* Invalid number of samples */
-    LVM_WRONGAUDIOTIME     = 5,                     /* Wrong time value for audio time*/
-    LVM_ALGORITHMDISABLED  = 6,                     /* Algorithm is disabled*/
-    LVM_ALGORITHMPSA       = 7,                     /* Algorithm PSA returns an error */
+typedef enum {
+    LVM_SUCCESS = 0,           /* Successful return from a routine */
+    LVM_ALIGNMENTERROR = 1,    /* Memory alignment error */
+    LVM_NULLADDRESS = 2,       /* NULL allocation address */
+    LVM_OUTOFRANGE = 3,        /* Out of range control parameter */
+    LVM_INVALIDNUMSAMPLES = 4, /* Invalid number of samples */
+    LVM_WRONGAUDIOTIME = 5,    /* Wrong time value for audio time*/
+    LVM_ALGORITHMDISABLED = 6, /* Algorithm is disabled*/
+    LVM_ALGORITHMPSA = 7,      /* Algorithm PSA returns an error */
     LVM_RETURNSTATUS_DUMMY = LVM_MAXENUM
 } LVM_ReturnStatus_en;
 
 /* Buffer Management mode */
-typedef enum
-{
-    LVM_MANAGED_BUFFERS   = 0,
+typedef enum {
+    LVM_MANAGED_BUFFERS = 0,
     LVM_UNMANAGED_BUFFERS = 1,
-    LVM_BUFFERS_DUMMY     = LVM_MAXENUM
+    LVM_BUFFERS_DUMMY = LVM_MAXENUM
 } LVM_BufferMode_en;
 
 /* Output device type */
-typedef enum
-{
-    LVM_HEADPHONES             = 0,
-    LVM_EX_HEADPHONES          = 1,
-    LVM_SPEAKERTYPE_MAX        = LVM_MAXENUM
+typedef enum {
+    LVM_HEADPHONES = 0,
+    LVM_EX_HEADPHONES = 1,
+    LVM_SPEAKERTYPE_MAX = LVM_MAXENUM
 } LVM_OutputDeviceType_en;
 
 /* Virtualizer mode selection*/
-typedef enum
-{
-    LVM_CONCERTSOUND       = 0,
-    LVM_VIRTUALIZERTYPE_DUMMY   = LVM_MAXENUM
+typedef enum {
+    LVM_CONCERTSOUND = 0,
+    LVM_VIRTUALIZERTYPE_DUMMY = LVM_MAXENUM
 } LVM_VirtualizerType_en;
 
 /* N-Band Equaliser operating mode */
-typedef enum
-{
-    LVM_EQNB_OFF   = 0,
-    LVM_EQNB_ON    = 1,
-    LVM_EQNB_DUMMY = LVM_MAXENUM
-} LVM_EQNB_Mode_en;
+typedef enum { LVM_EQNB_OFF = 0, LVM_EQNB_ON = 1, LVM_EQNB_DUMMY = LVM_MAXENUM } LVM_EQNB_Mode_en;
 
 /* Bass Enhancement operating mode */
-typedef enum
-{
-    LVM_BE_OFF   = 0,
-    LVM_BE_ON    = 1,
-    LVM_BE_DUMMY = LVM_MAXENUM
-} LVM_BE_Mode_en;
+typedef enum { LVM_BE_OFF = 0, LVM_BE_ON = 1, LVM_BE_DUMMY = LVM_MAXENUM } LVM_BE_Mode_en;
 
 /* Bass Enhancement centre frequency selection control */
-typedef enum
-{
-    LVM_BE_CENTRE_55Hz  = 0,
-    LVM_BE_CENTRE_66Hz  = 1,
-    LVM_BE_CENTRE_78Hz  = 2,
-    LVM_BE_CENTRE_90Hz  = 3,
+typedef enum {
+    LVM_BE_CENTRE_55Hz = 0,
+    LVM_BE_CENTRE_66Hz = 1,
+    LVM_BE_CENTRE_78Hz = 2,
+    LVM_BE_CENTRE_90Hz = 3,
     LVM_BE_CENTRE_DUMMY = LVM_MAXENUM
 } LVM_BE_CentreFreq_en;
 
 /* Bass Enhancement HPF selection control */
-typedef enum
-{
-    LVM_BE_HPF_OFF   = 0,
-    LVM_BE_HPF_ON    = 1,
+typedef enum {
+    LVM_BE_HPF_OFF = 0,
+    LVM_BE_HPF_ON = 1,
     LVM_BE_HPF_DUMMY = LVM_MAXENUM
 } LVM_BE_FilterSelect_en;
 
 /* Volume Control operating mode */
-typedef enum
-{
-    LVM_VC_OFF   = 0,
-    LVM_VC_ON    = 1,
-    LVM_VC_DUMMY = LVM_MAXENUM
-} LVM_VC_Mode_en;
+typedef enum { LVM_VC_OFF = 0, LVM_VC_ON = 1, LVM_VC_DUMMY = LVM_MAXENUM } LVM_VC_Mode_en;
 
 /* Treble Enhancement operating mode */
-typedef enum
-{
-    LVM_TE_OFF   = 0,
-    LVM_TE_ON    = 1,
-    LVM_TE_DUMMY = LVM_MAXENUM
-} LVM_TE_Mode_en;
+typedef enum { LVM_TE_OFF = 0, LVM_TE_ON = 1, LVM_TE_DUMMY = LVM_MAXENUM } LVM_TE_Mode_en;
 
 /* Headroom management operating mode */
-typedef enum
-{
-    LVM_HEADROOM_OFF   = 0,
-    LVM_HEADROOM_ON    = 1,
+typedef enum {
+    LVM_HEADROOM_OFF = 0,
+    LVM_HEADROOM_ON = 1,
     LVM_Headroom_DUMMY = LVM_MAXENUM
 } LVM_Headroom_Mode_en;
 
-typedef enum
-{
-    LVM_PSA_SPEED_SLOW,                                  /* Peak decaying at slow speed */
-    LVM_PSA_SPEED_MEDIUM,                                /* Peak decaying at medium speed */
-    LVM_PSA_SPEED_FAST,                                  /* Peak decaying at fast speed */
+typedef enum {
+    LVM_PSA_SPEED_SLOW,   /* Peak decaying at slow speed */
+    LVM_PSA_SPEED_MEDIUM, /* Peak decaying at medium speed */
+    LVM_PSA_SPEED_FAST,   /* Peak decaying at fast speed */
     LVM_PSA_SPEED_DUMMY = LVM_MAXENUM
 } LVM_PSA_DecaySpeed_en;
 
-typedef enum
-{
-    LVM_PSA_OFF   = 0,
-    LVM_PSA_ON    = 1,
-    LVM_PSA_DUMMY = LVM_MAXENUM
-} LVM_PSA_Mode_en;
+typedef enum { LVM_PSA_OFF = 0, LVM_PSA_ON = 1, LVM_PSA_DUMMY = LVM_MAXENUM } LVM_PSA_Mode_en;
 
 /* Version information */
-typedef struct
-{
-    LVM_CHAR                    *pVersionNumber;        /* Pointer to the version number in the format X.YY.ZZ */
-    LVM_CHAR                    *pPlatform;             /* Pointer to the library platform type */
+typedef struct {
+    LVM_CHAR* pVersionNumber; /* Pointer to the version number in the format X.YY.ZZ */
+    LVM_CHAR* pPlatform;      /* Pointer to the library platform type */
 } LVM_VersionInfo_st;
 
 /****************************************************************************************/
@@ -225,93 +188,80 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/* Memory table containing the region definitions */
-typedef struct
-{
-    LVM_MemoryRegion_st         Region[LVM_NR_MEMORY_REGIONS];  /* One definition for each region */
-} LVM_MemTab_t;
-
 /* N-Band equaliser band definition */
-typedef struct
-{
-    LVM_INT16                   Gain;                   /* Band gain in dB */
-    LVM_UINT16                  Frequency;              /* Band centre frequency in Hz */
-    LVM_UINT16                  QFactor;                /* Band quality factor (x100) */
+typedef struct {
+    LVM_INT16 Gain;       /* Band gain in dB */
+    LVM_UINT16 Frequency; /* Band centre frequency in Hz */
+    LVM_UINT16 QFactor;   /* Band quality factor (x100) */
 } LVM_EQNB_BandDef_t;
 
 /* Headroom band definition */
-typedef struct
-{
-    LVM_UINT16                  Limit_Low;              /* Low frequency limit of the band in Hertz */
-    LVM_UINT16                  Limit_High;             /* High frequency limit of the band in Hertz */
-    LVM_INT16                   Headroom_Offset;        /* Headroom = biggest band gain - Headroom_Offset */
+typedef struct {
+    LVM_UINT16 Limit_Low;      /* Low frequency limit of the band in Hertz */
+    LVM_UINT16 Limit_High;     /* High frequency limit of the band in Hertz */
+    LVM_INT16 Headroom_Offset; /* Headroom = biggest band gain - Headroom_Offset */
 } LVM_HeadroomBandDef_t;
 
 /* Control Parameter structure */
-typedef struct
-{
+typedef struct {
     /* General parameters */
-    LVM_Mode_en                 OperatingMode;          /* Bundle operating mode On/Bypass */
-    LVM_Fs_en                   SampleRate;             /* Sample rate */
-    LVM_Format_en               SourceFormat;           /* Input data format */
-    LVM_OutputDeviceType_en     SpeakerType;            /* Output device type */
+    LVM_Mode_en OperatingMode;           /* Bundle operating mode On/Bypass */
+    LVM_Fs_en SampleRate;                /* Sample rate */
+    LVM_Format_en SourceFormat;          /* Input data format */
+    LVM_OutputDeviceType_en SpeakerType; /* Output device type */
 
     /* Concert Sound Virtualizer parameters*/
-    LVM_Mode_en                 VirtualizerOperatingMode; /* Virtualizer operating mode On/Off */
-    LVM_VirtualizerType_en      VirtualizerType;          /* Virtualizer type: ConcertSound */
-    LVM_UINT16                  VirtualizerReverbLevel;   /* Virtualizer reverb level in % */
-    LVM_INT16                   CS_EffectLevel;           /* Concert Sound effect level */
+    LVM_Mode_en VirtualizerOperatingMode;   /* Virtualizer operating mode On/Off */
+    LVM_VirtualizerType_en VirtualizerType; /* Virtualizer type: ConcertSound */
+    LVM_UINT16 VirtualizerReverbLevel;      /* Virtualizer reverb level in % */
+    LVM_INT16 CS_EffectLevel;               /* Concert Sound effect level */
 
     /* N-Band Equaliser parameters */
-    LVM_EQNB_Mode_en            EQNB_OperatingMode;     /* N-Band Equaliser operating mode */
-    LVM_UINT16                  EQNB_NBands;            /* Number of bands */
-    LVM_EQNB_BandDef_t          *pEQNB_BandDefinition;  /* Pointer to equaliser definitions */
+    LVM_EQNB_Mode_en EQNB_OperatingMode;      /* N-Band Equaliser operating mode */
+    LVM_UINT16 EQNB_NBands;                   /* Number of bands */
+    LVM_EQNB_BandDef_t* pEQNB_BandDefinition; /* Pointer to equaliser definitions */
 
     /* Bass Enhancement parameters */
-    LVM_BE_Mode_en              BE_OperatingMode;       /* Bass Enhancement operating mode */
-    LVM_INT16                   BE_EffectLevel;         /* Bass Enhancement effect level */
-    LVM_BE_CentreFreq_en        BE_CentreFreq;          /* Bass Enhancement centre frequency */
-    LVM_BE_FilterSelect_en      BE_HPF;                 /* Bass Enhancement high pass filter selector */
+    LVM_BE_Mode_en BE_OperatingMode;    /* Bass Enhancement operating mode */
+    LVM_INT16 BE_EffectLevel;           /* Bass Enhancement effect level */
+    LVM_BE_CentreFreq_en BE_CentreFreq; /* Bass Enhancement centre frequency */
+    LVM_BE_FilterSelect_en BE_HPF;      /* Bass Enhancement high pass filter selector */
 
     /* Volume Control parameters */
-    LVM_INT16                   VC_EffectLevel;         /* Volume Control setting in dBs */
-    LVM_INT16                   VC_Balance;             /* Left Right Balance control in dB (-96 to 96 dB), -ve values reduce
-                                                           Right channel while +ve value reduces Left channel*/
+    LVM_INT16 VC_EffectLevel; /* Volume Control setting in dBs */
+    LVM_INT16 VC_Balance;     /* Left Right Balance control in dB (-96 to 96 dB), -ve values reduce
+                                 Right channel while +ve value reduces Left channel*/
 
     /* Treble Enhancement parameters */
-    LVM_TE_Mode_en              TE_OperatingMode;       /* Treble Enhancement On/Off */
-    LVM_INT16                   TE_EffectLevel;         /* Treble Enhancement gain dBs */
+    LVM_TE_Mode_en TE_OperatingMode; /* Treble Enhancement On/Off */
+    LVM_INT16 TE_EffectLevel;        /* Treble Enhancement gain dBs */
 
     /* Spectrum Analyzer parameters Control */
-    LVM_PSA_Mode_en             PSA_Enable;
-    LVM_PSA_DecaySpeed_en       PSA_PeakDecayRate;      /* Peak value decay rate*/
-#ifdef SUPPORT_MC
-    LVM_INT32                   NrChannels;
-    LVM_INT32                   ChMask;
-#endif
+    LVM_PSA_Mode_en PSA_Enable;
+    LVM_PSA_DecaySpeed_en PSA_PeakDecayRate; /* Peak value decay rate*/
+    LVM_INT32 NrChannels;
+    LVM_INT32 ChMask;
 
 } LVM_ControlParams_t;
 
 /* Instance Parameter structure */
-typedef struct
-{
+typedef struct {
     /* General */
-    LVM_BufferMode_en           BufferMode;             /* Buffer management mode */
-    LVM_UINT16                  MaxBlockSize;           /* Maximum processing block size */
+    LVM_BufferMode_en BufferMode; /* Buffer management mode */
+    LVM_UINT16 MaxBlockSize;      /* Maximum processing block size */
 
     /* N-Band Equaliser */
-    LVM_UINT16                  EQNB_NumBands;          /* Maximum number of equaliser bands */
+    LVM_UINT16 EQNB_NumBands; /* Maximum number of equaliser bands */
 
     /* PSA */
-    LVM_PSA_Mode_en             PSA_Included;            /* Controls the instance memory allocation for PSA: ON/OFF */
+    LVM_PSA_Mode_en PSA_Included; /* Controls the instance memory allocation for PSA: ON/OFF */
 } LVM_InstParams_t;
 
 /* Headroom management parameter structure */
-typedef struct
-{
-    LVM_Headroom_Mode_en        Headroom_OperatingMode; /* Headroom Control On/Off */
-    LVM_HeadroomBandDef_t       *pHeadroomDefinition;   /* Pointer to headroom bands definition */
-    LVM_UINT16                  NHeadroomBands;         /* Number of headroom bands */
+typedef struct {
+    LVM_Headroom_Mode_en Headroom_OperatingMode; /* Headroom Control On/Off */
+    LVM_HeadroomBandDef_t* pHeadroomDefinition;  /* Pointer to headroom bands definition */
+    LVM_UINT16 NHeadroomBands;                   /* Number of headroom bands */
 
 } LVM_HeadroomParams_t;
 
@@ -339,55 +289,18 @@
 /*  1.  This function may be interrupted by the LVM_Process function                    */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_GetVersionInfo(LVM_VersionInfo_st  *pVersion);
-
-/****************************************************************************************/
-/*                                                                                      */
-/* FUNCTION:                LVM_GetMemoryTable                                          */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*  This function is used for memory allocation and free. It can be called in           */
-/*  two ways:                                                                           */
-/*                                                                                      */
-/*      hInstance = NULL                Returns the memory requirements                 */
-/*      hInstance = Instance handle     Returns the memory requirements and             */
-/*                                      allocated base addresses for the instance       */
-/*                                                                                      */
-/*  When this function is called for memory allocation (hInstance=NULL) the memory      */
-/*  base address pointers are NULL on return.                                           */
-/*                                                                                      */
-/*  When the function is called for free (hInstance = Instance Handle) the memory       */
-/*  table returns the allocated memory and base addresses used during initialisation.   */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance               Instance Handle                                             */
-/*  pMemoryTable            Pointer to an empty memory definition table                 */
-/*  pInstParams             Pointer to the instance parameters                          */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVM_SUCCESS             Succeeded                                                   */
-/*  LVM_NULLADDRESS         When one of pMemoryTable or pInstParams is NULL             */
-/*  LVM_OUTOFRANGE          When any of the Instance parameters are out of range        */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*  1.  This function may be interrupted by the LVM_Process function                    */
-/*                                                                                      */
-/****************************************************************************************/
-LVM_ReturnStatus_en LVM_GetMemoryTable(LVM_Handle_t         hInstance,
-                                       LVM_MemTab_t         *pMemoryTable,
-                                       LVM_InstParams_t     *pInstParams);
+LVM_ReturnStatus_en LVM_GetVersionInfo(LVM_VersionInfo_st* pVersion);
 
 /****************************************************************************************/
 /*                                                                                      */
 /* FUNCTION:                LVM_GetInstanceHandle                                       */
 /*                                                                                      */
 /* DESCRIPTION:                                                                         */
-/*  This function is used to create a bundle instance. It returns the created instance  */
-/*  handle through phInstance. All parameters are set to their default, inactive state. */
+/*  This function is used to create a bundle instance.                                  */
+/*  All parameters are set to their default, inactive state.                            */
 /*                                                                                      */
 /* PARAMETERS:                                                                          */
-/*  phInstance              pointer to the instance handle                              */
-/*  pMemoryTable            Pointer to the memory definition table                      */
+/*  phInstance              Pointer to the instance handle                              */
 /*  pInstParams             Pointer to the instance parameters                          */
 /*                                                                                      */
 /* RETURNS:                                                                             */
@@ -399,9 +312,24 @@
 /*  1. This function must not be interrupted by the LVM_Process function                */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_GetInstanceHandle(LVM_Handle_t        *phInstance,
-                                          LVM_MemTab_t        *pMemoryTable,
-                                          LVM_InstParams_t    *pInstParams);
+LVM_ReturnStatus_en LVM_GetInstanceHandle(LVM_Handle_t* phInstance, LVM_InstParams_t* pInstParams);
+
+/****************************************************************************************/
+/*                                                                                      */
+/* FUNCTION:                LVM_DelInstanceHandle                                       */
+/*                                                                                      */
+/* DESCRIPTION:                                                                         */
+/*  This function is used to create a bundle instance. It returns the created instance  */
+/*  handle through phInstance. All parameters are set to their default, inactive state. */
+/*                                                                                      */
+/* PARAMETERS:                                                                          */
+/*  phInstance              Pointer to the instance handle                              */
+/*                                                                                      */
+/* NOTES:                                                                               */
+/*  1. This function must not be interrupted by the LVM_Process function                */
+/*                                                                                      */
+/****************************************************************************************/
+void LVM_DelInstanceHandle(LVM_Handle_t* phInstance);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -421,7 +349,7 @@
 /*  1. This function must not be interrupted by the LVM_Process function                */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_ClearAudioBuffers(LVM_Handle_t  hInstance);
+LVM_ReturnStatus_en LVM_ClearAudioBuffers(LVM_Handle_t hInstance);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -443,8 +371,7 @@
 /*  1.  This function may be interrupted by the LVM_Process function                    */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_GetControlParameters(LVM_Handle_t           hInstance,
-                                             LVM_ControlParams_t    *pParams);
+LVM_ReturnStatus_en LVM_GetControlParameters(LVM_Handle_t hInstance, LVM_ControlParams_t* pParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -466,8 +393,7 @@
 /*  1.  This function may be interrupted by the LVM_Process function                    */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_SetControlParameters(LVM_Handle_t           hInstance,
-                                             LVM_ControlParams_t    *pParams);
+LVM_ReturnStatus_en LVM_SetControlParameters(LVM_Handle_t hInstance, LVM_ControlParams_t* pParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -499,11 +425,8 @@
 /*      STEREO              the number of sample pairs in the block                     */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_Process(LVM_Handle_t                hInstance,
-                                const LVM_FLOAT             *pInData,
-                                LVM_FLOAT                      *pOutData,
-                                LVM_UINT16                  NumSamples,
-                                LVM_UINT32                  AudioTime);
+LVM_ReturnStatus_en LVM_Process(LVM_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                LVM_FLOAT* pOutData, LVM_UINT16 NumSamples, LVM_UINT32 AudioTime);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -524,8 +447,8 @@
 /*  1.  This function may be interrupted by the LVM_Process function                    */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_SetHeadroomParams(  LVM_Handle_t            hInstance,
-                                            LVM_HeadroomParams_t    *pHeadroomParams);
+LVM_ReturnStatus_en LVM_SetHeadroomParams(LVM_Handle_t hInstance,
+                                          LVM_HeadroomParams_t* pHeadroomParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -546,8 +469,8 @@
 /*  1.  This function may be interrupted by the LVM_Process function                    */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_GetHeadroomParams(  LVM_Handle_t            hInstance,
-                                            LVM_HeadroomParams_t    *pHeadroomParams);
+LVM_ReturnStatus_en LVM_GetHeadroomParams(LVM_Handle_t hInstance,
+                                          LVM_HeadroomParams_t* pHeadroomParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -574,10 +497,8 @@
 /*  1. This function may be interrupted by the LVM_Process function                     */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_GetSpectrum( LVM_Handle_t            hInstance,
-                                     LVM_UINT8               *pCurrentPeaks,
-                                     LVM_UINT8               *pPastPeaks,
-                                     LVM_INT32               AudioTime);
+LVM_ReturnStatus_en LVM_GetSpectrum(LVM_Handle_t hInstance, LVM_UINT8* pCurrentPeaks,
+                                    LVM_UINT8* pPastPeaks, LVM_INT32 AudioTime);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -599,8 +520,6 @@
 /*  1. This function may be interrupted by the LVM_Process function                     */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_SetVolumeNoSmoothing( LVM_Handle_t           hInstance,
-                                              LVM_ControlParams_t    *pParams);
+LVM_ReturnStatus_en LVM_SetVolumeNoSmoothing(LVM_Handle_t hInstance, LVM_ControlParams_t* pParams);
 
-#endif      /* __LVM_H__ */
-
+#endif /* __LVM_H__ */
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_API_Specials.cpp b/media/libeffects/lvm/lib/Bundle/src/LVM_API_Specials.cpp
index e241cdd..cea964c 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_API_Specials.cpp
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_API_Specials.cpp
@@ -47,69 +47,52 @@
 /*  1. This function may be interrupted by the LVM_Process function                     */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_GetSpectrum(
-                                    LVM_Handle_t            hInstance,
-                                    LVM_UINT8               *pCurrentPeaks,
-                                    LVM_UINT8               *pPastPeaks,
-                                    LVM_INT32               AudioTime
-                                    )
-{
-    LVM_Instance_t           *pInstance   = (LVM_Instance_t  *)hInstance;
+LVM_ReturnStatus_en LVM_GetSpectrum(LVM_Handle_t hInstance, LVM_UINT8* pCurrentPeaks,
+                                    LVM_UINT8* pPastPeaks, LVM_INT32 AudioTime) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
 
-    pLVPSA_Handle_t        *hPSAInstance;
-    LVPSA_RETURN           LVPSA_Status;
+    pLVPSA_Handle_t* hPSAInstance;
+    LVPSA_RETURN LVPSA_Status;
 
-    if(pInstance == LVM_NULL)
-    {
+    if (pInstance == LVM_NULL) {
         return LVM_NULLADDRESS;
     }
 
     /*If PSA is not included at the time of instance creation, return without any processing*/
-    if(pInstance->InstParams.PSA_Included!=LVM_PSA_ON)
-    {
+    if (pInstance->InstParams.PSA_Included != LVM_PSA_ON) {
         return LVM_SUCCESS;
     }
 
-    hPSAInstance = (pLVPSA_Handle_t *)pInstance->hPSAInstance;
+    hPSAInstance = (pLVPSA_Handle_t*)pInstance->hPSAInstance;
 
-    if((pCurrentPeaks == LVM_NULL) ||
-        (pPastPeaks == LVM_NULL))
-    {
+    if ((pCurrentPeaks == LVM_NULL) || (pPastPeaks == LVM_NULL)) {
         return LVM_NULLADDRESS;
     }
 
     /*
      * Update new parameters if necessary
      */
-    if (pInstance->ControlPending == LVM_TRUE)
-    {
+    if (pInstance->ControlPending == LVM_TRUE) {
         LVM_ApplyNewSettings(hInstance);
     }
 
     /* If PSA module is disabled, do nothing */
-    if(pInstance->Params.PSA_Enable==LVM_PSA_OFF)
-    {
+    if (pInstance->Params.PSA_Enable == LVM_PSA_OFF) {
         return LVM_ALGORITHMDISABLED;
     }
 
-    LVPSA_Status = LVPSA_GetSpectrum(hPSAInstance,
-                            (LVPSA_Time) (AudioTime),
-                            (LVM_UINT8*) pCurrentPeaks,
-                            (LVM_UINT8*) pPastPeaks );
+    LVPSA_Status = LVPSA_GetSpectrum(hPSAInstance, (LVPSA_Time)(AudioTime),
+                                     (LVM_UINT8*)pCurrentPeaks, (LVM_UINT8*)pPastPeaks);
 
-    if(LVPSA_Status != LVPSA_OK)
-    {
-        if(LVPSA_Status == LVPSA_ERROR_WRONGTIME)
-        {
-            return (LVM_ReturnStatus_en) LVM_WRONGAUDIOTIME;
-        }
-        else
-        {
-            return (LVM_ReturnStatus_en) LVM_NULLADDRESS;
+    if (LVPSA_Status != LVPSA_OK) {
+        if (LVPSA_Status == LVPSA_ERROR_WRONGTIME) {
+            return (LVM_ReturnStatus_en)LVM_WRONGAUDIOTIME;
+        } else {
+            return (LVM_ReturnStatus_en)LVM_NULLADDRESS;
         }
     }
 
-    return(LVM_SUCCESS);
+    return (LVM_SUCCESS);
 }
 
 /****************************************************************************************/
@@ -132,15 +115,12 @@
 /*  1. This function may be interrupted by the LVM_Process function                     */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_SetVolumeNoSmoothing( LVM_Handle_t           hInstance,
-                                              LVM_ControlParams_t    *pParams)
-{
-    LVM_Instance_t      *pInstance =(LVM_Instance_t  *)hInstance;
+LVM_ReturnStatus_en LVM_SetVolumeNoSmoothing(LVM_Handle_t hInstance, LVM_ControlParams_t* pParams) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
     LVM_ReturnStatus_en Error;
 
     /*Apply new controls*/
-    Error = LVM_SetControlParameters(hInstance,pParams);
+    Error = LVM_SetControlParameters(hInstance, pParams);
     pInstance->NoSmoothVolume = LVM_TRUE;
     return Error;
 }
-
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Buffers.cpp b/media/libeffects/lvm/lib/Bundle/src/LVM_Buffers.cpp
index 3aeddbb..1d913d7 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Buffers.cpp
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Buffers.cpp
@@ -49,109 +49,90 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-void LVM_BufferManagedIn(LVM_Handle_t       hInstance,
-                         const LVM_FLOAT    *pInData,
-                         LVM_FLOAT          **pToProcess,
-                         LVM_FLOAT          **pProcessed,
-                         LVM_UINT16         *pNumSamples)
-{
-
-    LVM_INT16        SampleCount;           /* Number of samples to be processed this call */
-    LVM_INT16        NumSamples;            /* Number of samples in scratch buffer */
-    LVM_FLOAT        *pStart;
-    LVM_Instance_t   *pInstance = (LVM_Instance_t  *)hInstance;
-    LVM_Buffer_t     *pBuffer;
-    LVM_FLOAT        *pDest;
-#ifdef SUPPORT_MC
-    LVM_INT16        NumChannels = pInstance->NrChannels;
-#else
-    LVM_INT16        NumChannels = 2;
-#endif
+void LVM_BufferManagedIn(LVM_Handle_t hInstance, const LVM_FLOAT* pInData, LVM_FLOAT** pToProcess,
+                         LVM_FLOAT** pProcessed, LVM_UINT16* pNumSamples) {
+    LVM_INT16 SampleCount; /* Number of samples to be processed this call */
+    LVM_INT16 NumSamples;  /* Number of samples in scratch buffer */
+    LVM_FLOAT* pStart;
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
+    LVM_Buffer_t* pBuffer;
+    LVM_FLOAT* pDest;
+    LVM_INT16 NumChannels = pInstance->NrChannels;
 
     /*
      * Set the processing address pointers
      */
-    pBuffer     = pInstance->pBufferManagement;
-    pDest       = pBuffer->pScratch;
+    pBuffer = pInstance->pBufferManagement;
+    pDest = pBuffer->pScratch;
     *pToProcess = pBuffer->pScratch;
     *pProcessed = pBuffer->pScratch;
 
     /*
      * Check if it is the first call of a block
      */
-    if (pInstance->SamplesToProcess == 0)
-    {
+    if (pInstance->SamplesToProcess == 0) {
         /*
          * First call for a new block of samples
          */
         pInstance->SamplesToProcess = (LVM_INT16)(*pNumSamples + pBuffer->InDelaySamples);
-        pInstance->pInputSamples    = (LVM_FLOAT *)pInData;
-        pBuffer->BufferState        = LVM_FIRSTCALL;
+        pInstance->pInputSamples = (LVM_FLOAT*)pInData;
+        pBuffer->BufferState = LVM_FIRSTCALL;
     }
-    pStart = pInstance->pInputSamples;                 /* Pointer to the input samples */
-    pBuffer->SamplesToOutput  = 0;                     /* Samples to output is same as
-                                                          number read for inplace processing */
+    pStart = pInstance->pInputSamples; /* Pointer to the input samples */
+    pBuffer->SamplesToOutput = 0;      /* Samples to output is same as
+                                          number read for inplace processing */
 
     /*
      * Calculate the number of samples to process this call and update the buffer state
      */
-    if (pInstance->SamplesToProcess > pInstance->InternalBlockSize)
-    {
+    if (pInstance->SamplesToProcess > pInstance->InternalBlockSize) {
         /*
          * Process the maximum bock size of samples.
          */
         SampleCount = pInstance->InternalBlockSize;
-        NumSamples  = pInstance->InternalBlockSize;
-    }
-    else
-    {
+        NumSamples = pInstance->InternalBlockSize;
+    } else {
         /*
          * Last call for the block, so calculate how many frames and samples to process
-          */
-        LVM_INT16   NumFrames;
+         */
+        LVM_INT16 NumFrames;
 
-        NumSamples  = pInstance->SamplesToProcess;
-        NumFrames    = (LVM_INT16)(NumSamples >> MIN_INTERNAL_BLOCKSHIFT);
+        NumSamples = pInstance->SamplesToProcess;
+        NumFrames = (LVM_INT16)(NumSamples >> MIN_INTERNAL_BLOCKSHIFT);
         SampleCount = (LVM_INT16)(NumFrames << MIN_INTERNAL_BLOCKSHIFT);
 
         /*
          * Update the buffer state
          */
-        if (pBuffer->BufferState == LVM_FIRSTCALL)
-        {
+        if (pBuffer->BufferState == LVM_FIRSTCALL) {
             pBuffer->BufferState = LVM_FIRSTLASTCALL;
-        }
-        else
-        {
+        } else {
             pBuffer->BufferState = LVM_LASTCALL;
         }
     }
-    *pNumSamples = (LVM_UINT16)SampleCount;  /* Set the number of samples to process this call */
+    *pNumSamples = (LVM_UINT16)SampleCount; /* Set the number of samples to process this call */
 
     /*
      * Copy samples from the delay buffer as required
      */
-    if (((pBuffer->BufferState == LVM_FIRSTCALL) ||
-        (pBuffer->BufferState == LVM_FIRSTLASTCALL)) &&
-        (pBuffer->InDelaySamples != 0))
-    {
-        Copy_Float(&pBuffer->InDelayBuffer[0],                             /* Source */
-                   pDest,                                                  /* Destination */
-                   (LVM_INT16)(NumChannels * pBuffer->InDelaySamples));    /* Number of delay \
-                                                                       samples, left and right */
+    if (((pBuffer->BufferState == LVM_FIRSTCALL) || (pBuffer->BufferState == LVM_FIRSTLASTCALL)) &&
+        (pBuffer->InDelaySamples != 0)) {
+        Copy_Float(&pBuffer->InDelayBuffer[0],                          /* Source */
+                   pDest,                                               /* Destination */
+                   (LVM_INT16)(NumChannels * pBuffer->InDelaySamples)); /* Number of delay \
+                                                                    samples, left and right */
         NumSamples = (LVM_INT16)(NumSamples - pBuffer->InDelaySamples); /* Update sample count */
-        pDest += NumChannels * pBuffer->InDelaySamples;      /* Update the destination pointer */
+        pDest += NumChannels * pBuffer->InDelaySamples; /* Update the destination pointer */
     }
 
     /*
      * Copy the rest of the samples for this call from the input buffer
      */
-    if (NumSamples > 0)
-    {
-        Copy_Float(pStart,                                      /* Source */
-                   pDest,                                       /* Destination */
-                   (LVM_INT16)(NumChannels * NumSamples));      /* Number of input samples */
-        pStart += NumChannels * NumSamples;                     /* Update the input pointer */
+    if (NumSamples > 0) {
+        Copy_Float(pStart,                                 /* Source */
+                   pDest,                                  /* Destination */
+                   (LVM_INT16)(NumChannels * NumSamples)); /* Number of input samples */
+        pStart += NumChannels * NumSamples;                /* Update the input pointer */
 
         /*
          * Update the input data pointer and samples to output
@@ -161,33 +142,30 @@
     }
 
     /*
-      * Update the sample count and input pointer
+     * Update the sample count and input pointer
      */
     /* Update the count of samples */
-    pInstance->SamplesToProcess  = (LVM_INT16)(pInstance->SamplesToProcess - SampleCount);
-    pInstance->pInputSamples     = pStart; /* Update input sample pointer */
+    pInstance->SamplesToProcess = (LVM_INT16)(pInstance->SamplesToProcess - SampleCount);
+    pInstance->pInputSamples = pStart; /* Update input sample pointer */
 
     /*
      * Save samples to the delay buffer if any left unprocessed
      */
-    if ((pBuffer->BufferState == LVM_FIRSTLASTCALL) ||
-        (pBuffer->BufferState == LVM_LASTCALL))
-    {
+    if ((pBuffer->BufferState == LVM_FIRSTLASTCALL) || (pBuffer->BufferState == LVM_LASTCALL)) {
         NumSamples = pInstance->SamplesToProcess;
-        pStart     = pBuffer->pScratch;                             /* Start of the buffer */
-        pStart    += NumChannels * SampleCount; /* Offset by the number of processed samples */
-        if (NumSamples != 0)
-        {
-            Copy_Float(pStart,                                         /* Source */
-                       &pBuffer->InDelayBuffer[0],                     /* Destination */
-                       (LVM_INT16)(NumChannels * NumSamples));   /* Number of input samples */
+        pStart = pBuffer->pScratch;          /* Start of the buffer */
+        pStart += NumChannels * SampleCount; /* Offset by the number of processed samples */
+        if (NumSamples != 0) {
+            Copy_Float(pStart,                                 /* Source */
+                       &pBuffer->InDelayBuffer[0],             /* Destination */
+                       (LVM_INT16)(NumChannels * NumSamples)); /* Number of input samples */
         }
 
         /*
          * Update the delay sample count
          */
-        pBuffer->InDelaySamples     = NumSamples;       /* Number of delay sample pairs */
-        pInstance->SamplesToProcess = 0;                            /* All Samples used */
+        pBuffer->InDelaySamples = NumSamples; /* Number of delay sample pairs */
+        pInstance->SamplesToProcess = 0;      /* All Samples used */
     }
 }
 
@@ -213,33 +191,25 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-void LVM_BufferUnmanagedIn(LVM_Handle_t     hInstance,
-                           LVM_FLOAT        **pToProcess,
-                           LVM_FLOAT        **pProcessed,
-                           LVM_UINT16       *pNumSamples)
-{
-
-    LVM_Instance_t    *pInstance = (LVM_Instance_t  *)hInstance;
+void LVM_BufferUnmanagedIn(LVM_Handle_t hInstance, LVM_FLOAT** pToProcess, LVM_FLOAT** pProcessed,
+                           LVM_UINT16* pNumSamples) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
 
     /*
      * Check if this is the first call of a block
      */
-    if (pInstance->SamplesToProcess == 0)
-    {
-        pInstance->SamplesToProcess = (LVM_INT16)*pNumSamples;    /* Get the number of samples
-                                                                               on first call */
-        pInstance->pInputSamples    = *pToProcess;                /* Get the I/O pointers */
-        pInstance->pOutputSamples    = *pProcessed;
+    if (pInstance->SamplesToProcess == 0) {
+        pInstance->SamplesToProcess = (LVM_INT16)*pNumSamples; /* Get the number of samples
+                                                                            on first call */
+        pInstance->pInputSamples = *pToProcess;                /* Get the I/O pointers */
+        pInstance->pOutputSamples = *pProcessed;
 
         /*
          * Set te block size to process
          */
-        if (pInstance->SamplesToProcess > pInstance->InternalBlockSize)
-        {
+        if (pInstance->SamplesToProcess > pInstance->InternalBlockSize) {
             *pNumSamples = (LVM_UINT16)pInstance->InternalBlockSize;
-        }
-        else
-        {
+        } else {
             *pNumSamples = (LVM_UINT16)pInstance->SamplesToProcess;
         }
     }
@@ -329,32 +299,17 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-void LVM_BufferIn(LVM_Handle_t      hInstance,
-                  const LVM_FLOAT   *pInData,
-                  LVM_FLOAT         **pToProcess,
-                  LVM_FLOAT         **pProcessed,
-                  LVM_UINT16        *pNumSamples)
-{
-
-    LVM_Instance_t    *pInstance = (LVM_Instance_t  *)hInstance;
+void LVM_BufferIn(LVM_Handle_t hInstance, const LVM_FLOAT* pInData, LVM_FLOAT** pToProcess,
+                  LVM_FLOAT** pProcessed, LVM_UINT16* pNumSamples) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
 
     /*
      * Check which mode, managed or unmanaged
      */
-    if (pInstance->InstParams.BufferMode == LVM_MANAGED_BUFFERS)
-    {
-        LVM_BufferManagedIn(hInstance,
-                            pInData,
-                            pToProcess,
-                            pProcessed,
-                            pNumSamples);
-    }
-    else
-    {
-        LVM_BufferUnmanagedIn(hInstance,
-                              pToProcess,
-                              pProcessed,
-                              pNumSamples);
+    if (pInstance->InstParams.BufferMode == LVM_MANAGED_BUFFERS) {
+        LVM_BufferManagedIn(hInstance, pInData, pToProcess, pProcessed, pNumSamples);
+    } else {
+        LVM_BufferUnmanagedIn(hInstance, pToProcess, pProcessed, pNumSamples);
     }
 }
 /****************************************************************************************/
@@ -377,196 +332,124 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-void LVM_BufferManagedOut(LVM_Handle_t        hInstance,
-                          LVM_FLOAT            *pOutData,
-                          LVM_UINT16        *pNumSamples)
-{
-
-    LVM_Instance_t  *pInstance  = (LVM_Instance_t  *)hInstance;
-    LVM_Buffer_t    *pBuffer    = pInstance->pBufferManagement;
-    LVM_INT16       SampleCount = (LVM_INT16)*pNumSamples;
-    LVM_INT16       NumSamples;
-    LVM_FLOAT       *pStart;
-    LVM_FLOAT       *pDest;
-#ifdef SUPPORT_MC
-    LVM_INT32       NrChannels = pInstance->NrChannels;
+void LVM_BufferManagedOut(LVM_Handle_t hInstance, LVM_FLOAT* pOutData, LVM_UINT16* pNumSamples) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
+    LVM_Buffer_t* pBuffer = pInstance->pBufferManagement;
+    LVM_INT16 SampleCount = (LVM_INT16)*pNumSamples;
+    LVM_INT16 NumSamples;
+    LVM_FLOAT* pStart;
+    LVM_FLOAT* pDest;
+    LVM_INT32 NrChannels = pInstance->NrChannels;
 #define NrFrames NumSamples  // alias for clarity
 #define FrameCount SampleCount
-#endif
 
     /*
      * Set the pointers
      */
     NumSamples = pBuffer->SamplesToOutput;
-    pStart     = pBuffer->pScratch;
+    pStart = pBuffer->pScratch;
 
     /*
      * check if it is the first call of a block
-      */
-    if ((pBuffer->BufferState == LVM_FIRSTCALL) ||
-        (pBuffer->BufferState == LVM_FIRSTLASTCALL))
-    {
+     */
+    if ((pBuffer->BufferState == LVM_FIRSTCALL) || (pBuffer->BufferState == LVM_FIRSTLASTCALL)) {
         /* First call for a new block */
-        pInstance->pOutputSamples = pOutData;                 /* Initialise the destination */
+        pInstance->pOutputSamples = pOutData; /* Initialise the destination */
     }
-    pDest = pInstance->pOutputSamples;                        /* Set the output address */
+    pDest = pInstance->pOutputSamples; /* Set the output address */
 
     /*
      * If the number of samples is non-zero then there are still samples to send to
      * the output buffer
      */
-    if ((NumSamples != 0) &&
-        (pBuffer->OutDelaySamples != 0))
-    {
+    if ((NumSamples != 0) && (pBuffer->OutDelaySamples != 0)) {
         /*
          * Copy the delayed output buffer samples to the output
          */
-        if (pBuffer->OutDelaySamples <= NumSamples)
-        {
+        if (pBuffer->OutDelaySamples <= NumSamples) {
             /*
              * Copy all output delay samples to the output
              */
-#ifdef SUPPORT_MC
-            Copy_Float(&pBuffer->OutDelayBuffer[0],                /* Source */
-                       pDest,                                      /* Destination */
+            Copy_Float(&pBuffer->OutDelayBuffer[0], /* Source */
+                       pDest,                       /* Destination */
                        /* Number of delay samples */
                        (LVM_INT16)(NrChannels * pBuffer->OutDelaySamples));
-#else
-            Copy_Float(&pBuffer->OutDelayBuffer[0],                /* Source */
-                       pDest,                                      /* Destination */
-                       (LVM_INT16)(2 * pBuffer->OutDelaySamples)); /* Number of delay samples */
-#endif
 
             /*
              * Update the pointer and sample counts
              */
-#ifdef SUPPORT_MC
             pDest += NrChannels * pBuffer->OutDelaySamples; /* Output sample pointer */
-#else
-            pDest += 2 * pBuffer->OutDelaySamples; /* Output sample pointer */
-#endif
             NumSamples = (LVM_INT16)(NumSamples - pBuffer->OutDelaySamples); /* Samples left \
                                                                                 to send */
             pBuffer->OutDelaySamples = 0; /* No samples left in the buffer */
-        }
-        else
-        {
+        } else {
             /*
-             * Copy only some of the ouput delay samples to the output
+             * Copy only some of the output delay samples to the output
              */
-#ifdef SUPPORT_MC
-            Copy_Float(&pBuffer->OutDelayBuffer[0],                    /* Source */
-                       pDest,                                          /* Destination */
-                       (LVM_INT16)(NrChannels * NrFrames));       /* Number of delay samples */
-#else
-            Copy_Float(&pBuffer->OutDelayBuffer[0],                    /* Source */
-                       pDest,                                          /* Destination */
-                       (LVM_INT16)(2 * NumSamples));       /* Number of delay samples */
-#endif
+            Copy_Float(&pBuffer->OutDelayBuffer[0],         /* Source */
+                       pDest,                               /* Destination */
+                       (LVM_INT16)(NrChannels * NrFrames)); /* Number of delay samples */
 
             /*
              * Update the pointer and sample counts
              */
-#ifdef SUPPORT_MC
             pDest += NrChannels * NrFrames; /* Output sample pointer */
-#else
-            pDest += 2 * NumSamples; /* Output sample pointer */
-#endif
             /* No samples left in the buffer */
             pBuffer->OutDelaySamples = (LVM_INT16)(pBuffer->OutDelaySamples - NumSamples);
 
             /*
              * Realign the delay buffer data to avoid using circular buffer management
              */
-#ifdef SUPPORT_MC
-            Copy_Float(&pBuffer->OutDelayBuffer[NrChannels * NrFrames],         /* Source */
-                       &pBuffer->OutDelayBuffer[0],                    /* Destination */
+            Copy_Float(&pBuffer->OutDelayBuffer[NrChannels * NrFrames], /* Source */
+                       &pBuffer->OutDelayBuffer[0],                     /* Destination */
                        /* Number of samples to move */
                        (LVM_INT16)(NrChannels * pBuffer->OutDelaySamples));
-#else
-            Copy_Float(&pBuffer->OutDelayBuffer[2 * NumSamples],         /* Source */
-                       &pBuffer->OutDelayBuffer[0],                    /* Destination */
-                       (LVM_INT16)(2 * pBuffer->OutDelaySamples)); /* Number of samples to move */
-#endif
-            NumSamples = 0;                                /* Samples left to send */
+            NumSamples = 0; /* Samples left to send */
         }
     }
 
     /*
      * Copy the processed results to the output
      */
-    if ((NumSamples != 0) &&
-        (SampleCount != 0))
-    {
-        if (SampleCount <= NumSamples)
-        {
+    if ((NumSamples != 0) && (SampleCount != 0)) {
+        if (SampleCount <= NumSamples) {
             /*
              * Copy all processed samples to the output
              */
-#ifdef SUPPORT_MC
-            Copy_Float(pStart,                                      /* Source */
-                       pDest,                                       /* Destination */
+            Copy_Float(pStart,                                /* Source */
+                       pDest,                                 /* Destination */
                        (LVM_INT16)(NrChannels * FrameCount)); /* Number of processed samples */
-#else
-            Copy_Float(pStart,                                      /* Source */
-                       pDest,                                       /* Destination */
-                       (LVM_INT16)(2 * SampleCount)); /* Number of processed samples */
-#endif
             /*
              * Update the pointer and sample counts
              */
-#ifdef SUPPORT_MC
-            pDest      += NrChannels * FrameCount;                 /* Output sample pointer */
-#else
-            pDest      += 2 * SampleCount;                          /* Output sample pointer */
-#endif
-            NumSamples  = (LVM_INT16)(NumSamples - SampleCount);    /* Samples left to send */
-            SampleCount = 0; /* No samples left in the buffer */
-        }
-        else
-        {
+            pDest += NrChannels * FrameCount;                   /* Output sample pointer */
+            NumSamples = (LVM_INT16)(NumSamples - SampleCount); /* Samples left to send */
+            SampleCount = 0;                                    /* No samples left in the buffer */
+        } else {
             /*
              * Copy only some processed samples to the output
              */
-#ifdef SUPPORT_MC
-            Copy_Float(pStart,                                         /* Source */
-                       pDest,                                          /* Destination */
-                       (LVM_INT16)(NrChannels * NrFrames));  /* Number of processed samples */
-#else
-            Copy_Float(pStart,                                         /* Source */
-                       pDest,                                          /* Destination */
-                       (LVM_INT16)(2 * NumSamples));     /* Number of processed samples */
-#endif
+            Copy_Float(pStart,                              /* Source */
+                       pDest,                               /* Destination */
+                       (LVM_INT16)(NrChannels * NrFrames)); /* Number of processed samples */
             /*
              * Update the pointers and sample counts
-               */
-#ifdef SUPPORT_MC
-            pStart      += NrChannels * NrFrames;               /* Processed sample pointer */
-            pDest       += NrChannels * NrFrames;               /* Output sample pointer */
-#else
-            pStart      += 2 * NumSamples;                        /* Processed sample pointer */
-            pDest       += 2 * NumSamples;                        /* Output sample pointer */
-#endif
-            SampleCount  = (LVM_INT16)(SampleCount - NumSamples); /* Processed samples left */
-            NumSamples   = 0;                                     /* Clear the sample count */
+             */
+            pStart += NrChannels * NrFrames;                     /* Processed sample pointer */
+            pDest += NrChannels * NrFrames;                      /* Output sample pointer */
+            SampleCount = (LVM_INT16)(SampleCount - NumSamples); /* Processed samples left */
+            NumSamples = 0;                                      /* Clear the sample count */
         }
     }
 
     /*
      * Copy the remaining processed data to the output delay buffer
      */
-    if (SampleCount != 0)
-    {
-#ifdef SUPPORT_MC
-        Copy_Float(pStart,                                                 /* Source */
+    if (SampleCount != 0) {
+        Copy_Float(pStart, /* Source */
                    /* Destination */
                    &pBuffer->OutDelayBuffer[NrChannels * pBuffer->OutDelaySamples],
-                   (LVM_INT16)(NrChannels * FrameCount));      /* Number of processed samples */
-#else
-        Copy_Float(pStart,                                                 /* Source */
-                   &pBuffer->OutDelayBuffer[2 * pBuffer->OutDelaySamples], /* Destination */
-                   (LVM_INT16)(2 * SampleCount));               /* Number of processed samples */
-#endif
+                   (LVM_INT16)(NrChannels * FrameCount)); /* Number of processed samples */
         /* Update the buffer count */
         pBuffer->OutDelaySamples = (LVM_INT16)(pBuffer->OutDelaySamples + SampleCount);
     }
@@ -574,10 +457,10 @@
     /*
      * pointers, counts and set default buffer processing
      */
-    pBuffer->SamplesToOutput  = NumSamples;                         /* Samples left to send */
-    pInstance->pOutputSamples = pDest;                              /* Output sample pointer */
-    pBuffer->BufferState      = LVM_MAXBLOCKCALL;                   /* Set for the default call \
-                                                                            block size */
+    pBuffer->SamplesToOutput = NumSamples;   /* Samples left to send */
+    pInstance->pOutputSamples = pDest;       /* Output sample pointer */
+    pBuffer->BufferState = LVM_MAXBLOCKCALL; /* Set for the default call \
+                                                     block size */
     /* This will terminate the loop when all samples processed */
     *pNumSamples = (LVM_UINT16)pInstance->SamplesToProcess;
 }
@@ -601,44 +484,27 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-void LVM_BufferUnmanagedOut(LVM_Handle_t        hInstance,
-                            LVM_UINT16          *pNumSamples)
-{
-
-    LVM_Instance_t      *pInstance  = (LVM_Instance_t  *)hInstance;
-#ifdef SUPPORT_MC
-    LVM_INT16           NumChannels = pInstance->NrChannels;
-    if (NumChannels == 1)
-    {
-        /* Mono input is processed as stereo by LVM module */
-        NumChannels = 2;
-    }
+void LVM_BufferUnmanagedOut(LVM_Handle_t hInstance, LVM_UINT16* pNumSamples) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
+    LVM_INT16 NumChannels = pInstance->NrChannels;
 #undef NrFrames
-#define NrFrames (*pNumSamples) // alias for clarity
-#else
-    LVM_INT16           NumChannels = 2;
-#endif
+#define NrFrames (*pNumSamples)  // alias for clarity
 
     /*
      * Update sample counts
      */
-    pInstance->pInputSamples    += (LVM_INT16)(*pNumSamples * NumChannels); /* Update the I/O pointers */
-#ifdef SUPPORT_MC
-    pInstance->pOutputSamples   += (LVM_INT16)(NrFrames * NumChannels);
-#else
-    pInstance->pOutputSamples   += (LVM_INT16)(*pNumSamples * 2);
-#endif
-    pInstance->SamplesToProcess  = (LVM_INT16)(pInstance->SamplesToProcess - *pNumSamples); /* Update the sample count */
+    pInstance->pInputSamples +=
+            (LVM_INT16)(*pNumSamples * NumChannels); /* Update the I/O pointers */
+    pInstance->pOutputSamples += (LVM_INT16)(NrFrames * NumChannels);
+    pInstance->SamplesToProcess =
+            (LVM_INT16)(pInstance->SamplesToProcess - *pNumSamples); /* Update the sample count */
 
     /*
      * Set te block size to process
      */
-    if (pInstance->SamplesToProcess > pInstance->InternalBlockSize)
-    {
+    if (pInstance->SamplesToProcess > pInstance->InternalBlockSize) {
         *pNumSamples = (LVM_UINT16)pInstance->InternalBlockSize;
-    }
-    else
-    {
+    } else {
         *pNumSamples = (LVM_UINT16)pInstance->SamplesToProcess;
     }
 }
@@ -698,25 +564,15 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-void LVM_BufferOut(LVM_Handle_t     hInstance,
-                   LVM_FLOAT        *pOutData,
-                   LVM_UINT16       *pNumSamples)
-{
-
-    LVM_Instance_t    *pInstance  = (LVM_Instance_t  *)hInstance;
+void LVM_BufferOut(LVM_Handle_t hInstance, LVM_FLOAT* pOutData, LVM_UINT16* pNumSamples) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
 
     /*
      * Check which mode, managed or unmanaged
      */
-    if (pInstance->InstParams.BufferMode == LVM_MANAGED_BUFFERS)
-    {
-        LVM_BufferManagedOut(hInstance,
-                             pOutData,
-                             pNumSamples);
-    }
-    else
-    {
-        LVM_BufferUnmanagedOut(hInstance,
-                               pNumSamples);
+    if (pInstance->InstParams.BufferMode == LVM_MANAGED_BUFFERS) {
+        LVM_BufferManagedOut(hInstance, pOutData, pNumSamples);
+    } else {
+        LVM_BufferUnmanagedOut(hInstance, pNumSamples);
     }
 }
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h b/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
index 812f8e5..c02caa1 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Coeffs.h
@@ -24,832 +24,832 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#define TrebleBoostCorner                                  8000
-#define TrebleBoostMinRate                                    4
-#define TrebleBoostSteps                                     15
+#define TrebleBoostCorner 8000
+#define TrebleBoostMinRate 4
+#define TrebleBoostSteps 15
 
 /* Coefficients for sample rate 22050Hz */
-                                                                    /* Gain =  1.000000 dB */
-#define HPF_Fs22050_Gain1_A0                            1.038434
-#define HPF_Fs22050_Gain1_A1                            0.331599
-#define HPF_Fs22050_Gain1_A2                            0.000000
-#define HPF_Fs22050_Gain1_B1                            0.370033
-#define HPF_Fs22050_Gain1_B2                            0.000000
-                                                                    /* Gain =  2.000000 dB */
-#define HPF_Fs22050_Gain2_A0                            1.081557
-#define HPF_Fs22050_Gain2_A1                            0.288475
-#define HPF_Fs22050_Gain2_A2                            0.000000
-#define HPF_Fs22050_Gain2_B1                            0.370033
-#define HPF_Fs22050_Gain2_B2                            0.000000
-                                                                    /* Gain =  3.000000 dB */
-#define HPF_Fs22050_Gain3_A0                            1.129943
-#define HPF_Fs22050_Gain3_A1                            0.240090
-#define HPF_Fs22050_Gain3_A2                            0.000000
-#define HPF_Fs22050_Gain3_B1                            0.370033
-#define HPF_Fs22050_Gain3_B2                            0.000000
-                                                                    /* Gain =  4.000000 dB */
-#define HPF_Fs22050_Gain4_A0                            1.184232
-#define HPF_Fs22050_Gain4_A1                            0.185801
-#define HPF_Fs22050_Gain4_A2                            0.000000
-#define HPF_Fs22050_Gain4_B1                            0.370033
-#define HPF_Fs22050_Gain4_B2                            0.000000
-                                                                    /* Gain =  5.000000 dB */
-#define HPF_Fs22050_Gain5_A0                            1.245145
-#define HPF_Fs22050_Gain5_A1                            0.124887
-#define HPF_Fs22050_Gain5_A2                            0.000000
-#define HPF_Fs22050_Gain5_B1                            0.370033
-#define HPF_Fs22050_Gain5_B2                            0.000000
-                                                                    /* Gain =  6.000000 dB */
-#define HPF_Fs22050_Gain6_A0                            1.313491
-#define HPF_Fs22050_Gain6_A1                            0.056541
-#define HPF_Fs22050_Gain6_A2                            0.000000
-#define HPF_Fs22050_Gain6_B1                            0.370033
-#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_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_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_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_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_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_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_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_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_A2                           0.000000
-#define HPF_Fs22050_Gain15_B1                           0.370033
-#define HPF_Fs22050_Gain15_B2                           0.000000
+/* Gain =  1.000000 dB */
+#define HPF_Fs22050_Gain1_A0 1.038434
+#define HPF_Fs22050_Gain1_A1 0.331599
+#define HPF_Fs22050_Gain1_A2 0.000000
+#define HPF_Fs22050_Gain1_B1 0.370033
+#define HPF_Fs22050_Gain1_B2 0.000000
+/* Gain =  2.000000 dB */
+#define HPF_Fs22050_Gain2_A0 1.081557
+#define HPF_Fs22050_Gain2_A1 0.288475
+#define HPF_Fs22050_Gain2_A2 0.000000
+#define HPF_Fs22050_Gain2_B1 0.370033
+#define HPF_Fs22050_Gain2_B2 0.000000
+/* Gain =  3.000000 dB */
+#define HPF_Fs22050_Gain3_A0 1.129943
+#define HPF_Fs22050_Gain3_A1 0.240090
+#define HPF_Fs22050_Gain3_A2 0.000000
+#define HPF_Fs22050_Gain3_B1 0.370033
+#define HPF_Fs22050_Gain3_B2 0.000000
+/* Gain =  4.000000 dB */
+#define HPF_Fs22050_Gain4_A0 1.184232
+#define HPF_Fs22050_Gain4_A1 0.185801
+#define HPF_Fs22050_Gain4_A2 0.000000
+#define HPF_Fs22050_Gain4_B1 0.370033
+#define HPF_Fs22050_Gain4_B2 0.000000
+/* Gain =  5.000000 dB */
+#define HPF_Fs22050_Gain5_A0 1.245145
+#define HPF_Fs22050_Gain5_A1 0.124887
+#define HPF_Fs22050_Gain5_A2 0.000000
+#define HPF_Fs22050_Gain5_B1 0.370033
+#define HPF_Fs22050_Gain5_B2 0.000000
+/* Gain =  6.000000 dB */
+#define HPF_Fs22050_Gain6_A0 1.313491
+#define HPF_Fs22050_Gain6_A1 0.056541
+#define HPF_Fs22050_Gain6_A2 0.000000
+#define HPF_Fs22050_Gain6_B1 0.370033
+#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_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_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_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_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_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_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_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_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_A2 0.000000
+#define HPF_Fs22050_Gain15_B1 0.370033
+#define HPF_Fs22050_Gain15_B2 0.000000
 /* Coefficients for sample rate 24000Hz */
-                                                                    /* Gain =  1.000000 dB */
-#define HPF_Fs24000_Gain1_A0                            1.044662
-#define HPF_Fs24000_Gain1_A1                            0.223287
-#define HPF_Fs24000_Gain1_A2                            0.000000
-#define HPF_Fs24000_Gain1_B1                            0.267949
-#define HPF_Fs24000_Gain1_B2                            0.000000
-                                                                    /* Gain =  2.000000 dB */
-#define HPF_Fs24000_Gain2_A0                            1.094773
-#define HPF_Fs24000_Gain2_A1                            0.173176
-#define HPF_Fs24000_Gain2_A2                            0.000000
-#define HPF_Fs24000_Gain2_B1                            0.267949
-#define HPF_Fs24000_Gain2_B2                            0.000000
-                                                                    /* Gain =  3.000000 dB */
-#define HPF_Fs24000_Gain3_A0                            1.150999
-#define HPF_Fs24000_Gain3_A1                            0.116950
-#define HPF_Fs24000_Gain3_A2                            0.000000
-#define HPF_Fs24000_Gain3_B1                            0.267949
-#define HPF_Fs24000_Gain3_B2                            0.000000
-                                                                    /* Gain =  4.000000 dB */
-#define HPF_Fs24000_Gain4_A0                            1.214086
-#define HPF_Fs24000_Gain4_A1                            0.053863
-#define HPF_Fs24000_Gain4_A2                            0.000000
-#define HPF_Fs24000_Gain4_B1                            0.267949
-#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_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_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_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_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_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_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_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_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_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_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_A2                           0.000000
-#define HPF_Fs24000_Gain15_B1                           0.267949
-#define HPF_Fs24000_Gain15_B2                           0.000000
+/* Gain =  1.000000 dB */
+#define HPF_Fs24000_Gain1_A0 1.044662
+#define HPF_Fs24000_Gain1_A1 0.223287
+#define HPF_Fs24000_Gain1_A2 0.000000
+#define HPF_Fs24000_Gain1_B1 0.267949
+#define HPF_Fs24000_Gain1_B2 0.000000
+/* Gain =  2.000000 dB */
+#define HPF_Fs24000_Gain2_A0 1.094773
+#define HPF_Fs24000_Gain2_A1 0.173176
+#define HPF_Fs24000_Gain2_A2 0.000000
+#define HPF_Fs24000_Gain2_B1 0.267949
+#define HPF_Fs24000_Gain2_B2 0.000000
+/* Gain =  3.000000 dB */
+#define HPF_Fs24000_Gain3_A0 1.150999
+#define HPF_Fs24000_Gain3_A1 0.116950
+#define HPF_Fs24000_Gain3_A2 0.000000
+#define HPF_Fs24000_Gain3_B1 0.267949
+#define HPF_Fs24000_Gain3_B2 0.000000
+/* Gain =  4.000000 dB */
+#define HPF_Fs24000_Gain4_A0 1.214086
+#define HPF_Fs24000_Gain4_A1 0.053863
+#define HPF_Fs24000_Gain4_A2 0.000000
+#define HPF_Fs24000_Gain4_B1 0.267949
+#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_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_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_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_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_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_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_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_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_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_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_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_A2                            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_A2                             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_A2                             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_A2                            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_A2                            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_A2                             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_A2                             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_A2                             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_A2                             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_A2                            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_A2                           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_A2                          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_A2                           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_A2                           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_A2                          0.000000
-#define HPF_Fs32000_Gain15_B1                          (-0.000000)
-#define HPF_Fs32000_Gain15_B2                          0.000000
+/* Gain =  1.000000 dB */
+#define HPF_Fs32000_Gain1_A0 1.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_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_A2 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_A2 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_A2 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_A2 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_A2 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_A2 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_A2 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_A2 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_A2 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_A2 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_A2 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_A2 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_A2 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_A2 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_A2                            0.000000
-#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_A2                            0.000000
-#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_A2                           0.000000
-#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_A2                            0.000000
-#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_A2                            0.000000
-#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_A2                           0.000000
-#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_A2                           0.000000
-#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_A2                            0.000000
-#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_A2                            0.000000
-#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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                           0.000000
-#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_A2                          0.000000
-#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_A2                          0.000000
-#define HPF_Fs44100_Gain15_B1                          (-0.218894)
-#define HPF_Fs44100_Gain15_B2                          0.000000
+/* Gain =  1.000000 dB */
+#define HPF_Fs44100_Gain1_A0 1.074364
+#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_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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                           0.000000
-#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_A2                           0.000000
-#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_A2                            0.000000
-#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_A2                            0.000000
-#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_A2                           0.000000
-#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_A2                          0.000000
-#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_A2                         0.000000
-#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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                           0.000000
-#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_A2                          0.000000
-#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_A2                         0.000000
-#define HPF_Fs48000_Gain15_B1                         (-0.267949)
-#define HPF_Fs48000_Gain15_B2                         0.000000
+/* Gain =  1.000000 dB */
+#define HPF_Fs48000_Gain1_A0 1.077357
+#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_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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#define HPF_Fs48000_Gain15_B1 (-0.267949)
+#define HPF_Fs48000_Gain15_B2 0.000000
 
 /* Coefficients for sample rate 88200 */
 /* Gain = 1.000000 dB */
-#define HPF_Fs88200_Gain1_A0                          1.094374f
-#define HPF_Fs88200_Gain1_A1                          (-0.641256f)
-#define HPF_Fs88200_Gain1_A2                          0.000000f
-#define HPF_Fs88200_Gain1_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain1_B2                          0.000000f
+#define HPF_Fs88200_Gain1_A0 1.094374f
+#define HPF_Fs88200_Gain1_A1 (-0.641256f)
+#define HPF_Fs88200_Gain1_A2 0.000000f
+#define HPF_Fs88200_Gain1_B1 (-0.546882f)
+#define HPF_Fs88200_Gain1_B2 0.000000f
 /* Gain = 2.000000 dB */
-#define HPF_Fs88200_Gain2_A0                          1.200264f
-#define HPF_Fs88200_Gain2_A1                          (-0.747146f)
-#define HPF_Fs88200_Gain2_A2                          0.000000f
-#define HPF_Fs88200_Gain2_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain2_B2                          0.000000f
+#define HPF_Fs88200_Gain2_A0 1.200264f
+#define HPF_Fs88200_Gain2_A1 (-0.747146f)
+#define HPF_Fs88200_Gain2_A2 0.000000f
+#define HPF_Fs88200_Gain2_B1 (-0.546882f)
+#define HPF_Fs88200_Gain2_B2 0.000000f
 /* Gain = 3.000000 dB */
-#define HPF_Fs88200_Gain3_A0                          1.319074f
-#define HPF_Fs88200_Gain3_A1                          (-0.865956f)
-#define HPF_Fs88200_Gain3_A2                          0.000000f
-#define HPF_Fs88200_Gain3_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain3_B2                          0.000000f
+#define HPF_Fs88200_Gain3_A0 1.319074f
+#define HPF_Fs88200_Gain3_A1 (-0.865956f)
+#define HPF_Fs88200_Gain3_A2 0.000000f
+#define HPF_Fs88200_Gain3_B1 (-0.546882f)
+#define HPF_Fs88200_Gain3_B2 0.000000f
 /* Gain = 4.000000 dB */
-#define HPF_Fs88200_Gain4_A0                          1.452380f
-#define HPF_Fs88200_Gain4_A1                          (-0.999263f)
-#define HPF_Fs88200_Gain4_A2                          0.000000f
-#define HPF_Fs88200_Gain4_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain4_B2                          0.000000f
+#define HPF_Fs88200_Gain4_A0 1.452380f
+#define HPF_Fs88200_Gain4_A1 (-0.999263f)
+#define HPF_Fs88200_Gain4_A2 0.000000f
+#define HPF_Fs88200_Gain4_B1 (-0.546882f)
+#define HPF_Fs88200_Gain4_B2 0.000000f
 /* Gain = 5.000000 dB */
-#define HPF_Fs88200_Gain5_A0                          1.601953f
-#define HPF_Fs88200_Gain5_A1                          (-1.148836f)
-#define HPF_Fs88200_Gain5_A2                          0.000000f
-#define HPF_Fs88200_Gain5_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain5_B2                          0.000000f
+#define HPF_Fs88200_Gain5_A0 1.601953f
+#define HPF_Fs88200_Gain5_A1 (-1.148836f)
+#define HPF_Fs88200_Gain5_A2 0.000000f
+#define HPF_Fs88200_Gain5_B1 (-0.546882f)
+#define HPF_Fs88200_Gain5_B2 0.000000f
 /* Gain = 6.000000 dB */
-#define HPF_Fs88200_Gain6_A0                          1.769777f
-#define HPF_Fs88200_Gain6_A1                          (-1.316659f)
-#define HPF_Fs88200_Gain6_A2                          0.000000f
-#define HPF_Fs88200_Gain6_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain6_B2                          0.000000f
+#define HPF_Fs88200_Gain6_A0 1.769777f
+#define HPF_Fs88200_Gain6_A1 (-1.316659f)
+#define HPF_Fs88200_Gain6_A2 0.000000f
+#define HPF_Fs88200_Gain6_B1 (-0.546882f)
+#define HPF_Fs88200_Gain6_B2 0.000000f
 /* Gain = 7.000000 dB */
-#define HPF_Fs88200_Gain7_A0                          1.958078f
-#define HPF_Fs88200_Gain7_A1                          (-1.504960f)
-#define HPF_Fs88200_Gain7_A2                          0.000000f
-#define HPF_Fs88200_Gain7_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain7_B2                          0.000000f
+#define HPF_Fs88200_Gain7_A0 1.958078f
+#define HPF_Fs88200_Gain7_A1 (-1.504960f)
+#define HPF_Fs88200_Gain7_A2 0.000000f
+#define HPF_Fs88200_Gain7_B1 (-0.546882f)
+#define HPF_Fs88200_Gain7_B2 0.000000f
 /* Gain = 8.000000 dB */
-#define HPF_Fs88200_Gain8_A0                          2.169355f
-#define HPF_Fs88200_Gain8_A1                          (-1.716238f)
-#define HPF_Fs88200_Gain8_A2                          0.000000f
-#define HPF_Fs88200_Gain8_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain8_B2                          0.000000f
+#define HPF_Fs88200_Gain8_A0 2.169355f
+#define HPF_Fs88200_Gain8_A1 (-1.716238f)
+#define HPF_Fs88200_Gain8_A2 0.000000f
+#define HPF_Fs88200_Gain8_B1 (-0.546882f)
+#define HPF_Fs88200_Gain8_B2 0.000000f
 /* Gain = 9.000000 dB */
-#define HPF_Fs88200_Gain9_A0                          2.406412f
-#define HPF_Fs88200_Gain9_A1                          (-1.953295f)
-#define HPF_Fs88200_Gain9_A2                          0.000000f
-#define HPF_Fs88200_Gain9_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain9_B2                          0.000000f
+#define HPF_Fs88200_Gain9_A0 2.406412f
+#define HPF_Fs88200_Gain9_A1 (-1.953295f)
+#define HPF_Fs88200_Gain9_A2 0.000000f
+#define HPF_Fs88200_Gain9_B1 (-0.546882f)
+#define HPF_Fs88200_Gain9_B2 0.000000f
 /* Gain = 10.000000 dB */
-#define HPF_Fs88200_Gain10_A0                          2.672395f
-#define HPF_Fs88200_Gain10_A1                          (-2.219277f)
-#define HPF_Fs88200_Gain10_A2                          0.000000f
-#define HPF_Fs88200_Gain10_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain10_B2                          0.000000f
+#define HPF_Fs88200_Gain10_A0 2.672395f
+#define HPF_Fs88200_Gain10_A1 (-2.219277f)
+#define HPF_Fs88200_Gain10_A2 0.000000f
+#define HPF_Fs88200_Gain10_B1 (-0.546882f)
+#define HPF_Fs88200_Gain10_B2 0.000000f
 /* Gain = 11.000000 dB */
-#define HPF_Fs88200_Gain11_A0                          2.970832f
-#define HPF_Fs88200_Gain11_A1                          (-2.517714f)
-#define HPF_Fs88200_Gain11_A2                          0.000000f
-#define HPF_Fs88200_Gain11_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain11_B2                          0.000000f
+#define HPF_Fs88200_Gain11_A0 2.970832f
+#define HPF_Fs88200_Gain11_A1 (-2.517714f)
+#define HPF_Fs88200_Gain11_A2 0.000000f
+#define HPF_Fs88200_Gain11_B1 (-0.546882f)
+#define HPF_Fs88200_Gain11_B2 0.000000f
 /* Gain = 12.000000 dB */
-#define HPF_Fs88200_Gain12_A0                          3.305684f
-#define HPF_Fs88200_Gain12_A1                          (-2.852566f)
-#define HPF_Fs88200_Gain12_A2                          0.000000f
-#define HPF_Fs88200_Gain12_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain12_B2                          0.000000f
+#define HPF_Fs88200_Gain12_A0 3.305684f
+#define HPF_Fs88200_Gain12_A1 (-2.852566f)
+#define HPF_Fs88200_Gain12_A2 0.000000f
+#define HPF_Fs88200_Gain12_B1 (-0.546882f)
+#define HPF_Fs88200_Gain12_B2 0.000000f
 /* Gain = 13.000000 dB */
-#define HPF_Fs88200_Gain13_A0                          3.681394f
-#define HPF_Fs88200_Gain13_A1                          (-3.228276f)
-#define HPF_Fs88200_Gain13_A2                          0.000000f
-#define HPF_Fs88200_Gain13_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain13_B2                          0.000000f
+#define HPF_Fs88200_Gain13_A0 3.681394f
+#define HPF_Fs88200_Gain13_A1 (-3.228276f)
+#define HPF_Fs88200_Gain13_A2 0.000000f
+#define HPF_Fs88200_Gain13_B1 (-0.546882f)
+#define HPF_Fs88200_Gain13_B2 0.000000f
 /* Gain = 14.000000 dB */
-#define HPF_Fs88200_Gain14_A0                          4.102947f
-#define HPF_Fs88200_Gain14_A1                          (-3.649830f)
-#define HPF_Fs88200_Gain14_A2                          0.000000f
-#define HPF_Fs88200_Gain14_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain14_B2                          0.000000f
+#define HPF_Fs88200_Gain14_A0 4.102947f
+#define HPF_Fs88200_Gain14_A1 (-3.649830f)
+#define HPF_Fs88200_Gain14_A2 0.000000f
+#define HPF_Fs88200_Gain14_B1 (-0.546882f)
+#define HPF_Fs88200_Gain14_B2 0.000000f
 /* Gain = 15.000000 dB */
-#define HPF_Fs88200_Gain15_A0                          4.575938f
-#define HPF_Fs88200_Gain15_A1                          (-4.122820f)
-#define HPF_Fs88200_Gain15_A2                          0.000000f
-#define HPF_Fs88200_Gain15_B1                          (-0.546882f)
-#define HPF_Fs88200_Gain15_B2                          0.000000f
+#define HPF_Fs88200_Gain15_A0 4.575938f
+#define HPF_Fs88200_Gain15_A1 (-4.122820f)
+#define HPF_Fs88200_Gain15_A2 0.000000f
+#define HPF_Fs88200_Gain15_B1 (-0.546882f)
+#define HPF_Fs88200_Gain15_B2 0.000000f
 
 /* 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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                           0.000000
-#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_A2                           0.000000
-#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_A2                            0.000000
-#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_A2                            0.000000
-#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_A2                           0.000000
-#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_A2                          0.000000
-#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_A2                         0.000000
-#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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                           0.000000
-#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_A2                          0.000000
-#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_A2                         0.000000
-#define HPF_Fs96000_Gain15_B1                         (-0.577350)
-#define HPF_Fs96000_Gain15_B2                         0.000000
+/* Gain =  1.000000 dB */
+#define HPF_Fs96000_Gain1_A0 1.096233
+#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_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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#define HPF_Fs96000_Gain15_B1 (-0.577350)
+#define HPF_Fs96000_Gain15_B2 0.000000
 
 /* Coefficients for sample rate 176400 */
 /* Gain = 1.000000 dB */
-#define HPF_Fs176400_Gain1_A0                          1.106711f
-#define HPF_Fs176400_Gain1_A1                          (-0.855807f)
-#define HPF_Fs176400_Gain1_A2                          0.000000f
-#define HPF_Fs176400_Gain1_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain1_B2                          0.000000f
+#define HPF_Fs176400_Gain1_A0 1.106711f
+#define HPF_Fs176400_Gain1_A1 (-0.855807f)
+#define HPF_Fs176400_Gain1_A2 0.000000f
+#define HPF_Fs176400_Gain1_B1 (-0.749096f)
+#define HPF_Fs176400_Gain1_B2 0.000000f
 /* Gain = 2.000000 dB */
-#define HPF_Fs176400_Gain2_A0                          1.226443f
-#define HPF_Fs176400_Gain2_A1                          (-0.975539f)
-#define HPF_Fs176400_Gain2_A2                          0.000000f
-#define HPF_Fs176400_Gain2_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain2_B2                          0.000000f
+#define HPF_Fs176400_Gain2_A0 1.226443f
+#define HPF_Fs176400_Gain2_A1 (-0.975539f)
+#define HPF_Fs176400_Gain2_A2 0.000000f
+#define HPF_Fs176400_Gain2_B1 (-0.749096f)
+#define HPF_Fs176400_Gain2_B2 0.000000f
 /* Gain = 3.000000 dB */
-#define HPF_Fs176400_Gain3_A0                          1.360784f
-#define HPF_Fs176400_Gain3_A1                          (-1.109880f)
-#define HPF_Fs176400_Gain3_A2                          0.000000f
-#define HPF_Fs176400_Gain3_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain3_B2                          0.000000f
+#define HPF_Fs176400_Gain3_A0 1.360784f
+#define HPF_Fs176400_Gain3_A1 (-1.109880f)
+#define HPF_Fs176400_Gain3_A2 0.000000f
+#define HPF_Fs176400_Gain3_B1 (-0.749096f)
+#define HPF_Fs176400_Gain3_B2 0.000000f
 /* Gain = 4.000000 dB */
-#define HPF_Fs176400_Gain4_A0                          1.511517f
-#define HPF_Fs176400_Gain4_A1                          (-1.260613f)
-#define HPF_Fs176400_Gain4_A2                          0.000000f
-#define HPF_Fs176400_Gain4_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain4_B2                          0.000000f
+#define HPF_Fs176400_Gain4_A0 1.511517f
+#define HPF_Fs176400_Gain4_A1 (-1.260613f)
+#define HPF_Fs176400_Gain4_A2 0.000000f
+#define HPF_Fs176400_Gain4_B1 (-0.749096f)
+#define HPF_Fs176400_Gain4_B2 0.000000f
 /* Gain = 5.000000 dB */
-#define HPF_Fs176400_Gain5_A0                          1.680643f
-#define HPF_Fs176400_Gain5_A1                          (-1.429739f)
-#define HPF_Fs176400_Gain5_A2                          0.000000f
-#define HPF_Fs176400_Gain5_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain5_B2                          0.000000f
+#define HPF_Fs176400_Gain5_A0 1.680643f
+#define HPF_Fs176400_Gain5_A1 (-1.429739f)
+#define HPF_Fs176400_Gain5_A2 0.000000f
+#define HPF_Fs176400_Gain5_B1 (-0.749096f)
+#define HPF_Fs176400_Gain5_B2 0.000000f
 /* Gain = 6.000000 dB */
-#define HPF_Fs176400_Gain6_A0                          1.870405f
-#define HPF_Fs176400_Gain6_A1                          (-1.619501f)
-#define HPF_Fs176400_Gain6_A2                          0.000000f
-#define HPF_Fs176400_Gain6_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain6_B2                          0.000000f
+#define HPF_Fs176400_Gain6_A0 1.870405f
+#define HPF_Fs176400_Gain6_A1 (-1.619501f)
+#define HPF_Fs176400_Gain6_A2 0.000000f
+#define HPF_Fs176400_Gain6_B1 (-0.749096f)
+#define HPF_Fs176400_Gain6_B2 0.000000f
 /* Gain = 7.000000 dB */
-#define HPF_Fs176400_Gain7_A0                          2.083321f
-#define HPF_Fs176400_Gain7_A1                          (-1.832417f)
-#define HPF_Fs176400_Gain7_A2                          0.000000f
-#define HPF_Fs176400_Gain7_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain7_B2                          0.000000f
+#define HPF_Fs176400_Gain7_A0 2.083321f
+#define HPF_Fs176400_Gain7_A1 (-1.832417f)
+#define HPF_Fs176400_Gain7_A2 0.000000f
+#define HPF_Fs176400_Gain7_B1 (-0.749096f)
+#define HPF_Fs176400_Gain7_B2 0.000000f
 /* Gain = 8.000000 dB */
-#define HPF_Fs176400_Gain8_A0                          2.322217f
-#define HPF_Fs176400_Gain8_A1                          (-2.071313f)
-#define HPF_Fs176400_Gain8_A2                          0.000000f
-#define HPF_Fs176400_Gain8_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain8_B2                          0.000000f
+#define HPF_Fs176400_Gain8_A0 2.322217f
+#define HPF_Fs176400_Gain8_A1 (-2.071313f)
+#define HPF_Fs176400_Gain8_A2 0.000000f
+#define HPF_Fs176400_Gain8_B1 (-0.749096f)
+#define HPF_Fs176400_Gain8_B2 0.000000f
 /* Gain = 9.000000 dB */
-#define HPF_Fs176400_Gain9_A0                          2.590263f
-#define HPF_Fs176400_Gain9_A1                          (-2.339359f)
-#define HPF_Fs176400_Gain9_A2                          0.000000f
-#define HPF_Fs176400_Gain9_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain9_B2                          0.000000f
+#define HPF_Fs176400_Gain9_A0 2.590263f
+#define HPF_Fs176400_Gain9_A1 (-2.339359f)
+#define HPF_Fs176400_Gain9_A2 0.000000f
+#define HPF_Fs176400_Gain9_B1 (-0.749096f)
+#define HPF_Fs176400_Gain9_B2 0.000000f
 /* Gain = 10.000000 dB */
-#define HPF_Fs176400_Gain10_A0                          2.891016f
-#define HPF_Fs176400_Gain10_A1                          (-2.640112f)
-#define HPF_Fs176400_Gain10_A2                          0.000000f
-#define HPF_Fs176400_Gain10_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain10_B2                          0.000000f
+#define HPF_Fs176400_Gain10_A0 2.891016f
+#define HPF_Fs176400_Gain10_A1 (-2.640112f)
+#define HPF_Fs176400_Gain10_A2 0.000000f
+#define HPF_Fs176400_Gain10_B1 (-0.749096f)
+#define HPF_Fs176400_Gain10_B2 0.000000f
 /* Gain = 11.000000 dB */
-#define HPF_Fs176400_Gain11_A0                          3.228465f
-#define HPF_Fs176400_Gain11_A1                          (-2.977561f)
-#define HPF_Fs176400_Gain11_A2                          0.000000f
-#define HPF_Fs176400_Gain11_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain11_B2                          0.000000f
+#define HPF_Fs176400_Gain11_A0 3.228465f
+#define HPF_Fs176400_Gain11_A1 (-2.977561f)
+#define HPF_Fs176400_Gain11_A2 0.000000f
+#define HPF_Fs176400_Gain11_B1 (-0.749096f)
+#define HPF_Fs176400_Gain11_B2 0.000000f
 /* Gain = 12.000000 dB */
-#define HPF_Fs176400_Gain12_A0                          3.607090f
-#define HPF_Fs176400_Gain12_A1                          (-3.356186f)
-#define HPF_Fs176400_Gain12_A2                          0.000000f
-#define HPF_Fs176400_Gain12_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain12_B2                          0.000000f
+#define HPF_Fs176400_Gain12_A0 3.607090f
+#define HPF_Fs176400_Gain12_A1 (-3.356186f)
+#define HPF_Fs176400_Gain12_A2 0.000000f
+#define HPF_Fs176400_Gain12_B1 (-0.749096f)
+#define HPF_Fs176400_Gain12_B2 0.000000f
 /* Gain = 13.000000 dB */
-#define HPF_Fs176400_Gain13_A0                          4.031914f
-#define HPF_Fs176400_Gain13_A1                          (-3.781010f)
-#define HPF_Fs176400_Gain13_A2                          0.000000f
-#define HPF_Fs176400_Gain13_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain13_B2                          0.000000f
+#define HPF_Fs176400_Gain13_A0 4.031914f
+#define HPF_Fs176400_Gain13_A1 (-3.781010f)
+#define HPF_Fs176400_Gain13_A2 0.000000f
+#define HPF_Fs176400_Gain13_B1 (-0.749096f)
+#define HPF_Fs176400_Gain13_B2 0.000000f
 /* Gain = 14.000000 dB */
-#define HPF_Fs176400_Gain14_A0                          4.508575f
-#define HPF_Fs176400_Gain14_A1                          (-4.257671f)
-#define HPF_Fs176400_Gain14_A2                          0.000000f
-#define HPF_Fs176400_Gain14_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain14_B2                          0.000000f
+#define HPF_Fs176400_Gain14_A0 4.508575f
+#define HPF_Fs176400_Gain14_A1 (-4.257671f)
+#define HPF_Fs176400_Gain14_A2 0.000000f
+#define HPF_Fs176400_Gain14_B1 (-0.749096f)
+#define HPF_Fs176400_Gain14_B2 0.000000f
 /* Gain = 15.000000 dB */
-#define HPF_Fs176400_Gain15_A0                          5.043397f
-#define HPF_Fs176400_Gain15_A1                          (-4.792493f)
-#define HPF_Fs176400_Gain15_A2                          0.000000f
-#define HPF_Fs176400_Gain15_B1                          (-0.749096f)
-#define HPF_Fs176400_Gain15_B2                          0.000000f
+#define HPF_Fs176400_Gain15_A0 5.043397f
+#define HPF_Fs176400_Gain15_A1 (-4.792493f)
+#define HPF_Fs176400_Gain15_A2 0.000000f
+#define HPF_Fs176400_Gain15_B1 (-0.749096f)
+#define HPF_Fs176400_Gain15_B2 0.000000f
 
 /* 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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                           0.000000
-#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_A2                           0.000000
-#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_A2                            0.000000
-#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_A2                            0.000000
-#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_A2                           0.000000
-#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_A2                          0.000000
-#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_A2                         0.000000
-#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_A2                          0.000000
-#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_A2                          0.000000
-#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_A2                           0.000000
-#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_A2                          0.000000
-#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_A2                         0.000000
-#define HPF_Fs192000_Gain15_B1                         (-0.767327)
-#define HPF_Fs192000_Gain15_B2                         0.000000
+/* Gain =  1.000000 dB */
+#define HPF_Fs192000_Gain1_A0 1.107823
+#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_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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#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_A2 0.000000
+#define HPF_Fs192000_Gain15_B1 (-0.767327)
+#define HPF_Fs192000_Gain15_B2 0.000000
 
 #endif
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Control.cpp b/media/libeffects/lvm/lib/Bundle/src/LVM_Control.cpp
index ff2c90a..b2a35d8 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Control.cpp
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Control.cpp
@@ -50,78 +50,62 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVM_ReturnStatus_en LVM_SetControlParameters(LVM_Handle_t           hInstance,
-                                             LVM_ControlParams_t    *pParams)
-{
-    LVM_Instance_t    *pInstance =(LVM_Instance_t  *)hInstance;
+LVM_ReturnStatus_en LVM_SetControlParameters(LVM_Handle_t hInstance, LVM_ControlParams_t* pParams) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
 
-    if ((pParams == LVM_NULL) || (hInstance == LVM_NULL))
-    {
+    if ((pParams == LVM_NULL) || (hInstance == LVM_NULL)) {
         return (LVM_NULLADDRESS);
     }
 
     pInstance->NewParams = *pParams;
 
-    if(
-        /* General parameters */
-        ((pParams->OperatingMode != LVM_MODE_OFF) && (pParams->OperatingMode != LVM_MODE_ON))                                         ||
-    ((pParams->SampleRate != LVM_FS_8000) && (pParams->SampleRate != LVM_FS_11025) && (pParams->SampleRate != LVM_FS_12000)       &&
-     (pParams->SampleRate != LVM_FS_16000) && (pParams->SampleRate != LVM_FS_22050) && (pParams->SampleRate != LVM_FS_24000)      &&
-     (pParams->SampleRate != LVM_FS_32000) && (pParams->SampleRate != LVM_FS_44100) && (pParams->SampleRate != LVM_FS_48000)      &&
-     (pParams->SampleRate != LVM_FS_88200) && (pParams->SampleRate != LVM_FS_96000) &&
-     (pParams->SampleRate != LVM_FS_176400) && (pParams->SampleRate != LVM_FS_192000))      ||
-#ifdef SUPPORT_MC
-        ((pParams->SourceFormat != LVM_STEREO) &&
-         (pParams->SourceFormat != LVM_MONOINSTEREO) &&
-         (pParams->SourceFormat != LVM_MONO) &&
-         (pParams->SourceFormat != LVM_MULTICHANNEL)) ||
-#else
-        ((pParams->SourceFormat != LVM_STEREO) && (pParams->SourceFormat != LVM_MONOINSTEREO) && (pParams->SourceFormat != LVM_MONO)) ||
-#endif
-        (pParams->SpeakerType > LVM_EX_HEADPHONES))
-    {
+    if (
+            /* General parameters */
+            ((pParams->OperatingMode != LVM_MODE_OFF) && (pParams->OperatingMode != LVM_MODE_ON)) ||
+            ((pParams->SampleRate != LVM_FS_8000) && (pParams->SampleRate != LVM_FS_11025) &&
+             (pParams->SampleRate != LVM_FS_12000) && (pParams->SampleRate != LVM_FS_16000) &&
+             (pParams->SampleRate != LVM_FS_22050) && (pParams->SampleRate != LVM_FS_24000) &&
+             (pParams->SampleRate != LVM_FS_32000) && (pParams->SampleRate != LVM_FS_44100) &&
+             (pParams->SampleRate != LVM_FS_48000) && (pParams->SampleRate != LVM_FS_88200) &&
+             (pParams->SampleRate != LVM_FS_96000) && (pParams->SampleRate != LVM_FS_176400) &&
+             (pParams->SampleRate != LVM_FS_192000)) ||
+            ((pParams->SourceFormat != LVM_STEREO) && (pParams->SourceFormat != LVM_MONOINSTEREO) &&
+             (pParams->SourceFormat != LVM_MONO) && (pParams->SourceFormat != LVM_MULTICHANNEL)) ||
+            (pParams->SpeakerType > LVM_EX_HEADPHONES)) {
         return (LVM_OUTOFRANGE);
     }
 
-#ifdef SUPPORT_MC
     pInstance->Params.NrChannels = pParams->NrChannels;
-    pInstance->Params.ChMask     = pParams->ChMask;
-#endif
+    pInstance->Params.ChMask = pParams->ChMask;
     /*
      * Cinema Sound parameters
      */
-    if((pParams->VirtualizerOperatingMode != LVM_MODE_OFF) && (pParams->VirtualizerOperatingMode != LVM_MODE_ON))
-    {
+    if ((pParams->VirtualizerOperatingMode != LVM_MODE_OFF) &&
+        (pParams->VirtualizerOperatingMode != LVM_MODE_ON)) {
         return (LVM_OUTOFRANGE);
     }
 
-    if(pParams->VirtualizerType != LVM_CONCERTSOUND)
-    {
+    if (pParams->VirtualizerType != LVM_CONCERTSOUND) {
         return (LVM_OUTOFRANGE);
     }
 
-    if(pParams->VirtualizerReverbLevel > LVM_VIRTUALIZER_MAX_REVERB_LEVEL)
-    {
+    if (pParams->VirtualizerReverbLevel > LVM_VIRTUALIZER_MAX_REVERB_LEVEL) {
         return (LVM_OUTOFRANGE);
     }
 
-    if(pParams->CS_EffectLevel < LVM_CS_MIN_EFFECT_LEVEL)
-    {
+    if (pParams->CS_EffectLevel < LVM_CS_MIN_EFFECT_LEVEL) {
         return (LVM_OUTOFRANGE);
     }
 
     /*
      * N-Band Equalizer
      */
-    if(pParams->EQNB_NBands > pInstance->InstParams.EQNB_NumBands)
-    {
+    if (pParams->EQNB_NBands > pInstance->InstParams.EQNB_NumBands) {
         return (LVM_OUTOFRANGE);
     }
 
     /* Definition pointer */
-    if ((pParams->pEQNB_BandDefinition == LVM_NULL) &&
-        (pParams->EQNB_NBands != 0))
-    {
+    if ((pParams->pEQNB_BandDefinition == LVM_NULL) && (pParams->EQNB_NBands != 0)) {
         return (LVM_NULLADDRESS);
     }
 
@@ -129,35 +113,31 @@
      * Copy the filter definitions for the Equaliser
      */
     {
-        LVM_INT16           i;
+        LVM_INT16 i;
 
-        if (pParams->EQNB_NBands != 0)
-        {
-            for (i=0; i<pParams->EQNB_NBands; i++)
-            {
+        if (pParams->EQNB_NBands != 0) {
+            for (i = 0; i < pParams->EQNB_NBands; i++) {
                 pInstance->pEQNB_BandDefs[i] = pParams->pEQNB_BandDefinition[i];
             }
             pInstance->NewParams.pEQNB_BandDefinition = pInstance->pEQNB_BandDefs;
         }
     }
-    if( /* N-Band Equaliser parameters */
-        ((pParams->EQNB_OperatingMode != LVM_EQNB_OFF) && (pParams->EQNB_OperatingMode != LVM_EQNB_ON)) ||
-        (pParams->EQNB_NBands > pInstance->InstParams.EQNB_NumBands))
-    {
+    if (/* N-Band Equaliser parameters */
+        ((pParams->EQNB_OperatingMode != LVM_EQNB_OFF) &&
+         (pParams->EQNB_OperatingMode != LVM_EQNB_ON)) ||
+        (pParams->EQNB_NBands > pInstance->InstParams.EQNB_NumBands)) {
         return (LVM_OUTOFRANGE);
     }
     /* Band parameters*/
     {
         LVM_INT16 i;
-        for(i = 0; i < pParams->EQNB_NBands; i++)
-        {
-            if(((pParams->pEQNB_BandDefinition[i].Frequency < LVM_EQNB_MIN_BAND_FREQ)  ||
-                (pParams->pEQNB_BandDefinition[i].Frequency > LVM_EQNB_MAX_BAND_FREQ)) ||
-                ((pParams->pEQNB_BandDefinition[i].Gain     < LVM_EQNB_MIN_BAND_GAIN)  ||
-                (pParams->pEQNB_BandDefinition[i].Gain      > LVM_EQNB_MAX_BAND_GAIN)) ||
-                ((pParams->pEQNB_BandDefinition[i].QFactor  < LVM_EQNB_MIN_QFACTOR)     ||
-                (pParams->pEQNB_BandDefinition[i].QFactor   > LVM_EQNB_MAX_QFACTOR)))
-            {
+        for (i = 0; i < pParams->EQNB_NBands; i++) {
+            if (((pParams->pEQNB_BandDefinition[i].Frequency < LVM_EQNB_MIN_BAND_FREQ) ||
+                 (pParams->pEQNB_BandDefinition[i].Frequency > LVM_EQNB_MAX_BAND_FREQ)) ||
+                ((pParams->pEQNB_BandDefinition[i].Gain < LVM_EQNB_MIN_BAND_GAIN) ||
+                 (pParams->pEQNB_BandDefinition[i].Gain > LVM_EQNB_MAX_BAND_GAIN)) ||
+                ((pParams->pEQNB_BandDefinition[i].QFactor < LVM_EQNB_MIN_QFACTOR) ||
+                 (pParams->pEQNB_BandDefinition[i].QFactor > LVM_EQNB_MAX_QFACTOR))) {
                 return (LVM_OUTOFRANGE);
             }
         }
@@ -166,24 +146,25 @@
     /*
      * Bass Enhancement parameters
      */
-    if(((pParams->BE_OperatingMode != LVM_BE_OFF) && (pParams->BE_OperatingMode != LVM_BE_ON))                      ||
-        ((pParams->BE_EffectLevel < LVM_BE_MIN_EFFECTLEVEL ) || (pParams->BE_EffectLevel > LVM_BE_MAX_EFFECTLEVEL ))||
-        ((pParams->BE_CentreFreq != LVM_BE_CENTRE_55Hz) && (pParams->BE_CentreFreq != LVM_BE_CENTRE_66Hz)           &&
-        (pParams->BE_CentreFreq != LVM_BE_CENTRE_78Hz) && (pParams->BE_CentreFreq != LVM_BE_CENTRE_90Hz))           ||
-        ((pParams->BE_HPF != LVM_BE_HPF_OFF) && (pParams->BE_HPF != LVM_BE_HPF_ON)))
-    {
+    if (((pParams->BE_OperatingMode != LVM_BE_OFF) && (pParams->BE_OperatingMode != LVM_BE_ON)) ||
+        ((pParams->BE_EffectLevel < LVM_BE_MIN_EFFECTLEVEL) ||
+         (pParams->BE_EffectLevel > LVM_BE_MAX_EFFECTLEVEL)) ||
+        ((pParams->BE_CentreFreq != LVM_BE_CENTRE_55Hz) &&
+         (pParams->BE_CentreFreq != LVM_BE_CENTRE_66Hz) &&
+         (pParams->BE_CentreFreq != LVM_BE_CENTRE_78Hz) &&
+         (pParams->BE_CentreFreq != LVM_BE_CENTRE_90Hz)) ||
+        ((pParams->BE_HPF != LVM_BE_HPF_OFF) && (pParams->BE_HPF != LVM_BE_HPF_ON))) {
         return (LVM_OUTOFRANGE);
     }
 
     /*
      * Volume Control parameters
      */
-    if((pParams->VC_EffectLevel < LVM_VC_MIN_EFFECTLEVEL ) || (pParams->VC_EffectLevel > LVM_VC_MAX_EFFECTLEVEL ))
-    {
+    if ((pParams->VC_EffectLevel < LVM_VC_MIN_EFFECTLEVEL) ||
+        (pParams->VC_EffectLevel > LVM_VC_MAX_EFFECTLEVEL)) {
         return (LVM_OUTOFRANGE);
     }
-    if((pParams->VC_Balance < LVM_VC_BALANCE_MIN ) || (pParams->VC_Balance > LVM_VC_BALANCE_MAX ))
-    {
+    if ((pParams->VC_Balance < LVM_VC_BALANCE_MIN) || (pParams->VC_Balance > LVM_VC_BALANCE_MAX)) {
         return (LVM_OUTOFRANGE);
     }
 
@@ -191,22 +172,21 @@
      * PSA parameters
      */
     if (((LVPSA_LevelDetectSpeed_en)pParams->PSA_PeakDecayRate > LVPSA_SPEED_HIGH) ||
-        (pParams->PSA_Enable > LVM_PSA_ON))
-    {
+        (pParams->PSA_Enable > LVM_PSA_ON)) {
         return (LVM_OUTOFRANGE);
     }
 
     /*
-    * Set the flag to indicate there are new parameters to use
-    *
-    * Protect the copy of the new parameters from interrupts to avoid possible problems
-    * with loss control parameters. This problem can occur if this control function is called more
-    * than once before a call to the process function. If the process function interrupts
-    * the copy to NewParams then one frame may have mixed parameters, some old and some new.
-    */
+     * Set the flag to indicate there are new parameters to use
+     *
+     * Protect the copy of the new parameters from interrupts to avoid possible problems
+     * with loss control parameters. This problem can occur if this control function is called more
+     * than once before a call to the process function. If the process function interrupts
+     * the copy to NewParams then one frame may have mixed parameters, some old and some new.
+     */
     pInstance->ControlPending = LVM_TRUE;
 
-    return(LVM_SUCCESS);
+    return (LVM_SUCCESS);
 }
 
 /****************************************************************************************/
@@ -230,16 +210,13 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVM_ReturnStatus_en LVM_GetControlParameters(LVM_Handle_t           hInstance,
-                                             LVM_ControlParams_t    *pParams)
-{
-    LVM_Instance_t    *pInstance =(LVM_Instance_t  *)hInstance;
+LVM_ReturnStatus_en LVM_GetControlParameters(LVM_Handle_t hInstance, LVM_ControlParams_t* pParams) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
 
     /*
      * Check pointer
      */
-    if ((pParams == LVM_NULL) || (hInstance == LVM_NULL))
-    {
+    if ((pParams == LVM_NULL) || (hInstance == LVM_NULL)) {
         return (LVM_NULLADDRESS);
     }
     *pParams = pInstance->NewParams;
@@ -248,17 +225,16 @@
      * Copy the filter definitions for the Equaliser
      */
     {
-        LVM_INT16           i;
+        LVM_INT16 i;
 
         if (pInstance->NewParams.EQNB_NBands != 0)
-        for (i=0; i<pInstance->NewParams.EQNB_NBands; i++)
-        {
-            pInstance->pEQNB_UserDefs[i] = pInstance->pEQNB_BandDefs[i];
-        }
+            for (i = 0; i < pInstance->NewParams.EQNB_NBands; i++) {
+                pInstance->pEQNB_UserDefs[i] = pInstance->pEQNB_BandDefs[i];
+            }
         pParams->pEQNB_BandDefinition = pInstance->pEQNB_UserDefs;
     }
 
-    return(LVM_SUCCESS);
+    return (LVM_SUCCESS);
 }
 
 /****************************************************************************************/
@@ -274,56 +250,42 @@
 /*  pParams                 Pointer to the parameters to use                            */
 /*                                                                                      */
 /****************************************************************************************/
-void LVM_SetTrebleBoost(LVM_Instance_t         *pInstance,
-                        LVM_ControlParams_t    *pParams)
-{
-    extern FO_FLOAT_LShx_Coefs_t  LVM_TrebleBoostCoefs[];
+void LVM_SetTrebleBoost(LVM_Instance_t* pInstance, LVM_ControlParams_t* pParams) {
+    extern FO_FLOAT_LShx_Coefs_t LVM_TrebleBoostCoefs[];
 
-    LVM_INT16               Offset;
-    LVM_INT16               EffectLevel = 0;
+    LVM_INT16 Offset;
+    LVM_INT16 EffectLevel = 0;
 
     /*
      * Load the coefficients
      */
-    if ((pParams->TE_OperatingMode == LVM_TE_ON) &&
-        (pParams->SampleRate >= TrebleBoostMinRate) &&
-        (pParams->OperatingMode == LVM_MODE_ON) &&
-        (pParams->TE_EffectLevel > 0))
-    {
-        if((pParams->TE_EffectLevel == LVM_TE_LOW_MIPS) &&
-            ((pParams->SpeakerType == LVM_HEADPHONES)||
-            (pParams->SpeakerType == LVM_EX_HEADPHONES)))
-        {
+    if ((pParams->TE_OperatingMode == LVM_TE_ON) && (pParams->SampleRate >= TrebleBoostMinRate) &&
+        (pParams->OperatingMode == LVM_MODE_ON) && (pParams->TE_EffectLevel > 0)) {
+        if ((pParams->TE_EffectLevel == LVM_TE_LOW_MIPS) &&
+            ((pParams->SpeakerType == LVM_HEADPHONES) ||
+             (pParams->SpeakerType == LVM_EX_HEADPHONES))) {
             pInstance->TE_Active = LVM_FALSE;
-        }
-        else
-        {
+        } else {
             EffectLevel = pParams->TE_EffectLevel;
             pInstance->TE_Active = LVM_TRUE;
         }
 
-        if(pInstance->TE_Active == LVM_TRUE)
-        {
+        if (pInstance->TE_Active == LVM_TRUE) {
             /*
              * Load the coefficients and enabled the treble boost
              */
-            Offset = (LVM_INT16)(EffectLevel - 1 + TrebleBoostSteps * (pParams->SampleRate - TrebleBoostMinRate));
-            FO_2I_D16F32Css_LShx_TRC_WRA_01_Init(&pInstance->pTE_State->TrebleBoost_State,
-                                            &pInstance->pTE_Taps->TrebleBoost_Taps,
-                                            &LVM_TrebleBoostCoefs[Offset]);
-
+            Offset = (LVM_INT16)(EffectLevel - 1 +
+                                 TrebleBoostSteps * (pParams->SampleRate - TrebleBoostMinRate));
             /*
-             * Clear the taps
+             * Create biquad instance
              */
-            LoadConst_Float((LVM_FLOAT)0,                                     /* Value */
-                            (LVM_FLOAT *)&pInstance->pTE_Taps->TrebleBoost_Taps,  /* Destination.\
-                                                     Cast to void: no dereferencing in function */
-                            (LVM_UINT16)(sizeof(pInstance->pTE_Taps->TrebleBoost_Taps) / \
-                                                        sizeof(LVM_FLOAT))); /* Number of words */
+            std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                    LVM_TrebleBoostCoefs[Offset].A0, LVM_TrebleBoostCoefs[Offset].A1, 0.0,
+                    -(LVM_TrebleBoostCoefs[Offset].B1), 0.0};
+            pInstance->pTEBiquad.reset(
+                    new android::audio_utils::BiquadFilter<LVM_FLOAT>(pParams->NrChannels, coefs));
         }
-    }
-    else
-    {
+    } else {
         /*
          * Disable the treble boost
          */
@@ -345,94 +307,76 @@
 /*  pParams             Initialisation parameters                                   */
 /*                                                                                  */
 /************************************************************************************/
-void    LVM_SetVolume(LVM_Instance_t         *pInstance,
-                      LVM_ControlParams_t    *pParams)
-{
-
-    LVM_UINT16      dBShifts;                                   /* 6dB shifts */
-    LVM_UINT16      dBOffset;                                   /* Table offset */
-    LVM_INT16       Volume = 0;                                 /* Required volume in dBs */
-    LVM_FLOAT        Temp;
+void LVM_SetVolume(LVM_Instance_t* pInstance, LVM_ControlParams_t* pParams) {
+    LVM_UINT16 dBShifts;  /* 6dB shifts */
+    LVM_UINT16 dBOffset;  /* Table offset */
+    LVM_INT16 Volume = 0; /* Required volume in dBs */
+    LVM_FLOAT Temp;
 
     /*
      * Limit the gain to the maximum allowed
      */
-     if  (pParams->VC_EffectLevel > 0)
-     {
-         Volume = 0;
-     }
-     else
-     {
-         Volume = pParams->VC_EffectLevel;
-     }
+    if (pParams->VC_EffectLevel > 0) {
+        Volume = 0;
+    } else {
+        Volume = pParams->VC_EffectLevel;
+    }
 
-     /* Compensate this volume in PSA plot */
-     if(Volume > -60)  /* Limit volume loss to PSA Limits*/
-         pInstance->PSA_GainOffset=(LVM_INT16)(-Volume);/* Loss is compensated by Gain*/
-     else
-         pInstance->PSA_GainOffset=(LVM_INT16)60;/* Loss is compensated by Gain*/
+    /* Compensate this volume in PSA plot */
+    if (Volume > -60)                                     /* Limit volume loss to PSA Limits*/
+        pInstance->PSA_GainOffset = (LVM_INT16)(-Volume); /* Loss is compensated by Gain*/
+    else
+        pInstance->PSA_GainOffset = (LVM_INT16)60; /* Loss is compensated by Gain*/
 
     pInstance->VC_AVLFixedVolume = 0;
 
     /*
      * Set volume control and AVL volumes according to headroom and volume user setting
      */
-    if(pParams->OperatingMode == LVM_MODE_ON)
-    {
+    if (pParams->OperatingMode == LVM_MODE_ON) {
         /* Default Situation with no AVL and no RS */
-        if(pParams->EQNB_OperatingMode == LVM_EQNB_ON)
-        {
-            if(Volume > -pInstance->Headroom)
-                Volume = (LVM_INT16)-pInstance->Headroom;
+        if (pParams->EQNB_OperatingMode == LVM_EQNB_ON) {
+            if (Volume > -pInstance->Headroom) Volume = (LVM_INT16)-pInstance->Headroom;
         }
     }
 
     /*
      * Activate volume control if necessary
      */
-    pInstance->VC_Active   = LVM_TRUE;
-    if (Volume != 0)
-    {
+    pInstance->VC_Active = LVM_TRUE;
+    if (Volume != 0) {
         pInstance->VC_VolumedB = Volume;
-    }
-    else
-    {
+    } else {
         pInstance->VC_VolumedB = 0;
     }
 
     /*
      * Calculate the required gain and shifts
      */
-    dBOffset = (LVM_UINT16)((-Volume) % 6);             /* Get the dBs 0-5 */
-    dBShifts = (LVM_UINT16)(Volume / -6);               /* Get the 6dB shifts */
+    dBOffset = (LVM_UINT16)((-Volume) % 6); /* Get the dBs 0-5 */
+    dBShifts = (LVM_UINT16)(Volume / -6);   /* Get the 6dB shifts */
 
     /*
      * Set the parameters
      */
-    if(dBShifts == 0)
-    {
+    if (dBShifts == 0) {
         LVC_Mixer_SetTarget(&pInstance->VC_Volume.MixerStream[0],
-                                (LVM_FLOAT)LVM_VolumeTable[dBOffset]);
-        }
-    else
-    {
+                            (LVM_FLOAT)LVM_VolumeTable[dBOffset]);
+    } else {
         Temp = LVM_VolumeTable[dBOffset];
-        while(dBShifts) {
+        while (dBShifts) {
             Temp = Temp / 2.0f;
             dBShifts--;
         }
         LVC_Mixer_SetTarget(&pInstance->VC_Volume.MixerStream[0], Temp);
     }
     pInstance->VC_Volume.MixerStream[0].CallbackSet = 1;
-    if(pInstance->NoSmoothVolume == LVM_TRUE)
-    {
+    if (pInstance->NoSmoothVolume == LVM_TRUE) {
         LVC_Mixer_SetTimeConstant(&pInstance->VC_Volume.MixerStream[0], 0,
                                   pInstance->Params.SampleRate, 2);
-    }
-    else
-    {
-        LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_Volume.MixerStream[0],
-                                           LVM_VC_MIXER_TIME, pInstance->Params.SampleRate, 2);
+    } else {
+        LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_Volume.MixerStream[0], LVM_VC_MIXER_TIME,
+                                           pInstance->Params.SampleRate, 2);
     }
 }
 
@@ -453,43 +397,39 @@
 /* NOTES:                                                                           */
 /*                                                                                  */
 /************************************************************************************/
-void    LVM_SetHeadroom(LVM_Instance_t         *pInstance,
-                        LVM_ControlParams_t    *pParams)
-{
-    LVM_INT16   ii, jj;
-    LVM_INT16   Headroom = 0;
-    LVM_INT16   MaxGain = 0;
+void LVM_SetHeadroom(LVM_Instance_t* pInstance, LVM_ControlParams_t* pParams) {
+    LVM_INT16 ii, jj;
+    LVM_INT16 Headroom = 0;
+    LVM_INT16 MaxGain = 0;
 
-    if (((LVEQNB_Mode_en)pParams->EQNB_OperatingMode == LVEQNB_ON)
-           && (pInstance->HeadroomParams.Headroom_OperatingMode == LVM_HEADROOM_ON))
-    {
+    if (((LVEQNB_Mode_en)pParams->EQNB_OperatingMode == LVEQNB_ON) &&
+        (pInstance->HeadroomParams.Headroom_OperatingMode == LVM_HEADROOM_ON)) {
         /* Find typical headroom value */
-        for(jj = 0; jj < pInstance->HeadroomParams.NHeadroomBands; jj++)
-        {
+        for (jj = 0; jj < pInstance->HeadroomParams.NHeadroomBands; jj++) {
             MaxGain = 0;
-            for( ii = 0; ii < pParams->EQNB_NBands; ii++)
-            {
-                if((pParams->pEQNB_BandDefinition[ii].Frequency >= pInstance->HeadroomParams.pHeadroomDefinition[jj].Limit_Low) &&
-                   (pParams->pEQNB_BandDefinition[ii].Frequency <= pInstance->HeadroomParams.pHeadroomDefinition[jj].Limit_High))
-                {
-                    if(pParams->pEQNB_BandDefinition[ii].Gain > MaxGain)
-                    {
+            for (ii = 0; ii < pParams->EQNB_NBands; ii++) {
+                if ((pParams->pEQNB_BandDefinition[ii].Frequency >=
+                     pInstance->HeadroomParams.pHeadroomDefinition[jj].Limit_Low) &&
+                    (pParams->pEQNB_BandDefinition[ii].Frequency <=
+                     pInstance->HeadroomParams.pHeadroomDefinition[jj].Limit_High)) {
+                    if (pParams->pEQNB_BandDefinition[ii].Gain > MaxGain) {
                         MaxGain = pParams->pEQNB_BandDefinition[ii].Gain;
                     }
                 }
             }
 
-            if((MaxGain - pInstance->HeadroomParams.pHeadroomDefinition[jj].Headroom_Offset) > Headroom){
-                Headroom = (LVM_INT16)(MaxGain - pInstance->HeadroomParams.pHeadroomDefinition[jj].Headroom_Offset);
+            if ((MaxGain - pInstance->HeadroomParams.pHeadroomDefinition[jj].Headroom_Offset) >
+                Headroom) {
+                Headroom = (LVM_INT16)(
+                        MaxGain -
+                        pInstance->HeadroomParams.pHeadroomDefinition[jj].Headroom_Offset);
             }
         }
 
         /* Saturate */
-        if(Headroom < 0)
-            Headroom = 0;
+        if (Headroom < 0) Headroom = 0;
     }
-    pInstance->Headroom = (LVM_UINT16)Headroom ;
-
+    pInstance->Headroom = (LVM_UINT16)Headroom;
 }
 
 /****************************************************************************************/
@@ -510,32 +450,26 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVM_ReturnStatus_en LVM_ApplyNewSettings(LVM_Handle_t   hInstance)
-{
-    LVM_Instance_t         *pInstance =(LVM_Instance_t *)hInstance;
-    LVM_ControlParams_t    LocalParams;
-    LVM_INT16              Count = 5;
+LVM_ReturnStatus_en LVM_ApplyNewSettings(LVM_Handle_t hInstance) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
+    LVM_ControlParams_t LocalParams;
+    LVM_INT16 Count = 5;
 
     /*
      * Copy the new parameters but make sure they didn't change while copying
      */
-    do
-    {
+    do {
         pInstance->ControlPending = LVM_FALSE;
         LocalParams = pInstance->NewParams;
         pInstance->HeadroomParams = pInstance->NewHeadroomParams;
         Count--;
-    } while ((pInstance->ControlPending != LVM_FALSE) &&
-             (Count > 0));
+    } while ((pInstance->ControlPending != LVM_FALSE) && (Count > 0));
 
-#ifdef SUPPORT_MC
     pInstance->NrChannels = LocalParams.NrChannels;
     pInstance->ChMask = LocalParams.ChMask;
-#endif
 
     /* Clear all internal data if format change*/
-    if(LocalParams.SourceFormat != pInstance->Params.SourceFormat)
-    {
+    if (LocalParams.SourceFormat != pInstance->Params.SourceFormat) {
         LVM_ClearAudioBuffers(pInstance);
         pInstance->ControlPending = LVM_FALSE;
     }
@@ -547,31 +481,27 @@
         (pInstance->Params.TE_EffectLevel != LocalParams.TE_EffectLevel) ||
         (pInstance->Params.TE_OperatingMode != LocalParams.TE_OperatingMode) ||
         (pInstance->Params.OperatingMode != LocalParams.OperatingMode) ||
-        (pInstance->Params.SpeakerType != LocalParams.SpeakerType))
-    {
-        LVM_SetTrebleBoost(pInstance,
-                           &LocalParams);
+        (pInstance->Params.SpeakerType != LocalParams.SpeakerType)) {
+        LVM_SetTrebleBoost(pInstance, &LocalParams);
     }
 
     /*
      * Update the headroom if required
      */
-        LVM_SetHeadroom(pInstance,                      /* Instance pointer */
-                        &LocalParams);                  /* New parameters */
+    LVM_SetHeadroom(pInstance,     /* Instance pointer */
+                    &LocalParams); /* New parameters */
 
     /*
      * Update the volume if required
      */
     {
-        LVM_SetVolume(pInstance,                      /* Instance pointer */
-                      &LocalParams);                  /* New parameters */
+        LVM_SetVolume(pInstance,     /* Instance pointer */
+                      &LocalParams); /* New parameters */
     }
     /* Apply balance changes*/
-    if(pInstance->Params.VC_Balance != LocalParams.VC_Balance)
-    {
+    if (pInstance->Params.VC_Balance != LocalParams.VC_Balance) {
         /* Configure Mixer module for gradual changes to volume*/
-        if(LocalParams.VC_Balance < 0)
-        {
+        if (LocalParams.VC_Balance < 0) {
             LVM_FLOAT Target_Float;
             /* Drop in right channel volume*/
             Target_Float = LVM_MAXFLOAT;
@@ -583,9 +513,7 @@
             LVC_Mixer_SetTarget(&pInstance->VC_BalanceMix.MixerStream[1], Target_Float);
             LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_BalanceMix.MixerStream[1],
                                                LVM_VC_MIXER_TIME, LocalParams.SampleRate, 1);
-        }
-        else if(LocalParams.VC_Balance >0)
-        {
+        } else if (LocalParams.VC_Balance > 0) {
             LVM_FLOAT Target_Float;
             /* Drop in left channel volume*/
             Target_Float = dB_to_LinFloat((LVM_INT16)((-LocalParams.VC_Balance) << 4));
@@ -597,63 +525,54 @@
             LVC_Mixer_SetTarget(&pInstance->VC_BalanceMix.MixerStream[1], Target_Float);
             LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_BalanceMix.MixerStream[1],
                                                LVM_VC_MIXER_TIME, LocalParams.SampleRate, 1);
-        }
-        else
-        {
+        } else {
             LVM_FLOAT Target_Float;
             /* No drop*/
             Target_Float = LVM_MAXFLOAT;
-            LVC_Mixer_SetTarget(&pInstance->VC_BalanceMix.MixerStream[0],Target_Float);
+            LVC_Mixer_SetTarget(&pInstance->VC_BalanceMix.MixerStream[0], Target_Float);
             LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_BalanceMix.MixerStream[0],
-                                               LVM_VC_MIXER_TIME,LocalParams.SampleRate, 1);
+                                               LVM_VC_MIXER_TIME, LocalParams.SampleRate, 1);
 
-            LVC_Mixer_SetTarget(&pInstance->VC_BalanceMix.MixerStream[1],Target_Float);
+            LVC_Mixer_SetTarget(&pInstance->VC_BalanceMix.MixerStream[1], Target_Float);
             LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_BalanceMix.MixerStream[1],
-                                               LVM_VC_MIXER_TIME,LocalParams.SampleRate, 1);
+                                               LVM_VC_MIXER_TIME, LocalParams.SampleRate, 1);
         }
     }
     /*
      * Update the bass enhancement
      */
     {
-        LVDBE_ReturnStatus_en       DBE_Status;
-        LVDBE_Params_t              DBE_Params;
-        LVDBE_Handle_t              *hDBEInstance = (LVDBE_Handle_t *)pInstance->hDBEInstance;
+        LVDBE_ReturnStatus_en DBE_Status;
+        LVDBE_Params_t DBE_Params;
+        LVDBE_Handle_t* hDBEInstance = (LVDBE_Handle_t*)pInstance->hDBEInstance;
 
         /*
          * Set the new parameters
          */
-        if(LocalParams.OperatingMode == LVM_MODE_OFF)
-        {
+        if (LocalParams.OperatingMode == LVM_MODE_OFF) {
             DBE_Params.OperatingMode = LVDBE_OFF;
+        } else {
+            DBE_Params.OperatingMode = (LVDBE_Mode_en)LocalParams.BE_OperatingMode;
         }
-        else
-        {
-            DBE_Params.OperatingMode    = (LVDBE_Mode_en)LocalParams.BE_OperatingMode;
-        }
-        DBE_Params.SampleRate       = (LVDBE_Fs_en)LocalParams.SampleRate;
-        DBE_Params.EffectLevel      = LocalParams.BE_EffectLevel;
-        DBE_Params.CentreFrequency  = (LVDBE_CentreFreq_en)LocalParams.BE_CentreFreq;
-        DBE_Params.HPFSelect        = (LVDBE_FilterSelect_en)LocalParams.BE_HPF;
-        DBE_Params.HeadroomdB       = 0;
-        DBE_Params.VolumeControl    = LVDBE_VOLUME_OFF;
-        DBE_Params.VolumedB         = 0;
-#ifdef SUPPORT_MC
-        DBE_Params.NrChannels         = LocalParams.NrChannels;
-#endif
+        DBE_Params.SampleRate = (LVDBE_Fs_en)LocalParams.SampleRate;
+        DBE_Params.EffectLevel = LocalParams.BE_EffectLevel;
+        DBE_Params.CentreFrequency = (LVDBE_CentreFreq_en)LocalParams.BE_CentreFreq;
+        DBE_Params.HPFSelect = (LVDBE_FilterSelect_en)LocalParams.BE_HPF;
+        DBE_Params.HeadroomdB = 0;
+        DBE_Params.VolumeControl = LVDBE_VOLUME_OFF;
+        DBE_Params.VolumedB = 0;
+        DBE_Params.NrChannels = LocalParams.NrChannels;
 
         /*
          * Make the changes
          */
-        DBE_Status = LVDBE_Control(hDBEInstance,
-                                   &DBE_Params);
+        DBE_Status = LVDBE_Control(hDBEInstance, &DBE_Params);
 
         /*
          * Quit if the changes were not accepted
          */
-        if (DBE_Status != LVDBE_SUCCESS)
-        {
-            return((LVM_ReturnStatus_en)DBE_Status);
+        if (DBE_Status != LVDBE_SUCCESS) {
+            return ((LVM_ReturnStatus_en)DBE_Status);
         }
 
         /*
@@ -666,168 +585,132 @@
      * Update the N-Band Equaliser
      */
     {
-        LVEQNB_ReturnStatus_en      EQNB_Status;
-        LVEQNB_Params_t             EQNB_Params;
-        LVEQNB_Handle_t             *hEQNBInstance = (LVEQNB_Handle_t *)pInstance->hEQNBInstance;
+        LVEQNB_ReturnStatus_en EQNB_Status;
+        LVEQNB_Params_t EQNB_Params;
+        LVEQNB_Handle_t* hEQNBInstance = (LVEQNB_Handle_t*)pInstance->hEQNBInstance;
 
         /*
          * Set the new parameters
          */
 
-        if(LocalParams.OperatingMode == LVM_MODE_OFF)
-        {
-            EQNB_Params.OperatingMode    = LVEQNB_BYPASS;
-        }
-        else
-        {
-            EQNB_Params.OperatingMode    = (LVEQNB_Mode_en)LocalParams.EQNB_OperatingMode;
+        if (LocalParams.OperatingMode == LVM_MODE_OFF) {
+            EQNB_Params.OperatingMode = LVEQNB_BYPASS;
+        } else {
+            EQNB_Params.OperatingMode = (LVEQNB_Mode_en)LocalParams.EQNB_OperatingMode;
         }
 
-        EQNB_Params.SampleRate       = (LVEQNB_Fs_en)LocalParams.SampleRate;
-        EQNB_Params.NBands           = LocalParams.EQNB_NBands;
-        EQNB_Params.pBandDefinition  = (LVEQNB_BandDef_t *)LocalParams.pEQNB_BandDefinition;
-        if (LocalParams.SourceFormat == LVM_STEREO)    /* Mono format not supported */
+        EQNB_Params.SampleRate = (LVEQNB_Fs_en)LocalParams.SampleRate;
+        EQNB_Params.NBands = LocalParams.EQNB_NBands;
+        EQNB_Params.pBandDefinition = (LVEQNB_BandDef_t*)LocalParams.pEQNB_BandDefinition;
+        if (LocalParams.SourceFormat == LVM_STEREO) /* Mono format not supported */
         {
             EQNB_Params.SourceFormat = LVEQNB_STEREO;
         }
-#ifdef SUPPORT_MC
         /* Note: Currently SourceFormat field of EQNB is not been
          *       used by the module.
          */
-        else if (LocalParams.SourceFormat == LVM_MULTICHANNEL)
-        {
+        else if (LocalParams.SourceFormat == LVM_MULTICHANNEL) {
             EQNB_Params.SourceFormat = LVEQNB_MULTICHANNEL;
+        } else {
+            EQNB_Params.SourceFormat = LVEQNB_MONOINSTEREO; /* Force to Mono-in-Stereo mode */
         }
-#endif
-        else
-        {
-            EQNB_Params.SourceFormat = LVEQNB_MONOINSTEREO;     /* Force to Mono-in-Stereo mode */
-        }
-#ifdef SUPPORT_MC
-        EQNB_Params.NrChannels         = LocalParams.NrChannels;
-#endif
+        EQNB_Params.NrChannels = LocalParams.NrChannels;
 
         /*
          * Set the control flag
          */
         if ((LocalParams.OperatingMode == LVM_MODE_ON) &&
-            (LocalParams.EQNB_OperatingMode == LVM_EQNB_ON))
-        {
+            (LocalParams.EQNB_OperatingMode == LVM_EQNB_ON)) {
             pInstance->EQNB_Active = LVM_TRUE;
-        }
-        else
-        {
+        } else {
             EQNB_Params.OperatingMode = LVEQNB_BYPASS;
         }
 
         /*
          * Make the changes
          */
-        EQNB_Status = LVEQNB_Control(hEQNBInstance,
-                                     &EQNB_Params);
+        EQNB_Status = LVEQNB_Control(hEQNBInstance, &EQNB_Params);
 
         /*
          * Quit if the changes were not accepted
          */
-        if (EQNB_Status != LVEQNB_SUCCESS)
-        {
-            return((LVM_ReturnStatus_en)EQNB_Status);
+        if (EQNB_Status != LVEQNB_SUCCESS) {
+            return ((LVM_ReturnStatus_en)EQNB_Status);
         }
-
     }
 
     /*
      * Update concert sound
      */
     {
-        LVCS_ReturnStatus_en        CS_Status;
-        LVCS_Params_t               CS_Params;
-        LVCS_Handle_t               *hCSInstance = (LVCS_Handle_t *)pInstance->hCSInstance;
-        LVM_Mode_en                 CompressorMode=LVM_MODE_ON;
+        LVCS_ReturnStatus_en CS_Status;
+        LVCS_Params_t CS_Params;
+        LVCS_Handle_t* hCSInstance = (LVCS_Handle_t*)pInstance->hCSInstance;
+        LVM_Mode_en CompressorMode = LVM_MODE_ON;
 
         /*
          * Set the new parameters
          */
-        if(LocalParams.VirtualizerOperatingMode == LVM_MODE_ON)
-        {
-            CS_Params.OperatingMode    = LVCS_ON;
-        }
-        else
-        {
-            CS_Params.OperatingMode    = LVCS_OFF;
+        if (LocalParams.VirtualizerOperatingMode == LVM_MODE_ON) {
+            CS_Params.OperatingMode = LVCS_ON;
+        } else {
+            CS_Params.OperatingMode = LVCS_OFF;
         }
 
-        if((LocalParams.TE_OperatingMode == LVM_TE_ON) && (LocalParams.TE_EffectLevel == LVM_TE_LOW_MIPS))
-        {
-            CS_Params.SpeakerType  = LVCS_EX_HEADPHONES;
-        }
-        else
-        {
-            CS_Params.SpeakerType  = LVCS_HEADPHONES;
+        if ((LocalParams.TE_OperatingMode == LVM_TE_ON) &&
+            (LocalParams.TE_EffectLevel == LVM_TE_LOW_MIPS)) {
+            CS_Params.SpeakerType = LVCS_EX_HEADPHONES;
+        } else {
+            CS_Params.SpeakerType = LVCS_HEADPHONES;
         }
 
-#ifdef SUPPORT_MC
         /* Concert sound module processes only the left and right channels
          * data. So the Source Format is set to LVCS_STEREO for multichannel
          * input also.
          */
         if (LocalParams.SourceFormat == LVM_STEREO ||
-            LocalParams.SourceFormat == LVM_MULTICHANNEL)
-#else
-        if (LocalParams.SourceFormat == LVM_STEREO)    /* Mono format not supported */
-#endif
-        {
+            LocalParams.SourceFormat == LVM_MULTICHANNEL) {
             CS_Params.SourceFormat = LVCS_STEREO;
+        } else {
+            CS_Params.SourceFormat = LVCS_MONOINSTEREO; /* Force to Mono-in-Stereo mode */
         }
-        else
-        {
-            CS_Params.SourceFormat = LVCS_MONOINSTEREO;          /* Force to Mono-in-Stereo mode */
-        }
-        CS_Params.SampleRate  = LocalParams.SampleRate;
+        CS_Params.SampleRate = LocalParams.SampleRate;
         CS_Params.ReverbLevel = LocalParams.VirtualizerReverbLevel;
         CS_Params.EffectLevel = LocalParams.CS_EffectLevel;
-#ifdef SUPPORT_MC
-        CS_Params.NrChannels  = LocalParams.NrChannels;
-#endif
+        CS_Params.NrChannels = LocalParams.NrChannels;
 
         /*
          * Set the control flag
          */
         if (((LVM_Mode_en)LocalParams.OperatingMode == LVM_MODE_ON) &&
-            ((LVCS_Modes_en)LocalParams.VirtualizerOperatingMode != LVCS_OFF))
-        {
+            ((LVCS_Modes_en)LocalParams.VirtualizerOperatingMode != LVCS_OFF)) {
             pInstance->CS_Active = LVM_TRUE;
-        }
-        else
-        {
+        } else {
             CS_Params.OperatingMode = LVCS_OFF;
         }
 
-        CS_Params.CompressorMode=CompressorMode;
+        CS_Params.CompressorMode = CompressorMode;
 
         /*
          * Make the changes
          */
-        CS_Status = LVCS_Control(hCSInstance,
-                                 &CS_Params);
+        CS_Status = LVCS_Control(hCSInstance, &CS_Params);
 
         /*
          * Quit if the changes were not accepted
          */
-        if (CS_Status != LVCS_SUCCESS)
-        {
-            return((LVM_ReturnStatus_en)CS_Status);
+        if (CS_Status != LVCS_SUCCESS) {
+            return ((LVM_ReturnStatus_en)CS_Status);
         }
-
     }
 
     /*
      * Update the Power Spectrum Analyser
      */
     {
-        LVPSA_RETURN                PSA_Status;
-        LVPSA_ControlParams_t       PSA_Params;
-        pLVPSA_Handle_t             *hPSAInstance = (pLVPSA_Handle_t *)pInstance->hPSAInstance;
+        LVPSA_RETURN PSA_Status;
+        LVPSA_ControlParams_t PSA_Params;
+        pLVPSA_Handle_t* hPSAInstance = (pLVPSA_Handle_t*)pInstance->hPSAInstance;
 
         /*
          * Set the new parameters
@@ -838,23 +721,19 @@
         /*
          * Make the changes
          */
-        if(pInstance->InstParams.PSA_Included==LVM_PSA_ON)
-        {
-            PSA_Status = LVPSA_Control(hPSAInstance,
-                &PSA_Params);
+        if (pInstance->InstParams.PSA_Included == LVM_PSA_ON) {
+            PSA_Status = LVPSA_Control(hPSAInstance, &PSA_Params);
 
-            if (PSA_Status != LVPSA_OK)
-            {
-                return((LVM_ReturnStatus_en)PSA_Status);
+            if (PSA_Status != LVPSA_OK) {
+                return ((LVM_ReturnStatus_en)PSA_Status);
             }
 
             /*
              * Apply new settings
              */
-            PSA_Status = LVPSA_ApplyNewSettings ((LVPSA_InstancePr_t*)hPSAInstance);
-            if(PSA_Status != LVPSA_OK)
-            {
-                return((LVM_ReturnStatus_en)PSA_Status);
+            PSA_Status = LVPSA_ApplyNewSettings((LVPSA_InstancePr_t*)hPSAInstance);
+            if (PSA_Status != LVPSA_OK) {
+                return ((LVM_ReturnStatus_en)PSA_Status);
             }
         }
     }
@@ -863,9 +742,9 @@
      * Update the parameters and clear the flag
      */
     pInstance->NoSmoothVolume = LVM_FALSE;
-    pInstance->Params =  LocalParams;
+    pInstance->Params = LocalParams;
 
-    return(LVM_SUCCESS);
+    return (LVM_SUCCESS);
 }
 
 /****************************************************************************************/
@@ -887,36 +766,30 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVM_ReturnStatus_en LVM_SetHeadroomParams(LVM_Handle_t              hInstance,
-                                          LVM_HeadroomParams_t      *pHeadroomParams)
-{
-    LVM_Instance_t      *pInstance =(LVM_Instance_t  *)hInstance;
-    LVM_UINT16          ii, NBands;
+LVM_ReturnStatus_en LVM_SetHeadroomParams(LVM_Handle_t hInstance,
+                                          LVM_HeadroomParams_t* pHeadroomParams) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
+    LVM_UINT16 ii, NBands;
 
     /* Check for NULL pointers */
-    if ((hInstance == LVM_NULL) || (pHeadroomParams == LVM_NULL))
-    {
+    if ((hInstance == LVM_NULL) || (pHeadroomParams == LVM_NULL)) {
         return (LVM_NULLADDRESS);
     }
-    if ((pHeadroomParams->NHeadroomBands != 0) && (pHeadroomParams->pHeadroomDefinition == LVM_NULL))
-    {
+    if ((pHeadroomParams->NHeadroomBands != 0) &&
+        (pHeadroomParams->pHeadroomDefinition == LVM_NULL)) {
         return (LVM_NULLADDRESS);
     }
 
     /* Consider only the LVM_HEADROOM_MAX_NBANDS first bands*/
-    if (pHeadroomParams->NHeadroomBands > LVM_HEADROOM_MAX_NBANDS)
-    {
+    if (pHeadroomParams->NHeadroomBands > LVM_HEADROOM_MAX_NBANDS) {
         NBands = LVM_HEADROOM_MAX_NBANDS;
-    }
-    else
-    {
+    } else {
         NBands = pHeadroomParams->NHeadroomBands;
     }
     pInstance->NewHeadroomParams.NHeadroomBands = NBands;
 
     /* Copy settings in memory */
-    for(ii = 0; ii < NBands; ii++)
-    {
+    for (ii = 0; ii < NBands; ii++) {
         pInstance->pHeadroom_BandDefs[ii] = pHeadroomParams->pHeadroomDefinition[ii];
     }
 
@@ -924,7 +797,7 @@
     pInstance->NewHeadroomParams.Headroom_OperatingMode = pHeadroomParams->Headroom_OperatingMode;
     pInstance->ControlPending = LVM_TRUE;
 
-    return(LVM_SUCCESS);
+    return (LVM_SUCCESS);
 }
 
 /****************************************************************************************/
@@ -947,29 +820,26 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVM_ReturnStatus_en LVM_GetHeadroomParams(LVM_Handle_t          hInstance,
-                                          LVM_HeadroomParams_t  *pHeadroomParams)
-{
-    LVM_Instance_t      *pInstance =(LVM_Instance_t  *)hInstance;
-    LVM_UINT16          ii;
+LVM_ReturnStatus_en LVM_GetHeadroomParams(LVM_Handle_t hInstance,
+                                          LVM_HeadroomParams_t* pHeadroomParams) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
+    LVM_UINT16 ii;
 
     /* Check for NULL pointers */
-    if ((hInstance == LVM_NULL) || (pHeadroomParams == LVM_NULL))
-    {
+    if ((hInstance == LVM_NULL) || (pHeadroomParams == LVM_NULL)) {
         return (LVM_NULLADDRESS);
     }
 
     pHeadroomParams->NHeadroomBands = pInstance->NewHeadroomParams.NHeadroomBands;
 
     /* Copy settings in memory */
-    for(ii = 0; ii < pInstance->NewHeadroomParams.NHeadroomBands; ii++)
-    {
+    for (ii = 0; ii < pInstance->NewHeadroomParams.NHeadroomBands; ii++) {
         pInstance->pHeadroom_UserDefs[ii] = pInstance->pHeadroom_BandDefs[ii];
     }
 
     pHeadroomParams->pHeadroomDefinition = pInstance->pHeadroom_UserDefs;
     pHeadroomParams->Headroom_OperatingMode = pInstance->NewHeadroomParams.Headroom_OperatingMode;
-    return(LVM_SUCCESS);
+    return (LVM_SUCCESS);
 }
 
 /****************************************************************************************/
@@ -988,18 +858,14 @@
 /*  1.  This function may be interrupted by the LVM_Process function                    */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_INT32 LVM_AlgoCallBack( void          *pBundleHandle,
-                            void          *pData,
-                            LVM_INT16     callbackId)
-{
-    LVM_Instance_t      *pInstance =(LVM_Instance_t  *)pBundleHandle;
+LVM_INT32 LVM_AlgoCallBack(void* pBundleHandle, void* pData, LVM_INT16 callbackId) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)pBundleHandle;
 
-    (void) pData;
+    (void)pData;
 
-    switch(callbackId & 0xFF00){
+    switch (callbackId & 0xFF00) {
         case ALGORITHM_CS_ID:
-            switch(callbackId & 0x00FF)
-            {
+            switch (callbackId & 0x00FF) {
                 case LVCS_EVENT_ALGOFF:
                     pInstance->CS_Active = LVM_FALSE;
                     break;
@@ -1008,8 +874,7 @@
             }
             break;
         case ALGORITHM_EQNB_ID:
-            switch(callbackId & 0x00FF)
-            {
+            switch (callbackId & 0x00FF) {
                 case LVEQNB_EVENT_ALGOFF:
                     pInstance->EQNB_Active = LVM_FALSE;
                     break;
@@ -1040,21 +905,17 @@
 /*  1.  This function may be interrupted by the LVM_Process function                    */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_INT32    LVM_VCCallBack(void*   pBundleHandle,
-                            void*   pGeneralPurpose,
-                            short   CallBackParam)
-{
-    LVM_Instance_t *pInstance =(LVM_Instance_t  *)pBundleHandle;
-    LVM_FLOAT    Target;
+LVM_INT32 LVM_VCCallBack(void* pBundleHandle, void* pGeneralPurpose, short CallBackParam) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)pBundleHandle;
+    LVM_FLOAT Target;
 
-    (void) pGeneralPurpose;
-    (void) CallBackParam;
+    (void)pGeneralPurpose;
+    (void)CallBackParam;
 
     /* When volume mixer has reached 0 dB target then stop it to avoid
        unnecessary processing. */
     Target = LVC_Mixer_GetTarget(&pInstance->VC_Volume.MixerStream[0]);
-    if(Target == 1.0f)
-    {
+    if (Target == 1.0f) {
         pInstance->VC_Active = LVM_FALSE;
     }
     return 1;
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Init.cpp b/media/libeffects/lvm/lib/Bundle/src/LVM_Init.cpp
index 5620529..6ea08bc 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Init.cpp
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Init.cpp
@@ -20,6 +20,7 @@
 /*  Includes                                                                        */
 /*                                                                                  */
 /************************************************************************************/
+#include <stdlib.h>
 
 #include "LVM_Private.h"
 #include "LVM_Tables.h"
@@ -28,570 +29,87 @@
 
 /****************************************************************************************/
 /*                                                                                      */
-/* FUNCTION:                LVM_GetMemoryTable                                          */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*  This function is used for memory allocation and free. It can be called in           */
-/*  two ways:                                                                           */
-/*                                                                                      */
-/*      hInstance = NULL                Returns the memory requirements                 */
-/*      hInstance = Instance handle     Returns the memory requirements and             */
-/*                                      allocated base addresses for the instance       */
-/*                                                                                      */
-/*  When this function is called for memory allocation (hInstance=NULL) the memory      */
-/*  base address pointers are NULL on return.                                           */
-/*                                                                                      */
-/*  When the function is called for free (hInstance = Instance Handle) the memory       */
-/*  table returns the allocated memory and base addresses used during initialisation.   */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance               Instance Handle                                             */
-/*  pMemoryTable            Pointer to an empty memory definition table                 */
-/*  pCapabilities           Pointer to the default capabilities                         */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVM_SUCCESS             Succeeded                                                   */
-/*  LVM_NULLADDRESS         When one of pMemoryTable or pInstParams is NULL             */
-/*  LVM_OUTOFRANGE          When any of the Instance parameters are out of range        */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*  1.  This function may be interrupted by the LVM_Process function                    */
-/*  2.  The scratch memory is the largest required by any of the sub-modules plus any   */
-/*      additional scratch requirements of the bundle                                   */
-/*                                                                                      */
-/****************************************************************************************/
-
-/*
- * 4 Types of Memory Regions of LVM
- * TODO: Allocate on the fly.
- * i)   LVM_MEMREGION_PERSISTENT_SLOW_DATA - For Instance Handles
- * ii)  LVM_MEMREGION_PERSISTENT_FAST_DATA - Persistent Buffers
- * iii) LVM_MEMREGION_PERSISTENT_FAST_COEF - For Holding Structure values
- * iv)  LVM_MEMREGION_TEMPORARY_FAST       - For Holding Structure values
- *
- * LVM_MEMREGION_PERSISTENT_SLOW_DATA:
- *   Total Memory size:
- *     sizeof(LVM_Instance_t) + \
- *     sizeof(LVM_Buffer_t) + \
- *     sizeof(LVPSA_InstancePr_t) + \
- *     sizeof(LVM_Buffer_t) - needed if buffer mode is LVM_MANAGED_BUFFER
- *
- * LVM_MEMREGION_PERSISTENT_FAST_DATA:
- *   Total Memory size:
- *     sizeof(LVM_TE_Data_t) + \
- *     2 * pInstParams->EQNB_NumBands * sizeof(LVM_EQNB_BandDef_t) + \
- *     sizeof(LVCS_Data_t) + \
- *     sizeof(LVDBE_Data_FLOAT_t) + \
- *     sizeof(Biquad_2I_Order2_FLOAT_Taps_t) + \
- *     sizeof(Biquad_2I_Order2_FLOAT_Taps_t) + \
- *     pInstParams->EQNB_NumBands * sizeof(Biquad_2I_Order2_FLOAT_Taps_t) + \
- *     pInstParams->EQNB_NumBands * sizeof(LVEQNB_BandDef_t) + \
- *     pInstParams->EQNB_NumBands * sizeof(LVEQNB_BiquadType_en) + \
- *     2 * LVM_HEADROOM_MAX_NBANDS * sizeof(LVM_HeadroomBandDef_t) + \
- *     PSA_InitParams.nBands * sizeof(Biquad_1I_Order2_Taps_t) + \
- *     PSA_InitParams.nBands * sizeof(QPD_Taps_t)
- *
- * LVM_MEMREGION_PERSISTENT_FAST_COEF:
- *   Total Memory size:
- *     sizeof(LVM_TE_Coefs_t) + \
- *     sizeof(LVCS_Coefficient_t) + \
- *     sizeof(LVDBE_Coef_FLOAT_t) + \
- *     sizeof(Biquad_FLOAT_Instance_t) + \
- *     sizeof(Biquad_FLOAT_Instance_t) + \
- *     pInstParams->EQNB_NumBands * sizeof(Biquad_FLOAT_Instance_t) + \
- *     PSA_InitParams.nBands * sizeof(Biquad_Instance_t) + \
- *     PSA_InitParams.nBands * sizeof(QPD_State_t)
- *
- * LVM_MEMREGION_TEMPORARY_FAST (Scratch):
- *   Total Memory Size:
- *     BundleScratchSize + \
- *     MAX_INTERNAL_BLOCKSIZE * sizeof(LVM_FLOAT) + \
- *     MaxScratchOf (CS, EQNB, DBE, PSA)
- *
- *     a)BundleScratchSize:
- *         3 * LVM_MAX_CHANNELS \
- *         * (MIN_INTERNAL_BLOCKSIZE + InternalBlockSize) * sizeof(LVM_FLOAT)
- *       This Memory is allocated only when Buffer mode is LVM_MANAGED_BUFFER.
- *     b)MaxScratchOf (CS, EQNB, DBE, PSA)
- *       This Memory is needed for scratch usage for CS, EQNB, DBE, PSA.
- *       CS   = (LVCS_SCRATCHBUFFERS * sizeof(LVM_FLOAT)
- *               * pCapabilities->MaxBlockSize)
- *       EQNB = (LVEQNB_SCRATCHBUFFERS * sizeof(LVM_FLOAT)
- *               * pCapabilities->MaxBlockSize)
- *       DBE  = (LVDBE_SCRATCHBUFFERS_INPLACE*sizeof(LVM_FLOAT)
- *               * pCapabilities->MaxBlockSize)
- *       PSA  = (2 * pInitParams->MaxInputBlockSize * sizeof(LVM_FLOAT))
- *              one MaxInputBlockSize for input and another for filter output
- *     c)MAX_INTERNAL_BLOCKSIZE
- *       This Memory is needed for PSAInput - Temp memory to store output
- *       from McToMono block and given as input to PSA block
- */
-
-LVM_ReturnStatus_en LVM_GetMemoryTable(LVM_Handle_t         hInstance,
-                                       LVM_MemTab_t         *pMemoryTable,
-                                       LVM_InstParams_t     *pInstParams)
-{
-
-    LVM_Instance_t      *pInstance = (LVM_Instance_t *)hInstance;
-    LVM_UINT32          AlgScratchSize;
-    LVM_UINT32          BundleScratchSize;
-    LVM_UINT16          InternalBlockSize;
-    INST_ALLOC          AllocMem[LVM_NR_MEMORY_REGIONS];
-    LVM_INT16           i;
-
-    /*
-     * Check parameters
-     */
-    if(pMemoryTable == LVM_NULL)
-    {
-        return LVM_NULLADDRESS;
-    }
-
-    /*
-     * Return memory table if the instance has already been created
-     */
-    if (hInstance != LVM_NULL)
-    {
-       /* Read back memory allocation table */
-        *pMemoryTable = pInstance->MemoryTable;
-        return(LVM_SUCCESS);
-    }
-
-    if(pInstParams == LVM_NULL)
-    {
-        return LVM_NULLADDRESS;
-    }
-
-    /*
-     *  Power Spectrum Analyser
-     */
-    if(pInstParams->PSA_Included > LVM_PSA_ON)
-    {
-        return (LVM_OUTOFRANGE);
-    }
-
-    /*
-     * Check the instance parameters
-     */
-    if( (pInstParams->BufferMode != LVM_MANAGED_BUFFERS) && (pInstParams->BufferMode != LVM_UNMANAGED_BUFFERS) )
-    {
-        return (LVM_OUTOFRANGE);
-    }
-
-    /* N-Band Equalizer */
-    if( pInstParams->EQNB_NumBands > 32 )
-    {
-        return (LVM_OUTOFRANGE);
-    }
-
-    if(pInstParams->BufferMode == LVM_MANAGED_BUFFERS)
-    {
-        if( (pInstParams->MaxBlockSize < LVM_MIN_MAXBLOCKSIZE ) || (pInstParams->MaxBlockSize > LVM_MANAGED_MAX_MAXBLOCKSIZE ) )
-        {
-            return (LVM_OUTOFRANGE);
-        }
-    }
-    else
-    {
-        if( (pInstParams->MaxBlockSize < LVM_MIN_MAXBLOCKSIZE ) || (pInstParams->MaxBlockSize > LVM_UNMANAGED_MAX_MAXBLOCKSIZE) )
-        {
-            return (LVM_OUTOFRANGE);
-        }
-    }
-
-    /*
-    * Initialise the AllocMem structures
-    */
-    for (i=0; i<LVM_NR_MEMORY_REGIONS; i++)
-    {
-        InstAlloc_Init(&AllocMem[i], LVM_NULL);
-    }
-    InternalBlockSize = (LVM_UINT16)((pInstParams->MaxBlockSize) & MIN_INTERNAL_BLOCKMASK); /* Force to a multiple of MIN_INTERNAL_BLOCKSIZE */
-
-    if (InternalBlockSize < MIN_INTERNAL_BLOCKSIZE)
-    {
-        InternalBlockSize = MIN_INTERNAL_BLOCKSIZE;
-    }
-
-    /* Maximum Internal Black Size should not be more than MAX_INTERNAL_BLOCKSIZE*/
-    if(InternalBlockSize > MAX_INTERNAL_BLOCKSIZE)
-    {
-        InternalBlockSize = MAX_INTERNAL_BLOCKSIZE;
-    }
-
-    /*
-    * Bundle requirements
-    */
-    InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_SLOW_DATA],
-        sizeof(LVM_Instance_t));
-
-    /*
-     * Set the algorithm and bundle scratch requirements
-     */
-    AlgScratchSize    = 0;
-    if (pInstParams->BufferMode == LVM_MANAGED_BUFFERS)
-    {
-        BundleScratchSize = 3 * LVM_MAX_CHANNELS \
-                            * (MIN_INTERNAL_BLOCKSIZE + InternalBlockSize) \
-                            * sizeof(LVM_FLOAT);
-        InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_TEMPORARY_FAST],        /* Scratch buffer */
-                            BundleScratchSize);
-        InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_SLOW_DATA],
-                            sizeof(LVM_Buffer_t));
-    }
-
-    /*
-     * Treble Enhancement requirements
-     */
-    InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                        sizeof(LVM_TE_Data_t));
-    InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                        sizeof(LVM_TE_Coefs_t));
-
-    /*
-     * N-Band Equalizer requirements
-     */
-    InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],      /* Local storage */
-                        (pInstParams->EQNB_NumBands * sizeof(LVM_EQNB_BandDef_t)));
-    InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],      /* User storage */
-                        (pInstParams->EQNB_NumBands * sizeof(LVM_EQNB_BandDef_t)));
-
-    /*
-     * Concert Sound requirements
-     */
-    {
-        LVCS_MemTab_t           CS_MemTab;
-        LVCS_Capabilities_t     CS_Capabilities;
-
-        /*
-         * Set the capabilities
-         */
-        CS_Capabilities.MaxBlockSize     = InternalBlockSize;
-
-        /*
-         * Get the memory requirements
-         */
-        LVCS_Memory(LVM_NULL,
-                    &CS_MemTab,
-                    &CS_Capabilities);
-
-        /*
-         * Update the memory allocation structures
-         */
-        InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                            CS_MemTab.Region[LVM_MEMREGION_PERSISTENT_FAST_DATA].Size);
-        InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                            CS_MemTab.Region[LVM_MEMREGION_PERSISTENT_FAST_COEF].Size);
-        if (CS_MemTab.Region[LVM_MEMREGION_TEMPORARY_FAST].Size > AlgScratchSize) AlgScratchSize = CS_MemTab.Region[LVM_MEMREGION_TEMPORARY_FAST].Size;
-
-    }
-
-    /*
-     * Dynamic Bass Enhancement requirements
-     */
-    {
-        LVDBE_MemTab_t          DBE_MemTab;
-        LVDBE_Capabilities_t    DBE_Capabilities;
-
-        /*
-         * Set the capabilities
-         */
-        DBE_Capabilities.SampleRate      = LVDBE_CAP_FS_8000 | LVDBE_CAP_FS_11025 |
-                                           LVDBE_CAP_FS_12000 | LVDBE_CAP_FS_16000 |
-                                           LVDBE_CAP_FS_22050 | LVDBE_CAP_FS_24000 |
-                                           LVDBE_CAP_FS_32000 | LVDBE_CAP_FS_44100 |
-                                           LVDBE_CAP_FS_48000 | LVDBE_CAP_FS_88200 |
-                                           LVDBE_CAP_FS_96000 | LVDBE_CAP_FS_176400 |
-                                           LVDBE_CAP_FS_192000;
-        DBE_Capabilities.CentreFrequency = LVDBE_CAP_CENTRE_55Hz | LVDBE_CAP_CENTRE_55Hz | LVDBE_CAP_CENTRE_66Hz | LVDBE_CAP_CENTRE_78Hz | LVDBE_CAP_CENTRE_90Hz;
-        DBE_Capabilities.MaxBlockSize    = InternalBlockSize;
-
-        /*
-         * Get the memory requirements
-         */
-        LVDBE_Memory(LVM_NULL,
-                    &DBE_MemTab,
-
-                    &DBE_Capabilities);
-        /*
-         * Update the bundle table
-         */
-        InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                            DBE_MemTab.Region[LVM_MEMREGION_PERSISTENT_FAST_DATA].Size);
-        InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                            DBE_MemTab.Region[LVM_MEMREGION_PERSISTENT_FAST_COEF].Size);
-        if (DBE_MemTab.Region[LVM_MEMREGION_TEMPORARY_FAST].Size > AlgScratchSize) AlgScratchSize = DBE_MemTab.Region[LVM_MEMREGION_TEMPORARY_FAST].Size;
-
-    }
-
-    /*
-     * N-Band equaliser requirements
-     */
-    {
-        LVEQNB_MemTab_t         EQNB_MemTab;            /* For N-Band Equaliser */
-        LVEQNB_Capabilities_t   EQNB_Capabilities;
-
-        /*
-         * Set the capabilities
-         */
-        EQNB_Capabilities.SampleRate   = LVEQNB_CAP_FS_8000 | LVEQNB_CAP_FS_11025 |
-                                         LVEQNB_CAP_FS_12000 | LVEQNB_CAP_FS_16000 |
-                                         LVEQNB_CAP_FS_22050 | LVEQNB_CAP_FS_24000 |
-                                         LVEQNB_CAP_FS_32000 | LVEQNB_CAP_FS_44100 |
-                                         LVEQNB_CAP_FS_48000 | LVEQNB_CAP_FS_88200 |
-                                         LVEQNB_CAP_FS_96000 | LVEQNB_CAP_FS_176400 |
-                                         LVEQNB_CAP_FS_192000;
-        EQNB_Capabilities.SourceFormat = LVEQNB_CAP_STEREO | LVEQNB_CAP_MONOINSTEREO;
-        EQNB_Capabilities.MaxBlockSize = InternalBlockSize;
-        EQNB_Capabilities.MaxBands     = pInstParams->EQNB_NumBands;
-
-        /*
-         * Get the memory requirements
-         */
-        LVEQNB_Memory(LVM_NULL,
-                      &EQNB_MemTab,
-                      &EQNB_Capabilities);
-
-        /*
-         * Update the bundle table
-         */
-        InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                            EQNB_MemTab.Region[LVM_MEMREGION_PERSISTENT_FAST_DATA].Size);
-        InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                            EQNB_MemTab.Region[LVM_MEMREGION_PERSISTENT_FAST_COEF].Size);
-        if (EQNB_MemTab.Region[LVM_MEMREGION_TEMPORARY_FAST].Size > AlgScratchSize) AlgScratchSize = EQNB_MemTab.Region[LVM_MEMREGION_TEMPORARY_FAST].Size;
-
-    }
-
-    /*
-     * Headroom management memory allocation
-     */
-    InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                       (LVM_HEADROOM_MAX_NBANDS * sizeof(LVM_HeadroomBandDef_t)));
-    InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                       (LVM_HEADROOM_MAX_NBANDS * sizeof(LVM_HeadroomBandDef_t)));
-
-    /*
-     * Spectrum Analyzer memory requirements
-     */
-    {
-        pLVPSA_Handle_t     hPSAInst = LVM_NULL;
-        LVPSA_MemTab_t      PSA_MemTab;
-        LVPSA_InitParams_t  PSA_InitParams;
-        LVPSA_FilterParam_t FiltersParams[9];
-        LVPSA_RETURN        PSA_Status;
-
-        if(pInstParams->PSA_Included == LVM_PSA_ON)
-        {
-            PSA_InitParams.SpectralDataBufferDuration   = (LVM_UINT16) 500;
-            PSA_InitParams.MaxInputBlockSize            = (LVM_UINT16) 1000;
-            PSA_InitParams.nBands                       = (LVM_UINT16) 9;
-
-            PSA_InitParams.pFiltersParams = &FiltersParams[0];
-            for(i = 0; i < PSA_InitParams.nBands; i++)
-            {
-                FiltersParams[i].CenterFrequency    = (LVM_UINT16) 1000;
-                FiltersParams[i].QFactor            = (LVM_UINT16) 25;
-                FiltersParams[i].PostGain           = (LVM_INT16)  0;
-            }
-
-            /*
-            * Get the memory requirements
-            */
-            PSA_Status = LVPSA_Memory (hPSAInst,
-                                        &PSA_MemTab,
-                                        &PSA_InitParams);
-
-            if (PSA_Status != LVPSA_OK)
-            {
-                return((LVM_ReturnStatus_en) LVM_ALGORITHMPSA);
-            }
-
-            /*
-            * Update the bundle table
-            */
-            /* Slow Data */
-            InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_SLOW_DATA],
-                PSA_MemTab.Region[LVM_PERSISTENT_SLOW_DATA].Size);
-
-            /* Fast Data */
-            InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                PSA_MemTab.Region[LVM_PERSISTENT_FAST_DATA].Size);
-
-            /* Fast Coef */
-            InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                PSA_MemTab.Region[LVM_PERSISTENT_FAST_COEF].Size);
-
-            /* Fast Temporary */
-            InstAlloc_AddMember(&AllocMem[LVM_TEMPORARY_FAST],
-                                MAX_INTERNAL_BLOCKSIZE * sizeof(LVM_FLOAT));
-
-            if (PSA_MemTab.Region[LVM_TEMPORARY_FAST].Size > AlgScratchSize)
-            {
-                AlgScratchSize = PSA_MemTab.Region[LVM_TEMPORARY_FAST].Size;
-            }
-        }
-    }
-
-    /*
-     * Return the memory table
-     */
-    pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_SLOW_DATA].Size         = InstAlloc_GetTotal(&AllocMem[LVM_MEMREGION_PERSISTENT_SLOW_DATA]);
-    pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_SLOW_DATA].Type         = LVM_PERSISTENT_SLOW_DATA;
-    pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_SLOW_DATA].pBaseAddress = LVM_NULL;
-
-    pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_DATA].Size         = InstAlloc_GetTotal(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA]);
-    pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_DATA].Type         = LVM_PERSISTENT_FAST_DATA;
-    pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_DATA].pBaseAddress = LVM_NULL;
-    if (pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_DATA].Size < 4)
-    {
-        pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_DATA].Size = 0;
-    }
-
-    pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_COEF].Size         = InstAlloc_GetTotal(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF]);
-    pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_COEF].Type         = LVM_PERSISTENT_FAST_COEF;
-    pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_COEF].pBaseAddress = LVM_NULL;
-    if (pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_COEF].Size < 4)
-    {
-        pMemoryTable->Region[LVM_MEMREGION_PERSISTENT_FAST_COEF].Size = 0;
-    }
-
-    InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_TEMPORARY_FAST],
-                        AlgScratchSize);
-    pMemoryTable->Region[LVM_MEMREGION_TEMPORARY_FAST].Size             = InstAlloc_GetTotal(&AllocMem[LVM_MEMREGION_TEMPORARY_FAST]);
-    pMemoryTable->Region[LVM_MEMREGION_TEMPORARY_FAST].Type             = LVM_TEMPORARY_FAST;
-    pMemoryTable->Region[LVM_MEMREGION_TEMPORARY_FAST].pBaseAddress     = LVM_NULL;
-    if (pMemoryTable->Region[LVM_MEMREGION_TEMPORARY_FAST].Size < 4)
-    {
-        pMemoryTable->Region[LVM_MEMREGION_TEMPORARY_FAST].Size = 0;
-    }
-
-    return(LVM_SUCCESS);
-
-}
-
-/****************************************************************************************/
-/*                                                                                      */
 /* FUNCTION:                LVM_GetInstanceHandle                                       */
 /*                                                                                      */
 /* DESCRIPTION:                                                                         */
-/*  This function is used to create a bundle instance. It returns the created instance  */
-/*  handle through phInstance. All parameters are set to their default, inactive state. */
+/*  This function is used to create a bundle instance.                                  */
+/*  All parameters are set to their default, inactive state.                            */
 /*                                                                                      */
 /* PARAMETERS:                                                                          */
-/*  phInstance              pointer to the instance handle                              */
-/*  pMemoryTable            Pointer to the memory definition table                      */
-/*  pInstParams             Pointer to the initialisation capabilities                  */
+/*  phInstance              Pointer to the instance handle                              */
+/*  pInstParams             Pointer to the instance parameters                          */
 /*                                                                                      */
 /* RETURNS:                                                                             */
 /*  LVM_SUCCESS             Initialisation succeeded                                    */
+/*  LVM_NULLADDRESS         One or more memory has a NULL pointer                       */
 /*  LVM_OUTOFRANGE          When any of the Instance parameters are out of range        */
-/*  LVM_NULLADDRESS         When one of phInstance, pMemoryTable or pInstParams are NULL*/
 /*                                                                                      */
 /* NOTES:                                                                               */
 /*  1. This function must not be interrupted by the LVM_Process function                */
 /*                                                                                      */
 /****************************************************************************************/
-
-LVM_ReturnStatus_en LVM_GetInstanceHandle(LVM_Handle_t           *phInstance,
-                                          LVM_MemTab_t           *pMemoryTable,
-                                          LVM_InstParams_t       *pInstParams)
-{
-
-    LVM_ReturnStatus_en     Status = LVM_SUCCESS;
-    LVM_Instance_t          *pInstance;
-    INST_ALLOC              AllocMem[LVM_NR_MEMORY_REGIONS];
-    LVM_INT16               i;
-    LVM_UINT16              InternalBlockSize;
-    LVM_INT32               BundleScratchSize;
+LVM_ReturnStatus_en LVM_GetInstanceHandle(LVM_Handle_t* phInstance, LVM_InstParams_t* pInstParams) {
+    LVM_ReturnStatus_en Status = LVM_SUCCESS;
+    LVM_Instance_t* pInstance;
+    LVM_INT16 i;
+    LVM_UINT16 InternalBlockSize;
+    LVM_INT32 BundleScratchSize;
 
     /*
      * Check valid points have been given
      */
-    if ((phInstance == LVM_NULL) || (pMemoryTable == LVM_NULL) || (pInstParams == LVM_NULL))
-    {
+    if ((phInstance == LVM_NULL) || (pInstParams == LVM_NULL)) {
         return (LVM_NULLADDRESS);
     }
 
     /*
-     * Check the memory table for NULL pointers
-     */
-    for (i=0; i<LVM_NR_MEMORY_REGIONS; i++)
-    {
-        if ((pMemoryTable->Region[i].Size != 0) &&
-            (pMemoryTable->Region[i].pBaseAddress==LVM_NULL))
-        {
-            return(LVM_NULLADDRESS);
-        }
-    }
-
-    /*
      * Check the instance parameters
      */
-    if( (pInstParams->BufferMode != LVM_MANAGED_BUFFERS) && (pInstParams->BufferMode != LVM_UNMANAGED_BUFFERS) )
-    {
+    if ((pInstParams->BufferMode != LVM_MANAGED_BUFFERS) &&
+        (pInstParams->BufferMode != LVM_UNMANAGED_BUFFERS)) {
         return (LVM_OUTOFRANGE);
     }
 
-    if( pInstParams->EQNB_NumBands > 32 )
-    {
+    if (pInstParams->EQNB_NumBands > 32) {
         return (LVM_OUTOFRANGE);
     }
 
-    if(pInstParams->BufferMode == LVM_MANAGED_BUFFERS)
-    {
-        if( (pInstParams->MaxBlockSize < LVM_MIN_MAXBLOCKSIZE ) || (pInstParams->MaxBlockSize > LVM_MANAGED_MAX_MAXBLOCKSIZE ) )
-        {
+    if (pInstParams->BufferMode == LVM_MANAGED_BUFFERS) {
+        if ((pInstParams->MaxBlockSize < LVM_MIN_MAXBLOCKSIZE) ||
+            (pInstParams->MaxBlockSize > LVM_MANAGED_MAX_MAXBLOCKSIZE)) {
             return (LVM_OUTOFRANGE);
         }
-    }
-    else
-    {
-        if( (pInstParams->MaxBlockSize < LVM_MIN_MAXBLOCKSIZE ) || (pInstParams->MaxBlockSize > LVM_UNMANAGED_MAX_MAXBLOCKSIZE) )
-        {
+    } else {
+        if ((pInstParams->MaxBlockSize < LVM_MIN_MAXBLOCKSIZE) ||
+            (pInstParams->MaxBlockSize > LVM_UNMANAGED_MAX_MAXBLOCKSIZE)) {
             return (LVM_OUTOFRANGE);
         }
     }
 
-    if(pInstParams->PSA_Included > LVM_PSA_ON)
-    {
+    if (pInstParams->PSA_Included > LVM_PSA_ON) {
         return (LVM_OUTOFRANGE);
     }
 
     /*
-     * Initialise the AllocMem structures
+     * Create the instance handle
      */
-    for (i=0; i<LVM_NR_MEMORY_REGIONS; i++)
-    {
-        InstAlloc_Init(&AllocMem[i],
-                       pMemoryTable->Region[i].pBaseAddress);
-    }
+    *phInstance = new LVM_Instance_t{};
+    pInstance = (LVM_Instance_t*)*phInstance;
+
+    pInstance->InstParams = *pInstParams;
 
     /*
-     * Set the instance handle
+     * Create the bundle scratch memory and initialse the buffer management
      */
-    *phInstance  = (LVM_Handle_t)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_SLOW_DATA],
-                                                     sizeof(LVM_Instance_t));
-    pInstance =(LVM_Instance_t  *)*phInstance;
-
-    /*
-     * Save the memory table, parameters and capabilities
-     */
-    pInstance->MemoryTable    = *pMemoryTable;
-    pInstance->InstParams     = *pInstParams;
-
-    /*
-     * Set the bundle scratch memory and initialse the buffer management
-     */
-    InternalBlockSize = (LVM_UINT16)((pInstParams->MaxBlockSize) & MIN_INTERNAL_BLOCKMASK); /* Force to a multiple of MIN_INTERNAL_BLOCKSIZE */
-    if (InternalBlockSize < MIN_INTERNAL_BLOCKSIZE)
-    {
+    InternalBlockSize = (LVM_UINT16)(
+            (pInstParams->MaxBlockSize) &
+            MIN_INTERNAL_BLOCKMASK); /* Force to a multiple of MIN_INTERNAL_BLOCKSIZE */
+    if (InternalBlockSize < MIN_INTERNAL_BLOCKSIZE) {
         InternalBlockSize = MIN_INTERNAL_BLOCKSIZE;
     }
 
     /* Maximum Internal Black Size should not be more than MAX_INTERNAL_BLOCKSIZE*/
-    if(InternalBlockSize > MAX_INTERNAL_BLOCKSIZE)
-    {
+    if (InternalBlockSize > MAX_INTERNAL_BLOCKSIZE) {
         InternalBlockSize = MAX_INTERNAL_BLOCKSIZE;
     }
     pInstance->InternalBlockSize = (LVM_INT16)InternalBlockSize;
@@ -599,40 +117,46 @@
     /*
      * Common settings for managed and unmanaged buffers
      */
-    pInstance->SamplesToProcess = 0;                /* No samples left to process */
-    if (pInstParams->BufferMode == LVM_MANAGED_BUFFERS)
-    {
+    pInstance->SamplesToProcess = 0; /* No samples left to process */
+    BundleScratchSize =
+            (LVM_INT32)(3 * LVM_MAX_CHANNELS * (MIN_INTERNAL_BLOCKSIZE + InternalBlockSize) *
+                        sizeof(LVM_FLOAT));
+    pInstance->pScratch = calloc(1, BundleScratchSize);
+    if (pInstance->pScratch == LVM_NULL) {
+        return LVM_NULLADDRESS;
+    }
+
+    if (pInstParams->BufferMode == LVM_MANAGED_BUFFERS) {
         /*
          * Managed buffers required
          */
-        pInstance->pBufferManagement = (LVM_Buffer_t *)
-            InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_SLOW_DATA],
-                                                           sizeof(LVM_Buffer_t));
-        BundleScratchSize = (LVM_INT32)
-                            (3 * LVM_MAX_CHANNELS \
-                             * (MIN_INTERNAL_BLOCKSIZE + InternalBlockSize) \
-                             * sizeof(LVM_FLOAT));
-        pInstance->pBufferManagement->pScratch = (LVM_FLOAT *)
-            InstAlloc_AddMember(
-                         &AllocMem[LVM_MEMREGION_TEMPORARY_FAST], /* Scratch 1 buffer */
-                                                  (LVM_UINT32)BundleScratchSize);
-        LoadConst_Float(0,                                   /* Clear the input delay buffer */
-                        (LVM_FLOAT *)&pInstance->pBufferManagement->InDelayBuffer,
+        pInstance->pBufferManagement =
+                (LVM_Buffer_t*)calloc(1, sizeof(*(pInstance->pBufferManagement)));
+        if (pInstance->pBufferManagement == LVM_NULL) {
+            return LVM_NULLADDRESS;
+        }
+
+        pInstance->pBufferManagement->pScratch = (LVM_FLOAT*)pInstance->pScratch;
+
+        LoadConst_Float(0, /* Clear the input delay buffer */
+                        (LVM_FLOAT*)&pInstance->pBufferManagement->InDelayBuffer,
                         (LVM_INT16)(LVM_MAX_CHANNELS * MIN_INTERNAL_BLOCKSIZE));
-        pInstance->pBufferManagement->InDelaySamples = MIN_INTERNAL_BLOCKSIZE; /* Set the number of delay samples */
-        pInstance->pBufferManagement->OutDelaySamples = 0;                     /* No samples in the output buffer */
-        pInstance->pBufferManagement->BufferState = LVM_FIRSTCALL;             /* Set the state ready for the first call */
+        pInstance->pBufferManagement->InDelaySamples =
+                MIN_INTERNAL_BLOCKSIZE;                    /* Set the number of delay samples */
+        pInstance->pBufferManagement->OutDelaySamples = 0; /* No samples in the output buffer */
+        pInstance->pBufferManagement->BufferState =
+                LVM_FIRSTCALL; /* Set the state ready for the first call */
     }
 
     /*
      * Set default parameters
      */
-    pInstance->Params.OperatingMode    = LVM_MODE_OFF;
-    pInstance->Params.SampleRate       = LVM_FS_8000;
-    pInstance->Params.SourceFormat     = LVM_MONO;
-    pInstance->Params.SpeakerType      = LVM_HEADPHONES;
-    pInstance->Params.VC_EffectLevel   = 0;
-    pInstance->Params.VC_Balance       = 0;
+    pInstance->Params.OperatingMode = LVM_MODE_OFF;
+    pInstance->Params.SampleRate = LVM_FS_8000;
+    pInstance->Params.SourceFormat = LVM_MONO;
+    pInstance->Params.SpeakerType = LVM_HEADPHONES;
+    pInstance->Params.VC_EffectLevel = 0;
+    pInstance->Params.VC_Balance = 0;
 
     /*
      * Set callback
@@ -642,338 +166,257 @@
     /*
      * DC removal filter
      */
-#ifdef SUPPORT_MC
     DC_Mc_D16_TRC_WRA_01_Init(&pInstance->DC_RemovalInstance);
-#else
-    DC_2I_D16_TRC_WRA_01_Init(&pInstance->DC_RemovalInstance);
-#endif
 
     /*
      * Treble Enhancement
      */
-    pInstance->pTE_Taps  = (LVM_TE_Data_t *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                                                                sizeof(LVM_TE_Data_t));
-
-    pInstance->pTE_State = (LVM_TE_Coefs_t *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                                                                 sizeof(LVM_TE_Coefs_t));
     pInstance->Params.TE_OperatingMode = LVM_TE_OFF;
-    pInstance->Params.TE_EffectLevel   = 0;
-    pInstance->TE_Active               = LVM_FALSE;
+    pInstance->Params.TE_EffectLevel = 0;
+    pInstance->TE_Active = LVM_FALSE;
 
     /*
      * Set the volume control and initialise Current to Target
      */
-    pInstance->VC_Volume.MixerStream[0].CallbackParam      = 0;
-    pInstance->VC_Volume.MixerStream[0].CallbackSet        = 0;
-    pInstance->VC_Volume.MixerStream[0].pCallbackHandle    = pInstance;
-    pInstance->VC_Volume.MixerStream[0].pCallBack          = LVM_VCCallBack;
+    pInstance->VC_Volume.MixerStream[0].CallbackParam = 0;
+    pInstance->VC_Volume.MixerStream[0].CallbackSet = 0;
+    pInstance->VC_Volume.MixerStream[0].pCallbackHandle = pInstance;
+    pInstance->VC_Volume.MixerStream[0].pCallBack = LVM_VCCallBack;
 
-    /* In managed buffering, start with low signal level as delay in buffer management causes a click*/
-    if (pInstParams->BufferMode == LVM_MANAGED_BUFFERS)
-    {
+    /* In managed buffering, start with low signal level as delay in buffer management causes a
+     * click*/
+    if (pInstParams->BufferMode == LVM_MANAGED_BUFFERS) {
         LVC_Mixer_Init(&pInstance->VC_Volume.MixerStream[0], 0, 0);
-    }
-    else
-    {
+    } else {
         LVC_Mixer_Init(&pInstance->VC_Volume.MixerStream[0], LVM_MAXFLOAT, LVM_MAXFLOAT);
     }
 
-    LVC_Mixer_SetTimeConstant(&pInstance->VC_Volume.MixerStream[0],0,LVM_FS_8000,2);
+    LVC_Mixer_SetTimeConstant(&pInstance->VC_Volume.MixerStream[0], 0, LVM_FS_8000, 2);
 
-    pInstance->VC_VolumedB                  = 0;
-    pInstance->VC_AVLFixedVolume            = 0;
-    pInstance->VC_Active                    = LVM_FALSE;
+    pInstance->VC_VolumedB = 0;
+    pInstance->VC_AVLFixedVolume = 0;
+    pInstance->VC_Active = LVM_FALSE;
 
-    pInstance->VC_BalanceMix.MixerStream[0].CallbackParam      = 0;
-    pInstance->VC_BalanceMix.MixerStream[0].CallbackSet        = 0;
-    pInstance->VC_BalanceMix.MixerStream[0].pCallbackHandle    = pInstance;
-    pInstance->VC_BalanceMix.MixerStream[0].pCallBack          = LVM_VCCallBack;
+    pInstance->VC_BalanceMix.MixerStream[0].CallbackParam = 0;
+    pInstance->VC_BalanceMix.MixerStream[0].CallbackSet = 0;
+    pInstance->VC_BalanceMix.MixerStream[0].pCallbackHandle = pInstance;
+    pInstance->VC_BalanceMix.MixerStream[0].pCallBack = LVM_VCCallBack;
     LVC_Mixer_Init(&pInstance->VC_BalanceMix.MixerStream[0], LVM_MAXFLOAT, LVM_MAXFLOAT);
-    LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_BalanceMix.MixerStream[0],LVM_VC_MIXER_TIME,LVM_FS_8000,2);
+    LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_BalanceMix.MixerStream[0], LVM_VC_MIXER_TIME,
+                                       LVM_FS_8000, 2);
 
-    pInstance->VC_BalanceMix.MixerStream[1].CallbackParam      = 0;
-    pInstance->VC_BalanceMix.MixerStream[1].CallbackSet        = 0;
-    pInstance->VC_BalanceMix.MixerStream[1].pCallbackHandle    = pInstance;
-    pInstance->VC_BalanceMix.MixerStream[1].pCallBack          = LVM_VCCallBack;
+    pInstance->VC_BalanceMix.MixerStream[1].CallbackParam = 0;
+    pInstance->VC_BalanceMix.MixerStream[1].CallbackSet = 0;
+    pInstance->VC_BalanceMix.MixerStream[1].pCallbackHandle = pInstance;
+    pInstance->VC_BalanceMix.MixerStream[1].pCallBack = LVM_VCCallBack;
     LVC_Mixer_Init(&pInstance->VC_BalanceMix.MixerStream[1], LVM_MAXFLOAT, LVM_MAXFLOAT);
-    LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_BalanceMix.MixerStream[1],LVM_VC_MIXER_TIME,LVM_FS_8000,2);
+    LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->VC_BalanceMix.MixerStream[1], LVM_VC_MIXER_TIME,
+                                       LVM_FS_8000, 2);
 
     /*
-     * Set the default EQNB pre-gain and pointer to the band definitions
+     * Create the default EQNB pre-gain and pointer to the band definitions
      */
-    pInstance->pEQNB_BandDefs =
-        (LVM_EQNB_BandDef_t *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                                   (pInstParams->EQNB_NumBands * sizeof(LVM_EQNB_BandDef_t)));
-    pInstance->pEQNB_UserDefs =
-        (LVM_EQNB_BandDef_t *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                                   (pInstParams->EQNB_NumBands * sizeof(LVM_EQNB_BandDef_t)));
+    pInstance->pEQNB_BandDefs = (LVM_EQNB_BandDef_t*)calloc(pInstParams->EQNB_NumBands,
+                                                            sizeof(*(pInstance->pEQNB_BandDefs)));
+    if (pInstance->pEQNB_BandDefs == LVM_NULL) {
+        return LVM_NULLADDRESS;
+    }
+    pInstance->pEQNB_UserDefs = (LVM_EQNB_BandDef_t*)calloc(pInstParams->EQNB_NumBands,
+                                                            sizeof(*(pInstance->pEQNB_UserDefs)));
+    if (pInstance->pEQNB_UserDefs == LVM_NULL) {
+        return LVM_NULLADDRESS;
+    }
 
     /*
      * Initialise the Concert Sound module
      */
     {
-        LVCS_Handle_t           hCSInstance;                /* Instance handle */
-        LVCS_MemTab_t           CS_MemTab;                  /* Memory table */
-        LVCS_Capabilities_t     CS_Capabilities;            /* Initial capabilities */
-        LVCS_ReturnStatus_en    LVCS_Status;                /* Function call status */
+        LVCS_Handle_t hCSInstance;           /* Instance handle */
+        LVCS_Capabilities_t CS_Capabilities; /* Initial capabilities */
+        LVCS_ReturnStatus_en LVCS_Status;    /* Function call status */
 
         /*
          * Set default parameters
          */
-        pInstance->Params.VirtualizerReverbLevel    = 100;
-        pInstance->Params.VirtualizerType           = LVM_CONCERTSOUND;
-        pInstance->Params.VirtualizerOperatingMode  = LVM_MODE_OFF;
-        pInstance->CS_Active                        = LVM_FALSE;
+        pInstance->Params.VirtualizerReverbLevel = 100;
+        pInstance->Params.VirtualizerType = LVM_CONCERTSOUND;
+        pInstance->Params.VirtualizerOperatingMode = LVM_MODE_OFF;
+        pInstance->CS_Active = LVM_FALSE;
 
         /*
          * Set the initialisation capabilities
          */
-        CS_Capabilities.MaxBlockSize    = (LVM_UINT16)InternalBlockSize;
+        CS_Capabilities.MaxBlockSize = (LVM_UINT16)InternalBlockSize;
         CS_Capabilities.CallBack = pInstance->CallBack;
         CS_Capabilities.pBundleInstance = (void*)pInstance;
 
         /*
-         * Get the memory requirements and then set the address pointers, forcing alignment
-         */
-        LVCS_Status = LVCS_Memory(LVM_NULL,                /* Get the memory requirements */
-                                  &CS_MemTab,
-                                  &CS_Capabilities);
-        CS_MemTab.Region[LVCS_MEMREGION_PERSISTENT_SLOW_DATA].pBaseAddress = &pInstance->CS_Instance;
-        CS_MemTab.Region[LVCS_MEMREGION_PERSISTENT_FAST_DATA].pBaseAddress = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                                                                                                         CS_MemTab.Region[LVCS_MEMREGION_PERSISTENT_FAST_DATA].Size);
-        CS_MemTab.Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].pBaseAddress = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                                                                                                         CS_MemTab.Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].Size);
-        CS_MemTab.Region[LVCS_MEMREGION_TEMPORARY_FAST].pBaseAddress       = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_TEMPORARY_FAST],
-                                                                                                         0);
-
-        /*
          * Initialise the Concert Sound instance and save the instance handle
          */
-        hCSInstance = LVM_NULL;                            /* Set to NULL to return handle */
-        LVCS_Status = LVCS_Init(&hCSInstance,              /* Initiailse */
-                                &CS_MemTab,
-                                &CS_Capabilities);
-        if (LVCS_Status != LVCS_SUCCESS) return((LVM_ReturnStatus_en)LVCS_Status);
-        pInstance->hCSInstance = hCSInstance;              /* Save the instance handle */
-
+        hCSInstance = LVM_NULL;               /* Set to NULL to return handle */
+        LVCS_Status = LVCS_Init(&hCSInstance, /* Create and initiailse */
+                                &CS_Capabilities, pInstance->pScratch);
+        if (LVCS_Status != LVCS_SUCCESS) return ((LVM_ReturnStatus_en)LVCS_Status);
+        pInstance->hCSInstance = hCSInstance; /* Save the instance handle */
     }
 
     /*
      * Initialise the Bass Enhancement module
      */
     {
-        LVDBE_Handle_t          hDBEInstance;               /* Instance handle */
-        LVDBE_MemTab_t          DBE_MemTab;                 /* Memory table */
-        LVDBE_Capabilities_t    DBE_Capabilities;           /* Initial capabilities */
-        LVDBE_ReturnStatus_en   LVDBE_Status;               /* Function call status */
+        LVDBE_Handle_t hDBEInstance;           /* Instance handle */
+        LVDBE_Capabilities_t DBE_Capabilities; /* Initial capabilities */
+        LVDBE_ReturnStatus_en LVDBE_Status;    /* Function call status */
 
         /*
          * Set the initialisation parameters
          */
         pInstance->Params.BE_OperatingMode = LVM_BE_OFF;
-        pInstance->Params.BE_CentreFreq    = LVM_BE_CENTRE_55Hz;
-        pInstance->Params.BE_EffectLevel   = 0;
-        pInstance->Params.BE_HPF           = LVM_BE_HPF_OFF;
+        pInstance->Params.BE_CentreFreq = LVM_BE_CENTRE_55Hz;
+        pInstance->Params.BE_EffectLevel = 0;
+        pInstance->Params.BE_HPF = LVM_BE_HPF_OFF;
 
-        pInstance->DBE_Active              = LVM_FALSE;
+        pInstance->DBE_Active = LVM_FALSE;
 
         /*
          * Set the initialisation capabilities
          */
-        DBE_Capabilities.SampleRate      = LVDBE_CAP_FS_8000 | LVDBE_CAP_FS_11025 |
-                                           LVDBE_CAP_FS_12000 | LVDBE_CAP_FS_16000 |
-                                           LVDBE_CAP_FS_22050 | LVDBE_CAP_FS_24000 |
-                                           LVDBE_CAP_FS_32000 | LVDBE_CAP_FS_44100 |
-                                           LVDBE_CAP_FS_48000 | LVDBE_CAP_FS_88200 |
-                                           LVDBE_CAP_FS_96000 | LVDBE_CAP_FS_176400 |
-                                           LVDBE_CAP_FS_192000;
-        DBE_Capabilities.CentreFrequency = LVDBE_CAP_CENTRE_55Hz | LVDBE_CAP_CENTRE_55Hz | LVDBE_CAP_CENTRE_66Hz | LVDBE_CAP_CENTRE_78Hz | LVDBE_CAP_CENTRE_90Hz;
-        DBE_Capabilities.MaxBlockSize    = (LVM_UINT16)InternalBlockSize;
+        DBE_Capabilities.SampleRate = LVDBE_CAP_FS_8000 | LVDBE_CAP_FS_11025 | LVDBE_CAP_FS_12000 |
+                                      LVDBE_CAP_FS_16000 | LVDBE_CAP_FS_22050 | LVDBE_CAP_FS_24000 |
+                                      LVDBE_CAP_FS_32000 | LVDBE_CAP_FS_44100 | LVDBE_CAP_FS_48000 |
+                                      LVDBE_CAP_FS_88200 | LVDBE_CAP_FS_96000 |
+                                      LVDBE_CAP_FS_176400 | LVDBE_CAP_FS_192000;
 
-        /*
-         * Get the memory requirements and then set the address pointers
-         */
-        LVDBE_Status = LVDBE_Memory(LVM_NULL,               /* Get the memory requirements */
-                                    &DBE_MemTab,
-                                    &DBE_Capabilities);
-        DBE_MemTab.Region[LVDBE_MEMREGION_INSTANCE].pBaseAddress        = &pInstance->DBE_Instance;
-        DBE_MemTab.Region[LVDBE_MEMREGION_PERSISTENT_DATA].pBaseAddress = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                                                                                                      DBE_MemTab.Region[LVDBE_MEMREGION_PERSISTENT_DATA].Size);
-        DBE_MemTab.Region[LVDBE_MEMREGION_PERSISTENT_COEF].pBaseAddress = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                                                                                                      DBE_MemTab.Region[LVDBE_MEMREGION_PERSISTENT_COEF].Size);
-        DBE_MemTab.Region[LVDBE_MEMREGION_SCRATCH].pBaseAddress         = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_TEMPORARY_FAST],
-                                                                                                      0);
+        DBE_Capabilities.CentreFrequency = LVDBE_CAP_CENTRE_55Hz | LVDBE_CAP_CENTRE_55Hz |
+                                           LVDBE_CAP_CENTRE_66Hz | LVDBE_CAP_CENTRE_78Hz |
+                                           LVDBE_CAP_CENTRE_90Hz;
+        DBE_Capabilities.MaxBlockSize = (LVM_UINT16)InternalBlockSize;
 
         /*
          * Initialise the Dynamic Bass Enhancement instance and save the instance handle
          */
-        hDBEInstance = LVM_NULL;                            /* Set to NULL to return handle */
-        LVDBE_Status = LVDBE_Init(&hDBEInstance,            /* Initiailse */
-                                  &DBE_MemTab,
-                                  &DBE_Capabilities);
-        if (LVDBE_Status != LVDBE_SUCCESS) return((LVM_ReturnStatus_en)LVDBE_Status);
-        pInstance->hDBEInstance = hDBEInstance;             /* Save the instance handle */
+        hDBEInstance = LVM_NULL;                 /* Set to NULL to return handle */
+        LVDBE_Status = LVDBE_Init(&hDBEInstance, /* Create and initiailse */
+                                  &DBE_Capabilities, pInstance->pScratch);
+        if (LVDBE_Status != LVDBE_SUCCESS) return ((LVM_ReturnStatus_en)LVDBE_Status);
+        pInstance->hDBEInstance = hDBEInstance; /* Save the instance handle */
     }
 
     /*
      * Initialise the N-Band Equaliser module
      */
     {
-        LVEQNB_Handle_t          hEQNBInstance;             /* Instance handle */
-        LVEQNB_MemTab_t          EQNB_MemTab;               /* Memory table */
-        LVEQNB_Capabilities_t    EQNB_Capabilities;         /* Initial capabilities */
-        LVEQNB_ReturnStatus_en   LVEQNB_Status;             /* Function call status */
+        LVEQNB_Handle_t hEQNBInstance;           /* Instance handle */
+        LVEQNB_Capabilities_t EQNB_Capabilities; /* Initial capabilities */
+        LVEQNB_ReturnStatus_en LVEQNB_Status;    /* Function call status */
 
         /*
          * Set the initialisation parameters
          */
-        pInstance->Params.EQNB_OperatingMode   = LVM_EQNB_OFF;
-        pInstance->Params.EQNB_NBands          = 0;
+        pInstance->Params.EQNB_OperatingMode = LVM_EQNB_OFF;
+        pInstance->Params.EQNB_NBands = 0;
         pInstance->Params.pEQNB_BandDefinition = LVM_NULL;
-        pInstance->EQNB_Active                 = LVM_FALSE;
+        pInstance->EQNB_Active = LVM_FALSE;
 
         /*
          * Set the initialisation capabilities
          */
-        EQNB_Capabilities.SampleRate      = LVEQNB_CAP_FS_8000 | LVEQNB_CAP_FS_11025 |
-                                            LVEQNB_CAP_FS_12000 | LVEQNB_CAP_FS_16000 |
-                                            LVEQNB_CAP_FS_22050 | LVEQNB_CAP_FS_24000 |
-                                            LVEQNB_CAP_FS_32000 | LVEQNB_CAP_FS_44100 |
-                                            LVEQNB_CAP_FS_48000 | LVEQNB_CAP_FS_88200 |
-                                            LVEQNB_CAP_FS_96000 | LVEQNB_CAP_FS_176400 |
-                                            LVEQNB_CAP_FS_192000;
-        EQNB_Capabilities.MaxBlockSize    = (LVM_UINT16)InternalBlockSize;
-        EQNB_Capabilities.MaxBands        = pInstParams->EQNB_NumBands;
-        EQNB_Capabilities.SourceFormat    = LVEQNB_CAP_STEREO | LVEQNB_CAP_MONOINSTEREO;
-        EQNB_Capabilities.CallBack        = pInstance->CallBack;
-        EQNB_Capabilities.pBundleInstance  = (void*)pInstance;
+        EQNB_Capabilities.SampleRate =
+                LVEQNB_CAP_FS_8000 | LVEQNB_CAP_FS_11025 | LVEQNB_CAP_FS_12000 |
+                LVEQNB_CAP_FS_16000 | LVEQNB_CAP_FS_22050 | LVEQNB_CAP_FS_24000 |
+                LVEQNB_CAP_FS_32000 | LVEQNB_CAP_FS_44100 | LVEQNB_CAP_FS_48000 |
+                LVEQNB_CAP_FS_88200 | LVEQNB_CAP_FS_96000 | LVEQNB_CAP_FS_176400 |
+                LVEQNB_CAP_FS_192000;
 
-        /*
-         * Get the memory requirements and then set the address pointers, forcing alignment
-         */
-        LVEQNB_Status = LVEQNB_Memory(LVM_NULL,             /* Get the memory requirements */
-                                      &EQNB_MemTab,
-                                      &EQNB_Capabilities);
-        EQNB_MemTab.Region[LVEQNB_MEMREGION_INSTANCE].pBaseAddress        = &pInstance->EQNB_Instance;
-        EQNB_MemTab.Region[LVEQNB_MEMREGION_PERSISTENT_DATA].pBaseAddress = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                                                                                                        EQNB_MemTab.Region[LVEQNB_MEMREGION_PERSISTENT_DATA].Size);
-        EQNB_MemTab.Region[LVEQNB_MEMREGION_PERSISTENT_COEF].pBaseAddress = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                                                                                                        EQNB_MemTab.Region[LVEQNB_MEMREGION_PERSISTENT_COEF].Size);
-        EQNB_MemTab.Region[LVEQNB_MEMREGION_SCRATCH].pBaseAddress         = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_TEMPORARY_FAST],
-                                                                                                        0);
+        EQNB_Capabilities.MaxBlockSize = (LVM_UINT16)InternalBlockSize;
+        EQNB_Capabilities.MaxBands = pInstParams->EQNB_NumBands;
+        EQNB_Capabilities.SourceFormat = LVEQNB_CAP_STEREO | LVEQNB_CAP_MONOINSTEREO;
+        EQNB_Capabilities.CallBack = pInstance->CallBack;
+        EQNB_Capabilities.pBundleInstance = (void*)pInstance;
 
         /*
          * Initialise the Dynamic Bass Enhancement instance and save the instance handle
          */
-        hEQNBInstance = LVM_NULL;                           /* Set to NULL to return handle */
-        LVEQNB_Status = LVEQNB_Init(&hEQNBInstance,         /* Initiailse */
-                                    &EQNB_MemTab,
-                                    &EQNB_Capabilities);
-        if (LVEQNB_Status != LVEQNB_SUCCESS) return((LVM_ReturnStatus_en)LVEQNB_Status);
-        pInstance->hEQNBInstance = hEQNBInstance;           /* Save the instance handle */
+        hEQNBInstance = LVM_NULL;                   /* Set to NULL to return handle */
+        LVEQNB_Status = LVEQNB_Init(&hEQNBInstance, /* Create and initiailse */
+                                    &EQNB_Capabilities, pInstance->pScratch);
+        if (LVEQNB_Status != LVEQNB_SUCCESS) return ((LVM_ReturnStatus_en)LVEQNB_Status);
+        pInstance->hEQNBInstance = hEQNBInstance; /* Save the instance handle */
     }
 
     /*
      * Headroom management memory allocation
      */
     {
-        pInstance->pHeadroom_BandDefs = (LVM_HeadroomBandDef_t *)
-              InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                                       (LVM_HEADROOM_MAX_NBANDS * sizeof(LVM_HeadroomBandDef_t)));
-        pInstance->pHeadroom_UserDefs = (LVM_HeadroomBandDef_t *)
-              InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                                       (LVM_HEADROOM_MAX_NBANDS * sizeof(LVM_HeadroomBandDef_t)));
+        pInstance->pHeadroom_BandDefs = (LVM_HeadroomBandDef_t*)calloc(
+                LVM_HEADROOM_MAX_NBANDS, sizeof(*(pInstance->pHeadroom_BandDefs)));
+        if (pInstance->pHeadroom_BandDefs == LVM_NULL) {
+            return LVM_NULLADDRESS;
+        }
+        pInstance->pHeadroom_UserDefs = (LVM_HeadroomBandDef_t*)calloc(
+                LVM_HEADROOM_MAX_NBANDS, sizeof(*(pInstance->pHeadroom_UserDefs)));
+        if (pInstance->pHeadroom_UserDefs == LVM_NULL) {
+            return LVM_NULLADDRESS;
+        }
 
         /* Headroom management parameters initialisation */
         pInstance->NewHeadroomParams.NHeadroomBands = 2;
         pInstance->NewHeadroomParams.pHeadroomDefinition = pInstance->pHeadroom_BandDefs;
-        pInstance->NewHeadroomParams.pHeadroomDefinition[0].Limit_Low          = 20;
-        pInstance->NewHeadroomParams.pHeadroomDefinition[0].Limit_High         = 4999;
-        pInstance->NewHeadroomParams.pHeadroomDefinition[0].Headroom_Offset    = 3;
-        pInstance->NewHeadroomParams.pHeadroomDefinition[1].Limit_Low          = 5000;
-        pInstance->NewHeadroomParams.pHeadroomDefinition[1].Limit_High         = 24000;
-        pInstance->NewHeadroomParams.pHeadroomDefinition[1].Headroom_Offset    = 4;
+        pInstance->NewHeadroomParams.pHeadroomDefinition[0].Limit_Low = 20;
+        pInstance->NewHeadroomParams.pHeadroomDefinition[0].Limit_High = 4999;
+        pInstance->NewHeadroomParams.pHeadroomDefinition[0].Headroom_Offset = 3;
+        pInstance->NewHeadroomParams.pHeadroomDefinition[1].Limit_Low = 5000;
+        pInstance->NewHeadroomParams.pHeadroomDefinition[1].Limit_High = 24000;
+        pInstance->NewHeadroomParams.pHeadroomDefinition[1].Headroom_Offset = 4;
         pInstance->NewHeadroomParams.Headroom_OperatingMode = LVM_HEADROOM_ON;
 
-        pInstance->Headroom =0;
+        pInstance->Headroom = 0;
     }
 
     /*
      * Initialise the PSA module
      */
     {
-        pLVPSA_Handle_t     hPSAInstance = LVM_NULL;   /* Instance handle */
-        LVPSA_MemTab_t      PSA_MemTab;
-        LVPSA_RETURN        PSA_Status;                 /* Function call status */
+        pLVPSA_Handle_t hPSAInstance = LVM_NULL; /* Instance handle */
+        LVPSA_RETURN PSA_Status;                 /* Function call status */
         LVPSA_FilterParam_t FiltersParams[9];
 
-        if(pInstParams->PSA_Included==LVM_PSA_ON)
-        {
-            pInstance->PSA_InitParams.SpectralDataBufferDuration   = (LVM_UINT16) 500;
-            pInstance->PSA_InitParams.MaxInputBlockSize            = (LVM_UINT16) 2048;
-            pInstance->PSA_InitParams.nBands                       = (LVM_UINT16) 9;
-            pInstance->PSA_InitParams.pFiltersParams               = &FiltersParams[0];
-            for(i = 0; i < pInstance->PSA_InitParams.nBands; i++)
-            {
-                FiltersParams[i].CenterFrequency    = (LVM_UINT16) 1000;
-                FiltersParams[i].QFactor            = (LVM_UINT16) 100;
-                FiltersParams[i].PostGain           = (LVM_INT16)  0;
+        if (pInstParams->PSA_Included == LVM_PSA_ON) {
+            pInstance->PSA_InitParams.SpectralDataBufferDuration = (LVM_UINT16)500;
+            pInstance->PSA_InitParams.MaxInputBlockSize = (LVM_UINT16)2048;
+            pInstance->PSA_InitParams.nBands = (LVM_UINT16)9;
+            pInstance->PSA_InitParams.pFiltersParams = &FiltersParams[0];
+            for (i = 0; i < pInstance->PSA_InitParams.nBands; i++) {
+                FiltersParams[i].CenterFrequency = (LVM_UINT16)1000;
+                FiltersParams[i].QFactor = (LVM_UINT16)100;
+                FiltersParams[i].PostGain = (LVM_INT16)0;
             }
 
-            /*Get the memory requirements and then set the address pointers*/
-            PSA_Status = LVPSA_Memory (hPSAInstance,
-                                          &PSA_MemTab,
-                                          &pInstance->PSA_InitParams);
-
-            if (PSA_Status != LVPSA_OK)
-            {
-                return((LVM_ReturnStatus_en) LVM_ALGORITHMPSA);
-            }
-
-            /* Slow Data */
-            PSA_MemTab.Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_SLOW_DATA],
-                PSA_MemTab.Region[LVM_PERSISTENT_SLOW_DATA].Size);
-
-            /* Fast Data */
-            PSA_MemTab.Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_DATA],
-                PSA_MemTab.Region[LVM_PERSISTENT_FAST_DATA].Size);
-
-            /* Fast Coef */
-            PSA_MemTab.Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_PERSISTENT_FAST_COEF],
-                PSA_MemTab.Region[LVM_PERSISTENT_FAST_COEF].Size);
-
-            /* Fast Temporary */
-            pInstance->pPSAInput = (LVM_FLOAT *)InstAlloc_AddMember(&AllocMem[LVM_TEMPORARY_FAST],
-                                                       (LVM_UINT32) MAX_INTERNAL_BLOCKSIZE * \
-                                                       sizeof(LVM_FLOAT));
-            PSA_MemTab.Region[LVM_TEMPORARY_FAST].pBaseAddress       = (void *)InstAlloc_AddMember(&AllocMem[LVM_MEMREGION_TEMPORARY_FAST],0);
-
             /*Initialise PSA instance and save the instance handle*/
             pInstance->PSA_ControlParams.Fs = LVM_FS_48000;
-            pInstance->PSA_ControlParams.LevelDetectionSpeed  = LVPSA_SPEED_MEDIUM;
-            PSA_Status = LVPSA_Init (&hPSAInstance,
-                                    &pInstance->PSA_InitParams,
-                                    &pInstance->PSA_ControlParams,
-                                    &PSA_MemTab);
+            pInstance->PSA_ControlParams.LevelDetectionSpeed = LVPSA_SPEED_MEDIUM;
+            pInstance->pPSAInput = (LVM_FLOAT*)calloc(MAX_INTERNAL_BLOCKSIZE, sizeof(LVM_FLOAT));
+            if (pInstance->pPSAInput == LVM_NULL) {
+                return LVM_NULLADDRESS;
+            }
+            PSA_Status = LVPSA_Init(&hPSAInstance, &pInstance->PSA_InitParams,
+                                    &pInstance->PSA_ControlParams, pInstance->pScratch);
 
-            if (PSA_Status != LVPSA_OK)
-            {
-                return((LVM_ReturnStatus_en) LVM_ALGORITHMPSA);
+            if (PSA_Status != LVPSA_OK) {
+                return ((LVM_ReturnStatus_en)LVM_ALGORITHMPSA);
             }
 
-            pInstance->hPSAInstance = hPSAInstance;       /* Save the instance handle */
+            pInstance->hPSAInstance = hPSAInstance; /* Save the instance handle */
             pInstance->PSA_GainOffset = 0;
-        }
-        else
-        {
+        } else {
             pInstance->hPSAInstance = LVM_NULL;
         }
 
         /*
          * Set the initialisation parameters.
          */
-        pInstance->Params.PSA_PeakDecayRate   = LVM_PSA_SPEED_MEDIUM;
-        pInstance->Params.PSA_Enable          = LVM_PSA_OFF;
+        pInstance->Params.PSA_PeakDecayRate = LVM_PSA_SPEED_MEDIUM;
+        pInstance->Params.PSA_Enable = LVM_PSA_OFF;
     }
 
     /*
@@ -992,20 +435,113 @@
     pInstance->ConfigurationNumber += LVM_VC_MASK;
     pInstance->ConfigurationNumber += LVM_PSA_MASK;
 
-    if(((pInstance->ConfigurationNumber  & LVM_CS_MASK)!=0)  ||
-        ((pInstance->ConfigurationNumber & LVM_DBE_MASK)!=0) ||
-        ((pInstance->ConfigurationNumber & LVM_EQNB_MASK)!=0)||
-        ((pInstance->ConfigurationNumber & LVM_TE_MASK)!=0)  ||
-        ((pInstance->ConfigurationNumber & LVM_VC_MASK)!=0))
-    {
-        pInstance->BlickSizeMultiple    = 4;
-    }
-    else
-    {
-        pInstance->BlickSizeMultiple    = 1;
+    if (((pInstance->ConfigurationNumber & LVM_CS_MASK) != 0) ||
+        ((pInstance->ConfigurationNumber & LVM_DBE_MASK) != 0) ||
+        ((pInstance->ConfigurationNumber & LVM_EQNB_MASK) != 0) ||
+        ((pInstance->ConfigurationNumber & LVM_TE_MASK) != 0) ||
+        ((pInstance->ConfigurationNumber & LVM_VC_MASK) != 0)) {
+        pInstance->BlickSizeMultiple = 4;
+    } else {
+        pInstance->BlickSizeMultiple = 1;
     }
 
-    return(Status);
+    return (Status);
+}
+/****************************************************************************************/
+/*                                                                                      */
+/* FUNCTION:                LVM_DelInstanceHandle                                       */
+/*                                                                                      */
+/* DESCRIPTION:                                                                         */
+/*  This function is used to create a bundle instance. It returns the created instance  */
+/*  handle through phInstance. All parameters are set to their default, inactive state. */
+/*                                                                                      */
+/* PARAMETERS:                                                                          */
+/*  phInstance              Pointer to the instance handle                              */
+/*                                                                                      */
+/* NOTES:                                                                               */
+/*  1. This function must not be interrupted by the LVM_Process function                */
+/*                                                                                      */
+/****************************************************************************************/
+void LVM_DelInstanceHandle(LVM_Handle_t* phInstance) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)*phInstance;
+
+    if (pInstance->pScratch != LVM_NULL) {
+        free(pInstance->pScratch);
+        pInstance->pScratch = LVM_NULL;
+    }
+
+    if (pInstance->InstParams.BufferMode == LVM_MANAGED_BUFFERS) {
+        /*
+         * Managed buffers required
+         */
+        if (pInstance->pBufferManagement != LVM_NULL) {
+            free(pInstance->pBufferManagement);
+            pInstance->pBufferManagement = LVM_NULL;
+        }
+    }
+
+    /*
+     * Treble Enhancement
+     */
+
+    /*
+     * Free the default EQNB pre-gain and pointer to the band definitions
+     */
+    if (pInstance->pEQNB_BandDefs != LVM_NULL) {
+        free(pInstance->pEQNB_BandDefs);
+        pInstance->pEQNB_BandDefs = LVM_NULL;
+    }
+    if (pInstance->pEQNB_UserDefs != LVM_NULL) {
+        free(pInstance->pEQNB_UserDefs);
+        pInstance->pEQNB_UserDefs = LVM_NULL;
+    }
+
+    /*
+     * De-initialise the Concert Sound module
+     */
+    if (pInstance->hCSInstance != LVM_NULL) {
+        LVCS_DeInit(&pInstance->hCSInstance);
+    }
+
+    /*
+     * De-initialise the Bass Enhancement module
+     */
+    if (pInstance->hDBEInstance != LVM_NULL) {
+        LVDBE_DeInit(&pInstance->hDBEInstance);
+    }
+
+    /*
+     * De-initialise the N-Band Equaliser module
+     */
+    if (pInstance->hEQNBInstance != LVM_NULL) {
+        LVEQNB_DeInit(&pInstance->hEQNBInstance);
+    }
+
+    /*
+     * Free Headroom management memory.
+     */
+    if (pInstance->pHeadroom_BandDefs != LVM_NULL) {
+        free(pInstance->pHeadroom_BandDefs);
+        pInstance->pHeadroom_BandDefs = LVM_NULL;
+    }
+    if (pInstance->pHeadroom_UserDefs != LVM_NULL) {
+        free(pInstance->pHeadroom_UserDefs);
+        pInstance->pHeadroom_UserDefs = LVM_NULL;
+    }
+
+    /*
+     * De-initialise the PSA module
+     */
+    if (pInstance->hPSAInstance != LVM_NULL) {
+        LVPSA_DeInit(&pInstance->hPSAInstance);
+    }
+    if (pInstance->pPSAInput != LVM_NULL) {
+        free(pInstance->pPSAInput);
+        pInstance->pPSAInput = LVM_NULL;
+    }
+
+    delete pInstance;
+    return;
 }
 
 /****************************************************************************************/
@@ -1027,48 +563,36 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVM_ReturnStatus_en LVM_ClearAudioBuffers(LVM_Handle_t  hInstance)
-{
-    LVM_MemTab_t            MemTab;                                     /* Memory table */
-    LVM_InstParams_t        InstParams;                                 /* Instance parameters */
-    LVM_ControlParams_t     Params;                                     /* Control Parameters */
-    LVM_Instance_t          *pInstance  = (LVM_Instance_t  *)hInstance; /* Pointer to Instance */
-    LVM_HeadroomParams_t    HeadroomParams;
+LVM_ReturnStatus_en LVM_ClearAudioBuffers(LVM_Handle_t hInstance) {
+    LVM_InstParams_t InstParams;                            /* Instance parameters */
+    LVM_ControlParams_t Params;                             /* Control Parameters */
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance; /* Pointer to Instance */
+    LVM_HeadroomParams_t HeadroomParams;
 
-    if(hInstance == LVM_NULL){
+    if (hInstance == LVM_NULL) {
         return LVM_NULLADDRESS;
     }
 
-    /* Save the control parameters */ /* coverity[unchecked_value] */ /* Do not check return value internal function calls */
+    /* Save the control parameters */ /* coverity[unchecked_value] */ /* Do not check return value
+                                                                         internal function calls */
     LVM_GetControlParameters(hInstance, &Params);
 
     /*Save the headroom parameters*/
     LVM_GetHeadroomParams(hInstance, &HeadroomParams);
 
-    /*  Retrieve allocated buffers in memtab */
-    LVM_GetMemoryTable(hInstance, &MemTab,  LVM_NULL);
-
     /*  Save the instance parameters */
     InstParams = pInstance->InstParams;
 
     /*  Call  LVM_GetInstanceHandle to re-initialise the bundle */
-    LVM_GetInstanceHandle( &hInstance,
-                           &MemTab,
-                           &InstParams);
-
-    /* Restore control parameters */ /* coverity[unchecked_value] */ /* Do not check return value internal function calls */
+    /* Restore control parameters */ /* coverity[unchecked_value] */ /* Do not check return value
+                                                                        internal function calls */
     LVM_SetControlParameters(hInstance, &Params);
 
     /*Restore the headroom parameters*/
     LVM_SetHeadroomParams(hInstance, &HeadroomParams);
 
     /* DC removal filter */
-#ifdef SUPPORT_MC
     DC_Mc_D16_TRC_WRA_01_Init(&pInstance->DC_RemovalInstance);
-#else
-    DC_2I_D16_TRC_WRA_01_Init(&pInstance->DC_RemovalInstance);
-#endif
 
     return LVM_SUCCESS;
 }
-
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Private.h b/media/libeffects/lvm/lib/Bundle/src/LVM_Private.h
index ddaac99..63c83c0 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Private.h
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Private.h
@@ -33,14 +33,15 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#include "LVM.h"                                /* LifeVibes */
-#include "LVM_Common.h"                         /* LifeVibes common */
-#include "BIQUAD.h"                             /* Biquad library */
-#include "LVC_Mixer.h"                          /* Mixer library */
-#include "LVCS_Private.h"                       /* Concert Sound */
-#include "LVDBE_Private.h"                      /* Dynamic Bass Enhancement */
-#include "LVEQNB_Private.h"                     /* N-Band equaliser */
-#include "LVPSA_Private.h"                      /* Parametric Spectrum Analyzer */
+#include <audio_utils/BiquadFilter.h>
+#include "LVM.h"            /* LifeVibes */
+#include "LVM_Common.h"     /* LifeVibes common */
+#include "BIQUAD.h"         /* Biquad library */
+#include "LVC_Mixer.h"      /* Mixer library */
+#include "LVCS_Private.h"   /* Concert Sound */
+#include "LVDBE_Private.h"  /* Dynamic Bass Enhancement */
+#include "LVEQNB_Private.h" /* N-Band equaliser */
+#include "LVPSA_Private.h"  /* Parametric Spectrum Analyzer */
 
 /************************************************************************************/
 /*                                                                                  */
@@ -49,63 +50,64 @@
 /************************************************************************************/
 
 /* General */
-#define LVM_INVALID                     0xFFFF    /* Invalid init parameter */
+#define LVM_INVALID 0xFFFF /* Invalid init parameter */
 
 /* Memory */
-#define LVM_INSTANCE_ALIGN              4         /* 32-bit for structures */
-#define LVM_FIRSTCALL                   0         /* First call to the buffer */
-#define LVM_MAXBLOCKCALL                1         /* Maximum block size calls to the buffer */
-#define LVM_LASTCALL                    2         /* Last call to the buffer */
-#define LVM_FIRSTLASTCALL               3         /* Single call for small number of samples */
+#define LVM_INSTANCE_ALIGN 4 /* 32-bit for structures */
+#define LVM_FIRSTCALL 0      /* First call to the buffer */
+#define LVM_MAXBLOCKCALL 1   /* Maximum block size calls to the buffer */
+#define LVM_LASTCALL 2       /* Last call to the buffer */
+#define LVM_FIRSTLASTCALL 3  /* Single call for small number of samples */
 
 /* Block Size */
-#define LVM_MIN_MAXBLOCKSIZE            16        /* Minimum MaxBlockSize Limit*/
-#define LVM_MANAGED_MAX_MAXBLOCKSIZE    8191      /* Maximum MaxBlockSzie Limit for Managed Buffer Mode*/
-#define LVM_UNMANAGED_MAX_MAXBLOCKSIZE  4096      /* Maximum MaxBlockSzie Limit for Unmanaged Buffer Mode */
+#define LVM_MIN_MAXBLOCKSIZE 16           /* Minimum MaxBlockSize Limit*/
+#define LVM_MANAGED_MAX_MAXBLOCKSIZE 8191 /* Maximum MaxBlockSzie Limit for Managed Buffer Mode*/
+#define LVM_UNMANAGED_MAX_MAXBLOCKSIZE \
+    4096 /* Maximum MaxBlockSzie Limit for Unmanaged Buffer Mode */
 
-#define MAX_INTERNAL_BLOCKSIZE          8128      /* Maximum multiple of 64  below 8191*/
+#define MAX_INTERNAL_BLOCKSIZE 8128 /* Maximum multiple of 64  below 8191*/
 
-#define MIN_INTERNAL_BLOCKSIZE          16        /* Minimum internal block size */
-#define MIN_INTERNAL_BLOCKSHIFT         4         /* Minimum internal block size as a power of 2 */
-#define MIN_INTERNAL_BLOCKMASK          0xFFF0    /* Minimum internal block size mask */
+#define MIN_INTERNAL_BLOCKSIZE 16     /* Minimum internal block size */
+#define MIN_INTERNAL_BLOCKSHIFT 4     /* Minimum internal block size as a power of 2 */
+#define MIN_INTERNAL_BLOCKMASK 0xFFF0 /* Minimum internal block size mask */
 
-#define LVM_PSA_DYNAMICRANGE            60        /* Spectral Dynamic range: used for offseting output*/
-#define LVM_PSA_BARHEIGHT               127       /* Spectral Bar Height*/
+#define LVM_PSA_DYNAMICRANGE 60 /* Spectral Dynamic range: used for offseting output*/
+#define LVM_PSA_BARHEIGHT 127   /* Spectral Bar Height*/
 
-#define LVM_TE_MIN_EFFECTLEVEL          0         /*TE Minimum EffectLevel*/
-#define LVM_TE_MAX_EFFECTLEVEL          15        /*TE Maximum Effect level*/
+#define LVM_TE_MIN_EFFECTLEVEL 0  /*TE Minimum EffectLevel*/
+#define LVM_TE_MAX_EFFECTLEVEL 15 /*TE Maximum Effect level*/
 
-#define LVM_VC_MIN_EFFECTLEVEL          (-96)     /*VC Minimum EffectLevel*/
-#define LVM_VC_MAX_EFFECTLEVEL          0         /*VC Maximum Effect level*/
+#define LVM_VC_MIN_EFFECTLEVEL (-96) /*VC Minimum EffectLevel*/
+#define LVM_VC_MAX_EFFECTLEVEL 0     /*VC Maximum Effect level*/
 
-#define LVM_BE_MIN_EFFECTLEVEL          0         /*BE Minimum EffectLevel*/
-#define LVM_BE_MAX_EFFECTLEVEL          15        /*BE Maximum Effect level*/
+#define LVM_BE_MIN_EFFECTLEVEL 0  /*BE Minimum EffectLevel*/
+#define LVM_BE_MAX_EFFECTLEVEL 15 /*BE Maximum Effect level*/
 
-#define LVM_EQNB_MIN_BAND_FREQ          20        /*EQNB Minimum Band Frequency*/
-#define LVM_EQNB_MAX_BAND_FREQ          24000     /*EQNB Maximum Band Frequency*/
-#define LVM_EQNB_MIN_BAND_GAIN          (-15)     /*EQNB Minimum Band Frequency*/
-#define LVM_EQNB_MAX_BAND_GAIN          15        /*EQNB Maximum Band Frequency*/
-#define LVM_EQNB_MIN_QFACTOR            25        /*EQNB Minimum Q Factor*/
-#define LVM_EQNB_MAX_QFACTOR            1200      /*EQNB Maximum Q Factor*/
-#define LVM_EQNB_MIN_LPF_FREQ           1000      /*EQNB Minimum Low Pass Corner frequency*/
-#define LVM_EQNB_MIN_HPF_FREQ           20        /*EQNB Minimum High Pass Corner frequency*/
-#define LVM_EQNB_MAX_HPF_FREQ           1000      /*EQNB Maximum High Pass Corner frequency*/
+#define LVM_EQNB_MIN_BAND_FREQ 20    /*EQNB Minimum Band Frequency*/
+#define LVM_EQNB_MAX_BAND_FREQ 24000 /*EQNB Maximum Band Frequency*/
+#define LVM_EQNB_MIN_BAND_GAIN (-15) /*EQNB Minimum Band Frequency*/
+#define LVM_EQNB_MAX_BAND_GAIN 15    /*EQNB Maximum Band Frequency*/
+#define LVM_EQNB_MIN_QFACTOR 25      /*EQNB Minimum Q Factor*/
+#define LVM_EQNB_MAX_QFACTOR 1200    /*EQNB Maximum Q Factor*/
+#define LVM_EQNB_MIN_LPF_FREQ 1000   /*EQNB Minimum Low Pass Corner frequency*/
+#define LVM_EQNB_MIN_HPF_FREQ 20     /*EQNB Minimum High Pass Corner frequency*/
+#define LVM_EQNB_MAX_HPF_FREQ 1000   /*EQNB Maximum High Pass Corner frequency*/
 
-#define LVM_CS_MIN_EFFECT_LEVEL         0         /*CS Minimum Effect Level*/
-#define LVM_CS_MAX_REVERB_LEVEL         100       /*CS Maximum Reverb Level*/
-#define LVM_VIRTUALIZER_MAX_REVERB_LEVEL 100      /*Vitrualizer Maximum Reverb Level*/
+#define LVM_CS_MIN_EFFECT_LEVEL 0            /*CS Minimum Effect Level*/
+#define LVM_CS_MAX_REVERB_LEVEL 100          /*CS Maximum Reverb Level*/
+#define LVM_VIRTUALIZER_MAX_REVERB_LEVEL 100 /*Vitrualizer Maximum Reverb Level*/
 
-#define LVM_VC_MIXER_TIME              100       /*VC mixer time*/
-#define LVM_VC_BALANCE_MAX             96        /*VC balance max value*/
-#define LVM_VC_BALANCE_MIN             (-96)     /*VC balance min value*/
+#define LVM_VC_MIXER_TIME 100    /*VC mixer time*/
+#define LVM_VC_BALANCE_MAX 96    /*VC balance max value*/
+#define LVM_VC_BALANCE_MIN (-96) /*VC balance min value*/
 
 /* Algorithm masks */
-#define LVM_CS_MASK                     1
-#define LVM_EQNB_MASK                   2
-#define LVM_DBE_MASK                    4
-#define LVM_VC_MASK                     16
-#define LVM_TE_MASK                     32
-#define LVM_PSA_MASK                    2048
+#define LVM_CS_MASK 1
+#define LVM_EQNB_MASK 2
+#define LVM_DBE_MASK 4
+#define LVM_VC_MASK 16
+#define LVM_TE_MASK 32
+#define LVM_PSA_MASK 2048
 
 /************************************************************************************/
 /*                                                                                  */
@@ -113,133 +115,93 @@
 /*                                                                                  */
 /************************************************************************************/
 
-/* Memory region definition */
-typedef struct
-{
-    LVM_UINT32              Size;               /* Region size in bytes */
-    LVM_UINT16              Alignment;          /* Byte alignment */
-    LVM_MemoryTypes_en      Type;               /* Region type */
-    void                    *pBaseAddress;      /* Pointer to the region base address */
-} LVM_IntMemoryRegion_t;
-
-/* Memory table containing the region definitions */
-typedef struct
-{
-    LVM_IntMemoryRegion_t   Region[LVM_NR_MEMORY_REGIONS];  /* One definition for each region */
-} LVM_IntMemTab_t;
-
 /* Buffer Management */
-typedef struct
-{
-    LVM_FLOAT               *pScratch;          /* Bundle scratch buffer */
+typedef struct {
+    LVM_FLOAT* pScratch; /* Bundle scratch buffer */
 
-    LVM_INT16               BufferState;        /* Buffer status */
-#ifdef SUPPORT_MC
-    LVM_FLOAT               InDelayBuffer[3 * LVM_MAX_CHANNELS * MIN_INTERNAL_BLOCKSIZE];
-#else
-    LVM_FLOAT               InDelayBuffer[6 * MIN_INTERNAL_BLOCKSIZE]; /* Input buffer delay line, \
-                                                                           left and right */
-#endif
-    LVM_INT16               InDelaySamples;     /* Number of samples in the input delay buffer */
-#ifdef SUPPORT_MC
-    LVM_FLOAT               OutDelayBuffer[LVM_MAX_CHANNELS * MIN_INTERNAL_BLOCKSIZE];
-#else
-    LVM_FLOAT               OutDelayBuffer[2 * MIN_INTERNAL_BLOCKSIZE]; /* Output buffer delay \
-                                                                                      line */
-#endif
-    LVM_INT16               OutDelaySamples;    /* Number of samples in the output delay buffer, \
-                                                                             left and right */
-    LVM_INT16               SamplesToOutput;    /* Samples to write to the output */
+    LVM_INT16 BufferState; /* Buffer status */
+    LVM_FLOAT InDelayBuffer[3 * LVM_MAX_CHANNELS * MIN_INTERNAL_BLOCKSIZE];
+    LVM_INT16 InDelaySamples; /* Number of samples in the input delay buffer */
+    LVM_FLOAT OutDelayBuffer[LVM_MAX_CHANNELS * MIN_INTERNAL_BLOCKSIZE];
+    LVM_INT16 OutDelaySamples; /* Number of samples in the output delay buffer, \
+                                                            left and right */
+    LVM_INT16 SamplesToOutput; /* Samples to write to the output */
 } LVM_Buffer_t;
 
-/* Filter taps */
-typedef struct
-{
-    Biquad_2I_Order1_FLOAT_Taps_t TrebleBoost_Taps;   /* Treble boost Taps */
-} LVM_TE_Data_t;
 
-/* Coefficients */
-typedef struct
-{
-    Biquad_FLOAT_Instance_t       TrebleBoost_State;  /* State for the treble boost filter */
-} LVM_TE_Coefs_t;
-
-typedef struct
-{
+typedef struct {
     /* Public parameters */
-    LVM_MemTab_t            MemoryTable;        /* Instance memory allocation table */
-    LVM_ControlParams_t     Params;             /* Control parameters */
-    LVM_InstParams_t        InstParams;         /* Instance parameters */
+    LVM_ControlParams_t Params;  /* Control parameters */
+    LVM_InstParams_t InstParams; /* Instance parameters */
 
     /* Private parameters */
-    LVM_UINT16              ControlPending;     /* Control flag to indicate update pending */
-    LVM_ControlParams_t     NewParams;          /* New control parameters pending update */
+    LVM_UINT16 ControlPending;     /* Control flag to indicate update pending */
+    LVM_ControlParams_t NewParams; /* New control parameters pending update */
 
     /* Buffer control */
-    LVM_INT16               InternalBlockSize;  /* Maximum internal block size */
-    LVM_Buffer_t            *pBufferManagement; /* Buffer management variables */
-    LVM_INT16               SamplesToProcess;   /* Input samples left to process */
-    LVM_FLOAT               *pInputSamples;     /* External input sample pointer */
-    LVM_FLOAT               *pOutputSamples;    /* External output sample pointer */
+    LVM_INT16 InternalBlockSize;     /* Maximum internal block size */
+    LVM_Buffer_t* pBufferManagement; /* Buffer management variables */
+    LVM_INT16 SamplesToProcess;      /* Input samples left to process */
+    LVM_FLOAT* pInputSamples;        /* External input sample pointer */
+    LVM_FLOAT* pOutputSamples;       /* External output sample pointer */
 
     /* Configuration number */
-    LVM_INT32               ConfigurationNumber;
-    LVM_INT32               BlickSizeMultiple;
+    LVM_INT32 ConfigurationNumber;
+    LVM_INT32 BlickSizeMultiple;
 
     /* DC removal */
-    Biquad_FLOAT_Instance_t       DC_RemovalInstance; /* DC removal filter instance */
+    Biquad_FLOAT_Instance_t DC_RemovalInstance; /* DC removal filter instance */
 
     /* Concert Sound */
-    LVCS_Handle_t           hCSInstance;        /* Concert Sound instance handle */
-    LVCS_Instance_t         CS_Instance;        /* Concert Sound instance */
-    LVM_INT16               CS_Active;          /* Control flag */
+    LVCS_Handle_t hCSInstance;   /* Concert Sound instance handle */
+    LVCS_Instance_t CS_Instance; /* Concert Sound instance */
+    LVM_INT16 CS_Active;         /* Control flag */
 
     /* Equalizer */
-    LVEQNB_Handle_t         hEQNBInstance;      /* N-Band Equaliser instance handle */
-    LVEQNB_Instance_t       EQNB_Instance;      /* N-Band Equaliser instance */
-    LVM_EQNB_BandDef_t      *pEQNB_BandDefs;    /* Local storage for new definitions */
-    LVM_EQNB_BandDef_t      *pEQNB_UserDefs;    /* Local storage for the user's definitions */
-    LVM_INT16               EQNB_Active;        /* Control flag */
+    LVEQNB_Handle_t hEQNBInstance;      /* N-Band Equaliser instance handle */
+    LVEQNB_Instance_t EQNB_Instance;    /* N-Band Equaliser instance */
+    LVM_EQNB_BandDef_t* pEQNB_BandDefs; /* Local storage for new definitions */
+    LVM_EQNB_BandDef_t* pEQNB_UserDefs; /* Local storage for the user's definitions */
+    LVM_INT16 EQNB_Active;              /* Control flag */
 
     /* Dynamic Bass Enhancement */
-    LVDBE_Handle_t          hDBEInstance;       /* Dynamic Bass Enhancement instance handle */
-    LVDBE_Instance_t        DBE_Instance;       /* Dynamic Bass Enhancement instance */
-    LVM_INT16               DBE_Active;         /* Control flag */
+    LVDBE_Handle_t hDBEInstance;   /* Dynamic Bass Enhancement instance handle */
+    LVDBE_Instance_t DBE_Instance; /* Dynamic Bass Enhancement instance */
+    LVM_INT16 DBE_Active;          /* Control flag */
 
     /* Volume Control */
-    LVMixer3_1St_FLOAT_st   VC_Volume;          /* Volume scaler */
-    LVMixer3_2St_FLOAT_st         VC_BalanceMix;      /* VC balance mixer */
-    LVM_INT16               VC_VolumedB;        /* Gain in dB */
-    LVM_INT16               VC_Active;          /* Control flag */
-    LVM_INT16               VC_AVLFixedVolume;  /* AVL fixed volume */
+    LVMixer3_1St_FLOAT_st VC_Volume;     /* Volume scaler */
+    LVMixer3_2St_FLOAT_st VC_BalanceMix; /* VC balance mixer */
+    LVM_INT16 VC_VolumedB;               /* Gain in dB */
+    LVM_INT16 VC_Active;                 /* Control flag */
+    LVM_INT16 VC_AVLFixedVolume;         /* AVL fixed volume */
 
     /* Treble Enhancement */
-    LVM_TE_Data_t           *pTE_Taps;          /* Treble boost Taps */
-    LVM_TE_Coefs_t          *pTE_State;         /* State for the treble boost filter */
-    LVM_INT16               TE_Active;          /* Control flag */
+    std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            pTEBiquad; /* Biquad filter instance */
+    LVM_INT16 TE_Active;       /* Control flag */
 
     /* Headroom */
-    LVM_HeadroomParams_t    NewHeadroomParams;   /* New headroom parameters pending update */
-    LVM_HeadroomParams_t    HeadroomParams;      /* Headroom parameters */
-    LVM_HeadroomBandDef_t   *pHeadroom_BandDefs; /* Local storage for new definitions */
-    LVM_HeadroomBandDef_t   *pHeadroom_UserDefs; /* Local storage for the user's definitions */
-    LVM_UINT16              Headroom;            /* Value of the current headroom */
+    LVM_HeadroomParams_t NewHeadroomParams;    /* New headroom parameters pending update */
+    LVM_HeadroomParams_t HeadroomParams;       /* Headroom parameters */
+    LVM_HeadroomBandDef_t* pHeadroom_BandDefs; /* Local storage for new definitions */
+    LVM_HeadroomBandDef_t* pHeadroom_UserDefs; /* Local storage for the user's definitions */
+    LVM_UINT16 Headroom;                       /* Value of the current headroom */
 
     /* Spectrum Analyzer */
-    pLVPSA_Handle_t         hPSAInstance;       /* Spectrum Analyzer instance handle */
-    LVPSA_InstancePr_t      PSA_Instance;       /* Spectrum Analyzer instance */
-    LVPSA_InitParams_t      PSA_InitParams;     /* Spectrum Analyzer initialization parameters */
-    LVPSA_ControlParams_t   PSA_ControlParams;  /* Spectrum Analyzer control parameters */
-    LVM_INT16               PSA_GainOffset;     /* Tone control flag */
-    LVM_Callback            CallBack;
-    LVM_FLOAT               *pPSAInput;         /* PSA input pointer */
+    pLVPSA_Handle_t hPSAInstance;            /* Spectrum Analyzer instance handle */
+    LVPSA_InstancePr_t PSA_Instance;         /* Spectrum Analyzer instance */
+    LVPSA_InitParams_t PSA_InitParams;       /* Spectrum Analyzer initialization parameters */
+    LVPSA_ControlParams_t PSA_ControlParams; /* Spectrum Analyzer control parameters */
+    LVM_INT16 PSA_GainOffset;                /* Tone control flag */
+    LVM_Callback CallBack;
+    LVM_FLOAT* pPSAInput; /* PSA input pointer */
 
-    LVM_INT16              NoSmoothVolume;      /* Enable or disable smooth volume changes*/
+    LVM_INT16 NoSmoothVolume; /* Enable or disable smooth volume changes*/
 
-#ifdef SUPPORT_MC
-    LVM_INT16              NrChannels;
-    LVM_INT32              ChMask;
-#endif
+    LVM_INT16 NrChannels;
+    LVM_INT32 ChMask;
+    void* pScratch; /* Pointer to bundle scratch buffer*/
 
 } LVM_Instance_t;
 
@@ -249,32 +211,19 @@
 /*                                                                                  */
 /************************************************************************************/
 
-LVM_ReturnStatus_en LVM_ApplyNewSettings(LVM_Handle_t       hInstance);
+LVM_ReturnStatus_en LVM_ApplyNewSettings(LVM_Handle_t hInstance);
 
-void    LVM_SetTrebleBoost( LVM_Instance_t         *pInstance,
-                            LVM_ControlParams_t    *pParams);
+void LVM_SetTrebleBoost(LVM_Instance_t* pInstance, LVM_ControlParams_t* pParams);
 
-void    LVM_SetVolume(  LVM_Instance_t         *pInstance,
-                        LVM_ControlParams_t    *pParams);
+void LVM_SetVolume(LVM_Instance_t* pInstance, LVM_ControlParams_t* pParams);
 
-LVM_INT32    LVM_VCCallBack(void*   pBundleHandle,
-                            void*   pGeneralPurpose,
-                            short   CallBackParam);
+LVM_INT32 LVM_VCCallBack(void* pBundleHandle, void* pGeneralPurpose, short CallBackParam);
 
-void    LVM_SetHeadroom(    LVM_Instance_t         *pInstance,
-                            LVM_ControlParams_t    *pParams);
-void    LVM_BufferIn(   LVM_Handle_t      hInstance,
-                        const LVM_FLOAT   *pInData,
-                        LVM_FLOAT         **pToProcess,
-                        LVM_FLOAT         **pProcessed,
-                        LVM_UINT16        *pNumSamples);
-void    LVM_BufferOut(  LVM_Handle_t     hInstance,
-                        LVM_FLOAT        *pOutData,
-                        LVM_UINT16       *pNumSamples);
+void LVM_SetHeadroom(LVM_Instance_t* pInstance, LVM_ControlParams_t* pParams);
+void LVM_BufferIn(LVM_Handle_t hInstance, const LVM_FLOAT* pInData, LVM_FLOAT** pToProcess,
+                  LVM_FLOAT** pProcessed, LVM_UINT16* pNumSamples);
+void LVM_BufferOut(LVM_Handle_t hInstance, LVM_FLOAT* pOutData, LVM_UINT16* pNumSamples);
 
-LVM_INT32 LVM_AlgoCallBack(     void          *pBundleHandle,
-                                void          *pData,
-                                LVM_INT16     callbackId);
+LVM_INT32 LVM_AlgoCallBack(void* pBundleHandle, void* pData, LVM_INT16 callbackId);
 
-#endif      /* __LVM_PRIVATE_H__ */
-
+#endif /* __LVM_PRIVATE_H__ */
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Process.cpp b/media/libeffects/lvm/lib/Bundle/src/LVM_Process.cpp
index dc86cfd..20058a1 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Process.cpp
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Process.cpp
@@ -51,279 +51,163 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_ReturnStatus_en LVM_Process(LVM_Handle_t                hInstance,
-                                const LVM_FLOAT             *pInData,
-                                LVM_FLOAT                   *pOutData,
-                                LVM_UINT16                  NumSamples,
-                                LVM_UINT32                  AudioTime)
-{
-
-    LVM_Instance_t      *pInstance  = (LVM_Instance_t  *)hInstance;
-    LVM_UINT16          SampleCount = NumSamples;
-    LVM_FLOAT           *pInput     = (LVM_FLOAT *)pInData;
-    LVM_FLOAT           *pToProcess = (LVM_FLOAT *)pInData;
-    LVM_FLOAT           *pProcessed = pOutData;
-    LVM_ReturnStatus_en  Status;
-#ifdef SUPPORT_MC
-    LVM_INT32           NrChannels  = pInstance->NrChannels;
-    LVM_INT32           ChMask      = pInstance->ChMask;
+LVM_ReturnStatus_en LVM_Process(LVM_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                LVM_FLOAT* pOutData, LVM_UINT16 NumSamples, LVM_UINT32 AudioTime) {
+    LVM_Instance_t* pInstance = (LVM_Instance_t*)hInstance;
+    LVM_UINT16 SampleCount = NumSamples;
+    LVM_FLOAT* pInput = (LVM_FLOAT*)pInData;
+    LVM_FLOAT* pToProcess = (LVM_FLOAT*)pInData;
+    LVM_FLOAT* pProcessed = pOutData;
+    LVM_ReturnStatus_en Status;
+    LVM_INT32 NrChannels = pInstance->NrChannels;
+    LVM_INT32 ChMask = pInstance->ChMask;
 #define NrFrames SampleCount  // alias for clarity
-#endif
 
     /*
      * Check if the number of samples is zero
      */
-    if (NumSamples == 0)
-    {
-        return(LVM_SUCCESS);
+    if (NumSamples == 0) {
+        return (LVM_SUCCESS);
     }
 
     /*
      * Check valid points have been given
      */
-    if ((hInstance == LVM_NULL) || (pInData == LVM_NULL) || (pOutData == LVM_NULL))
-    {
+    if ((hInstance == LVM_NULL) || (pInData == LVM_NULL) || (pOutData == LVM_NULL)) {
         return (LVM_NULLADDRESS);
     }
 
     /*
      * For unmanaged mode only
      */
-    if(pInstance->InstParams.BufferMode == LVM_UNMANAGED_BUFFERS)
-    {
-         /*
+    if (pInstance->InstParams.BufferMode == LVM_UNMANAGED_BUFFERS) {
+        /*
          * Check if the number of samples is a good multiple (unmanaged mode only)
          */
-        if((NumSamples % pInstance->BlickSizeMultiple) != 0)
-        {
-            return(LVM_INVALIDNUMSAMPLES);
+        if ((NumSamples % pInstance->BlickSizeMultiple) != 0) {
+            return (LVM_INVALIDNUMSAMPLES);
         }
 
         /*
          * Check the buffer alignment
          */
-        if((((uintptr_t)pInData % 4) != 0) || (((uintptr_t)pOutData % 4) != 0))
-        {
-            return(LVM_ALIGNMENTERROR);
+        if ((((uintptr_t)pInData % 4) != 0) || (((uintptr_t)pOutData % 4) != 0)) {
+            return (LVM_ALIGNMENTERROR);
         }
     }
 
     /*
      * Update new parameters if necessary
      */
-    if (pInstance->ControlPending == LVM_TRUE)
-    {
+    if (pInstance->ControlPending == LVM_TRUE) {
         Status = LVM_ApplyNewSettings(hInstance);
-#ifdef SUPPORT_MC
         /* Update the local variable NrChannels from pInstance->NrChannels value */
         NrChannels = pInstance->NrChannels;
-        ChMask     = pInstance->ChMask;
-#endif
+        ChMask = pInstance->ChMask;
 
-        if(Status != LVM_SUCCESS)
-        {
+        if (Status != LVM_SUCCESS) {
             return Status;
         }
     }
 
     /*
-     * Convert from Mono if necessary
-     */
-    if (pInstance->Params.SourceFormat == LVM_MONO)
-    {
-        MonoTo2I_Float(pInData,                                /* Source */
-                       pOutData,                               /* Destination */
-                       (LVM_INT16)NumSamples);                 /* Number of input samples */
-        pInput     = pOutData;
-        pToProcess = pOutData;
-#ifdef SUPPORT_MC
-        NrChannels = 2;
-        ChMask     = AUDIO_CHANNEL_OUT_STEREO;
-#endif
-    }
-
-    /*
      * Process the data with managed buffers
      */
-    while (SampleCount != 0)
-    {
+    while (SampleCount != 0) {
         /*
          * Manage the input buffer and frame processing
          */
-        LVM_BufferIn(hInstance,
-                     pInput,
-                     &pToProcess,
-                     &pProcessed,
-                     &SampleCount);
+        LVM_BufferIn(hInstance, pInput, &pToProcess, &pProcessed, &SampleCount);
 
         /*
          * Only process data when SampleCount is none zero, a zero count can occur when
          * the BufferIn routine is working in managed mode.
          */
-        if (SampleCount != 0)
-        {
+        if (SampleCount != 0) {
             /*
              * Apply ConcertSound if required
              */
-            if (pInstance->CS_Active == LVM_TRUE)
-            {
-                (void)LVCS_Process(pInstance->hCSInstance,     /* Concert Sound instance handle */
-                                   pToProcess,
-                                   pProcessed,
-                                   SampleCount);
+            if (pInstance->CS_Active == LVM_TRUE) {
+                (void)LVCS_Process(pInstance->hCSInstance, /* Concert Sound instance handle */
+                                   pToProcess, pProcessed, SampleCount);
                 pToProcess = pProcessed;
             }
 
             /*
              * Apply volume if required
              */
-            if (pInstance->VC_Active!=0)
-            {
-#ifdef SUPPORT_MC
-                LVC_MixSoft_Mc_D16C31_SAT(&pInstance->VC_Volume,
-                                       pToProcess,
-                                       pProcessed,
-                                       (LVM_INT16)(NrFrames),
-                                       NrChannels);
-#else
-                LVC_MixSoft_1St_D16C31_SAT(&pInstance->VC_Volume,
-                                       pToProcess,
-                                       pProcessed,
-                                       (LVM_INT16)(2 * SampleCount));     /* Left and right*/
-#endif
+            if (pInstance->VC_Active != 0) {
+                LVC_MixSoft_Mc_D16C31_SAT(&pInstance->VC_Volume, pToProcess, pProcessed,
+                                          (LVM_INT16)(NrFrames), NrChannels);
                 pToProcess = pProcessed;
             }
 
             /*
              * Call N-Band equaliser if enabled
              */
-            if (pInstance->EQNB_Active == LVM_TRUE)
-            {
-                LVEQNB_Process(pInstance->hEQNBInstance,    /* N-Band equaliser instance handle */
-                               pToProcess,
-                               pProcessed,
-                               SampleCount);
+            if (pInstance->EQNB_Active == LVM_TRUE) {
+                LVEQNB_Process(pInstance->hEQNBInstance, /* N-Band equaliser instance handle */
+                               pToProcess, pProcessed, SampleCount);
                 pToProcess = pProcessed;
             }
 
             /*
              * Call bass enhancement if enabled
              */
-            if (pInstance->DBE_Active == LVM_TRUE)
-            {
-                LVDBE_Process(pInstance->hDBEInstance,       /* Dynamic Bass Enhancement \
-                                                                instance handle */
-                              pToProcess,
-                              pProcessed,
-                              SampleCount);
+            if (pInstance->DBE_Active == LVM_TRUE) {
+                LVDBE_Process(pInstance->hDBEInstance, /* Dynamic Bass Enhancement \
+                                                          instance handle */
+                              pToProcess, pProcessed, SampleCount);
                 pToProcess = pProcessed;
             }
 
             /*
              * Bypass mode or everything off, so copy the input to the output
              */
-            if (pToProcess != pProcessed)
-            {
-#ifdef SUPPORT_MC
-                Copy_Float(pToProcess,                             /* Source */
-                           pProcessed,                             /* Destination */
-                           (LVM_INT16)(NrChannels * NrFrames));    /* Copy all samples */
-#else
-                Copy_Float(pToProcess,                             /* Source */
-                           pProcessed,                             /* Destination */
-                           (LVM_INT16)(2 * SampleCount));          /* Left and right */
-#endif
+            if (pToProcess != pProcessed) {
+                Copy_Float(pToProcess,                          /* Source */
+                           pProcessed,                          /* Destination */
+                           (LVM_INT16)(NrChannels * NrFrames)); /* Copy all samples */
             }
 
             /*
              * Apply treble boost if required
              */
-            if (pInstance->TE_Active == LVM_TRUE)
-            {
+            if (pInstance->TE_Active == LVM_TRUE) {
                 /*
                  * Apply the filter
                  */
-#ifdef SUPPORT_MC
-                FO_Mc_D16F32C15_LShx_TRC_WRA_01(&pInstance->pTE_State->TrebleBoost_State,
-                                           pProcessed,
-                                           pProcessed,
-                                           (LVM_INT16)NrFrames,
-                                           (LVM_INT16)NrChannels);
-#else
-                FO_2I_D16F32C15_LShx_TRC_WRA_01(&pInstance->pTE_State->TrebleBoost_State,
-                                           pProcessed,
-                                           pProcessed,
-                                           (LVM_INT16)SampleCount);
-#endif
-
+                pInstance->pTEBiquad->process(pProcessed, pProcessed, NrFrames);
             }
-#ifdef SUPPORT_MC
             /*
              * Volume balance
              */
-            LVC_MixSoft_1St_MC_float_SAT(&pInstance->VC_BalanceMix,
-                                          pProcessed,
-                                          pProcessed,
-                                          NrFrames,
-                                          NrChannels,
-                                          ChMask);
-#else
-            /*
-             * Volume balance
-             */
-            LVC_MixSoft_1St_2i_D16C31_SAT(&pInstance->VC_BalanceMix,
-                                          pProcessed,
-                                          pProcessed,
-                                          SampleCount);
-#endif
+            LVC_MixSoft_1St_MC_float_SAT(&pInstance->VC_BalanceMix, pProcessed, pProcessed,
+                                         NrFrames, NrChannels, ChMask);
 
             /*
              * Perform Parametric Spectum Analysis
              */
             if ((pInstance->Params.PSA_Enable == LVM_PSA_ON) &&
-                                            (pInstance->InstParams.PSA_Included == LVM_PSA_ON))
-            {
-#ifdef SUPPORT_MC
-                FromMcToMono_Float(pProcessed,
-                                   pInstance->pPSAInput,
-                                   (LVM_INT16)(NrFrames),
+                (pInstance->InstParams.PSA_Included == LVM_PSA_ON)) {
+                FromMcToMono_Float(pProcessed, pInstance->pPSAInput, (LVM_INT16)(NrFrames),
                                    NrChannels);
-#else
-                From2iToMono_Float(pProcessed,
-                                   pInstance->pPSAInput,
-                                   (LVM_INT16)(SampleCount));
-#endif
 
-                LVPSA_Process(pInstance->hPSAInstance,
-                        pInstance->pPSAInput,
-                        (LVM_UINT16)(SampleCount),
-                        AudioTime);
+                LVPSA_Process(pInstance->hPSAInstance, pInstance->pPSAInput,
+                              (LVM_UINT16)(SampleCount), AudioTime);
             }
 
             /*
              * DC removal
              */
-#ifdef SUPPORT_MC
-            DC_Mc_D16_TRC_WRA_01(&pInstance->DC_RemovalInstance,
-                                 pProcessed,
-                                 pProcessed,
-                                 (LVM_INT16)NrFrames,
-                                 NrChannels);
-#else
-            DC_2I_D16_TRC_WRA_01(&pInstance->DC_RemovalInstance,
-                                 pProcessed,
-                                 pProcessed,
-                                 (LVM_INT16)SampleCount);
-#endif
+            DC_Mc_D16_TRC_WRA_01(&pInstance->DC_RemovalInstance, pProcessed, pProcessed,
+                                 (LVM_INT16)NrFrames, NrChannels);
         }
         /*
          * Manage the output buffer
          */
-        LVM_BufferOut(hInstance,
-                      pOutData,
-                      &SampleCount);
-
+        LVM_BufferOut(hInstance, pOutData, &SampleCount);
     }
 
-    return(LVM_SUCCESS);
+    return (LVM_SUCCESS);
 }
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Tables.cpp b/media/libeffects/lvm/lib/Bundle/src/LVM_Tables.cpp
index 66392e2..860196b 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Tables.cpp
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Tables.cpp
@@ -30,431 +30,297 @@
 /*                                                                                  */
 /************************************************************************************/
 
-FO_FLOAT_LShx_Coefs_t    LVM_TrebleBoostCoefs[] = {
+FO_FLOAT_LShx_Coefs_t LVM_TrebleBoostCoefs[] = {
 
-                    /* 22kHz sampling rate */
-                    {HPF_Fs22050_Gain1_A1,             /* Gain setting 1 */
-                     HPF_Fs22050_Gain1_A0,
-                     -HPF_Fs22050_Gain1_B1},
-                    {HPF_Fs22050_Gain2_A1,             /* Gain setting 2 */
-                     HPF_Fs22050_Gain2_A0,
-                     -HPF_Fs22050_Gain2_B1},
-                    {HPF_Fs22050_Gain3_A1,             /* Gain setting 3 */
-                     HPF_Fs22050_Gain3_A0,
-                     -HPF_Fs22050_Gain3_B1},
-                    {HPF_Fs22050_Gain4_A1,             /* Gain setting 4 */
-                     HPF_Fs22050_Gain4_A0,
-                     -HPF_Fs22050_Gain4_B1},
-                    {HPF_Fs22050_Gain5_A1,             /* Gain setting 5 */
-                     HPF_Fs22050_Gain5_A0,
-                     -HPF_Fs22050_Gain5_B1},
-                    {HPF_Fs22050_Gain6_A1,             /* Gain setting 6 */
-                     HPF_Fs22050_Gain6_A0,
-                     -HPF_Fs22050_Gain6_B1},
-                    {HPF_Fs22050_Gain7_A1,             /* Gain setting 7 */
-                     HPF_Fs22050_Gain7_A0,
-                     -HPF_Fs22050_Gain7_B1},
-                    {HPF_Fs22050_Gain8_A1,             /* Gain setting 8 */
-                     HPF_Fs22050_Gain8_A0,
-                     -HPF_Fs22050_Gain8_B1},
-                    {HPF_Fs22050_Gain9_A1,             /* Gain setting 9 */
-                     HPF_Fs22050_Gain9_A0,
-                     -HPF_Fs22050_Gain9_B1},
-                    {HPF_Fs22050_Gain10_A1,             /* Gain setting 10 */
-                     HPF_Fs22050_Gain10_A0,
-                     -HPF_Fs22050_Gain10_B1},
-                    {HPF_Fs22050_Gain11_A1,             /* Gain setting 11 */
-                     HPF_Fs22050_Gain11_A0,
-                     -HPF_Fs22050_Gain11_B1},
-                    {HPF_Fs22050_Gain12_A1,             /* Gain setting 12 */
-                     HPF_Fs22050_Gain12_A0,
-                     -HPF_Fs22050_Gain12_B1},
-                    {HPF_Fs22050_Gain13_A1,             /* Gain setting 13 */
-                     HPF_Fs22050_Gain13_A0,
-                     -HPF_Fs22050_Gain13_B1},
-                    {HPF_Fs22050_Gain14_A1,             /* Gain setting 14 */
-                     HPF_Fs22050_Gain14_A0,
-                     -HPF_Fs22050_Gain14_B1},
-                    {HPF_Fs22050_Gain15_A1,             /* Gain setting 15 */
-                     HPF_Fs22050_Gain15_A0,
-                     -HPF_Fs22050_Gain15_B1},
+        /* 22kHz sampling rate */
+        {HPF_Fs22050_Gain1_A1, /* Gain setting 1 */
+         HPF_Fs22050_Gain1_A0, -HPF_Fs22050_Gain1_B1},
+        {HPF_Fs22050_Gain2_A1, /* Gain setting 2 */
+         HPF_Fs22050_Gain2_A0, -HPF_Fs22050_Gain2_B1},
+        {HPF_Fs22050_Gain3_A1, /* Gain setting 3 */
+         HPF_Fs22050_Gain3_A0, -HPF_Fs22050_Gain3_B1},
+        {HPF_Fs22050_Gain4_A1, /* Gain setting 4 */
+         HPF_Fs22050_Gain4_A0, -HPF_Fs22050_Gain4_B1},
+        {HPF_Fs22050_Gain5_A1, /* Gain setting 5 */
+         HPF_Fs22050_Gain5_A0, -HPF_Fs22050_Gain5_B1},
+        {HPF_Fs22050_Gain6_A1, /* Gain setting 6 */
+         HPF_Fs22050_Gain6_A0, -HPF_Fs22050_Gain6_B1},
+        {HPF_Fs22050_Gain7_A1, /* Gain setting 7 */
+         HPF_Fs22050_Gain7_A0, -HPF_Fs22050_Gain7_B1},
+        {HPF_Fs22050_Gain8_A1, /* Gain setting 8 */
+         HPF_Fs22050_Gain8_A0, -HPF_Fs22050_Gain8_B1},
+        {HPF_Fs22050_Gain9_A1, /* Gain setting 9 */
+         HPF_Fs22050_Gain9_A0, -HPF_Fs22050_Gain9_B1},
+        {HPF_Fs22050_Gain10_A1, /* Gain setting 10 */
+         HPF_Fs22050_Gain10_A0, -HPF_Fs22050_Gain10_B1},
+        {HPF_Fs22050_Gain11_A1, /* Gain setting 11 */
+         HPF_Fs22050_Gain11_A0, -HPF_Fs22050_Gain11_B1},
+        {HPF_Fs22050_Gain12_A1, /* Gain setting 12 */
+         HPF_Fs22050_Gain12_A0, -HPF_Fs22050_Gain12_B1},
+        {HPF_Fs22050_Gain13_A1, /* Gain setting 13 */
+         HPF_Fs22050_Gain13_A0, -HPF_Fs22050_Gain13_B1},
+        {HPF_Fs22050_Gain14_A1, /* Gain setting 14 */
+         HPF_Fs22050_Gain14_A0, -HPF_Fs22050_Gain14_B1},
+        {HPF_Fs22050_Gain15_A1, /* Gain setting 15 */
+         HPF_Fs22050_Gain15_A0, -HPF_Fs22050_Gain15_B1},
 
-                    /* 24kHz sampling rate */
-                    {HPF_Fs24000_Gain1_A1,             /* Gain setting 1 */
-                     HPF_Fs24000_Gain1_A0,
-                     -HPF_Fs24000_Gain1_B1},
-                    {HPF_Fs24000_Gain2_A1,             /* Gain setting 2 */
-                     HPF_Fs24000_Gain2_A0,
-                     -HPF_Fs24000_Gain2_B1},
-                    {HPF_Fs24000_Gain3_A1,             /* Gain setting 3 */
-                     HPF_Fs24000_Gain3_A0,
-                     -HPF_Fs24000_Gain3_B1},
-                    {HPF_Fs24000_Gain4_A1,             /* Gain setting 4 */
-                     HPF_Fs24000_Gain4_A0,
-                     -HPF_Fs24000_Gain4_B1},
-                    {HPF_Fs24000_Gain5_A1,             /* Gain setting 5 */
-                     HPF_Fs24000_Gain5_A0,
-                     -HPF_Fs24000_Gain5_B1},
-                    {HPF_Fs24000_Gain6_A1,             /* Gain setting 6 */
-                     HPF_Fs24000_Gain6_A0,
-                     -HPF_Fs24000_Gain6_B1},
-                    {HPF_Fs24000_Gain7_A1,             /* Gain setting 7 */
-                     HPF_Fs24000_Gain7_A0,
-                     -HPF_Fs24000_Gain7_B1},
-                    {HPF_Fs24000_Gain8_A1,             /* Gain setting 8 */
-                     HPF_Fs24000_Gain8_A0,
-                     -HPF_Fs24000_Gain8_B1},
-                    {HPF_Fs24000_Gain9_A1,             /* Gain setting 9 */
-                     HPF_Fs24000_Gain9_A0,
-                     -HPF_Fs24000_Gain9_B1},
-                    {HPF_Fs24000_Gain10_A1,             /* Gain setting 10 */
-                     HPF_Fs24000_Gain10_A0,
-                     -HPF_Fs24000_Gain10_B1},
-                    {HPF_Fs24000_Gain11_A1,             /* Gain setting 11 */
-                     HPF_Fs24000_Gain11_A0,
-                     -HPF_Fs24000_Gain11_B1},
-                    {HPF_Fs24000_Gain12_A1,             /* Gain setting 12 */
-                     HPF_Fs24000_Gain12_A0,
-                     -HPF_Fs24000_Gain12_B1},
-                    {HPF_Fs24000_Gain13_A1,             /* Gain setting 13 */
-                     HPF_Fs24000_Gain13_A0,
-                     -HPF_Fs24000_Gain13_B1},
-                    {HPF_Fs24000_Gain14_A1,             /* Gain setting 14 */
-                     HPF_Fs24000_Gain14_A0,
-                     -HPF_Fs24000_Gain14_B1},
-                    {HPF_Fs24000_Gain15_A1,             /* Gain setting 15 */
-                     HPF_Fs24000_Gain15_A0,
-                     -HPF_Fs24000_Gain15_B1},
+        /* 24kHz sampling rate */
+        {HPF_Fs24000_Gain1_A1, /* Gain setting 1 */
+         HPF_Fs24000_Gain1_A0, -HPF_Fs24000_Gain1_B1},
+        {HPF_Fs24000_Gain2_A1, /* Gain setting 2 */
+         HPF_Fs24000_Gain2_A0, -HPF_Fs24000_Gain2_B1},
+        {HPF_Fs24000_Gain3_A1, /* Gain setting 3 */
+         HPF_Fs24000_Gain3_A0, -HPF_Fs24000_Gain3_B1},
+        {HPF_Fs24000_Gain4_A1, /* Gain setting 4 */
+         HPF_Fs24000_Gain4_A0, -HPF_Fs24000_Gain4_B1},
+        {HPF_Fs24000_Gain5_A1, /* Gain setting 5 */
+         HPF_Fs24000_Gain5_A0, -HPF_Fs24000_Gain5_B1},
+        {HPF_Fs24000_Gain6_A1, /* Gain setting 6 */
+         HPF_Fs24000_Gain6_A0, -HPF_Fs24000_Gain6_B1},
+        {HPF_Fs24000_Gain7_A1, /* Gain setting 7 */
+         HPF_Fs24000_Gain7_A0, -HPF_Fs24000_Gain7_B1},
+        {HPF_Fs24000_Gain8_A1, /* Gain setting 8 */
+         HPF_Fs24000_Gain8_A0, -HPF_Fs24000_Gain8_B1},
+        {HPF_Fs24000_Gain9_A1, /* Gain setting 9 */
+         HPF_Fs24000_Gain9_A0, -HPF_Fs24000_Gain9_B1},
+        {HPF_Fs24000_Gain10_A1, /* Gain setting 10 */
+         HPF_Fs24000_Gain10_A0, -HPF_Fs24000_Gain10_B1},
+        {HPF_Fs24000_Gain11_A1, /* Gain setting 11 */
+         HPF_Fs24000_Gain11_A0, -HPF_Fs24000_Gain11_B1},
+        {HPF_Fs24000_Gain12_A1, /* Gain setting 12 */
+         HPF_Fs24000_Gain12_A0, -HPF_Fs24000_Gain12_B1},
+        {HPF_Fs24000_Gain13_A1, /* Gain setting 13 */
+         HPF_Fs24000_Gain13_A0, -HPF_Fs24000_Gain13_B1},
+        {HPF_Fs24000_Gain14_A1, /* Gain setting 14 */
+         HPF_Fs24000_Gain14_A0, -HPF_Fs24000_Gain14_B1},
+        {HPF_Fs24000_Gain15_A1, /* Gain setting 15 */
+         HPF_Fs24000_Gain15_A0, -HPF_Fs24000_Gain15_B1},
 
-                    /* 32kHz sampling rate */
-                    {HPF_Fs32000_Gain1_A1,             /* Gain setting 1 */
-                     HPF_Fs32000_Gain1_A0,
-                     -HPF_Fs32000_Gain1_B1},
-                    {HPF_Fs32000_Gain2_A1,             /* Gain setting 2 */
-                     HPF_Fs32000_Gain2_A0,
-                     -HPF_Fs32000_Gain2_B1},
-                    {HPF_Fs32000_Gain3_A1,             /* Gain setting 3 */
-                     HPF_Fs32000_Gain3_A0,
-                     -HPF_Fs32000_Gain3_B1},
-                    {HPF_Fs32000_Gain4_A1,             /* Gain setting 4 */
-                     HPF_Fs32000_Gain4_A0,
-                     -HPF_Fs32000_Gain4_B1},
-                    {HPF_Fs32000_Gain5_A1,             /* Gain setting 5 */
-                     HPF_Fs32000_Gain5_A0,
-                     -HPF_Fs32000_Gain5_B1},
-                    {HPF_Fs32000_Gain6_A1,             /* Gain setting 6 */
-                     HPF_Fs32000_Gain6_A0,
-                     -HPF_Fs32000_Gain6_B1},
-                    {HPF_Fs32000_Gain7_A1,             /* Gain setting 7 */
-                     HPF_Fs32000_Gain7_A0,
-                     -HPF_Fs32000_Gain7_B1},
-                    {HPF_Fs32000_Gain8_A1,             /* Gain setting 8 */
-                     HPF_Fs32000_Gain8_A0,
-                     -HPF_Fs32000_Gain8_B1},
-                    {HPF_Fs32000_Gain9_A1,             /* Gain setting 9 */
-                     HPF_Fs32000_Gain9_A0,
-                     -HPF_Fs32000_Gain9_B1},
-                    {HPF_Fs32000_Gain10_A1,             /* Gain setting 10 */
-                     HPF_Fs32000_Gain10_A0,
-                     -HPF_Fs32000_Gain10_B1},
-                    {HPF_Fs32000_Gain11_A1,             /* Gain setting 11 */
-                     HPF_Fs32000_Gain11_A0,
-                     -HPF_Fs32000_Gain11_B1},
-                    {HPF_Fs32000_Gain12_A1,             /* Gain setting 12 */
-                     HPF_Fs32000_Gain12_A0,
-                     -HPF_Fs32000_Gain12_B1},
-                    {HPF_Fs32000_Gain13_A1,             /* Gain setting 13 */
-                     HPF_Fs32000_Gain13_A0,
-                     -HPF_Fs32000_Gain13_B1},
-                    {HPF_Fs32000_Gain14_A1,             /* Gain setting 14 */
-                     HPF_Fs32000_Gain14_A0,
-                     -HPF_Fs32000_Gain14_B1},
-                    {HPF_Fs32000_Gain15_A1,             /* Gain setting 15 */
-                     HPF_Fs32000_Gain15_A0,
-                     -HPF_Fs32000_Gain15_B1},
+        /* 32kHz sampling rate */
+        {HPF_Fs32000_Gain1_A1, /* Gain setting 1 */
+         HPF_Fs32000_Gain1_A0, -HPF_Fs32000_Gain1_B1},
+        {HPF_Fs32000_Gain2_A1, /* Gain setting 2 */
+         HPF_Fs32000_Gain2_A0, -HPF_Fs32000_Gain2_B1},
+        {HPF_Fs32000_Gain3_A1, /* Gain setting 3 */
+         HPF_Fs32000_Gain3_A0, -HPF_Fs32000_Gain3_B1},
+        {HPF_Fs32000_Gain4_A1, /* Gain setting 4 */
+         HPF_Fs32000_Gain4_A0, -HPF_Fs32000_Gain4_B1},
+        {HPF_Fs32000_Gain5_A1, /* Gain setting 5 */
+         HPF_Fs32000_Gain5_A0, -HPF_Fs32000_Gain5_B1},
+        {HPF_Fs32000_Gain6_A1, /* Gain setting 6 */
+         HPF_Fs32000_Gain6_A0, -HPF_Fs32000_Gain6_B1},
+        {HPF_Fs32000_Gain7_A1, /* Gain setting 7 */
+         HPF_Fs32000_Gain7_A0, -HPF_Fs32000_Gain7_B1},
+        {HPF_Fs32000_Gain8_A1, /* Gain setting 8 */
+         HPF_Fs32000_Gain8_A0, -HPF_Fs32000_Gain8_B1},
+        {HPF_Fs32000_Gain9_A1, /* Gain setting 9 */
+         HPF_Fs32000_Gain9_A0, -HPF_Fs32000_Gain9_B1},
+        {HPF_Fs32000_Gain10_A1, /* Gain setting 10 */
+         HPF_Fs32000_Gain10_A0, -HPF_Fs32000_Gain10_B1},
+        {HPF_Fs32000_Gain11_A1, /* Gain setting 11 */
+         HPF_Fs32000_Gain11_A0, -HPF_Fs32000_Gain11_B1},
+        {HPF_Fs32000_Gain12_A1, /* Gain setting 12 */
+         HPF_Fs32000_Gain12_A0, -HPF_Fs32000_Gain12_B1},
+        {HPF_Fs32000_Gain13_A1, /* Gain setting 13 */
+         HPF_Fs32000_Gain13_A0, -HPF_Fs32000_Gain13_B1},
+        {HPF_Fs32000_Gain14_A1, /* Gain setting 14 */
+         HPF_Fs32000_Gain14_A0, -HPF_Fs32000_Gain14_B1},
+        {HPF_Fs32000_Gain15_A1, /* Gain setting 15 */
+         HPF_Fs32000_Gain15_A0, -HPF_Fs32000_Gain15_B1},
 
-                    /* 44kHz sampling rate */
-                    {HPF_Fs44100_Gain1_A1,             /* Gain setting 1 */
-                     HPF_Fs44100_Gain1_A0,
-                     -HPF_Fs44100_Gain1_B1,},
-                    {HPF_Fs44100_Gain2_A1,             /* Gain setting 2 */
-                     HPF_Fs44100_Gain2_A0,
-                     -HPF_Fs44100_Gain2_B1},
-                    {HPF_Fs44100_Gain3_A1,             /* Gain setting 3 */
-                     HPF_Fs44100_Gain3_A0,
-                     -HPF_Fs44100_Gain3_B1},
-                    {HPF_Fs44100_Gain4_A1,             /* Gain setting 4 */
-                     HPF_Fs44100_Gain4_A0,
-                     -HPF_Fs44100_Gain4_B1},
-                    {HPF_Fs44100_Gain5_A1,             /* Gain setting 5 */
-                     HPF_Fs44100_Gain5_A0,
-                     -HPF_Fs44100_Gain5_B1},
-                    {HPF_Fs44100_Gain6_A1,             /* Gain setting 6 */
-                     HPF_Fs44100_Gain6_A0,
-                     -HPF_Fs44100_Gain6_B1},
-                    {HPF_Fs44100_Gain7_A1,             /* Gain setting 7 */
-                     HPF_Fs44100_Gain7_A0,
-                     -HPF_Fs44100_Gain7_B1},
-                    {HPF_Fs44100_Gain8_A1,             /* Gain setting 8 */
-                     HPF_Fs44100_Gain8_A0,
-                     -HPF_Fs44100_Gain8_B1},
-                    {HPF_Fs44100_Gain9_A1,             /* Gain setting 9 */
-                     HPF_Fs44100_Gain9_A0,
-                     -HPF_Fs44100_Gain9_B1},
-                    {HPF_Fs44100_Gain10_A1,             /* Gain setting 10 */
-                     HPF_Fs44100_Gain10_A0,
-                     -HPF_Fs44100_Gain10_B1},
-                    {HPF_Fs44100_Gain11_A1,             /* Gain setting 11 */
-                     HPF_Fs44100_Gain11_A0,
-                     -HPF_Fs44100_Gain11_B1},
-                    {HPF_Fs44100_Gain12_A1,             /* Gain setting 12 */
-                     HPF_Fs44100_Gain12_A0,
-                     -HPF_Fs44100_Gain12_B1},
-                    {HPF_Fs44100_Gain13_A1,             /* Gain setting 13 */
-                     HPF_Fs44100_Gain13_A0,
-                     -HPF_Fs44100_Gain13_B1},
-                    {HPF_Fs44100_Gain14_A1,             /* Gain setting 14 */
-                     HPF_Fs44100_Gain14_A0,
-                     -HPF_Fs44100_Gain14_B1},
-                    {HPF_Fs44100_Gain15_A1,             /* Gain setting 15 */
-                     HPF_Fs44100_Gain15_A0,
-                     -HPF_Fs44100_Gain15_B1},
+        /* 44kHz sampling rate */
+        {
+                HPF_Fs44100_Gain1_A1, /* Gain setting 1 */
+                HPF_Fs44100_Gain1_A0,
+                -HPF_Fs44100_Gain1_B1,
+        },
+        {HPF_Fs44100_Gain2_A1, /* Gain setting 2 */
+         HPF_Fs44100_Gain2_A0, -HPF_Fs44100_Gain2_B1},
+        {HPF_Fs44100_Gain3_A1, /* Gain setting 3 */
+         HPF_Fs44100_Gain3_A0, -HPF_Fs44100_Gain3_B1},
+        {HPF_Fs44100_Gain4_A1, /* Gain setting 4 */
+         HPF_Fs44100_Gain4_A0, -HPF_Fs44100_Gain4_B1},
+        {HPF_Fs44100_Gain5_A1, /* Gain setting 5 */
+         HPF_Fs44100_Gain5_A0, -HPF_Fs44100_Gain5_B1},
+        {HPF_Fs44100_Gain6_A1, /* Gain setting 6 */
+         HPF_Fs44100_Gain6_A0, -HPF_Fs44100_Gain6_B1},
+        {HPF_Fs44100_Gain7_A1, /* Gain setting 7 */
+         HPF_Fs44100_Gain7_A0, -HPF_Fs44100_Gain7_B1},
+        {HPF_Fs44100_Gain8_A1, /* Gain setting 8 */
+         HPF_Fs44100_Gain8_A0, -HPF_Fs44100_Gain8_B1},
+        {HPF_Fs44100_Gain9_A1, /* Gain setting 9 */
+         HPF_Fs44100_Gain9_A0, -HPF_Fs44100_Gain9_B1},
+        {HPF_Fs44100_Gain10_A1, /* Gain setting 10 */
+         HPF_Fs44100_Gain10_A0, -HPF_Fs44100_Gain10_B1},
+        {HPF_Fs44100_Gain11_A1, /* Gain setting 11 */
+         HPF_Fs44100_Gain11_A0, -HPF_Fs44100_Gain11_B1},
+        {HPF_Fs44100_Gain12_A1, /* Gain setting 12 */
+         HPF_Fs44100_Gain12_A0, -HPF_Fs44100_Gain12_B1},
+        {HPF_Fs44100_Gain13_A1, /* Gain setting 13 */
+         HPF_Fs44100_Gain13_A0, -HPF_Fs44100_Gain13_B1},
+        {HPF_Fs44100_Gain14_A1, /* Gain setting 14 */
+         HPF_Fs44100_Gain14_A0, -HPF_Fs44100_Gain14_B1},
+        {HPF_Fs44100_Gain15_A1, /* Gain setting 15 */
+         HPF_Fs44100_Gain15_A0, -HPF_Fs44100_Gain15_B1},
 
-                    /* 48kHz sampling rate */
-                    {HPF_Fs48000_Gain1_A1,             /* Gain setting 1 */
-                     HPF_Fs48000_Gain1_A0,
-                     -HPF_Fs48000_Gain1_B1},
-                    {HPF_Fs48000_Gain2_A1,             /* Gain setting 2 */
-                     HPF_Fs48000_Gain2_A0,
-                     -HPF_Fs48000_Gain2_B1},
-                    {HPF_Fs48000_Gain3_A1,             /* Gain setting 3 */
-                     HPF_Fs48000_Gain3_A0,
-                     -HPF_Fs48000_Gain3_B1},
-                    {HPF_Fs48000_Gain4_A1,             /* Gain setting 4 */
-                     HPF_Fs48000_Gain4_A0,
-                     -HPF_Fs48000_Gain4_B1},
-                    {HPF_Fs48000_Gain5_A1,             /* Gain setting 5 */
-                     HPF_Fs48000_Gain5_A0,
-                     -HPF_Fs48000_Gain5_B1},
-                    {HPF_Fs48000_Gain6_A1,             /* Gain setting 6 */
-                     HPF_Fs48000_Gain6_A0,
-                     -HPF_Fs48000_Gain6_B1},
-                    {HPF_Fs48000_Gain7_A1,             /* Gain setting 7 */
-                     HPF_Fs48000_Gain7_A0,
-                     -HPF_Fs48000_Gain7_B1},
-                    {HPF_Fs48000_Gain8_A1,             /* Gain setting 8 */
-                     HPF_Fs48000_Gain8_A0,
-                     -HPF_Fs48000_Gain8_B1},
-                    {HPF_Fs48000_Gain9_A1,             /* Gain setting 9 */
-                     HPF_Fs48000_Gain9_A0,
-                     -HPF_Fs48000_Gain9_B1},
-                    {HPF_Fs48000_Gain10_A1,             /* Gain setting 10 */
-                     HPF_Fs48000_Gain10_A0,
-                     -HPF_Fs48000_Gain10_B1},
-                    {HPF_Fs48000_Gain11_A1,             /* Gain setting 11 */
-                     HPF_Fs48000_Gain11_A0,
-                     -HPF_Fs48000_Gain11_B1},
-                    {HPF_Fs48000_Gain12_A1,             /* Gain setting 12 */
-                     HPF_Fs48000_Gain12_A0,
-                     -HPF_Fs48000_Gain12_B1},
-                    {HPF_Fs48000_Gain13_A1,             /* Gain setting 13 */
-                     HPF_Fs48000_Gain13_A0,
-                     -HPF_Fs48000_Gain13_B1},
-                    {HPF_Fs48000_Gain14_A1,             /* Gain setting 14 */
-                     HPF_Fs48000_Gain14_A0,
-                     -HPF_Fs48000_Gain14_B1},
-                    {HPF_Fs48000_Gain15_A1,             /* Gain setting 15 */
-                     HPF_Fs48000_Gain15_A0,
-                     -HPF_Fs48000_Gain15_B1}
-                    ,
-                    /* 88kHz Sampling rate */
-                    {HPF_Fs88200_Gain1_A1,             /* Gain Setting  1 */
-                    HPF_Fs88200_Gain1_A0,
-                    -HPF_Fs88200_Gain1_B1},
-                    {HPF_Fs88200_Gain2_A1,             /* Gain Setting  2 */
-                    HPF_Fs88200_Gain2_A0,
-                    -HPF_Fs88200_Gain2_B1},
-                    {HPF_Fs88200_Gain3_A1,             /* Gain Setting  3 */
-                    HPF_Fs88200_Gain3_A0,
-                    -HPF_Fs88200_Gain3_B1},
-                    {HPF_Fs88200_Gain4_A1,             /* Gain Setting  4 */
-                    HPF_Fs88200_Gain4_A0,
-                    -HPF_Fs88200_Gain4_B1},
-                    {HPF_Fs88200_Gain5_A1,             /* Gain Setting  5 */
-                    HPF_Fs88200_Gain5_A0,
-                    -HPF_Fs88200_Gain5_B1},
-                    {HPF_Fs88200_Gain6_A1,             /* Gain Setting  6 */
-                    HPF_Fs88200_Gain6_A0,
-                    -HPF_Fs88200_Gain6_B1},
-                    {HPF_Fs88200_Gain7_A1,             /* Gain Setting  7 */
-                    HPF_Fs88200_Gain7_A0,
-                    -HPF_Fs88200_Gain7_B1},
-                    {HPF_Fs88200_Gain8_A1,             /* Gain Setting  8 */
-                    HPF_Fs88200_Gain8_A0,
-                    -HPF_Fs88200_Gain8_B1},
-                    {HPF_Fs88200_Gain9_A1,             /* Gain Setting  9 */
-                    HPF_Fs88200_Gain9_A0,
-                    -HPF_Fs88200_Gain9_B1},
-                    {HPF_Fs88200_Gain10_A1,             /* Gain Setting  10 */
-                    HPF_Fs88200_Gain10_A0,
-                    -HPF_Fs88200_Gain10_B1},
-                    {HPF_Fs88200_Gain11_A1,             /* Gain Setting  11 */
-                    HPF_Fs88200_Gain11_A0,
-                    -HPF_Fs88200_Gain11_B1},
-                    {HPF_Fs88200_Gain12_A1,             /* Gain Setting  12 */
-                    HPF_Fs88200_Gain12_A0,
-                    -HPF_Fs88200_Gain12_B1},
-                    {HPF_Fs88200_Gain13_A1,             /* Gain Setting  13 */
-                    HPF_Fs88200_Gain13_A0,
-                    -HPF_Fs88200_Gain13_B1},
-                    {HPF_Fs88200_Gain14_A1,             /* Gain Setting  14 */
-                    HPF_Fs88200_Gain14_A0,
-                    -HPF_Fs88200_Gain14_B1},
-                    {HPF_Fs88200_Gain15_A1,             /* Gain Setting  15 */
-                    HPF_Fs88200_Gain15_A0,
-                    -HPF_Fs88200_Gain15_B1},
+        /* 48kHz sampling rate */
+        {HPF_Fs48000_Gain1_A1, /* Gain setting 1 */
+         HPF_Fs48000_Gain1_A0, -HPF_Fs48000_Gain1_B1},
+        {HPF_Fs48000_Gain2_A1, /* Gain setting 2 */
+         HPF_Fs48000_Gain2_A0, -HPF_Fs48000_Gain2_B1},
+        {HPF_Fs48000_Gain3_A1, /* Gain setting 3 */
+         HPF_Fs48000_Gain3_A0, -HPF_Fs48000_Gain3_B1},
+        {HPF_Fs48000_Gain4_A1, /* Gain setting 4 */
+         HPF_Fs48000_Gain4_A0, -HPF_Fs48000_Gain4_B1},
+        {HPF_Fs48000_Gain5_A1, /* Gain setting 5 */
+         HPF_Fs48000_Gain5_A0, -HPF_Fs48000_Gain5_B1},
+        {HPF_Fs48000_Gain6_A1, /* Gain setting 6 */
+         HPF_Fs48000_Gain6_A0, -HPF_Fs48000_Gain6_B1},
+        {HPF_Fs48000_Gain7_A1, /* Gain setting 7 */
+         HPF_Fs48000_Gain7_A0, -HPF_Fs48000_Gain7_B1},
+        {HPF_Fs48000_Gain8_A1, /* Gain setting 8 */
+         HPF_Fs48000_Gain8_A0, -HPF_Fs48000_Gain8_B1},
+        {HPF_Fs48000_Gain9_A1, /* Gain setting 9 */
+         HPF_Fs48000_Gain9_A0, -HPF_Fs48000_Gain9_B1},
+        {HPF_Fs48000_Gain10_A1, /* Gain setting 10 */
+         HPF_Fs48000_Gain10_A0, -HPF_Fs48000_Gain10_B1},
+        {HPF_Fs48000_Gain11_A1, /* Gain setting 11 */
+         HPF_Fs48000_Gain11_A0, -HPF_Fs48000_Gain11_B1},
+        {HPF_Fs48000_Gain12_A1, /* Gain setting 12 */
+         HPF_Fs48000_Gain12_A0, -HPF_Fs48000_Gain12_B1},
+        {HPF_Fs48000_Gain13_A1, /* Gain setting 13 */
+         HPF_Fs48000_Gain13_A0, -HPF_Fs48000_Gain13_B1},
+        {HPF_Fs48000_Gain14_A1, /* Gain setting 14 */
+         HPF_Fs48000_Gain14_A0, -HPF_Fs48000_Gain14_B1},
+        {HPF_Fs48000_Gain15_A1, /* Gain setting 15 */
+         HPF_Fs48000_Gain15_A0, -HPF_Fs48000_Gain15_B1},
+        /* 88kHz Sampling rate */
+        {HPF_Fs88200_Gain1_A1, /* Gain Setting  1 */
+         HPF_Fs88200_Gain1_A0, -HPF_Fs88200_Gain1_B1},
+        {HPF_Fs88200_Gain2_A1, /* Gain Setting  2 */
+         HPF_Fs88200_Gain2_A0, -HPF_Fs88200_Gain2_B1},
+        {HPF_Fs88200_Gain3_A1, /* Gain Setting  3 */
+         HPF_Fs88200_Gain3_A0, -HPF_Fs88200_Gain3_B1},
+        {HPF_Fs88200_Gain4_A1, /* Gain Setting  4 */
+         HPF_Fs88200_Gain4_A0, -HPF_Fs88200_Gain4_B1},
+        {HPF_Fs88200_Gain5_A1, /* Gain Setting  5 */
+         HPF_Fs88200_Gain5_A0, -HPF_Fs88200_Gain5_B1},
+        {HPF_Fs88200_Gain6_A1, /* Gain Setting  6 */
+         HPF_Fs88200_Gain6_A0, -HPF_Fs88200_Gain6_B1},
+        {HPF_Fs88200_Gain7_A1, /* Gain Setting  7 */
+         HPF_Fs88200_Gain7_A0, -HPF_Fs88200_Gain7_B1},
+        {HPF_Fs88200_Gain8_A1, /* Gain Setting  8 */
+         HPF_Fs88200_Gain8_A0, -HPF_Fs88200_Gain8_B1},
+        {HPF_Fs88200_Gain9_A1, /* Gain Setting  9 */
+         HPF_Fs88200_Gain9_A0, -HPF_Fs88200_Gain9_B1},
+        {HPF_Fs88200_Gain10_A1, /* Gain Setting  10 */
+         HPF_Fs88200_Gain10_A0, -HPF_Fs88200_Gain10_B1},
+        {HPF_Fs88200_Gain11_A1, /* Gain Setting  11 */
+         HPF_Fs88200_Gain11_A0, -HPF_Fs88200_Gain11_B1},
+        {HPF_Fs88200_Gain12_A1, /* Gain Setting  12 */
+         HPF_Fs88200_Gain12_A0, -HPF_Fs88200_Gain12_B1},
+        {HPF_Fs88200_Gain13_A1, /* Gain Setting  13 */
+         HPF_Fs88200_Gain13_A0, -HPF_Fs88200_Gain13_B1},
+        {HPF_Fs88200_Gain14_A1, /* Gain Setting  14 */
+         HPF_Fs88200_Gain14_A0, -HPF_Fs88200_Gain14_B1},
+        {HPF_Fs88200_Gain15_A1, /* Gain Setting  15 */
+         HPF_Fs88200_Gain15_A0, -HPF_Fs88200_Gain15_B1},
 
-                    /* 96kHz sampling rate */
-                    {HPF_Fs96000_Gain1_A1,             /* Gain setting 1 */
-                    HPF_Fs96000_Gain1_A0,
-                    -HPF_Fs96000_Gain1_B1},
-                    {HPF_Fs96000_Gain2_A1,             /* Gain setting 2 */
-                    HPF_Fs96000_Gain2_A0,
-                    -HPF_Fs96000_Gain2_B1},
-                    {HPF_Fs96000_Gain3_A1,             /* Gain setting 3 */
-                    HPF_Fs96000_Gain3_A0,
-                    -HPF_Fs96000_Gain3_B1},
-                    {HPF_Fs96000_Gain4_A1,             /* Gain setting 4 */
-                    HPF_Fs96000_Gain4_A0,
-                    -HPF_Fs96000_Gain4_B1},
-                    {HPF_Fs96000_Gain5_A1,             /* Gain setting 5 */
-                    HPF_Fs96000_Gain5_A0,
-                    -HPF_Fs96000_Gain5_B1},
-                    {HPF_Fs96000_Gain6_A1,             /* Gain setting 6 */
-                    HPF_Fs96000_Gain6_A0,
-                    -HPF_Fs96000_Gain6_B1},
-                    {HPF_Fs96000_Gain7_A1,             /* Gain setting 7 */
-                    HPF_Fs96000_Gain7_A0,
-                    -HPF_Fs96000_Gain7_B1},
-                    {HPF_Fs96000_Gain8_A1,             /* Gain setting 8 */
-                    HPF_Fs96000_Gain8_A0,
-                    -HPF_Fs96000_Gain8_B1},
-                    {HPF_Fs96000_Gain9_A1,             /* Gain setting 9 */
-                    HPF_Fs96000_Gain9_A0,
-                    -HPF_Fs96000_Gain9_B1},
-                    {HPF_Fs96000_Gain10_A1,             /* Gain setting 10 */
-                    HPF_Fs96000_Gain10_A0,
-                    -HPF_Fs96000_Gain10_B1},
-                    {HPF_Fs96000_Gain11_A1,             /* Gain setting 11 */
-                    HPF_Fs96000_Gain11_A0,
-                    -HPF_Fs96000_Gain11_B1},
-                    {HPF_Fs96000_Gain12_A1,             /* Gain setting 12 */
-                    HPF_Fs96000_Gain12_A0,
-                    -HPF_Fs96000_Gain12_B1},
-                    {HPF_Fs96000_Gain13_A1,             /* Gain setting 13 */
-                    HPF_Fs96000_Gain13_A0,
-                    -HPF_Fs96000_Gain13_B1},
-                    {HPF_Fs96000_Gain14_A1,             /* Gain setting 14 */
-                    HPF_Fs96000_Gain14_A0,
-                    -HPF_Fs96000_Gain14_B1},
-                    {HPF_Fs96000_Gain15_A1,             /* Gain setting 15 */
-                    HPF_Fs96000_Gain15_A0,
-                    -HPF_Fs96000_Gain15_B1},
+        /* 96kHz sampling rate */
+        {HPF_Fs96000_Gain1_A1, /* Gain setting 1 */
+         HPF_Fs96000_Gain1_A0, -HPF_Fs96000_Gain1_B1},
+        {HPF_Fs96000_Gain2_A1, /* Gain setting 2 */
+         HPF_Fs96000_Gain2_A0, -HPF_Fs96000_Gain2_B1},
+        {HPF_Fs96000_Gain3_A1, /* Gain setting 3 */
+         HPF_Fs96000_Gain3_A0, -HPF_Fs96000_Gain3_B1},
+        {HPF_Fs96000_Gain4_A1, /* Gain setting 4 */
+         HPF_Fs96000_Gain4_A0, -HPF_Fs96000_Gain4_B1},
+        {HPF_Fs96000_Gain5_A1, /* Gain setting 5 */
+         HPF_Fs96000_Gain5_A0, -HPF_Fs96000_Gain5_B1},
+        {HPF_Fs96000_Gain6_A1, /* Gain setting 6 */
+         HPF_Fs96000_Gain6_A0, -HPF_Fs96000_Gain6_B1},
+        {HPF_Fs96000_Gain7_A1, /* Gain setting 7 */
+         HPF_Fs96000_Gain7_A0, -HPF_Fs96000_Gain7_B1},
+        {HPF_Fs96000_Gain8_A1, /* Gain setting 8 */
+         HPF_Fs96000_Gain8_A0, -HPF_Fs96000_Gain8_B1},
+        {HPF_Fs96000_Gain9_A1, /* Gain setting 9 */
+         HPF_Fs96000_Gain9_A0, -HPF_Fs96000_Gain9_B1},
+        {HPF_Fs96000_Gain10_A1, /* Gain setting 10 */
+         HPF_Fs96000_Gain10_A0, -HPF_Fs96000_Gain10_B1},
+        {HPF_Fs96000_Gain11_A1, /* Gain setting 11 */
+         HPF_Fs96000_Gain11_A0, -HPF_Fs96000_Gain11_B1},
+        {HPF_Fs96000_Gain12_A1, /* Gain setting 12 */
+         HPF_Fs96000_Gain12_A0, -HPF_Fs96000_Gain12_B1},
+        {HPF_Fs96000_Gain13_A1, /* Gain setting 13 */
+         HPF_Fs96000_Gain13_A0, -HPF_Fs96000_Gain13_B1},
+        {HPF_Fs96000_Gain14_A1, /* Gain setting 14 */
+         HPF_Fs96000_Gain14_A0, -HPF_Fs96000_Gain14_B1},
+        {HPF_Fs96000_Gain15_A1, /* Gain setting 15 */
+         HPF_Fs96000_Gain15_A0, -HPF_Fs96000_Gain15_B1},
 
-                    /* 176kHz Sampling rate */
-                    {HPF_Fs176400_Gain1_A1,             /* Gain Setting  1 */
-                    HPF_Fs176400_Gain1_A0,
-                    -HPF_Fs176400_Gain1_B1},
-                    {HPF_Fs176400_Gain2_A1,             /* Gain Setting  2 */
-                    HPF_Fs176400_Gain2_A0,
-                    -HPF_Fs176400_Gain2_B1},
-                    {HPF_Fs176400_Gain3_A1,             /* Gain Setting  3 */
-                    HPF_Fs176400_Gain3_A0,
-                    -HPF_Fs176400_Gain3_B1},
-                    {HPF_Fs176400_Gain4_A1,             /* Gain Setting  4 */
-                    HPF_Fs176400_Gain4_A0,
-                    -HPF_Fs176400_Gain4_B1},
-                    {HPF_Fs176400_Gain5_A1,             /* Gain Setting  5 */
-                    HPF_Fs176400_Gain5_A0,
-                    -HPF_Fs176400_Gain5_B1},
-                    {HPF_Fs176400_Gain6_A1,             /* Gain Setting  6 */
-                    HPF_Fs176400_Gain6_A0,
-                    -HPF_Fs176400_Gain6_B1},
-                    {HPF_Fs176400_Gain7_A1,             /* Gain Setting  7 */
-                    HPF_Fs176400_Gain7_A0,
-                    -HPF_Fs176400_Gain7_B1},
-                    {HPF_Fs176400_Gain8_A1,             /* Gain Setting  8 */
-                    HPF_Fs176400_Gain8_A0,
-                    -HPF_Fs176400_Gain8_B1},
-                    {HPF_Fs176400_Gain9_A1,             /* Gain Setting  9 */
-                    HPF_Fs176400_Gain9_A0,
-                    -HPF_Fs176400_Gain9_B1},
-                    {HPF_Fs176400_Gain10_A1,             /* Gain Setting  10 */
-                    HPF_Fs176400_Gain10_A0,
-                    -HPF_Fs176400_Gain10_B1},
-                    {HPF_Fs176400_Gain11_A1,             /* Gain Setting  11 */
-                    HPF_Fs176400_Gain11_A0,
-                    -HPF_Fs176400_Gain11_B1},
-                    {HPF_Fs176400_Gain12_A1,             /* Gain Setting  12 */
-                    HPF_Fs176400_Gain12_A0,
-                    -HPF_Fs176400_Gain12_B1},
-                    {HPF_Fs176400_Gain13_A1,             /* Gain Setting  13 */
-                    HPF_Fs176400_Gain13_A0,
-                    -HPF_Fs176400_Gain13_B1},
-                    {HPF_Fs176400_Gain14_A1,             /* Gain Setting  14 */
-                    HPF_Fs176400_Gain14_A0,
-                    -HPF_Fs176400_Gain14_B1},
-                    {HPF_Fs176400_Gain15_A1,             /* Gain Setting  15 */
-                    HPF_Fs176400_Gain15_A0,
-                    -HPF_Fs176400_Gain15_B1},
+        /* 176kHz Sampling rate */
+        {HPF_Fs176400_Gain1_A1, /* Gain Setting  1 */
+         HPF_Fs176400_Gain1_A0, -HPF_Fs176400_Gain1_B1},
+        {HPF_Fs176400_Gain2_A1, /* Gain Setting  2 */
+         HPF_Fs176400_Gain2_A0, -HPF_Fs176400_Gain2_B1},
+        {HPF_Fs176400_Gain3_A1, /* Gain Setting  3 */
+         HPF_Fs176400_Gain3_A0, -HPF_Fs176400_Gain3_B1},
+        {HPF_Fs176400_Gain4_A1, /* Gain Setting  4 */
+         HPF_Fs176400_Gain4_A0, -HPF_Fs176400_Gain4_B1},
+        {HPF_Fs176400_Gain5_A1, /* Gain Setting  5 */
+         HPF_Fs176400_Gain5_A0, -HPF_Fs176400_Gain5_B1},
+        {HPF_Fs176400_Gain6_A1, /* Gain Setting  6 */
+         HPF_Fs176400_Gain6_A0, -HPF_Fs176400_Gain6_B1},
+        {HPF_Fs176400_Gain7_A1, /* Gain Setting  7 */
+         HPF_Fs176400_Gain7_A0, -HPF_Fs176400_Gain7_B1},
+        {HPF_Fs176400_Gain8_A1, /* Gain Setting  8 */
+         HPF_Fs176400_Gain8_A0, -HPF_Fs176400_Gain8_B1},
+        {HPF_Fs176400_Gain9_A1, /* Gain Setting  9 */
+         HPF_Fs176400_Gain9_A0, -HPF_Fs176400_Gain9_B1},
+        {HPF_Fs176400_Gain10_A1, /* Gain Setting  10 */
+         HPF_Fs176400_Gain10_A0, -HPF_Fs176400_Gain10_B1},
+        {HPF_Fs176400_Gain11_A1, /* Gain Setting  11 */
+         HPF_Fs176400_Gain11_A0, -HPF_Fs176400_Gain11_B1},
+        {HPF_Fs176400_Gain12_A1, /* Gain Setting  12 */
+         HPF_Fs176400_Gain12_A0, -HPF_Fs176400_Gain12_B1},
+        {HPF_Fs176400_Gain13_A1, /* Gain Setting  13 */
+         HPF_Fs176400_Gain13_A0, -HPF_Fs176400_Gain13_B1},
+        {HPF_Fs176400_Gain14_A1, /* Gain Setting  14 */
+         HPF_Fs176400_Gain14_A0, -HPF_Fs176400_Gain14_B1},
+        {HPF_Fs176400_Gain15_A1, /* Gain Setting  15 */
+         HPF_Fs176400_Gain15_A0, -HPF_Fs176400_Gain15_B1},
 
-                    /* 192kHz sampling rate */
-                    {HPF_Fs192000_Gain1_A1,             /* Gain setting 1 */
-                    HPF_Fs192000_Gain1_A0,
-                    -HPF_Fs192000_Gain1_B1},
-                    {HPF_Fs192000_Gain2_A1,             /* Gain setting 2 */
-                    HPF_Fs192000_Gain2_A0,
-                    -HPF_Fs192000_Gain2_B1},
-                    {HPF_Fs192000_Gain3_A1,             /* Gain setting 3 */
-                    HPF_Fs192000_Gain3_A0,
-                    -HPF_Fs192000_Gain3_B1},
-                    {HPF_Fs192000_Gain4_A1,             /* Gain setting 4 */
-                    HPF_Fs192000_Gain4_A0,
-                    -HPF_Fs192000_Gain4_B1},
-                    {HPF_Fs192000_Gain5_A1,             /* Gain setting 5 */
-                    HPF_Fs192000_Gain5_A0,
-                    -HPF_Fs192000_Gain5_B1},
-                    {HPF_Fs192000_Gain6_A1,             /* Gain setting 6 */
-                    HPF_Fs192000_Gain6_A0,
-                    -HPF_Fs192000_Gain6_B1},
-                    {HPF_Fs192000_Gain7_A1,             /* Gain setting 7 */
-                    HPF_Fs192000_Gain7_A0,
-                    -HPF_Fs192000_Gain7_B1},
-                    {HPF_Fs192000_Gain8_A1,             /* Gain setting 8 */
-                    HPF_Fs192000_Gain8_A0,
-                    -HPF_Fs192000_Gain8_B1},
-                    {HPF_Fs192000_Gain9_A1,             /* Gain setting 9 */
-                    HPF_Fs192000_Gain9_A0,
-                    -HPF_Fs192000_Gain9_B1},
-                    {HPF_Fs192000_Gain10_A1,             /* Gain setting 10 */
-                    HPF_Fs192000_Gain10_A0,
-                    -HPF_Fs192000_Gain10_B1},
-                    {HPF_Fs192000_Gain11_A1,             /* Gain setting 11 */
-                    HPF_Fs192000_Gain11_A0,
-                    -HPF_Fs192000_Gain11_B1},
-                    {HPF_Fs192000_Gain12_A1,             /* Gain setting 12 */
-                    HPF_Fs192000_Gain12_A0,
-                    -HPF_Fs192000_Gain12_B1},
-                    {HPF_Fs192000_Gain13_A1,             /* Gain setting 13 */
-                    HPF_Fs192000_Gain13_A0,
-                    -HPF_Fs192000_Gain13_B1},
-                    {HPF_Fs192000_Gain14_A1,             /* Gain setting 14 */
-                    HPF_Fs192000_Gain14_A0,
-                    -HPF_Fs192000_Gain14_B1},
-                    {HPF_Fs192000_Gain15_A1,             /* Gain setting 15 */
-                    HPF_Fs192000_Gain15_A0,
-                    -HPF_Fs192000_Gain15_B1}
-                    };
+        /* 192kHz sampling rate */
+        {HPF_Fs192000_Gain1_A1, /* Gain setting 1 */
+         HPF_Fs192000_Gain1_A0, -HPF_Fs192000_Gain1_B1},
+        {HPF_Fs192000_Gain2_A1, /* Gain setting 2 */
+         HPF_Fs192000_Gain2_A0, -HPF_Fs192000_Gain2_B1},
+        {HPF_Fs192000_Gain3_A1, /* Gain setting 3 */
+         HPF_Fs192000_Gain3_A0, -HPF_Fs192000_Gain3_B1},
+        {HPF_Fs192000_Gain4_A1, /* Gain setting 4 */
+         HPF_Fs192000_Gain4_A0, -HPF_Fs192000_Gain4_B1},
+        {HPF_Fs192000_Gain5_A1, /* Gain setting 5 */
+         HPF_Fs192000_Gain5_A0, -HPF_Fs192000_Gain5_B1},
+        {HPF_Fs192000_Gain6_A1, /* Gain setting 6 */
+         HPF_Fs192000_Gain6_A0, -HPF_Fs192000_Gain6_B1},
+        {HPF_Fs192000_Gain7_A1, /* Gain setting 7 */
+         HPF_Fs192000_Gain7_A0, -HPF_Fs192000_Gain7_B1},
+        {HPF_Fs192000_Gain8_A1, /* Gain setting 8 */
+         HPF_Fs192000_Gain8_A0, -HPF_Fs192000_Gain8_B1},
+        {HPF_Fs192000_Gain9_A1, /* Gain setting 9 */
+         HPF_Fs192000_Gain9_A0, -HPF_Fs192000_Gain9_B1},
+        {HPF_Fs192000_Gain10_A1, /* Gain setting 10 */
+         HPF_Fs192000_Gain10_A0, -HPF_Fs192000_Gain10_B1},
+        {HPF_Fs192000_Gain11_A1, /* Gain setting 11 */
+         HPF_Fs192000_Gain11_A0, -HPF_Fs192000_Gain11_B1},
+        {HPF_Fs192000_Gain12_A1, /* Gain setting 12 */
+         HPF_Fs192000_Gain12_A0, -HPF_Fs192000_Gain12_B1},
+        {HPF_Fs192000_Gain13_A1, /* Gain setting 13 */
+         HPF_Fs192000_Gain13_A0, -HPF_Fs192000_Gain13_B1},
+        {HPF_Fs192000_Gain14_A1, /* Gain setting 14 */
+         HPF_Fs192000_Gain14_A0, -HPF_Fs192000_Gain14_B1},
+        {HPF_Fs192000_Gain15_A1, /* Gain setting 15 */
+         HPF_Fs192000_Gain15_A0, -HPF_Fs192000_Gain15_B1}};
 
 /************************************************************************************/
 /*                                                                                    */
@@ -463,14 +329,13 @@
 /************************************************************************************/
 
 /* dB to linear conversion table */
-const LVM_FLOAT LVM_VolumeTable[] = {
-    1.000f,             /*  0dB */
-    0.891f,             /* -1dB */
-    0.794f,             /* -2dB */
-    0.708f,             /* -3dB */
-    0.631f,             /* -4dB */
-    0.562f,             /* -5dB */
-    0.501f};            /* -6dB */
+const LVM_FLOAT LVM_VolumeTable[] = {1.000f,  /*  0dB */
+                                     0.891f,  /* -1dB */
+                                     0.794f,  /* -2dB */
+                                     0.708f,  /* -3dB */
+                                     0.631f,  /* -4dB */
+                                     0.562f,  /* -5dB */
+                                     0.501f}; /* -6dB */
 
 /************************************************************************************/
 /*                                                                                  */
@@ -478,24 +343,16 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#define LVM_MIX_TC_Fs8000      32580         /* Floating point value 0.994262695 */
-#define LVM_MIX_TC_Fs11025     32632         /* Floating point value 0.995849609 */
-#define LVM_MIX_TC_Fs12000     32643         /* Floating point value 0.996185303 */
-#define LVM_MIX_TC_Fs16000     32674         /* Floating point value 0.997131348 */
-#define LVM_MIX_TC_Fs22050     32700         /* Floating point value 0.997924805 */
-#define LVM_MIX_TC_Fs24000     32705         /* Floating point value 0.998077393 */
-#define LVM_MIX_TC_Fs32000     32721         /* Floating point value 0.998565674 */
-#define LVM_MIX_TC_Fs44100     32734         /* Floating point value 0.998962402 */
-#define LVM_MIX_TC_Fs48000     32737         /* Floating point value 0.999053955 */
+#define LVM_MIX_TC_Fs8000 32580  /* Floating point value 0.994262695 */
+#define LVM_MIX_TC_Fs11025 32632 /* Floating point value 0.995849609 */
+#define LVM_MIX_TC_Fs12000 32643 /* Floating point value 0.996185303 */
+#define LVM_MIX_TC_Fs16000 32674 /* Floating point value 0.997131348 */
+#define LVM_MIX_TC_Fs22050 32700 /* Floating point value 0.997924805 */
+#define LVM_MIX_TC_Fs24000 32705 /* Floating point value 0.998077393 */
+#define LVM_MIX_TC_Fs32000 32721 /* Floating point value 0.998565674 */
+#define LVM_MIX_TC_Fs44100 32734 /* Floating point value 0.998962402 */
+#define LVM_MIX_TC_Fs48000 32737 /* Floating point value 0.999053955 */
 
-const LVM_INT16 LVM_MixerTCTable[] = {
-    LVM_MIX_TC_Fs8000,
-    LVM_MIX_TC_Fs11025,
-    LVM_MIX_TC_Fs12000,
-    LVM_MIX_TC_Fs16000,
-    LVM_MIX_TC_Fs22050,
-    LVM_MIX_TC_Fs24000,
-    LVM_MIX_TC_Fs32000,
-    LVM_MIX_TC_Fs44100,
-    LVM_MIX_TC_Fs48000};
-
+const LVM_INT16 LVM_MixerTCTable[] = {LVM_MIX_TC_Fs8000,  LVM_MIX_TC_Fs11025, LVM_MIX_TC_Fs12000,
+                                      LVM_MIX_TC_Fs16000, LVM_MIX_TC_Fs22050, LVM_MIX_TC_Fs24000,
+                                      LVM_MIX_TC_Fs32000, LVM_MIX_TC_Fs44100, LVM_MIX_TC_Fs48000};
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Tables.h b/media/libeffects/lvm/lib/Bundle/src/LVM_Tables.h
index fc82194..cf2fb5d 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Tables.h
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Tables.h
@@ -33,7 +33,7 @@
 /*                                                                                  */
 /************************************************************************************/
 
-extern FO_FLOAT_LShx_Coefs_t     LVM_TrebleBoostCoefs[];
+extern FO_FLOAT_LShx_Coefs_t LVM_TrebleBoostCoefs[];
 
 /************************************************************************************/
 /*                                                                                  */
@@ -45,4 +45,3 @@
 extern const LVM_INT16 LVM_MixerTCTable[];
 
 #endif /* __LVM_TABLES_H__ */
-
diff --git a/media/libeffects/lvm/lib/Common/lib/AGC.h b/media/libeffects/lvm/lib/Common/lib/AGC.h
index bef7fa1..31c8200 100644
--- a/media/libeffects/lvm/lib/Common/lib/AGC.h
+++ b/media/libeffects/lvm/lib/Common/lib/AGC.h
@@ -31,16 +31,15 @@
 /*    Types                                                                       */
 /*                                                                                */
 /**********************************************************************************/
-typedef struct
-{
-    LVM_FLOAT  AGC_Gain;                        /* The current AGC gain */
-    LVM_FLOAT  AGC_MaxGain;                     /* The maximum AGC gain */
-    LVM_FLOAT  Volume;                          /* The current volume setting */
-    LVM_FLOAT  Target;                          /* The target volume setting */
-    LVM_FLOAT  AGC_Target;                      /* AGC target level */
-    LVM_FLOAT  AGC_Attack;                      /* AGC attack scaler */
-    LVM_FLOAT  AGC_Decay;                       /* AGC decay scaler */
-    LVM_FLOAT  VolumeTC;                        /* Volume update time constant */
+typedef struct {
+    LVM_FLOAT AGC_Gain;    /* The current AGC gain */
+    LVM_FLOAT AGC_MaxGain; /* The maximum AGC gain */
+    LVM_FLOAT Volume;      /* The current volume setting */
+    LVM_FLOAT Target;      /* The target volume setting */
+    LVM_FLOAT AGC_Target;  /* AGC target level */
+    LVM_FLOAT AGC_Attack;  /* AGC attack scaler */
+    LVM_FLOAT AGC_Decay;   /* AGC decay scaler */
+    LVM_FLOAT VolumeTC;    /* Volume update time constant */
 
 } AGC_MIX_VOL_2St1Mon_FLOAT_t;
 
@@ -49,19 +48,11 @@
 /*    Function Prototypes                                                              */
 /*                                                                                */
 /**********************************************************************************/
-void AGC_MIX_VOL_2St1Mon_D32_WRA(AGC_MIX_VOL_2St1Mon_FLOAT_t  *pInstance,     /* Instance pointer */
-                                 const LVM_FLOAT            *pStSrc,        /* Stereo source */
-                                 const LVM_FLOAT            *pMonoSrc,      /* Mono source */
-                                 LVM_FLOAT                  *pDst,          /* Stereo destination */
-                                 LVM_UINT16                 n);             /* Number of samples */
-#ifdef SUPPORT_MC
-void AGC_MIX_VOL_Mc1Mon_D32_WRA(AGC_MIX_VOL_2St1Mon_FLOAT_t  *pInstance,  /* Instance pointer */
-                                 const LVM_FLOAT            *pStSrc,      /* Source */
-                                 const LVM_FLOAT            *pMonoSrc,    /* Mono source */
-                                 LVM_FLOAT                  *pDst,        /* Destination */
-                                 LVM_UINT16                 NrFrames,     /* Number of frames */
-                                 LVM_UINT16                 NrChannels);  /* Number of channels */
-#endif
+void AGC_MIX_VOL_Mc1Mon_D32_WRA(AGC_MIX_VOL_2St1Mon_FLOAT_t* pInstance,  /* Instance pointer */
+                                const LVM_FLOAT* pStSrc,                 /* Source */
+                                const LVM_FLOAT* pMonoSrc,               /* Mono source */
+                                LVM_FLOAT* pDst,                         /* Destination */
+                                LVM_UINT16 NrFrames,                     /* Number of frames */
+                                LVM_UINT16 NrChannels);                  /* Number of channels */
 
-#endif  /* __AGC_H__ */
-
+#endif /* __AGC_H__ */
diff --git a/media/libeffects/lvm/lib/Common/lib/BIQUAD.h b/media/libeffects/lvm/lib/Common/lib/BIQUAD.h
index c050cd0..00b539a 100644
--- a/media/libeffects/lvm/lib/Common/lib/BIQUAD.h
+++ b/media/libeffects/lvm/lib/Common/lib/BIQUAD.h
@@ -22,281 +22,67 @@
 /**********************************************************************************
    INSTANCE MEMORY TYPE DEFINITION
 ***********************************************************************************/
-typedef struct
-{
-#ifdef SUPPORT_MC
+typedef struct {
     /* The memory region created by this structure instance is typecast
      * into another structure containing a pointer and an array of filter
      * coefficients. In one case this memory region is used for storing
      * DC component of channels
      */
-    LVM_FLOAT *pStorage;
+    LVM_FLOAT* pStorage;
     LVM_FLOAT Storage[LVM_MAX_CHANNELS];
-#else
-    LVM_FLOAT Storage[6];
-#endif
 } Biquad_FLOAT_Instance_t;
 /**********************************************************************************
    COEFFICIENT TYPE DEFINITIONS
 ***********************************************************************************/
 
 /*** Biquad coefficients **********************************************************/
-typedef struct
-{
-    LVM_FLOAT  A2;   /*  a2  */
-    LVM_FLOAT  A1;   /*  a1  */
-    LVM_FLOAT  A0;   /*  a0  */
-    LVM_FLOAT  B2;   /* -b2! */
-    LVM_FLOAT  B1;   /* -b1! */
+typedef struct {
+    LVM_FLOAT A2; /*  a2  */
+    LVM_FLOAT A1; /*  a1  */
+    LVM_FLOAT A0; /*  a0  */
+    LVM_FLOAT B2; /* -b2! */
+    LVM_FLOAT B1; /* -b1! */
 } BQ_FLOAT_Coefs_t;
 
 /*** First order coefficients *****************************************************/
-typedef struct
-{
-    LVM_FLOAT A1;   /*  a1  */
-    LVM_FLOAT A0;   /*  a0  */
-    LVM_FLOAT B1;   /* -b1! */
+typedef struct {
+    LVM_FLOAT A1; /*  a1  */
+    LVM_FLOAT A0; /*  a0  */
+    LVM_FLOAT B1; /* -b1! */
 } FO_FLOAT_Coefs_t;
 
 /*** First order coefficients with Shift*****************************************************/
-typedef struct
-{
-    LVM_FLOAT A1;    /*  a1  */
-    LVM_FLOAT A0;    /*  a0  */
-    LVM_FLOAT B1;    /* -b1! */
+typedef struct {
+    LVM_FLOAT A1; /*  a1  */
+    LVM_FLOAT A0; /*  a0  */
+    LVM_FLOAT B1; /* -b1! */
 } FO_FLOAT_LShx_Coefs_t;
 /*** Band pass coefficients *******************************************************/
-typedef struct
-{
-    LVM_FLOAT  A0;   /*  a0  */
-    LVM_FLOAT  B2;   /* -b2! */
-    LVM_FLOAT  B1;   /* -b1! */
+typedef struct {
+    LVM_FLOAT A0; /*  a0  */
+    LVM_FLOAT B2; /* -b2! */
+    LVM_FLOAT B1; /* -b1! */
 } BP_FLOAT_Coefs_t;
 
 /*** Peaking coefficients *********************************************************/
-typedef struct
-{
-    LVM_FLOAT A0;   /*  a0  */
-    LVM_FLOAT B2;   /* -b2! */
-    LVM_FLOAT B1;   /* -b1! */
-    LVM_FLOAT  G;   /* Gain */
+typedef struct {
+    LVM_FLOAT A0; /*  a0  */
+    LVM_FLOAT B2; /* -b2! */
+    LVM_FLOAT B1; /* -b1! */
+    LVM_FLOAT G;  /* Gain */
 } PK_FLOAT_Coefs_t;
 
-/**********************************************************************************
-   TAPS TYPE DEFINITIONS
-***********************************************************************************/
-
-/*** Types used for first order and shelving filter *******************************/
-typedef struct
-{
-    LVM_FLOAT Storage[ (1 * 2) ];  /* One channel, two taps of size LVM_INT32 */
-} Biquad_1I_Order1_FLOAT_Taps_t;
-
-typedef struct
-{
-#ifdef SUPPORT_MC
-    /* LVM_MAX_CHANNELS channels, two taps of size LVM_FLOAT */
-    LVM_FLOAT Storage[ (LVM_MAX_CHANNELS * 2) ];
-#else
-    LVM_FLOAT Storage[ (2 * 2) ];  /* Two channels, two taps of size LVM_FLOAT */
-#endif
-} Biquad_2I_Order1_FLOAT_Taps_t;
-
-/*** Types used for biquad, band pass and peaking filter **************************/
-typedef struct
-{
-    LVM_FLOAT Storage[ (1 * 4) ];  /* One channel, four taps of size LVM_FLOAT */
-} Biquad_1I_Order2_FLOAT_Taps_t;
-
-typedef struct
-{
-#ifdef SUPPORT_MC
-    /* LVM_MAX_CHANNELS, four taps of size LVM_FLOAT */
-    LVM_FLOAT Storage[ (LVM_MAX_CHANNELS * 4) ];
-#else
-    LVM_FLOAT Storage[ (2 * 4) ];  /* Two channels, four taps of size LVM_FLOAT */
-#endif
-} Biquad_2I_Order2_FLOAT_Taps_t;
-/* The names of the functions are changed to satisfy QAC rules: Name should be Unique withing 16 characters*/
-#define BQ_2I_D32F32Cll_TRC_WRA_01_Init  Init_BQ_2I_D32F32Cll_TRC_WRA_01
-#define BP_1I_D32F32C30_TRC_WRA_02       TWO_BP_1I_D32F32C30_TRC_WRA_02
-
-/**********************************************************************************
-   FUNCTION PROTOTYPES: BIQUAD FILTERS
-***********************************************************************************/
-
-/*** 16 bit data path *************************************************************/
-
-void BQ_2I_D16F32Css_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_2I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BQ_FLOAT_Coefs_t            *pCoef);
-
-void BQ_2I_D16F32C15_TRC_WRA_01 (           Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrSamples);
-
-void BQ_2I_D16F32C14_TRC_WRA_01 (           Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrSamples);
-
-void BQ_2I_D16F32C13_TRC_WRA_01 (           Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrSamples);
-
-void BQ_2I_D16F16Css_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_2I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BQ_FLOAT_Coefs_t            *pCoef);
-
-void BQ_2I_D16F16C15_TRC_WRA_01( Biquad_FLOAT_Instance_t       *pInstance,
-                                 LVM_FLOAT               *pDataIn,
-                                 LVM_FLOAT               *pDataOut,
-                                 LVM_INT16               NrSamples);
-
-void BQ_2I_D16F16C14_TRC_WRA_01( Biquad_FLOAT_Instance_t       *pInstance,
-                                 LVM_FLOAT               *pDataIn,
-                                 LVM_FLOAT               *pDataOut,
-                                 LVM_INT16               NrSamples);
-
-void BQ_1I_D16F16Css_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_1I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BQ_FLOAT_Coefs_t            *pCoef);
-
-void BQ_1I_D16F16C15_TRC_WRA_01 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                  LVM_FLOAT               *pDataIn,
-                                  LVM_FLOAT               *pDataOut,
-                                  LVM_INT16               NrSamples);
-
-void BQ_1I_D16F32Css_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_1I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BQ_FLOAT_Coefs_t            *pCoef);
-
-void BQ_1I_D16F32C14_TRC_WRA_01 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                  LVM_FLOAT              *pDataIn,
-                                  LVM_FLOAT               *pDataOut,
-                                  LVM_INT16               NrSamples);
-/*** 32 bit data path *************************************************************/
-void BQ_2I_D32F32Cll_TRC_WRA_01_Init (      Biquad_FLOAT_Instance_t       *pInstance,
-                                            Biquad_2I_Order2_FLOAT_Taps_t *pTaps,
-                                            BQ_FLOAT_Coefs_t          *pCoef);
-void BQ_2I_D32F32C30_TRC_WRA_01 (           Biquad_FLOAT_Instance_t  *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                 NrSamples);
-#ifdef SUPPORT_MC
-void BQ_MC_D32F32C30_TRC_WRA_01 (           Biquad_FLOAT_Instance_t      *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrFrames,
-                                            LVM_INT16                    NrChannels);
-#endif
-
-/**********************************************************************************
-   FUNCTION PROTOTYPES: FIRST ORDER FILTERS
-***********************************************************************************/
-
-/*** 16 bit data path *************************************************************/
-void FO_1I_D16F16Css_TRC_WRA_01_Init(    Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_1I_Order1_FLOAT_Taps_t   *pTaps,
-                                         FO_FLOAT_Coefs_t            *pCoef);
-
-void FO_1I_D16F16C15_TRC_WRA_01( Biquad_FLOAT_Instance_t       *pInstance,
-                                 LVM_FLOAT               *pDataIn,
-                                 LVM_FLOAT               *pDataOut,
-                                 LVM_INT16               NrSamples);
-
-void FO_2I_D16F32Css_LShx_TRC_WRA_01_Init(Biquad_FLOAT_Instance_t       *pInstance,
-                                          Biquad_2I_Order1_FLOAT_Taps_t *pTaps,
-                                          FO_FLOAT_LShx_Coefs_t     *pCoef);
-
-void FO_2I_D16F32C15_LShx_TRC_WRA_01(Biquad_FLOAT_Instance_t       *pInstance,
-                                     LVM_FLOAT               *pDataIn,
-                                     LVM_FLOAT               *pDataOut,
-                                     LVM_INT16               NrSamples);
-/*** 32 bit data path *************************************************************/
-void FO_1I_D32F32Cll_TRC_WRA_01_Init( Biquad_FLOAT_Instance_t       *pInstance,
-                                      Biquad_1I_Order1_FLOAT_Taps_t *pTaps,
-                                      FO_FLOAT_Coefs_t          *pCoef);
-void FO_1I_D32F32C31_TRC_WRA_01( Biquad_FLOAT_Instance_t       *pInstance,
-                                 LVM_FLOAT                     *pDataIn,
-                                 LVM_FLOAT                     *pDataOut,
-                                 LVM_INT16                     NrSamples);
-#ifdef SUPPORT_MC
-void FO_Mc_D16F32C15_LShx_TRC_WRA_01(Biquad_FLOAT_Instance_t  *pInstance,
-                                     LVM_FLOAT                *pDataIn,
-                                     LVM_FLOAT                *pDataOut,
-                                     LVM_INT16                NrFrames,
-                                     LVM_INT16                NrChannels);
-#endif
-/**********************************************************************************
-   FUNCTION PROTOTYPES: BAND PASS FILTERS
-***********************************************************************************/
-
-/*** 16 bit data path *************************************************************/
-void BP_1I_D16F16Css_TRC_WRA_01_Init( Biquad_FLOAT_Instance_t       *pInstance,
-                                      Biquad_1I_Order2_FLOAT_Taps_t *pTaps,
-                                      BP_FLOAT_Coefs_t              *pCoef);
-void BP_1I_D16F16C14_TRC_WRA_01 (     Biquad_FLOAT_Instance_t       *pInstance,
-                                      LVM_FLOAT                     *pDataIn,
-                                      LVM_FLOAT                     *pDataOut,
-                                      LVM_INT16                     NrSamples);
-void BP_1I_D16F32Cll_TRC_WRA_01_Init (Biquad_FLOAT_Instance_t       *pInstance,
-                                      Biquad_1I_Order2_FLOAT_Taps_t *pTaps,
-                                      BP_FLOAT_Coefs_t              *pCoef);
-void BP_1I_D16F32C30_TRC_WRA_01 (           Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrSamples);
-/*** 32 bit data path *************************************************************/
-void BP_1I_D32F32Cll_TRC_WRA_02_Init (      Biquad_FLOAT_Instance_t       *pInstance,
-                                            Biquad_1I_Order2_FLOAT_Taps_t *pTaps,
-                                            BP_FLOAT_Coefs_t          *pCoef);
-void BP_1I_D32F32C30_TRC_WRA_02(            Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrSamples);
-
-/*** 32 bit data path STEREO ******************************************************/
-void PK_2I_D32F32CssGss_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t       *pInstance,
-                                            Biquad_2I_Order2_FLOAT_Taps_t *pTaps,
-                                            PK_FLOAT_Coefs_t          *pCoef);
-void PK_2I_D32F32C14G11_TRC_WRA_01( Biquad_FLOAT_Instance_t       *pInstance,
-                                    LVM_FLOAT               *pDataIn,
-                                    LVM_FLOAT               *pDataOut,
-                                    LVM_INT16               NrSamples);
-#ifdef SUPPORT_MC
-void PK_Mc_D32F32C14G11_TRC_WRA_01(Biquad_FLOAT_Instance_t       *pInstance,
-                                   LVM_FLOAT               *pDataIn,
-                                   LVM_FLOAT               *pDataOut,
-                                   LVM_INT16               NrFrames,
-                                   LVM_INT16               NrChannels);
-#endif
 
 /**********************************************************************************
    FUNCTION PROTOTYPES: DC REMOVAL FILTERS
 ***********************************************************************************/
 
 /*** 16 bit data path STEREO ******************************************************/
-#ifdef SUPPORT_MC
-void DC_Mc_D16_TRC_WRA_01_Init     (        Biquad_FLOAT_Instance_t       *pInstance);
+void DC_Mc_D16_TRC_WRA_01_Init(Biquad_FLOAT_Instance_t* pInstance);
 
-void DC_Mc_D16_TRC_WRA_01          (        Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT               *pDataIn,
-                                            LVM_FLOAT               *pDataOut,
-                                            LVM_INT16               NrFrames,
-                                            LVM_INT16               NrChannels);
-#else
-void DC_2I_D16_TRC_WRA_01_Init     (        Biquad_FLOAT_Instance_t       *pInstance);
-
-void DC_2I_D16_TRC_WRA_01          (        Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT               *pDataIn,
-                                            LVM_FLOAT               *pDataOut,
-                                            LVM_INT16               NrSamples);
-#endif
+void DC_Mc_D16_TRC_WRA_01(Biquad_FLOAT_Instance_t* pInstance, LVM_FLOAT* pDataIn,
+                          LVM_FLOAT* pDataOut, LVM_INT16 NrFrames, LVM_INT16 NrChannels);
 
 /**********************************************************************************/
 
-#endif  /** _BIQUAD_H_ **/
-
+#endif /** _BIQUAD_H_ **/
diff --git a/media/libeffects/lvm/lib/Common/lib/CompLim.h b/media/libeffects/lvm/lib/Common/lib/CompLim.h
index 5b7cb1b..2fc78b4 100644
--- a/media/libeffects/lvm/lib/Common/lib/CompLim.h
+++ b/media/libeffects/lvm/lib/Common/lib/CompLim.h
@@ -35,21 +35,21 @@
 typedef struct /* Compressor state */
 {
     /* Normaliser */
-    LVM_INT16   Norm_Attack;        /* Attack time constant of the Normaliser integrator */
-    LVM_INT16   Norm_Decay;         /* Decay time constant of the Normaliser integrator */
-    LVM_INT32   NormInt;            /* Normaliser integrator current value */
-    LVM_INT16   Shift;              /* Shift gain */
-    LVM_INT16   Threshold;          /* Target threshold */
+    LVM_INT16 Norm_Attack; /* Attack time constant of the Normaliser integrator */
+    LVM_INT16 Norm_Decay;  /* Decay time constant of the Normaliser integrator */
+    LVM_INT32 NormInt;     /* Normaliser integrator current value */
+    LVM_INT16 Shift;       /* Shift gain */
+    LVM_INT16 Threshold;   /* Target threshold */
 
     /* Compressor */
-    LVM_INT16   Comp_Atten;         /* Attenuation applied before soft knee compressor */
-    LVM_INT16   Comp_Attack_S;      /* Attack time constant of the slow integrator */
-    LVM_INT16   Comp_Decay_S;       /* Decay time constant of slow the integrator */
-    LVM_INT16   Comp_Attack_F;      /* Attack time constant of fast the integrator */
-    LVM_INT16   Comp_Decay_F;       /* Decay time constant of fast the integrator */
-    LVM_INT16   SoftClipGain;       /* Soft clip gain control */
-    LVM_INT32   CompIntSlow;        /* Compressor slow integrator current value */
-    LVM_INT32   CompIntFast;        /* Compressor fast integrator current value */
+    LVM_INT16 Comp_Atten;    /* Attenuation applied before soft knee compressor */
+    LVM_INT16 Comp_Attack_S; /* Attack time constant of the slow integrator */
+    LVM_INT16 Comp_Decay_S;  /* Decay time constant of slow the integrator */
+    LVM_INT16 Comp_Attack_F; /* Attack time constant of fast the integrator */
+    LVM_INT16 Comp_Decay_F;  /* Decay time constant of fast the integrator */
+    LVM_INT16 SoftClipGain;  /* Soft clip gain control */
+    LVM_INT32 CompIntSlow;   /* Compressor slow integrator current value */
+    LVM_INT32 CompIntFast;   /* Compressor fast integrator current value */
 
 } CompLim_Instance_t;
 
@@ -58,10 +58,7 @@
 /*  Function Prototypes                                                             */
 /*                                                                                  */
 /************************************************************************************/
-void NonLinComp_Float(LVM_FLOAT        Gain,
-                      LVM_FLOAT        *pDataIn,
-                      LVM_FLOAT        *pDataOut,
-                      LVM_INT32        BlockLength);
+void NonLinComp_Float(LVM_FLOAT Gain, LVM_FLOAT* pDataIn, LVM_FLOAT* pDataOut,
+                      LVM_INT32 BlockLength);
 
 #endif /* #ifndef _COMP_LIM_H */
-
diff --git a/media/libeffects/lvm/lib/Common/lib/Filter.h b/media/libeffects/lvm/lib/Common/lib/Filter.h
index 1eeb321..0ba5223 100644
--- a/media/libeffects/lvm/lib/Common/lib/Filter.h
+++ b/media/libeffects/lvm/lib/Common/lib/Filter.h
@@ -27,26 +27,20 @@
 /**********************************************************************************
    DEFINES
 ***********************************************************************************/
-#define FILTER_LOSS     32730       /* -0.01dB loss to avoid wrapping due to band ripple */
-#define FILTER_LOSS_FLOAT    0.998849f
+#define FILTER_LOSS 32730 /* -0.01dB loss to avoid wrapping due to band ripple */
+#define FILTER_LOSS_FLOAT 0.998849f
 /**********************************************************************************
    FUNCTION PROTOTYPES
 ***********************************************************************************/
 
-LVM_FLOAT LVM_Power10(   LVM_FLOAT  X);
+LVM_FLOAT LVM_Power10(LVM_FLOAT X);
 
-LVM_FLOAT LVM_Polynomial(LVM_UINT16 N,
-                         LVM_FLOAT  *pCoefficients,
-                         LVM_FLOAT  X);
-LVM_FLOAT   LVM_GetOmega(LVM_UINT32  Fc,
-                         LVM_Fs_en   SampleRate);
+LVM_FLOAT LVM_Polynomial(LVM_UINT16 N, LVM_FLOAT* pCoefficients, LVM_FLOAT X);
+LVM_FLOAT LVM_GetOmega(LVM_UINT32 Fc, LVM_Fs_en SampleRate);
 
-LVM_FLOAT LVM_FO_LPF(    LVM_FLOAT  w,
-                         FO_FLOAT_Coefs_t  *pCoeffs);
+LVM_FLOAT LVM_FO_LPF(LVM_FLOAT w, FO_FLOAT_Coefs_t* pCoeffs);
 
-LVM_FLOAT LVM_FO_HPF(    LVM_FLOAT  w,
-                         FO_FLOAT_Coefs_t  *pCoeffs);
+LVM_FLOAT LVM_FO_HPF(LVM_FLOAT w, FO_FLOAT_Coefs_t* pCoeffs);
 /**********************************************************************************/
 
-#endif  /** _FILTER_H_ **/
-
+#endif /** _FILTER_H_ **/
diff --git a/media/libeffects/lvm/lib/Common/lib/InstAlloc.h b/media/libeffects/lvm/lib/Common/lib/InstAlloc.h
index bae84e7..17699ef 100644
--- a/media/libeffects/lvm/lib/Common/lib/InstAlloc.h
+++ b/media/libeffects/lvm/lib/Common/lib/InstAlloc.h
@@ -22,11 +22,10 @@
 /*######################################################################################*/
 /*  Type declarations                                                                   */
 /*######################################################################################*/
-typedef struct
-{
-    LVM_UINT32              TotalSize;      /*  Accumulative total memory size                      */
-    uintptr_t               pNextMember;    /*  Pointer to the next instance member to be allocated */
-}   INST_ALLOC;
+typedef struct {
+    LVM_UINT32 TotalSize;  /*  Accumulative total memory size                      */
+    uintptr_t pNextMember; /*  Pointer to the next instance member to be allocated */
+} INST_ALLOC;
 
 /*######################################################################################*/
 /*  Function prototypes                                                          */
@@ -41,7 +40,7 @@
  *  Remarks     :
  ****************************************************************************************/
 
-void   InstAlloc_Init( INST_ALLOC *pms, void *StartAddr );
+void InstAlloc_Init(INST_ALLOC* pms, void* StartAddr);
 
 /****************************************************************************************
  *  Name        : InstAlloc_AddMember()
@@ -54,7 +53,7 @@
  *  Remarks     :
  ****************************************************************************************/
 
-void* InstAlloc_AddMember( INST_ALLOC *pms, LVM_UINT32 Size );
+void* InstAlloc_AddMember(INST_ALLOC* pms, LVM_UINT32 Size);
 
 /****************************************************************************************
  *  Name        : InstAlloc_GetTotal()
@@ -64,19 +63,14 @@
  *  Remarks     :
  ****************************************************************************************/
 
-LVM_UINT32 InstAlloc_GetTotal( INST_ALLOC *pms);
+LVM_UINT32 InstAlloc_GetTotal(INST_ALLOC* pms);
 
-void*   InstAlloc_AddMemberAllRet(     INST_ALLOC                 *pms,
-                                     LVM_UINT32               Size[],
-                                     void                    **ptr);
+void* InstAlloc_AddMemberAllRet(INST_ALLOC* pms, LVM_UINT32 Size[], void** ptr);
 
-void*   InstAlloc_AddMemberAll( INST_ALLOC                     *pms,
-                                 LVM_UINT32                   Size[],
-                                 LVM_MemoryTable_st           *pMemoryTable);
+void* InstAlloc_AddMemberAll(INST_ALLOC* pms, LVM_UINT32 Size[], LVM_MemoryTable_st* pMemoryTable);
 
-void    InstAlloc_InitAll( INST_ALLOC                      *pms,
-                           LVM_MemoryTable_st             *pMemoryTable);
+void InstAlloc_InitAll(INST_ALLOC* pms, LVM_MemoryTable_st* pMemoryTable);
 
-void    InstAlloc_InitAll_NULL( INST_ALLOC              *pms);
+void InstAlloc_InitAll_NULL(INST_ALLOC* pms);
 
 #endif /* __JBS_INSTALLOC_H__ */
diff --git a/media/libeffects/lvm/lib/Common/lib/LVM_Common.h b/media/libeffects/lvm/lib/Common/lib/LVM_Common.h
index 49f16ad..d3d128a 100644
--- a/media/libeffects/lvm/lib/Common/lib/LVM_Common.h
+++ b/media/libeffects/lvm/lib/Common/lib/LVM_Common.h
@@ -39,12 +39,11 @@
 /*                                                                                      */
 /****************************************************************************************/
 /* Algorithm identification */
-#define ALGORITHM_NONE_ID      0x0000
-#define ALGORITHM_CS_ID        0x0100
-#define ALGORITHM_EQNB_ID      0x0200
-#define ALGORITHM_DBE_ID       0x0300
-#define ALGORITHM_VC_ID        0x0500
-#define ALGORITHM_TE_ID        0x0600
+#define ALGORITHM_NONE_ID 0x0000
+#define ALGORITHM_CS_ID 0x0100
+#define ALGORITHM_EQNB_ID 0x0200
+#define ALGORITHM_DBE_ID 0x0300
+#define ALGORITHM_VC_ID 0x0500
+#define ALGORITHM_TE_ID 0x0600
 
-#endif      /* __LVM_COMMON_H__ */
-
+#endif /* __LVM_COMMON_H__ */
diff --git a/media/libeffects/lvm/lib/Common/lib/LVM_Macros.h b/media/libeffects/lvm/lib/Common/lib/LVM_Macros.h
index 1a15125..b984745 100644
--- a/media/libeffects/lvm/lib/Common/lib/LVM_Macros.h
+++ b/media/libeffects/lvm/lib/Common/lib/LVM_Macros.h
@@ -28,31 +28,36 @@
         of overflow is undefined.
 
 ***********************************************************************************/
-#define MUL32x32INTO32(A,B,C,ShiftR)   \
-        {LVM_INT32 MUL32x32INTO32_temp,MUL32x32INTO32_temp2,MUL32x32INTO32_mask,MUL32x32INTO32_HH,MUL32x32INTO32_HL,MUL32x32INTO32_LH,MUL32x32INTO32_LL;\
-         LVM_INT32  shiftValue;\
-        shiftValue = (ShiftR);\
-        MUL32x32INTO32_mask=0x0000FFFF;\
-        MUL32x32INTO32_HH= ((LVM_INT32)((LVM_INT16)((A)>>16))*((LVM_INT16)((B)>>16)) );\
-        MUL32x32INTO32_HL= ((LVM_INT32)((B)&MUL32x32INTO32_mask)*((LVM_INT16)((A)>>16))) ;\
-        MUL32x32INTO32_LH= ((LVM_INT32)((A)&MUL32x32INTO32_mask)*((LVM_INT16)((B)>>16)));\
-        MUL32x32INTO32_LL= (LVM_INT32)((A)&MUL32x32INTO32_mask)*(LVM_INT32)((B)&MUL32x32INTO32_mask);\
-        MUL32x32INTO32_temp= (LVM_INT32)(MUL32x32INTO32_HL&MUL32x32INTO32_mask)+(LVM_INT32)(MUL32x32INTO32_LH&MUL32x32INTO32_mask)+(LVM_INT32)((MUL32x32INTO32_LL>>16)&MUL32x32INTO32_mask);\
-        MUL32x32INTO32_HH= MUL32x32INTO32_HH+(LVM_INT32)(MUL32x32INTO32_HL>>16)+(LVM_INT32)(MUL32x32INTO32_LH>>16)+(LVM_INT32)(MUL32x32INTO32_temp>>16);\
-        MUL32x32INTO32_LL=MUL32x32INTO32_LL+(LVM_INT32)(MUL32x32INTO32_HL<<16)+(LVM_INT32)(MUL32x32INTO32_LH<<16);\
-        if(shiftValue<32)\
-        {\
-        MUL32x32INTO32_HH=MUL32x32INTO32_HH<<(32-shiftValue);\
-        MUL32x32INTO32_mask=((LVM_INT32)1<<(32-shiftValue))-1;\
-        MUL32x32INTO32_LL=(MUL32x32INTO32_LL>>shiftValue)&MUL32x32INTO32_mask;\
-        MUL32x32INTO32_temp2=MUL32x32INTO32_HH|MUL32x32INTO32_LL;\
-        }\
-        else\
-       {\
-        MUL32x32INTO32_temp2=(LVM_INT32)MUL32x32INTO32_HH>>(shiftValue-32);\
-       }\
-       (C) = MUL32x32INTO32_temp2;\
-       }
+#define MUL32x32INTO32(A, B, C, ShiftR)                                                        \
+    {                                                                                          \
+        LVM_INT32 MUL32x32INTO32_temp, MUL32x32INTO32_temp2, MUL32x32INTO32_mask,              \
+                MUL32x32INTO32_HH, MUL32x32INTO32_HL, MUL32x32INTO32_LH, MUL32x32INTO32_LL;    \
+        LVM_INT32 shiftValue;                                                                  \
+        shiftValue = (ShiftR);                                                                 \
+        MUL32x32INTO32_mask = 0x0000FFFF;                                                      \
+        MUL32x32INTO32_HH = ((LVM_INT32)((LVM_INT16)((A) >> 16)) * ((LVM_INT16)((B) >> 16)));  \
+        MUL32x32INTO32_HL = ((LVM_INT32)((B)&MUL32x32INTO32_mask) * ((LVM_INT16)((A) >> 16))); \
+        MUL32x32INTO32_LH = ((LVM_INT32)((A)&MUL32x32INTO32_mask) * ((LVM_INT16)((B) >> 16))); \
+        MUL32x32INTO32_LL =                                                                    \
+                (LVM_INT32)((A)&MUL32x32INTO32_mask) * (LVM_INT32)((B)&MUL32x32INTO32_mask);   \
+        MUL32x32INTO32_temp = (LVM_INT32)(MUL32x32INTO32_HL & MUL32x32INTO32_mask) +           \
+                              (LVM_INT32)(MUL32x32INTO32_LH & MUL32x32INTO32_mask) +           \
+                              (LVM_INT32)((MUL32x32INTO32_LL >> 16) & MUL32x32INTO32_mask);    \
+        MUL32x32INTO32_HH = MUL32x32INTO32_HH + (LVM_INT32)(MUL32x32INTO32_HL >> 16) +         \
+                            (LVM_INT32)(MUL32x32INTO32_LH >> 16) +                             \
+                            (LVM_INT32)(MUL32x32INTO32_temp >> 16);                            \
+        MUL32x32INTO32_LL = MUL32x32INTO32_LL + (LVM_INT32)(MUL32x32INTO32_HL << 16) +         \
+                            (LVM_INT32)(MUL32x32INTO32_LH << 16);                              \
+        if (shiftValue < 32) {                                                                 \
+            MUL32x32INTO32_HH = MUL32x32INTO32_HH << (32 - shiftValue);                        \
+            MUL32x32INTO32_mask = ((LVM_INT32)1 << (32 - shiftValue)) - 1;                     \
+            MUL32x32INTO32_LL = (MUL32x32INTO32_LL >> shiftValue) & MUL32x32INTO32_mask;       \
+            MUL32x32INTO32_temp2 = MUL32x32INTO32_HH | MUL32x32INTO32_LL;                      \
+        } else {                                                                               \
+            MUL32x32INTO32_temp2 = (LVM_INT32)MUL32x32INTO32_HH >> (shiftValue - 32);          \
+        }                                                                                      \
+        (C) = MUL32x32INTO32_temp2;                                                            \
+    }
 
 /**********************************************************************************
    MUL32x16INTO32(A,B,C,ShiftR)
@@ -65,25 +70,24 @@
         of overflow is undefined.
 
 ***********************************************************************************/
-#define MUL32x16INTO32(A,B,C,ShiftR)   \
-        {LVM_INT32 MUL32x16INTO32_mask,MUL32x16INTO32_HH,MUL32x16INTO32_LL;\
-         LVM_INT32  shiftValue;\
-        shiftValue = (ShiftR);\
-        MUL32x16INTO32_mask=0x0000FFFF;\
-        MUL32x16INTO32_HH= ((LVM_INT32)(B)*((LVM_INT16)((A)>>16)));\
-        MUL32x16INTO32_LL= ((LVM_INT32)((A)&MUL32x16INTO32_mask)*(B));\
-        if(shiftValue<16)\
-        {\
-        MUL32x16INTO32_HH=(LVM_INT32)((LVM_UINT32)MUL32x16INTO32_HH<<(16-shiftValue));\
-        (C)=MUL32x16INTO32_HH+(LVM_INT32)(MUL32x16INTO32_LL>>shiftValue);\
-        }\
-        else if(shiftValue<32) {\
-        MUL32x16INTO32_HH=(LVM_INT32)(MUL32x16INTO32_HH>>(shiftValue-16));\
-        (C)=MUL32x16INTO32_HH+(LVM_INT32)(MUL32x16INTO32_LL>>shiftValue);\
-        }\
-        else {\
-        (C)=MUL32x16INTO32_HH>>(shiftValue-16);}\
-        }
+#define MUL32x16INTO32(A, B, C, ShiftR)                                                          \
+    {                                                                                            \
+        LVM_INT32 MUL32x16INTO32_mask, MUL32x16INTO32_HH, MUL32x16INTO32_LL;                     \
+        LVM_INT32 shiftValue;                                                                    \
+        shiftValue = (ShiftR);                                                                   \
+        MUL32x16INTO32_mask = 0x0000FFFF;                                                        \
+        MUL32x16INTO32_HH = ((LVM_INT32)(B) * ((LVM_INT16)((A) >> 16)));                         \
+        MUL32x16INTO32_LL = ((LVM_INT32)((A)&MUL32x16INTO32_mask) * (B));                        \
+        if (shiftValue < 16) {                                                                   \
+            MUL32x16INTO32_HH = (LVM_INT32)((LVM_UINT32)MUL32x16INTO32_HH << (16 - shiftValue)); \
+            (C) = MUL32x16INTO32_HH + (LVM_INT32)(MUL32x16INTO32_LL >> shiftValue);              \
+        } else if (shiftValue < 32) {                                                            \
+            MUL32x16INTO32_HH = (LVM_INT32)(MUL32x16INTO32_HH >> (shiftValue - 16));             \
+            (C) = MUL32x16INTO32_HH + (LVM_INT32)(MUL32x16INTO32_LL >> shiftValue);              \
+        } else {                                                                                 \
+            (C) = MUL32x16INTO32_HH >> (shiftValue - 16);                                        \
+        }                                                                                        \
+    }
 
 /**********************************************************************************
    ADD2_SAT_32x32(A,B,C)
@@ -91,16 +95,16 @@
 
         A,B and C are 32 bit SIGNED numbers.
 ***********************************************************************************/
-#define ADD2_SAT_32x32(A,B,C)   \
-        {(C)=(A)+(B);\
-         if ((((C) ^ (A)) & ((C) ^ (B))) >> 31)\
-            {\
-                if((A)<0)\
-                    (C)=0x80000000l;\
-                else\
-                    (C)=0x7FFFFFFFl;\
-            }\
-        }
+#define ADD2_SAT_32x32(A, B, C)                  \
+    {                                            \
+        (C) = (A) + (B);                         \
+        if ((((C) ^ (A)) & ((C) ^ (B))) >> 31) { \
+            if ((A) < 0)                         \
+                (C) = 0x80000000l;               \
+            else                                 \
+                (C) = 0x7FFFFFFFl;               \
+        }                                        \
+    }
 
 #endif /* _LVM_MACROS_H_ */
 
diff --git a/media/libeffects/lvm/lib/Common/lib/LVM_Timer.h b/media/libeffects/lvm/lib/Common/lib/LVM_Timer.h
index dbf9e6a..75f4785 100644
--- a/media/libeffects/lvm/lib/Common/lib/LVM_Timer.h
+++ b/media/libeffects/lvm/lib/Common/lib/LVM_Timer.h
@@ -37,8 +37,7 @@
 /*  TYPE DEFINITIONS                                                                    */
 /****************************************************************************************/
 
-typedef struct
-{
+typedef struct {
     /*
      * The memory area created using this structure is internally
      * typecast to LVM_Timer_Instance_Private_t and used.
@@ -51,14 +50,13 @@
 
 } LVM_Timer_Instance_t;
 
-typedef struct
-{
-    LVM_INT32  SamplingRate;
-    LVM_INT16  TimeInMs;
-    LVM_INT32  CallBackParam;
-    void       *pCallBackParams;
-    void       *pCallbackInstance;
-    void       (*pCallBack)(void*,void*,LVM_INT32);
+typedef struct {
+    LVM_INT32 SamplingRate;
+    LVM_INT16 TimeInMs;
+    LVM_INT32 CallBackParam;
+    void* pCallBackParams;
+    void* pCallbackInstance;
+    void (*pCallBack)(void*, void*, LVM_INT32);
 
 } LVM_Timer_Params_t;
 
@@ -66,14 +64,12 @@
 /*  FUNCTION PROTOTYPES                                                                 */
 /****************************************************************************************/
 
-void LVM_Timer_Init (   LVM_Timer_Instance_t       *pInstance,
-                        LVM_Timer_Params_t         *pParams     );
+void LVM_Timer_Init(LVM_Timer_Instance_t* pInstance, LVM_Timer_Params_t* pParams);
 
-void LVM_Timer      (   LVM_Timer_Instance_t       *pInstance,
-                        LVM_INT16                       BlockSize );
+void LVM_Timer(LVM_Timer_Instance_t* pInstance, LVM_INT16 BlockSize);
 
 /****************************************************************************************/
 /*  END OF HEADER                                                                       */
 /****************************************************************************************/
 
-#endif  /* __LVM_TIMER_H__ */
+#endif /* __LVM_TIMER_H__ */
diff --git a/media/libeffects/lvm/lib/Common/lib/LVM_Types.h b/media/libeffects/lvm/lib/Common/lib/LVM_Types.h
index 8b687f6..5cdcf35 100644
--- a/media/libeffects/lvm/lib/Common/lib/LVM_Types.h
+++ b/media/libeffects/lvm/lib/Common/lib/LVM_Types.h
@@ -26,53 +26,34 @@
 #define LVM_TYPES_H
 
 #include <stdint.h>
-
+#include <system/audio.h>
 /****************************************************************************************/
 /*                                                                                      */
 /*  definitions                                                                         */
 /*                                                                                      */
 /****************************************************************************************/
 
-#define LVM_NULL                0                   /* NULL pointer */
+#define LVM_NULL 0 /* NULL pointer */
 
-#define LVM_TRUE                1                   /* Booleans */
-#define LVM_FALSE               0
+#define LVM_TRUE 1 /* Booleans */
+#define LVM_FALSE 0
 
-#define LVM_MAXINT_8            127                 /* Maximum positive integer size */
-#define LVM_MAXINT_16           32767
-#define LVM_MAXINT_32           2147483647
-#define LVM_MAXENUM             2147483647
+#define LVM_MAXINT_8 127 /* Maximum positive integer size */
+#define LVM_MAXINT_16 32767
+#define LVM_MAXINT_32 2147483647
+#define LVM_MAXENUM 2147483647
 
-#define LVM_MODULEID_MASK       0xFF00              /* Mask to extract the calling module ID from callbackId */
-#define LVM_EVENTID_MASK        0x00FF              /* Mask to extract the callback event from callbackId */
+#define LVM_MODULEID_MASK 0xFF00 /* Mask to extract the calling module ID from callbackId */
+#define LVM_EVENTID_MASK 0x00FF  /* Mask to extract the callback event from callbackId */
 
 /* Memory table*/
-#define LVM_MEMREGION_PERSISTENT_SLOW_DATA      0   /* Offset to the instance memory region */
-#define LVM_MEMREGION_PERSISTENT_FAST_DATA      1   /* Offset to the persistent data memory region */
-#define LVM_MEMREGION_PERSISTENT_FAST_COEF      2   /* Offset to the persistent coefficient memory region */
-#define LVM_MEMREGION_TEMPORARY_FAST            3   /* Offset to temporary memory region */
+#define LVM_MEMREGION_PERSISTENT_SLOW_DATA 0 /* Offset to the instance memory region */
+#define LVM_MEMREGION_PERSISTENT_FAST_DATA 1 /* Offset to the persistent data memory region */
+#define LVM_MEMREGION_PERSISTENT_FAST_COEF \
+    2                                  /* Offset to the persistent coefficient memory region */
+#define LVM_MEMREGION_TEMPORARY_FAST 3 /* Offset to temporary memory region */
 
-#define LVM_NR_MEMORY_REGIONS                   4   /* Number of memory regions */
-
-/* Memory partition type */
-#define LVM_MEM_PARTITION0      0                   /* 1st memory partition */
-#define LVM_MEM_PARTITION1      1                   /* 2nd memory partition */
-#define LVM_MEM_PARTITION2      2                   /* 3rd memory partition */
-#define LVM_MEM_PARTITION3      3                   /* 4th memory partition */
-
-/* Use type */
-#define LVM_MEM_PERSISTENT      0                   /* Persistent memory type */
-#define LVM_MEM_SCRATCH         4                   /* Scratch  memory type */
-
-/* Access type */
-#define LVM_MEM_INTERNAL        0                   /* Internal (fast) access memory */
-#define LVM_MEM_EXTERNAL        8                   /* External (slow) access memory */
-
-/* Platform specific */
-#define LVM_PERSISTENT          (LVM_MEM_PARTITION0+LVM_MEM_PERSISTENT+LVM_MEM_INTERNAL)
-#define LVM_PERSISTENT_DATA     (LVM_MEM_PARTITION1+LVM_MEM_PERSISTENT+LVM_MEM_INTERNAL)
-#define LVM_PERSISTENT_COEF     (LVM_MEM_PARTITION2+LVM_MEM_PERSISTENT+LVM_MEM_INTERNAL)
-#define LVM_SCRATCH             (LVM_MEM_PARTITION3+LVM_MEM_SCRATCH+LVM_MEM_INTERNAL)
+#define LVM_NR_MEMORY_REGIONS 4 /* Number of memory regions */
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -80,33 +61,28 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-typedef     char                LVM_CHAR;           /* ASCII character */
+typedef char LVM_CHAR; /* ASCII character */
 
-typedef     int8_t              LVM_INT8;           /* Signed 8-bit word */
-typedef     uint8_t             LVM_UINT8;          /* Unsigned 8-bit word */
+typedef int8_t LVM_INT8;   /* Signed 8-bit word */
+typedef uint8_t LVM_UINT8; /* Unsigned 8-bit word */
 
-typedef     int16_t             LVM_INT16;          /* Signed 16-bit word */
-typedef     uint16_t            LVM_UINT16;         /* Unsigned 16-bit word */
+typedef int16_t LVM_INT16;   /* Signed 16-bit word */
+typedef uint16_t LVM_UINT16; /* Unsigned 16-bit word */
 
-typedef     int32_t             LVM_INT32;          /* Signed 32-bit word */
-typedef     uint32_t            LVM_UINT32;         /* Unsigned 32-bit word */
-typedef     int64_t             LVM_INT64;          /* Signed 64-bit word */
+typedef int32_t LVM_INT32;   /* Signed 32-bit word */
+typedef uint32_t LVM_UINT32; /* Unsigned 32-bit word */
+typedef int64_t LVM_INT64;   /* Signed 64-bit word */
 
-#define LVM_MAXFLOAT            1.f
+#define LVM_MAXFLOAT 1.f
 
-typedef     float               LVM_FLOAT;          /* single precision floating point */
+typedef float LVM_FLOAT; /* single precision floating point */
 
 // Select whether we expose int16_t or float buffers.
 
-#define    EFFECT_BUFFER_FORMAT AUDIO_FORMAT_PCM_FLOAT
-typedef     float               effect_buffer_t;
+#define EFFECT_BUFFER_FORMAT AUDIO_FORMAT_PCM_FLOAT
+typedef float effect_buffer_t;
 
-
-#ifdef SUPPORT_MC
-#define LVM_MAX_CHANNELS 8 // FCC_8
-#else
-#define LVM_MAX_CHANNELS 2 // FCC_2
-#endif
+#define LVM_MAX_CHANNELS FCC_24
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -115,29 +91,20 @@
 /****************************************************************************************/
 
 /* Operating mode */
-typedef enum
-{
-    LVM_MODE_OFF    = 0,
-    LVM_MODE_ON     = 1,
-    LVM_MODE_DUMMY  = LVM_MAXENUM
-} LVM_Mode_en;
+typedef enum { LVM_MODE_OFF = 0, LVM_MODE_ON = 1, LVM_MODE_DUMMY = LVM_MAXENUM } LVM_Mode_en;
 
 /* Format */
-typedef enum
-{
-    LVM_STEREO          = 0,
-    LVM_MONOINSTEREO    = 1,
-    LVM_MONO            = 2,
-#ifdef SUPPORT_MC
-    LVM_MULTICHANNEL    = 3,
-#endif
-    LVM_SOURCE_DUMMY    = LVM_MAXENUM
+typedef enum {
+    LVM_STEREO = 0,
+    LVM_MONOINSTEREO = 1,
+    LVM_MONO = 2,
+    LVM_MULTICHANNEL = 3,
+    LVM_SOURCE_DUMMY = LVM_MAXENUM
 } LVM_Format_en;
 
 /* LVM sampling rates */
-typedef enum
-{
-    LVM_FS_8000  = 0,
+typedef enum {
+    LVM_FS_8000 = 0,
     LVM_FS_11025 = 1,
     LVM_FS_12000 = 2,
     LVM_FS_16000 = 3,
@@ -150,32 +117,42 @@
     LVM_FS_96000 = 10,
     LVM_FS_176400 = 11,
     LVM_FS_192000 = 12,
-    LVM_FS_INVALID = LVM_MAXENUM-1,
+    LVM_FS_INVALID = LVM_MAXENUM - 1,
     LVM_FS_DUMMY = LVM_MAXENUM
 } LVM_Fs_en;
 
+static inline LVM_Fs_en lvmFsForSampleRate(int sampleRate) {
+    static const std::map<int, LVM_Fs_en> kLVMFsMap = {
+            {8000, LVM_FS_8000},    {11025, LVM_FS_11025}, {12000, LVM_FS_12000},
+            {16000, LVM_FS_16000},  {22050, LVM_FS_22050}, {24000, LVM_FS_24000},
+            {32000, LVM_FS_32000},  {44100, LVM_FS_44100}, {48000, LVM_FS_48000},
+            {88200, LVM_FS_88200},  {96000, LVM_FS_96000}, {176400, LVM_FS_176400},
+            {192000, LVM_FS_192000}};
+    if (kLVMFsMap.find(sampleRate) != kLVMFsMap.end()) {
+        return kLVMFsMap.at(sampleRate);
+    }
+    return LVM_FS_INVALID;
+}
+
 /* Memory Types */
-typedef enum
-{
-    LVM_PERSISTENT_SLOW_DATA    = LVM_MEMREGION_PERSISTENT_SLOW_DATA,
-    LVM_PERSISTENT_FAST_DATA    = LVM_MEMREGION_PERSISTENT_FAST_DATA,
-    LVM_PERSISTENT_FAST_COEF    = LVM_MEMREGION_PERSISTENT_FAST_COEF,
-    LVM_TEMPORARY_FAST          = LVM_MEMREGION_TEMPORARY_FAST,
-    LVM_MEMORYTYPE_DUMMY        = LVM_MAXENUM
+typedef enum {
+    LVM_PERSISTENT_SLOW_DATA = LVM_MEMREGION_PERSISTENT_SLOW_DATA,
+    LVM_PERSISTENT_FAST_DATA = LVM_MEMREGION_PERSISTENT_FAST_DATA,
+    LVM_PERSISTENT_FAST_COEF = LVM_MEMREGION_PERSISTENT_FAST_COEF,
+    LVM_TEMPORARY_FAST = LVM_MEMREGION_TEMPORARY_FAST,
+    LVM_MEMORYTYPE_DUMMY = LVM_MAXENUM
 } LVM_MemoryTypes_en;
 
 /* Memory region definition */
-typedef struct
-{
-    LVM_UINT32                  Size;                   /* Region size in bytes */
-    LVM_MemoryTypes_en          Type;                   /* Region type */
-    void                        *pBaseAddress;          /* Pointer to the region base address */
+typedef struct {
+    LVM_UINT32 Size;         /* Region size in bytes */
+    LVM_MemoryTypes_en Type; /* Region type */
+    void* pBaseAddress;      /* Pointer to the region base address */
 } LVM_MemoryRegion_st;
 
 /* Memory table containing the region definitions */
-typedef struct
-{
-    LVM_MemoryRegion_st         Region[LVM_NR_MEMORY_REGIONS];  /* One definition for each region */
+typedef struct {
+    LVM_MemoryRegion_st Region[LVM_NR_MEMORY_REGIONS]; /* One definition for each region */
 } LVM_MemoryTable_st;
 
 /****************************************************************************************/
@@ -183,9 +160,11 @@
 /*  Standard Function Prototypes                                                        */
 /*                                                                                      */
 /****************************************************************************************/
-typedef LVM_INT32 (*LVM_Callback)(void          *pCallbackData,     /* Pointer to the callback data structure */
-                                  void          *pGeneralPurpose,   /* General purpose pointer (e.g. to a data structure needed in the callback) */
-                                  LVM_INT16     GeneralPurpose );   /* General purpose variable (e.g. to be used as callback ID) */
+typedef LVM_INT32 (*LVM_Callback)(
+        void* pCallbackData,   /* Pointer to the callback data structure */
+        void* pGeneralPurpose, /* General purpose pointer (e.g. to a data structure needed in the
+                                  callback) */
+        LVM_INT16 GeneralPurpose); /* General purpose variable (e.g. to be used as callback ID) */
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -193,4 +172,4 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-#endif  /* LVM_TYPES_H */
+#endif /* LVM_TYPES_H */
diff --git a/media/libeffects/lvm/lib/Common/lib/Mixer.h b/media/libeffects/lvm/lib/Common/lib/Mixer.h
index b2e0195..ba605e5 100644
--- a/media/libeffects/lvm/lib/Common/lib/Mixer.h
+++ b/media/libeffects/lvm/lib/Common/lib/Mixer.h
@@ -24,80 +24,62 @@
    INSTANCE MEMORY TYPE DEFINITION
 ***********************************************************************************/
 
-typedef struct
-{
-    LVM_FLOAT   Alpha;                   /* Time constant. Set by calling application. \
-                                            Can be changed at any time */
-    LVM_FLOAT   Target;                  /* Target value.  Set by calling application. \
-                                            Can be changed at any time */
-    LVM_FLOAT   Current;                 /* Current value.  Set by the mixer function. */
-    LVM_INT16   CallbackSet;             /* Boolean.  Should be set by calling application \
-                                            each time the target value is updated */
-    LVM_INT16   CallbackParam;           /* Parameter that will be used in the calback function */
-    void        *pCallbackHandle;        /* Pointer to the instance of the callback function */
-    void        *pGeneralPurpose;        /* Pointer for general purpose usage */
-    LVM_Callback pCallBack;              /* Pointer to the callback function */
+typedef struct {
+    LVM_FLOAT Alpha;         /* Time constant. Set by calling application. \
+                                Can be changed at any time */
+    LVM_FLOAT Target;        /* Target value.  Set by calling application. \
+                                Can be changed at any time */
+    LVM_FLOAT Current;       /* Current value.  Set by the mixer function. */
+    LVM_INT16 CallbackSet;   /* Boolean.  Should be set by calling application \
+                                each time the target value is updated */
+    LVM_INT16 CallbackParam; /* Parameter that will be used in the calback function */
+    void* pCallbackHandle;   /* Pointer to the instance of the callback function */
+    void* pGeneralPurpose;   /* Pointer for general purpose usage */
+    LVM_Callback pCallBack;  /* Pointer to the callback function */
 } Mix_1St_Cll_FLOAT_t;
-typedef struct
-{
-    LVM_FLOAT   Alpha1;
-    LVM_FLOAT   Target1;
-    LVM_FLOAT   Current1;
-    LVM_INT16   CallbackSet1;
-    LVM_INT16   CallbackParam1;
-    void        *pCallbackHandle1;
-    void        *pGeneralPurpose1;
+typedef struct {
+    LVM_FLOAT Alpha1;
+    LVM_FLOAT Target1;
+    LVM_FLOAT Current1;
+    LVM_INT16 CallbackSet1;
+    LVM_INT16 CallbackParam1;
+    void* pCallbackHandle1;
+    void* pGeneralPurpose1;
     LVM_Callback pCallBack1;
 
-    LVM_FLOAT   Alpha2;                   /* Warning the address of this location is passed as a \
-                                             pointer to Mix_1St_Cll_t in some functions */
-    LVM_FLOAT   Target2;
-    LVM_FLOAT   Current2;
-    LVM_INT16   CallbackSet2;
-    LVM_INT16   CallbackParam2;
-    void        *pCallbackHandle2;
-    void        *pGeneralPurpose2;
+    LVM_FLOAT Alpha2; /* Warning the address of this location is passed as a \
+                         pointer to Mix_1St_Cll_t in some functions */
+    LVM_FLOAT Target2;
+    LVM_FLOAT Current2;
+    LVM_INT16 CallbackSet2;
+    LVM_INT16 CallbackParam2;
+    void* pCallbackHandle2;
+    void* pGeneralPurpose2;
     LVM_Callback pCallBack2;
 } Mix_2St_Cll_FLOAT_t;
 
 /*** General functions ************************************************************/
 
-LVM_FLOAT LVM_Mixer_TimeConstant(LVM_UINT32   tc,
-                                 LVM_UINT32   Fs,
-                                 LVM_UINT16   NumChannels);
+LVM_FLOAT LVM_Mixer_TimeConstant(LVM_UINT32 tc, LVM_UINT32 Fs, LVM_UINT16 NumChannels);
 
-void MixSoft_1St_D32C31_WRA(    Mix_1St_Cll_FLOAT_t       *pInstance,
-                                const LVM_FLOAT     *src,
-                                LVM_FLOAT     *dst,
-                                LVM_INT16     n);
+void MixSoft_1St_D32C31_WRA(Mix_1St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src, LVM_FLOAT* dst,
+                            LVM_INT16 n);
 
-void MixSoft_2St_D32C31_SAT(    Mix_2St_Cll_FLOAT_t       *pInstance,
-                                const LVM_FLOAT     *src1,
-                                const LVM_FLOAT     *src2,
-                                LVM_FLOAT     *dst,
-                                LVM_INT16     n);
+void MixSoft_2St_D32C31_SAT(Mix_2St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src1,
+                            const LVM_FLOAT* src2, LVM_FLOAT* dst, LVM_INT16 n);
 
-void MixInSoft_D32C31_SAT(      Mix_1St_Cll_FLOAT_t       *pInstance,
-                                const LVM_FLOAT     *src,
-                                LVM_FLOAT     *dst,
-                                LVM_INT16     n);
+void MixInSoft_D32C31_SAT(Mix_1St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src, LVM_FLOAT* dst,
+                          LVM_INT16 n);
 
 /**********************************************************************************
    FUNCTION PROTOTYPES (LOW LEVEL SUBFUNCTIONS)
 ***********************************************************************************/
-void Core_MixSoft_1St_D32C31_WRA(   Mix_1St_Cll_FLOAT_t       *pInstance,
-                                    const LVM_FLOAT     *src,
-                                    LVM_FLOAT     *dst,
-                                    LVM_INT16     n);
-void Core_MixHard_2St_D32C31_SAT(   Mix_2St_Cll_FLOAT_t       *pInstance,
-                                    const LVM_FLOAT     *src1,
-                                    const LVM_FLOAT     *src2,
-                                    LVM_FLOAT     *dst,
-                                    LVM_INT16     n);
-void Core_MixInSoft_D32C31_SAT(     Mix_1St_Cll_FLOAT_t       *pInstance,
-                                    const LVM_FLOAT     *src,
-                                    LVM_FLOAT     *dst,
-                                    LVM_INT16     n);
+void Core_MixSoft_1St_D32C31_WRA(Mix_1St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src,
+                                 LVM_FLOAT* dst, LVM_INT16 n);
+void Core_MixHard_2St_D32C31_SAT(Mix_2St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src1,
+                                 const LVM_FLOAT* src2, LVM_FLOAT* dst, LVM_INT16 n);
+void Core_MixInSoft_D32C31_SAT(Mix_1St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src, LVM_FLOAT* dst,
+                               LVM_INT16 n);
 
 /**********************************************************************************/
 
diff --git a/media/libeffects/lvm/lib/Common/lib/ScalarArithmetic.h b/media/libeffects/lvm/lib/Common/lib/ScalarArithmetic.h
index ae54419..36c4cd2 100644
--- a/media/libeffects/lvm/lib/Common/lib/ScalarArithmetic.h
+++ b/media/libeffects/lvm/lib/Common/lib/ScalarArithmetic.h
@@ -21,7 +21,7 @@
 /*######################################################################################*/
 /*  Include files                                                                       */
 /*######################################################################################*/
-
+#include <math.h>
 #include "LVM_Types.h"
 
 /*######################################################################################*/
@@ -30,7 +30,13 @@
 
 /* Absolute value including the corner case for the extreme negative value */
 
-LVM_FLOAT   Abs_Float(LVM_FLOAT     input);
+static inline LVM_FLOAT Abs_Float(LVM_FLOAT input) {
+    return fabs(input);
+}
+
+static inline LVM_FLOAT LVM_Clamp(LVM_FLOAT val) {
+    return fmin(fmax(val, -1.0f), 1.0f);
+}
 
 /****************************************************************************************
  *  Name        : dB_to_Lin32()
@@ -44,7 +50,6 @@
  *                  (15->01) = decimal part
  *  Returns     : Lin value format 1.16.15
  ****************************************************************************************/
-LVM_FLOAT dB_to_LinFloat(LVM_INT16    db_fix);
+LVM_FLOAT dB_to_LinFloat(LVM_INT16 db_fix);
 
-#endif  /* __SCALARARITHMETIC_H__ */
-
+#endif /* __SCALARARITHMETIC_H__ */
diff --git a/media/libeffects/lvm/lib/Common/lib/VectorArithmetic.h b/media/libeffects/lvm/lib/Common/lib/VectorArithmetic.h
index b27bac5..18de85b 100644
--- a/media/libeffects/lvm/lib/Common/lib/VectorArithmetic.h
+++ b/media/libeffects/lvm/lib/Common/lib/VectorArithmetic.h
@@ -24,127 +24,43 @@
     VARIOUS FUNCTIONS
 ***********************************************************************************/
 
-void LoadConst_Float(          const LVM_FLOAT val,
-                               LVM_FLOAT *dst,
-                               LVM_INT16 n );
+void LoadConst_Float(const LVM_FLOAT val, LVM_FLOAT* dst, LVM_INT16 n);
 
-void Copy_Float(                 const LVM_FLOAT *src,
-                                 LVM_FLOAT *dst,
-                                 LVM_INT16 n );
-#ifdef SUPPORT_MC
-void Copy_Float_Mc_Stereo(       const LVM_FLOAT *src,
-                                 LVM_FLOAT *dst,
-                                 LVM_INT16 NrFrames,
-                                 LVM_INT32 NrChannels);
-void Copy_Float_Stereo_Mc(       const LVM_FLOAT *src,
-                                 LVM_FLOAT *StereoOut,
-                                 LVM_FLOAT *dst,
-                                 LVM_INT16 NrFrames,
-                                 LVM_INT32 NrChannels);
-#endif
+void Copy_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n);
+void Copy_Float_Mc_Stereo(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 NrFrames,
+                          LVM_INT32 NrChannels);
+void Copy_Float_Stereo_Mc(const LVM_FLOAT* src, const LVM_FLOAT* StereoOut, LVM_FLOAT* dst,
+                          LVM_INT16 NrFrames, LVM_INT32 NrChannels);
 
-/*********************************************************************************
- * note: In Mult3s_16x16() saturation of result is not taken care when           *
- *       overflow occurs.                                                        *
- *       For example when *src = 0x8000, val = *0x8000                           *
- *       The function gives the output as 0x8000 instead of 0x7fff               *
- *       This is the only case which will give wrong result.                     *
- *       For more information refer to Vector_Arithmetic.doc in /doc folder      *
- *********************************************************************************/
-void Mult3s_Float(            const LVM_FLOAT *src,
-                              const LVM_FLOAT val,
-                              LVM_FLOAT *dst,
-                              LVM_INT16 n);
+void Mult3s_Float(const LVM_FLOAT* src, const LVM_FLOAT val, LVM_FLOAT* dst, LVM_INT16 n);
 
-/*********************************************************************************
- * note: In Mult3s_32x16() saturation of result is not taken care when           *
- *       overflow occurs.                                                        *
- *       For example when *src = 0x8000000, val = *0x8000                        *
- *       The function gives the output as 0x8000000 instead of 0x7fffffff        *
- *       This is the only extreme condition which is giving unexpected result    *
- *       For more information refer to Vector_Arithmetic.doc in /doc folder      *
- *********************************************************************************/
-void Mult3s_32x16(            const LVM_INT32  *src,
-                              const LVM_INT16 val,
-                                    LVM_INT32  *dst,
-                                    LVM_INT16 n);
-void DelayMix_Float(const LVM_FLOAT *src,           /* Source 1, to be delayed */
-                    LVM_FLOAT *delay,         /* Delay buffer */
-                    LVM_INT16 size,           /* Delay size */
-                    LVM_FLOAT *dst,           /* Source/destination */
-                    LVM_INT16 *pOffset,       /* Delay offset */
-                    LVM_INT16 n)  ;            /* Number of stereo samples */
-void DelayWrite_32(           const LVM_INT32  *src,               /* Source 1, to be delayed */
-                                    LVM_INT32  *delay,             /* Delay buffer */
-                                    LVM_UINT16 size,               /* Delay size */
-                                    LVM_UINT16 *pOffset,           /* Delay offset */
-                                    LVM_INT16 n);
-void Add2_Sat_Float(          const LVM_FLOAT *src,
-                              LVM_FLOAT *dst,
-                              LVM_INT16 n );
-void Mac3s_Sat_Float(         const LVM_FLOAT *src,
-                              const LVM_FLOAT val,
-                              LVM_FLOAT *dst,
-                              LVM_INT16 n);
-void DelayAllPass_Sat_32x16To32(    LVM_INT32  *delay,              /* Delay buffer */
-                                    LVM_UINT16 size,                /* Delay size */
-                                    LVM_INT16 coeff,                /* All pass filter coefficient */
-                                    LVM_UINT16 DelayOffset,         /* Simple delay offset */
-                                    LVM_UINT16 *pAllPassOffset,     /* All pass filter delay offset */
-                                    LVM_INT32  *dst,                /* Source/destination */
-                                    LVM_INT16 n);
+void DelayMix_Float(const LVM_FLOAT* src,  /* Source 1, to be delayed */
+                    LVM_FLOAT* delay,      /* Delay buffer */
+                    LVM_INT16 size,        /* Delay size */
+                    LVM_FLOAT* dst,        /* Source/destination */
+                    LVM_INT16* pOffset,    /* Delay offset */
+                    LVM_INT16 n,           /* Number of stereo samples */
+                    LVM_INT32 NrChannels); /* Number of channels */
+void Add2_Sat_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n);
+void Mac3s_Sat_Float(const LVM_FLOAT* src, const LVM_FLOAT val, LVM_FLOAT* dst, LVM_INT16 n);
 
 /**********************************************************************************
     SHIFT FUNCTIONS
 ***********************************************************************************/
-void Shift_Sat_Float (const   LVM_INT16   val,
-                      const   LVM_FLOAT   *src,
-                      LVM_FLOAT   *dst,
-                      LVM_INT16   n);
+void Shift_Sat_Float(const LVM_INT16 val, const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n);
 /**********************************************************************************
     AUDIO FORMAT CONVERSION FUNCTIONS
 ***********************************************************************************/
-void MonoTo2I_Float( const LVM_FLOAT     *src,
-                     LVM_FLOAT     *dst,
-                     LVM_INT16 n);
-void From2iToMono_Float(         const LVM_FLOAT  *src,
-                                 LVM_FLOAT  *dst,
-                                 LVM_INT16 n);
-#ifdef SUPPORT_MC
-void FromMcToMono_Float(const LVM_FLOAT *src,
-                        LVM_FLOAT *dst,
-                        LVM_INT16 NrFrames,
+void MonoTo2I_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n);
+void From2iToMono_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n);
+void FromMcToMono_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 NrFrames,
                         LVM_INT16 NrChannels);
-#endif
-void MSTo2i_Sat_Float(        const LVM_FLOAT *srcM,
-                              const LVM_FLOAT *srcS,
-                              LVM_FLOAT *dst,
-                              LVM_INT16 n );
-void From2iToMS_Float(        const LVM_FLOAT *src,
-                              LVM_FLOAT *dstM,
-                              LVM_FLOAT *dstS,
-                              LVM_INT16 n );
-void JoinTo2i_Float(          const LVM_FLOAT  *srcL,
-                              const LVM_FLOAT  *srcR,
-                              LVM_FLOAT  *dst,
-                              LVM_INT16 n );
-
-/**********************************************************************************
-    DATA TYPE CONVERSION FUNCTIONS
-***********************************************************************************/
-
-void Int16LShiftToInt32_16x32(const LVM_INT16 *src,
-                                    LVM_INT32  *dst,
-                                    LVM_INT16 n,
-                                    LVM_INT16 shift );
-
-void Int32RShiftToInt16_Sat_32x16(const  LVM_INT32  *src,
-                                    LVM_INT16 *dst,
-                                    LVM_INT16 n,
-                                    LVM_INT16 shift );
+void MSTo2i_Sat_Float(const LVM_FLOAT* srcM, const LVM_FLOAT* srcS, LVM_FLOAT* dst, LVM_INT16 n);
+void From2iToMS_Float(const LVM_FLOAT* src, LVM_FLOAT* dstM, LVM_FLOAT* dstS, LVM_INT16 n);
+void JoinTo2i_Float(const LVM_FLOAT* srcL, const LVM_FLOAT* srcR, LVM_FLOAT* dst, LVM_INT16 n);
 
 /**********************************************************************************/
 
-#endif  /* _VECTOR_ARITHMETIC_H_ */
+#endif /* _VECTOR_ARITHMETIC_H_ */
 
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/AGC_MIX_VOL_2St1Mon_D32_WRA.cpp b/media/libeffects/lvm/lib/Common/src/AGC_MIX_VOL_2St1Mon_D32_WRA.cpp
index e18aa78..78f329e 100644
--- a/media/libeffects/lvm/lib/Common/src/AGC_MIX_VOL_2St1Mon_D32_WRA.cpp
+++ b/media/libeffects/lvm/lib/Common/src/AGC_MIX_VOL_2St1Mon_D32_WRA.cpp
@@ -20,7 +20,6 @@
 /*    Includes                                                                          */
 /*                                                                                      */
 /****************************************************************************************/
-
 #include "AGC.h"
 #include "ScalarArithmetic.h"
 
@@ -30,151 +29,13 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-#define VOL_TC_SHIFT                                        21          /* As a power of 2 */
-#define DECAY_SHIFT                                        10           /* As a power of 2 */
-#define VOL_TC_FLOAT                                      2.0f          /* As a power of 2 */
-#define DECAY_FAC_FLOAT                                  64.0f          /* As a power of 2 */
+#define VOL_TC_SHIFT 21       /* As a power of 2 */
+#define DECAY_SHIFT 10        /* As a power of 2 */
+#define VOL_TC_FLOAT 2.0f     /* As a power of 2 */
+#define DECAY_FAC_FLOAT 64.0f /* As a power of 2 */
 
 /****************************************************************************************/
 /*                                                                                      */
-/* FUNCTION:                  AGC_MIX_VOL_2St1Mon_D32_WRA                               */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*    Apply AGC and mix signals                                                         */
-/*                                                                                      */
-/*                                                                                      */
-/*  StSrc   ------------------|                                                         */
-/*                            |                                                         */
-/*              ______       _|_        ________                                        */
-/*             |      |     |   |      |        |                                       */
-/*  MonoSrc -->| AGC  |---->| + |----->| Volume |------------------------------+--->    */
-/*             | Gain |     |___|      | Gain   |                              |        */
-/*             |______|                |________|                              |        */
-/*                /|\                               __________     ________    |        */
-/*                 |                               |          |   |        |   |        */
-/*                 |-------------------------------| AGC Gain |<--| Peak   |<--|        */
-/*                                                 | Update   |   | Detect |            */
-/*                                                 |__________|   |________|            */
-/*                                                                                      */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  pInstance               Instance pointer                                            */
-/*  pStereoIn               Stereo source                                               */
-/*  pMonoIn                 Mono band pass source                                       */
-/*  pStereoOut              Stereo destination                                          */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  Void                                                                                */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*                                                                                      */
-/****************************************************************************************/
-void AGC_MIX_VOL_2St1Mon_D32_WRA(AGC_MIX_VOL_2St1Mon_FLOAT_t  *pInstance,     /* Instance pointer */
-                                 const LVM_FLOAT            *pStSrc,        /* Stereo source */
-                                 const LVM_FLOAT            *pMonoSrc,      /* Mono source */
-                                 LVM_FLOAT                  *pDst,          /* Stereo destination */
-                                 LVM_UINT16                 NumSamples)     /* Number of samples */
-{
-
-    /*
-     * General variables
-     */
-    LVM_UINT16      i;                                          /* Sample index */
-    LVM_FLOAT       Left;                                       /* Left sample */
-    LVM_FLOAT       Right;                                      /* Right sample */
-    LVM_FLOAT       Mono;                                       /* Mono sample */
-    LVM_FLOAT       AbsPeak;                                    /* Absolute peak signal */
-    LVM_FLOAT       AGC_Mult;                                   /* Short AGC gain */
-    LVM_FLOAT       Vol_Mult;                                   /* Short volume */
-
-    /*
-     * Instance control variables
-     */
-    LVM_FLOAT      AGC_Gain      = pInstance->AGC_Gain;         /* Get the current AGC gain */
-    LVM_FLOAT      AGC_MaxGain   = pInstance->AGC_MaxGain;      /* Get maximum AGC gain */
-    LVM_FLOAT      AGC_Attack    = pInstance->AGC_Attack;       /* Attack scaler */
-    LVM_FLOAT      AGC_Decay     = (pInstance->AGC_Decay * (1 << (DECAY_SHIFT)));/* Decay scaler */
-    LVM_FLOAT      AGC_Target    = pInstance->AGC_Target;       /* Get the target level */
-    LVM_FLOAT      Vol_Current   = pInstance->Volume;           /* Actual volume setting */
-    LVM_FLOAT      Vol_Target    = pInstance->Target;           /* Target volume setting */
-    LVM_FLOAT      Vol_TC        = pInstance->VolumeTC;         /* Time constant */
-
-    /*
-     * Process on a sample by sample basis
-     */
-    for (i = 0; i < NumSamples; i++)                                  /* For each sample */
-    {
-
-        /*
-         * Get the short scalers
-         */
-        AGC_Mult    = (LVM_FLOAT)(AGC_Gain);              /* Get the short AGC gain */
-        Vol_Mult    = (LVM_FLOAT)(Vol_Current);           /* Get the short volume gain */
-
-        /*
-         * Get the input samples
-         */
-        Left  = *pStSrc++;                                      /* Get the left sample */
-        Right = *pStSrc++;                                      /* Get the right sample */
-        Mono  = *pMonoSrc++;                                    /* Get the mono sample */
-
-        /*
-         * Apply the AGC gain to the mono input and mix with the stereo signal
-         */
-        Left  += (Mono * AGC_Mult);                               /* Mix in the mono signal */
-        Right += (Mono * AGC_Mult);
-
-        /*
-         * Apply the volume and write to the output stream
-         */
-        Left  = Left  * Vol_Mult;
-        Right = Right * Vol_Mult;
-        *pDst++ = Left;                                         /* Save the results */
-        *pDst++ = Right;
-
-        /*
-         * Update the AGC gain
-         */
-        AbsPeak = Abs_Float(Left) > Abs_Float(Right) ? Abs_Float(Left) : Abs_Float(Right);
-        if (AbsPeak > AGC_Target)
-        {
-            /*
-             * The signal is too large so decrease the gain
-             */
-            AGC_Gain = AGC_Gain * AGC_Attack;
-        }
-        else
-        {
-            /*
-             * The signal is too small so increase the gain
-             */
-            if (AGC_Gain > AGC_MaxGain)
-            {
-                AGC_Gain -= (AGC_Decay);
-            }
-            else
-            {
-                AGC_Gain += (AGC_Decay);
-            }
-        }
-
-        /*
-         * Update the gain
-         */
-        Vol_Current +=  (Vol_Target - Vol_Current) * ((LVM_FLOAT)Vol_TC / VOL_TC_FLOAT);
-    }
-
-    /*
-     * Update the parameters
-     */
-    pInstance->Volume = Vol_Current;                            /* Actual volume setting */
-    pInstance->AGC_Gain = AGC_Gain;
-
-    return;
-}
-#ifdef SUPPORT_MC
-/****************************************************************************************/
-/*                                                                                      */
 /* FUNCTION:                  AGC_MIX_VOL_Mc1Mon_D32_WRA                                */
 /*                                                                                      */
 /* DESCRIPTION:                                                                         */
@@ -209,93 +70,80 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-void AGC_MIX_VOL_Mc1Mon_D32_WRA(AGC_MIX_VOL_2St1Mon_FLOAT_t  *pInstance,
-                                 const LVM_FLOAT            *pMcSrc,
-                                 const LVM_FLOAT            *pMonoSrc,
-                                 LVM_FLOAT                  *pDst,
-                                 LVM_UINT16                 NrFrames,
-                                 LVM_UINT16                 NrChannels)
-{
-
+void AGC_MIX_VOL_Mc1Mon_D32_WRA(AGC_MIX_VOL_2St1Mon_FLOAT_t* pInstance, const LVM_FLOAT* pMcSrc,
+                                const LVM_FLOAT* pMonoSrc, LVM_FLOAT* pDst, LVM_UINT16 NrFrames,
+                                LVM_UINT16 NrChannels) {
     /*
      * General variables
      */
-    LVM_UINT16      i, jj;                                      /* Sample index */
-    LVM_FLOAT       SampleVal;                                  /* Sample value */
-    LVM_FLOAT       Mono;                                       /* Mono sample */
-    LVM_FLOAT       AbsPeak;                                    /* Absolute peak signal */
-    LVM_FLOAT       AGC_Mult;                                   /* Short AGC gain */
-    LVM_FLOAT       Vol_Mult;                                   /* Short volume */
+    LVM_UINT16 i, jj;    /* Sample index */
+    LVM_FLOAT SampleVal; /* Sample value */
+    LVM_FLOAT Mono;      /* Mono sample */
+    LVM_FLOAT AbsPeak;   /* Absolute peak signal */
+    LVM_FLOAT AGC_Mult;  /* Short AGC gain */
+    LVM_FLOAT Vol_Mult;  /* Short volume */
 
     /*
      * Instance control variables
      */
-    LVM_FLOAT      AGC_Gain      = pInstance->AGC_Gain;         /* Get the current AGC gain */
-    LVM_FLOAT      AGC_MaxGain   = pInstance->AGC_MaxGain;      /* Get maximum AGC gain */
-    LVM_FLOAT      AGC_Attack    = pInstance->AGC_Attack;       /* Attack scaler */
+    LVM_FLOAT AGC_Gain = pInstance->AGC_Gain;       /* Get the current AGC gain */
+    LVM_FLOAT AGC_MaxGain = pInstance->AGC_MaxGain; /* Get maximum AGC gain */
+    LVM_FLOAT AGC_Attack = pInstance->AGC_Attack;   /* Attack scaler */
     /* Decay scaler */
-    LVM_FLOAT      AGC_Decay     = (pInstance->AGC_Decay * (1 << (DECAY_SHIFT)));
-    LVM_FLOAT      AGC_Target    = pInstance->AGC_Target;       /* Get the target level */
-    LVM_FLOAT      Vol_Current   = pInstance->Volume;           /* Actual volume setting */
-    LVM_FLOAT      Vol_Target    = pInstance->Target;           /* Target volume setting */
-    LVM_FLOAT      Vol_TC        = pInstance->VolumeTC;         /* Time constant */
+    LVM_FLOAT AGC_Decay = (pInstance->AGC_Decay * (1 << (DECAY_SHIFT)));
+    LVM_FLOAT AGC_Target = pInstance->AGC_Target; /* Get the target level */
+    LVM_FLOAT Vol_Current = pInstance->Volume;    /* Actual volume setting */
+    LVM_FLOAT Vol_Target = pInstance->Target;     /* Target volume setting */
+    LVM_FLOAT Vol_TC = pInstance->VolumeTC;       /* Time constant */
 
     /*
      * Process on a sample by sample basis
      */
-    for (i = 0; i < NrFrames; i++)                                  /* For each frame */
+    for (i = 0; i < NrFrames; i++) /* For each frame */
     {
-
         /*
          * Get the scalers
          */
-        AGC_Mult    = (LVM_FLOAT)(AGC_Gain);              /* Get the AGC gain */
-        Vol_Mult    = (LVM_FLOAT)(Vol_Current);           /* Get the volume gain */
+        AGC_Mult = (LVM_FLOAT)(AGC_Gain);    /* Get the AGC gain */
+        Vol_Mult = (LVM_FLOAT)(Vol_Current); /* Get the volume gain */
 
         AbsPeak = 0.0f;
         /*
          * Get the input samples
          */
-        for (jj = 0; jj < NrChannels; jj++)
-        {
-            SampleVal  = *pMcSrc++;                       /* Get the sample value of jj Channel*/
-            Mono       = *pMonoSrc;                       /* Get the mono sample */
+        for (jj = 0; jj < NrChannels; jj++) {
+            SampleVal = *pMcSrc++; /* Get the sample value of jj Channel*/
+            Mono = *pMonoSrc;      /* Get the mono sample */
 
             /*
              * Apply the AGC gain to the mono input and mix with the input signal
              */
-            SampleVal  += (Mono * AGC_Mult);                        /* Mix in the mono signal */
+            SampleVal += (Mono * AGC_Mult); /* Mix in the mono signal */
 
             /*
              * Apply the volume and write to the output stream
              */
-            SampleVal  = SampleVal  * Vol_Mult;
+            SampleVal = SampleVal * Vol_Mult;
 
-            *pDst++ = SampleVal;                                         /* Save the results */
+            *pDst++ = LVM_Clamp(SampleVal); /* Save the results */
 
             /*
              * Update the AGC gain
              */
             AbsPeak = Abs_Float(SampleVal) > AbsPeak ? Abs_Float(SampleVal) : AbsPeak;
         }
-        if (AbsPeak > AGC_Target)
-        {
+        if (AbsPeak > AGC_Target) {
             /*
              * The signal is too large so decrease the gain
              */
             AGC_Gain = AGC_Gain * AGC_Attack;
-        }
-        else
-        {
+        } else {
             /*
              * The signal is too small so increase the gain
              */
-            if (AGC_Gain > AGC_MaxGain)
-            {
+            if (AGC_Gain > AGC_MaxGain) {
                 AGC_Gain -= (AGC_Decay);
-            }
-            else
-            {
+            } else {
                 AGC_Gain += (AGC_Decay);
             }
         }
@@ -303,15 +151,14 @@
         /*
          * Update the gain
          */
-        Vol_Current +=  (Vol_Target - Vol_Current) * ((LVM_FLOAT)Vol_TC / VOL_TC_FLOAT);
+        Vol_Current += (Vol_Target - Vol_Current) * ((LVM_FLOAT)Vol_TC / VOL_TC_FLOAT);
     }
 
     /*
      * Update the parameters
      */
-    pInstance->Volume = Vol_Current;                            /* Actual volume setting */
+    pInstance->Volume = Vol_Current; /* Actual volume setting */
     pInstance->AGC_Gain = AGC_Gain;
 
     return;
 }
-#endif /*SUPPORT_MC*/
diff --git a/media/libeffects/lvm/lib/Common/src/Abs_32.cpp b/media/libeffects/lvm/lib/Common/src/Abs_32.cpp
deleted file mode 100644
index e013809..0000000
--- a/media/libeffects/lvm/lib/Common/src/Abs_32.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*######################################################################################*/
-/*  Include files                                                                       */
-/*######################################################################################*/
-
-#include    "ScalarArithmetic.h"
-
-/****************************************************************************************
- *  Name        : Abs_32()
- *  Input       : Signed 32-bit integer
- *  Output      :
- *  Returns     : Absolute value
- *  Description : Absolute value with maximum negative value corner case
- *  Remarks     :
- ****************************************************************************************/
-
-LVM_INT32    Abs_32(LVM_INT32    input)
-{
-    if(input <  0)
-    {
-        if (input == (LVM_INT32)(0x80000000U))
-        {
-            /* The corner case, so set to the maximum positive value */
-            input=(LVM_INT32) 0x7fffffff;
-        }
-        else
-        {
-            /* Negative input, so invert */
-            input = (LVM_INT32)(-input);
-        }
-    }
-    return input;
-}
-LVM_FLOAT    Abs_Float(LVM_FLOAT    input)
-{
-    if(input <  0)
-    {
-        /* Negative input, so invert */
-        input = (LVM_FLOAT)(-input);
-    }
-    return input;
-}
diff --git a/media/libeffects/lvm/lib/Common/src/Add2_Sat_16x16.cpp b/media/libeffects/lvm/lib/Common/src/Add2_Sat_16x16.cpp
deleted file mode 100644
index 6978fe7..0000000
--- a/media/libeffects/lvm/lib/Common/src/Add2_Sat_16x16.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "VectorArithmetic.h"
-
-/**********************************************************************************
-   FUNCTION ADD2_SAT_16X16
-***********************************************************************************/
-
-void Add2_Sat_16x16( const LVM_INT16 *src,
-                           LVM_INT16 *dst,
-                           LVM_INT16  n )
-{
-    LVM_INT32 Temp;
-    LVM_INT16 ii;
-    for (ii = n; ii != 0; ii--)
-    {
-        Temp = ((LVM_INT32) *src) + ((LVM_INT32) *dst);
-        src++;
-
-        if (Temp > 0x00007FFF)
-        {
-            *dst = 0x7FFF;
-        }
-        else if (Temp < -0x00008000)
-        {
-            *dst = - 0x8000;
-        }
-        else
-        {
-            *dst = (LVM_INT16)Temp;
-        }
-        dst++;
-    }
-    return;
-}
-
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/Add2_Sat_32x32.cpp b/media/libeffects/lvm/lib/Common/src/Add2_Sat_32x32.cpp
index a48e668..1981edd 100644
--- a/media/libeffects/lvm/lib/Common/src/Add2_Sat_32x32.cpp
+++ b/media/libeffects/lvm/lib/Common/src/Add2_Sat_32x32.cpp
@@ -18,69 +18,15 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
+#include "ScalarArithmetic.h"
 #include "VectorArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION ADD2_SAT_32X32
-***********************************************************************************/
-
-void Add2_Sat_32x32( const LVM_INT32  *src,
-                           LVM_INT32  *dst,
-                           LVM_INT16  n )
-{
-    LVM_INT32 a,b,c;
-    LVM_INT16 ii;
-    for (ii = n; ii != 0; ii--)
-    {
-        a=*src;
-        src++;
-
-        b=*dst;
-        c=a+b;
-        if ((((c ^ a) & (c ^ b)) >> 31)!=0)     /* overflow / underflow */
-        {
-            if(a<0)
-            {
-                c=0x80000000L;
-            }
-            else
-            {
-                c=0x7FFFFFFFL;
-            }
-        }
-
-        *dst = c;
-        dst++;
-    }
-    return;
-}
-
-void Add2_Sat_Float( const LVM_FLOAT  *src,
-                           LVM_FLOAT  *dst,
-                           LVM_INT16  n )
-{
+void Add2_Sat_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n) {
     LVM_FLOAT Temp;
     LVM_INT16 ii;
-    for (ii = n; ii != 0; ii--)
-    {
-        Temp = ((LVM_FLOAT) *src) + ((LVM_FLOAT) *dst);
-        src++;
-
-        if (Temp > 1.000000f)
-        {
-            *dst = 1.000000f;
-        }
-        else if (Temp < -1.000000f)
-        {
-            *dst = -1.000000f;
-        }
-        else
-        {
-            *dst = Temp;
-        }
-        dst++;
+    for (ii = n; ii != 0; ii--) {
+        Temp = *src++ + *dst;
+        *dst++ = LVM_Clamp(Temp);
     }
     return;
 }
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F16C14_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BP_1I_D16F16C14_TRC_WRA_01.cpp
deleted file mode 100644
index 1a5e07f..0000000
--- a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F16C14_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BP_1I_D16F16Css_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A0,
- pBiquadState->coefs[1] is -B2,
- pBiquadState->coefs[2] is -B1, these are in Q14 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-2)L in Q0 format
- pBiquadState->pDelays[2] is y(n-1)L in Q0 format
- pBiquadState->pDelays[3] is y(n-2)L in Q0 format
-***************************************************************************/
-void BP_1I_D16F16C14_TRC_WRA_01 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                  LVM_FLOAT               *pDataIn,
-                                  LVM_FLOAT               *pDataOut,
-                                  LVM_INT16               NrSamples)
-
-    {
-        LVM_FLOAT ynL;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-         for (ii = NrSamples; ii != 0; ii--)
-         {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            // ynL= (A0  * (x(n)L  - x(n-2)L  ) )
-            ynL = pBiquadState->coefs[0] * ((*pDataIn)-pBiquadState->pDelays[1]);
-
-            // ynL+= ((-B2  * y(n-2)L  ) )
-            ynL += pBiquadState->coefs[1] * pBiquadState->pDelays[3];
-
-            // ynL+= ((-B1  * y(n-1)L  ) )
-            ynL += pBiquadState->coefs[2] * pBiquadState->pDelays[2];
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[2]; // y(n-2)L=y(n-1)L
-            pBiquadState->pDelays[1] = pBiquadState->pDelays[0]; // x(n-2)L=x(n-1)L
-            pBiquadState->pDelays[2] = ynL; // Update y(n-1)L
-            pBiquadState->pDelays[0] = (*pDataIn++); // Update x(n-1)L
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut++=ynL; // Write Left output
-
-        }
-
-    }
-
diff --git a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F16Css_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/BP_1I_D16F16Css_TRC_WRA_01_Init.cpp
deleted file mode 100644
index 60b6c16..0000000
--- a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F16Css_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*-------------------------------------------------------------------------*/
-#include "BIQUAD.h"
-#include "BP_1I_D16F16Css_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   BP_1I_D16F16Css_TRC_WRA_01_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void BP_1I_D16F16Css_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t          *pInstance,
-                                         Biquad_1I_Order2_FLOAT_Taps_t    *pTaps,
-                                         BP_FLOAT_Coefs_t                  *pCoef)
-{
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-    pBiquadState->pDelays      = (LVM_FLOAT *) pTaps;
-
-    pBiquadState->coefs[0] = pCoef->A0;
-    pBiquadState->coefs[1] = pCoef->B2;
-    pBiquadState->coefs[2] = pCoef->B1;
-}
-/*-------------------------------------------------------------------------*/
-/* End Of File: BP_1I_D16F16Css_TRC_WRA_01_Init.c                              */
-
diff --git a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F16Css_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/BP_1I_D16F16Css_TRC_WRA_01_Private.h
deleted file mode 100644
index 8a000b6..0000000
--- a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F16Css_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef _BP_1I_D16F16CSS_TRC_WRA_01_PRIVATE_H_
-#define _BP_1I_D16F16CSS_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT32         coefs[3];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-typedef struct _Filter_State_FLOAT
-{
-
-    LVM_FLOAT *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-    LVM_FLOAT         coefs[3];       /* pointer to the filter coefficients */
-}Filter_State_FLOAT;
-typedef Filter_State_FLOAT * PFilter_State_FLOAT ;
-#endif /*_BP_1I_D16F16CSS_TRC_WRA_01_PRIVATE_H_*/
diff --git a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F32C30_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BP_1I_D16F32C30_TRC_WRA_01.cpp
deleted file mode 100644
index c844d03..0000000
--- a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F32C30_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BP_1I_D16F32Cll_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A0,
- pBiquadState->coefs[1] is -B2,
- pBiquadState->coefs[2] is -B1, these are in Q30 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-2)L in Q0 format
- pBiquadState->pDelays[2] is y(n-1)L in Q16 format
- pBiquadState->pDelays[3] is y(n-2)L in Q16 format
-***************************************************************************/
-void BP_1I_D16F32C30_TRC_WRA_01 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                  LVM_FLOAT               *pDataIn,
-                                  LVM_FLOAT               *pDataOut,
-                                  LVM_INT16               NrSamples)
-{
-    LVM_FLOAT ynL,templ;
-    LVM_INT16 ii;
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT)pInstance;
-
-    for (ii = NrSamples; ii != 0; ii--)
-    {
-        /**************************************************************************
-                       PROCESSING OF THE LEFT CHANNEL
-        ***************************************************************************/
-        // ynL= (A0 * (x(n)L - x(n-2)L ))
-        templ = (LVM_FLOAT) *pDataIn - pBiquadState->pDelays[1];
-        ynL = pBiquadState->coefs[0] * templ;
-
-        // ynL+= ((-B2  * y(n-2)L  ) )
-        templ = pBiquadState->coefs[1] * pBiquadState->pDelays[3];
-        ynL += templ;
-
-        // ynL+= ((-B1  * y(n-1)L  ))
-        templ = pBiquadState->coefs[2] * pBiquadState->pDelays[2];
-        ynL += templ;
-
-        /**************************************************************************
-                        UPDATING THE DELAYS
-        ***************************************************************************/
-        pBiquadState->pDelays[3] = pBiquadState->pDelays[2]; // y(n-2)L=y(n-1)L
-        pBiquadState->pDelays[1] = pBiquadState->pDelays[0]; // x(n-2)L=x(n-1)L
-        pBiquadState->pDelays[2] = ynL; // Update y(n-1)L in Q16
-        pBiquadState->pDelays[0] = (*pDataIn++); // Update x(n-1)L in Q0
-
-        /**************************************************************************
-                        WRITING THE OUTPUT
-        ***************************************************************************/
-        *pDataOut++ = (ynL); // Write Left output
-        }
-}
diff --git a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F32Cll_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/BP_1I_D16F32Cll_TRC_WRA_01_Init.cpp
deleted file mode 100644
index eb15032..0000000
--- a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F32Cll_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*-------------------------------------------------------------------------*/
-#include "BIQUAD.h"
-#include "BP_1I_D16F32Cll_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   BP_1I_D16F32Cll_TRC_WRA_01_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a Band pass filter (BIQUAD)               */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/*                                                                         */
-/*        The coefficients are modified in the init() function such that lower               */
-/*        half word is right shifted by one and most significant bit of the lower            */
-/*        word is made to be zero.                                                           */
-/*                                                                                           */
-/*       Reason: For MIPS effciency,we are using DSP 32*16 multiplication                    */
-/*       instruction. But we have 32*32 multiplication. This can be realized by two 32*16    */
-/*       multiplication. But 16th bit in the 32 bit word is not a sign bit. So this is done  */
-/*       by putting 16th bit to zero and lossing one bit precision by division of lower      */
-/*       half word by 2.                                                                     */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void BP_1I_D16F32Cll_TRC_WRA_01_Init (    Biquad_FLOAT_Instance_t         *pInstance,
-                                          Biquad_1I_Order2_FLOAT_Taps_t   *pTaps,
-                                          BP_FLOAT_Coefs_t                *pCoef)
-{
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-    pBiquadState->pDelays       =(LVM_FLOAT *) pTaps;
-
-    pBiquadState->coefs[0] =  pCoef->A0;
-    pBiquadState->coefs[1] =  pCoef->B2;
-    pBiquadState->coefs[2] =  pCoef->B1;
-}
-/*-------------------------------------------------------------------------*/
-/* End Of File: BP_1I_D16F32Cll_TRC_WRA_01_Init.c                              */
-
diff --git a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F32Cll_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/BP_1I_D16F32Cll_TRC_WRA_01_Private.h
deleted file mode 100644
index 6d754e2..0000000
--- a/media/libeffects/lvm/lib/Common/src/BP_1I_D16F32Cll_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef _BP_1I_D16F32CLL_TRC_WRA_01_PRIVATE_H_
-#define _BP_1I_D16F32CLL_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT32         coefs[3];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-typedef struct _Filter_State_FLOAT
-{
-    LVM_FLOAT *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-    LVM_FLOAT         coefs[3];       /* pointer to the filter coefficients */
-}Filter_State_Float;
-typedef Filter_State_Float * PFilter_State_FLOAT ;
-#endif /*_BP_1I_D16F32CLL_TRC_WRA_01_PRIVATE_H_*/
diff --git a/media/libeffects/lvm/lib/Common/src/BP_1I_D32F32C30_TRC_WRA_02.cpp b/media/libeffects/lvm/lib/Common/src/BP_1I_D32F32C30_TRC_WRA_02.cpp
deleted file mode 100644
index d0ba206..0000000
--- a/media/libeffects/lvm/lib/Common/src/BP_1I_D32F32C30_TRC_WRA_02.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BP_1I_D32F32Cll_TRC_WRA_02_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A0,
- pBiquadState->coefs[1] is -B2,
- pBiquadState->coefs[2] is -B1, these are in Q30 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-2)L in Q0 format
- pBiquadState->pDelays[2] is y(n-1)L in Q0 format
- pBiquadState->pDelays[3] is y(n-2)L in Q0 format
-***************************************************************************/
-void BP_1I_D32F32C30_TRC_WRA_02 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                  LVM_FLOAT               *pDataIn,
-                                  LVM_FLOAT               *pDataOut,
-                                  LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT ynL,templ;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-        for (ii = NrSamples; ii != 0; ii--)
-        {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            // ynL= (A0  * (x(n)L  - x(n-2)L  ) )
-            templ = (*pDataIn) - pBiquadState->pDelays[1];
-            ynL = pBiquadState->coefs[0] * templ;
-
-            // ynL+= ((-B2  * y(n-2)L  ) )
-            templ = pBiquadState->coefs[1] * pBiquadState->pDelays[3];
-            ynL += templ;
-
-            // ynL+= ((-B1  * y(n-1)L  ) )
-            templ = pBiquadState->coefs[2] * pBiquadState->pDelays[2];
-            ynL += templ;
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[2]; // y(n-2)L=y(n-1)L
-            pBiquadState->pDelays[1] = pBiquadState->pDelays[0]; // x(n-2)L=x(n-1)L
-            pBiquadState->pDelays[2] = ynL; // Update y(n-1)L
-            pBiquadState->pDelays[0] = (*pDataIn++); // Update x(n-1)L
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut++ = ynL; // Write Left output in Q0
-
-        }
-
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/BP_1I_D32F32Cll_TRC_WRA_02_Init.cpp b/media/libeffects/lvm/lib/Common/src/BP_1I_D32F32Cll_TRC_WRA_02_Init.cpp
deleted file mode 100644
index 6f7d0b5..0000000
--- a/media/libeffects/lvm/lib/Common/src/BP_1I_D32F32Cll_TRC_WRA_02_Init.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*-------------------------------------------------------------------------*/
-#include "BIQUAD.h"
-#include "BP_1I_D32F32Cll_TRC_WRA_02_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   BP_1I_D32F32Cll_TRC_WRA_02_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void BP_1I_D32F32Cll_TRC_WRA_02_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_1I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BP_FLOAT_Coefs_t            *pCoef)
-{
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-    pBiquadState->pDelays       =(LVM_FLOAT *) pTaps;
-
-    pBiquadState->coefs[0] = pCoef->A0;
-
-    pBiquadState->coefs[1] = pCoef->B2;
-
-    pBiquadState->coefs[2] = pCoef->B1;
-}
-/*-------------------------------------------------------------------------*/
-/* End Of File: BP_1I_D32F32Cll_TRC_WRA_02_Init.c                              */
-
diff --git a/media/libeffects/lvm/lib/Common/src/BP_1I_D32F32Cll_TRC_WRA_02_Private.h b/media/libeffects/lvm/lib/Common/src/BP_1I_D32F32Cll_TRC_WRA_02_Private.h
deleted file mode 100644
index 9f1c66a..0000000
--- a/media/libeffects/lvm/lib/Common/src/BP_1I_D32F32Cll_TRC_WRA_02_Private.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef _BP_1I_D32F32CLL_TRC_WRA_02_PRIVATE_H_
-#define _BP_1I_D32F32CLL_TRC_WRA_02_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT32         coefs[3];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-typedef struct _Filter_State_FLOAT
-{
-    LVM_FLOAT *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-    LVM_FLOAT         coefs[3];       /* pointer to the filter coefficients */
-}Filter_State_Float;
-typedef Filter_State_Float* PFilter_State_FLOAT ;
-
-#endif /*_BP_1I_D32F32CLL_TRC_WRA_02_PRIVATE_H_*/
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F16C15_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F16C15_TRC_WRA_01.cpp
deleted file mode 100644
index 9aecc40..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F16C15_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BQ_1I_D16F16Css_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A2, pBiquadState->coefs[1] is A1
- pBiquadState->coefs[2] is A0, pBiquadState->coefs[3] is -B2
- pBiquadState->coefs[4] is -B1, these are in Q15 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-2)L in Q0 format
- pBiquadState->pDelays[2] is y(n-1)L in Q0 format
- pBiquadState->pDelays[3] is y(n-2)L in Q0 format
-***************************************************************************/
-void BQ_1I_D16F16C15_TRC_WRA_01 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                  LVM_FLOAT               *pDataIn,
-                                  LVM_FLOAT               *pDataOut,
-                                  LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT  ynL;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-         for (ii = NrSamples; ii != 0; ii--)
-         {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            // ynL=A2  * x(n-2)L
-            ynL = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[1];
-
-            // ynL+=A1 * x(n-1)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[0];
-
-            // ynL+=A0 * x(n)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[2] * (*pDataIn);
-
-            // ynL+=  (-B2  * y(n-2)L )
-            ynL += (LVM_FLOAT)pBiquadState->coefs[3] * pBiquadState->pDelays[3];
-
-            // ynL+= (-B1  * y(n-1)L  )
-            ynL += (LVM_FLOAT)pBiquadState->coefs[4] * pBiquadState->pDelays[2];
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[2]; // y(n-2)L=y(n-1)L
-            pBiquadState->pDelays[1] = pBiquadState->pDelays[0]; // x(n-2)L=x(n-1)L
-            pBiquadState->pDelays[2] = ynL; // Update y(n-1)L
-            pBiquadState->pDelays[0] = (*pDataIn++); // Update x(n-1)L
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut++ = (LVM_FLOAT)ynL; // Write Left output in Q0
-
-        }
-
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F16Css_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F16Css_TRC_WRA_01_Init.cpp
deleted file mode 100644
index f0b5d06..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F16Css_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*-------------------------------------------------------------------------*/
-#include "BIQUAD.h"
-#include "BQ_1I_D16F16Css_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   BQ_1I_D16F16Css_TRC_WRA_01_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void BQ_1I_D16F16Css_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_1I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BQ_FLOAT_Coefs_t            *pCoef)
-{
-    LVM_FLOAT temp;
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-    pBiquadState->pDelays      = (LVM_FLOAT *) pTaps ;
-    temp = pCoef->A2;
-    pBiquadState->coefs[0] = temp;
-    temp = pCoef->A1;
-    pBiquadState->coefs[1] = temp;
-    temp = pCoef->A0;
-    pBiquadState->coefs[2] = temp;
-    temp = pCoef->B2;
-    pBiquadState->coefs[3] = temp;
-    temp = pCoef->B1;
-    pBiquadState->coefs[4] = temp;
-}
-/*-------------------------------------------------------------------------*/
-/* End Of File: BQ_1I_D16F16Css_TRC_WRA_01_Init.c                              */
-
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F16Css_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F16Css_TRC_WRA_01_Private.h
deleted file mode 100644
index fad345d..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F16Css_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef _BQ_1I_D16F16CSS_TRC_WRA_01_PRIVATE_H_
-#define _BQ_1I_D16F16CSS_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT16         coefs[5];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-typedef struct _Filter_State_FLOAT
-{
-    LVM_FLOAT *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-    LVM_FLOAT         coefs[5];       /* pointer to the filter coefficients */
-
-}Filter_State_FLOAT;
-typedef Filter_State_FLOAT * PFilter_State_FLOAT ;
-#endif /*_BQ_1I_D16F16CSS_TRC_WRA_01_PRIVATE_H_ */
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F32C14_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F32C14_TRC_WRA_01.cpp
deleted file mode 100644
index 043bc5f..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F32C14_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BQ_1I_D16F32Css_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A2, pBiquadState->coefs[1] is A1
- pBiquadState->coefs[2] is A0, pBiquadState->coefs[3] is -B2
- pBiquadState->coefs[4] is -B1, these are in Q14 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-2)L in Q0 format
- pBiquadState->pDelays[2] is y(n-1)L in Q16 format
- pBiquadState->pDelays[3] is y(n-2)L in Q16 format
-***************************************************************************/
-void BQ_1I_D16F32C14_TRC_WRA_01 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                  LVM_FLOAT               *pDataIn,
-                                  LVM_FLOAT               *pDataOut,
-                                  LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT  ynL;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-         for (ii = NrSamples; ii != 0; ii--)
-         {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            // ynL=A2  * x(n-2)L
-            ynL = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[1];
-
-            // ynL+=A1  * x(n-1)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[0];
-
-            // ynL+=A0  * x(n)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[2] * (*pDataIn);
-
-            // ynL+= ( (-B2  * y(n-2)L )
-            ynL += pBiquadState->pDelays[3] * pBiquadState->coefs[3];
-
-            // ynL+= -B1  * y(n-1)L
-            ynL += pBiquadState->pDelays[2] * pBiquadState->coefs[4];
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[2];  // y(n-2)L=y(n-1)L
-            pBiquadState->pDelays[1] = pBiquadState->pDelays[0];  // x(n-2)L=x(n-1)L
-            pBiquadState->pDelays[2] = ynL;                    // Update y(n-1)L
-            pBiquadState->pDelays[0] = (*pDataIn++);              // Update x(n-1)L
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut++ = (LVM_FLOAT)(ynL); // Write Left output
-
-        }
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F32Css_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F32Css_TRC_WRA_01_Private.h
deleted file mode 100644
index 6a61d9a..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F32Css_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef _BQ_1I_D16F32CSS_TRC_WRA_01_PRIVATE_H_
-#define _BQ_1I_D16F32CSS_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *   pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT16     coefs[5];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-typedef struct _Filter_State_FLOAT
-{
-    LVM_FLOAT *   pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-    LVM_FLOAT     coefs[5];       /* pointer to the filter coefficients */
-
-}Filter_State_FLOAT;
-typedef Filter_State_FLOAT * PFilter_State_FLOAT ;
-#endif /*_BQ_1I_D16F32CSS_TRC_WRA_01_PRIVATE_H_*/
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F32Css_TRC_WRA_01_init.cpp b/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F32Css_TRC_WRA_01_init.cpp
deleted file mode 100644
index 2b80691..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_1I_D16F32Css_TRC_WRA_01_init.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*-------------------------------------------------------------------------*/
-#include "BIQUAD.h"
-#include "BQ_1I_D16F32Css_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   BQ_1I_D16F32Css_TRC_WRA_01_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void BQ_1I_D16F32Css_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_1I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BQ_FLOAT_Coefs_t            *pCoef)
-{
-    LVM_FLOAT temp;
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-    pBiquadState->pDelays      = (LVM_FLOAT *)pTaps;
-
-    temp = pCoef->A2;
-    pBiquadState->coefs[0] = temp;
-    temp = pCoef->A1;
-    pBiquadState->coefs[1] = temp;
-    temp = pCoef->A0;
-    pBiquadState->coefs[2] = temp;
-    temp = pCoef->B2;
-    pBiquadState->coefs[3] = temp;
-    temp = pCoef->B1;
-    pBiquadState->coefs[4] = temp;
-}
-/*-------------------------------------------------------------------------*/
-/* End Of File: BQ_1I_D16F32Css_TRC_WRA_01_Init                              */
-
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16C14_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16C14_TRC_WRA_01.cpp
deleted file mode 100644
index 51cd918..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16C14_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BQ_2I_D16F16Css_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A2, pBiquadState->coefs[1] is A1
- pBiquadState->coefs[2] is A0, pBiquadState->coefs[3] is -B2
- pBiquadState->coefs[4] is -B1, these are in Q14 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-1)R in Q0 format
- pBiquadState->pDelays[2] is x(n-2)L in Q0 format
- pBiquadState->pDelays[3] is x(n-2)R in Q0 format
- pBiquadState->pDelays[4] is y(n-1)L in Q0 format
- pBiquadState->pDelays[5] is y(n-1)R in Q0 format
- pBiquadState->pDelays[6] is y(n-2)L in Q0 format
- pBiquadState->pDelays[7] is y(n-2)R in Q0 format
-***************************************************************************/
-void BQ_2I_D16F16C14_TRC_WRA_01 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                  LVM_FLOAT               *pDataIn,
-                                  LVM_FLOAT               *pDataOut,
-                                  LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT  ynL,ynR;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-         for (ii = NrSamples; ii != 0; ii--)
-         {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            // ynL=A2  * x(n-2)L
-            ynL = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[2];
-
-            // ynL+=A1  * x(n-1)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[0];
-
-            // ynL+=A0  * x(n)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[2] * (*pDataIn);
-
-            // ynL+= ( -B2  * y(n-2)L  )
-            ynL += (LVM_FLOAT)pBiquadState->coefs[3] * pBiquadState->pDelays[6];
-
-            // ynL+=( -B1  * y(n-1)L )
-            ynL += (LVM_FLOAT)pBiquadState->coefs[4] * pBiquadState->pDelays[4];
-
-            /**************************************************************************
-                            PROCESSING OF THE RIGHT CHANNEL
-            ***************************************************************************/
-            // ynR=A2  * x(n-2)R
-            ynR = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[3];
-
-            // ynR+=A1  * x(n-1)R
-            ynR += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[1];
-
-            // ynR+=A0  * x(n)R
-            ynR += (LVM_FLOAT)pBiquadState->coefs[2] * (*(pDataIn+1));
-
-            // ynR+= ( -B2  * y(n-2)R  )
-            ynR += (LVM_FLOAT)pBiquadState->coefs[3] * pBiquadState->pDelays[7];
-
-            // ynR+=( -B1  * y(n-1)R  )
-            ynR += (LVM_FLOAT)pBiquadState->coefs[4] * pBiquadState->pDelays[5];
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[7] = pBiquadState->pDelays[5];  // y(n-2)R=y(n-1)R
-            pBiquadState->pDelays[6] = pBiquadState->pDelays[4];  // y(n-2)L=y(n-1)L
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[1];  // x(n-2)R=x(n-1)R
-            pBiquadState->pDelays[2] = pBiquadState->pDelays[0];  // x(n-2)L=x(n-1)L
-            pBiquadState->pDelays[5] = ynR;                       // Update y(n-1)R
-            pBiquadState->pDelays[4] = ynL;                       // Update y(n-1)L
-            pBiquadState->pDelays[0] = (*pDataIn++);              // Update x(n-1)L
-            pBiquadState->pDelays[1] = (*pDataIn++);              // Update x(n-1)R
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut++ = (LVM_FLOAT)ynL; // Write Left output
-            *pDataOut++ = (LVM_FLOAT)ynR; // Write Right ouput
-
-        }
-
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16C15_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16C15_TRC_WRA_01.cpp
deleted file mode 100644
index 8f74749..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16C15_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BQ_2I_D16F16Css_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A2, pBiquadState->coefs[1] is A1
- pBiquadState->coefs[2] is A0, pBiquadState->coefs[3] is -B2
- pBiquadState->coefs[4] is -B1, these are in Q15 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-1)R in Q0 format
- pBiquadState->pDelays[2] is x(n-2)L in Q0 format
- pBiquadState->pDelays[3] is x(n-2)R in Q0 format
- pBiquadState->pDelays[4] is y(n-1)L in Q0 format
- pBiquadState->pDelays[5] is y(n-1)R in Q0 format
- pBiquadState->pDelays[6] is y(n-2)L in Q0 format
- pBiquadState->pDelays[7] is y(n-2)R in Q0 format
-***************************************************************************/
-void BQ_2I_D16F16C15_TRC_WRA_01 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                  LVM_FLOAT               *pDataIn,
-                                  LVM_FLOAT               *pDataOut,
-                                  LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT  ynL,ynR;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-         for (ii = NrSamples; ii != 0; ii--)
-         {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            // ynL=A2  * x(n-2)L
-            ynL = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[2];
-
-            // ynL+=A1  * x(n-1)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[0];
-
-            // ynL+=A0  * x(n)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[2] * (*pDataIn);
-
-            // ynL+= ( -B2  * y(n-2)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[3] * pBiquadState->pDelays[6];
-
-            // ynL+=( -B1  * y(n-1)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[4] * pBiquadState->pDelays[4];
-
-            /**************************************************************************
-                            PROCESSING OF THE RIGHT CHANNEL
-            ***************************************************************************/
-            // ynR=A2  * x(n-2)R
-            ynR = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[3];
-
-            // ynR+=A1  * x(n-1)R
-            ynR += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[1];
-
-            // ynR+=A0  * x(n)R
-            ynR += (LVM_FLOAT)pBiquadState->coefs[2] * (*(pDataIn+1));
-
-            // ynR+= ( -B2  * y(n-2)R  )
-            ynR += (LVM_FLOAT)pBiquadState->coefs[3] * pBiquadState->pDelays[7];
-
-            // ynR+=( -B1  * y(n-1)R  )
-            ynR += (LVM_FLOAT)pBiquadState->coefs[4] * pBiquadState->pDelays[5];
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[7] = pBiquadState->pDelays[5];  // y(n-2)R=y(n-1)R
-            pBiquadState->pDelays[6] = pBiquadState->pDelays[4];  // y(n-2)L=y(n-1)L
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[1];  // x(n-2)R=x(n-1)R
-            pBiquadState->pDelays[2] = pBiquadState->pDelays[0];  // x(n-2)L=x(n-1)L
-            pBiquadState->pDelays[5] = ynR;                       // Update y(n-1)R
-            pBiquadState->pDelays[4] = ynL;                       // Update y(n-1)L
-            pBiquadState->pDelays[0] = (*pDataIn++);              // Update x(n-1)L
-            pBiquadState->pDelays[1] = (*pDataIn++);              // Update x(n-1)R
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut++ = (LVM_FLOAT)ynL; // Write Left output
-            *pDataOut++ = (LVM_FLOAT)ynR; // Write Right ouput
-
-        }
-
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16Css_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16Css_TRC_WRA_01_Init.cpp
deleted file mode 100644
index 987cbcf..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16Css_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*-------------------------------------------------------------------------*/
-#include "BIQUAD.h"
-#include "BQ_2I_D16F16Css_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   BQ_2I_D16F16Css_TRC_WRA_01_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void BQ_2I_D16F16Css_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_2I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BQ_FLOAT_Coefs_t            *pCoef)
-{
-    LVM_FLOAT temp;
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-    pBiquadState->pDelays      = (LVM_FLOAT *) pTaps            ;
-
-    temp = pCoef->A2;
-    pBiquadState->coefs[0] = temp;
-    temp = pCoef->A1;
-    pBiquadState->coefs[1] = temp;
-    temp = pCoef->A0;
-    pBiquadState->coefs[2] = temp;
-    temp = pCoef->B2;
-    pBiquadState->coefs[3] = temp;
-    temp = pCoef->B1;
-    pBiquadState->coefs[4] = temp;
-}
-/*-------------------------------------------------------------------------*/
-/* End Of File: BQ_2I_D16F16Css_TRC_WRA_01_Init.c                              */
-
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16Css_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16Css_TRC_WRA_01_Private.h
deleted file mode 100644
index 5a9a0e9..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F16Css_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _BQ_2I_D16F16CSS_TRC_WRA_01_PRIVATE_H_
-#define _BQ_2I_D16F16CSS_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *   pDelays;            /* pointer to the delayed samples (data of 32 bits) */
-  LVM_INT16     coefs[5];           /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-typedef struct _Filter_State_FLOAT
-{
-    LVM_FLOAT *   pDelays;            /* pointer to the delayed samples (data of 32 bits) */
-    LVM_FLOAT     coefs[5];           /* pointer to the filter coefficients */
-
-}Filter_State_FLOAT;
-typedef Filter_State_FLOAT * PFilter_State_FLOAT ;
-
-#endif /* _BQ_2I_D16F16CSS_TRC_WRA_01_PRIVATE_H_ */
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32C13_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32C13_TRC_WRA_01.cpp
deleted file mode 100644
index 331c97f..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32C13_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BQ_2I_D16F32Css_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A2, pBiquadState->coefs[1] is A1
- pBiquadState->coefs[2] is A0, pBiquadState->coefs[3] is -B2
- pBiquadState->coefs[4] is -B1, these are in Q13 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-1)R in Q0 format
- pBiquadState->pDelays[2] is x(n-2)L in Q0 format
- pBiquadState->pDelays[3] is x(n-2)R in Q0 format
- pBiquadState->pDelays[4] is y(n-1)L in Q16 format
- pBiquadState->pDelays[5] is y(n-1)R in Q16 format
- pBiquadState->pDelays[6] is y(n-2)L in Q16 format
- pBiquadState->pDelays[7] is y(n-2)R in Q16 format
-***************************************************************************/
-void BQ_2I_D16F32C13_TRC_WRA_01 (           Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrSamples)
-    {
-        LVM_FLOAT  ynL,ynR;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-        for (ii = NrSamples; ii != 0; ii--)
-        {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            /* ynL=A2 * x(n-2)L */
-            ynL = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[2];
-
-            /* ynL+=A1* x(n-1)L */
-            ynL += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[0];
-
-            /* ynL+=A0* x(n)L   */
-            ynL += (LVM_FLOAT)pBiquadState->coefs[2] * (*pDataIn);
-
-            /* ynL+=-B2*y(n-2)L */
-            ynL += pBiquadState->pDelays[6] * pBiquadState->coefs[3];
-
-            /* ynL+=-B1*y(n-1)L */
-            ynL += pBiquadState->pDelays[4] * pBiquadState->coefs[4];
-
-            /**************************************************************************
-                            PROCESSING OF THE RIGHT CHANNEL
-            ***************************************************************************/
-            /* ynR=A2 * x(n-2)R */
-            ynR = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[3];
-
-            /* ynR+=A1* x(n-1)R */
-            ynR += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[1];
-
-            /* ynR+=A0* x(n)R   */
-            ynR += (LVM_FLOAT)pBiquadState->coefs[2] * (*(pDataIn+1));
-
-            /* ynR+=-B2 * y(n-2)R */
-            ynR += pBiquadState->pDelays[7] * pBiquadState->coefs[3];
-
-            /* ynR+=-B1 * y(n-1)R */
-            ynR += pBiquadState->pDelays[5] * pBiquadState->coefs[4];
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[7] = pBiquadState->pDelays[5];  /* y(n-2)R=y(n-1)R*/
-            pBiquadState->pDelays[6] = pBiquadState->pDelays[4];  /* y(n-2)L=y(n-1)L*/
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[1];  /* x(n-2)R=x(n-1)R*/
-            pBiquadState->pDelays[2] = pBiquadState->pDelays[0];  /* x(n-2)L=x(n-1)L*/
-            pBiquadState->pDelays[5] = ynR;                       /* Update y(n-1)R */
-            pBiquadState->pDelays[4] = ynL;                       /* Update y(n-1)L */
-            pBiquadState->pDelays[0] = (*pDataIn);                /* Update x(n-1)L */
-            pDataIn++;
-            pBiquadState->pDelays[1] = (*pDataIn);                /* Update x(n-1)R */
-            pDataIn++;
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut = (LVM_FLOAT)(ynL); /* Write Left output */
-            pDataOut++;
-            *pDataOut = (LVM_FLOAT)(ynR); /* Write Right ouput */
-            pDataOut++;
-        }
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32C14_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32C14_TRC_WRA_01.cpp
deleted file mode 100644
index 3a396df..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32C14_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BQ_2I_D16F32Css_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A2, pBiquadState->coefs[1] is A1
- pBiquadState->coefs[2] is A0, pBiquadState->coefs[3] is -B2
- pBiquadState->coefs[4] is -B1, these are in Q14 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-1)R in Q0 format
- pBiquadState->pDelays[2] is x(n-2)L in Q0 format
- pBiquadState->pDelays[3] is x(n-2)R in Q0 format
- pBiquadState->pDelays[4] is y(n-1)L in Q16 format
- pBiquadState->pDelays[5] is y(n-1)R in Q16 format
- pBiquadState->pDelays[6] is y(n-2)L in Q16 format
- pBiquadState->pDelays[7] is y(n-2)R in Q16 format
-***************************************************************************/
-void BQ_2I_D16F32C14_TRC_WRA_01 (           Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrSamples)
-    {
-        LVM_FLOAT  ynL,ynR;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-        for (ii = NrSamples; ii != 0; ii--)
-        {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            /* ynL=A2  * x(n-2)L */
-            ynL = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[2];
-
-            /* ynL+=A1  * x(n-1)L */
-            ynL += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[0];
-
-            /* ynL+=A0  * x(n)L */
-            ynL += (LVM_FLOAT)pBiquadState->coefs[2] * (*pDataIn);
-
-            /* ynL+= ( (-B2  * y(n-2)L  ))*/
-            ynL += pBiquadState->pDelays[6] * pBiquadState->coefs[3];
-
-            /* ynL+=( (-B1  * y(n-1)L  ))  */
-            ynL += pBiquadState->pDelays[4] * pBiquadState->coefs[4];
-
-            /**************************************************************************
-                            PROCESSING OF THE RIGHT CHANNEL
-            ***************************************************************************/
-            /* ynR=A2  * x(n-2)R */
-            ynR = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[3];
-
-            /* ynR+=A1  * x(n-1)R */
-            ynR += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[1];
-
-            /* ynR+=A0  * x(n)R */
-            ynR += (LVM_FLOAT)pBiquadState->coefs[2] * (*(pDataIn+1));
-
-            /* ynR+= ( (-B2  * y(n-2)R  ))*/
-            ynR += pBiquadState->pDelays[7] * pBiquadState->coefs[3];
-
-            /* ynR+=( (-B1  * y(n-1)R  ))  */
-            ynR += pBiquadState->pDelays[5] * pBiquadState->coefs[4];
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[7] = pBiquadState->pDelays[5];  /* y(n-2)R=y(n-1)R*/
-            pBiquadState->pDelays[6] = pBiquadState->pDelays[4];  /* y(n-2)L=y(n-1)L*/
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[1];  /* x(n-2)R=x(n-1)R*/
-            pBiquadState->pDelays[2] = pBiquadState->pDelays[0];  /* x(n-2)L=x(n-1)L*/
-            pBiquadState->pDelays[5] = ynR;                    /* Update y(n-1)R */
-            pBiquadState->pDelays[4] = ynL;                    /* Update y(n-1)L */
-            pBiquadState->pDelays[0] = (*pDataIn);                /* Update x(n-1)L */
-            pDataIn++;
-            pBiquadState->pDelays[1] = (*pDataIn);                /* Update x(n-1)R */
-            pDataIn++;
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut = (LVM_FLOAT)(ynL); /* Write Left output */
-            pDataOut++;
-            *pDataOut = (LVM_FLOAT)(ynR); /* Write Right ouput */
-            pDataOut++;
-        }
-
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32C15_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32C15_TRC_WRA_01.cpp
deleted file mode 100644
index 1cbff1a..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32C15_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BQ_2I_D16F32Css_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A2, pBiquadState->coefs[1] is A1
- pBiquadState->coefs[2] is A0, pBiquadState->coefs[3] is -B2
- pBiquadState->coefs[4] is -B1, these are in Q15 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-1)R in Q0 format
- pBiquadState->pDelays[2] is x(n-2)L in Q0 format
- pBiquadState->pDelays[3] is x(n-2)R in Q0 format
- pBiquadState->pDelays[4] is y(n-1)L in Q16 format
- pBiquadState->pDelays[5] is y(n-1)R in Q16 format
- pBiquadState->pDelays[6] is y(n-2)L in Q16 format
- pBiquadState->pDelays[7] is y(n-2)R in Q16 format
-***************************************************************************/
-void BQ_2I_D16F32C15_TRC_WRA_01 (           Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrSamples)
-    {
-        LVM_FLOAT  ynL,ynR;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-         for (ii = NrSamples; ii != 0; ii--)
-         {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            /* ynL=A2  * x(n-2)L */
-            ynL = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[2];
-
-            /* ynL+=A1  * x(n-1)L */
-            ynL += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[0];
-
-            /* ynL+=A0  * x(n)L */
-            ynL += (LVM_FLOAT)pBiquadState->coefs[2] * (*pDataIn);
-
-            /* ynL+= ( (-B2  * y(n-2)L )  */
-            ynL += pBiquadState->pDelays[6] * pBiquadState->coefs[3];
-
-            /* ynL+=( (-B1  * y(n-1)L  ))  */
-            ynL += pBiquadState->pDelays[4] * pBiquadState->coefs[4];
-
-            /**************************************************************************
-                            PROCESSING OF THE RIGHT CHANNEL
-            ***************************************************************************/
-            /* ynR=A2  * x(n-2)R */
-            ynR = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[3];
-
-            /* ynR+=A1  * x(n-1)R */
-            ynR += (LVM_FLOAT)pBiquadState->coefs[1] * pBiquadState->pDelays[1];
-
-            /* ynR+=A0  * x(n)R */
-            ynR += (LVM_FLOAT)pBiquadState->coefs[2] * (*(pDataIn+1));
-
-            /* ynR+= ( (-B2  * y(n-2)R ) */
-            ynR += pBiquadState->pDelays[7] * pBiquadState->coefs[3];
-
-            /* ynR+=( (-B1  * y(n-1)R  )) in Q15 */
-            ynR += pBiquadState->pDelays[5] * pBiquadState->coefs[4];
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[7] = pBiquadState->pDelays[5]; /* y(n-2)R=y(n-1)R*/
-            pBiquadState->pDelays[6] = pBiquadState->pDelays[4]; /* y(n-2)L=y(n-1)L*/
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[1]; /* x(n-2)R=x(n-1)R*/
-            pBiquadState->pDelays[2] = pBiquadState->pDelays[0]; /* x(n-2)L=x(n-1)L*/
-            pBiquadState->pDelays[5] = ynR; /* Update y(n-1)R*/
-            pBiquadState->pDelays[4] = ynL; /* Update y(n-1)L*/
-            pBiquadState->pDelays[0] = (*pDataIn); /* Update x(n-1)L*/
-            pDataIn++;
-            pBiquadState->pDelays[1] = (*pDataIn); /* Update x(n-1)R*/
-            pDataIn++;
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut = (LVM_FLOAT)(ynL); /* Write Left output*/
-            pDataOut++;
-            *pDataOut = (LVM_FLOAT)(ynR); /* Write Right ouput*/
-            pDataOut++;
-        }
-
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32Css_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32Css_TRC_WRA_01_Private.h
deleted file mode 100644
index 314388a..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32Css_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _BQ_2I_D16F32CSS_TRC_WRA_01_PRIVATE_H_
-#define _BQ_2I_D16F32CSS_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *                          pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT16                           coefs[5];         /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-typedef struct _Filter_State_FLOAT
-{
-    LVM_FLOAT *                          pDelays;        /* pointer to the delayed samples \
-                                                           (data of 32 bits)   */
-    LVM_FLOAT                           coefs[5];        /* pointer to the filter coefficients */
-}Filter_State_FLOAT;
-typedef Filter_State_FLOAT * PFilter_State_FLOAT ;
-
-#endif /* _BQ_2I_D16F32CSS_TRC_WRA_01_PRIVATE_H_ */
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32Css_TRC_WRA_01_init.cpp b/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32Css_TRC_WRA_01_init.cpp
deleted file mode 100644
index 058541a..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D16F32Css_TRC_WRA_01_init.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BQ_2I_D16F32Css_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   BQ_2I_D16F32Css_TRC_WRA_01_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void BQ_2I_D16F32Css_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_2I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BQ_FLOAT_Coefs_t            *pCoef)
-{
-    LVM_FLOAT temp;
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-    pBiquadState->pDelays      = (LVM_FLOAT *) pTaps;
-    temp = pCoef->A2;
-    pBiquadState->coefs[0] = temp;
-    temp = pCoef->A1;
-    pBiquadState->coefs[1] = temp;
-    temp = pCoef->A0;
-    pBiquadState->coefs[2] = temp;
-    temp = pCoef->B2;
-    pBiquadState->coefs[3] = temp;
-    temp = pCoef->B1;
-    pBiquadState->coefs[4] = temp;
-}
-/*-------------------------------------------------------------------------*/
-/* End Of File: BQ_2I_D16F32Css_TRC_WRA_01_Init                              */
-
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D32F32C30_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/BQ_2I_D32F32C30_TRC_WRA_01.cpp
deleted file mode 100644
index 78d1ba1..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D32F32C30_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "BQ_2I_D32F32Cll_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A2, pBiquadState->coefs[1] is A1
- pBiquadState->coefs[2] is A0, pBiquadState->coefs[3] is -B2
- pBiquadState->coefs[4] is -B1, these are in Q30 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-1)R in Q0 format
- pBiquadState->pDelays[2] is x(n-2)L in Q0 format
- pBiquadState->pDelays[3] is x(n-2)R in Q0 format
- pBiquadState->pDelays[4] is y(n-1)L in Q0 format
- pBiquadState->pDelays[5] is y(n-1)R in Q0 format
- pBiquadState->pDelays[6] is y(n-2)L in Q0 format
- pBiquadState->pDelays[7] is y(n-2)R in Q0 format
-***************************************************************************/
-void BQ_2I_D32F32C30_TRC_WRA_01 (           Biquad_FLOAT_Instance_t       *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrSamples)
-
-    {
-        LVM_FLOAT ynL,ynR,templ,tempd;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-         for (ii = NrSamples; ii != 0; ii--)
-         {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            /* ynL= ( A2  * x(n-2)L  ) */
-            ynL = pBiquadState->coefs[0] * pBiquadState->pDelays[2];
-
-            /* ynL+= ( A1  * x(n-1)L  )*/
-            templ = pBiquadState->coefs[1] * pBiquadState->pDelays[0];
-            ynL += templ;
-
-            /* ynL+= ( A0  * x(n)L  ) */
-            templ = pBiquadState->coefs[2] * (*pDataIn);
-            ynL += templ;
-
-             /* ynL+= (-B2  * y(n-2)L  ) */
-            templ = pBiquadState->coefs[3] * pBiquadState->pDelays[6];
-            ynL += templ;
-
-            /* ynL+= (-B1  * y(n-1)L  )*/
-            templ = pBiquadState->coefs[4] * pBiquadState->pDelays[4];
-            ynL += templ;
-
-            /**************************************************************************
-                            PROCESSING OF THE RIGHT CHANNEL
-            ***************************************************************************/
-            /* ynR= ( A2  * x(n-2)R  ) */
-            ynR = pBiquadState->coefs[0] * pBiquadState->pDelays[3];
-
-            /* ynR+= ( A1  * x(n-1)R  ) */
-            templ = pBiquadState->coefs[1] * pBiquadState->pDelays[1];
-            ynR += templ;
-
-            /* ynR+= ( A0  * x(n)R  ) */
-            tempd =* (pDataIn+1);
-            templ = pBiquadState->coefs[2] * tempd;
-            ynR += templ;
-
-            /* ynR+= (-B2  * y(n-2)R  ) */
-            templ = pBiquadState->coefs[3] * pBiquadState->pDelays[7];
-            ynR += templ;
-
-            /* ynR+= (-B1  * y(n-1)R  )  */
-            templ = pBiquadState->coefs[4] * pBiquadState->pDelays[5];
-            ynR += templ;
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[7] = pBiquadState->pDelays[5]; /* y(n-2)R=y(n-1)R*/
-            pBiquadState->pDelays[6] = pBiquadState->pDelays[4]; /* y(n-2)L=y(n-1)L*/
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[1]; /* x(n-2)R=x(n-1)R*/
-            pBiquadState->pDelays[2] = pBiquadState->pDelays[0]; /* x(n-2)L=x(n-1)L*/
-            pBiquadState->pDelays[5] = (LVM_FLOAT)ynR; /* Update y(n-1)R */
-            pBiquadState->pDelays[4] = (LVM_FLOAT)ynL; /* Update y(n-1)L */
-            pBiquadState->pDelays[0] = (*pDataIn); /* Update x(n-1)L */
-            pDataIn++;
-            pBiquadState->pDelays[1] = (*pDataIn); /* Update x(n-1)R */
-            pDataIn++;
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut = (LVM_FLOAT)ynL; /* Write Left output */
-            pDataOut++;
-            *pDataOut = (LVM_FLOAT)ynR; /* Write Right ouput */
-            pDataOut++;
-
-        }
-
-    }
-
-#ifdef SUPPORT_MC
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A2, pBiquadState->coefs[1] is A1
- pBiquadState->coefs[2] is A0, pBiquadState->coefs[3] is -B2
- pBiquadState->coefs[4] is -B1
-
- DELAYS-
- pBiquadState->pDelays[0] to
- pBiquadState->pDelays[NrChannels - 1] is x(n-1) for all NrChannels
-
- pBiquadState->pDelays[NrChannels] to
- pBiquadState->pDelays[2*NrChannels - 1] is x(n-2) for all NrChannels
-
- pBiquadState->pDelays[2*NrChannels] to
- pBiquadState->pDelays[3*NrChannels - 1] is y(n-1) for all NrChannels
-
- pBiquadState->pDelays[3*NrChannels] to
- pBiquadState->pDelays[4*NrChannels - 1] is y(n-2) for all NrChannels
-***************************************************************************/
-void BQ_MC_D32F32C30_TRC_WRA_01 (           Biquad_FLOAT_Instance_t      *pInstance,
-                                            LVM_FLOAT                    *pDataIn,
-                                            LVM_FLOAT                    *pDataOut,
-                                            LVM_INT16                    NrFrames,
-                                            LVM_INT16                    NrChannels)
-
-    {
-        LVM_FLOAT yn, temp;
-        LVM_INT16 ii, jj;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-         for (ii = NrFrames; ii != 0; ii--)
-         {
-            /**************************************************************************
-                            PROCESSING CHANNEL-WISE
-            ***************************************************************************/
-            for (jj = 0; jj < NrChannels; jj++)
-            {
-                /* yn= (A2  * x(n-2)) */
-                yn = pBiquadState->coefs[0] * pBiquadState->pDelays[NrChannels + jj];
-
-                /* yn+= (A1  * x(n-1)) */
-                temp = pBiquadState->coefs[1] * pBiquadState->pDelays[jj];
-                yn += temp;
-
-                /* yn+= (A0  * x(n)) */
-                temp = pBiquadState->coefs[2] * (*pDataIn);
-                yn += temp;
-
-                 /* yn+= (-B2  * y(n-2)) */
-                temp = pBiquadState->coefs[3] * pBiquadState->pDelays[NrChannels*3 + jj];
-                yn += temp;
-
-                /* yn+= (-B1  * y(n-1)) */
-                temp = pBiquadState->coefs[4] * pBiquadState->pDelays[NrChannels*2 + jj];
-                yn += temp;
-
-                /**************************************************************************
-                                UPDATING THE DELAYS
-                ***************************************************************************/
-                pBiquadState->pDelays[NrChannels * 3 + jj] =
-                    pBiquadState->pDelays[NrChannels * 2 + jj]; /* y(n-2)=y(n-1)*/
-                pBiquadState->pDelays[NrChannels * 1 + jj] =
-                    pBiquadState->pDelays[jj]; /* x(n-2)=x(n-1)*/
-                pBiquadState->pDelays[NrChannels * 2 + jj] = (LVM_FLOAT)yn; /* Update y(n-1)*/
-                pBiquadState->pDelays[jj] = (*pDataIn); /* Update x(n-1)*/
-                pDataIn++;
-                /**************************************************************************
-                                WRITING THE OUTPUT
-                ***************************************************************************/
-                *pDataOut = (LVM_FLOAT)yn; /* Write jj Channel output */
-                pDataOut++;
-            }
-        }
-
-    }
-#endif /*SUPPORT_MC*/
-
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D32F32Cll_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/BQ_2I_D32F32Cll_TRC_WRA_01_Init.cpp
deleted file mode 100644
index 492a9e0..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D32F32Cll_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*-------------------------------------------------------------------------*/
-#include "BIQUAD.h"
-#include "BQ_2I_D32F32Cll_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   BQ_2I_D32F32Cll_TRC_WRA_01_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void BQ_2I_D32F32Cll_TRC_WRA_01_Init (   Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_2I_Order2_FLOAT_Taps_t   *pTaps,
-                                         BQ_FLOAT_Coefs_t            *pCoef)
-{
-    LVM_FLOAT temp;
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-    pBiquadState->pDelays      = (LVM_FLOAT *) pTaps;
-    temp = pCoef->A2;
-    pBiquadState->coefs[0] = temp;
-    temp = pCoef->A1;
-    pBiquadState->coefs[1] = temp;
-    temp = pCoef->A0;
-    pBiquadState->coefs[2] = temp;
-    temp = pCoef->B2;
-    pBiquadState->coefs[3] = temp;
-    temp = pCoef->B1;
-    pBiquadState->coefs[4] = temp;
-}
-/*-------------------------------------------------------------------------*/
-/* End Of File: BQ_2I_D32F32C32_TRC_WRA_01_Init.c                              */
-
diff --git a/media/libeffects/lvm/lib/Common/src/BQ_2I_D32F32Cll_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/BQ_2I_D32F32Cll_TRC_WRA_01_Private.h
deleted file mode 100644
index 7eb6474..0000000
--- a/media/libeffects/lvm/lib/Common/src/BQ_2I_D32F32Cll_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _BQ_2I_D32F32CLL_TRC_WRA_01_PRIVATE_H_
-#define _BQ_2I_D32F32CLL_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *                          pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT32                            coefs[5];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-typedef struct _Filter_State_FLOAT
-{
-    LVM_FLOAT *                          pDelays;        /* pointer to the delayed samples \
-                                                            (data of 32 bits)   */
-    LVM_FLOAT                            coefs[5];       /* pointer to the filter coefficients */
-}Filter_State_FLOAT;
-typedef Filter_State_FLOAT * PFilter_State_FLOAT ;
-
-#endif /* _BQ_2I_D32F32CLL_TRC_WRA_01_PRIVATE_H_*/
diff --git a/media/libeffects/lvm/lib/Common/src/CompLim_private.h b/media/libeffects/lvm/lib/Common/src/CompLim_private.h
index 06a21c3..9c7a96b 100644
--- a/media/libeffects/lvm/lib/Common/src/CompLim_private.h
+++ b/media/libeffects/lvm/lib/Common/src/CompLim_private.h
@@ -28,17 +28,16 @@
    DEFINITIONS
 ***********************************************************************************/
 
-#define FS_48K      48000
+#define FS_48K 48000
 
-#define INTEGER_16  0xFFFF /*   65535*/
-#define INTEGER_15  0x7FFF /*   32767*/
+#define INTEGER_16 0xFFFF /*   65535*/
+#define INTEGER_15 0x7FFF /*   32767*/
 
-#define GAIN_6DB    1
-#define GAIN_12DB   2
-#define GAIN_18DB   3
-#define GAIN_24DB   4
+#define GAIN_6DB 1
+#define GAIN_12DB 2
+#define GAIN_18DB 3
+#define GAIN_24DB 4
 
 #endif /* #ifndef _COMP_LIM_PRIVATE_ */
 
 /*** End of file ******************************************************************/
-
diff --git a/media/libeffects/lvm/lib/Common/src/Copy_16.cpp b/media/libeffects/lvm/lib/Common/src/Copy_16.cpp
index 3a50554..1fe7470 100644
--- a/media/libeffects/lvm/lib/Common/src/Copy_16.cpp
+++ b/media/libeffects/lvm/lib/Common/src/Copy_16.cpp
@@ -18,130 +18,65 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
+#include <string.h>
 #include "VectorArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION COPY_16
-***********************************************************************************/
-
-void Copy_16( const LVM_INT16 *src,
-                    LVM_INT16 *dst,
-                    LVM_INT16  n )
-{
-    LVM_INT16 ii;
-
-    if (src > dst)
-    {
-        for (ii = n; ii != 0; ii--)
-        {
-            *dst = *src;
-            dst++;
-            src++;
-        }
-    }
-    else
-    {
-        src += n - 1;
-        dst += n - 1;
-        for (ii = n; ii != 0; ii--)
-        {
-            *dst = *src;
-            dst--;
-            src--;
-        }
-    }
-
+void Copy_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n) {
+    memmove(dst, src, n * sizeof(LVM_FLOAT));
     return;
 }
-void Copy_Float( const LVM_FLOAT *src,
-                 LVM_FLOAT *dst,
-                 LVM_INT16  n )
-{
-    LVM_INT16 ii;
-
-    if (src > dst)
-    {
-        for (ii = n; ii != 0; ii--)
-        {
-            *dst = *src;
-            dst++;
-            src++;
-        }
-    }
-    else
-    {
-        src += n - 1;
-        dst += n - 1;
-        for (ii = n; ii != 0; ii--)
-        {
-            *dst = *src;
-            dst--;
-            src--;
-        }
-    }
-
-    return;
-}
-#ifdef SUPPORT_MC
 // Extract out the stereo channel pair from multichannel source.
-void Copy_Float_Mc_Stereo(const LVM_FLOAT *src,
-                 LVM_FLOAT *dst,
-                 LVM_INT16 NrFrames, /* Number of frames */
-                 LVM_INT32 NrChannels)
-{
+void Copy_Float_Mc_Stereo(const LVM_FLOAT* src, LVM_FLOAT* dst,
+                          LVM_INT16 NrFrames, /* Number of frames */
+                          LVM_INT32 NrChannels) {
     LVM_INT16 ii;
 
-    if (NrChannels >= 2)
-    {
-        for (ii = NrFrames; ii != 0; ii--)
-        {
+    if (NrChannels >= 2) {
+        for (ii = NrFrames; ii != 0; ii--) {
             dst[0] = src[0];
             dst[1] = src[1];
             dst += 2;
             src += NrChannels;
         }
-    }
-    else if (NrChannels == 1)
-    {   // not expected to occur, provided for completeness.
+    } else if (NrChannels == 1) {  // not expected to occur, provided for completeness.
         src += (NrFrames - 1);
         dst += 2 * (NrFrames - 1);
-        for (ii = NrFrames; ii != 0; ii--)
-        {
+        for (ii = NrFrames; ii != 0; ii--) {
             dst[0] = src[0];
             dst[1] = src[0];
             dst -= 2;
-            src --;
+            src--;
         }
     }
 }
 
 // Merge a multichannel source with stereo contained in StereoOut, to dst.
-void Copy_Float_Stereo_Mc(const LVM_FLOAT *src,
-                 LVM_FLOAT *StereoOut,
-                 LVM_FLOAT *dst,
-                 LVM_INT16 NrFrames, /* Number of frames*/
-                 LVM_INT32 NrChannels)
-{
+void Copy_Float_Stereo_Mc(const LVM_FLOAT* src, const LVM_FLOAT* StereoOut, LVM_FLOAT* dst,
+                          LVM_INT16 NrFrames, /* Number of frames*/
+                          LVM_INT32 NrChannels) {
     LVM_INT16 ii, jj;
 
-    // pack dst with stereo information of StereoOut
-    // together with the upper channels of src.
-    StereoOut += 2 * (NrFrames - 1);
-    dst += NrChannels * (NrFrames - 1);
-    src += NrChannels * (NrFrames - 1);
-    for (ii = NrFrames; ii != 0; ii--)
-    {
-        dst[1] = StereoOut[1];
-        dst[0] = StereoOut[0]; // copy 1 before 0 is required for NrChannels == 3.
-        for (jj = 2; jj < NrChannels; jj++)
-        {
-            dst[jj] = src[jj];
+    if (NrChannels >= FCC_2) {
+        // pack dst with stereo information of StereoOut
+        // together with the upper channels of src.
+        StereoOut += 2 * (NrFrames - 1);
+        dst += NrChannels * (NrFrames - 1);
+        src += NrChannels * (NrFrames - 1);
+
+        for (ii = NrFrames; ii != 0; ii--) {
+            dst[1] = StereoOut[1];
+            dst[0] = StereoOut[0];  // copy 1 before 0 is required for NrChannels == 3.
+            for (jj = FCC_2; jj < NrChannels; jj++) {
+                dst[jj] = src[jj];
+            }
+            dst -= NrChannels;
+            src -= NrChannels;
+            StereoOut -= 2;
         }
-        dst    -= NrChannels;
-        src    -= NrChannels;
-        StereoOut -= 2;
+    } else {
+        Copy_Float((const LVM_FLOAT*)StereoOut, /* Source */
+                   (LVM_FLOAT*)dst,             /* Destination */
+                   (LVM_INT16)NrFrames);        /* Number of frames */
     }
 }
-#endif
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/Core_MixHard_2St_D32C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/Core_MixHard_2St_D32C31_SAT.cpp
index 5e77335..2c2061a 100644
--- a/media/libeffects/lvm/lib/Common/src/Core_MixHard_2St_D32C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/Core_MixHard_2St_D32C31_SAT.cpp
@@ -25,13 +25,9 @@
 /**********************************************************************************
    FUNCTION CORE_MIXHARD_2ST_D32C31_SAT
 ***********************************************************************************/
-void Core_MixHard_2St_D32C31_SAT(   Mix_2St_Cll_FLOAT_t       *pInstance,
-                                    const LVM_FLOAT     *src1,
-                                    const LVM_FLOAT     *src2,
-                                    LVM_FLOAT     *dst,
-                                    LVM_INT16     n)
-{
-    LVM_FLOAT  Temp1,Temp2,Temp3;
+void Core_MixHard_2St_D32C31_SAT(Mix_2St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src1,
+                                 const LVM_FLOAT* src2, LVM_FLOAT* dst, LVM_INT16 n) {
+    LVM_FLOAT Temp1, Temp2, Temp3;
     LVM_INT16 ii;
     LVM_FLOAT Current1Short;
     LVM_FLOAT Current2Short;
@@ -39,7 +35,7 @@
     Current1Short = (pInstance->Current1);
     Current2Short = (pInstance->Current2);
 
-    for (ii = n; ii != 0; ii--){
+    for (ii = n; ii != 0; ii--) {
         Temp1 = *src1++;
         Temp3 = Temp1 * Current1Short;
         Temp2 = *src2++;
@@ -47,11 +43,11 @@
         Temp2 = (Temp1 / 2.0f) + (Temp3 / 2.0f);
         if (Temp2 > 0.5f)
             Temp2 = 1.0f;
-        else if (Temp2 < -0.5f )
+        else if (Temp2 < -0.5f)
             Temp2 = -1.0f;
         else
             Temp2 = (Temp2 * 2);
-            *dst++ = Temp2;
+        *dst++ = Temp2;
     }
 }
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/Core_MixInSoft_D32C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/Core_MixInSoft_D32C31_SAT.cpp
index 8f5c0ae..b7f4b55 100644
--- a/media/libeffects/lvm/lib/Common/src/Core_MixInSoft_D32C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/Core_MixInSoft_D32C31_SAT.cpp
@@ -18,72 +18,54 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
 #include "Mixer_private.h"
 #include "LVM_Macros.h"
+#include "ScalarArithmetic.h"
 
 /**********************************************************************************
    FUNCTION CORE_MIXSOFT_1ST_D32C31_WRA
 ***********************************************************************************/
 
-void Core_MixInSoft_D32C31_SAT(     Mix_1St_Cll_FLOAT_t       *pInstance,
-                                    const LVM_FLOAT     *src,
-                                          LVM_FLOAT     *dst,
-                                          LVM_INT16     n)
-{
-    LVM_FLOAT    Temp1,Temp2,Temp3;
-    LVM_INT16     OutLoop;
-    LVM_INT16     InLoop;
-    LVM_FLOAT    TargetTimesOneMinAlpha;
-    LVM_FLOAT    CurrentTimesAlpha;
-    LVM_INT16     ii,jj;
+void Core_MixInSoft_D32C31_SAT(Mix_1St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src, LVM_FLOAT* dst,
+                               LVM_INT16 n) {
+    LVM_FLOAT Temp1, Temp2, Temp3;
+    LVM_INT16 OutLoop;
+    LVM_INT16 InLoop;
+    LVM_FLOAT TargetTimesOneMinAlpha;
+    LVM_FLOAT CurrentTimesAlpha;
+    LVM_INT16 ii, jj;
 
     InLoop = (LVM_INT16)(n >> 2); /* Process per 4 samples */
     OutLoop = (LVM_INT16)(n - (InLoop << 2));
 
-    TargetTimesOneMinAlpha = ((1.0f -pInstance->Alpha) * pInstance->Target);
-    if (pInstance->Target >= pInstance->Current){
-        TargetTimesOneMinAlpha +=(LVM_FLOAT)(2.0f / 2147483647.0f); /* Ceil*/
+    TargetTimesOneMinAlpha = ((1.0f - pInstance->Alpha) * pInstance->Target);
+    if (pInstance->Target >= pInstance->Current) {
+        TargetTimesOneMinAlpha += (LVM_FLOAT)(2.0f / 2147483647.0f); /* Ceil*/
     }
 
-    if (OutLoop){
-
+    if (OutLoop) {
         CurrentTimesAlpha = pInstance->Current * pInstance->Alpha;
         pInstance->Current = TargetTimesOneMinAlpha + CurrentTimesAlpha;
 
-        for (ii = OutLoop; ii != 0; ii--){
-        Temp1 = *src++;
-        Temp2 = *dst;
-
-        Temp3 = Temp1 * (pInstance->Current);
-        Temp1 = Temp2 + Temp3;
-
-        if (Temp1 > 1.0f)
-            Temp1 = 1.0f;
-        else if (Temp1 < -1.0f)
-            Temp1 = -1.0f;
-
-        *dst++ = Temp1;
-        }
-    }
-
-    for (ii = InLoop; ii != 0; ii--){
-
-        CurrentTimesAlpha = pInstance->Current * pInstance->Alpha;
-        pInstance->Current = TargetTimesOneMinAlpha + CurrentTimesAlpha;
-
-        for (jj = 4; jj!=0 ; jj--){
+        for (ii = OutLoop; ii != 0; ii--) {
             Temp1 = *src++;
             Temp2 = *dst;
 
             Temp3 = Temp1 * (pInstance->Current);
-            Temp1 = Temp2 + Temp3;
+            *dst++ = LVM_Clamp(Temp2 + Temp3);
+        }
+    }
 
-            if (Temp1 > 1.0f)
-                Temp1 = 1.0f;
-            else if (Temp1 < -1.0f)
-                Temp1 = -1.0f;
-            *dst++ = Temp1;
+    for (ii = InLoop; ii != 0; ii--) {
+        CurrentTimesAlpha = pInstance->Current * pInstance->Alpha;
+        pInstance->Current = TargetTimesOneMinAlpha + CurrentTimesAlpha;
+
+        for (jj = 4; jj != 0; jj--) {
+            Temp1 = *src++;
+            Temp2 = *dst;
+
+            Temp3 = Temp1 * (pInstance->Current);
+            *dst++ = LVM_Clamp(Temp2 + Temp3);
         }
     }
 }
diff --git a/media/libeffects/lvm/lib/Common/src/Core_MixSoft_1St_D32C31_WRA.cpp b/media/libeffects/lvm/lib/Common/src/Core_MixSoft_1St_D32C31_WRA.cpp
index 6ff7853..61a4752 100644
--- a/media/libeffects/lvm/lib/Common/src/Core_MixSoft_1St_D32C31_WRA.cpp
+++ b/media/libeffects/lvm/lib/Common/src/Core_MixSoft_1St_D32C31_WRA.cpp
@@ -25,12 +25,9 @@
 /**********************************************************************************
    FUNCTION CORE_MIXSOFT_1ST_D32C31_WRA
 ***********************************************************************************/
-void Core_MixSoft_1St_D32C31_WRA(   Mix_1St_Cll_FLOAT_t       *pInstance,
-                                    const LVM_FLOAT     *src,
-                                    LVM_FLOAT     *dst,
-                                    LVM_INT16     n)
-{
-    LVM_FLOAT Temp1,Temp2;
+void Core_MixSoft_1St_D32C31_WRA(Mix_1St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src,
+                                 LVM_FLOAT* dst, LVM_INT16 n) {
+    LVM_FLOAT Temp1, Temp2;
     LVM_INT16 OutLoop;
     LVM_INT16 InLoop;
     LVM_FLOAT TargetTimesOneMinAlpha;
@@ -41,19 +38,17 @@
     InLoop = (LVM_INT16)(n >> 2); /* Process per 4 samples */
     OutLoop = (LVM_INT16)(n - (InLoop << 2));
 
-    TargetTimesOneMinAlpha = (1.0f - pInstance->Alpha) * pInstance->Target; /* float * float in float */
-    if (pInstance->Target >= pInstance->Current)
-    {
+    TargetTimesOneMinAlpha =
+            (1.0f - pInstance->Alpha) * pInstance->Target; /* float * float in float */
+    if (pInstance->Target >= pInstance->Current) {
         TargetTimesOneMinAlpha += (LVM_FLOAT)(2.0f / 2147483647.0f); /* Ceil*/
     }
 
-    if (OutLoop != 0)
-    {
+    if (OutLoop != 0) {
         CurrentTimesAlpha = (pInstance->Current * pInstance->Alpha);
         pInstance->Current = TargetTimesOneMinAlpha + CurrentTimesAlpha;
 
-        for (ii = OutLoop; ii != 0; ii--)
-        {
+        for (ii = OutLoop; ii != 0; ii--) {
             Temp1 = *src;
             src++;
 
@@ -63,37 +58,36 @@
         }
     }
 
-    for (ii = InLoop; ii != 0; ii--)
-    {
+    for (ii = InLoop; ii != 0; ii--) {
         CurrentTimesAlpha = pInstance->Current * pInstance->Alpha;
         pInstance->Current = TargetTimesOneMinAlpha + CurrentTimesAlpha;
 
-            Temp1 = *src;
-            src++;
+        Temp1 = *src;
+        src++;
 
-            Temp2 = Temp1 * (pInstance->Current);
-            *dst = Temp2;
-            dst++;
+        Temp2 = Temp1 * (pInstance->Current);
+        *dst = Temp2;
+        dst++;
 
-            Temp1 = *src;
-            src++;
+        Temp1 = *src;
+        src++;
 
-            Temp2 = Temp1 * (pInstance->Current);
-            *dst = Temp2;
-            dst++;
+        Temp2 = Temp1 * (pInstance->Current);
+        *dst = Temp2;
+        dst++;
 
-            Temp1 = *src;
-            src++;
+        Temp1 = *src;
+        src++;
 
-            Temp2 = Temp1 * (pInstance->Current);
-            *dst = Temp2;
-            dst++;
+        Temp2 = Temp1 * (pInstance->Current);
+        *dst = Temp2;
+        dst++;
 
-            Temp1 = *src;
-            src++;
-            Temp2 = Temp1 * (pInstance->Current);
-            *dst = Temp2;
-            dst++;
+        Temp1 = *src;
+        src++;
+        Temp2 = Temp1 * (pInstance->Current);
+        *dst = Temp2;
+        dst++;
     }
 }
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01.cpp
index a7ce4d3..6e859f4 100644
--- a/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01.cpp
+++ b/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01.cpp
@@ -14,54 +14,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 #include "BIQUAD.h"
 #include "DC_2I_D16_TRC_WRA_01_Private.h"
 #include "LVM_Macros.h"
-void DC_2I_D16_TRC_WRA_01( Biquad_FLOAT_Instance_t       *pInstance,
-                           LVM_FLOAT               *pDataIn,
-                           LVM_FLOAT               *pDataOut,
-                           LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT LeftDC,RightDC;
-        LVM_FLOAT Diff;
-        LVM_INT32 j;
-        PFilter_FLOAT_State pBiquadState = (PFilter_FLOAT_State) pInstance;
-
-        LeftDC = pBiquadState->LeftDC;
-        RightDC = pBiquadState->RightDC;
-        for(j = NrSamples-1; j >= 0; j--)
-        {
-            /* Subtract DC and saturate */
-            Diff =* (pDataIn++) - (LeftDC);
-            if (Diff > 1.0f) {
-                Diff = 1.0f; }
-            else if (Diff < -1.0f) {
-                Diff = -1.0f; }
-            *(pDataOut++) = (LVM_FLOAT)Diff;
-            if (Diff < 0) {
-                LeftDC -= DC_FLOAT_STEP; }
-            else {
-                LeftDC += DC_FLOAT_STEP; }
-
-            /* Subtract DC an saturate */
-            Diff =* (pDataIn++) - (RightDC);
-            if (Diff > 1.0f) {
-                Diff = 1.0f; }
-            else if (Diff < -1.0f) {
-                Diff = -1.0f; }
-            *(pDataOut++) = (LVM_FLOAT)Diff;
-            if (Diff < 0) {
-                RightDC -= DC_FLOAT_STEP; }
-            else {
-                RightDC += DC_FLOAT_STEP; }
-
-        }
-        pBiquadState->LeftDC = LeftDC;
-        pBiquadState->RightDC = RightDC;
-
-    }
-#ifdef SUPPORT_MC
+#include "ScalarArithmetic.h"
 /*
  * FUNCTION:       DC_Mc_D16_TRC_WRA_01
  *
@@ -79,37 +35,25 @@
  *  void
  *
  */
-void DC_Mc_D16_TRC_WRA_01(Biquad_FLOAT_Instance_t       *pInstance,
-                          LVM_FLOAT               *pDataIn,
-                          LVM_FLOAT               *pDataOut,
-                          LVM_INT16               NrFrames,
-                          LVM_INT16               NrChannels)
-    {
-        LVM_FLOAT *ChDC;
-        LVM_FLOAT Diff;
-        LVM_INT32 j;
-        LVM_INT32 i;
-        PFilter_FLOAT_State_Mc pBiquadState = (PFilter_FLOAT_State_Mc) pInstance;
+void DC_Mc_D16_TRC_WRA_01(Biquad_FLOAT_Instance_t* pInstance, LVM_FLOAT* pDataIn,
+                          LVM_FLOAT* pDataOut, LVM_INT16 NrFrames, LVM_INT16 NrChannels) {
+    LVM_FLOAT* ChDC;
+    LVM_FLOAT Diff;
+    LVM_INT32 j;
+    LVM_INT32 i;
+    PFilter_FLOAT_State_Mc pBiquadState = (PFilter_FLOAT_State_Mc)pInstance;
 
-        ChDC = &pBiquadState->ChDC[0];
-        for (j = NrFrames - 1; j >= 0; j--)
-        {
-            /* Subtract DC and saturate */
-            for (i = NrChannels - 1; i >= 0; i--)
-            {
-                Diff = *(pDataIn++) - (ChDC[i]);
-                if (Diff > 1.0f) {
-                    Diff = 1.0f;
-                } else if (Diff < -1.0f) {
-                    Diff = -1.0f; }
-                *(pDataOut++) = (LVM_FLOAT)Diff;
-                if (Diff < 0) {
-                    ChDC[i] -= DC_FLOAT_STEP;
-                } else {
-                    ChDC[i] += DC_FLOAT_STEP; }
+    ChDC = &pBiquadState->ChDC[0];
+    for (j = NrFrames - 1; j >= 0; j--) {
+        /* Subtract DC and saturate */
+        for (i = NrChannels - 1; i >= 0; i--) {
+            Diff = *(pDataIn++) - (ChDC[i]);
+            *(pDataOut++) = LVM_Clamp(Diff);
+            if (Diff < 0) {
+                ChDC[i] -= DC_FLOAT_STEP;
+            } else {
+                ChDC[i] += DC_FLOAT_STEP;
             }
-
         }
-
     }
-#endif
+}
diff --git a/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01_Init.cpp
index beee112..c16718c 100644
--- a/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01_Init.cpp
+++ b/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01_Init.cpp
@@ -17,20 +17,10 @@
 
 #include "BIQUAD.h"
 #include "DC_2I_D16_TRC_WRA_01_Private.h"
-void  DC_2I_D16_TRC_WRA_01_Init(Biquad_FLOAT_Instance_t   *pInstance)
-{
-    PFilter_FLOAT_State pBiquadState  = (PFilter_FLOAT_State) pInstance;
-    pBiquadState->LeftDC        = 0.0f;
-    pBiquadState->RightDC       = 0.0f;
-}
-#ifdef SUPPORT_MC
-void  DC_Mc_D16_TRC_WRA_01_Init(Biquad_FLOAT_Instance_t   *pInstance)
-{
-    PFilter_FLOAT_State_Mc pBiquadState  = (PFilter_FLOAT_State_Mc) pInstance;
+void DC_Mc_D16_TRC_WRA_01_Init(Biquad_FLOAT_Instance_t* pInstance) {
+    PFilter_FLOAT_State_Mc pBiquadState = (PFilter_FLOAT_State_Mc)pInstance;
     LVM_INT32 i;
-    for (i = 0; i < LVM_MAX_CHANNELS; i++)
-    {
+    for (i = 0; i < LVM_MAX_CHANNELS; i++) {
         pBiquadState->ChDC[i] = 0.0f;
     }
 }
-#endif
diff --git a/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01_Private.h
index 6508b73..8f459d2 100644
--- a/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01_Private.h
+++ b/media/libeffects/lvm/lib/Common/src/DC_2I_D16_TRC_WRA_01_Private.h
@@ -18,21 +18,17 @@
 #ifndef _DC_2I_D16_TRC_WRA_01_PRIVATE_H_
 #define _DC_2I_D16_TRC_WRA_01_PRIVATE_H_
 
-#define DC_FLOAT_STEP   0.0000002384f;
+#define DC_FLOAT_STEP 0.0000002384f
 
 /* The internal state variables are implemented in a (for the user)  hidden structure */
 /* In this (private) file, the internal structure is declared fro private use.*/
-typedef struct _Filter_FLOAT_State_
-{
-    LVM_FLOAT  LeftDC;     /* LeftDC  */
-    LVM_FLOAT  RightDC;    /* RightDC  */
-}Filter_FLOAT_State;
-typedef Filter_FLOAT_State * PFilter_FLOAT_State ;
-#ifdef SUPPORT_MC
-typedef struct _Filter_FLOAT_State_Mc_
-{
-    LVM_FLOAT  ChDC[LVM_MAX_CHANNELS];     /* ChannelDC  */
+typedef struct _Filter_FLOAT_State_ {
+    LVM_FLOAT LeftDC;  /* LeftDC  */
+    LVM_FLOAT RightDC; /* RightDC  */
+} Filter_FLOAT_State;
+typedef Filter_FLOAT_State* PFilter_FLOAT_State;
+typedef struct _Filter_FLOAT_State_Mc_ {
+    LVM_FLOAT ChDC[LVM_MAX_CHANNELS]; /* ChannelDC  */
 } Filter_FLOAT_State_Mc;
-typedef Filter_FLOAT_State_Mc * PFilter_FLOAT_State_Mc ;
-#endif
+typedef Filter_FLOAT_State_Mc* PFilter_FLOAT_State_Mc;
 #endif /* _DC_2I_D16_TRC_WRA_01_PRIVATE_H_ */
diff --git a/media/libeffects/lvm/lib/Common/src/DelayAllPass_Sat_32x16To32.cpp b/media/libeffects/lvm/lib/Common/src/DelayAllPass_Sat_32x16To32.cpp
deleted file mode 100644
index 771fae2..0000000
--- a/media/libeffects/lvm/lib/Common/src/DelayAllPass_Sat_32x16To32.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "LVM_Types.h"
-#include "LVM_Macros.h"
-#include "VectorArithmetic.h"
-
-/**********************************************************************************
-   FUNCTION DelayAllPass_32x32
-***********************************************************************************/
-
-void DelayAllPass_Sat_32x16To32(  LVM_INT32  *delay,                    /* Delay buffer */
-                                  LVM_UINT16 size,                      /* Delay size */
-                                  LVM_INT16 coeff,                      /* All pass filter coefficient */
-                                  LVM_UINT16 DelayOffset,               /* Simple delay offset */
-                                  LVM_UINT16 *pAllPassOffset,           /* All pass filter delay offset */
-                                  LVM_INT32  *dst,                      /* Source/destination */
-                                  LVM_INT16 n)                          /* Number of  samples */
-{
-    LVM_INT16   i;
-    LVM_UINT16   AllPassOffset = *pAllPassOffset;
-    LVM_INT32    temp;
-    LVM_INT32    a,b,c;
-
-    for (i = 0; i < n; i++)
-    {
-
-        MUL32x16INTO32(delay[AllPassOffset], coeff, temp, 15)
-        a = temp;
-        b = delay[DelayOffset];
-        DelayOffset++;
-
-        c = a + b;
-        if ((((c ^ a) & (c ^ b)) >> 31) != 0)  /* overflow / underflow */
-        {
-            if(a < 0)
-            {
-                c = 0x80000000L;
-            }
-            else
-            {
-                c = 0x7FFFFFFFL;
-            }
-        }
-        *dst = c;
-        dst++;
-
-        MUL32x16INTO32(c, -coeff, temp, 15)
-        a = temp;
-        b = delay[AllPassOffset];
-        c = a + b;
-        if ((((c ^ a) & (c ^ b)) >> 31)!=0)  /* overflow / underflow */
-        {
-            if(a < 0)
-            {
-                c = 0x80000000L;
-            }
-            else
-            {
-                c = 0x7FFFFFFFL;
-            }
-        }
-        delay[AllPassOffset] = c;
-        AllPassOffset++;
-
-        /* Make the delay buffer a circular buffer */
-        if (DelayOffset >= size)
-        {
-            DelayOffset = 0;
-        }
-
-        if (AllPassOffset >= size)
-        {
-            AllPassOffset = 0;
-        }
-    }
-
-    /* Update the offset */
-    *pAllPassOffset = AllPassOffset;
-
-    return;
-}
-
-/**********************************************************************************/
-
diff --git a/media/libeffects/lvm/lib/Common/src/DelayMix_16x16.cpp b/media/libeffects/lvm/lib/Common/src/DelayMix_16x16.cpp
index 52d263f..a346636 100644
--- a/media/libeffects/lvm/lib/Common/src/DelayMix_16x16.cpp
+++ b/media/libeffects/lvm/lib/Common/src/DelayMix_16x16.cpp
@@ -21,45 +21,55 @@
 
 #include "VectorArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION DelayMix_16x16
-***********************************************************************************/
-
-void DelayMix_16x16(const LVM_INT16 *src,           /* Source 1, to be delayed */
-                          LVM_INT16 *delay,         /* Delay buffer */
-                          LVM_INT16 size,           /* Delay size */
-                          LVM_INT16 *dst,           /* Source/destination */
-                          LVM_INT16 *pOffset,       /* Delay offset */
-                          LVM_INT16 n)              /* Number of stereo samples */
+void DelayMix_Float(const LVM_FLOAT* src, /* Source 1, to be delayed */
+                    LVM_FLOAT* delay,     /* Delay buffer */
+                    LVM_INT16 size,       /* Delay size */
+                    LVM_FLOAT* dst,       /* Source/destination */
+                    LVM_INT16* pOffset,   /* Delay offset */
+                    LVM_INT16 n,          /* Number of samples */
+                    LVM_INT32 NrChannels) /* Number of channels */
 {
-    LVM_INT16   i;
-    LVM_INT16   Offset  = *pOffset;
-    LVM_INT16   temp;
+    LVM_INT16 i;
+    LVM_INT16 Offset = *pOffset;
+    LVM_FLOAT temp;
 
-    for (i = 0; i < n; i++)
-    {
-        /* Left channel */
-        temp = (LVM_INT16)((LVM_UINT32)((LVM_INT32)(*dst) + (LVM_INT32)delay[Offset]) >> 1);
-        *dst = temp;
-        dst++;
+    for (i = 0; i < n; i++) {
+        if (NrChannels == FCC_1) {
+            temp = (LVM_FLOAT)(*dst + (LVM_FLOAT)delay[Offset]) / 2.0f;
+            *dst = temp;
+            dst++;
 
-        delay[Offset] = *src;
-        Offset++;
-        src++;
+            delay[Offset] = *src;
+            Offset++;
+            src++;
 
-        /* Right channel */
-        temp = (LVM_INT16)((LVM_UINT32)((LVM_INT32)(*dst) - (LVM_INT32)delay[Offset]) >> 1);
-        *dst = temp;
-        dst++;
+            /* Make the reverb delay buffer a circular buffer */
+            if (Offset >= size) {
+                Offset = 0;
+            }
+        } else {
+            /* Left channel */
+            temp = (LVM_FLOAT)(*dst + (LVM_FLOAT)delay[Offset]) / 2.0f;
+            *dst = temp;
+            dst++;
 
-        delay[Offset] = *src;
-        Offset++;
-        src++;
+            delay[Offset] = *src;
+            Offset++;
+            src++;
 
-        /* Make the reverb delay buffer a circular buffer */
-        if (Offset >= size)
-        {
-            Offset = 0;
+            /* Right channel */
+            temp = (LVM_FLOAT)(*dst - (LVM_FLOAT)delay[Offset]) / 2.0f;
+            *dst = temp;
+            dst++;
+
+            delay[Offset] = *src;
+            Offset++;
+            src++;
+
+            /* Make the reverb delay buffer a circular buffer */
+            if (Offset >= size) {
+                Offset = 0;
+            }
         }
     }
 
@@ -68,47 +78,3 @@
 
     return;
 }
-void DelayMix_Float(const LVM_FLOAT *src,           /* Source 1, to be delayed */
-                          LVM_FLOAT *delay,         /* Delay buffer */
-                          LVM_INT16 size,           /* Delay size */
-                          LVM_FLOAT *dst,           /* Source/destination */
-                          LVM_INT16 *pOffset,       /* Delay offset */
-                          LVM_INT16 n)              /* Number of stereo samples */
-{
-    LVM_INT16   i;
-    LVM_INT16   Offset  = *pOffset;
-    LVM_FLOAT   temp;
-
-    for (i=0; i<n; i++)
-    {
-        /* Left channel */
-        temp            = (LVM_FLOAT)((LVM_FLOAT)(*dst + (LVM_FLOAT)delay[Offset]) / 2.0f);
-        *dst            = temp;
-        dst++;
-
-        delay[Offset] = *src;
-        Offset++;
-        src++;
-
-        /* Right channel */
-        temp            = (LVM_FLOAT)((LVM_FLOAT)(*dst - (LVM_FLOAT)delay[Offset]) / 2.0f);
-        *dst            = temp;
-        dst++;
-
-        delay[Offset] = *src;
-        Offset++;
-        src++;
-
-        /* Make the reverb delay buffer a circular buffer */
-        if (Offset >= size)
-        {
-            Offset = 0;
-        }
-    }
-
-    /* Update the offset */
-    *pOffset = Offset;
-
-    return;
-}
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/DelayWrite_32.cpp b/media/libeffects/lvm/lib/Common/src/DelayWrite_32.cpp
deleted file mode 100644
index 809cddc..0000000
--- a/media/libeffects/lvm/lib/Common/src/DelayWrite_32.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "VectorArithmetic.h"
-
-/**********************************************************************************
-   FUNCTION DelayMix_16x16
-***********************************************************************************/
-
-void DelayWrite_32(const LVM_INT32  *src,               /* Source 1, to be delayed */
-                         LVM_INT32  *delay,             /* Delay buffer */
-                         LVM_UINT16 size,               /* Delay size */
-                         LVM_UINT16 *pOffset,           /* Delay offset */
-                         LVM_INT16  n)                  /* Number of samples */
-{
-    LVM_INT16   i;
-    LVM_INT16   Offset  = (LVM_INT16)*pOffset;
-
-    for (i=0; i<n; i++)
-    {
-        delay[Offset] = *src;
-        Offset++;
-        src++;
-
-        /* Make the delay buffer a circular buffer */
-        if (Offset >= size)
-        {
-            Offset = 0;
-        }
-    }
-
-    /* Update the offset */
-    *pOffset = (LVM_UINT16)Offset;
-
-    return;
-}
-
-/**********************************************************************************/
-
diff --git a/media/libeffects/lvm/lib/Common/src/FO_1I_D16F16C15_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/FO_1I_D16F16C15_TRC_WRA_01.cpp
deleted file mode 100644
index bef0d62..0000000
--- a/media/libeffects/lvm/lib/Common/src/FO_1I_D16F16C15_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "FO_1I_D16F16Css_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A1,
- pBiquadState->coefs[1] is A0,
- pBiquadState->coefs[2] is -B1, these are in Q15 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is y(n-1)L in Q0 format
-***************************************************************************/
-
-void FO_1I_D16F16C15_TRC_WRA_01( Biquad_FLOAT_Instance_t       *pInstance,
-                                 LVM_FLOAT               *pDataIn,
-                                 LVM_FLOAT               *pDataOut,
-                                 LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT  ynL;
-        LVM_INT16 ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-         for (ii = NrSamples; ii != 0; ii--)
-         {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            // ynL=A1  * x(n-1)L
-            ynL = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[0];
-
-            // ynL+=A0  * x(n)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[1] * (*pDataIn);
-
-            // ynL+=  (-B1  * y(n-1)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[2] * pBiquadState->pDelays[1];
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[1] = ynL; // Update y(n-1)L
-            pBiquadState->pDelays[0] = (*pDataIn++); // Update x(n-1)L
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut++ = (LVM_FLOAT)ynL; // Write Left output
-
-        }
-
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/FO_1I_D16F16Css_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/FO_1I_D16F16Css_TRC_WRA_01_Init.cpp
deleted file mode 100644
index 161225e..0000000
--- a/media/libeffects/lvm/lib/Common/src/FO_1I_D16F16Css_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*-------------------------------------------------------------------------*/
-#include "BIQUAD.h"
-#include "FO_1I_D16F16Css_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   FO_1I_D16F16Css_TRC_WRA_01_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void FO_1I_D16F16Css_TRC_WRA_01_Init(    Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_1I_Order1_FLOAT_Taps_t   *pTaps,
-                                         FO_FLOAT_Coefs_t            *pCoef)
-{
-    LVM_FLOAT temp;
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT)  pInstance;
-    pBiquadState->pDelays      = (LVM_FLOAT *)pTaps;
-    temp = pCoef->A1;
-    pBiquadState->coefs[0] = temp;
-    temp = pCoef->A0;
-    pBiquadState->coefs[1] = temp;
-    temp = pCoef->B1;
-    pBiquadState->coefs[2] = temp;
-}
-/*------------------------------------------------*/
-/* End Of File: FO_1I_D16F16Css_TRC_WRA_01_Init.c */
-
diff --git a/media/libeffects/lvm/lib/Common/src/FO_1I_D16F16Css_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/FO_1I_D16F16Css_TRC_WRA_01_Private.h
deleted file mode 100644
index 34f3df9..0000000
--- a/media/libeffects/lvm/lib/Common/src/FO_1I_D16F16Css_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _FO_1I_D16F16CSS_TRC_WRA_01_PRIVATE_H_
-#define _FO_1I_D16F16CSS_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32*        pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT16         coefs[3];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-typedef struct _Filter_State_FLOAT
-{
-    LVM_FLOAT *                          pDelays;        /* pointer to the delayed samples \
-                                                            (data of 32 bits)   */
-    LVM_FLOAT                            coefs[3];       /* pointer to the filter coefficients */
-}Filter_State_FLOAT;
-
-typedef Filter_State_FLOAT * PFilter_State_FLOAT ;
-#endif /* _FO_1I_D16F16CSS_TRC_WRA_01_PRIVATE_H_ */
diff --git a/media/libeffects/lvm/lib/Common/src/FO_1I_D32F32C31_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/FO_1I_D32F32C31_TRC_WRA_01.cpp
deleted file mode 100644
index e3efad7..0000000
--- a/media/libeffects/lvm/lib/Common/src/FO_1I_D32F32C31_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "FO_1I_D32F32Cll_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A1,
- pBiquadState->coefs[1] is A0,
- pBiquadState->coefs[2] is -B1, these are in Q31 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is y(n-1)L in Q0 format
-***************************************************************************/
-void FO_1I_D32F32C31_TRC_WRA_01( Biquad_FLOAT_Instance_t       *pInstance,
-                                 LVM_FLOAT               *pDataIn,
-                                 LVM_FLOAT               *pDataOut,
-                                 LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT  ynL,templ;
-        LVM_INT16  ii;
-        PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT) pInstance;
-
-        for (ii = NrSamples; ii != 0; ii--)
-        {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            // ynL=A1  * x(n-1)L
-            ynL = pBiquadState->coefs[0] * pBiquadState->pDelays[0];
-
-            // ynL+=A0  * x(n)L
-            templ = pBiquadState->coefs[1] * (*pDataIn);
-            ynL += templ;
-
-            // ynL+=  (-B1  * y(n-1)L
-            templ = pBiquadState->coefs[2] * pBiquadState->pDelays[1];
-            ynL += templ;
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[1] = ynL; // Update y(n-1)L
-            pBiquadState->pDelays[0] = (*pDataIn++); // Update x(n-1)L
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut++ = (LVM_FLOAT)ynL; // Write Left output in Q0
-        }
-
-    }
diff --git a/media/libeffects/lvm/lib/Common/src/FO_1I_D32F32Cll_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/FO_1I_D32F32Cll_TRC_WRA_01_Init.cpp
deleted file mode 100644
index bb5295c..0000000
--- a/media/libeffects/lvm/lib/Common/src/FO_1I_D32F32Cll_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "FO_1I_D32F32Cll_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   FO_1I_D32F32Cll_TRC_WRA_01_Init                                       */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void FO_1I_D32F32Cll_TRC_WRA_01_Init( Biquad_FLOAT_Instance_t         *pInstance,
-                                      Biquad_1I_Order1_FLOAT_Taps_t   *pTaps,
-                                      FO_FLOAT_Coefs_t            *pCoef)
-{
-    LVM_FLOAT temp;
-    PFilter_State_FLOAT pBiquadState = (PFilter_State_FLOAT)  pInstance;
-    pBiquadState->pDelays      = (LVM_FLOAT *)    pTaps;
-
-    temp = pCoef->A1;
-    pBiquadState->coefs[0] = temp;
-    temp = pCoef->A0;
-    pBiquadState->coefs[1] = temp;
-    temp = pCoef->B1;
-    pBiquadState->coefs[2] = temp;
-}
-/*------------------------------------------------*/
-/* End Of File: FO_1I_D32F32Cll_TRC_WRA_01_Init.c */
-
diff --git a/media/libeffects/lvm/lib/Common/src/FO_1I_D32F32Cll_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/FO_1I_D32F32Cll_TRC_WRA_01_Private.h
deleted file mode 100644
index 67d1384..0000000
--- a/media/libeffects/lvm/lib/Common/src/FO_1I_D32F32Cll_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _FO_1I_D32F32CLL_TRC_WRA_01_PRIVATE_H_
-#define _FO_1I_D32F32CLL_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT32         coefs[3];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-typedef struct _Filter_State_FLOAT_
-{
-    LVM_FLOAT *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-    LVM_FLOAT         coefs[3];       /* pointer to the filter coefficients */
-}Filter_State_FLOAT;
-
-typedef Filter_State_FLOAT * PFilter_State_FLOAT ;
-#endif /* _FO_1I_D32F32CLL_TRC_WRA_01_PRIVATE_H_ */
diff --git a/media/libeffects/lvm/lib/Common/src/FO_2I_D16F32C15_LShx_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/FO_2I_D16F32C15_LShx_TRC_WRA_01.cpp
deleted file mode 100644
index 6ca819a..0000000
--- a/media/libeffects/lvm/lib/Common/src/FO_2I_D16F32C15_LShx_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "FO_2I_D16F32Css_LShx_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
-ASSUMPTIONS:
-COEFS-
-pBiquadState->coefs[0] is A1,
-pBiquadState->coefs[1] is A0,
-pBiquadState->coefs[2] is -B1, these are in Q15 format
-pBiquadState->Shift    is Shift value
-DELAYS-
-pBiquadState->pDelays[0] is x(n-1)L in Q15 format
-pBiquadState->pDelays[1] is y(n-1)L in Q30 format
-pBiquadState->pDelays[2] is x(n-1)R in Q15 format
-pBiquadState->pDelays[3] is y(n-1)R in Q30 format
-***************************************************************************/
-void FO_2I_D16F32C15_LShx_TRC_WRA_01(Biquad_FLOAT_Instance_t       *pInstance,
-                                     LVM_FLOAT               *pDataIn,
-                                     LVM_FLOAT               *pDataOut,
-                                     LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT   ynL,ynR;
-        LVM_FLOAT   Temp;
-        LVM_FLOAT   NegSatValue;
-        LVM_INT16   ii;
-
-        PFilter_Float_State pBiquadState = (PFilter_Float_State) pInstance;
-
-        NegSatValue = -1.0f;
-
-        for (ii = NrSamples; ii != 0; ii--)
-        {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-
-            // ynL =A1  * x(n-1)L
-            ynL = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[0];
-            // ynR =A1  * x(n-1)R
-            ynR = (LVM_FLOAT)pBiquadState->coefs[0] * pBiquadState->pDelays[2];
-
-            // ynL+=A0  * x(n)L
-            ynL += (LVM_FLOAT)pBiquadState->coefs[1] * (*pDataIn);
-            // ynR+=A0  * x(n)L
-            ynR += (LVM_FLOAT)pBiquadState->coefs[1] * (*(pDataIn+1));
-
-            // ynL +=  (-B1  * y(n-1)L  )
-            Temp = pBiquadState->pDelays[1] * pBiquadState->coefs[2];
-            ynL += Temp;
-            // ynR +=  (-B1  * y(n-1)R ) )
-            Temp = pBiquadState->pDelays[3] * pBiquadState->coefs[2];
-            ynR += Temp;
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[1] = ynL; // Update y(n-1)L
-            pBiquadState->pDelays[0] = (*pDataIn++); // Update x(n-1)L
-
-            pBiquadState->pDelays[3] = ynR; // Update y(n-1)R
-            pBiquadState->pDelays[2] = (*pDataIn++); // Update x(n-1)R
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-
-            /*Saturate results*/
-            if(ynL > 1.0f)
-            {
-                ynL = 1.0f;
-            }
-            else
-            {
-                if(ynL < NegSatValue)
-                {
-                    ynL = NegSatValue;
-                }
-            }
-
-            if(ynR > 1.0f)
-            {
-                ynR = 1.0f;
-            }
-            else
-            {
-                if(ynR < NegSatValue)
-                {
-                    ynR = NegSatValue;
-                }
-            }
-
-            *pDataOut++ = (LVM_FLOAT)ynL;
-            *pDataOut++ = (LVM_FLOAT)ynR;
-        }
-
-    }
-#ifdef SUPPORT_MC
-/**************************************************************************
-ASSUMPTIONS:
-COEFS-
-pBiquadState->coefs[0] is A1,
-pBiquadState->coefs[1] is A0,
-pBiquadState->coefs[2] is -B1,
-DELAYS-
-pBiquadState->pDelays[2*ch + 0] is x(n-1) of the 'ch' - channel
-pBiquadState->pDelays[2*ch + 1] is y(n-1) of the 'ch' - channel
-The index 'ch' runs from 0 to (NrChannels - 1)
-
-PARAMETERS:
- pInstance        Pointer Instance
- pDataIn          Input/Source
- pDataOut         Output/Destination
- NrFrames         Number of frames
- NrChannels       Number of channels
-
-RETURNS:
- void
-***************************************************************************/
-void FO_Mc_D16F32C15_LShx_TRC_WRA_01(Biquad_FLOAT_Instance_t *pInstance,
-                                     LVM_FLOAT               *pDataIn,
-                                     LVM_FLOAT               *pDataOut,
-                                     LVM_INT16               NrFrames,
-                                     LVM_INT16               NrChannels)
-    {
-        LVM_FLOAT   yn;
-        LVM_FLOAT   Temp;
-        LVM_INT16   ii;
-        LVM_INT16   ch;
-        PFilter_Float_State pBiquadState = (PFilter_Float_State) pInstance;
-
-        LVM_FLOAT   *pDelays = pBiquadState->pDelays;
-        LVM_FLOAT   *pCoefs  = &pBiquadState->coefs[0];
-        LVM_FLOAT   A0 = pCoefs[1];
-        LVM_FLOAT   A1 = pCoefs[0];
-        LVM_FLOAT   B1 = pCoefs[2];
-
-        for (ii = NrFrames; ii != 0; ii--)
-        {
-
-            /**************************************************************************
-                            PROCESSING OF THE CHANNELS
-            ***************************************************************************/
-            for (ch = 0; ch < NrChannels; ch++)
-            {
-                // yn =A1  * x(n-1)
-                yn = (LVM_FLOAT)A1 * pDelays[0];
-
-                // yn+=A0  * x(n)
-                yn += (LVM_FLOAT)A0 * (*pDataIn);
-
-                // yn +=  (-B1  * y(n-1))
-                Temp = B1 * pDelays[1];
-                yn += Temp;
-
-                /**************************************************************************
-                                UPDATING THE DELAYS
-                ***************************************************************************/
-                pDelays[1] = yn; // Update y(n-1)
-                pDelays[0] = (*pDataIn++); // Update x(n-1)
-
-                /**************************************************************************
-                                WRITING THE OUTPUT
-                ***************************************************************************/
-
-                /*Saturate results*/
-                if (yn > 1.0f)
-                {
-                    yn = 1.0f;
-                } else if (yn < -1.0f) {
-                    yn = -1.0f;
-                }
-
-                *pDataOut++ = (LVM_FLOAT)yn;
-                pDelays += 2;
-            }
-            pDelays -= NrChannels * 2;
-        }
-    }
-#endif
diff --git a/media/libeffects/lvm/lib/Common/src/FO_2I_D16F32Css_LShx_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/FO_2I_D16F32Css_LShx_TRC_WRA_01_Init.cpp
deleted file mode 100644
index b81b976..0000000
--- a/media/libeffects/lvm/lib/Common/src/FO_2I_D16F32Css_LShx_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*-------------------------------------------------------------------------*/
-#include "BIQUAD.h"
-#include "FO_2I_D16F32Css_LShx_TRC_WRA_01_Private.h"
-
-/*-------------------------------------------------------------------------*/
-/* FUNCTION:                                                               */
-/*   FO_2I_D16F32Css_LShx_TRC_WRA_01_Init                                  */
-/*                                                                         */
-/* DESCRIPTION:                                                            */
-/*   These functions initializes a BIQUAD filter defined as a cascade of   */
-/*   biquadratic Filter Sections.                                          */
-/*                                                                         */
-/* PARAMETERS:                                                             */
-/*   pInstance    - output, returns the pointer to the State Variable      */
-/*                   This state pointer must be passed to any subsequent   */
-/*                   call to "Biquad" functions.                           */
-/*   pTaps         - input, pointer to the taps memory                     */
-/*   pCoef         - input, pointer to the coefficient structure           */
-/*   N             - M coefficient factor of QM.N                          */
-/* RETURNS:                                                                */
-/*   void return code                                                      */
-/*-------------------------------------------------------------------------*/
-void FO_2I_D16F32Css_LShx_TRC_WRA_01_Init(Biquad_FLOAT_Instance_t         *pInstance,
-                                          Biquad_2I_Order1_FLOAT_Taps_t   *pTaps,
-                                          FO_FLOAT_LShx_Coefs_t        *pCoef)
-{
-    LVM_FLOAT temp;
-    PFilter_Float_State pBiquadState = (PFilter_Float_State) pInstance;
-    pBiquadState->pDelays      = (LVM_FLOAT *) pTaps            ;
-
-    temp = pCoef->A1;
-    pBiquadState->coefs[0] = temp;
-    temp = pCoef->A0;
-    pBiquadState->coefs[1] = temp;
-    temp = pCoef->B1;
-    pBiquadState->coefs[2] = temp;
-}
-/*-------------------------------------------------------------------------*/
-/* End Of File: FO_2I_D16F32Css_LShx_TRC_WRA_01_Init.c                     */
-
diff --git a/media/libeffects/lvm/lib/Common/src/FO_2I_D16F32Css_LShx_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/FO_2I_D16F32Css_LShx_TRC_WRA_01_Private.h
deleted file mode 100644
index 5022500..0000000
--- a/media/libeffects/lvm/lib/Common/src/FO_2I_D16F32Css_LShx_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _FO_2I_D16F32CSS_LSHX_TRC_WRA_01_PRIVATE_H_
-#define _FO_2I_D16F32CSS_LSHX_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-    LVM_FLOAT     *pDelays;       /* pointer to the delayed samples (data of 32 bits)   */
-    LVM_FLOAT     coefs[3];       /* pointer to the filter coefficients */
-}Filter_Float_State;
-
-typedef Filter_Float_State * PFilter_Float_State ;
-#endif /* _FO_2I_D16F32CSS_LSHX_TRC_WRA_01_PRIVATE_H_ */
diff --git a/media/libeffects/lvm/lib/Common/src/Filters.h b/media/libeffects/lvm/lib/Common/src/Filters.h
index b5db8f4..8eb3e76 100644
--- a/media/libeffects/lvm/lib/Common/src/Filters.h
+++ b/media/libeffects/lvm/lib/Common/src/Filters.h
@@ -30,26 +30,23 @@
  * Biquad with coefficients A0, A1, A2, B1 and B2 coefficients
  */
 /* Single precision (16-bit) Biquad section coefficients */
-typedef struct
-{
-    LVM_FLOAT   A0;
-    LVM_FLOAT   A1;
-    LVM_FLOAT   A2;
-    LVM_FLOAT   B1;
-    LVM_FLOAT   B2;
-    LVM_UINT16  Scale;
+typedef struct {
+    LVM_FLOAT A0;
+    LVM_FLOAT A1;
+    LVM_FLOAT A2;
+    LVM_FLOAT B1;
+    LVM_FLOAT B2;
+    LVM_UINT16 Scale;
 } BiquadA012B12CoefsSP_t;
 /*
  * Biquad with coefficients A0, A1 and B1 coefficients
  */
 /* Single precision (16-bit) Biquad section coefficients */
-typedef struct
-{
-    LVM_FLOAT   A0;
-    LVM_FLOAT   A1;
-    LVM_FLOAT   B1;
-    LVM_UINT16  Scale;
+typedef struct {
+    LVM_FLOAT A0;
+    LVM_FLOAT A1;
+    LVM_FLOAT B1;
+    LVM_UINT16 Scale;
 } BiquadA01B1CoefsSP_t;
 
-#endif      /* FILTERS_H */
-
+#endif /* FILTERS_H */
diff --git a/media/libeffects/lvm/lib/Common/src/From2iToMS_16x16.cpp b/media/libeffects/lvm/lib/Common/src/From2iToMS_16x16.cpp
index c3f6648..e2f8c67 100644
--- a/media/libeffects/lvm/lib/Common/src/From2iToMS_16x16.cpp
+++ b/media/libeffects/lvm/lib/Common/src/From2iToMS_16x16.cpp
@@ -21,47 +21,10 @@
 
 #include "VectorArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION  From2iToMS_16x16
-***********************************************************************************/
-
-void From2iToMS_16x16( const LVM_INT16  *src,
-                             LVM_INT16  *dstM,
-                             LVM_INT16  *dstS,
-                             LVM_INT16  n )
-{
-    LVM_INT32 temp1,left,right;
+void From2iToMS_Float(const LVM_FLOAT* src, LVM_FLOAT* dstM, LVM_FLOAT* dstS, LVM_INT16 n) {
+    LVM_FLOAT temp1, left, right;
     LVM_INT16 ii;
-    for (ii = n; ii != 0; ii--)
-    {
-        left = (LVM_INT32)*src;
-        src++;
-
-        right = (LVM_INT32)*src;
-        src++;
-
-        /* Compute M signal*/
-        temp1 =  (left+right)>>1;
-        *dstM = (LVM_INT16)temp1;
-        dstM++;
-
-        /* Compute S signal*/
-        temp1 =  (left-right)>>1;
-        *dstS = (LVM_INT16)temp1;
-        dstS++;
-    }
-
-    return;
-}
-void From2iToMS_Float( const LVM_FLOAT  *src,
-                             LVM_FLOAT  *dstM,
-                             LVM_FLOAT  *dstS,
-                             LVM_INT16  n )
-{
-    LVM_FLOAT temp1,left,right;
-    LVM_INT16 ii;
-    for (ii = n; ii != 0; ii--)
-    {
+    for (ii = n; ii != 0; ii--) {
         left = (LVM_FLOAT)*src;
         src++;
 
@@ -69,16 +32,15 @@
         src++;
 
         /* Compute M signal*/
-        temp1 =  (left + right) / 2.0f;
+        temp1 = (left + right) / 2.0f;
         *dstM = (LVM_FLOAT)temp1;
         dstM++;
 
         /* Compute S signal*/
-        temp1 =  (left - right) / 2.0f;
+        temp1 = (left - right) / 2.0f;
         *dstS = (LVM_FLOAT)temp1;
         dstS++;
     }
 
     return;
 }
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/From2iToMono_16.cpp b/media/libeffects/lvm/lib/Common/src/From2iToMono_16.cpp
deleted file mode 100644
index b758ee7..0000000
--- a/media/libeffects/lvm/lib/Common/src/From2iToMono_16.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "VectorArithmetic.h"
-
-/**********************************************************************************
-   FUNCTION From2iToMono_16
-***********************************************************************************/
-
-void From2iToMono_16( const LVM_INT16 *src,
-                            LVM_INT16 *dst,
-                            LVM_INT16 n)
-{
-    LVM_INT16 ii;
-    LVM_INT32 Temp;
-    for (ii = n; ii != 0; ii--)
-    {
-        Temp = (LVM_INT32)*src;
-        src++;
-
-        Temp += (LVM_INT32)*src;
-        src++;
-
-        *dst  = (LVM_INT16)(Temp >>1);
-        dst++;
-    }
-
-    return;
-}
-
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/From2iToMono_32.cpp b/media/libeffects/lvm/lib/Common/src/From2iToMono_32.cpp
index a8688b4..039ee14 100644
--- a/media/libeffects/lvm/lib/Common/src/From2iToMono_32.cpp
+++ b/media/libeffects/lvm/lib/Common/src/From2iToMono_32.cpp
@@ -21,40 +21,11 @@
 
 #include "VectorArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION From2iToMono_32
-***********************************************************************************/
-
-void From2iToMono_32( const LVM_INT32 *src,
-                            LVM_INT32 *dst,
-                            LVM_INT16 n)
-{
-    LVM_INT16 ii;
-    LVM_INT32 Temp;
-
-    for (ii = n; ii != 0; ii--)
-    {
-        Temp = (*src>>1);
-        src++;
-
-        Temp +=(*src>>1);
-        src++;
-
-        *dst = Temp;
-        dst++;
-    }
-
-    return;
-}
-void From2iToMono_Float( const LVM_FLOAT *src,
-                         LVM_FLOAT *dst,
-                         LVM_INT16 n)
-{
+void From2iToMono_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n) {
     LVM_INT16 ii;
     LVM_FLOAT Temp;
 
-    for (ii = n; ii != 0; ii--)
-    {
+    for (ii = n; ii != 0; ii--) {
         Temp = (*src);
         src++;
 
@@ -67,7 +38,6 @@
 
     return;
 }
-#ifdef SUPPORT_MC
 /*
  * FUNCTION:       FromMcToMono_Float
  *
@@ -85,19 +55,14 @@
  *  void
  *
  */
-void FromMcToMono_Float(const LVM_FLOAT *src,
-                        LVM_FLOAT *dst,
-                        LVM_INT16 NrFrames,
-                        LVM_INT16 NrChannels)
-{
+void FromMcToMono_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 NrFrames,
+                        LVM_INT16 NrChannels) {
     LVM_INT16 ii, jj;
     LVM_FLOAT Temp;
 
-    for (ii = NrFrames; ii != 0; ii--)
-    {
+    for (ii = NrFrames; ii != 0; ii--) {
         Temp = 0.0f;
-        for (jj = NrChannels; jj !=0; jj--)
-        {
+        for (jj = NrChannels; jj != 0; jj--) {
             Temp += (*src);
             src++;
         }
@@ -107,6 +72,3 @@
 
     return;
 }
-#endif
-
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/InstAlloc.cpp b/media/libeffects/lvm/lib/Common/src/InstAlloc.cpp
index a039bf5..2cfe056 100644
--- a/media/libeffects/lvm/lib/Common/src/InstAlloc.cpp
+++ b/media/libeffects/lvm/lib/Common/src/InstAlloc.cpp
@@ -26,9 +26,7 @@
  *  Remarks     :
  ****************************************************************************************/
 
-void    InstAlloc_Init( INST_ALLOC      *pms,
-                        void            *StartAddr )
-{
+void InstAlloc_Init(INST_ALLOC* pms, void* StartAddr) {
     pms->TotalSize = 3;
     pms->pNextMember = (((uintptr_t)StartAddr + 3) & (uintptr_t)~3);
 }
@@ -44,10 +42,8 @@
  *  Remarks     :
  ****************************************************************************************/
 
-void*   InstAlloc_AddMember( INST_ALLOC         *pms,
-                             LVM_UINT32           Size )
-{
-    void *NewMemberAddress; /* Variable to temporarily store the return value */
+void* InstAlloc_AddMember(INST_ALLOC* pms, LVM_UINT32 Size) {
+    void* NewMemberAddress; /* Variable to temporarily store the return value */
     NewMemberAddress = (void*)pms->pNextMember;
 
     Size = ((Size + 3) & (LVM_UINT32)~3); /* Ceil the size to a multiple of four */
@@ -55,7 +51,7 @@
     pms->TotalSize += Size;
     pms->pNextMember += Size;
 
-    return(NewMemberAddress);
+    return (NewMemberAddress);
 }
 
 /****************************************************************************************
@@ -66,21 +62,15 @@
  *  Remarks     :
  ****************************************************************************************/
 
-LVM_UINT32 InstAlloc_GetTotal( INST_ALLOC *pms)
-{
-    if (pms->TotalSize > 3)
-    {
-        return(pms->TotalSize);
-    }
-    else
-    {
-        return 0;           /* No memory added */
+LVM_UINT32 InstAlloc_GetTotal(INST_ALLOC* pms) {
+    if (pms->TotalSize > 3) {
+        return (pms->TotalSize);
+    } else {
+        return 0; /* No memory added */
     }
 }
 
-void    InstAlloc_InitAll( INST_ALLOC                      *pms,
-                           LVM_MemoryTable_st             *pMemoryTable)
-{
+void InstAlloc_InitAll(INST_ALLOC* pms, LVM_MemoryTable_st* pMemoryTable) {
     uintptr_t StartAddr;
 
     StartAddr = (uintptr_t)pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress;
@@ -102,7 +92,6 @@
 
     pms[3].TotalSize = 3;
     pms[3].pNextMember = ((StartAddr + 3) & (uintptr_t)~3);
-
 }
 
 /****************************************************************************************
@@ -114,8 +103,7 @@
  *  Remarks     :
  ****************************************************************************************/
 
-void    InstAlloc_InitAll_NULL( INST_ALLOC  *pms)
-{
+void InstAlloc_InitAll_NULL(INST_ALLOC* pms) {
     pms[0].TotalSize = 3;
     pms[0].pNextMember = 0;
 
@@ -127,47 +115,46 @@
 
     pms[3].TotalSize = 3;
     pms[3].pNextMember = 0;
-
 }
 
-void*   InstAlloc_AddMemberAll( INST_ALLOC                     *pms,
-                                 LVM_UINT32                   Size[],
-                                 LVM_MemoryTable_st           *pMemoryTable)
-{
-    void *NewMemberAddress; /* Variable to temporarily store the return value */
+void* InstAlloc_AddMemberAll(INST_ALLOC* pms, LVM_UINT32 Size[], LVM_MemoryTable_st* pMemoryTable) {
+    void* NewMemberAddress; /* Variable to temporarily store the return value */
 
     /* coverity[returned_pointer] Ignore coverity warning that ptr is not used */
-    NewMemberAddress = InstAlloc_AddMember(&pms[LVM_PERSISTENT_SLOW_DATA], Size[LVM_PERSISTENT_SLOW_DATA]);
+    NewMemberAddress =
+            InstAlloc_AddMember(&pms[LVM_PERSISTENT_SLOW_DATA], Size[LVM_PERSISTENT_SLOW_DATA]);
 
-    pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Size         = InstAlloc_GetTotal(&pms[LVM_PERSISTENT_SLOW_DATA]);
-    pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Type         = LVM_PERSISTENT_SLOW_DATA;
+    pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Size =
+            InstAlloc_GetTotal(&pms[LVM_PERSISTENT_SLOW_DATA]);
+    pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Type = LVM_PERSISTENT_SLOW_DATA;
     pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress = LVM_NULL;
 
-    NewMemberAddress = InstAlloc_AddMember(&pms[LVM_PERSISTENT_FAST_DATA], Size[LVM_PERSISTENT_FAST_DATA]);
+    NewMemberAddress =
+            InstAlloc_AddMember(&pms[LVM_PERSISTENT_FAST_DATA], Size[LVM_PERSISTENT_FAST_DATA]);
 
-    pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Size         = InstAlloc_GetTotal(&pms[LVM_PERSISTENT_FAST_DATA]);
-    pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Type         = LVM_PERSISTENT_FAST_DATA;
+    pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Size =
+            InstAlloc_GetTotal(&pms[LVM_PERSISTENT_FAST_DATA]);
+    pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Type = LVM_PERSISTENT_FAST_DATA;
     pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress = LVM_NULL;
 
-    NewMemberAddress = InstAlloc_AddMember(&pms[LVM_PERSISTENT_FAST_COEF], Size[LVM_PERSISTENT_FAST_COEF]);
+    NewMemberAddress =
+            InstAlloc_AddMember(&pms[LVM_PERSISTENT_FAST_COEF], Size[LVM_PERSISTENT_FAST_COEF]);
 
-    pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Size         = InstAlloc_GetTotal(&pms[LVM_PERSISTENT_FAST_COEF]);
-    pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Type         = LVM_PERSISTENT_FAST_COEF;
+    pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Size =
+            InstAlloc_GetTotal(&pms[LVM_PERSISTENT_FAST_COEF]);
+    pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Type = LVM_PERSISTENT_FAST_COEF;
     pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress = LVM_NULL;
 
     NewMemberAddress = InstAlloc_AddMember(&pms[LVM_TEMPORARY_FAST], Size[LVM_TEMPORARY_FAST]);
 
-    pMemoryTable->Region[LVM_TEMPORARY_FAST].Size                 = InstAlloc_GetTotal(&pms[LVM_TEMPORARY_FAST]);
-    pMemoryTable->Region[LVM_TEMPORARY_FAST].Type                 = LVM_TEMPORARY_FAST;
-    pMemoryTable->Region[LVM_TEMPORARY_FAST].pBaseAddress         = LVM_NULL;
+    pMemoryTable->Region[LVM_TEMPORARY_FAST].Size = InstAlloc_GetTotal(&pms[LVM_TEMPORARY_FAST]);
+    pMemoryTable->Region[LVM_TEMPORARY_FAST].Type = LVM_TEMPORARY_FAST;
+    pMemoryTable->Region[LVM_TEMPORARY_FAST].pBaseAddress = LVM_NULL;
 
-    return(NewMemberAddress);
+    return (NewMemberAddress);
 }
 
-void*   InstAlloc_AddMemberAllRet(     INST_ALLOC                 *pms,
-                                     LVM_UINT32               Size[],
-                                     void                    **ptr)
-{
+void* InstAlloc_AddMemberAllRet(INST_ALLOC* pms, LVM_UINT32 Size[], void** ptr) {
     ptr[0] = InstAlloc_AddMember(&pms[LVM_PERSISTENT_SLOW_DATA], Size[LVM_PERSISTENT_SLOW_DATA]);
     ptr[1] = InstAlloc_AddMember(&pms[LVM_PERSISTENT_FAST_DATA], Size[LVM_PERSISTENT_FAST_DATA]);
     ptr[2] = InstAlloc_AddMember(&pms[LVM_PERSISTENT_FAST_COEF], Size[LVM_PERSISTENT_FAST_COEF]);
diff --git a/media/libeffects/lvm/lib/Common/src/Int16LShiftToInt32_16x32.cpp b/media/libeffects/lvm/lib/Common/src/Int16LShiftToInt32_16x32.cpp
deleted file mode 100644
index 9f09e4d..0000000
--- a/media/libeffects/lvm/lib/Common/src/Int16LShiftToInt32_16x32.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "VectorArithmetic.h"
-
-/**********************************************************************************
-   FUNCTION INT16LSHIFTTOINT32_16X32
-***********************************************************************************/
-
-void Int16LShiftToInt32_16x32(const LVM_INT16   *src,
-                              LVM_INT32         *dst,
-                              LVM_INT16         n,
-                              LVM_INT16         shift )
-{
-    LVM_INT16 ii;
-
-    src += n-1;
-    dst += n-1;
-
-    for (ii = n; ii != 0; ii--)
-    {
-        *dst = ( ((LVM_INT32)*src) << shift);
-        src--;
-        dst--;
-    }
-
-    return;
-}
-
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/Int32RShiftToInt16_Sat_32x16.cpp b/media/libeffects/lvm/lib/Common/src/Int32RShiftToInt16_Sat_32x16.cpp
deleted file mode 100644
index 8c9980d..0000000
--- a/media/libeffects/lvm/lib/Common/src/Int32RShiftToInt16_Sat_32x16.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "VectorArithmetic.h"
-
-/**********************************************************************************
-   FUNCTION INT32RSHIFTTOINT16_SAT_32X16
-***********************************************************************************/
-
-void Int32RShiftToInt16_Sat_32x16(const LVM_INT32  *src,
-                                  LVM_INT16 *dst,
-                                  LVM_INT16 n,
-                                  LVM_INT16 shift )
-{
-    LVM_INT32 temp;
-    LVM_INT16 ii;
-
-    for (ii = n; ii != 0; ii--)
-    {
-        temp = *src >> shift;
-        src++;
-
-        if (temp > 0x00007FFF)
-        {
-            *dst = 0x7FFF;
-        }
-        else if (temp < -0x00008000)
-        {
-            *dst = - 0x8000;
-        }
-        else
-        {
-            *dst = (LVM_INT16)temp;
-        }
-
-        dst++;
-    }
-
-    return;
-}
-
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/JoinTo2i_32x32.cpp b/media/libeffects/lvm/lib/Common/src/JoinTo2i_32x32.cpp
index 05df656..6c7c8ae 100644
--- a/media/libeffects/lvm/lib/Common/src/JoinTo2i_32x32.cpp
+++ b/media/libeffects/lvm/lib/Common/src/JoinTo2i_32x32.cpp
@@ -21,47 +21,14 @@
 
 #include "VectorArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION JoinTo2i_32x32
-***********************************************************************************/
-
-void JoinTo2i_32x32( const LVM_INT32    *srcL,
-                     const LVM_INT32    *srcR,
-                           LVM_INT32    *dst,
-                           LVM_INT16    n )
-{
-    LVM_INT16 ii;
-
-    srcL += n-1;
-    srcR += n-1;
-    dst  += ((2*n)-1);
-
-    for (ii = n; ii != 0; ii--)
-    {
-        *dst = *srcR;
-        dst--;
-        srcR--;
-
-        *dst = *srcL;
-        dst--;
-        srcL--;
-    }
-
-    return;
-}
-void JoinTo2i_Float( const LVM_FLOAT    *srcL,
-                     const LVM_FLOAT    *srcR,
-                           LVM_FLOAT    *dst,
-                           LVM_INT16    n )
-{
+void JoinTo2i_Float(const LVM_FLOAT* srcL, const LVM_FLOAT* srcR, LVM_FLOAT* dst, LVM_INT16 n) {
     LVM_INT16 ii;
 
     srcL += n - 1;
     srcR += n - 1;
-    dst  += ((2 * n) - 1);
+    dst += ((2 * n) - 1);
 
-    for (ii = n; ii != 0; ii--)
-    {
+    for (ii = n; ii != 0; ii--) {
         *dst = *srcR;
         dst--;
         srcR--;
@@ -74,4 +41,3 @@
     return;
 }
 /**********************************************************************************/
-
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixHard_1St_2i_D16C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixHard_1St_2i_D16C31_SAT.cpp
index 14d61bd..d670b3d 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixHard_1St_2i_D16C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixHard_1St_2i_D16C31_SAT.cpp
@@ -18,67 +18,19 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
 #include "LVC_Mixer_Private.h"
 #include "LVM_Macros.h"
 #include "ScalarArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION LVC_Core_MixHard_1St_2i_D16C31_SAT
-***********************************************************************************/
-void LVC_Core_MixHard_1St_2i_D16C31_SAT( LVMixer3_FLOAT_st        *ptrInstance1,
-                                         LVMixer3_FLOAT_st        *ptrInstance2,
-                                         const LVM_FLOAT    *src,
-                                         LVM_FLOAT          *dst,
-                                         LVM_INT16          n)
-{
-    LVM_FLOAT  Temp;
-    LVM_INT16 ii;
-    Mix_Private_FLOAT_st  *pInstance1 = (Mix_Private_FLOAT_st *)(ptrInstance1->PrivateParams);
-    Mix_Private_FLOAT_st  *pInstance2 = (Mix_Private_FLOAT_st *)(ptrInstance2->PrivateParams);
-    for (ii = n; ii != 0; ii--)
-    {
-        Temp = ((LVM_FLOAT)*(src++) * (LVM_FLOAT)pInstance1->Current);
-        if (Temp > 1.0f)
-            *dst++ = 1.0f;
-        else if (Temp < -1.0f)
-            *dst++ = -1.0f;
-        else
-            *dst++ = (LVM_FLOAT)Temp;
-
-        Temp = ((LVM_FLOAT)*(src++) * (LVM_FLOAT)pInstance2->Current);
-        if (Temp > 1.0f)
-            *dst++ = 1.0f;
-        else if (Temp < -1.0f)
-            *dst++ = -1.0f;
-        else
-            *dst++ = (LVM_FLOAT)Temp;
-    }
-
-}
-#ifdef SUPPORT_MC
-void LVC_Core_MixHard_1St_MC_float_SAT (Mix_Private_FLOAT_st **ptrInstance,
-                                         const LVM_FLOAT      *src,
-                                         LVM_FLOAT            *dst,
-                                         LVM_INT16            NrFrames,
-                                         LVM_INT16            NrChannels)
-{
-    LVM_FLOAT  Temp;
+void LVC_Core_MixHard_1St_MC_float_SAT(Mix_Private_FLOAT_st** ptrInstance, const LVM_FLOAT* src,
+                                       LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels) {
+    LVM_FLOAT Temp;
     LVM_INT16 ii, jj;
-    for (ii = NrFrames; ii != 0; ii--)
-    {
-        for (jj = 0; jj < NrChannels; jj++)
-        {
-            Mix_Private_FLOAT_st  *pInstance1 = (Mix_Private_FLOAT_st *)(ptrInstance[jj]);
-            Temp = ((LVM_FLOAT)*(src++) * (LVM_FLOAT)pInstance1->Current);
-            if (Temp > 1.0f)
-                *dst++ = 1.0f;
-            else if (Temp < -1.0f)
-                *dst++ = -1.0f;
-            else
-                *dst++ = (LVM_FLOAT)Temp;
+    for (ii = NrFrames; ii != 0; ii--) {
+        for (jj = 0; jj < NrChannels; jj++) {
+            Mix_Private_FLOAT_st* pInstance1 = (Mix_Private_FLOAT_st*)(ptrInstance[jj]);
+            Temp =  *src++ * pInstance1->Current;
+            *dst++ = LVM_Clamp(Temp);
         }
     }
 }
-#endif
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixHard_2St_D16C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixHard_2St_D16C31_SAT.cpp
index 841fa1e..417c1f0 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixHard_2St_D16C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixHard_2St_D16C31_SAT.cpp
@@ -18,38 +18,28 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
 #include "LVC_Mixer_Private.h"
+#include "ScalarArithmetic.h"
 
 /**********************************************************************************
    FUNCTION LVCore_MIXHARD_2ST_D16C31_SAT
 ***********************************************************************************/
-void LVC_Core_MixHard_2St_D16C31_SAT( LVMixer3_FLOAT_st *ptrInstance1,
-                                    LVMixer3_FLOAT_st         *ptrInstance2,
-                                    const LVM_FLOAT     *src1,
-                                    const LVM_FLOAT     *src2,
-                                          LVM_FLOAT     *dst,
-                                          LVM_INT16     n)
-{
-    LVM_FLOAT  Temp;
+void LVC_Core_MixHard_2St_D16C31_SAT(LVMixer3_FLOAT_st* ptrInstance1,
+                                     LVMixer3_FLOAT_st* ptrInstance2, const LVM_FLOAT* src1,
+                                     const LVM_FLOAT* src2, LVM_FLOAT* dst, LVM_INT16 n) {
+    LVM_FLOAT Temp;
     LVM_INT16 ii;
     LVM_FLOAT Current1;
     LVM_FLOAT Current2;
-    Mix_Private_FLOAT_st  *pInstance1 = (Mix_Private_FLOAT_st *)(ptrInstance1->PrivateParams);
-    Mix_Private_FLOAT_st  *pInstance2 = (Mix_Private_FLOAT_st *)(ptrInstance2->PrivateParams);
+    Mix_Private_FLOAT_st* pInstance1 = (Mix_Private_FLOAT_st*)(ptrInstance1->PrivateParams);
+    Mix_Private_FLOAT_st* pInstance2 = (Mix_Private_FLOAT_st*)(ptrInstance2->PrivateParams);
 
-    Current1 = (pInstance1->Current);
-    Current2 = (pInstance2->Current);
+    Current1 = pInstance1->Current;
+    Current2 = pInstance2->Current;
 
-    for (ii = n; ii != 0; ii--){
-        Temp = (((LVM_FLOAT)*(src1++) * (LVM_FLOAT)Current1)) +
-               (((LVM_FLOAT)*(src2++) * (LVM_FLOAT)Current2));
-        if (Temp > 1.0f)
-            *dst++ = 1.0f;
-        else if (Temp < -1.0f)
-            *dst++ = -1.0f;
-        else
-            *dst++ = Temp;
+    for (ii = n; ii != 0; ii--) {
+        Temp =  *src1++ * Current1 + *src2++ * Current2;
+        *dst++ = LVM_Clamp(Temp);
     }
 }
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixInSoft_D16C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixInSoft_D16C31_SAT.cpp
index 318138d..d8c25c9 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixInSoft_D16C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixInSoft_D16C31_SAT.cpp
@@ -18,102 +18,72 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
 #include "LVC_Mixer_Private.h"
 #include "LVM_Macros.h"
+#include "ScalarArithmetic.h"
 
 /**********************************************************************************
    FUNCTION LVCore_MIXSOFT_1ST_D16C31_WRA
 ***********************************************************************************/
-void LVC_Core_MixInSoft_D16C31_SAT(LVMixer3_FLOAT_st *ptrInstance,
-                                   const LVM_FLOAT   *src,
-                                         LVM_FLOAT   *dst,
-                                         LVM_INT16   n)
-{
-
-    LVM_INT16   OutLoop;
-    LVM_INT16   InLoop;
-    LVM_INT32   ii,jj;
-    Mix_Private_FLOAT_st  *pInstance = (Mix_Private_FLOAT_st *)(ptrInstance->PrivateParams);
-    LVM_FLOAT   Delta = pInstance->Delta;
-    LVM_FLOAT   Current = pInstance->Current;
-    LVM_FLOAT   Target = pInstance->Target;
-    LVM_FLOAT   Temp;
+void LVC_Core_MixInSoft_D16C31_SAT(LVMixer3_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                   LVM_FLOAT* dst, LVM_INT16 n) {
+    LVM_INT16 OutLoop;
+    LVM_INT16 InLoop;
+    LVM_INT32 ii, jj;
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)(ptrInstance->PrivateParams);
+    LVM_FLOAT Delta = pInstance->Delta;
+    LVM_FLOAT Current = pInstance->Current;
+    LVM_FLOAT Target = pInstance->Target;
+    LVM_FLOAT Temp;
 
     InLoop = (LVM_INT16)(n >> 2); /* Process per 4 samples */
     OutLoop = (LVM_INT16)(n - (InLoop << 2));
 
-    if(Current < Target){
-        if (OutLoop){
+    if (Current < Target) {
+        if (OutLoop) {
             Temp = Current + Delta;
             Current = Temp;
-            if (Current > Target)
-                Current = Target;
+            if (Current > Target) Current = Target;
 
-           for (ii = OutLoop; ii != 0; ii--){
-                Temp = ((LVM_FLOAT)*dst) + (((LVM_FLOAT)*(src++) * Current));
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = (LVM_FLOAT)Temp;
+            for (ii = OutLoop; ii != 0; ii--) {
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
             }
         }
 
-        for (ii = InLoop; ii != 0; ii--){
+        for (ii = InLoop; ii != 0; ii--) {
             Temp = Current + Delta;
             Current = Temp;
-            if (Current > Target)
-                Current = Target;
+            if (Current > Target) Current = Target;
 
-            for (jj = 4; jj != 0 ; jj--){
-                Temp = ((LVM_FLOAT)*dst) + (((LVM_FLOAT)*(src++) * Current));
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = (LVM_FLOAT)Temp;
+            for (jj = 4; jj != 0; jj--) {
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
             }
         }
-    }
-    else{
-        if (OutLoop){
+    } else {
+        if (OutLoop) {
             Current -= Delta;
-            if (Current < Target)
-                Current = Target;
+            if (Current < Target) Current = Target;
 
-            for (ii = OutLoop; ii != 0; ii--){
-                Temp = ((LVM_FLOAT)*dst) + (((LVM_FLOAT)*(src++) * Current));
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = (LVM_FLOAT)Temp;
+            for (ii = OutLoop; ii != 0; ii--) {
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
             }
         }
 
-        for (ii = InLoop; ii != 0; ii--){
+        for (ii = InLoop; ii != 0; ii--) {
             Current -= Delta;
-            if (Current < Target)
-                Current = Target;
+            if (Current < Target) Current = Target;
 
-            for (jj = 4; jj != 0 ; jj--){
-                Temp = ((LVM_FLOAT)*dst) + (((LVM_FLOAT)*(src++) * Current));
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = (LVM_FLOAT)Temp;
+            for (jj = 4; jj != 0; jj--) {
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
             }
         }
     }
     pInstance->Current = Current;
 }
-#ifdef SUPPORT_MC
 /*
  * FUNCTION:       LVC_Core_MixInSoft_Mc_D16C31_SAT
  *
@@ -131,21 +101,16 @@
  *  void
  *
  */
-void LVC_Core_MixInSoft_Mc_D16C31_SAT(LVMixer3_FLOAT_st *ptrInstance,
-                                      const LVM_FLOAT   *src,
-                                            LVM_FLOAT   *dst,
-                                            LVM_INT16   NrFrames,
-                                            LVM_INT16   NrChannels)
-{
-
-    LVM_INT16   OutLoop;
-    LVM_INT16   InLoop;
-    LVM_INT32   ii, jj;
-    Mix_Private_FLOAT_st  *pInstance = (Mix_Private_FLOAT_st *)(ptrInstance->PrivateParams);
-    LVM_FLOAT   Delta = pInstance->Delta;
-    LVM_FLOAT   Current = pInstance->Current;
-    LVM_FLOAT   Target = pInstance->Target;
-    LVM_FLOAT   Temp;
+void LVC_Core_MixInSoft_Mc_D16C31_SAT(LVMixer3_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                      LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels) {
+    LVM_INT16 OutLoop;
+    LVM_INT16 InLoop;
+    LVM_INT32 ii, jj;
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)(ptrInstance->PrivateParams);
+    LVM_FLOAT Delta = pInstance->Delta;
+    LVM_FLOAT Current = pInstance->Current;
+    LVM_FLOAT Target = pInstance->Target;
+    LVM_FLOAT Temp;
 
     /*
      * Same operation is performed on consecutive frames.
@@ -160,90 +125,52 @@
         if (OutLoop) {
             Temp = Current + Delta;
             Current = Temp;
-            if (Current > Target)
-                Current = Target;
+            if (Current > Target) Current = Target;
 
-           for (ii = OutLoop*NrChannels; ii != 0; ii--) {
-                Temp = (*dst) + (*(src++) * Current);
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = Temp;
+            for (ii = OutLoop * NrChannels; ii != 0; ii--) {
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
             }
         }
 
         for (ii = InLoop; ii != 0; ii--) {
             Temp = Current + Delta;
             Current = Temp;
-            if (Current > Target)
-                Current = Target;
+            if (Current > Target) Current = Target;
 
-            for (jj = NrChannels; jj != 0 ; jj--) {
-                Temp = (*dst) + (*(src++) * Current);
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = Temp;
+            for (jj = NrChannels; jj != 0; jj--) {
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
 
-                Temp = (*dst) + (*(src++) * Current);
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = Temp;
-
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
             }
         }
-    }
-    else{
+    } else {
         if (OutLoop) {
             Current -= Delta;
-            if (Current < Target)
-                Current = Target;
+            if (Current < Target) Current = Target;
 
-            for (ii = OutLoop*NrChannels; ii != 0; ii--) {
-                Temp = (*dst) + (*(src++) * Current);
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = Temp;
+            for (ii = OutLoop * NrChannels; ii != 0; ii--) {
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
             }
         }
 
         for (ii = InLoop; ii != 0; ii--) {
             Current -= Delta;
-            if (Current < Target)
-                Current = Target;
+            if (Current < Target) Current = Target;
 
-            for (jj = NrChannels; jj != 0 ; jj--) {
-                Temp = (*dst) + (*(src++) * Current);
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = Temp;
+            for (jj = NrChannels; jj != 0; jj--) {
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
 
-                Temp = (*dst) + (*(src++) * Current);
-                if (Temp > 1.0f)
-                    *dst++ = 1.0f;
-                else if (Temp < -1.0f)
-                    *dst++ = -1.0f;
-                else
-                    *dst++ = Temp;
-
+                Temp = *dst + *src++ * Current;
+                *dst++ = LVM_Clamp(Temp);
             }
         }
     }
     pInstance->Current = Current;
 }
 
-#endif
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixSoft_1St_2i_D16C31_WRA.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixSoft_1St_2i_D16C31_WRA.cpp
index 1f4b08a..0968cf8 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixSoft_1St_2i_D16C31_WRA.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixSoft_1St_2i_D16C31_WRA.cpp
@@ -18,176 +18,38 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
 #include "LVC_Mixer_Private.h"
-#include "ScalarArithmetic.h"
 #include "LVM_Macros.h"
+#include "ScalarArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION LVC_Core_MixSoft_1St_2i_D16C31_WRA
-***********************************************************************************/
-static LVM_FLOAT ADD2_SAT_FLOAT(LVM_FLOAT a,
-                                LVM_FLOAT b,
-                                LVM_FLOAT c)
-{
-    LVM_FLOAT temp;
-    temp = a + b ;
-    if (temp < -1.0f)
-        c = -1.0f;
-    else if (temp > 1.0f)
-        c = 1.0f;
-    else
-        c = temp;
-    return c;
+static inline LVM_FLOAT ADD2_SAT_FLOAT(LVM_FLOAT a, LVM_FLOAT b) {
+    return LVM_Clamp(a + b);
 }
-void LVC_Core_MixSoft_1St_2i_D16C31_WRA( LVMixer3_FLOAT_st        *ptrInstance1,
-                                         LVMixer3_FLOAT_st        *ptrInstance2,
-                                         const LVM_FLOAT    *src,
-                                         LVM_FLOAT          *dst,
-                                         LVM_INT16          n)
-{
-    LVM_INT16   OutLoop;
-    LVM_INT16   InLoop;
-    LVM_INT32   ii;
-    Mix_Private_FLOAT_st  *pInstanceL = (Mix_Private_FLOAT_st *)(ptrInstance1->PrivateParams);
-    Mix_Private_FLOAT_st  *pInstanceR = (Mix_Private_FLOAT_st *)(ptrInstance2->PrivateParams);
-
-    LVM_FLOAT   DeltaL = pInstanceL->Delta;
-    LVM_FLOAT   CurrentL = pInstanceL->Current;
-    LVM_FLOAT   TargetL = pInstanceL->Target;
-
-    LVM_FLOAT   DeltaR = pInstanceR->Delta;
-    LVM_FLOAT   CurrentR = pInstanceR->Current;
-    LVM_FLOAT   TargetR = pInstanceR->Target;
-
-    LVM_FLOAT   Temp = 0;
-
-    InLoop = (LVM_INT16)(n >> 2); /* Process per 4 samples */
-    OutLoop = (LVM_INT16)(n - (InLoop << 2));
-
-    if (OutLoop)
-    {
-        if(CurrentL < TargetL)
-        {
-            ADD2_SAT_FLOAT(CurrentL, DeltaL, Temp);
-            CurrentL = Temp;
-            if (CurrentL > TargetL)
-                CurrentL = TargetL;
-        }
-        else
-        {
-            CurrentL -= DeltaL;
-            if (CurrentL < TargetL)
-                CurrentL = TargetL;
-        }
-
-        if(CurrentR < TargetR)
-        {
-            ADD2_SAT_FLOAT(CurrentR, DeltaR, Temp);
-            CurrentR = Temp;
-            if (CurrentR > TargetR)
-                CurrentR = TargetR;
-        }
-        else
-        {
-            CurrentR -= DeltaR;
-            if (CurrentR < TargetR)
-                CurrentR = TargetR;
-        }
-
-        for (ii = OutLoop * 2; ii != 0; ii -= 2)
-        {
-            *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentL));
-            *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentR));
-        }
-    }
-
-    for (ii = InLoop * 2; ii != 0; ii-=2)
-    {
-        if(CurrentL < TargetL)
-        {
-            ADD2_SAT_FLOAT(CurrentL, DeltaL, Temp);
-            CurrentL = Temp;
-            if (CurrentL > TargetL)
-                CurrentL = TargetL;
-        }
-        else
-        {
-            CurrentL -= DeltaL;
-            if (CurrentL < TargetL)
-                CurrentL = TargetL;
-        }
-
-        if(CurrentR < TargetR)
-        {
-            ADD2_SAT_FLOAT(CurrentR, DeltaR, Temp);
-            CurrentR = Temp;
-            if (CurrentR > TargetR)
-                CurrentR = TargetR;
-        }
-        else
-        {
-            CurrentR -= DeltaR;
-            if (CurrentR < TargetR)
-                CurrentR = TargetR;
-        }
-
-        *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentL));
-        *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentR));
-        *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentL));
-        *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentR));
-        *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentL));
-        *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentR));
-        *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentL));
-        *(dst++) = (LVM_FLOAT)(((LVM_FLOAT)*(src++) * (LVM_FLOAT)CurrentR));
-    }
-    pInstanceL->Current = CurrentL;
-    pInstanceR->Current = CurrentR;
-
-}
-#ifdef SUPPORT_MC
-void LVC_Core_MixSoft_1St_MC_float_WRA (Mix_Private_FLOAT_st **ptrInstance,
-                                         const LVM_FLOAT      *src,
-                                         LVM_FLOAT            *dst,
-                                         LVM_INT16            NrFrames,
-                                         LVM_INT16            NrChannels)
-{
-    LVM_INT32   ii, ch;
-    LVM_FLOAT   Temp =0.0f;
-    LVM_FLOAT   tempCurrent[NrChannels];
-    for (ch = 0; ch < NrChannels; ch++)
-    {
+void LVC_Core_MixSoft_1St_MC_float_WRA(Mix_Private_FLOAT_st** ptrInstance, const LVM_FLOAT* src,
+                                       LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels) {
+    LVM_INT32 ii, ch;
+    LVM_FLOAT tempCurrent[NrChannels];
+    for (ch = 0; ch < NrChannels; ch++) {
         tempCurrent[ch] = ptrInstance[ch]->Current;
     }
-    for (ii = NrFrames; ii > 0; ii--)
-    {
-        for (ch = 0; ch < NrChannels; ch++)
-        {
-            Mix_Private_FLOAT_st *pInstance = ptrInstance[ch];
-            const LVM_FLOAT   Delta = pInstance->Delta;
-            LVM_FLOAT         Current = tempCurrent[ch];
-            const LVM_FLOAT   Target = pInstance->Target;
-            if (Current < Target)
-            {
-                ADD2_SAT_FLOAT(Current, Delta, Temp);
-                Current = Temp;
-                if (Current > Target)
-                    Current = Target;
-            }
-            else
-            {
+    for (ii = NrFrames; ii > 0; ii--) {
+        for (ch = 0; ch < NrChannels; ch++) {
+            Mix_Private_FLOAT_st* pInstance = ptrInstance[ch];
+            const LVM_FLOAT Delta = pInstance->Delta;
+            LVM_FLOAT Current = tempCurrent[ch];
+            const LVM_FLOAT Target = pInstance->Target;
+            if (Current < Target) {
+                Current = ADD2_SAT_FLOAT(Current, Delta);
+                if (Current > Target) Current = Target;
+            } else {
                 Current -= Delta;
-                if (Current < Target)
-                    Current = Target;
+                if (Current < Target) Current = Target;
             }
             *dst++ = *src++ * Current;
             tempCurrent[ch] = Current;
         }
     }
-    for (ch = 0; ch < NrChannels; ch++)
-    {
+    for (ch = 0; ch < NrChannels; ch++) {
         ptrInstance[ch]->Current = tempCurrent[ch];
     }
 }
-#endif
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixSoft_1St_D16C31_WRA.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixSoft_1St_D16C31_WRA.cpp
index 5d8aadc..fc464e6 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Core_MixSoft_1St_D16C31_WRA.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Core_MixSoft_1St_D16C31_WRA.cpp
@@ -18,7 +18,6 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
 #include "LVC_Mixer_Private.h"
 #include "LVM_Macros.h"
 #include "ScalarArithmetic.h"
@@ -26,86 +25,62 @@
 /**********************************************************************************
    FUNCTION LVCore_MIXSOFT_1ST_D16C31_WRA
 ***********************************************************************************/
-void LVC_Core_MixSoft_1St_D16C31_WRA(LVMixer3_FLOAT_st *ptrInstance,
-                                     const LVM_FLOAT   *src,
-                                           LVM_FLOAT   *dst,
-                                           LVM_INT16   n)
-{
-    LVM_INT16   OutLoop;
-    LVM_INT16   InLoop;
-    LVM_INT32   ii;
-    Mix_Private_FLOAT_st  *pInstance=(Mix_Private_FLOAT_st *)(ptrInstance->PrivateParams);
-    LVM_FLOAT   Delta= (LVM_FLOAT)pInstance->Delta;
-    LVM_FLOAT   Current = (LVM_FLOAT)pInstance->Current;
-    LVM_FLOAT   Target= (LVM_FLOAT)pInstance->Target;
-    LVM_FLOAT   Temp;
+void LVC_Core_MixSoft_1St_D16C31_WRA(LVMixer3_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                     LVM_FLOAT* dst, LVM_INT16 n) {
+    LVM_INT16 OutLoop;
+    LVM_INT16 InLoop;
+    LVM_INT32 ii;
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)(ptrInstance->PrivateParams);
+    LVM_FLOAT Delta = (LVM_FLOAT)pInstance->Delta;
+    LVM_FLOAT Current = (LVM_FLOAT)pInstance->Current;
+    LVM_FLOAT Target = (LVM_FLOAT)pInstance->Target;
 
     InLoop = (LVM_INT16)(n >> 2); /* Process per 4 samples */
     OutLoop = (LVM_INT16)(n - (InLoop << 2));
 
-    if(Current<Target){
-        if (OutLoop){
+    if (Current < Target) {
+        if (OutLoop) {
+            Current = LVM_Clamp(Current + Delta);
+            if (Current > Target) Current = Target;
 
-            Temp = Current + Delta;
-            if (Temp > 1.0f)
-                Temp = 1.0f;
-            else if (Temp < -1.0f)
-                Temp = -1.0f;
-
-            Current=Temp;
-            if (Current > Target)
-                Current = Target;
-
-            for (ii = OutLoop; ii != 0; ii--){
-                *(dst++) = (((LVM_FLOAT)*(src++) * (LVM_FLOAT)Current));
+            for (ii = OutLoop; ii != 0; ii--) {
+                *(dst++) = (((LVM_FLOAT) * (src++) * (LVM_FLOAT)Current));
             }
         }
 
-        for (ii = InLoop; ii != 0; ii--){
+        for (ii = InLoop; ii != 0; ii--) {
+            Current = LVM_Clamp(Current + Delta);
 
-            Temp = Current + Delta;
+            if (Current > Target) Current = Target;
 
-            if (Temp > 1.0f)
-                Temp = 1.0f;
-            else if (Temp < -1.0f)
-                Temp = -1.0f;
-
-            Current=Temp;
-            if (Current > Target)
-                Current = Target;
-
-            *(dst++) = (((LVM_FLOAT)*(src++) * Current) );
-            *(dst++) = (((LVM_FLOAT)*(src++) * Current) );
-            *(dst++) = (((LVM_FLOAT)*(src++) * Current) );
-            *(dst++) = (((LVM_FLOAT)*(src++) * Current) );
+            *(dst++) = (((LVM_FLOAT) * (src++) * Current));
+            *(dst++) = (((LVM_FLOAT) * (src++) * Current));
+            *(dst++) = (((LVM_FLOAT) * (src++) * Current));
+            *(dst++) = (((LVM_FLOAT) * (src++) * Current));
         }
-    }
-    else{
-        if (OutLoop){
+    } else {
+        if (OutLoop) {
             Current -= Delta;
-            if (Current < Target)
-                Current = Target;
+            if (Current < Target) Current = Target;
 
-            for (ii = OutLoop; ii != 0; ii--){
-                *(dst++) = (((LVM_FLOAT)*(src++) * Current));
+            for (ii = OutLoop; ii != 0; ii--) {
+                *(dst++) = (((LVM_FLOAT) * (src++) * Current));
             }
         }
 
-        for (ii = InLoop; ii != 0; ii--){
+        for (ii = InLoop; ii != 0; ii--) {
             Current -= Delta;
-            if (Current < Target)
-                Current = Target;
+            if (Current < Target) Current = Target;
 
-            *(dst++) = (((LVM_FLOAT)*(src++) * Current));
-            *(dst++) = (((LVM_FLOAT)*(src++) * Current));
-            *(dst++) = (((LVM_FLOAT)*(src++) * Current));
-            *(dst++) = (((LVM_FLOAT)*(src++) * Current));
+            *(dst++) = (((LVM_FLOAT) * (src++) * Current));
+            *(dst++) = (((LVM_FLOAT) * (src++) * Current));
+            *(dst++) = (((LVM_FLOAT) * (src++) * Current));
+            *(dst++) = (((LVM_FLOAT) * (src++) * Current));
         }
     }
-    pInstance->Current=Current;
+    pInstance->Current = Current;
 }
 
-#ifdef SUPPORT_MC
 /*
  * FUNCTION:       LVC_Core_MixSoft_Mc_D16C31_WRA
  *
@@ -123,20 +98,15 @@
  *  void
  *
  */
-void LVC_Core_MixSoft_Mc_D16C31_WRA(LVMixer3_FLOAT_st *ptrInstance,
-                                    const LVM_FLOAT   *src,
-                                          LVM_FLOAT   *dst,
-                                          LVM_INT16   NrFrames,
-                                          LVM_INT16   NrChannels)
-{
-    LVM_INT16   OutLoop;
-    LVM_INT16   InLoop;
-    LVM_INT32   ii, jj;
-    Mix_Private_FLOAT_st  *pInstance=(Mix_Private_FLOAT_st *)(ptrInstance->PrivateParams);
-    LVM_FLOAT   Delta= (LVM_FLOAT)pInstance->Delta;
-    LVM_FLOAT   Current = (LVM_FLOAT)pInstance->Current;
-    LVM_FLOAT   Target= (LVM_FLOAT)pInstance->Target;
-    LVM_FLOAT   Temp;
+void LVC_Core_MixSoft_Mc_D16C31_WRA(LVMixer3_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                    LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels) {
+    LVM_INT16 OutLoop;
+    LVM_INT16 InLoop;
+    LVM_INT32 ii, jj;
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)(ptrInstance->PrivateParams);
+    LVM_FLOAT Delta = (LVM_FLOAT)pInstance->Delta;
+    LVM_FLOAT Current = (LVM_FLOAT)pInstance->Current;
+    LVM_FLOAT Target = (LVM_FLOAT)pInstance->Target;
 
     /*
      * Same operation is performed on consecutive frames.
@@ -147,73 +117,50 @@
     /* OutLoop is calculated to handle cases where NrFrames value can be odd.*/
     OutLoop = (LVM_INT16)(NrFrames - (InLoop << 1));
 
-    if (Current<Target) {
+    if (Current < Target) {
         if (OutLoop) {
-
-            Temp = Current + Delta;
-            if (Temp > 1.0f)
-                Temp = 1.0f;
-            else if (Temp < -1.0f)
-                Temp = -1.0f;
-
-            Current=Temp;
-            if (Current > Target)
-                Current = Target;
+            Current = LVM_Clamp(Current + Delta);
+            if (Current > Target) Current = Target;
 
             for (ii = OutLoop; ii != 0; ii--) {
-                for (jj = NrChannels; jj !=0; jj--) {
-                    *(dst++) = (((LVM_FLOAT)*(src++) * (LVM_FLOAT)Current));
+                for (jj = NrChannels; jj != 0; jj--) {
+                    *(dst++) = (((LVM_FLOAT) * (src++) * (LVM_FLOAT)Current));
                 }
             }
         }
 
         for (ii = InLoop; ii != 0; ii--) {
+            Current = LVM_Clamp(Current + Delta);
+            if (Current > Target) Current = Target;
 
-            Temp = Current + Delta;
-
-            if (Temp > 1.0f)
-                Temp = 1.0f;
-            else if (Temp < -1.0f)
-                Temp = -1.0f;
-
-            Current=Temp;
-            if (Current > Target)
-                Current = Target;
-
-            for (jj = NrChannels; jj != 0 ; jj--)
-            {
-                *(dst++) = (((LVM_FLOAT)*(src++) * Current));
-                *(dst++) = (((LVM_FLOAT)*(src++) * Current));
+            for (jj = NrChannels; jj != 0; jj--) {
+                *(dst++) = (((LVM_FLOAT) * (src++) * Current));
+                *(dst++) = (((LVM_FLOAT) * (src++) * Current));
             }
         }
-    }
-    else{
+    } else {
         if (OutLoop) {
             Current -= Delta;
-            if (Current < Target)
-                Current = Target;
+            if (Current < Target) Current = Target;
 
             for (ii = OutLoop; ii != 0; ii--) {
-                for (jj = NrChannels; jj !=0; jj--) {
-                    *(dst++) = (((LVM_FLOAT)*(src++) * (LVM_FLOAT)Current));
+                for (jj = NrChannels; jj != 0; jj--) {
+                    *(dst++) = (((LVM_FLOAT) * (src++) * (LVM_FLOAT)Current));
                 }
             }
         }
 
         for (ii = InLoop; ii != 0; ii--) {
             Current -= Delta;
-            if (Current < Target)
-                Current = Target;
+            if (Current < Target) Current = Target;
 
-            for (jj = NrChannels; jj != 0 ; jj--)
-            {
-                *(dst++) = (((LVM_FLOAT)*(src++) * Current));
-                *(dst++) = (((LVM_FLOAT)*(src++) * Current));
+            for (jj = NrChannels; jj != 0; jj--) {
+                *(dst++) = (((LVM_FLOAT) * (src++) * Current));
+                *(dst++) = (((LVM_FLOAT) * (src++) * Current));
             }
         }
     }
-    pInstance->Current=Current;
+    pInstance->Current = Current;
 }
-#endif
 
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_MixInSoft_D16C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/LVC_MixInSoft_D16C31_SAT.cpp
index 2bec3be..270c7e0 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_MixInSoft_D16C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_MixInSoft_D16C31_SAT.cpp
@@ -27,39 +27,35 @@
    DEFINITIONS
 ***********************************************************************************/
 
-#define TRUE          1
-#define FALSE         0
+#define TRUE 1
+#define FALSE 0
 
 /**********************************************************************************
    FUNCTION MIXINSOFT_D16C31_SAT
 ***********************************************************************************/
-void LVC_MixInSoft_D16C31_SAT(LVMixer3_1St_FLOAT_st *ptrInstance,
-                              const LVM_FLOAT       *src,
-                                    LVM_FLOAT       *dst,
-                                    LVM_INT16       n)
-{
-    char        HardMixing = TRUE;
-    LVM_FLOAT   TargetGain;
-    Mix_Private_FLOAT_st  *pInstance = \
-                             (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[0].PrivateParams);
+void LVC_MixInSoft_D16C31_SAT(LVMixer3_1St_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                              LVM_FLOAT* dst, LVM_INT16 n) {
+    char HardMixing = TRUE;
+    LVM_FLOAT TargetGain;
+    Mix_Private_FLOAT_st* pInstance =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[0].PrivateParams);
 
-    if(n <= 0)    return;
+    if (n <= 0) return;
 
     /******************************************************************************
        SOFT MIXING
     *******************************************************************************/
-    if (pInstance->Current != pInstance->Target)
-    {
-        if(pInstance->Delta == 1.0f){
+    if (pInstance->Current != pInstance->Target) {
+        if (pInstance->Delta == 1.0f) {
             pInstance->Current = pInstance->Target;
             TargetGain = pInstance->Target;
             LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }else if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta){
+        } else if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta) {
             pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
                                                        Make them equal. */
             TargetGain = pInstance->Target;
             LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }else{
+        } else {
             /* Soft mixing has to be applied */
             HardMixing = FALSE;
             LVC_Core_MixInSoft_D16C31_SAT(&(ptrInstance->MixerStream[0]), src, dst, n);
@@ -70,111 +66,12 @@
        HARD MIXING
     *******************************************************************************/
 
-    if (HardMixing){
-        if (pInstance->Target != 0){ /* Nothing to do in case Target = 0 */
-            if ((pInstance->Target) == 1.0f){
-                Add2_Sat_Float(src, dst, n);
-            }
-            else{
-                Mac3s_Sat_Float(src, (pInstance->Target), dst, n);
-                /* In case the LVCore function would have changed the Current value */
-                pInstance->Current = pInstance->Target;
-            }
-        }
-    }
-
-    /******************************************************************************
-       CALL BACK
-    *******************************************************************************/
-
-    if (ptrInstance->MixerStream[0].CallbackSet){
-        if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta){
-            pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
-                                                       Make them equal. */
-            TargetGain = pInstance->Target;
-            LVC_Mixer_SetTarget(ptrInstance->MixerStream, TargetGain);
-            ptrInstance->MixerStream[0].CallbackSet = FALSE;
-            if (ptrInstance->MixerStream[0].pCallBack != 0){
-                (*ptrInstance->MixerStream[0].pCallBack) ( \
-                                                ptrInstance->MixerStream[0].pCallbackHandle,
-                                                ptrInstance->MixerStream[0].pGeneralPurpose,
-                                                ptrInstance->MixerStream[0].CallbackParam );
-            }
-        }
-    }
-
-}
-
-#ifdef SUPPORT_MC
-/*
- * FUNCTION:       LVC_MixInSoft_Mc_D16C31_SAT
- *
- * DESCRIPTION:
- *  Mixer function with support for processing multichannel input
- *
- * PARAMETERS:
- *  ptrInstance    Instance pointer
- *  src            Source
- *  dst            Destination
- *  NrFrames       Number of frames
- *  NrChannels     Number of channels
- *
- * RETURNS:
- *  void
- *
- */
-void LVC_MixInSoft_Mc_D16C31_SAT(LVMixer3_1St_FLOAT_st *ptrInstance,
-                                 const LVM_FLOAT       *src,
-                                       LVM_FLOAT       *dst,
-                                       LVM_INT16       NrFrames,
-                                       LVM_INT16       NrChannels)
-{
-    char        HardMixing = TRUE;
-    LVM_FLOAT   TargetGain;
-    Mix_Private_FLOAT_st  *pInstance = \
-                             (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[0].PrivateParams);
-
-    if (NrFrames <= 0)    return;
-
-    /******************************************************************************
-       SOFT MIXING
-    *******************************************************************************/
-    if (pInstance->Current != pInstance->Target)
-    {
-        if (pInstance->Delta == 1.0f) {
-            pInstance->Current = pInstance->Target;
-            TargetGain = pInstance->Target;
-            LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }else if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta) {
-            pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
-                                                       Make them equal. */
-            TargetGain = pInstance->Target;
-            LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }else{
-            /* Soft mixing has to be applied */
-            HardMixing = FALSE;
-            LVC_Core_MixInSoft_Mc_D16C31_SAT(&(ptrInstance->MixerStream[0]),
-                                             src,
-                                             dst,
-                                             NrFrames,
-                                             NrChannels);
-        }
-    }
-
-    /******************************************************************************
-       HARD MIXING
-    *******************************************************************************/
-
     if (HardMixing) {
         if (pInstance->Target != 0) { /* Nothing to do in case Target = 0 */
             if ((pInstance->Target) == 1.0f) {
-                Add2_Sat_Float(src, dst, NrFrames*NrChannels);
-            }
-            else{
-                Mac3s_Sat_Float(src,
-                                (pInstance->Target),
-                                dst,
-                                NrFrames * NrChannels);
+                Add2_Sat_Float(src, dst, n);
+            } else {
+                Mac3s_Sat_Float(src, (pInstance->Target), dst, n);
                 /* In case the LVCore function would have changed the Current value */
                 pInstance->Current = pInstance->Target;
             }
@@ -193,15 +90,97 @@
             LVC_Mixer_SetTarget(ptrInstance->MixerStream, TargetGain);
             ptrInstance->MixerStream[0].CallbackSet = FALSE;
             if (ptrInstance->MixerStream[0].pCallBack != 0) {
-                (*ptrInstance->MixerStream[0].pCallBack) (\
-                                                ptrInstance->MixerStream[0].pCallbackHandle,
-                                                ptrInstance->MixerStream[0].pGeneralPurpose,
-                                                ptrInstance->MixerStream[0].CallbackParam);
+                (*ptrInstance->MixerStream[0].pCallBack)(
+                        ptrInstance->MixerStream[0].pCallbackHandle,
+                        ptrInstance->MixerStream[0].pGeneralPurpose,
+                        ptrInstance->MixerStream[0].CallbackParam);
+            }
+        }
+    }
+}
+
+/*
+ * FUNCTION:       LVC_MixInSoft_Mc_D16C31_SAT
+ *
+ * DESCRIPTION:
+ *  Mixer function with support for processing multichannel input
+ *
+ * PARAMETERS:
+ *  ptrInstance    Instance pointer
+ *  src            Source
+ *  dst            Destination
+ *  NrFrames       Number of frames
+ *  NrChannels     Number of channels
+ *
+ * RETURNS:
+ *  void
+ *
+ */
+void LVC_MixInSoft_Mc_D16C31_SAT(LVMixer3_1St_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                 LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels) {
+    char HardMixing = TRUE;
+    LVM_FLOAT TargetGain;
+    Mix_Private_FLOAT_st* pInstance =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[0].PrivateParams);
+
+    if (NrFrames <= 0) return;
+
+    /******************************************************************************
+       SOFT MIXING
+    *******************************************************************************/
+    if (pInstance->Current != pInstance->Target) {
+        if (pInstance->Delta == 1.0f) {
+            pInstance->Current = pInstance->Target;
+            TargetGain = pInstance->Target;
+            LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
+        } else if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta) {
+            pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
+                                                       Make them equal. */
+            TargetGain = pInstance->Target;
+            LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
+        } else {
+            /* Soft mixing has to be applied */
+            HardMixing = FALSE;
+            LVC_Core_MixInSoft_Mc_D16C31_SAT(&(ptrInstance->MixerStream[0]), src, dst, NrFrames,
+                                             NrChannels);
+        }
+    }
+
+    /******************************************************************************
+       HARD MIXING
+    *******************************************************************************/
+
+    if (HardMixing) {
+        if (pInstance->Target != 0) { /* Nothing to do in case Target = 0 */
+            if ((pInstance->Target) == 1.0f) {
+                Add2_Sat_Float(src, dst, NrFrames * NrChannels);
+            } else {
+                Mac3s_Sat_Float(src, (pInstance->Target), dst, NrFrames * NrChannels);
+                /* In case the LVCore function would have changed the Current value */
+                pInstance->Current = pInstance->Target;
             }
         }
     }
 
+    /******************************************************************************
+       CALL BACK
+    *******************************************************************************/
+
+    if (ptrInstance->MixerStream[0].CallbackSet) {
+        if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta) {
+            pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
+                                                       Make them equal. */
+            TargetGain = pInstance->Target;
+            LVC_Mixer_SetTarget(ptrInstance->MixerStream, TargetGain);
+            ptrInstance->MixerStream[0].CallbackSet = FALSE;
+            if (ptrInstance->MixerStream[0].pCallBack != 0) {
+                (*ptrInstance->MixerStream[0].pCallBack)(
+                        ptrInstance->MixerStream[0].pCallbackHandle,
+                        ptrInstance->MixerStream[0].pGeneralPurpose,
+                        ptrInstance->MixerStream[0].CallbackParam);
+            }
+        }
+    }
 }
-#endif
 
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_1St_2i_D16C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_1St_2i_D16C31_SAT.cpp
index 3153ada..b0aa172 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_1St_2i_D16C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_1St_2i_D16C31_SAT.cpp
@@ -29,144 +29,118 @@
    DEFINITIONS
 ***********************************************************************************/
 
-#define TRUE          1
-#define FALSE         0
+#define TRUE 1
+#define FALSE 0
 
 #define ARRAY_SIZE(a) ((sizeof(a)) / (sizeof(*(a))))
 
 /**********************************************************************************
-   FUNCTION LVC_MixSoft_1St_2i_D16C31_SAT
+   FUNCTION LVC_MixSoft_1St_MC_float_SAT
 ***********************************************************************************/
-#ifdef SUPPORT_MC
 /* This threshold is used to decide on the processing to be applied on
  * front center and back center channels
  */
 #define LVM_VOL_BAL_THR (0.000016f)
-void LVC_MixSoft_1St_MC_float_SAT (LVMixer3_2St_FLOAT_st *ptrInstance,
-                                    const LVM_FLOAT       *src,
-                                    LVM_FLOAT             *dst,
-                                    LVM_INT16             NrFrames,
-                                    LVM_INT32             NrChannels,
-                                    LVM_INT32             ChMask)
-{
-    char        HardMixing = TRUE;
-    LVM_FLOAT   TargetGain;
-    Mix_Private_FLOAT_st  Target_lfe = {LVM_MAXFLOAT, LVM_MAXFLOAT, LVM_MAXFLOAT};
-    Mix_Private_FLOAT_st  Target_ctr = {LVM_MAXFLOAT, LVM_MAXFLOAT, LVM_MAXFLOAT};
-    Mix_Private_FLOAT_st  *pInstance1 = \
-                              (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[0].PrivateParams);
-    Mix_Private_FLOAT_st  *pInstance2 = \
-                              (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[1].PrivateParams);
-    Mix_Private_FLOAT_st  *pMixPrivInst[4] = {pInstance1, pInstance2, &Target_ctr, &Target_lfe};
-    Mix_Private_FLOAT_st  *pInstance[NrChannels];
+void LVC_MixSoft_1St_MC_float_SAT(LVMixer3_2St_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                  LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT32 NrChannels,
+                                  LVM_INT32 ChMask) {
+    char HardMixing = TRUE;
+    LVM_FLOAT TargetGain;
+    Mix_Private_FLOAT_st Target_lfe = {LVM_MAXFLOAT, LVM_MAXFLOAT, LVM_MAXFLOAT};
+    Mix_Private_FLOAT_st Target_ctr = {LVM_MAXFLOAT, LVM_MAXFLOAT, LVM_MAXFLOAT};
+    Mix_Private_FLOAT_st* pInstance1 =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[0].PrivateParams);
+    Mix_Private_FLOAT_st* pInstance2 =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[1].PrivateParams);
+    Mix_Private_FLOAT_st* pMixPrivInst[4] = {pInstance1, pInstance2, &Target_ctr, &Target_lfe};
+    Mix_Private_FLOAT_st* pInstance[NrChannels];
 
-    if (audio_channel_mask_get_representation(ChMask)
-            == AUDIO_CHANNEL_REPRESENTATION_INDEX)
-    {
-        for (int i = 0; i < 2; i++)
-        {
+    if (audio_channel_mask_get_representation(ChMask) == AUDIO_CHANNEL_REPRESENTATION_INDEX) {
+        int loopLimit = (NrChannels == FCC_1) ? NrChannels : FCC_2;
+        for (int i = 0; i < loopLimit; i++) {
             pInstance[i] = pMixPrivInst[i];
         }
-        for (int i = 2; i < NrChannels; i++)
-        {
+        for (int i = loopLimit; i < NrChannels; i++) {
             pInstance[i] = pMixPrivInst[2];
         }
-    }
-    else
-    {
+    } else {
         // TODO: Combine with system/media/audio_utils/Balance.cpp
         // Constants in system/media/audio/include/system/audio-base.h
         // 'mixInstIdx' is used to map the appropriate mixer instance for each channel.
         const int mixInstIdx[] = {
-            0, // AUDIO_CHANNEL_OUT_FRONT_LEFT            = 0x1u,
-            1, // AUDIO_CHANNEL_OUT_FRONT_RIGHT           = 0x2u,
-            2, // AUDIO_CHANNEL_OUT_FRONT_CENTER          = 0x4u,
-            3, // AUDIO_CHANNEL_OUT_LOW_FREQUENCY         = 0x8u,
-            0, // AUDIO_CHANNEL_OUT_BACK_LEFT             = 0x10u,
-            1, // AUDIO_CHANNEL_OUT_BACK_RIGHT            = 0x20u,
-            0, // AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER  = 0x40u,
-            1, // AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x80u,
-            2, // AUDIO_CHANNEL_OUT_BACK_CENTER           = 0x100u,
-            0, // AUDIO_CHANNEL_OUT_SIDE_LEFT             = 0x200u,
-            1, // AUDIO_CHANNEL_OUT_SIDE_RIGHT            = 0x400u,
-            2, // AUDIO_CHANNEL_OUT_TOP_CENTER            = 0x800u,
-            0, // AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT        = 0x1000u,
-            2, // AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER      = 0x2000u,
-            1, // AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT       = 0x4000u,
-            0, // AUDIO_CHANNEL_OUT_TOP_BACK_LEFT         = 0x8000u,
-            2, // AUDIO_CHANNEL_OUT_TOP_BACK_CENTER       = 0x10000u,
-            1, // AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT        = 0x20000u,
-            0, // AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT         = 0x40000u,
-            1, // AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT        = 0x80000u
+                0,  // AUDIO_CHANNEL_OUT_FRONT_LEFT            = 0x1u,
+                1,  // AUDIO_CHANNEL_OUT_FRONT_RIGHT           = 0x2u,
+                2,  // AUDIO_CHANNEL_OUT_FRONT_CENTER          = 0x4u,
+                3,  // AUDIO_CHANNEL_OUT_LOW_FREQUENCY         = 0x8u,
+                0,  // AUDIO_CHANNEL_OUT_BACK_LEFT             = 0x10u,
+                1,  // AUDIO_CHANNEL_OUT_BACK_RIGHT            = 0x20u,
+                0,  // AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER  = 0x40u,
+                1,  // AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x80u,
+                2,  // AUDIO_CHANNEL_OUT_BACK_CENTER           = 0x100u,
+                0,  // AUDIO_CHANNEL_OUT_SIDE_LEFT             = 0x200u,
+                1,  // AUDIO_CHANNEL_OUT_SIDE_RIGHT            = 0x400u,
+                2,  // AUDIO_CHANNEL_OUT_TOP_CENTER            = 0x800u,
+                0,  // AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT        = 0x1000u,
+                2,  // AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER      = 0x2000u,
+                1,  // AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT       = 0x4000u,
+                0,  // AUDIO_CHANNEL_OUT_TOP_BACK_LEFT         = 0x8000u,
+                2,  // AUDIO_CHANNEL_OUT_TOP_BACK_CENTER       = 0x10000u,
+                1,  // AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT        = 0x20000u,
+                0,  // AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT         = 0x40000u,
+                1,  // AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT        = 0x80000u
         };
-        if (pInstance1->Target <= LVM_VOL_BAL_THR ||
-            pInstance2->Target <= LVM_VOL_BAL_THR)
-        {
-            Target_ctr.Target  = 0.0f;
+        if (pInstance1->Target <= LVM_VOL_BAL_THR || pInstance2->Target <= LVM_VOL_BAL_THR) {
+            Target_ctr.Target = 0.0f;
             Target_ctr.Current = 0.0f;
-            Target_ctr.Delta   = 0.0f;
+            Target_ctr.Delta = 0.0f;
         }
         const unsigned int idxArrSize = ARRAY_SIZE(mixInstIdx);
-        for (unsigned int i = 0, channel = ChMask; channel !=0 ; ++i)
-        {
+        for (unsigned int i = 0, channel = ChMask; channel != 0; ++i) {
             const unsigned int idx = __builtin_ctz(channel);
-            if (idx < idxArrSize)
-            {
+            if (idx < idxArrSize) {
                 pInstance[i] = pMixPrivInst[mixInstIdx[idx]];
-            }
-            else
-            {
+            } else {
                 pInstance[i] = pMixPrivInst[2];
             }
             channel &= ~(1 << idx);
         }
     }
 
-    if (NrFrames <= 0)    return;
+    if (NrFrames <= 0) return;
 
     /******************************************************************************
        SOFT MIXING
     *******************************************************************************/
 
     if ((pInstance1->Current != pInstance1->Target) ||
-        (pInstance2->Current != pInstance2->Target))
-    {
+        (pInstance2->Current != pInstance2->Target)) {
         // TODO: combine similar checks below.
-        if (pInstance1->Delta == LVM_MAXFLOAT
-                || Abs_Float(pInstance1->Current - pInstance1->Target) < pInstance1->Delta)
-        {
+        if (pInstance1->Delta == LVM_MAXFLOAT ||
+            Abs_Float(pInstance1->Current - pInstance1->Target) < pInstance1->Delta) {
             /* Difference is not significant anymore. Make them equal. */
             pInstance1->Current = pInstance1->Target;
             TargetGain = pInstance1->Target;
             LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }
-        else
-        {
+        } else {
             /* Soft mixing has to be applied */
             HardMixing = FALSE;
         }
 
-        if (HardMixing == TRUE)
-        {
-            if (pInstance2->Delta == LVM_MAXFLOAT
-                    || Abs_Float(pInstance2->Current - pInstance2->Target) < pInstance2->Delta)
-            {
+        if (HardMixing == TRUE) {
+            if (pInstance2->Delta == LVM_MAXFLOAT ||
+                Abs_Float(pInstance2->Current - pInstance2->Target) < pInstance2->Delta) {
                 /* Difference is not significant anymore. Make them equal. */
                 pInstance2->Current = pInstance2->Target;
                 TargetGain = pInstance2->Target;
                 LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[1]), TargetGain);
-            }
-            else
-            {
+            } else {
                 /* Soft mixing has to be applied */
                 HardMixing = FALSE;
             }
         }
 
-        if (HardMixing == FALSE)
-        {
-             LVC_Core_MixSoft_1St_MC_float_WRA (&pInstance[0],
-                                                 src, dst, NrFrames, NrChannels);
+        if (HardMixing == FALSE) {
+            LVC_Core_MixSoft_1St_MC_float_WRA(&pInstance[0], src, dst, NrFrames, NrChannels);
         }
     }
 
@@ -174,19 +148,13 @@
        HARD MIXING
     *******************************************************************************/
 
-    if (HardMixing == TRUE)
-    {
-        if ((pInstance1->Target == LVM_MAXFLOAT) && (pInstance2->Target == LVM_MAXFLOAT))
-        {
-            if (src != dst)
-            {
-                Copy_Float(src, dst, NrFrames*NrChannels);
+    if (HardMixing == TRUE) {
+        if ((pInstance1->Target == LVM_MAXFLOAT) && (pInstance2->Target == LVM_MAXFLOAT)) {
+            if (src != dst) {
+                Copy_Float(src, dst, NrFrames * NrChannels);
             }
-        }
-        else
-        {
-            LVC_Core_MixHard_1St_MC_float_SAT(&(pInstance[0]),
-                                               src, dst, NrFrames, NrChannels);
+        } else {
+            LVC_Core_MixHard_1St_MC_float_SAT(&(pInstance[0]), src, dst, NrFrames, NrChannels);
         }
     }
 
@@ -194,172 +162,34 @@
        CALL BACK
     *******************************************************************************/
 
-    if (ptrInstance->MixerStream[0].CallbackSet)
-    {
-        if (Abs_Float(pInstance1->Current - pInstance1->Target) < pInstance1->Delta)
-        {
+    if (ptrInstance->MixerStream[0].CallbackSet) {
+        if (Abs_Float(pInstance1->Current - pInstance1->Target) < pInstance1->Delta) {
             pInstance1->Current = pInstance1->Target; /* Difference is not significant anymore. \
                                                          Make them equal. */
             TargetGain = pInstance1->Target;
             LVC_Mixer_SetTarget(&ptrInstance->MixerStream[0], TargetGain);
             ptrInstance->MixerStream[0].CallbackSet = FALSE;
-            if (ptrInstance->MixerStream[0].pCallBack != 0)
-            {
-                (*ptrInstance->MixerStream[0].pCallBack) (\
-                    ptrInstance->MixerStream[0].pCallbackHandle,
-                    ptrInstance->MixerStream[0].pGeneralPurpose,
-                    ptrInstance->MixerStream[0].CallbackParam);
+            if (ptrInstance->MixerStream[0].pCallBack != 0) {
+                (*ptrInstance->MixerStream[0].pCallBack)(
+                        ptrInstance->MixerStream[0].pCallbackHandle,
+                        ptrInstance->MixerStream[0].pGeneralPurpose,
+                        ptrInstance->MixerStream[0].CallbackParam);
             }
         }
     }
-    if (ptrInstance->MixerStream[1].CallbackSet)
-    {
-        if (Abs_Float(pInstance2->Current - pInstance2->Target) < pInstance2->Delta)
-        {
+    if (ptrInstance->MixerStream[1].CallbackSet) {
+        if (Abs_Float(pInstance2->Current - pInstance2->Target) < pInstance2->Delta) {
             pInstance2->Current = pInstance2->Target; /* Difference is not significant anymore.
                                                          Make them equal. */
             TargetGain = pInstance2->Target;
             LVC_Mixer_SetTarget(&ptrInstance->MixerStream[1], TargetGain);
             ptrInstance->MixerStream[1].CallbackSet = FALSE;
-            if (ptrInstance->MixerStream[1].pCallBack != 0)
-            {
-                (*ptrInstance->MixerStream[1].pCallBack) (\
-                    ptrInstance->MixerStream[1].pCallbackHandle,
-                    ptrInstance->MixerStream[1].pGeneralPurpose,
-                    ptrInstance->MixerStream[1].CallbackParam);
+            if (ptrInstance->MixerStream[1].pCallBack != 0) {
+                (*ptrInstance->MixerStream[1].pCallBack)(
+                        ptrInstance->MixerStream[1].pCallbackHandle,
+                        ptrInstance->MixerStream[1].pGeneralPurpose,
+                        ptrInstance->MixerStream[1].CallbackParam);
             }
         }
     }
 }
-#endif
-void LVC_MixSoft_1St_2i_D16C31_SAT( LVMixer3_2St_FLOAT_st *ptrInstance,
-                                    const LVM_FLOAT             *src,
-                                    LVM_FLOAT             *dst,
-                                    LVM_INT16             n)
-{
-    char        HardMixing = TRUE;
-    LVM_FLOAT   TargetGain;
-    Mix_Private_FLOAT_st  *pInstance1 = \
-                              (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[0].PrivateParams);
-    Mix_Private_FLOAT_st  *pInstance2 = \
-                              (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[1].PrivateParams);
-
-    if(n <= 0)    return;
-
-    /******************************************************************************
-       SOFT MIXING
-    *******************************************************************************/
-    if ((pInstance1->Current != pInstance1->Target) || (pInstance2->Current != pInstance2->Target))
-    {
-        if(pInstance1->Delta == 1.0f)
-        {
-            pInstance1->Current = pInstance1->Target;
-            TargetGain = pInstance1->Target;
-            LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }
-        else if (Abs_Float(pInstance1->Current - pInstance1->Target) < pInstance1->Delta)
-        {
-            pInstance1->Current = pInstance1->Target; /* Difference is not significant anymore. \
-                                                         Make them equal. */
-            TargetGain = pInstance1->Target;
-            LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }
-        else
-        {
-            /* Soft mixing has to be applied */
-            HardMixing = FALSE;
-        }
-
-        if(HardMixing == TRUE)
-        {
-            if(pInstance2->Delta == 1.0f)
-            {
-                pInstance2->Current = pInstance2->Target;
-                TargetGain = pInstance2->Target;
-                LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[1]), TargetGain);
-            }
-            else if (Abs_Float(pInstance2->Current - pInstance2->Target) < pInstance2->Delta)
-            {
-                pInstance2->Current = pInstance2->Target; /* Difference is not significant anymore. \
-                                                             Make them equal. */
-                TargetGain = pInstance2->Target;
-                LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[1]), TargetGain);
-            }
-            else
-            {
-                /* Soft mixing has to be applied */
-                HardMixing = FALSE;
-            }
-        }
-
-        if(HardMixing == FALSE)
-        {
-             LVC_Core_MixSoft_1St_2i_D16C31_WRA( &(ptrInstance->MixerStream[0]),
-                                                 &(ptrInstance->MixerStream[1]),
-                                                 src, dst, n);
-        }
-    }
-
-    /******************************************************************************
-       HARD MIXING
-    *******************************************************************************/
-
-    if (HardMixing)
-    {
-        if ((pInstance1->Target == 1.0f) && (pInstance2->Target == 1.0f))
-        {
-            if(src != dst)
-            {
-                Copy_Float(src, dst, n);
-            }
-        }
-        else
-        {
-            LVC_Core_MixHard_1St_2i_D16C31_SAT(&(ptrInstance->MixerStream[0]),
-                                               &(ptrInstance->MixerStream[1]),
-                                               src, dst, n);
-        }
-    }
-
-    /******************************************************************************
-       CALL BACK
-    *******************************************************************************/
-
-    if (ptrInstance->MixerStream[0].CallbackSet)
-    {
-        if (Abs_Float(pInstance1->Current - pInstance1->Target) < pInstance1->Delta)
-        {
-            pInstance1->Current = pInstance1->Target; /* Difference is not significant anymore. \
-                                                         Make them equal. */
-            TargetGain = pInstance1->Target;
-            LVC_Mixer_SetTarget(&ptrInstance->MixerStream[0], TargetGain);
-            ptrInstance->MixerStream[0].CallbackSet = FALSE;
-            if (ptrInstance->MixerStream[0].pCallBack != 0)
-            {
-                (*ptrInstance->MixerStream[0].pCallBack) ( \
-                                                ptrInstance->MixerStream[0].pCallbackHandle,
-                                                ptrInstance->MixerStream[0].pGeneralPurpose,
-                                                ptrInstance->MixerStream[0].CallbackParam );
-            }
-        }
-    }
-    if (ptrInstance->MixerStream[1].CallbackSet)
-    {
-        if (Abs_Float(pInstance2->Current - pInstance2->Target) < pInstance2->Delta)
-        {
-            pInstance2->Current = pInstance2->Target; /* Difference is not significant anymore.
-                                                         Make them equal. */
-            TargetGain = pInstance2->Target;
-            LVC_Mixer_SetTarget(&ptrInstance->MixerStream[1], TargetGain);
-            ptrInstance->MixerStream[1].CallbackSet = FALSE;
-            if (ptrInstance->MixerStream[1].pCallBack != 0)
-            {
-                (*ptrInstance->MixerStream[1].pCallBack) (
-                                                ptrInstance->MixerStream[1].pCallbackHandle,
-                                                ptrInstance->MixerStream[1].pGeneralPurpose,
-                                                ptrInstance->MixerStream[1].CallbackParam );
-            }
-        }
-    }
-}
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_1St_D16C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_1St_D16C31_SAT.cpp
index 4d229da..be19fa0 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_1St_D16C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_1St_D16C31_SAT.cpp
@@ -27,39 +27,35 @@
    DEFINITIONS
 ***********************************************************************************/
 
-#define TRUE          1
-#define FALSE         0
+#define TRUE 1
+#define FALSE 0
 
 /**********************************************************************************
    FUNCTION LVMixer3_MIXSOFT_1ST_D16C31_SAT
 ***********************************************************************************/
-void LVC_MixSoft_1St_D16C31_SAT( LVMixer3_1St_FLOAT_st *ptrInstance,
-                                  const LVM_FLOAT             *src,
-                                        LVM_FLOAT             *dst,
-                                        LVM_INT16             n)
-{
-    char        HardMixing = TRUE;
-    LVM_FLOAT   TargetGain;
-    Mix_Private_FLOAT_st  *pInstance = \
-                          (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[0].PrivateParams);
+void LVC_MixSoft_1St_D16C31_SAT(LVMixer3_1St_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                LVM_FLOAT* dst, LVM_INT16 n) {
+    char HardMixing = TRUE;
+    LVM_FLOAT TargetGain;
+    Mix_Private_FLOAT_st* pInstance =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[0].PrivateParams);
 
-    if(n <= 0)    return;
+    if (n <= 0) return;
 
     /******************************************************************************
        SOFT MIXING
     *******************************************************************************/
-    if (pInstance->Current != pInstance->Target)
-    {
-        if(pInstance->Delta == 1.0f){
+    if (pInstance->Current != pInstance->Target) {
+        if (pInstance->Delta == 1.0f) {
             pInstance->Current = pInstance->Target;
             TargetGain = pInstance->Target;
             LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }else if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta){
+        } else if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta) {
             pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
                                                        Make them equal. */
             TargetGain = pInstance->Target;
             LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }else{
+        } else {
             /* Soft mixing has to be applied */
             HardMixing = FALSE;
             LVC_Core_MixSoft_1St_D16C31_WRA(&(ptrInstance->MixerStream[0]), src, dst, n);
@@ -70,39 +66,37 @@
        HARD MIXING
     *******************************************************************************/
 
-    if (HardMixing){
+    if (HardMixing) {
         if (pInstance->Target == 0)
             LoadConst_Float(0.0, dst, n);
         else {
             if ((pInstance->Target) != 1.0f)
                 Mult3s_Float(src, (pInstance->Target), dst, n);
-            else if(src != dst)
+            else if (src != dst)
                 Copy_Float(src, dst, n);
         }
-
     }
 
     /******************************************************************************
        CALL BACK
     *******************************************************************************/
 
-    if (ptrInstance->MixerStream[0].CallbackSet){
-        if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta){
+    if (ptrInstance->MixerStream[0].CallbackSet) {
+        if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta) {
             pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
                                                        Make them equal. */
             TargetGain = pInstance->Target;
             LVC_Mixer_SetTarget(ptrInstance->MixerStream, TargetGain);
             ptrInstance->MixerStream[0].CallbackSet = FALSE;
-            if (ptrInstance->MixerStream[0].pCallBack != 0){
-                (*ptrInstance->MixerStream[0].pCallBack) ( \
-                                                ptrInstance->MixerStream[0].pCallbackHandle,
-                                                ptrInstance->MixerStream[0].pGeneralPurpose,
-                                                ptrInstance->MixerStream[0].CallbackParam );
+            if (ptrInstance->MixerStream[0].pCallBack != 0) {
+                (*ptrInstance->MixerStream[0].pCallBack)(
+                        ptrInstance->MixerStream[0].pCallbackHandle,
+                        ptrInstance->MixerStream[0].pGeneralPurpose,
+                        ptrInstance->MixerStream[0].CallbackParam);
             }
         }
     }
 }
-#ifdef SUPPORT_MC
 /*
  * FUNCTION:       LVC_MixSoft_Mc_D16C31_SAT
  *
@@ -120,40 +114,32 @@
  *  void
  *
  */
-void LVC_MixSoft_Mc_D16C31_SAT(LVMixer3_1St_FLOAT_st *ptrInstance,
-                                  const LVM_FLOAT      *src,
-                                        LVM_FLOAT      *dst,
-                                        LVM_INT16      NrFrames,
-                                        LVM_INT16      NrChannels)
-{
-    char        HardMixing = TRUE;
-    LVM_FLOAT   TargetGain;
-    Mix_Private_FLOAT_st  *pInstance = \
-                          (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[0].PrivateParams);
+void LVC_MixSoft_Mc_D16C31_SAT(LVMixer3_1St_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                               LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels) {
+    char HardMixing = TRUE;
+    LVM_FLOAT TargetGain;
+    Mix_Private_FLOAT_st* pInstance =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[0].PrivateParams);
 
-    if (NrFrames <= 0)    return;
+    if (NrFrames <= 0) return;
 
     /******************************************************************************
        SOFT MIXING
     *******************************************************************************/
-    if (pInstance->Current != pInstance->Target)
-    {
+    if (pInstance->Current != pInstance->Target) {
         if (pInstance->Delta == 1.0f) {
             pInstance->Current = pInstance->Target;
             TargetGain = pInstance->Target;
             LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }else if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta) {
+        } else if (Abs_Float(pInstance->Current - pInstance->Target) < pInstance->Delta) {
             pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
                                                        Make them equal. */
             TargetGain = pInstance->Target;
             LVC_Mixer_SetTarget(&(ptrInstance->MixerStream[0]), TargetGain);
-        }else{
+        } else {
             /* Soft mixing has to be applied */
             HardMixing = FALSE;
-            LVC_Core_MixSoft_Mc_D16C31_WRA(&(ptrInstance->MixerStream[0]),
-                                           src,
-                                           dst,
-                                           NrFrames,
+            LVC_Core_MixSoft_Mc_D16C31_WRA(&(ptrInstance->MixerStream[0]), src, dst, NrFrames,
                                            NrChannels);
         }
     }
@@ -171,7 +157,6 @@
             else if (src != dst)
                 Copy_Float(src, dst, NrFrames * NrChannels);
         }
-
     }
 
     /******************************************************************************
@@ -186,15 +171,13 @@
             LVC_Mixer_SetTarget(ptrInstance->MixerStream, TargetGain);
             ptrInstance->MixerStream[0].CallbackSet = FALSE;
             if (ptrInstance->MixerStream[0].pCallBack != 0) {
-                (*ptrInstance->MixerStream[0].pCallBack) (\
-                                                ptrInstance->MixerStream[0].pCallbackHandle,
-                                                ptrInstance->MixerStream[0].pGeneralPurpose,
-                                                ptrInstance->MixerStream[0].CallbackParam);
+                (*ptrInstance->MixerStream[0].pCallBack)(
+                        ptrInstance->MixerStream[0].pCallbackHandle,
+                        ptrInstance->MixerStream[0].pGeneralPurpose,
+                        ptrInstance->MixerStream[0].CallbackParam);
             }
         }
     }
 }
 
-#endif
-
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_2St_D16C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_2St_D16C31_SAT.cpp
index 54ab79d..882a8ce 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_2St_D16C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_MixSoft_2St_D16C31_SAT.cpp
@@ -25,49 +25,39 @@
 /**********************************************************************************
    FUNCTION LVC_MixSoft_2St_D16C31_SAT.c
 ***********************************************************************************/
-void LVC_MixSoft_2St_D16C31_SAT(LVMixer3_2St_FLOAT_st *ptrInstance,
-                                const LVM_FLOAT       *src1,
-                                const LVM_FLOAT       *src2,
-                                      LVM_FLOAT       *dst,
-                                      LVM_INT16       n)
-{
-    Mix_Private_FLOAT_st  *pInstance1 = \
-                             (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[0].PrivateParams);
-    Mix_Private_FLOAT_st  *pInstance2 = \
-                             (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[1].PrivateParams);
+void LVC_MixSoft_2St_D16C31_SAT(LVMixer3_2St_FLOAT_st* ptrInstance, const LVM_FLOAT* src1,
+                                const LVM_FLOAT* src2, LVM_FLOAT* dst, LVM_INT16 n) {
+    Mix_Private_FLOAT_st* pInstance1 =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[0].PrivateParams);
+    Mix_Private_FLOAT_st* pInstance2 =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[1].PrivateParams);
 
-    if(n <= 0)    return;
+    if (n <= 0) return;
 
     /******************************************************************************
        SOFT MIXING
     *******************************************************************************/
-    if ((pInstance1->Current == pInstance1->Target) && (pInstance1->Current == 0)){
-        LVC_MixSoft_1St_D16C31_SAT((LVMixer3_1St_FLOAT_st *)(&ptrInstance->MixerStream[1]),
-                                    src2, dst, n);
-    }
-    else if ((pInstance2->Current == pInstance2->Target) && (pInstance2->Current == 0)){
-        LVC_MixSoft_1St_D16C31_SAT((LVMixer3_1St_FLOAT_st *)(&ptrInstance->MixerStream[0]),
-                                    src1, dst, n);
-    }
-    else if ((pInstance1->Current != pInstance1->Target) || \
-                                    (pInstance2->Current != pInstance2->Target))
-    {
-        LVC_MixSoft_1St_D16C31_SAT((LVMixer3_1St_FLOAT_st *)(&ptrInstance->MixerStream[0]),
-                                   src1, dst, n);
-        LVC_MixInSoft_D16C31_SAT((LVMixer3_1St_FLOAT_st *)(&ptrInstance->MixerStream[1]),
-                                  src2, dst, n);
-    }
-    else{
+    if ((pInstance1->Current == pInstance1->Target) && (pInstance1->Current == 0)) {
+        LVC_MixSoft_1St_D16C31_SAT((LVMixer3_1St_FLOAT_st*)(&ptrInstance->MixerStream[1]), src2,
+                                   dst, n);
+    } else if ((pInstance2->Current == pInstance2->Target) && (pInstance2->Current == 0)) {
+        LVC_MixSoft_1St_D16C31_SAT((LVMixer3_1St_FLOAT_st*)(&ptrInstance->MixerStream[0]), src1,
+                                   dst, n);
+    } else if ((pInstance1->Current != pInstance1->Target) ||
+               (pInstance2->Current != pInstance2->Target)) {
+        LVC_MixSoft_1St_D16C31_SAT((LVMixer3_1St_FLOAT_st*)(&ptrInstance->MixerStream[0]), src1,
+                                   dst, n);
+        LVC_MixInSoft_D16C31_SAT((LVMixer3_1St_FLOAT_st*)(&ptrInstance->MixerStream[1]), src2, dst,
+                                 n);
+    } else {
         /******************************************************************************
            HARD MIXING
         *******************************************************************************/
-        LVC_Core_MixHard_2St_D16C31_SAT( &ptrInstance->MixerStream[0],
-                                         &ptrInstance->MixerStream[1],
-                                         src1, src2, dst, n);
+        LVC_Core_MixHard_2St_D16C31_SAT(&ptrInstance->MixerStream[0], &ptrInstance->MixerStream[1],
+                                        src1, src2, dst, n);
     }
 }
 
-#ifdef SUPPORT_MC
 /*
  * FUNCTION:       LVC_MixSoft_2Mc_D16C31_SAT
  *
@@ -86,48 +76,38 @@
  *  void
  *
  */
-void LVC_MixSoft_2Mc_D16C31_SAT(LVMixer3_2St_FLOAT_st *ptrInstance,
-                                const LVM_FLOAT       *src1,
-                                const LVM_FLOAT       *src2,
-                                      LVM_FLOAT       *dst,
-                                      LVM_INT16       NrFrames,
-                                      LVM_INT16       NrChannels)
-{
-    Mix_Private_FLOAT_st  *pInstance1 = \
-                             (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[0].PrivateParams);
-    Mix_Private_FLOAT_st  *pInstance2 = \
-                             (Mix_Private_FLOAT_st *)(ptrInstance->MixerStream[1].PrivateParams);
+void LVC_MixSoft_2Mc_D16C31_SAT(LVMixer3_2St_FLOAT_st* ptrInstance, const LVM_FLOAT* src1,
+                                const LVM_FLOAT* src2, LVM_FLOAT* dst, LVM_INT16 NrFrames,
+                                LVM_INT16 NrChannels) {
+    Mix_Private_FLOAT_st* pInstance1 =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[0].PrivateParams);
+    Mix_Private_FLOAT_st* pInstance2 =
+            (Mix_Private_FLOAT_st*)(ptrInstance->MixerStream[1].PrivateParams);
 
-    if (NrFrames <= 0)    return;
+    if (NrFrames <= 0) return;
 
     /******************************************************************************
        SOFT MIXING
     *******************************************************************************/
     if ((pInstance1->Current == pInstance1->Target) && (pInstance1->Current == 0)) {
-        LVC_MixSoft_Mc_D16C31_SAT((LVMixer3_1St_FLOAT_st *)(&ptrInstance->MixerStream[1]),
-                                    src2, dst, NrFrames, NrChannels);
-    }
-    else if ((pInstance2->Current == pInstance2->Target) && (pInstance2->Current == 0)) {
-        LVC_MixSoft_Mc_D16C31_SAT((LVMixer3_1St_FLOAT_st *)(&ptrInstance->MixerStream[0]),
-                                    src1, dst, NrFrames, NrChannels);
-    }
-    else if ((pInstance1->Current != pInstance1->Target) || \
-                                    (pInstance2->Current != pInstance2->Target))
-    {
-        LVC_MixSoft_Mc_D16C31_SAT((LVMixer3_1St_FLOAT_st *)(&ptrInstance->MixerStream[0]),
-                                   src1, dst, NrFrames, NrChannels);
-        LVC_MixInSoft_Mc_D16C31_SAT((LVMixer3_1St_FLOAT_st *)(&ptrInstance->MixerStream[1]),
-                                   src2, dst, NrFrames, NrChannels);
-    }
-    else{
+        LVC_MixSoft_Mc_D16C31_SAT((LVMixer3_1St_FLOAT_st*)(&ptrInstance->MixerStream[1]), src2, dst,
+                                  NrFrames, NrChannels);
+    } else if ((pInstance2->Current == pInstance2->Target) && (pInstance2->Current == 0)) {
+        LVC_MixSoft_Mc_D16C31_SAT((LVMixer3_1St_FLOAT_st*)(&ptrInstance->MixerStream[0]), src1, dst,
+                                  NrFrames, NrChannels);
+    } else if ((pInstance1->Current != pInstance1->Target) ||
+               (pInstance2->Current != pInstance2->Target)) {
+        LVC_MixSoft_Mc_D16C31_SAT((LVMixer3_1St_FLOAT_st*)(&ptrInstance->MixerStream[0]), src1, dst,
+                                  NrFrames, NrChannels);
+        LVC_MixInSoft_Mc_D16C31_SAT((LVMixer3_1St_FLOAT_st*)(&ptrInstance->MixerStream[1]), src2,
+                                    dst, NrFrames, NrChannels);
+    } else {
         /******************************************************************************
            HARD MIXING
         *******************************************************************************/
-        LVC_Core_MixHard_2St_D16C31_SAT(&ptrInstance->MixerStream[0],
-                                        &ptrInstance->MixerStream[1],
+        LVC_Core_MixHard_2St_D16C31_SAT(&ptrInstance->MixerStream[0], &ptrInstance->MixerStream[1],
                                         src1, src2, dst, NrFrames * NrChannels);
     }
 }
-#endif
 
 /**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Mixer.h b/media/libeffects/lvm/lib/Common/src/LVC_Mixer.h
index ce42d2e..1eb2dea 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Mixer.h
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Mixer.h
@@ -25,34 +25,31 @@
 ***********************************************************************************/
 
 /* LVMixer3_st structure stores Instance parameters for one audio stream */
-typedef struct
-{
-    LVM_FLOAT       PrivateParams[3];   /* Private Instance params for \
-                                           Audio Stream shift parameter */
-    LVM_INT16       CallbackSet;        /* Boolean.  Should be set by calling application \
-                                           each time the target value is updated */
-    LVM_INT16       CallbackParam;      /* Parameter that will be used in the calback function */
-    void            *pCallbackHandle;   /* Pointer to the instance of the callback function */
-    void            *pGeneralPurpose;   /* Pointer for general purpose usage */
-    LVM_Callback    pCallBack;          /* Pointer to the callback function */
+typedef struct {
+    LVM_FLOAT PrivateParams[3]; /* Private Instance params for \
+                                   Audio Stream shift parameter */
+    LVM_INT16 CallbackSet;      /* Boolean.  Should be set by calling application \
+                                   each time the target value is updated */
+    LVM_INT16 CallbackParam;    /* Parameter that will be used in the calback function */
+    void* pCallbackHandle;      /* Pointer to the instance of the callback function */
+    void* pGeneralPurpose;      /* Pointer for general purpose usage */
+    LVM_Callback pCallBack;     /* Pointer to the callback function */
 } LVMixer3_FLOAT_st;
-typedef struct
-{
-    LVMixer3_FLOAT_st     MixerStream[1];    /* Instance Params for one Audio Stream */
+typedef struct {
+    LVMixer3_FLOAT_st MixerStream[1]; /* Instance Params for one Audio Stream */
 } LVMixer3_1St_FLOAT_st;
-typedef struct
-{
-    LVMixer3_FLOAT_st     MixerStream[2];    /* Instance Params for two Audio Streams */
+typedef struct {
+    LVMixer3_FLOAT_st MixerStream[2]; /* Instance Params for two Audio Streams */
 } LVMixer3_2St_FLOAT_st;
 /**********************************************************************************
    FUNCTION PROTOTYPES (HIGH LEVEL FUNCTIONS)
 ***********************************************************************************/
 
 /* Function names should be unique within first 16 characters  */
-#define    LVMixer3_MixSoft_1St_D16C31_SAT   LVMixer3_1St_D16C31_SAT_MixSoft
-#define    LVMixer3_MixInSoft_D16C31_SAT     LVMixer3_D16C31_SAT_MixInSoft
-#define    LVMixer3_MixSoft_2St_D16C31_SAT   LVMixer3_2St_D16C31_SAT_MixSoft
-#define    LVMixer3_MixSoft_3St_D16C31_SAT   LVMixer3_3St_D16C31_SAT_MixSoft
+#define LVMixer3_MixSoft_1St_D16C31_SAT LVMixer3_1St_D16C31_SAT_MixSoft
+#define LVMixer3_MixInSoft_D16C31_SAT LVMixer3_D16C31_SAT_MixInSoft
+#define LVMixer3_MixSoft_2St_D16C31_SAT LVMixer3_2St_D16C31_SAT_MixSoft
+#define LVMixer3_MixSoft_3St_D16C31_SAT LVMixer3_3St_D16C31_SAT_MixSoft
 
 /*** General functions ************************************************************/
 
@@ -62,85 +59,49 @@
 /* then the calculation will give an incorrect value for alpha, see the mixer     */
 /* documentation for further details.                                             */
 /* ********************************************************************************/
-void LVC_Mixer_SetTarget( LVMixer3_FLOAT_st *pStream,
-                          LVM_FLOAT        TargetGain);
-LVM_FLOAT LVC_Mixer_GetTarget( LVMixer3_FLOAT_st *pStream);
+void LVC_Mixer_SetTarget(LVMixer3_FLOAT_st* pStream, LVM_FLOAT TargetGain);
+LVM_FLOAT LVC_Mixer_GetTarget(LVMixer3_FLOAT_st* pStream);
 
-LVM_FLOAT LVC_Mixer_GetCurrent( LVMixer3_FLOAT_st *pStream);
+LVM_FLOAT LVC_Mixer_GetCurrent(LVMixer3_FLOAT_st* pStream);
 
-void LVC_Mixer_Init( LVMixer3_FLOAT_st *pStream,
-                     LVM_FLOAT           TargetGain,
-                     LVM_FLOAT           CurrentGain);
+void LVC_Mixer_Init(LVMixer3_FLOAT_st* pStream, LVM_FLOAT TargetGain, LVM_FLOAT CurrentGain);
 
-void LVC_Mixer_SetTimeConstant( LVMixer3_FLOAT_st *pStream,
-                                LVM_INT32           Tc_millisec,
-                                LVM_Fs_en           Fs,
-                                LVM_INT16           NumChannels);
+void LVC_Mixer_SetTimeConstant(LVMixer3_FLOAT_st* pStream, LVM_INT32 Tc_millisec, LVM_Fs_en Fs,
+                               LVM_INT16 NumChannels);
 
-void LVC_Mixer_VarSlope_SetTimeConstant( LVMixer3_FLOAT_st *pStream,
-                                         LVM_INT32           Tc_millisec,
-                                         LVM_Fs_en           Fs,
-                                         LVM_INT16           NumChannels);
+void LVC_Mixer_VarSlope_SetTimeConstant(LVMixer3_FLOAT_st* pStream, LVM_INT32 Tc_millisec,
+                                        LVM_Fs_en Fs, LVM_INT16 NumChannels);
 
 /*** 16 bit functions *************************************************************/
 
-void LVC_MixSoft_1St_D16C31_SAT(LVMixer3_1St_FLOAT_st *pInstance,
-                                const LVM_FLOAT       *src,
-                                      LVM_FLOAT       *dst,
-                                      LVM_INT16       n);
-#ifdef SUPPORT_MC
-void LVC_MixSoft_Mc_D16C31_SAT(LVMixer3_1St_FLOAT_st *pInstance,
-                               const LVM_FLOAT       *src,
-                                     LVM_FLOAT       *dst,
-                                     LVM_INT16       NrFrames,
-                                     LVM_INT16       NrChannels);
-#endif
+void LVC_MixSoft_1St_D16C31_SAT(LVMixer3_1St_FLOAT_st* pInstance, const LVM_FLOAT* src,
+                                LVM_FLOAT* dst, LVM_INT16 n);
+void LVC_MixSoft_Mc_D16C31_SAT(LVMixer3_1St_FLOAT_st* pInstance, const LVM_FLOAT* src,
+                               LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels);
 
-void LVC_MixInSoft_D16C31_SAT(LVMixer3_1St_FLOAT_st *pInstance,
-                              const LVM_FLOAT       *src,
-                                    LVM_FLOAT       *dst,
-                                    LVM_INT16       n);
-#ifdef SUPPORT_MC
-void LVC_MixInSoft_Mc_D16C31_SAT(LVMixer3_1St_FLOAT_st *pInstance,
-                                 const LVM_FLOAT       *src,
-                                       LVM_FLOAT       *dst,
-                                       LVM_INT16       NrFrames,
-                                       LVM_INT16       NrChannels);
-#endif
+void LVC_MixInSoft_D16C31_SAT(LVMixer3_1St_FLOAT_st* pInstance, const LVM_FLOAT* src,
+                              LVM_FLOAT* dst, LVM_INT16 n);
+void LVC_MixInSoft_Mc_D16C31_SAT(LVMixer3_1St_FLOAT_st* pInstance, const LVM_FLOAT* src,
+                                 LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels);
 
-void LVC_MixSoft_2St_D16C31_SAT(LVMixer3_2St_FLOAT_st *pInstance,
-                                const LVM_FLOAT       *src1,
-                                const LVM_FLOAT       *src2,
-                                LVM_FLOAT             *dst,  /* dst cannot be equal to src2 */
-                                LVM_INT16             n);
-#ifdef SUPPORT_MC
-void LVC_MixSoft_2Mc_D16C31_SAT(LVMixer3_2St_FLOAT_st *pInstance,
-                                const LVM_FLOAT       *src1,
-                                const LVM_FLOAT       *src2,
-                                LVM_FLOAT             *dst,  /* dst cannot be equal to src2 */
-                                LVM_INT16             NrFrames,
-                                LVM_INT16             NrChannels);
-#endif
+void LVC_MixSoft_2St_D16C31_SAT(LVMixer3_2St_FLOAT_st* pInstance, const LVM_FLOAT* src1,
+                                const LVM_FLOAT* src2,
+                                LVM_FLOAT* dst, /* dst cannot be equal to src2 */
+                                LVM_INT16 n);
+void LVC_MixSoft_2Mc_D16C31_SAT(LVMixer3_2St_FLOAT_st* pInstance, const LVM_FLOAT* src1,
+                                const LVM_FLOAT* src2,
+                                LVM_FLOAT* dst, /* dst cannot be equal to src2 */
+                                LVM_INT16 NrFrames, LVM_INT16 NrChannels);
 /**********************************************************************************/
 /* For applying different gains to Left and right chennals                        */
 /* MixerStream[0] applies to Left channel                                         */
 /* MixerStream[1] applies to Right channel                                        */
 /* Gain values should not be more that 1.0                                        */
 /**********************************************************************************/
-#ifdef SUPPORT_MC
-void LVC_MixSoft_1St_MC_float_SAT(LVMixer3_2St_FLOAT_st *pInstance,
-                                   const   LVM_FLOAT     *src,
-                                   LVM_FLOAT             *dst,   /* dst can be equal to src */
-                                   LVM_INT16             NrFrames,
-                                   LVM_INT32             NrChannels,
-                                   LVM_INT32             ChMask);
-#endif
-void LVC_MixSoft_1St_2i_D16C31_SAT(LVMixer3_2St_FLOAT_st *pInstance,
-                                   const   LVM_FLOAT     *src,
-                                   LVM_FLOAT             *dst,   /* dst can be equal to src */
-                                   LVM_INT16             n);     /* Number of stereo samples */
+void LVC_MixSoft_1St_MC_float_SAT(LVMixer3_2St_FLOAT_st* pInstance, const LVM_FLOAT* src,
+                                  LVM_FLOAT* dst, /* dst can be equal to src */
+                                  LVM_INT16 NrFrames, LVM_INT32 NrChannels, LVM_INT32 ChMask);
 
 /**********************************************************************************/
 
-#endif //#ifndef __LVC_MIXER_H__
-
+#endif  //#ifndef __LVC_MIXER_H__
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_GetCurrent.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_GetCurrent.cpp
index d0b50e6..03de8b0 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_GetCurrent.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_GetCurrent.cpp
@@ -30,10 +30,9 @@
 /*  CurrentGain      - CurrentGain value in Q 16.15 format              */
 /*                                                                      */
 /************************************************************************/
-LVM_FLOAT LVC_Mixer_GetCurrent( LVMixer3_FLOAT_st *pStream)
-{
-    LVM_FLOAT       CurrentGain;
-    Mix_Private_FLOAT_st  *pInstance = (Mix_Private_FLOAT_st *)pStream->PrivateParams;
+LVM_FLOAT LVC_Mixer_GetCurrent(LVMixer3_FLOAT_st* pStream) {
+    LVM_FLOAT CurrentGain;
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)pStream->PrivateParams;
     CurrentGain = pInstance->Current;  // CurrentGain
     return CurrentGain;
 }
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_GetTarget.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_GetTarget.cpp
index 3ae5ba4..21ebac1f 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_GetTarget.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_GetTarget.cpp
@@ -30,10 +30,9 @@
 /*  TargetGain      - TargetGain value in Q 16.15 format                */
 /*                                                                      */
 /************************************************************************/
-LVM_FLOAT LVC_Mixer_GetTarget( LVMixer3_FLOAT_st *pStream)
-{
-    LVM_FLOAT       TargetGain;
-    Mix_Private_FLOAT_st  *pInstance = (Mix_Private_FLOAT_st *)pStream->PrivateParams;
+LVM_FLOAT LVC_Mixer_GetTarget(LVMixer3_FLOAT_st* pStream) {
+    LVM_FLOAT TargetGain;
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)pStream->PrivateParams;
 
     TargetGain = pInstance->Target;  // TargetGain
     return TargetGain;
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_Init.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_Init.cpp
index c9fd344..e37f635 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_Init.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_Init.cpp
@@ -44,14 +44,10 @@
 /*  void                                                                */
 /*                                                                      */
 /************************************************************************/
-void LVC_Mixer_Init( LVMixer3_FLOAT_st *pStream,
-                     LVM_FLOAT           TargetGain,
-                     LVM_FLOAT           CurrentGain)
-{
+void LVC_Mixer_Init(LVMixer3_FLOAT_st* pStream, LVM_FLOAT TargetGain, LVM_FLOAT CurrentGain) {
     LVM_FLOAT MaxGain = TargetGain;
-    Mix_Private_FLOAT_st *pInstance = (Mix_Private_FLOAT_st *)pStream->PrivateParams;
-    if(CurrentGain > MaxGain)
-        MaxGain = CurrentGain;
-    pInstance->Target = TargetGain;   // Update fractional gain Target
-    pInstance->Current = CurrentGain; // Update fractional gain Current
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)pStream->PrivateParams;
+    if (CurrentGain > MaxGain) MaxGain = CurrentGain;
+    pInstance->Target = TargetGain;    // Update fractional gain Target
+    pInstance->Current = CurrentGain;  // Update fractional gain Current
 }
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_Private.h b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_Private.h
index 123d22b..9206fae 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_Private.h
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_Private.h
@@ -26,54 +26,36 @@
 #include "VectorArithmetic.h"
 
 /* Instance parameter structure */
-typedef struct
-{
+typedef struct {
     /* General */
-    LVM_FLOAT                       Target;           /*number specifying value of Target Gain */
-    LVM_FLOAT                       Current;          /*number specifying value of Current Gain */
-    LVM_FLOAT                       Delta;            /*number specifying value of Delta Gain */
+    LVM_FLOAT Target;  /*number specifying value of Target Gain */
+    LVM_FLOAT Current; /*number specifying value of Current Gain */
+    LVM_FLOAT Delta;   /*number specifying value of Delta Gain */
 } Mix_Private_FLOAT_st;
 
 /**********************************************************************************
    DEFINITIONS
 ***********************************************************************************/
-#define LVCore_MixInSoft_D32C31_SAT    LVCore_InSoft_D32C31_SAT
-#define LVCore_MixSoft_1St_D32C31_WRA  LVCore_Soft_1St_D32C31_WRA
-#define LVCore_MixHard_2St_D32C31_SAT  LVCore_Hard_2St_D32C31_SAT
+#define LVCore_MixInSoft_D32C31_SAT LVCore_InSoft_D32C31_SAT
+#define LVCore_MixSoft_1St_D32C31_WRA LVCore_Soft_1St_D32C31_WRA
+#define LVCore_MixHard_2St_D32C31_SAT LVCore_Hard_2St_D32C31_SAT
 
 /**********************************************************************************
    FUNCTION PROTOTYPES (LOW LEVEL SUBFUNCTIONS)
 ***********************************************************************************/
 
 /*** 16 bit functions *************************************************************/
-void LVC_Core_MixInSoft_D16C31_SAT( LVMixer3_FLOAT_st *ptrInstance,
-                                    const LVM_FLOAT     *src,
-                                    LVM_FLOAT     *dst,
-                                    LVM_INT16     n);
-#ifdef SUPPORT_MC
-void LVC_Core_MixInSoft_Mc_D16C31_SAT(LVMixer3_FLOAT_st *ptrInstance,
-                                    const LVM_FLOAT     *src,
-                                          LVM_FLOAT     *dst,
-                                          LVM_INT16     NrFrames,
-                                          LVM_INT16     NrChannels);
-#endif
-void LVC_Core_MixSoft_1St_D16C31_WRA( LVMixer3_FLOAT_st *ptrInstance,
-                                      const LVM_FLOAT     *src,
-                                      LVM_FLOAT     *dst,
-                                      LVM_INT16     n);
-#ifdef SUPPORT_MC
-void LVC_Core_MixSoft_Mc_D16C31_WRA(LVMixer3_FLOAT_st *ptrInstance,
-                                    const LVM_FLOAT     *src,
-                                          LVM_FLOAT     *dst,
-                                          LVM_INT16     NrFrames,
-                                          LVM_INT16     NrChannels);
-#endif
-void LVC_Core_MixHard_2St_D16C31_SAT( LVMixer3_FLOAT_st *pInstance1,
-                                      LVMixer3_FLOAT_st         *pInstance2,
-                                      const LVM_FLOAT     *src1,
-                                      const LVM_FLOAT     *src2,
-                                      LVM_FLOAT     *dst,
-                                      LVM_INT16     n);
+void LVC_Core_MixInSoft_D16C31_SAT(LVMixer3_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                   LVM_FLOAT* dst, LVM_INT16 n);
+void LVC_Core_MixInSoft_Mc_D16C31_SAT(LVMixer3_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                      LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels);
+void LVC_Core_MixSoft_1St_D16C31_WRA(LVMixer3_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                     LVM_FLOAT* dst, LVM_INT16 n);
+void LVC_Core_MixSoft_Mc_D16C31_WRA(LVMixer3_FLOAT_st* ptrInstance, const LVM_FLOAT* src,
+                                    LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels);
+void LVC_Core_MixHard_2St_D16C31_SAT(LVMixer3_FLOAT_st* pInstance1, LVMixer3_FLOAT_st* pInstance2,
+                                     const LVM_FLOAT* src1, const LVM_FLOAT* src2, LVM_FLOAT* dst,
+                                     LVM_INT16 n);
 
 /**********************************************************************************/
 /* For applying different gains to Left and right chennals                        */
@@ -81,18 +63,8 @@
 /* ptrInstance2 applies to Right channel                                          */
 /* Gain values should not be more that 1.0                                        */
 /**********************************************************************************/
-#ifdef SUPPORT_MC
-void LVC_Core_MixSoft_1St_MC_float_WRA(Mix_Private_FLOAT_st **ptrInstance,
-                                         const LVM_FLOAT      *src,
-                                         LVM_FLOAT            *dst,
-                                         LVM_INT16            NrFrames,
-                                         LVM_INT16            NrChannels);
-#endif
-void LVC_Core_MixSoft_1St_2i_D16C31_WRA( LVMixer3_FLOAT_st        *ptrInstance1,
-                                         LVMixer3_FLOAT_st        *ptrInstance2,
-                                         const LVM_FLOAT    *src,
-                                         LVM_FLOAT          *dst,
-                                         LVM_INT16          n);
+void LVC_Core_MixSoft_1St_MC_float_WRA(Mix_Private_FLOAT_st** ptrInstance, const LVM_FLOAT* src,
+                                       LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels);
 
 /**********************************************************************************/
 /* For applying different gains to Left and right chennals                        */
@@ -100,21 +72,7 @@
 /* ptrInstance2 applies to Right channel                                          */
 /* Gain values should not be more that 1.0                                        */
 /**********************************************************************************/
-#ifdef SUPPORT_MC
-void LVC_Core_MixHard_1St_MC_float_SAT(Mix_Private_FLOAT_st **ptrInstance,
-                                         const LVM_FLOAT      *src,
-                                         LVM_FLOAT            *dst,
-                                         LVM_INT16            NrFrames,
-                                         LVM_INT16            NrChannels);
-#endif
-void LVC_Core_MixHard_1St_2i_D16C31_SAT( LVMixer3_FLOAT_st        *ptrInstance1,
-                                         LVMixer3_FLOAT_st        *ptrInstance2,
-                                         const LVM_FLOAT    *src,
-                                         LVM_FLOAT          *dst,
-                                         LVM_INT16          n);
+void LVC_Core_MixHard_1St_MC_float_SAT(Mix_Private_FLOAT_st** ptrInstance, const LVM_FLOAT* src,
+                                       LVM_FLOAT* dst, LVM_INT16 NrFrames, LVM_INT16 NrChannels);
 
-/*** 32 bit functions *************************************************************/
-/**********************************************************************************/
-
-#endif //#ifndef __LVC_MIXER_PRIVATE_H__
-
+#endif  //#ifndef __LVC_MIXER_PRIVATE_H__
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_SetTarget.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_SetTarget.cpp
index 47b0cec..d8015c4 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_SetTarget.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_SetTarget.cpp
@@ -43,9 +43,7 @@
 /*  void                                                                */
 /*                                                                      */
 /************************************************************************/
-void LVC_Mixer_SetTarget(LVMixer3_FLOAT_st *pStream,
-                         LVM_FLOAT         TargetGain)
-{
-    Mix_Private_FLOAT_st *pInstance = (Mix_Private_FLOAT_st *)pStream->PrivateParams;
-    pInstance->Target = TargetGain;               // Update gain Target
+void LVC_Mixer_SetTarget(LVMixer3_FLOAT_st* pStream, LVM_FLOAT TargetGain) {
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)pStream->PrivateParams;
+    pInstance->Target = TargetGain;  // Update gain Target
 }
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_SetTimeConstant.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_SetTimeConstant.cpp
index 1a8da7a..715b908 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_SetTimeConstant.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_SetTimeConstant.cpp
@@ -44,36 +44,33 @@
 /* RETURNS:                                                             */
 /*  void                                                                */
 /************************************************************************/
-void LVC_Mixer_SetTimeConstant(LVMixer3_FLOAT_st *pStream,
-                               LVM_INT32           Tc_millisec,
-                               LVM_Fs_en           Fs,
-                               LVM_INT16           NumChannels)
-{
-    LVM_FLOAT   DeltaTable[13] = {0.500000f,/*8000*/
-                                  0.362812f,/*11025*/
-                                  0.333333f,/*12000*/
-                                  0.250000f,/*16000*/
-                                  0.181406f,/*22050*/
-                                  0.166666f,/*24000*/
-                                  0.125000f,/*32000*/
-                                  0.090703f,/*44100*/
-                                  0.083333f,/*48000*/
-                                  0.045352f,/*88200*/
-                                  0.041667f,/*96000*/
-                                  0.022676f,/*176400*/
-                                  0.020833f};/*192000*/
+void LVC_Mixer_SetTimeConstant(LVMixer3_FLOAT_st* pStream, LVM_INT32 Tc_millisec, LVM_Fs_en Fs,
+                               LVM_INT16 NumChannels) {
+    LVM_FLOAT DeltaTable[13] = {0.500000f,  /*8000*/
+                                0.362812f,  /*11025*/
+                                0.333333f,  /*12000*/
+                                0.250000f,  /*16000*/
+                                0.181406f,  /*22050*/
+                                0.166666f,  /*24000*/
+                                0.125000f,  /*32000*/
+                                0.090703f,  /*44100*/
+                                0.083333f,  /*48000*/
+                                0.045352f,  /*88200*/
+                                0.041667f,  /*96000*/
+                                0.022676f,  /*176400*/
+                                0.020833f}; /*192000*/
 
-    Mix_Private_FLOAT_st *pInstance = (Mix_Private_FLOAT_st *)pStream->PrivateParams;
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)pStream->PrivateParams;
     LVM_FLOAT Delta = DeltaTable[Fs];
     Delta = Delta / (NumChannels);
 
-    if(Tc_millisec == 0)
+    if (Tc_millisec == 0)
         Delta = 1.000000f;
     else
         Delta = Delta / Tc_millisec;
 
-    if(Delta == 0)
-        Delta = 0.0000000005f;  /* If Time Constant is so large that Delta is 0, \
-                                  assign minimum value to Delta */
+    if (Delta == 0)
+        Delta = 0.0000000005f; /* If Time Constant is so large that Delta is 0, \
+                                 assign minimum value to Delta */
     pInstance->Delta = Delta;  // Delta=(2147483647*4*1000)/(NumChannels*SampleRate*Tc_millisec)
 }
diff --git a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_VarSlope_SetTimeConstant.cpp b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_VarSlope_SetTimeConstant.cpp
index f335a1e..cf84613 100644
--- a/media/libeffects/lvm/lib/Common/src/LVC_Mixer_VarSlope_SetTimeConstant.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVC_Mixer_VarSlope_SetTimeConstant.cpp
@@ -44,57 +44,50 @@
 /* RETURNS:                                                             */
 /*  void                                                                */
 /************************************************************************/
-void LVC_Mixer_VarSlope_SetTimeConstant( LVMixer3_FLOAT_st *pStream,
-                                         LVM_INT32           Tc_millisec,
-                                         LVM_Fs_en           Fs,
-                                         LVM_INT16           NumChannels)
-{
-     LVM_FLOAT   DeltaTable[13] = {0.500000f,/*8000*/
-                                   0.362812f,/*11025*/
-                                   0.333333f,/*12000*/
-                                   0.250000f,/*16000*/
-                                   0.181406f,/*22050*/
-                                   0.166666f,/*24000*/
-                                   0.125000f,/*32000*/
-                                   0.090703f,/*44100*/
-                                   0.083333f,/*48000*/
-                                   0.045352f,/*88200*/
-                                   0.041666f,/*96000*/
-                                   0.022676f,/*176400*/
-                                   0.020833f};/*192000*/
+void LVC_Mixer_VarSlope_SetTimeConstant(LVMixer3_FLOAT_st* pStream, LVM_INT32 Tc_millisec,
+                                        LVM_Fs_en Fs, LVM_INT16 NumChannels) {
+    LVM_FLOAT DeltaTable[13] = {0.500000f,  /*8000*/
+                                0.362812f,  /*11025*/
+                                0.333333f,  /*12000*/
+                                0.250000f,  /*16000*/
+                                0.181406f,  /*22050*/
+                                0.166666f,  /*24000*/
+                                0.125000f,  /*32000*/
+                                0.090703f,  /*44100*/
+                                0.083333f,  /*48000*/
+                                0.045352f,  /*88200*/
+                                0.041666f,  /*96000*/
+                                0.022676f,  /*176400*/
+                                0.020833f}; /*192000*/
     LVM_FLOAT Tc_millisec_float;
-    Mix_Private_FLOAT_st *pInstance = (Mix_Private_FLOAT_st *)pStream->PrivateParams;
+    Mix_Private_FLOAT_st* pInstance = (Mix_Private_FLOAT_st*)pStream->PrivateParams;
     LVM_FLOAT Delta = DeltaTable[Fs];
 
-    LVM_FLOAT   Current;
-    LVM_FLOAT   Target;
+    LVM_FLOAT Current;
+    LVM_FLOAT Target;
 
-    Delta=Delta / (NumChannels);
+    Delta = Delta / (NumChannels);
 
     /*  Get gain values  */
     Current = pInstance->Current;
     Target = pInstance->Target;
 
-    if (Current != Target)
-    {
+    if (Current != Target) {
         Tc_millisec_float = (LVM_FLOAT)(Tc_millisec) / (Current - Target);
-        if (Tc_millisec_float < 0)
-            Tc_millisec_float = -Tc_millisec_float;
+        if (Tc_millisec_float < 0) Tc_millisec_float = -Tc_millisec_float;
 
-        if(Tc_millisec == 0)
+        if (Tc_millisec == 0)
             Delta = 1.000000f;
         else
             Delta = Delta / Tc_millisec_float;
 
-        if(Delta == 0)
+        if (Delta == 0)
             Delta = 0.0000000005f; /* If Time Constant is so large that Delta is 0, \
                                       assign minimum value to Delta */
-    }
-    else
-    {
-        Delta = 0.0000000005f;  /* Minimum value for proper call-backs \
-                             (setting it to zero has some problems, to be corrected) */
+    } else {
+        Delta = 0.0000000005f; /* Minimum value for proper call-backs \
+                            (setting it to zero has some problems, to be corrected) */
     }
 
-    pInstance->Delta = Delta;     // Delta=(2147483647*4*1000)/(NumChannels*SampleRate*Tc_millisec)
+    pInstance->Delta = Delta;  // Delta=(2147483647*4*1000)/(NumChannels*SampleRate*Tc_millisec)
 }
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_FO_HPF.cpp b/media/libeffects/lvm/lib/Common/src/LVM_FO_HPF.cpp
index 2497d29..59095df 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_FO_HPF.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVM_FO_HPF.cpp
@@ -67,31 +67,19 @@
 /* RETURNS:                                                                */
 /*                                                                         */
 /*-------------------------------------------------------------------------*/
-LVM_FLOAT LVM_FO_HPF(   LVM_FLOAT       w,
-                        FO_FLOAT_Coefs_t  *pCoeffs)
-{
-    LVM_FLOAT Y,Coefficients[13] = {-0.999996f,
-                                    0.999801f,
-                                    -0.497824f,
-                                    0.322937f,
-                                    -0.180880f,
-                                    0.087658f,
-                                    -0.032102f,
-                                    0.008163f,
-                                    -0.001252f,
-                                    0.000089f,
-                                    0,
-                                    0,
-                                    0};
-    Y=LVM_Polynomial((LVM_UINT16)9, Coefficients, w);
+LVM_FLOAT LVM_FO_HPF(LVM_FLOAT w, FO_FLOAT_Coefs_t* pCoeffs) {
+    LVM_FLOAT Y, Coefficients[13] = {-0.999996f, 0.999801f,  -0.497824f, 0.322937f,  -0.180880f,
+                                     0.087658f,  -0.032102f, 0.008163f,  -0.001252f, 0.000089f,
+                                     0,          0,          0};
+    Y = LVM_Polynomial((LVM_UINT16)9, Coefficients, w);
 
-    pCoeffs->B1 = -Y;         /* Store -B1 in filter structure instead of B1!*/
-                            /* A0=(1-B1)/2= B1/2 - 0.5*/
-    Y = Y / 2.0f;                 /* A0=Y=B1/2*/
-    Y = Y - 0.5f;         /* A0=Y=(B1/2 - 0.5)*/
+    pCoeffs->B1 = -Y; /* Store -B1 in filter structure instead of B1!*/
+                      /* A0=(1-B1)/2= B1/2 - 0.5*/
+    Y = Y / 2.0f;     /* A0=Y=B1/2*/
+    Y = Y - 0.5f;     /* A0=Y=(B1/2 - 0.5)*/
 
-    pCoeffs->A0 = Y * FILTER_LOSS_FLOAT;                  /* Apply loss to avoid overflow*/
-    pCoeffs->A1 = -pCoeffs->A0;                           /* Store A1=-A0*/
+    pCoeffs->A0 = Y * FILTER_LOSS_FLOAT; /* Apply loss to avoid overflow*/
+    pCoeffs->A1 = -pCoeffs->A0;          /* Store A1=-A0*/
 
     return 1;
 }
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_FO_LPF.cpp b/media/libeffects/lvm/lib/Common/src/LVM_FO_LPF.cpp
index 7bc6046..91964fb 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_FO_LPF.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVM_FO_LPF.cpp
@@ -67,25 +67,15 @@
 /* RETURNS:                                                                */
 /*                                                                         */
 /*-------------------------------------------------------------------------*/
-LVM_FLOAT LVM_FO_LPF(   LVM_FLOAT       w,
-                        FO_FLOAT_Coefs_t  *pCoeffs)
-{
-    LVM_FLOAT Y,Coefficients[13] = {-0.999996f,
-                                    0.999801f,
-                                    -0.497824f,
-                                    0.322937f,
-                                    -0.180880f,
-                                    0.087658f,
-                                    -0.032102f,
-                                    0.008163f,
-                                    -0.001252f,
-                                    0.000089f,
-                                    0};
-    Y=LVM_Polynomial((LVM_UINT16)9, Coefficients, w);
-    pCoeffs->B1 = -Y;     // Store -B1 in filter structure instead of B1!
-                        // A0=(1+B1)/2= B1/2 + 0.5
-    Y = Y / 2.0f;             // A0=Y=B1/2
-    Y = Y + 0.5f;     // A0=Y=(B1/2 + 0.5)
+LVM_FLOAT LVM_FO_LPF(LVM_FLOAT w, FO_FLOAT_Coefs_t* pCoeffs) {
+    LVM_FLOAT Y,
+            Coefficients[13] = {-0.999996f, 0.999801f, -0.497824f, 0.322937f, -0.180880f, 0.087658f,
+                                -0.032102f, 0.008163f, -0.001252f, 0.000089f, 0};
+    Y = LVM_Polynomial((LVM_UINT16)9, Coefficients, w);
+    pCoeffs->B1 = -Y;  // Store -B1 in filter structure instead of B1!
+                       // A0=(1+B1)/2= B1/2 + 0.5
+    Y = Y / 2.0f;      // A0=Y=B1/2
+    Y = Y + 0.5f;      // A0=Y=(B1/2 + 0.5)
 
     pCoeffs->A0 = Y * FILTER_LOSS_FLOAT;
     pCoeffs->A1 = pCoeffs->A0;
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_GetOmega.cpp b/media/libeffects/lvm/lib/Common/src/LVM_GetOmega.cpp
index 2a7cca2..5f25677 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_GetOmega.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVM_GetOmega.cpp
@@ -25,41 +25,32 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#define LVVDL_2PiBy_8000        1727108826  /* In Q41 format */
-#define LVVDL_2PiBy_11025       1253230894  /* In Q41 format */
-#define LVVDL_2PiBy_12000       1151405884  /* In Q41 format */
+#define LVVDL_2PiBy_8000 1727108826  /* In Q41 format */
+#define LVVDL_2PiBy_11025 1253230894 /* In Q41 format */
+#define LVVDL_2PiBy_12000 1151405884 /* In Q41 format */
 
-#define LVVDL_2PiByFs_SHIFT1    12          /* Qformat shift for 8kHz, 11.025kHz and 12kHz i.e. 12=41-29 */
-#define LVVDL_2PiByFs_SHIFT2    13          /* Qformat shift for 16kHz, 22.050kHz and 24kHz i.e. 13=42-29 */
-#define LVVDL_2PiByFs_SHIFT3    14          /* Qformat shift for 32kHz, 44.1kHz and 48kHz i.e. 14=43-29 */
-#define LVVDL_2PiBy_8000_f        0.000785398f
-#define LVVDL_2PiBy_11025_f       0.000569903f
-#define LVVDL_2PiBy_12000_f       0.000523599f
-#define LVVDL_2PiBy_16000_f       0.000392700f
-#define LVVDL_2PiBy_22050_f       0.000284952f
-#define LVVDL_2PiBy_24000_f       0.000261800f
-#define LVVDL_2PiBy_32000_f       0.000196350f
-#define LVVDL_2PiBy_44100_f       0.000142476f
-#define LVVDL_2PiBy_48000_f       0.000130900f
+#define LVVDL_2PiByFs_SHIFT1 12 /* Qformat shift for 8kHz, 11.025kHz and 12kHz i.e. 12=41-29 */
+#define LVVDL_2PiByFs_SHIFT2 13 /* Qformat shift for 16kHz, 22.050kHz and 24kHz i.e. 13=42-29 */
+#define LVVDL_2PiByFs_SHIFT3 14 /* Qformat shift for 32kHz, 44.1kHz and 48kHz i.e. 14=43-29 */
+#define LVVDL_2PiBy_8000_f 0.000785398f
+#define LVVDL_2PiBy_11025_f 0.000569903f
+#define LVVDL_2PiBy_12000_f 0.000523599f
+#define LVVDL_2PiBy_16000_f 0.000392700f
+#define LVVDL_2PiBy_22050_f 0.000284952f
+#define LVVDL_2PiBy_24000_f 0.000261800f
+#define LVVDL_2PiBy_32000_f 0.000196350f
+#define LVVDL_2PiBy_44100_f 0.000142476f
+#define LVVDL_2PiBy_48000_f 0.000130900f
 
-#define LVVDL_2PiBy_88200_f       0.000071238f
-#define LVVDL_2PiBy_96000_f       0.000065450f
-#define LVVDL_2PiBy_176400_f      0.000035619f
-#define LVVDL_2PiBy_192000_f      0.000032725f
-const LVM_FLOAT     LVVDL_2PiOnFsTable[] =  {LVVDL_2PiBy_8000_f,
-                                             LVVDL_2PiBy_11025_f,
-                                             LVVDL_2PiBy_12000_f,
-                                             LVVDL_2PiBy_16000_f,
-                                             LVVDL_2PiBy_22050_f,
-                                             LVVDL_2PiBy_24000_f,
-                                             LVVDL_2PiBy_32000_f,
-                                             LVVDL_2PiBy_44100_f,
-                                             LVVDL_2PiBy_48000_f
-                                            ,LVVDL_2PiBy_88200_f
-                                            ,LVVDL_2PiBy_96000_f
-                                            ,LVVDL_2PiBy_176400_f
-                                            ,LVVDL_2PiBy_192000_f
-                                           };
+#define LVVDL_2PiBy_88200_f 0.000071238f
+#define LVVDL_2PiBy_96000_f 0.000065450f
+#define LVVDL_2PiBy_176400_f 0.000035619f
+#define LVVDL_2PiBy_192000_f 0.000032725f
+const LVM_FLOAT LVVDL_2PiOnFsTable[] = {
+        LVVDL_2PiBy_8000_f,  LVVDL_2PiBy_11025_f, LVVDL_2PiBy_12000_f, LVVDL_2PiBy_16000_f,
+        LVVDL_2PiBy_22050_f, LVVDL_2PiBy_24000_f, LVVDL_2PiBy_32000_f, LVVDL_2PiBy_44100_f,
+        LVVDL_2PiBy_48000_f, LVVDL_2PiBy_88200_f, LVVDL_2PiBy_96000_f, LVVDL_2PiBy_176400_f,
+        LVVDL_2PiBy_192000_f};
 /*-------------------------------------------------------------------------*/
 /* FUNCTION:                                                               */
 /*   LVM_GetOmega                                                          */
@@ -77,10 +68,8 @@
 /* RETURNS:                                                                */
 /*   w=2*pi*Fc/Fs in Q2.29 format                                          */
 /*-------------------------------------------------------------------------*/
-LVM_FLOAT LVM_GetOmega(LVM_UINT32                  Fc,
-                       LVM_Fs_en                   Fs)
-{
-    LVM_FLOAT   w;
+LVM_FLOAT LVM_GetOmega(LVM_UINT32 Fc, LVM_Fs_en Fs) {
+    LVM_FLOAT w;
     w = (LVM_FLOAT)Fc * LVVDL_2PiOnFsTable[Fs];
     return w;
 }
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_Mixer_FilterCoeffs.h b/media/libeffects/lvm/lib/Common/src/LVM_Mixer_FilterCoeffs.h
index 244f09d..31dcaa4 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_Mixer_FilterCoeffs.h
+++ b/media/libeffects/lvm/lib/Common/src/LVM_Mixer_FilterCoeffs.h
@@ -33,109 +33,109 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#define Alpha_TableSize                        50      /* The number of table entires */
-#define ALPHA_0                        2147480769      /* Floating point Alpha = 0.999999 */
-#define ALPHA_1                        2147479577      /* Floating point Alpha = 0.999998 */
-#define ALPHA_2                        2147477892      /* Floating point Alpha = 0.999997 */
-#define ALPHA_3                        2147475510      /* Floating point Alpha = 0.999996 */
-#define ALPHA_4                        2147472141      /* Floating point Alpha = 0.999995 */
-#define ALPHA_5                        2147467377      /* Floating point Alpha = 0.999992 */
-#define ALPHA_6                        2147460642      /* Floating point Alpha = 0.999989 */
-#define ALPHA_7                        2147451118      /* Floating point Alpha = 0.999985 */
-#define ALPHA_8                        2147437651      /* Floating point Alpha = 0.999979 */
-#define ALPHA_9                        2147418608      /* Floating point Alpha = 0.999970 */
-#define ALPHA_10                       2147391683      /* Floating point Alpha = 0.999957 */
-#define ALPHA_11                       2147353611      /* Floating point Alpha = 0.999939 */
-#define ALPHA_12                       2147299779      /* Floating point Alpha = 0.999914 */
-#define ALPHA_13                       2147223662      /* Floating point Alpha = 0.999879 */
-#define ALPHA_14                       2147116037      /* Floating point Alpha = 0.999829 */
-#define ALPHA_15                       2146963865      /* Floating point Alpha = 0.999758 */
-#define ALPHA_16                       2146748712      /* Floating point Alpha = 0.999658 */
-#define ALPHA_17                       2146444522      /* Floating point Alpha = 0.999516 */
-#define ALPHA_18                       2146014472      /* Floating point Alpha = 0.999316 */
-#define ALPHA_19                       2145406527      /* Floating point Alpha = 0.999033 */
-#define ALPHA_20                       2144547188      /* Floating point Alpha = 0.998633 */
-#define ALPHA_21                       2143332669      /* Floating point Alpha = 0.998067 */
-#define ALPHA_22                       2141616514      /* Floating point Alpha = 0.997268 */
-#define ALPHA_23                       2139192215      /* Floating point Alpha = 0.996139 */
-#define ALPHA_24                       2135768939      /* Floating point Alpha = 0.994545 */
-#define ALPHA_25                       2130937774      /* Floating point Alpha = 0.992295 */
-#define ALPHA_26                       2124125153      /* Floating point Alpha = 0.989123 */
-#define ALPHA_27                       2114529263      /* Floating point Alpha = 0.984654 */
-#define ALPHA_28                       2101034612      /* Floating point Alpha = 0.978370 */
-#define ALPHA_29                       2082100030      /* Floating point Alpha = 0.969553 */
-#define ALPHA_30                       2055617398      /* Floating point Alpha = 0.957221 */
-#define ALPHA_31                       2018744824      /* Floating point Alpha = 0.940051 */
-#define ALPHA_32                       1967733015      /* Floating point Alpha = 0.916297 */
-#define ALPHA_33                       1897794587      /* Floating point Alpha = 0.883729 */
-#define ALPHA_34                       1803123234      /* Floating point Alpha = 0.839645 */
-#define ALPHA_35                       1677262220      /* Floating point Alpha = 0.781036 */
-#define ALPHA_36                       1514142675      /* Floating point Alpha = 0.705078 */
-#define ALPHA_37                       1310197875      /* Floating point Alpha = 0.610108 */
-#define ALPHA_38                       1067813480      /* Floating point Alpha = 0.497239 */
-#define ALPHA_39                        799601371      /* Floating point Alpha = 0.372343 */
-#define ALPHA_40                        531183049      /* Floating point Alpha = 0.247351 */
-#define ALPHA_41                        297904007      /* Floating point Alpha = 0.138722 */
-#define ALPHA_42                        131499768      /* Floating point Alpha = 0.061234 */
-#define ALPHA_43                         41375282      /* Floating point Alpha = 0.019267 */
-#define ALPHA_44                          8065899      /* Floating point Alpha = 0.003756 */
-#define ALPHA_45                           799076      /* Floating point Alpha = 0.000372 */
-#define ALPHA_46                            30398      /* Floating point Alpha = 0.000014 */
-#define ALPHA_47                              299      /* Floating point Alpha = 0.000000 */
-#define ALPHA_48                                0      /* Floating point Alpha = 0.000000 */
-#define ALPHA_49                                0      /* Floating point Alpha = 0.000000 */
-#define ALPHA_50                                0      /* Floating point Alpha = 0.000000 */
+#define Alpha_TableSize 50  /* The number of table entires */
+#define ALPHA_0 2147480769  /* Floating point Alpha = 0.999999 */
+#define ALPHA_1 2147479577  /* Floating point Alpha = 0.999998 */
+#define ALPHA_2 2147477892  /* Floating point Alpha = 0.999997 */
+#define ALPHA_3 2147475510  /* Floating point Alpha = 0.999996 */
+#define ALPHA_4 2147472141  /* Floating point Alpha = 0.999995 */
+#define ALPHA_5 2147467377  /* Floating point Alpha = 0.999992 */
+#define ALPHA_6 2147460642  /* Floating point Alpha = 0.999989 */
+#define ALPHA_7 2147451118  /* Floating point Alpha = 0.999985 */
+#define ALPHA_8 2147437651  /* Floating point Alpha = 0.999979 */
+#define ALPHA_9 2147418608  /* Floating point Alpha = 0.999970 */
+#define ALPHA_10 2147391683 /* Floating point Alpha = 0.999957 */
+#define ALPHA_11 2147353611 /* Floating point Alpha = 0.999939 */
+#define ALPHA_12 2147299779 /* Floating point Alpha = 0.999914 */
+#define ALPHA_13 2147223662 /* Floating point Alpha = 0.999879 */
+#define ALPHA_14 2147116037 /* Floating point Alpha = 0.999829 */
+#define ALPHA_15 2146963865 /* Floating point Alpha = 0.999758 */
+#define ALPHA_16 2146748712 /* Floating point Alpha = 0.999658 */
+#define ALPHA_17 2146444522 /* Floating point Alpha = 0.999516 */
+#define ALPHA_18 2146014472 /* Floating point Alpha = 0.999316 */
+#define ALPHA_19 2145406527 /* Floating point Alpha = 0.999033 */
+#define ALPHA_20 2144547188 /* Floating point Alpha = 0.998633 */
+#define ALPHA_21 2143332669 /* Floating point Alpha = 0.998067 */
+#define ALPHA_22 2141616514 /* Floating point Alpha = 0.997268 */
+#define ALPHA_23 2139192215 /* Floating point Alpha = 0.996139 */
+#define ALPHA_24 2135768939 /* Floating point Alpha = 0.994545 */
+#define ALPHA_25 2130937774 /* Floating point Alpha = 0.992295 */
+#define ALPHA_26 2124125153 /* Floating point Alpha = 0.989123 */
+#define ALPHA_27 2114529263 /* Floating point Alpha = 0.984654 */
+#define ALPHA_28 2101034612 /* Floating point Alpha = 0.978370 */
+#define ALPHA_29 2082100030 /* Floating point Alpha = 0.969553 */
+#define ALPHA_30 2055617398 /* Floating point Alpha = 0.957221 */
+#define ALPHA_31 2018744824 /* Floating point Alpha = 0.940051 */
+#define ALPHA_32 1967733015 /* Floating point Alpha = 0.916297 */
+#define ALPHA_33 1897794587 /* Floating point Alpha = 0.883729 */
+#define ALPHA_34 1803123234 /* Floating point Alpha = 0.839645 */
+#define ALPHA_35 1677262220 /* Floating point Alpha = 0.781036 */
+#define ALPHA_36 1514142675 /* Floating point Alpha = 0.705078 */
+#define ALPHA_37 1310197875 /* Floating point Alpha = 0.610108 */
+#define ALPHA_38 1067813480 /* Floating point Alpha = 0.497239 */
+#define ALPHA_39 799601371  /* Floating point Alpha = 0.372343 */
+#define ALPHA_40 531183049  /* Floating point Alpha = 0.247351 */
+#define ALPHA_41 297904007  /* Floating point Alpha = 0.138722 */
+#define ALPHA_42 131499768  /* Floating point Alpha = 0.061234 */
+#define ALPHA_43 41375282   /* Floating point Alpha = 0.019267 */
+#define ALPHA_44 8065899    /* Floating point Alpha = 0.003756 */
+#define ALPHA_45 799076     /* Floating point Alpha = 0.000372 */
+#define ALPHA_46 30398      /* Floating point Alpha = 0.000014 */
+#define ALPHA_47 299        /* Floating point Alpha = 0.000000 */
+#define ALPHA_48 0          /* Floating point Alpha = 0.000000 */
+#define ALPHA_49 0          /* Floating point Alpha = 0.000000 */
+#define ALPHA_50 0          /* Floating point Alpha = 0.000000 */
 
-#define ALPHA_Float_0                        0.999999f
-#define ALPHA_Float_1                        0.999998f
-#define ALPHA_Float_2                        0.999997f
-#define ALPHA_Float_3                        0.999996f
-#define ALPHA_Float_4                        0.999995f
-#define ALPHA_Float_5                        0.999992f
-#define ALPHA_Float_6                        0.999989f
-#define ALPHA_Float_7                        0.999985f
-#define ALPHA_Float_8                        0.999979f
-#define ALPHA_Float_9                        0.999970f
-#define ALPHA_Float_10                       0.999957f
-#define ALPHA_Float_11                       0.999939f
-#define ALPHA_Float_12                       0.999914f
-#define ALPHA_Float_13                       0.999879f
-#define ALPHA_Float_14                       0.999829f
-#define ALPHA_Float_15                       0.999758f
-#define ALPHA_Float_16                       0.999658f
-#define ALPHA_Float_17                       0.999516f
-#define ALPHA_Float_18                       0.999316f
-#define ALPHA_Float_19                       0.999033f
-#define ALPHA_Float_20                       0.998633f
-#define ALPHA_Float_21                       0.998067f
-#define ALPHA_Float_22                       0.997268f
-#define ALPHA_Float_23                       0.996139f
-#define ALPHA_Float_24                       0.994545f
-#define ALPHA_Float_25                       0.992295f
-#define ALPHA_Float_26                       0.989123f
-#define ALPHA_Float_27                       0.984654f
-#define ALPHA_Float_28                       0.978370f
-#define ALPHA_Float_29                       0.969553f
-#define ALPHA_Float_30                       0.957221f
-#define ALPHA_Float_31                       0.940051f
-#define ALPHA_Float_32                       0.916297f
-#define ALPHA_Float_33                       0.883729f
-#define ALPHA_Float_34                       0.839645f
-#define ALPHA_Float_35                       0.781036f
-#define ALPHA_Float_36                       0.705078f
-#define ALPHA_Float_37                       0.610108f
-#define ALPHA_Float_38                       0.497239f
-#define ALPHA_Float_39                       0.372343f
-#define ALPHA_Float_40                       0.247351f
-#define ALPHA_Float_41                       0.138722f
-#define ALPHA_Float_42                       0.061234f
-#define ALPHA_Float_43                       0.019267f
-#define ALPHA_Float_44                       0.003756f
-#define ALPHA_Float_45                       0.000372f
-#define ALPHA_Float_46                       0.000014f
-#define ALPHA_Float_47                       0.000000f
-#define ALPHA_Float_48                       0.000000f
-#define ALPHA_Float_49                       0.000000f
-#define ALPHA_Float_50                       0.000000f
+#define ALPHA_Float_0 0.999999f
+#define ALPHA_Float_1 0.999998f
+#define ALPHA_Float_2 0.999997f
+#define ALPHA_Float_3 0.999996f
+#define ALPHA_Float_4 0.999995f
+#define ALPHA_Float_5 0.999992f
+#define ALPHA_Float_6 0.999989f
+#define ALPHA_Float_7 0.999985f
+#define ALPHA_Float_8 0.999979f
+#define ALPHA_Float_9 0.999970f
+#define ALPHA_Float_10 0.999957f
+#define ALPHA_Float_11 0.999939f
+#define ALPHA_Float_12 0.999914f
+#define ALPHA_Float_13 0.999879f
+#define ALPHA_Float_14 0.999829f
+#define ALPHA_Float_15 0.999758f
+#define ALPHA_Float_16 0.999658f
+#define ALPHA_Float_17 0.999516f
+#define ALPHA_Float_18 0.999316f
+#define ALPHA_Float_19 0.999033f
+#define ALPHA_Float_20 0.998633f
+#define ALPHA_Float_21 0.998067f
+#define ALPHA_Float_22 0.997268f
+#define ALPHA_Float_23 0.996139f
+#define ALPHA_Float_24 0.994545f
+#define ALPHA_Float_25 0.992295f
+#define ALPHA_Float_26 0.989123f
+#define ALPHA_Float_27 0.984654f
+#define ALPHA_Float_28 0.978370f
+#define ALPHA_Float_29 0.969553f
+#define ALPHA_Float_30 0.957221f
+#define ALPHA_Float_31 0.940051f
+#define ALPHA_Float_32 0.916297f
+#define ALPHA_Float_33 0.883729f
+#define ALPHA_Float_34 0.839645f
+#define ALPHA_Float_35 0.781036f
+#define ALPHA_Float_36 0.705078f
+#define ALPHA_Float_37 0.610108f
+#define ALPHA_Float_38 0.497239f
+#define ALPHA_Float_39 0.372343f
+#define ALPHA_Float_40 0.247351f
+#define ALPHA_Float_41 0.138722f
+#define ALPHA_Float_42 0.061234f
+#define ALPHA_Float_43 0.019267f
+#define ALPHA_Float_44 0.003756f
+#define ALPHA_Float_45 0.000372f
+#define ALPHA_Float_46 0.000014f
+#define ALPHA_Float_47 0.000000f
+#define ALPHA_Float_48 0.000000f
+#define ALPHA_Float_49 0.000000f
+#define ALPHA_Float_50 0.000000f
 
 #endif
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_Mixer_TimeConstant.cpp b/media/libeffects/lvm/lib/Common/src/LVM_Mixer_TimeConstant.cpp
index 73da2cf..3ec103a 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_Mixer_TimeConstant.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVM_Mixer_TimeConstant.cpp
@@ -56,83 +56,37 @@
 /*  Alpha   - the filter coefficient Q31 format                         */
 /*                                                                      */
 /************************************************************************/
-LVM_FLOAT LVM_Mixer_TimeConstant(LVM_UINT32   tc,
-                                  LVM_UINT32   Fs,
-                                  LVM_UINT16   NumChannels)
-{
-
-    LVM_UINT32  Product;
-    LVM_FLOAT  ProductFloat;
-    LVM_INT16   InterpolateShort;
-    LVM_FLOAT   Interpolate;
-    LVM_UINT16  Shift;
-    LVM_FLOAT   Diff;
-    LVM_FLOAT  Table[] = {ALPHA_Float_0,             /* Log spaced look-up table */
-                          ALPHA_Float_1,
-                          ALPHA_Float_2,
-                          ALPHA_Float_3,
-                          ALPHA_Float_4,
-                          ALPHA_Float_5,
-                          ALPHA_Float_6,
-                          ALPHA_Float_7,
-                          ALPHA_Float_8,
-                          ALPHA_Float_9,
-                          ALPHA_Float_10,
-                          ALPHA_Float_11,
-                          ALPHA_Float_12,
-                          ALPHA_Float_13,
-                          ALPHA_Float_14,
-                          ALPHA_Float_15,
-                          ALPHA_Float_16,
-                          ALPHA_Float_17,
-                          ALPHA_Float_18,
-                          ALPHA_Float_19,
-                          ALPHA_Float_20,
-                          ALPHA_Float_21,
-                          ALPHA_Float_22,
-                          ALPHA_Float_23,
-                          ALPHA_Float_24,
-                          ALPHA_Float_25,
-                          ALPHA_Float_26,
-                          ALPHA_Float_27,
-                          ALPHA_Float_28,
-                          ALPHA_Float_29,
-                          ALPHA_Float_30,
-                          ALPHA_Float_31,
-                          ALPHA_Float_32,
-                          ALPHA_Float_33,
-                          ALPHA_Float_34,
-                          ALPHA_Float_35,
-                          ALPHA_Float_36,
-                          ALPHA_Float_37,
-                          ALPHA_Float_38,
-                          ALPHA_Float_39,
-                          ALPHA_Float_40,
-                          ALPHA_Float_41,
-                          ALPHA_Float_42,
-                          ALPHA_Float_43,
-                          ALPHA_Float_44,
-                          ALPHA_Float_45,
-                          ALPHA_Float_46,
-                          ALPHA_Float_47,
-                          ALPHA_Float_48,
-                          ALPHA_Float_49,
-                          ALPHA_Float_50};
+LVM_FLOAT LVM_Mixer_TimeConstant(LVM_UINT32 tc, LVM_UINT32 Fs, LVM_UINT16 NumChannels) {
+    LVM_UINT32 Product;
+    LVM_FLOAT ProductFloat;
+    LVM_INT16 InterpolateShort;
+    LVM_FLOAT Interpolate;
+    LVM_UINT16 Shift;
+    LVM_FLOAT Diff;
+    LVM_FLOAT Table[] = {
+            ALPHA_Float_0, /* Log spaced look-up table */
+            ALPHA_Float_1,  ALPHA_Float_2,  ALPHA_Float_3,  ALPHA_Float_4,  ALPHA_Float_5,
+            ALPHA_Float_6,  ALPHA_Float_7,  ALPHA_Float_8,  ALPHA_Float_9,  ALPHA_Float_10,
+            ALPHA_Float_11, ALPHA_Float_12, ALPHA_Float_13, ALPHA_Float_14, ALPHA_Float_15,
+            ALPHA_Float_16, ALPHA_Float_17, ALPHA_Float_18, ALPHA_Float_19, ALPHA_Float_20,
+            ALPHA_Float_21, ALPHA_Float_22, ALPHA_Float_23, ALPHA_Float_24, ALPHA_Float_25,
+            ALPHA_Float_26, ALPHA_Float_27, ALPHA_Float_28, ALPHA_Float_29, ALPHA_Float_30,
+            ALPHA_Float_31, ALPHA_Float_32, ALPHA_Float_33, ALPHA_Float_34, ALPHA_Float_35,
+            ALPHA_Float_36, ALPHA_Float_37, ALPHA_Float_38, ALPHA_Float_39, ALPHA_Float_40,
+            ALPHA_Float_41, ALPHA_Float_42, ALPHA_Float_43, ALPHA_Float_44, ALPHA_Float_45,
+            ALPHA_Float_46, ALPHA_Float_47, ALPHA_Float_48, ALPHA_Float_49, ALPHA_Float_50};
 
     /* Calculate the product of the time constant and the sample rate */
-    Product = ((tc >> 16) * (LVM_UINT32)Fs) << 13;  /* Stereo value */
+    Product = ((tc >> 16) * (LVM_UINT32)Fs) << 13; /* Stereo value */
     Product = Product + (((tc & 0x0000FFFF) * (LVM_UINT32)Fs) >> 3);
 
-    if (NumChannels == 1)
-    {
-        Product = Product >> 1;   /* Mono value */
+    if (NumChannels == 1) {
+        Product = Product >> 1; /* Mono value */
     }
 
     /* Normalize to get the table index and interpolation factor */
-    for (Shift = 0; Shift < ((Alpha_TableSize - 1) / 2); Shift++)
-    {
-        if ((Product & 0x80000000) != 0)
-        {
+    for (Shift = 0; Shift < ((Alpha_TableSize - 1) / 2); Shift++) {
+        if ((Product & 0x80000000) != 0) {
             break;
         }
 
@@ -140,8 +94,7 @@
     }
     Shift = (LVM_UINT16)((Shift << 1));
 
-    if ((Product & 0x40000000)==0)
-    {
+    if ((Product & 0x40000000) == 0) {
         Shift++;
     }
 
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_Polynomial.cpp b/media/libeffects/lvm/lib/Common/src/LVM_Polynomial.cpp
index 2c3e9ec..8382529 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_Polynomial.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVM_Polynomial.cpp
@@ -40,33 +40,25 @@
 /* RETURNS:                                                                */
 /*   The result of the polynomial expansion in Q1.31 format                */
 /*-------------------------------------------------------------------------*/
-LVM_FLOAT LVM_Polynomial(LVM_UINT16    N,
-                         LVM_FLOAT    *pCoefficients,
-                         LVM_FLOAT    X)
-{
+LVM_FLOAT LVM_Polynomial(LVM_UINT16 N, LVM_FLOAT* pCoefficients, LVM_FLOAT X) {
     LVM_INT32 i;
-    LVM_FLOAT Y,A,XTemp,Temp,sign;
+    LVM_FLOAT Y, A, XTemp, Temp, sign;
 
     Y = *pCoefficients; /* Y=A0*/
     pCoefficients++;
 
-    if(X == -1.0f)
-    {
+    if (X == -1.0f) {
         Temp = -1;
         sign = Temp;
-        for(i = 1; i <= N; i++)
-        {
+        for (i = 1; i <= N; i++) {
             Y += ((*pCoefficients) * sign);
             pCoefficients++;
             sign *= Temp;
         }
 
-    }
-    else
-    {
+    } else {
         XTemp = X;
-        for(i = N-1; i >= 0; i--)
-        {
+        for (i = N - 1; i >= 0; i--) {
             A = *pCoefficients;
             pCoefficients++;
 
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_Power10.cpp b/media/libeffects/lvm/lib/Common/src/LVM_Power10.cpp
index ae8e9d1..85596aa 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_Power10.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVM_Power10.cpp
@@ -53,23 +53,10 @@
 /* RETURNS:                                                                */
 /*   The result of the 10x expansion in Q8.24 format                       */
 /*-------------------------------------------------------------------------*/
-LVM_FLOAT LVM_Power10(LVM_FLOAT     X)
-{
-    LVM_FLOAT Y,Coefficients[13]={0.999906f,
-                                  2.302475f,
-                                  2.652765f,
-                                  2.035494f,
-                                  1.165667f,
-                                  0.537676f,
-                                  0.213192f,
-                                  0.069603f,
-                                  0.016553f,
-                                  0.004373f,
-                                  0.001817f,
-                                  0.000367f,
-                                  0};
-    Y=LVM_Polynomial((LVM_UINT16)11,
-                     Coefficients,
-                     X);
+LVM_FLOAT LVM_Power10(LVM_FLOAT X) {
+    LVM_FLOAT Y, Coefficients[13] = {0.999906f, 2.302475f, 2.652765f, 2.035494f, 1.165667f,
+                                     0.537676f, 0.213192f, 0.069603f, 0.016553f, 0.004373f,
+                                     0.001817f, 0.000367f, 0};
+    Y = LVM_Polynomial((LVM_UINT16)11, Coefficients, X);
     return Y;
 }
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_Timer.cpp b/media/libeffects/lvm/lib/Common/src/LVM_Timer.cpp
index 5995f54..be7c8e4 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_Timer.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVM_Timer.cpp
@@ -26,19 +26,16 @@
 /*  TIMER FUNCTION                                                                      */
 /****************************************************************************************/
 
-void LVM_Timer      (   LVM_Timer_Instance_t       *pInstance,
-                        LVM_INT16                  BlockSize ){
+void LVM_Timer(LVM_Timer_Instance_t* pInstance, LVM_INT16 BlockSize) {
+    LVM_Timer_Instance_Private_t* pInstancePr;
+    pInstancePr = (LVM_Timer_Instance_Private_t*)pInstance;
 
-    LVM_Timer_Instance_Private_t *pInstancePr;
-    pInstancePr = (LVM_Timer_Instance_Private_t *)pInstance;
-
-    if (pInstancePr->TimerArmed){
+    if (pInstancePr->TimerArmed) {
         pInstancePr->RemainingTimeInSamples -= BlockSize;
-        if (pInstancePr->RemainingTimeInSamples <= 0){
+        if (pInstancePr->RemainingTimeInSamples <= 0) {
             pInstancePr->TimerArmed = 0;
-            (*pInstancePr->pCallBack) ( pInstancePr->pCallbackInstance,
-                                        pInstancePr->pCallBackParams,
-                                        pInstancePr->CallBackParam );
+            (*pInstancePr->pCallBack)(pInstancePr->pCallbackInstance, pInstancePr->pCallBackParams,
+                                      pInstancePr->CallBackParam);
         }
     }
 }
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_Timer_Init.cpp b/media/libeffects/lvm/lib/Common/src/LVM_Timer_Init.cpp
index 3015057..bfd6bcf 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_Timer_Init.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LVM_Timer_Init.cpp
@@ -33,20 +33,20 @@
 /*  INIT FUNCTION                                                                       */
 /****************************************************************************************/
 
-void LVM_Timer_Init (   LVM_Timer_Instance_t       *pInstance,
-                        LVM_Timer_Params_t         *pParams     ){
+void LVM_Timer_Init(LVM_Timer_Instance_t* pInstance, LVM_Timer_Params_t* pParams) {
+    LVM_Timer_Instance_Private_t* pInstancePr;
+    pInstancePr = (LVM_Timer_Instance_Private_t*)pInstance;
 
-    LVM_Timer_Instance_Private_t *pInstancePr;
-    pInstancePr = (LVM_Timer_Instance_Private_t *)pInstance;
-
-    pInstancePr->CallBackParam     = pParams->CallBackParam;
-    pInstancePr->pCallBackParams   = (LVM_INT32 *)pParams->pCallBackParams;
+    pInstancePr->CallBackParam = pParams->CallBackParam;
+    pInstancePr->pCallBackParams = (LVM_INT32*)pParams->pCallBackParams;
     pInstancePr->pCallbackInstance = pParams->pCallbackInstance;
-    pInstancePr->pCallBack         = pParams->pCallBack;
-    pInstancePr->TimerArmed        = 1;
+    pInstancePr->pCallBack = pParams->pCallBack;
+    pInstancePr->TimerArmed = 1;
 
-    MUL32x16INTO32(pParams->SamplingRate,OneOverThousandInQ24,pInstancePr->RemainingTimeInSamples,16);  /* (Q0 * Q24) >>16 into Q8*/
-    MUL32x16INTO32(pInstancePr->RemainingTimeInSamples,pParams->TimeInMs,pInstancePr->RemainingTimeInSamples,8);  /* (Q8 * Q0) >>8 into Q0*/
+    MUL32x16INTO32(pParams->SamplingRate, OneOverThousandInQ24, pInstancePr->RemainingTimeInSamples,
+                   16); /* (Q0 * Q24) >>16 into Q8*/
+    MUL32x16INTO32(pInstancePr->RemainingTimeInSamples, pParams->TimeInMs,
+                   pInstancePr->RemainingTimeInSamples, 8); /* (Q8 * Q0) >>8 into Q0*/
 }
 
 /****************************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LVM_Timer_Private.h b/media/libeffects/lvm/lib/Common/src/LVM_Timer_Private.h
index a372b82..3e8aba8 100644
--- a/media/libeffects/lvm/lib/Common/src/LVM_Timer_Private.h
+++ b/media/libeffects/lvm/lib/Common/src/LVM_Timer_Private.h
@@ -24,14 +24,13 @@
 /*  TYPE DEFINITIONS                                                                    */
 /****************************************************************************************/
 
-typedef struct
-{
-    LVM_INT32  RemainingTimeInSamples;
-    LVM_INT32  CallBackParam;
-    LVM_INT32  *pCallBackParams;
-    void  *pCallbackInstance;
-    void  (*pCallBack)(void*,void*,LVM_INT32);
-    LVM_INT16 TimerArmed;                        /* Boolean, true between init and callback */
+typedef struct {
+    LVM_INT32 RemainingTimeInSamples;
+    LVM_INT32 CallBackParam;
+    LVM_INT32* pCallBackParams;
+    void* pCallbackInstance;
+    void (*pCallBack)(void*, void*, LVM_INT32);
+    LVM_INT16 TimerArmed; /* Boolean, true between init and callback */
 
 } LVM_Timer_Instance_Private_t;
 
@@ -39,4 +38,4 @@
 /*  END OF HEADER                                                                       */
 /****************************************************************************************/
 
-#endif  /* LVM_TIMER_PRIVATE_H */
+#endif /* LVM_TIMER_PRIVATE_H */
diff --git a/media/libeffects/lvm/lib/Common/src/LoadConst_16.cpp b/media/libeffects/lvm/lib/Common/src/LoadConst_16.cpp
deleted file mode 100644
index f88ca0e..0000000
--- a/media/libeffects/lvm/lib/Common/src/LoadConst_16.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "VectorArithmetic.h"
-
-/**********************************************************************************
-   FUNCTION LoadConst_16
-***********************************************************************************/
-
-void LoadConst_16(const LVM_INT16 val,
-                  LVM_INT16 *dst,
-                  LVM_INT16 n )
-{
-    LVM_INT16 ii;
-
-    for (ii = n; ii != 0; ii--)
-    {
-        *dst = val;
-        dst++;
-    }
-
-    return;
-}
-
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/LoadConst_32.cpp b/media/libeffects/lvm/lib/Common/src/LoadConst_32.cpp
index c789756..df7a558 100644
--- a/media/libeffects/lvm/lib/Common/src/LoadConst_32.cpp
+++ b/media/libeffects/lvm/lib/Common/src/LoadConst_32.cpp
@@ -24,14 +24,10 @@
 /**********************************************************************************
    FUNCTION LoadConst_32
 ***********************************************************************************/
-void LoadConst_Float(const LVM_FLOAT   val,
-                     LVM_FLOAT  *dst,
-                     LVM_INT16 n )
-{
+void LoadConst_Float(const LVM_FLOAT val, LVM_FLOAT* dst, LVM_INT16 n) {
     LVM_INT16 ii;
 
-    for (ii = n; ii != 0; ii--)
-    {
+    for (ii = n; ii != 0; ii--) {
         *dst = val;
         dst++;
     }
diff --git a/media/libeffects/lvm/lib/Common/src/MSTo2i_Sat_16x16.cpp b/media/libeffects/lvm/lib/Common/src/MSTo2i_Sat_16x16.cpp
index 1ea765a..e5c6f15 100644
--- a/media/libeffects/lvm/lib/Common/src/MSTo2i_Sat_16x16.cpp
+++ b/media/libeffects/lvm/lib/Common/src/MSTo2i_Sat_16x16.cpp
@@ -18,74 +18,14 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
+#include "ScalarArithmetic.h"
 #include "VectorArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION  MSTO2I_SAT_16X16
-***********************************************************************************/
-
-void MSTo2i_Sat_16x16(const LVM_INT16  *srcM,
-                      const LVM_INT16  *srcS,
-                      LVM_INT16  *dst,
-                      LVM_INT16  n )
-{
-    LVM_INT32 temp,mVal,sVal;
+void MSTo2i_Sat_Float(const LVM_FLOAT* srcM, const LVM_FLOAT* srcS, LVM_FLOAT* dst, LVM_INT16 n) {
+    LVM_FLOAT temp, mVal, sVal;
     LVM_INT16 ii;
 
-    for (ii = n; ii != 0; ii--)
-    {
-        mVal=(LVM_INT32)*srcM;
-        srcM++;
-
-        sVal=(LVM_INT32)*srcS;
-        srcS++;
-
-        temp = mVal + sVal;
-
-        if (temp > 0x00007FFF)
-        {
-            *dst = 0x7FFF;
-        }
-        else if (temp < -0x00008000)
-        {
-            *dst = - 0x8000;
-        }
-        else
-        {
-            *dst = (LVM_INT16)temp;
-        }
-        dst++;
-
-        temp = mVal - sVal;
-
-        if (temp > 0x00007FFF)
-        {
-            *dst = 0x7FFF;
-        }
-        else if (temp < -0x00008000)
-        {
-            *dst = - 0x8000;
-        }
-        else
-        {
-            *dst = (LVM_INT16)temp;
-        }
-        dst++;
-    }
-
-    return;
-}
-void MSTo2i_Sat_Float(const LVM_FLOAT  *srcM,
-                      const LVM_FLOAT  *srcS,
-                      LVM_FLOAT  *dst,
-                      LVM_INT16  n )
-{
-    LVM_FLOAT temp,mVal,sVal;
-    LVM_INT16 ii;
-
-    for (ii = n; ii != 0; ii--)
-    {
+    for (ii = n; ii != 0; ii--) {
         mVal = (LVM_FLOAT)*srcM;
         srcM++;
 
@@ -93,38 +33,11 @@
         srcS++;
 
         temp = mVal + sVal;
-
-        if (temp > 1.0f)
-        {
-            *dst = 1.0f;
-        }
-        else if (temp < -1.0f)
-        {
-            *dst = -1.0f;
-        }
-        else
-        {
-            *dst = (LVM_FLOAT)temp;
-        }
-        dst++;
+        *dst++ = LVM_Clamp(temp);
 
         temp = mVal - sVal;
-
-        if (temp > 1.0f)
-        {
-            *dst = 1.0f;
-        }
-        else if (temp < -1.0f)
-        {
-            *dst = - 1.0f;
-        }
-        else
-        {
-            *dst = (LVM_FLOAT)temp;
-        }
-        dst++;
+        *dst++ = LVM_Clamp(temp);
     }
 
     return;
 }
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/Mac3s_Sat_16x16.cpp b/media/libeffects/lvm/lib/Common/src/Mac3s_Sat_16x16.cpp
deleted file mode 100644
index 6584251..0000000
--- a/media/libeffects/lvm/lib/Common/src/Mac3s_Sat_16x16.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-
-     %created_by:    sra % (CM/S)
-     %name:          Mac3s_Sat_16x16.c % (CM/S)
-     %version:       1 % (CM/S)
-     %date_created:  Fri Nov 13 12:07:13 2009 % (CM/S)
-
-***********************************************************************************/
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "VectorArithmetic.h"
-#include "LVM_Macros.h"
-
-/**********************************************************************************
-   FUNCTION Mac3S_16X16
-***********************************************************************************/
-
-void Mac3s_Sat_16x16( const LVM_INT16 *src,
-                     const LVM_INT16 val,
-                     LVM_INT16 *dst,
-                     LVM_INT16 n)
-{
-    LVM_INT16 ii;
-    LVM_INT16 srcval;
-    LVM_INT32 Temp,dInVal;
-
-    for (ii = n; ii != 0; ii--)
-    {
-        srcval=*src;
-        src++;
-
-        Temp = (srcval *val)>>15;
-
-        dInVal  = (LVM_INT32)*dst;
-
-        Temp = Temp + dInVal;
-
-        if (Temp > 0x00007FFF)
-        {
-            *dst = 0x7FFF;
-        }
-        else if (Temp < -0x00008000)
-        {
-            *dst = - 0x8000;
-        }
-        else
-        {
-            *dst = (LVM_INT16)Temp;
-        }
-
-        dst++;
-    }
-
-    return;
-}
-
-/**********************************************************************************/
-
diff --git a/media/libeffects/lvm/lib/Common/src/Mac3s_Sat_32x16.cpp b/media/libeffects/lvm/lib/Common/src/Mac3s_Sat_32x16.cpp
index 5d5564f..24bdf3e 100644
--- a/media/libeffects/lvm/lib/Common/src/Mac3s_Sat_32x16.cpp
+++ b/media/libeffects/lvm/lib/Common/src/Mac3s_Sat_32x16.cpp
@@ -18,85 +18,19 @@
 /**********************************************************************************
    INCLUDE FILES
 ***********************************************************************************/
-
+#include "ScalarArithmetic.h"
 #include "VectorArithmetic.h"
 #include "LVM_Macros.h"
 
-/**********************************************************************************
-   FUNCTION MAC3S_16X16
-***********************************************************************************/
-
-void Mac3s_Sat_32x16(  const LVM_INT32 *src,
-                     const LVM_INT16 val,
-                     LVM_INT32 *dst,
-                     LVM_INT16 n)
-{
+void Mac3s_Sat_Float(const LVM_FLOAT* src, const LVM_FLOAT val, LVM_FLOAT* dst, LVM_INT16 n) {
     LVM_INT16 ii;
-    LVM_INT32 srcval,temp, dInVal, dOutVal;
 
-    for (ii = n; ii != 0; ii--)
-    {
-        srcval=*src;
-        src++;
+    for (ii = n; ii != 0; ii--) {
+        LVM_FLOAT Temp = *src++ * val;
+        Temp += *dst;
 
-        MUL32x16INTO32(srcval,val,temp,15)
-
-            dInVal  = *dst;
-        dOutVal = temp + dInVal;
-
-        if ((((dOutVal ^ temp) & (dOutVal ^ dInVal)) >> 31)!=0)     /* overflow / underflow */
-        {
-            if(temp<0)
-            {
-                dOutVal=0x80000000L;
-            }
-            else
-            {
-                dOutVal=0x7FFFFFFFL;
-            }
-        }
-
-        *dst = dOutVal;
-        dst++;
+        *dst++ = LVM_Clamp(Temp);
     }
 
     return;
 }
-void Mac3s_Sat_Float(const LVM_FLOAT *src,
-                     const LVM_FLOAT val,
-                     LVM_FLOAT *dst,
-                     LVM_INT16 n)
-{
-    LVM_INT16 ii;
-    LVM_FLOAT srcval;
-    LVM_FLOAT Temp,dInVal;
-
-    for (ii = n; ii != 0; ii--)
-    {
-        srcval = *src;
-        src++;
-
-        Temp = srcval * val;
-
-        dInVal  = (LVM_FLOAT)*dst;
-        Temp = Temp + dInVal;
-
-        if (Temp > 1.000000f)
-        {
-            *dst = 1.000000f;
-        }
-        else if (Temp < -1.000000f)
-        {
-            *dst = -1.000000f;
-        }
-        else
-        {
-            *dst = Temp;
-        }
-        dst++;
-    }
-
-    return;
-}
-/**********************************************************************************/
-
diff --git a/media/libeffects/lvm/lib/Common/src/MixInSoft_D32C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/MixInSoft_D32C31_SAT.cpp
index 7c7b36f..9663998 100644
--- a/media/libeffects/lvm/lib/Common/src/MixInSoft_D32C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/MixInSoft_D32C31_SAT.cpp
@@ -26,33 +26,29 @@
    DEFINITIONS
 ***********************************************************************************/
 
-#define TRUE          1
-#define FALSE         0
+#define TRUE 1
+#define FALSE 0
 
 /**********************************************************************************
    FUNCTION MIXINSOFT_D32C31_SAT
 ***********************************************************************************/
-void MixInSoft_D32C31_SAT( Mix_1St_Cll_FLOAT_t        *pInstance,
-                           const LVM_FLOAT      *src,
-                           LVM_FLOAT      *dst,
-                           LVM_INT16      n)
-{
+void MixInSoft_D32C31_SAT(Mix_1St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src, LVM_FLOAT* dst,
+                          LVM_INT16 n) {
     char HardMixing = TRUE;
 
-    if(n <= 0)    return;
+    if (n <= 0) return;
 
     /******************************************************************************
        SOFT MIXING
     *******************************************************************************/
-    if (pInstance->Current != pInstance->Target)
-    {
-        if(pInstance->Alpha == 0){
+    if (pInstance->Current != pInstance->Target) {
+        if (pInstance->Alpha == 0) {
             pInstance->Current = pInstance->Target;
-        }else if ((pInstance->Current-pInstance->Target < POINT_ZERO_ONE_DB_FLOAT) &&
-                 (pInstance->Current-pInstance->Target > -POINT_ZERO_ONE_DB_FLOAT)){
+        } else if ((pInstance->Current - pInstance->Target < POINT_ZERO_ONE_DB_FLOAT) &&
+                   (pInstance->Current - pInstance->Target > -POINT_ZERO_ONE_DB_FLOAT)) {
             pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
                                                        Make them equal. */
-        }else{
+        } else {
             /* Soft mixing has to be applied */
             HardMixing = FALSE;
             Core_MixInSoft_D32C31_SAT(pInstance, src, dst, n);
@@ -63,11 +59,11 @@
        HARD MIXING
     *******************************************************************************/
 
-    if (HardMixing){
-        if (pInstance->Target != 0){ /* Nothing to do in case Target = 0 */
+    if (HardMixing) {
+        if (pInstance->Target != 0) { /* Nothing to do in case Target = 0 */
             if ((pInstance->Target) == 1.0f)
                 Add2_Sat_Float(src, dst, n);
-            else{
+            else {
                 Core_MixInSoft_D32C31_SAT(pInstance, src, dst, n);
                 pInstance->Current = pInstance->Target; /* In case the core function would \
                                                            have changed the Current value */
@@ -81,16 +77,15 @@
     /* Call back before the hard mixing, because in this case, hard mixing makes
        use of the core soft mix function which can change the Current value!      */
 
-    if (pInstance->CallbackSet){
+    if (pInstance->CallbackSet) {
         if ((pInstance->Current - pInstance->Target < POINT_ZERO_ONE_DB_FLOAT) &&
-            (pInstance->Current - pInstance->Target > -POINT_ZERO_ONE_DB_FLOAT)){
+            (pInstance->Current - pInstance->Target > -POINT_ZERO_ONE_DB_FLOAT)) {
             pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
                                                        Make them equal. */
             pInstance->CallbackSet = FALSE;
-            if (pInstance->pCallBack != 0){
-                (*pInstance->pCallBack) ( pInstance->pCallbackHandle,
-                                          pInstance->pGeneralPurpose,
-                                          pInstance->CallbackParam );
+            if (pInstance->pCallBack != 0) {
+                (*pInstance->pCallBack)(pInstance->pCallbackHandle, pInstance->pGeneralPurpose,
+                                        pInstance->CallbackParam);
             }
         }
     }
diff --git a/media/libeffects/lvm/lib/Common/src/MixSoft_1St_D32C31_WRA.cpp b/media/libeffects/lvm/lib/Common/src/MixSoft_1St_D32C31_WRA.cpp
index d3325ec..8408962 100644
--- a/media/libeffects/lvm/lib/Common/src/MixSoft_1St_D32C31_WRA.cpp
+++ b/media/libeffects/lvm/lib/Common/src/MixSoft_1St_D32C31_WRA.cpp
@@ -26,33 +26,29 @@
    DEFINITIONS
 ***********************************************************************************/
 
-#define TRUE          1
-#define FALSE         0
+#define TRUE 1
+#define FALSE 0
 
 /**********************************************************************************
    FUNCTION MIXSOFT_1ST_D32C31_WRA
 ***********************************************************************************/
-void MixSoft_1St_D32C31_WRA(    Mix_1St_Cll_FLOAT_t       *pInstance,
-                                const LVM_FLOAT     *src,
-                                      LVM_FLOAT     *dst,
-                                      LVM_INT16     n)
-{
+void MixSoft_1St_D32C31_WRA(Mix_1St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src, LVM_FLOAT* dst,
+                            LVM_INT16 n) {
     char HardMixing = TRUE;
 
-    if(n <= 0)    return;
+    if (n <= 0) return;
 
     /******************************************************************************
        SOFT MIXING
     *******************************************************************************/
-    if (pInstance->Current != pInstance->Target)
-    {
-        if(pInstance->Alpha == 0){
+    if (pInstance->Current != pInstance->Target) {
+        if (pInstance->Alpha == 0) {
             pInstance->Current = pInstance->Target;
-        }else if ((pInstance->Current - pInstance->Target < POINT_ZERO_ONE_DB_FLOAT) &&
-                 (pInstance->Current - pInstance->Target > -POINT_ZERO_ONE_DB_FLOAT)){
+        } else if ((pInstance->Current - pInstance->Target < POINT_ZERO_ONE_DB_FLOAT) &&
+                   (pInstance->Current - pInstance->Target > -POINT_ZERO_ONE_DB_FLOAT)) {
             pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
                                                        Make them equal. */
-        }else{
+        } else {
             /* Soft mixing has to be applied */
             HardMixing = FALSE;
             Core_MixSoft_1St_D32C31_WRA(pInstance, src, dst, n);
@@ -63,14 +59,12 @@
        HARD MIXING
     *******************************************************************************/
 
-    if (HardMixing){
+    if (HardMixing) {
         if (pInstance->Target == 0)
             LoadConst_Float(0, dst, n);
-        else if ((pInstance->Target) == 1.0f){
-            if (src != dst)
-                Copy_Float((LVM_FLOAT*)src, (LVM_FLOAT*)dst, (LVM_INT16)(n));
-        }
-        else
+        else if ((pInstance->Target) == 1.0f) {
+            if (src != dst) Copy_Float((LVM_FLOAT*)src, (LVM_FLOAT*)dst, (LVM_INT16)(n));
+        } else
             Mult3s_Float(src, pInstance->Current, dst, n);
     }
 
@@ -78,16 +72,15 @@
        CALL BACK
     *******************************************************************************/
 
-    if (pInstance->CallbackSet){
+    if (pInstance->CallbackSet) {
         if ((pInstance->Current - pInstance->Target < POINT_ZERO_ONE_DB_FLOAT) &&
-            (pInstance->Current - pInstance->Target > -POINT_ZERO_ONE_DB_FLOAT)){
+            (pInstance->Current - pInstance->Target > -POINT_ZERO_ONE_DB_FLOAT)) {
             pInstance->Current = pInstance->Target; /* Difference is not significant anymore. \
                                                        Make them equal. */
             pInstance->CallbackSet = FALSE;
-            if (pInstance->pCallBack != 0){
-                (*pInstance->pCallBack) ( pInstance->pCallbackHandle,
-                                          pInstance->pGeneralPurpose,
-                                          pInstance->CallbackParam );
+            if (pInstance->pCallBack != 0) {
+                (*pInstance->pCallBack)(pInstance->pCallbackHandle, pInstance->pGeneralPurpose,
+                                        pInstance->CallbackParam);
             }
         }
     }
diff --git a/media/libeffects/lvm/lib/Common/src/MixSoft_2St_D32C31_SAT.cpp b/media/libeffects/lvm/lib/Common/src/MixSoft_2St_D32C31_SAT.cpp
index b002738..aba8537 100644
--- a/media/libeffects/lvm/lib/Common/src/MixSoft_2St_D32C31_SAT.cpp
+++ b/media/libeffects/lvm/lib/Common/src/MixSoft_2St_D32C31_SAT.cpp
@@ -25,42 +25,35 @@
 /**********************************************************************************
    FUNCTION MIXSOFT_2ST_D32C31_SAT
 ***********************************************************************************/
-void MixSoft_2St_D32C31_SAT(    Mix_2St_Cll_FLOAT_t       *pInstance,
-                                const LVM_FLOAT     *src1,
-                                const LVM_FLOAT     *src2,
-                                      LVM_FLOAT     *dst,
-                                      LVM_INT16     n)
-{
-
-    if(n <= 0)    return;
+void MixSoft_2St_D32C31_SAT(Mix_2St_Cll_FLOAT_t* pInstance, const LVM_FLOAT* src1,
+                            const LVM_FLOAT* src2, LVM_FLOAT* dst, LVM_INT16 n) {
+    if (n <= 0) return;
 
     /******************************************************************************
        SOFT MIXING
     *******************************************************************************/
-    if ((pInstance->Current1 != pInstance->Target1) || (pInstance->Current2 != pInstance->Target2))
-    {
+    if ((pInstance->Current1 != pInstance->Target1) ||
+        (pInstance->Current2 != pInstance->Target2)) {
         MixSoft_1St_D32C31_WRA((Mix_1St_Cll_FLOAT_t*)pInstance, src1, dst, n);
-        MixInSoft_D32C31_SAT((Mix_1St_Cll_FLOAT_t *)&pInstance->Alpha2, /* Cast to void: \
-                                                              no dereferencing in function*/
-                              src2, dst, n);
+        MixInSoft_D32C31_SAT((Mix_1St_Cll_FLOAT_t*)&pInstance->Alpha2, /* Cast to void: \
+                                                             no dereferencing in function*/
+                             src2, dst, n);
     }
 
     /******************************************************************************
        HARD MIXING
     *******************************************************************************/
 
-    else
-    {
+    else {
         if (pInstance->Current1 == 0)
             MixSoft_1St_D32C31_WRA(
-                    (Mix_1St_Cll_FLOAT_t *) &pInstance->Alpha2, /* Cast to void: no \
-                                                             dereferencing in function*/
-                                    src2, dst, n);
+                    (Mix_1St_Cll_FLOAT_t*)&pInstance->Alpha2, /* Cast to void: no \
+                                                           dereferencing in function*/
+                    src2, dst, n);
         else if (pInstance->Current2 == 0)
-            MixSoft_1St_D32C31_WRA((Mix_1St_Cll_FLOAT_t*) pInstance, src1, dst, n);
+            MixSoft_1St_D32C31_WRA((Mix_1St_Cll_FLOAT_t*)pInstance, src1, dst, n);
         else
             Core_MixHard_2St_D32C31_SAT(pInstance, src1, src2, dst, n);
     }
 }
 /**********************************************************************************/
-
diff --git a/media/libeffects/lvm/lib/Common/src/Mixer_private.h b/media/libeffects/lvm/lib/Common/src/Mixer_private.h
index 1d653bb..e1e62c5 100644
--- a/media/libeffects/lvm/lib/Common/src/Mixer_private.h
+++ b/media/libeffects/lvm/lib/Common/src/Mixer_private.h
@@ -26,13 +26,13 @@
 
 #define POINT_ZERO_ONE_DB 2473805 /* 0.01 dB on a full scale signal = (10^(0.01/20) -1) * 2^31 */
 
-#define POINT_ZERO_ONE_DB_FLOAT 0.001152 /* 0.01 dB on a full scale \
-                                            signal = (10^(0.01/20) -1) * 2^31 */
+#define POINT_ZERO_ONE_DB_FLOAT         \
+    0.001152 /* 0.01 dB on a full scale \
+                signal = (10^(0.01/20) -1) * 2^31 */
 /**********************************************************************************
    DEFINITIONS
 ***********************************************************************************/
 
 /**********************************************************************************/
 
-#endif //#ifndef __MIXER_PRIVATE_H__
-
+#endif  //#ifndef __MIXER_PRIVATE_H__
diff --git a/media/libeffects/lvm/lib/Common/src/MonoTo2I_16.cpp b/media/libeffects/lvm/lib/Common/src/MonoTo2I_16.cpp
deleted file mode 100644
index ead798d..0000000
--- a/media/libeffects/lvm/lib/Common/src/MonoTo2I_16.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "VectorArithmetic.h"
-
-/**********************************************************************************
-   FUNCTION MonoTo2I_16
-***********************************************************************************/
-
-void MonoTo2I_16( const LVM_INT16 *src,
-                 LVM_INT16 *dst,
-                 LVM_INT16 n)
-{
-    LVM_INT16 ii;
-    src += (n-1);
-    dst += ((n*2)-1);
-
-    for (ii = n; ii != 0; ii--)
-    {
-        *dst = *src;
-        dst--;
-
-        *dst = *src;
-        dst--;
-        src--;
-    }
-
-    return;
-}
-
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/MonoTo2I_32.cpp b/media/libeffects/lvm/lib/Common/src/MonoTo2I_32.cpp
index 603d1fc..ef3e633 100644
--- a/media/libeffects/lvm/lib/Common/src/MonoTo2I_32.cpp
+++ b/media/libeffects/lvm/lib/Common/src/MonoTo2I_32.cpp
@@ -21,40 +21,12 @@
 
 #include "VectorArithmetic.h"
 
-/**********************************************************************************
-   FUNCTION MonoTo2I_32
-***********************************************************************************/
-
-void MonoTo2I_32( const LVM_INT32  *src,
-                 LVM_INT32  *dst,
-                 LVM_INT16 n)
-{
-    LVM_INT16 ii;
-    src += (n-1);
-    dst += ((n*2)-1);
-
-    for (ii = n; ii != 0; ii--)
-    {
-        *dst = *src;
-        dst--;
-
-        *dst = *src;
-        dst--;
-        src--;
-    }
-
-    return;
-}
-void MonoTo2I_Float( const LVM_FLOAT  *src,
-                     LVM_FLOAT  *dst,
-                     LVM_INT16 n)
-{
+void MonoTo2I_Float(const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n) {
     LVM_INT16 ii;
     src += (n - 1);
     dst += ((n * 2) - 1);
 
-    for (ii = n; ii != 0; ii--)
-    {
+    for (ii = n; ii != 0; ii--) {
         *dst = *src;
         dst--;
 
@@ -65,4 +37,3 @@
 
     return;
 }
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/Mult3s_32x16.cpp b/media/libeffects/lvm/lib/Common/src/Mult3s_32x16.cpp
index 370c39a..babfef3 100644
--- a/media/libeffects/lvm/lib/Common/src/Mult3s_32x16.cpp
+++ b/media/libeffects/lvm/lib/Common/src/Mult3s_32x16.cpp
@@ -22,41 +22,11 @@
 #include "VectorArithmetic.h"
 #include "LVM_Macros.h"
 
-/**********************************************************************************
-FUNCTION MULT3S_16X16
-***********************************************************************************/
-
-void Mult3s_32x16( const LVM_INT32 *src,
-                  const LVM_INT16 val,
-                  LVM_INT32 *dst,
-                  LVM_INT16 n)
-{
-    LVM_INT16 ii;
-    LVM_INT32 srcval,temp;
-
-    for (ii = n; ii != 0; ii--)
-    {
-        srcval=*src;
-        src++;
-
-        MUL32x16INTO32(srcval,val,temp,15)
-
-        *dst = temp;
-        dst++;
-    }
-
-    return;
-}
-void Mult3s_Float( const LVM_FLOAT *src,
-                   const LVM_FLOAT val,
-                   LVM_FLOAT *dst,
-                   LVM_INT16 n)
-{
+void Mult3s_Float(const LVM_FLOAT* src, const LVM_FLOAT val, LVM_FLOAT* dst, LVM_INT16 n) {
     LVM_INT16 ii;
     LVM_FLOAT temp;
 
-    for (ii = n; ii != 0; ii--)
-    {
+    for (ii = n; ii != 0; ii--) {
         temp = (*src) * val;
         src++;
         *dst = temp;
@@ -64,4 +34,3 @@
     }
     return;
 }
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/NonLinComp_D16.cpp b/media/libeffects/lvm/lib/Common/src/NonLinComp_D16.cpp
index 36d1149..f3a1a67 100644
--- a/media/libeffects/lvm/lib/Common/src/NonLinComp_D16.cpp
+++ b/media/libeffects/lvm/lib/Common/src/NonLinComp_D16.cpp
@@ -61,22 +61,16 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-void NonLinComp_D16(LVM_INT16        Gain,
-                      LVM_INT16        *pDataIn,
-                    LVM_INT16        *pDataOut,
-                    LVM_INT32        BlockLength)
-{
-
-    LVM_INT16            Sample;                    /* Input samples */
-    LVM_INT32            SampleNo;                /* Sample index */
-    LVM_INT16            Temp;
+void NonLinComp_Float(LVM_FLOAT Gain, LVM_FLOAT* pDataIn, LVM_FLOAT* pDataOut,
+                      LVM_INT32 BlockLength) {
+    LVM_FLOAT Sample;   /* Input samples */
+    LVM_INT32 SampleNo; /* Sample index */
+    LVM_FLOAT Temp;
 
     /*
      * Process a block of samples
      */
-    for(SampleNo = 0; SampleNo<BlockLength; SampleNo++)
-    {
-
+    for (SampleNo = 0; SampleNo < BlockLength; SampleNo++) {
         /*
          * Read the input
          */
@@ -88,64 +82,12 @@
          * harmonic distortion. The amount of compression is control by the
          * gain factor
          */
-        if ((LVM_INT32)Sample != -32768)
-        {
-            Temp = (LVM_INT16)((Sample * Sample) >> 15);
-            if(Sample >0)
-            {
-                Sample = (LVM_INT16)(Sample + ((Gain * (Sample - Temp)) >> 15));
-            }
-            else
-            {
-                Sample = (LVM_INT16)(Sample + ((Gain * (Sample + Temp)) >> 15));
-            }
-        }
-
-        /*
-         * Save the output
-         */
-        *pDataOut = Sample;
-        pDataOut++;
-
-    }
-
-}
-void NonLinComp_Float(LVM_FLOAT        Gain,
-                      LVM_FLOAT        *pDataIn,
-                      LVM_FLOAT        *pDataOut,
-                      LVM_INT32        BlockLength)
-{
-
-    LVM_FLOAT            Sample;                    /* Input samples */
-    LVM_INT32            SampleNo;                /* Sample index */
-    LVM_FLOAT            Temp;
-
-    /*
-     * Process a block of samples
-     */
-    for(SampleNo = 0; SampleNo < BlockLength; SampleNo++)
-    {
-        /*
-         * Read the input
-         */
-        Sample = *pDataIn;
-        pDataIn++;
-
-        /*
-         * Apply the compander, this compresses the signal at the expense of
-         * harmonic distortion. The amount of compression is control by the
-         * gain factor
-         */
-        if (Sample != -1.0f)
-        {
+        if (Sample != -1.0f) {
             Temp = ((Sample * Sample));
-            if(Sample > 0)
-            {
-                Sample = (Sample + ((Gain * (Sample - Temp)) ));
-            }
-            else
-            {
-                Sample = (Sample + ((Gain * (Sample + Temp)) ));
+            if (Sample > 0) {
+                Sample = (Sample + ((Gain * (Sample - Temp))));
+            } else {
+                Sample = (Sample + ((Gain * (Sample + Temp))));
             }
         }
 
diff --git a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32C14G11_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32C14G11_TRC_WRA_01.cpp
deleted file mode 100644
index 3f62f99..0000000
--- a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32C14G11_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "PK_2I_D32F32CssGss_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A0,
- pBiquadState->coefs[1] is -B2,
- pBiquadState->coefs[2] is -B1, these are in Q14 format
- pBiquadState->coefs[3] is Gain, in Q11 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-1)R in Q0 format
- pBiquadState->pDelays[2] is x(n-2)L in Q0 format
- pBiquadState->pDelays[3] is x(n-2)R in Q0 format
- pBiquadState->pDelays[4] is y(n-1)L in Q0 format
- pBiquadState->pDelays[5] is y(n-1)R in Q0 format
- pBiquadState->pDelays[6] is y(n-2)L in Q0 format
- pBiquadState->pDelays[7] is y(n-2)R in Q0 format
-***************************************************************************/
-void PK_2I_D32F32C14G11_TRC_WRA_01 ( Biquad_FLOAT_Instance_t       *pInstance,
-                                     LVM_FLOAT               *pDataIn,
-                                     LVM_FLOAT               *pDataOut,
-                                     LVM_INT16               NrSamples)
-    {
-        LVM_FLOAT ynL,ynR,ynLO,ynRO,templ;
-        LVM_INT16 ii;
-        PFilter_State_Float pBiquadState = (PFilter_State_Float) pInstance;
-
-         for (ii = NrSamples; ii != 0; ii--)
-         {
-
-            /**************************************************************************
-                            PROCESSING OF THE LEFT CHANNEL
-            ***************************************************************************/
-            /* ynL= (A0  * (x(n)L - x(n-2)L  ) )*/
-            templ = (*pDataIn) - pBiquadState->pDelays[2];
-            ynL = templ * pBiquadState->coefs[0];
-
-            /* ynL+= ((-B2  * y(n-2)L  )) */
-            templ = pBiquadState->pDelays[6] * pBiquadState->coefs[1];
-            ynL += templ;
-
-            /* ynL+= ((-B1 * y(n-1)L  ) ) */
-            templ = pBiquadState->pDelays[4] * pBiquadState->coefs[2];
-            ynL += templ;
-
-            /* ynLO= ((Gain * ynL )) */
-            ynLO = ynL * pBiquadState->coefs[3];
-
-            /* ynLO=( ynLO + x(n)L  )*/
-            ynLO += (*pDataIn);
-
-            /**************************************************************************
-                            PROCESSING OF THE RIGHT CHANNEL
-            ***************************************************************************/
-            /* ynR= (A0  * (x(n)R  - x(n-2)R  ) ) */
-            templ = (*(pDataIn + 1)) - pBiquadState->pDelays[3];
-            ynR = templ * pBiquadState->coefs[0];
-
-            /* ynR+= ((-B2  * y(n-2)R  ) )  */
-            templ = pBiquadState->pDelays[7] * pBiquadState->coefs[1];
-            ynR += templ;
-
-            /* ynR+= ((-B1  * y(n-1)R  ) )   */
-            templ = pBiquadState->pDelays[5] * pBiquadState->coefs[2];
-            ynR += templ;
-
-            /* ynRO= ((Gain  * ynR )) */
-            ynRO = ynR * pBiquadState->coefs[3];
-
-            /* ynRO=( ynRO + x(n)R  )*/
-            ynRO += (*(pDataIn+1));
-
-            /**************************************************************************
-                            UPDATING THE DELAYS
-            ***************************************************************************/
-            pBiquadState->pDelays[7] = pBiquadState->pDelays[5]; /* y(n-2)R=y(n-1)R*/
-            pBiquadState->pDelays[6] = pBiquadState->pDelays[4]; /* y(n-2)L=y(n-1)L*/
-            pBiquadState->pDelays[3] = pBiquadState->pDelays[1]; /* x(n-2)R=x(n-1)R*/
-            pBiquadState->pDelays[2] = pBiquadState->pDelays[0]; /* x(n-2)L=x(n-1)L*/
-            pBiquadState->pDelays[5] = ynR; /* Update y(n-1)R */
-            pBiquadState->pDelays[4] = ynL; /* Update y(n-1)L */
-            pBiquadState->pDelays[0] = (*pDataIn); /* Update x(n-1)L */
-            pDataIn++;
-            pBiquadState->pDelays[1] = (*pDataIn); /* Update x(n-1)R */
-            pDataIn++;
-
-            /**************************************************************************
-                            WRITING THE OUTPUT
-            ***************************************************************************/
-            *pDataOut = ynLO; /* Write Left output*/
-            pDataOut++;
-            *pDataOut = ynRO; /* Write Right ouput*/
-            pDataOut++;
-
-        }
-
-    }
-
-#ifdef SUPPORT_MC
-/**************************************************************************
-DELAYS-
-pBiquadState->pDelays[0] to
-pBiquadState->pDelays[NrChannels - 1] is x(n-1) for all NrChannels
-
-pBiquadState->pDelays[NrChannels] to
-pBiquadState->pDelays[2*NrChannels - 1] is x(n-2) for all NrChannels
-
-pBiquadState->pDelays[2*NrChannels] to
-pBiquadState->pDelays[3*NrChannels - 1] is y(n-1) for all NrChannels
-
-pBiquadState->pDelays[3*NrChannels] to
-pBiquadState->pDelays[4*NrChannels - 1] is y(n-2) for all NrChannels
-***************************************************************************/
-
-void PK_Mc_D32F32C14G11_TRC_WRA_01 (Biquad_FLOAT_Instance_t       *pInstance,
-                                    LVM_FLOAT               *pDataIn,
-                                    LVM_FLOAT               *pDataOut,
-                                    LVM_INT16               NrFrames,
-                                    LVM_INT16               NrChannels)
-    {
-        LVM_FLOAT yn, ynO, temp;
-        LVM_INT16 ii, jj;
-        PFilter_State_Float pBiquadState = (PFilter_State_Float) pInstance;
-
-         for (ii = NrFrames; ii != 0; ii--)
-         {
-
-            for (jj = 0; jj < NrChannels; jj++)
-            {
-                /**************************************************************************
-                                PROCESSING OF THE jj CHANNEL
-                ***************************************************************************/
-                /* yn= (A0  * (x(n) - x(n-2)))*/
-                temp = (*pDataIn) - pBiquadState->pDelays[NrChannels + jj];
-                yn = temp * pBiquadState->coefs[0];
-
-                /* yn+= ((-B2  * y(n-2))) */
-                temp = pBiquadState->pDelays[NrChannels*3 + jj] * pBiquadState->coefs[1];
-                yn += temp;
-
-                /* yn+= ((-B1 * y(n-1))) */
-                temp = pBiquadState->pDelays[NrChannels*2 + jj] * pBiquadState->coefs[2];
-                yn += temp;
-
-                /* ynO= ((Gain * yn)) */
-                ynO = yn * pBiquadState->coefs[3];
-
-                /* ynO=(ynO + x(n))*/
-                ynO += (*pDataIn);
-
-                /**************************************************************************
-                                UPDATING THE DELAYS
-                ***************************************************************************/
-                pBiquadState->pDelays[NrChannels * 3 + jj] =
-                    pBiquadState->pDelays[NrChannels * 2 + jj]; /* y(n-2)=y(n-1)*/
-                pBiquadState->pDelays[NrChannels * 1 + jj] =
-                    pBiquadState->pDelays[jj]; /* x(n-2)=x(n-1)*/
-                pBiquadState->pDelays[NrChannels * 2 + jj] = yn; /* Update y(n-1) */
-                pBiquadState->pDelays[jj] = (*pDataIn); /* Update x(n-1)*/
-                pDataIn++;
-
-                /**************************************************************************
-                                WRITING THE OUTPUT
-                ***************************************************************************/
-                *pDataOut = ynO; /* Write output*/
-                pDataOut++;
-            }
-        }
-
-    }
-#endif
diff --git a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32C30G11_TRC_WRA_01.cpp b/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32C30G11_TRC_WRA_01.cpp
deleted file mode 100644
index 41de1de..0000000
--- a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32C30G11_TRC_WRA_01.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "PK_2I_D32F32CllGss_TRC_WRA_01_Private.h"
-#include "LVM_Macros.h"
-
-/**************************************************************************
- ASSUMPTIONS:
- COEFS-
- pBiquadState->coefs[0] is A0,
- pBiquadState->coefs[1] is -B2,
- pBiquadState->coefs[2] is -B1, these are in Q30 format
- pBiquadState->coefs[3] is Gain, in Q11 format
-
- DELAYS-
- pBiquadState->pDelays[0] is x(n-1)L in Q0 format
- pBiquadState->pDelays[1] is x(n-1)R in Q0 format
- pBiquadState->pDelays[2] is x(n-2)L in Q0 format
- pBiquadState->pDelays[3] is x(n-2)R in Q0 format
- pBiquadState->pDelays[4] is y(n-1)L in Q0 format
- pBiquadState->pDelays[5] is y(n-1)R in Q0 format
- pBiquadState->pDelays[6] is y(n-2)L in Q0 format
- pBiquadState->pDelays[7] is y(n-2)R in Q0 format
-***************************************************************************/
diff --git a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CllGss_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CllGss_TRC_WRA_01_Init.cpp
deleted file mode 100644
index 714aa52..0000000
--- a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CllGss_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "PK_2I_D32F32CllGss_TRC_WRA_01_Private.h"
-
diff --git a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CllGss_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CllGss_TRC_WRA_01_Private.h
deleted file mode 100644
index c5f9c7c..0000000
--- a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CllGss_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _PK_2I_D32F32CLLGSS_TRC_WRA_01_PRIVATE_H_
-#define _PK_2I_D32F32CLLGSS_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-typedef struct _Filter_State_
-{
-  LVM_INT32 *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT32         coefs[5];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-#endif /* _PK_2I_D32F32CLLGSS_TRC_WRA_01_PRIVATE_H_ */
diff --git a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CssGss_TRC_WRA_01_Init.cpp b/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CssGss_TRC_WRA_01_Init.cpp
deleted file mode 100644
index f6c05da..0000000
--- a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CssGss_TRC_WRA_01_Init.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "BIQUAD.h"
-#include "PK_2I_D32F32CssGss_TRC_WRA_01_Private.h"
-void  PK_2I_D32F32CssGss_TRC_WRA_01_Init(Biquad_FLOAT_Instance_t         *pInstance,
-                                         Biquad_2I_Order2_FLOAT_Taps_t   *pTaps,
-                                         PK_FLOAT_Coefs_t            *pCoef)
-{
-    PFilter_State_Float pBiquadState = (PFilter_State_Float) pInstance;
-    pBiquadState->pDelays       = (LVM_FLOAT *) pTaps;
-
-    pBiquadState->coefs[0] = pCoef->A0;
-
-    pBiquadState->coefs[1] = pCoef->B2;
-
-    pBiquadState->coefs[2] = pCoef->B1;
-
-    pBiquadState->coefs[3] = pCoef->G;
-}
diff --git a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CssGss_TRC_WRA_01_Private.h b/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CssGss_TRC_WRA_01_Private.h
deleted file mode 100644
index cc924c4..0000000
--- a/media/libeffects/lvm/lib/Common/src/PK_2I_D32F32CssGss_TRC_WRA_01_Private.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _PK_2I_D32F32CSSGSS_TRC_WRA_01_PRIVATE_H_
-#define _PK_2I_D32F32CSSGSS_TRC_WRA_01_PRIVATE_H_
-
-/* The internal state variables are implemented in a (for the user)  hidden structure */
-/* In this (private) file, the internal structure is declared fro private use.        */
-
-typedef struct _Filter_State_Float_
-{
-    LVM_FLOAT *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-    LVM_FLOAT         coefs[5];       /* pointer to the filter coefficients */
-}Filter_State_Float;
-
-typedef Filter_State_Float * PFilter_State_Float ;
-typedef struct _Filter_State_
-{
-  LVM_INT32 *       pDelays;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT32         coefs[5];       /* pointer to the filter coefficients */
-}Filter_State;
-
-typedef Filter_State * PFilter_State ;
-
-#endif /* _PK_2I_D32F32CSSGSS_TRC_WRA_01_PRIVATE_H_ */
diff --git a/media/libeffects/lvm/lib/Common/src/Shift_Sat_v32xv32.cpp b/media/libeffects/lvm/lib/Common/src/Shift_Sat_v32xv32.cpp
index 97a04c1..f54ba90 100644
--- a/media/libeffects/lvm/lib/Common/src/Shift_Sat_v32xv32.cpp
+++ b/media/libeffects/lvm/lib/Common/src/Shift_Sat_v32xv32.cpp
@@ -24,55 +24,39 @@
 /**********************************************************************************
    FUNCTION Shift_Sat_v32xv32
 ***********************************************************************************/
-void Shift_Sat_Float (const   LVM_INT16   val,
-                      const   LVM_FLOAT   *src,
-                      LVM_FLOAT   *dst,
-                      LVM_INT16   n)
-{
-    LVM_FLOAT   temp;
-    LVM_INT32   ii,ij;
-    LVM_INT16   RShift;
+void Shift_Sat_Float(const LVM_INT16 val, const LVM_FLOAT* src, LVM_FLOAT* dst, LVM_INT16 n) {
+    LVM_FLOAT temp;
+    LVM_INT32 ii, ij;
+    LVM_INT16 RShift;
 
-    if(val > 0)
-    {
-        for (ii = n; ii != 0; ii--)
-        {
+    if (val > 0) {
+        for (ii = n; ii != 0; ii--) {
             temp = (LVM_FLOAT)*src;
             src++;
-            for(ij = 0; ij < val; ij++)
-            {
+            for (ij = 0; ij < val; ij++) {
                 temp = temp * 2;
             }
 
-            if(temp > 1.0)
-                temp = 1.0;
-            if(temp < -1.0)
-                temp = -1.0;
+            if (temp > 1.0) temp = 1.0;
+            if (temp < -1.0) temp = -1.0;
 
             *dst = (LVM_FLOAT)temp;
             dst++;
         }
-    }
-    else if(val < 0)
-    {
-        RShift=(LVM_INT16)(-val);
+    } else if (val < 0) {
+        RShift = (LVM_INT16)(-val);
 
-        for (ii = n; ii != 0; ii--)
-        {
+        for (ii = n; ii != 0; ii--) {
             temp = (LVM_FLOAT)*src;
             src++;
-            for(ij = 0; ij < RShift; ij++)
-            {
+            for (ij = 0; ij < RShift; ij++) {
                 temp = temp / 2;
             }
             *dst = (LVM_FLOAT)temp;
             dst++;
         }
-    }
-    else
-    {
-        if(src != dst)
-        {
+    } else {
+        if (src != dst) {
             Copy_Float(src, dst, n);
         }
     }
diff --git a/media/libeffects/lvm/lib/Common/src/dB_to_Lin32.cpp b/media/libeffects/lvm/lib/Common/src/dB_to_Lin32.cpp
index 4da2013..2143465 100644
--- a/media/libeffects/lvm/lib/Common/src/dB_to_Lin32.cpp
+++ b/media/libeffects/lvm/lib/Common/src/dB_to_Lin32.cpp
@@ -57,17 +57,16 @@
  *
  ****************************************************************************************/
 
-#define FOUR_OVER_SIX    21846                  /* (4 / 6) * 2^15 */
-#define SIX_DB           96                     /* 6 * 16 or 6dB in Q11.4 format */
-#define FIRST_COEF_NEG   14884305
-#define FIRST_COEF_POS   7442152                /* FIRST_COEF_NEG / 2 */
-#define SECOND_COEF      38836
-#define MAX_VALUE        1536                   /* 96 * 16 */
+#define FOUR_OVER_SIX 21846 /* (4 / 6) * 2^15 */
+#define SIX_DB 96           /* 6 * 16 or 6dB in Q11.4 format */
+#define FIRST_COEF_NEG 14884305
+#define FIRST_COEF_POS 7442152 /* FIRST_COEF_NEG / 2 */
+#define SECOND_COEF 38836
+#define MAX_VALUE 1536 /* 96 * 16 */
 
-LVM_FLOAT   dB_to_LinFloat(LVM_INT16    db_fix)
-{
-    LVM_FLOAT    dB_Float;
-    LVM_FLOAT    LinFloat;
+LVM_FLOAT dB_to_LinFloat(LVM_INT16 db_fix) {
+    LVM_FLOAT dB_Float;
+    LVM_FLOAT LinFloat;
 
     dB_Float = (LVM_FLOAT)((LVM_FLOAT)db_fix / 16.0f);
     LinFloat = pow(10, dB_Float / 20.0);
diff --git a/media/libeffects/lvm/lib/Common/src/mult3s_16x16.cpp b/media/libeffects/lvm/lib/Common/src/mult3s_16x16.cpp
deleted file mode 100644
index 4092560..0000000
--- a/media/libeffects/lvm/lib/Common/src/mult3s_16x16.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**********************************************************************************
-   INCLUDE FILES
-***********************************************************************************/
-
-#include "VectorArithmetic.h"
-
-/**********************************************************************************
-   FUNCTION MULT3S_16X16
-***********************************************************************************/
-
-void Mult3s_16x16( const LVM_INT16 *src,
-                  const LVM_INT16 val,
-                  LVM_INT16 *dst,
-                  LVM_INT16 n)
-{
-    LVM_INT16 ii;
-    LVM_INT32 temp;
-
-    for (ii = n; ii != 0; ii--)
-    {
-        temp = (LVM_INT32)(*src) * (LVM_INT32)val;
-        src++;
-
-        *dst = (LVM_INT16)(temp >> 15);
-        dst++;
-    }
-
-    return;
-}
-
-/**********************************************************************************/
diff --git a/media/libeffects/lvm/lib/Eq/lib/LVEQNB.h b/media/libeffects/lvm/lib/Eq/lib/LVEQNB.h
index c5ddf77..f1afcd6 100644
--- a/media/libeffects/lvm/lib/Eq/lib/LVEQNB.h
+++ b/media/libeffects/lvm/lib/Eq/lib/LVEQNB.h
@@ -86,16 +86,9 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/* Memory table */
-#define LVEQNB_MEMREGION_INSTANCE          0   /* Offset to the instance memory region */
-#define LVEQNB_MEMREGION_PERSISTENT_DATA   1   /* Offset to persistent data memory region */
-#define LVEQNB_MEMREGION_PERSISTENT_COEF   2   /* Offset to persistent coefficient region */
-#define LVEQNB_MEMREGION_SCRATCH           3   /* Offset to data scratch memory region */
-#define LVEQNB_NR_MEMORY_REGIONS           4   /* Number of memory regions */
-
 /* Callback events */
-#define LVEQNB_EVENT_NONE                   0x0000    /* Not a valid event */
-#define LVEQNB_EVENT_ALGOFF                 0x0001    /* EQNB has completed switch off */
+#define LVEQNB_EVENT_NONE 0x0000   /* Not a valid event */
+#define LVEQNB_EVENT_ALGOFF 0x0001 /* EQNB has completed switch off */
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -104,42 +97,25 @@
 /****************************************************************************************/
 
 /* Instance handle */
-typedef void *LVEQNB_Handle_t;
+typedef void* LVEQNB_Handle_t;
 
 /* Operating modes */
-typedef enum
-{
-    LVEQNB_BYPASS   = 0,
-    LVEQNB_ON       = 1,
-    LVEQNB_MODE_MAX = LVM_MAXINT_32
-} LVEQNB_Mode_en;
+typedef enum { LVEQNB_BYPASS = 0, LVEQNB_ON = 1, LVEQNB_MODE_MAX = LVM_MAXINT_32 } LVEQNB_Mode_en;
 
 /* Filter mode control */
-typedef enum
-{
-    LVEQNB_FILTER_OFF   = 0,
-    LVEQNB_FILTER_ON    = 1,
+typedef enum {
+    LVEQNB_FILTER_OFF = 0,
+    LVEQNB_FILTER_ON = 1,
     LVEQNB_FILTER_DUMMY = LVM_MAXINT_32
 } LVEQNB_FilterMode_en;
 
-/* Memory Types */
-typedef enum
-{
-    LVEQNB_PERSISTENT      = 0,
-    LVEQNB_PERSISTENT_DATA = 1,
-    LVEQNB_PERSISTENT_COEF = 2,
-    LVEQNB_SCRATCH         = 3,
-    LVEQNB_MEMORY_MAX      = LVM_MAXINT_32
-} LVEQNB_MemoryTypes_en;
-
 /* Function return status */
-typedef enum
-{
-    LVEQNB_SUCCESS        = 0,                          /* Successful return from a routine */
-    LVEQNB_ALIGNMENTERROR = 1,                          /* Memory alignment error */
-    LVEQNB_NULLADDRESS    = 2,                          /* NULL allocation address */
-    LVEQNB_TOOMANYSAMPLES = 3,                          /* Maximum block size exceeded */
-    LVEQNB_STATUS_MAX     = LVM_MAXINT_32
+typedef enum {
+    LVEQNB_SUCCESS = 0,        /* Successful return from a routine */
+    LVEQNB_ALIGNMENTERROR = 1, /* Memory alignment error */
+    LVEQNB_NULLADDRESS = 2,    /* NULL allocation address */
+    LVEQNB_TOOMANYSAMPLES = 3, /* Maximum block size exceeded */
+    LVEQNB_STATUS_MAX = LVM_MAXINT_32
 } LVEQNB_ReturnStatus_en;
 
 /****************************************************************************************/
@@ -166,39 +142,35 @@
 /*
  * Supported source data formats
  */
-#define LVEQNB_CAP_STEREO                  1
-#define LVEQNB_CAP_MONOINSTEREO            2
+#define LVEQNB_CAP_STEREO 1
+#define LVEQNB_CAP_MONOINSTEREO 2
 
-typedef enum
-{
-    LVEQNB_STEREO       = 0,
+typedef enum {
+    LVEQNB_STEREO = 0,
     LVEQNB_MONOINSTEREO = 1,
-#ifdef SUPPORT_MC
     LVEQNB_MULTICHANNEL = 2,
-#endif
-    LVEQNB_SOURCE_MAX   = LVM_MAXINT_32
+    LVEQNB_SOURCE_MAX = LVM_MAXINT_32
 } LVEQNB_SourceFormat_en;
 
 /*
  * Supported sample rates in samples per second
  */
-#define LVEQNB_CAP_FS_8000                 1
-#define LVEQNB_CAP_FS_11025                2
-#define LVEQNB_CAP_FS_12000                4
-#define LVEQNB_CAP_FS_16000                8
-#define LVEQNB_CAP_FS_22050                16
-#define LVEQNB_CAP_FS_24000                32
-#define LVEQNB_CAP_FS_32000                64
-#define LVEQNB_CAP_FS_44100                128
-#define LVEQNB_CAP_FS_48000                256
-#define LVEQNB_CAP_FS_88200                512
-#define LVEQNB_CAP_FS_96000                1024
-#define LVEQNB_CAP_FS_176400               2048
-#define LVEQNB_CAP_FS_192000               4096
+#define LVEQNB_CAP_FS_8000 1
+#define LVEQNB_CAP_FS_11025 2
+#define LVEQNB_CAP_FS_12000 4
+#define LVEQNB_CAP_FS_16000 8
+#define LVEQNB_CAP_FS_22050 16
+#define LVEQNB_CAP_FS_24000 32
+#define LVEQNB_CAP_FS_32000 64
+#define LVEQNB_CAP_FS_44100 128
+#define LVEQNB_CAP_FS_48000 256
+#define LVEQNB_CAP_FS_88200 512
+#define LVEQNB_CAP_FS_96000 1024
+#define LVEQNB_CAP_FS_176400 2048
+#define LVEQNB_CAP_FS_192000 4096
 
-typedef enum
-{
-    LVEQNB_FS_8000  = 0,
+typedef enum {
+    LVEQNB_FS_8000 = 0,
     LVEQNB_FS_11025 = 1,
     LVEQNB_FS_12000 = 2,
     LVEQNB_FS_16000 = 3,
@@ -211,7 +183,7 @@
     LVEQNB_FS_96000 = 10,
     LVEQNB_FS_176400 = 11,
     LVEQNB_FS_192000 = 12,
-    LVEQNB_FS_MAX   = LVM_MAXINT_32
+    LVEQNB_FS_MAX = LVM_MAXINT_32
 } LVEQNB_Fs_en;
 
 /****************************************************************************************/
@@ -220,58 +192,38 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/* Memory region definition */
-typedef struct
-{
-    LVM_UINT32                  Size;                   /* Region size in bytes */
-    LVM_UINT16                  Alignment;              /* Region alignment in bytes */
-    LVEQNB_MemoryTypes_en       Type;                   /* Region type */
-    void                        *pBaseAddress;          /* Pointer to the region base address */
-} LVEQNB_MemoryRegion_t;
-
-/* Memory table containing the region definitions */
-typedef struct
-{
-    LVEQNB_MemoryRegion_t       Region[LVEQNB_NR_MEMORY_REGIONS];  /* One definition for each region */
-} LVEQNB_MemTab_t;
-
 /* Equaliser band definition */
-typedef struct
-{
-    LVM_INT16                   Gain;                   /* Band gain in dB */
-    LVM_UINT16                  Frequency;              /* Band centre frequency in Hz */
-    LVM_UINT16                  QFactor;                /* Band quality factor */
+typedef struct {
+    LVM_INT16 Gain;       /* Band gain in dB */
+    LVM_UINT16 Frequency; /* Band centre frequency in Hz */
+    LVM_UINT16 QFactor;   /* Band quality factor */
 } LVEQNB_BandDef_t;
 
 /* Parameter structure */
-typedef struct
-{
+typedef struct {
     /* General parameters */
-    LVEQNB_Mode_en              OperatingMode;
-    LVEQNB_Fs_en                SampleRate;
-    LVEQNB_SourceFormat_en      SourceFormat;
+    LVEQNB_Mode_en OperatingMode;
+    LVEQNB_Fs_en SampleRate;
+    LVEQNB_SourceFormat_en SourceFormat;
 
     /* Equaliser parameters */
-    LVM_UINT16                  NBands;                 /* Number of bands */
-    LVEQNB_BandDef_t            *pBandDefinition;       /* Pointer to equaliser definitions */
-#ifdef SUPPORT_MC
-    LVM_INT16                   NrChannels;
-#endif
+    LVM_UINT16 NBands;                 /* Number of bands */
+    LVEQNB_BandDef_t* pBandDefinition; /* Pointer to equaliser definitions */
+    LVM_INT16 NrChannels;
 } LVEQNB_Params_t;
 
 /* Capability structure */
-typedef struct
-{
+typedef struct {
     /* General parameters */
-    LVM_UINT16                  SampleRate;
+    LVM_UINT16 SampleRate;
 
-    LVM_UINT16                  SourceFormat;
-    LVM_UINT16                  MaxBlockSize;
-    LVM_UINT16                  MaxBands;
+    LVM_UINT16 SourceFormat;
+    LVM_UINT16 MaxBlockSize;
+    LVM_UINT16 MaxBands;
 
     /* Callback parameters */
-    LVM_Callback                CallBack;               /* Bundle callback */
-    void                        *pBundleInstance;       /* Bundle instance handle */
+    LVM_Callback CallBack; /* Bundle callback */
+    void* pBundleInstance; /* Bundle instance handle */
 
 } LVEQNB_Capabilities_t;
 
@@ -283,78 +235,43 @@
 
 /****************************************************************************************/
 /*                                                                                      */
-/* FUNCTION:                LVEQNB_Memory                                               */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*  This function is used for memory allocation and free. It can be called in           */
-/*  two ways:                                                                           */
-/*                                                                                      */
-/*      hInstance = NULL                Returns the memory requirements                 */
-/*      hInstance = Instance handle     Returns the memory requirements and             */
-/*                                      allocated base addresses for the instance       */
-/*                                                                                      */
-/*  When this function is called for memory allocation (hInstance=NULL) the memory      */
-/*  base address pointers are NULL on return.                                           */
-/*                                                                                      */
-/*  When the function is called for free (hInstance = Instance Handle) the memory       */
-/*  table returns the allocated memory and base addresses used during initialisation.   */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance               Instance Handle                                             */
-/*  pMemoryTable            Pointer to an empty memory definition table                 */
-/*  pCapabilities           Pointer to the default capabilities                         */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVEQNB_SUCCESS          Succeeded                                                   */
-/*  LVEQNB_NULLADDRESS      When any of pMemoryTable and pCapabilities is NULL address  */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*  1.  This function may be interrupted by the LVEQNB_Process function                 */
-/*                                                                                      */
-/****************************************************************************************/
-
-LVEQNB_ReturnStatus_en LVEQNB_Memory(LVEQNB_Handle_t            hInstance,
-                                     LVEQNB_MemTab_t            *pMemoryTable,
-                                     LVEQNB_Capabilities_t      *pCapabilities);
-
-/****************************************************************************************/
-/*                                                                                      */
 /* FUNCTION:                LVEQNB_Init                                                 */
 /*                                                                                      */
 /* DESCRIPTION:                                                                         */
-/*  Create and initialisation function for the N-Band equalliser module                 */
-/*                                                                                      */
-/*  This function can be used to create an algorithm instance by calling with           */
-/*  hInstance set to NULL. In this case the algorithm returns the new instance          */
-/*  handle.                                                                             */
-/*                                                                                      */
-/*  This function can be used to force a full re-initialisation of the algorithm        */
-/*  by calling with hInstance = Instance Handle. In this case the memory table          */
-/*  should be correct for the instance, this can be ensured by calling the function     */
-/*  LVEQNB_Memory before calling this function.                                         */
+/*  Create and initialisation function for the N-Band equaliser module.                 */
 /*                                                                                      */
 /* PARAMETERS:                                                                          */
-/*  hInstance               Instance handle                                             */
-/*  pMemoryTable            Pointer to the memory definition table                      */
+/*  phInstance              Pointer to instance handle                                  */
 /*  pCapabilities           Pointer to the initialisation capabilities                  */
+/*  pScratch                Pointer to bundle scratch buffer                            */
 /*                                                                                      */
 /* RETURNS:                                                                             */
 /*  LVEQNB_SUCCESS          Initialisation succeeded                                    */
-/*  LVEQNB_NULLADDRESS        When pCapabilities or pMemoryTableis or phInstance are NULL */
-/*  LVEQNB_NULLADDRESS        One or more of the memory regions has a NULL base address   */
-/*                          pointer for a memory region with a non-zero size.           */
-/*                                                                                      */
+/*  LVEQNB_NULLADDRESS      When pCapabilities or phInstance are NULL                   */
+/*  LVEQNB_NULLADDRESS      When allocated memory has a NULL base address               */
 /*                                                                                      */
 /* NOTES:                                                                               */
-/*  1.  The instance handle is the pointer to the base address of the first memory      */
-/*      region.                                                                         */
-/*  2.  This function must not be interrupted by the LVEQNB_Process function            */
+/*  1.  This function must not be interrupted by the LVEQNB_Process function            */
 /*                                                                                      */
 /****************************************************************************************/
+LVEQNB_ReturnStatus_en LVEQNB_Init(LVEQNB_Handle_t* phInstance,
+                                   LVEQNB_Capabilities_t* pCapabilities, void* pScratch);
 
-LVEQNB_ReturnStatus_en LVEQNB_Init(LVEQNB_Handle_t          *phInstance,
-                                   LVEQNB_MemTab_t          *pMemoryTable,
-                                   LVEQNB_Capabilities_t    *pCapabilities);
+/****************************************************************************************/
+/*                                                                                      */
+/* FUNCTION:                LVEQNB_DeInit                                               */
+/*                                                                                      */
+/* DESCRIPTION:                                                                         */
+/*    Free the memories created during LVEQNB_Init including instance handle            */
+/*                                                                                      */
+/* PARAMETERS:                                                                          */
+/*  phInstance              Pointer to instance handle                                  */
+/*                                                                                      */
+/* NOTES:                                                                               */
+/*  1.  This function must not be interrupted by the LVEQNB_Process function            */
+/*                                                                                      */
+/****************************************************************************************/
+void LVEQNB_DeInit(LVEQNB_Handle_t* phInstance);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -377,8 +294,7 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVEQNB_ReturnStatus_en LVEQNB_GetParameters(LVEQNB_Handle_t     hInstance,
-                                            LVEQNB_Params_t     *pParams);
+LVEQNB_ReturnStatus_en LVEQNB_GetParameters(LVEQNB_Handle_t hInstance, LVEQNB_Params_t* pParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -401,8 +317,8 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVEQNB_ReturnStatus_en LVEQNB_GetCapabilities(LVEQNB_Handle_t           hInstance,
-                                              LVEQNB_Capabilities_t     *pCapabilities);
+LVEQNB_ReturnStatus_en LVEQNB_GetCapabilities(LVEQNB_Handle_t hInstance,
+                                              LVEQNB_Capabilities_t* pCapabilities);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -426,8 +342,7 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVEQNB_ReturnStatus_en LVEQNB_Control(LVEQNB_Handle_t       hInstance,
-                                      LVEQNB_Params_t       *pParams);
+LVEQNB_ReturnStatus_en LVEQNB_Control(LVEQNB_Handle_t hInstance, LVEQNB_Params_t* pParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -451,10 +366,7 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-LVEQNB_ReturnStatus_en LVEQNB_Process(LVEQNB_Handle_t       hInstance,
-                                      const LVM_FLOAT       *pInData,
-                                      LVM_FLOAT             *pOutData,
-                                      LVM_UINT16            NumSamples);
+LVEQNB_ReturnStatus_en LVEQNB_Process(LVEQNB_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                      LVM_FLOAT* pOutData, LVM_UINT16 NumSamples);
 
-#endif      /* __LVEQNB__ */
-
+#endif /* __LVEQNB__ */
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_CalcCoef.cpp b/media/libeffects/lvm/lib/Eq/src/LVEQNB_CalcCoef.cpp
index c3c0fad..f8a5f2a 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_CalcCoef.cpp
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_CalcCoef.cpp
@@ -111,43 +111,37 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVEQNB_ReturnStatus_en LVEQNB_SinglePrecCoefs(LVM_UINT16        Fs,
-                                              LVEQNB_BandDef_t  *pFilterDefinition,
-                                              PK_FLOAT_Coefs_t  *pCoefficients)
-{
-
-    extern LVM_FLOAT    LVEQNB_GainTable[];
-    extern LVM_FLOAT    LVEQNB_TwoPiOnFsTable[];
-    extern LVM_FLOAT    LVEQNB_DTable[];
+LVEQNB_ReturnStatus_en LVEQNB_SinglePrecCoefs(LVM_UINT16 Fs, LVEQNB_BandDef_t* pFilterDefinition,
+                                              PK_FLOAT_Coefs_t* pCoefficients) {
+    extern LVM_FLOAT LVEQNB_GainTable[];
+    extern LVM_FLOAT LVEQNB_TwoPiOnFsTable[];
+    extern LVM_FLOAT LVEQNB_DTable[];
 
     /*
      * Get the filter definition
      */
-    LVM_INT16           Gain        = pFilterDefinition->Gain;
-    LVM_UINT16          Frequency   = pFilterDefinition->Frequency;
+    LVM_INT16 Gain = pFilterDefinition->Gain;
+    LVM_UINT16 Frequency = pFilterDefinition->Frequency;
     /* As mentioned in effectbundle.h */
-    LVM_FLOAT           QFactor     = (LVM_FLOAT)pFilterDefinition->QFactor / 100.0f;
+    LVM_FLOAT QFactor = (LVM_FLOAT)pFilterDefinition->QFactor / 100.0f;
 
     /*
      * Intermediate variables and temporary values
      */
-    LVM_FLOAT           T0;
-    LVM_FLOAT           D;
-    LVM_FLOAT           A0;
-    LVM_FLOAT           B1;
-    LVM_FLOAT           B2;
+    LVM_FLOAT T0;
+    LVM_FLOAT D;
+    LVM_FLOAT A0;
+    LVM_FLOAT B1;
+    LVM_FLOAT B2;
 
     /*
      * Calculating the intermediate values
      */
-    T0 = Frequency * LVEQNB_TwoPiOnFsTable[Fs];        /* T0 = 2 * Pi * Fc / Fs */
-    if (Gain >= 0)
-    {
-        D = LVEQNB_DTable[15];                         /* D = 1            if GaindB >= 0 */
-    }
-    else
-    {
-        D = LVEQNB_DTable[Gain + 15];                    /* D = 1 / (1 + G)  if GaindB <  0 */
+    T0 = Frequency * LVEQNB_TwoPiOnFsTable[Fs]; /* T0 = 2 * Pi * Fc / Fs */
+    if (Gain >= 0) {
+        D = LVEQNB_DTable[15]; /* D = 1            if GaindB >= 0 */
+    } else {
+        D = LVEQNB_DTable[Gain + 15]; /* D = 1 / (1 + G)  if GaindB <  0 */
     }
 
     /*
@@ -164,7 +158,7 @@
     pCoefficients->A0 = 2 * A0;
     pCoefficients->B1 = 2 * B1;
     pCoefficients->B2 = 2 * B2;
-    pCoefficients->G  = LVEQNB_GainTable[Gain + 15];
+    pCoefficients->G = LVEQNB_GainTable[Gain + 15];
 
-    return(LVEQNB_SUCCESS);
+    return (LVEQNB_SUCCESS);
 }
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
index 6329181..c44a9be 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Coeffs.h
@@ -23,78 +23,78 @@
 /* Gain table for (10^(Gain/20) - 1)                                                */
 /*                                                                                  */
 /************************************************************************************/
-#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
-#define LVEQNB_Gain_3_dB                                  0.412538f
-#define LVEQNB_Gain_4_dB                                  0.584893f
-#define LVEQNB_Gain_5_dB                                  0.778279f
-#define LVEQNB_Gain_6_dB                                  0.995262f
-#define LVEQNB_Gain_7_dB                                  1.238721f
-#define LVEQNB_Gain_8_dB                                  1.511886f
-#define LVEQNB_Gain_9_dB                                  1.818383f
-#define LVEQNB_Gain_10_dB                                 2.162278f
-#define LVEQNB_Gain_11_dB                                 2.548134f
-#define LVEQNB_Gain_12_dB                                 2.981072f
-#define LVEQNB_Gain_13_dB                                 3.466836f
-#define LVEQNB_Gain_14_dB                                 4.011872f
-#define LVEQNB_Gain_15_dB                                 4.623413f
+#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
+#define LVEQNB_Gain_3_dB 0.412538f
+#define LVEQNB_Gain_4_dB 0.584893f
+#define LVEQNB_Gain_5_dB 0.778279f
+#define LVEQNB_Gain_6_dB 0.995262f
+#define LVEQNB_Gain_7_dB 1.238721f
+#define LVEQNB_Gain_8_dB 1.511886f
+#define LVEQNB_Gain_9_dB 1.818383f
+#define LVEQNB_Gain_10_dB 2.162278f
+#define LVEQNB_Gain_11_dB 2.548134f
+#define LVEQNB_Gain_12_dB 2.981072f
+#define LVEQNB_Gain_13_dB 3.466836f
+#define LVEQNB_Gain_14_dB 4.011872f
+#define LVEQNB_Gain_15_dB 4.623413f
 
 /************************************************************************************/
 /*                                                                                  */
 /* Frequency table for 2*Pi/Fs                                                      */
 /*                                                                                  */
 /************************************************************************************/
-#define LVEQNB_2PiOn_8000                                0.000785f
-#define LVEQNB_2PiOn_11025                               0.000570f
-#define LVEQNB_2PiOn_12000                               0.000524f
-#define LVEQNB_2PiOn_16000                               0.000393f
-#define LVEQNB_2PiOn_22050                               0.000285f
-#define LVEQNB_2PiOn_24000                               0.000262f
-#define LVEQNB_2PiOn_32000                               0.000196f
-#define LVEQNB_2PiOn_44100                               0.000142f
-#define LVEQNB_2PiOn_48000                               0.000131f
+#define LVEQNB_2PiOn_8000 0.000785f
+#define LVEQNB_2PiOn_11025 0.000570f
+#define LVEQNB_2PiOn_12000 0.000524f
+#define LVEQNB_2PiOn_16000 0.000393f
+#define LVEQNB_2PiOn_22050 0.000285f
+#define LVEQNB_2PiOn_24000 0.000262f
+#define LVEQNB_2PiOn_32000 0.000196f
+#define LVEQNB_2PiOn_44100 0.000142f
+#define LVEQNB_2PiOn_48000 0.000131f
 
-#define LVEQNB_2PiOn_88200                               0.000071f
-#define LVEQNB_2PiOn_96000                               0.000065f
-#define LVEQNB_2PiOn_176400                              0.000036f
-#define LVEQNB_2PiOn_192000                              0.000033f
+#define LVEQNB_2PiOn_88200 0.000071f
+#define LVEQNB_2PiOn_96000 0.000065f
+#define LVEQNB_2PiOn_176400 0.000036f
+#define LVEQNB_2PiOn_192000 0.000033f
 
 /************************************************************************************/
 /*                                                                                  */
 /* 50D table for 50 / ( 1 + Gain )                                                  */
 /*                                                                                  */
 /************************************************************************************/
-#define LVEQNB_100D_Neg15_dB                             5.623413f
-#define LVEQNB_100D_Neg14_dB                             5.011872f
-#define LVEQNB_100D_Neg13_dB                             4.466836f
-#define LVEQNB_100D_Neg12_dB                             3.981072f
-#define LVEQNB_100D_Neg11_dB                             3.548134f
-#define LVEQNB_100D_Neg10_dB                             3.162278f
-#define LVEQNB_100D_Neg9_dB                              2.818383f
-#define LVEQNB_100D_Neg8_dB                              2.511886f
-#define LVEQNB_100D_Neg7_dB                              2.238721f
-#define LVEQNB_100D_Neg6_dB                              1.995262f
-#define LVEQNB_100D_Neg5_dB                              1.778279f
-#define LVEQNB_100D_Neg4_dB                              1.584893f
-#define LVEQNB_100D_Neg3_dB                              1.412538f
-#define LVEQNB_100D_Neg2_dB                              1.258925f
-#define LVEQNB_100D_Neg1_dB                              1.122018f
-#define LVEQNB_100D_0_dB                                 1.000000f
+#define LVEQNB_100D_Neg15_dB 5.623413f
+#define LVEQNB_100D_Neg14_dB 5.011872f
+#define LVEQNB_100D_Neg13_dB 4.466836f
+#define LVEQNB_100D_Neg12_dB 3.981072f
+#define LVEQNB_100D_Neg11_dB 3.548134f
+#define LVEQNB_100D_Neg10_dB 3.162278f
+#define LVEQNB_100D_Neg9_dB 2.818383f
+#define LVEQNB_100D_Neg8_dB 2.511886f
+#define LVEQNB_100D_Neg7_dB 2.238721f
+#define LVEQNB_100D_Neg6_dB 1.995262f
+#define LVEQNB_100D_Neg5_dB 1.778279f
+#define LVEQNB_100D_Neg4_dB 1.584893f
+#define LVEQNB_100D_Neg3_dB 1.412538f
+#define LVEQNB_100D_Neg2_dB 1.258925f
+#define LVEQNB_100D_Neg1_dB 1.122018f
+#define LVEQNB_100D_0_dB 1.000000f
 
 #endif
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Control.cpp b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Control.cpp
index 6bb4a7e..7e5caed 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Control.cpp
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Control.cpp
@@ -21,6 +21,7 @@
 /*                                                                                      */
 /****************************************************************************************/
 
+#include <system/audio.h>
 #include "LVEQNB.h"
 #include "LVEQNB_Private.h"
 #include "VectorArithmetic.h"
@@ -32,8 +33,8 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-#define     LOW_FREQ            298             /* 32768/110 for low test frequency */
-#define     HIGH_FREQ           386             /* 32768/85 for high test frequency */
+#define LOW_FREQ 298  /* 32768/110 for low test frequency */
+#define HIGH_FREQ 386 /* 32768/85 for high test frequency */
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -56,23 +57,19 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVEQNB_ReturnStatus_en LVEQNB_GetParameters(LVEQNB_Handle_t     hInstance,
-                                            LVEQNB_Params_t     *pParams)
-{
+LVEQNB_ReturnStatus_en LVEQNB_GetParameters(LVEQNB_Handle_t hInstance, LVEQNB_Params_t* pParams) {
+    LVEQNB_Instance_t* pInstance = (LVEQNB_Instance_t*)hInstance;
 
-    LVEQNB_Instance_t    *pInstance =(LVEQNB_Instance_t  *)hInstance;
-
-   /*
+    /*
      * Check for error conditions
      */
-    if((hInstance == LVM_NULL) || (pParams == LVM_NULL))
-    {
+    if ((hInstance == LVM_NULL) || (pParams == LVM_NULL)) {
         return LVEQNB_NULLADDRESS;
     }
 
     *pParams = pInstance->Params;
 
-    return(LVEQNB_SUCCESS);
+    return (LVEQNB_SUCCESS);
 }
 
 /************************************************************************************/
@@ -96,20 +93,17 @@
 /*                                                                                  */
 /************************************************************************************/
 
-LVEQNB_ReturnStatus_en LVEQNB_GetCapabilities(LVEQNB_Handle_t           hInstance,
-                                              LVEQNB_Capabilities_t     *pCapabilities)
-{
+LVEQNB_ReturnStatus_en LVEQNB_GetCapabilities(LVEQNB_Handle_t hInstance,
+                                              LVEQNB_Capabilities_t* pCapabilities) {
+    LVEQNB_Instance_t* pInstance = (LVEQNB_Instance_t*)hInstance;
 
-    LVEQNB_Instance_t    *pInstance =(LVEQNB_Instance_t  *)hInstance;
-
-    if((hInstance == LVM_NULL) || (pCapabilities == LVM_NULL))
-    {
+    if ((hInstance == LVM_NULL) || (pCapabilities == LVM_NULL)) {
         return LVEQNB_NULLADDRESS;
     }
 
     *pCapabilities = pInstance->Capabilities;
 
-    return(LVEQNB_SUCCESS);
+    return (LVEQNB_SUCCESS);
 }
 
 /************************************************************************************/
@@ -134,33 +128,30 @@
 /*                                                                                  */
 /************************************************************************************/
 
-void    LVEQNB_SetFilters(LVEQNB_Instance_t     *pInstance,
-                          LVEQNB_Params_t       *pParams)
-{
-    extern const LVM_UINT32   LVEQNB_SampleRateTab[];           /* Sample rate table */
+void LVEQNB_SetFilters(LVEQNB_Instance_t* pInstance, LVEQNB_Params_t* pParams) {
+    extern const LVM_UINT32 LVEQNB_SampleRateTab[]; /* Sample rate table */
 
-    LVM_UINT16          i;                                      /* Filter band index */
-    LVM_UINT32          fs = (LVM_UINT32)LVEQNB_SampleRateTab[(LVM_UINT16)pParams->SampleRate];  /* Sample rate */
-    LVM_UINT32          fc;                                     /* Filter centre frequency */
-    LVM_INT16           QFactor;                                /* Filter Q factor */
+    LVM_UINT16 i; /* Filter band index */
+    LVM_UINT32 fs =
+            (LVM_UINT32)LVEQNB_SampleRateTab[(LVM_UINT16)pParams->SampleRate]; /* Sample rate */
+    LVM_UINT32 fc;     /* Filter centre frequency */
+    LVM_INT16 QFactor; /* Filter Q factor */
 
     pInstance->NBands = pParams->NBands;
 
-    for (i=0; i<pParams->NBands; i++)
-    {
+    for (i = 0; i < pParams->NBands; i++) {
         /*
          * Get the filter settings
          */
-        fc = (LVM_UINT32)pParams->pBandDefinition[i].Frequency;     /* Get the band centre frequency */
-        QFactor = (LVM_INT16)pParams->pBandDefinition[i].QFactor;   /* Get the band Q factor */
+        fc = (LVM_UINT32)pParams->pBandDefinition[i].Frequency; /* Get the band centre frequency */
+        QFactor = (LVM_INT16)pParams->pBandDefinition[i].QFactor; /* Get the band Q factor */
 
         pInstance->pBiquadType[i] = LVEQNB_SinglePrecision_Float; /* Default to single precision */
 
         /*
          * Check for out of range frequencies
          */
-        if (fc > (fs >> 1))
-        {
+        if (fc > (fs >> 1)) {
             pInstance->pBiquadType[i] = LVEQNB_OutOfRange;
         }
 
@@ -168,7 +159,6 @@
          * Copy the filter definition to persistant memory
          */
         pInstance->pBandDefinitions[i] = pParams->pBandDefinition[i];
-
     }
 }
 
@@ -186,46 +176,44 @@
 /*                                                                                  */
 /************************************************************************************/
 
-void    LVEQNB_SetCoefficients(LVEQNB_Instance_t     *pInstance)
-{
+void LVEQNB_SetCoefficients(LVEQNB_Instance_t* pInstance) {
+    LVM_UINT16 i;                    /* Filter band index */
+    LVEQNB_BiquadType_en BiquadType; /* Filter biquad type */
 
-    LVM_UINT16              i;                          /* Filter band index */
-    LVEQNB_BiquadType_en    BiquadType;                 /* Filter biquad type */
-
+    pInstance->gain.resize(pInstance->Params.NBands);
     /*
      * Set the coefficients for each band by the init function
      */
-    for (i=0; i<pInstance->Params.NBands; i++)
-    {
-
+    for (i = 0; i < pInstance->Params.NBands; i++) {
         /*
          * Check band type for correct initialisation method and recalculate the coefficients
          */
         BiquadType = pInstance->pBiquadType[i];
-        switch  (BiquadType)
-        {
-            case    LVEQNB_SinglePrecision_Float:
-            {
-                PK_FLOAT_Coefs_t      Coefficients;
+        switch (BiquadType) {
+            case LVEQNB_SinglePrecision_Float: {
+                PK_FLOAT_Coefs_t Coefficients;
                 /*
                  * Calculate the single precision coefficients
                  */
                 LVEQNB_SinglePrecCoefs((LVM_UINT16)pInstance->Params.SampleRate,
-                                       &pInstance->pBandDefinitions[i],
-                                       &Coefficients);
+                                       &pInstance->pBandDefinitions[i], &Coefficients);
                 /*
                  * Set the coefficients
                  */
-                PK_2I_D32F32CssGss_TRC_WRA_01_Init(&pInstance->pEQNB_FilterState_Float[i],
-                                                   &pInstance->pEQNB_Taps_Float[i],
-                                                   &Coefficients);
+                pInstance->gain[i] = Coefficients.G;
+                std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                        Coefficients.A0, 0.0, -(Coefficients.A0), -(Coefficients.B1),
+                        -(Coefficients.B2)};
+                pInstance->eqBiquad[i]
+                        .setCoefficients<
+                                std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs>>(
+                                coefs);
                 break;
             }
             default:
                 break;
         }
     }
-
 }
 
 /************************************************************************************/
@@ -239,20 +227,9 @@
 /*  pInstance           Pointer to the instance                                     */
 /*                                                                                  */
 /************************************************************************************/
-void    LVEQNB_ClearFilterHistory(LVEQNB_Instance_t     *pInstance)
-{
-    LVM_FLOAT       *pTapAddress;
-    LVM_INT16       NumTaps;
-
-    pTapAddress = (LVM_FLOAT *)pInstance->pEQNB_Taps_Float;
-    NumTaps     = (LVM_INT16)((pInstance->Capabilities.MaxBands * \
-                                    sizeof(Biquad_2I_Order2_FLOAT_Taps_t)) / sizeof(LVM_FLOAT));
-
-    if (NumTaps != 0)
-    {
-        LoadConst_Float(0,                                 /* Clear the history, value 0 */
-                        pTapAddress,                       /* Destination */
-                        NumTaps);                          /* Number of words */
+void LVEQNB_ClearFilterHistory(LVEQNB_Instance_t* pInstance) {
+    for (size_t i = 0; i < pInstance->eqBiquad.size(); i++) {
+        pInstance->eqBiquad[i].clear();
     }
 }
 /****************************************************************************************/
@@ -277,56 +254,47 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVEQNB_ReturnStatus_en LVEQNB_Control(LVEQNB_Handle_t        hInstance,
-                                      LVEQNB_Params_t        *pParams)
-{
-
-    LVEQNB_Instance_t    *pInstance = (LVEQNB_Instance_t  *)hInstance;
-    LVM_INT16            bChange    = LVM_FALSE;
-    LVM_INT16            i = 0;
-    LVEQNB_Mode_en       OperatingModeSave ;
+LVEQNB_ReturnStatus_en LVEQNB_Control(LVEQNB_Handle_t hInstance, LVEQNB_Params_t* pParams) {
+    LVEQNB_Instance_t* pInstance = (LVEQNB_Instance_t*)hInstance;
+    LVM_INT16 bChange = LVM_FALSE;
+    LVM_INT16 i = 0;
+    LVEQNB_Mode_en OperatingModeSave;
 
     /*
      * Check for error conditions
      */
-    if((hInstance == LVM_NULL) || (pParams == LVM_NULL))
-    {
+    if ((hInstance == LVM_NULL) || (pParams == LVM_NULL)) {
         return LVEQNB_NULLADDRESS;
     }
 
-    if((pParams->NBands !=0) && (pParams->pBandDefinition==LVM_NULL))
-    {
+    if ((pParams->NBands != 0) && (pParams->pBandDefinition == LVM_NULL)) {
         return LVEQNB_NULLADDRESS;
     }
 
     OperatingModeSave = pInstance->Params.OperatingMode;
 
     /* Set the alpha factor of the mixer */
-    if (pParams->SampleRate != pInstance->Params.SampleRate)
-    {
-        LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMixer.MixerStream[0],LVEQNB_BYPASS_MIXER_TC,(LVM_Fs_en)pParams->SampleRate,2);
-        LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMixer.MixerStream[1],LVEQNB_BYPASS_MIXER_TC,(LVM_Fs_en)pParams->SampleRate,2);
+    if (pParams->SampleRate != pInstance->Params.SampleRate) {
+        LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMixer.MixerStream[0],
+                                           LVEQNB_BYPASS_MIXER_TC, (LVM_Fs_en)pParams->SampleRate,
+                                           2);
+        LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMixer.MixerStream[1],
+                                           LVEQNB_BYPASS_MIXER_TC, (LVM_Fs_en)pParams->SampleRate,
+                                           2);
     }
 
-    if( (pInstance->Params.NBands            !=  pParams->NBands          ) ||
-        (pInstance->Params.OperatingMode     !=  pParams->OperatingMode   ) ||
-        (pInstance->Params.pBandDefinition   !=  pParams->pBandDefinition ) ||
-        (pInstance->Params.SampleRate        !=  pParams->SampleRate      ) ||
-        (pInstance->Params.SourceFormat      !=  pParams->SourceFormat    ))
-    {
-
+    if ((pInstance->Params.NBands != pParams->NBands) ||
+        (pInstance->Params.OperatingMode != pParams->OperatingMode) ||
+        (pInstance->Params.pBandDefinition != pParams->pBandDefinition) ||
+        (pInstance->Params.SampleRate != pParams->SampleRate) ||
+        (pInstance->Params.SourceFormat != pParams->SourceFormat)) {
         bChange = LVM_TRUE;
-    }
-    else
-    {
-        for(i = 0; i < pParams->NBands; i++)
-        {
-
-            if((pInstance->pBandDefinitions[i].Frequency  != pParams->pBandDefinition[i].Frequency )||
-                (pInstance->pBandDefinitions[i].Gain       != pParams->pBandDefinition[i].Gain      )||
-                (pInstance->pBandDefinitions[i].QFactor    != pParams->pBandDefinition[i].QFactor   ))
-            {
-
+    } else {
+        for (i = 0; i < pParams->NBands; i++) {
+            if ((pInstance->pBandDefinitions[i].Frequency !=
+                 pParams->pBandDefinition[i].Frequency) ||
+                (pInstance->pBandDefinitions[i].Gain != pParams->pBandDefinition[i].Gain) ||
+                (pInstance->pBandDefinitions[i].QFactor != pParams->pBandDefinition[i].QFactor)) {
                 bChange = LVM_TRUE;
             }
         }
@@ -335,19 +303,24 @@
     // During operating mode transition, there is a race condition where the mode
     // is still LVEQNB_ON, but the effect is considered disabled in the upper layers.
     // modeChange handles this special race condition.
-    const int /* bool */ modeChange = pParams->OperatingMode != OperatingModeSave
-            || (OperatingModeSave == LVEQNB_ON
-                    && pInstance->bInOperatingModeTransition
-                    && LVC_Mixer_GetTarget(&pInstance->BypassMixer.MixerStream[0]) == 0);
+    const int /* bool */ modeChange =
+            pParams->OperatingMode != OperatingModeSave ||
+            (OperatingModeSave == LVEQNB_ON && pInstance->bInOperatingModeTransition &&
+             LVC_Mixer_GetTarget(&pInstance->BypassMixer.MixerStream[0]) == 0);
+
+    /*
+     * Create biquad instance
+     */
+    pInstance->eqBiquad.resize(pParams->NBands,
+                               android::audio_utils::BiquadFilter<LVM_FLOAT>(pParams->NrChannels));
+    LVEQNB_ClearFilterHistory(pInstance);
 
     if (bChange || modeChange) {
-
         /*
          * If the sample rate has changed clear the history
          */
-        if (pInstance->Params.SampleRate != pParams->SampleRate)
-        {
-            LVEQNB_ClearFilterHistory(pInstance);           /* Clear the history */
+        if (pInstance->Params.SampleRate != pParams->SampleRate) {
+            LVEQNB_ClearFilterHistory(pInstance); /* Clear the history */
         }
 
         /*
@@ -358,45 +331,45 @@
         /*
          * Reset the filters except if the algo is switched off
          */
-        if(pParams->OperatingMode != LVEQNB_BYPASS){
+        if (pParams->OperatingMode != LVEQNB_BYPASS) {
             /*
              * Reset the filters as all parameters could have changed
              */
-            LVEQNB_SetFilters(pInstance,                        /* Instance pointer */
-                              pParams);                         /* New parameters */
+            LVEQNB_SetFilters(pInstance, /* Instance pointer */
+                              pParams);  /* New parameters */
 
             /*
              * Update the filters
              */
-            LVEQNB_SetCoefficients(pInstance);                  /* Instance pointer */
+            LVEQNB_SetCoefficients(pInstance); /* Instance pointer */
         }
 
         if (modeChange) {
-            if(pParams->OperatingMode == LVEQNB_ON)
-            {
+            if (pParams->OperatingMode == LVEQNB_ON) {
                 LVC_Mixer_SetTarget(&pInstance->BypassMixer.MixerStream[0], 1.0f);
                 LVC_Mixer_SetTarget(&pInstance->BypassMixer.MixerStream[1], 0.0f);
-                pInstance->BypassMixer.MixerStream[0].CallbackSet        = 1;
-                pInstance->BypassMixer.MixerStream[1].CallbackSet        = 1;
-            }
-            else
-            {
+                pInstance->BypassMixer.MixerStream[0].CallbackSet = 1;
+                pInstance->BypassMixer.MixerStream[1].CallbackSet = 1;
+            } else {
                 /* Stay on the ON operating mode until the transition is done */
                 // This may introduce a state race condition if the effect is enabled again
                 // while in transition.  This is fixed in the modeChange logic.
                 pInstance->Params.OperatingMode = LVEQNB_ON;
                 LVC_Mixer_SetTarget(&pInstance->BypassMixer.MixerStream[0], 0.0f);
                 LVC_Mixer_SetTarget(&pInstance->BypassMixer.MixerStream[1], 1.0f);
-                pInstance->BypassMixer.MixerStream[0].CallbackSet        = 1;
-                pInstance->BypassMixer.MixerStream[1].CallbackSet        = 1;
+                pInstance->BypassMixer.MixerStream[0].CallbackSet = 1;
+                pInstance->BypassMixer.MixerStream[1].CallbackSet = 1;
             }
-            LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMixer.MixerStream[0],LVEQNB_BYPASS_MIXER_TC,(LVM_Fs_en)pParams->SampleRate,2);
-            LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMixer.MixerStream[1],LVEQNB_BYPASS_MIXER_TC,(LVM_Fs_en)pParams->SampleRate,2);
+            LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMixer.MixerStream[0],
+                                               LVEQNB_BYPASS_MIXER_TC,
+                                               (LVM_Fs_en)pParams->SampleRate, 2);
+            LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMixer.MixerStream[1],
+                                               LVEQNB_BYPASS_MIXER_TC,
+                                               (LVM_Fs_en)pParams->SampleRate, 2);
             pInstance->bInOperatingModeTransition = LVM_TRUE;
         }
-
     }
-    return(LVEQNB_SUCCESS);
+    return (LVEQNB_SUCCESS);
 }
 
 /****************************************************************************************/
@@ -408,23 +381,22 @@
 /*  transition                                                                          */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_INT32 LVEQNB_BypassMixerCallBack (void* hInstance,
-                                      void *pGeneralPurpose,
-                                      LVM_INT16 CallbackParam)
-{
-    LVEQNB_Instance_t      *pInstance =(LVEQNB_Instance_t  *)hInstance;
-    LVM_Callback            CallBack  = pInstance->Capabilities.CallBack;
+LVM_INT32 LVEQNB_BypassMixerCallBack(void* hInstance, void* pGeneralPurpose,
+                                     LVM_INT16 CallbackParam) {
+    LVEQNB_Instance_t* pInstance = (LVEQNB_Instance_t*)hInstance;
+    LVM_Callback CallBack = pInstance->Capabilities.CallBack;
 
-    (void) pGeneralPurpose;
+    (void)pGeneralPurpose;
 
-     /*
-      * Send an ALGOFF event if the ON->OFF switch transition is finished
-      */
-    if((LVC_Mixer_GetTarget(&pInstance->BypassMixer.MixerStream[0]) == 0) &&
-       (CallbackParam == 0)){
+    /*
+     * Send an ALGOFF event if the ON->OFF switch transition is finished
+     */
+    if ((LVC_Mixer_GetTarget(&pInstance->BypassMixer.MixerStream[0]) == 0) &&
+        (CallbackParam == 0)) {
         pInstance->Params.OperatingMode = LVEQNB_BYPASS;
-        if (CallBack != LVM_NULL){
-            CallBack(pInstance->Capabilities.pBundleInstance, LVM_NULL, ALGORITHM_EQNB_ID|LVEQNB_EVENT_ALGOFF);
+        if (CallBack != LVM_NULL) {
+            CallBack(pInstance->Capabilities.pBundleInstance, LVM_NULL,
+                     ALGORITHM_EQNB_ID | LVEQNB_EVENT_ALGOFF);
         }
     }
 
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Init.cpp b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Init.cpp
index 271a914..8cb7013 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Init.cpp
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Init.cpp
@@ -21,6 +21,7 @@
 /*                                                                                      */
 /****************************************************************************************/
 
+#include <stdlib.h>
 #include "LVEQNB.h"
 #include "LVEQNB_Private.h"
 #include "InstAlloc.h"
@@ -28,295 +29,120 @@
 
 /****************************************************************************************/
 /*                                                                                      */
-/* FUNCTION:                LVEQNB_Memory                                               */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*  This function is used for memory allocation and free. It can be called in           */
-/*  two ways:                                                                           */
-/*                                                                                      */
-/*      hInstance = NULL                Returns the memory requirements                 */
-/*      hInstance = Instance handle     Returns the memory requirements and             */
-/*                                      allocated base addresses for the instance       */
-/*                                                                                      */
-/*  When this function is called for memory allocation (hInstance=NULL) the memory      */
-/*  base address pointers are NULL on return.                                           */
-/*                                                                                      */
-/*  When the function is called for free (hInstance = Instance Handle) the memory       */
-/*  table returns the allocated memory and base addresses used during initialisation.   */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance               Instance Handle                                             */
-/*  pMemoryTable            Pointer to an empty memory definition table                 */
-/*  pCapabilities           Pointer to the instance capabilities                        */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVEQNB_SUCCESS          Succeeded                                                   */
-/*  LVEQNB_NULLADDRESS      When any of pMemoryTable and pCapabilities is NULL address  */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*  1.  This function may be interrupted by the LVEQNB_Process function                 */
-/*                                                                                      */
-/****************************************************************************************/
-
-LVEQNB_ReturnStatus_en LVEQNB_Memory(LVEQNB_Handle_t            hInstance,
-                                     LVEQNB_MemTab_t            *pMemoryTable,
-                                     LVEQNB_Capabilities_t      *pCapabilities)
-{
-
-    INST_ALLOC          AllocMem;
-    LVEQNB_Instance_t   *pInstance = (LVEQNB_Instance_t *)hInstance;
-
-    if((pMemoryTable == LVM_NULL)|| (pCapabilities == LVM_NULL))
-    {
-        return LVEQNB_NULLADDRESS;
-    }
-
-    /*
-     * Fill in the memory table
-     */
-    if (hInstance == LVM_NULL)
-    {
-        /*
-         * Instance memory
-         */
-        InstAlloc_Init(&AllocMem,
-                       LVM_NULL);
-        InstAlloc_AddMember(&AllocMem,                              /* Low pass filter */
-                            sizeof(LVEQNB_Instance_t));
-        pMemoryTable->Region[LVEQNB_MEMREGION_INSTANCE].Size         = InstAlloc_GetTotal(&AllocMem);
-        pMemoryTable->Region[LVEQNB_MEMREGION_INSTANCE].Alignment    = LVEQNB_INSTANCE_ALIGN;
-        pMemoryTable->Region[LVEQNB_MEMREGION_INSTANCE].Type         = LVEQNB_PERSISTENT;
-        pMemoryTable->Region[LVEQNB_MEMREGION_INSTANCE].pBaseAddress = LVM_NULL;
-
-        /*
-         * Persistant data memory
-         */
-        InstAlloc_Init(&AllocMem,
-                       LVM_NULL);
-        InstAlloc_AddMember(&AllocMem,                              /* Low pass filter */
-                            sizeof(Biquad_2I_Order2_FLOAT_Taps_t));
-        InstAlloc_AddMember(&AllocMem,                              /* High pass filter */
-                            sizeof(Biquad_2I_Order2_FLOAT_Taps_t));
-        /* Equaliser Biquad Taps */
-        InstAlloc_AddMember(&AllocMem,
-                            (pCapabilities->MaxBands * sizeof(Biquad_2I_Order2_FLOAT_Taps_t)));
-        /* Filter definitions */
-        InstAlloc_AddMember(&AllocMem,
-                            (pCapabilities->MaxBands * sizeof(LVEQNB_BandDef_t)));
-        /* Biquad types */
-        InstAlloc_AddMember(&AllocMem,
-                            (pCapabilities->MaxBands * sizeof(LVEQNB_BiquadType_en)));
-        pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_DATA].Size         = InstAlloc_GetTotal(&AllocMem);
-        pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_DATA].Alignment    = LVEQNB_DATA_ALIGN;
-        pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_DATA].Type         = LVEQNB_PERSISTENT_DATA;
-        pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_DATA].pBaseAddress = LVM_NULL;
-
-        /*
-         * Persistant coefficient memory
-         */
-        InstAlloc_Init(&AllocMem,
-                       LVM_NULL);
-        InstAlloc_AddMember(&AllocMem,                              /* Low pass filter */
-                            sizeof(Biquad_FLOAT_Instance_t));
-        InstAlloc_AddMember(&AllocMem,                              /* High pass filter */
-                            sizeof(Biquad_FLOAT_Instance_t));
-        /* Equaliser Biquad Instance */
-        InstAlloc_AddMember(&AllocMem,
-                            pCapabilities->MaxBands * sizeof(Biquad_FLOAT_Instance_t));
-        pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_COEF].Size         = InstAlloc_GetTotal(&AllocMem);
-        pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_COEF].Alignment    = LVEQNB_COEF_ALIGN;
-        pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_COEF].Type         = LVEQNB_PERSISTENT_COEF;
-        pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_COEF].pBaseAddress = LVM_NULL;
-
-        /*
-         * Scratch memory
-         */
-        InstAlloc_Init(&AllocMem,
-                       LVM_NULL);
-        InstAlloc_AddMember(&AllocMem,                              /* Low pass filter */
-                            LVEQNB_SCRATCHBUFFERS * sizeof(LVM_FLOAT) * \
-                                             pCapabilities->MaxBlockSize);
-        pMemoryTable->Region[LVEQNB_MEMREGION_SCRATCH].Size              = InstAlloc_GetTotal(&AllocMem);
-        pMemoryTable->Region[LVEQNB_MEMREGION_SCRATCH].Alignment         = LVEQNB_SCRATCH_ALIGN;
-        pMemoryTable->Region[LVEQNB_MEMREGION_SCRATCH].Type              = LVEQNB_SCRATCH;
-        pMemoryTable->Region[LVEQNB_MEMREGION_SCRATCH].pBaseAddress      = LVM_NULL;
-    }
-    else
-    {
-        /* Read back memory allocation table */
-        *pMemoryTable = pInstance->MemoryTable;
-    }
-
-    return(LVEQNB_SUCCESS);
-}
-
-/****************************************************************************************/
-/*                                                                                      */
 /* FUNCTION:                LVEQNB_Init                                                 */
 /*                                                                                      */
 /* DESCRIPTION:                                                                         */
-/*  Create and initialisation function for the N-Band equaliser module                  */
-/*                                                                                      */
-/*  This function can be used to create an algorithm instance by calling with           */
-/*  hInstance set to NULL. In this case the algorithm returns the new instance          */
-/*  handle.                                                                             */
-/*                                                                                      */
-/*  This function can be used to force a full re-initialisation of the algorithm        */
-/*  by calling with hInstance = Instance Handle. In this case the memory table          */
-/*  should be correct for the instance, this can be ensured by calling the function     */
-/*  DBE_Memory before calling this function.                                            */
+/*  Create and initialisation function for the N-Band equaliser module.                 */
 /*                                                                                      */
 /* PARAMETERS:                                                                          */
-/*  hInstance               Instance handle                                             */
-/*  pMemoryTable            Pointer to the memory definition table                      */
-/*  pCapabilities           Pointer to the instance capabilities                        */
+/*  phInstance              Pointer to instance handle                                  */
+/*  pCapabilities           Pointer to the initialisation capabilities                  */
+/*  pScratch                Pointer to bundle scratch buffer                            */
 /*                                                                                      */
 /* RETURNS:                                                                             */
 /*  LVEQNB_SUCCESS          Initialisation succeeded                                    */
-/*  LVEQNB_NULLADDRESS        When pCapabilities or pMemoryTableis or phInstance are NULL */
-/*  LVEQNB_NULLADDRESS        One or more of the memory regions has a NULL base address   */
-/*                          pointer for a memory region with a non-zero size.           */
+/*  LVEQNB_NULLADDRESS      One or more memory has a NULL pointer - malloc failure      */
 /*                                                                                      */
 /* NOTES:                                                                               */
-/*  1.  The instance handle is the pointer to the base address of the first memory      */
-/*      region.                                                                         */
-/*  2.  This function must not be interrupted by the LVEQNB_Process function            */
+/*  1.  This function must not be interrupted by the LVEQNB_Process function            */
 /*                                                                                      */
 /****************************************************************************************/
 
-LVEQNB_ReturnStatus_en LVEQNB_Init(LVEQNB_Handle_t          *phInstance,
-                                   LVEQNB_MemTab_t          *pMemoryTable,
-                                   LVEQNB_Capabilities_t    *pCapabilities)
-{
+LVEQNB_ReturnStatus_en LVEQNB_Init(LVEQNB_Handle_t* phInstance,
+                                   LVEQNB_Capabilities_t* pCapabilities, void* pScratch) {
+    LVEQNB_Instance_t* pInstance;
 
-    LVEQNB_Instance_t   *pInstance;
-    LVM_UINT32          MemSize;
-    INST_ALLOC          AllocMem;
-    LVM_INT32           i;
+    *phInstance = new LVEQNB_Instance_t{};
+    pInstance = (LVEQNB_Instance_t*)*phInstance;
 
-    /*
-     * Check for NULL pointers
-     */
-    if((phInstance == LVM_NULL) || (pMemoryTable == LVM_NULL) || (pCapabilities == LVM_NULL))
-    {
-        return LVEQNB_NULLADDRESS;
-    }
-
-    /*
-     * Check the memory table for NULL pointers
-     */
-    for (i = 0; i < LVEQNB_NR_MEMORY_REGIONS; i++)
-    {
-        if (pMemoryTable->Region[i].Size!=0)
-        {
-            if (pMemoryTable->Region[i].pBaseAddress==LVM_NULL)
-            {
-                return(LVEQNB_NULLADDRESS);
-            }
-        }
-    }
-
-    /*
-     * Set the instance handle if not already initialised
-     */
-
-    InstAlloc_Init(&AllocMem,  pMemoryTable->Region[LVEQNB_MEMREGION_INSTANCE].pBaseAddress);
-
-    if (*phInstance == LVM_NULL)
-    {
-        *phInstance = InstAlloc_AddMember(&AllocMem, sizeof(LVEQNB_Instance_t));
-    }
-    pInstance =(LVEQNB_Instance_t  *)*phInstance;
-
-    /*
-     * Save the memory table in the instance structure
-     */
     pInstance->Capabilities = *pCapabilities;
-
-    /*
-     * Save the memory table in the instance structure and
-     * set the structure pointers
-     */
-    pInstance->MemoryTable       = *pMemoryTable;
-
-    /*
-     * Allocate coefficient memory
-     */
-    InstAlloc_Init(&AllocMem,
-                   pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_COEF].pBaseAddress);
+    pInstance->pScratch = pScratch;
 
     /* Equaliser Biquad Instance */
-    pInstance->pEQNB_FilterState_Float = (Biquad_FLOAT_Instance_t *)
-        InstAlloc_AddMember(&AllocMem, pCapabilities->MaxBands * \
-                                                       sizeof(Biquad_FLOAT_Instance_t));
-
-    /*
-     * Allocate data memory
-     */
-    InstAlloc_Init(&AllocMem,
-                   pMemoryTable->Region[LVEQNB_MEMREGION_PERSISTENT_DATA].pBaseAddress);
-
-    MemSize = (pCapabilities->MaxBands * sizeof(Biquad_2I_Order2_FLOAT_Taps_t));
-    pInstance->pEQNB_Taps_Float = (Biquad_2I_Order2_FLOAT_Taps_t *)InstAlloc_AddMember(&AllocMem,
-                                                                                       MemSize);
-    MemSize = (pCapabilities->MaxBands * sizeof(LVEQNB_BandDef_t));
-    pInstance->pBandDefinitions  = (LVEQNB_BandDef_t *)InstAlloc_AddMember(&AllocMem,
-                                                                           MemSize);
+    LVM_UINT32 MemSize = pCapabilities->MaxBands * sizeof(*(pInstance->pBandDefinitions));
+    pInstance->pBandDefinitions = (LVEQNB_BandDef_t*)calloc(1, MemSize);
+    if (pInstance->pBandDefinitions == LVM_NULL) {
+        return LVEQNB_NULLADDRESS;
+    }
     // clear all the bands, setting their gain to 0, otherwise when applying new params,
     // it will compare against uninitialized values
     memset(pInstance->pBandDefinitions, 0, MemSize);
-    MemSize = (pCapabilities->MaxBands * sizeof(LVEQNB_BiquadType_en));
-    pInstance->pBiquadType = (LVEQNB_BiquadType_en *)InstAlloc_AddMember(&AllocMem,
-                                                                         MemSize);
 
-    /*
-     * Internally map, structure and allign scratch memory
-     */
-    InstAlloc_Init(&AllocMem,
-                   pMemoryTable->Region[LVEQNB_MEMREGION_SCRATCH].pBaseAddress);
+    MemSize = (pCapabilities->MaxBands * sizeof(*(pInstance->pBiquadType)));
+    pInstance->pBiquadType = (LVEQNB_BiquadType_en*)calloc(1, MemSize);
+    if (pInstance->pBiquadType == LVM_NULL) {
+        return LVEQNB_NULLADDRESS;
+    }
 
-    pInstance->pFastTemporary = (LVM_FLOAT *)InstAlloc_AddMember(&AllocMem,
-                                                                 sizeof(LVM_FLOAT));
+    pInstance->pFastTemporary = (LVM_FLOAT*)pScratch;
 
     /*
      * Update the instance parameters
      */
-    pInstance->Params.NBands          = 0;
-    pInstance->Params.OperatingMode   = LVEQNB_BYPASS;
+    pInstance->Params.NBands = 0;
+    pInstance->Params.OperatingMode = LVEQNB_BYPASS;
     pInstance->Params.pBandDefinition = LVM_NULL;
-    pInstance->Params.SampleRate      = LVEQNB_FS_8000;
-    pInstance->Params.SourceFormat    = LVEQNB_STEREO;
+    pInstance->Params.SampleRate = LVEQNB_FS_8000;
+    pInstance->Params.SourceFormat = LVEQNB_STEREO;
 
     /*
      * Initialise the filters
      */
-    LVEQNB_SetFilters(pInstance,                        /* Set the filter types */
+    LVEQNB_SetFilters(pInstance, /* Set the filter types */
                       &pInstance->Params);
 
-    LVEQNB_SetCoefficients(pInstance);                  /* Set the filter coefficients */
-
-    LVEQNB_ClearFilterHistory(pInstance);               /* Clear the filter history */
-
     /*
      * Initialise the bypass variables
      */
-    pInstance->BypassMixer.MixerStream[0].CallbackSet        = 0;
-    pInstance->BypassMixer.MixerStream[0].CallbackParam      = 0;
-    pInstance->BypassMixer.MixerStream[0].pCallbackHandle    = (void*)pInstance;
-    pInstance->BypassMixer.MixerStream[0].pCallBack          = LVEQNB_BypassMixerCallBack;
+    pInstance->BypassMixer.MixerStream[0].CallbackSet = 0;
+    pInstance->BypassMixer.MixerStream[0].CallbackParam = 0;
+    pInstance->BypassMixer.MixerStream[0].pCallbackHandle = (void*)pInstance;
+    pInstance->BypassMixer.MixerStream[0].pCallBack = LVEQNB_BypassMixerCallBack;
 
-    LVC_Mixer_Init(&pInstance->BypassMixer.MixerStream[0],0,0);
-    LVC_Mixer_SetTimeConstant(&pInstance->BypassMixer.MixerStream[0],0,LVM_FS_8000,2);
+    LVC_Mixer_Init(&pInstance->BypassMixer.MixerStream[0], 0, 0);
+    LVC_Mixer_SetTimeConstant(&pInstance->BypassMixer.MixerStream[0], 0, LVM_FS_8000, 2);
 
-    pInstance->BypassMixer.MixerStream[1].CallbackSet        = 1;
-    pInstance->BypassMixer.MixerStream[1].CallbackParam      = 0;
-    pInstance->BypassMixer.MixerStream[1].pCallbackHandle    = LVM_NULL;
-    pInstance->BypassMixer.MixerStream[1].pCallBack          = LVM_NULL;
+    pInstance->BypassMixer.MixerStream[1].CallbackSet = 1;
+    pInstance->BypassMixer.MixerStream[1].CallbackParam = 0;
+    pInstance->BypassMixer.MixerStream[1].pCallbackHandle = LVM_NULL;
+    pInstance->BypassMixer.MixerStream[1].pCallBack = LVM_NULL;
     LVC_Mixer_Init(&pInstance->BypassMixer.MixerStream[1], 0, 1.0f);
     LVC_Mixer_SetTimeConstant(&pInstance->BypassMixer.MixerStream[1], 0, LVM_FS_8000, 2);
 
-    pInstance->bInOperatingModeTransition      = LVM_FALSE;
+    pInstance->bInOperatingModeTransition = LVM_FALSE;
 
-    return(LVEQNB_SUCCESS);
+    return (LVEQNB_SUCCESS);
 }
+/****************************************************************************************/
+/*                                                                                      */
+/* FUNCTION:                LVEQNB_DeInit                                               */
+/*                                                                                      */
+/* DESCRIPTION:                                                                         */
+/*    Free the memories created during LVEQNB_Init including instance handle            */
+/*                                                                                      */
+/* PARAMETERS:                                                                          */
+/*  phInstance              Pointer to instance handle                                  */
+/*                                                                                      */
+/* NOTES:                                                                               */
+/*  1.  This function must not be interrupted by the LVEQNB_Process function            */
+/*                                                                                      */
+/****************************************************************************************/
 
+void LVEQNB_DeInit(LVEQNB_Handle_t* phInstance) {
+    LVEQNB_Instance_t* pInstance;
+    if (phInstance == LVM_NULL) {
+        return;
+    }
+    pInstance = (LVEQNB_Instance_t*)*phInstance;
+
+    if (pInstance->pBandDefinitions != LVM_NULL) {
+        free(pInstance->pBandDefinitions);
+        pInstance->pBandDefinitions = LVM_NULL;
+    }
+    if (pInstance->pBiquadType != LVM_NULL) {
+        free(pInstance->pBiquadType);
+        pInstance->pBiquadType = LVM_NULL;
+    }
+    delete pInstance;
+    *phInstance = LVM_NULL;
+}
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Private.h b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Private.h
index 40facfb..2225fec 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Private.h
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Private.h
@@ -24,7 +24,8 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-#include "LVEQNB.h"                                     /* Calling or Application layer definitions */
+#include <audio_utils/BiquadFilter.h>
+#include "LVEQNB.h" /* Calling or Application layer definitions */
 #include "BIQUAD.h"
 #include "LVC_Mixer.h"
 
@@ -35,21 +36,8 @@
 /****************************************************************************************/
 
 /* General */
-#define LVEQNB_INVALID              0xFFFF              /* Invalid init parameter */
-
-/* Memory */
-#define LVEQNB_INSTANCE_ALIGN       4                   /* 32-bit alignment for instance structures */
-#define LVEQNB_DATA_ALIGN           4                   /* 32-bit alignment for structures */
-#define LVEQNB_COEF_ALIGN           4                   /* 32-bit alignment for long words */
-#ifdef SUPPORT_MC
-/* Number of buffers required for inplace processing */
-#define LVEQNB_SCRATCHBUFFERS       (LVM_MAX_CHANNELS * 2)
-#else
-#define LVEQNB_SCRATCHBUFFERS       4                   /* Number of buffers required for inplace processing */
-#endif
-#define LVEQNB_SCRATCH_ALIGN        4                   /* 32-bit alignment for long data */
-
-#define LVEQNB_BYPASS_MIXER_TC      100                 /* Bypass Mixer TC */
+#define LVEQNB_INVALID 0xFFFF      /* Invalid init parameter */
+#define LVEQNB_BYPASS_MIXER_TC 100 /* Bypass Mixer TC */
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -58,13 +46,12 @@
 /****************************************************************************************/
 
 /* Filter biquad types */
-typedef enum
-{
+typedef enum {
     LVEQNB_SinglePrecision_Float = -1,
     LVEQNB_SinglePrecision = 0,
     LVEQNB_DoublePrecision = 1,
-    LVEQNB_OutOfRange      = 2,
-    LVEQNB_BIQUADTYPE_MAX  = LVM_MAXINT_32
+    LVEQNB_OutOfRange = 2,
+    LVEQNB_BIQUADTYPE_MAX = LVM_MAXINT_32
 } LVEQNB_BiquadType_en;
 
 /****************************************************************************************/
@@ -74,28 +61,28 @@
 /****************************************************************************************/
 
 /* Instance structure */
-typedef struct
-{
+typedef struct {
     /* Public parameters */
-    LVEQNB_MemTab_t                 MemoryTable;        /* Instance memory allocation table */
-    LVEQNB_Params_t                 Params;             /* Instance parameters */
-    LVEQNB_Capabilities_t           Capabilities;       /* Instance capabilities */
+    void* pScratch;                     /* Pointer to bundle scratch buffer */
+    LVEQNB_Params_t Params;             /* Instance parameters */
+    LVEQNB_Capabilities_t Capabilities; /* Instance capabilities */
 
     /* Aligned memory pointers */
-    LVM_FLOAT                      *pFastTemporary;        /* Fast temporary data base address */
+    LVM_FLOAT* pFastTemporary; /* Fast temporary data base address */
 
-    Biquad_2I_Order2_FLOAT_Taps_t   *pEQNB_Taps_Float;        /* Equaliser Taps */
-    Biquad_FLOAT_Instance_t         *pEQNB_FilterState_Float; /* State for each filter band */
+    std::vector<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            eqBiquad;            /* Biquad filter instances */
+    std::vector<LVM_FLOAT> gain; /* Gain values for all bands*/
 
     /* Filter definitions and call back */
-    LVM_UINT16                      NBands;             /* Number of bands */
-    LVEQNB_BandDef_t                *pBandDefinitions;  /* Filter band definitions */
-    LVEQNB_BiquadType_en            *pBiquadType;       /* Filter biquad types */
+    LVM_UINT16 NBands;                  /* Number of bands */
+    LVEQNB_BandDef_t* pBandDefinitions; /* Filter band definitions */
+    LVEQNB_BiquadType_en* pBiquadType;  /* Filter biquad types */
 
     /* Bypass variable */
-    LVMixer3_2St_FLOAT_st     BypassMixer;
+    LVMixer3_2St_FLOAT_st BypassMixer;
 
-    LVM_INT16               bInOperatingModeTransition; /* Operating mode transition flag */
+    LVM_INT16 bInOperatingModeTransition; /* Operating mode transition flag */
 
 } LVEQNB_Instance_t;
 
@@ -105,17 +92,15 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-void    LVEQNB_SetFilters(LVEQNB_Instance_t   *pInstance,
-                          LVEQNB_Params_t     *pParams);
+void LVEQNB_SetFilters(LVEQNB_Instance_t* pInstance, LVEQNB_Params_t* pParams);
 
-void    LVEQNB_SetCoefficients(LVEQNB_Instance_t    *pInstance);
+void LVEQNB_SetCoefficients(LVEQNB_Instance_t* pInstance);
 
-void    LVEQNB_ClearFilterHistory(LVEQNB_Instance_t *pInstance);
-LVEQNB_ReturnStatus_en LVEQNB_SinglePrecCoefs(LVM_UINT16        Fs,
-                                              LVEQNB_BandDef_t  *pFilterDefinition,
-                                              PK_FLOAT_Coefs_t    *pCoefficients);
+void LVEQNB_ClearFilterHistory(LVEQNB_Instance_t* pInstance);
+LVEQNB_ReturnStatus_en LVEQNB_SinglePrecCoefs(LVM_UINT16 Fs, LVEQNB_BandDef_t* pFilterDefinition,
+                                              PK_FLOAT_Coefs_t* pCoefficients);
 
-LVM_INT32 LVEQNB_BypassMixerCallBack (void* hInstance, void *pGeneralPurpose, LVM_INT16 CallbackParam);
+LVM_INT32 LVEQNB_BypassMixerCallBack(void* hInstance, void* pGeneralPurpose,
+                                     LVM_INT16 CallbackParam);
 
 #endif /* __LVEQNB_PRIVATE_H__ */
-
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Process.cpp b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Process.cpp
index 65eff53..b177dd4 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Process.cpp
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Process.cpp
@@ -34,7 +34,7 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-#define SHIFT       13
+#define SHIFT 13
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -58,89 +58,60 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-LVEQNB_ReturnStatus_en LVEQNB_Process(LVEQNB_Handle_t       hInstance,
-                                      const LVM_FLOAT       *pInData,
-                                      LVM_FLOAT             *pOutData,
-                                      const LVM_UINT16      NrFrames)
-{                                     // updated to use samples = frames * channels.
-    LVEQNB_Instance_t   *pInstance = (LVEQNB_Instance_t  *)hInstance;
-
-#ifdef SUPPORT_MC
-    // Mono passed in as stereo
-    const LVM_INT32 NrChannels = pInstance->Params.NrChannels == 1
-        ? 2 : pInstance->Params.NrChannels;
-#else
-    const LVM_INT32 NrChannels = 2; // FCC_2
-#endif
+LVEQNB_ReturnStatus_en LVEQNB_Process(
+        LVEQNB_Handle_t hInstance, const LVM_FLOAT* pInData, LVM_FLOAT* pOutData,
+        const LVM_UINT16 NrFrames) {  // updated to use samples = frames * channels.
+    LVEQNB_Instance_t* pInstance = (LVEQNB_Instance_t*)hInstance;
+    const LVM_INT32 NrChannels = pInstance->Params.NrChannels;
     const LVM_INT32 NrSamples = NrChannels * NrFrames;
 
-     /* Check for NULL pointers */
-    if((hInstance == LVM_NULL) || (pInData == LVM_NULL) || (pOutData == LVM_NULL))
-    {
+    /* Check for NULL pointers */
+    if ((hInstance == LVM_NULL) || (pInData == LVM_NULL) || (pOutData == LVM_NULL)) {
         return LVEQNB_NULLADDRESS;
     }
 
     /* Check if the input and output data buffers are 32-bit aligned */
-    if ((((uintptr_t)pInData % 4) != 0) || (((uintptr_t)pOutData % 4) != 0))
-    {
+    if ((((uintptr_t)pInData % 4) != 0) || (((uintptr_t)pOutData % 4) != 0)) {
         return LVEQNB_ALIGNMENTERROR;
     }
 
-    LVM_FLOAT * const pScratch = (LVM_FLOAT *)pInstance->pFastTemporary;
+    LVM_FLOAT* const pScratch = (LVM_FLOAT*)pInstance->pFastTemporary;
 
     /*
-    * Check the number of frames is not too large
-    */
-    if (NrFrames > pInstance->Capabilities.MaxBlockSize)
-    {
+     * Check the number of frames is not too large
+     */
+    if (NrFrames > pInstance->Capabilities.MaxBlockSize) {
         return LVEQNB_TOOMANYSAMPLES;
     }
 
-    if (pInstance->Params.OperatingMode == LVEQNB_ON)
-    {
+    if (pInstance->Params.OperatingMode == LVEQNB_ON) {
         /*
          * Copy input data in to scratch buffer
          */
-        Copy_Float(pInData,     /* Source */
-                   pScratch,    /* Destination */
+        Copy_Float(pInData,  /* Source */
+                   pScratch, /* Destination */
                    (LVM_INT16)NrSamples);
 
         /*
          * For each section execte the filter unless the gain is 0dB
          */
-        if (pInstance->NBands != 0)
-        {
-            for (LVM_UINT16 i = 0; i < pInstance->NBands; i++)
-            {
+        if (pInstance->NBands != 0) {
+            for (LVM_UINT16 i = 0; i < pInstance->NBands; i++) {
                 /*
                  * Check if band is non-zero dB gain
                  */
-                if (pInstance->pBandDefinitions[i].Gain != 0)
-                {
-                    /*
-                     * Get the address of the biquad instance
-                     */
-                    Biquad_FLOAT_Instance_t *pBiquad = &pInstance->pEQNB_FilterState_Float[i];
-
+                if (pInstance->pBandDefinitions[i].Gain != 0) {
                     /*
                      * Select single or double precision as required
                      */
-                    switch (pInstance->pBiquadType[i])
-                    {
-                        case LVEQNB_SinglePrecision_Float:
-                        {
-#ifdef SUPPORT_MC
-                            PK_Mc_D32F32C14G11_TRC_WRA_01(pBiquad,
-                                                          pScratch,
-                                                          pScratch,
-                                                          (LVM_INT16)NrFrames,
-                                                          (LVM_INT16)NrChannels);
-#else
-                            PK_2I_D32F32C14G11_TRC_WRA_01(pBiquad,
-                                                          pScratch,
-                                                          pScratch,
-                                                          (LVM_INT16)NrFrames);
-#endif
+                    switch (pInstance->pBiquadType[i]) {
+                        case LVEQNB_SinglePrecision_Float: {
+                            LVM_FLOAT* pTemp = pScratch + NrSamples;
+                            pInstance->eqBiquad[i].process(pTemp, pScratch, NrFrames);
+                            const auto gain = pInstance->gain[i];
+                            for (unsigned j = 0; j < NrSamples; ++j) {
+                                pScratch[j] += pTemp[j] * gain;
+                            }
                             break;
                         }
                         default:
@@ -150,44 +121,27 @@
             }
         }
 
-        if(pInstance->bInOperatingModeTransition == LVM_TRUE){
-#ifdef SUPPORT_MC
-            LVC_MixSoft_2Mc_D16C31_SAT(&pInstance->BypassMixer,
-                                       pScratch,
-                                       pInData,
-                                       pScratch,
-                                       (LVM_INT16)NrFrames,
-                                       (LVM_INT16)NrChannels);
-#else
-            LVC_MixSoft_2St_D16C31_SAT(&pInstance->BypassMixer,
-                                       pScratch,
-                                       pInData,
-                                       pScratch,
-                                       (LVM_INT16)NrSamples);
-#endif
+        if (pInstance->bInOperatingModeTransition == LVM_TRUE) {
+            LVC_MixSoft_2Mc_D16C31_SAT(&pInstance->BypassMixer, pScratch, pInData, pScratch,
+                                       (LVM_INT16)NrFrames, (LVM_INT16)NrChannels);
             // duplicate with else clause(s)
-            Copy_Float(pScratch,                         /* Source */
-                       pOutData,                         /* Destination */
-                       (LVM_INT16)NrSamples);            /* All channel samples */
-        }
-        else{
+            Copy_Float(pScratch,              /* Source */
+                       pOutData,              /* Destination */
+                       (LVM_INT16)NrSamples); /* All channel samples */
+        } else {
             Copy_Float(pScratch,              /* Source */
                        pOutData,              /* Destination */
                        (LVM_INT16)NrSamples); /* All channel samples */
         }
-    }
-    else
-    {
+    } else {
         /*
          * Mode is OFF so copy the data if necessary
          */
-        if (pInData != pOutData)
-        {
-            Copy_Float(pInData,                          /* Source */
-                       pOutData,                         /* Destination */
-                       (LVM_INT16)NrSamples);            /* All channel samples */
+        if (pInData != pOutData) {
+            Copy_Float(pInData,               /* Source */
+                       pOutData,              /* Destination */
+                       (LVM_INT16)NrSamples); /* All channel samples */
         }
     }
     return LVEQNB_SUCCESS;
-
 }
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Tables.cpp b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Tables.cpp
index 0628114..d79d7c9 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Tables.cpp
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Tables.cpp
@@ -35,20 +35,9 @@
  * Sample rate table for converting between the enumerated type and the actual
  * frequency
  */
-const LVM_UINT32    LVEQNB_SampleRateTab[] = {8000,                    /* 8kS/s  */
-                                              11025,
-                                              12000,
-                                              16000,
-                                              22050,
-                                              24000,
-                                              32000,
-                                              44100,
-                                              48000,
-                                              88200,
-                                              96000,
-                                              176400,
-                                              192000
-};
+const LVM_UINT32 LVEQNB_SampleRateTab[] = {8000, /* 8kS/s  */
+                                           11025, 12000, 16000, 22050, 24000,  32000,
+                                           44100, 48000, 88200, 96000, 176400, 192000};
 
 /************************************************************************************/
 /*                                                                                  */
@@ -59,74 +48,34 @@
 /*
  * Table for 2 * Pi / Fs
  */
-const LVM_FLOAT     LVEQNB_TwoPiOnFsTable[] = {LVEQNB_2PiOn_8000,      /* 8kS/s */
-                                               LVEQNB_2PiOn_11025,
-                                               LVEQNB_2PiOn_12000,
-                                               LVEQNB_2PiOn_16000,
-                                               LVEQNB_2PiOn_22050,
-                                               LVEQNB_2PiOn_24000,
-                                               LVEQNB_2PiOn_32000,
-                                               LVEQNB_2PiOn_44100,
-                                               LVEQNB_2PiOn_48000
-                                              ,LVEQNB_2PiOn_88200
-                                              ,LVEQNB_2PiOn_96000
-                                              ,LVEQNB_2PiOn_176400
-                                              ,LVEQNB_2PiOn_192000
-                                               };
+const LVM_FLOAT LVEQNB_TwoPiOnFsTable[] = {
+        LVEQNB_2PiOn_8000, /* 8kS/s */
+        LVEQNB_2PiOn_11025, LVEQNB_2PiOn_12000, LVEQNB_2PiOn_16000,  LVEQNB_2PiOn_22050,
+        LVEQNB_2PiOn_24000, LVEQNB_2PiOn_32000, LVEQNB_2PiOn_44100,  LVEQNB_2PiOn_48000,
+        LVEQNB_2PiOn_88200, LVEQNB_2PiOn_96000, LVEQNB_2PiOn_176400, LVEQNB_2PiOn_192000};
 
 /*
  * Gain table
  */
-const LVM_FLOAT     LVEQNB_GainTable[] = {LVEQNB_Gain_Neg15_dB,        /* -15dB gain */
-                                          LVEQNB_Gain_Neg14_dB,
-                                          LVEQNB_Gain_Neg13_dB,
-                                          LVEQNB_Gain_Neg12_dB,
-                                          LVEQNB_Gain_Neg11_dB,
-                                          LVEQNB_Gain_Neg10_dB,
-                                          LVEQNB_Gain_Neg9_dB,
-                                          LVEQNB_Gain_Neg8_dB,
-                                          LVEQNB_Gain_Neg7_dB,
-                                          LVEQNB_Gain_Neg6_dB,
-                                          LVEQNB_Gain_Neg5_dB,
-                                          LVEQNB_Gain_Neg4_dB,
-                                          LVEQNB_Gain_Neg3_dB,
-                                          LVEQNB_Gain_Neg2_dB,
-                                          LVEQNB_Gain_Neg1_dB,
-                                          LVEQNB_Gain_0_dB,            /* 0dB gain */
-                                          LVEQNB_Gain_1_dB,
-                                          LVEQNB_Gain_2_dB,
-                                          LVEQNB_Gain_3_dB,
-                                          LVEQNB_Gain_4_dB,
-                                          LVEQNB_Gain_5_dB,
-                                          LVEQNB_Gain_6_dB,
-                                          LVEQNB_Gain_7_dB,
-                                          LVEQNB_Gain_8_dB,
-                                          LVEQNB_Gain_9_dB,
-                                          LVEQNB_Gain_10_dB,
-                                          LVEQNB_Gain_11_dB,
-                                          LVEQNB_Gain_12_dB,
-                                          LVEQNB_Gain_13_dB,
-                                          LVEQNB_Gain_14_dB,
-                                          LVEQNB_Gain_15_dB};          /* +15dB gain */
+const LVM_FLOAT LVEQNB_GainTable[] = {
+        LVEQNB_Gain_Neg15_dB, /* -15dB gain */
+        LVEQNB_Gain_Neg14_dB, LVEQNB_Gain_Neg13_dB, LVEQNB_Gain_Neg12_dB, LVEQNB_Gain_Neg11_dB,
+        LVEQNB_Gain_Neg10_dB, LVEQNB_Gain_Neg9_dB,  LVEQNB_Gain_Neg8_dB,  LVEQNB_Gain_Neg7_dB,
+        LVEQNB_Gain_Neg6_dB,  LVEQNB_Gain_Neg5_dB,  LVEQNB_Gain_Neg4_dB,  LVEQNB_Gain_Neg3_dB,
+        LVEQNB_Gain_Neg2_dB,  LVEQNB_Gain_Neg1_dB,  LVEQNB_Gain_0_dB, /* 0dB gain */
+        LVEQNB_Gain_1_dB,     LVEQNB_Gain_2_dB,     LVEQNB_Gain_3_dB,     LVEQNB_Gain_4_dB,
+        LVEQNB_Gain_5_dB,     LVEQNB_Gain_6_dB,     LVEQNB_Gain_7_dB,     LVEQNB_Gain_8_dB,
+        LVEQNB_Gain_9_dB,     LVEQNB_Gain_10_dB,    LVEQNB_Gain_11_dB,    LVEQNB_Gain_12_dB,
+        LVEQNB_Gain_13_dB,    LVEQNB_Gain_14_dB,    LVEQNB_Gain_15_dB}; /* +15dB gain */
 /*
  * D table for 100 / (Gain + 1)
  */
-const LVM_FLOAT    LVEQNB_DTable[] = {LVEQNB_100D_Neg15_dB,            /* -15dB gain */
-                                      LVEQNB_100D_Neg14_dB,
-                                      LVEQNB_100D_Neg13_dB,
-                                      LVEQNB_100D_Neg12_dB,
-                                      LVEQNB_100D_Neg11_dB,
-                                      LVEQNB_100D_Neg10_dB,
-                                      LVEQNB_100D_Neg9_dB,
-                                      LVEQNB_100D_Neg8_dB,
-                                      LVEQNB_100D_Neg7_dB,
-                                      LVEQNB_100D_Neg6_dB,
-                                      LVEQNB_100D_Neg5_dB,
-                                      LVEQNB_100D_Neg4_dB,
-                                      LVEQNB_100D_Neg3_dB,
-                                      LVEQNB_100D_Neg2_dB,
-                                      LVEQNB_100D_Neg1_dB,
-                                      LVEQNB_100D_0_dB};               /* 0dB gain */
+const LVM_FLOAT LVEQNB_DTable[] = {
+        LVEQNB_100D_Neg15_dB, /* -15dB gain */
+        LVEQNB_100D_Neg14_dB, LVEQNB_100D_Neg13_dB, LVEQNB_100D_Neg12_dB, LVEQNB_100D_Neg11_dB,
+        LVEQNB_100D_Neg10_dB, LVEQNB_100D_Neg9_dB,  LVEQNB_100D_Neg8_dB,  LVEQNB_100D_Neg7_dB,
+        LVEQNB_100D_Neg6_dB,  LVEQNB_100D_Neg5_dB,  LVEQNB_100D_Neg4_dB,  LVEQNB_100D_Neg3_dB,
+        LVEQNB_100D_Neg2_dB,  LVEQNB_100D_Neg1_dB,  LVEQNB_100D_0_dB}; /* 0dB gain */
 /************************************************************************************/
 /*                                                                                  */
 /*    Filter polynomial coefficients                                                */
@@ -142,13 +91,13 @@
  * a range of 0 to Pi. The output is in the range 32767 to -32768 representing the range
  * +1.0 to -1.0
  */
-const LVM_INT16     LVEQNB_CosCoef[] = {3,                             /* Shifts */
-                                        4096,                          /* a0 */
-                                        -36,                           /* a1 */
-                                        -19725,                        /* a2 */
-                                        -2671,                         /* a3 */
-                                        23730,                         /* a4 */
-                                        -9490};                        /* a5 */
+const LVM_INT16 LVEQNB_CosCoef[] = {3,      /* Shifts */
+                                    4096,   /* a0 */
+                                    -36,    /* a1 */
+                                    -19725, /* a2 */
+                                    -2671,  /* a3 */
+                                    23730,  /* a4 */
+                                    -9490}; /* a5 */
 
 /*
  * Coefficients for calculating the cosine error with the equation:
@@ -164,9 +113,8 @@
  *
  * Cos(x) = 1.0 - CosErr(x)
  */
-const LVM_INT16     LVEQNB_DPCosCoef[] = {1,                           /* Shifts */
-                                          0,                           /* a0 */
-                                          -6,                          /* a1 */
-                                          16586,                       /* a2 */
-                                          -44};                        /* a3 */
-
+const LVM_INT16 LVEQNB_DPCosCoef[] = {1,     /* Shifts */
+                                      0,     /* a0 */
+                                      -6,    /* a1 */
+                                      16586, /* a2 */
+                                      -44};  /* a3 */
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Tables.h b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Tables.h
index a71eeb9..ab51196 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Tables.h
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Tables.h
@@ -27,7 +27,7 @@
  * Sample rate table for converting between the enumerated type and the actual
  * frequency
  */
-extern const LVM_UINT32    LVEQNB_SampleRateTab[];
+extern const LVM_UINT32 LVEQNB_SampleRateTab[];
 
 /************************************************************************************/
 /*                                                                                  */
@@ -38,17 +38,17 @@
 /*
  * Table for 2 * Pi / Fs
  */
-extern const LVM_FLOAT     LVEQNB_TwoPiOnFsTable[];
+extern const LVM_FLOAT LVEQNB_TwoPiOnFsTable[];
 
 /*
  * Gain table
  */
-extern const LVM_FLOAT     LVEQNB_GainTable[];
+extern const LVM_FLOAT LVEQNB_GainTable[];
 
 /*
  * D table for 100 / (Gain + 1)
  */
-extern const LVM_FLOAT     LVEQNB_DTable[];
+extern const LVM_FLOAT LVEQNB_DTable[];
 
 /************************************************************************************/
 /*                                                                                  */
@@ -65,7 +65,7 @@
  * a range of 0 to Pi. The output is in the range 32767 to -32768 representing the range
  * +1.0 to -1.0
  */
-extern const LVM_INT16     LVEQNB_CosCoef[];
+extern const LVM_INT16 LVEQNB_CosCoef[];
 
 /*
  * Coefficients for calculating the cosine error with the equation:
@@ -81,6 +81,6 @@
  *
  * Cos(x) = 1.0 - CosErr(x)
  */
-extern const LVM_INT16     LVEQNB_DPCosCoef[];
+extern const LVM_INT16 LVEQNB_DPCosCoef[];
 
 #endif /* __LVEQNB_TABLES_H__ */
diff --git a/media/libeffects/lvm/lib/Reverb/lib/LVREV.h b/media/libeffects/lvm/lib/Reverb/lib/LVREV.h
index 8c91ea9..489bc6f 100644
--- a/media/libeffects/lvm/lib/Reverb/lib/LVREV.h
+++ b/media/libeffects/lvm/lib/Reverb/lib/LVREV.h
@@ -41,11 +41,11 @@
 /*                                                                                      */
 /****************************************************************************************/
 /* General */
-#define LVREV_BLOCKSIZE_MULTIPLE                1       /* Processing block size multiple */
-#define LVREV_MAX_T60                        7000       /* Maximum decay time is 7000ms */
+#define LVREV_BLOCKSIZE_MULTIPLE 1 /* Processing block size multiple */
+#define LVREV_MAX_T60 7000         /* Maximum decay time is 7000ms */
 
 /* Memory table*/
-#define LVREV_NR_MEMORY_REGIONS                 4       /* Number of memory regions */
+#define LVREV_NR_MEMORY_REGIONS 4 /* Number of memory regions */
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -53,24 +53,22 @@
 /*                                                                                      */
 /****************************************************************************************/
 /* Instance handle */
-typedef void *LVREV_Handle_t;
+typedef void* LVREV_Handle_t;
 
 /* Status return values */
-typedef enum
-{
-    LVREV_SUCCESS            = 0,                       /* Successful return from a routine */
-    LVREV_NULLADDRESS        = 1,                       /* NULL allocation address */
-    LVREV_OUTOFRANGE         = 2,                       /* Out of range control parameter */
-    LVREV_INVALIDNUMSAMPLES  = 3,                       /* Invalid number of samples */
+typedef enum {
+    LVREV_SUCCESS = 0,           /* Successful return from a routine */
+    LVREV_NULLADDRESS = 1,       /* NULL allocation address */
+    LVREV_OUTOFRANGE = 2,        /* Out of range control parameter */
+    LVREV_INVALIDNUMSAMPLES = 3, /* Invalid number of samples */
     LVREV_RETURNSTATUS_DUMMY = LVM_MAXENUM
 } LVREV_ReturnStatus_en;
 
 /* Reverb delay lines */
-typedef enum
-{
-    LVREV_DELAYLINES_1     = 1,                         /* One delay line */
-    LVREV_DELAYLINES_2     = 2,                         /* Two delay lines */
-    LVREV_DELAYLINES_4     = 4,                         /* Four delay lines */
+typedef enum {
+    LVREV_DELAYLINES_1 = 1, /* One delay line */
+    LVREV_DELAYLINES_2 = 2, /* Two delay lines */
+    LVREV_DELAYLINES_4 = 4, /* Four delay lines */
     LVREV_DELAYLINES_DUMMY = LVM_MAXENUM
 } LVREV_NumDelayLines_en;
 
@@ -81,40 +79,37 @@
 /****************************************************************************************/
 
 /* Memory table containing the region definitions */
-typedef struct
-{
-    LVM_MemoryRegion_st        Region[LVREV_NR_MEMORY_REGIONS];  /* One definition for each region */
+typedef struct {
+    LVM_MemoryRegion_st Region[LVREV_NR_MEMORY_REGIONS]; /* One definition for each region */
 } LVREV_MemoryTable_st;
 
 /* Control Parameter structure */
-typedef struct
-{
+typedef struct {
     /* General parameters */
-    LVM_Mode_en                 OperatingMode;          /* Operating mode */
-    LVM_Fs_en                   SampleRate;             /* Sample rate */
-    LVM_Format_en               SourceFormat;           /* Source data format */
+    LVM_Mode_en OperatingMode;  /* Operating mode */
+    LVM_Fs_en SampleRate;       /* Sample rate */
+    LVM_Format_en SourceFormat; /* Source data format */
 
     /* Parameters for REV */
-    LVM_UINT16                  Level;                  /* Level, 0 to 100 representing percentage of reverb */
-    LVM_UINT32                  LPF;                    /* Low pass filter, in Hz */
-    LVM_UINT32                  HPF;                    /* High pass filter, in Hz */
+    LVM_UINT16 Level; /* Level, 0 to 100 representing percentage of reverb */
+    LVM_UINT32 LPF;   /* Low pass filter, in Hz */
+    LVM_UINT32 HPF;   /* High pass filter, in Hz */
 
-    LVM_UINT16                  T60;                    /* Decay time constant, in ms */
-    LVM_UINT16                  Density;                /* Echo density, 0 to 100 for minimum to maximum density */
-    LVM_UINT16                  Damping;                /* Damping */
-    LVM_UINT16                  RoomSize;               /* Simulated room size, 1 to 100 for minimum to maximum size */
+    LVM_UINT16 T60;      /* Decay time constant, in ms */
+    LVM_UINT16 Density;  /* Echo density, 0 to 100 for minimum to maximum density */
+    LVM_UINT16 Damping;  /* Damping */
+    LVM_UINT16 RoomSize; /* Simulated room size, 1 to 100 for minimum to maximum size */
 
 } LVREV_ControlParams_st;
 
 /* Instance Parameter structure */
-typedef struct
-{
+typedef struct {
     /* General */
-    LVM_UINT16                  MaxBlockSize;           /* Maximum processing block size */
+    LVM_UINT16 MaxBlockSize; /* Maximum processing block size */
 
     /* Reverb */
-    LVM_Format_en               SourceFormat;           /* Source data formats to support */
-    LVREV_NumDelayLines_en      NumDelays;              /* The number of delay lines, 1, 2 or 4 */
+    LVM_Format_en SourceFormat;       /* Source data formats to support */
+    LVREV_NumDelayLines_en NumDelays; /* The number of delay lines, 1, 2 or 4 */
 
 } LVREV_InstanceParams_st;
 
@@ -160,9 +155,9 @@
 /*  1.  This function may be interrupted by the LVREV_Process function                  */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_GetMemoryTable(LVREV_Handle_t           hInstance,
-                                           LVREV_MemoryTable_st     *pMemoryTable,
-                                           LVREV_InstanceParams_st  *pInstanceParams);
+LVREV_ReturnStatus_en LVREV_GetMemoryTable(LVREV_Handle_t hInstance,
+                                           LVREV_MemoryTable_st* pMemoryTable,
+                                           LVREV_InstanceParams_st* pInstanceParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -190,9 +185,26 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_GetInstanceHandle(LVREV_Handle_t            *phInstance,
-                                              LVREV_MemoryTable_st      *pMemoryTable,
-                                              LVREV_InstanceParams_st   *pInstanceParams);
+LVREV_ReturnStatus_en LVREV_GetInstanceHandle(LVREV_Handle_t* phInstance,
+                                              LVREV_MemoryTable_st* pMemoryTable,
+                                              LVREV_InstanceParams_st* pInstanceParams);
+
+/****************************************************************************************/
+/*                                                                                      */
+/* FUNCTION:                LVREV_FreeInstance                                          */
+/*                                                                                      */
+/* DESCRIPTION:                                                                         */
+/*  This function is used to free the internal allocations of the module.               */
+/*                                                                                      */
+/* PARAMETERS:                                                                          */
+/*  hInstance               Instance handle                                             */
+/*                                                                                      */
+/* RETURNS:                                                                             */
+/*  LVREV_SUCCESS          free instance succeeded                                      */
+/*  LVREV_NULLADDRESS      Instance is NULL                                             */
+/*                                                                                      */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_FreeInstance(LVREV_Handle_t hInstance);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -214,8 +226,8 @@
 /*  1.  This function may be interrupted by the LVREV_Process function                  */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_GetControlParameters(LVREV_Handle_t           hInstance,
-                                                 LVREV_ControlParams_st   *pControlParams);
+LVREV_ReturnStatus_en LVREV_GetControlParameters(LVREV_Handle_t hInstance,
+                                                 LVREV_ControlParams_st* pControlParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -236,8 +248,8 @@
 /*  1.  This function may be interrupted by the LVREV_Process function                  */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_SetControlParameters(LVREV_Handle_t           hInstance,
-                                                 LVREV_ControlParams_st   *pNewParams);
+LVREV_ReturnStatus_en LVREV_SetControlParameters(LVREV_Handle_t hInstance,
+                                                 LVREV_ControlParams_st* pNewParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -257,7 +269,7 @@
 /*  1. This function must not be interrupted by the LVREV_Process function              */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_ClearAudioBuffers(LVREV_Handle_t  hInstance);
+LVREV_ReturnStatus_en LVREV_ClearAudioBuffers(LVREV_Handle_t hInstance);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -280,11 +292,9 @@
 /*  1. The input and output buffers must be 32-bit aligned                              */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_Process(LVREV_Handle_t      hInstance,
-                                    const LVM_FLOAT     *pInData,
-                                    LVM_FLOAT           *pOutData,
-                                    const LVM_UINT16          NumSamples);
+LVREV_ReturnStatus_en LVREV_Process(LVREV_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                    LVM_FLOAT* pOutData, const LVM_UINT16 NumSamples);
 
-#endif      /* __LVREV_H__ */
+#endif /* __LVREV_H__ */
 
 /* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_ApplyNewSettings.cpp b/media/libeffects/lvm/lib/Reverb/src/LVREV_ApplyNewSettings.cpp
index 1f0d39b..b7883f5 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_ApplyNewSettings.cpp
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_ApplyNewSettings.cpp
@@ -20,6 +20,8 @@
 /*  Includes                                                                            */
 /*                                                                                      */
 /****************************************************************************************/
+
+#include <system/audio.h>
 #include "LVREV_Private.h"
 #include "Filter.h"
 
@@ -41,160 +43,130 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVREV_ReturnStatus_en LVREV_ApplyNewSettings (LVREV_Instance_st     *pPrivate)
-{
-
-    LVM_Mode_en  OperatingMode;
-    LVM_INT32    NumberOfDelayLines;
+LVREV_ReturnStatus_en LVREV_ApplyNewSettings(LVREV_Instance_st* pPrivate) {
+    LVM_Mode_en OperatingMode;
+    LVM_INT32 NumberOfDelayLines;
 
     /* Check for NULL pointer */
-    if(pPrivate == LVM_NULL)
-    {
+    if (pPrivate == LVM_NULL) {
         return LVREV_NULLADDRESS;
     }
 
     OperatingMode = pPrivate->NewParams.OperatingMode;
 
-    if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4)
-    {
+    if (pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4) {
         NumberOfDelayLines = 4;
-    }
-    else if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_2)
-    {
+    } else if (pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_2) {
         NumberOfDelayLines = 2;
-    }
-    else
-    {
+    } else {
         NumberOfDelayLines = 1;
     }
 
     /*
      * Update the high pass filter coefficients
      */
-    if((pPrivate->NewParams.HPF        != pPrivate->CurrentParams.HPF)        ||
-       (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
-       (pPrivate->bFirstControl        == LVM_TRUE))
-    {
-        LVM_FLOAT       Omega;
-        FO_FLOAT_Coefs_t  Coeffs;
+    if ((pPrivate->NewParams.HPF != pPrivate->CurrentParams.HPF) ||
+        (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+        (pPrivate->bFirstControl == LVM_TRUE)) {
+        LVM_FLOAT Omega;
+        FO_FLOAT_Coefs_t Coeffs;
 
         Omega = LVM_GetOmega(pPrivate->NewParams.HPF, pPrivate->NewParams.SampleRate);
         LVM_FO_HPF(Omega, &Coeffs);
-        FO_1I_D32F32Cll_TRC_WRA_01_Init( &pPrivate->pFastCoef->HPCoefs,
-                                         &pPrivate->pFastData->HPTaps, &Coeffs);
-        LoadConst_Float(0,
-                (LVM_FLOAT *)&pPrivate->pFastData->HPTaps,
-                        sizeof(Biquad_1I_Order1_FLOAT_Taps_t) / sizeof(LVM_FLOAT));
+        const std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                Coeffs.A0, Coeffs.A1, 0.0, -(Coeffs.B1), 0.0};
+        pPrivate->pRevHPFBiquad.reset(
+                new android::audio_utils::BiquadFilter<LVM_FLOAT>(FCC_1, coefs));
     }
 
     /*
      * Update the low pass filter coefficients
      */
-    if((pPrivate->NewParams.LPF        != pPrivate->CurrentParams.LPF)        ||
-       (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
-       (pPrivate->bFirstControl        == LVM_TRUE))
-    {
-        LVM_FLOAT       Omega;
-        FO_FLOAT_Coefs_t  Coeffs;
+    if ((pPrivate->NewParams.LPF != pPrivate->CurrentParams.LPF) ||
+        (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+        (pPrivate->bFirstControl == LVM_TRUE)) {
+        LVM_FLOAT Omega;
+        FO_FLOAT_Coefs_t Coeffs;
 
         Coeffs.A0 = 1;
         Coeffs.A1 = 0;
         Coeffs.B1 = 0;
-        if(pPrivate->NewParams.LPF <= (LVM_FsTable[pPrivate->NewParams.SampleRate] >> 1))
-        {
+        if (pPrivate->NewParams.LPF <= (LVM_FsTable[pPrivate->NewParams.SampleRate] >> 1)) {
             Omega = LVM_GetOmega(pPrivate->NewParams.LPF, pPrivate->NewParams.SampleRate);
 
             /*
              * Do not apply filter if w =2*pi*fc/fs >= 2.9
              */
-            if(Omega <= (LVM_FLOAT)LVREV_2_9_INQ29)
-            {
+            if (Omega <= (LVM_FLOAT)LVREV_2_9_INQ29) {
                 LVM_FO_LPF(Omega, &Coeffs);
             }
         }
-        FO_1I_D32F32Cll_TRC_WRA_01_Init( &pPrivate->pFastCoef->LPCoefs,
-                                         &pPrivate->pFastData->LPTaps, &Coeffs);
-        LoadConst_Float(0,
-                (LVM_FLOAT *)&pPrivate->pFastData->LPTaps,
-                        sizeof(Biquad_1I_Order1_FLOAT_Taps_t) / sizeof(LVM_FLOAT));
+        const std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                Coeffs.A0, Coeffs.A1, 0.0, -(Coeffs.B1), 0.0};
+        pPrivate->pRevLPFBiquad.reset(
+                new android::audio_utils::BiquadFilter<LVM_FLOAT>(FCC_1, coefs));
     }
 
     /*
      * Calculate the room size parameter
      */
-    if( pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize)
-    {
+    if (pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) {
         /* Room size range is 10ms to 200ms
          * 0%   -- 10ms
          * 50%  -- 65ms
          * 100% -- 120ms
          */
-        pPrivate->RoomSizeInms = 10 + (((pPrivate->NewParams.RoomSize*11) + 5) / 10);
+        pPrivate->RoomSizeInms = 10 + (((pPrivate->NewParams.RoomSize * 11) + 5) / 10);
     }
 
     /*
      * Update the T delay number of samples and the all pass delay number of samples
      */
-    if( (pPrivate->NewParams.RoomSize   != pPrivate->CurrentParams.RoomSize)   ||
+    if ((pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) ||
         (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
-        (pPrivate->bFirstControl        == LVM_TRUE))
-    {
-
-        LVM_UINT32  Temp;
-        LVM_INT32   APDelaySize;
-        LVM_INT32   Fs = LVM_GetFsFromTable(pPrivate->NewParams.SampleRate);
-        LVM_UINT32  DelayLengthSamples = (LVM_UINT32)(Fs * pPrivate->RoomSizeInms);
-        LVM_INT16   i;
-        LVM_FLOAT   ScaleTable[]  = {LVREV_T_3_Power_minus0_on_4, LVREV_T_3_Power_minus1_on_4, \
-                                     LVREV_T_3_Power_minus2_on_4, LVREV_T_3_Power_minus3_on_4};
-        LVM_INT16   MaxT_Delay[]  = {LVREV_MAX_T0_DELAY, LVREV_MAX_T1_DELAY, \
-                                     LVREV_MAX_T2_DELAY, LVREV_MAX_T3_DELAY};
-        LVM_INT16   MaxAP_Delay[] = {LVREV_MAX_AP0_DELAY, LVREV_MAX_AP1_DELAY, \
-                                     LVREV_MAX_AP2_DELAY, LVREV_MAX_AP3_DELAY};
+        (pPrivate->bFirstControl == LVM_TRUE)) {
+        LVM_UINT32 Temp;
+        LVM_INT32 APDelaySize;
+        LVM_INT32 Fs = LVM_GetFsFromTable(pPrivate->NewParams.SampleRate);
+        LVM_UINT32 DelayLengthSamples = (LVM_UINT32)(Fs * pPrivate->RoomSizeInms);
+        LVM_INT16 i;
+        LVM_FLOAT ScaleTable[] = {LVREV_T_3_Power_minus0_on_4, LVREV_T_3_Power_minus1_on_4,
+                                  LVREV_T_3_Power_minus2_on_4, LVREV_T_3_Power_minus3_on_4};
 
         /*
          * For each delay line
          */
-        for (i = 0; i < NumberOfDelayLines; i++)
-        {
-            if (i != 0)
-            {
-                LVM_FLOAT Temp1;  /* to avoid QAC warning on type conversion */
+        for (i = 0; i < NumberOfDelayLines; i++) {
+            if (i != 0) {
+                LVM_FLOAT Temp1; /* to avoid QAC warning on type conversion */
 
-                Temp1=(LVM_FLOAT)DelayLengthSamples;
+                Temp1 = (LVM_FLOAT)DelayLengthSamples;
                 Temp = (LVM_UINT32)(Temp1 * ScaleTable[i]);
+            } else {
+                Temp = DelayLengthSamples;
             }
-            else
-            {
-               Temp = DelayLengthSamples;
-            }
-            APDelaySize = Temp  / 1500;
+            APDelaySize = Temp / 1500;
 
             /*
              * Set the fixed delay
              */
 
-            Temp  = (MaxT_Delay[i] - MaxAP_Delay[i]) * Fs / 192000;
+            Temp = (LVREV_MAX_T_DELAY[i] - LVREV_MAX_AP_DELAY[i]) * Fs / 192000;
             pPrivate->Delay_AP[i] = pPrivate->T[i] - Temp;
 
             /*
              * Set the tap selection
              */
-            if (pPrivate->AB_Selection)
-            {
+            if (pPrivate->AB_Selection) {
                 /* Smooth from tap A to tap B */
-                pPrivate->pOffsetB[i]             = &pPrivate->pDelay_T[i][pPrivate->T[i] - \
-                                                                           Temp - APDelaySize];
-                pPrivate->B_DelaySize[i]          = APDelaySize;
+                pPrivate->pOffsetB[i] = &pPrivate->pDelay_T[i][pPrivate->T[i] - Temp - APDelaySize];
+                pPrivate->B_DelaySize[i] = APDelaySize;
                 pPrivate->Mixer_APTaps[i].Target1 = 0;
                 pPrivate->Mixer_APTaps[i].Target2 = 1.0f;
-            }
-            else
-            {
+            } else {
                 /* Smooth from tap B to tap A */
-                pPrivate->pOffsetA[i]             = &pPrivate->pDelay_T[i][pPrivate->T[i] - \
-                                                                           Temp - APDelaySize];
-                pPrivate->A_DelaySize[i]          = APDelaySize;
+                pPrivate->pOffsetA[i] = &pPrivate->pDelay_T[i][pPrivate->T[i] - Temp - APDelaySize];
+                pPrivate->A_DelaySize[i] = APDelaySize;
                 pPrivate->Mixer_APTaps[i].Target2 = 0;
                 pPrivate->Mixer_APTaps[i].Target1 = 1.0f;
             }
@@ -202,22 +174,17 @@
             /*
              * Set the maximum block size to the smallest delay size
              */
-            pPrivate->MaxBlkLen   = Temp;
-            if (pPrivate->MaxBlkLen > pPrivate->A_DelaySize[i])
-            {
+            pPrivate->MaxBlkLen = Temp;
+            if (pPrivate->MaxBlkLen > pPrivate->A_DelaySize[i]) {
                 pPrivate->MaxBlkLen = pPrivate->A_DelaySize[i];
             }
-            if (pPrivate->MaxBlkLen > pPrivate->B_DelaySize[i])
-            {
+            if (pPrivate->MaxBlkLen > pPrivate->B_DelaySize[i]) {
                 pPrivate->MaxBlkLen = pPrivate->B_DelaySize[i];
             }
         }
-        if (pPrivate->AB_Selection)
-        {
+        if (pPrivate->AB_Selection) {
             pPrivate->AB_Selection = 0;
-        }
-        else
-        {
+        } else {
             pPrivate->AB_Selection = 1;
         }
 
@@ -226,8 +193,7 @@
          */
         /* Just as a precausion, but no problem if we remove this line      */
         pPrivate->MaxBlkLen = pPrivate->MaxBlkLen - 2;
-        if(pPrivate->MaxBlkLen > pPrivate->InstanceParams.MaxBlockSize)
-        {
+        if (pPrivate->MaxBlkLen > pPrivate->InstanceParams.MaxBlockSize) {
             pPrivate->MaxBlkLen = (LVM_INT32)pPrivate->InstanceParams.MaxBlockSize;
         }
     }
@@ -235,72 +201,61 @@
     /*
      * Update the low pass filter coefficient
      */
-    if( (pPrivate->NewParams.Damping    != pPrivate->CurrentParams.Damping)    ||
+    if ((pPrivate->NewParams.Damping != pPrivate->CurrentParams.Damping) ||
         (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
-        (pPrivate->bFirstControl        == LVM_TRUE))
-    {
-
-        LVM_INT32       Temp;
-        LVM_FLOAT       Omega;
-        FO_FLOAT_Coefs_t  Coeffs;
-        LVM_INT16       i;
-        LVM_INT16       Damping      = (LVM_INT16)((pPrivate->NewParams.Damping * 100) + 1000);
-        LVM_FLOAT       ScaleTable[] = {LVREV_T_3_Power_0_on_4, LVREV_T_3_Power_1_on_4,
-                                        LVREV_T_3_Power_2_on_4, LVREV_T_3_Power_3_on_4};
+        (pPrivate->bFirstControl == LVM_TRUE)) {
+        LVM_INT32 Temp;
+        LVM_FLOAT Omega;
+        FO_FLOAT_Coefs_t Coeffs;
+        LVM_INT16 i;
+        LVM_INT16 Damping = (LVM_INT16)((pPrivate->NewParams.Damping * 100) + 1000);
+        LVM_FLOAT ScaleTable[] = {LVREV_T_3_Power_0_on_4, LVREV_T_3_Power_1_on_4,
+                                  LVREV_T_3_Power_2_on_4, LVREV_T_3_Power_3_on_4};
 
         /*
          * For each filter
          */
-        for (i = 0; i < NumberOfDelayLines; i++)
-        {
-            if (i != 0)
-            {
+        for (i = 0; i < NumberOfDelayLines; i++) {
+            if (i != 0) {
                 Temp = (LVM_INT32)(ScaleTable[i] * Damping);
-            }
-            else
-            {
+            } else {
                 Temp = Damping;
             }
-            if(Temp <= (LVM_INT32)(LVM_FsTable[pPrivate->NewParams.SampleRate] >> 1))
-            {
+            if (Temp <= (LVM_INT32)(LVM_FsTable[pPrivate->NewParams.SampleRate] >> 1)) {
                 Omega = LVM_GetOmega(Temp, pPrivate->NewParams.SampleRate);
                 LVM_FO_LPF(Omega, &Coeffs);
-            }
-            else
-            {
+            } else {
                 Coeffs.A0 = 1;
                 Coeffs.A1 = 0;
                 Coeffs.B1 = 0;
             }
-            FO_1I_D32F32Cll_TRC_WRA_01_Init(&pPrivate->pFastCoef->RevLPCoefs[i],
-                                            &pPrivate->pFastData->RevLPTaps[i], &Coeffs);
+            const std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                    Coeffs.A0, Coeffs.A1, 0.0, -(Coeffs.B1), 0.0};
+            pPrivate->revLPFBiquad[i].reset(
+                    new android::audio_utils::BiquadFilter<LVM_FLOAT>(FCC_1, coefs));
         }
     }
 
     /*
      * Update All-pass filter mixer time constants
      */
-    if( (pPrivate->NewParams.RoomSize   != pPrivate->CurrentParams.RoomSize)   ||
+    if ((pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) ||
         (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
-        (pPrivate->NewParams.Density    != pPrivate->CurrentParams.Density))
-    {
-        LVM_INT16   i;
-        LVM_FLOAT   Alpha;
-        LVM_FLOAT   AlphaTap;
+        (pPrivate->NewParams.Density != pPrivate->CurrentParams.Density)) {
+        LVM_INT16 i;
+        LVM_FLOAT Alpha;
+        LVM_FLOAT AlphaTap;
 
         Alpha = LVM_Mixer_TimeConstant(LVREV_ALLPASS_TC,
-                                       LVM_GetFsFromTable(pPrivate->NewParams.SampleRate),
-                                       1);
+                                       LVM_GetFsFromTable(pPrivate->NewParams.SampleRate), 1);
 
         AlphaTap = LVM_Mixer_TimeConstant(LVREV_ALLPASS_TAP_TC,
-                                          LVM_GetFsFromTable(pPrivate->NewParams.SampleRate),
-                                          1);
+                                          LVM_GetFsFromTable(pPrivate->NewParams.SampleRate), 1);
 
-        for (i = 0; i < 4; i++)
-        {
-            pPrivate->Mixer_APTaps[i].Alpha1       = AlphaTap;
-            pPrivate->Mixer_APTaps[i].Alpha2       = AlphaTap;
-            pPrivate->Mixer_SGFeedback[i].Alpha    = Alpha;
+        for (i = 0; i < 4; i++) {
+            pPrivate->Mixer_APTaps[i].Alpha1 = AlphaTap;
+            pPrivate->Mixer_APTaps[i].Alpha2 = AlphaTap;
+            pPrivate->Mixer_SGFeedback[i].Alpha = Alpha;
             pPrivate->Mixer_SGFeedforward[i].Alpha = Alpha;
         }
     }
@@ -308,150 +263,121 @@
     /*
      * Update the feed back gain
      */
-    if( (pPrivate->NewParams.RoomSize   != pPrivate->CurrentParams.RoomSize)   ||
+    if ((pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) ||
         (pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
-        (pPrivate->NewParams.T60        != pPrivate->CurrentParams.T60)        ||
-        (pPrivate->bFirstControl        == LVM_TRUE))
-    {
+        (pPrivate->NewParams.T60 != pPrivate->CurrentParams.T60) ||
+        (pPrivate->bFirstControl == LVM_TRUE)) {
+        LVM_FLOAT G[4]; /* Feedback gain (Q7.24) */
 
-        LVM_FLOAT               G[4];                       /* Feedback gain (Q7.24) */
-
-        if(pPrivate->NewParams.T60 == 0)
-        {
+        if (pPrivate->NewParams.T60 == 0) {
             G[3] = 0;
             G[2] = 0;
             G[1] = 0;
             G[0] = 0;
-        }
-        else
-        {
-            LVM_FLOAT   Temp1;
-            LVM_FLOAT   Temp2;
-            LVM_INT16   i;
-            LVM_FLOAT   ScaleTable[] = {LVREV_T_3_Power_minus0_on_4, LVREV_T_3_Power_minus1_on_4,
-                                        LVREV_T_3_Power_minus2_on_4, LVREV_T_3_Power_minus3_on_4};
+        } else {
+            LVM_FLOAT Temp1;
+            LVM_FLOAT Temp2;
+            LVM_INT16 i;
+            LVM_FLOAT ScaleTable[] = {LVREV_T_3_Power_minus0_on_4, LVREV_T_3_Power_minus1_on_4,
+                                      LVREV_T_3_Power_minus2_on_4, LVREV_T_3_Power_minus3_on_4};
 
             /*
              * For each delay line
              */
-            for (i = 0; i < NumberOfDelayLines; i++)
-            {
+            for (i = 0; i < NumberOfDelayLines; i++) {
                 Temp1 = (3 * pPrivate->RoomSizeInms * ScaleTable[i]) / pPrivate->NewParams.T60;
-                if(Temp1 >= (4))
-                {
+                if (Temp1 >= (4)) {
                     G[i] = 0;
-                }
-                else if((Temp1 >= (2)))
-                {
+                } else if ((Temp1 >= (2))) {
                     Temp2 = LVM_Power10(-(Temp1 / 2.0f));
                     Temp1 = LVM_Power10(-(Temp1 / 2.0f));
                     Temp1 = Temp1 * Temp2;
-                }
-                else
-                {
+                } else {
                     Temp1 = LVM_Power10(-(Temp1));
                 }
-                if (NumberOfDelayLines == 1)
-                {
+                if (NumberOfDelayLines == 1) {
                     G[i] = Temp1;
-                }
-                else
-                {
-                    LVM_FLOAT   TempG;
+                } else {
+                    LVM_FLOAT TempG;
                     TempG = Temp1 * ONE_OVER_SQRT_TWO;
-                    G[i]=TempG;
+                    G[i] = TempG;
                 }
             }
         }
 
         /* Set up the feedback mixers for four delay lines */
-        pPrivate->FeedbackMixer[0].Target=G[0];
-        pPrivate->FeedbackMixer[1].Target=G[1];
-        pPrivate->FeedbackMixer[2].Target=G[2];
-        pPrivate->FeedbackMixer[3].Target=G[3];
+        pPrivate->FeedbackMixer[0].Target = G[0];
+        pPrivate->FeedbackMixer[1].Target = G[1];
+        pPrivate->FeedbackMixer[2].Target = G[2];
+        pPrivate->FeedbackMixer[3].Target = G[3];
     }
 
     /*
      * Calculate the gain correction
      */
-    if((pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) ||
-       (pPrivate->NewParams.Level    != pPrivate->CurrentParams.Level)    ||
-       (pPrivate->NewParams.T60      != pPrivate->CurrentParams.T60) )
-    {
-        LVM_INT32 Index=0;
+    if ((pPrivate->NewParams.RoomSize != pPrivate->CurrentParams.RoomSize) ||
+        (pPrivate->NewParams.Level != pPrivate->CurrentParams.Level) ||
+        (pPrivate->NewParams.T60 != pPrivate->CurrentParams.T60)) {
+        LVM_INT32 Index = 0;
         LVM_FLOAT Index_FLOAT;
-        LVM_INT32 i=0;
-        LVM_FLOAT Gain=0;
-        LVM_INT32 RoomSize=0;
+        LVM_INT32 i = 0;
+        LVM_FLOAT Gain = 0;
+        LVM_INT32 RoomSize = 0;
         LVM_FLOAT T60;
         LVM_FLOAT Coefs[5];
 
-        if(pPrivate->NewParams.RoomSize == 0)
-        {
+        if (pPrivate->NewParams.RoomSize == 0) {
             RoomSize = 1;
-        }
-        else
-        {
+        } else {
             RoomSize = (LVM_INT32)pPrivate->NewParams.RoomSize;
         }
 
-        if(pPrivate->NewParams.T60 < 100)
-        {
+        if (pPrivate->NewParams.T60 < 100) {
             T60 = 100 * LVREV_T60_SCALE;
-        }
-        else
-        {
+        } else {
             T60 = pPrivate->NewParams.T60 * LVREV_T60_SCALE;
         }
 
         /* Find the nearest room size in table */
-        for(i = 0; i < 24; i++)
-        {
-            if(RoomSize <= LVREV_GainPolyTable[i][0])
-            {
+        for (i = 0; i < 24; i++) {
+            if (RoomSize <= LVREV_GainPolyTable[i][0]) {
                 Index = i;
                 break;
             }
         }
 
-        if(RoomSize == LVREV_GainPolyTable[Index][0])
-        {
+        if (RoomSize == LVREV_GainPolyTable[Index][0]) {
             /* Take table values if the room size is in table */
-            for(i = 1; i < 5; i++)
-            {
-                Coefs[i-1] = LVREV_GainPolyTable[Index][i];
+            for (i = 1; i < 5; i++) {
+                Coefs[i - 1] = LVREV_GainPolyTable[Index][i];
             }
             Coefs[4] = 0;
-            Gain = LVM_Polynomial(3, Coefs, T60);       /* Q.24 result */
-        }
-        else
-        {
+            Gain = LVM_Polynomial(3, Coefs, T60); /* Q.24 result */
+        } else {
             /* Interpolate the gain between nearest room sizes */
 
-            LVM_FLOAT Gain1,Gain2;
-            LVM_INT32 Tot_Dist,Dist;
+            LVM_FLOAT Gain1, Gain2;
+            LVM_INT32 Tot_Dist, Dist;
 
-            Tot_Dist = (LVM_UINT32)LVREV_GainPolyTable[Index][0] - \
-                                            (LVM_UINT32)LVREV_GainPolyTable[Index-1][0];
+            Tot_Dist = (LVM_UINT32)LVREV_GainPolyTable[Index][0] -
+                       (LVM_UINT32)LVREV_GainPolyTable[Index - 1][0];
             Dist = RoomSize - (LVM_UINT32)LVREV_GainPolyTable[Index - 1][0];
 
             /* Get gain for first */
-            for(i = 1; i < 5; i++)
-            {
-                Coefs[i-1] = LVREV_GainPolyTable[Index-1][i];
+            for (i = 1; i < 5; i++) {
+                Coefs[i - 1] = LVREV_GainPolyTable[Index - 1][i];
             }
             Coefs[4] = 0;
 
-            Gain1 = LVM_Polynomial(3, Coefs, T60);      /* Q.24 result */
+            Gain1 = LVM_Polynomial(3, Coefs, T60); /* Q.24 result */
 
             /* Get gain for second */
-            for(i = 1; i < 5; i++)
-            {
-                Coefs[i-1] = LVREV_GainPolyTable[Index][i];
+            for (i = 1; i < 5; i++) {
+                Coefs[i - 1] = LVREV_GainPolyTable[Index][i];
             }
             Coefs[4] = 0;
 
-            Gain2 = LVM_Polynomial(3, Coefs, T60);      /* Q.24 result */
+            Gain2 = LVM_Polynomial(3, Coefs, T60); /* Q.24 result */
 
             /* Linear Interpolate the gain */
             Gain = Gain1 + (((Gain2 - Gain1) * Dist) / (Tot_Dist));
@@ -461,32 +387,27 @@
          * Get the inverse of gain: Q.15
          * Gain is mostly above one except few cases, take only gains above 1
          */
-        if(Gain < 1)
-        {
+        if (Gain < 1) {
             pPrivate->Gain = 1;
-        }
-        else
-        {
+        } else {
             pPrivate->Gain = 1 / Gain;
         }
 
         Index_FLOAT = 100.0f / (LVM_FLOAT)(100 + pPrivate->NewParams.Level);
         pPrivate->Gain = pPrivate->Gain * Index_FLOAT;
-        pPrivate->GainMixer.Target = (pPrivate->Gain*Index_FLOAT) / 2;
+        pPrivate->GainMixer.Target = (pPrivate->Gain * Index_FLOAT) / 2;
     }
 
     /*
      * Update the all pass comb filter coefficient
      */
-    if( (pPrivate->NewParams.Density != pPrivate->CurrentParams.Density) ||
-        (pPrivate->bFirstControl     == LVM_TRUE))
-    {
-        LVM_INT16   i;
-        LVM_FLOAT   b = (LVM_FLOAT)pPrivate->NewParams.Density * LVREV_B_8_on_1000;
+    if ((pPrivate->NewParams.Density != pPrivate->CurrentParams.Density) ||
+        (pPrivate->bFirstControl == LVM_TRUE)) {
+        LVM_INT16 i;
+        LVM_FLOAT b = (LVM_FLOAT)pPrivate->NewParams.Density * LVREV_B_8_on_1000;
 
-        for (i = 0; i < 4; i++)
-        {
-            pPrivate->Mixer_SGFeedback[i].Target    = b;
+        for (i = 0; i < 4; i++) {
+            pPrivate->Mixer_SGFeedback[i].Target = b;
             pPrivate->Mixer_SGFeedforward[i].Target = b;
         }
     }
@@ -494,11 +415,10 @@
     /*
      * Update the bypass mixer time constant
      */
-    if((pPrivate->NewParams.SampleRate   != pPrivate->CurrentParams.SampleRate)   ||
-       (pPrivate->bFirstControl          == LVM_TRUE))
-    {
-        LVM_UINT16   NumChannels = 1;                       /* Assume MONO format */
-        LVM_FLOAT    Alpha;
+    if ((pPrivate->NewParams.SampleRate != pPrivate->CurrentParams.SampleRate) ||
+        (pPrivate->bFirstControl == LVM_TRUE)) {
+        LVM_UINT16 NumChannels = 1; /* Assume MONO format */
+        LVM_FLOAT Alpha;
 
         Alpha = LVM_Mixer_TimeConstant(LVREV_FEEDBACKMIXER_TC,
                                        LVM_GetFsFromTable(pPrivate->NewParams.SampleRate),
@@ -508,67 +428,55 @@
         pPrivate->FeedbackMixer[2].Alpha = Alpha;
         pPrivate->FeedbackMixer[3].Alpha = Alpha;
 
-        NumChannels = 2;                                    /* Always stereo output */
-        pPrivate->BypassMixer.Alpha1 = LVM_Mixer_TimeConstant(LVREV_BYPASSMIXER_TC,
-                             LVM_GetFsFromTable(pPrivate->NewParams.SampleRate), NumChannels);
+        NumChannels = 2; /* Always stereo output */
+        pPrivate->BypassMixer.Alpha1 = LVM_Mixer_TimeConstant(
+                LVREV_BYPASSMIXER_TC, LVM_GetFsFromTable(pPrivate->NewParams.SampleRate),
+                NumChannels);
         pPrivate->BypassMixer.Alpha2 = pPrivate->BypassMixer.Alpha1;
-        pPrivate->GainMixer.Alpha    = pPrivate->BypassMixer.Alpha1;
+        pPrivate->GainMixer.Alpha = pPrivate->BypassMixer.Alpha1;
     }
 
     /*
      * Update the bypass mixer targets
      */
-    if( (pPrivate->NewParams.Level != pPrivate->CurrentParams.Level) &&
-        (pPrivate->NewParams.OperatingMode == LVM_MODE_ON))
-    {
-        pPrivate->BypassMixer.Target2 = (LVM_FLOAT)(pPrivate->NewParams.Level ) / 100.0f;
+    if ((pPrivate->NewParams.Level != pPrivate->CurrentParams.Level) &&
+        (pPrivate->NewParams.OperatingMode == LVM_MODE_ON)) {
+        pPrivate->BypassMixer.Target2 = (LVM_FLOAT)(pPrivate->NewParams.Level) / 100.0f;
         pPrivate->BypassMixer.Target1 = 0x00000000;
-        if ((pPrivate->NewParams.Level == 0) && (pPrivate->bFirstControl == LVM_FALSE))
-        {
+        if ((pPrivate->NewParams.Level == 0) && (pPrivate->bFirstControl == LVM_FALSE)) {
             pPrivate->BypassMixer.CallbackSet2 = LVM_TRUE;
         }
-        if (pPrivate->NewParams.Level != 0)
-        {
+        if (pPrivate->NewParams.Level != 0) {
             pPrivate->bDisableReverb = LVM_FALSE;
         }
     }
 
-    if(pPrivate->NewParams.OperatingMode != pPrivate->CurrentParams.OperatingMode)
-    {
-        if(pPrivate->NewParams.OperatingMode == LVM_MODE_ON)
-        {
-            pPrivate->BypassMixer.Target2 = (LVM_FLOAT)(pPrivate->NewParams.Level ) / 100.0f;
+    if (pPrivate->NewParams.OperatingMode != pPrivate->CurrentParams.OperatingMode) {
+        if (pPrivate->NewParams.OperatingMode == LVM_MODE_ON) {
+            pPrivate->BypassMixer.Target2 = (LVM_FLOAT)(pPrivate->NewParams.Level) / 100.0f;
             pPrivate->BypassMixer.Target1 = 0x00000000;
 
             pPrivate->BypassMixer.CallbackSet2 = LVM_FALSE;
-            OperatingMode                      = LVM_MODE_ON;
-            if (pPrivate->NewParams.Level == 0)
-            {
+            OperatingMode = LVM_MODE_ON;
+            if (pPrivate->NewParams.Level == 0) {
                 pPrivate->bDisableReverb = LVM_TRUE;
-            }
-            else
-            {
+            } else {
                 pPrivate->bDisableReverb = LVM_FALSE;
             }
-        }
-        else if (pPrivate->bFirstControl == LVM_FALSE)
-        {
+        } else if (pPrivate->bFirstControl == LVM_FALSE) {
             pPrivate->BypassMixer.Target2 = 0x00000000;
             pPrivate->BypassMixer.Target1 = 0x00000000;
             pPrivate->BypassMixer.CallbackSet2 = LVM_TRUE;
-            pPrivate->GainMixer.Target    = 0.03125f;
+            pPrivate->GainMixer.Target = 0.03125f;
             OperatingMode = LVM_MODE_ON;
-        }
-        else
-        {
+        } else {
             OperatingMode = LVM_MODE_OFF;
         }
     }
 
     /*  If it is the first call to ApplyNew settings force the current to the target \
         to begin immediate playback of the effect */
-    if(pPrivate->bFirstControl == LVM_TRUE)
-    {
+    if (pPrivate->bFirstControl == LVM_TRUE) {
         pPrivate->BypassMixer.Current1 = pPrivate->BypassMixer.Target1;
         pPrivate->BypassMixer.Current2 = pPrivate->BypassMixer.Target2;
     }
@@ -582,8 +490,7 @@
     /*
      * Update flag
      */
-    if(pPrivate->bFirstControl == LVM_TRUE)
-    {
+    if (pPrivate->bFirstControl == LVM_TRUE) {
         pPrivate->bFirstControl = LVM_FALSE;
     }
 
@@ -606,12 +513,9 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_INT32 BypassMixer_Callback (void *pCallbackData,
-                                void *pGeneralPurpose,
-                                LVM_INT16 GeneralPurpose )
-{
-
-    LVREV_Instance_st     *pLVREV_Private = (LVREV_Instance_st *)pCallbackData;
+LVM_INT32 BypassMixer_Callback(void* pCallbackData, void* pGeneralPurpose,
+                               LVM_INT16 GeneralPurpose) {
+    LVREV_Instance_st* pLVREV_Private = (LVREV_Instance_st*)pCallbackData;
 
     /*
      * Avoid build warnings
@@ -623,11 +527,10 @@
      * Turn off
      */
     pLVREV_Private->CurrentParams.OperatingMode = LVM_MODE_OFF;
-    pLVREV_Private->bDisableReverb              = LVM_TRUE;
+    pLVREV_Private->bDisableReverb = LVM_TRUE;
     LVREV_ClearAudioBuffers((LVREV_Handle_t)pCallbackData);
 
     return 0;
 }
 
 /* End of file */
-
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_ClearAudioBuffers.cpp b/media/libeffects/lvm/lib/Reverb/src/LVREV_ClearAudioBuffers.cpp
index 586539f..d4b321f 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_ClearAudioBuffers.cpp
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_ClearAudioBuffers.cpp
@@ -41,17 +41,14 @@
 /*  1. This function must not be interrupted by the LVM_Process function                */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_ClearAudioBuffers(LVREV_Handle_t  hInstance)
-{
-
-   LVREV_Instance_st     *pLVREV_Private = (LVREV_Instance_st *)hInstance;
+LVREV_ReturnStatus_en LVREV_ClearAudioBuffers(LVREV_Handle_t hInstance) {
+    LVREV_Instance_st* pLVREV_Private = (LVREV_Instance_st*)hInstance;
 
     /*
      * Check for error conditions
      */
     /* Check for NULL pointers */
-    if(hInstance == LVM_NULL)
-    {
+    if (hInstance == LVM_NULL) {
         return LVREV_NULLADDRESS;
     }
 
@@ -59,38 +56,11 @@
      * Clear all filter tap data, delay-lines and other signal related data
      */
 
-    LoadConst_Float(0,
-        (LVM_FLOAT *)&pLVREV_Private->pFastData->HPTaps,
-        2);
-    LoadConst_Float(0,
-        (LVM_FLOAT *)&pLVREV_Private->pFastData->LPTaps,
-        2);
-    if((LVM_UINT16)pLVREV_Private->InstanceParams.NumDelays == LVREV_DELAYLINES_4)
-    {
-        LoadConst_Float(0, (LVM_FLOAT *)&pLVREV_Private->pFastData->RevLPTaps[3], 2);
-        LoadConst_Float(0, (LVM_FLOAT *)&pLVREV_Private->pFastData->RevLPTaps[2], 2);
-        LoadConst_Float(0, (LVM_FLOAT *)&pLVREV_Private->pFastData->RevLPTaps[1], 2);
-        LoadConst_Float(0, (LVM_FLOAT *)&pLVREV_Private->pFastData->RevLPTaps[0], 2);
-
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[3], LVREV_MAX_T3_DELAY);
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[2], LVREV_MAX_T2_DELAY);
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[1], LVREV_MAX_T1_DELAY);
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[0], LVREV_MAX_T0_DELAY);
-    }
-
-    if((LVM_UINT16)pLVREV_Private->InstanceParams.NumDelays >= LVREV_DELAYLINES_2)
-    {
-        LoadConst_Float(0, (LVM_FLOAT *)&pLVREV_Private->pFastData->RevLPTaps[1], 2);
-        LoadConst_Float(0, (LVM_FLOAT *)&pLVREV_Private->pFastData->RevLPTaps[0], 2);
-
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[1], LVREV_MAX_T1_DELAY);
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[0], LVREV_MAX_T0_DELAY);
-    }
-
-    if((LVM_UINT16)pLVREV_Private->InstanceParams.NumDelays >= LVREV_DELAYLINES_1)
-    {
-        LoadConst_Float(0, (LVM_FLOAT *)&pLVREV_Private->pFastData->RevLPTaps[0], 2);
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[0], LVREV_MAX_T0_DELAY);
+    pLVREV_Private->pRevHPFBiquad->clear();
+    pLVREV_Private->pRevLPFBiquad->clear();
+    for (size_t i = 0; i < pLVREV_Private->InstanceParams.NumDelays; i++) {
+        pLVREV_Private->revLPFBiquad[i]->clear();
+        LoadConst_Float(0, pLVREV_Private->pDelay_T[i], LVREV_MAX_T_DELAY[i]);
     }
     return LVREV_SUCCESS;
 }
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_GetControlParameters.cpp b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetControlParameters.cpp
index e0b0142..f858b74 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_GetControlParameters.cpp
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetControlParameters.cpp
@@ -42,17 +42,14 @@
 /*  1.  This function may be interrupted by the LVREV_Process function                  */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_GetControlParameters(LVREV_Handle_t           hInstance,
-                                                 LVREV_ControlParams_st   *pControlParams)
-{
-
-    LVREV_Instance_st  *pLVREV_Private = (LVREV_Instance_st *)hInstance;
+LVREV_ReturnStatus_en LVREV_GetControlParameters(LVREV_Handle_t hInstance,
+                                                 LVREV_ControlParams_st* pControlParams) {
+    LVREV_Instance_st* pLVREV_Private = (LVREV_Instance_st*)hInstance;
 
     /*
      * Check for error conditions
      */
-    if((hInstance == LVM_NULL) || (pControlParams == LVM_NULL))
-    {
+    if ((hInstance == LVM_NULL) || (pControlParams == LVM_NULL)) {
         return LVREV_NULLADDRESS;
     }
 
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_GetInstanceHandle.cpp b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetInstanceHandle.cpp
index 68f883a..298655b 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_GetInstanceHandle.cpp
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetInstanceHandle.cpp
@@ -45,35 +45,29 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_GetInstanceHandle(LVREV_Handle_t            *phInstance,
-                                              LVREV_MemoryTable_st      *pMemoryTable,
-                                              LVREV_InstanceParams_st   *pInstanceParams)
-{
-
-    INST_ALLOC              SlowData;
-    INST_ALLOC              FastData;
-    INST_ALLOC              FastCoef;
-    INST_ALLOC              Temporary;
-    LVREV_Instance_st       *pLVREV_Private;
-    LVM_INT16               i;
-    LVM_UINT16              MaxBlockSize;
+LVREV_ReturnStatus_en LVREV_GetInstanceHandle(LVREV_Handle_t* phInstance,
+                                              LVREV_MemoryTable_st* pMemoryTable,
+                                              LVREV_InstanceParams_st* pInstanceParams) {
+    INST_ALLOC SlowData;
+    INST_ALLOC FastData;
+    INST_ALLOC FastCoef;
+    INST_ALLOC Temporary;
+    LVREV_Instance_st* pLVREV_Private;
+    LVM_INT16 i;
+    LVM_UINT16 MaxBlockSize;
 
     /*
      * Check for error conditions
      */
     /* Check for NULL pointers */
-    if((phInstance == LVM_NULL) || (pMemoryTable == LVM_NULL) || (pInstanceParams == LVM_NULL))
-    {
+    if ((phInstance == LVM_NULL) || (pMemoryTable == LVM_NULL) || (pInstanceParams == LVM_NULL)) {
         return LVREV_NULLADDRESS;
     }
     /* Check the memory table for NULL pointers */
-    for (i = 0; i < LVREV_NR_MEMORY_REGIONS; i++)
-    {
-        if (pMemoryTable->Region[i].Size!=0)
-        {
-            if (pMemoryTable->Region[i].pBaseAddress==LVM_NULL)
-            {
-                return(LVREV_NULLADDRESS);
+    for (i = 0; i < LVREV_NR_MEMORY_REGIONS; i++) {
+        if (pMemoryTable->Region[i].Size != 0) {
+            if (pMemoryTable->Region[i].pBaseAddress == LVM_NULL) {
+                return (LVREV_NULLADDRESS);
             }
         }
     }
@@ -82,163 +76,84 @@
      * Check all instance parameters are in range
      */
     /* Check for a non-zero block size */
-    if (pInstanceParams->MaxBlockSize == 0)
-    {
+    if (pInstanceParams->MaxBlockSize == 0) {
         return LVREV_OUTOFRANGE;
     }
 
     /* Check for a valid number of delay lines */
-    if ((pInstanceParams->NumDelays != LVREV_DELAYLINES_1)&&
-        (pInstanceParams->NumDelays != LVREV_DELAYLINES_2)&&
-        (pInstanceParams->NumDelays != LVREV_DELAYLINES_4))
-    {
+    if ((pInstanceParams->NumDelays != LVREV_DELAYLINES_1) &&
+        (pInstanceParams->NumDelays != LVREV_DELAYLINES_2) &&
+        (pInstanceParams->NumDelays != LVREV_DELAYLINES_4)) {
         return LVREV_OUTOFRANGE;
     }
 
     /*
      * Initialise the InstAlloc instances
      */
-    InstAlloc_Init(&SlowData,  pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress);
-    InstAlloc_Init(&FastData,  pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress);
-    InstAlloc_Init(&FastCoef,  pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress);
+    InstAlloc_Init(&SlowData, pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress);
+    InstAlloc_Init(&FastData, pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress);
+    InstAlloc_Init(&FastCoef, pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress);
     InstAlloc_Init(&Temporary, pMemoryTable->Region[LVM_TEMPORARY_FAST].pBaseAddress);
 
     /*
      * Zero all memory regions
      */
-    LoadConst_Float(0,
-                    (LVM_FLOAT *)pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress,
-                    (LVM_INT16)((pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Size) / \
-                                                    sizeof(LVM_FLOAT)));
-    LoadConst_Float(0,
-                    (LVM_FLOAT *)pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress,
-                    (LVM_INT16)((pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Size) / \
-                                                    sizeof(LVM_FLOAT)));
-    LoadConst_Float(0,
-                    (LVM_FLOAT *)pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress,
-                    (LVM_INT16)((pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Size) / \
-                                                    sizeof(LVM_FLOAT)));
-    LoadConst_Float(0,
-                    (LVM_FLOAT *)pMemoryTable->Region[LVM_TEMPORARY_FAST].pBaseAddress,
-                    (LVM_INT16)((pMemoryTable->Region[LVM_TEMPORARY_FAST].Size) / \
-                                                    sizeof(LVM_FLOAT)));
+    LoadConst_Float(
+            0, (LVM_FLOAT*)pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress,
+            (LVM_INT16)((pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Size) / sizeof(LVM_FLOAT)));
+    LoadConst_Float(
+            0, (LVM_FLOAT*)pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress,
+            (LVM_INT16)((pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Size) / sizeof(LVM_FLOAT)));
+    LoadConst_Float(
+            0, (LVM_FLOAT*)pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress,
+            (LVM_INT16)((pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Size) / sizeof(LVM_FLOAT)));
+    LoadConst_Float(
+            0, (LVM_FLOAT*)pMemoryTable->Region[LVM_TEMPORARY_FAST].pBaseAddress,
+            (LVM_INT16)((pMemoryTable->Region[LVM_TEMPORARY_FAST].Size) / sizeof(LVM_FLOAT)));
     /*
      * Set the instance handle if not already initialised
      */
-    if (*phInstance == LVM_NULL)
-    {
-        *phInstance = InstAlloc_AddMember(&SlowData, sizeof(LVREV_Instance_st));
+    if (*phInstance == LVM_NULL) {
+        *phInstance = new LVREV_Instance_st{};
     }
-    pLVREV_Private              =(LVREV_Instance_st *)*phInstance;
+    pLVREV_Private = (LVREV_Instance_st*)*phInstance;
     pLVREV_Private->MemoryTable = *pMemoryTable;
 
-    if(pInstanceParams->NumDelays ==LVREV_DELAYLINES_4)
-    {
-        MaxBlockSize = LVREV_MAX_AP3_DELAY;
-    }
-    else if(pInstanceParams->NumDelays ==LVREV_DELAYLINES_2)
-    {
-        MaxBlockSize = LVREV_MAX_AP1_DELAY;
-    }
-    else
-    {
-        MaxBlockSize = LVREV_MAX_AP0_DELAY;
+    if (pInstanceParams->NumDelays == LVREV_DELAYLINES_4) {
+        MaxBlockSize = LVREV_MAX_AP_DELAY[3];
+    } else if (pInstanceParams->NumDelays == LVREV_DELAYLINES_2) {
+        MaxBlockSize = LVREV_MAX_AP_DELAY[1];
+    } else {
+        MaxBlockSize = LVREV_MAX_AP_DELAY[0];
     }
 
-    if(MaxBlockSize>pInstanceParams->MaxBlockSize)
-    {
-        MaxBlockSize=pInstanceParams->MaxBlockSize;
+    if (MaxBlockSize > pInstanceParams->MaxBlockSize) {
+        MaxBlockSize = pInstanceParams->MaxBlockSize;
     }
 
     /*
      * Set the data, coefficient and temporary memory pointers
      */
-    /* Fast data memory base address */
-    pLVREV_Private->pFastData = (LVREV_FastData_st *)
-        InstAlloc_AddMember(&FastData, sizeof(LVREV_FastData_st));
-    if(pInstanceParams->NumDelays == LVREV_DELAYLINES_4)
-    {
-        pLVREV_Private->pDelay_T[3]     =
-            (LVM_FLOAT *)InstAlloc_AddMember(&FastData, LVREV_MAX_T3_DELAY * \
-                                                              sizeof(LVM_FLOAT));
-        pLVREV_Private->pDelay_T[2]     =
-            (LVM_FLOAT *)InstAlloc_AddMember(&FastData, LVREV_MAX_T2_DELAY * \
-                                                              sizeof(LVM_FLOAT));
-        pLVREV_Private->pDelay_T[1]     =
-            (LVM_FLOAT *)InstAlloc_AddMember(&FastData, LVREV_MAX_T1_DELAY * \
-                                                              sizeof(LVM_FLOAT));
-        pLVREV_Private->pDelay_T[0]     =
-            (LVM_FLOAT *)InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * \
-                                                              sizeof(LVM_FLOAT));
-
-        for(i = 0; i < 4; i++)
-        {
-            /* Scratch for each delay line output */
-            pLVREV_Private->pScratchDelayLine[i] = (LVM_FLOAT *)InstAlloc_AddMember(&Temporary,
-                                                                       sizeof(LVM_FLOAT) * \
-                                                                       MaxBlockSize);
-        }
-
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[3], LVREV_MAX_T3_DELAY);
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[2], LVREV_MAX_T2_DELAY);
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[1], LVREV_MAX_T1_DELAY);
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[0], LVREV_MAX_T0_DELAY);
-    }
-
-    if(pInstanceParams->NumDelays == LVREV_DELAYLINES_2)
-    {
-        pLVREV_Private->pDelay_T[1]  = (LVM_FLOAT *)
-                InstAlloc_AddMember(&FastData, LVREV_MAX_T1_DELAY * \
-                                                           sizeof(LVM_FLOAT));
-        pLVREV_Private->pDelay_T[0]  = (LVM_FLOAT *)
-                InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * \
-                                                           sizeof(LVM_FLOAT));
-
-        for(i = 0; i < 2; i++)
-        {
-            /* Scratch for each delay line output */
-            pLVREV_Private->pScratchDelayLine[i] = (LVM_FLOAT *)InstAlloc_AddMember(&Temporary,
-                                                                       sizeof(LVM_FLOAT) * \
-                                                                       MaxBlockSize);
-        }
-
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[1], (LVM_INT16)LVREV_MAX_T1_DELAY);
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[0], (LVM_INT16)LVREV_MAX_T0_DELAY);
-    }
-
-    if(pInstanceParams->NumDelays == LVREV_DELAYLINES_1)
-    {
-        pLVREV_Private->pDelay_T[0]  = (LVM_FLOAT *)InstAlloc_AddMember(&FastData,
-                                                           LVREV_MAX_T0_DELAY * sizeof(LVM_FLOAT));
-
-        for(i = 0; i < 1; i++)
-        {
-            /* Scratch for each delay line output */
-            pLVREV_Private->pScratchDelayLine[i] = (LVM_FLOAT *)InstAlloc_AddMember(&Temporary,
-                                                                       sizeof(LVM_FLOAT) * \
-                                                                       MaxBlockSize);
-        }
-
-        LoadConst_Float(0, pLVREV_Private->pDelay_T[0], (LVM_INT16)LVREV_MAX_T0_DELAY);
+    for (size_t i = 0; i < pInstanceParams->NumDelays; i++) {
+        pLVREV_Private->pDelay_T[i] = (LVM_FLOAT*)InstAlloc_AddMember(
+                &FastData, LVREV_MAX_T_DELAY[i] * sizeof(LVM_FLOAT));
+        /* Scratch for each delay line output */
+        pLVREV_Private->pScratchDelayLine[i] =
+                (LVM_FLOAT*)InstAlloc_AddMember(&Temporary, sizeof(LVM_FLOAT) * MaxBlockSize);
+        LoadConst_Float(0, pLVREV_Private->pDelay_T[i], LVREV_MAX_T_DELAY[i]);
     }
     /* All-pass delay buffer addresses and sizes */
-    pLVREV_Private->T[0]         = LVREV_MAX_T0_DELAY;
-    pLVREV_Private->T[1]         = LVREV_MAX_T1_DELAY;
-    pLVREV_Private->T[2]         = LVREV_MAX_T2_DELAY;
-    pLVREV_Private->T[3]         = LVREV_MAX_T3_DELAY;
-    pLVREV_Private->AB_Selection = 1;       /* Select smoothing A to B */
+    for (size_t i = 0; i < LVREV_DELAYLINES_4; i++) {
+        pLVREV_Private->T[i] = LVREV_MAX_T_DELAY[i];
+    }
+    pLVREV_Private->AB_Selection = 1; /* Select smoothing A to B */
 
-    /* Fast coefficient memory base address */
-    pLVREV_Private->pFastCoef       =
-        (LVREV_FastCoef_st *)InstAlloc_AddMember(&FastCoef, sizeof(LVREV_FastCoef_st));
     /* General purpose scratch */
-    pLVREV_Private->pScratch        =
-            (LVM_FLOAT *)InstAlloc_AddMember(&Temporary, sizeof(LVM_FLOAT) * \
-                                                          MaxBlockSize);
+    pLVREV_Private->pScratch =
+            (LVM_FLOAT*)InstAlloc_AddMember(&Temporary, sizeof(LVM_FLOAT) * MaxBlockSize);
     /* Mono->stereo input save for end mix */
-    pLVREV_Private->pInputSave      =
-            (LVM_FLOAT *)InstAlloc_AddMember(&Temporary, 2 * sizeof(LVM_FLOAT) * \
-                                                          MaxBlockSize);
+    pLVREV_Private->pInputSave =
+            (LVM_FLOAT*)InstAlloc_AddMember(&Temporary, 2 * sizeof(LVM_FLOAT) * MaxBlockSize);
     LoadConst_Float(0, pLVREV_Private->pInputSave, (LVM_INT16)(MaxBlockSize * 2));
 
     /*
@@ -249,105 +164,132 @@
     /*
      * Set the parameters to invalid
      */
-    pLVREV_Private->CurrentParams.SampleRate    = LVM_FS_INVALID;
+    pLVREV_Private->CurrentParams.SampleRate = LVM_FS_INVALID;
     pLVREV_Private->CurrentParams.OperatingMode = LVM_MODE_DUMMY;
-    pLVREV_Private->CurrentParams.SourceFormat  = LVM_SOURCE_DUMMY;
+    pLVREV_Private->CurrentParams.SourceFormat = LVM_SOURCE_DUMMY;
 
-    pLVREV_Private->bControlPending             = LVM_FALSE;
-    pLVREV_Private->bFirstControl               = LVM_TRUE;
-    pLVREV_Private->bDisableReverb              = LVM_FALSE;
+    pLVREV_Private->bControlPending = LVM_FALSE;
+    pLVREV_Private->bFirstControl = LVM_TRUE;
+    pLVREV_Private->bDisableReverb = LVM_FALSE;
 
     /*
      * Set mixer parameters
      */
-    pLVREV_Private->BypassMixer.CallbackParam2      = 0;
-    pLVREV_Private->BypassMixer.pCallbackHandle2    = pLVREV_Private;
-    pLVREV_Private->BypassMixer.pGeneralPurpose2    = LVM_NULL;
-    pLVREV_Private->BypassMixer.pCallBack2          = BypassMixer_Callback;
-    pLVREV_Private->BypassMixer.CallbackSet2        = LVM_FALSE;
-    pLVREV_Private->BypassMixer.Current2            = 0;
-    pLVREV_Private->BypassMixer.Target2             = 0;
-    pLVREV_Private->BypassMixer.CallbackParam1      = 0;
-    pLVREV_Private->BypassMixer.pCallbackHandle1    = LVM_NULL;
-    pLVREV_Private->BypassMixer.pGeneralPurpose1    = LVM_NULL;
-    pLVREV_Private->BypassMixer.pCallBack1          = LVM_NULL;
-    pLVREV_Private->BypassMixer.CallbackSet1        = LVM_FALSE;
-    pLVREV_Private->BypassMixer.Current1            = 0x00000000;
-    pLVREV_Private->BypassMixer.Target1             = 0x00000000;
+    pLVREV_Private->BypassMixer.CallbackParam2 = 0;
+    pLVREV_Private->BypassMixer.pCallbackHandle2 = pLVREV_Private;
+    pLVREV_Private->BypassMixer.pGeneralPurpose2 = LVM_NULL;
+    pLVREV_Private->BypassMixer.pCallBack2 = BypassMixer_Callback;
+    pLVREV_Private->BypassMixer.CallbackSet2 = LVM_FALSE;
+    pLVREV_Private->BypassMixer.Current2 = 0;
+    pLVREV_Private->BypassMixer.Target2 = 0;
+    pLVREV_Private->BypassMixer.CallbackParam1 = 0;
+    pLVREV_Private->BypassMixer.pCallbackHandle1 = LVM_NULL;
+    pLVREV_Private->BypassMixer.pGeneralPurpose1 = LVM_NULL;
+    pLVREV_Private->BypassMixer.pCallBack1 = LVM_NULL;
+    pLVREV_Private->BypassMixer.CallbackSet1 = LVM_FALSE;
+    pLVREV_Private->BypassMixer.Current1 = 0x00000000;
+    pLVREV_Private->BypassMixer.Target1 = 0x00000000;
 
-    pLVREV_Private->RoomSizeInms                    = 100;  // 100 msec
+    pLVREV_Private->RoomSizeInms = 100;  // 100 msec
 
     /*
      *  Set the output gain mixer parameters
      */
-    pLVREV_Private->GainMixer.CallbackParam      = 0;
-    pLVREV_Private->GainMixer.pCallbackHandle    = LVM_NULL;
-    pLVREV_Private->GainMixer.pGeneralPurpose    = LVM_NULL;
-    pLVREV_Private->GainMixer.pCallBack          = LVM_NULL;
-    pLVREV_Private->GainMixer.CallbackSet        = LVM_FALSE;
-    pLVREV_Private->GainMixer.Current            = 0.03125f;//0x03ffffff;
-    pLVREV_Private->GainMixer.Target             = 0.03125f;//0x03ffffff;
+    pLVREV_Private->GainMixer.CallbackParam = 0;
+    pLVREV_Private->GainMixer.pCallbackHandle = LVM_NULL;
+    pLVREV_Private->GainMixer.pGeneralPurpose = LVM_NULL;
+    pLVREV_Private->GainMixer.pCallBack = LVM_NULL;
+    pLVREV_Private->GainMixer.CallbackSet = LVM_FALSE;
+    pLVREV_Private->GainMixer.Current = 0.03125f;  // 0x03ffffff;
+    pLVREV_Private->GainMixer.Target = 0.03125f;   // 0x03ffffff;
 
     /*
      * Set the All-Pass Filter mixers
      */
-    for (i=0; i<4; i++)
-    {
+    for (i = 0; i < 4; i++) {
         pLVREV_Private->pOffsetA[i] = pLVREV_Private->pDelay_T[i];
         pLVREV_Private->pOffsetB[i] = pLVREV_Private->pDelay_T[i];
         /* Delay tap selection mixer */
-        pLVREV_Private->Mixer_APTaps[i].CallbackParam2   = 0;
+        pLVREV_Private->Mixer_APTaps[i].CallbackParam2 = 0;
         pLVREV_Private->Mixer_APTaps[i].pCallbackHandle2 = LVM_NULL;
         pLVREV_Private->Mixer_APTaps[i].pGeneralPurpose2 = LVM_NULL;
-        pLVREV_Private->Mixer_APTaps[i].pCallBack2       = LVM_NULL;
-        pLVREV_Private->Mixer_APTaps[i].CallbackSet2     = LVM_FALSE;
-        pLVREV_Private->Mixer_APTaps[i].Current2         = 0;
-        pLVREV_Private->Mixer_APTaps[i].Target2          = 0;
-        pLVREV_Private->Mixer_APTaps[i].CallbackParam1   = 0;
+        pLVREV_Private->Mixer_APTaps[i].pCallBack2 = LVM_NULL;
+        pLVREV_Private->Mixer_APTaps[i].CallbackSet2 = LVM_FALSE;
+        pLVREV_Private->Mixer_APTaps[i].Current2 = 0;
+        pLVREV_Private->Mixer_APTaps[i].Target2 = 0;
+        pLVREV_Private->Mixer_APTaps[i].CallbackParam1 = 0;
         pLVREV_Private->Mixer_APTaps[i].pCallbackHandle1 = LVM_NULL;
         pLVREV_Private->Mixer_APTaps[i].pGeneralPurpose1 = LVM_NULL;
-        pLVREV_Private->Mixer_APTaps[i].pCallBack1       = LVM_NULL;
-        pLVREV_Private->Mixer_APTaps[i].CallbackSet1     = LVM_FALSE;
-        pLVREV_Private->Mixer_APTaps[i].Current1         = 0;
-        pLVREV_Private->Mixer_APTaps[i].Target1          = 1;
+        pLVREV_Private->Mixer_APTaps[i].pCallBack1 = LVM_NULL;
+        pLVREV_Private->Mixer_APTaps[i].CallbackSet1 = LVM_FALSE;
+        pLVREV_Private->Mixer_APTaps[i].Current1 = 0;
+        pLVREV_Private->Mixer_APTaps[i].Target1 = 1;
         /* Feedforward mixer */
-        pLVREV_Private->Mixer_SGFeedforward[i].CallbackParam   = 0;
+        pLVREV_Private->Mixer_SGFeedforward[i].CallbackParam = 0;
         pLVREV_Private->Mixer_SGFeedforward[i].pCallbackHandle = LVM_NULL;
         pLVREV_Private->Mixer_SGFeedforward[i].pGeneralPurpose = LVM_NULL;
-        pLVREV_Private->Mixer_SGFeedforward[i].pCallBack       = LVM_NULL;
-        pLVREV_Private->Mixer_SGFeedforward[i].CallbackSet     = LVM_FALSE;
-        pLVREV_Private->Mixer_SGFeedforward[i].Current         = 0;
-        pLVREV_Private->Mixer_SGFeedforward[i].Target          = 0;
+        pLVREV_Private->Mixer_SGFeedforward[i].pCallBack = LVM_NULL;
+        pLVREV_Private->Mixer_SGFeedforward[i].CallbackSet = LVM_FALSE;
+        pLVREV_Private->Mixer_SGFeedforward[i].Current = 0;
+        pLVREV_Private->Mixer_SGFeedforward[i].Target = 0;
         /* Feedback mixer */
-        pLVREV_Private->Mixer_SGFeedback[i].CallbackParam   = 0;
+        pLVREV_Private->Mixer_SGFeedback[i].CallbackParam = 0;
         pLVREV_Private->Mixer_SGFeedback[i].pCallbackHandle = LVM_NULL;
         pLVREV_Private->Mixer_SGFeedback[i].pGeneralPurpose = LVM_NULL;
-        pLVREV_Private->Mixer_SGFeedback[i].pCallBack       = LVM_NULL;
-        pLVREV_Private->Mixer_SGFeedback[i].CallbackSet     = LVM_FALSE;
-        pLVREV_Private->Mixer_SGFeedback[i].Current         = 0;
-        pLVREV_Private->Mixer_SGFeedback[i].Target          = 0;
+        pLVREV_Private->Mixer_SGFeedback[i].pCallBack = LVM_NULL;
+        pLVREV_Private->Mixer_SGFeedback[i].CallbackSet = LVM_FALSE;
+        pLVREV_Private->Mixer_SGFeedback[i].Current = 0;
+        pLVREV_Private->Mixer_SGFeedback[i].Target = 0;
         /* Feedback gain mixer */
-        pLVREV_Private->FeedbackMixer[i].CallbackParam    = 0;
-        pLVREV_Private->FeedbackMixer[i].pCallbackHandle  = LVM_NULL;
-        pLVREV_Private->FeedbackMixer[i].pGeneralPurpose  = LVM_NULL;
-        pLVREV_Private->FeedbackMixer[i].pCallBack        = LVM_NULL;
-        pLVREV_Private->FeedbackMixer[i].CallbackSet      = LVM_FALSE;
-        pLVREV_Private->FeedbackMixer[i].Current          = 0;
-        pLVREV_Private->FeedbackMixer[i].Target           = 0;
+        pLVREV_Private->FeedbackMixer[i].CallbackParam = 0;
+        pLVREV_Private->FeedbackMixer[i].pCallbackHandle = LVM_NULL;
+        pLVREV_Private->FeedbackMixer[i].pGeneralPurpose = LVM_NULL;
+        pLVREV_Private->FeedbackMixer[i].pCallBack = LVM_NULL;
+        pLVREV_Private->FeedbackMixer[i].CallbackSet = LVM_FALSE;
+        pLVREV_Private->FeedbackMixer[i].Current = 0;
+        pLVREV_Private->FeedbackMixer[i].Target = 0;
     }
     /* Delay tap index */
-    pLVREV_Private->A_DelaySize[0] = LVREV_MAX_AP0_DELAY;
-    pLVREV_Private->B_DelaySize[0] = LVREV_MAX_AP0_DELAY;
-    pLVREV_Private->A_DelaySize[1] = LVREV_MAX_AP1_DELAY;
-    pLVREV_Private->B_DelaySize[1] = LVREV_MAX_AP1_DELAY;
-    pLVREV_Private->A_DelaySize[2] = LVREV_MAX_AP2_DELAY;
-    pLVREV_Private->B_DelaySize[2] = LVREV_MAX_AP2_DELAY;
-    pLVREV_Private->A_DelaySize[3] = LVREV_MAX_AP3_DELAY;
-    pLVREV_Private->B_DelaySize[3] = LVREV_MAX_AP3_DELAY;
+    for (size_t i = 0; i < LVREV_DELAYLINES_4; i++) {
+        pLVREV_Private->A_DelaySize[i] = LVREV_MAX_AP_DELAY[i];
+        pLVREV_Private->B_DelaySize[i] = LVREV_MAX_AP_DELAY[i];
+    }
+
+    pLVREV_Private->pRevHPFBiquad.reset(
+            new android::audio_utils::BiquadFilter<LVM_FLOAT>(LVM_MAX_CHANNELS));
+    pLVREV_Private->pRevLPFBiquad.reset(
+            new android::audio_utils::BiquadFilter<LVM_FLOAT>(LVM_MAX_CHANNELS));
+    for (int i = 0; i < LVREV_DELAYLINES_4; i++) {
+        pLVREV_Private->revLPFBiquad[i].reset(
+                new android::audio_utils::BiquadFilter<LVM_FLOAT>(LVM_MAX_CHANNELS));
+    }
 
     LVREV_ClearAudioBuffers(*phInstance);
 
     return LVREV_SUCCESS;
 }
 
+/****************************************************************************************/
+/*                                                                                      */
+/* FUNCTION:                LVREV_FreeInstance                                          */
+/*                                                                                      */
+/* DESCRIPTION:                                                                         */
+/*  This function is used to free the internal allocations of the module.               */
+/*                                                                                      */
+/* PARAMETERS:                                                                          */
+/*  hInstance               Instance handle                                             */
+/*                                                                                      */
+/* RETURNS:                                                                             */
+/*  LVREV_SUCCESS          free instance succeeded                                      */
+/*  LVREV_NULLADDRESS      Instance is NULL                                             */
+/*                                                                                      */
+/****************************************************************************************/
+LVREV_ReturnStatus_en LVREV_FreeInstance(LVREV_Handle_t hInstance) {
+    if (hInstance == LVM_NULL) {
+        return LVREV_NULLADDRESS;
+    }
+
+    delete (LVREV_Instance_st*)hInstance;
+    return LVREV_SUCCESS;
+}
 /* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_GetMemoryTable.cpp b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetMemoryTable.cpp
index f59933c..02ceb16 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_GetMemoryTable.cpp
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_GetMemoryTable.cpp
@@ -56,46 +56,39 @@
 /*  1.  This function may be interrupted by the LVREV_Process function                  */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_GetMemoryTable(LVREV_Handle_t           hInstance,
-                                           LVREV_MemoryTable_st     *pMemoryTable,
-                                           LVREV_InstanceParams_st  *pInstanceParams)
-{
-
-    INST_ALLOC              SlowData;
-    INST_ALLOC              FastData;
-    INST_ALLOC              FastCoef;
-    INST_ALLOC              Temporary;
-    LVM_INT16               i;
-    LVM_UINT16              MaxBlockSize;
+LVREV_ReturnStatus_en LVREV_GetMemoryTable(LVREV_Handle_t hInstance,
+                                           LVREV_MemoryTable_st* pMemoryTable,
+                                           LVREV_InstanceParams_st* pInstanceParams) {
+    INST_ALLOC SlowData;
+    INST_ALLOC FastData;
+    INST_ALLOC FastCoef;
+    INST_ALLOC Temporary;
+    LVM_UINT16 MaxBlockSize;
 
     /*
      * Check for error conditions
      */
     /* Check for NULL pointer */
-    if (pMemoryTable == LVM_NULL)
-    {
-        return(LVREV_NULLADDRESS);
+    if (pMemoryTable == LVM_NULL) {
+        return (LVREV_NULLADDRESS);
     }
 
     /*
      * Check all instance parameters are in range
      */
-    if (pInstanceParams != LVM_NULL)
-    {
+    if (pInstanceParams != LVM_NULL) {
         /*
          * Call for memory allocation, so check the parameters
          */
         /* Check for a non-zero block size */
-        if (pInstanceParams->MaxBlockSize == 0)
-        {
+        if (pInstanceParams->MaxBlockSize == 0) {
             return LVREV_OUTOFRANGE;
         }
 
         /* Check for a valid number of delay lines */
         if ((pInstanceParams->NumDelays != LVREV_DELAYLINES_1) &&
             (pInstanceParams->NumDelays != LVREV_DELAYLINES_2) &&
-            (pInstanceParams->NumDelays != LVREV_DELAYLINES_4))
-        {
+            (pInstanceParams->NumDelays != LVREV_DELAYLINES_4)) {
             return LVREV_OUTOFRANGE;
         }
     }
@@ -103,86 +96,61 @@
     /*
      * Initialise the InstAlloc instances
      */
-    InstAlloc_Init(&SlowData,  (void *)LVM_NULL);
-    InstAlloc_Init(&FastData,  (void *)LVM_NULL);
-    InstAlloc_Init(&FastCoef,  (void *)LVM_NULL);
-    InstAlloc_Init(&Temporary, (void *)LVM_NULL);
+    InstAlloc_Init(&SlowData, (void*)LVM_NULL);
+    InstAlloc_Init(&FastData, (void*)LVM_NULL);
+    InstAlloc_Init(&FastCoef, (void*)LVM_NULL);
+    InstAlloc_Init(&Temporary, (void*)LVM_NULL);
 
     /*
      * Fill in the memory table
      */
-    if (hInstance == LVM_NULL)
-    {
+    if (hInstance == LVM_NULL) {
         /*
          * Check for null pointers
          */
-        if (pInstanceParams == LVM_NULL)
-        {
-            return(LVREV_NULLADDRESS);
+        if (pInstanceParams == LVM_NULL) {
+            return (LVREV_NULLADDRESS);
         }
 
         /*
          * Select the maximum internal block size
          */
-        if(pInstanceParams->NumDelays ==LVREV_DELAYLINES_4)
-        {
-            MaxBlockSize = LVREV_MAX_AP3_DELAY;
-        }
-        else if(pInstanceParams->NumDelays ==LVREV_DELAYLINES_2)
-        {
-            MaxBlockSize = LVREV_MAX_AP1_DELAY;
-        }
-        else
-        {
-            MaxBlockSize = LVREV_MAX_AP0_DELAY;
+        if (pInstanceParams->NumDelays == LVREV_DELAYLINES_4) {
+            MaxBlockSize = LVREV_MAX_AP_DELAY[3];
+        } else if (pInstanceParams->NumDelays == LVREV_DELAYLINES_2) {
+            MaxBlockSize = LVREV_MAX_AP_DELAY[1];
+        } else {
+            MaxBlockSize = LVREV_MAX_AP_DELAY[0];
         }
 
-        if(MaxBlockSize>pInstanceParams->MaxBlockSize)
-        {
-            MaxBlockSize=pInstanceParams->MaxBlockSize;
+        if (MaxBlockSize > pInstanceParams->MaxBlockSize) {
+            MaxBlockSize = pInstanceParams->MaxBlockSize;
         }
 
         /*
          * Slow data memory
          */
         InstAlloc_AddMember(&SlowData, sizeof(LVREV_Instance_st));
-        pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Size         = InstAlloc_GetTotal(&SlowData);
-        pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Type         = LVM_PERSISTENT_SLOW_DATA;
+        pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Size = InstAlloc_GetTotal(&SlowData);
+        pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].Type = LVM_PERSISTENT_SLOW_DATA;
         pMemoryTable->Region[LVM_PERSISTENT_SLOW_DATA].pBaseAddress = LVM_NULL;
 
         /*
          * Persistent fast data memory
          */
-        InstAlloc_AddMember(&FastData, sizeof(LVREV_FastData_st));
-        if(pInstanceParams->NumDelays == LVREV_DELAYLINES_4)
-        {
-            InstAlloc_AddMember(&FastData, LVREV_MAX_T3_DELAY * sizeof(LVM_FLOAT));
-            InstAlloc_AddMember(&FastData, LVREV_MAX_T2_DELAY * sizeof(LVM_FLOAT));
-            InstAlloc_AddMember(&FastData, LVREV_MAX_T1_DELAY * sizeof(LVM_FLOAT));
-            InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * sizeof(LVM_FLOAT));
+        for (size_t i = 0; i < pInstanceParams->NumDelays; i++) {
+            InstAlloc_AddMember(&FastData, LVREV_MAX_T_DELAY[i] * sizeof(LVM_FLOAT));
         }
 
-        if(pInstanceParams->NumDelays == LVREV_DELAYLINES_2)
-        {
-            InstAlloc_AddMember(&FastData, LVREV_MAX_T1_DELAY * sizeof(LVM_FLOAT));
-            InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * sizeof(LVM_FLOAT));
-        }
-
-        if(pInstanceParams->NumDelays == LVREV_DELAYLINES_1)
-        {
-            InstAlloc_AddMember(&FastData, LVREV_MAX_T0_DELAY * sizeof(LVM_FLOAT));
-        }
-
-        pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Size         = InstAlloc_GetTotal(&FastData);
-        pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Type         = LVM_PERSISTENT_FAST_DATA;
+        pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Size = InstAlloc_GetTotal(&FastData);
+        pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].Type = LVM_PERSISTENT_FAST_DATA;
         pMemoryTable->Region[LVM_PERSISTENT_FAST_DATA].pBaseAddress = LVM_NULL;
 
         /*
          * Persistent fast coefficient memory
          */
-        InstAlloc_AddMember(&FastCoef, sizeof(LVREV_FastCoef_st));
-        pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Size         = InstAlloc_GetTotal(&FastCoef);
-        pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Type         = LVM_PERSISTENT_FAST_COEF;
+        pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Size = InstAlloc_GetTotal(&FastCoef);
+        pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].Type = LVM_PERSISTENT_FAST_COEF;
         pMemoryTable->Region[LVM_PERSISTENT_FAST_COEF].pBaseAddress = LVM_NULL;
 
         /*
@@ -192,41 +160,17 @@
         InstAlloc_AddMember(&Temporary, sizeof(LVM_FLOAT) * MaxBlockSize);
         /* Mono->stereo input saved for end mix */
         InstAlloc_AddMember(&Temporary, 2 * sizeof(LVM_FLOAT) * MaxBlockSize);
-        if(pInstanceParams->NumDelays == LVREV_DELAYLINES_4)
-        {
-            for(i=0; i<4; i++)
-            {
-                /* A Scratch buffer for each delay line */
-                InstAlloc_AddMember(&Temporary, sizeof(LVM_FLOAT) * MaxBlockSize);
-            }
+        for (size_t i = 0; i < pInstanceParams->NumDelays; i++) {
+            /* A Scratch buffer for each delay line */
+            InstAlloc_AddMember(&Temporary, sizeof(LVM_FLOAT) * MaxBlockSize);
         }
 
-        if(pInstanceParams->NumDelays == LVREV_DELAYLINES_2)
-        {
-            for(i=0; i<2; i++)
-            {
-                /* A Scratch buffer for each delay line */
-                InstAlloc_AddMember(&Temporary, sizeof(LVM_FLOAT) * MaxBlockSize);
-            }
-        }
-
-        if(pInstanceParams->NumDelays == LVREV_DELAYLINES_1)
-        {
-            for(i=0; i<1; i++)
-            {
-                /* A Scratch buffer for each delay line */
-                InstAlloc_AddMember(&Temporary, sizeof(LVM_FLOAT) * MaxBlockSize);
-            }
-        }
-
-        pMemoryTable->Region[LVM_TEMPORARY_FAST].Size         = InstAlloc_GetTotal(&Temporary);
-        pMemoryTable->Region[LVM_TEMPORARY_FAST].Type         = LVM_TEMPORARY_FAST;
+        pMemoryTable->Region[LVM_TEMPORARY_FAST].Size = InstAlloc_GetTotal(&Temporary);
+        pMemoryTable->Region[LVM_TEMPORARY_FAST].Type = LVM_TEMPORARY_FAST;
         pMemoryTable->Region[LVM_TEMPORARY_FAST].pBaseAddress = LVM_NULL;
 
-    }
-    else
-    {
-        LVREV_Instance_st   *pLVREV_Private = (LVREV_Instance_st *)hInstance;
+    } else {
+        LVREV_Instance_st* pLVREV_Private = (LVREV_Instance_st*)hInstance;
 
         /*
          * Read back memory allocation table
@@ -234,7 +178,7 @@
         *pMemoryTable = pLVREV_Private->MemoryTable;
     }
 
-    return(LVREV_SUCCESS);
+    return (LVREV_SUCCESS);
 }
 
 /* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_Private.h b/media/libeffects/lvm/lib/Reverb/src/LVREV_Private.h
index 2c27c6e..33f8165 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_Private.h
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_Private.h
@@ -23,6 +23,8 @@
 /*  Includes                                                                            */
 /*                                                                                      */
 /****************************************************************************************/
+
+#include <audio_utils/BiquadFilter.h>
 #include "LVREV.h"
 #include "LVREV_Tables.h"
 #include "BIQUAD.h"
@@ -37,63 +39,63 @@
 /*                                                                                      */
 /****************************************************************************************/
 /* General */
-#define ONE_OVER_SQRT_TWO            0.707107f           /* 1/sqrt(2) * 2^15 */
-#define LVREV_B_8_on_1000               0.008f           /* 0.8 * 2^31 */
-#define LVREV_HEADROOM                   0.25f           /* -12dB * 2^15 */
-#define LVREV_2_9_INQ29                   2.9f           /* 2.9 in Q29 format */
-#define LVREV_MIN3DB                0.7079457f           /* -3dB in Q15 format */
+#define ONE_OVER_SQRT_TWO 0.707107f /* 1/sqrt(2) * 2^15 */
+#define LVREV_B_8_on_1000 0.008f    /* 0.8 * 2^31 */
+#define LVREV_HEADROOM 0.25f        /* -12dB * 2^15 */
+#define LVREV_2_9_INQ29 2.9f        /* 2.9 in Q29 format */
+#define LVREV_MIN3DB 0.7079457f     /* -3dB in Q15 format */
 
 /* Intenal constants */
-#define LVREV_LP_Poly_Order                 4
-#define LVREV_LP_Poly_Shift                 5
+#define LVREV_LP_Poly_Order 4
+#define LVREV_LP_Poly_Shift 5
 
-#define LVREV_T60_SCALE                0.000142f           /*(1/7000) */
+#define LVREV_T60_SCALE 0.000142f /*(1/7000) */
 
-#define LVREV_T_3_Power_0_on_4              1.0f
-#define LVREV_T_3_Power_1_on_4         1.316074f
-#define LVREV_T_3_Power_2_on_4         1.732051f
-#define LVREV_T_3_Power_3_on_4         2.279507f
-#define LVREV_T_3_Power_minus0_on_4         1.0f        /* 3^(-0/4) * 2^15 */
-#define LVREV_T_3_Power_minus1_on_4    0.759836f        /* 3^(-1/4) * 2^15 */
-#define LVREV_T_3_Power_minus2_on_4    0.577350f        /* 3^(-2/4) * 2^15 */
-#define LVREV_T_3_Power_minus3_on_4    0.438691f        /* 3^(-3/4) * 2^15 */
+#define LVREV_T_3_Power_0_on_4 1.0f
+#define LVREV_T_3_Power_1_on_4 1.316074f
+#define LVREV_T_3_Power_2_on_4 1.732051f
+#define LVREV_T_3_Power_3_on_4 2.279507f
+#define LVREV_T_3_Power_minus0_on_4 1.0f      /* 3^(-0/4) * 2^15 */
+#define LVREV_T_3_Power_minus1_on_4 0.759836f /* 3^(-1/4) * 2^15 */
+#define LVREV_T_3_Power_minus2_on_4 0.577350f /* 3^(-2/4) * 2^15 */
+#define LVREV_T_3_Power_minus3_on_4 0.438691f /* 3^(-3/4) * 2^15 */
 
-    /* ((192000 * 120 * LVREV_T_3_Power_minus3_on_4) >> 15) / 1000 */
-#define LVREV_MAX_T3_DELAY               10108
-    /* ((192000 * 120 * LVREV_T_3_Power_minus2_on_4) >> 15) / 1000 */
-#define LVREV_MAX_T2_DELAY               13304
-    /* ((192000 * 120 * LVREV_T_3_Power_minus1_on_4) >> 15) / 1000 */
-#define LVREV_MAX_T1_DELAY               17508
-    /* ((192000 * 120 * LVREV_T_3_Power_minus0_on_4) >> 15) / 1000 */
-#define LVREV_MAX_T0_DELAY               23040
-    /* ((192000 * 120 * LVREV_T_3_Power_minus3_on_4) >> 15) / 1500 */
-#define LVREV_MAX_AP3_DELAY               6740
-    /* ((192000 * 120 * LVREV_T_3_Power_minus2_on_4) >> 15) / 1500 */
-#define LVREV_MAX_AP2_DELAY               8872
-    /* ((192000 * 120 * LVREV_T_3_Power_minus1_on_4) >> 15) / 1500 */
-#define LVREV_MAX_AP1_DELAY              11672
-    /* ((192000 * 120 * LVREV_T_3_Power_minus0_on_4) >> 15) / 1500 */
-#define LVREV_MAX_AP0_DELAY              15360
+/* ((192000 * 120 * LVREV_T_3_Power_minus3_on_4) >> 15) / 1000 */
+#define LVREV_MAX_T3_DELAY 10108
+/* ((192000 * 120 * LVREV_T_3_Power_minus2_on_4) >> 15) / 1000 */
+#define LVREV_MAX_T2_DELAY 13304
+/* ((192000 * 120 * LVREV_T_3_Power_minus1_on_4) >> 15) / 1000 */
+#define LVREV_MAX_T1_DELAY 17508
+/* ((192000 * 120 * LVREV_T_3_Power_minus0_on_4) >> 15) / 1000 */
+#define LVREV_MAX_T0_DELAY 23040
+/* ((192000 * 120 * LVREV_T_3_Power_minus3_on_4) >> 15) / 1500 */
+#define LVREV_MAX_AP3_DELAY 6740
+/* ((192000 * 120 * LVREV_T_3_Power_minus2_on_4) >> 15) / 1500 */
+#define LVREV_MAX_AP2_DELAY 8872
+/* ((192000 * 120 * LVREV_T_3_Power_minus1_on_4) >> 15) / 1500 */
+#define LVREV_MAX_AP1_DELAY 11672
+/* ((192000 * 120 * LVREV_T_3_Power_minus0_on_4) >> 15) / 1500 */
+#define LVREV_MAX_AP0_DELAY 15360
 
-#define LVREV_BYPASSMIXER_TC             1000           /* Bypass mixer time constant*/
-#define LVREV_ALLPASS_TC                 1000           /* All-pass filter time constant */
-#define LVREV_ALLPASS_TAP_TC             10000           /* All-pass filter dely tap change */
-#define LVREV_FEEDBACKMIXER_TC            100           /* Feedback mixer time constant*/
-#define LVREV_OUTPUTGAIN_SHIFT              5           /* Bits shift for output gain correction */
+#define LVREV_BYPASSMIXER_TC 1000  /* Bypass mixer time constant*/
+#define LVREV_ALLPASS_TC 1000      /* All-pass filter time constant */
+#define LVREV_ALLPASS_TAP_TC 10000 /* All-pass filter dely tap change */
+#define LVREV_FEEDBACKMIXER_TC 100 /* Feedback mixer time constant*/
+#define LVREV_OUTPUTGAIN_SHIFT 5   /* Bits shift for output gain correction */
 
 /* Parameter limits */
-#define LVREV_NUM_FS                       13           /* Number of supported sample rates */
+#define LVREV_NUM_FS 13 /* Number of supported sample rates */
 
-#define LVREV_MAXBLKSIZE_LIMIT             64           /* Maximum block size low limit */
-#define LVREV_MAX_LEVEL                   100           /* Maximum level, 100% */
-#define LVREV_MIN_LPF_CORNER               50           /* Low pass filter limits */
-#define LVREV_MAX_LPF_CORNER            23999
-#define LVREV_MIN_HPF_CORNER               20           /* High pass filrer limits */
-#define LVREV_MAX_HPF_CORNER             1000
-#define LVREV_MAX_T60                    7000           /* Maximum T60 time in ms */
-#define LVREV_MAX_DENSITY                 100           /* Maximum density, 100% */
-#define LVREV_MAX_DAMPING                 100           /* Maximum damping, 100% */
-#define LVREV_MAX_ROOMSIZE                100           /* Maximum room size, 100% */
+#define LVREV_MAXBLKSIZE_LIMIT 64 /* Maximum block size low limit */
+#define LVREV_MAX_LEVEL 100       /* Maximum level, 100% */
+#define LVREV_MIN_LPF_CORNER 50   /* Low pass filter limits */
+#define LVREV_MAX_LPF_CORNER 23999
+#define LVREV_MIN_HPF_CORNER 20 /* High pass filrer limits */
+#define LVREV_MAX_HPF_CORNER 1000
+#define LVREV_MAX_T60 7000     /* Maximum T60 time in ms */
+#define LVREV_MAX_DENSITY 100  /* Maximum density, 100% */
+#define LVREV_MAX_DAMPING 100  /* Maximum damping, 100% */
+#define LVREV_MAX_ROOMSIZE 100 /* Maximum room size, 100% */
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -101,73 +103,59 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/* Fast data structure */
-typedef struct
-{
-    Biquad_1I_Order1_FLOAT_Taps_t HPTaps;                     /* High pass filter taps */
-    Biquad_1I_Order1_FLOAT_Taps_t LPTaps;                     /* Low pass filter taps */
-    Biquad_1I_Order1_FLOAT_Taps_t RevLPTaps[4];               /* Reverb low pass filters taps */
 
-} LVREV_FastData_st;
-
-/* Fast coefficient structure */
-typedef struct
-{
-
-    Biquad_FLOAT_Instance_t       HPCoefs;              /* High pass filter coefficients */
-    Biquad_FLOAT_Instance_t       LPCoefs;              /* Low pass filter coefficients */
-    Biquad_FLOAT_Instance_t       RevLPCoefs[4];        /* Reverb low pass filters coefficients */
-
-} LVREV_FastCoef_st;
-typedef struct
-{
+typedef struct {
     /* General */
-    LVREV_InstanceParams_st InstanceParams;           /* Initialisation time instance parameters */
-    LVREV_MemoryTable_st    MemoryTable;              /* Memory table */
-    LVREV_ControlParams_st  CurrentParams;            /* Parameters being used */
-    LVREV_ControlParams_st  NewParams;                /* New parameters from the \
-                                                         calling application */
-    LVM_CHAR                bControlPending;          /* Flag to indicate new parameters \
-                                                         are available */
-    LVM_CHAR                bFirstControl;            /* Flag to indicate that the control \
-                                                         function is called for the first time */
-    LVM_CHAR                bDisableReverb;           /* Flag to indicate that the mix level is
-                                                         0% and the reverb can be disabled */
-    LVM_INT32               RoomSizeInms;             /* Room size in msec */
-    LVM_INT32               MaxBlkLen;                /* Maximum block size for internal
-                                                         processing */
+    LVREV_InstanceParams_st InstanceParams; /* Initialisation time instance parameters */
+    LVREV_MemoryTable_st MemoryTable;       /* Memory table */
+    LVREV_ControlParams_st CurrentParams;   /* Parameters being used */
+    LVREV_ControlParams_st NewParams;       /* New parameters from the \
+                                               calling application */
+    LVM_CHAR bControlPending;               /* Flag to indicate new parameters \
+                                               are available */
+    LVM_CHAR bFirstControl;                 /* Flag to indicate that the control \
+                                               function is called for the first time */
+    LVM_CHAR bDisableReverb;                /* Flag to indicate that the mix level is
+                                               0% and the reverb can be disabled */
+    LVM_INT32 RoomSizeInms;                 /* Room size in msec */
+    LVM_INT32 MaxBlkLen;                    /* Maximum block size for internal
+                                               processing */
 
     /* Aligned memory pointers */
-    LVREV_FastData_st       *pFastData;               /* Fast data memory base address */
-    LVREV_FastCoef_st       *pFastCoef;               /* Fast coefficient memory base address */
-    LVM_FLOAT               *pScratchDelayLine[4];    /* Delay line scratch memory */
-    LVM_FLOAT               *pScratch;                /* Multi ussge scratch */
-    LVM_FLOAT               *pInputSave;              /* Reverb block input save for dry/wet
-                                                         mixing*/
+    std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            pRevHPFBiquad; /* Biquad filter instance for HPF */
+    std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            pRevLPFBiquad; /* Biquad filter instance for LPF */
+    std::array<std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>, LVREV_DELAYLINES_4>
+            revLPFBiquad; /* Biquad filter instance for Reverb LPF */
+    LVM_FLOAT* pScratchDelayLine[LVREV_DELAYLINES_4]; /* Delay line scratch memory */
+    LVM_FLOAT* pScratch;             /* Multi ussge scratch */
+    LVM_FLOAT* pInputSave;           /* Reverb block input save for dry/wet
+                                        mixing*/
 
     /* Feedback matrix */
-    Mix_1St_Cll_FLOAT_t     FeedbackMixer[4];         /* Mixer for Pop and Click Supression \
-                                                         caused by feedback Gain */
+    Mix_1St_Cll_FLOAT_t FeedbackMixer[LVREV_DELAYLINES_4]; /* Mixer for Pop and Click Suppression \
+                                             caused by feedback Gain */
 
     /* All-Pass Filter */
-    LVM_INT32               T[4];                     /* Maximum delay size of buffer */
-    LVM_FLOAT               *pDelay_T[4];             /* Pointer to delay buffers */
-    LVM_INT32               Delay_AP[4];              /* Offset to AP delay buffer start */
-    LVM_INT16               AB_Selection;             /* Smooth from tap A to B when 1 \
-                                                         otherwise B to A */
-    LVM_INT32               A_DelaySize[4];           /* A delay length in samples */
-    LVM_INT32               B_DelaySize[4];           /* B delay length in samples */
-    LVM_FLOAT               *pOffsetA[4];             /* Offset for the A delay tap */
-    LVM_FLOAT               *pOffsetB[4];             /* Offset for the B delay tap */
-    Mix_2St_Cll_FLOAT_t     Mixer_APTaps[4];          /* Smoothed AP delay mixer */
-    Mix_1St_Cll_FLOAT_t     Mixer_SGFeedback[4];      /* Smoothed SAfeedback gain */
-    Mix_1St_Cll_FLOAT_t     Mixer_SGFeedforward[4];   /* Smoothed AP feedforward gain */
+    LVM_INT32 T[LVREV_DELAYLINES_4];                          /* Maximum delay size of buffer */
+    LVM_FLOAT* pDelay_T[LVREV_DELAYLINES_4];                  /* Pointer to delay buffers */
+    LVM_INT32 Delay_AP[LVREV_DELAYLINES_4];                   /* Offset to AP delay buffer start */
+    LVM_INT16 AB_Selection;                     /* Smooth from tap A to B when 1 \
+                                                   otherwise B to A */
+    LVM_INT32 A_DelaySize[LVREV_DELAYLINES_4];                /* A delay length in samples */
+    LVM_INT32 B_DelaySize[LVREV_DELAYLINES_4];                /* B delay length in samples */
+    LVM_FLOAT* pOffsetA[LVREV_DELAYLINES_4];                  /* Offset for the A delay tap */
+    LVM_FLOAT* pOffsetB[LVREV_DELAYLINES_4];                  /* Offset for the B delay tap */
+    Mix_2St_Cll_FLOAT_t Mixer_APTaps[LVREV_DELAYLINES_4];     /* Smoothed AP delay mixer */
+    Mix_1St_Cll_FLOAT_t Mixer_SGFeedback[LVREV_DELAYLINES_4]; /* Smoothed SAfeedback gain */
+    Mix_1St_Cll_FLOAT_t Mixer_SGFeedforward[LVREV_DELAYLINES_4]; /* Smoothed AP feedforward gain */
 
     /* Output gain */
-    Mix_2St_Cll_FLOAT_t     BypassMixer;              /* Dry/wet mixer */
-    LVM_FLOAT               Gain;                     /* Gain applied to output to maintain
-                                                         average signal power */
-    Mix_1St_Cll_FLOAT_t     GainMixer;                /* Gain smoothing */
+    Mix_2St_Cll_FLOAT_t BypassMixer; /* Dry/wet mixer */
+    LVM_FLOAT Gain;                  /* Gain applied to output to maintain
+                                        average signal power */
+    Mix_1St_Cll_FLOAT_t GainMixer;   /* Gain smoothing */
 
 } LVREV_Instance_st;
 
@@ -177,15 +165,12 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVREV_ReturnStatus_en   LVREV_ApplyNewSettings(LVREV_Instance_st     *pPrivate);
-void                    ReverbBlock(LVM_FLOAT           *pInput,
-                                    LVM_FLOAT           *pOutput,
-                                    LVREV_Instance_st   *pPrivate,
-                                    LVM_UINT16          NumSamples);
-LVM_INT32               BypassMixer_Callback(void       *pCallbackData,
-                                             void       *pGeneralPurpose,
-                                             LVM_INT16  GeneralPurpose );
+LVREV_ReturnStatus_en LVREV_ApplyNewSettings(LVREV_Instance_st* pPrivate);
+void ReverbBlock(LVM_FLOAT* pInput, LVM_FLOAT* pOutput, LVREV_Instance_st* pPrivate,
+                 LVM_UINT16 NumSamples);
+LVM_INT32 BypassMixer_Callback(void* pCallbackData, void* pGeneralPurpose,
+                               LVM_INT16 GeneralPurpose);
 
-#endif  /** __LVREV_PRIVATE_H__ **/
+#endif /** __LVREV_PRIVATE_H__ **/
 
 /* End of file */
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_Process.cpp b/media/libeffects/lvm/lib/Reverb/src/LVREV_Process.cpp
index 35f9ad8..f9c3266 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_Process.cpp
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_Process.cpp
@@ -45,43 +45,37 @@
 /*  1. The input and output buffers must be 32-bit aligned                              */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_Process(LVREV_Handle_t      hInstance,
-                                    const LVM_FLOAT     *pInData,
-                                    LVM_FLOAT           *pOutData,
-                                    const LVM_UINT16    NumSamples)
-{
-   LVREV_Instance_st     *pLVREV_Private = (LVREV_Instance_st *)hInstance;
-   LVM_FLOAT             *pInput  = (LVM_FLOAT *)pInData;
-   LVM_FLOAT             *pOutput = pOutData;
-   LVM_INT32             SamplesToProcess, RemainingSamples;
-   LVM_INT32             format = 1;
+LVREV_ReturnStatus_en LVREV_Process(LVREV_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                    LVM_FLOAT* pOutData, const LVM_UINT16 NumSamples) {
+    LVREV_Instance_st* pLVREV_Private = (LVREV_Instance_st*)hInstance;
+    LVM_FLOAT* pInput = (LVM_FLOAT*)pInData;
+    LVM_FLOAT* pOutput = pOutData;
+    LVM_INT32 SamplesToProcess, RemainingSamples;
+    LVM_INT32 format = 1;
 
     /*
      * Check for error conditions
      */
 
     /* Check for NULL pointers */
-    if((hInstance == LVM_NULL) || (pInData == LVM_NULL) || (pOutData == LVM_NULL))
-    {
+    if ((hInstance == LVM_NULL) || (pInData == LVM_NULL) || (pOutData == LVM_NULL)) {
         return LVREV_NULLADDRESS;
     }
 
     /*
      * Apply the new controls settings if required
      */
-    if(pLVREV_Private->bControlPending == LVM_TRUE)
-    {
-        LVREV_ReturnStatus_en   errorCode;
+    if (pLVREV_Private->bControlPending == LVM_TRUE) {
+        LVREV_ReturnStatus_en errorCode;
 
         /*
          * Clear the pending flag and update the control settings
          */
         pLVREV_Private->bControlPending = LVM_FALSE;
 
-        errorCode = LVREV_ApplyNewSettings (pLVREV_Private);
+        errorCode = LVREV_ApplyNewSettings(pLVREV_Private);
 
-        if(errorCode != LVREV_SUCCESS)
-        {
+        if (errorCode != LVREV_SUCCESS) {
             return errorCode;
         }
     }
@@ -89,27 +83,23 @@
     /*
      * Trap the case where the number of samples is zero.
      */
-    if (NumSamples == 0)
-    {
+    if (NumSamples == 0) {
         return LVREV_SUCCESS;
     }
 
     /*
      * If OFF copy and reformat the data as necessary
      */
-    if (pLVREV_Private->CurrentParams.OperatingMode == LVM_MODE_OFF)
-    {
-        if(pInput != pOutput)
-        {
+    if (pLVREV_Private->CurrentParams.OperatingMode == LVM_MODE_OFF) {
+        if (pInput != pOutput) {
             /*
              * Copy the data to the output buffer, convert to stereo is required
              */
-            if(pLVREV_Private->CurrentParams.SourceFormat == LVM_MONO){
+            if (pLVREV_Private->CurrentParams.SourceFormat == LVM_MONO) {
                 MonoTo2I_Float(pInput, pOutput, NumSamples);
             } else {
-                Copy_Float(pInput,
-                           pOutput,
-                           (LVM_INT16)(NumSamples << 1)); // 32 bit data, stereo
+                Copy_Float(pInput, pOutput,
+                           (LVM_INT16)(NumSamples << 1));  // 32 bit data, stereo
             }
         }
 
@@ -118,31 +108,26 @@
 
     RemainingSamples = (LVM_INT32)NumSamples;
 
-    if (pLVREV_Private->CurrentParams.SourceFormat != LVM_MONO)
-    {
+    if (pLVREV_Private->CurrentParams.SourceFormat != LVM_MONO) {
         format = 2;
     }
 
-    while (RemainingSamples!=0)
-    {
+    while (RemainingSamples != 0) {
         /*
          * Process the data
          */
 
-        if(RemainingSamples >  pLVREV_Private->MaxBlkLen)
-        {
-            SamplesToProcess =  pLVREV_Private->MaxBlkLen;
+        if (RemainingSamples > pLVREV_Private->MaxBlkLen) {
+            SamplesToProcess = pLVREV_Private->MaxBlkLen;
             RemainingSamples = (LVM_INT16)(RemainingSamples - SamplesToProcess);
-        }
-        else
-        {
+        } else {
             SamplesToProcess = RemainingSamples;
             RemainingSamples = 0;
         }
 
         ReverbBlock(pInput, pOutput, pLVREV_Private, (LVM_UINT16)SamplesToProcess);
-        pInput  = (LVM_FLOAT *)(pInput + (SamplesToProcess * format));
-        pOutput = (LVM_FLOAT *)(pOutput + (SamplesToProcess * 2));      // Always stereo output
+        pInput = (LVM_FLOAT*)(pInput + (SamplesToProcess * format));
+        pOutput = (LVM_FLOAT*)(pOutput + (SamplesToProcess * 2));  // Always stereo output
     }
 
     return LVREV_SUCCESS;
@@ -170,16 +155,15 @@
 /*  1. The input and output buffers must be 32-bit aligned                              */
 /*                                                                                      */
 /****************************************************************************************/
-void ReverbBlock(LVM_FLOAT *pInput, LVM_FLOAT *pOutput,
-                 LVREV_Instance_st *pPrivate, LVM_UINT16 NumSamples)
-{
-    LVM_INT16   j, size;
-    LVM_FLOAT   *pDelayLine;
-    LVM_FLOAT   *pDelayLineInput = pPrivate->pScratch;
-    LVM_FLOAT   *pScratch = pPrivate->pScratch;
-    LVM_FLOAT   *pIn;
-    LVM_FLOAT   *pTemp = pPrivate->pInputSave;
-    LVM_INT32   NumberOfDelayLines;
+void ReverbBlock(LVM_FLOAT* pInput, LVM_FLOAT* pOutput, LVREV_Instance_st* pPrivate,
+                 LVM_UINT16 NumSamples) {
+    LVM_INT16 j, size;
+    LVM_FLOAT* pDelayLine;
+    LVM_FLOAT* pDelayLineInput = pPrivate->pScratch;
+    LVM_FLOAT* pScratch = pPrivate->pScratch;
+    LVM_FLOAT* pIn;
+    LVM_FLOAT* pTemp = pPrivate->pInputSave;
+    LVM_INT32 NumberOfDelayLines;
 
     /******************************************************************************
      * All calculations will go into the buffer pointed to by pTemp, this will    *
@@ -196,85 +180,61 @@
      * and the final output is converted to STEREO after the mixer                *
      ******************************************************************************/
 
-    if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4)
-    {
+    if (pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4) {
         NumberOfDelayLines = 4;
-    }
-    else if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_2)
-    {
+    } else if (pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_2) {
         NumberOfDelayLines = 2;
-    }
-    else
-    {
+    } else {
         NumberOfDelayLines = 1;
     }
 
-    if(pPrivate->CurrentParams.SourceFormat == LVM_MONO)
-    {
+    if (pPrivate->CurrentParams.SourceFormat == LVM_MONO) {
         pIn = pInput;
-    }
-    else
-    {
+    } else {
         /*
          *  Stereo to mono conversion
          */
 
-        From2iToMono_Float(pInput,
-                           pTemp,
-                           (LVM_INT16)NumSamples);
+        From2iToMono_Float(pInput, pTemp, (LVM_INT16)NumSamples);
         pIn = pTemp;
     }
 
-    Mult3s_Float(pIn,
-                 (LVM_FLOAT)LVREV_HEADROOM,
-                 pTemp,
-                 (LVM_INT16)NumSamples);
+    Mult3s_Float(pIn, (LVM_FLOAT)LVREV_HEADROOM, pTemp, (LVM_INT16)NumSamples);
 
     /*
      *  High pass filter
      */
-    FO_1I_D32F32C31_TRC_WRA_01(&pPrivate->pFastCoef->HPCoefs,
-                               pTemp,
-                               pTemp,
-                               (LVM_INT16)NumSamples);
+    pPrivate->pRevHPFBiquad->process(pTemp, pTemp, NumSamples);
+
     /*
      *  Low pass filter
      */
-    FO_1I_D32F32C31_TRC_WRA_01(&pPrivate->pFastCoef->LPCoefs,
-                               pTemp,
-                               pTemp,
-                               (LVM_INT16)NumSamples);
+    pPrivate->pRevLPFBiquad->process(pTemp, pTemp, NumSamples);
 
     /*
      *  Process all delay lines
      */
 
-    for(j = 0; j < NumberOfDelayLines; j++)
-    {
+    for (j = 0; j < NumberOfDelayLines; j++) {
         pDelayLine = pPrivate->pScratchDelayLine[j];
 
         /*
          * All-pass filter with pop and click suppression
          */
         /* Get the smoothed, delayed output. Put it in the output buffer */
-        MixSoft_2St_D32C31_SAT(&pPrivate->Mixer_APTaps[j],
-                               pPrivate->pOffsetA[j],
-                               pPrivate->pOffsetB[j],
-                               pDelayLine,
-                               (LVM_INT16)NumSamples);
+        MixSoft_2St_D32C31_SAT(&pPrivate->Mixer_APTaps[j], pPrivate->pOffsetA[j],
+                               pPrivate->pOffsetB[j], pDelayLine, (LVM_INT16)NumSamples);
         /* Re-align the all pass filter delay buffer and copying the fixed delay data \
            to the AP delay in the process */
-        Copy_Float(&pPrivate->pDelay_T[j][NumSamples],
-                   pPrivate->pDelay_T[j],
-                   (LVM_INT16)(pPrivate->T[j] - NumSamples));         /* 32-bit data */
+        Copy_Float(&pPrivate->pDelay_T[j][NumSamples], pPrivate->pDelay_T[j],
+                   (LVM_INT16)(pPrivate->T[j] - NumSamples)); /* 32-bit data */
         /* Apply the smoothed feedback and save to fixed delay input (currently empty) */
-        MixSoft_1St_D32C31_WRA(&pPrivate->Mixer_SGFeedback[j],
-                               pDelayLine,
+        MixSoft_1St_D32C31_WRA(&pPrivate->Mixer_SGFeedback[j], pDelayLine,
                                &pPrivate->pDelay_T[j][pPrivate->T[j] - NumSamples],
                                (LVM_INT16)NumSamples);
         /* Sum into the AP delay line */
         Mac3s_Sat_Float(&pPrivate->pDelay_T[j][pPrivate->T[j] - NumSamples],
-                        -1.0f,    /* Invert since the feedback coefficient is negative */
+                        -1.0f, /* Invert since the feedback coefficient is negative */
                         &pPrivate->pDelay_T[j][pPrivate->Delay_AP[j] - NumSamples],
                         (LVM_INT16)NumSamples);
         /* Apply smoothed feedforward sand save to fixed delay input (currently empty) */
@@ -283,9 +243,7 @@
                                &pPrivate->pDelay_T[j][pPrivate->T[j] - NumSamples],
                                (LVM_INT16)NumSamples);
         /* Sum into the AP output */
-        Mac3s_Sat_Float(&pPrivate->pDelay_T[j][pPrivate->T[j] - NumSamples],
-                        1.0f,
-                        pDelayLine,
+        Mac3s_Sat_Float(&pPrivate->pDelay_T[j][pPrivate->T[j] - NumSamples], 1.0f, pDelayLine,
                         (LVM_INT16)NumSamples);
 
         /*
@@ -296,34 +254,26 @@
         /*
          *  Low pass filter
          */
-        FO_1I_D32F32C31_TRC_WRA_01(&pPrivate->pFastCoef->RevLPCoefs[j],
-                                   pDelayLine,
-                                   pDelayLine,
-                                   (LVM_INT16)NumSamples);
+        pPrivate->revLPFBiquad[j]->process(pDelayLine, pDelayLine, NumSamples);
     }
 
     /*
      *  Apply rotation matrix and delay samples
      */
-    for(j = 0; j < NumberOfDelayLines; j++)
-    {
-
-        Copy_Float(pTemp,
-                   pDelayLineInput,
-                   (LVM_INT16)(NumSamples));
+    for (j = 0; j < NumberOfDelayLines; j++) {
+        Copy_Float(pTemp, pDelayLineInput, (LVM_INT16)(NumSamples));
         /*
          *  Rotation matrix mix
          */
-        switch(j)
-        {
+        switch (j) {
             case 3:
                 /*
                  *  Add delay line 1 and 2 contribution
                  */
-                 Mac3s_Sat_Float(pPrivate->pScratchDelayLine[1], -1.0f,
-                                 pDelayLineInput, (LVM_INT16)NumSamples);
-                 Mac3s_Sat_Float(pPrivate->pScratchDelayLine[2], -1.0f,
-                                 pDelayLineInput, (LVM_INT16)NumSamples);
+                Mac3s_Sat_Float(pPrivate->pScratchDelayLine[1], -1.0f, pDelayLineInput,
+                                (LVM_INT16)NumSamples);
+                Mac3s_Sat_Float(pPrivate->pScratchDelayLine[2], -1.0f, pDelayLineInput,
+                                (LVM_INT16)NumSamples);
 
                 break;
             case 2:
@@ -331,61 +281,52 @@
                 /*
                  *  Add delay line 0 and 3 contribution
                  */
-                 Mac3s_Sat_Float(pPrivate->pScratchDelayLine[0], -1.0f,
-                                 pDelayLineInput, (LVM_INT16)NumSamples);
-                 Mac3s_Sat_Float(pPrivate->pScratchDelayLine[3], -1.0f,
-                                 pDelayLineInput, (LVM_INT16)NumSamples);
+                Mac3s_Sat_Float(pPrivate->pScratchDelayLine[0], -1.0f, pDelayLineInput,
+                                (LVM_INT16)NumSamples);
+                Mac3s_Sat_Float(pPrivate->pScratchDelayLine[3], -1.0f, pDelayLineInput,
+                                (LVM_INT16)NumSamples);
 
                 break;
             case 1:
-                if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4)
-                {
+                if (pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4) {
                     /*
                      *  Add delay line 0 and 3 contribution
                      */
-                    Mac3s_Sat_Float(pPrivate->pScratchDelayLine[0], -1.0f,
-                                    pDelayLineInput, (LVM_INT16)NumSamples);
+                    Mac3s_Sat_Float(pPrivate->pScratchDelayLine[0], -1.0f, pDelayLineInput,
+                                    (LVM_INT16)NumSamples);
                     Add2_Sat_Float(pPrivate->pScratchDelayLine[3], pDelayLineInput,
                                    (LVM_INT16)NumSamples);
 
-                }
-                else
-                {
+                } else {
                     /*
                      *  Add delay line 0 and 1 contribution
                      */
-                     Mac3s_Sat_Float(pPrivate->pScratchDelayLine[0], -1.0f,
-                                     pDelayLineInput, (LVM_INT16)NumSamples);
-                     Mac3s_Sat_Float(pPrivate->pScratchDelayLine[1], -1.0f,
-                                     pDelayLineInput, (LVM_INT16)NumSamples);
-
+                    Mac3s_Sat_Float(pPrivate->pScratchDelayLine[0], -1.0f, pDelayLineInput,
+                                    (LVM_INT16)NumSamples);
+                    Mac3s_Sat_Float(pPrivate->pScratchDelayLine[1], -1.0f, pDelayLineInput,
+                                    (LVM_INT16)NumSamples);
                 }
                 break;
             case 0:
-                if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4)
-                {
+                if (pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_4) {
                     /*
                      *  Add delay line 1 and 2 contribution
                      */
-                    Mac3s_Sat_Float(pPrivate->pScratchDelayLine[1], -1.0f,
-                                    pDelayLineInput, (LVM_INT16)NumSamples);
+                    Mac3s_Sat_Float(pPrivate->pScratchDelayLine[1], -1.0f, pDelayLineInput,
+                                    (LVM_INT16)NumSamples);
                     Add2_Sat_Float(pPrivate->pScratchDelayLine[2], pDelayLineInput,
                                    (LVM_INT16)NumSamples);
 
-                }
-                else if(pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_2)
-                {
+                } else if (pPrivate->InstanceParams.NumDelays == LVREV_DELAYLINES_2) {
                     /*
                      *  Add delay line 0 and 1 contribution
                      */
                     Add2_Sat_Float(pPrivate->pScratchDelayLine[0], pDelayLineInput,
                                    (LVM_INT16)NumSamples);
-                    Mac3s_Sat_Float(pPrivate->pScratchDelayLine[1], -1.0f,
-                                    pDelayLineInput, (LVM_INT16)NumSamples);
+                    Mac3s_Sat_Float(pPrivate->pScratchDelayLine[1], -1.0f, pDelayLineInput,
+                                    (LVM_INT16)NumSamples);
 
-                }
-                else
-                {
+                } else {
                     /*
                      *  Add delay line 0 contribution
                      */
@@ -402,54 +343,37 @@
         /*
          *  Delay samples
          */
-        Copy_Float(pDelayLineInput,
-                   &pPrivate->pDelay_T[j][pPrivate->T[j] - NumSamples],
-                   (LVM_INT16)(NumSamples));              /* 32-bit data */
+        Copy_Float(pDelayLineInput, &pPrivate->pDelay_T[j][pPrivate->T[j] - NumSamples],
+                   (LVM_INT16)(NumSamples)); /* 32-bit data */
     }
 
     /*
      *  Create stereo output
      */
-    switch(pPrivate->InstanceParams.NumDelays)
-    {
+    switch (pPrivate->InstanceParams.NumDelays) {
         case LVREV_DELAYLINES_4:
-             Add2_Sat_Float(pPrivate->pScratchDelayLine[3],
-                            pPrivate->pScratchDelayLine[0],
-                            (LVM_INT16)NumSamples);
-             Add2_Sat_Float(pPrivate->pScratchDelayLine[2],
-                            pPrivate->pScratchDelayLine[1],
-                            (LVM_INT16)NumSamples);
+            Add2_Sat_Float(pPrivate->pScratchDelayLine[3], pPrivate->pScratchDelayLine[0],
+                           (LVM_INT16)NumSamples);
+            Add2_Sat_Float(pPrivate->pScratchDelayLine[2], pPrivate->pScratchDelayLine[1],
+                           (LVM_INT16)NumSamples);
 
-            JoinTo2i_Float(pPrivate->pScratchDelayLine[0],
-                           pPrivate->pScratchDelayLine[1],
-                           pTemp,
+            JoinTo2i_Float(pPrivate->pScratchDelayLine[0], pPrivate->pScratchDelayLine[1], pTemp,
                            (LVM_INT16)NumSamples);
 
             break;
         case LVREV_DELAYLINES_2:
 
-             Copy_Float(pPrivate->pScratchDelayLine[1],
-                        pScratch,
-                        (LVM_INT16)(NumSamples));
+            Copy_Float(pPrivate->pScratchDelayLine[1], pScratch, (LVM_INT16)(NumSamples));
 
-             Mac3s_Sat_Float(pPrivate->pScratchDelayLine[0],
-                            -1.0f,
-                            pScratch,
-                            (LVM_INT16)NumSamples);
+            Mac3s_Sat_Float(pPrivate->pScratchDelayLine[0], -1.0f, pScratch, (LVM_INT16)NumSamples);
 
-             Add2_Sat_Float(pPrivate->pScratchDelayLine[1],
-                            pPrivate->pScratchDelayLine[0],
-                            (LVM_INT16)NumSamples);
+            Add2_Sat_Float(pPrivate->pScratchDelayLine[1], pPrivate->pScratchDelayLine[0],
+                           (LVM_INT16)NumSamples);
 
-             JoinTo2i_Float(pPrivate->pScratchDelayLine[0],
-                            pScratch,
-                            pTemp,
-                            (LVM_INT16)NumSamples);
+            JoinTo2i_Float(pPrivate->pScratchDelayLine[0], pScratch, pTemp, (LVM_INT16)NumSamples);
             break;
         case LVREV_DELAYLINES_1:
-            MonoTo2I_Float(pPrivate->pScratchDelayLine[0],
-                           pTemp,
-                           (LVM_INT16)NumSamples);
+            MonoTo2I_Float(pPrivate->pScratchDelayLine[0], pTemp, (LVM_INT16)NumSamples);
             break;
         default:
             break;
@@ -460,25 +384,14 @@
      */
 
     size = (LVM_INT16)(NumSamples << 1);
-    MixSoft_2St_D32C31_SAT(&pPrivate->BypassMixer,
-                           pTemp,
-                           pTemp,
-                           pOutput,
-                           size);
+    MixSoft_2St_D32C31_SAT(&pPrivate->BypassMixer, pTemp, pTemp, pOutput, size);
 
     /* Apply Gain*/
 
-    Shift_Sat_Float(LVREV_OUTPUTGAIN_SHIFT,
-                    pOutput,
-                    pOutput,
-                    size);
+    Shift_Sat_Float(LVREV_OUTPUTGAIN_SHIFT, pOutput, pOutput, size);
 
-    MixSoft_1St_D32C31_WRA(&pPrivate->GainMixer,
-                           pOutput,
-                           pOutput,
-                           size);
+    MixSoft_1St_D32C31_WRA(&pPrivate->GainMixer, pOutput, pOutput, size);
 
     return;
 }
 /* End of file */
-
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_SetControlParameters.cpp b/media/libeffects/lvm/lib/Reverb/src/LVREV_SetControlParameters.cpp
index 2a75559..e5a0bc8 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_SetControlParameters.cpp
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_SetControlParameters.cpp
@@ -42,84 +42,67 @@
 /*  1.  This function may be interrupted by the LVREV_Process function                  */
 /*                                                                                      */
 /****************************************************************************************/
-LVREV_ReturnStatus_en LVREV_SetControlParameters(LVREV_Handle_t           hInstance,
-                                                 LVREV_ControlParams_st   *pNewParams)
-{
-
-    LVREV_Instance_st     *pLVREV_Private = (LVREV_Instance_st *)hInstance;
+LVREV_ReturnStatus_en LVREV_SetControlParameters(LVREV_Handle_t hInstance,
+                                                 LVREV_ControlParams_st* pNewParams) {
+    LVREV_Instance_st* pLVREV_Private = (LVREV_Instance_st*)hInstance;
 
     /*
      * Check for error conditions
      */
-    if((hInstance == LVM_NULL) || (pNewParams == LVM_NULL))
-    {
+    if ((hInstance == LVM_NULL) || (pNewParams == LVM_NULL)) {
         return LVREV_NULLADDRESS;
     }
 
     /*
      * Check all new control parameters are in range
      */
-    if(    ((pNewParams->OperatingMode != LVM_MODE_OFF) && (pNewParams->OperatingMode != LVM_MODE_ON))                                         ||
-        (
-        (pNewParams->SampleRate != LVM_FS_8000) && (pNewParams->SampleRate != LVM_FS_11025) && (pNewParams->SampleRate != LVM_FS_12000)       &&
-        (pNewParams->SampleRate != LVM_FS_16000) && (pNewParams->SampleRate != LVM_FS_22050) && (pNewParams->SampleRate != LVM_FS_24000)       &&
-        (pNewParams->SampleRate != LVM_FS_32000) &&
-        (pNewParams->SampleRate != LVM_FS_44100) &&
-        (pNewParams->SampleRate != LVM_FS_48000)
-        && (pNewParams->SampleRate != LVM_FS_88200) && (pNewParams->SampleRate != LVM_FS_96000)
-        && (pNewParams->SampleRate != LVM_FS_176400) && (pNewParams->SampleRate != LVM_FS_192000)
-        )
-#ifdef SUPPORT_MC
-        || ((pNewParams->SourceFormat != LVM_STEREO)       &&
-            (pNewParams->SourceFormat != LVM_MONOINSTEREO) &&
-            (pNewParams->SourceFormat != LVM_MONO)         &&
-            (pNewParams->SourceFormat != LVM_MULTICHANNEL)))
-#else
-        || ((pNewParams->SourceFormat != LVM_STEREO) && (pNewParams->SourceFormat != LVM_MONOINSTEREO) && (pNewParams->SourceFormat != LVM_MONO)) )
-#endif
-    {
+    if (((pNewParams->OperatingMode != LVM_MODE_OFF) &&
+         (pNewParams->OperatingMode != LVM_MODE_ON)) ||
+        ((pNewParams->SampleRate != LVM_FS_8000) && (pNewParams->SampleRate != LVM_FS_11025) &&
+         (pNewParams->SampleRate != LVM_FS_12000) && (pNewParams->SampleRate != LVM_FS_16000) &&
+         (pNewParams->SampleRate != LVM_FS_22050) && (pNewParams->SampleRate != LVM_FS_24000) &&
+         (pNewParams->SampleRate != LVM_FS_32000) && (pNewParams->SampleRate != LVM_FS_44100) &&
+         (pNewParams->SampleRate != LVM_FS_48000) && (pNewParams->SampleRate != LVM_FS_88200) &&
+         (pNewParams->SampleRate != LVM_FS_96000) && (pNewParams->SampleRate != LVM_FS_176400) &&
+         (pNewParams->SampleRate != LVM_FS_192000)) ||
+        ((pNewParams->SourceFormat != LVM_STEREO) &&
+         (pNewParams->SourceFormat != LVM_MONOINSTEREO) && (pNewParams->SourceFormat != LVM_MONO) &&
+         (pNewParams->SourceFormat != LVM_MULTICHANNEL))) {
         return (LVREV_OUTOFRANGE);
     }
 
-    if (pNewParams->Level > LVREV_MAX_LEVEL)
-    {
+    if (pNewParams->Level > LVREV_MAX_LEVEL) {
         return LVREV_OUTOFRANGE;
     }
 
-    if ((pNewParams->LPF < LVREV_MIN_LPF_CORNER) || (pNewParams->LPF > LVREV_MAX_LPF_CORNER))
-    {
+    if ((pNewParams->LPF < LVREV_MIN_LPF_CORNER) || (pNewParams->LPF > LVREV_MAX_LPF_CORNER)) {
         return LVREV_OUTOFRANGE;
     }
 
-    if ((pNewParams->HPF < LVREV_MIN_HPF_CORNER) || (pNewParams->HPF > LVREV_MAX_HPF_CORNER))
-    {
+    if ((pNewParams->HPF < LVREV_MIN_HPF_CORNER) || (pNewParams->HPF > LVREV_MAX_HPF_CORNER)) {
         return LVREV_OUTOFRANGE;
     }
 
-    if (pNewParams->T60 > LVREV_MAX_T60)
-    {
+    if (pNewParams->T60 > LVREV_MAX_T60) {
         return LVREV_OUTOFRANGE;
     }
 
-    if (pNewParams->Density > LVREV_MAX_DENSITY)
-    {
+    if (pNewParams->Density > LVREV_MAX_DENSITY) {
         return LVREV_OUTOFRANGE;
     }
 
-    if (pNewParams->Damping > LVREV_MAX_DAMPING)
-    {
+    if (pNewParams->Damping > LVREV_MAX_DAMPING) {
         return LVREV_OUTOFRANGE;
     }
 
-    if (pNewParams->RoomSize > LVREV_MAX_ROOMSIZE)
-    {
+    if (pNewParams->RoomSize > LVREV_MAX_ROOMSIZE) {
         return LVREV_OUTOFRANGE;
     }
 
     /*
      * Copy the new parameters and set the flag to indicate they are available
      */
-    pLVREV_Private->NewParams       = *pNewParams;
+    pLVREV_Private->NewParams = *pNewParams;
     pLVREV_Private->bControlPending = LVM_TRUE;
 
     return LVREV_SUCCESS;
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.cpp b/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.cpp
index 5cd623e..bb6cf12 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.cpp
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.cpp
@@ -29,26 +29,17 @@
 /*                                                                                      */
 /****************************************************************************************/
 
+const LVM_INT16 LVREV_MAX_T_DELAY[] = {LVREV_MAX_T0_DELAY, LVREV_MAX_T1_DELAY, LVREV_MAX_T2_DELAY,
+                                       LVREV_MAX_T3_DELAY};
+const LVM_INT16 LVREV_MAX_AP_DELAY[] = {LVREV_MAX_AP0_DELAY, LVREV_MAX_AP1_DELAY,
+                                        LVREV_MAX_AP2_DELAY, LVREV_MAX_AP3_DELAY};
+
 /* Table with supported sampling rates.  The table can be indexed using LVM_Fs_en       */
-const LVM_UINT32 LVM_FsTable[] = {
-    8000 ,
-    11025,
-    12000,
-    16000,
-    22050,
-    24000,
-    32000,
-    44100,
-    48000,
-    88200,
-    96000,
-    176400,
-    192000
-};
+const LVM_UINT32 LVM_FsTable[] = {8000,  11025, 12000, 16000, 22050,  24000, 32000,
+                                  44100, 48000, 88200, 96000, 176400, 192000};
 /* Table with supported sampling rates.  The table can be indexed using LVM_Fs_en       */
-LVM_UINT32 LVM_GetFsFromTable(LVM_Fs_en FsIndex){
-    if (FsIndex > LVM_FS_192000)
-        return 0;
+LVM_UINT32 LVM_GetFsFromTable(LVM_Fs_en FsIndex) {
+    if (FsIndex > LVM_FS_192000) return 0;
 
     return (LVM_FsTable[FsIndex]);
 }
@@ -73,30 +64,174 @@
   */
 
 /* Normalizing output including Reverb Level part (only shift up)*/
-const LVM_FLOAT LVREV_GainPolyTable[24][5]={{1,1.045909f,7.681098f,-7.211500f,3.025605f,},
-                                            {2,1.088194f,10.291749f,-11.513787f,5.265817f,},
-                                            {3,0.988919f,8.299956f,-8.920862f,3.979806f,},
-                                            {4,1.035927f,10.182567f,-10.346134f,4.546533f,},
-                                            {5,1.130313f,12.538727f,-13.627023f,6.165208f,},
-                                            {6,1.060743f,8.091713f,-8.588079f,3.834230f,},
-                                            {7,1.040381f,10.406566f,-11.176650f,5.075132f,},
-                                            {8,1.026944f,8.387302f,-8.689796f,3.895863f,},
-                                            {9,1.013312f,9.727236f,-10.534165f,4.742272f,},
-                                            {10,0.996095f,8.492249f,-7.947677f,3.478917f,},
-                                            {13,1.079346f,8.894425f,-9.641768f,4.434442f,},
-                                            {15,0.994327f,7.441335f,-8.003979f,3.581177f,},
-                                            {17,0.991067f,7.208373f,-7.257859f,3.167774f,},
-                                            {20,1.033445f,7.476371f,-7.546960f,3.369703f,},
-                                            {25,0.982830f,5.913867f,-5.638448f,2.420932f,},
-                                            {30,0.928782f,5.035343f,-4.492104f,1.844904f,},
-                                            {40,0.953714f,5.060232f,-4.472204f,1.829642f,},
-                                            {50,0.899258f,4.273357f,-3.537492f,1.387576f,},
-                                            {60,0.943584f,4.093228f,-3.469658f,1.410911f,},
-                                            {70,0.926021f,3.973125f,-3.331985f,1.344690f,},
-                                            {75,0.894853f,2.871747f,-1.438758f,0.311856f,},
-                                            {80,0.935122f,2.991857f,-2.038882f,0.686395f,},
-                                            {90,0.953872f,2.880315f,-2.122365f,0.784032f,},
-                                            {100,0.951005f,2.894294f,-2.009086f,0.698316f,},
+const LVM_FLOAT LVREV_GainPolyTable[24][5] = {
+        {
+                1,
+                1.045909f,
+                7.681098f,
+                -7.211500f,
+                3.025605f,
+        },
+        {
+                2,
+                1.088194f,
+                10.291749f,
+                -11.513787f,
+                5.265817f,
+        },
+        {
+                3,
+                0.988919f,
+                8.299956f,
+                -8.920862f,
+                3.979806f,
+        },
+        {
+                4,
+                1.035927f,
+                10.182567f,
+                -10.346134f,
+                4.546533f,
+        },
+        {
+                5,
+                1.130313f,
+                12.538727f,
+                -13.627023f,
+                6.165208f,
+        },
+        {
+                6,
+                1.060743f,
+                8.091713f,
+                -8.588079f,
+                3.834230f,
+        },
+        {
+                7,
+                1.040381f,
+                10.406566f,
+                -11.176650f,
+                5.075132f,
+        },
+        {
+                8,
+                1.026944f,
+                8.387302f,
+                -8.689796f,
+                3.895863f,
+        },
+        {
+                9,
+                1.013312f,
+                9.727236f,
+                -10.534165f,
+                4.742272f,
+        },
+        {
+                10,
+                0.996095f,
+                8.492249f,
+                -7.947677f,
+                3.478917f,
+        },
+        {
+                13,
+                1.079346f,
+                8.894425f,
+                -9.641768f,
+                4.434442f,
+        },
+        {
+                15,
+                0.994327f,
+                7.441335f,
+                -8.003979f,
+                3.581177f,
+        },
+        {
+                17,
+                0.991067f,
+                7.208373f,
+                -7.257859f,
+                3.167774f,
+        },
+        {
+                20,
+                1.033445f,
+                7.476371f,
+                -7.546960f,
+                3.369703f,
+        },
+        {
+                25,
+                0.982830f,
+                5.913867f,
+                -5.638448f,
+                2.420932f,
+        },
+        {
+                30,
+                0.928782f,
+                5.035343f,
+                -4.492104f,
+                1.844904f,
+        },
+        {
+                40,
+                0.953714f,
+                5.060232f,
+                -4.472204f,
+                1.829642f,
+        },
+        {
+                50,
+                0.899258f,
+                4.273357f,
+                -3.537492f,
+                1.387576f,
+        },
+        {
+                60,
+                0.943584f,
+                4.093228f,
+                -3.469658f,
+                1.410911f,
+        },
+        {
+                70,
+                0.926021f,
+                3.973125f,
+                -3.331985f,
+                1.344690f,
+        },
+        {
+                75,
+                0.894853f,
+                2.871747f,
+                -1.438758f,
+                0.311856f,
+        },
+        {
+                80,
+                0.935122f,
+                2.991857f,
+                -2.038882f,
+                0.686395f,
+        },
+        {
+                90,
+                0.953872f,
+                2.880315f,
+                -2.122365f,
+                0.784032f,
+        },
+        {
+                100,
+                0.951005f,
+                2.894294f,
+                -2.009086f,
+                0.698316f,
+        },
 };
 /* End of file */
-
diff --git a/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.h b/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.h
index e100d8a..723d1ff 100644
--- a/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.h
+++ b/media/libeffects/lvm/lib/Reverb/src/LVREV_Tables.h
@@ -31,11 +31,13 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-extern const    LVM_UINT32  LVM_FsTable[];
-extern          LVM_UINT32  LVM_GetFsFromTable(LVM_Fs_en FsIndex);
+extern const LVM_UINT32 LVM_FsTable[];
+extern LVM_UINT32 LVM_GetFsFromTable(LVM_Fs_en FsIndex);
 
-extern const    LVM_FLOAT   LVREV_GainPolyTable[24][5];
+extern const LVM_FLOAT LVREV_GainPolyTable[24][5];
+extern const LVM_INT16 LVREV_MAX_T_DELAY[];
+extern const LVM_INT16 LVREV_MAX_AP_DELAY[];
 
-#endif  /** _LVREV_TABLES_H_ **/
+#endif /** _LVREV_TABLES_H_ **/
 
 /* End of file */
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/lib/LVPSA.h b/media/libeffects/lvm/lib/SpectrumAnalyzer/lib/LVPSA.h
index c9fa7ad..85e3ab9 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/lib/LVPSA.h
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/lib/LVPSA.h
@@ -22,255 +22,191 @@
 
 /****************************************************************************************/
 /*                                                                                      */
-/*  CONSTANTS DEFINITIONS                                                               */
-/*                                                                                      */
-/****************************************************************************************/
-
-/* Memory table*/
-#define     LVPSA_NR_MEMORY_REGIONS                  4      /* Number of memory regions                                          */
-
-/****************************************************************************************/
-/*                                                                                      */
 /*  TYPES DEFINITIONS                                                                   */
 /*                                                                                      */
 /****************************************************************************************/
-/* Memory Types */
-typedef enum
-{
-    LVPSA_PERSISTENT      = LVM_PERSISTENT,
-    LVPSA_PERSISTENT_DATA = LVM_PERSISTENT_DATA,
-    LVPSA_PERSISTENT_COEF = LVM_PERSISTENT_COEF,
-    LVPSA_SCRATCH         = LVM_SCRATCH,
-    LVPSA_MEMORY_DUMMY = LVM_MAXINT_32                      /* Force 32 bits enum, don't use it!                                 */
-} LVPSA_MemoryTypes_en;
-
 /* Level detection speed control parameters */
-typedef enum
-{
-    LVPSA_SPEED_LOW,                                        /* Low speed level   detection                                       */
-    LVPSA_SPEED_MEDIUM,                                     /* Medium speed level   detection                                    */
-    LVPSA_SPEED_HIGH,                                       /* High speed level   detection                                      */
-    LVPSA_SPEED_DUMMY = LVM_MAXINT_32                       /* Force 32 bits enum, don't use it!                                 */
+typedef enum {
+    LVPSA_SPEED_LOW,    /* Low speed level   detection                                       */
+    LVPSA_SPEED_MEDIUM, /* Medium speed level   detection                                    */
+    LVPSA_SPEED_HIGH,   /* High speed level   detection                                      */
+    LVPSA_SPEED_DUMMY = LVM_MAXINT_32 /* Force 32 bits enum, don't use it! */
 } LVPSA_LevelDetectSpeed_en;
 
 /* Filter control parameters */
-typedef struct
-{
-    LVM_UINT16                 CenterFrequency;             /* Center frequency of the band-pass filter (in Hz)                  */
-    LVM_UINT16                 QFactor;                     /* Quality factor of the filter             (in 1/100)               */
-    LVM_INT16                  PostGain;                    /* Postgain to apply after the filtering    (in dB Q16.0)            */
+typedef struct {
+    LVM_UINT16 CenterFrequency; /* Center frequency of the band-pass filter (in Hz) */
+    LVM_UINT16 QFactor; /* Quality factor of the filter             (in 1/100)               */
+    LVM_INT16 PostGain; /* Postgain to apply after the filtering    (in dB Q16.0)            */
 
 } LVPSA_FilterParam_t;
 
 /* LVPSA initialization parameters */
-typedef struct
-{
-    LVM_UINT16                 SpectralDataBufferDuration;  /* Spectral data buffer duration in time (ms in Q16.0)               */
-    LVM_UINT16                 MaxInputBlockSize;           /* Maximum expected input block size (in samples)                    */
-    LVM_UINT16                 nBands;                      /* Number of bands of the SA                                         */
-    LVPSA_FilterParam_t       *pFiltersParams;              /* Points to nBands filter param structures for filters settings     */
+typedef struct {
+    LVM_UINT16
+            SpectralDataBufferDuration; /* Spectral data buffer duration in time (ms in Q16.0) */
+    LVM_UINT16 MaxInputBlockSize;       /* Maximum expected input block size (in samples)       */
+    LVM_UINT16 nBands; /* Number of bands of the SA                                         */
+    LVPSA_FilterParam_t*
+            pFiltersParams; /* Points to nBands filter param structures for filters settings     */
 
 } LVPSA_InitParams_t, *pLVPSA_InitParams_t;
 
 /* LVPSA control parameters */
-typedef struct
-{
-    LVM_Fs_en                  Fs;                          /* Input sampling rate                                               */
-    LVPSA_LevelDetectSpeed_en  LevelDetectionSpeed;         /* Level detection speed                                             */
+typedef struct {
+    LVM_Fs_en Fs; /* Input sampling rate                                               */
+    LVPSA_LevelDetectSpeed_en LevelDetectionSpeed; /* Level detection speed */
 
 } LVPSA_ControlParams_t, *pLVPSA_ControlParams_t;
 
-/* Memory region definition */
-typedef struct
-{
-    LVM_UINT32                 Size;                        /* Region size in bytes                                              */
-    LVPSA_MemoryTypes_en       Type;                        /* Region type                                                       */
-    void                       *pBaseAddress;               /* Pointer to the region base address                                */
-} LVPSA_MemoryRegion_t;
-
-/* Memory table containing the region definitions */
-typedef struct
-{
-    LVPSA_MemoryRegion_t       Region[LVPSA_NR_MEMORY_REGIONS];/* One definition for each region                                 */
-} LVPSA_MemTab_t;
-
 /* Audio time type */
 typedef LVM_INT32 LVPSA_Time;
 
 /* Module instance Handle */
-typedef void *pLVPSA_Handle_t;
+typedef void* pLVPSA_Handle_t;
 
 /* LVPSA return codes */
-typedef enum
-{
-    LVPSA_OK,                                               /* The function ran without any problem                              */
-    LVPSA_ERROR_INVALIDPARAM,                               /* A parameter is incorrect                                          */
-    LVPSA_ERROR_WRONGTIME,                                  /* An incorrect AudioTime is used                                    */
-    LVPSA_ERROR_NULLADDRESS,                                /* A pointer has a NULL value                                        */
-    LVPSA_RETURN_DUMMY = LVM_MAXINT_32                      /* Force 32 bits enum, don't use it!                                 */
+typedef enum {
+    LVPSA_OK, /* The function ran without any problem                              */
+    LVPSA_ERROR_INVALIDPARAM, /* A parameter is incorrect */
+    LVPSA_ERROR_WRONGTIME,   /* An incorrect AudioTime is used                                    */
+    LVPSA_ERROR_NULLADDRESS, /* A pointer has a NULL value                                        */
+    LVPSA_RETURN_DUMMY = LVM_MAXINT_32 /* Force 32 bits enum, don't use it! */
 } LVPSA_RETURN;
 
 /*********************************************************************************************************************************
    FUNCTIONS PROTOTYPE
 **********************************************************************************************************************************/
-/*********************************************************************************************************************************/
-/*                                                                                                                               */
-/* FUNCTION:            LVPSA_Memory                                                                                         */
-/*                                                                                                                               */
-/* DESCRIPTION:                                                                                                                  */
-/*  This function is used for memory allocation and free. It can be called in                                                    */
-/*  two ways:                                                                                                                    */
-/*                                                                                                                               */
-/*      hInstance = NULL                Returns the memory requirements                                                          */
-/*      hInstance = Instance handle     Returns the memory requirements and                                                      */
-/*                                      allocated base addresses for the instance                                                */
-/*                                                                                                                               */
-/*  When this function is called for memory allocation (hInstance=NULL) the memory                                               */
-/*  base address pointers are NULL on return.                                                                                    */
-/*                                                                                                                               */
-/*  When the function is called for free (hInstance = Instance Handle) the memory                                                */
-/*  table returns the allocated memory and base addresses used during initialisation.                                            */
-/*                                                                                                                               */
-/* PARAMETERS:                                                                                                                   */
-/*  hInstance           Instance Handle                                                                                          */
-/*  pMemoryTable        Pointer to an empty memory definition table                                                              */
-/*  pInitParams         Pointer to the instance init parameters                                                                  */
-/*                                                                                                                               */
-/* RETURNS:                                                                                                                      */
-/*  LVPSA_OK            Succeeds                                                                                                 */
-/*  otherwise           Error due to bad parameters                                                                              */
-/*                                                                                                                               */
-/*********************************************************************************************************************************/
-LVPSA_RETURN LVPSA_Memory            ( pLVPSA_Handle_t             hInstance,
-                                       LVPSA_MemTab_t             *pMemoryTable,
-                                       LVPSA_InitParams_t         *pInitParams    );
+/************************************************************************************/
+/*                                                                                  */
+/* FUNCTION:            LVPSA_Init                                                  */
+/*                                                                                  */
+/* DESCRIPTION:                                                                     */
+/*  Create and Initialize the LVPSA module including instance handle                */
+/*                                                                                  */
+/*                                                                                  */
+/* PARAMETERS:                                                                      */
+/*  phInstance          Pointer to the instance handle                              */
+/*  InitParams          Init parameters structure                                   */
+/*  ControlParams       Control parameters structure                                */
+/*  pScratch            Pointer to bundle scratch memory area                       */
+/*                                                                                  */
+/*                                                                                  */
+/* RETURNS:                                                                         */
+/*  LVPSA_OK            Succeeds                                                    */
+/*  otherwise           Error due to bad parameters                                 */
+/*                                                                                  */
+/************************************************************************************/
+LVPSA_RETURN LVPSA_Init(pLVPSA_Handle_t* phInstance, LVPSA_InitParams_t* pInitParams,
+                        LVPSA_ControlParams_t* pControlParams, void* pScratch);
+
+/************************************************************************************/
+/*                                                                                  */
+/* FUNCTION:            LVPSA_DeInit                                                */
+/*                                                                                  */
+/* DESCRIPTION:                                                                     */
+/*    Free the memories created in LVPSA_Init call including instance handle        */
+/*                                                                                  */
+/* PARAMETERS:                                                                      */
+/*  phInstance          Pointer to the instance handle                              */
+/*                                                                                  */
+/************************************************************************************/
+void LVPSA_DeInit(pLVPSA_Handle_t* phInstance);
 
 /*********************************************************************************************************************************/
 /*                                                                                                                               */
-/* FUNCTION:            LVPSA_Init                                                                                               */
+/* FUNCTION:            LVPSA_Control */
 /*                                                                                                                               */
-/* DESCRIPTION:                                                                                                                  */
-/*  Initializes the LVPSA module.                                                                                                */
+/* DESCRIPTION: */
+/*  Controls the LVPSA module. */
 /*                                                                                                                               */
+/* PARAMETERS: */
+/*  hInstance           Instance Handle */
+/*  pNewParams          Pointer to the instance new control parameters */
 /*                                                                                                                               */
-/* PARAMETERS:                                                                                                                   */
-/*  phInstance          Pointer to the instance Handle                                                                           */
-/*  pInitParams         Pointer to the instance init parameters                                                                  */
-/*  pControlParams      Pointer to the instance control parameters                                                               */
-/*  pMemoryTable        Pointer to the memory definition table                                                                   */
-/*                                                                                                                               */
-/*                                                                                                                               */
-/* RETURNS:                                                                                                                      */
-/*  LVPSA_OK            Succeeds                                                                                                 */
-/*  otherwise           Error due to bad parameters                                                                              */
+/* RETURNS: */
+/*  LVPSA_OK            Succeeds */
+/*  otherwise           Error due to bad parameters */
 /*                                                                                                                               */
 /*********************************************************************************************************************************/
-LVPSA_RETURN LVPSA_Init              ( pLVPSA_Handle_t             *phInstance,
-                                       LVPSA_InitParams_t          *pInitParams,
-                                       LVPSA_ControlParams_t       *pControlParams,
-                                       LVPSA_MemTab_t              *pMemoryTable  );
+LVPSA_RETURN LVPSA_Control(pLVPSA_Handle_t hInstance, LVPSA_ControlParams_t* pNewParams);
 
 /*********************************************************************************************************************************/
 /*                                                                                                                               */
-/* FUNCTION:            LVPSA_Control                                                                                            */
+/* FUNCTION:            LVPSA_Process */
 /*                                                                                                                               */
-/* DESCRIPTION:                                                                                                                  */
-/*  Controls the LVPSA module.                                                                                                   */
+/* DESCRIPTION: */
+/*  The process calculates the levels of the frequency bands. */
 /*                                                                                                                               */
-/* PARAMETERS:                                                                                                                   */
-/*  hInstance           Instance Handle                                                                                          */
-/*  pNewParams          Pointer to the instance new control parameters                                                           */
+/* PARAMETERS: */
+/*  hInstance           Instance Handle */
+/*  pLVPSA_InputSamples Pointer to the input samples buffer */
+/*  InputBlockSize      Number of mono samples to process */
+/*  AudioTime           Playback time of the first input sample */
 /*                                                                                                                               */
-/* RETURNS:                                                                                                                      */
-/*  LVPSA_OK            Succeeds                                                                                                 */
-/*  otherwise           Error due to bad parameters                                                                              */
+/*                                                                                                                               */
+/* RETURNS: */
+/*  LVPSA_OK            Succeeds */
+/*  otherwise           Error due to bad parameters */
 /*                                                                                                                               */
 /*********************************************************************************************************************************/
-LVPSA_RETURN LVPSA_Control           ( pLVPSA_Handle_t             hInstance,
-                                       LVPSA_ControlParams_t      *pNewParams     );
+LVPSA_RETURN LVPSA_Process(pLVPSA_Handle_t hInstance, LVM_FLOAT* pLVPSA_InputSamples,
+                           LVM_UINT16 InputBlockSize, LVPSA_Time AudioTime);
+/*********************************************************************************************************************************/
+/*                                                                                                                               */
+/* FUNCTION:            LVPSA_GetSpectrum */
+/*                                                                                                                               */
+/* DESCRIPTION: */
+/*  This function is used for memory allocation and free. */
+/*                                                                                                                               */
+/*                                                                                                                               */
+/* PARAMETERS: */
+/*  hInstance            Instance Handle */
+/*  GetSpectrumAudioTime Time to retrieve the values at */
+/*  pCurrentValues       Pointer to an empty buffer : Current level values output */
+/*  pPeakValues          Pointer to an empty buffer : Peak level values output */
+/*                                                                                                                               */
+/*                                                                                                                               */
+/* RETURNS: */
+/*  LVPSA_OK            Succeeds */
+/*  otherwise           Error due to bad parameters */
+/*                                                                                                                               */
+/*********************************************************************************************************************************/
+LVPSA_RETURN LVPSA_GetSpectrum(pLVPSA_Handle_t hInstance, LVPSA_Time GetSpectrumAudioTime,
+                               LVM_UINT8* pCurrentValues, LVM_UINT8* pPeakValues);
 
 /*********************************************************************************************************************************/
 /*                                                                                                                               */
-/* FUNCTION:            LVPSA_Process                                                                                            */
+/* FUNCTION:            LVPSA_GetControlParams */
 /*                                                                                                                               */
-/* DESCRIPTION:                                                                                                                  */
-/*  The process calculates the levels of the frequency bands.                                                                    */
+/* DESCRIPTION: */
+/*  Get the current control parameters of the LVPSA module. */
 /*                                                                                                                               */
-/* PARAMETERS:                                                                                                                   */
-/*  hInstance           Instance Handle                                                                                          */
-/*  pLVPSA_InputSamples Pointer to the input samples buffer                                                                      */
-/*  InputBlockSize      Number of mono samples to process                                                                        */
-/*  AudioTime           Playback time of the first input sample                                                                  */
-/*                                                                                                                               */
-/*                                                                                                                               */
-/* RETURNS:                                                                                                                      */
-/*  LVPSA_OK            Succeeds                                                                                                 */
-/*  otherwise           Error due to bad parameters                                                                              */
+/* PARAMETERS: */
+/*  hInstance           Instance Handle */
+/*  pParams             Pointer to an empty control parameters structure */
+/* RETURNS: */
+/*  LVPSA_OK            Succeeds */
+/*  otherwise           Error due to bad parameters */
 /*                                                                                                                               */
 /*********************************************************************************************************************************/
-LVPSA_RETURN LVPSA_Process           ( pLVPSA_Handle_t      hInstance,
-                                       LVM_FLOAT           *pLVPSA_InputSamples,
-                                       LVM_UINT16           InputBlockSize,
-                                       LVPSA_Time           AudioTime             );
-/*********************************************************************************************************************************/
-/*                                                                                                                               */
-/* FUNCTION:            LVPSA_GetSpectrum                                                                                        */
-/*                                                                                                                               */
-/* DESCRIPTION:                                                                                                                  */
-/*  This function is used for memory allocation and free.                                                                        */
-/*                                                                                                                               */
-/*                                                                                                                               */
-/* PARAMETERS:                                                                                                                   */
-/*  hInstance            Instance Handle                                                                                         */
-/*  GetSpectrumAudioTime Time to retrieve the values at                                                                          */
-/*  pCurrentValues       Pointer to an empty buffer : Current level values output                                                */
-/*  pPeakValues          Pointer to an empty buffer : Peak level values output                                                   */
-/*                                                                                                                               */
-/*                                                                                                                               */
-/* RETURNS:                                                                                                                      */
-/*  LVPSA_OK            Succeeds                                                                                                 */
-/*  otherwise           Error due to bad parameters                                                                              */
-/*                                                                                                                               */
-/*********************************************************************************************************************************/
-LVPSA_RETURN LVPSA_GetSpectrum       ( pLVPSA_Handle_t      hInstance,
-                                       LVPSA_Time           GetSpectrumAudioTime,
-                                       LVM_UINT8           *pCurrentValues,
-                                       LVM_UINT8           *pPeakValues           );
+LVPSA_RETURN LVPSA_GetControlParams(pLVPSA_Handle_t hInstance, LVPSA_ControlParams_t* pParams);
 
 /*********************************************************************************************************************************/
 /*                                                                                                                               */
-/* FUNCTION:            LVPSA_GetControlParams                                                                                   */
+/* FUNCTION:            LVPSA_GetInitParams */
 /*                                                                                                                               */
-/* DESCRIPTION:                                                                                                                  */
-/*  Get the current control parameters of the LVPSA module.                                                                      */
+/* DESCRIPTION: */
+/*  Get the initialization parameters of the LVPSA module. */
 /*                                                                                                                               */
-/* PARAMETERS:                                                                                                                   */
-/*  hInstance           Instance Handle                                                                                          */
-/*  pParams             Pointer to an empty control parameters structure                                                         */
-/* RETURNS:                                                                                                                      */
-/*  LVPSA_OK            Succeeds                                                                                                 */
-/*  otherwise           Error due to bad parameters                                                                              */
+/* PARAMETERS: */
+/*  hInstance           Instance Handle */
+/*  pParams             Pointer to an empty init parameters structure */
+/* RETURNS: */
+/*  LVPSA_OK            Succeeds */
+/*  otherwise           Error due to bad parameters */
 /*                                                                                                                               */
 /*********************************************************************************************************************************/
-LVPSA_RETURN LVPSA_GetControlParams  (    pLVPSA_Handle_t            hInstance,
-                                          LVPSA_ControlParams_t     *pParams      );
-
-/*********************************************************************************************************************************/
-/*                                                                                                                               */
-/* FUNCTION:            LVPSA_GetInitParams                                                                                      */
-/*                                                                                                                               */
-/* DESCRIPTION:                                                                                                                  */
-/*  Get the initialization parameters of the LVPSA module.                                                                       */
-/*                                                                                                                               */
-/* PARAMETERS:                                                                                                                   */
-/*  hInstance           Instance Handle                                                                                          */
-/*  pParams             Pointer to an empty init parameters structure                                                            */
-/* RETURNS:                                                                                                                      */
-/*  LVPSA_OK            Succeeds                                                                                                 */
-/*  otherwise           Error due to bad parameters                                                                              */
-/*                                                                                                                               */
-/*********************************************************************************************************************************/
-LVPSA_RETURN LVPSA_GetInitParams     (    pLVPSA_Handle_t            hInstance,
-                                          LVPSA_InitParams_t        *pParams      );
+LVPSA_RETURN LVPSA_GetInitParams(pLVPSA_Handle_t hInstance, LVPSA_InitParams_t* pParams);
 
 #endif /* _LVPSA_H */
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Control.cpp b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Control.cpp
index deafaa7..8e63502 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Control.cpp
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Control.cpp
@@ -15,30 +15,26 @@
  * limitations under the License.
  */
 
-#include    "LVPSA.h"
-#include    "LVPSA_Private.h"
-#include    "VectorArithmetic.h"
+#include <system/audio.h>
+#include "LVPSA.h"
+#include "LVPSA_Private.h"
+#include "VectorArithmetic.h"
 
-#define     LOW_FREQ            298             /* 32768/110 for low test frequency */
-#define     HIGH_FREQ           386             /* 32768/85 for high test frequency */
+#define LOW_FREQ 298  /* 32768/110 for low test frequency */
+#define HIGH_FREQ 386 /* 32768/85 for high test frequency */
 
-LVPSA_RETURN LVPSA_SetBPFiltersType (  LVPSA_InstancePr_t        *pInst,
-                                       LVPSA_ControlParams_t      *pParams  );
+LVPSA_RETURN LVPSA_SetBPFiltersType(LVPSA_InstancePr_t* pInst, LVPSA_ControlParams_t* pParams);
 
-LVPSA_RETURN LVPSA_SetQPFCoefficients( LVPSA_InstancePr_t        *pInst,
-                                       LVPSA_ControlParams_t      *pParams  );
+LVPSA_RETURN LVPSA_SetQPFCoefficients(LVPSA_InstancePr_t* pInst, LVPSA_ControlParams_t* pParams);
 
-LVPSA_RETURN LVPSA_BPSinglePrecCoefs(  LVM_UINT16             Fs,
-                                       LVPSA_FilterParam_t   *pFilterParams,
-                                       BP_FLOAT_Coefs_t        *pCoefficients);
+LVPSA_RETURN LVPSA_BPSinglePrecCoefs(LVM_UINT16 Fs, LVPSA_FilterParam_t* pFilterParams,
+                                     BP_FLOAT_Coefs_t* pCoefficients);
 
-LVPSA_RETURN LVPSA_BPDoublePrecCoefs(  LVM_UINT16            Fs,
-                                       LVPSA_FilterParam_t  *pFilterParams,
-                                       BP_FLOAT_Coefs_t       *pCoefficients);
-LVPSA_RETURN LVPSA_SetBPFCoefficients( LVPSA_InstancePr_t        *pInst,
-                                       LVPSA_ControlParams_t      *pParams  );
+LVPSA_RETURN LVPSA_BPDoublePrecCoefs(LVM_UINT16 Fs, LVPSA_FilterParam_t* pFilterParams,
+                                     BP_FLOAT_Coefs_t* pCoefficients);
+LVPSA_RETURN LVPSA_SetBPFCoefficients(LVPSA_InstancePr_t* pInst, LVPSA_ControlParams_t* pParams);
 
-LVPSA_RETURN LVPSA_ClearFilterHistory( LVPSA_InstancePr_t        *pInst);
+LVPSA_RETURN LVPSA_ClearFilterHistory(LVPSA_InstancePr_t* pInst);
 
 /************************************************************************************/
 /*                                                                                  */
@@ -56,29 +52,23 @@
 /*  otherwise           Error due to bad parameters                                 */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_Control           ( pLVPSA_Handle_t             hInstance,
-                                       LVPSA_ControlParams_t      *pNewParams     )
-{
+LVPSA_RETURN LVPSA_Control(pLVPSA_Handle_t hInstance, LVPSA_ControlParams_t* pNewParams) {
+    LVPSA_InstancePr_t* pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
 
-    LVPSA_InstancePr_t     *pLVPSA_Inst    = (LVPSA_InstancePr_t*)hInstance;
-
-    if((hInstance == LVM_NULL) || (pNewParams == LVM_NULL))
-    {
-        return(LVPSA_ERROR_NULLADDRESS);
+    if ((hInstance == LVM_NULL) || (pNewParams == LVM_NULL)) {
+        return (LVPSA_ERROR_NULLADDRESS);
     }
-    if(pNewParams->Fs >= LVPSA_NR_SUPPORTED_RATE)
-    {
-        return(LVPSA_ERROR_INVALIDPARAM);
+    if (pNewParams->Fs >= LVPSA_NR_SUPPORTED_RATE) {
+        return (LVPSA_ERROR_INVALIDPARAM);
     }
-    if(pNewParams->LevelDetectionSpeed >= LVPSA_NR_SUPPORTED_SPEED)
-    {
-        return(LVPSA_ERROR_INVALIDPARAM);
+    if (pNewParams->LevelDetectionSpeed >= LVPSA_NR_SUPPORTED_SPEED) {
+        return (LVPSA_ERROR_INVALIDPARAM);
     }
 
     pLVPSA_Inst->NewParams = *pNewParams;
     pLVPSA_Inst->bControlPending = LVM_TRUE;
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
 
 /************************************************************************************/
@@ -96,20 +86,17 @@
 /*  otherwise           Error due to bad parameters                                 */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_GetControlParams         (    pLVPSA_Handle_t            hInstance,
-                                                 LVPSA_ControlParams_t     *pParams )
-{
-    LVPSA_InstancePr_t     *pLVPSA_Inst    = (LVPSA_InstancePr_t*)hInstance;
+LVPSA_RETURN LVPSA_GetControlParams(pLVPSA_Handle_t hInstance, LVPSA_ControlParams_t* pParams) {
+    LVPSA_InstancePr_t* pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
 
-    if((hInstance == LVM_NULL) || (pParams == LVM_NULL))
-    {
-        return(LVPSA_ERROR_NULLADDRESS);
+    if ((hInstance == LVM_NULL) || (pParams == LVM_NULL)) {
+        return (LVPSA_ERROR_NULLADDRESS);
     }
 
-    pParams->Fs                     = pLVPSA_Inst->CurrentParams.Fs;
-    pParams->LevelDetectionSpeed    = pLVPSA_Inst->CurrentParams.LevelDetectionSpeed;
+    pParams->Fs = pLVPSA_Inst->CurrentParams.Fs;
+    pParams->LevelDetectionSpeed = pLVPSA_Inst->CurrentParams.LevelDetectionSpeed;
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
 
 /************************************************************************************/
@@ -127,22 +114,19 @@
 /*  otherwise           Error due to bad parameters                                 */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_GetInitParams         (    pLVPSA_Handle_t            hInstance,
-                                              LVPSA_InitParams_t        *pParams )
-{
-    LVPSA_InstancePr_t     *pLVPSA_Inst    = (LVPSA_InstancePr_t*)hInstance;
+LVPSA_RETURN LVPSA_GetInitParams(pLVPSA_Handle_t hInstance, LVPSA_InitParams_t* pParams) {
+    LVPSA_InstancePr_t* pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
 
-    if((hInstance == LVM_NULL) || (pParams == LVM_NULL))
-    {
-        return(LVPSA_ERROR_NULLADDRESS);
+    if ((hInstance == LVM_NULL) || (pParams == LVM_NULL)) {
+        return (LVPSA_ERROR_NULLADDRESS);
     }
 
-    pParams->SpectralDataBufferDuration   = pLVPSA_Inst->SpectralDataBufferDuration;
-    pParams->MaxInputBlockSize            = pLVPSA_Inst->MaxInputBlockSize;
-    pParams->nBands                       = pLVPSA_Inst->nBands;
-    pParams->pFiltersParams               = pLVPSA_Inst->pFiltersParams;
+    pParams->SpectralDataBufferDuration = pLVPSA_Inst->SpectralDataBufferDuration;
+    pParams->MaxInputBlockSize = pLVPSA_Inst->MaxInputBlockSize;
+    pParams->nBands = pLVPSA_Inst->nBands;
+    pParams->pFiltersParams = pLVPSA_Inst->pFiltersParams;
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
 
 /************************************************************************************/
@@ -163,46 +147,47 @@
 /* NOTES:                                                                           */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_ApplyNewSettings (LVPSA_InstancePr_t     *pInst)
-{
+LVPSA_RETURN LVPSA_ApplyNewSettings(LVPSA_InstancePr_t* pInst) {
     LVM_UINT16 ii;
     LVM_UINT16 Freq;
-    LVPSA_ControlParams_t   Params;
-    extern LVM_INT16        LVPSA_nSamplesBufferUpdate[];
-    extern LVM_UINT32       LVPSA_SampleRateTab[];
-    extern LVM_UINT16       LVPSA_DownSamplingFactor[];
+    LVPSA_ControlParams_t Params;
+    extern LVM_INT16 LVPSA_nSamplesBufferUpdate[];
+    extern LVM_UINT32 LVPSA_SampleRateTab[];
+    extern LVM_UINT16 LVPSA_DownSamplingFactor[];
 
-    if(pInst == 0)
-    {
-        return(LVPSA_ERROR_NULLADDRESS);
+    if (pInst == 0) {
+        return (LVPSA_ERROR_NULLADDRESS);
     }
 
     Params = pInst->NewParams;
 
     /* Modifies filters types and coefficients, clear the taps and
        re-initializes parameters if sample frequency has changed    */
-    if(Params.Fs != pInst->CurrentParams.Fs)
-    {
+    if (Params.Fs != pInst->CurrentParams.Fs) {
         pInst->CurrentParams.Fs = Params.Fs;
 
         /* Initialize the center freqeuncies as a function of the sample rate */
-        Freq = (LVM_UINT16) ((LVPSA_SampleRateTab[pInst->CurrentParams.Fs]>>1) / (pInst->nBands + 1));
-        for(ii = pInst->nBands; ii > 0; ii--)
-        {
-            pInst->pFiltersParams[ii-1].CenterFrequency = (LVM_UINT16) (Freq * ii);
+        Freq = (LVM_UINT16)((LVPSA_SampleRateTab[pInst->CurrentParams.Fs] >> 1) /
+                            (pInst->nBands + 1));
+        for (ii = pInst->nBands; ii > 0; ii--) {
+            pInst->pFiltersParams[ii - 1].CenterFrequency = (LVM_UINT16)(Freq * ii);
         }
 
         /* Count the number of relevant filters. If the center frequency of the filter is
            bigger than the nyquist frequency, then the filter is not relevant and doesn't
            need to be used */
-        for(ii = pInst->nBands; ii > 0; ii--)
-        {
-            if(pInst->pFiltersParams[ii-1].CenterFrequency < (LVPSA_SampleRateTab[pInst->CurrentParams.Fs]>>1))
-            {
+        for (ii = pInst->nBands; ii > 0; ii--) {
+            if (pInst->pFiltersParams[ii - 1].CenterFrequency <
+                (LVPSA_SampleRateTab[pInst->CurrentParams.Fs] >> 1)) {
                 pInst->nRelevantFilters = ii;
                 break;
             }
         }
+        /*
+         * Create biquad instance
+         */
+        pInst->specBiquad.resize(pInst->nRelevantFilters,
+                                 android::audio_utils::BiquadFilter<LVM_FLOAT>(FCC_1));
         LVPSA_SetBPFiltersType(pInst, &Params);
         LVPSA_SetBPFCoefficients(pInst, &Params);
         LVPSA_SetQPFCoefficients(pInst, &Params);
@@ -211,19 +196,14 @@
         pInst->BufferUpdateSamplesCount = 0;
         pInst->DownSamplingFactor = LVPSA_DownSamplingFactor[Params.Fs];
         pInst->DownSamplingCount = 0;
-        for(ii = 0; ii < (pInst->nBands * pInst->SpectralDataBufferLength); ii++)
-        {
+        for (ii = 0; ii < (pInst->nBands * pInst->SpectralDataBufferLength); ii++) {
             pInst->pSpectralDataBufferStart[ii] = 0;
         }
-        for(ii = 0; ii < pInst->nBands; ii++)
-        {
+        for (ii = 0; ii < pInst->nBands; ii++) {
             pInst->pPreviousPeaks[ii] = 0;
         }
-    }
-    else
-    {
-        if(Params.LevelDetectionSpeed != pInst->CurrentParams.LevelDetectionSpeed)
-        {
+    } else {
+        if (Params.LevelDetectionSpeed != pInst->CurrentParams.LevelDetectionSpeed) {
             LVPSA_SetQPFCoefficients(pInst, &Params);
         }
     }
@@ -253,47 +233,43 @@
 /*          Single precision    otherwise                                           */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_SetBPFiltersType (   LVPSA_InstancePr_t        *pInst,
-                                        LVPSA_ControlParams_t      *pParams  )
-{
-    extern LVM_UINT32   LVPSA_SampleRateTab[];                 /* Sample rate table */
-    LVM_UINT16          ii;                                                         /* Filter band index */
-    LVM_UINT32          fs = (LVM_UINT32)LVPSA_SampleRateTab[(LVM_UINT16)pParams->Fs];      /* Sample rate */
-    LVM_UINT32          fc;                                                         /* Filter centre frequency */
-    LVM_INT16           QFactor;                                                    /* Filter Q factor */
+LVPSA_RETURN LVPSA_SetBPFiltersType(LVPSA_InstancePr_t* pInst, LVPSA_ControlParams_t* pParams) {
+    extern LVM_UINT32 LVPSA_SampleRateTab[]; /* Sample rate table */
+    LVM_UINT16 ii;                           /* Filter band index */
+    LVM_UINT32 fs = (LVM_UINT32)LVPSA_SampleRateTab[(LVM_UINT16)pParams->Fs]; /* Sample rate */
+    LVM_UINT32 fc;     /* Filter centre frequency */
+    LVM_INT16 QFactor; /* Filter Q factor */
 
-    for (ii = 0; ii < pInst->nRelevantFilters; ii++)
-    {
+    for (ii = 0; ii < pInst->nRelevantFilters; ii++) {
         /*
          * Get the filter settings
          */
-        fc = (LVM_UINT32)pInst->pFiltersParams[ii].CenterFrequency;     /* Get the band centre frequency */
-        QFactor =(LVM_INT16) pInst->pFiltersParams[ii].QFactor;                    /* Get the band Q factor */
+        fc = (LVM_UINT32)pInst->pFiltersParams[ii]
+                     .CenterFrequency;                          /* Get the band centre frequency */
+        QFactor = (LVM_INT16)pInst->pFiltersParams[ii].QFactor; /* Get the band Q factor */
 
         /*
          * For each filter set the type of biquad required
          */
-        pInst->pBPFiltersPrecision[ii] = LVPSA_SimplePrecisionFilter;     /* Default to single precision */
-        if ((LOW_FREQ * fs) >= (fc << 15))
-        {
+        pInst->pBPFiltersPrecision[ii] =
+                LVPSA_SimplePrecisionFilter; /* Default to single precision */
+        if ((LOW_FREQ * fs) >= (fc << 15)) {
             /*
              * fc <= fs/110
              */
             pInst->pBPFiltersPrecision[ii] = LVPSA_DoublePrecisionFilter;
-        }
-        else
-        {
-            if (((LOW_FREQ * fs) < (fc << 15)) && ((fc << 15) < (HIGH_FREQ * fs)) && (QFactor > 300))
-            {
+        } else {
+            if (((LOW_FREQ * fs) < (fc << 15)) && ((fc << 15) < (HIGH_FREQ * fs)) &&
+                (QFactor > 300)) {
                 /*
-                * (fs/110 < fc < fs/85) & (Q>3)
-                */
+                 * (fs/110 < fc < fs/85) & (Q>3)
+                 */
                 pInst->pBPFiltersPrecision[ii] = LVPSA_DoublePrecisionFilter;
             }
         }
     }
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
 
 /************************************************************************************/
@@ -314,60 +290,59 @@
 /* NOTES:                                                                           */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_SetBPFCoefficients(  LVPSA_InstancePr_t        *pInst,
-                                        LVPSA_ControlParams_t      *pParams)
-{
-
-    LVM_UINT16                      ii;
+LVPSA_RETURN LVPSA_SetBPFCoefficients(LVPSA_InstancePr_t* pInst, LVPSA_ControlParams_t* pParams) {
+    LVM_UINT16 ii;
 
     /*
      * Set the coefficients for each band by the init function
      */
-    for (ii = 0; ii < pInst->nRelevantFilters; ii++)
-    {
-        switch  (pInst->pBPFiltersPrecision[ii])
-        {
-            case    LVPSA_DoublePrecisionFilter:
-            {
-                BP_FLOAT_Coefs_t      Coefficients;
+    for (ii = 0; ii < pInst->nRelevantFilters; ii++) {
+        switch (pInst->pBPFiltersPrecision[ii]) {
+            case LVPSA_DoublePrecisionFilter: {
+                BP_FLOAT_Coefs_t Coefficients;
                 /*
                  * Calculate the double precision coefficients
                  */
-                LVPSA_BPDoublePrecCoefs((LVM_UINT16)pParams->Fs,
-                                        &pInst->pFiltersParams[ii],
+                LVPSA_BPDoublePrecCoefs((LVM_UINT16)pParams->Fs, &pInst->pFiltersParams[ii],
                                         &Coefficients);
                 /*
                  * Set the coefficients
                  */
-                BP_1I_D16F32Cll_TRC_WRA_01_Init ( &pInst->pBP_Instances[ii],
-                                                  &pInst->pBP_Taps[ii],
-                                                  &Coefficients);
+                const std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                        Coefficients.A0, 0.0, -(Coefficients.A0), -(Coefficients.B1),
+                        -(Coefficients.B2)};
+                pInst->specBiquad[ii]
+                        .setCoefficients<
+                                std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs>>(
+                                coefs);
                 break;
             }
 
-            case    LVPSA_SimplePrecisionFilter:
-            {
-                BP_FLOAT_Coefs_t      Coefficients;
+            case LVPSA_SimplePrecisionFilter: {
+                BP_FLOAT_Coefs_t Coefficients;
 
                 /*
                  * Calculate the single precision coefficients
                  */
-                LVPSA_BPSinglePrecCoefs((LVM_UINT16)pParams->Fs,
-                                        &pInst->pFiltersParams[ii],
+                LVPSA_BPSinglePrecCoefs((LVM_UINT16)pParams->Fs, &pInst->pFiltersParams[ii],
                                         &Coefficients);
 
                 /*
                  * Set the coefficients
                  */
-                BP_1I_D16F16Css_TRC_WRA_01_Init (&pInst->pBP_Instances[ii],
-                                                  &pInst->pBP_Taps[ii],
-                                                  &Coefficients);
+                const std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                        Coefficients.A0, 0.0, -(Coefficients.A0), -(Coefficients.B1),
+                        -(Coefficients.B2)};
+                pInst->specBiquad[ii]
+                        .setCoefficients<
+                                std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs>>(
+                                coefs);
                 break;
             }
         }
     }
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
 
 /************************************************************************************/
@@ -388,26 +363,20 @@
 /* NOTES:                                                                           */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_SetQPFCoefficients(   LVPSA_InstancePr_t        *pInst,
-                                         LVPSA_ControlParams_t      *pParams  )
-{
-    LVM_UINT16     ii;
-    LVM_Fs_en      Fs = pParams->Fs;
-    QPD_FLOAT_Coefs  *pCoefficients;
-    extern         QPD_FLOAT_Coefs     LVPSA_QPD_Float_Coefs[];
+LVPSA_RETURN LVPSA_SetQPFCoefficients(LVPSA_InstancePr_t* pInst, LVPSA_ControlParams_t* pParams) {
+    LVM_UINT16 ii;
+    LVM_Fs_en Fs = pParams->Fs;
+    QPD_FLOAT_Coefs* pCoefficients;
+    extern QPD_FLOAT_Coefs LVPSA_QPD_Float_Coefs[];
 
-    pCoefficients = &LVPSA_QPD_Float_Coefs[(pParams->LevelDetectionSpeed * \
-                                    LVPSA_NR_SUPPORTED_RATE) + Fs];
+    pCoefficients =
+            &LVPSA_QPD_Float_Coefs[(pParams->LevelDetectionSpeed * LVPSA_NR_SUPPORTED_RATE) + Fs];
 
-    for (ii = 0; ii < pInst->nRelevantFilters; ii++)
-    {
-        LVPSA_QPD_Init_Float (&pInst->pQPD_States[ii],
-                              &pInst->pQPD_Taps[ii],
-                              pCoefficients );
+    for (ii = 0; ii < pInst->nRelevantFilters; ii++) {
+        LVPSA_QPD_Init_Float(&pInst->pQPD_States[ii], &pInst->pQPD_Taps[ii], pCoefficients);
     }
 
-    return(LVPSA_OK);
-
+    return (LVPSA_OK);
 }
 
 /****************************************************************************************/
@@ -443,49 +412,46 @@
 /*     of the n bands equalizer (LVEQNB                                                 */
 /*                                                                                      */
 /****************************************************************************************/
-LVPSA_RETURN LVPSA_BPSinglePrecCoefs(    LVM_UINT16              Fs,
-                                         LVPSA_FilterParam_t     *pFilterParams,
-                                         BP_FLOAT_Coefs_t        *pCoefficients)
-{
-
-    extern LVM_FLOAT    LVPSA_Float_TwoPiOnFsTable[];
-    extern LVM_FLOAT    LVPSA_Float_CosCoef[];
+LVPSA_RETURN LVPSA_BPSinglePrecCoefs(LVM_UINT16 Fs, LVPSA_FilterParam_t* pFilterParams,
+                                     BP_FLOAT_Coefs_t* pCoefficients) {
+    extern LVM_FLOAT LVPSA_Float_TwoPiOnFsTable[];
+    extern LVM_FLOAT LVPSA_Float_CosCoef[];
 
     /*
      * Intermediate variables and temporary values
      */
-    LVM_FLOAT           T0;
-    LVM_FLOAT           D;
-    LVM_FLOAT           A0;
-    LVM_FLOAT           B1;
-    LVM_FLOAT           B2;
-    LVM_FLOAT           Dt0;
-    LVM_FLOAT           B2_Den;
-    LVM_FLOAT           B2_Num;
-    LVM_FLOAT           COS_T0;
-    LVM_FLOAT           coef;
-    LVM_FLOAT           factor;
-    LVM_FLOAT           t0;
-    LVM_INT16           i;
+    LVM_FLOAT T0;
+    LVM_FLOAT D;
+    LVM_FLOAT A0;
+    LVM_FLOAT B1;
+    LVM_FLOAT B2;
+    LVM_FLOAT Dt0;
+    LVM_FLOAT B2_Den;
+    LVM_FLOAT B2_Num;
+    LVM_FLOAT COS_T0;
+    LVM_FLOAT coef;
+    LVM_FLOAT factor;
+    LVM_FLOAT t0;
+    LVM_INT16 i;
 
     /*
      * Get the filter definition
      */
-    LVM_FLOAT          Frequency   = (LVM_FLOAT)(pFilterParams->CenterFrequency);
-    LVM_FLOAT          QFactor     = ((LVM_FLOAT)(pFilterParams->QFactor)) / 100;
+    LVM_FLOAT Frequency = (LVM_FLOAT)(pFilterParams->CenterFrequency);
+    LVM_FLOAT QFactor = ((LVM_FLOAT)(pFilterParams->QFactor)) / 100;
 
     /*
      * Calculating the intermediate values
      */
-    T0 = Frequency * LVPSA_Float_TwoPiOnFsTable[Fs];   /* T0 = 2 * Pi * Fc / Fs */
-    D = 3200;                 /* Floating point value 1.000000 (1*100*2^5) */
-                    /* Force D = 1 : the function was originally used for a peaking filter.
-                       The D parameter do not exist for a BandPass filter coefficients */
+    T0 = Frequency * LVPSA_Float_TwoPiOnFsTable[Fs]; /* T0 = 2 * Pi * Fc / Fs */
+    D = 3200;                                        /* Floating point value 1.000000 (1*100*2^5) */
+    /* Force D = 1 : the function was originally used for a peaking filter.
+       The D parameter do not exist for a BandPass filter coefficients */
 
     /*
      * Calculate the B2 coefficient
      */
-    Dt0 =  T0 / 2048 ;
+    Dt0 = T0 / 2048;
     B2_Den = QFactor + Dt0;
     B2_Num = Dt0 - QFactor;
     B2 = B2_Num / (2 * B2_Den);
@@ -495,20 +461,19 @@
      *
      *  Cos += coef(n) * t0^n                   For n = 0 to 6
      */
-    T0 = (T0 / 2048) * 0.63658558f;              /* Scale to 1.0 in 16-bit for range 0 to fs/2 */
-    t0 = T0 ;
-    factor = 1.0f;                            /* Initialise to 1.0 for the a0 coefficient */
-    COS_T0 = 0.0f;                                 /* Initialise the error to zero */
-    for (i = 1; i < 7; i++)
-    {
-        coef    = LVPSA_Float_CosCoef[i];                /* Get the nth coefficient */
-        COS_T0 += (factor * coef);         /* The nth partial sum */
-        factor  = (factor * t0) ;           /* Calculate t0^n */
+    T0 = (T0 / 2048) * 0.63658558f; /* Scale to 1.0 in 16-bit for range 0 to fs/2 */
+    t0 = T0;
+    factor = 1.0f; /* Initialise to 1.0 for the a0 coefficient */
+    COS_T0 = 0.0f; /* Initialise the error to zero */
+    for (i = 1; i < 7; i++) {
+        coef = LVPSA_Float_CosCoef[i]; /* Get the nth coefficient */
+        COS_T0 += (factor * coef);     /* The nth partial sum */
+        factor = (factor * t0);        /* Calculate t0^n */
     }
-    COS_T0 = COS_T0 * 8;    /*LVPSA_CosCoef_float[0]*/      /* Correct the scaling */
+    COS_T0 = COS_T0 * 8; /*LVPSA_CosCoef_float[0]*/ /* Correct the scaling */
 
-    B1 = ((LVM_FLOAT)0.5 - B2) * (COS_T0);    /* B1 = (0.5 - b2) * cos(t0) */
-    A0 = ((LVM_FLOAT)0.5 + B2) / 2;                        /* A0 = (0.5 + b2) / 2 */
+    B1 = ((LVM_FLOAT)0.5 - B2) * (COS_T0); /* B1 = (0.5 - b2) * cos(t0) */
+    A0 = ((LVM_FLOAT)0.5 + B2) / 2;        /* A0 = (0.5 + b2) / 2 */
 
     /*
      * Write coeff into the data structure
@@ -517,7 +482,7 @@
     pCoefficients->B1 = B1 * 2;
     pCoefficients->B2 = B2 * 2;
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
 /****************************************************************************************/
 /*                                                                                      */
@@ -561,49 +526,46 @@
 /*     of the n bands equalizer (LVEQNB                                                 */
 /*                                                                                      */
 /****************************************************************************************/
-LVPSA_RETURN LVPSA_BPDoublePrecCoefs(   LVM_UINT16            Fs,
-                                        LVPSA_FilterParam_t   *pFilterParams,
-                                        BP_FLOAT_Coefs_t      *pCoefficients)
-{
-
-    extern LVM_FLOAT    LVPSA_Float_TwoPiOnFsTable[];
-    extern LVM_FLOAT    LVPSA_Float_DPCosCoef[];
+LVPSA_RETURN LVPSA_BPDoublePrecCoefs(LVM_UINT16 Fs, LVPSA_FilterParam_t* pFilterParams,
+                                     BP_FLOAT_Coefs_t* pCoefficients) {
+    extern LVM_FLOAT LVPSA_Float_TwoPiOnFsTable[];
+    extern LVM_FLOAT LVPSA_Float_DPCosCoef[];
 
     /*
      * Intermediate variables and temporary values
      */
-    LVM_FLOAT           T0;
-    LVM_FLOAT           D;
-    LVM_FLOAT           A0;
-    LVM_FLOAT           B1;
-    LVM_FLOAT           B2;
-    LVM_FLOAT           Dt0;
-    LVM_FLOAT           B2_Den;
-    LVM_FLOAT           B2_Num;
-    LVM_FLOAT           CosErr;
-    LVM_FLOAT           coef;
-    LVM_FLOAT           factor;
-    LVM_FLOAT           t0;
-    LVM_INT16           i;
+    LVM_FLOAT T0;
+    LVM_FLOAT D;
+    LVM_FLOAT A0;
+    LVM_FLOAT B1;
+    LVM_FLOAT B2;
+    LVM_FLOAT Dt0;
+    LVM_FLOAT B2_Den;
+    LVM_FLOAT B2_Num;
+    LVM_FLOAT CosErr;
+    LVM_FLOAT coef;
+    LVM_FLOAT factor;
+    LVM_FLOAT t0;
+    LVM_INT16 i;
 
     /*
      * Get the filter definition
      */
-    LVM_FLOAT          Frequency   = (LVM_FLOAT)(pFilterParams->CenterFrequency);
-    LVM_FLOAT          QFactor     = ((LVM_FLOAT)(pFilterParams->QFactor)) / 100;
+    LVM_FLOAT Frequency = (LVM_FLOAT)(pFilterParams->CenterFrequency);
+    LVM_FLOAT QFactor = ((LVM_FLOAT)(pFilterParams->QFactor)) / 100;
 
     /*
      * Calculating the intermediate values
      */
-    T0 = Frequency * LVPSA_Float_TwoPiOnFsTable[Fs];   /* T0 = 2 * Pi * Fc / Fs */
-    D = 3200;    /* Floating point value 1.000000 (1*100*2^5) */
-                 /* Force D = 1 : the function was originally used for a peaking filter.
-                    The D parameter do not exist for a BandPass filter coefficients */
+    T0 = Frequency * LVPSA_Float_TwoPiOnFsTable[Fs]; /* T0 = 2 * Pi * Fc / Fs */
+    D = 3200;                                        /* Floating point value 1.000000 (1*100*2^5) */
+    /* Force D = 1 : the function was originally used for a peaking filter.
+       The D parameter do not exist for a BandPass filter coefficients */
 
     /*
      * Calculate the B2 coefficient
      */
-    Dt0 =  T0 / 2048 ;
+    Dt0 = T0 / 2048;
     B2_Den = QFactor + Dt0;
     B2_Num = Dt0 - QFactor;
     B2 = B2_Num / (2 * B2_Den);
@@ -613,25 +575,24 @@
      *
      *  CosErr += coef(n) * t0^n                For n = 0 to 4
      */
-    T0 = T0 * 0.994750f;                    /* Scale to 1.0 in 16-bit for range 0 to fs/50 */
+    T0 = T0 * 0.994750f; /* Scale to 1.0 in 16-bit for range 0 to fs/50 */
     t0 = T0;
-    factor = 1.0f;                            /* Initialise to 1.0 for the a0 coefficient */
-    CosErr = 0.0f;                                 /* Initialise the error to zero */
-    for (i = 1; i < 5; i++)
-    {
-        coef = LVPSA_Float_DPCosCoef[i];              /* Get the nth coefficient */
+    factor = 1.0f; /* Initialise to 1.0 for the a0 coefficient */
+    CosErr = 0.0f; /* Initialise the error to zero */
+    for (i = 1; i < 5; i++) {
+        coef = LVPSA_Float_DPCosCoef[i]; /* Get the nth coefficient */
         CosErr += factor * coef;         /* The nth partial sum */
-        factor = factor * t0;           /* Calculate t0^n */
+        factor = factor * t0;            /* Calculate t0^n */
     }
-    CosErr = CosErr * 2;          /* Correct the scaling */
+    CosErr = CosErr * 2; /* Correct the scaling */
 
     /*
      * Calculate the B1 and A0 coefficients
      */
-    B1 = ((LVM_FLOAT)0.5 - B2);                     /* B1 = (0.5 - b2) */
-    A0 = B1 * CosErr ;    /* Temporary storage for (0.5 - b2) * coserr(t0) */
-    B1 -= A0;                                   /* B1 = (0.5 - b2) * (1 - coserr(t0))  */
-    A0 = ((LVM_FLOAT)0.5  + B2) / 2;                /* A0 = (0.5 + b2) / 2 */
+    B1 = ((LVM_FLOAT)0.5 - B2);     /* B1 = (0.5 - b2) */
+    A0 = B1 * CosErr;               /* Temporary storage for (0.5 - b2) * coserr(t0) */
+    B1 -= A0;                       /* B1 = (0.5 - b2) * (1 - coserr(t0))  */
+    A0 = ((LVM_FLOAT)0.5 + B2) / 2; /* A0 = (0.5 + b2) / 2 */
 
     /*
      * Write coeff into the data structure
@@ -640,7 +601,7 @@
     pCoefficients->B1 = B1;
     pCoefficients->B2 = B2;
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
 /************************************************************************************/
 /*                                                                                  */
@@ -658,24 +619,10 @@
 /* NOTES:                                                                           */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_ClearFilterHistory(LVPSA_InstancePr_t        *pInst)
-{
-    LVM_INT8       *pTapAddress;
-    LVM_UINT32       i;
-
-    /* Band Pass filters taps */
-    pTapAddress = (LVM_INT8 *)pInst->pBP_Taps;
-    for(i = 0; i < pInst->nBands * sizeof(Biquad_1I_Order2_FLOAT_Taps_t); i++)
-    {
-        pTapAddress[i] = 0;
-    }
-    /* Quasi-peak filters taps */
-    pTapAddress = (LVM_INT8 *)pInst->pQPD_Taps;
-    for(i = 0; i < pInst->nBands * sizeof(QPD_Taps_t); i++)
-    {
-        pTapAddress[i] = 0;
+LVPSA_RETURN LVPSA_ClearFilterHistory(LVPSA_InstancePr_t* pInst) {
+    for (size_t i = 0; i < pInst->specBiquad.size(); i++) {
+        pInst->specBiquad[i].clear();
     }
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
-
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Init.cpp b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Init.cpp
index 9fcd82f..5550b9c 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Init.cpp
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Init.cpp
@@ -15,23 +15,24 @@
  * limitations under the License.
  */
 
-#include    "LVPSA.h"
-#include    "LVPSA_Private.h"
-#include    "InstAlloc.h"
+#include <stdlib.h>
+#include "LVPSA.h"
+#include "LVPSA_Private.h"
+#include "InstAlloc.h"
 
 /************************************************************************************/
 /*                                                                                  */
 /* FUNCTION:            LVPSA_Init                                                  */
 /*                                                                                  */
 /* DESCRIPTION:                                                                     */
-/*  Initialize the LVPSA module                                                     */
+/*  Create and Initialize the LVPSA module including instance handle                */
 /*                                                                                  */
 /*                                                                                  */
 /* PARAMETERS:                                                                      */
-/*  phInstance          Pointer to pointer to the instance                          */
+/*  phInstance          Pointer to the instance handle                              */
 /*  InitParams          Init parameters structure                                   */
 /*  ControlParams       Control parameters structure                                */
-/*  pMemoryTable        Memory table that contains memory areas definition          */
+/*  pScratch            Pointer to bundle scratch memory area                       */
 /*                                                                                  */
 /*                                                                                  */
 /* RETURNS:                                                                         */
@@ -39,75 +40,19 @@
 /*  otherwise           Error due to bad parameters                                 */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_Init              ( pLVPSA_Handle_t             *phInstance,
-                                       LVPSA_InitParams_t          *pInitParams,
-                                       LVPSA_ControlParams_t       *pControlParams,
-                                       LVPSA_MemTab_t              *pMemoryTable )
-{
-    LVPSA_InstancePr_t          *pLVPSA_Inst;
-    LVPSA_RETURN                errorCode       = LVPSA_OK;
-    LVM_UINT32                  ii;
-    extern LVM_FLOAT            LVPSA_Float_GainTable[];
-    LVM_UINT32                  BufferLength = 0;
-
-    /* Ints_Alloc instances, needed for memory alignment management */
-    INST_ALLOC          Instance;
-    INST_ALLOC          Scratch;
-    INST_ALLOC          Data;
-    INST_ALLOC          Coef;
-
-    /* Check parameters */
-    if((phInstance == LVM_NULL) || (pInitParams == LVM_NULL) || (pControlParams == LVM_NULL) || (pMemoryTable == LVM_NULL))
-    {
-        return(LVPSA_ERROR_NULLADDRESS);
-    }
-    if( (pInitParams->SpectralDataBufferDuration > LVPSA_MAXBUFFERDURATION)   ||
-        (pInitParams->SpectralDataBufferDuration == 0)                        ||
-        (pInitParams->MaxInputBlockSize > LVPSA_MAXINPUTBLOCKSIZE)      ||
-        (pInitParams->MaxInputBlockSize == 0)                           ||
-        (pInitParams->nBands < LVPSA_NBANDSMIN)                         ||
-        (pInitParams->nBands > LVPSA_NBANDSMAX)                         ||
-        (pInitParams->pFiltersParams == 0))
-    {
-        return(LVPSA_ERROR_INVALIDPARAM);
-    }
-    for(ii = 0; ii < pInitParams->nBands; ii++)
-    {
-        if((pInitParams->pFiltersParams[ii].CenterFrequency > LVPSA_MAXCENTERFREQ) ||
-           (pInitParams->pFiltersParams[ii].PostGain        > LVPSA_MAXPOSTGAIN)   ||
-           (pInitParams->pFiltersParams[ii].PostGain        < LVPSA_MINPOSTGAIN)   ||
-           (pInitParams->pFiltersParams[ii].QFactor < LVPSA_MINQFACTOR)            ||
-           (pInitParams->pFiltersParams[ii].QFactor > LVPSA_MAXQFACTOR))
-           {
-                return(LVPSA_ERROR_INVALIDPARAM);
-           }
-    }
-
-    /*Inst_Alloc instances initialization */
-    InstAlloc_Init( &Instance   , pMemoryTable->Region[LVPSA_MEMREGION_INSTANCE].pBaseAddress);
-    InstAlloc_Init( &Scratch    , pMemoryTable->Region[LVPSA_MEMREGION_SCRATCH].pBaseAddress);
-    InstAlloc_Init( &Data       , pMemoryTable->Region[LVPSA_MEMREGION_PERSISTENT_DATA].pBaseAddress);
-    InstAlloc_Init( &Coef       , pMemoryTable->Region[LVPSA_MEMREGION_PERSISTENT_COEF].pBaseAddress);
+LVPSA_RETURN LVPSA_Init(pLVPSA_Handle_t* phInstance, LVPSA_InitParams_t* pInitParams,
+                        LVPSA_ControlParams_t* pControlParams, void* pScratch) {
+    LVPSA_InstancePr_t* pLVPSA_Inst;
+    LVPSA_RETURN errorCode = LVPSA_OK;
+    LVM_UINT32 ii;
+    extern LVM_FLOAT LVPSA_Float_GainTable[];
+    LVM_UINT32 BufferLength = 0;
 
     /* Set the instance handle if not already initialised */
-    if (*phInstance == LVM_NULL)
-    {
-        *phInstance = InstAlloc_AddMember( &Instance, sizeof(LVPSA_InstancePr_t) );
-    }
-    pLVPSA_Inst =(LVPSA_InstancePr_t*)*phInstance;
+    *phInstance = new LVPSA_InstancePr_t{};
+    pLVPSA_Inst = (LVPSA_InstancePr_t*)*phInstance;
 
-    /* Check the memory table for NULL pointers */
-    for (ii = 0; ii < LVPSA_NR_MEMORY_REGIONS; ii++)
-    {
-        if (pMemoryTable->Region[ii].Size!=0)
-        {
-            if (pMemoryTable->Region[ii].pBaseAddress==LVM_NULL)
-            {
-                return(LVPSA_ERROR_NULLADDRESS);
-            }
-            pLVPSA_Inst->MemoryTable.Region[ii] = pMemoryTable->Region[ii];
-        }
-    }
+    pLVPSA_Inst->pScratch = pScratch;
 
     /* Initialize module's internal parameters */
     pLVPSA_Inst->bControlPending = LVM_FALSE;
@@ -117,81 +62,132 @@
     pLVPSA_Inst->CurrentParams.Fs = LVM_FS_DUMMY;
     pLVPSA_Inst->CurrentParams.LevelDetectionSpeed = LVPSA_SPEED_DUMMY;
 
-    {   /* for avoiding QAC warnings */
-        LVM_INT32 SDBD=(LVM_INT32)pLVPSA_Inst->SpectralDataBufferDuration;
-        LVM_INT32 IRTI=(LVM_INT32)LVPSA_InternalRefreshTimeInv;
+    { /* for avoiding QAC warnings */
+        LVM_INT32 SDBD = (LVM_INT32)pLVPSA_Inst->SpectralDataBufferDuration;
+        LVM_INT32 IRTI = (LVM_INT32)LVPSA_InternalRefreshTimeInv;
         LVM_INT32 BL;
 
-        MUL32x32INTO32(SDBD,IRTI,BL,LVPSA_InternalRefreshTimeShift)
+        MUL32x32INTO32(SDBD, IRTI, BL, LVPSA_InternalRefreshTimeShift)
 
-        BufferLength=(LVM_UINT32)BL;
+                BufferLength = (LVM_UINT32)BL;
     }
 
-    if((BufferLength * LVPSA_InternalRefreshTime) != pLVPSA_Inst->SpectralDataBufferDuration)
-    {
+    if ((BufferLength * LVPSA_InternalRefreshTime) != pLVPSA_Inst->SpectralDataBufferDuration) {
         pLVPSA_Inst->SpectralDataBufferLength = BufferLength + 1;
-    }
-    else
-    {
+    } else {
         pLVPSA_Inst->SpectralDataBufferLength = BufferLength;
     }
 
     /* Assign the pointers */
-    pLVPSA_Inst->pPostGains             =
-        (LVM_FLOAT *)InstAlloc_AddMember(&Instance, pInitParams->nBands * sizeof(LVM_FLOAT));
-    pLVPSA_Inst->pFiltersParams             = (LVPSA_FilterParam_t *)
-        InstAlloc_AddMember(&Instance, pInitParams->nBands * sizeof(LVPSA_FilterParam_t));
-    pLVPSA_Inst->pSpectralDataBufferStart   = (LVM_UINT8 *)
-        InstAlloc_AddMember(&Instance, pInitParams->nBands * \
-                                pLVPSA_Inst->SpectralDataBufferLength * sizeof(LVM_UINT8));
-    pLVPSA_Inst->pPreviousPeaks             = (LVM_UINT8 *)
-                  InstAlloc_AddMember(&Instance, pInitParams->nBands * sizeof(LVM_UINT8));
-    pLVPSA_Inst->pBPFiltersPrecision        = (LVPSA_BPFilterPrecision_en *)
-                  InstAlloc_AddMember(&Instance, pInitParams->nBands * \
-                                                       sizeof(LVPSA_BPFilterPrecision_en));
-    pLVPSA_Inst->pBP_Instances          = (Biquad_FLOAT_Instance_t *)
-                  InstAlloc_AddMember(&Coef, pInitParams->nBands * \
-                                                          sizeof(Biquad_FLOAT_Instance_t));
-    pLVPSA_Inst->pQPD_States            = (QPD_FLOAT_State_t *)
-                  InstAlloc_AddMember(&Coef, pInitParams->nBands * \
-                                                                sizeof(QPD_FLOAT_State_t));
-
-    pLVPSA_Inst->pBP_Taps               = (Biquad_1I_Order2_FLOAT_Taps_t *)
-        InstAlloc_AddMember(&Data, pInitParams->nBands * \
-                                                     sizeof(Biquad_1I_Order2_FLOAT_Taps_t));
-    pLVPSA_Inst->pQPD_Taps              = (QPD_FLOAT_Taps_t *)
-        InstAlloc_AddMember(&Data, pInitParams->nBands * \
-                                                    sizeof(QPD_FLOAT_Taps_t));
+    pLVPSA_Inst->pPostGains =
+            (LVM_FLOAT*)calloc(pInitParams->nBands, sizeof(*(pLVPSA_Inst->pPostGains)));
+    if (pLVPSA_Inst->pPostGains == LVM_NULL) {
+        return LVPSA_ERROR_NULLADDRESS;
+    }
+    pLVPSA_Inst->pFiltersParams = (LVPSA_FilterParam_t*)calloc(
+            pInitParams->nBands, sizeof(*(pLVPSA_Inst->pFiltersParams)));
+    if (pLVPSA_Inst->pFiltersParams == LVM_NULL) {
+        return LVPSA_ERROR_NULLADDRESS;
+    }
+    pLVPSA_Inst->pSpectralDataBufferStart = (LVM_UINT8*)calloc(
+            pInitParams->nBands, pLVPSA_Inst->SpectralDataBufferLength *
+                                         sizeof(*(pLVPSA_Inst->pSpectralDataBufferStart)));
+    if (pLVPSA_Inst->pSpectralDataBufferStart == LVM_NULL) {
+        return LVPSA_ERROR_NULLADDRESS;
+    }
+    pLVPSA_Inst->pPreviousPeaks =
+            (LVM_UINT8*)calloc(pInitParams->nBands, sizeof(*(pLVPSA_Inst->pPreviousPeaks)));
+    if (pLVPSA_Inst->pPreviousPeaks == LVM_NULL) {
+        return LVPSA_ERROR_NULLADDRESS;
+    }
+    pLVPSA_Inst->pBPFiltersPrecision = (LVPSA_BPFilterPrecision_en*)calloc(
+            pInitParams->nBands, sizeof(*(pLVPSA_Inst->pBPFiltersPrecision)));
+    if (pLVPSA_Inst->pBPFiltersPrecision == LVM_NULL) {
+        return LVPSA_ERROR_NULLADDRESS;
+    }
+    pLVPSA_Inst->pQPD_States =
+            (QPD_FLOAT_State_t*)calloc(pInitParams->nBands, sizeof(*(pLVPSA_Inst->pQPD_States)));
+    if (pLVPSA_Inst->pQPD_States == LVM_NULL) {
+        return LVPSA_ERROR_NULLADDRESS;
+    }
+    pLVPSA_Inst->pQPD_Taps =
+            (QPD_FLOAT_Taps_t*)calloc(pInitParams->nBands, sizeof(*(pLVPSA_Inst->pQPD_Taps)));
+    if (pLVPSA_Inst->pQPD_Taps == LVM_NULL) {
+        return LVPSA_ERROR_NULLADDRESS;
+    }
 
     /* Copy filters parameters in the private instance */
-    for(ii = 0; ii < pLVPSA_Inst->nBands; ii++)
-    {
+    for (ii = 0; ii < pLVPSA_Inst->nBands; ii++) {
         pLVPSA_Inst->pFiltersParams[ii] = pInitParams->pFiltersParams[ii];
     }
 
     /* Set Post filters gains*/
-    for(ii = 0; ii < pLVPSA_Inst->nBands; ii++)
-    {
-        pLVPSA_Inst->pPostGains[ii] = LVPSA_Float_GainTable[15 + \
-                                                        pInitParams->pFiltersParams[ii].PostGain];
+    for (ii = 0; ii < pLVPSA_Inst->nBands; ii++) {
+        pLVPSA_Inst->pPostGains[ii] =
+                LVPSA_Float_GainTable[15 + pInitParams->pFiltersParams[ii].PostGain];
     }
     pLVPSA_Inst->pSpectralDataBufferWritePointer = pLVPSA_Inst->pSpectralDataBufferStart;
 
     /* Initialize control dependant internal parameters */
-    errorCode = LVPSA_Control (*phInstance, pControlParams);
+    errorCode = LVPSA_Control(*phInstance, pControlParams);
 
-    if(errorCode!=0)
-    {
+    if (errorCode != 0) {
         return errorCode;
     }
 
-    errorCode = LVPSA_ApplyNewSettings (pLVPSA_Inst);
+    errorCode = LVPSA_ApplyNewSettings(pLVPSA_Inst);
 
-    if(errorCode!=0)
-    {
+    if (errorCode != 0) {
         return errorCode;
     }
 
-    return(errorCode);
+    return (errorCode);
 }
 
+/************************************************************************************/
+/*                                                                                  */
+/* FUNCTION:            LVPSA_DeInit                                                */
+/*                                                                                  */
+/* DESCRIPTION:                                                                     */
+/*    Free the memories created in LVPSA_Init call including instance handle        */
+/*                                                                                  */
+/* PARAMETERS:                                                                      */
+/*  phInstance          Pointer to the instance handle                              */
+/*                                                                                  */
+/************************************************************************************/
+void LVPSA_DeInit(pLVPSA_Handle_t* phInstance) {
+    LVPSA_InstancePr_t* pLVPSA_Inst = (LVPSA_InstancePr_t*)*phInstance;
+    if (pLVPSA_Inst == LVM_NULL) {
+        return;
+    }
+    if (pLVPSA_Inst->pPostGains != LVM_NULL) {
+        free(pLVPSA_Inst->pPostGains);
+        pLVPSA_Inst->pPostGains = LVM_NULL;
+    }
+    if (pLVPSA_Inst->pFiltersParams != LVM_NULL) {
+        free(pLVPSA_Inst->pFiltersParams);
+        pLVPSA_Inst->pFiltersParams = LVM_NULL;
+    }
+    if (pLVPSA_Inst->pSpectralDataBufferStart != LVM_NULL) {
+        free(pLVPSA_Inst->pSpectralDataBufferStart);
+        pLVPSA_Inst->pSpectralDataBufferStart = LVM_NULL;
+    }
+    if (pLVPSA_Inst->pPreviousPeaks != LVM_NULL) {
+        free(pLVPSA_Inst->pPreviousPeaks);
+        pLVPSA_Inst->pPreviousPeaks = LVM_NULL;
+    }
+    if (pLVPSA_Inst->pBPFiltersPrecision != LVM_NULL) {
+        free(pLVPSA_Inst->pBPFiltersPrecision);
+        pLVPSA_Inst->pBPFiltersPrecision = LVM_NULL;
+    }
+    if (pLVPSA_Inst->pQPD_States != LVM_NULL) {
+        free(pLVPSA_Inst->pQPD_States);
+        pLVPSA_Inst->pQPD_States = LVM_NULL;
+    }
+    if (pLVPSA_Inst->pQPD_Taps != LVM_NULL) {
+        free(pLVPSA_Inst->pQPD_Taps);
+        pLVPSA_Inst->pQPD_Taps = LVM_NULL;
+    }
+    delete pLVPSA_Inst;
+    *phInstance = LVM_NULL;
+}
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Memory.cpp b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Memory.cpp
deleted file mode 100644
index eafcbe6..0000000
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Memory.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2004-2010 NXP Software
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include    "LVPSA.h"
-#include    "LVPSA_Private.h"
-#include    "InstAlloc.h"
-
-/****************************************************************************************/
-/*                                                                                      */
-/* FUNCTION:                LVEQNB_Memory                                               */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*  This function is used for memory allocation and free. It can be called in           */
-/*  two ways:                                                                           */
-/*                                                                                      */
-/*      hInstance = NULL         Returns the memory requirements                        */
-/*      hInstance = Instance handle     Returns the memory requirements and             */
-/*                                      allocated base addresses for the instance       */
-/*                                                                                      */
-/*  When this function is called for memory allocation (hInstance=NULL) the memory      */
-/*  base address pointers are NULL on return.                                           */
-/*                                                                                      */
-/*  When the function is called for free (hInstance = Instance Handle) the memory       */
-/*  table returns the allocated memory and base addresses used during initialisation.   */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance               Instance Handle                                             */
-/*  pMemoryTable            Pointer to an empty memory definition table                 */
-/*  InitParams              Pointer to the instance init parameters                     */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVPSA_OK            Succeeds                                                        */
-/*  otherwise           Error due to bad parameters                                     */
-/*                                                                                      */
-/****************************************************************************************/
-LVPSA_RETURN LVPSA_Memory            ( pLVPSA_Handle_t             hInstance,
-                                       LVPSA_MemTab_t             *pMemoryTable,
-                                       LVPSA_InitParams_t         *pInitParams    )
-{
-    LVM_UINT32          ii;
-    LVM_UINT32          BufferLength;
-    INST_ALLOC          Instance;
-    INST_ALLOC          Scratch;
-    INST_ALLOC          Data;
-    INST_ALLOC          Coef;
-    LVPSA_InstancePr_t *pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
-
-    InstAlloc_Init( &Instance   , LVM_NULL);
-    InstAlloc_Init( &Scratch    , LVM_NULL);
-    InstAlloc_Init( &Data       , LVM_NULL);
-    InstAlloc_Init( &Coef       , LVM_NULL);
-
-    if((pMemoryTable == LVM_NULL) || (pInitParams == LVM_NULL))
-    {
-        return(LVPSA_ERROR_NULLADDRESS);
-    }
-
-    /*
-     * Fill in the memory table
-     */
-    if (hInstance == LVM_NULL)
-    {
-
-        /* Check init parameter */
-        if( (pInitParams->SpectralDataBufferDuration > LVPSA_MAXBUFFERDURATION)   ||
-            (pInitParams->SpectralDataBufferDuration == 0)                        ||
-            (pInitParams->MaxInputBlockSize > LVPSA_MAXINPUTBLOCKSIZE)      ||
-            (pInitParams->MaxInputBlockSize == 0)                           ||
-            (pInitParams->nBands < LVPSA_NBANDSMIN)                         ||
-            (pInitParams->nBands > LVPSA_NBANDSMAX)                         ||
-            (pInitParams->pFiltersParams == 0))
-        {
-            return(LVPSA_ERROR_INVALIDPARAM);
-        }
-        for(ii = 0; ii < pInitParams->nBands; ii++)
-        {
-            if((pInitParams->pFiltersParams[ii].CenterFrequency > LVPSA_MAXCENTERFREQ) ||
-               (pInitParams->pFiltersParams[ii].PostGain        > LVPSA_MAXPOSTGAIN)   ||
-               (pInitParams->pFiltersParams[ii].PostGain        < LVPSA_MINPOSTGAIN)   ||
-               (pInitParams->pFiltersParams[ii].QFactor < LVPSA_MINQFACTOR)            ||
-               (pInitParams->pFiltersParams[ii].QFactor > LVPSA_MAXQFACTOR))
-               {
-                    return(LVPSA_ERROR_INVALIDPARAM);
-               }
-        }
-
-        /*
-         * Instance memory
-         */
-
-        InstAlloc_AddMember( &Instance, sizeof(LVPSA_InstancePr_t) );
-        InstAlloc_AddMember( &Instance, pInitParams->nBands * sizeof(LVM_FLOAT) );
-        InstAlloc_AddMember( &Instance, pInitParams->nBands * sizeof(LVPSA_FilterParam_t) );
-
-        {
-            /* for avoiding QAC warnings as MUL32x32INTO32 works on LVM_INT32 only*/
-            LVM_INT32 SDBD=(LVM_INT32)pInitParams->SpectralDataBufferDuration;
-            LVM_INT32 IRTI=(LVM_INT32)LVPSA_InternalRefreshTimeInv;
-            LVM_INT32 BL;
-
-            MUL32x32INTO32(SDBD,IRTI,BL,LVPSA_InternalRefreshTimeShift)
-            BufferLength=(LVM_UINT32)BL;
-        }
-
-        if((BufferLength * LVPSA_InternalRefreshTime) != pInitParams->SpectralDataBufferDuration)
-        {
-            BufferLength++;
-        }
-        InstAlloc_AddMember( &Instance, pInitParams->nBands * BufferLength * sizeof(LVM_UINT8) );
-        InstAlloc_AddMember( &Instance, pInitParams->nBands * sizeof(LVM_UINT8) );
-        InstAlloc_AddMember( &Instance, pInitParams->nBands * sizeof(LVPSA_BPFilterPrecision_en) );
-        pMemoryTable->Region[LVPSA_MEMREGION_INSTANCE].Size         = InstAlloc_GetTotal(&Instance);
-        pMemoryTable->Region[LVPSA_MEMREGION_INSTANCE].Type         = LVPSA_PERSISTENT;
-        pMemoryTable->Region[LVPSA_MEMREGION_INSTANCE].pBaseAddress = LVM_NULL;
-
-        /*
-         * Scratch memory
-         */
-        InstAlloc_AddMember( &Scratch, 2 * pInitParams->MaxInputBlockSize * sizeof(LVM_FLOAT) );
-        pMemoryTable->Region[LVPSA_MEMREGION_SCRATCH].Size         = InstAlloc_GetTotal(&Scratch);
-        pMemoryTable->Region[LVPSA_MEMREGION_SCRATCH].Type         = LVPSA_SCRATCH;
-        pMemoryTable->Region[LVPSA_MEMREGION_SCRATCH].pBaseAddress = LVM_NULL;
-
-        /*
-         * Persistent coefficients memory
-         */
-        InstAlloc_AddMember( &Coef, pInitParams->nBands * sizeof(Biquad_FLOAT_Instance_t) );
-        InstAlloc_AddMember( &Coef, pInitParams->nBands * sizeof(QPD_FLOAT_State_t) );
-        pMemoryTable->Region[LVPSA_MEMREGION_PERSISTENT_COEF].Size         = InstAlloc_GetTotal(&Coef);
-        pMemoryTable->Region[LVPSA_MEMREGION_PERSISTENT_COEF].Type         = LVPSA_PERSISTENT_COEF;
-        pMemoryTable->Region[LVPSA_MEMREGION_PERSISTENT_COEF].pBaseAddress = LVM_NULL;
-
-        /*
-         * Persistent data memory
-         */
-        InstAlloc_AddMember( &Data, pInitParams->nBands * sizeof(Biquad_1I_Order2_FLOAT_Taps_t) );
-        InstAlloc_AddMember( &Data, pInitParams->nBands * sizeof(QPD_FLOAT_Taps_t) );
-        pMemoryTable->Region[LVPSA_MEMREGION_PERSISTENT_DATA].Size         = InstAlloc_GetTotal(&Data);
-        pMemoryTable->Region[LVPSA_MEMREGION_PERSISTENT_DATA].Type         = LVPSA_PERSISTENT_DATA;
-        pMemoryTable->Region[LVPSA_MEMREGION_PERSISTENT_DATA].pBaseAddress = LVM_NULL;
-
-    }
-    else
-    {
-        /* Read back memory allocation table */
-        *pMemoryTable = pLVPSA_Inst->MemoryTable;
-    }
-
-    return(LVPSA_OK);
-}
-
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Private.h b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Private.h
index 61987b5..605a22e 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Private.h
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Private.h
@@ -18,6 +18,7 @@
 #ifndef _LVPSA_PRIVATE_H_
 #define _LVPSA_PRIVATE_H_
 
+#include <audio_utils/BiquadFilter.h>
 #include "LVPSA.h"
 #include "BIQUAD.h"
 #include "LVPSA_QPD.h"
@@ -27,95 +28,99 @@
    CONSTANT DEFINITIONS
 ***********************************************************************************/
 
-/* Memory */
-#define LVPSA_INSTANCE_ALIGN             4      /* 32-bit alignment for structures                                  */
-#define LVPSA_SCRATCH_ALIGN              4      /* 32-bit alignment for long data                                   */
-#define LVPSA_COEF_ALIGN                 4      /* 32-bit alignment for long words                                  */
-#define LVPSA_DATA_ALIGN                 4      /* 32-bit alignment for long data                                   */
+#define LVPSA_NR_SUPPORTED_RATE 13 /* From 8000Hz to 192000Hz*/
+#define LVPSA_NR_SUPPORTED_SPEED \
+    3 /* LOW, MEDIUM, HIGH                                                */
 
-#define LVPSA_MEMREGION_INSTANCE         0      /* Offset to instance memory region in memory table                 */
-#define LVPSA_MEMREGION_PERSISTENT_COEF  1      /* Offset to persistent coefficients  memory region in memory table */
-#define LVPSA_MEMREGION_PERSISTENT_DATA  2      /* Offset to persistent taps  memory region in memory table         */
-#define LVPSA_MEMREGION_SCRATCH          3      /* Offset to scratch  memory region in memory table                 */
-#define LVPSA_NR_SUPPORTED_RATE          13      /* From 8000Hz to 192000Hz*/
-#define LVPSA_NR_SUPPORTED_SPEED         3      /* LOW, MEDIUM, HIGH                                                */
+#define LVPSA_MAXBUFFERDURATION \
+    4000 /* Maximum length in ms of the levels buffer                        */
+#define LVPSA_MAXINPUTBLOCKSIZE \
+    5000                   /* Maximum length in mono samples of the block to process           */
+#define LVPSA_NBANDSMIN 1  /* Minimum number of frequency band                                 */
+#define LVPSA_NBANDSMAX 30 /* Maximum number of frequency band                                 */
+#define LVPSA_MAXCENTERFREQ \
+    20000 /* Maximum possible center frequency                                */
+#define LVPSA_MINPOSTGAIN \
+    (-15)                     /* Minimum possible post gain                                       */
+#define LVPSA_MAXPOSTGAIN 15  /* Maximum possible post gain  */
+#define LVPSA_MINQFACTOR 25   /* Minimum possible Q factor                                        */
+#define LVPSA_MAXQFACTOR 1200 /* Maximum possible Q factor */
 
-#define LVPSA_MAXBUFFERDURATION          4000   /* Maximum length in ms of the levels buffer                        */
-#define LVPSA_MAXINPUTBLOCKSIZE          5000   /* Maximum length in mono samples of the block to process           */
-#define LVPSA_NBANDSMIN                  1      /* Minimum number of frequency band                                 */
-#define LVPSA_NBANDSMAX                  30     /* Maximum number of frequency band                                 */
-#define LVPSA_MAXCENTERFREQ              20000  /* Maximum possible center frequency                                */
-#define LVPSA_MINPOSTGAIN              (-15)    /* Minimum possible post gain                                       */
-#define LVPSA_MAXPOSTGAIN                15     /* Maximum possible post gain                                       */
-#define LVPSA_MINQFACTOR                 25     /* Minimum possible Q factor                                        */
-#define LVPSA_MAXQFACTOR                 1200   /* Maximum possible Q factor                                        */
+#define LVPSA_MAXLEVELDECAYFACTOR \
+    0x4111 /* Decay factor for the maximum values calculation                  */
+#define LVPSA_MAXLEVELDECAYSHIFT \
+    14 /* Decay shift for the maximum values calculation                   */
 
-#define LVPSA_MAXLEVELDECAYFACTOR        0x4111 /* Decay factor for the maximum values calculation                  */
-#define LVPSA_MAXLEVELDECAYSHIFT         14     /* Decay shift for the maximum values calculation                   */
+#define LVPSA_MAXUNSIGNEDCHAR 0xFF
 
-#define LVPSA_MAXUNSIGNEDCHAR            0xFF
-
-#define LVPSA_FsInvertShift              31
-#define LVPSA_GAINSHIFT                  11
-#define LVPSA_FREQSHIFT                  25
+#define LVPSA_FsInvertShift 31
+#define LVPSA_GAINSHIFT 11
+#define LVPSA_FREQSHIFT 25
 
 /**********************************************************************************
    TYPES DEFINITIONS
 ***********************************************************************************/
 
-#define LVPSA_InternalRefreshTime       0x0014    /* 20 ms (50Hz) in Q16.0      */
-#define LVPSA_InternalRefreshTimeInv    0x0666    /* 1/20ms left shifted by 15  */
-#define LVPSA_InternalRefreshTimeShift  15
+#define LVPSA_InternalRefreshTime 0x0014    /* 20 ms (50Hz) in Q16.0      */
+#define LVPSA_InternalRefreshTimeInv 0x0666 /* 1/20ms left shifted by 15  */
+#define LVPSA_InternalRefreshTimeShift 15
 
 /* Precision of the filter */
-typedef enum
-{
-    LVPSA_SimplePrecisionFilter,    /* Simple precision */
-    LVPSA_DoublePrecisionFilter     /* Double precision */
+typedef enum {
+    LVPSA_SimplePrecisionFilter, /* Simple precision */
+    LVPSA_DoublePrecisionFilter  /* Double precision */
 } LVPSA_BPFilterPrecision_en;
 
-typedef struct
-{
-    LVM_CHAR                    bControlPending;                    /* Flag incating a change of the control parameters                                             */
-    LVM_UINT16                  nBands;                             /* Number of bands of the spectrum analyzer                                                     */
-    LVM_UINT16                  MaxInputBlockSize;                  /* Maximum input data buffer size                                                               */
+typedef struct {
+    LVM_CHAR bControlPending;     /* Flag incating a change of the control parameters     */
+    LVM_UINT16 nBands;            /* Number of bands of the spectrum analyzer            */
+    LVM_UINT16 MaxInputBlockSize; /* Maximum input data buffer size */
 
-    LVPSA_ControlParams_t       CurrentParams;                      /* Current control parameters of the module                                                     */
-    LVPSA_ControlParams_t       NewParams;                          /* New control parameters given by the user                                                     */
-    LVPSA_MemTab_t              MemoryTable;
+    LVPSA_ControlParams_t CurrentParams; /* Current control parameters of the module */
+    LVPSA_ControlParams_t NewParams;     /* New control parameters given by the user     */
+    void* pScratch;
+    /* Pointer to bundle scratch buffer */
 
-    LVPSA_BPFilterPrecision_en *pBPFiltersPrecision;                /* Points a nBands elements array that contains the filter precision for each band              */
-    Biquad_FLOAT_Instance_t          *pBP_Instances;
-    /* Points a nBands elements array that contains the band pass filter taps for each band */
-    Biquad_1I_Order2_FLOAT_Taps_t    *pBP_Taps;
+    LVPSA_BPFilterPrecision_en* pBPFiltersPrecision; /* Points a nBands elements array that contains
+                                                        the filter precision for each band */
+    std::vector<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            specBiquad; /* Biquad filter instances */
     /* Points a nBands elements array that contains the QPD filter instance for each band */
-    QPD_FLOAT_State_t                *pQPD_States;
+    QPD_FLOAT_State_t* pQPD_States;
     /* Points a nBands elements array that contains the QPD filter taps for each band */
-    QPD_FLOAT_Taps_t                 *pQPD_Taps;
+    QPD_FLOAT_Taps_t* pQPD_Taps;
 
     /* Points a nBands elements array that contains the post-filter gains for each band */
-    LVM_FLOAT                  *pPostGains;
-    LVPSA_FilterParam_t        *pFiltersParams;                     /* Copy of the filters parameters from the input parameters                                     */
+    LVM_FLOAT* pPostGains;
+    LVPSA_FilterParam_t*
+            pFiltersParams; /* Copy of the filters parameters from the input parameters */
 
-    LVM_UINT16                  nSamplesBufferUpdate;               /* Number of samples to make 20ms                                                               */
-    LVM_INT32                   BufferUpdateSamplesCount;           /* Counter used to know when to put a new value in the buffer                                   */
-    LVM_UINT16                  nRelevantFilters;                   /* Number of relevent filters depending on sampling frequency and bands center frequency        */
-    LVM_UINT16                  LocalSamplesCount;                  /* Counter used to update the SpectralDataBufferAudioTime                                       */
+    LVM_UINT16 nSamplesBufferUpdate;    /* Number of samples to make 20ms    */
+    LVM_INT32 BufferUpdateSamplesCount; /* Counter used to know when to put a new value in the
+                                           buffer                                   */
+    LVM_UINT16 nRelevantFilters;  /* Number of relevant filters depending on sampling frequency and
+                                     bands center frequency        */
+    LVM_UINT16 LocalSamplesCount; /* Counter used to update the SpectralDataBufferAudioTime */
 
-    LVM_UINT16                  DownSamplingFactor;                 /* Down sampling factor depending on the sampling frequency                                     */
-    LVM_UINT16                  DownSamplingCount;                  /* Counter used for the downsampling handling                                                   */
+    LVM_UINT16 DownSamplingFactor; /* Down sampling factor depending on the sampling frequency */
+    LVM_UINT16 DownSamplingCount;  /* Counter used for the downsampling handling  */
 
-    LVM_UINT16                  SpectralDataBufferDuration;         /* Length of the buffer in time (ms) defined by the application                                 */
-    LVM_UINT8                  *pSpectralDataBufferStart;           /* Starting address of the buffer                                                               */
-    LVM_UINT8                  *pSpectralDataBufferWritePointer;    /* Current position of the writting pointer of the buffer                                       */
-    LVPSA_Time                  SpectralDataBufferAudioTime;        /* AudioTime at which the last value save occured in the buffer                                 */
-    LVM_UINT32                  SpectralDataBufferLength;           /* Number of spectrum data value that the buffer can contain (per band)
-                                                                       = SpectralDataBufferDuration/20ms                                                            */
+    LVM_UINT16 SpectralDataBufferDuration;      /* Length of the buffer in time (ms) defined by the
+                                                   application                                 */
+    LVM_UINT8* pSpectralDataBufferStart;        /* Starting address of the buffer        */
+    LVM_UINT8* pSpectralDataBufferWritePointer; /* Current position of the writing pointer of the
+                                                   buffer                                       */
+    LVPSA_Time SpectralDataBufferAudioTime; /* AudioTime at which the last value save occurred in
+                                               the buffer                                 */
+    LVM_UINT32
+            SpectralDataBufferLength; /* Number of spectrum data value that the buffer can contain
+                                         (per band) = SpectralDataBufferDuration/20ms */
 
-    LVM_UINT8                  *pPreviousPeaks;                     /* Points to a nBands elements array that contains the previous peak value of the level
-                                                                     detection. Those values are decremented after each call to the GetSpectrum function          */
+    LVM_UINT8* pPreviousPeaks; /* Points to a nBands elements array that contains the previous peak
+                                value of the level detection. Those values are decremented after
+                                each call to the GetSpectrum function          */
 
-}LVPSA_InstancePr_t, *pLVPSA_InstancePr_t;
+} LVPSA_InstancePr_t, *pLVPSA_InstancePr_t;
 
 /**********************************************************************************
    FUNCTIONS PROTOTYPE
@@ -135,6 +140,6 @@
 /*  LVPSA_OK            Always succeeds                                             */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_ApplyNewSettings (LVPSA_InstancePr_t     *pInst);
+LVPSA_RETURN LVPSA_ApplyNewSettings(LVPSA_InstancePr_t* pInst);
 
 #endif /* _LVPSA_PRIVATE_H */
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Process.cpp b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Process.cpp
index 81a88c5..c89c4f6 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Process.cpp
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Process.cpp
@@ -15,23 +15,23 @@
  * limitations under the License.
  */
 
-#include    "LVPSA.h"
-#include    "LVPSA_Private.h"
-#include    "LVM_Macros.h"
-#include    "VectorArithmetic.h"
+#include "LVPSA.h"
+#include "LVPSA_Private.h"
+#include "LVM_Macros.h"
+#include "VectorArithmetic.h"
 
-#define LVM_MININT_32   0x80000000
+#define LVM_MININT_32 0x80000000
 
 static LVM_INT32 mult32x32in32_shiftr(LVM_INT32 a, LVM_INT32 b, LVM_INT32 c) {
-  LVM_INT64 result = ((LVM_INT64)a * b) >> c;
+    LVM_INT64 result = ((LVM_INT64)a * b) >> c;
 
-  if (result >= INT32_MAX) {
-    return INT32_MAX;
-  } else if (result <= INT32_MIN) {
-    return INT32_MIN;
-  } else {
-    return (LVM_INT32)result;
-  }
+    if (result >= INT32_MAX) {
+        return INT32_MAX;
+    } else if (result <= INT32_MIN) {
+        return INT32_MIN;
+    } else {
+        return (LVM_INT32)result;
+    }
 }
 
 /************************************************************************************/
@@ -54,42 +54,36 @@
 /*  otherwise           Error due to bad parameters                                 */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_Process           ( pLVPSA_Handle_t      hInstance,
-                                       LVM_FLOAT           *pLVPSA_InputSamples,
-                                       LVM_UINT16           InputBlockSize,
-                                       LVPSA_Time           AudioTime            )
+LVPSA_RETURN LVPSA_Process(pLVPSA_Handle_t hInstance, LVM_FLOAT* pLVPSA_InputSamples,
+                           LVM_UINT16 InputBlockSize, LVPSA_Time AudioTime)
 
 {
-    LVPSA_InstancePr_t     *pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
-    LVM_FLOAT               *pScratch;
-    LVM_INT16               ii;
-    LVM_INT32               AudioTimeInc;
-    extern LVM_UINT32       LVPSA_SampleRateInvTab[];
-    LVM_UINT8               *pWrite_Save;         /* Position of the write pointer
-                                                     at the beginning of the process  */
+    LVPSA_InstancePr_t* pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
+    LVM_FLOAT* pScratch;
+    LVM_INT16 ii;
+    LVM_INT32 AudioTimeInc;
+    extern LVM_UINT32 LVPSA_SampleRateInvTab[];
+    LVM_UINT8* pWrite_Save; /* Position of the write pointer
+                               at the beginning of the process  */
 
     /******************************************************************************
        CHECK PARAMETERS
     *******************************************************************************/
-    if(hInstance == LVM_NULL || pLVPSA_InputSamples == LVM_NULL)
-    {
-        return(LVPSA_ERROR_NULLADDRESS);
+    if (hInstance == LVM_NULL || pLVPSA_InputSamples == LVM_NULL) {
+        return (LVPSA_ERROR_NULLADDRESS);
     }
-    if(InputBlockSize == 0 || InputBlockSize > pLVPSA_Inst->MaxInputBlockSize)
-    {
-        return(LVPSA_ERROR_INVALIDPARAM);
+    if (InputBlockSize == 0 || InputBlockSize > pLVPSA_Inst->MaxInputBlockSize) {
+        return (LVPSA_ERROR_INVALIDPARAM);
     }
-
-    pScratch = (LVM_FLOAT*)pLVPSA_Inst->MemoryTable.Region[LVPSA_MEMREGION_SCRATCH].pBaseAddress;
+    pScratch = (LVM_FLOAT*)pLVPSA_Inst->pScratch;
     pWrite_Save = pLVPSA_Inst->pSpectralDataBufferWritePointer;
 
     /******************************************************************************
        APPLY NEW SETTINGS IF NEEDED
     *******************************************************************************/
-    if (pLVPSA_Inst->bControlPending == LVM_TRUE)
-    {
+    if (pLVPSA_Inst->bControlPending == LVM_TRUE) {
         pLVPSA_Inst->bControlPending = 0;
-        LVPSA_ApplyNewSettings( pLVPSA_Inst);
+        LVPSA_ApplyNewSettings(pLVPSA_Inst);
     }
 
     /******************************************************************************
@@ -99,39 +93,30 @@
     Copy_Float(pLVPSA_InputSamples, pScratch, (LVM_INT16)InputBlockSize);
     Shift_Sat_Float(-1, pScratch, pScratch, (LVM_INT16)InputBlockSize);
 
-    for (ii = 0; ii < pLVPSA_Inst->nRelevantFilters; ii++)
-    {
-        switch(pLVPSA_Inst->pBPFiltersPrecision[ii])
-        {
+    for (ii = 0; ii < pLVPSA_Inst->nRelevantFilters; ii++) {
+        switch (pLVPSA_Inst->pBPFiltersPrecision[ii]) {
             case LVPSA_SimplePrecisionFilter:
-                BP_1I_D16F16C14_TRC_WRA_01  ( &pLVPSA_Inst->pBP_Instances[ii],
-                                              pScratch,
-                                              pScratch + InputBlockSize,
-                                              (LVM_INT16)InputBlockSize);
+                pLVPSA_Inst->specBiquad[ii].process(pScratch + InputBlockSize, pScratch,
+                                                    (LVM_INT16)InputBlockSize);
                 break;
 
             case LVPSA_DoublePrecisionFilter:
-                BP_1I_D16F32C30_TRC_WRA_01  ( &pLVPSA_Inst->pBP_Instances[ii],
-                                              pScratch,
-                                              pScratch + InputBlockSize,
-                                              (LVM_INT16)InputBlockSize);
+                pLVPSA_Inst->specBiquad[ii].process(pScratch + InputBlockSize, pScratch,
+                                                    (LVM_INT16)InputBlockSize);
                 break;
             default:
                 break;
         }
 
-        LVPSA_QPD_Process_Float   ( pLVPSA_Inst,
-                                    pScratch + InputBlockSize,
-                                    (LVM_INT16)InputBlockSize,
-                                    ii);
+        LVPSA_QPD_Process_Float(pLVPSA_Inst, pScratch + InputBlockSize, (LVM_INT16)InputBlockSize,
+                                ii);
     }
 
     /******************************************************************************
        UPDATE SpectralDataBufferAudioTime
     *******************************************************************************/
 
-    if(pLVPSA_Inst->pSpectralDataBufferWritePointer != pWrite_Save)
-    {
+    if (pLVPSA_Inst->pSpectralDataBufferWritePointer != pWrite_Save) {
         AudioTimeInc = mult32x32in32_shiftr(
                 (AudioTime + ((LVM_INT32)pLVPSA_Inst->LocalSamplesCount * 1000)),
                 (LVM_INT32)LVPSA_SampleRateInvTab[pLVPSA_Inst->CurrentParams.Fs],
@@ -139,7 +124,7 @@
         pLVPSA_Inst->SpectralDataBufferAudioTime = AudioTime + AudioTimeInc;
     }
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
 
 /************************************************************************************/
@@ -162,99 +147,95 @@
 /*  otherwise           Error due to bad parameters                                 */
 /*                                                                                  */
 /************************************************************************************/
-LVPSA_RETURN LVPSA_GetSpectrum       ( pLVPSA_Handle_t      hInstance,
-                                       LVPSA_Time           GetSpectrumAudioTime,
-                                       LVM_UINT8           *pCurrentValues,
-                                       LVM_UINT8           *pPeakValues           )
+LVPSA_RETURN LVPSA_GetSpectrum(pLVPSA_Handle_t hInstance, LVPSA_Time GetSpectrumAudioTime,
+                               LVM_UINT8* pCurrentValues, LVM_UINT8* pPeakValues)
 
 {
+    LVPSA_InstancePr_t* pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
+    LVM_INT32 StatusDelta, ii;
+    LVM_UINT8* pRead;
 
-    LVPSA_InstancePr_t      *pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
-    LVM_INT32               StatusDelta, ii;
-    LVM_UINT8               *pRead;
-
-    if(hInstance == LVM_NULL || pCurrentValues == LVM_NULL || pPeakValues == LVM_NULL)
-    {
-        return(LVPSA_ERROR_NULLADDRESS);
+    if (hInstance == LVM_NULL || pCurrentValues == LVM_NULL || pPeakValues == LVM_NULL) {
+        return (LVPSA_ERROR_NULLADDRESS);
     }
 
     /* First find the place where to look in the status buffer */
-    if(GetSpectrumAudioTime <= pLVPSA_Inst->SpectralDataBufferAudioTime)
-    {
-        MUL32x32INTO32((pLVPSA_Inst->SpectralDataBufferAudioTime - GetSpectrumAudioTime),LVPSA_InternalRefreshTimeInv,StatusDelta,LVPSA_InternalRefreshTimeShift);
-        if((StatusDelta * LVPSA_InternalRefreshTime) != (pLVPSA_Inst->SpectralDataBufferAudioTime - GetSpectrumAudioTime))
-        {
+    if (GetSpectrumAudioTime <= pLVPSA_Inst->SpectralDataBufferAudioTime) {
+        MUL32x32INTO32((pLVPSA_Inst->SpectralDataBufferAudioTime - GetSpectrumAudioTime),
+                       LVPSA_InternalRefreshTimeInv, StatusDelta, LVPSA_InternalRefreshTimeShift);
+        if ((StatusDelta * LVPSA_InternalRefreshTime) !=
+            (pLVPSA_Inst->SpectralDataBufferAudioTime - GetSpectrumAudioTime)) {
             StatusDelta += 1;
         }
-    }
-    else
-    {
+    } else {
         /* This part handles the wrap around */
-        MUL32x32INTO32(((pLVPSA_Inst->SpectralDataBufferAudioTime - (LVM_INT32)LVM_MININT_32) + ((LVM_INT32)LVM_MAXINT_32 - GetSpectrumAudioTime)),LVPSA_InternalRefreshTimeInv,StatusDelta,LVPSA_InternalRefreshTimeShift)
-        if(((LVM_INT32)(StatusDelta * LVPSA_InternalRefreshTime)) != ((LVM_INT32)((pLVPSA_Inst->SpectralDataBufferAudioTime - (LVM_INT32)LVM_MININT_32) + ((LVM_INT32)LVM_MAXINT_32 - GetSpectrumAudioTime))))
-        {
+        MUL32x32INTO32(
+                ((pLVPSA_Inst->SpectralDataBufferAudioTime - (LVM_INT32)LVM_MININT_32) +
+                 ((LVM_INT32)LVM_MAXINT_32 - GetSpectrumAudioTime)),
+                LVPSA_InternalRefreshTimeInv, StatusDelta,
+                LVPSA_InternalRefreshTimeShift) if (((LVM_INT32)(StatusDelta *
+                                                                 LVPSA_InternalRefreshTime)) !=
+                                                    ((LVM_INT32)(
+                                                            (pLVPSA_Inst
+                                                                     ->SpectralDataBufferAudioTime -
+                                                             (LVM_INT32)LVM_MININT_32) +
+                                                            ((LVM_INT32)LVM_MAXINT_32 -
+                                                             GetSpectrumAudioTime)))) {
             StatusDelta += 1;
         }
     }
     /* Check whether the desired level is not too "old" (see 2.10 in LVPSA_DesignNotes.doc)*/
-    if(
-        ((GetSpectrumAudioTime < pLVPSA_Inst->SpectralDataBufferAudioTime)&&
-         ((GetSpectrumAudioTime<0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime>0))&&
-         (((LVM_INT32)(-GetSpectrumAudioTime + pLVPSA_Inst->SpectralDataBufferAudioTime))>LVM_MAXINT_32))||
+    if (((GetSpectrumAudioTime < pLVPSA_Inst->SpectralDataBufferAudioTime) &&
+         ((GetSpectrumAudioTime < 0) && (pLVPSA_Inst->SpectralDataBufferAudioTime > 0)) &&
+         (((LVM_INT32)(-GetSpectrumAudioTime + pLVPSA_Inst->SpectralDataBufferAudioTime)) >
+          LVM_MAXINT_32)) ||
 
-         ((GetSpectrumAudioTime > pLVPSA_Inst->SpectralDataBufferAudioTime)&&
-         (((GetSpectrumAudioTime>=0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime>=0))||
-          ((GetSpectrumAudioTime<=0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime<=0))||
-         (((GetSpectrumAudioTime>=0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime<=0))&&
-         (((LVM_INT32)(GetSpectrumAudioTime - pLVPSA_Inst->SpectralDataBufferAudioTime))<LVM_MAXINT_32))))||
+        ((GetSpectrumAudioTime > pLVPSA_Inst->SpectralDataBufferAudioTime) &&
+         (((GetSpectrumAudioTime >= 0) && (pLVPSA_Inst->SpectralDataBufferAudioTime >= 0)) ||
+          ((GetSpectrumAudioTime <= 0) && (pLVPSA_Inst->SpectralDataBufferAudioTime <= 0)) ||
+          (((GetSpectrumAudioTime >= 0) && (pLVPSA_Inst->SpectralDataBufferAudioTime <= 0)) &&
+           (((LVM_INT32)(GetSpectrumAudioTime - pLVPSA_Inst->SpectralDataBufferAudioTime)) <
+            LVM_MAXINT_32)))) ||
 
-        (StatusDelta > (LVM_INT32)pLVPSA_Inst->SpectralDataBufferLength) ||
-        (!StatusDelta))
-    {
-        for(ii = 0; ii < pLVPSA_Inst->nBands; ii++)
-        {
-            pCurrentValues[ii]  = 0;
-            pPeakValues[ii]      = 0;
+        (StatusDelta > (LVM_INT32)pLVPSA_Inst->SpectralDataBufferLength) || (!StatusDelta)) {
+        for (ii = 0; ii < pLVPSA_Inst->nBands; ii++) {
+            pCurrentValues[ii] = 0;
+            pPeakValues[ii] = 0;
         }
-        return(LVPSA_OK);
+        return (LVPSA_OK);
     }
     /* Set the reading pointer */
-    if((LVM_INT32)(StatusDelta * pLVPSA_Inst->nBands) > (pLVPSA_Inst->pSpectralDataBufferWritePointer - pLVPSA_Inst->pSpectralDataBufferStart))
-    {
-        pRead = pLVPSA_Inst->pSpectralDataBufferWritePointer + (pLVPSA_Inst->SpectralDataBufferLength - (LVM_UINT32)StatusDelta) * pLVPSA_Inst->nBands;
-    }
-    else
-    {
-        pRead = pLVPSA_Inst->pSpectralDataBufferWritePointer  - StatusDelta * pLVPSA_Inst->nBands;
+    if ((LVM_INT32)(StatusDelta * pLVPSA_Inst->nBands) >
+        (pLVPSA_Inst->pSpectralDataBufferWritePointer - pLVPSA_Inst->pSpectralDataBufferStart)) {
+        pRead = pLVPSA_Inst->pSpectralDataBufferWritePointer +
+                (pLVPSA_Inst->SpectralDataBufferLength - (LVM_UINT32)StatusDelta) *
+                        pLVPSA_Inst->nBands;
+    } else {
+        pRead = pLVPSA_Inst->pSpectralDataBufferWritePointer - StatusDelta * pLVPSA_Inst->nBands;
     }
 
     /* Read the status buffer and fill the output buffers */
-    for(ii = 0; ii < pLVPSA_Inst->nBands; ii++)
-    {
+    for (ii = 0; ii < pLVPSA_Inst->nBands; ii++) {
         pCurrentValues[ii] = pRead[ii];
-        if(pLVPSA_Inst->pPreviousPeaks[ii] <= pRead[ii])
-        {
+        if (pLVPSA_Inst->pPreviousPeaks[ii] <= pRead[ii]) {
             pLVPSA_Inst->pPreviousPeaks[ii] = pRead[ii];
-        }
-        else if(pLVPSA_Inst->pPreviousPeaks[ii] != 0)
-        {
+        } else if (pLVPSA_Inst->pPreviousPeaks[ii] != 0) {
             LVM_INT32 temp;
             /*Re-compute max values for decay */
             temp = (LVM_INT32)(LVPSA_MAXUNSIGNEDCHAR - pLVPSA_Inst->pPreviousPeaks[ii]);
-            temp = ((temp * LVPSA_MAXLEVELDECAYFACTOR)>>LVPSA_MAXLEVELDECAYSHIFT);
+            temp = ((temp * LVPSA_MAXLEVELDECAYFACTOR) >> LVPSA_MAXLEVELDECAYSHIFT);
             /* If the gain has no effect, "help" the value to increase */
-            if(temp == (LVPSA_MAXUNSIGNEDCHAR - pLVPSA_Inst->pPreviousPeaks[ii]))
-            {
+            if (temp == (LVPSA_MAXUNSIGNEDCHAR - pLVPSA_Inst->pPreviousPeaks[ii])) {
                 temp += 1;
             }
             /* Saturate */
             temp = (temp > LVPSA_MAXUNSIGNEDCHAR) ? LVPSA_MAXUNSIGNEDCHAR : temp;
             /* Store new max level */
-            pLVPSA_Inst->pPreviousPeaks[ii] =  (LVM_UINT8)(LVPSA_MAXUNSIGNEDCHAR - temp);
+            pLVPSA_Inst->pPreviousPeaks[ii] = (LVM_UINT8)(LVPSA_MAXUNSIGNEDCHAR - temp);
         }
 
         pPeakValues[ii] = pLVPSA_Inst->pPreviousPeaks[ii];
     }
 
-    return(LVPSA_OK);
+    return (LVPSA_OK);
 }
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD.h b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD.h
index 609a485..2f752bf 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD.h
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD.h
@@ -20,41 +20,35 @@
 
 #include "LVM_Types.h"
 
-typedef struct
-{
-  LVM_INT32                            *pDelay;        /* pointer to the delayed samples (data of 32 bits)   */
-  LVM_INT32                            Coefs[2];       /* pointer to the filter coefficients */
-}QPD_State_t, *pQPD_State_t;
+typedef struct {
+    LVM_INT32* pDelay;  /* pointer to the delayed samples (data of 32 bits)   */
+    LVM_INT32 Coefs[2]; /* pointer to the filter coefficients */
+} QPD_State_t, *pQPD_State_t;
 
-typedef struct
-{
+typedef struct {
     /* pointer to the delayed samples (data of 32 bits)   */
-    LVM_FLOAT                            *pDelay;
-    LVM_FLOAT                            Coefs[2];       /* pointer to the filter coefficients */
-}QPD_FLOAT_State_t, *pQPD_FLOAT_State_t;
+    LVM_FLOAT* pDelay;
+    LVM_FLOAT Coefs[2]; /* pointer to the filter coefficients */
+} QPD_FLOAT_State_t, *pQPD_FLOAT_State_t;
 
-typedef struct
-{
-    LVM_INT32 KP;    /*should store a0*/
-    LVM_INT32 KM;    /*should store b2*/
+typedef struct {
+    LVM_INT32 KP; /*should store a0*/
+    LVM_INT32 KM; /*should store b2*/
 
 } QPD_C32_Coefs, *PQPD_C32_Coefs;
 
-typedef struct
-{
-    LVM_FLOAT KP;    /*should store a0*/
-    LVM_FLOAT KM;    /*should store b2*/
+typedef struct {
+    LVM_FLOAT KP; /*should store a0*/
+    LVM_FLOAT KM; /*should store b2*/
 
 } QPD_FLOAT_Coefs, *PQPD_FLOAT_Coefs;
 
-typedef struct
-{
+typedef struct {
     LVM_INT32 Storage[1];
 
 } QPD_Taps_t, *pQPD_Taps_t;
 
-typedef struct
-{
+typedef struct {
     LVM_FLOAT Storage[1];
 
 } QPD_FLOAT_Taps_t, *pQPD_FLOAT_Taps_t;
@@ -72,15 +66,11 @@
 /* RETURNS:             void                                                        */
 /*                                                                                  */
 /************************************************************************************/
-void LVPSA_QPD_Process (            void                               *hInstance,
-                                    LVM_INT16                          *pInSamps,
-                                    LVM_INT16                           numSamples,
-                                    LVM_INT16                           BandIndex);
+void LVPSA_QPD_Process(void* hInstance, LVM_INT16* pInSamps, LVM_INT16 numSamples,
+                       LVM_INT16 BandIndex);
 
-void LVPSA_QPD_Process_Float (      void                               *hInstance,
-                                    LVM_FLOAT                          *pInSamps,
-                                    LVM_INT16                           numSamples,
-                                    LVM_INT16                           BandIndex);
+void LVPSA_QPD_Process_Float(void* hInstance, LVM_FLOAT* pInSamps, LVM_INT16 numSamples,
+                             LVM_INT16 BandIndex);
 /************************************************************************************/
 /*                                                                                  */
 /* FUNCTION:            LVPSA_QPD_Init                                              */
@@ -96,13 +86,9 @@
 /* RETURNS:     void                                                                */
 /*                                                                                  */
 /************************************************************************************/
-void LVPSA_QPD_Init (   QPD_State_t       *pInstance,
-                        QPD_Taps_t        *pTaps,
-                        QPD_C32_Coefs     *pCoef     );
+void LVPSA_QPD_Init(QPD_State_t* pInstance, QPD_Taps_t* pTaps, QPD_C32_Coefs* pCoef);
 
-void LVPSA_QPD_Init_Float (   QPD_FLOAT_State_t       *pInstance,
-                              QPD_FLOAT_Taps_t        *pTaps,
-                              QPD_FLOAT_Coefs         *pCoef     );
+void LVPSA_QPD_Init_Float(QPD_FLOAT_State_t* pInstance, QPD_FLOAT_Taps_t* pTaps,
+                          QPD_FLOAT_Coefs* pCoef);
 
 #endif
-
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD_Init.cpp b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD_Init.cpp
index 2dbf694..c5023c3 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD_Init.cpp
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD_Init.cpp
@@ -32,20 +32,15 @@
 /* RETURNS:     void                                                                */
 /*                                                                                  */
 /************************************************************************************/
-void LVPSA_QPD_Init (   pQPD_State_t       pQPD_State,
-                        QPD_Taps_t        *pTaps,
-                        QPD_C32_Coefs     *pCoef     )
-{
-    pQPD_State->pDelay  = pTaps->Storage;
-    pQPD_State->Coefs[0]  = pCoef->KP;
-    pQPD_State->Coefs[1]  = pCoef->KM;
+void LVPSA_QPD_Init(pQPD_State_t pQPD_State, QPD_Taps_t* pTaps, QPD_C32_Coefs* pCoef) {
+    pQPD_State->pDelay = pTaps->Storage;
+    pQPD_State->Coefs[0] = pCoef->KP;
+    pQPD_State->Coefs[1] = pCoef->KM;
 }
 
-void LVPSA_QPD_Init_Float (   pQPD_FLOAT_State_t       pQPD_State,
-                              QPD_FLOAT_Taps_t         *pTaps,
-                              QPD_FLOAT_Coefs          *pCoef     )
-{
-    pQPD_State->pDelay  = pTaps->Storage;
-    pQPD_State->Coefs[0]  = ((LVM_FLOAT)pCoef->KP);
-    pQPD_State->Coefs[1]  = ((LVM_FLOAT)pCoef->KM);
+void LVPSA_QPD_Init_Float(pQPD_FLOAT_State_t pQPD_State, QPD_FLOAT_Taps_t* pTaps,
+                          QPD_FLOAT_Coefs* pCoef) {
+    pQPD_State->pDelay = pTaps->Storage;
+    pQPD_State->Coefs[0] = ((LVM_FLOAT)pCoef->KP);
+    pQPD_State->Coefs[1] = ((LVM_FLOAT)pCoef->KM);
 }
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD_Process.cpp b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD_Process.cpp
index 8805420..e301cf9 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD_Process.cpp
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_QPD_Process.cpp
@@ -34,15 +34,11 @@
 /* RETURNS:             void                                                        */
 /*                                                                                  */
 /************************************************************************************/
-void LVPSA_QPD_WritePeak(   pLVPSA_InstancePr_t       pLVPSA_Inst,
-                            LVM_UINT8                 **ppWrite,
-                            LVM_INT16                 BandIndex,
-                            LVM_INT16                 Value   );
+void LVPSA_QPD_WritePeak(pLVPSA_InstancePr_t pLVPSA_Inst, LVM_UINT8** ppWrite, LVM_INT16 BandIndex,
+                         LVM_INT16 Value);
 
-void LVPSA_QPD_WritePeak_Float(   pLVPSA_InstancePr_t       pLVPSA_Inst,
-                                  LVM_UINT8             **ppWrite,
-                                  LVM_INT16               BandIndex,
-                                  LVM_FLOAT               Value   );
+void LVPSA_QPD_WritePeak_Float(pLVPSA_InstancePr_t pLVPSA_Inst, LVM_UINT8** ppWrite,
+                               LVM_INT16 BandIndex, LVM_FLOAT Value);
 /************************************************************************************/
 /*                                                                                  */
 /* FUNCTION:            LVPSA_QPD_Process                                           */
@@ -56,38 +52,34 @@
 /* RETURNS:             void                                                        */
 /*                                                                                  */
 /************************************************************************************/
-void LVPSA_QPD_Process_Float (      void                               *hInstance,
-                                    LVM_FLOAT                          *pInSamps,
-                                    LVM_INT16                           numSamples,
-                                    LVM_INT16                           BandIndex)
-{
-
+void LVPSA_QPD_Process_Float(void* hInstance, LVM_FLOAT* pInSamps, LVM_INT16 numSamples,
+                             LVM_INT16 BandIndex) {
     /******************************************************************************
        PARAMETERS
     *******************************************************************************/
-    LVPSA_InstancePr_t     *pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
-    QPD_FLOAT_State_t *pQPDState =  (QPD_FLOAT_State_t*)&pLVPSA_Inst->pQPD_States[BandIndex];
+    LVPSA_InstancePr_t* pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance;
+    QPD_FLOAT_State_t* pQPDState = (QPD_FLOAT_State_t*)&pLVPSA_Inst->pQPD_States[BandIndex];
 
     /* Pointer to taps */
-    LVM_FLOAT* pDelay  = pQPDState->pDelay;
+    LVM_FLOAT* pDelay = pQPDState->pDelay;
 
     /* Parameters needed during quasi peak calculations */
-    LVM_FLOAT   X0;
-    LVM_FLOAT   temp,temp2;
-    LVM_FLOAT   accu;
-    LVM_FLOAT   Xg0;
-    LVM_FLOAT   D0;
-    LVM_FLOAT   V0 = (LVM_FLOAT)(*pDelay);
+    LVM_FLOAT X0;
+    LVM_FLOAT temp, temp2;
+    LVM_FLOAT accu;
+    LVM_FLOAT Xg0;
+    LVM_FLOAT D0;
+    LVM_FLOAT V0 = (LVM_FLOAT)(*pDelay);
 
     /* Filter's coef */
-    LVM_FLOAT   Kp = ((LVM_FLOAT)(pQPDState->Coefs[0]));
-    LVM_FLOAT   Km = ((LVM_FLOAT)(pQPDState->Coefs[1]));
+    LVM_FLOAT Kp = ((LVM_FLOAT)(pQPDState->Coefs[0]));
+    LVM_FLOAT Km = ((LVM_FLOAT)(pQPDState->Coefs[1]));
 
-    LVM_INT16   ii = numSamples;
+    LVM_INT16 ii = numSamples;
 
-    LVM_UINT8  *pWrite = pLVPSA_Inst->pSpectralDataBufferWritePointer;
-    LVM_INT32   BufferUpdateSamplesCount = pLVPSA_Inst->BufferUpdateSamplesCount;
-    LVM_UINT16  DownSamplingFactor = pLVPSA_Inst->DownSamplingFactor;
+    LVM_UINT8* pWrite = pLVPSA_Inst->pSpectralDataBufferWritePointer;
+    LVM_INT32 BufferUpdateSamplesCount = pLVPSA_Inst->BufferUpdateSamplesCount;
+    LVM_UINT16 DownSamplingFactor = pLVPSA_Inst->DownSamplingFactor;
 
     /******************************************************************************
        INITIALIZATION
@@ -97,29 +89,27 @@
     /* Correct also the number of samples */
     ii = (LVM_INT16)(ii - (LVM_INT16)pLVPSA_Inst->DownSamplingCount);
 
-    while (ii > 0)
-    {
+    while (ii > 0) {
         /* Apply post gain */
         /* - 1 to compensate scaling in process function*/
         X0 = (*pInSamps) * pLVPSA_Inst->pPostGains[BandIndex];
         pInSamps = pInSamps + DownSamplingFactor;
 
         /* Saturate and take absolute value */
-        if(X0 < 0.0f)
-            X0 = -X0;
+        if (X0 < 0.0f) X0 = -X0;
         if (X0 > 1.0f)
             Xg0 = 1.0f;
         else
-            Xg0 =X0;
+            Xg0 = X0;
 
         /* Quasi peak filter calculation */
-        D0  = Xg0 - V0;
+        D0 = Xg0 - V0;
 
         temp2 = D0;
 
         accu = temp2 * Kp;
-        D0    = D0 / 2.0f;
-        if (D0 < 0.0f){
+        D0 = D0 / 2.0f;
+        if (D0 < 0.0f) {
             D0 = -D0;
         }
 
@@ -130,17 +120,13 @@
 
         if (accu > 1.0f)
             accu = 1.0f;
-        else if(accu < 0.0f)
+        else if (accu < 0.0f)
             accu = 0.0f;
 
         V0 = accu;
 
-        if(((pLVPSA_Inst->nSamplesBufferUpdate - BufferUpdateSamplesCount) < DownSamplingFactor))
-        {
-            LVPSA_QPD_WritePeak_Float( pLVPSA_Inst,
-                                       &pWrite,
-                                       BandIndex,
-                                       V0);
+        if (((pLVPSA_Inst->nSamplesBufferUpdate - BufferUpdateSamplesCount) < DownSamplingFactor)) {
+            LVPSA_QPD_WritePeak_Float(pLVPSA_Inst, &pWrite, BandIndex, V0);
 
             BufferUpdateSamplesCount -= pLVPSA_Inst->nSamplesBufferUpdate;
             pLVPSA_Inst->LocalSamplesCount = (LVM_UINT16)(numSamples - ii);
@@ -148,7 +134,6 @@
         BufferUpdateSamplesCount += DownSamplingFactor;
 
         ii = (LVM_INT16)(ii - DownSamplingFactor);
-
     }
 
     /* Store last taps in memory */
@@ -156,20 +141,15 @@
 
     /* If this is the last call to the function after last band processing,
        update the parameters. */
-    if(BandIndex == (pLVPSA_Inst->nRelevantFilters - 1))
-    {
+    if (BandIndex == (pLVPSA_Inst->nRelevantFilters - 1)) {
         pLVPSA_Inst->pSpectralDataBufferWritePointer = pWrite;
         /* Adjustment for 11025Hz input, 220,5 is normally
            the exact number of samples for 20ms.*/
-        if((pLVPSA_Inst->pSpectralDataBufferWritePointer != pWrite)&&
-                                        (pLVPSA_Inst->CurrentParams.Fs == LVM_FS_11025))
-        {
-            if(pLVPSA_Inst->nSamplesBufferUpdate == 220)
-            {
+        if ((pLVPSA_Inst->pSpectralDataBufferWritePointer != pWrite) &&
+            (pLVPSA_Inst->CurrentParams.Fs == LVM_FS_11025)) {
+            if (pLVPSA_Inst->nSamplesBufferUpdate == 220) {
                 pLVPSA_Inst->nSamplesBufferUpdate = 221;
-            }
-            else
-            {
+            } else {
                 pLVPSA_Inst->nSamplesBufferUpdate = 220;
             }
         }
@@ -194,37 +174,29 @@
 /* RETURNS:             void                                                        */
 /*                                                                                  */
 /************************************************************************************/
-void LVPSA_QPD_WritePeak(   pLVPSA_InstancePr_t       pLVPSA_Inst,
-                            LVM_UINT8             **ppWrite,
-                            LVM_INT16               BandIndex,
-                            LVM_INT16               Value   )
-{
-    LVM_UINT8 *pWrite = *ppWrite;
+void LVPSA_QPD_WritePeak(pLVPSA_InstancePr_t pLVPSA_Inst, LVM_UINT8** ppWrite, LVM_INT16 BandIndex,
+                         LVM_INT16 Value) {
+    LVM_UINT8* pWrite = *ppWrite;
 
     /* Write the value and update the write pointer */
-    *(pWrite + BandIndex) = (LVM_UINT8)(Value>>7);
+    *(pWrite + BandIndex) = (LVM_UINT8)(Value >> 7);
     pWrite += pLVPSA_Inst->nBands;
-    if (pWrite == (pLVPSA_Inst->pSpectralDataBufferStart + pLVPSA_Inst->nBands * pLVPSA_Inst->SpectralDataBufferLength))
-    {
+    if (pWrite == (pLVPSA_Inst->pSpectralDataBufferStart +
+                   pLVPSA_Inst->nBands * pLVPSA_Inst->SpectralDataBufferLength)) {
         pWrite = pLVPSA_Inst->pSpectralDataBufferStart;
     }
 
     *ppWrite = pWrite;
-
 }
-void LVPSA_QPD_WritePeak_Float(   pLVPSA_InstancePr_t     pLVPSA_Inst,
-                                  LVM_UINT8               **ppWrite,
-                                  LVM_INT16               BandIndex,
-                                  LVM_FLOAT               Value   )
-{
-    LVM_UINT8 *pWrite = *ppWrite;
+void LVPSA_QPD_WritePeak_Float(pLVPSA_InstancePr_t pLVPSA_Inst, LVM_UINT8** ppWrite,
+                               LVM_INT16 BandIndex, LVM_FLOAT Value) {
+    LVM_UINT8* pWrite = *ppWrite;
 
     /* Write the value and update the write pointer */
     *(pWrite + BandIndex) = (LVM_UINT8)(Value * 256);
     pWrite += pLVPSA_Inst->nBands;
-    if (pWrite == (pLVPSA_Inst->pSpectralDataBufferStart + pLVPSA_Inst->nBands * \
-                                    pLVPSA_Inst->SpectralDataBufferLength))
-    {
+    if (pWrite == (pLVPSA_Inst->pSpectralDataBufferStart +
+                   pLVPSA_Inst->nBands * pLVPSA_Inst->SpectralDataBufferLength)) {
         pWrite = pLVPSA_Inst->pSpectralDataBufferStart;
     }
 
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Tables.cpp b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Tables.cpp
index 9f0aa02..4fbff6f 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Tables.cpp
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Tables.cpp
@@ -34,19 +34,9 @@
  * Sample rate table for converting between the enumerated type and the actual
  * frequency
  */
-const LVM_UINT32    LVPSA_SampleRateTab[] = {   8000,                    /* 8kS/s  */
-                                                11025,
-                                                12000,
-                                                16000,
-                                                22050,
-                                                24000,
-                                                32000,
-                                                44100,
-                                                48000,
-                                                88200,
-                                                96000,
-                                               176400,
-                                               192000};                  /* 192kS/s */
+const LVM_UINT32 LVPSA_SampleRateTab[] = {8000, /* 8kS/s  */
+                                          11025, 12000, 16000, 22050, 24000,  32000,
+                                          44100, 48000, 88200, 96000, 176400, 192000}; /* 192kS/s */
 
 /************************************************************************************/
 /*                                                                                  */
@@ -58,20 +48,11 @@
  * Sample rate table for converting between the enumerated type and the actual
  * frequency
  */
-const LVM_UINT32    LVPSA_SampleRateInvTab[] = {    268435,                    /* 8kS/s  */
-                                                    194783,
-                                                    178957,
-                                                    134218,
-                                                    97391,
-                                                    89478,
-                                                    67109,
-                                                    48696,
-                                                    44739
-                                                    ,24348
-                                                    ,22369
-                                                    ,12174
-                                                    ,11185                  /* 192kS/s */
-                                               };
+const LVM_UINT32 LVPSA_SampleRateInvTab[] = {
+        268435, /* 8kS/s  */
+        194783, 178957, 134218, 97391, 89478, 67109,
+        48696,  44739,  24348,  22369, 12174, 11185 /* 192kS/s */
+};
 
 /************************************************************************************/
 /*                                                                                  */
@@ -83,20 +64,10 @@
  * Table for converting between the enumerated type and the number of samples
  * during 20ms
  */
-const LVM_UINT16    LVPSA_nSamplesBufferUpdate[]  = {   160,                   /* 8kS/s  */
-                                                        220,
-                                                        240,
-                                                        320,
-                                                        441,
-                                                        480,
-                                                        640,
-                                                        882,
-                                                        960
-                                                        ,1764
-                                                        ,1920
-                                                        ,3528
-                                                        ,3840                  /* 192kS/s */
-                                                    };
+const LVM_UINT16 LVPSA_nSamplesBufferUpdate[] = {
+        160,                                                           /* 8kS/s  */
+        220, 240, 320, 441, 480, 640, 882, 960, 1764, 1920, 3528, 3840 /* 192kS/s */
+};
 /************************************************************************************/
 /*                                                                                  */
 /*  Down sampling factors                                                           */
@@ -106,20 +77,25 @@
 /*
  * Table for converting between the enumerated type and the down sampling factor
  */
-const LVM_UINT16    LVPSA_DownSamplingFactor[]  = {     5,                    /* 8000  S/s  */
-                                                        7,                    /* 11025 S/s  */
-                                                        8,                    /* 12000 S/s  */
-                                                        10,                   /* 16000 S/s  */
-                                                        15,                   /* 22050 S/s  */
-                                                        16,                   /* 24000 S/s  */
-                                                        21,                   /* 32000 S/s  */
-                                                        30,                   /* 44100 S/s  */
-                                                        32                    /* 48000 S/s  */
-                                                       ,60                   /* 88200 S/s  */
-                                                       ,64                   /* 96000 S/s  */
-                                                       ,120                  /* 176400 S/s  */
-                                                       ,128                  /*192000 S/s  */
-                                                  };
+const LVM_UINT16 LVPSA_DownSamplingFactor[] = {
+        5,  /* 8000  S/s  */
+        7,  /* 11025 S/s  */
+        8,  /* 12000 S/s  */
+        10, /* 16000 S/s  */
+        15, /* 22050 S/s  */
+        16, /* 24000 S/s  */
+        21, /* 32000 S/s  */
+        30, /* 44100 S/s  */
+        32  /* 48000 S/s  */
+        ,
+        60 /* 88200 S/s  */
+        ,
+        64 /* 96000 S/s  */
+        ,
+        120 /* 176400 S/s  */
+        ,
+        128 /*192000 S/s  */
+};
 
 /************************************************************************************/
 /*                                                                                  */
@@ -130,102 +106,34 @@
 /*
  * Table for 2 * Pi / Fs
  */
-const LVM_INT16     LVPSA_TwoPiOnFsTable[] = {  26354,      /* 8kS/s */
-                                                19123,
-                                                17569,
-                                                13177,
-                                                 9561,
-                                                 8785,
-                                                 6588,
-                                                 4781,
-                                                 4392
-                                                ,2390
-                                                ,2196
-                                                ,1195
-                                                ,1098    /* 192kS/s */
-                                             };
+const LVM_INT16 LVPSA_TwoPiOnFsTable[] = {
+        26354,                                                                    /* 8kS/s */
+        19123, 17569, 13177, 9561, 8785, 6588, 4781, 4392, 2390, 2196, 1195, 1098 /* 192kS/s */
+};
 
-const LVM_FLOAT     LVPSA_Float_TwoPiOnFsTable[] = {  0.8042847f,      /* 8kS/s */
-                                                      0.5836054f,
-                                                      0.5361796f,
-                                                      0.4021423f,
-                                                      0.2917874f,
-                                                      0.2681051f,
-                                                      0.2010559f,
-                                                      0.1459089f,
-                                                      0.1340372f
-                                                     ,0.0729476f
-                                                     ,0.0670186f
-                                                     ,0.0364738f
-                                                     ,0.0335093f    /* 192kS/s */
-                                                   };
+const LVM_FLOAT LVPSA_Float_TwoPiOnFsTable[] = {
+        0.8042847f, /* 8kS/s */
+        0.5836054f, 0.5361796f, 0.4021423f, 0.2917874f, 0.2681051f, 0.2010559f,
+        0.1459089f, 0.1340372f, 0.0729476f, 0.0670186f, 0.0364738f, 0.0335093f /* 192kS/s */
+};
 
 /*
  * Gain table
  */
-const LVM_INT16     LVPSA_GainTable[] = {   364,          /* -15dB gain */
-                                            408,
-                                            458,
-                                            514,
-                                            577,
-                                            647,
-                                            726,
-                                            815,
-                                            914,
-                                            1026,
-                                            1151,
-                                            1292,
-                                            1449,
-                                            1626,
-                                            1825,
-                                            2048,         /* 0dB gain */
-                                            2297,
-                                            2578,
-                                            2892,
-                                            3245,
-                                            3641,
-                                            4096,
-                                            4584,
-                                            5144,
-                                            5772,
-                                            6476,
-                                            7266,
-                                            8153,
-                                            9148,
-                                            10264,
-                                            11576};        /* +15dB gain */
+const LVM_INT16 LVPSA_GainTable[] = {364, /* -15dB gain */
+                                     408,  458,  514,  577,  647,  726,   815,  914,
+                                     1026, 1151, 1292, 1449, 1626, 1825,  2048, /* 0dB gain */
+                                     2297, 2578, 2892, 3245, 3641, 4096,  4584, 5144,
+                                     5772, 6476, 7266, 8153, 9148, 10264, 11576}; /* +15dB gain */
 
-const LVM_FLOAT  LVPSA_Float_GainTable[]={  0.177734375f,          /* -15dB gain */
-                                            0.199218750f,
-                                            0.223632812f,
-                                            0.250976562f,
-                                            0.281738281f,
-                                            0.315917968f,
-                                            0.354492187f,
-                                            0.397949218f,
-                                            0.446289062f,
-                                            0.500976562f,
-                                            0.562011718f,
-                                            0.630859375f,
-                                            0.707519531f,
-                                            0.793945312f,
-                                            0.891113281f,
-                                            1.000000000f,         /* 0dB gain */
-                                            1.121582031f,
-                                            1.258789062f,
-                                            1.412109375f,
-                                            1.584472656f,
-                                            1.777832031f,
-                                            2.000000000f,
-                                            2.238281250f,
-                                            2.511718750f,
-                                            2.818359375f,
-                                            3.162109375f,
-                                            3.547851562f,
-                                            3.980957031f,
-                                            4.466796875f,
-                                            5.011718750f,
-                                            5.652343750f};        /* +15dB gain */
+const LVM_FLOAT LVPSA_Float_GainTable[] = {
+        0.177734375f, /* -15dB gain */
+        0.199218750f, 0.223632812f, 0.250976562f, 0.281738281f, 0.315917968f,
+        0.354492187f, 0.397949218f, 0.446289062f, 0.500976562f, 0.562011718f,
+        0.630859375f, 0.707519531f, 0.793945312f, 0.891113281f, 1.000000000f, /* 0dB gain */
+        1.121582031f, 1.258789062f, 1.412109375f, 1.584472656f, 1.777832031f,
+        2.000000000f, 2.238281250f, 2.511718750f, 2.818359375f, 3.162109375f,
+        3.547851562f, 3.980957031f, 4.466796875f, 5.011718750f, 5.652343750f}; /* +15dB gain */
 /************************************************************************************/
 /*                                                                                  */
 /*  Cosone polynomial coefficients                                                  */
@@ -241,20 +149,20 @@
  * a range of 0 to Pi. The output is in the range 32767 to -32768 representing the range
  * +1.0 to -1.0
  */
-const LVM_INT16     LVPSA_CosCoef[] = { 3,                             /* Shifts */
-                                        4096,                          /* a0 */
-                                        -36,                           /* a1 */
-                                        -19725,                        /* a2 */
-                                        -2671,                         /* a3 */
-                                        23730,                         /* a4 */
-                                        -9490};                        /* a5 */
-const LVM_FLOAT     LVPSA_Float_CosCoef[] = { 3,                             /* Shifts */
-                                              0.1250038f,                          /* a0 */
-                                              -0.0010986f,                           /* a1 */
-                                              -0.6019775f,                        /* a2 */
-                                              -0.0815149f,                         /* a3 */
-                                              0.7242042f,                         /* a4 */
-                                              -0.2896206f};                        /* a5 */
+const LVM_INT16 LVPSA_CosCoef[] = {3,                  /* Shifts */
+                                   4096,               /* a0 */
+                                   -36,                /* a1 */
+                                   -19725,             /* a2 */
+                                   -2671,              /* a3 */
+                                   23730,              /* a4 */
+                                   -9490};             /* a5 */
+const LVM_FLOAT LVPSA_Float_CosCoef[] = {3,            /* Shifts */
+                                         0.1250038f,   /* a0 */
+                                         -0.0010986f,  /* a1 */
+                                         -0.6019775f,  /* a2 */
+                                         -0.0815149f,  /* a3 */
+                                         0.7242042f,   /* a4 */
+                                         -0.2896206f}; /* a5 */
 /*
  * Coefficients for calculating the cosine error with the equation:
  *
@@ -269,101 +177,100 @@
  *
  * Cos(x) = 1.0 - CosErr(x)
  */
-const LVM_INT16     LVPSA_DPCosCoef[] = {   1,                           /* Shifts */
-                                            0,                           /* a0 */
-                                            -6,                          /* a1 */
-                                            16586,                       /* a2 */
-                                            -44};                        /* a3 */
-const LVM_FLOAT    LVPSA_Float_DPCosCoef[] = {1.0f,                        /* Shifts */
-                                              0.0f,                        /* a0 */
-                                              -0.00008311f,                 /* a1 */
-                                              0.50617999f,                 /* a2 */
-                                              -0.00134281f};                /* a3 */
+const LVM_INT16 LVPSA_DPCosCoef[] = {1,                   /* Shifts */
+                                     0,                   /* a0 */
+                                     -6,                  /* a1 */
+                                     16586,               /* a2 */
+                                     -44};                /* a3 */
+const LVM_FLOAT LVPSA_Float_DPCosCoef[] = {1.0f,          /* Shifts */
+                                           0.0f,          /* a0 */
+                                           -0.00008311f,  /* a1 */
+                                           0.50617999f,   /* a2 */
+                                           -0.00134281f}; /* a3 */
 /************************************************************************************/
 /*                                                                                  */
 /*  Quasi peak filter coefficients table                                            */
 /*                                                                                  */
 /************************************************************************************/
-const QPD_C32_Coefs     LVPSA_QPD_Coefs[] = {
-                                         /* 8kS/s  */    /* LVPSA_SPEED_LOW   */
-                                         {(LVM_INT32)0x80CEFD2B,0x00CB9B17},
-                                         {(LVM_INT32)0x80D242E7,0x00CED11D},
-                                         {(LVM_INT32)0x80DCBAF5,0x00D91679},
-                                         {(LVM_INT32)0x80CEFD2B,0x00CB9B17},
-                                         {(LVM_INT32)0x80E13739,0x00DD7CD3},
-                                         {(LVM_INT32)0x80DCBAF5,0x00D91679},
-                                         {(LVM_INT32)0x80D94BAF,0x00D5B7E7},
-                                         {(LVM_INT32)0x80E13739,0x00DD7CD3},
-                                         {(LVM_INT32)0x80DCBAF5,0x00D91679},  /* 48kS/s */
+const QPD_C32_Coefs LVPSA_QPD_Coefs[] = {
+        /* 8kS/s  */ /* LVPSA_SPEED_LOW   */
+        {(LVM_INT32)0x80CEFD2B, 0x00CB9B17},
+        {(LVM_INT32)0x80D242E7, 0x00CED11D},
+        {(LVM_INT32)0x80DCBAF5, 0x00D91679},
+        {(LVM_INT32)0x80CEFD2B, 0x00CB9B17},
+        {(LVM_INT32)0x80E13739, 0x00DD7CD3},
+        {(LVM_INT32)0x80DCBAF5, 0x00D91679},
+        {(LVM_INT32)0x80D94BAF, 0x00D5B7E7},
+        {(LVM_INT32)0x80E13739, 0x00DD7CD3},
+        {(LVM_INT32)0x80DCBAF5, 0x00D91679}, /* 48kS/s */
 
-                                         /* 8kS/s  */    /* LVPSA_SPEED_MEDIUM */
-                                         {(LVM_INT32)0x8587513D,0x055C22CF},
-                                         {(LVM_INT32)0x859D2967,0x0570F007},
-                                         {(LVM_INT32)0x85E2EFAC,0x05B34D79},
-                                         {(LVM_INT32)0x8587513D,0x055C22CF},
-                                         {(LVM_INT32)0x8600C7B9,0x05CFA6CF},
-                                         {(LVM_INT32)0x85E2EFAC,0x05B34D79},
-                                         {(LVM_INT32)0x85CC1018,0x059D8F69},
-                                         {(LVM_INT32)0x8600C7B9,0x05CFA6CF},
-                                         {(LVM_INT32)0x85E2EFAC,0x05B34D79},  /* 48kS/s */
+        /* 8kS/s  */ /* LVPSA_SPEED_MEDIUM */
+        {(LVM_INT32)0x8587513D, 0x055C22CF},
+        {(LVM_INT32)0x859D2967, 0x0570F007},
+        {(LVM_INT32)0x85E2EFAC, 0x05B34D79},
+        {(LVM_INT32)0x8587513D, 0x055C22CF},
+        {(LVM_INT32)0x8600C7B9, 0x05CFA6CF},
+        {(LVM_INT32)0x85E2EFAC, 0x05B34D79},
+        {(LVM_INT32)0x85CC1018, 0x059D8F69},
+        {(LVM_INT32)0x8600C7B9, 0x05CFA6CF},
+        {(LVM_INT32)0x85E2EFAC, 0x05B34D79}, /* 48kS/s */
 
-                                         /* 8kS/s  */   /* LVPSA_SPEED_HIGH    */
-                                         {(LVM_INT32)0xA115EA7A,0x1CDB3F5C},
-                                         {(LVM_INT32)0xA18475F0,0x1D2C83A2},
-                                         {(LVM_INT32)0xA2E1E950,0x1E2A532E},
-                                         {(LVM_INT32)0xA115EA7A,0x1CDB3F5C},
-                                         {(LVM_INT32)0xA375B2C6,0x1E943BBC},
-                                         {(LVM_INT32)0xA2E1E950,0x1E2A532E},
-                                         {(LVM_INT32)0xA26FF6BD,0x1DD81530},
-                                         {(LVM_INT32)0xA375B2C6,0x1E943BBC},
-                                         {(LVM_INT32)0xA2E1E950,0x1E2A532E}}; /* 48kS/s */
+        /* 8kS/s  */ /* LVPSA_SPEED_HIGH    */
+        {(LVM_INT32)0xA115EA7A, 0x1CDB3F5C},
+        {(LVM_INT32)0xA18475F0, 0x1D2C83A2},
+        {(LVM_INT32)0xA2E1E950, 0x1E2A532E},
+        {(LVM_INT32)0xA115EA7A, 0x1CDB3F5C},
+        {(LVM_INT32)0xA375B2C6, 0x1E943BBC},
+        {(LVM_INT32)0xA2E1E950, 0x1E2A532E},
+        {(LVM_INT32)0xA26FF6BD, 0x1DD81530},
+        {(LVM_INT32)0xA375B2C6, 0x1E943BBC},
+        {(LVM_INT32)0xA2E1E950, 0x1E2A532E}}; /* 48kS/s */
 
-const QPD_FLOAT_Coefs     LVPSA_QPD_Float_Coefs[] = {
+const QPD_FLOAT_Coefs LVPSA_QPD_Float_Coefs[] = {
 
-                                         /* 8kS/s  */    /* LVPSA_SPEED_LOW   */
-                                         {-0.9936831989325583f,0.0062135565094650f},
-                                         {-0.9935833332128823f,0.0063115493394434f},
-                                         {-0.9932638457976282f,0.0066249934025109f},
-                                         {-0.9936831989325583f,0.0062135565094650f},
-                                         {-0.9931269618682563f,0.0067592649720609f},
-                                         {-0.9932638457976282f,0.0066249934025109f},
-                                         {-0.9933686633594334f,0.0065221670083702f},
-                                         {-0.9931269618682563f,0.0067592649720609f},
-                                          /* 48kS/s */
-                                         {-0.9932638457976282f,0.0066249934025109f},
-                                         {-0.9931269618682563f,0.0067592649720609f},
-                                         {-0.9932638457976282f,0.0066249934025109f},
-                                         {-0.9931269618682563f,0.0067592649720609f},
-                                         {-0.9932638457976282f,0.0066249934025109f},
-                                         /* 8kS/s  */    /* LVPSA_SPEED_MEDIUM      */
-                                         {-0.9568079425953329f,0.0418742666952312f},
-                                         {-0.9561413046903908f,0.0425090822391212f},
-                                         {-0.9540119562298059f,0.0445343819446862f},
-                                         {-0.9568079425953329f,0.0418742666952312f},
-                                         {-0.9531011912040412f,0.0453995238058269f},
-                                         {-0.9540119562298059f,0.0445343819446862f},
-                                         {-0.9547099955379963f,0.0438708555884659f},
-                                          //{0x8600C7B9,0x05CFA6CF},
-                                         {-0.9531011912040412f,0.0453995238058269f},
-                                          /* 48kS/s */
-                                         {-0.9540119562298059f,0.0445343819446862f},
-                                         {-0.9531011912040412f,0.0453995238058269f},
-                                         {-0.9540119562298059f,0.0445343819446862f},
-                                         {-0.9531011912040412f,0.0453995238058269f},
-                                         {-0.9540119562298059f,0.0445343819446862f},
-                                          /* 8kS/s  */   /* LVPSA_SPEED_HIGH      */
-                                         {-0.7415186790749431f,0.2254409026354551f},
-                                         {-0.7381451204419136f,0.2279209652915597f},
-                                         {-0.7274807319045067f,0.2356666540727019f},
-                                         {-0.7415186790749431f,0.2254409026354551f},
-                                         {-0.7229706319049001f,0.2388987224549055f},
-                                         {-0.7274807319045067f,0.2356666540727019f},
-                                         {-0.7309581353329122f,0.2331568226218224f},
-                                         {-0.7229706319049001f,0.2388987224549055f},
-                                           /* 48kS/s */
-                                         {-0.7274807319045067f,0.2356666540727019f}
-                                        ,{-0.7229706319049001f,0.2388987224549055f}
-                                        ,{-0.7274807319045067f,0.2356666540727019f}
-                                        ,{-0.7229706319049001f,0.2388987224549055f}
-                                        ,{-0.7274807319045067f,0.2356666540727019f}
-                                        };
+        /* 8kS/s  */ /* LVPSA_SPEED_LOW   */
+        {-0.9936831989325583f, 0.0062135565094650f},
+        {-0.9935833332128823f, 0.0063115493394434f},
+        {-0.9932638457976282f, 0.0066249934025109f},
+        {-0.9936831989325583f, 0.0062135565094650f},
+        {-0.9931269618682563f, 0.0067592649720609f},
+        {-0.9932638457976282f, 0.0066249934025109f},
+        {-0.9933686633594334f, 0.0065221670083702f},
+        {-0.9931269618682563f, 0.0067592649720609f},
+        /* 48kS/s */
+        {-0.9932638457976282f, 0.0066249934025109f},
+        {-0.9931269618682563f, 0.0067592649720609f},
+        {-0.9932638457976282f, 0.0066249934025109f},
+        {-0.9931269618682563f, 0.0067592649720609f},
+        {-0.9932638457976282f, 0.0066249934025109f},
+        /* 8kS/s  */ /* LVPSA_SPEED_MEDIUM      */
+        {-0.9568079425953329f, 0.0418742666952312f},
+        {-0.9561413046903908f, 0.0425090822391212f},
+        {-0.9540119562298059f, 0.0445343819446862f},
+        {-0.9568079425953329f, 0.0418742666952312f},
+        {-0.9531011912040412f, 0.0453995238058269f},
+        {-0.9540119562298059f, 0.0445343819446862f},
+        {-0.9547099955379963f, 0.0438708555884659f},
+        //{0x8600C7B9,0x05CFA6CF},
+        {-0.9531011912040412f, 0.0453995238058269f},
+        /* 48kS/s */
+        {-0.9540119562298059f, 0.0445343819446862f},
+        {-0.9531011912040412f, 0.0453995238058269f},
+        {-0.9540119562298059f, 0.0445343819446862f},
+        {-0.9531011912040412f, 0.0453995238058269f},
+        {-0.9540119562298059f, 0.0445343819446862f},
+        /* 8kS/s  */ /* LVPSA_SPEED_HIGH      */
+        {-0.7415186790749431f, 0.2254409026354551f},
+        {-0.7381451204419136f, 0.2279209652915597f},
+        {-0.7274807319045067f, 0.2356666540727019f},
+        {-0.7415186790749431f, 0.2254409026354551f},
+        {-0.7229706319049001f, 0.2388987224549055f},
+        {-0.7274807319045067f, 0.2356666540727019f},
+        {-0.7309581353329122f, 0.2331568226218224f},
+        {-0.7229706319049001f, 0.2388987224549055f},
+        /* 48kS/s */
+        {-0.7274807319045067f, 0.2356666540727019f},
+        {-0.7229706319049001f, 0.2388987224549055f},
+        {-0.7274807319045067f, 0.2356666540727019f},
+        {-0.7229706319049001f, 0.2388987224549055f},
+        {-0.7274807319045067f, 0.2356666540727019f}};
diff --git a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Tables.h b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Tables.h
index 65872fe..c771dad 100644
--- a/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Tables.h
+++ b/media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Tables.h
@@ -27,7 +27,7 @@
  * Sample rate table for converting between the enumerated type and the actual
  * frequency
  */
-extern const LVM_UINT32    LVPSA_SampleRateTab[];
+extern const LVM_UINT32 LVPSA_SampleRateTab[];
 
 /************************************************************************************/
 /*                                                                                  */
@@ -39,7 +39,7 @@
  * Sample rate table for converting between the enumerated type and the actual
  * frequency
  */
-extern const LVM_UINT32    LVPSA_SampleRateInvTab[];
+extern const LVM_UINT32 LVPSA_SampleRateInvTab[];
 
 /************************************************************************************/
 /*                                                                                  */
@@ -51,7 +51,7 @@
  * Table for converting between the enumerated type and the number of samples
  * during 20ms
  */
-extern const LVM_UINT16    LVPSA_nSamplesBufferUpdate[];
+extern const LVM_UINT16 LVPSA_nSamplesBufferUpdate[];
 
 /************************************************************************************/
 /*                                                                                  */
@@ -62,7 +62,7 @@
 /*
  * Table for converting between the enumerated type and the down sampling factor
  */
-extern const LVM_UINT16    LVPSA_DownSamplingFactor[];
+extern const LVM_UINT16 LVPSA_DownSamplingFactor[];
 
 /************************************************************************************/
 /*                                                                                  */
@@ -73,14 +73,14 @@
 /*
  * Table for 2 * Pi / Fs
  */
-extern const LVM_INT16     LVPSA_TwoPiOnFsTable[];
-extern const LVM_FLOAT     LVPSA_Float_TwoPiOnFsTable[];
+extern const LVM_INT16 LVPSA_TwoPiOnFsTable[];
+extern const LVM_FLOAT LVPSA_Float_TwoPiOnFsTable[];
 
 /*
  * Gain table
  */
-extern const LVM_INT16     LVPSA_GainTable[];
-extern const LVM_FLOAT     LVPSA_Float_GainTable[];
+extern const LVM_INT16 LVPSA_GainTable[];
+extern const LVM_FLOAT LVPSA_Float_GainTable[];
 
 /************************************************************************************/
 /*                                                                                  */
@@ -97,8 +97,8 @@
  * a range of 0 to Pi. The output is in the range 32767 to -32768 representing the range
  * +1.0 to -1.0
  */
-extern const LVM_INT16     LVPSA_CosCoef[];
-extern const LVM_FLOAT     LVPSA_Float_CosCoef[];
+extern const LVM_INT16 LVPSA_CosCoef[];
+extern const LVM_FLOAT LVPSA_Float_CosCoef[];
 
 /*
  * Coefficients for calculating the cosine error with the equation:
@@ -114,15 +114,15 @@
  *
  * Cos(x) = 1.0 - CosErr(x)
  */
-extern const LVM_INT16     LVPSA_DPCosCoef[];
-extern const LVM_FLOAT    LVPSA_Float_DPCosCoef[];
+extern const LVM_INT16 LVPSA_DPCosCoef[];
+extern const LVM_FLOAT LVPSA_Float_DPCosCoef[];
 
 /************************************************************************************/
 /*                                                                                  */
 /*  Quasi peak filter coefficients table                                            */
 /*                                                                                  */
 /************************************************************************************/
-extern const QPD_C32_Coefs     LVPSA_QPD_Coefs[];
-extern const QPD_FLOAT_Coefs     LVPSA_QPD_Float_Coefs[];
+extern const QPD_C32_Coefs LVPSA_QPD_Coefs[];
+extern const QPD_FLOAT_Coefs LVPSA_QPD_Float_Coefs[];
 
 #endif /* __LVPSA_TABLES_H__ */
diff --git a/media/libeffects/lvm/lib/StereoWidening/lib/LVCS.h b/media/libeffects/lvm/lib/StereoWidening/lib/LVCS.h
index 0adfd1b..ffe7902 100644
--- a/media/libeffects/lvm/lib/StereoWidening/lib/LVCS.h
+++ b/media/libeffects/lvm/lib/StereoWidening/lib/LVCS.h
@@ -71,21 +71,14 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/* Memory table */
-#define LVCS_MEMREGION_PERSISTENT_SLOW_DATA    0    /* Offset to the instance memory region */
-#define LVCS_MEMREGION_PERSISTENT_FAST_DATA    1    /* Offset to the persistent data memory region */
-#define LVCS_MEMREGION_PERSISTENT_FAST_COEF    2    /* Offset to the persistent coefficient memory region */
-#define LVCS_MEMREGION_TEMPORARY_FAST          3    /* Offset to temporary memory region */
-#define LVCS_NR_MEMORY_REGIONS                 4    /* Number of memory regions */
-
 /* Effect Level */
-#define LVCS_EFFECT_LOW                    16384    /* Effect scaling 50% */
-#define LVCS_EFFECT_MEDIUM                 24576    /* Effect scaling 75% */
-#define LVCS_EFFECT_HIGH                   32767    /* Effect Scaling 100% */
+#define LVCS_EFFECT_LOW 16384    /* Effect scaling 50% */
+#define LVCS_EFFECT_MEDIUM 24576 /* Effect scaling 75% */
+#define LVCS_EFFECT_HIGH 32767   /* Effect Scaling 100% */
 
 /* Callback events */
-#define LVCS_EVENT_NONE                   0x0000    /* Not a valid event */
-#define LVCS_EVENT_ALGOFF                 0x0001    /* CS has completed switch off */
+#define LVCS_EVENT_NONE 0x0000   /* Not a valid event */
+#define LVCS_EVENT_ALGOFF 0x0001 /* CS has completed switch off */
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -94,70 +87,49 @@
 /****************************************************************************************/
 
 /* Instance handle */
-typedef void *LVCS_Handle_t;
+typedef void* LVCS_Handle_t;
 
 /* Operating modes */
-typedef enum
-{
-    LVCS_OFF = 0,
-    LVCS_ON  = 15,
-    LVCS_MAX = LVM_MAXENUM
-} LVCS_Modes_en;
-
-/* Memory Types */
-typedef enum
-{
-    LVCS_SCRATCH        = 0,
-    LVCS_DATA           = 1,
-    LVCS_COEFFICIENT    = 2,
-    LVCS_PERSISTENT     = 3,
-    LVCS_MEMORYTYPE_MAX = LVM_MAXENUM
-} LVCS_MemoryTypes_en;
+typedef enum { LVCS_OFF = 0, LVCS_ON = 15, LVCS_MAX = LVM_MAXENUM } LVCS_Modes_en;
 
 /* Function return status */
-typedef enum
-{
-    LVCS_SUCCESS        = 0,                        /* Successful return from a routine */
-    LVCS_ALIGNMENTERROR = 1,                        /* Memory alignment error */
-    LVCS_NULLADDRESS    = 2,                        /* NULL allocation address */
-    LVCS_TOOMANYSAMPLES = 3,                        /* Maximum block size exceeded */
-    LVCS_INVALIDBUFFER  = 4,                        /* Invalid buffer processing request */
-    LVCS_STATUSMAX      = LVM_MAXENUM
+typedef enum {
+    LVCS_SUCCESS = 0,        /* Successful return from a routine */
+    LVCS_NULLADDRESS = 1,    /* NULL allocation address */
+    LVCS_TOOMANYSAMPLES = 2, /* Maximum block size exceeded */
+    LVCS_STATUSMAX = LVM_MAXENUM
 } LVCS_ReturnStatus_en;
 
 /*
  * Source data formats
  */
-typedef enum
-{
-    LVCS_STEREO       = 0,
+typedef enum {
+    LVCS_STEREO = 0,
     LVCS_MONOINSTEREO = 1,
-    LVCS_SOURCEMAX    = LVM_MAXENUM
+    LVCS_SOURCEMAX = LVM_MAXENUM
 } LVCS_SourceFormat_en;
 
 /*
  * Supported output devices
  */
-typedef enum
-{
-    LVCS_HEADPHONES             = 0,
-    LVCS_EX_HEADPHONES          = 1,
-    LVCS_SPEAKERTYPE_MAX        = LVM_MAXENUM
+typedef enum {
+    LVCS_HEADPHONES = 0,
+    LVCS_EX_HEADPHONES = 1,
+    LVCS_SPEAKERTYPE_MAX = LVM_MAXENUM
 } LVCS_SpeakerType_en;
 
 /*
  * Speaker Coefficients Table
  */
-typedef struct
-{
-    void    *pTable1;
-    void    *pTable2;
-    void    *pTable3;
-    void    *pTable4;
-    void    *pTable5;
-    void    *pTable6;
-    void    *pTable7;
-    void    *pTable8;
+typedef struct {
+    void* pTable1;
+    void* pTable2;
+    void* pTable3;
+    void* pTable4;
+    void* pTable5;
+    void* pTable6;
+    void* pTable7;
+    void* pTable8;
 } LVCS_CSMS_Coef_Tables_t;
 
 /****************************************************************************************/
@@ -166,44 +138,26 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/* Memory region definition */
-typedef struct
-{
-    LVM_UINT32              Size;                   /* Region size in bytes */
-    LVCS_MemoryTypes_en     Type;                   /* Region type */
-    void                    *pBaseAddress;          /* Pointer to the region base address */
-} LVCS_MemoryRegion_t;
-
-/* Memory table containing the region definitions */
-typedef struct
-{
-    LVCS_MemoryRegion_t Region[LVCS_NR_MEMORY_REGIONS]; /* One definition for each region */
-} LVCS_MemTab_t;
-
 /* Concert Sound parameter structure */
-typedef struct
-{
-    LVCS_Modes_en           OperatingMode;          /* Algorithm mode */
-    LVCS_SpeakerType_en     SpeakerType;            /* Output device type */
-    LVCS_SourceFormat_en    SourceFormat;           /* Source data format */
-    LVM_Mode_en             CompressorMode;         /* Non-Linear Compressor Mode */
-    LVM_Fs_en               SampleRate;             /* Sampling rate */
-    LVM_INT16               EffectLevel;            /* Effect level */
-    LVM_UINT16              ReverbLevel;            /* Reverb level in % */
-#ifdef SUPPORT_MC
-    LVM_INT32               NrChannels;
-#endif
+typedef struct {
+    LVCS_Modes_en OperatingMode;       /* Algorithm mode */
+    LVCS_SpeakerType_en SpeakerType;   /* Output device type */
+    LVCS_SourceFormat_en SourceFormat; /* Source data format */
+    LVM_Mode_en CompressorMode;        /* Non-Linear Compressor Mode */
+    LVM_Fs_en SampleRate;              /* Sampling rate */
+    LVM_INT16 EffectLevel;             /* Effect level */
+    LVM_UINT16 ReverbLevel;            /* Reverb level in % */
+    LVM_INT32 NrChannels;
 } LVCS_Params_t;
 
 /* Concert Sound Capability structure */
-typedef struct
-{
+typedef struct {
     /* General parameters */
-    LVM_UINT16              MaxBlockSize;           /* Maximum block size in sample pairs */
+    LVM_UINT16 MaxBlockSize; /* Maximum block size in sample pairs */
 
     /* Callback parameters */
-    LVM_Callback            CallBack;               /* Bundle callback */
-    void                    *pBundleInstance;       /* Bundle instance handle */
+    LVM_Callback CallBack; /* Bundle callback */
+    void* pBundleInstance; /* Bundle instance handle */
 
 } LVCS_Capabilities_t;
 
@@ -213,82 +167,44 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-/****************************************************************************************/
-/*                                                                                      */
-/* FUNCTION:                LVCS_Memory                                                 */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*  This function is used for memory allocation and free. It can be called in           */
-/*  two ways:                                                                           */
-/*                                                                                      */
-/*      hInstance = NULL                Returns the memory requirements                 */
-/*      hInstance = Instance handle     Returns the memory requirements and             */
-/*                                      allocated base addresses for the instance       */
-/*                                                                                      */
-/*  When this function is called for memory allocation (hInstance=NULL) it is           */
-/*  passed the default capabilities, of these only the buffer processing setting is     */
-/*  used.                                                                               */
-/*                                                                                      */
-/*  When called for memory allocation the memory base address pointers are NULL on      */
-/*  return.                                                                             */
-/*                                                                                      */
-/*  When the function is called for free (hInstance = Instance Handle) the              */
-/*  capabilities are ignored and the memory table returns the allocated memory and      */
-/*  base addresses used during initialisation.                                          */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance               Instance Handle                                             */
-/*  pMemoryTable            Pointer to an empty memory definition table                 */
-/*  pCapabilities           Pointer to the default capabilites                          */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVCS_Success            Succeeded                                                   */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*  1.  This function may be interrupted by the LVCS_Process function                   */
-/*                                                                                      */
-/****************************************************************************************/
+/************************************************************************************/
+/*                                                                                  */
+/* FUNCTION:                LVCS_Init                                               */
+/*                                                                                  */
+/* DESCRIPTION:                                                                     */
+/*  Create and initialisation function for the Concert Sound module                 */
+/*                                                                                  */
+/* PARAMETERS:                                                                      */
+/*  phInstance              Pointer to instance handle                              */
+/*  pCapabilities           Pointer to the capabilities structure                   */
+/*  pScratch                Pointer to the scratch buffer                           */
+/*                                                                                  */
+/* RETURNS:                                                                         */
+/*  LVCS_Success            Initialisation succeeded                                */
+/*  LVDBE_NULLADDRESS       One or more memory has a NULL pointer                   */
+/*                                                                                  */
+/* NOTES:                                                                           */
+/*  1.  This function must not be interrupted by the LVCS_Process function          */
+/*                                                                                  */
+/************************************************************************************/
+LVCS_ReturnStatus_en LVCS_Init(LVCS_Handle_t* phInstance, LVCS_Capabilities_t* pCapabilities,
+                               void* pScratch);
 
-LVCS_ReturnStatus_en LVCS_Memory(LVCS_Handle_t          hInstance,
-                                 LVCS_MemTab_t          *pMemoryTable,
-                                 LVCS_Capabilities_t    *pCapabilities);
-
-/****************************************************************************************/
-/*                                                                                      */
-/* FUNCTION:                LVCS_Init                                                   */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*  Create and initialisation function for the Concert Sound module                     */
-/*                                                                                      */
-/*  This function can be used to create an algorithm instance by calling with           */
-/*  hInstance set to NULL. In this case the algorithm returns the new instance          */
-/*  handle.                                                                             */
-/*                                                                                      */
-/*  This function can be used to force a full re-initialisation of the algorithm        */
-/*  by calling with hInstance = Instance Handle. In this case the memory table          */
-/*  should be correct for the instance, this can be ensured by calling the function     */
-/*  LVCS_Memory before calling this function.                                           */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance               Instance handle                                             */
-/*  pMemoryTable            Pointer to the memory definition table                      */
-/*  pCapabilities           Pointer to the initialisation capabilities                  */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVCS_Success            Initialisation succeeded                                    */
-/*  LVCS_AlignmentError     Instance or scratch memory on incorrect alignment           */
-/*  LVCS_NullAddress        Instance or scratch memory has a NULL pointer               */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*  1.  The instance handle is the pointer to the base address of the first memory      */
-/*      region.                                                                         */
-/*  2.  This function must not be interrupted by the LVCS_Process function              */
-/*                                                                                      */
-/****************************************************************************************/
-
-LVCS_ReturnStatus_en LVCS_Init(LVCS_Handle_t            *phInstance,
-                               LVCS_MemTab_t            *pMemoryTable,
-                               LVCS_Capabilities_t      *pCapabilities);
+/************************************************************************************/
+/*                                                                                  */
+/* FUNCTION:                LVCS_DeInit                                             */
+/*                                                                                  */
+/* DESCRIPTION:                                                                     */
+/*  Free memories created during the LVCS_Init call including instance handle       */
+/*                                                                                  */
+/* PARAMETERS:                                                                      */
+/*  phInstance              Pointer to instance handle                              */
+/*                                                                                  */
+/* NOTES:                                                                           */
+/*  1.  This function must not be interrupted by the LVCS_Process function          */
+/*                                                                                  */
+/************************************************************************************/
+void LVCS_DeInit(LVCS_Handle_t* phInstance);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -310,8 +226,7 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_GetParameters(LVCS_Handle_t   hInstance,
-                                        LVCS_Params_t   *pParams);
+LVCS_ReturnStatus_en LVCS_GetParameters(LVCS_Handle_t hInstance, LVCS_Params_t* pParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -332,8 +247,7 @@
 /*                                                                                      */
 /****************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_Control(LVCS_Handle_t     hInstance,
-                                  LVCS_Params_t     *pParams);
+LVCS_ReturnStatus_en LVCS_Control(LVCS_Handle_t hInstance, LVCS_Params_t* pParams);
 
 /****************************************************************************************/
 /*                                                                                      */
@@ -356,9 +270,7 @@
 /* NOTES:                                                                               */
 /*                                                                                      */
 /****************************************************************************************/
-LVCS_ReturnStatus_en LVCS_Process(LVCS_Handle_t             hInstance,
-                                  const LVM_FLOAT           *pInData,
-                                  LVM_FLOAT                 *pOutData,
-                                  LVM_UINT16                NumSamples);
+LVCS_ReturnStatus_en LVCS_Process(LVCS_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                  LVM_FLOAT* pOutData, LVM_UINT16 NumSamples);
 
-#endif  /* LVCS_H */
+#endif /* LVCS_H */
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_BypassMix.cpp b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_BypassMix.cpp
index ba152c0..f805fca 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_BypassMix.cpp
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_BypassMix.cpp
@@ -32,9 +32,8 @@
 /*  Function Prototypes                                                                 */
 /*                                                                                      */
 /****************************************************************************************/
-LVM_INT32 LVCS_MixerCallback(   LVCS_Handle_t   hInstance,
-                                void            *pGeneralPurpose,
-                                LVM_INT16       CallbackParam);
+LVM_INT32 LVCS_MixerCallback(LVCS_Handle_t hInstance, void* pGeneralPurpose,
+                             LVM_INT16 CallbackParam);
 
 /************************************************************************************/
 /*                                                                                  */
@@ -65,29 +64,22 @@
 /*                                                                                  */
 /************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_BypassMixInit(LVCS_Handle_t       hInstance,
-                                        LVCS_Params_t       *pParams)
-{
-
-    LVM_UINT16          Offset;
-    LVM_FLOAT           Gain;
-    LVM_FLOAT           Current;
-    LVCS_Instance_t     *pInstance = (LVCS_Instance_t  *)hInstance;
-    LVCS_BypassMix_t    *pConfig   = (LVCS_BypassMix_t *)&pInstance->BypassMix;
-    const Gain_t        *pOutputGainTable;
+LVCS_ReturnStatus_en LVCS_BypassMixInit(LVCS_Handle_t hInstance, LVCS_Params_t* pParams) {
+    LVM_UINT16 Offset;
+    LVM_FLOAT Gain;
+    LVM_FLOAT Current;
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
+    LVCS_BypassMix_t* pConfig = (LVCS_BypassMix_t*)&pInstance->BypassMix;
+    const Gain_t* pOutputGainTable;
 
     /*
      * Set the transition gain
      */
-    if ((pParams->OperatingMode == LVCS_ON) &&
-        (pInstance->bTimerDone == LVM_TRUE)
-        && (pInstance->MSTarget1 != 0x7FFF) /* this indicates an off->on transtion */
-        )
-    {
+    if ((pParams->OperatingMode == LVCS_ON) && (pInstance->bTimerDone == LVM_TRUE) &&
+        (pInstance->MSTarget1 != 0x7FFF) /* this indicates an off->on transition */
+    ) {
         pInstance->TransitionGain = ((LVM_FLOAT)pParams->EffectLevel / 32767);
-    }
-    else
-    {
+    } else {
         /* Select no effect level */
         pInstance->TransitionGain = 0;
     }
@@ -95,18 +87,19 @@
     /*
      * Calculate the output gain table offset
      */
-    Offset = (LVM_UINT16)(pParams->SpeakerType + (pParams->SourceFormat*(1+LVCS_EX_HEADPHONES)));
+    Offset =
+            (LVM_UINT16)(pParams->SpeakerType + (pParams->SourceFormat * (1 + LVCS_EX_HEADPHONES)));
     pOutputGainTable = (Gain_t*)&LVCS_OutputGainTable[0];
 
     /*
      * Setup the mixer gain for the processed path
      */
-    Gain =  (LVM_FLOAT)(pOutputGainTable[Offset].Loss * pInstance->TransitionGain);
+    Gain = (LVM_FLOAT)(pOutputGainTable[Offset].Loss * pInstance->TransitionGain);
 
     pConfig->Mixer_Instance.MixerStream[0].CallbackParam = 0;
     pConfig->Mixer_Instance.MixerStream[0].pCallbackHandle = LVM_NULL;
     pConfig->Mixer_Instance.MixerStream[0].pCallBack = LVM_NULL;
-    pConfig->Mixer_Instance.MixerStream[0].CallbackSet=1;
+    pConfig->Mixer_Instance.MixerStream[0].CallbackSet = 1;
 
     Current = LVC_Mixer_GetCurrent(&pConfig->Mixer_Instance.MixerStream[0]);
     LVC_Mixer_Init(&pConfig->Mixer_Instance.MixerStream[0], (LVM_FLOAT)(Gain), Current);
@@ -116,8 +109,8 @@
     /*
      * Setup the mixer gain for the unprocessed path
      */
-    Gain = (LVM_FLOAT)(pOutputGainTable[Offset].Loss * (1.0 - \
-                                    (LVM_FLOAT)pInstance->TransitionGain));
+    Gain = (LVM_FLOAT)(pOutputGainTable[Offset].Loss *
+                       (1.0 - (LVM_FLOAT)pInstance->TransitionGain));
     Gain = (LVM_FLOAT)pOutputGainTable[Offset].UnprocLoss * Gain;
     Current = LVC_Mixer_GetCurrent(&pConfig->Mixer_Instance.MixerStream[1]);
     LVC_Mixer_Init(&pConfig->Mixer_Instance.MixerStream[1], (LVM_FLOAT)(Gain), Current);
@@ -125,7 +118,7 @@
                                        LVCS_BYPASS_MIXER_TC, pParams->SampleRate, 2);
     pConfig->Mixer_Instance.MixerStream[1].CallbackParam = 0;
     pConfig->Mixer_Instance.MixerStream[1].pCallbackHandle = hInstance;
-    pConfig->Mixer_Instance.MixerStream[1].CallbackSet=1;
+    pConfig->Mixer_Instance.MixerStream[1].CallbackSet = 1;
     pConfig->Mixer_Instance.MixerStream[1].pCallBack = LVCS_MixerCallback;
 
     /*
@@ -137,45 +130,42 @@
      * Correct gain for the effect level
      */
     {
-        LVM_FLOAT           GainCorrect;
-        LVM_FLOAT           Gain1;
-        LVM_FLOAT           Gain2;
+        LVM_FLOAT GainCorrect;
+        LVM_FLOAT Gain1;
+        LVM_FLOAT Gain2;
 
         Gain1 = LVC_Mixer_GetTarget(&pConfig->Mixer_Instance.MixerStream[0]);
         Gain2 = LVC_Mixer_GetTarget(&pConfig->Mixer_Instance.MixerStream[1]);
         /*
          * Calculate the gain correction
          */
-        if (pInstance->Params.CompressorMode == LVM_MODE_ON)
-        {
-        GainCorrect = (LVM_FLOAT)(  pInstance->VolCorrect.GainMin
-                                    - (((LVM_FLOAT)pInstance->VolCorrect.GainMin * \
-                                                         ((LVM_FLOAT)pInstance->TransitionGain)))
-                                    + (((LVM_FLOAT)pInstance->VolCorrect.GainFull * \
-                                                        ((LVM_FLOAT)pInstance->TransitionGain))));
+        if (pInstance->Params.CompressorMode == LVM_MODE_ON) {
+            GainCorrect = (LVM_FLOAT)(pInstance->VolCorrect.GainMin -
+                                      (((LVM_FLOAT)pInstance->VolCorrect.GainMin *
+                                        ((LVM_FLOAT)pInstance->TransitionGain))) +
+                                      (((LVM_FLOAT)pInstance->VolCorrect.GainFull *
+                                        ((LVM_FLOAT)pInstance->TransitionGain))));
 
-        /*
-         * Apply the gain correction
-         */
-        Gain1 = (Gain1 * GainCorrect);
-        Gain2 = (Gain2 * GainCorrect);
-
+            /*
+             * Apply the gain correction
+             */
+            Gain1 = (Gain1 * GainCorrect);
+            Gain2 = (Gain2 * GainCorrect);
         }
 
         /*
          * Set the gain values
          */
         pConfig->Output_Shift = pConfig->Output_Shift;
-        LVC_Mixer_SetTarget(&pConfig->Mixer_Instance.MixerStream[0],Gain1);
+        LVC_Mixer_SetTarget(&pConfig->Mixer_Instance.MixerStream[0], Gain1);
         LVC_Mixer_VarSlope_SetTimeConstant(&pConfig->Mixer_Instance.MixerStream[0],
                                            LVCS_BYPASS_MIXER_TC, pParams->SampleRate, 2);
-        LVC_Mixer_SetTarget(&pConfig->Mixer_Instance.MixerStream[1],Gain2);
+        LVC_Mixer_SetTarget(&pConfig->Mixer_Instance.MixerStream[1], Gain2);
         LVC_Mixer_VarSlope_SetTimeConstant(&pConfig->Mixer_Instance.MixerStream[1],
                                            LVCS_BYPASS_MIXER_TC, pParams->SampleRate, 2);
     }
 
-    return(LVCS_SUCCESS);
-
+    return (LVCS_SUCCESS);
 }
 
 /************************************************************************************/
@@ -205,39 +195,31 @@
 /*                                                                                  */
 /************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_BypassMixer(LVCS_Handle_t         hInstance,
-                                      const LVM_FLOAT       *pProcessed,
-                                      const LVM_FLOAT       *pUnprocessed,
-                                      LVM_FLOAT             *pOutData,
-                                      LVM_UINT16            NumSamples)
-{
-
-    LVCS_Instance_t     *pInstance      = (LVCS_Instance_t  *)hInstance;
-    LVCS_BypassMix_t    *pConfig        = (LVCS_BypassMix_t *)&pInstance->BypassMix;
+LVCS_ReturnStatus_en LVCS_BypassMixer(LVCS_Handle_t hInstance, const LVM_FLOAT* pProcessed,
+                                      const LVM_FLOAT* pUnprocessed, LVM_FLOAT* pOutData,
+                                      LVM_UINT16 NumSamples) {
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
+    LVCS_BypassMix_t* pConfig = (LVCS_BypassMix_t*)&pInstance->BypassMix;
+    LVM_UINT16 destNumSamples =
+            (pInstance->Params.NrChannels == FCC_1) ? NumSamples : FCC_2 * NumSamples;
 
     /*
      * Check if the bypass mixer is enabled
      */
-    if ((pInstance->Params.OperatingMode & LVCS_BYPASSMIXSWITCH) != 0)
-    {
+    if ((pInstance->Params.OperatingMode & LVCS_BYPASSMIXSWITCH) != 0) {
         /*
          * Apply the bypass mix
          */
-        LVC_MixSoft_2St_D16C31_SAT(&pConfig->Mixer_Instance,
-                                   pProcessed,
-                                   (LVM_FLOAT *) pUnprocessed,
-                                   pOutData,
-                                   (LVM_INT16)(2 * NumSamples));
+        LVC_MixSoft_2St_D16C31_SAT(&pConfig->Mixer_Instance, pProcessed, (LVM_FLOAT*)pUnprocessed,
+                                   pOutData, (LVM_INT16)destNumSamples);
         /*
          * Apply output gain correction shift
          */
-        Shift_Sat_Float((LVM_INT16)pConfig->Output_Shift,
-                        (LVM_FLOAT*)pOutData,
-                        (LVM_FLOAT*)pOutData,
-                        (LVM_INT16)(2 * NumSamples));          /* Left and right*/
+        Shift_Sat_Float((LVM_INT16)pConfig->Output_Shift, (LVM_FLOAT*)pOutData,
+                        (LVM_FLOAT*)pOutData, (LVM_INT16)destNumSamples);
     }
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
 
 /************************************************************************************/
@@ -245,22 +227,18 @@
 /* FUNCTION:                LVCS_MixerCallback                                      */
 /*                                                                                  */
 /************************************************************************************/
-LVM_INT32 LVCS_MixerCallback(LVCS_Handle_t      hInstance,
-                            void                *pGeneralPurpose,
-                            LVM_INT16           CallbackParam)
-{
-    LVCS_Instance_t     *pInstance = (LVCS_Instance_t  *)hInstance;
+LVM_INT32 LVCS_MixerCallback(LVCS_Handle_t hInstance, void* pGeneralPurpose,
+                             LVM_INT16 CallbackParam) {
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
 
-   (void)pGeneralPurpose;
+    (void)pGeneralPurpose;
 
     /*
      * Off transition has completed in Headphone mode
      */
-    if ((pInstance->OutputDevice == LVCS_HEADPHONE) &&
-        (pInstance->bInOperatingModeTransition)     &&
-        (pInstance->MSTarget0 == 0x0000)&&  /* this indicates an on->off transition */
-        (CallbackParam == 0))
-    {
+    if ((pInstance->OutputDevice == LVCS_HEADPHONE) && (pInstance->bInOperatingModeTransition) &&
+        (pInstance->MSTarget0 == 0x0000) && /* this indicates an on->off transition */
+        (CallbackParam == 0)) {
         /* Set operating mode to OFF */
         pInstance->Params.OperatingMode = LVCS_OFF;
 
@@ -268,21 +246,17 @@
         pInstance->bInOperatingModeTransition = LVM_FALSE;
 
         /* Signal to the bundle */
-        if((*pInstance->Capabilities.CallBack) != LVM_NULL){
-            (*pInstance->Capabilities.CallBack)(pInstance->Capabilities.pBundleInstance,
-                                                LVM_NULL,
+        if ((*pInstance->Capabilities.CallBack) != LVM_NULL) {
+            (*pInstance->Capabilities.CallBack)(pInstance->Capabilities.pBundleInstance, LVM_NULL,
                                                 (ALGORITHM_CS_ID | LVCS_EVENT_ALGOFF));
         }
     }
 
-    if ((pInstance->OutputDevice == LVCS_HEADPHONE)  &&
-        (pInstance->MSTarget0 == 1) &&
-        (pInstance->bTimerDone == LVM_TRUE)){
-
+    if ((pInstance->OutputDevice == LVCS_HEADPHONE) && (pInstance->MSTarget0 == 1) &&
+        (pInstance->bTimerDone == LVM_TRUE)) {
         /* Exit transition state */
         pInstance->bInOperatingModeTransition = LVM_FALSE;
     }
 
     return 1;
 }
-
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_BypassMix.h b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_BypassMix.h
index fcd8ee3..69afcbb 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_BypassMix.h
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_BypassMix.h
@@ -33,20 +33,18 @@
 /************************************************************************************/
 
 /* Bypass mixer structure */
-typedef struct
-{
+typedef struct {
     /* Mixer settings */
-    LVMixer3_2St_FLOAT_st   Mixer_Instance;             /* Mixer instance */
-    LVM_UINT16              Output_Shift;               /* Correcting gain output shift */
+    LVMixer3_2St_FLOAT_st Mixer_Instance; /* Mixer instance */
+    LVM_UINT16 Output_Shift;              /* Correcting gain output shift */
 
 } LVCS_BypassMix_t;
 
-typedef struct
-{
+typedef struct {
     /* Output gain settings, Gain = (Loss/32768) * 2^Shift */
-    LVM_UINT16             Shift;                      /* Left shifts required */
-    LVM_FLOAT              Loss;                       /* Loss required */
-    LVM_FLOAT              UnprocLoss;                 /* Unprocessed path loss */
+    LVM_UINT16 Shift;     /* Left shifts required */
+    LVM_FLOAT Loss;       /* Loss required */
+    LVM_FLOAT UnprocLoss; /* Unprocessed path loss */
 } Gain_t;
 /************************************************************************************/
 /*                                                                                    */
@@ -54,13 +52,10 @@
 /*                                                                                    */
 /************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_BypassMixInit(LVCS_Handle_t       hInstance,
-                                           LVCS_Params_t    *pParams);
+LVCS_ReturnStatus_en LVCS_BypassMixInit(LVCS_Handle_t hInstance, LVCS_Params_t* pParams);
 
-LVCS_ReturnStatus_en LVCS_BypassMixer(LVCS_Handle_t         hInstance,
-                                      const LVM_FLOAT       *pProcessed,
-                                      const LVM_FLOAT       *unProcessed,
-                                      LVM_FLOAT       *pOutData,
-                                      LVM_UINT16      NumSamples);
+LVCS_ReturnStatus_en LVCS_BypassMixer(LVCS_Handle_t hInstance, const LVM_FLOAT* pProcessed,
+                                      const LVM_FLOAT* unProcessed, LVM_FLOAT* pOutData,
+                                      LVM_UINT16 NumSamples);
 
-#endif  /* BYPASSMIX_H */
+#endif /* BYPASSMIX_H */
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Control.cpp b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Control.cpp
index 50db03d..89f2f3b 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Control.cpp
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Control.cpp
@@ -45,15 +45,12 @@
 /*                                                                                  */
 /************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_GetParameters(LVCS_Handle_t   hInstance,
-                                        LVCS_Params_t   *pParams)
-{
-
-    LVCS_Instance_t     *pInstance =(LVCS_Instance_t  *)hInstance;
+LVCS_ReturnStatus_en LVCS_GetParameters(LVCS_Handle_t hInstance, LVCS_Params_t* pParams) {
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
 
     *pParams = pInstance->Params;
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
 
 /************************************************************************************/
@@ -75,34 +72,29 @@
 /*                                                                                  */
 /************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_Control(LVCS_Handle_t      hInstance,
-                                  LVCS_Params_t      *pParams)
-{
-    LVM_INT16                   Offset;
-    LVCS_Instance_t             *pInstance =(LVCS_Instance_t  *)hInstance;
-    LVCS_ReturnStatus_en        err;
-    LVCS_Modes_en               OperatingModeSave = pInstance->Params.OperatingMode;
+LVCS_ReturnStatus_en LVCS_Control(LVCS_Handle_t hInstance, LVCS_Params_t* pParams) {
+    LVM_INT16 Offset;
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
+    LVCS_ReturnStatus_en err;
+    LVCS_Modes_en OperatingModeSave = pInstance->Params.OperatingMode;
 
-    if (pParams->SampleRate != pInstance->Params.SampleRate)
-    {
+    if (pParams->SampleRate != pInstance->Params.SampleRate) {
         pInstance->TimerParams.SamplingRate = LVCS_SampleRateTable[pParams->SampleRate];
     }
 
     /*
      * If the reverb level has changed
      */
-    if(pInstance->Params.ReverbLevel != pParams->ReverbLevel)
-    {
-        err=LVCS_ReverbGeneratorInit(hInstance,pParams);
+    if (pInstance->Params.ReverbLevel != pParams->ReverbLevel) {
+        err = LVCS_ReverbGeneratorInit(hInstance, pParams);
     }
 
     /*
      * If the sample rate or speaker has changed then perform a full re-initialisation
      */
     if ((pInstance->Params.SampleRate != pParams->SampleRate) ||
-       (pInstance->Params.SpeakerType != pParams->SpeakerType))
-    {
-        const LVCS_VolCorrect_t *pLVCS_VolCorrectTable;
+        (pInstance->Params.SpeakerType != pParams->SpeakerType)) {
+        const LVCS_VolCorrect_t* pLVCS_VolCorrectTable;
 
         /*
          * Output device
@@ -114,15 +106,16 @@
          */
         /* Use internal coefficient table */
         pLVCS_VolCorrectTable = (LVCS_VolCorrect_t*)&LVCS_VolCorrectTable[0];
-        Offset = (LVM_INT16)(pParams->SpeakerType + pParams->SourceFormat*(1+LVCS_EX_HEADPHONES));
+        Offset = (LVM_INT16)(pParams->SpeakerType +
+                             pParams->SourceFormat * (1 + LVCS_EX_HEADPHONES));
 
         pInstance->VolCorrect = pLVCS_VolCorrectTable[Offset];
 
         pInstance->CompressGain = pInstance->VolCorrect.CompMin;
         LVC_Mixer_Init(&pInstance->BypassMix.Mixer_Instance.MixerStream[0], 0, 0);
         {
-            LVM_FLOAT          Gain;
-            const Gain_t        *pOutputGainTable = (Gain_t*)&LVCS_OutputGainTable[0];
+            LVM_FLOAT Gain;
+            const Gain_t* pOutputGainTable = (Gain_t*)&LVCS_OutputGainTable[0];
             Gain = (LVM_FLOAT)(pOutputGainTable[Offset].Loss);
             Gain = (LVM_FLOAT)pOutputGainTable[Offset].UnprocLoss * (Gain);
 
@@ -133,22 +126,18 @@
 
             LVC_Mixer_Init(&pInstance->BypassMix.Mixer_Instance.MixerStream[1], 0, Gain);
             LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMix.Mixer_Instance.MixerStream[0],
-                    LVCS_BYPASS_MIXER_TC, pParams->SampleRate, 2);
+                                               LVCS_BYPASS_MIXER_TC, pParams->SampleRate, 2);
             LVC_Mixer_VarSlope_SetTimeConstant(&pInstance->BypassMix.Mixer_Instance.MixerStream[1],
-                    LVCS_BYPASS_MIXER_TC, pParams->SampleRate, 2);
+                                               LVCS_BYPASS_MIXER_TC, pParams->SampleRate, 2);
         }
 
-        err=LVCS_SEnhancerInit(hInstance,
-                           pParams);
+        err = LVCS_SEnhancerInit(hInstance, pParams);
 
-        err=LVCS_ReverbGeneratorInit(hInstance,
-                                 pParams);
+        err = LVCS_ReverbGeneratorInit(hInstance, pParams);
 
-        err=LVCS_EqualiserInit(hInstance,
-                           pParams);
+        err = LVCS_EqualiserInit(hInstance, pParams);
 
-        err=LVCS_BypassMixInit(hInstance,
-                           pParams);
+        err = LVCS_BypassMixInit(hInstance, pParams);
 
     }
 
@@ -156,30 +145,26 @@
      * Check if the effect level or source format has changed
      */
     else if ((pInstance->Params.EffectLevel != pParams->EffectLevel) ||
-            (pInstance->Params.SourceFormat != pParams->SourceFormat))
-    {
-        const LVCS_VolCorrect_t *pLVCS_VolCorrectTable;
+             (pInstance->Params.SourceFormat != pParams->SourceFormat)) {
+        const LVCS_VolCorrect_t* pLVCS_VolCorrectTable;
 
         /*
          * Get the volume correction parameters
          */
         /* Use internal coefficient table */
         pLVCS_VolCorrectTable = (LVCS_VolCorrect_t*)&LVCS_VolCorrectTable[0];
-        Offset = (LVM_INT16)(pParams->SpeakerType + pParams->SourceFormat*(1+LVCS_EX_HEADPHONES));
+        Offset = (LVM_INT16)(pParams->SpeakerType +
+                             pParams->SourceFormat * (1 + LVCS_EX_HEADPHONES));
 
         pInstance->VolCorrect = pLVCS_VolCorrectTable[Offset];
 
         /* Update the effect level and alpha-mixer gains */
-        err=LVCS_BypassMixInit(hInstance,
-                           pParams);
+        err = LVCS_BypassMixInit(hInstance, pParams);
 
-        if(err != LVCS_SUCCESS)
-        {
+        if (err != LVCS_SUCCESS) {
             return err;
         }
-    }
-    else
-    {
+    } else {
         pInstance->Params = *pParams;
     }
 
@@ -189,40 +174,38 @@
     pInstance->Params = *pParams;
 
     /* Stay on the current operating mode until the transition is done */
-    if((pParams->OperatingMode != OperatingModeSave) ||
-       (pInstance->bInOperatingModeTransition == LVM_TRUE)){
-
+    if ((pParams->OperatingMode != OperatingModeSave) ||
+        (pInstance->bInOperatingModeTransition == LVM_TRUE)) {
         /* Set the reverb delay timeout */
-        if(pInstance->bInOperatingModeTransition != LVM_TRUE){
+        if (pInstance->bInOperatingModeTransition != LVM_TRUE) {
             pInstance->bTimerDone = LVM_FALSE;
             pInstance->TimerParams.TimeInMs =
-            (LVM_INT16)(((pInstance->Reverberation.DelaySize << 2)
-            /pInstance->TimerParams.SamplingRate) + 1);
-            LVM_Timer_Init ( &pInstance->TimerInstance,
-                             &pInstance->TimerParams);
+                    (LVM_INT16)(((pInstance->Params.NrChannels == FCC_1
+                                          ? pInstance->Reverberation.DelaySize << 3
+                                          : pInstance->Reverberation.DelaySize << 2) /
+                                 pInstance->TimerParams.SamplingRate) +
+                                1);
+            LVM_Timer_Init(&pInstance->TimerInstance, &pInstance->TimerParams);
         }
 
         /* Update the effect level and alpha-mixer gains */
-        err=LVCS_BypassMixInit(hInstance,
-                           pParams);
+        err = LVCS_BypassMixInit(hInstance, pParams);
 
         /* Change transition bypass mixer settings if needed depending on transition type */
-        if(pParams->OperatingMode != LVCS_OFF){
-            pInstance->MSTarget0=LVM_MAXINT_16;
-            pInstance->MSTarget1=0;
-        }
-        else
-        {
+        if (pParams->OperatingMode != LVCS_OFF) {
+            pInstance->MSTarget0 = LVM_MAXINT_16;
+            pInstance->MSTarget1 = 0;
+        } else {
             pInstance->Params.OperatingMode = OperatingModeSave;
-            pInstance->MSTarget1=LVM_MAXINT_16;
-            pInstance->MSTarget0=0;
+            pInstance->MSTarget1 = LVM_MAXINT_16;
+            pInstance->MSTarget0 = 0;
         }
 
         /* Set transition flag */
         pInstance->bInOperatingModeTransition = LVM_TRUE;
     }
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
 
 /****************************************************************************************/
@@ -233,12 +216,11 @@
 /*  CallBack function of the Timer.                                                     */
 /*                                                                                      */
 /****************************************************************************************/
-void LVCS_TimerCallBack (void* hInstance, void* pCallBackParams, LVM_INT32 CallbackParam)
-{
-    LVCS_Instance_t     *pInstance  = (LVCS_Instance_t  *)hInstance;
+void LVCS_TimerCallBack(void* hInstance, void* pCallBackParams, LVM_INT32 CallbackParam) {
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
 
     /* Avoid warnings because pCallBackParams and CallbackParam are not used*/
-    if((pCallBackParams != LVM_NULL) || (CallbackParam != 0)){
+    if ((pCallBackParams != LVM_NULL) || (CallbackParam != 0)) {
         pCallBackParams = hInstance;
         CallbackParam = 0;
         return;
@@ -248,4 +230,3 @@
 
     return;
 }
-
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.cpp b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.cpp
index 431b7e3..1746786 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.cpp
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.cpp
@@ -21,6 +21,7 @@
 /*                                                                                  */
 /************************************************************************************/
 
+#include <system/audio.h>
 #include "LVCS.h"
 #include "LVCS_Private.h"
 #include "LVCS_Equaliser.h"
@@ -53,68 +54,31 @@
 /* NOTES:                                                                           */
 /*                                                                                  */
 /************************************************************************************/
-LVCS_ReturnStatus_en LVCS_EqualiserInit(LVCS_Handle_t       hInstance,
-                                        LVCS_Params_t       *pParams)
-{
+LVCS_ReturnStatus_en LVCS_EqualiserInit(LVCS_Handle_t hInstance, LVCS_Params_t* pParams) {
+    LVM_UINT16 Offset;
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
+    const BiquadA012B12CoefsSP_t* pEqualiserCoefTable;
 
-    LVM_UINT16          Offset;
-    LVCS_Instance_t     *pInstance = (LVCS_Instance_t  *)hInstance;
-    LVCS_Equaliser_t    *pConfig   = (LVCS_Equaliser_t *)&pInstance->Equaliser;
-    LVCS_Data_t         *pData;
-    LVCS_Coefficient_t  *pCoefficients;
-    BQ_FLOAT_Coefs_t      Coeffs;
-    const BiquadA012B12CoefsSP_t *pEqualiserCoefTable;
-
-    pData = (LVCS_Data_t *) \
-                pInstance->MemoryTable.Region[LVCS_MEMREGION_PERSISTENT_FAST_DATA].pBaseAddress;
-
-    pCoefficients = (LVCS_Coefficient_t *) \
-                pInstance->MemoryTable.Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].pBaseAddress;
     /*
      * If the sample rate changes re-initialise the filters
      */
     if ((pInstance->Params.SampleRate != pParams->SampleRate) ||
-        (pInstance->Params.SpeakerType != pParams->SpeakerType))
-    {
+        (pInstance->Params.SpeakerType != pParams->SpeakerType)) {
         /*
          * Setup the filter coefficients and clear the history
          */
         Offset = (LVM_UINT16)(pParams->SampleRate + (pParams->SpeakerType * (1 + LVM_FS_48000)));
         pEqualiserCoefTable = (BiquadA012B12CoefsSP_t*)&LVCS_EqualiserCoefTable[0];
 
-        /* Left and right filters */
-        /* Convert incoming coefficients to the required format/ordering */
-        Coeffs.A0 = (LVM_FLOAT) pEqualiserCoefTable[Offset].A0;
-        Coeffs.A1 = (LVM_FLOAT) pEqualiserCoefTable[Offset].A1;
-        Coeffs.A2 = (LVM_FLOAT) pEqualiserCoefTable[Offset].A2;
-        Coeffs.B1 = (LVM_FLOAT)-pEqualiserCoefTable[Offset].B1;
-        Coeffs.B2 = (LVM_FLOAT)-pEqualiserCoefTable[Offset].B2;
-
-        LoadConst_Float((LVM_INT16)0,                                         /* Value */
-                        (LVM_FLOAT *)&pData->EqualiserBiquadTaps, /* Destination */
-                        /* Number of words */
-                        (LVM_UINT16)(sizeof(pData->EqualiserBiquadTaps) / sizeof(LVM_FLOAT)));
-
-        BQ_2I_D16F32Css_TRC_WRA_01_Init(&pCoefficients->EqualiserBiquadInstance,
-                                        &pData->EqualiserBiquadTaps,
-                                        &Coeffs);
-
-        /* Callbacks */
-        switch(pEqualiserCoefTable[Offset].Scale)
-        {
-            case 13:
-                pConfig->pBiquadCallBack  = BQ_2I_D16F32C13_TRC_WRA_01;
-                break;
-            case 14:
-                pConfig->pBiquadCallBack  = BQ_2I_D16F32C14_TRC_WRA_01;
-                break;
-            case 15:
-                pConfig->pBiquadCallBack  = BQ_2I_D16F32C15_TRC_WRA_01;
-                break;
-        }
+        std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                pEqualiserCoefTable[Offset].A0, pEqualiserCoefTable[Offset].A1,
+                pEqualiserCoefTable[Offset].A2, -(pEqualiserCoefTable[Offset].B1),
+                -(pEqualiserCoefTable[Offset].B2)};
+        pInstance->pEqBiquad.reset(new android::audio_utils::BiquadFilter<LVM_FLOAT>(
+                (pParams->NrChannels == FCC_1) ? FCC_1 : FCC_2, coefs));
     }
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
 /************************************************************************************/
 /*                                                                                  */
@@ -135,30 +99,17 @@
 /*  1.  Always processes in place.                                                  */
 /*                                                                                  */
 /************************************************************************************/
-LVCS_ReturnStatus_en LVCS_Equaliser(LVCS_Handle_t       hInstance,
-                                    LVM_FLOAT           *pInputOutput,
-                                    LVM_UINT16          NumSamples)
-{
-
-    LVCS_Instance_t     *pInstance = (LVCS_Instance_t  *)hInstance;
-    LVCS_Equaliser_t    *pConfig   = (LVCS_Equaliser_t  *)&pInstance->Equaliser;
-    LVCS_Coefficient_t  *pCoefficients;
-
-    pCoefficients = (LVCS_Coefficient_t *) \
-                  pInstance->MemoryTable.Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].pBaseAddress;
+LVCS_ReturnStatus_en LVCS_Equaliser(LVCS_Handle_t hInstance, LVM_FLOAT* pInputOutput,
+                                    LVM_UINT16 NumSamples) {
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
 
     /*
      * Check if the equaliser is required
      */
-    if ((pInstance->Params.OperatingMode & LVCS_EQUALISERSWITCH) != 0)
-    {
+    if ((pInstance->Params.OperatingMode & LVCS_EQUALISERSWITCH) != 0) {
         /* Apply filter to the left and right channels */
-        (pConfig->pBiquadCallBack)((Biquad_FLOAT_Instance_t*) \
-                                        &pCoefficients->EqualiserBiquadInstance,
-                                        (LVM_FLOAT *)pInputOutput,
-                                        (LVM_FLOAT *)pInputOutput,
-                                        (LVM_INT16)NumSamples);
+        pInstance->pEqBiquad->process(pInputOutput, pInputOutput, NumSamples);
     }
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.h b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.h
index 918d931..5237344 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.h
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Equaliser.h
@@ -23,23 +23,14 @@
 /*    Structures                                                                    */
 /*                                                                                  */
 /************************************************************************************/
-
-/* Equaliser structure */
-typedef struct
-{
-    void (*pBiquadCallBack) (Biquad_FLOAT_Instance_t*, LVM_FLOAT*, LVM_FLOAT*, LVM_INT16);
-} LVCS_Equaliser_t;
-
 /************************************************************************************/
 /*                                                                                  */
 /*    Function prototypes                                                           */
 /*                                                                                  */
 /************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_EqualiserInit(LVCS_Handle_t       hInstance,
-                                        LVCS_Params_t       *pParams);
-LVCS_ReturnStatus_en LVCS_Equaliser(LVCS_Handle_t            hInstance,
-                                    LVM_FLOAT                *pInputOutput,
-                                    LVM_UINT16                NumSamples);
+LVCS_ReturnStatus_en LVCS_EqualiserInit(LVCS_Handle_t hInstance, LVCS_Params_t* pParams);
+LVCS_ReturnStatus_en LVCS_Equaliser(LVCS_Handle_t hInstance, LVM_FLOAT* pInputOutput,
+                                    LVM_UINT16 NumSamples);
 
-#endif  /* EQUALISER_H */
+#endif /* EQUALISER_H */
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 c7ee232..69c46c6 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Headphone_Coeffs.h
@@ -24,201 +24,201 @@
 /*                                                                                  */
 /************************************************************************************/
 /* 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_A2                           0.000000
-#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_SCALE                         15
+#define CS_MIDDLE_8000_A0 0.227720
+#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_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_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_A2                       0.000000
-#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_B2                         0.032397
-#define CS_SIDE_11025_SCALE                      15
+#define CS_MIDDLE_11025_A0 0.230838
+#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_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_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_A2                        0.000000
-#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_B2                         0.032856
-#define CS_SIDE_12000_SCALE                          15
+#define CS_MIDDLE_12000_A0 0.229932
+#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_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_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_A2                       0.000000
-#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_B2                         0.144104
-#define CS_SIDE_16000_SCALE                          14
+#define CS_MIDDLE_16000_A0 0.230638
+#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_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_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_A2                       0.000000
-#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_B2                          0.182507
-#define CS_SIDE_22050_SCALE                          14
+#define CS_MIDDLE_22050_A0 0.228749
+#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_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_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_A2                         0.000000
-#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_B2                           0.282177
-#define CS_SIDE_24000_SCALE                          14
+#define CS_MIDDLE_24000_A0 0.230395
+#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_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_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_A2                          0.000000
-#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_B2                            0.312495
-#define CS_SIDE_32000_SCALE                          14
+#define CS_MIDDLE_32000_A0 0.228400
+#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_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_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_A2                     0.000000
-#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_B2                       0.588399
-#define CS_SIDE_44100_SCALE                  14
+#define CS_MIDDLE_44100_A0 0.233593
+#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_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_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_A2                     0.000000
-#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_B2                     0.630405
-#define CS_SIDE_48000_SCALE                          14
+#define CS_MIDDLE_48000_A0 0.234445
+#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_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_B2 0.630405
+#define CS_SIDE_48000_SCALE 14
 
 /* Coefficients for 88200Hz sample rate.
  * The filter coefficients are obtained by carrying out
  * state-space analysis using the coefficients available
  * for 44100Hz.
  */
-#define CS_MIDDLE_88200_A0                     0.233846f
-#define CS_MIDDLE_88200_A1                     (-0.232657f)
-#define CS_MIDDLE_88200_A2                     0.000000f
-#define CS_MIDDLE_88200_B1                     (-0.992747f)
-#define CS_MIDDLE_88200_B2                     0.000000f
-#define CS_MIDDLE_88200_SCALE                  15
-#define CS_SIDE_88200_A0                       0.231541f
-#define CS_SIDE_88200_A1                       (-0.289586f)
-#define CS_SIDE_88200_A2                       0.058045f
-#define CS_SIDE_88200_B1                       (-1.765300f)
-#define CS_SIDE_88200_B2                       0.769816f
-#define CS_SIDE_88200_SCALE                    14
+#define CS_MIDDLE_88200_A0 0.233846f
+#define CS_MIDDLE_88200_A1 (-0.232657f)
+#define CS_MIDDLE_88200_A2 0.000000f
+#define CS_MIDDLE_88200_B1 (-0.992747f)
+#define CS_MIDDLE_88200_B2 0.000000f
+#define CS_MIDDLE_88200_SCALE 15
+#define CS_SIDE_88200_A0 0.231541f
+#define CS_SIDE_88200_A1 (-0.289586f)
+#define CS_SIDE_88200_A2 0.058045f
+#define CS_SIDE_88200_B1 (-1.765300f)
+#define CS_SIDE_88200_B2 0.769816f
+#define CS_SIDE_88200_SCALE 14
 
 /* 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_A2                     0.000000
-#define CS_MIDDLE_96000_B1                    (-0.993334)
-#define CS_MIDDLE_96000_B2                     0.000000
-#define CS_MIDDLE_96000_SCALE                        15
+#define CS_MIDDLE_96000_A0 0.235532
+#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_B2 0.000000
+#define CS_MIDDLE_96000_SCALE 15
 /* Coefficients calculated using tf2ss and ss2tf functions based on
  * coefficients available for 48000Hz sampling frequency
  */
-#define CS_SIDE_96000_A0                     0.224326f
-#define CS_SIDE_96000_A1                     (-0.294937f)
-#define CS_SIDE_96000_A2                     0.070611f
-#define CS_SIDE_96000_B1                     (-1.792166f)
-#define CS_SIDE_96000_B2                     0.795830f
-#define CS_SIDE_96000_SCALE                  14
+#define CS_SIDE_96000_A0 0.224326f
+#define CS_SIDE_96000_A1 (-0.294937f)
+#define CS_SIDE_96000_A2 0.070611f
+#define CS_SIDE_96000_B1 (-1.792166f)
+#define CS_SIDE_96000_B2 0.795830f
+#define CS_SIDE_96000_SCALE 14
 
 /* Stereo Enhancer coefficients for 176400Hz sample rate.
  * The filter coefficients are obtained by carrying out
  * state-space analysis using the coefficients available
  * for 44100Hz.
  */
-#define CS_MIDDLE_176400_A0                     0.233973f
-#define CS_MIDDLE_176400_A1                     (-0.233378f)
-#define CS_MIDDLE_176400_A2                     0.000000f
-#define CS_MIDDLE_176400_B1                     (-0.996367f)
-#define CS_MIDDLE_176400_B2                     0.000000f
-#define CS_MIDDLE_176400_SCALE                  15
-#define CS_SIDE_176400_A0                       0.199836f
-#define CS_SIDE_176400_A1                       (-0.307544f)
-#define CS_SIDE_176400_A2                       0.107708f
-#define CS_SIDE_176400_B1                       (-1.876572f)
-#define CS_SIDE_176400_B2                       0.877771f
-#define CS_SIDE_176400_SCALE                    14
+#define CS_MIDDLE_176400_A0 0.233973f
+#define CS_MIDDLE_176400_A1 (-0.233378f)
+#define CS_MIDDLE_176400_A2 0.000000f
+#define CS_MIDDLE_176400_B1 (-0.996367f)
+#define CS_MIDDLE_176400_B2 0.000000f
+#define CS_MIDDLE_176400_SCALE 15
+#define CS_SIDE_176400_A0 0.199836f
+#define CS_SIDE_176400_A1 (-0.307544f)
+#define CS_SIDE_176400_A2 0.107708f
+#define CS_SIDE_176400_B1 (-1.876572f)
+#define CS_SIDE_176400_B2 0.877771f
+#define CS_SIDE_176400_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_A2                     0.000000
-#define CS_MIDDLE_192000_B1                    (-0.996661)
-#define CS_MIDDLE_192000_B2                     0.000000
-#define CS_MIDDLE_192000_SCALE                        15
+#define CS_MIDDLE_192000_A0 0.241219
+#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_B2 0.000000
+#define CS_MIDDLE_192000_SCALE 15
 /* Coefficients calculated using tf2ss and ss2tf functions based on
  * coefficients available for 48000Hz sampling frequency
  */
-#define CS_SIDE_192000_A0                    0.196039f
-#define CS_SIDE_192000_A1                    (-0.311027f)
-#define CS_SIDE_192000_A2                    0.114988f
-#define CS_SIDE_192000_B1                    (-1.891380f)
-#define CS_SIDE_192000_B2                    0.8923460f
-#define CS_SIDE_192000_SCALE                 14
+#define CS_SIDE_192000_A0 0.196039f
+#define CS_SIDE_192000_A1 (-0.311027f)
+#define CS_SIDE_192000_A2 0.114988f
+#define CS_SIDE_192000_B1 (-1.891380f)
+#define CS_SIDE_192000_B2 0.8923460f
+#define CS_SIDE_192000_SCALE 14
 
 /************************************************************************************/
 /*                                                                                  */
@@ -227,133 +227,133 @@
 /************************************************************************************/
 
 /* Reverb delay settings in samples */
-#define LVCS_STEREODELAY_CS_8KHZ                     93         /* Sample rate 8kS/s */
-#define LVCS_STEREODELAY_CS_11KHZ                   128         /* Sample rate 11kS/s */
-#define LVCS_STEREODELAY_CS_12KHZ                   139         /* Sample rate 12kS/s */
-#define LVCS_STEREODELAY_CS_16KHZ                   186         /* Sample rate 16kS/s */
-#define LVCS_STEREODELAY_CS_22KHZ                   256         /* Sample rate 22kS/s */
-#define LVCS_STEREODELAY_CS_24KHZ                   279         /* Sample rate 24kS/s */
-#define LVCS_STEREODELAY_CS_32KHZ                   372         /* Sample rate 32kS/s */
-#define LVCS_STEREODELAY_CS_44KHZ                   512         /* Sample rate 44kS/s */
-#define LVCS_STEREODELAY_CS_48KHZ                   557         /* Sample rate 48kS/s */
-#define LVCS_STEREODELAY_CS_88KHZ                   1024        /* Sample rate 88.2kS/s */
-#define LVCS_STEREODELAY_CS_96KHZ                   1115        /* Sample rate 96kS/s */
-#define LVCS_STEREODELAY_CS_176KHZ                  2048        /* Sample rate 176.4kS/s */
-#define LVCS_STEREODELAY_CS_192KHZ                  2229        /* Sample rate 196kS/s */
-#define LVCS_STEREODELAY_CS_MAX_VAL                 LVCS_STEREODELAY_CS_192KHZ
+#define LVCS_STEREODELAY_CS_8KHZ 93     /* Sample rate 8kS/s */
+#define LVCS_STEREODELAY_CS_11KHZ 128   /* Sample rate 11kS/s */
+#define LVCS_STEREODELAY_CS_12KHZ 139   /* Sample rate 12kS/s */
+#define LVCS_STEREODELAY_CS_16KHZ 186   /* Sample rate 16kS/s */
+#define LVCS_STEREODELAY_CS_22KHZ 256   /* Sample rate 22kS/s */
+#define LVCS_STEREODELAY_CS_24KHZ 279   /* Sample rate 24kS/s */
+#define LVCS_STEREODELAY_CS_32KHZ 372   /* Sample rate 32kS/s */
+#define LVCS_STEREODELAY_CS_44KHZ 512   /* Sample rate 44kS/s */
+#define LVCS_STEREODELAY_CS_48KHZ 557   /* Sample rate 48kS/s */
+#define LVCS_STEREODELAY_CS_88KHZ 1024  /* Sample rate 88.2kS/s */
+#define LVCS_STEREODELAY_CS_96KHZ 1115  /* Sample rate 96kS/s */
+#define LVCS_STEREODELAY_CS_176KHZ 2048 /* Sample rate 176.4kS/s */
+#define LVCS_STEREODELAY_CS_192KHZ 2229 /* Sample rate 196kS/s */
+#define LVCS_STEREODELAY_CS_MAX_VAL LVCS_STEREODELAY_CS_192KHZ
 
 /* 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_A2                          0.000000
-#define CS_REVERB_8000_B1                         (-0.668179)
-#define CS_REVERB_8000_B2                          0.000000
-#define CS_REVERB_8000_SCALE                         15
+#define CS_REVERB_8000_A0 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_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_A2                     0.000000
-#define CS_REVERB_11025_B1                    (-0.749096)
-#define CS_REVERB_11025_B2                     0.000000
-#define CS_REVERB_11025_SCALE                  15
+#define CS_REVERB_11025_A0 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_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_A2                   0.000000
-#define CS_REVERB_12000_B1                  (-0.767327)
-#define CS_REVERB_12000_B2                   0.000000
-#define CS_REVERB_12000_SCALE                15
+#define CS_REVERB_12000_A0 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_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_A2                      0.000000
-#define CS_REVERB_16000_B1                     (-0.820679)
-#define CS_REVERB_16000_B2                      0.000000
-#define CS_REVERB_16000_SCALE                        15
+#define CS_REVERB_16000_A0 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_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_SCALE                        15
+#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_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_SCALE                        15
+#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_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_B2                      0.049127
-#define CS_REVERB_32000_SCALE                        15
+#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_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_B2                         0.256529
-#define CS_REVERB_44100_SCALE                        14
+#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_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_B2                       0.303347
-#define CS_REVERB_48000_SCALE                        14
+#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_B2 0.303347
+#define CS_REVERB_48000_SCALE 14
 
 /* Reverb coefficients for 88200Hz sample rate, scaled with 0.8 */
 /* Band pass filter with fc1=500 and fc2=8000 */
-#define CS_REVERB_88200_A0                       0.171901f
-#define CS_REVERB_88200_A1                       0.000000f
-#define CS_REVERB_88200_A2                      (-0.171901f)
-#define CS_REVERB_88200_B1                      (-1.553948f)
-#define CS_REVERB_88200_B2                      (0.570248f)
-#define CS_REVERB_88200_SCALE                      14
+#define CS_REVERB_88200_A0 0.171901f
+#define CS_REVERB_88200_A1 0.000000f
+#define CS_REVERB_88200_A2 (-0.171901f)
+#define CS_REVERB_88200_B1 (-1.553948f)
+#define CS_REVERB_88200_B2 (0.570248f)
+#define CS_REVERB_88200_SCALE 14
 /* Reverb coefficients for 96000Hz sample rate, scaled with 0.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_B2                       0.599377
-#define CS_REVERB_96000_SCALE                        14
+#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_B2 0.599377
+#define CS_REVERB_96000_SCALE 14
 
 /* Reverb coefficients for 176400Hz sample rate, scaled with 0.8 */
 /* Band pass filter with fc1=500 and fc2=8000 */
-#define CS_REVERB_176400_A0                       0.094763f
-#define CS_REVERB_176400_A1                       0.000000f
-#define CS_REVERB_176400_A2                      (-0.094763f)
-#define CS_REVERB_176400_B1                      (-1.758593f)
-#define CS_REVERB_176400_B2                      (0.763091f)
-#define CS_REVERB_176400_SCALE                      14
+#define CS_REVERB_176400_A0 0.094763f
+#define CS_REVERB_176400_A1 0.000000f
+#define CS_REVERB_176400_A2 (-0.094763f)
+#define CS_REVERB_176400_B1 (-1.758593f)
+#define CS_REVERB_176400_B2 (0.763091f)
+#define CS_REVERB_176400_SCALE 14
 /* Reverb coefficients for 192000Hz sample rate, scaled with 0.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_B2                       0.7804076
-#define CS_REVERB_192000_SCALE                        14
+#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_B2 0.7804076
+#define CS_REVERB_192000_SCALE 14
 
 /* Reverb Gain Settings */
-#define LVCS_HEADPHONE_DELAYGAIN               0.800000         /* Algorithm delay path gain */
-#define LVCS_HEADPHONE_OUTPUTGAIN              1.000000         /* Algorithm output gain */
-#define LVCS_HEADPHONE_PROCGAIN                   18403         /* Processed path gain */
-#define LVCS_HEADPHONE_UNPROCGAIN                 18403         /* Unprocessed path gain */
-#define LVCS_HEADPHONE_GAINCORRECT             1.009343         /* Delay mixer gain correction */
+#define LVCS_HEADPHONE_DELAYGAIN 0.800000   /* Algorithm delay path gain */
+#define LVCS_HEADPHONE_OUTPUTGAIN 1.000000  /* Algorithm output gain */
+#define LVCS_HEADPHONE_PROCGAIN 18403       /* Processed path gain */
+#define LVCS_HEADPHONE_UNPROCGAIN 18403     /* Unprocessed path gain */
+#define LVCS_HEADPHONE_GAINCORRECT 1.009343 /* Delay mixer gain correction */
 
 /************************************************************************************/
 /*                                                                                  */
@@ -363,205 +363,204 @@
 
 /* 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_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_SCALE                    15
+#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_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_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_B1                    0.024541
-#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_SCALE                   15
+#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_B1 0.024541
+#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_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_SCALE                     14
-#define CSEX_EQUALISER_12000_A0                 1.007095
-#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_SCALE                   14
+#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_SCALE 14
+#define CSEX_EQUALISER_12000_A0 1.007095
+#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_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_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_SCALE                   14
+#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_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_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_A2                   0.039922
-#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_A2                   0.167462
-#define CSEX_EQUALISER_22050_B1                  (-0.614219)
-#define CSEX_EQUALISER_22050_B2                  (-0.345384)
-#define CSEX_EQUALISER_22050_SCALE                   14
+#define CS_EQUALISER_22050_A0 1.388605
+#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_SCALE 14
+#define CSEX_EQUALISER_22050_A0 1.272910
+#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_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_A2                    0.151410
-#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_A2                  0.240489
-#define CSEX_EQUALISER_24000_B1                 (-0.669303)
-#define CSEX_EQUALISER_24000_B2                 (-0.294984)
-#define CSEX_EQUALISER_24000_SCALE                   14
+#define CS_EQUALISER_24000_A0 1.409832
+#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_SCALE 14
+#define CSEX_EQUALISER_24000_A0 1.299198
+#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_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_A2                     0.389741
-#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_A2                  0.526431
-#define CSEX_EQUALISER_32000_B1                 (-0.445939)
-#define CSEX_EQUALISER_32000_B2                 (-0.522446)
-#define CSEX_EQUALISER_32000_SCALE                   13
+#define CS_EQUALISER_32000_A0 1.560988
+#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_SCALE 14
+#define CSEX_EQUALISER_32000_A0 1.785049
+#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_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_A2                  0.688829
-#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_A2                   0.904535
-#define CSEX_EQUALISER_44100_B1                  (-0.593308)
-#define CSEX_EQUALISER_44100_B2                  (-0.385816)
-#define CSEX_EQUALISER_44100_SCALE                   13
+#define CS_EQUALISER_44100_A0 1.623993
+#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_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_A2 0.904535
+#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_A2                    0.759910
-#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_A2                  1.010417
-#define CSEX_EQUALISER_48000_B1                 (-0.634021)
-#define CSEX_EQUALISER_48000_B2                 (-0.347332)
-#define CSEX_EQUALISER_48000_SCALE                   13
+#define CS_EQUALISER_48000_A0 1.641177
+#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_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_A2 1.010417
+#define CSEX_EQUALISER_48000_B1 (-0.634021)
+#define CSEX_EQUALISER_48000_B2 (-0.347332)
+#define CSEX_EQUALISER_48000_SCALE 13
 
 /* Equaliser coefficients for 88200Hz sample rate.
  * The filter coefficients are obtained by carrying out
  * state-space analysis using the coefficients available
  * for 44100Hz.
  */
-#define CS_EQUALISER_88200_A0                   1.771899f
-#define CS_EQUALISER_88200_A1                   (-2.930762f)
-#define CS_EQUALISER_88200_A2                   1.172175f
-#define CS_EQUALISER_88200_B1                   (-1.438349f)
-#define CS_EQUALISER_88200_B2                   0.442520f
-#define CS_EQUALISER_88200_SCALE                13
-#define CSEX_EQUALISER_88200_A0                 2.675241f
-#define CSEX_EQUALISER_88200_A1                 (-4.466154f)
-#define CSEX_EQUALISER_88200_A2                 1.810305f
-#define CSEX_EQUALISER_88200_B1                 (-0.925350f)
-#define CSEX_EQUALISER_88200_B2                 (-0.066616f)
-#define CSEX_EQUALISER_88200_SCALE              13
+#define CS_EQUALISER_88200_A0 1.771899f
+#define CS_EQUALISER_88200_A1 (-2.930762f)
+#define CS_EQUALISER_88200_A2 1.172175f
+#define CS_EQUALISER_88200_B1 (-1.438349f)
+#define CS_EQUALISER_88200_B2 0.442520f
+#define CS_EQUALISER_88200_SCALE 13
+#define CSEX_EQUALISER_88200_A0 2.675241f
+#define CSEX_EQUALISER_88200_A1 (-4.466154f)
+#define CSEX_EQUALISER_88200_A2 1.810305f
+#define CSEX_EQUALISER_88200_B1 (-0.925350f)
+#define CSEX_EQUALISER_88200_B2 (-0.066616f)
+#define CSEX_EQUALISER_88200_SCALE 13
 
-#define CS_EQUALISER_96000_A0                    1.784497
-#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_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_A2                  1.9317
-#define CSEX_EQUALISER_96000_B1                 (-0.971718)
-#define CSEX_EQUALISER_96000_B2                 (-0.021216)
-#define CSEX_EQUALISER_96000_SCALE                   13
+#define CS_EQUALISER_96000_A0 1.784497
+#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_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_A2 1.9317
+#define CSEX_EQUALISER_96000_B1 (-0.971718)
+#define CSEX_EQUALISER_96000_B2 (-0.021216)
+#define CSEX_EQUALISER_96000_SCALE 13
 /* Equaliser coefficients for 176400Hz sample rate.
  * The filter coefficients are obtained by carrying out
  * state-space analysis using the coefficients available
  * for 44100Hz.
  */
-#define CS_EQUALISER_176400_A0                  1.883440f
-#define CS_EQUALISER_176400_A1                  (-3.414272f)
-#define CS_EQUALISER_176400_A2                  1.534702f
-#define CS_EQUALISER_176400_B1                  (-1.674614f)
-#define CS_EQUALISER_176400_B2                  0.675827f
-#define CS_EQUALISER_176400_SCALE               13
-#define CSEX_EQUALISER_176400_A0                3.355068f
-#define CSEX_EQUALISER_176400_A1                (-6.112578f)
-#define CSEX_EQUALISER_176400_A2                2.764135f
-#define CSEX_EQUALISER_176400_B1                (-1.268533f)
-#define CSEX_EQUALISER_176400_B2                0.271277f
-#define CSEX_EQUALISER_176400_SCALE             13
+#define CS_EQUALISER_176400_A0 1.883440f
+#define CS_EQUALISER_176400_A1 (-3.414272f)
+#define CS_EQUALISER_176400_A2 1.534702f
+#define CS_EQUALISER_176400_B1 (-1.674614f)
+#define CS_EQUALISER_176400_B2 0.675827f
+#define CS_EQUALISER_176400_SCALE 13
+#define CSEX_EQUALISER_176400_A0 3.355068f
+#define CSEX_EQUALISER_176400_A1 (-6.112578f)
+#define CSEX_EQUALISER_176400_A2 2.764135f
+#define CSEX_EQUALISER_176400_B1 (-1.268533f)
+#define CSEX_EQUALISER_176400_B2 0.271277f
+#define CSEX_EQUALISER_176400_SCALE 13
 
-#define CS_EQUALISER_192000_A0                    1.889582
-#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_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_A2                  2.8720
-#define CSEX_EQUALISER_192000_B1                 (-1.31074)
-#define CSEX_EQUALISER_192000_B2                 0.31312
-#define CSEX_EQUALISER_192000_SCALE                   13
+#define CS_EQUALISER_192000_A0 1.889582
+#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_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_A2 2.8720
+#define CSEX_EQUALISER_192000_B1 (-1.31074)
+#define CSEX_EQUALISER_192000_B2 0.31312
+#define CSEX_EQUALISER_192000_SCALE 13
 
-#define LVCS_HEADPHONE_SHIFT                          2              /* Output Shift */
-#define LVCS_HEADPHONE_SHIFTLOSS                  0.8477735          /* Output Shift loss */
-#define LVCS_HEADPHONE_GAIN                       0.2087465          /* Unprocessed path gain */
-#define LVCS_EX_HEADPHONE_SHIFT                       3              /* EX Output Shift */
-#define LVCS_EX_HEADPHONE_SHIFTLOSS               0.569225           /* EX Output Shift loss */
-#define LVCS_EX_HEADPHONE_GAIN                    0.07794425         /* EX Unprocessed path gain */
+#define LVCS_HEADPHONE_SHIFT 2               /* Output Shift */
+#define LVCS_HEADPHONE_SHIFTLOSS 0.8477735   /* Output Shift loss */
+#define LVCS_HEADPHONE_GAIN 0.2087465        /* Unprocessed path gain */
+#define LVCS_EX_HEADPHONE_SHIFT 3            /* EX Output Shift */
+#define LVCS_EX_HEADPHONE_SHIFTLOSS 0.569225 /* EX Output Shift loss */
+#define LVCS_EX_HEADPHONE_GAIN 0.07794425    /* EX Unprocessed path gain */
 #endif
-
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Init.cpp b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Init.cpp
index 630ecf7..dd1baf3 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Init.cpp
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Init.cpp
@@ -20,99 +20,11 @@
 /*  Includes                                                                        */
 /*                                                                                  */
 /************************************************************************************/
-
+#include <stdlib.h>
 #include "LVCS.h"
 #include "LVCS_Private.h"
 #include "LVCS_Tables.h"
 
-/****************************************************************************************/
-/*                                                                                      */
-/* FUNCTION:                LVCS_Memory                                                 */
-/*                                                                                      */
-/* DESCRIPTION:                                                                         */
-/*  This function is used for memory allocation and free. It can be called in           */
-/*  two ways:                                                                           */
-/*                                                                                      */
-/*      hInstance = NULL                Returns the memory requirements                 */
-/*      hInstance = Instance handle     Returns the memory requirements and             */
-/*                                      allocated base addresses for the instance       */
-/*                                                                                      */
-/*  When this function is called for memory allocation (hInstance=NULL) it is           */
-/*  passed the default capabilities.                                                    */
-/*                                                                                      */
-/*  When called for memory allocation the memory base address pointers are NULL on      */
-/*  return.                                                                             */
-/*                                                                                      */
-/*  When the function is called for free (hInstance = Instance Handle) the              */
-/*  capabilities are ignored and the memory table returns the allocated memory and      */
-/*  base addresses used during initialisation.                                          */
-/*                                                                                      */
-/* PARAMETERS:                                                                          */
-/*  hInstance               Instance Handle                                             */
-/*  pMemoryTable            Pointer to an empty memory definition table                 */
-/*  pCapabilities           Pointer to the default capabilites                          */
-/*                                                                                      */
-/* RETURNS:                                                                             */
-/*  LVCS_Success            Succeeded                                                   */
-/*                                                                                      */
-/* NOTES:                                                                               */
-/*  1.  This function may be interrupted by the LVCS_Process function                   */
-/*                                                                                      */
-/****************************************************************************************/
-
-LVCS_ReturnStatus_en LVCS_Memory(LVCS_Handle_t          hInstance,
-                                 LVCS_MemTab_t          *pMemoryTable,
-                                 LVCS_Capabilities_t    *pCapabilities)
-{
-
-    LVM_UINT32          ScratchSize;
-    LVCS_Instance_t     *pInstance = (LVCS_Instance_t *)hInstance;
-
-    /*
-     * Fill in the memory table
-     */
-    if (hInstance == LVM_NULL)
-    {
-        /*
-         * Instance memory
-         */
-        pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_SLOW_DATA].Size         = (LVM_UINT32)sizeof(LVCS_Instance_t);
-        pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_SLOW_DATA].Type         = LVCS_PERSISTENT;
-        pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_SLOW_DATA].pBaseAddress = LVM_NULL;
-
-        /*
-         * Data memory
-         */
-        pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_FAST_DATA].Size         = (LVM_UINT32)sizeof(LVCS_Data_t);
-        pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_FAST_DATA].Type         = LVCS_DATA;
-        pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_FAST_DATA].pBaseAddress = LVM_NULL;
-
-        /*
-         * Coefficient memory
-         */
-        pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].Size         = (LVM_UINT32)sizeof(LVCS_Coefficient_t);
-        pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].Type         = LVCS_COEFFICIENT;
-        pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].pBaseAddress = LVM_NULL;
-
-        /*
-         * Scratch memory
-         */
-        /* Inplace processing */
-        ScratchSize = (LVM_UINT32) \
-                        (LVCS_SCRATCHBUFFERS * sizeof(LVM_FLOAT) * pCapabilities->MaxBlockSize);
-        pMemoryTable->Region[LVCS_MEMREGION_TEMPORARY_FAST].Size         = ScratchSize;
-        pMemoryTable->Region[LVCS_MEMREGION_TEMPORARY_FAST].Type         = LVCS_SCRATCH;
-        pMemoryTable->Region[LVCS_MEMREGION_TEMPORARY_FAST].pBaseAddress = LVM_NULL;
-    }
-    else
-    {
-        /* Read back memory allocation table */
-        *pMemoryTable = pInstance->MemoryTable;
-    }
-
-    return(LVCS_SUCCESS);
-}
-
 /************************************************************************************/
 /*                                                                                  */
 /* FUNCTION:                LVCS_Init                                               */
@@ -120,91 +32,95 @@
 /* DESCRIPTION:                                                                     */
 /*  Create and initialisation function for the Concert Sound module                 */
 /*                                                                                  */
-/*  This function can be used to create an algorithm instance by calling with       */
-/*  hInstance set to LVM_NULL. In this case the algorithm returns the new instance  */
-/*  handle.                                                                         */
-/*                                                                                  */
-/*  This function can be used to force a full re-initialisation of the algorithm    */
-/*  by calling with hInstance = Instance Handle. In this case the memory table      */
-/*  should be correct for the instance, this can be ensured by calling the function */
-/*  LVCS_Memory before calling this function.                                       */
-/*                                                                                  */
 /* PARAMETERS:                                                                      */
-/*  hInstance               Instance handle                                         */
-/*  pMemoryTable            Pointer to the memory definition table                  */
+/*  phInstance              Pointer to instance handle                              */
 /*  pCapabilities           Pointer to the capabilities structure                   */
+/*  pScratch                Pointer to scratch buffer                               */
 /*                                                                                  */
 /* RETURNS:                                                                         */
 /*  LVCS_Success            Initialisation succeeded                                */
+/*  LVDBE_NULLADDRESS       One or more memory has a NULL pointer - malloc failure  */
 /*                                                                                  */
 /* NOTES:                                                                           */
-/*  1.  The instance handle is the pointer to the base address of the first memory  */
-/*      region.                                                                     */
-/*  2.  This function must not be interrupted by the LVCS_Process function          */
-/*  3.  This function must be called with the same capabilities as used for the     */
-/*      call to the memory function                                                 */
+/*  1.  This function must not be interrupted by the LVCS_Process function          */
 /*                                                                                  */
 /************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_Init(LVCS_Handle_t         *phInstance,
-                               LVCS_MemTab_t         *pMemoryTable,
-                               LVCS_Capabilities_t   *pCapabilities)
-{
-
-    LVCS_Instance_t                 *pInstance;
-    LVCS_VolCorrect_t               *pLVCS_VolCorrectTable;
+LVCS_ReturnStatus_en LVCS_Init(LVCS_Handle_t* phInstance, LVCS_Capabilities_t* pCapabilities,
+                               void* pScratch) {
+    LVCS_Instance_t* pInstance;
+    LVCS_VolCorrect_t* pLVCS_VolCorrectTable;
 
     /*
-     * Set the instance handle if not already initialised
+     * Create the instance handle if not already initialised
      */
-    if (*phInstance == LVM_NULL)
-    {
-        *phInstance = (LVCS_Handle_t)pMemoryTable->Region[LVCS_MEMREGION_PERSISTENT_SLOW_DATA].pBaseAddress;
+    if (*phInstance == LVM_NULL) {
+        *phInstance = new LVCS_Instance_t{};
     }
-    pInstance =(LVCS_Instance_t  *)*phInstance;
+    pInstance = (LVCS_Instance_t*)*phInstance;
 
     /*
      * Save the capabilities in the instance structure
      */
     pInstance->Capabilities = *pCapabilities;
 
-    /*
-     * Save the memory table in the instance structure
-     */
-    pInstance->MemoryTable = *pMemoryTable;
+    pInstance->pScratch = pScratch;
 
     /*
      * Set all initial parameters to invalid to force a full initialisation
      */
-    pInstance->Params.OperatingMode  = LVCS_OFF;
-    pInstance->Params.SpeakerType    = LVCS_SPEAKERTYPE_MAX;
-    pInstance->OutputDevice          = LVCS_HEADPHONE;
-    pInstance->Params.SourceFormat   = LVCS_SOURCEMAX;
+    pInstance->Params.OperatingMode = LVCS_OFF;
+    pInstance->Params.SpeakerType = LVCS_SPEAKERTYPE_MAX;
+    pInstance->OutputDevice = LVCS_HEADPHONE;
+    pInstance->Params.SourceFormat = LVCS_SOURCEMAX;
     pInstance->Params.CompressorMode = LVM_MODE_OFF;
-    pInstance->Params.SampleRate     = LVM_FS_INVALID;
-    pInstance->Params.EffectLevel    = 0;
-    pInstance->Params.ReverbLevel    = (LVM_UINT16)0x8000;
-    pLVCS_VolCorrectTable            = (LVCS_VolCorrect_t*)&LVCS_VolCorrectTable[0];
-    pInstance->VolCorrect            = pLVCS_VolCorrectTable[0];
-    pInstance->TransitionGain        = 0;
+    pInstance->Params.SampleRate = LVM_FS_INVALID;
+    pInstance->Params.EffectLevel = 0;
+    pInstance->Params.ReverbLevel = (LVM_UINT16)0x8000;
+    pLVCS_VolCorrectTable = (LVCS_VolCorrect_t*)&LVCS_VolCorrectTable[0];
+    pInstance->VolCorrect = pLVCS_VolCorrectTable[0];
+    pInstance->TransitionGain = 0;
 
     /* These current and target values are intialized again in LVCS_Control.c */
-    LVC_Mixer_Init(&pInstance->BypassMix.Mixer_Instance.MixerStream[0],0,0);
+    LVC_Mixer_Init(&pInstance->BypassMix.Mixer_Instance.MixerStream[0], 0, 0);
     /* These current and target values are intialized again in LVCS_Control.c */
-    LVC_Mixer_Init(&pInstance->BypassMix.Mixer_Instance.MixerStream[1],0,0);
+    LVC_Mixer_Init(&pInstance->BypassMix.Mixer_Instance.MixerStream[1], 0, 0);
 
     /*
      * Initialise the bypass variables
      */
-    pInstance->MSTarget0=0;
-    pInstance->MSTarget1=0;
-    pInstance->bInOperatingModeTransition          = LVM_FALSE;
-    pInstance->bTimerDone                        = LVM_FALSE;
-    pInstance->TimerParams.CallBackParam         = 0;
-    pInstance->TimerParams.pCallBack             = LVCS_TimerCallBack;
-    pInstance->TimerParams.pCallbackInstance     = pInstance;
-    pInstance->TimerParams.pCallBackParams       = LVM_NULL;
+    pInstance->MSTarget0 = 0;
+    pInstance->MSTarget1 = 0;
+    pInstance->bInOperatingModeTransition = LVM_FALSE;
+    pInstance->bTimerDone = LVM_FALSE;
+    pInstance->TimerParams.CallBackParam = 0;
+    pInstance->TimerParams.pCallBack = LVCS_TimerCallBack;
+    pInstance->TimerParams.pCallbackInstance = pInstance;
+    pInstance->TimerParams.pCallBackParams = LVM_NULL;
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
 
+/************************************************************************************/
+/*                                                                                  */
+/* FUNCTION:                LVCS_DeInit                                             */
+/*                                                                                  */
+/* DESCRIPTION:                                                                     */
+/*  Free memories created during the LVCS_Init call including instance handle       */
+/*                                                                                  */
+/* PARAMETERS:                                                                      */
+/*  phInstance              Pointer to instance handle                              */
+/*                                                                                  */
+/* NOTES:                                                                           */
+/*  1.  This function must not be interrupted by the LVCS_Process function          */
+/*                                                                                  */
+/************************************************************************************/
+void LVCS_DeInit(LVCS_Handle_t* phInstance) {
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)*phInstance;
+    if (pInstance == LVM_NULL) {
+        return;
+    }
+    delete pInstance;
+    *phInstance = LVM_NULL;
+    return;
+}
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Private.h b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Private.h
index 154ea55..58e21bd 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Private.h
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Private.h
@@ -33,11 +33,12 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#include "LVCS.h"                               /* Calling or Application layer definitions */
-#include "LVCS_StereoEnhancer.h"                /* Stereo enhancer module definitions */
-#include "LVCS_ReverbGenerator.h"               /* Reverberation module definitions */
-#include "LVCS_Equaliser.h"                     /* Equaliser module definitions */
-#include "LVCS_BypassMix.h"                     /* Bypass Mixer module definitions */
+#include <audio_utils/BiquadFilter.h>
+#include "LVCS.h"                 /* Calling or Application layer definitions */
+#include "LVCS_StereoEnhancer.h"  /* Stereo enhancer module definitions */
+#include "LVCS_ReverbGenerator.h" /* Reverberation module definitions */
+#include "LVCS_Equaliser.h"       /* Equaliser module definitions */
+#include "LVCS_BypassMix.h"       /* Bypass Mixer module definitions */
 #include "LVM_Timer.h"
 
 /************************************************************************************/
@@ -47,35 +48,29 @@
 /************************************************************************************/
 
 /* Configuration switch controls */
-#define LVCS_STEREOENHANCESWITCH    0x0001      /* Stereo enhancement enable control */
-#define LVCS_REVERBSWITCH           0x0002      /* Reverberation enable control */
-#define LVCS_EQUALISERSWITCH        0x0004      /* Equaliser enable control */
-#define LVCS_BYPASSMIXSWITCH        0x0008      /* Bypass mixer enable control */
-#define LVCS_COMPGAINFRAME          64          /* Compressor gain update interval */
+#define LVCS_STEREOENHANCESWITCH 0x0001 /* Stereo enhancement enable control */
+#define LVCS_REVERBSWITCH 0x0002        /* Reverberation enable control */
+#define LVCS_EQUALISERSWITCH 0x0004     /* Equaliser enable control */
+#define LVCS_BYPASSMIXSWITCH 0x0008     /* Bypass mixer enable control */
+#define LVCS_COMPGAINFRAME 64           /* Compressor gain update interval */
 
 /* Memory */
-#ifdef SUPPORT_MC
-#define LVCS_SCRATCHBUFFERS              8      /* Number of buffers required for inplace processing */
-#else
-#define LVCS_SCRATCHBUFFERS              6      /* Number of buffers required for inplace processing */
-#endif
-#ifdef SUPPORT_MC
+#define LVCS_SCRATCHBUFFERS 8 /* Number of buffers required for inplace processing */
 /*
  * The Concert Surround module applies processing only on the first two
  * channels of a multichannel input. The data of first two channels is copied
  * from the multichannel input into scratch buffer. The buffers added here
  * are used for this purpose
  */
-#define LVCS_MC_SCRATCHBUFFERS           2
-#endif
+#define LVCS_MC_SCRATCHBUFFERS 2
 
 /* General */
-#define LVCS_INVALID                0xFFFF      /* Invalid init parameter */
-#define LVCS_BYPASS_MIXER_TC        100         /* Bypass mixer time */
+#define LVCS_INVALID 0xFFFF      /* Invalid init parameter */
+#define LVCS_BYPASS_MIXER_TC 100 /* Bypass mixer time */
 
 /* Access to external coefficients table */
-#define LVCS_NR_OF_FS                    9
-#define LVCS_NR_OF_CHAN_CFG              2
+#define LVCS_NR_OF_FS 9
+#define LVCS_NR_OF_CHAN_CFG 2
 
 /************************************************************************************/
 /*                                                                                  */
@@ -83,13 +78,9 @@
 /*                                                                                  */
 /************************************************************************************/
 
-typedef LVM_UINT16  LVCS_Configuration_t;       /* Internal algorithm configuration */
+typedef LVM_UINT16 LVCS_Configuration_t; /* Internal algorithm configuration */
 
-typedef enum
-{
-    LVCS_HEADPHONE  = 0,
-    LVCS_DEVICE_MAX = LVM_MAXENUM
-} LVCS_OutputDevice_en;
+typedef enum { LVCS_HEADPHONE = 0, LVCS_DEVICE_MAX = LVM_MAXENUM } LVCS_OutputDevice_en;
 
 /************************************************************************************/
 /*                                                                                  */
@@ -98,65 +89,50 @@
 /************************************************************************************/
 
 /* Volume correction structure */
-typedef struct
-{
-    LVM_FLOAT   CompFull;                       /* Post CS compression 100% effect */
-    LVM_FLOAT   CompMin;                        /* Post CS compression 0% effect */
-    LVM_FLOAT   GainFull;                       /* CS gain correct 100% effect */
-    LVM_FLOAT   GainMin;                        /* CS gain correct 0% effect */
+typedef struct {
+    LVM_FLOAT CompFull; /* Post CS compression 100% effect */
+    LVM_FLOAT CompMin;  /* Post CS compression 0% effect */
+    LVM_FLOAT GainFull; /* CS gain correct 100% effect */
+    LVM_FLOAT GainMin;  /* CS gain correct 0% effect */
 } LVCS_VolCorrect_t;
 
 /* Instance structure */
-typedef struct
-{
+typedef struct {
     /* Public parameters */
-    LVCS_MemTab_t           MemoryTable;        /* Instance memory allocation table */
-    LVCS_Params_t           Params;             /* Instance parameters */
-    LVCS_Capabilities_t     Capabilities;       /* Initialisation capabilities */
+    LVCS_Params_t Params;             /* Instance parameters */
+    LVCS_Capabilities_t Capabilities; /* Initialisation capabilities */
 
     /* Private parameters */
-    LVCS_OutputDevice_en    OutputDevice;       /* Selected output device type */
-    LVCS_VolCorrect_t       VolCorrect;         /* Volume correction settings */
-    LVM_FLOAT               TransitionGain;     /* Transition gain */
-    LVM_FLOAT               CompressGain;       /* Last used compressor gain*/
+    LVCS_OutputDevice_en OutputDevice; /* Selected output device type */
+    LVCS_VolCorrect_t VolCorrect;      /* Volume correction settings */
+    LVM_FLOAT TransitionGain;          /* Transition gain */
+    LVM_FLOAT CompressGain;            /* Last used compressor gain*/
 
     /* Sub-block configurations */
-    LVCS_StereoEnhancer_t   StereoEnhancer;     /* Stereo enhancer configuration */
-    LVCS_ReverbGenerator_t  Reverberation;      /* Reverberation configuration */
-    LVCS_Equaliser_t        Equaliser;          /* Equaliser configuration */
-    LVCS_BypassMix_t        BypassMix;          /* Bypass mixer configuration */
+    LVCS_StereoEnhancer_t StereoEnhancer; /* Stereo enhancer configuration */
+    LVCS_ReverbGenerator_t Reverberation; /* Reverberation configuration */
+    LVCS_BypassMix_t BypassMix;           /* Bypass mixer configuration */
 
     /* Bypass variable */
-    LVM_INT16               MSTarget0;                          /* Mixer state control variable for smooth transtion */
-    LVM_INT16               MSTarget1;                          /* Mixer state control variable for smooth transtion */
-    LVM_INT16               bInOperatingModeTransition;         /* Operating mode transition flag */
-    LVM_INT16               bTimerDone;                         /* Timer completion flag */
-    LVM_Timer_Params_t      TimerParams;                        /* Timer parameters */
-    LVM_Timer_Instance_t    TimerInstance;                      /* Timer instance */
+    LVM_INT16 MSTarget0;                  /* Mixer state control variable for smooth transition */
+    LVM_INT16 MSTarget1;                  /* Mixer state control variable for smooth transition */
+    LVM_INT16 bInOperatingModeTransition; /* Operating mode transition flag */
+    LVM_INT16 bTimerDone;                 /* Timer completion flag */
+    LVM_Timer_Params_t TimerParams;       /* Timer parameters */
+    LVM_Timer_Instance_t TimerInstance;   /* Timer instance */
+    std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            pEqBiquad; /* Biquad filter instance for Equaliser */
+    std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            pRevBiquad; /* Biquad filter instance for Reverberation */
+    std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            pSEMidBiquad; /* Biquad filter instance for Stereo enhancement mid */
+    std::unique_ptr<android::audio_utils::BiquadFilter<LVM_FLOAT>>
+            pSESideBiquad; /* Biquad filter instance for Stereo enhancement side */
+    void* pScratch;                       /* Pointer to bundle scratch buffer */
 
 } LVCS_Instance_t;
 
-/* Coefficient Structure */
-typedef struct
-{
-    Biquad_FLOAT_Instance_t       EqualiserBiquadInstance;
-    Biquad_FLOAT_Instance_t       ReverbBiquadInstance;
-    Biquad_FLOAT_Instance_t       SEBiquadInstanceMid;
-    Biquad_FLOAT_Instance_t       SEBiquadInstanceSide;
-} LVCS_Coefficient_t;
 
-/* Data Structure */
-typedef struct
-{
-    Biquad_2I_Order2_FLOAT_Taps_t EqualiserBiquadTaps;
-    Biquad_2I_Order2_FLOAT_Taps_t ReverbBiquadTaps;
-    Biquad_1I_Order1_FLOAT_Taps_t SEBiquadTapsMid;
-    Biquad_1I_Order2_FLOAT_Taps_t SEBiquadTapsSide;
-} LVCS_Data_t;
+void LVCS_TimerCallBack(void* hInstance, void* pCallBackParams, LVM_INT32 CallbackParam);
 
-void LVCS_TimerCallBack (   void* hInstance,
-                            void* pCallBackParams,
-                            LVM_INT32 CallbackParam);
-
-#endif      /* PRIVATE_H */
-
+#endif /* PRIVATE_H */
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Process.cpp b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Process.cpp
index 8e09be2..6af0f75 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Process.cpp
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Process.cpp
@@ -65,116 +65,75 @@
 /* NOTES:                                                                           */
 /*                                                                                  */
 /************************************************************************************/
-LVCS_ReturnStatus_en LVCS_Process_CS(LVCS_Handle_t              hInstance,
-                                     const LVM_FLOAT            *pInData,
-                                     LVM_FLOAT                  *pOutData,
-                                     LVM_UINT16                 NumSamples)
-{
-    const LVM_FLOAT     *pInput;
-    LVCS_Instance_t     *pInstance = (LVCS_Instance_t  *)hInstance;
-    LVM_FLOAT           *pScratch;
+LVCS_ReturnStatus_en LVCS_Process_CS(LVCS_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                     LVM_FLOAT* pOutData, LVM_UINT16 NumSamples) {
+    const LVM_FLOAT* pInput;
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
+    LVM_FLOAT* pScratch;
     LVCS_ReturnStatus_en err;
-#ifdef SUPPORT_MC
-    LVM_FLOAT           *pStIn;
-    LVM_INT32           channels = pInstance->Params.NrChannels;
+    LVM_FLOAT* pStIn;
+    LVM_INT32 channels = pInstance->Params.NrChannels;
 #define NrFrames NumSamples  // alias for clarity
 
-    /*In case of mono processing, stereo input is created from mono
-     *and stored in pInData before applying any of the effects.
-     *However we do not update the value pInstance->Params.NrChannels
-     *at this point.
-     *So to treat the pInData as stereo we are setting channels to 2
-     */
-    if (channels == 1)
-    {
-        channels = 2;
-    }
-#endif
-
-    pScratch  = (LVM_FLOAT *) \
-                  pInstance->MemoryTable.Region[LVCS_MEMREGION_TEMPORARY_FAST].pBaseAddress;
+    pScratch = (LVM_FLOAT*)pInstance->pScratch;
 
     /*
      * Check if the processing is inplace
      */
-#ifdef SUPPORT_MC
     /*
      * The pInput buffer holds the first 2 (Left, Right) channels information.
      * Hence the memory required by this buffer is 2 * NumFrames.
      * The Concert Surround module carries out processing only on L, R.
      */
     pInput = pScratch + (2 * NrFrames);
-    pStIn  = pScratch + ((LVCS_SCRATCHBUFFERS - 2) * NrFrames);
-    /* The first two channel data is extracted from the input data and
-     * copied into pInput buffer
-     */
-    Copy_Float_Mc_Stereo((LVM_FLOAT *)pInData,
-                         (LVM_FLOAT *)pInput,
-                         NrFrames,
-                         channels);
-    Copy_Float((LVM_FLOAT *)pInput,
-               (LVM_FLOAT *)pStIn,
-               (LVM_INT16)(2 * NrFrames));
-#else
-    if (pInData == pOutData)
-    {
-        /* Processing inplace */
-        pInput = pScratch + (2 * NumSamples);
-        Copy_Float((LVM_FLOAT *)pInData,           /* Source */
-                   (LVM_FLOAT *)pInput,            /* Destination */
-                   (LVM_INT16)(2 * NumSamples));     /* Left and right */
+    pStIn = pScratch + ((LVCS_SCRATCHBUFFERS - 2) * NrFrames);
+    if (channels == FCC_1) {
+        Copy_Float((LVM_FLOAT*)pInData, (LVM_FLOAT*)pInput, (LVM_INT16)NrFrames);
+        Copy_Float((LVM_FLOAT*)pInput, (LVM_FLOAT*)pStIn, (LVM_INT16)NrFrames);
+    } else {
+        /* The first two channel data is extracted from the input data and
+         * copied into pInput buffer
+         */
+        Copy_Float_Mc_Stereo((LVM_FLOAT*)pInData, (LVM_FLOAT*)pInput, NrFrames, channels);
+        Copy_Float((LVM_FLOAT*)pInput, (LVM_FLOAT*)pStIn, (LVM_INT16)(FCC_2 * NrFrames));
     }
-    else
-    {
-        /* Processing outplace */
-        pInput = pInData;
-    }
-#endif
     /*
      * Call the stereo enhancer
      */
-#ifdef SUPPORT_MC
-    err = LVCS_StereoEnhancer(hInstance,              /* Instance handle */
-                              pStIn,                  /* Pointer to the input data */
-                              pOutData,               /* Pointer to the output data */
-                              NrFrames);              /* Number of frames to process */
-#else
-    err = LVCS_StereoEnhancer(hInstance,              /* Instance handle */
-                              pInData,                    /* Pointer to the input data */
-                              pOutData,                   /* Pointer to the output data */
-                              NumSamples);                /* Number of samples to process */
-#endif
+    err = LVCS_StereoEnhancer(hInstance, /* Instance handle */
+                              pStIn,     /* Pointer to the input data */
+                              pOutData,  /* Pointer to the output data */
+                              NrFrames); /* Number of frames to process */
 
     /*
      * Call the reverb generator
      */
-    err = LVCS_ReverbGenerator(hInstance,             /* Instance handle */
-                               pOutData,                  /* Pointer to the input data */
-                               pOutData,                  /* Pointer to the output data */
-                               NumSamples);               /* Number of samples to process */
+    err = LVCS_ReverbGenerator(hInstance,   /* Instance handle */
+                               pOutData,    /* Pointer to the input data */
+                               pOutData,    /* Pointer to the output data */
+                               NumSamples); /* Number of samples to process */
 
     /*
      * Call the equaliser
      */
-    err = LVCS_Equaliser(hInstance,                   /* Instance handle */
-                         pOutData,                        /* Pointer to the input data */
-                         NumSamples);                     /* Number of samples to process */
+    err = LVCS_Equaliser(hInstance,   /* Instance handle */
+                         pOutData,    /* Pointer to the input data */
+                         NumSamples); /* Number of samples to process */
 
     /*
      * Call the bypass mixer
      */
-    err = LVCS_BypassMixer(hInstance,                 /* Instance handle */
-                           pOutData,                      /* Pointer to the processed data */
-                           pInput,                        /* Pointer to the input (unprocessed) data */
-                           pOutData,                      /* Pointer to the output data */
-                           NumSamples);                   /* Number of samples to process */
+    err = LVCS_BypassMixer(hInstance,   /* Instance handle */
+                           pOutData,    /* Pointer to the processed data */
+                           pInput,      /* Pointer to the input (unprocessed) data */
+                           pOutData,    /* Pointer to the output data */
+                           NumSamples); /* Number of samples to process */
 
-    if(err != LVCS_SUCCESS)
-    {
+    if (err != LVCS_SUCCESS) {
         return err;
     }
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
 /************************************************************************************/
 /*                                                                                  */
@@ -202,171 +161,117 @@
 /* NOTES:                                                                           */
 /*                                                                                  */
 /************************************************************************************/
-LVCS_ReturnStatus_en LVCS_Process(LVCS_Handle_t             hInstance,
-                                  const LVM_FLOAT           *pInData,
-                                  LVM_FLOAT                 *pOutData,
-                                  LVM_UINT16                NumSamples)
-{
-
-    LVCS_Instance_t *pInstance = (LVCS_Instance_t  *)hInstance;
+LVCS_ReturnStatus_en LVCS_Process(LVCS_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                  LVM_FLOAT* pOutData, LVM_UINT16 NumSamples) {
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
     LVCS_ReturnStatus_en err;
-#ifdef SUPPORT_MC
     /*Extract number of Channels info*/
     LVM_INT32 channels = pInstance->Params.NrChannels;
+    LVM_UINT16 destNumSamples = (channels == FCC_1) ? NumSamples : FCC_2 * NumSamples;
+    LVM_INT32 compGainInterval =
+            (channels == FCC_1) ? LVCS_COMPGAINFRAME : FCC_2 * LVCS_COMPGAINFRAME;
 #define NrFrames NumSamples  // alias for clarity
-    if (channels == 1)
-    {
-        channels = 2;
-    }
-#endif
     /*
      * Check the number of samples is not too large
      */
-    if (NumSamples > pInstance->Capabilities.MaxBlockSize)
-    {
-        return(LVCS_TOOMANYSAMPLES);
+    if (NumSamples > pInstance->Capabilities.MaxBlockSize) {
+        return (LVCS_TOOMANYSAMPLES);
     }
 
     /*
      * Check if the algorithm is enabled
      */
-    if (pInstance->Params.OperatingMode != LVCS_OFF)
-    {
-#ifdef SUPPORT_MC
-        LVM_FLOAT *pStereoOut;
+    if (pInstance->Params.OperatingMode != LVCS_OFF) {
+        LVM_FLOAT* pStereoOut;
         /*
          * LVCS_Process_CS uses output buffer to store intermediate outputs of StereoEnhancer,
          * Equalizer, ReverbGenerator and BypassMixer.
          * So, to avoid i/o data overlapping, when i/o buffers are common, use scratch buffer
          * to store intermediate outputs.
          */
-        if (pOutData == pInData)
-        {
-          /*
-           * Scratch memory is used in 4 chunks of (2 * NrFrames) size.
-           * First chunk of memory is used by LVCS_StereoEnhancer and LVCS_ReverbGenerator,
-           * second and fourth are used as input buffers by pInput and pStIn in LVCS_Process_CS.
-           * Hence, pStereoOut is pointed to use unused third portion of scratch memory.
-           */
-            pStereoOut = (LVM_FLOAT *) \
-                          pInstance->MemoryTable. \
-                          Region[LVCS_MEMREGION_TEMPORARY_FAST].pBaseAddress +
-                          ((LVCS_SCRATCHBUFFERS - 4) * NrFrames);
-        }
-        else
-        {
+        if (pOutData == pInData) {
+            /*
+             * Scratch memory is used in 4 chunks of (2 * NrFrames) size.
+             * First chunk of memory is used by LVCS_StereoEnhancer and LVCS_ReverbGenerator,
+             * second and fourth are used as input buffers by pInput and pStIn in LVCS_Process_CS.
+             * Hence, pStereoOut is pointed to use unused third portion of scratch memory.
+             */
+            pStereoOut = (LVM_FLOAT*)pInstance->pScratch + ((LVCS_SCRATCHBUFFERS - 4) * NrFrames);
+        } else {
             pStereoOut = pOutData;
         }
 
         /*
          * Call CS process function
          */
-            err = LVCS_Process_CS(hInstance,
-                                  pInData,
-                                  pStereoOut,
-                                  NrFrames);
-#else
-            err = LVCS_Process_CS(hInstance,
-                                  pInData,
-                                  pOutData,
-                                  NumSamples);
-#endif
+        err = LVCS_Process_CS(hInstance, pInData, pStereoOut, NrFrames);
 
         /*
          * Compress to reduce expansion effect of Concert Sound and correct volume
          * differences for difference settings. Not applied in test modes
          */
-        if ((pInstance->Params.OperatingMode == LVCS_ON)&& \
-                                        (pInstance->Params.CompressorMode == LVM_MODE_ON))
-        {
+        if ((pInstance->Params.OperatingMode == LVCS_ON) &&
+            (pInstance->Params.CompressorMode == LVM_MODE_ON)) {
             LVM_FLOAT Gain = pInstance->VolCorrect.CompMin;
             LVM_FLOAT Current1;
 
             Current1 = LVC_Mixer_GetCurrent(&pInstance->BypassMix.Mixer_Instance.MixerStream[0]);
-            Gain = (LVM_FLOAT)(  pInstance->VolCorrect.CompMin
-                               - (((LVM_FLOAT)pInstance->VolCorrect.CompMin  * (Current1)))
-                               + (((LVM_FLOAT)pInstance->VolCorrect.CompFull * (Current1))));
+            Gain = (LVM_FLOAT)(pInstance->VolCorrect.CompMin -
+                               (((LVM_FLOAT)pInstance->VolCorrect.CompMin * (Current1))) +
+                               (((LVM_FLOAT)pInstance->VolCorrect.CompFull * (Current1))));
 
-            if(NumSamples < LVCS_COMPGAINFRAME)
-            {
-#ifdef SUPPORT_MC
-                NonLinComp_Float(Gain,                    /* Compressor gain setting */
-                                 pStereoOut,
-                                 pStereoOut,
-                                 (LVM_INT32)(2 * NrFrames));
-#else
-                NonLinComp_Float(Gain,                    /* Compressor gain setting */
-                                 pOutData,
-                                 pOutData,
-                                 (LVM_INT32)(2 * NumSamples));
-#endif
-            }
-            else
-            {
-                LVM_FLOAT  GainStep;
-                LVM_FLOAT  FinalGain;
-                LVM_INT16  SampleToProcess = NumSamples;
-                LVM_FLOAT  *pOutPtr;
+            if (NumSamples < LVCS_COMPGAINFRAME) {
+                NonLinComp_Float(Gain, /* Compressor gain setting */
+                                 pStereoOut, pStereoOut, (LVM_INT32)destNumSamples);
+            } else {
+                LVM_FLOAT GainStep;
+                LVM_FLOAT FinalGain;
+                LVM_INT16 SampleToProcess = NumSamples;
+                LVM_FLOAT* pOutPtr;
 
                 /* Large changes in Gain can cause clicks in output
                    Split data into small blocks and use interpolated gain values */
 
-                GainStep = (LVM_FLOAT)(((Gain-pInstance->CompressGain) * \
-                                                LVCS_COMPGAINFRAME) / NumSamples);
+                GainStep = (LVM_FLOAT)(((Gain - pInstance->CompressGain) * LVCS_COMPGAINFRAME) /
+                                       NumSamples);
 
-                if((GainStep == 0) && (pInstance->CompressGain < Gain))
-                {
+                if ((GainStep == 0) && (pInstance->CompressGain < Gain)) {
                     GainStep = 1;
-                }
-                else
-                {
-                    if((GainStep == 0) && (pInstance->CompressGain > Gain))
-                    {
+                } else {
+                    if ((GainStep == 0) && (pInstance->CompressGain > Gain)) {
                         GainStep = -1;
                     }
                 }
 
                 FinalGain = Gain;
                 Gain = pInstance->CompressGain;
-#ifdef SUPPORT_MC
                 pOutPtr = pStereoOut;
-#else
-                pOutPtr = pOutData;
-#endif
 
-                while(SampleToProcess > 0)
-                {
+                while (SampleToProcess > 0) {
                     Gain = (LVM_FLOAT)(Gain + GainStep);
-                    if((GainStep > 0) && (FinalGain <= Gain))
-                    {
+                    if ((GainStep > 0) && (FinalGain <= Gain)) {
                         Gain = FinalGain;
                         GainStep = 0;
                     }
 
-                    if((GainStep < 0) && (FinalGain > Gain))
-                    {
+                    if ((GainStep < 0) && (FinalGain > Gain)) {
                         Gain = FinalGain;
                         GainStep = 0;
                     }
 
-                    if(SampleToProcess > LVCS_COMPGAINFRAME)
-                    {
-                        NonLinComp_Float(Gain,                    /* Compressor gain setting */
-                                         pOutPtr,
-                                         pOutPtr,
-                                         (LVM_INT32)(2 * LVCS_COMPGAINFRAME));
-                        pOutPtr += (2 * LVCS_COMPGAINFRAME);
+                    if (SampleToProcess > LVCS_COMPGAINFRAME) {
+                        NonLinComp_Float(Gain, /* Compressor gain setting */
+                                         pOutPtr, pOutPtr, compGainInterval);
+                        pOutPtr += compGainInterval;
                         SampleToProcess = (LVM_INT16)(SampleToProcess - LVCS_COMPGAINFRAME);
-                    }
-                    else
-                    {
-                        NonLinComp_Float(Gain,                    /* Compressor gain setting */
-                                         pOutPtr,
-                                         pOutPtr,
-                                         (LVM_INT32)(2 * SampleToProcess));
+                    } else {
+                        NonLinComp_Float(Gain, /* Compressor gain setting */
+                                         pOutPtr, pOutPtr,
+                                         (channels == FCC_1)
+                                                 ? (LVM_INT32)(SampleToProcess)
+                                                 : (LVM_INT32)(FCC_2 * SampleToProcess));
                         SampleToProcess = 0;
                     }
-
                 }
             }
 
@@ -374,57 +279,33 @@
             pInstance->CompressGain = Gain;
         }
 
-        if(pInstance->bInOperatingModeTransition == LVM_TRUE){
-
+        if (pInstance->bInOperatingModeTransition == LVM_TRUE) {
             /*
              * Re-init bypass mix when timer has completed
              */
             if ((pInstance->bTimerDone == LVM_TRUE) &&
-                (pInstance->BypassMix.Mixer_Instance.MixerStream[1].CallbackSet == 0))
-            {
-                err = LVCS_BypassMixInit(hInstance,
-                                         &pInstance->Params);
+                (pInstance->BypassMix.Mixer_Instance.MixerStream[1].CallbackSet == 0)) {
+                err = LVCS_BypassMixInit(hInstance, &pInstance->Params);
 
-                if(err != LVCS_SUCCESS)
-                {
+                if (err != LVCS_SUCCESS) {
                     return err;
                 }
 
-            }
-            else{
-                LVM_Timer ( &pInstance->TimerInstance,
-                            (LVM_INT16)NumSamples);
+            } else {
+                LVM_Timer(&pInstance->TimerInstance, (LVM_INT16)NumSamples);
             }
         }
-#ifdef SUPPORT_MC
-        Copy_Float_Stereo_Mc(pInData,
-                             pStereoOut,
-                             pOutData,
-                             NrFrames,
-                             channels);
-#endif
-    }
-    else
-    {
-        if (pInData != pOutData)
-        {
-#ifdef SUPPORT_MC
+        Copy_Float_Stereo_Mc(pInData, (const LVM_FLOAT*)pStereoOut, pOutData, NrFrames, channels);
+    } else {
+        if (pInData != pOutData) {
             /*
              * The algorithm is disabled so just copy the data
              */
-            Copy_Float((LVM_FLOAT *)pInData,               /* Source */
-                       (LVM_FLOAT *)pOutData,                  /* Destination */
-                       (LVM_INT16)(channels * NrFrames));    /* All Channels*/
-#else
-            /*
-             * The algorithm is disabled so just copy the data
-             */
-            Copy_Float((LVM_FLOAT *)pInData,               /* Source */
-                       (LVM_FLOAT *)pOutData,                  /* Destination */
-                       (LVM_INT16)(2 * NumSamples));             /* Left and right */
-#endif
+            Copy_Float((LVM_FLOAT*)pInData,               /* Source */
+                       (LVM_FLOAT*)pOutData,              /* Destination */
+                       (LVM_INT16)(channels * NrFrames)); /* All Channels*/
         }
     }
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_ReverbGenerator.cpp b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_ReverbGenerator.cpp
index d0e6e09..12b1dc3 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_ReverbGenerator.cpp
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_ReverbGenerator.cpp
@@ -20,7 +20,8 @@
 /*  Includes                                                                        */
 /*                                                                                  */
 /************************************************************************************/
-
+#include <system/audio.h>
+#include <stdlib.h>
 #include "LVCS.h"
 #include "LVCS_Private.h"
 #include "LVCS_ReverbGenerator.h"
@@ -57,31 +58,19 @@
 /*  2.  The numerator coefficients of the filter are negated to cause an inversion. */
 /*                                                                                  */
 /************************************************************************************/
-LVCS_ReturnStatus_en LVCS_ReverbGeneratorInit(LVCS_Handle_t     hInstance,
-                                              LVCS_Params_t     *pParams)
-{
-
-    LVM_UINT16              Delay;
-    LVM_UINT16              Offset;
-    LVCS_Instance_t         *pInstance = (LVCS_Instance_t  *)hInstance;
-    LVCS_ReverbGenerator_t  *pConfig   = (LVCS_ReverbGenerator_t *)&pInstance->Reverberation;
-    LVCS_Data_t             *pData;
-    LVCS_Coefficient_t      *pCoefficients;
-    BQ_FLOAT_Coefs_t         Coeffs;
-    const BiquadA012B12CoefsSP_t  *pReverbCoefTable;
-
-    pData = (LVCS_Data_t *) \
-                 pInstance->MemoryTable.Region[LVCS_MEMREGION_PERSISTENT_FAST_DATA].pBaseAddress;
-
-    pCoefficients = (LVCS_Coefficient_t *) \
-                 pInstance->MemoryTable.Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].pBaseAddress;
+LVCS_ReturnStatus_en LVCS_ReverbGeneratorInit(LVCS_Handle_t hInstance, LVCS_Params_t* pParams) {
+    LVM_UINT16 Delay;
+    LVM_UINT16 Offset;
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
+    LVCS_ReverbGenerator_t* pConfig = (LVCS_ReverbGenerator_t*)&pInstance->Reverberation;
+    const BiquadA012B12CoefsSP_t* pReverbCoefTable;
 
     /*
      * Initialise the delay and filters if:
      *  - the sample rate has changed
      *  - the speaker type has changed to or from the mobile speaker
      */
-    if(pInstance->Params.SampleRate != pParams->SampleRate )      /* Sample rate change test */
+    if (pInstance->Params.SampleRate != pParams->SampleRate) /* Sample rate change test */
 
     {
         /*
@@ -89,10 +78,11 @@
          */
         Delay = (LVM_UINT16)LVCS_StereoDelayCS[(LVM_UINT16)pParams->SampleRate];
 
-        pConfig->DelaySize      = (LVM_INT16)(2 * Delay);
-        pConfig->DelayOffset    = 0;
-        LoadConst_Float(0,                                            /* Value */
-                        (LVM_FLOAT *)&pConfig->StereoSamples[0],      /* Destination */
+        pConfig->DelaySize =
+                (pParams->NrChannels == FCC_1) ? (LVM_INT16)Delay : (LVM_INT16)(FCC_2 * Delay);
+        pConfig->DelayOffset = 0;
+        LoadConst_Float(0,                                      /* Value */
+                        (LVM_FLOAT*)&pConfig->StereoSamples[0], /* Destination */
                         /* Number of words */
                         (LVM_UINT16)(sizeof(pConfig->StereoSamples) / sizeof(LVM_FLOAT)));
         /*
@@ -101,47 +91,26 @@
         Offset = (LVM_UINT16)pParams->SampleRate;
         pReverbCoefTable = (BiquadA012B12CoefsSP_t*)&LVCS_ReverbCoefTable[0];
 
-        /* Convert incoming coefficients to the required format/ordering */
-        Coeffs.A0 = (LVM_FLOAT)pReverbCoefTable[Offset].A0;
-        Coeffs.A1 = (LVM_FLOAT)pReverbCoefTable[Offset].A1;
-        Coeffs.A2 = (LVM_FLOAT)pReverbCoefTable[Offset].A2;
-        Coeffs.B1 = (LVM_FLOAT)-pReverbCoefTable[Offset].B1;
-        Coeffs.B2 = (LVM_FLOAT)-pReverbCoefTable[Offset].B2;
-
-        LoadConst_Float(0,                                 /* Value */
-                        (LVM_FLOAT *)&pData->ReverbBiquadTaps, /* Destination */
-                        /* Number of words */
-                        (LVM_UINT16)(sizeof(pData->ReverbBiquadTaps) / sizeof(LVM_FLOAT)));
-
-        BQ_2I_D16F16Css_TRC_WRA_01_Init(&pCoefficients->ReverbBiquadInstance,
-                                        &pData->ReverbBiquadTaps,
-                                        &Coeffs);
-
-        /* Callbacks */
-        switch(pReverbCoefTable[Offset].Scale)
-        {
-            case 14:
-                pConfig->pBiquadCallBack  = BQ_2I_D16F16C14_TRC_WRA_01;
-                break;
-            case 15:
-                pConfig->pBiquadCallBack  = BQ_2I_D16F16C15_TRC_WRA_01;
-                break;
-        }
+        std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                pReverbCoefTable[Offset].A0, pReverbCoefTable[Offset].A1,
+                pReverbCoefTable[Offset].A2, -(pReverbCoefTable[Offset].B1),
+                -(pReverbCoefTable[Offset].B2)};
+        pInstance->pRevBiquad.reset(new android::audio_utils::BiquadFilter<LVM_FLOAT>(
+                (pParams->NrChannels == FCC_1) ? FCC_1 : FCC_2, coefs));
 
         /*
          * Setup the mixer
          */
         pConfig->ProcGain = (LVM_UINT16)(HEADPHONEGAINPROC);
-        pConfig->UnprocGain  = (LVM_UINT16)(HEADPHONEGAINUNPROC);
+        pConfig->UnprocGain = (LVM_UINT16)(HEADPHONEGAINUNPROC);
     }
 
-    if(pInstance->Params.ReverbLevel != pParams->ReverbLevel)
-    {
-        LVM_INT32   ReverbPercentage = 83886;      // 1 Percent Reverb i.e 1/100 in Q 23 format
+    if (pInstance->Params.ReverbLevel != pParams->ReverbLevel) {
+        LVM_INT32 ReverbPercentage = 83886;        // 1 Percent Reverb i.e 1/100 in Q 23 format
         ReverbPercentage *= pParams->ReverbLevel;  // Actual Reverb Level in Q 23 format
-        pConfig->ReverbLevel = ((LVM_FLOAT)(ReverbPercentage>>8)) / 32767.0f;
+        pConfig->ReverbLevel = ((LVM_FLOAT)(ReverbPercentage >> 8)) / 32767.0f;
     }
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
 /************************************************************************************/
 /*                                                                                  */
@@ -181,46 +150,38 @@
 /*  2.  The Gain is combined with the LPF and incorporated in to the coefficients   */
 /*                                                                                  */
 /************************************************************************************/
-LVCS_ReturnStatus_en LVCS_ReverbGenerator(LVCS_Handle_t         hInstance,
-                                          const LVM_FLOAT       *pInData,
-                                          LVM_FLOAT             *pOutData,
-                                          LVM_UINT16            NumSamples)
-{
+LVCS_ReturnStatus_en LVCS_ReverbGenerator(LVCS_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                          LVM_FLOAT* pOutData, LVM_UINT16 NumSamples) {
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
+    LVCS_ReverbGenerator_t* pConfig = (LVCS_ReverbGenerator_t*)&pInstance->Reverberation;
+    LVM_FLOAT* pScratch;
+    LVM_INT32 NumChannels = pInstance->Params.NrChannels;
+    LVM_UINT16 destNumSamples =
+            (pInstance->Params.NrChannels == FCC_1) ? NumSamples : FCC_2 * NumSamples;
 
-    LVCS_Instance_t         *pInstance = (LVCS_Instance_t  *)hInstance;
-    LVCS_ReverbGenerator_t  *pConfig   = (LVCS_ReverbGenerator_t *)&pInstance->Reverberation;
-    LVCS_Coefficient_t      *pCoefficients;
-    LVM_FLOAT               *pScratch;
-
-    pCoefficients = (LVCS_Coefficient_t *)\
-                   pInstance->MemoryTable.Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].pBaseAddress;
-
-    pScratch  = (LVM_FLOAT *)\
-                    pInstance->MemoryTable.Region[LVCS_MEMREGION_TEMPORARY_FAST].pBaseAddress;
+    pScratch = (LVM_FLOAT*)pInstance->pScratch;
 
     /*
      * Copy the data to the output in outplace processing
      */
-    if (pInData != pOutData)
-    {
+    if (pInData != pOutData) {
         /*
          * Reverb not required so just copy the data
          */
-        Copy_Float((LVM_FLOAT *)pInData,                                       /* Source */
-                   (LVM_FLOAT *)pOutData,                                      /* Destination */
-                   (LVM_INT16)(2 * NumSamples));                                 /* Left and right */
+        Copy_Float((LVM_FLOAT*)pInData,        /* Source */
+                   (LVM_FLOAT*)pOutData,       /* Destination */
+                   (LVM_INT16)destNumSamples); /* Number of frames */
     }
 
     /*
      * Check if the reverb is required
      */
     /* Disable when CS4MS in stereo mode */
-    if ((((LVCS_OutputDevice_en)pInstance->Params.SpeakerType == LVCS_HEADPHONE) || \
+    if ((((LVCS_OutputDevice_en)pInstance->Params.SpeakerType == LVCS_HEADPHONE) ||
          (pInstance->Params.SpeakerType == LVCS_EX_HEADPHONES) ||
-         (pInstance->Params.SourceFormat != LVCS_STEREO))  &&
-                                    /* For validation testing */
-        ((pInstance->Params.OperatingMode & LVCS_REVERBSWITCH) !=0))
-    {
+         (pInstance->Params.SourceFormat != LVCS_STEREO)) &&
+        /* For validation testing */
+        ((pInstance->Params.OperatingMode & LVCS_REVERBSWITCH) != 0)) {
         /********************************************************************************/
         /*                                                                              */
         /* Copy the input data to scratch memory and filter it                          */
@@ -230,34 +191,24 @@
         /*
          * Copy the input data to the scratch memory
          */
-        Copy_Float((LVM_FLOAT *)pInData,                                     /* Source */
-                   (LVM_FLOAT *)pScratch,                                    /* Destination */
-                   (LVM_INT16)(2 * NumSamples));                               /* Left and right */
+        Copy_Float((LVM_FLOAT*)pInData,        /* Source */
+                   (LVM_FLOAT*)pScratch,       /* Destination */
+                   (LVM_INT16)destNumSamples); /* Number of frames */
 
         /*
          * Filter the data
          */
-        (pConfig->pBiquadCallBack)((Biquad_FLOAT_Instance_t*)&pCoefficients->ReverbBiquadInstance,
-                                   (LVM_FLOAT *)pScratch,
-                                   (LVM_FLOAT *)pScratch,
-                                   (LVM_INT16)NumSamples);
+        pInstance->pRevBiquad->process(pScratch, pScratch, NumSamples);
 
-        Mult3s_Float( (LVM_FLOAT *)pScratch,
-                      pConfig->ReverbLevel,
-                      (LVM_FLOAT *)pScratch,
-                      (LVM_INT16)(2 * NumSamples));
+        Mult3s_Float((LVM_FLOAT*)pScratch, pConfig->ReverbLevel, (LVM_FLOAT*)pScratch,
+                     (LVM_INT16)destNumSamples); /* Number of frames */
 
         /*
          * Apply the delay mix
          */
-        DelayMix_Float((LVM_FLOAT *)pScratch,
-                       &pConfig->StereoSamples[0],
-                       pConfig->DelaySize,
-                       pOutData,
-                       &pConfig->DelayOffset,
-                       (LVM_INT16)NumSamples);
-
+        DelayMix_Float((LVM_FLOAT*)pScratch, &pConfig->StereoSamples[0], pConfig->DelaySize,
+                       pOutData, &pConfig->DelayOffset, (LVM_INT16)NumSamples, NumChannels);
     }
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_ReverbGenerator.h b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_ReverbGenerator.h
index 1bc4338..049eef2 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_ReverbGenerator.h
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_ReverbGenerator.h
@@ -32,8 +32,8 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#define     HEADPHONEGAINPROC           LVCS_HEADPHONE_PROCGAIN
-#define     HEADPHONEGAINUNPROC         LVCS_HEADPHONE_UNPROCGAIN
+#define HEADPHONEGAINPROC LVCS_HEADPHONE_PROCGAIN
+#define HEADPHONEGAINUNPROC LVCS_HEADPHONE_UNPROCGAIN
 
 /************************************************************************************/
 /*                                                                                  */
@@ -42,20 +42,15 @@
 /************************************************************************************/
 
 /* Reverberation module structure */
-typedef struct
-{
-
+typedef struct {
     /* Stereo delay */
-    LVM_INT16                   DelaySize;
-    LVM_INT16                   DelayOffset;
-    LVM_INT16                   ProcGain;
-    LVM_INT16                   UnprocGain;
-    LVM_FLOAT                   StereoSamples[2 * LVCS_STEREODELAY_CS_MAX_VAL];
+    LVM_INT16 DelaySize;
+    LVM_INT16 DelayOffset;
+    LVM_INT16 ProcGain;
+    LVM_INT16 UnprocGain;
+    LVM_FLOAT StereoSamples[2 * LVCS_STEREODELAY_CS_MAX_VAL];
     /* Reverb Level */
-    LVM_FLOAT                   ReverbLevel;
-    /* Filter */
-    void                        (*pBiquadCallBack) (Biquad_FLOAT_Instance_t*,
-                                                    LVM_FLOAT*, LVM_FLOAT*, LVM_INT16);
+    LVM_FLOAT ReverbLevel;
 } LVCS_ReverbGenerator_t;
 
 /************************************************************************************/
@@ -64,11 +59,8 @@
 /*                                                                                    */
 /************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_ReverbGeneratorInit(LVCS_Handle_t     hInstance,
-                                                 LVCS_Params_t  *pParams);
-LVCS_ReturnStatus_en LVCS_ReverbGenerator(LVCS_Handle_t         hInstance,
-                                          const LVM_FLOAT       *pInput,
-                                          LVM_FLOAT             *pOutput,
-                                          LVM_UINT16            NumSamples);
+LVCS_ReturnStatus_en LVCS_ReverbGeneratorInit(LVCS_Handle_t hInstance, LVCS_Params_t* pParams);
+LVCS_ReturnStatus_en LVCS_ReverbGenerator(LVCS_Handle_t hInstance, const LVM_FLOAT* pInput,
+                                          LVM_FLOAT* pOutput, LVM_UINT16 NumSamples);
 
-#endif  /* REVERB_H */
+#endif /* REVERB_H */
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.cpp b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.cpp
index 7fd8444..e3ff604 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.cpp
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.cpp
@@ -21,6 +21,7 @@
 /*                                                                                  */
 /************************************************************************************/
 
+#include <system/audio.h>
 #include "LVCS.h"
 #include "LVCS_Private.h"
 #include "LVCS_StereoEnhancer.h"
@@ -49,96 +50,39 @@
 /* NOTES:                                                                           */
 /*                                                                                  */
 /************************************************************************************/
-LVCS_ReturnStatus_en LVCS_SEnhancerInit(LVCS_Handle_t       hInstance,
-                                        LVCS_Params_t       *pParams)
-{
-
-    LVM_UINT16              Offset;
-    LVCS_Instance_t         *pInstance = (LVCS_Instance_t  *)hInstance;
-    LVCS_StereoEnhancer_t   *pConfig   = (LVCS_StereoEnhancer_t *)&pInstance->StereoEnhancer;
-    LVCS_Data_t             *pData;
-    LVCS_Coefficient_t      *pCoefficient;
-    FO_FLOAT_Coefs_t          CoeffsMid;
-    BQ_FLOAT_Coefs_t          CoeffsSide;
-    const BiquadA012B12CoefsSP_t *pSESideCoefs;
-
-    pData     = (LVCS_Data_t *) \
-                  pInstance->MemoryTable.Region[LVCS_MEMREGION_PERSISTENT_FAST_DATA].pBaseAddress;
-
-    pCoefficient = (LVCS_Coefficient_t *) \
-                  pInstance->MemoryTable.Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].pBaseAddress;
+LVCS_ReturnStatus_en LVCS_SEnhancerInit(LVCS_Handle_t hInstance, LVCS_Params_t* pParams) {
+    LVM_UINT16 Offset;
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
+    const BiquadA012B12CoefsSP_t* pSESideCoefs;
 
     /*
      * If the sample rate or speaker type has changed update the filters
      */
     if ((pInstance->Params.SampleRate != pParams->SampleRate) ||
-        (pInstance->Params.SpeakerType != pParams->SpeakerType))
-    {
+        (pInstance->Params.SpeakerType != pParams->SpeakerType)) {
         /*
          * Set the filter coefficients based on the sample rate
          */
         /* Mid filter */
         Offset = (LVM_UINT16)pParams->SampleRate;
 
-        /* Convert incoming coefficients to the required format/ordering */
-        CoeffsMid.A0 = (LVM_FLOAT) LVCS_SEMidCoefTable[Offset].A0;
-        CoeffsMid.A1 = (LVM_FLOAT) LVCS_SEMidCoefTable[Offset].A1;
-        CoeffsMid.B1 = (LVM_FLOAT)-LVCS_SEMidCoefTable[Offset].B1;
-
-        /* Clear the taps */
-        LoadConst_Float(0,                                  /* Value */
-                        (LVM_FLOAT *)&pData->SEBiquadTapsMid,    /* Destination */
-                        /* Number of words */
-                        (LVM_UINT16)(sizeof(pData->SEBiquadTapsMid) / sizeof(LVM_FLOAT)));
-
-        FO_1I_D16F16Css_TRC_WRA_01_Init(&pCoefficient->SEBiquadInstanceMid,
-                                        &pData->SEBiquadTapsMid,
-                                        &CoeffsMid);
-
-        /* Callbacks */
-        if(LVCS_SEMidCoefTable[Offset].Scale == 15)
-        {
-            pConfig->pBiquadCallBack_Mid  = FO_1I_D16F16C15_TRC_WRA_01;
-        }
+        std::array<LVM_FLOAT, android::audio_utils::kBiquadNumCoefs> coefs = {
+                LVCS_SEMidCoefTable[Offset].A0, LVCS_SEMidCoefTable[Offset].A1, 0.0,
+                -(LVCS_SEMidCoefTable[Offset].B1), 0.0};
+        pInstance->pSEMidBiquad.reset(
+                new android::audio_utils::BiquadFilter<LVM_FLOAT>(FCC_1, coefs));
 
         Offset = (LVM_UINT16)(pParams->SampleRate);
         pSESideCoefs = (BiquadA012B12CoefsSP_t*)&LVCS_SESideCoefTable[0];
 
         /* Side filter */
-        /* Convert incoming coefficients to the required format/ordering */
-        CoeffsSide.A0 = (LVM_FLOAT) pSESideCoefs[Offset].A0;
-        CoeffsSide.A1 = (LVM_FLOAT) pSESideCoefs[Offset].A1;
-        CoeffsSide.A2 = (LVM_FLOAT) pSESideCoefs[Offset].A2;
-        CoeffsSide.B1 = (LVM_FLOAT)-pSESideCoefs[Offset].B1;
-        CoeffsSide.B2 = (LVM_FLOAT)-pSESideCoefs[Offset].B2;
-
-        /* Clear the taps */
-        LoadConst_Float(0,                                /* Value */
-                        (LVM_FLOAT *)&pData->SEBiquadTapsSide, /* Destination */
-                        /* Number of words */
-                        (LVM_UINT16)(sizeof(pData->SEBiquadTapsSide) / sizeof(LVM_FLOAT)));
-        /* Callbacks */
-        switch(pSESideCoefs[Offset].Scale)
-        {
-            case 14:
-                BQ_1I_D16F32Css_TRC_WRA_01_Init(&pCoefficient->SEBiquadInstanceSide,
-                                                &pData->SEBiquadTapsSide,
-                                                &CoeffsSide);
-
-                pConfig->pBiquadCallBack_Side  = BQ_1I_D16F32C14_TRC_WRA_01;
-                break;
-            case 15:
-                BQ_1I_D16F16Css_TRC_WRA_01_Init(&pCoefficient->SEBiquadInstanceSide,
-                                                &pData->SEBiquadTapsSide,
-                                                &CoeffsSide);
-
-                pConfig->pBiquadCallBack_Side  = BQ_1I_D16F16C15_TRC_WRA_01;
-                break;
-        }
-
+        coefs = {pSESideCoefs[Offset].A0, pSESideCoefs[Offset].A1, pSESideCoefs[Offset].A2,
+                 -(pSESideCoefs[Offset].B1), -(pSESideCoefs[Offset].B2)};
+        pInstance->pSESideBiquad.reset(
+                new android::audio_utils::BiquadFilter<LVM_FLOAT>(FCC_1, coefs));
     }
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
 /************************************************************************************/
 /*                                                                                  */
@@ -178,85 +122,67 @@
 /*  1.  The side filter is not used in Mobile Speaker mode                          */
 /*                                                                                  */
 /************************************************************************************/
-LVCS_ReturnStatus_en LVCS_StereoEnhancer(LVCS_Handle_t          hInstance,
-                                         const LVM_FLOAT        *pInData,
-                                         LVM_FLOAT              *pOutData,
-                                         LVM_UINT16             NumSamples)
-{
-
-    LVCS_Instance_t         *pInstance = (LVCS_Instance_t  *)hInstance;
-    LVCS_StereoEnhancer_t   *pConfig   = (LVCS_StereoEnhancer_t *)&pInstance->StereoEnhancer;
-    LVCS_Coefficient_t      *pCoefficient;
-    LVM_FLOAT               *pScratch;
-
-    pCoefficient = (LVCS_Coefficient_t *) \
-                   pInstance->MemoryTable.Region[LVCS_MEMREGION_PERSISTENT_FAST_COEF].pBaseAddress;
-
-    pScratch  = (LVM_FLOAT *) \
-                    pInstance->MemoryTable.Region[LVCS_MEMREGION_TEMPORARY_FAST].pBaseAddress;
+LVCS_ReturnStatus_en LVCS_StereoEnhancer(LVCS_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                         LVM_FLOAT* pOutData, LVM_UINT16 NumSamples) {
+    LVCS_Instance_t* pInstance = (LVCS_Instance_t*)hInstance;
+    LVCS_StereoEnhancer_t* pConfig = (LVCS_StereoEnhancer_t*)&pInstance->StereoEnhancer;
+    LVM_FLOAT* pScratch;
+    pScratch = (LVM_FLOAT*)pInstance->pScratch;
+    LVM_INT32 NumChannels = pInstance->Params.NrChannels;
+    LVM_UINT16 destNumSamples = (NumChannels == FCC_1) ? NumSamples : FCC_2 * NumSamples;
     /*
      * Check if the Stereo Enhancer is enabled
      */
-    if ((pInstance->Params.OperatingMode & LVCS_STEREOENHANCESWITCH) != 0)
-        {
+    if ((pInstance->Params.OperatingMode & LVCS_STEREOENHANCESWITCH) != 0) {
         /*
          * Convert from stereo to middle and side
          */
-        From2iToMS_Float(pInData,
-                         pScratch,
-                         pScratch + NumSamples,
-                         (LVM_INT16)NumSamples);
+        if (NumChannels == 1) {
+            // Copy same input to scratch as Middle data
+            Copy_Float((LVM_FLOAT*)pInData, (LVM_FLOAT*)pScratch, (LVM_INT16)NumSamples);
+        } else {
+            From2iToMS_Float(pInData, pScratch, pScratch + NumSamples, (LVM_INT16)NumSamples);
+        }
 
         /*
          * Apply filter to the middle signal
          */
-        if (pInstance->OutputDevice == LVCS_HEADPHONE)
-        {
-            (pConfig->pBiquadCallBack_Mid)((Biquad_FLOAT_Instance_t*)\
-                                            &pCoefficient->SEBiquadInstanceMid,
-                                            (LVM_FLOAT *)pScratch,
-                                            (LVM_FLOAT *)pScratch,
-                                            (LVM_INT16)NumSamples);
-        }
-        else
-        {
-            Mult3s_Float(pScratch,              /* Source */
-                         (LVM_FLOAT)pConfig->MidGain,      /* Gain */
-                         pScratch,              /* Destination */
-                         (LVM_INT16)NumSamples);           /* Number of samples */
+        if (pInstance->OutputDevice == LVCS_HEADPHONE) {
+            pInstance->pSEMidBiquad->process(pScratch, pScratch, NumSamples);
+        } else {
+            Mult3s_Float(pScratch,                    /* Source */
+                         (LVM_FLOAT)pConfig->MidGain, /* Gain */
+                         pScratch,                    /* Destination */
+                         (LVM_INT16)NumSamples);      /* Number of samples */
         }
 
         /*
          * Apply the filter the side signal only in stereo mode for headphones
          * and in all modes for mobile speakers
          */
-        if (pInstance->Params.SourceFormat == LVCS_STEREO)
-        {
-            (pConfig->pBiquadCallBack_Side)((Biquad_FLOAT_Instance_t*) \
-                                            &pCoefficient->SEBiquadInstanceSide,
-                                            (LVM_FLOAT *)(pScratch + NumSamples),
-                                            (LVM_FLOAT *)(pScratch + NumSamples),
-                                            (LVM_INT16)NumSamples);
+        if (pInstance->Params.SourceFormat == LVCS_STEREO) {
+            pInstance->pSESideBiquad->process(pScratch + NumSamples, pScratch + NumSamples,
+                                              NumSamples);
         }
 
-        /*
-         * Convert from middle and side to stereo
-         */
-        MSTo2i_Sat_Float(pScratch,
-                         pScratch + NumSamples,
-                         pOutData,
-                         (LVM_INT16)NumSamples);
+        if (NumChannels == 1) {
+            // Copy processed Middle data from scratch to pOutData
+            Copy_Float((LVM_FLOAT*)pScratch, (LVM_FLOAT*)pOutData, (LVM_INT16)NumSamples);
+        } else {
+            /*
+             * Convert from middle and side to stereo
+             */
+            MSTo2i_Sat_Float(pScratch, pScratch + NumSamples, pOutData, (LVM_INT16)NumSamples);
+        }
 
-    }
-    else
-    {
+    } else {
         /*
          * The stereo enhancer is disabled so just copy the data
          */
-        Copy_Float((LVM_FLOAT *)pInData,           /* Source */
-                   (LVM_FLOAT *)pOutData,          /* Destination */
-                   (LVM_INT16)(2 * NumSamples));     /* Left and right */
+        Copy_Float((LVM_FLOAT*)pInData,        /* Source */
+                   (LVM_FLOAT*)pOutData,       /* Destination */
+                   (LVM_INT16)destNumSamples); /* Number of frames */
     }
 
-    return(LVCS_SUCCESS);
+    return (LVCS_SUCCESS);
 }
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.h b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.h
index 12a5982..0bed591 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.h
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_StereoEnhancer.h
@@ -24,8 +24,8 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#include "Filters.h"                        /* Filter definitions */
-#include "LVCS_Headphone_Coeffs.h"          /* Headphone coefficients */
+#include "Filters.h"               /* Filter definitions */
+#include "LVCS_Headphone_Coeffs.h" /* Headphone coefficients */
 #include "BIQUAD.h"
 
 /************************************************************************************/
@@ -35,21 +35,8 @@
 /************************************************************************************/
 
 /* Stereo enhancer structure */
-typedef struct
-{
-
-    /*
-     * Middle filter
-     */
-    void                    (*pBiquadCallBack_Mid)(Biquad_FLOAT_Instance_t*,
-                                    LVM_FLOAT*, LVM_FLOAT*, LVM_INT16);
-
-    /*
-     * Side filter
-     */
-    void                    (*pBiquadCallBack_Side)(Biquad_FLOAT_Instance_t*,
-                                    LVM_FLOAT*, LVM_FLOAT*, LVM_INT16);
-    LVM_FLOAT              MidGain;            /* Middle gain in mobile speaker mode */
+typedef struct {
+    LVM_FLOAT MidGain; /* Middle gain in mobile speaker mode */
 } LVCS_StereoEnhancer_t;
 
 /************************************************************************************/
@@ -58,12 +45,9 @@
 /*                                                                                  */
 /************************************************************************************/
 
-LVCS_ReturnStatus_en LVCS_SEnhancerInit(LVCS_Handle_t        hInstance,
-                                        LVCS_Params_t        *pParams);
+LVCS_ReturnStatus_en LVCS_SEnhancerInit(LVCS_Handle_t hInstance, LVCS_Params_t* pParams);
 
-LVCS_ReturnStatus_en LVCS_StereoEnhancer(LVCS_Handle_t        hInstance,
-                                         const LVM_FLOAT    *pInData,
-                                         LVM_FLOAT            *pOutData,
-                                         LVM_UINT16            NumSamples);
+LVCS_ReturnStatus_en LVCS_StereoEnhancer(LVCS_Handle_t hInstance, const LVM_FLOAT* pInData,
+                                         LVM_FLOAT* pOutData, LVM_UINT16 NumSamples);
 
-#endif  /* STEREOENHANCE_H */
+#endif /* STEREOENHANCE_H */
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Tables.cpp b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Tables.cpp
index d79db61..55b5243 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Tables.cpp
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Tables.cpp
@@ -23,9 +23,9 @@
 
 #include "LVCS_Private.h"
 #include "LVCS_Tables.h"
-#include "Filters.h"                            /* Filter definitions */
-#include "BIQUAD.h"                             /* Biquad definitions */
-#include "LVCS_Headphone_Coeffs.h"              /* Headphone coefficients */
+#include "Filters.h"               /* Filter definitions */
+#include "BIQUAD.h"                /* Biquad definitions */
+#include "LVCS_Headphone_Coeffs.h" /* Headphone coefficients */
 
 /************************************************************************************/
 /*                                                                                  */
@@ -35,144 +35,75 @@
 
 /* Coefficient table for the middle filter */
 const BiquadA01B1CoefsSP_t LVCS_SEMidCoefTable[] = {
-    {CS_MIDDLE_8000_A0,         /* 8kS/s coefficients */
-     CS_MIDDLE_8000_A1,
-     CS_MIDDLE_8000_B1,
-     (LVM_UINT16 )CS_MIDDLE_8000_SCALE},
-    {CS_MIDDLE_11025_A0,        /* 11kS/s coefficients */
-     CS_MIDDLE_11025_A1,
-     CS_MIDDLE_11025_B1,
-     (LVM_UINT16 )CS_MIDDLE_11025_SCALE},
-    {CS_MIDDLE_12000_A0,        /* 12kS/s coefficients */
-     CS_MIDDLE_12000_A1,
-     CS_MIDDLE_12000_B1,
-     (LVM_UINT16 )CS_MIDDLE_12000_SCALE},
-    {CS_MIDDLE_16000_A0,        /* 16kS/s coefficients */
-     CS_MIDDLE_16000_A1,
-     CS_MIDDLE_16000_B1,
-     (LVM_UINT16 )CS_MIDDLE_16000_SCALE},
-    {CS_MIDDLE_22050_A0,        /* 22kS/s coefficients */
-     CS_MIDDLE_22050_A1,
-     CS_MIDDLE_22050_B1,
-     (LVM_UINT16 )CS_MIDDLE_22050_SCALE},
-    {CS_MIDDLE_24000_A0,        /* 24kS/s coefficients */
-     CS_MIDDLE_24000_A1,
-     CS_MIDDLE_24000_B1,
-     (LVM_UINT16 )CS_MIDDLE_24000_SCALE},
-    {CS_MIDDLE_32000_A0,        /* 32kS/s coefficients */
-     CS_MIDDLE_32000_A1,
-     CS_MIDDLE_32000_B1,
-     (LVM_UINT16 )CS_MIDDLE_32000_SCALE},
-    {CS_MIDDLE_44100_A0,        /* 44kS/s coefficients */
-     CS_MIDDLE_44100_A1,
-     CS_MIDDLE_44100_B1,
-     (LVM_UINT16 )CS_MIDDLE_44100_SCALE},
-    {CS_MIDDLE_48000_A0,        /* 48kS/s coefficients */
-     CS_MIDDLE_48000_A1,
-     CS_MIDDLE_48000_B1,
-     (LVM_UINT16 )CS_MIDDLE_48000_SCALE}
-    ,
-    {CS_MIDDLE_88200_A0,        /* 88kS/s coefficients */
-     CS_MIDDLE_88200_A1,
-     CS_MIDDLE_88200_B1,
-     (LVM_UINT16)CS_MIDDLE_88200_SCALE},
-    {CS_MIDDLE_96000_A0,        /* 96kS/s coefficients */
-     CS_MIDDLE_96000_A1,
-     CS_MIDDLE_96000_B1,
-     (LVM_UINT16 )CS_MIDDLE_96000_SCALE},
-    {CS_MIDDLE_176400_A0,        /* 176kS/s coefficients */
-     CS_MIDDLE_176400_A1,
-     CS_MIDDLE_176400_B1,
-     (LVM_UINT16)CS_MIDDLE_176400_SCALE},
-    {CS_MIDDLE_192000_A0,        /* 192kS/s coefficients */
-     CS_MIDDLE_192000_A1,
-     CS_MIDDLE_192000_B1,
-     (LVM_UINT16 )CS_MIDDLE_192000_SCALE}
-    };
+        {CS_MIDDLE_8000_A0, /* 8kS/s coefficients */
+         CS_MIDDLE_8000_A1, CS_MIDDLE_8000_B1, (LVM_UINT16)CS_MIDDLE_8000_SCALE},
+        {CS_MIDDLE_11025_A0, /* 11kS/s coefficients */
+         CS_MIDDLE_11025_A1, CS_MIDDLE_11025_B1, (LVM_UINT16)CS_MIDDLE_11025_SCALE},
+        {CS_MIDDLE_12000_A0, /* 12kS/s coefficients */
+         CS_MIDDLE_12000_A1, CS_MIDDLE_12000_B1, (LVM_UINT16)CS_MIDDLE_12000_SCALE},
+        {CS_MIDDLE_16000_A0, /* 16kS/s coefficients */
+         CS_MIDDLE_16000_A1, CS_MIDDLE_16000_B1, (LVM_UINT16)CS_MIDDLE_16000_SCALE},
+        {CS_MIDDLE_22050_A0, /* 22kS/s coefficients */
+         CS_MIDDLE_22050_A1, CS_MIDDLE_22050_B1, (LVM_UINT16)CS_MIDDLE_22050_SCALE},
+        {CS_MIDDLE_24000_A0, /* 24kS/s coefficients */
+         CS_MIDDLE_24000_A1, CS_MIDDLE_24000_B1, (LVM_UINT16)CS_MIDDLE_24000_SCALE},
+        {CS_MIDDLE_32000_A0, /* 32kS/s coefficients */
+         CS_MIDDLE_32000_A1, CS_MIDDLE_32000_B1, (LVM_UINT16)CS_MIDDLE_32000_SCALE},
+        {CS_MIDDLE_44100_A0, /* 44kS/s coefficients */
+         CS_MIDDLE_44100_A1, CS_MIDDLE_44100_B1, (LVM_UINT16)CS_MIDDLE_44100_SCALE},
+        {CS_MIDDLE_48000_A0, /* 48kS/s coefficients */
+         CS_MIDDLE_48000_A1, CS_MIDDLE_48000_B1, (LVM_UINT16)CS_MIDDLE_48000_SCALE},
+        {CS_MIDDLE_88200_A0, /* 88kS/s coefficients */
+         CS_MIDDLE_88200_A1, CS_MIDDLE_88200_B1, (LVM_UINT16)CS_MIDDLE_88200_SCALE},
+        {CS_MIDDLE_96000_A0, /* 96kS/s coefficients */
+         CS_MIDDLE_96000_A1, CS_MIDDLE_96000_B1, (LVM_UINT16)CS_MIDDLE_96000_SCALE},
+        {CS_MIDDLE_176400_A0, /* 176kS/s coefficients */
+         CS_MIDDLE_176400_A1, CS_MIDDLE_176400_B1, (LVM_UINT16)CS_MIDDLE_176400_SCALE},
+        {CS_MIDDLE_192000_A0, /* 192kS/s coefficients */
+         CS_MIDDLE_192000_A1, CS_MIDDLE_192000_B1, (LVM_UINT16)CS_MIDDLE_192000_SCALE}};
 
 /* Coefficient table for the side filter */
 const BiquadA012B12CoefsSP_t LVCS_SESideCoefTable[] = {
-    /* Headphone Side coefficients */
-    {CS_SIDE_8000_A0,           /* 8kS/s coefficients */
-     CS_SIDE_8000_A1,
-     CS_SIDE_8000_A2,
-     CS_SIDE_8000_B1,
-     CS_SIDE_8000_B2,
-     (LVM_UINT16 )CS_SIDE_8000_SCALE},
-    {CS_SIDE_11025_A0,          /* 11kS/s coefficients */
-     CS_SIDE_11025_A1,
-     CS_SIDE_11025_A2,
-     CS_SIDE_11025_B1,
-     CS_SIDE_11025_B2,
-     (LVM_UINT16 )CS_SIDE_11025_SCALE},
-    {CS_SIDE_12000_A0,          /* 12kS/s coefficients */
-     CS_SIDE_12000_A1,
-     CS_SIDE_12000_A2,
-     CS_SIDE_12000_B1,
-     CS_SIDE_12000_B2,
-     (LVM_UINT16 )CS_SIDE_12000_SCALE},
-    {CS_SIDE_16000_A0,          /* 16kS/s coefficients */
-     CS_SIDE_16000_A1,
-     CS_SIDE_16000_A2,
-     CS_SIDE_16000_B1,
-     CS_SIDE_16000_B2,
-     (LVM_UINT16 )CS_SIDE_16000_SCALE},
-    {CS_SIDE_22050_A0,          /* 22kS/s coefficients */
-     CS_SIDE_22050_A1,
-     CS_SIDE_22050_A2,
-     CS_SIDE_22050_B1,
-     CS_SIDE_22050_B2,
-     (LVM_UINT16 )CS_SIDE_22050_SCALE},
-    {CS_SIDE_24000_A0,          /* 24kS/s coefficients */
-     CS_SIDE_24000_A1,
-     CS_SIDE_24000_A2,
-     CS_SIDE_24000_B1,
-     CS_SIDE_24000_B2,
-     (LVM_UINT16 )CS_SIDE_24000_SCALE},
-    {CS_SIDE_32000_A0,          /* 32kS/s coefficients */
-     CS_SIDE_32000_A1,
-     CS_SIDE_32000_A2,
-     CS_SIDE_32000_B1,
-     CS_SIDE_32000_B2,
-     (LVM_UINT16 )CS_SIDE_32000_SCALE},
-    {CS_SIDE_44100_A0,          /* 44kS/s coefficients */
-     CS_SIDE_44100_A1,
-     CS_SIDE_44100_A2,
-     CS_SIDE_44100_B1,
-     CS_SIDE_44100_B2,
-     (LVM_UINT16 )CS_SIDE_44100_SCALE},
-    {CS_SIDE_48000_A0,          /* 48kS/s coefficients */
-     CS_SIDE_48000_A1,
-     CS_SIDE_48000_A2,
-     CS_SIDE_48000_B1,
-     CS_SIDE_48000_B2,
-     (LVM_UINT16 )CS_SIDE_48000_SCALE}
-     ,
-    {CS_SIDE_88200_A0,          /* 88kS/s coefficients */
-     CS_SIDE_88200_A1,
-     CS_SIDE_88200_A2,
-     CS_SIDE_88200_B1,
-     CS_SIDE_88200_B2,
-     (LVM_UINT16)CS_SIDE_88200_SCALE},
-     {CS_SIDE_96000_A0,          /* 96kS/s coefficients */
-     CS_SIDE_96000_A1,
-     CS_SIDE_96000_A2,
-     CS_SIDE_96000_B1,
-     CS_SIDE_96000_B2,
-     (LVM_UINT16 )CS_SIDE_96000_SCALE},
-    {CS_SIDE_176400_A0,          /*176kS/s coefficients */
-     CS_SIDE_176400_A1,
-     CS_SIDE_176400_A2,
-     CS_SIDE_176400_B1,
-     CS_SIDE_176400_B2,
-     (LVM_UINT16)CS_SIDE_176400_SCALE},
-     {CS_SIDE_192000_A0,          /* 192kS/s coefficients */
-     CS_SIDE_192000_A1,
-     CS_SIDE_192000_A2,
-     CS_SIDE_192000_B1,
-     CS_SIDE_192000_B2,
-     (LVM_UINT16 )CS_SIDE_192000_SCALE}
-};
+        /* Headphone Side coefficients */
+        {CS_SIDE_8000_A0, /* 8kS/s coefficients */
+         CS_SIDE_8000_A1, CS_SIDE_8000_A2, CS_SIDE_8000_B1, CS_SIDE_8000_B2,
+         (LVM_UINT16)CS_SIDE_8000_SCALE},
+        {CS_SIDE_11025_A0, /* 11kS/s coefficients */
+         CS_SIDE_11025_A1, CS_SIDE_11025_A2, CS_SIDE_11025_B1, CS_SIDE_11025_B2,
+         (LVM_UINT16)CS_SIDE_11025_SCALE},
+        {CS_SIDE_12000_A0, /* 12kS/s coefficients */
+         CS_SIDE_12000_A1, CS_SIDE_12000_A2, CS_SIDE_12000_B1, CS_SIDE_12000_B2,
+         (LVM_UINT16)CS_SIDE_12000_SCALE},
+        {CS_SIDE_16000_A0, /* 16kS/s coefficients */
+         CS_SIDE_16000_A1, CS_SIDE_16000_A2, CS_SIDE_16000_B1, CS_SIDE_16000_B2,
+         (LVM_UINT16)CS_SIDE_16000_SCALE},
+        {CS_SIDE_22050_A0, /* 22kS/s coefficients */
+         CS_SIDE_22050_A1, CS_SIDE_22050_A2, CS_SIDE_22050_B1, CS_SIDE_22050_B2,
+         (LVM_UINT16)CS_SIDE_22050_SCALE},
+        {CS_SIDE_24000_A0, /* 24kS/s coefficients */
+         CS_SIDE_24000_A1, CS_SIDE_24000_A2, CS_SIDE_24000_B1, CS_SIDE_24000_B2,
+         (LVM_UINT16)CS_SIDE_24000_SCALE},
+        {CS_SIDE_32000_A0, /* 32kS/s coefficients */
+         CS_SIDE_32000_A1, CS_SIDE_32000_A2, CS_SIDE_32000_B1, CS_SIDE_32000_B2,
+         (LVM_UINT16)CS_SIDE_32000_SCALE},
+        {CS_SIDE_44100_A0, /* 44kS/s coefficients */
+         CS_SIDE_44100_A1, CS_SIDE_44100_A2, CS_SIDE_44100_B1, CS_SIDE_44100_B2,
+         (LVM_UINT16)CS_SIDE_44100_SCALE},
+        {CS_SIDE_48000_A0, /* 48kS/s coefficients */
+         CS_SIDE_48000_A1, CS_SIDE_48000_A2, CS_SIDE_48000_B1, CS_SIDE_48000_B2,
+         (LVM_UINT16)CS_SIDE_48000_SCALE},
+        {CS_SIDE_88200_A0, /* 88kS/s coefficients */
+         CS_SIDE_88200_A1, CS_SIDE_88200_A2, CS_SIDE_88200_B1, CS_SIDE_88200_B2,
+         (LVM_UINT16)CS_SIDE_88200_SCALE},
+        {CS_SIDE_96000_A0, /* 96kS/s coefficients */
+         CS_SIDE_96000_A1, CS_SIDE_96000_A2, CS_SIDE_96000_B1, CS_SIDE_96000_B2,
+         (LVM_UINT16)CS_SIDE_96000_SCALE},
+        {CS_SIDE_176400_A0, /*176kS/s coefficients */
+         CS_SIDE_176400_A1, CS_SIDE_176400_A2, CS_SIDE_176400_B1, CS_SIDE_176400_B2,
+         (LVM_UINT16)CS_SIDE_176400_SCALE},
+        {CS_SIDE_192000_A0, /* 192kS/s coefficients */
+         CS_SIDE_192000_A1, CS_SIDE_192000_A2, CS_SIDE_192000_B1, CS_SIDE_192000_B2,
+         (LVM_UINT16)CS_SIDE_192000_SCALE}};
 
 /************************************************************************************/
 /*                                                                                  */
@@ -181,167 +112,87 @@
 /************************************************************************************/
 
 const BiquadA012B12CoefsSP_t LVCS_EqualiserCoefTable[] = {
-    /* Headphone coefficients */
-    {CS_EQUALISER_8000_A0,      /* 8kS/s coefficients */
-     CS_EQUALISER_8000_A1,
-     CS_EQUALISER_8000_A2,
-     CS_EQUALISER_8000_B1,
-     CS_EQUALISER_8000_B2,
-     (LVM_UINT16 )CS_EQUALISER_8000_SCALE},
-    {CS_EQUALISER_11025_A0,     /* 11kS/s coefficients */
-     CS_EQUALISER_11025_A1,
-     CS_EQUALISER_11025_A2,
-     CS_EQUALISER_11025_B1,
-     CS_EQUALISER_11025_B2,
-     (LVM_UINT16 )CS_EQUALISER_11025_SCALE},
-    {CS_EQUALISER_12000_A0,     /* 12kS/s coefficients */
-     CS_EQUALISER_12000_A1,
-     CS_EQUALISER_12000_A2,
-     CS_EQUALISER_12000_B1,
-     CS_EQUALISER_12000_B2,
-     (LVM_UINT16 )CS_EQUALISER_12000_SCALE},
-    {CS_EQUALISER_16000_A0,     /* 16kS/s coefficients */
-     CS_EQUALISER_16000_A1,
-     CS_EQUALISER_16000_A2,
-     CS_EQUALISER_16000_B1,
-     CS_EQUALISER_16000_B2,
-     (LVM_UINT16 )CS_EQUALISER_16000_SCALE},
-    {CS_EQUALISER_22050_A0,     /* 22kS/s coefficients */
-     CS_EQUALISER_22050_A1,
-     CS_EQUALISER_22050_A2,
-     CS_EQUALISER_22050_B1,
-     CS_EQUALISER_22050_B2,
-     (LVM_UINT16 )CS_EQUALISER_22050_SCALE},
-    {CS_EQUALISER_24000_A0,     /* 24kS/s coefficients */
-     CS_EQUALISER_24000_A1,
-     CS_EQUALISER_24000_A2,
-     CS_EQUALISER_24000_B1,
-     CS_EQUALISER_24000_B2,
-     (LVM_UINT16 )CS_EQUALISER_24000_SCALE},
-    {CS_EQUALISER_32000_A0,     /* 32kS/s coefficients */
-     CS_EQUALISER_32000_A1,
-     CS_EQUALISER_32000_A2,
-     CS_EQUALISER_32000_B1,
-     CS_EQUALISER_32000_B2,
-     (LVM_UINT16 )CS_EQUALISER_32000_SCALE},
-    {CS_EQUALISER_44100_A0,     /* 44kS/s coefficients */
-     CS_EQUALISER_44100_A1,
-     CS_EQUALISER_44100_A2,
-     CS_EQUALISER_44100_B1,
-     CS_EQUALISER_44100_B2,
-     (LVM_UINT16 )CS_EQUALISER_44100_SCALE},
-    {CS_EQUALISER_48000_A0,     /* 48kS/s coefficients */
-     CS_EQUALISER_48000_A1,
-     CS_EQUALISER_48000_A2,
-     CS_EQUALISER_48000_B1,
-     CS_EQUALISER_48000_B2,
-     (LVM_UINT16 )CS_EQUALISER_48000_SCALE},
-    {CS_EQUALISER_88200_A0,     /* 88kS/s coeffieients */
-     CS_EQUALISER_88200_A1,
-     CS_EQUALISER_88200_A2,
-     CS_EQUALISER_88200_B1,
-     CS_EQUALISER_88200_B2,
-     (LVM_UINT16)CS_EQUALISER_88200_SCALE},
-    {CS_EQUALISER_96000_A0,     /* 96kS/s coefficients */
-     CS_EQUALISER_96000_A1,
-     CS_EQUALISER_96000_A2,
-     CS_EQUALISER_96000_B1,
-     CS_EQUALISER_96000_B2,
-     (LVM_UINT16 )CS_EQUALISER_96000_SCALE},
-    {CS_EQUALISER_176400_A0,     /* 176kS/s coefficients */
-     CS_EQUALISER_176400_A1,
-     CS_EQUALISER_176400_A2,
-     CS_EQUALISER_176400_B1,
-     CS_EQUALISER_176400_B2,
-     (LVM_UINT16)CS_EQUALISER_176400_SCALE},
-    {CS_EQUALISER_192000_A0,     /* 192kS/s coefficients */
-     CS_EQUALISER_192000_A1,
-     CS_EQUALISER_192000_A2,
-     CS_EQUALISER_192000_B1,
-     CS_EQUALISER_192000_B2,
-     (LVM_UINT16 )CS_EQUALISER_192000_SCALE},
+        /* Headphone coefficients */
+        {CS_EQUALISER_8000_A0, /* 8kS/s coefficients */
+         CS_EQUALISER_8000_A1, CS_EQUALISER_8000_A2, CS_EQUALISER_8000_B1, CS_EQUALISER_8000_B2,
+         (LVM_UINT16)CS_EQUALISER_8000_SCALE},
+        {CS_EQUALISER_11025_A0, /* 11kS/s coefficients */
+         CS_EQUALISER_11025_A1, CS_EQUALISER_11025_A2, CS_EQUALISER_11025_B1, CS_EQUALISER_11025_B2,
+         (LVM_UINT16)CS_EQUALISER_11025_SCALE},
+        {CS_EQUALISER_12000_A0, /* 12kS/s coefficients */
+         CS_EQUALISER_12000_A1, CS_EQUALISER_12000_A2, CS_EQUALISER_12000_B1, CS_EQUALISER_12000_B2,
+         (LVM_UINT16)CS_EQUALISER_12000_SCALE},
+        {CS_EQUALISER_16000_A0, /* 16kS/s coefficients */
+         CS_EQUALISER_16000_A1, CS_EQUALISER_16000_A2, CS_EQUALISER_16000_B1, CS_EQUALISER_16000_B2,
+         (LVM_UINT16)CS_EQUALISER_16000_SCALE},
+        {CS_EQUALISER_22050_A0, /* 22kS/s coefficients */
+         CS_EQUALISER_22050_A1, CS_EQUALISER_22050_A2, CS_EQUALISER_22050_B1, CS_EQUALISER_22050_B2,
+         (LVM_UINT16)CS_EQUALISER_22050_SCALE},
+        {CS_EQUALISER_24000_A0, /* 24kS/s coefficients */
+         CS_EQUALISER_24000_A1, CS_EQUALISER_24000_A2, CS_EQUALISER_24000_B1, CS_EQUALISER_24000_B2,
+         (LVM_UINT16)CS_EQUALISER_24000_SCALE},
+        {CS_EQUALISER_32000_A0, /* 32kS/s coefficients */
+         CS_EQUALISER_32000_A1, CS_EQUALISER_32000_A2, CS_EQUALISER_32000_B1, CS_EQUALISER_32000_B2,
+         (LVM_UINT16)CS_EQUALISER_32000_SCALE},
+        {CS_EQUALISER_44100_A0, /* 44kS/s coefficients */
+         CS_EQUALISER_44100_A1, CS_EQUALISER_44100_A2, CS_EQUALISER_44100_B1, CS_EQUALISER_44100_B2,
+         (LVM_UINT16)CS_EQUALISER_44100_SCALE},
+        {CS_EQUALISER_48000_A0, /* 48kS/s coefficients */
+         CS_EQUALISER_48000_A1, CS_EQUALISER_48000_A2, CS_EQUALISER_48000_B1, CS_EQUALISER_48000_B2,
+         (LVM_UINT16)CS_EQUALISER_48000_SCALE},
+        {CS_EQUALISER_88200_A0, /* 88kS/s coeffieients */
+         CS_EQUALISER_88200_A1, CS_EQUALISER_88200_A2, CS_EQUALISER_88200_B1, CS_EQUALISER_88200_B2,
+         (LVM_UINT16)CS_EQUALISER_88200_SCALE},
+        {CS_EQUALISER_96000_A0, /* 96kS/s coefficients */
+         CS_EQUALISER_96000_A1, CS_EQUALISER_96000_A2, CS_EQUALISER_96000_B1, CS_EQUALISER_96000_B2,
+         (LVM_UINT16)CS_EQUALISER_96000_SCALE},
+        {CS_EQUALISER_176400_A0, /* 176kS/s coefficients */
+         CS_EQUALISER_176400_A1, CS_EQUALISER_176400_A2, CS_EQUALISER_176400_B1,
+         CS_EQUALISER_176400_B2, (LVM_UINT16)CS_EQUALISER_176400_SCALE},
+        {CS_EQUALISER_192000_A0, /* 192kS/s coefficients */
+         CS_EQUALISER_192000_A1, CS_EQUALISER_192000_A2, CS_EQUALISER_192000_B1,
+         CS_EQUALISER_192000_B2, (LVM_UINT16)CS_EQUALISER_192000_SCALE},
 
-    /* Concert Sound EX Headphone coefficients */
-    {CSEX_EQUALISER_8000_A0,    /* 8kS/s coefficients */
-     CSEX_EQUALISER_8000_A1,
-     CSEX_EQUALISER_8000_A2,
-     CSEX_EQUALISER_8000_B1,
-     CSEX_EQUALISER_8000_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_8000_SCALE},
-    {CSEX_EQUALISER_11025_A0,   /* 11kS/s coefficients */
-     CSEX_EQUALISER_11025_A1,
-     CSEX_EQUALISER_11025_A2,
-     CSEX_EQUALISER_11025_B1,
-     CSEX_EQUALISER_11025_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_11025_SCALE},
-    {CSEX_EQUALISER_12000_A0,   /* 12kS/s coefficients */
-     CSEX_EQUALISER_12000_A1,
-     CSEX_EQUALISER_12000_A2,
-     CSEX_EQUALISER_12000_B1,
-     CSEX_EQUALISER_12000_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_12000_SCALE},
-    {CSEX_EQUALISER_16000_A0,   /* 16kS/s coefficients */
-     CSEX_EQUALISER_16000_A1,
-     CSEX_EQUALISER_16000_A2,
-     CSEX_EQUALISER_16000_B1,
-     CSEX_EQUALISER_16000_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_16000_SCALE},
-    {CSEX_EQUALISER_22050_A0,   /* 22kS/s coefficients */
-     CSEX_EQUALISER_22050_A1,
-     CSEX_EQUALISER_22050_A2,
-     CSEX_EQUALISER_22050_B1,
-     CSEX_EQUALISER_22050_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_22050_SCALE},
-    {CSEX_EQUALISER_24000_A0,   /* 24kS/s coefficients */
-     CSEX_EQUALISER_24000_A1,
-     CSEX_EQUALISER_24000_A2,
-     CSEX_EQUALISER_24000_B1,
-     CSEX_EQUALISER_24000_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_24000_SCALE},
-    {CSEX_EQUALISER_32000_A0,   /* 32kS/s coefficients */
-     CSEX_EQUALISER_32000_A1,
-     CSEX_EQUALISER_32000_A2,
-     CSEX_EQUALISER_32000_B1,
-     CSEX_EQUALISER_32000_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_32000_SCALE},
-    {CSEX_EQUALISER_44100_A0,   /* 44kS/s coefficients */
-     CSEX_EQUALISER_44100_A1,
-     CSEX_EQUALISER_44100_A2,
-     CSEX_EQUALISER_44100_B1,
-     CSEX_EQUALISER_44100_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_44100_SCALE},
-    {CSEX_EQUALISER_48000_A0,   /* 48kS/s coefficients */
-     CSEX_EQUALISER_48000_A1,
-     CSEX_EQUALISER_48000_A2,
-     CSEX_EQUALISER_48000_B1,
-     CSEX_EQUALISER_48000_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_48000_SCALE}
-    ,
-    {CSEX_EQUALISER_88200_A0,   /* 88kS/s coefficients */
-     CSEX_EQUALISER_88200_A1,
-     CSEX_EQUALISER_88200_A2,
-     CSEX_EQUALISER_88200_B1,
-     CSEX_EQUALISER_88200_B2,
-     (LVM_UINT16)CSEX_EQUALISER_88200_SCALE},
-    {CSEX_EQUALISER_96000_A0,   /* 96kS/s coefficients */
-     CSEX_EQUALISER_96000_A1,
-     CSEX_EQUALISER_96000_A2,
-     CSEX_EQUALISER_96000_B1,
-     CSEX_EQUALISER_96000_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_96000_SCALE},
-    {CSEX_EQUALISER_176400_A0,   /* 176kS/s coefficients */
-     CSEX_EQUALISER_176400_A1,
-     CSEX_EQUALISER_176400_A2,
-     CSEX_EQUALISER_176400_B1,
-     CSEX_EQUALISER_176400_B2,
-     (LVM_UINT16)CSEX_EQUALISER_176400_SCALE},
-     {CSEX_EQUALISER_192000_A0,   /* 192kS/s coefficients */
-     CSEX_EQUALISER_192000_A1,
-     CSEX_EQUALISER_192000_A2,
-     CSEX_EQUALISER_192000_B1,
-     CSEX_EQUALISER_192000_B2,
-     (LVM_UINT16 )CSEX_EQUALISER_192000_SCALE}
-};
+        /* Concert Sound EX Headphone coefficients */
+        {CSEX_EQUALISER_8000_A0, /* 8kS/s coefficients */
+         CSEX_EQUALISER_8000_A1, CSEX_EQUALISER_8000_A2, CSEX_EQUALISER_8000_B1,
+         CSEX_EQUALISER_8000_B2, (LVM_UINT16)CSEX_EQUALISER_8000_SCALE},
+        {CSEX_EQUALISER_11025_A0, /* 11kS/s coefficients */
+         CSEX_EQUALISER_11025_A1, CSEX_EQUALISER_11025_A2, CSEX_EQUALISER_11025_B1,
+         CSEX_EQUALISER_11025_B2, (LVM_UINT16)CSEX_EQUALISER_11025_SCALE},
+        {CSEX_EQUALISER_12000_A0, /* 12kS/s coefficients */
+         CSEX_EQUALISER_12000_A1, CSEX_EQUALISER_12000_A2, CSEX_EQUALISER_12000_B1,
+         CSEX_EQUALISER_12000_B2, (LVM_UINT16)CSEX_EQUALISER_12000_SCALE},
+        {CSEX_EQUALISER_16000_A0, /* 16kS/s coefficients */
+         CSEX_EQUALISER_16000_A1, CSEX_EQUALISER_16000_A2, CSEX_EQUALISER_16000_B1,
+         CSEX_EQUALISER_16000_B2, (LVM_UINT16)CSEX_EQUALISER_16000_SCALE},
+        {CSEX_EQUALISER_22050_A0, /* 22kS/s coefficients */
+         CSEX_EQUALISER_22050_A1, CSEX_EQUALISER_22050_A2, CSEX_EQUALISER_22050_B1,
+         CSEX_EQUALISER_22050_B2, (LVM_UINT16)CSEX_EQUALISER_22050_SCALE},
+        {CSEX_EQUALISER_24000_A0, /* 24kS/s coefficients */
+         CSEX_EQUALISER_24000_A1, CSEX_EQUALISER_24000_A2, CSEX_EQUALISER_24000_B1,
+         CSEX_EQUALISER_24000_B2, (LVM_UINT16)CSEX_EQUALISER_24000_SCALE},
+        {CSEX_EQUALISER_32000_A0, /* 32kS/s coefficients */
+         CSEX_EQUALISER_32000_A1, CSEX_EQUALISER_32000_A2, CSEX_EQUALISER_32000_B1,
+         CSEX_EQUALISER_32000_B2, (LVM_UINT16)CSEX_EQUALISER_32000_SCALE},
+        {CSEX_EQUALISER_44100_A0, /* 44kS/s coefficients */
+         CSEX_EQUALISER_44100_A1, CSEX_EQUALISER_44100_A2, CSEX_EQUALISER_44100_B1,
+         CSEX_EQUALISER_44100_B2, (LVM_UINT16)CSEX_EQUALISER_44100_SCALE},
+        {CSEX_EQUALISER_48000_A0, /* 48kS/s coefficients */
+         CSEX_EQUALISER_48000_A1, CSEX_EQUALISER_48000_A2, CSEX_EQUALISER_48000_B1,
+         CSEX_EQUALISER_48000_B2, (LVM_UINT16)CSEX_EQUALISER_48000_SCALE},
+        {CSEX_EQUALISER_88200_A0, /* 88kS/s coefficients */
+         CSEX_EQUALISER_88200_A1, CSEX_EQUALISER_88200_A2, CSEX_EQUALISER_88200_B1,
+         CSEX_EQUALISER_88200_B2, (LVM_UINT16)CSEX_EQUALISER_88200_SCALE},
+        {CSEX_EQUALISER_96000_A0, /* 96kS/s coefficients */
+         CSEX_EQUALISER_96000_A1, CSEX_EQUALISER_96000_A2, CSEX_EQUALISER_96000_B1,
+         CSEX_EQUALISER_96000_B2, (LVM_UINT16)CSEX_EQUALISER_96000_SCALE},
+        {CSEX_EQUALISER_176400_A0, /* 176kS/s coefficients */
+         CSEX_EQUALISER_176400_A1, CSEX_EQUALISER_176400_A2, CSEX_EQUALISER_176400_B1,
+         CSEX_EQUALISER_176400_B2, (LVM_UINT16)CSEX_EQUALISER_176400_SCALE},
+        {CSEX_EQUALISER_192000_A0, /* 192kS/s coefficients */
+         CSEX_EQUALISER_192000_A1, CSEX_EQUALISER_192000_A2, CSEX_EQUALISER_192000_B1,
+         CSEX_EQUALISER_192000_B2, (LVM_UINT16)CSEX_EQUALISER_192000_SCALE}};
 
 /************************************************************************************/
 /*                                                                                  */
@@ -350,20 +201,12 @@
 /************************************************************************************/
 
 /* Stereo delay table for Concert Sound */
-const LVM_UINT16    LVCS_StereoDelayCS[] = {
-    LVCS_STEREODELAY_CS_8KHZ,
-    LVCS_STEREODELAY_CS_11KHZ,
-    LVCS_STEREODELAY_CS_12KHZ,
-    LVCS_STEREODELAY_CS_16KHZ,
-    LVCS_STEREODELAY_CS_22KHZ,
-    LVCS_STEREODELAY_CS_24KHZ,
-    LVCS_STEREODELAY_CS_32KHZ,
-    LVCS_STEREODELAY_CS_44KHZ,
-    LVCS_STEREODELAY_CS_48KHZ,
-    LVCS_STEREODELAY_CS_88KHZ,
-    LVCS_STEREODELAY_CS_96KHZ,
-    LVCS_STEREODELAY_CS_176KHZ,
-    LVCS_STEREODELAY_CS_192KHZ,
+const LVM_UINT16 LVCS_StereoDelayCS[] = {
+        LVCS_STEREODELAY_CS_8KHZ,   LVCS_STEREODELAY_CS_11KHZ, LVCS_STEREODELAY_CS_12KHZ,
+        LVCS_STEREODELAY_CS_16KHZ,  LVCS_STEREODELAY_CS_22KHZ, LVCS_STEREODELAY_CS_24KHZ,
+        LVCS_STEREODELAY_CS_32KHZ,  LVCS_STEREODELAY_CS_44KHZ, LVCS_STEREODELAY_CS_48KHZ,
+        LVCS_STEREODELAY_CS_88KHZ,  LVCS_STEREODELAY_CS_96KHZ, LVCS_STEREODELAY_CS_176KHZ,
+        LVCS_STEREODELAY_CS_192KHZ,
 };
 
 /************************************************************************************/
@@ -373,87 +216,46 @@
 /************************************************************************************/
 
 const BiquadA012B12CoefsSP_t LVCS_ReverbCoefTable[] = {
-    /* Headphone coefficients */
-    {CS_REVERB_8000_A0,             /* 8kS/s coefficients */
-     CS_REVERB_8000_A1,
-     CS_REVERB_8000_A2,
-     CS_REVERB_8000_B1,
-     CS_REVERB_8000_B2,
-     (LVM_UINT16 )CS_REVERB_8000_SCALE},
-    {CS_REVERB_11025_A0,            /* 11kS/s coefficients */
-     CS_REVERB_11025_A1,
-     CS_REVERB_11025_A2,
-     CS_REVERB_11025_B1,
-     CS_REVERB_11025_B2,
-     (LVM_UINT16 )CS_REVERB_11025_SCALE},
-    {CS_REVERB_12000_A0,            /* 12kS/s coefficients */
-     CS_REVERB_12000_A1,
-     CS_REVERB_12000_A2,
-     CS_REVERB_12000_B1,
-     CS_REVERB_12000_B2,
-     (LVM_UINT16 )CS_REVERB_12000_SCALE},
-    {CS_REVERB_16000_A0,            /* 16kS/s coefficients */
-     CS_REVERB_16000_A1,
-     CS_REVERB_16000_A2,
-     CS_REVERB_16000_B1,
-     CS_REVERB_16000_B2,
-     (LVM_UINT16 )CS_REVERB_16000_SCALE},
-    {CS_REVERB_22050_A0,            /* 22kS/s coefficients */
-     CS_REVERB_22050_A1,
-     CS_REVERB_22050_A2,
-     CS_REVERB_22050_B1,
-     CS_REVERB_22050_B2,
-     (LVM_UINT16 )CS_REVERB_22050_SCALE},
-    {CS_REVERB_24000_A0,            /* 24kS/s coefficients */
-     CS_REVERB_24000_A1,
-     CS_REVERB_24000_A2,
-     CS_REVERB_24000_B1,
-     CS_REVERB_24000_B2,
-     (LVM_UINT16 )CS_REVERB_24000_SCALE},
-    {CS_REVERB_32000_A0,            /* 32kS/s coefficients */
-     CS_REVERB_32000_A1,
-     CS_REVERB_32000_A2,
-     CS_REVERB_32000_B1,
-     CS_REVERB_32000_B2,
-     (LVM_UINT16 )CS_REVERB_32000_SCALE},
-    {CS_REVERB_44100_A0,            /* 44kS/s coefficients */
-     CS_REVERB_44100_A1,
-     CS_REVERB_44100_A2,
-     CS_REVERB_44100_B1,
-     CS_REVERB_44100_B2,
-     (LVM_UINT16 )CS_REVERB_44100_SCALE},
-    {CS_REVERB_48000_A0,            /* 48kS/s coefficients */
-     CS_REVERB_48000_A1,
-     CS_REVERB_48000_A2,
-     CS_REVERB_48000_B1,
-     CS_REVERB_48000_B2,
-     (LVM_UINT16 )CS_REVERB_48000_SCALE}
-    ,
-    {CS_REVERB_88200_A0,            /* 88kS/s coefficients */
-     CS_REVERB_88200_A1,
-     CS_REVERB_88200_A2,
-     CS_REVERB_88200_B1,
-     CS_REVERB_88200_B2,
-     (LVM_UINT16)CS_REVERB_88200_SCALE},
-    {CS_REVERB_96000_A0,            /* 96kS/s coefficients */
-     CS_REVERB_96000_A1,
-     CS_REVERB_96000_A2,
-     CS_REVERB_96000_B1,
-     CS_REVERB_96000_B2,
-     (LVM_UINT16 )CS_REVERB_96000_SCALE},
-    {CS_REVERB_176400_A0,            /* 176kS/s coefficients */
-     CS_REVERB_176400_A1,
-     CS_REVERB_176400_A2,
-     CS_REVERB_176400_B1,
-     CS_REVERB_176400_B2,
-     (LVM_UINT16)CS_REVERB_176400_SCALE},
-     {CS_REVERB_192000_A0,            /* 192kS/s coefficients */
-     CS_REVERB_192000_A1,
-     CS_REVERB_192000_A2,
-     CS_REVERB_192000_B1,
-     CS_REVERB_192000_B2,
-     (LVM_UINT16 )CS_REVERB_192000_SCALE}
-};
+        /* Headphone coefficients */
+        {CS_REVERB_8000_A0, /* 8kS/s coefficients */
+         CS_REVERB_8000_A1, CS_REVERB_8000_A2, CS_REVERB_8000_B1, CS_REVERB_8000_B2,
+         (LVM_UINT16)CS_REVERB_8000_SCALE},
+        {CS_REVERB_11025_A0, /* 11kS/s coefficients */
+         CS_REVERB_11025_A1, CS_REVERB_11025_A2, CS_REVERB_11025_B1, CS_REVERB_11025_B2,
+         (LVM_UINT16)CS_REVERB_11025_SCALE},
+        {CS_REVERB_12000_A0, /* 12kS/s coefficients */
+         CS_REVERB_12000_A1, CS_REVERB_12000_A2, CS_REVERB_12000_B1, CS_REVERB_12000_B2,
+         (LVM_UINT16)CS_REVERB_12000_SCALE},
+        {CS_REVERB_16000_A0, /* 16kS/s coefficients */
+         CS_REVERB_16000_A1, CS_REVERB_16000_A2, CS_REVERB_16000_B1, CS_REVERB_16000_B2,
+         (LVM_UINT16)CS_REVERB_16000_SCALE},
+        {CS_REVERB_22050_A0, /* 22kS/s coefficients */
+         CS_REVERB_22050_A1, CS_REVERB_22050_A2, CS_REVERB_22050_B1, CS_REVERB_22050_B2,
+         (LVM_UINT16)CS_REVERB_22050_SCALE},
+        {CS_REVERB_24000_A0, /* 24kS/s coefficients */
+         CS_REVERB_24000_A1, CS_REVERB_24000_A2, CS_REVERB_24000_B1, CS_REVERB_24000_B2,
+         (LVM_UINT16)CS_REVERB_24000_SCALE},
+        {CS_REVERB_32000_A0, /* 32kS/s coefficients */
+         CS_REVERB_32000_A1, CS_REVERB_32000_A2, CS_REVERB_32000_B1, CS_REVERB_32000_B2,
+         (LVM_UINT16)CS_REVERB_32000_SCALE},
+        {CS_REVERB_44100_A0, /* 44kS/s coefficients */
+         CS_REVERB_44100_A1, CS_REVERB_44100_A2, CS_REVERB_44100_B1, CS_REVERB_44100_B2,
+         (LVM_UINT16)CS_REVERB_44100_SCALE},
+        {CS_REVERB_48000_A0, /* 48kS/s coefficients */
+         CS_REVERB_48000_A1, CS_REVERB_48000_A2, CS_REVERB_48000_B1, CS_REVERB_48000_B2,
+         (LVM_UINT16)CS_REVERB_48000_SCALE},
+        {CS_REVERB_88200_A0, /* 88kS/s coefficients */
+         CS_REVERB_88200_A1, CS_REVERB_88200_A2, CS_REVERB_88200_B1, CS_REVERB_88200_B2,
+         (LVM_UINT16)CS_REVERB_88200_SCALE},
+        {CS_REVERB_96000_A0, /* 96kS/s coefficients */
+         CS_REVERB_96000_A1, CS_REVERB_96000_A2, CS_REVERB_96000_B1, CS_REVERB_96000_B2,
+         (LVM_UINT16)CS_REVERB_96000_SCALE},
+        {CS_REVERB_176400_A0, /* 176kS/s coefficients */
+         CS_REVERB_176400_A1, CS_REVERB_176400_A2, CS_REVERB_176400_B1, CS_REVERB_176400_B2,
+         (LVM_UINT16)CS_REVERB_176400_SCALE},
+        {CS_REVERB_192000_A0, /* 192kS/s coefficients */
+         CS_REVERB_192000_A1, CS_REVERB_192000_A2, CS_REVERB_192000_B1, CS_REVERB_192000_B2,
+         (LVM_UINT16)CS_REVERB_192000_SCALE}};
 
 /************************************************************************************/
 /*                                                                                  */
@@ -461,20 +263,14 @@
 /*                                                                                  */
 /************************************************************************************/
 
-const Gain_t LVCS_OutputGainTable[] = {
-    {LVCS_HEADPHONE_SHIFT,         /* Headphone, stereo mode */
-     LVCS_HEADPHONE_SHIFTLOSS,
-     LVCS_HEADPHONE_GAIN},
-    {LVCS_EX_HEADPHONE_SHIFT,      /* EX Headphone, stereo mode */
-     LVCS_EX_HEADPHONE_SHIFTLOSS,
-     LVCS_EX_HEADPHONE_GAIN},
-    {LVCS_HEADPHONE_SHIFT,         /* Headphone, mono mode */
-     LVCS_HEADPHONE_SHIFTLOSS,
-     LVCS_HEADPHONE_GAIN},
-    {LVCS_EX_HEADPHONE_SHIFT,      /* EX Headphone, mono mode */
-     LVCS_EX_HEADPHONE_SHIFTLOSS,
-     LVCS_EX_HEADPHONE_GAIN}
-};
+const Gain_t LVCS_OutputGainTable[] = {{LVCS_HEADPHONE_SHIFT, /* Headphone, stereo mode */
+                                        LVCS_HEADPHONE_SHIFTLOSS, LVCS_HEADPHONE_GAIN},
+                                       {LVCS_EX_HEADPHONE_SHIFT, /* EX Headphone, stereo mode */
+                                        LVCS_EX_HEADPHONE_SHIFTLOSS, LVCS_EX_HEADPHONE_GAIN},
+                                       {LVCS_HEADPHONE_SHIFT, /* Headphone, mono mode */
+                                        LVCS_HEADPHONE_SHIFTLOSS, LVCS_HEADPHONE_GAIN},
+                                       {LVCS_EX_HEADPHONE_SHIFT, /* EX Headphone, mono mode */
+                                        LVCS_EX_HEADPHONE_SHIFTLOSS, LVCS_EX_HEADPHONE_GAIN}};
 
 /************************************************************************************/
 /*                                                                                  */
@@ -501,24 +297,14 @@
 /*          1024    is -12dB gain                                                   */
 /*                                                                                  */
 /************************************************************************************/
-const LVCS_VolCorrect_t LVCS_VolCorrectTable[] = {
-    {0.433362f,          /* Headphone, stereo mode */
-     0.000000f,
-     1.000024f,
-     1.412640f},
-    {0.433362f,          /* EX Headphone, stereo mode */
-     0.000000f,
-     1.000024f,
-     1.412640f},
-    {1.000000f,         /* Headphone, mono mode */
-     0.000000f,
-     1.000024f,
-     1.412640f},
-    {1.000000f,         /* EX Headphone, mono mode */
-     0.000000f,
-     1.000024f,
-     1.412640f}
-};
+const LVCS_VolCorrect_t LVCS_VolCorrectTable[] = {{0.433362f, /* Headphone, stereo mode */
+                                                   0.000000f, 1.000024f, 1.412640f},
+                                                  {0.433362f, /* EX Headphone, stereo mode */
+                                                   0.000000f, 1.000024f, 1.412640f},
+                                                  {1.000000f, /* Headphone, mono mode */
+                                                   0.000000f, 1.000024f, 1.412640f},
+                                                  {1.000000f, /* EX Headphone, mono mode */
+                                                   0.000000f, 1.000024f, 1.412640f}};
 
 /************************************************************************************/
 /*                                                                                  */
@@ -526,51 +312,32 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#define LVCS_VOL_TC_Fs8000      32580       /* Floating point value 0.994262695 */
-#define LVCS_VOL_TC_Fs11025     32632       /* Floating point value 0.995849609 */
-#define LVCS_VOL_TC_Fs12000     32643       /* Floating point value 0.996185303 */
-#define LVCS_VOL_TC_Fs16000     32674       /* Floating point value 0.997131348 */
-#define LVCS_VOL_TC_Fs22050     32700       /* Floating point value 0.997924805 */
-#define LVCS_VOL_TC_Fs24000     32705       /* Floating point value 0.998077393 */
-#define LVCS_VOL_TC_Fs32000     32721       /* Floating point value 0.998565674 */
-#define LVCS_VOL_TC_Fs44100     32734       /* Floating point value 0.998962402 */
-#define LVCS_VOL_TC_Fs48000     32737       /* Floating point value 0.999053955 */
-#define LVCS_VOL_TC_Fs88200     32751       /* Floating point value 0.999481066 */
-#define LVCS_VOL_TC_Fs96000     32751       /* Floating point value 0.999511703 */   /* Todo @ need to re check this value*/
-#define LVCS_VOL_TC_Fs176400    32759       /* Floating point value 0.999740499 */
-#define LVCS_VOL_TC_Fs192000    32763       /* Floating point value 0.999877925 */  /* Todo @ need to re check this value*/
+#define LVCS_VOL_TC_Fs8000 32580  /* Floating point value 0.994262695 */
+#define LVCS_VOL_TC_Fs11025 32632 /* Floating point value 0.995849609 */
+#define LVCS_VOL_TC_Fs12000 32643 /* Floating point value 0.996185303 */
+#define LVCS_VOL_TC_Fs16000 32674 /* Floating point value 0.997131348 */
+#define LVCS_VOL_TC_Fs22050 32700 /* Floating point value 0.997924805 */
+#define LVCS_VOL_TC_Fs24000 32705 /* Floating point value 0.998077393 */
+#define LVCS_VOL_TC_Fs32000 32721 /* Floating point value 0.998565674 */
+#define LVCS_VOL_TC_Fs44100 32734 /* Floating point value 0.998962402 */
+#define LVCS_VOL_TC_Fs48000 32737 /* Floating point value 0.999053955 */
+#define LVCS_VOL_TC_Fs88200 32751 /* Floating point value 0.999481066 */
+#define LVCS_VOL_TC_Fs96000 \
+    32751 /* Floating point value 0.999511703 */ /* Todo @ need to re check this value*/
+#define LVCS_VOL_TC_Fs176400 32759               /* Floating point value 0.999740499 */
+#define LVCS_VOL_TC_Fs192000 \
+    32763 /* Floating point value 0.999877925 */ /* Todo @ need to re check this value*/
 
-const LVM_INT16 LVCS_VolumeTCTable[13] = {LVCS_VOL_TC_Fs8000,
-                                          LVCS_VOL_TC_Fs11025,
-                                          LVCS_VOL_TC_Fs12000,
-                                          LVCS_VOL_TC_Fs16000,
-                                          LVCS_VOL_TC_Fs22050,
-                                          LVCS_VOL_TC_Fs24000,
-                                          LVCS_VOL_TC_Fs32000,
-                                          LVCS_VOL_TC_Fs44100,
-                                          LVCS_VOL_TC_Fs48000,
-                                          LVCS_VOL_TC_Fs88200,
-                                          LVCS_VOL_TC_Fs96000,
-                                          LVCS_VOL_TC_Fs176400,
-                                          LVCS_VOL_TC_Fs192000
-};
+const LVM_INT16 LVCS_VolumeTCTable[13] = {
+        LVCS_VOL_TC_Fs8000,  LVCS_VOL_TC_Fs11025, LVCS_VOL_TC_Fs12000, LVCS_VOL_TC_Fs16000,
+        LVCS_VOL_TC_Fs22050, LVCS_VOL_TC_Fs24000, LVCS_VOL_TC_Fs32000, LVCS_VOL_TC_Fs44100,
+        LVCS_VOL_TC_Fs48000, LVCS_VOL_TC_Fs88200, LVCS_VOL_TC_Fs96000, LVCS_VOL_TC_Fs176400,
+        LVCS_VOL_TC_Fs192000};
 
 /************************************************************************************/
 /*                                                                                  */
 /*  Sample rate table                                                               */
 /*                                                                                  */
 /************************************************************************************/
-const LVM_INT32   LVCS_SampleRateTable[13] = {8000,
-                                              11025,
-                                              12000,
-                                              16000,
-                                              22050,
-                                              24000,
-                                              32000,
-                                              44100,
-                                              48000,
-                                              88200,
-                                              96000,
-                                              176400,
-                                              192000
-};
+const LVM_INT32 LVCS_SampleRateTable[13] = {8000,  11025, 12000, 16000, 22050,  24000, 32000,
+                                            44100, 48000, 88200, 96000, 176400, 192000};
diff --git a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Tables.h b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Tables.h
index 5490699..766f5f2 100644
--- a/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Tables.h
+++ b/media/libeffects/lvm/lib/StereoWidening/src/LVCS_Tables.h
@@ -24,7 +24,7 @@
 /*                                                                                  */
 /************************************************************************************/
 
-#include "BIQUAD.h"                             /* Biquad definitions */
+#include "BIQUAD.h" /* Biquad definitions */
 
 /************************************************************************************/
 /*                                                                                  */
@@ -106,35 +106,34 @@
 /*                                                                                  */
 /************************************************************************************/
 
-extern const LVM_INT32          LVCS_SampleRateTable[];
+extern const LVM_INT32 LVCS_SampleRateTable[];
 
 /*Speaker coeffient tables*/
-extern LVM_UINT16               LVCS_MS_Small_SEMiddleGainTable[];
-extern BiquadA012B12CoefsSP_t   LVCS_MS_Small_SESideCoefTable[];
-extern BiquadA012B12CoefsSP_t   LVCS_MS_Small_EqualiserCoefTable[];
-extern BiquadA012B12CoefsSP_t   LVCS_MS_Small_ReverbCoefTable[] ;
-extern LVM_UINT16               LVCS_MS_Small_StereoDelayCS4MS[];
-extern Gain_t                   LVCS_MS_Small_OutputGainTable[];
-extern LVCS_VolCorrect_t        LVCS_MS_Small_VolCorrectTable[];
-extern LVM_UINT16               LVCS_MS_Small_ReverbGainTable[];
+extern LVM_UINT16 LVCS_MS_Small_SEMiddleGainTable[];
+extern BiquadA012B12CoefsSP_t LVCS_MS_Small_SESideCoefTable[];
+extern BiquadA012B12CoefsSP_t LVCS_MS_Small_EqualiserCoefTable[];
+extern BiquadA012B12CoefsSP_t LVCS_MS_Small_ReverbCoefTable[];
+extern LVM_UINT16 LVCS_MS_Small_StereoDelayCS4MS[];
+extern Gain_t LVCS_MS_Small_OutputGainTable[];
+extern LVCS_VolCorrect_t LVCS_MS_Small_VolCorrectTable[];
+extern LVM_UINT16 LVCS_MS_Small_ReverbGainTable[];
 
-extern LVM_UINT16               LVCS_MS_Medium_SEMiddleGainTable[];
-extern BiquadA012B12CoefsSP_t   LVCS_MS_Medium_SESideCoefTable[];
-extern BiquadA012B12CoefsSP_t   LVCS_MS_Medium_EqualiserCoefTable[];
-extern BiquadA012B12CoefsSP_t   LVCS_MS_Medium_ReverbCoefTable[] ;
-extern LVM_UINT16               LVCS_MS_Medium_StereoDelayCS4MS[];
-extern Gain_t                   LVCS_MS_Medium_OutputGainTable[];
-extern LVCS_VolCorrect_t        LVCS_MS_Medium_VolCorrectTable[];
-extern LVM_UINT16               LVCS_MS_Medium_ReverbGainTable[];
+extern LVM_UINT16 LVCS_MS_Medium_SEMiddleGainTable[];
+extern BiquadA012B12CoefsSP_t LVCS_MS_Medium_SESideCoefTable[];
+extern BiquadA012B12CoefsSP_t LVCS_MS_Medium_EqualiserCoefTable[];
+extern BiquadA012B12CoefsSP_t LVCS_MS_Medium_ReverbCoefTable[];
+extern LVM_UINT16 LVCS_MS_Medium_StereoDelayCS4MS[];
+extern Gain_t LVCS_MS_Medium_OutputGainTable[];
+extern LVCS_VolCorrect_t LVCS_MS_Medium_VolCorrectTable[];
+extern LVM_UINT16 LVCS_MS_Medium_ReverbGainTable[];
 
-extern LVM_UINT16               LVCS_MS_Large_SEMiddleGainTable[];
-extern BiquadA012B12CoefsSP_t   LVCS_MS_Large_SESideCoefTable[];
-extern BiquadA012B12CoefsSP_t   LVCS_MS_Large_EqualiserCoefTable[];
-extern BiquadA012B12CoefsSP_t   LVCS_MS_Large_ReverbCoefTable[] ;
-extern LVM_UINT16               LVCS_MS_Large_StereoDelayCS4MS[];
-extern Gain_t                   LVCS_MS_Large_OutputGainTable[];
-extern LVCS_VolCorrect_t        LVCS_MS_Large_VolCorrectTable[];
-extern LVM_UINT16               LVCS_MS_Large_ReverbGainTable[];
+extern LVM_UINT16 LVCS_MS_Large_SEMiddleGainTable[];
+extern BiquadA012B12CoefsSP_t LVCS_MS_Large_SESideCoefTable[];
+extern BiquadA012B12CoefsSP_t LVCS_MS_Large_EqualiserCoefTable[];
+extern BiquadA012B12CoefsSP_t LVCS_MS_Large_ReverbCoefTable[];
+extern LVM_UINT16 LVCS_MS_Large_StereoDelayCS4MS[];
+extern Gain_t LVCS_MS_Large_OutputGainTable[];
+extern LVCS_VolCorrect_t LVCS_MS_Large_VolCorrectTable[];
+extern LVM_UINT16 LVCS_MS_Large_ReverbGainTable[];
 
 #endif /* __LVCS_TABLES_H__ */
-
diff --git a/media/libeffects/lvm/tests/Android.bp b/media/libeffects/lvm/tests/Android.bp
index 674c246..9939ed1 100644
--- a/media/libeffects/lvm/tests/Android.bp
+++ b/media/libeffects/lvm/tests/Android.bp
@@ -1,5 +1,64 @@
 // Build the unit tests for effects
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_test {
+    name: "EffectReverbTest",
+    vendor: true,
+    gtest: true,
+    host_supported: true,
+    srcs: [
+        "EffectReverbTest.cpp",
+        "EffectTestHelper.cpp",
+    ],
+    include_dirs: [
+        "frameworks/av/media/libeffects/lvm/lib/Common/lib",
+        "frameworks/av/media/libeffects/lvm/wrapper/Reverb",
+    ],
+    static_libs: [
+        "libaudioutils",
+        "libreverb",
+        "libreverbwrapper",
+    ],
+    shared_libs: [
+        "liblog",
+    ],
+    header_libs: [
+        "libaudioeffects",
+        "libhardware_headers",
+    ],
+}
+
+cc_test {
+    name: "EffectBundleTest",
+    vendor: true,
+    gtest: true,
+    host_supported: true,
+    test_suites: ["device-tests"],
+    srcs: [
+        "EffectBundleTest.cpp",
+        "EffectTestHelper.cpp",
+    ],
+    static_libs: [
+        "libaudioutils",
+        "libbundlewrapper",
+        "libmusicbundle",
+    ],
+    shared_libs: [
+        "liblog",
+    ],
+    header_libs: [
+        "libhardware_headers",
+    ],
+}
+
 cc_test {
     name: "lvmtest",
     host_supported: false,
@@ -44,6 +103,40 @@
 }
 
 cc_test {
+    name: "reverb_test",
+    host_supported: true,
+    proprietary: true,
+    gtest: false,
+
+    include_dirs: [
+        "frameworks/av/media/libeffects/lvm/wrapper/Reverb",
+    ],
+
+    header_libs: [
+        "libaudioeffects",
+    ],
+
+    shared_libs: [
+        "libaudioutils",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libreverb",
+        "libreverbwrapper",
+    ],
+    srcs: [
+        "reverb_test.cpp",
+    ],
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+}
+
+cc_test {
     name: "snr",
     host_supported: false,
 
diff --git a/media/libeffects/lvm/tests/EffectBundleTest.cpp b/media/libeffects/lvm/tests/EffectBundleTest.cpp
new file mode 100644
index 0000000..881ffb1
--- /dev/null
+++ b/media/libeffects/lvm/tests/EffectBundleTest.cpp
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2021 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 "EffectTestHelper.h"
+using namespace android;
+
+// Update isBassBoost, if the order of effects is updated
+constexpr effect_uuid_t kEffectUuids[] = {
+        // NXP SW BassBoost
+        {0x8631f300, 0x72e2, 0x11df, 0xb57e, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // NXP SW Virtualizer
+        {0x1d4033c0, 0x8557, 0x11df, 0x9f2d, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // NXP SW Equalizer
+        {0xce772f20, 0x847d, 0x11df, 0xbb17, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // NXP SW Volume
+        {0x119341a0, 0x8469, 0x11df, 0x81f9, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+};
+
+static bool isBassBoost(const effect_uuid_t* uuid) {
+    // Update this, if the order of effects in kEffectUuids is updated
+    return uuid == &kEffectUuids[0];
+}
+
+constexpr size_t kNumEffectUuids = std::size(kEffectUuids);
+
+typedef std::tuple<int, int, int, int, int> SingleEffectTestParam;
+class SingleEffectTest : public ::testing::TestWithParam<SingleEffectTestParam> {
+  public:
+    SingleEffectTest()
+        : mChMask(EffectTestHelper::kChMasks[std::get<0>(GetParam())]),
+          mChannelCount(audio_channel_count_from_out_mask(mChMask)),
+          mSampleRate(EffectTestHelper::kSampleRates[std::get<1>(GetParam())]),
+          mFrameCount(EffectTestHelper::kFrameCounts[std::get<2>(GetParam())]),
+          mLoopCount(EffectTestHelper::kLoopCounts[std::get<3>(GetParam())]),
+          mTotalFrameCount(mFrameCount * mLoopCount),
+          mUuid(&kEffectUuids[std::get<4>(GetParam())]) {}
+
+    const size_t mChMask;
+    const size_t mChannelCount;
+    const size_t mSampleRate;
+    const size_t mFrameCount;
+    const size_t mLoopCount;
+    const size_t mTotalFrameCount;
+    const effect_uuid_t* mUuid;
+};
+
+// Tests applying a single effect
+TEST_P(SingleEffectTest, SimpleProcess) {
+    SCOPED_TRACE(testing::Message()
+                 << "chMask: " << mChMask << " sampleRate: " << mSampleRate
+                 << " frameCount: " << mFrameCount << " loopCount: " << mLoopCount);
+
+    EffectTestHelper effect(mUuid, mChMask, mChMask, mSampleRate, mFrameCount, mLoopCount);
+
+    ASSERT_NO_FATAL_FAILURE(effect.createEffect());
+    ASSERT_NO_FATAL_FAILURE(effect.setConfig());
+
+    // Initialize input buffer with deterministic pseudo-random values
+    std::vector<float> input(mTotalFrameCount * mChannelCount);
+    std::vector<float> output(mTotalFrameCount * mChannelCount);
+    std::minstd_rand gen(mChMask);
+    std::uniform_real_distribution<> dis(-1.0f, 1.0f);
+    for (auto& in : input) {
+        in = dis(gen);
+    }
+    ASSERT_NO_FATAL_FAILURE(effect.process(input.data(), output.data()));
+    ASSERT_NO_FATAL_FAILURE(effect.releaseEffect());
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        EffectBundleTestAll, SingleEffectTest,
+        ::testing::Combine(::testing::Range(0, (int)EffectTestHelper::kNumChMasks),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumSampleRates),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumFrameCounts),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumLoopCounts),
+                           ::testing::Range(0, (int)kNumEffectUuids)));
+
+typedef std::tuple<int, int, int, int> SingleEffectComparisonTestParam;
+class SingleEffectComparisonTest
+    : public ::testing::TestWithParam<SingleEffectComparisonTestParam> {
+  public:
+    SingleEffectComparisonTest()
+        : mSampleRate(EffectTestHelper::kSampleRates[std::get<0>(GetParam())]),
+          mFrameCount(EffectTestHelper::kFrameCounts[std::get<1>(GetParam())]),
+          mLoopCount(EffectTestHelper::kLoopCounts[std::get<2>(GetParam())]),
+          mTotalFrameCount(mFrameCount * mLoopCount),
+          mUuid(&kEffectUuids[std::get<3>(GetParam())]) {}
+
+    const size_t mSampleRate;
+    const size_t mFrameCount;
+    const size_t mLoopCount;
+    const size_t mTotalFrameCount;
+    const effect_uuid_t* mUuid;
+};
+
+// Compares first two channels in multi-channel output to stereo output when same effect is applied
+TEST_P(SingleEffectComparisonTest, SimpleProcess) {
+    SCOPED_TRACE(testing::Message() << " sampleRate: " << mSampleRate << " frameCount: "
+                                    << mFrameCount << " loopCount: " << mLoopCount);
+
+    // Initialize mono input buffer with deterministic pseudo-random values
+    std::vector<float> monoInput(mTotalFrameCount);
+
+    std::minstd_rand gen(mSampleRate);
+    std::uniform_real_distribution<> dis(-1.0f, 1.0f);
+    for (auto& in : monoInput) {
+        in = dis(gen);
+    }
+
+    // Generate stereo by repeating mono channel data
+    std::vector<float> stereoInput(mTotalFrameCount * FCC_2);
+    adjust_channels(monoInput.data(), FCC_1, stereoInput.data(), FCC_2, sizeof(float),
+                    mTotalFrameCount * sizeof(float) * FCC_1);
+
+    // Apply effect on stereo channels
+    EffectTestHelper stereoEffect(mUuid, AUDIO_CHANNEL_OUT_STEREO, AUDIO_CHANNEL_OUT_STEREO,
+                                  mSampleRate, mFrameCount, mLoopCount);
+
+    ASSERT_NO_FATAL_FAILURE(stereoEffect.createEffect());
+    ASSERT_NO_FATAL_FAILURE(stereoEffect.setConfig());
+
+    std::vector<float> stereoOutput(mTotalFrameCount * FCC_2);
+    ASSERT_NO_FATAL_FAILURE(stereoEffect.process(stereoInput.data(), stereoOutput.data()));
+    ASSERT_NO_FATAL_FAILURE(stereoEffect.releaseEffect());
+
+    // Convert stereo float data to stereo int16_t to be used as reference
+    std::vector<int16_t> stereoRefI16(mTotalFrameCount * FCC_2);
+    memcpy_to_i16_from_float(stereoRefI16.data(), stereoOutput.data(), mTotalFrameCount * FCC_2);
+
+    for (size_t chMask : EffectTestHelper::kChMasks) {
+        size_t channelCount = audio_channel_count_from_out_mask(chMask);
+        EffectTestHelper testEffect(mUuid, chMask, chMask, mSampleRate, mFrameCount, mLoopCount);
+
+        ASSERT_NO_FATAL_FAILURE(testEffect.createEffect());
+        ASSERT_NO_FATAL_FAILURE(testEffect.setConfig());
+
+        std::vector<float> testInput(mTotalFrameCount * channelCount);
+
+        // Repeat mono channel data to all the channels
+        // adjust_channels() zero fills channels > 2, hence can't be used here
+        for (size_t i = 0; i < mTotalFrameCount; ++i) {
+            auto* fp = &testInput[i * channelCount];
+            std::fill(fp, fp + channelCount, monoInput[i]);
+        }
+
+        std::vector<float> testOutput(mTotalFrameCount * channelCount);
+        ASSERT_NO_FATAL_FAILURE(testEffect.process(testInput.data(), testOutput.data()));
+        ASSERT_NO_FATAL_FAILURE(testEffect.releaseEffect());
+
+        // Extract first two channels
+        std::vector<float> stereoTestOutput(mTotalFrameCount * FCC_2);
+        adjust_channels(testOutput.data(), channelCount, stereoTestOutput.data(), FCC_2,
+                        sizeof(float), mTotalFrameCount * sizeof(float) * channelCount);
+
+        // Convert the test data to int16_t
+        std::vector<int16_t> stereoTestI16(mTotalFrameCount * FCC_2);
+        memcpy_to_i16_from_float(stereoTestI16.data(), stereoTestOutput.data(),
+                                 mTotalFrameCount * FCC_2);
+
+        if (isBassBoost(mUuid)) {
+            // SNR must be above the threshold
+            float snr = computeSnr<int16_t>(stereoRefI16.data(), stereoTestI16.data(),
+                                            mTotalFrameCount * FCC_2);
+            ASSERT_GT(snr, EffectTestHelper::kSNRThreshold)
+                    << "SNR " << snr << "is lower than " << EffectTestHelper::kSNRThreshold;
+        } else {
+            ASSERT_EQ(0,
+                      memcmp(stereoRefI16.data(), stereoTestI16.data(), mTotalFrameCount * FCC_2))
+                    << "First two channels do not match with stereo output \n";
+        }
+    }
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        EffectBundleTestAll, SingleEffectComparisonTest,
+        ::testing::Combine(::testing::Range(0, (int)EffectTestHelper::kNumSampleRates),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumFrameCounts),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumLoopCounts),
+                           ::testing::Range(0, (int)kNumEffectUuids)));
+
+int main(int argc, char** argv) {
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = RUN_ALL_TESTS();
+    ALOGV("Test result = %d\n", status);
+    return status;
+}
diff --git a/media/libeffects/lvm/tests/EffectReverbTest.cpp b/media/libeffects/lvm/tests/EffectReverbTest.cpp
new file mode 100644
index 0000000..59453eb
--- /dev/null
+++ b/media/libeffects/lvm/tests/EffectReverbTest.cpp
@@ -0,0 +1,239 @@
+/*
+ * Copyright 2021 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 <audio_effects/effect_presetreverb.h>
+#include <VectorArithmetic.h>
+
+#include "EffectTestHelper.h"
+using namespace android;
+
+constexpr effect_uuid_t kEffectUuids[] = {
+        // NXP SW insert environmental reverb
+        {0xc7a511a0, 0xa3bb, 0x11df, 0x860e, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // NXP SW insert preset reverb
+        {0x172cdf00, 0xa3bc, 0x11df, 0xa72f, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // NXP SW auxiliary environmental reverb
+        {0x4a387fc0, 0x8ab3, 0x11df, 0x8bad, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // NXP SW auxiliary preset reverb
+        {0xf29a1400, 0xa3bb, 0x11df, 0x8ddc, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+};
+
+constexpr size_t kNumEffectUuids = std::size(kEffectUuids);
+
+static bool isAuxMode(const effect_uuid_t* uuid) {
+    // Update this, if the order of effects in kEffectUuids is updated
+    return (uuid == &kEffectUuids[2] || uuid == &kEffectUuids[3]);
+}
+
+constexpr int kPresets[] = {
+        REVERB_PRESET_NONE,      REVERB_PRESET_SMALLROOM,  REVERB_PRESET_MEDIUMROOM,
+        REVERB_PRESET_LARGEROOM, REVERB_PRESET_MEDIUMHALL, REVERB_PRESET_LARGEHALL,
+        REVERB_PRESET_PLATE,
+};
+
+constexpr size_t kNumPresets = std::size(kPresets);
+
+typedef std::tuple<int, int, int, int, int, int> SingleEffectTestParam;
+class SingleEffectTest : public ::testing::TestWithParam<SingleEffectTestParam> {
+  public:
+    SingleEffectTest()
+        : mSampleRate(EffectTestHelper::kSampleRates[std::get<1>(GetParam())]),
+          mFrameCount(EffectTestHelper::kFrameCounts[std::get<2>(GetParam())]),
+          mLoopCount(EffectTestHelper::kLoopCounts[std::get<3>(GetParam())]),
+          mTotalFrameCount(mFrameCount * mLoopCount),
+          mUuid(&kEffectUuids[std::get<4>(GetParam())]),
+          mInChMask(isAuxMode(mUuid) ? AUDIO_CHANNEL_OUT_MONO
+                                     : EffectTestHelper::kChMasks[std::get<0>(GetParam())]),
+          mInChannelCount(audio_channel_count_from_out_mask(mInChMask)),
+          mOutChMask(EffectTestHelper::kChMasks[std::get<0>(GetParam())]),
+          mOutChannelCount(audio_channel_count_from_out_mask(mOutChMask)),
+          mPreset(kPresets[std::get<5>(GetParam())]) {}
+
+    const size_t mSampleRate;
+    const size_t mFrameCount;
+    const size_t mLoopCount;
+    const size_t mTotalFrameCount;
+    const effect_uuid_t* mUuid;
+    const size_t mInChMask;
+    const size_t mInChannelCount;
+    const size_t mOutChMask;
+    const size_t mOutChannelCount;
+    const size_t mPreset;
+};
+
+// Tests applying a single effect
+TEST_P(SingleEffectTest, SimpleProcess) {
+    SCOPED_TRACE(testing::Message() << "outChMask: " << mOutChMask << " sampleRate: " << mSampleRate
+                                    << " frameCount: " << mFrameCount
+                                    << " loopCount: " << mLoopCount << " preset: " << mPreset);
+
+    EffectTestHelper effect(mUuid, mInChMask, mOutChMask, mSampleRate, mFrameCount, mLoopCount);
+
+    ASSERT_NO_FATAL_FAILURE(effect.createEffect());
+    ASSERT_NO_FATAL_FAILURE(effect.setConfig());
+    ASSERT_NO_FATAL_FAILURE(effect.setParam(REVERB_PARAM_PRESET, mPreset));
+
+    // Initialize input buffer with deterministic pseudo-random values
+    std::vector<float> input(mTotalFrameCount * mInChannelCount);
+    std::vector<float> output(mTotalFrameCount * mOutChannelCount);
+    std::minstd_rand gen(mOutChMask);
+    std::uniform_real_distribution<> dis(-1.0f, 1.0f);
+    for (auto& in : input) {
+        in = dis(gen);
+    }
+    ASSERT_NO_FATAL_FAILURE(effect.process(input.data(), output.data()));
+    ASSERT_NO_FATAL_FAILURE(effect.releaseEffect());
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        EffectReverbTestAll, SingleEffectTest,
+        ::testing::Combine(::testing::Range(0, (int)EffectTestHelper::kNumChMasks),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumSampleRates),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumFrameCounts),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumLoopCounts),
+                           ::testing::Range(0, (int)kNumEffectUuids),
+                           ::testing::Range(0, (int)kNumPresets)));
+
+typedef std::tuple<int, int, int, int, int> SingleEffectComparisonTestParam;
+class SingleEffectComparisonTest
+    : public ::testing::TestWithParam<SingleEffectComparisonTestParam> {
+  public:
+    SingleEffectComparisonTest()
+        : mSampleRate(EffectTestHelper::kSampleRates[std::get<0>(GetParam())]),
+          mFrameCount(EffectTestHelper::kFrameCounts[std::get<1>(GetParam())]),
+          mLoopCount(EffectTestHelper::kLoopCounts[std::get<2>(GetParam())]),
+          mTotalFrameCount(mFrameCount * mLoopCount),
+          mUuid(&kEffectUuids[std::get<3>(GetParam())]),
+          mPreset(kPresets[std::get<4>(GetParam())]) {}
+
+    const size_t mSampleRate;
+    const size_t mFrameCount;
+    const size_t mLoopCount;
+    const size_t mTotalFrameCount;
+    const effect_uuid_t* mUuid;
+    const size_t mPreset;
+};
+
+// Compares first two channels in multi-channel output to stereo output when same effect is applied
+TEST_P(SingleEffectComparisonTest, SimpleProcess) {
+    SCOPED_TRACE(testing::Message()
+                 << " sampleRate: " << mSampleRate << " frameCount: " << mFrameCount
+                 << " loopCount: " << mLoopCount << " preset: " << mPreset);
+
+    // Initialize mono input buffer with deterministic pseudo-random values
+    std::vector<float> monoInput(mTotalFrameCount);
+
+    std::minstd_rand gen(mSampleRate);
+    std::uniform_real_distribution<> dis(-1.0f, 1.0f);
+    for (auto& in : monoInput) {
+        in = dis(gen);
+    }
+
+    // Generate stereo by repeating mono channel data
+    std::vector<float> stereoInput(mTotalFrameCount * FCC_2);
+    adjust_channels(monoInput.data(), FCC_1, stereoInput.data(), FCC_2, sizeof(float),
+                    mTotalFrameCount * sizeof(float) * FCC_1);
+
+    // Apply effect on stereo channels
+    EffectTestHelper stereoEffect(
+            mUuid, isAuxMode(mUuid) ? AUDIO_CHANNEL_OUT_MONO : AUDIO_CHANNEL_OUT_STEREO,
+            AUDIO_CHANNEL_OUT_STEREO, mSampleRate, mFrameCount, mLoopCount);
+
+    ASSERT_NO_FATAL_FAILURE(stereoEffect.createEffect());
+    ASSERT_NO_FATAL_FAILURE(stereoEffect.setConfig());
+    ASSERT_NO_FATAL_FAILURE(stereoEffect.setParam(REVERB_PARAM_PRESET, mPreset));
+
+    std::vector<float> stereoOutput(mTotalFrameCount * FCC_2);
+    ASSERT_NO_FATAL_FAILURE(stereoEffect.process(
+            (isAuxMode(mUuid) ? monoInput.data() : stereoInput.data()), stereoOutput.data()));
+    ASSERT_NO_FATAL_FAILURE(stereoEffect.releaseEffect());
+
+    // Average of both channels data is stored for mono comparison
+    std::vector<float> monoOutput(mTotalFrameCount);
+    From2iToMono_Float((const float*)stereoOutput.data(), monoOutput.data(), mTotalFrameCount);
+
+    // Convert stereo float data to stereo int16_t to be used as reference
+    std::vector<int16_t> stereoRefI16(mTotalFrameCount * FCC_2);
+    memcpy_to_i16_from_float(stereoRefI16.data(), stereoOutput.data(), mTotalFrameCount * FCC_2);
+
+    // mono int16_t to be used as refernece for mono comparison
+    std::vector<int16_t> monoRefI16(mTotalFrameCount);
+    memcpy_to_i16_from_float(monoRefI16.data(), monoOutput.data(), mTotalFrameCount);
+
+    for (size_t outChMask : EffectTestHelper::kChMasks) {
+        size_t outChannelCount = audio_channel_count_from_out_mask(outChMask);
+        size_t inChMask = isAuxMode(mUuid) ? AUDIO_CHANNEL_OUT_MONO : outChMask;
+
+        EffectTestHelper testEffect(mUuid, inChMask, outChMask, mSampleRate, mFrameCount,
+                                    mLoopCount);
+
+        ASSERT_NO_FATAL_FAILURE(testEffect.createEffect());
+        ASSERT_NO_FATAL_FAILURE(testEffect.setConfig());
+        ASSERT_NO_FATAL_FAILURE(testEffect.setParam(REVERB_PARAM_PRESET, mPreset));
+
+        std::vector<float> testInput(mTotalFrameCount * outChannelCount);
+
+        // Repeat mono channel data to all the channels
+        // adjust_channels() zero fills channels > 2, hence can't be used here
+        for (size_t i = 0; i < mTotalFrameCount; ++i) {
+            auto* fp = &testInput[i * outChannelCount];
+            std::fill(fp, fp + outChannelCount, monoInput[i]);
+        }
+
+        std::vector<float> testOutput(mTotalFrameCount * outChannelCount);
+        ASSERT_NO_FATAL_FAILURE(testEffect.process(
+                (isAuxMode(mUuid) ? monoInput.data() : testInput.data()), testOutput.data()));
+        ASSERT_NO_FATAL_FAILURE(testEffect.releaseEffect());
+
+        if (outChannelCount == FCC_1) {
+            // Convert the test data to int16_t
+            std::vector<int16_t> monoTestI16(mTotalFrameCount);
+            memcpy_to_i16_from_float(monoTestI16.data(), testOutput.data(), mTotalFrameCount);
+
+            ASSERT_EQ(0, memcmp(monoRefI16.data(), monoTestI16.data(), mTotalFrameCount * FCC_2))
+                    << "Mono channel do not match with reference output \n";
+        } else {
+            // Extract first two channels
+            std::vector<float> stereoTestOutput(mTotalFrameCount * FCC_2);
+            adjust_channels(testOutput.data(), outChannelCount, stereoTestOutput.data(), FCC_2,
+                            sizeof(float), mTotalFrameCount * sizeof(float) * outChannelCount);
+
+            // Convert the test data to int16_t
+            std::vector<int16_t> stereoTestI16(mTotalFrameCount * FCC_2);
+            memcpy_to_i16_from_float(stereoTestI16.data(), stereoTestOutput.data(),
+                                     mTotalFrameCount * FCC_2);
+
+            ASSERT_EQ(0,
+                      memcmp(stereoRefI16.data(), stereoTestI16.data(), mTotalFrameCount * FCC_2))
+                    << "First two channels do not match with stereo output \n";
+        }
+    }
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        EffectReverbTestAll, SingleEffectComparisonTest,
+        ::testing::Combine(::testing::Range(0, (int)EffectTestHelper::kNumSampleRates),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumFrameCounts),
+                           ::testing::Range(0, (int)EffectTestHelper::kNumLoopCounts),
+                           ::testing::Range(0, (int)kNumEffectUuids),
+                           ::testing::Range(0, (int)kNumPresets)));
+
+int main(int argc, char** argv) {
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = RUN_ALL_TESTS();
+    ALOGV("Test result = %d\n", status);
+    return status;
+}
diff --git a/media/libeffects/lvm/tests/EffectTestHelper.cpp b/media/libeffects/lvm/tests/EffectTestHelper.cpp
new file mode 100644
index 0000000..625c15a
--- /dev/null
+++ b/media/libeffects/lvm/tests/EffectTestHelper.cpp
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2021 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 "EffectTestHelper.h"
+extern audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM;
+
+namespace android {
+
+void EffectTestHelper::createEffect() {
+    int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.create_effect(mUuid, 1, 1, &mEffectHandle);
+    ASSERT_EQ(status, 0) << "create_effect returned an error " << status;
+}
+
+void EffectTestHelper::releaseEffect() {
+    int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.release_effect(mEffectHandle);
+    ASSERT_EQ(status, 0) << "release_effect returned an error " << status;
+}
+
+void EffectTestHelper::setConfig() {
+    effect_config_t config{};
+    config.inputCfg.samplingRate = config.outputCfg.samplingRate = mSampleRate;
+    config.inputCfg.channels = mInChMask;
+    config.outputCfg.channels = mOutChMask;
+    config.inputCfg.format = config.outputCfg.format = AUDIO_FORMAT_PCM_FLOAT;
+
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    int status = (*mEffectHandle)
+                         ->command(mEffectHandle, EFFECT_CMD_SET_CONFIG, sizeof(effect_config_t),
+                                   &config, &replySize, &reply);
+    ASSERT_EQ(status, 0) << "set_config returned an error " << status;
+    ASSERT_EQ(reply, 0) << "set_config reply non zero " << reply;
+
+    status = (*mEffectHandle)
+                     ->command(mEffectHandle, EFFECT_CMD_ENABLE, 0, nullptr, &replySize, &reply);
+    ASSERT_EQ(status, 0) << "cmd_enable returned an error " << status;
+    ASSERT_EQ(reply, 0) << "cmd_enable reply non zero " << reply;
+}
+
+void EffectTestHelper::setParam(uint32_t type, uint32_t value) {
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    uint32_t paramData[2] = {type, value};
+    auto effectParam = new effect_param_t[sizeof(effect_param_t) + sizeof(paramData)];
+    memcpy(&effectParam->data[0], &paramData[0], sizeof(paramData));
+    effectParam->psize = sizeof(paramData[0]);
+    effectParam->vsize = sizeof(paramData[1]);
+    int status = (*mEffectHandle)
+                         ->command(mEffectHandle, EFFECT_CMD_SET_PARAM,
+                                   sizeof(effect_param_t) + sizeof(paramData), effectParam,
+                                   &replySize, &reply);
+    delete[] effectParam;
+    ASSERT_EQ(status, 0) << "set_param returned an error " << status;
+    ASSERT_EQ(reply, 0) << "set_param reply non zero " << reply;
+}
+
+void EffectTestHelper::process(float* input, float* output) {
+    audio_buffer_t inBuffer = {.frameCount = mFrameCount, .f32 = input};
+    audio_buffer_t outBuffer = {.frameCount = mFrameCount, .f32 = output};
+    for (size_t i = 0; i < mLoopCount; i++) {
+        int status = (*mEffectHandle)->process(mEffectHandle, &inBuffer, &outBuffer);
+        ASSERT_EQ(status, 0) << "process returned an error " << status;
+
+        inBuffer.f32 += mFrameCount * mInChannelCount;
+        outBuffer.f32 += mFrameCount * mOutChannelCount;
+    }
+}
+}  // namespace android
diff --git a/media/libeffects/lvm/tests/EffectTestHelper.h b/media/libeffects/lvm/tests/EffectTestHelper.h
new file mode 100644
index 0000000..3854d46
--- /dev/null
+++ b/media/libeffects/lvm/tests/EffectTestHelper.h
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2021 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.
+ */
+
+#pragma once
+
+#include <array>
+#include <audio_utils/channels.h>
+#include <audio_utils/primitives.h>
+#include <climits>
+#include <cstdlib>
+#include <gtest/gtest.h>
+#include <hardware/audio_effect.h>
+#include <log/log.h>
+#include <random>
+#include <stdint.h>
+#include <system/audio.h>
+#include <vector>
+
+namespace android {
+template <typename T>
+static float computeSnr(const T* ref, const T* tst, size_t count) {
+    double signal{};
+    double noise{};
+
+    for (size_t i = 0; i < count; ++i) {
+        const double value(ref[i]);
+        const double diff(tst[i] - value);
+        signal += value * value;
+        noise += diff * diff;
+    }
+    // Initialized to large value to handle
+    // cases where ref and tst match exactly
+    float snr = FLT_MAX;
+    if (signal > 0.0f && noise > 0.0f) {
+        snr = 10.f * log(signal / noise);
+    }
+    return snr;
+}
+
+class EffectTestHelper {
+  public:
+    EffectTestHelper(const effect_uuid_t* uuid, size_t inChMask, size_t outChMask,
+                     size_t sampleRate, size_t frameCount, size_t loopCount)
+        : mUuid(uuid),
+          mInChMask(inChMask),
+          mInChannelCount(audio_channel_count_from_out_mask(mInChMask)),
+          mOutChMask(outChMask),
+          mOutChannelCount(audio_channel_count_from_out_mask(mOutChMask)),
+          mSampleRate(sampleRate),
+          mFrameCount(frameCount),
+          mLoopCount(loopCount) {}
+    void createEffect();
+    void releaseEffect();
+    void setConfig();
+    void setParam(uint32_t type, uint32_t val);
+    void process(float* input, float* output);
+
+    // Corresponds to SNR for 1 bit difference between two int16_t signals
+    static constexpr float kSNRThreshold = 90.308998;
+
+    static constexpr audio_channel_mask_t kChMasks[] = {
+            AUDIO_CHANNEL_OUT_MONO,          AUDIO_CHANNEL_OUT_STEREO,
+            AUDIO_CHANNEL_OUT_2POINT1,       AUDIO_CHANNEL_OUT_2POINT0POINT2,
+            AUDIO_CHANNEL_OUT_QUAD,          AUDIO_CHANNEL_OUT_QUAD_BACK,
+            AUDIO_CHANNEL_OUT_QUAD_SIDE,     AUDIO_CHANNEL_OUT_SURROUND,
+            AUDIO_CHANNEL_INDEX_MASK_4,      AUDIO_CHANNEL_OUT_2POINT1POINT2,
+            AUDIO_CHANNEL_OUT_3POINT0POINT2, AUDIO_CHANNEL_OUT_PENTA,
+            AUDIO_CHANNEL_INDEX_MASK_5,      AUDIO_CHANNEL_OUT_3POINT1POINT2,
+            AUDIO_CHANNEL_OUT_5POINT1,       AUDIO_CHANNEL_OUT_5POINT1_BACK,
+            AUDIO_CHANNEL_OUT_5POINT1_SIDE,  AUDIO_CHANNEL_INDEX_MASK_6,
+            AUDIO_CHANNEL_OUT_6POINT1,       AUDIO_CHANNEL_INDEX_MASK_7,
+            AUDIO_CHANNEL_OUT_5POINT1POINT2, AUDIO_CHANNEL_OUT_7POINT1,
+            AUDIO_CHANNEL_INDEX_MASK_8,      AUDIO_CHANNEL_INDEX_MASK_9,
+            AUDIO_CHANNEL_INDEX_MASK_10,     AUDIO_CHANNEL_INDEX_MASK_11,
+            AUDIO_CHANNEL_INDEX_MASK_12,     AUDIO_CHANNEL_INDEX_MASK_13,
+            AUDIO_CHANNEL_INDEX_MASK_14,     AUDIO_CHANNEL_INDEX_MASK_15,
+            AUDIO_CHANNEL_INDEX_MASK_16,     AUDIO_CHANNEL_INDEX_MASK_17,
+            AUDIO_CHANNEL_INDEX_MASK_18,     AUDIO_CHANNEL_INDEX_MASK_19,
+            AUDIO_CHANNEL_INDEX_MASK_20,     AUDIO_CHANNEL_INDEX_MASK_21,
+            AUDIO_CHANNEL_INDEX_MASK_22,     AUDIO_CHANNEL_INDEX_MASK_23,
+            AUDIO_CHANNEL_INDEX_MASK_24,
+    };
+
+    static constexpr size_t kNumChMasks = std::size(kChMasks);
+
+    static constexpr size_t kSampleRates[] = {8000,  11025, 12000, 16000, 22050,  24000, 32000,
+                                              44100, 48000, 88200, 96000, 176400, 192000};
+
+    static constexpr size_t kNumSampleRates = std::size(kSampleRates);
+
+    static constexpr size_t kFrameCounts[] = {4, 2048};
+
+    static constexpr size_t kNumFrameCounts = std::size(kFrameCounts);
+
+    static constexpr size_t kLoopCounts[] = {1, 4};
+
+    static constexpr size_t kNumLoopCounts = std::size(kLoopCounts);
+
+  private:
+    const effect_uuid_t* mUuid;
+    const size_t mInChMask;
+    const size_t mInChannelCount;
+    const size_t mOutChMask;
+    const size_t mOutChannelCount;
+    const size_t mSampleRate;
+    const size_t mFrameCount;
+    const size_t mLoopCount;
+    effect_handle_t mEffectHandle{};
+};
+}  // namespace android
diff --git a/media/libeffects/lvm/tests/build_and_run_all_unit_tests.sh b/media/libeffects/lvm/tests/build_and_run_all_unit_tests.sh
index a97acc9..df7ca5a 100755
--- a/media/libeffects/lvm/tests/build_and_run_all_unit_tests.sh
+++ b/media/libeffects/lvm/tests/build_and_run_all_unit_tests.sh
@@ -23,7 +23,7 @@
 echo "========================================"
 echo "testing lvm"
 adb shell mkdir -p $testdir
-adb push $ANDROID_BUILD_TOP/cts/tests/tests/media/res/raw/sinesweepraw.raw $testdir
+adb push $ANDROID_BUILD_TOP/frameworks/av/media/libeffects/res/raw/sinesweepraw.raw $testdir
 adb push $OUT/testcases/snr/arm64/snr $testdir
 
 E_VAL=1
@@ -91,7 +91,7 @@
     do
         for fs in ${fs_arr[*]}
         do
-            for chMask in {0..22}
+            for chMask in {0..38}
             do
                 adb shell $testdir/lvmtest -i:$testdir/sinesweepraw.raw \
                     -o:$testdir/sinesweep_$((chMask))_$((fs)).raw -chMask:$chMask -fs:$fs $flags
@@ -102,6 +102,11 @@
                     ((++error_count))
                 fi
 
+                # Do not compare cases where -vcBal is in flags and chMask is 0 (due to
+                # stereo computation)
+                if [[ $flags == *"-vcBal:"* ]] && [[ $chMask -eq 0 ]]; then
+                    continue
+                fi
 
                 # two channel files should be identical to higher channel
                 # computation (first 2 channels).
diff --git a/media/libeffects/lvm/tests/build_and_run_all_unit_tests_reverb.sh b/media/libeffects/lvm/tests/build_and_run_all_unit_tests_reverb.sh
new file mode 100755
index 0000000..72b370e
--- /dev/null
+++ b/media/libeffects/lvm/tests/build_and_run_all_unit_tests_reverb.sh
@@ -0,0 +1,105 @@
+#!/bin/bash
+#
+# reverb test
+#
+
+if [ -z "$ANDROID_BUILD_TOP" ]; then
+    echo "Android build environment not set"
+    exit -1
+fi
+
+# ensure we have mm
+. $ANDROID_BUILD_TOP/build/envsetup.sh
+
+mm -j
+
+echo "waiting for device"
+
+adb root && adb wait-for-device remount
+
+# location of test files
+testdir="/data/local/tmp/revTest"
+
+echo "========================================"
+echo "testing reverb"
+adb shell mkdir -p $testdir
+adb push $ANDROID_BUILD_TOP/frameworks/av/media/libeffects/res/raw/sinesweepraw.raw $testdir
+
+E_VAL=1
+cmds="adb push $OUT/testcases/reverb_test/arm/reverb_test $testdir"
+
+fs_arr=(
+    8000
+    16000
+    22050
+    32000
+    44100
+    48000
+    88200
+    96000
+    176400
+    192000
+)
+
+flags_arr=(
+    "--M --fch 1"
+    "--fch 2"
+)
+
+# run reverb at different configs, saving only the stereo channel
+# pair.
+error_count=0
+testcase_count=0
+for cmd in "${cmds[@]}"
+do
+    $cmd
+    for flags in "${flags_arr[@]}"
+    do
+        for preset_val in {0..6}
+        do
+            for fs in ${fs_arr[*]}
+            do
+                for chMask in {0..38}
+                do
+                    adb shell $testdir/reverb_test \
+                        --input $testdir/sinesweepraw.raw \
+                        --output $testdir/sinesweep_$((chMask))_$((fs)).raw \
+                        --chMask $chMask $flags --fs $fs --preset $preset_val
+
+                    shell_ret=$?
+                    if [ $shell_ret -ne 0 ]; then
+                        echo "error: $shell_ret"
+                        ((++error_count))
+                    fi
+
+                    if [[ "$chMask" -gt 0 ]] && [[ $flags != *"--fch 2"* ]]
+                    then
+                        # single channel files should be identical to higher channel
+                        # computation (first channel).
+                        adb shell cmp $testdir/sinesweep_0_$((fs)).raw \
+                            $testdir/sinesweep_$((chMask))_$((fs)).raw
+                    elif [[ "$chMask" -gt 1 ]]
+                    then
+                        # two channel files should be identical to higher channel
+                        # computation (first 2 channels).
+                        adb shell cmp $testdir/sinesweep_1_$((fs)).raw \
+                            $testdir/sinesweep_$((chMask))_$((fs)).raw
+                    fi
+
+                    # cmp returns EXIT_FAILURE on mismatch.
+                    shell_ret=$?
+                    if [ $shell_ret -ne 0 ]; then
+                        echo "error: $shell_ret"
+                        ((++error_count))
+                    fi
+                    ((++testcase_count))
+                done
+            done
+        done
+    done
+done
+
+adb shell rm -r $testdir
+echo "$testcase_count tests performed"
+echo "$error_count errors"
+exit $error_count
diff --git a/media/libeffects/lvm/tests/lvmtest.cpp b/media/libeffects/lvm/tests/lvmtest.cpp
index a4ace6c..e484a1a 100644
--- a/media/libeffects/lvm/tests/lvmtest.cpp
+++ b/media/libeffects/lvm/tests/lvmtest.cpp
@@ -33,198 +33,164 @@
 #define ALOGVV ALOGV
 #else
 #define ALOGVV(a...) \
-  do {               \
-  } while (false)
+    do {             \
+    } while (false)
 #endif
 
-#define CHECK_ARG(cond)                                \
-  {                                                    \
-    if (!(cond)) {                                     \
-      ALOGE("\tLVM_ERROR : Invalid argument: " #cond); \
-      return -EINVAL;                                  \
-    }                                                  \
-  \
-}
+#define CHECK_ARG(cond)                                      \
+    {                                                        \
+        if (!(cond)) {                                       \
+            ALOGE("\tLVM_ERROR : Invalid argument: " #cond); \
+            return -EINVAL;                                  \
+        }                                                    \
+    }
 
-#define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc)     \
-  {                                                             \
-    if ((LvmStatus) == LVM_NULLADDRESS) {                       \
-      ALOGE(                                                    \
-          "\tLVM_ERROR : Parameter error - "                    \
-          "null pointer returned by %s in %s\n\n\n\n",          \
-          callingFunc, calledFunc);                             \
-    }                                                           \
-    if ((LvmStatus) == LVM_ALIGNMENTERROR) {                    \
-      ALOGE(                                                    \
-          "\tLVM_ERROR : Parameter error - "                    \
-          "bad alignment returned by %s in %s\n\n\n\n",         \
-          callingFunc, calledFunc);                             \
-    }                                                           \
-    if ((LvmStatus) == LVM_INVALIDNUMSAMPLES) {                 \
-      ALOGE(                                                    \
-          "\tLVM_ERROR : Parameter error - "                    \
-          "bad number of samples returned by %s in %s\n\n\n\n", \
-          callingFunc, calledFunc);                             \
-    }                                                           \
-    if ((LvmStatus) == LVM_OUTOFRANGE) {                        \
-      ALOGE(                                                    \
-          "\tLVM_ERROR : Parameter error - "                    \
-          "out of range returned by %s in %s\n",                \
-          callingFunc, calledFunc);                             \
-    }                                                           \
-  }
+#define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc)             \
+    {                                                                   \
+        if ((LvmStatus) == LVM_NULLADDRESS) {                           \
+            ALOGE("\tLVM_ERROR : Parameter error - "                    \
+                  "null pointer returned by %s in %s\n\n\n\n",          \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
+        if ((LvmStatus) == LVM_ALIGNMENTERROR) {                        \
+            ALOGE("\tLVM_ERROR : Parameter error - "                    \
+                  "bad alignment returned by %s in %s\n\n\n\n",         \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
+        if ((LvmStatus) == LVM_INVALIDNUMSAMPLES) {                     \
+            ALOGE("\tLVM_ERROR : Parameter error - "                    \
+                  "bad number of samples returned by %s in %s\n\n\n\n", \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
+        if ((LvmStatus) == LVM_OUTOFRANGE) {                            \
+            ALOGE("\tLVM_ERROR : Parameter error - "                    \
+                  "out of range returned by %s in %s\n",                \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
+    }
 
 struct lvmConfigParams_t {
-  int              samplingFreq    = 44100;
-  int              nrChannels      = 2;
-  int              chMask          = AUDIO_CHANNEL_OUT_STEREO;
-  int              vcBal           = 0;
-  int              fChannels       = 2;
-  bool             monoMode        = false;
-  int              bassEffectLevel = 0;
-  int              eqPresetLevel   = 0;
-  int              frameLength     = 256;
-  LVM_BE_Mode_en   bassEnable      = LVM_BE_OFF;
-  LVM_TE_Mode_en   trebleEnable    = LVM_TE_OFF;
-  LVM_EQNB_Mode_en eqEnable        = LVM_EQNB_OFF;
-  LVM_Mode_en      csEnable        = LVM_MODE_OFF;
+    int samplingFreq = 44100;
+    int nrChannels = 2;
+    int chMask = AUDIO_CHANNEL_OUT_STEREO;
+    int vcBal = 0;
+    int fChannels = 2;
+    bool monoMode = false;
+    int bassEffectLevel = 0;
+    int eqPresetLevel = 0;
+    int frameLength = 256;
+    LVM_BE_Mode_en bassEnable = LVM_BE_OFF;
+    LVM_TE_Mode_en trebleEnable = LVM_TE_OFF;
+    LVM_EQNB_Mode_en eqEnable = LVM_EQNB_OFF;
+    LVM_Mode_en csEnable = LVM_MODE_OFF;
 };
 
 constexpr audio_channel_mask_t lvmConfigChMask[] = {
-    AUDIO_CHANNEL_OUT_MONO,
-    AUDIO_CHANNEL_OUT_STEREO,
-    AUDIO_CHANNEL_OUT_2POINT1,
-    AUDIO_CHANNEL_OUT_2POINT0POINT2,
-    AUDIO_CHANNEL_OUT_QUAD,
-    AUDIO_CHANNEL_OUT_QUAD_BACK,
-    AUDIO_CHANNEL_OUT_QUAD_SIDE,
-    AUDIO_CHANNEL_OUT_SURROUND,
-    (1 << 4) - 1,
-    AUDIO_CHANNEL_OUT_2POINT1POINT2,
-    AUDIO_CHANNEL_OUT_3POINT0POINT2,
-    AUDIO_CHANNEL_OUT_PENTA,
-    (1 << 5) - 1,
-    AUDIO_CHANNEL_OUT_3POINT1POINT2,
-    AUDIO_CHANNEL_OUT_5POINT1,
-    AUDIO_CHANNEL_OUT_5POINT1_BACK,
-    AUDIO_CHANNEL_OUT_5POINT1_SIDE,
-    (1 << 6) - 1,
-    AUDIO_CHANNEL_OUT_6POINT1,
-    (1 << 7) - 1,
-    AUDIO_CHANNEL_OUT_5POINT1POINT2,
-    AUDIO_CHANNEL_OUT_7POINT1,
-    (1 << 8) - 1,
+        AUDIO_CHANNEL_OUT_MONO,
+        AUDIO_CHANNEL_OUT_STEREO,
+        AUDIO_CHANNEL_OUT_2POINT1,
+        AUDIO_CHANNEL_OUT_2POINT0POINT2,
+        AUDIO_CHANNEL_OUT_QUAD,
+        AUDIO_CHANNEL_OUT_QUAD_BACK,
+        AUDIO_CHANNEL_OUT_QUAD_SIDE,
+        AUDIO_CHANNEL_OUT_SURROUND,
+        AUDIO_CHANNEL_INDEX_MASK_4,
+        AUDIO_CHANNEL_OUT_2POINT1POINT2,
+        AUDIO_CHANNEL_OUT_3POINT0POINT2,
+        AUDIO_CHANNEL_OUT_PENTA,
+        AUDIO_CHANNEL_INDEX_MASK_5,
+        AUDIO_CHANNEL_OUT_3POINT1POINT2,
+        AUDIO_CHANNEL_OUT_5POINT1,
+        AUDIO_CHANNEL_OUT_5POINT1_BACK,
+        AUDIO_CHANNEL_OUT_5POINT1_SIDE,
+        AUDIO_CHANNEL_INDEX_MASK_6,
+        AUDIO_CHANNEL_OUT_6POINT1,
+        AUDIO_CHANNEL_INDEX_MASK_7,
+        AUDIO_CHANNEL_OUT_5POINT1POINT2,
+        AUDIO_CHANNEL_OUT_7POINT1,
+        AUDIO_CHANNEL_INDEX_MASK_8,
+        AUDIO_CHANNEL_INDEX_MASK_9,
+        AUDIO_CHANNEL_INDEX_MASK_10,
+        AUDIO_CHANNEL_INDEX_MASK_11,
+        AUDIO_CHANNEL_INDEX_MASK_12,
+        AUDIO_CHANNEL_INDEX_MASK_13,
+        AUDIO_CHANNEL_INDEX_MASK_14,
+        AUDIO_CHANNEL_INDEX_MASK_15,
+        AUDIO_CHANNEL_INDEX_MASK_16,
+        AUDIO_CHANNEL_INDEX_MASK_17,
+        AUDIO_CHANNEL_INDEX_MASK_18,
+        AUDIO_CHANNEL_INDEX_MASK_19,
+        AUDIO_CHANNEL_INDEX_MASK_20,
+        AUDIO_CHANNEL_INDEX_MASK_21,
+        AUDIO_CHANNEL_INDEX_MASK_22,
+        AUDIO_CHANNEL_INDEX_MASK_23,
+        AUDIO_CHANNEL_INDEX_MASK_24,
 };
 
-
 void printUsage() {
-  printf("\nUsage: ");
-  printf("\n     <executable> -i:<input_file> -o:<out_file> [options]\n");
-  printf("\nwhere, \n     <inputfile>  is the input file name");
-  printf("\n                  on which LVM effects are applied");
-  printf("\n     <outputfile> processed output file");
-  printf("\n     and options are mentioned below");
-  printf("\n");
-  printf("\n     -help (or) -h");
-  printf("\n           Prints this usage information");
-  printf("\n");
-  printf("\n     -chMask:<channel_mask>\n");
-  printf("\n         0  - AUDIO_CHANNEL_OUT_MONO");
-  printf("\n         1  - AUDIO_CHANNEL_OUT_STEREO");
-  printf("\n         2  - AUDIO_CHANNEL_OUT_2POINT1");
-  printf("\n         3  - AUDIO_CHANNEL_OUT_2POINT0POINT2");
-  printf("\n         4  - AUDIO_CHANNEL_OUT_QUAD");
-  printf("\n         5  - AUDIO_CHANNEL_OUT_QUAD_BACK");
-  printf("\n         6  - AUDIO_CHANNEL_OUT_QUAD_SIDE");
-  printf("\n         7  - AUDIO_CHANNEL_OUT_SURROUND");
-  printf("\n         8  - canonical channel index mask for 4 ch: (1 << 4) - 1");
-  printf("\n         9  - AUDIO_CHANNEL_OUT_2POINT1POINT2");
-  printf("\n         10 - AUDIO_CHANNEL_OUT_3POINT0POINT2");
-  printf("\n         11 - AUDIO_CHANNEL_OUT_PENTA");
-  printf("\n         12 - canonical channel index mask for 5 ch: (1 << 5) - 1");
-  printf("\n         13 - AUDIO_CHANNEL_OUT_3POINT1POINT2");
-  printf("\n         14 - AUDIO_CHANNEL_OUT_5POINT1");
-  printf("\n         15 - AUDIO_CHANNEL_OUT_5POINT1_BACK");
-  printf("\n         16 - AUDIO_CHANNEL_OUT_5POINT1_SIDE");
-  printf("\n         17 - canonical channel index mask for 6 ch: (1 << 6) - 1");
-  printf("\n         18 - AUDIO_CHANNEL_OUT_6POINT1");
-  printf("\n         19 - canonical channel index mask for 7 ch: (1 << 7) - 1");
-  printf("\n         20 - AUDIO_CHANNEL_OUT_5POINT1POINT2");
-  printf("\n         21 - AUDIO_CHANNEL_OUT_7POINT1");
-  printf("\n         22 - canonical channel index mask for 8 ch: (1 << 8) - 1");
-  printf("\n         default 0");
-  printf("\n     -vcBal:<Left Right Balance control in dB [-96 to 96 dB]>");
-  printf("\n            -ve values reduce Right channel while +ve value reduces Left channel");
-  printf("\n                 default 0");
-  printf("\n     -fch:<file_channels> (1 through 8)\n\n");
-  printf("\n     -M");
-  printf("\n           Mono mode (force all input audio channels to be identical)");
-  printf("\n     -basslvl:<effect_level>");
-  printf("\n           A value that ranges between %d - %d default 0", LVM_BE_MIN_EFFECTLEVEL,
-    LVM_BE_MAX_EFFECTLEVEL);
-  printf("\n");
-  printf("\n     -eqPreset:<preset Value>");
-  const size_t numPresetLvls  = std::size(gEqualizerPresets);
-  for (size_t i = 0; i < numPresetLvls; ++i) {
-    printf("\n           %zu - %s", i, gEqualizerPresets[i].name);
-  }
-  printf("\n           default - 0");
-  printf("\n     -bE ");
-  printf("\n           Enable Dynamic Bass Enhancement");
-  printf("\n");
-  printf("\n     -tE ");
-  printf("\n           Enable Treble Boost");
-  printf("\n");
-  printf("\n     -csE ");
-  printf("\n           Enable Concert Surround");
-  printf("\n");
-  printf("\n     -eqE ");
-  printf("\n           Enable Equalizer");
-}
-
-//----------------------------------------------------------------------------
-// LvmEffect_free()
-//----------------------------------------------------------------------------
-// Purpose: Free all memory associated with the Bundle.
-//
-// Inputs:
-//  pContext:   effect engine context
-//
-// Outputs:
-//
-//----------------------------------------------------------------------------
-
-void LvmEffect_free(struct EffectContext *pContext) {
-  LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
-  LVM_MemTab_t MemTab;
-
-  /* Free the algorithm memory */
-  LvmStatus = LVM_GetMemoryTable(pContext->pBundledContext->hInstance, &MemTab,
-                                 LVM_NULL);
-
-  LVM_ERROR_CHECK(LvmStatus, "LVM_GetMemoryTable", "LvmEffect_free")
-
-  for (int i = 0; i < LVM_NR_MEMORY_REGIONS; i++) {
-    if (MemTab.Region[i].Size != 0) {
-      if (MemTab.Region[i].pBaseAddress != NULL) {
-        ALOGV("\tLvmEffect_free - START freeing %" PRIu32
-              " bytes for region %u at %p\n",
-              MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
-
-        free(MemTab.Region[i].pBaseAddress);
-
-        ALOGV("\tLvmEffect_free - END   freeing %" PRIu32
-              " bytes for region %u at %p\n",
-              MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
-      } else {
-        ALOGE(
-            "\tLVM_ERROR : LvmEffect_free - trying to free with NULL pointer "
-            "%" PRIu32 " bytes for region %u at %p ERROR\n",
-            MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
-      }
+    printf("\nUsage: ");
+    printf("\n     <executable> -i:<input_file> -o:<out_file> [options]\n");
+    printf("\nwhere, \n     <inputfile>  is the input file name");
+    printf("\n                  on which LVM effects are applied");
+    printf("\n     <outputfile> processed output file");
+    printf("\n     and options are mentioned below");
+    printf("\n");
+    printf("\n     -help (or) -h");
+    printf("\n           Prints this usage information");
+    printf("\n");
+    printf("\n     -chMask:<channel_mask>\n");
+    printf("\n         0  - AUDIO_CHANNEL_OUT_MONO");
+    printf("\n         1  - AUDIO_CHANNEL_OUT_STEREO");
+    printf("\n         2  - AUDIO_CHANNEL_OUT_2POINT1");
+    printf("\n         3  - AUDIO_CHANNEL_OUT_2POINT0POINT2");
+    printf("\n         4  - AUDIO_CHANNEL_OUT_QUAD");
+    printf("\n         5  - AUDIO_CHANNEL_OUT_QUAD_BACK");
+    printf("\n         6  - AUDIO_CHANNEL_OUT_QUAD_SIDE");
+    printf("\n         7  - AUDIO_CHANNEL_OUT_SURROUND");
+    printf("\n         8  - canonical channel index mask for 4 ch: (1 << 4) - 1");
+    printf("\n         9  - AUDIO_CHANNEL_OUT_2POINT1POINT2");
+    printf("\n         10 - AUDIO_CHANNEL_OUT_3POINT0POINT2");
+    printf("\n         11 - AUDIO_CHANNEL_OUT_PENTA");
+    printf("\n         12 - canonical channel index mask for 5 ch: (1 << 5) - 1");
+    printf("\n         13 - AUDIO_CHANNEL_OUT_3POINT1POINT2");
+    printf("\n         14 - AUDIO_CHANNEL_OUT_5POINT1");
+    printf("\n         15 - AUDIO_CHANNEL_OUT_5POINT1_BACK");
+    printf("\n         16 - AUDIO_CHANNEL_OUT_5POINT1_SIDE");
+    printf("\n         17 - canonical channel index mask for 6 ch: (1 << 6) - 1");
+    printf("\n         18 - AUDIO_CHANNEL_OUT_6POINT1");
+    printf("\n         19 - canonical channel index mask for 7 ch: (1 << 7) - 1");
+    printf("\n         20 - AUDIO_CHANNEL_OUT_5POINT1POINT2");
+    printf("\n         21 - AUDIO_CHANNEL_OUT_7POINT1");
+    printf("\n         22 - canonical channel index mask for 8 ch: (1 << 8) - 1");
+    printf("\n         default 0");
+    printf("\n     -vcBal:<Left Right Balance control in dB [-96 to 96 dB]>");
+    printf("\n            -ve values reduce Right channel while +ve value reduces Left channel");
+    printf("\n                 default 0");
+    printf("\n     -fch:<file_channels> (1 through 8)\n\n");
+    printf("\n     -M");
+    printf("\n           Mono mode (force all input audio channels to be identical)");
+    printf("\n     -basslvl:<effect_level>");
+    printf("\n           A value that ranges between %d - %d default 0", LVM_BE_MIN_EFFECTLEVEL,
+           LVM_BE_MAX_EFFECTLEVEL);
+    printf("\n");
+    printf("\n     -eqPreset:<preset Value>");
+    const size_t numPresetLvls = std::size(gEqualizerPresets);
+    for (size_t i = 0; i < numPresetLvls; ++i) {
+        printf("\n           %zu - %s", i, gEqualizerPresets[i].name);
     }
-  }
-} /* end LvmEffect_free */
+    printf("\n           default - 0");
+    printf("\n     -bE ");
+    printf("\n           Enable Dynamic Bass Enhancement");
+    printf("\n");
+    printf("\n     -tE ");
+    printf("\n           Enable Treble Boost");
+    printf("\n");
+    printf("\n     -csE ");
+    printf("\n           Enable Concert Surround");
+    printf("\n");
+    printf("\n     -eqE ");
+    printf("\n           Enable Equalizer");
+}
 
 //----------------------------------------------------------------------------
 // LvmBundle_init()
@@ -239,586 +205,461 @@
 //
 //----------------------------------------------------------------------------
 
-int LvmBundle_init(struct EffectContext *pContext, LVM_ControlParams_t *params) {
-  ALOGV("\tLvmBundle_init start");
+int LvmBundle_init(struct EffectContext* pContext, LVM_ControlParams_t* params) {
+    ALOGV("\tLvmBundle_init start");
 
-  pContext->config.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
-  pContext->config.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
-  pContext->config.inputCfg.format = EFFECT_BUFFER_FORMAT;
-  pContext->config.inputCfg.samplingRate = 44100;
-  pContext->config.inputCfg.bufferProvider.getBuffer = NULL;
-  pContext->config.inputCfg.bufferProvider.releaseBuffer = NULL;
-  pContext->config.inputCfg.bufferProvider.cookie = NULL;
-  pContext->config.inputCfg.mask = EFFECT_CONFIG_ALL;
-  pContext->config.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
-  pContext->config.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
-  pContext->config.outputCfg.format = EFFECT_BUFFER_FORMAT;
-  pContext->config.outputCfg.samplingRate = 44100;
-  pContext->config.outputCfg.bufferProvider.getBuffer = NULL;
-  pContext->config.outputCfg.bufferProvider.releaseBuffer = NULL;
-  pContext->config.outputCfg.bufferProvider.cookie = NULL;
-  pContext->config.outputCfg.mask = EFFECT_CONFIG_ALL;
+    pContext->config.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
+    pContext->config.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
+    pContext->config.inputCfg.format = EFFECT_BUFFER_FORMAT;
+    pContext->config.inputCfg.samplingRate = 44100;
+    pContext->config.inputCfg.bufferProvider.getBuffer = NULL;
+    pContext->config.inputCfg.bufferProvider.releaseBuffer = NULL;
+    pContext->config.inputCfg.bufferProvider.cookie = NULL;
+    pContext->config.inputCfg.mask = EFFECT_CONFIG_ALL;
+    pContext->config.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
+    pContext->config.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
+    pContext->config.outputCfg.format = EFFECT_BUFFER_FORMAT;
+    pContext->config.outputCfg.samplingRate = 44100;
+    pContext->config.outputCfg.bufferProvider.getBuffer = NULL;
+    pContext->config.outputCfg.bufferProvider.releaseBuffer = NULL;
+    pContext->config.outputCfg.bufferProvider.cookie = NULL;
+    pContext->config.outputCfg.mask = EFFECT_CONFIG_ALL;
 
-  if (pContext->pBundledContext->hInstance != NULL) {
-    ALOGV(
-        "\tLvmBundle_init pContext->pBassBoost != NULL "
-        "-> Calling pContext->pBassBoost->free()");
+    if (pContext->pBundledContext->hInstance != NULL) {
+        ALOGV("\tLvmBundle_init pContext->pBassBoost != NULL "
+              "-> Calling pContext->pBassBoost->free()");
+        LVM_DelInstanceHandle(&pContext->pBundledContext->hInstance);
 
-    LvmEffect_free(pContext);
-
-    ALOGV(
-        "\tLvmBundle_init pContext->pBassBoost != NULL "
-        "-> Called pContext->pBassBoost->free()");
-  }
-
-  LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
-  LVM_InstParams_t InstParams;                 /* Instance parameters */
-  LVM_EQNB_BandDef_t BandDefs[MAX_NUM_BANDS];  /* Equaliser band definitions */
-  LVM_HeadroomParams_t HeadroomParams;         /* Headroom parameters */
-  LVM_HeadroomBandDef_t HeadroomBandDef[LVM_HEADROOM_MAX_NBANDS];
-  LVM_MemTab_t MemTab; /* Memory allocation table */
-  bool bMallocFailure = LVM_FALSE;
-
-  /* Set the capabilities */
-  InstParams.BufferMode = LVM_UNMANAGED_BUFFERS;
-  InstParams.MaxBlockSize = MAX_CALL_SIZE;
-  InstParams.EQNB_NumBands = MAX_NUM_BANDS;
-  InstParams.PSA_Included = LVM_PSA_ON;
-
-  /* Allocate memory, forcing alignment */
-  LvmStatus = LVM_GetMemoryTable(LVM_NULL, &MemTab, &InstParams);
-
-  LVM_ERROR_CHECK(LvmStatus, "LVM_GetMemoryTable", "LvmBundle_init");
-  if (LvmStatus != LVM_SUCCESS) return -EINVAL;
-
-  ALOGV("\tCreateInstance Succesfully called LVM_GetMemoryTable\n");
-
-  /* Allocate memory */
-  for (int i = 0; i < LVM_NR_MEMORY_REGIONS; i++) {
-    if (MemTab.Region[i].Size != 0) {
-      MemTab.Region[i].pBaseAddress = malloc(MemTab.Region[i].Size);
-
-      if (MemTab.Region[i].pBaseAddress == LVM_NULL) {
-        ALOGE(
-            "\tLVM_ERROR :LvmBundle_init CreateInstance Failed to allocate "
-            "%" PRIu32 " bytes for region %u\n",
-            MemTab.Region[i].Size, i);
-        bMallocFailure = LVM_TRUE;
-        break;
-      } else {
-        ALOGV("\tLvmBundle_init CreateInstance allocated %" PRIu32
-              " bytes for region %u at %p\n",
-              MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
-      }
+        ALOGV("\tLvmBundle_init pContext->pBassBoost != NULL "
+              "-> Called pContext->pBassBoost->free()");
     }
-  }
 
-  /* If one or more of the memory regions failed to allocate, free the regions
-   * that were
-   * succesfully allocated and return with an error
-   */
-  if (bMallocFailure == LVM_TRUE) {
-    for (int i = 0; i < LVM_NR_MEMORY_REGIONS; i++) {
-      if (MemTab.Region[i].pBaseAddress == LVM_NULL) {
-        ALOGE(
-            "\tLVM_ERROR :LvmBundle_init CreateInstance Failed to allocate "
-            "%" PRIu32 " bytes for region %u Not freeing\n",
-            MemTab.Region[i].Size, i);
-      } else {
-        ALOGE(
-            "\tLVM_ERROR :LvmBundle_init CreateInstance Failed: but allocated "
-            "%" PRIu32 " bytes for region %u at %p- free\n",
-            MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
-        free(MemTab.Region[i].pBaseAddress);
-      }
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
+    LVM_InstParams_t InstParams;                 /* Instance parameters */
+    LVM_EQNB_BandDef_t BandDefs[MAX_NUM_BANDS];  /* Equaliser band definitions */
+    LVM_HeadroomParams_t HeadroomParams;         /* Headroom parameters */
+    LVM_HeadroomBandDef_t HeadroomBandDef[LVM_HEADROOM_MAX_NBANDS];
+
+    /* Set the capabilities */
+    InstParams.BufferMode = LVM_UNMANAGED_BUFFERS;
+    InstParams.MaxBlockSize = MAX_CALL_SIZE;
+    InstParams.EQNB_NumBands = MAX_NUM_BANDS;
+    InstParams.PSA_Included = LVM_PSA_ON;
+
+    LvmStatus = LVM_GetInstanceHandle(&pContext->pBundledContext->hInstance, &InstParams);
+
+    LVM_ERROR_CHECK(LvmStatus, "LVM_GetInstanceHandle", "LvmBundle_init");
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
+
+    ALOGV("\tLvmBundle_init CreateInstance Successfully called "
+          "LVM_GetInstanceHandle\n");
+
+    /* Set the initial process parameters */
+    /* General parameters */
+    params->OperatingMode = LVM_MODE_ON;
+    params->SampleRate = LVM_FS_44100;
+    params->SourceFormat = LVM_STEREO;
+    params->ChMask = AUDIO_CHANNEL_OUT_STEREO;
+    params->SpeakerType = LVM_HEADPHONES;
+
+    pContext->pBundledContext->SampleRate = LVM_FS_44100;
+
+    /* Concert Sound parameters */
+    params->VirtualizerOperatingMode = LVM_MODE_OFF;
+    params->VirtualizerType = LVM_CONCERTSOUND;
+    params->VirtualizerReverbLevel = 100;
+    params->CS_EffectLevel = LVM_CS_EFFECT_NONE;
+
+    /* N-Band Equaliser parameters */
+    params->EQNB_OperatingMode = LVM_EQNB_ON;
+    params->EQNB_NBands = FIVEBAND_NUMBANDS;
+    params->pEQNB_BandDefinition = &BandDefs[0];
+
+    for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
+        BandDefs[i].Frequency = EQNB_5BandPresetsFrequencies[i];
+        BandDefs[i].QFactor = EQNB_5BandPresetsQFactors[i];
+        BandDefs[i].Gain = EQNB_5BandSoftPresets[i];
     }
-    return -EINVAL;
-  }
-  ALOGV("\tLvmBundle_init CreateInstance Succesfully malloc'd memory\n");
 
-  /* Initialise */
-  pContext->pBundledContext->hInstance = LVM_NULL;
+    /* Volume Control parameters */
+    params->VC_EffectLevel = 0;
+    params->VC_Balance = 0;
 
-  /* Init sets the instance handle */
-  LvmStatus = LVM_GetInstanceHandle(&pContext->pBundledContext->hInstance,
-                                    &MemTab, &InstParams);
+    /* Treble Enhancement parameters */
+    params->TE_OperatingMode = LVM_TE_OFF;
+    params->TE_EffectLevel = 0;
 
-  LVM_ERROR_CHECK(LvmStatus, "LVM_GetInstanceHandle", "LvmBundle_init");
-  if (LvmStatus != LVM_SUCCESS) return -EINVAL;
+    /* PSA Control parameters */
+    params->PSA_Enable = LVM_PSA_OFF;
+    params->PSA_PeakDecayRate = (LVM_PSA_DecaySpeed_en)0;
 
-  ALOGV(
-      "\tLvmBundle_init CreateInstance Succesfully called "
-      "LVM_GetInstanceHandle\n");
+    /* Bass Enhancement parameters */
+    params->BE_OperatingMode = LVM_BE_ON;
+    params->BE_EffectLevel = 0;
+    params->BE_CentreFreq = LVM_BE_CENTRE_90Hz;
+    params->BE_HPF = LVM_BE_HPF_ON;
 
-  /* Set the initial process parameters */
-  /* General parameters */
-  params->OperatingMode = LVM_MODE_ON;
-  params->SampleRate = LVM_FS_44100;
-  params->SourceFormat = LVM_STEREO;
-  params->ChMask       = AUDIO_CHANNEL_OUT_STEREO;
-  params->SpeakerType = LVM_HEADPHONES;
+    /* PSA Control parameters */
+    params->PSA_Enable = LVM_PSA_OFF;
+    params->PSA_PeakDecayRate = LVM_PSA_SPEED_MEDIUM;
 
-  pContext->pBundledContext->SampleRate = LVM_FS_44100;
+    /* TE Control parameters */
+    params->TE_OperatingMode = LVM_TE_OFF;
+    params->TE_EffectLevel = 0;
 
-  /* Concert Sound parameters */
-  params->VirtualizerOperatingMode = LVM_MODE_OFF;
-  params->VirtualizerType = LVM_CONCERTSOUND;
-  params->VirtualizerReverbLevel = 100;
-  params->CS_EffectLevel = LVM_CS_EFFECT_NONE;
+    /* Activate the initial settings */
+    LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, params);
 
-  /* N-Band Equaliser parameters */
-  params->EQNB_OperatingMode = LVM_EQNB_ON;
-  params->EQNB_NBands = FIVEBAND_NUMBANDS;
-  params->pEQNB_BandDefinition = &BandDefs[0];
+    LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmBundle_init");
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-  for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
-    BandDefs[i].Frequency = EQNB_5BandPresetsFrequencies[i];
-    BandDefs[i].QFactor = EQNB_5BandPresetsQFactors[i];
-    BandDefs[i].Gain = EQNB_5BandSoftPresets[i];
-  }
+    ALOGV("\tLvmBundle_init CreateInstance Successfully called "
+          "LVM_SetControlParameters\n");
 
-  /* Volume Control parameters */
-  params->VC_EffectLevel = 0;
-  params->VC_Balance = 0;
+    /* Set the headroom parameters */
+    HeadroomBandDef[0].Limit_Low = 20;
+    HeadroomBandDef[0].Limit_High = 4999;
+    HeadroomBandDef[0].Headroom_Offset = 0;
+    HeadroomBandDef[1].Limit_Low = 5000;
+    HeadroomBandDef[1].Limit_High = 24000;
+    HeadroomBandDef[1].Headroom_Offset = 0;
+    HeadroomParams.pHeadroomDefinition = &HeadroomBandDef[0];
+    HeadroomParams.Headroom_OperatingMode = LVM_HEADROOM_ON;
+    HeadroomParams.NHeadroomBands = 2;
 
-  /* Treble Enhancement parameters */
-  params->TE_OperatingMode = LVM_TE_OFF;
-  params->TE_EffectLevel = 0;
+    LvmStatus = LVM_SetHeadroomParams(pContext->pBundledContext->hInstance, &HeadroomParams);
 
-  /* PSA Control parameters */
-  params->PSA_Enable = LVM_PSA_OFF;
-  params->PSA_PeakDecayRate = (LVM_PSA_DecaySpeed_en)0;
+    LVM_ERROR_CHECK(LvmStatus, "LVM_SetHeadroomParams", "LvmBundle_init");
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-  /* Bass Enhancement parameters */
-  params->BE_OperatingMode = LVM_BE_ON;
-  params->BE_EffectLevel = 0;
-  params->BE_CentreFreq = LVM_BE_CENTRE_90Hz;
-  params->BE_HPF = LVM_BE_HPF_ON;
-
-  /* PSA Control parameters */
-  params->PSA_Enable = LVM_PSA_OFF;
-  params->PSA_PeakDecayRate = LVM_PSA_SPEED_MEDIUM;
-
-  /* TE Control parameters */
-  params->TE_OperatingMode = LVM_TE_OFF;
-  params->TE_EffectLevel = 0;
-
-  /* Activate the initial settings */
-  LvmStatus =
-      LVM_SetControlParameters(pContext->pBundledContext->hInstance, params);
-
-  LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmBundle_init");
-  if (LvmStatus != LVM_SUCCESS) return -EINVAL;
-
-  ALOGV(
-      "\tLvmBundle_init CreateInstance Succesfully called "
-      "LVM_SetControlParameters\n");
-
-  /* Set the headroom parameters */
-  HeadroomBandDef[0].Limit_Low = 20;
-  HeadroomBandDef[0].Limit_High = 4999;
-  HeadroomBandDef[0].Headroom_Offset = 0;
-  HeadroomBandDef[1].Limit_Low = 5000;
-  HeadroomBandDef[1].Limit_High = 24000;
-  HeadroomBandDef[1].Headroom_Offset = 0;
-  HeadroomParams.pHeadroomDefinition = &HeadroomBandDef[0];
-  HeadroomParams.Headroom_OperatingMode = LVM_HEADROOM_ON;
-  HeadroomParams.NHeadroomBands = 2;
-
-  LvmStatus = LVM_SetHeadroomParams(pContext->pBundledContext->hInstance,
-                                    &HeadroomParams);
-
-  LVM_ERROR_CHECK(LvmStatus, "LVM_SetHeadroomParams", "LvmBundle_init");
-  if (LvmStatus != LVM_SUCCESS) return -EINVAL;
-
-  ALOGV(
-      "\tLvmBundle_init CreateInstance Succesfully called "
-      "LVM_SetHeadroomParams\n");
-  ALOGV("\tLvmBundle_init End");
-  return 0;
+    ALOGV("\tLvmBundle_init CreateInstance Successfully called "
+          "LVM_SetHeadroomParams\n");
+    ALOGV("\tLvmBundle_init End");
+    return 0;
 } /* end LvmBundle_init */
 
-int lvmCreate(struct EffectContext *pContext,
-              lvmConfigParams_t    *plvmConfigParams,
-              LVM_ControlParams_t  *params) {
-  int ret = 0;
-  pContext->pBundledContext = NULL;
-  pContext->pBundledContext = (BundledEffectContext *)malloc(sizeof(struct BundledEffectContext));
-  if (NULL == pContext->pBundledContext) {
-    return -EINVAL;
-  }
-
-  pContext->pBundledContext->SessionNo = 0;
-  pContext->pBundledContext->SessionId = 0;
-  pContext->pBundledContext->hInstance = NULL;
-  pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
-  pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
-  pContext->pBundledContext->bBassEnabled = LVM_FALSE;
-  pContext->pBundledContext->bBassTempDisabled = LVM_FALSE;
-  pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE;
-  pContext->pBundledContext->bVirtualizerTempDisabled = LVM_FALSE;
-  pContext->pBundledContext->nOutputDevice = AUDIO_DEVICE_NONE;
-  pContext->pBundledContext->nVirtualizerForcedDevice = AUDIO_DEVICE_NONE;
-  pContext->pBundledContext->NumberEffectsEnabled = 0;
-  pContext->pBundledContext->NumberEffectsCalled = 0;
-  pContext->pBundledContext->firstVolume = LVM_TRUE;
-  pContext->pBundledContext->volume = 0;
-
-  /* Saved strength is used to return the exact strength that was used in the
-   * set to the get
-   * because we map the original strength range of 0:1000 to 1:15, and this will
-   * avoid
-   * quantisation like effect when returning
-   */
-  pContext->pBundledContext->BassStrengthSaved = 0;
-  pContext->pBundledContext->VirtStrengthSaved = 0;
-  pContext->pBundledContext->CurPreset = PRESET_CUSTOM;
-  pContext->pBundledContext->levelSaved = 0;
-  pContext->pBundledContext->bMuteEnabled = LVM_FALSE;
-  pContext->pBundledContext->bStereoPositionEnabled = LVM_FALSE;
-  pContext->pBundledContext->positionSaved = 0;
-  pContext->pBundledContext->workBuffer = NULL;
-  pContext->pBundledContext->frameCount = -1;
-  pContext->pBundledContext->SamplesToExitCountVirt = 0;
-  pContext->pBundledContext->SamplesToExitCountBb = 0;
-  pContext->pBundledContext->SamplesToExitCountEq = 0;
-  for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
-    pContext->pBundledContext->bandGaindB[i] = EQNB_5BandSoftPresets[i];
-  }
-  pContext->config.inputCfg.channels = plvmConfigParams->nrChannels;
-  ALOGV("\tEffectCreate - Calling LvmBundle_init");
-  ret = LvmBundle_init(pContext, params);
-
-  if (ret < 0) {
-    ALOGE("\tLVM_ERROR : lvmCreate() Bundle init failed");
-    return ret;
-  }
-  return 0;
-}
-
-int lvmControl(struct EffectContext *pContext,
-               lvmConfigParams_t    *plvmConfigParams,
-               LVM_ControlParams_t  *params) {
-  LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
-
-  /* Set the initial process parameters */
-  /* General parameters */
-  params->OperatingMode = LVM_MODE_ON;
-  params->SpeakerType = LVM_HEADPHONES;
-
-  params->ChMask     = plvmConfigParams->chMask;
-  params->NrChannels = plvmConfigParams->nrChannels;
-  if (params->NrChannels == 1) {
-    params->SourceFormat = LVM_MONO;
-  } else if (params->NrChannels == 2) {
-    params->SourceFormat = LVM_STEREO;
-  } else if (params->NrChannels > 2 && params->NrChannels <= 8) { // FCC_2 FCC_8
-    params->SourceFormat = LVM_MULTICHANNEL;
-  } else {
-      return -EINVAL;
-  }
-
-  LVM_Fs_en sampleRate;
-  switch (plvmConfigParams->samplingFreq) {
-    case 8000:
-      sampleRate = LVM_FS_8000;
-      break;
-    case 11025:
-      sampleRate = LVM_FS_11025;
-      break;
-    case 12000:
-      sampleRate = LVM_FS_12000;
-      break;
-    case 16000:
-      sampleRate = LVM_FS_16000;
-      break;
-    case 22050:
-      sampleRate = LVM_FS_22050;
-      break;
-    case 24000:
-      sampleRate = LVM_FS_24000;
-      break;
-    case 32000:
-      sampleRate = LVM_FS_32000;
-      break;
-    case 44100:
-      sampleRate = LVM_FS_44100;
-      break;
-    case 48000:
-      sampleRate = LVM_FS_48000;
-      break;
-    case 88200:
-      sampleRate = LVM_FS_88200;
-      break;
-    case 96000:
-      sampleRate = LVM_FS_96000;
-      break;
-    case 176400:
-      sampleRate = LVM_FS_176400;
-      break;
-    case 192000:
-      sampleRate = LVM_FS_192000;
-      break;
-    default:
-      return -EINVAL;
-  }
-  params->SampleRate = sampleRate;
-
-  /* Concert Sound parameters */
-  params->VirtualizerOperatingMode = plvmConfigParams->csEnable;
-  params->VirtualizerType = LVM_CONCERTSOUND;
-  params->VirtualizerReverbLevel = 100;
-  params->CS_EffectLevel = LVM_CS_EFFECT_NONE;
-
-  /* N-Band Equaliser parameters */
-  const int eqPresetLevel = plvmConfigParams->eqPresetLevel;
-  LVM_EQNB_BandDef_t BandDefs[MAX_NUM_BANDS];  /* Equaliser band definitions */
-  for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
-    BandDefs[i].Frequency = EQNB_5BandPresetsFrequencies[i];
-    BandDefs[i].QFactor = EQNB_5BandPresetsQFactors[i];
-    BandDefs[i].Gain =
-        EQNB_5BandSoftPresets[(FIVEBAND_NUMBANDS * eqPresetLevel) + i];
-  }
-  params->EQNB_OperatingMode = plvmConfigParams->eqEnable;
- // Caution: raw pointer to stack data, stored in instance by LVM_SetControlParameters.
-  params->pEQNB_BandDefinition = &BandDefs[0];
-
-  /* Volume Control parameters */
-  params->VC_EffectLevel = 0;
-  params->VC_Balance = plvmConfigParams->vcBal;
-
-  /* Treble Enhancement parameters */
-  params->TE_OperatingMode = plvmConfigParams->trebleEnable;
-
-  /* PSA Control parameters */
-  params->PSA_Enable = LVM_PSA_ON;
-
-  /* Bass Enhancement parameters */
-  params->BE_OperatingMode = plvmConfigParams->bassEnable;
-
-  /* Activate the initial settings */
-  LvmStatus =
-      LVM_SetControlParameters(pContext->pBundledContext->hInstance, params);
-
-  LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmBundle_init");
-  if (LvmStatus != LVM_SUCCESS) return -EINVAL;
-
-  LvmStatus = LVM_ApplyNewSettings(pContext->pBundledContext->hInstance);
-
-  if (LvmStatus != LVM_SUCCESS) return -EINVAL;
-
-  return 0;
-}
-
-int lvmExecute(float *floatIn, float *floatOut, struct EffectContext *pContext,
-               lvmConfigParams_t *plvmConfigParams) {
-  const int frameLength = plvmConfigParams->frameLength;
-  return
-      LVM_Process(pContext->pBundledContext->hInstance, /* Instance handle */
-                  floatIn,                              /* Input buffer */
-                  floatOut,                             /* Output buffer */
-                  (LVM_UINT16)frameLength, /* Number of samples to read */
-                  0);                      /* Audio Time */
-}
-
-int lvmMainProcess(EffectContext *pContext,
-                   LVM_ControlParams_t *pParams,
-                   lvmConfigParams_t *plvmConfigParams,
-                   FILE *finp,
-                   FILE *fout) {
-  int errCode = lvmControl(pContext, plvmConfigParams, pParams);
-  if (errCode) {
-    ALOGE("Error: lvmControl returned with %d\n", errCode);
-    return errCode;
-  }
-
-  const int channelCount = plvmConfigParams->nrChannels;
-  const int frameLength = plvmConfigParams->frameLength;
-  const int frameSize = channelCount * sizeof(float);  // processing size
-  const int ioChannelCount = plvmConfigParams->fChannels;
-  const int ioFrameSize = ioChannelCount * sizeof(short); // file load size
-  const int maxChannelCount = std::max(channelCount, ioChannelCount);
-  /*
-   * Mono input will be converted to 2 channels internally in the process call
-   * by copying the same data into the second channel.
-   * Hence when channelCount is 1, output buffer should be allocated for
-   * 2 channels. The memAllocChCount takes care of allocation of sufficient
-   * memory for the output buffer.
-   */
-  const int memAllocChCount = (channelCount == 1 ? 2 : channelCount);
-
-  std::vector<short> in(frameLength * maxChannelCount);
-  std::vector<short> out(frameLength * maxChannelCount);
-  std::vector<float> floatIn(frameLength * channelCount);
-  std::vector<float> floatOut(frameLength * memAllocChCount);
-
-  int frameCounter = 0;
-  while (fread(in.data(), ioFrameSize, frameLength, finp) == (size_t)frameLength) {
-    if (ioChannelCount != channelCount) {
-        adjust_channels(in.data(), ioChannelCount, in.data(), channelCount,
-               sizeof(short), frameLength * ioFrameSize);
+int lvmCreate(struct EffectContext* pContext, lvmConfigParams_t* plvmConfigParams,
+              LVM_ControlParams_t* params) {
+    int ret = 0;
+    pContext->pBundledContext = NULL;
+    pContext->pBundledContext = (BundledEffectContext*)malloc(sizeof(struct BundledEffectContext));
+    if (NULL == pContext->pBundledContext) {
+        return -EINVAL;
     }
-    memcpy_to_float_from_i16(floatIn.data(), in.data(), frameLength * channelCount);
 
-    // Mono mode will replicate the first channel to all other channels.
-    // This ensures all audio channels are identical. This is useful for testing
-    // Bass Boost, which extracts a mono signal for processing.
-    if (plvmConfigParams->monoMode && channelCount > 1) {
-        for (int i = 0; i < frameLength; ++i) {
-            auto *fp = &floatIn[i * channelCount];
-            std::fill(fp + 1, fp + channelCount, *fp); // replicate ch 0
+    pContext->pBundledContext->SessionNo = 0;
+    pContext->pBundledContext->SessionId = 0;
+    pContext->pBundledContext->hInstance = NULL;
+    pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
+    pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
+    pContext->pBundledContext->bBassEnabled = LVM_FALSE;
+    pContext->pBundledContext->bBassTempDisabled = LVM_FALSE;
+    pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE;
+    pContext->pBundledContext->bVirtualizerTempDisabled = LVM_FALSE;
+    pContext->pBundledContext->nOutputDevice = AUDIO_DEVICE_NONE;
+    pContext->pBundledContext->nVirtualizerForcedDevice = AUDIO_DEVICE_NONE;
+    pContext->pBundledContext->NumberEffectsEnabled = 0;
+    pContext->pBundledContext->NumberEffectsCalled = 0;
+    pContext->pBundledContext->firstVolume = LVM_TRUE;
+    pContext->pBundledContext->volume = 0;
+
+    /* Saved strength is used to return the exact strength that was used in the
+     * set to the get
+     * because we map the original strength range of 0:1000 to 1:15, and this will
+     * avoid
+     * quantisation like effect when returning
+     */
+    pContext->pBundledContext->BassStrengthSaved = 0;
+    pContext->pBundledContext->VirtStrengthSaved = 0;
+    pContext->pBundledContext->CurPreset = PRESET_CUSTOM;
+    pContext->pBundledContext->levelSaved = 0;
+    pContext->pBundledContext->bMuteEnabled = LVM_FALSE;
+    pContext->pBundledContext->bStereoPositionEnabled = LVM_FALSE;
+    pContext->pBundledContext->positionSaved = 0;
+    pContext->pBundledContext->workBuffer = NULL;
+    pContext->pBundledContext->frameCount = -1;
+    pContext->pBundledContext->SamplesToExitCountVirt = 0;
+    pContext->pBundledContext->SamplesToExitCountBb = 0;
+    pContext->pBundledContext->SamplesToExitCountEq = 0;
+    for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
+        pContext->pBundledContext->bandGaindB[i] = EQNB_5BandSoftPresets[i];
+    }
+    pContext->config.inputCfg.channels = plvmConfigParams->nrChannels;
+    ALOGV("\tEffectCreate - Calling LvmBundle_init");
+    ret = LvmBundle_init(pContext, params);
+
+    if (ret < 0) {
+        ALOGE("\tLVM_ERROR : lvmCreate() Bundle init failed");
+        return ret;
+    }
+    return 0;
+}
+
+int lvmControl(struct EffectContext* pContext, lvmConfigParams_t* plvmConfigParams,
+               LVM_ControlParams_t* params) {
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
+
+    /* Set the initial process parameters */
+    /* General parameters */
+    params->OperatingMode = LVM_MODE_ON;
+    params->SpeakerType = LVM_HEADPHONES;
+
+    params->ChMask = plvmConfigParams->chMask;
+    params->NrChannels = plvmConfigParams->nrChannels;
+    if (params->NrChannels == 1) {
+        params->SourceFormat = LVM_MONO;
+    } else if (params->NrChannels == 2) {
+        params->SourceFormat = LVM_STEREO;
+    } else if (params->NrChannels > FCC_2 && params->NrChannels <= FCC_24) {
+        params->SourceFormat = LVM_MULTICHANNEL;
+    } else {
+        return -EINVAL;
+    }
+    params->SampleRate = lvmFsForSampleRate(plvmConfigParams->samplingFreq);
+    if (params->SampleRate == LVM_FS_INVALID) {
+        ALOGE("lvmControl invalid sampling rate %d", plvmConfigParams->samplingFreq);
+        return -EINVAL;
+    }
+
+    /* Concert Sound parameters */
+    params->VirtualizerOperatingMode = plvmConfigParams->csEnable;
+    params->VirtualizerType = LVM_CONCERTSOUND;
+    params->VirtualizerReverbLevel = 100;
+    params->CS_EffectLevel = LVM_CS_EFFECT_NONE;
+
+    /* N-Band Equaliser parameters */
+    const int eqPresetLevel = plvmConfigParams->eqPresetLevel;
+    LVM_EQNB_BandDef_t BandDefs[MAX_NUM_BANDS]; /* Equaliser band definitions */
+    for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
+        BandDefs[i].Frequency = EQNB_5BandPresetsFrequencies[i];
+        BandDefs[i].QFactor = EQNB_5BandPresetsQFactors[i];
+        BandDefs[i].Gain = EQNB_5BandSoftPresets[(FIVEBAND_NUMBANDS * eqPresetLevel) + i];
+    }
+    params->EQNB_OperatingMode = plvmConfigParams->eqEnable;
+    // Caution: raw pointer to stack data, stored in instance by LVM_SetControlParameters.
+    params->pEQNB_BandDefinition = &BandDefs[0];
+
+    /* Volume Control parameters */
+    params->VC_EffectLevel = 0;
+    params->VC_Balance = plvmConfigParams->vcBal;
+
+    /* Treble Enhancement parameters */
+    params->TE_OperatingMode = plvmConfigParams->trebleEnable;
+
+    /* PSA Control parameters */
+    params->PSA_Enable = LVM_PSA_ON;
+
+    /* Bass Enhancement parameters */
+    params->BE_OperatingMode = plvmConfigParams->bassEnable;
+
+    /* Activate the initial settings */
+    LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, params);
+
+    LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmBundle_init");
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
+
+    LvmStatus = LVM_ApplyNewSettings(pContext->pBundledContext->hInstance);
+
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
+
+    return 0;
+}
+
+int lvmExecute(float* floatIn, float* floatOut, struct EffectContext* pContext,
+               lvmConfigParams_t* plvmConfigParams) {
+    const int frameLength = plvmConfigParams->frameLength;
+    return LVM_Process(pContext->pBundledContext->hInstance, /* Instance handle */
+                       floatIn,                              /* Input buffer */
+                       floatOut,                             /* Output buffer */
+                       (LVM_UINT16)frameLength,              /* Number of samples to read */
+                       0);                                   /* Audio Time */
+}
+
+int lvmMainProcess(EffectContext* pContext, LVM_ControlParams_t* pParams,
+                   lvmConfigParams_t* plvmConfigParams, FILE* finp, FILE* fout) {
+    int errCode = lvmControl(pContext, plvmConfigParams, pParams);
+    if (errCode) {
+        ALOGE("Error: lvmControl returned with %d\n", errCode);
+        return errCode;
+    }
+
+    const int channelCount = plvmConfigParams->nrChannels;
+    const int frameLength = plvmConfigParams->frameLength;
+    const int frameSize = channelCount * sizeof(float);  // processing size
+    const int ioChannelCount = plvmConfigParams->fChannels;
+    const int ioFrameSize = ioChannelCount * sizeof(short);  // file load size
+    const int maxChannelCount = std::max(channelCount, ioChannelCount);
+
+    std::vector<short> in(frameLength * maxChannelCount);
+    std::vector<short> out(frameLength * maxChannelCount);
+    std::vector<float> floatIn(frameLength * channelCount);
+    std::vector<float> floatOut(frameLength * channelCount);
+
+    int frameCounter = 0;
+    while (fread(in.data(), ioFrameSize, frameLength, finp) == (size_t)frameLength) {
+        if (ioChannelCount != channelCount) {
+            adjust_channels(in.data(), ioChannelCount, in.data(), channelCount, sizeof(short),
+                            frameLength * ioFrameSize);
+        }
+        memcpy_to_float_from_i16(floatIn.data(), in.data(), frameLength * channelCount);
+
+        // Mono mode will replicate the first channel to all other channels.
+        // This ensures all audio channels are identical. This is useful for testing
+        // Bass Boost, which extracts a mono signal for processing.
+        if (plvmConfigParams->monoMode && channelCount > 1) {
+            for (int i = 0; i < frameLength; ++i) {
+                auto* fp = &floatIn[i * channelCount];
+                std::fill(fp + 1, fp + channelCount, *fp);  // replicate ch 0
+            }
+        }
+#ifndef BYPASS_EXEC
+        errCode = lvmExecute(floatIn.data(), floatOut.data(), pContext, plvmConfigParams);
+        if (errCode) {
+            printf("\nError: lvmExecute returned with %d\n", errCode);
+            return errCode;
+        }
+
+        (void)frameSize;  // eliminate warning
+#else
+        memcpy(floatOut.data(), floatIn.data(), frameLength * frameSize);
+#endif
+        memcpy_to_i16_from_float(out.data(), floatOut.data(), frameLength * channelCount);
+        if (ioChannelCount != channelCount) {
+            adjust_channels(out.data(), channelCount, out.data(), ioChannelCount, sizeof(short),
+                            frameLength * channelCount * sizeof(short));
+        }
+        (void)fwrite(out.data(), ioFrameSize, frameLength, fout);
+        frameCounter += frameLength;
+    }
+    printf("frameCounter: [%d]\n", frameCounter);
+    return 0;
+}
+
+int main(int argc, const char* argv[]) {
+    if (argc == 1) {
+        printUsage();
+        return -1;
+    }
+
+    lvmConfigParams_t lvmConfigParams{};  // default initialize
+    const char* infile = nullptr;
+    const char* outfile = nullptr;
+
+    for (int i = 1; i < argc; i++) {
+        printf("%s ", argv[i]);
+        if (!strncmp(argv[i], "-i:", 3)) {
+            infile = argv[i] + 3;
+        } else if (!strncmp(argv[i], "-o:", 3)) {
+            outfile = argv[i] + 3;
+        } else if (!strncmp(argv[i], "-fs:", 4)) {
+            const int samplingFreq = atoi(argv[i] + 4);
+            if (samplingFreq != 8000 && samplingFreq != 11025 && samplingFreq != 12000 &&
+                samplingFreq != 16000 && samplingFreq != 22050 && samplingFreq != 24000 &&
+                samplingFreq != 32000 && samplingFreq != 44100 && samplingFreq != 48000 &&
+                samplingFreq != 88200 && samplingFreq != 96000 && samplingFreq != 176400 &&
+                samplingFreq != 192000) {
+                printf("Error: Unsupported Sampling Frequency : %d\n", samplingFreq);
+                return -1;
+            }
+            lvmConfigParams.samplingFreq = samplingFreq;
+        } else if (!strncmp(argv[i], "-chMask:", 8)) {
+            const int chMaskConfigIdx = atoi(argv[i] + 8);
+            if (chMaskConfigIdx < 0 || (size_t)chMaskConfigIdx >= std::size(lvmConfigChMask)) {
+                ALOGE("\nError: Unsupported Channel Mask : %d\n", chMaskConfigIdx);
+                return -1;
+            }
+            const audio_channel_mask_t chMask = lvmConfigChMask[chMaskConfigIdx];
+            lvmConfigParams.chMask = chMask;
+            lvmConfigParams.nrChannels = audio_channel_count_from_out_mask(chMask);
+        } else if (!strncmp(argv[i], "-vcBal:", 7)) {
+            const int vcBalance = atoi(argv[i] + 7);
+            if (vcBalance > 96 || vcBalance < -96) {
+                ALOGE("\nError: Unsupported volume balance value: %d\n", vcBalance);
+            }
+            lvmConfigParams.vcBal = vcBalance;
+        } else if (!strncmp(argv[i], "-fch:", 5)) {
+            const int fChannels = atoi(argv[i] + 5);
+            if (fChannels > 8 || fChannels < 1) {
+                printf("Error: Unsupported number of file channels : %d\n", fChannels);
+                return -1;
+            }
+            lvmConfigParams.fChannels = fChannels;
+        } else if (!strcmp(argv[i], "-M")) {
+            lvmConfigParams.monoMode = true;
+        } else if (!strncmp(argv[i], "-basslvl:", 9)) {
+            const int bassEffectLevel = atoi(argv[i] + 9);
+            if (bassEffectLevel > LVM_BE_MAX_EFFECTLEVEL ||
+                bassEffectLevel < LVM_BE_MIN_EFFECTLEVEL) {
+                printf("Error: Unsupported Bass Effect Level : %d\n", bassEffectLevel);
+                printUsage();
+                return -1;
+            }
+            lvmConfigParams.bassEffectLevel = bassEffectLevel;
+        } else if (!strncmp(argv[i], "-eqPreset:", 10)) {
+            const int eqPresetLevel = atoi(argv[i] + 10);
+            const int numPresetLvls = std::size(gEqualizerPresets);
+            if (eqPresetLevel >= numPresetLvls || eqPresetLevel < 0) {
+                printf("Error: Unsupported Equalizer Preset : %d\n", eqPresetLevel);
+                printUsage();
+                return -1;
+            }
+            lvmConfigParams.eqPresetLevel = eqPresetLevel;
+        } else if (!strcmp(argv[i], "-bE")) {
+            lvmConfigParams.bassEnable = LVM_BE_ON;
+        } else if (!strcmp(argv[i], "-eqE")) {
+            lvmConfigParams.eqEnable = LVM_EQNB_ON;
+        } else if (!strcmp(argv[i], "-tE")) {
+            lvmConfigParams.trebleEnable = LVM_TE_ON;
+        } else if (!strcmp(argv[i], "-csE")) {
+            lvmConfigParams.csEnable = LVM_MODE_ON;
+        } else if (!strcmp(argv[i], "-h")) {
+            printUsage();
+            return 0;
         }
     }
-#ifndef BYPASS_EXEC
-    errCode = lvmExecute(floatIn.data(), floatOut.data(), pContext, plvmConfigParams);
-    if (errCode) {
-      printf("\nError: lvmExecute returned with %d\n", errCode);
-      return errCode;
-    }
 
-    (void)frameSize; // eliminate warning
-#else
-    memcpy(floatOut.data(), floatIn.data(), frameLength * frameSize);
-#endif
-    memcpy_to_i16_from_float(out.data(), floatOut.data(), frameLength * channelCount);
-    if (ioChannelCount != channelCount) {
-        adjust_channels(out.data(), channelCount, out.data(), ioChannelCount,
-               sizeof(short), frameLength * channelCount * sizeof(short));
-    }
-    (void) fwrite(out.data(), ioFrameSize, frameLength, fout);
-    frameCounter += frameLength;
-  }
-  printf("frameCounter: [%d]\n", frameCounter);
-  return 0;
-}
-
-int main(int argc, const char *argv[]) {
-  if (argc == 1) {
-    printUsage();
-    return -1;
-  }
-
-  lvmConfigParams_t lvmConfigParams{}; // default initialize
-  const char *infile = nullptr;
-  const char *outfile = nullptr;
-
-  for (int i = 1; i < argc; i++) {
-    printf("%s ", argv[i]);
-    if (!strncmp(argv[i], "-i:", 3)) {
-      infile = argv[i] + 3;
-    } else if (!strncmp(argv[i], "-o:", 3)) {
-      outfile = argv[i] + 3;
-    } else if (!strncmp(argv[i], "-fs:", 4)) {
-      const int samplingFreq = atoi(argv[i] + 4);
-      if (samplingFreq != 8000 && samplingFreq != 11025 &&
-          samplingFreq != 12000 && samplingFreq != 16000 &&
-          samplingFreq != 22050 && samplingFreq != 24000 &&
-          samplingFreq != 32000 && samplingFreq != 44100 &&
-          samplingFreq != 48000 && samplingFreq != 88200 &&
-          samplingFreq != 96000 && samplingFreq != 176400 &&
-          samplingFreq != 192000) {
-        printf("Error: Unsupported Sampling Frequency : %d\n", samplingFreq);
-        return -1;
-      }
-      lvmConfigParams.samplingFreq = samplingFreq;
-    } else if (!strncmp(argv[i], "-chMask:", 8)) {
-      const int chMaskConfigIdx = atoi(argv[i] + 8);
-      if (chMaskConfigIdx < 0 || (size_t)chMaskConfigIdx >= std::size(lvmConfigChMask)) {
-        ALOGE("\nError: Unsupported Channel Mask : %d\n", chMaskConfigIdx);
-        return -1;
-      }
-      const audio_channel_mask_t chMask = lvmConfigChMask[chMaskConfigIdx];
-      lvmConfigParams.chMask = chMask;
-      lvmConfigParams.nrChannels = audio_channel_count_from_out_mask(chMask);
-    } else if (!strncmp(argv[i], "-vcBal:", 7)) {
-      const int vcBalance = atoi(argv[i] + 7);
-      if (vcBalance > 96 || vcBalance < -96) {
-        ALOGE("\nError: Unsupported volume balance value: %d\n", vcBalance);
-      }
-      lvmConfigParams.vcBal = vcBalance;
-    } else if (!strncmp(argv[i], "-fch:", 5)) {
-      const int fChannels = atoi(argv[i] + 5);
-      if (fChannels > 8 || fChannels < 1) {
-             printf("Error: Unsupported number of file channels : %d\n", fChannels);
-             return -1;
-           }
-           lvmConfigParams.fChannels = fChannels;
-    } else if (!strcmp(argv[i],"-M")) {
-          lvmConfigParams.monoMode = true;
-    } else if (!strncmp(argv[i], "-basslvl:", 9)) {
-      const int bassEffectLevel = atoi(argv[i] + 9);
-      if (bassEffectLevel > LVM_BE_MAX_EFFECTLEVEL || bassEffectLevel < LVM_BE_MIN_EFFECTLEVEL) {
-        printf("Error: Unsupported Bass Effect Level : %d\n",
-               bassEffectLevel);
+    if (infile == nullptr || outfile == nullptr) {
+        printf("Error: missing input/output files\n");
         printUsage();
         return -1;
-      }
-      lvmConfigParams.bassEffectLevel = bassEffectLevel;
-    } else if (!strncmp(argv[i], "-eqPreset:", 10)) {
-      const int eqPresetLevel = atoi(argv[i] + 10);
-      const int numPresetLvls = std::size(gEqualizerPresets);
-      if (eqPresetLevel >= numPresetLvls || eqPresetLevel < 0) {
-        printf("Error: Unsupported Equalizer Preset : %d\n", eqPresetLevel);
-        printUsage();
-        return -1;
-      }
-      lvmConfigParams.eqPresetLevel = eqPresetLevel;
-    } else if (!strcmp(argv[i], "-bE")) {
-      lvmConfigParams.bassEnable = LVM_BE_ON;
-    } else if (!strcmp(argv[i], "-eqE")) {
-      lvmConfigParams.eqEnable = LVM_EQNB_ON;
-    } else if (!strcmp(argv[i], "-tE")) {
-      lvmConfigParams.trebleEnable = LVM_TE_ON;
-    } else if (!strcmp(argv[i], "-csE")) {
-      lvmConfigParams.csEnable = LVM_MODE_ON;
-    } else if (!strcmp(argv[i], "-h")) {
-      printUsage();
-      return 0;
     }
-  }
 
-  if (infile == nullptr || outfile == nullptr) {
-    printf("Error: missing input/output files\n");
-    printUsage();
-    return -1;
-  }
+    FILE* finp = fopen(infile, "rb");
+    if (finp == nullptr) {
+        printf("Cannot open input file %s", infile);
+        return -1;
+    }
 
-  FILE *finp = fopen(infile, "rb");
-  if (finp == nullptr) {
-    printf("Cannot open input file %s", infile);
-    return -1;
-  }
+    FILE* fout = fopen(outfile, "wb");
+    if (fout == nullptr) {
+        printf("Cannot open output file %s", outfile);
+        fclose(finp);
+        return -1;
+    }
 
-  FILE *fout = fopen(outfile, "wb");
-  if (fout == nullptr) {
-    printf("Cannot open output file %s", outfile);
+    EffectContext context;
+    LVM_ControlParams_t params;
+    int errCode = lvmCreate(&context, &lvmConfigParams, &params);
+    if (errCode == 0) {
+        errCode = lvmMainProcess(&context, &params, &lvmConfigParams, finp, fout);
+        if (errCode != 0) {
+            printf("Error: lvmMainProcess returned with the error: %d", errCode);
+        }
+    } else {
+        printf("Error: lvmCreate returned with the error: %d", errCode);
+    }
     fclose(finp);
-    return -1;
-  }
-
-  EffectContext context;
-  LVM_ControlParams_t params;
-  int errCode = lvmCreate(&context, &lvmConfigParams, &params);
-  if (errCode == 0) {
-    errCode = lvmMainProcess(&context, &params, &lvmConfigParams, finp, fout);
-    if (errCode != 0) {
-      printf("Error: lvmMainProcess returned with the error: %d",errCode);
+    fclose(fout);
+    /* Free the allocated buffers */
+    if (context.pBundledContext != nullptr) {
+        if (context.pBundledContext->hInstance != nullptr) {
+            LVM_DelInstanceHandle(&context.pBundledContext->hInstance);
+        }
+        free(context.pBundledContext);
     }
-  } else {
-    printf("Error: lvmCreate returned with the error: %d", errCode);
-  }
-  fclose(finp);
-  fclose(fout);
-  /* Free the allocated buffers */
-  if (context.pBundledContext != nullptr) {
-    if (context.pBundledContext->hInstance != nullptr) {
-      LvmEffect_free(&context);
-    }
-    free(context.pBundledContext);
-  }
 
-  if (errCode) {
-    return -1;
-  }
-  return 0;
+    if (errCode) {
+        return -1;
+    }
+    return 0;
 }
diff --git a/media/libeffects/lvm/tests/reverb_test.cpp b/media/libeffects/lvm/tests/reverb_test.cpp
new file mode 100644
index 0000000..0ea401c
--- /dev/null
+++ b/media/libeffects/lvm/tests/reverb_test.cpp
@@ -0,0 +1,401 @@
+/*
+ * Copyright (C) 2020 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 <assert.h>
+#include <getopt.h>
+#include <inttypes.h>
+#include <iterator>
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#include <vector>
+
+#include <audio_utils/channels.h>
+#include <audio_utils/primitives.h>
+#include <log/log.h>
+#include <system/audio.h>
+
+#include "EffectReverb.h"
+
+// This is the only symbol that needs to be exported
+extern audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM;
+
+// Global Variables
+enum ReverbParams {
+    ARG_HELP = 1,
+    ARG_INPUT,
+    ARG_OUTPUT,
+    ARG_FS,
+    ARG_CH_MASK,
+    ARG_PRESET,
+    ARG_AUX,
+    ARG_MONO_MODE,
+    ARG_FILE_CH,
+};
+
+const effect_uuid_t kReverbUuids[] = {
+        {0x172cdf00,
+         0xa3bc,
+         0x11df,
+         0xa72f,
+         {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // preset-insert mode
+        {0xf29a1400,
+         0xa3bb,
+         0x11df,
+         0x8ddc,
+         {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // preset-aux mode
+};
+
+// structures
+struct reverbConfigParams_t {
+    int fChannels = 2;
+    int monoMode = false;
+    int frameLength = 256;
+    int preset = 0;
+    int nrChannels = 2;
+    int sampleRate = 48000;
+    int auxiliary = 0;
+    audio_channel_mask_t chMask = AUDIO_CHANNEL_OUT_STEREO;
+};
+
+constexpr audio_channel_mask_t kReverbConfigChMask[] = {
+        AUDIO_CHANNEL_OUT_MONO,
+        AUDIO_CHANNEL_OUT_STEREO,
+        AUDIO_CHANNEL_OUT_2POINT1,
+        AUDIO_CHANNEL_OUT_2POINT0POINT2,
+        AUDIO_CHANNEL_OUT_QUAD,
+        AUDIO_CHANNEL_OUT_QUAD_BACK,
+        AUDIO_CHANNEL_OUT_QUAD_SIDE,
+        AUDIO_CHANNEL_OUT_SURROUND,
+        AUDIO_CHANNEL_INDEX_MASK_4,
+        AUDIO_CHANNEL_OUT_2POINT1POINT2,
+        AUDIO_CHANNEL_OUT_3POINT0POINT2,
+        AUDIO_CHANNEL_OUT_PENTA,
+        AUDIO_CHANNEL_INDEX_MASK_5,
+        AUDIO_CHANNEL_OUT_3POINT1POINT2,
+        AUDIO_CHANNEL_OUT_5POINT1,
+        AUDIO_CHANNEL_OUT_5POINT1_BACK,
+        AUDIO_CHANNEL_OUT_5POINT1_SIDE,
+        AUDIO_CHANNEL_INDEX_MASK_6,
+        AUDIO_CHANNEL_OUT_6POINT1,
+        AUDIO_CHANNEL_INDEX_MASK_7,
+        AUDIO_CHANNEL_OUT_5POINT1POINT2,
+        AUDIO_CHANNEL_OUT_7POINT1,
+        AUDIO_CHANNEL_INDEX_MASK_8,
+        AUDIO_CHANNEL_INDEX_MASK_9,
+        AUDIO_CHANNEL_INDEX_MASK_10,
+        AUDIO_CHANNEL_INDEX_MASK_11,
+        AUDIO_CHANNEL_INDEX_MASK_12,
+        AUDIO_CHANNEL_INDEX_MASK_13,
+        AUDIO_CHANNEL_INDEX_MASK_14,
+        AUDIO_CHANNEL_INDEX_MASK_15,
+        AUDIO_CHANNEL_INDEX_MASK_16,
+        AUDIO_CHANNEL_INDEX_MASK_17,
+        AUDIO_CHANNEL_INDEX_MASK_18,
+        AUDIO_CHANNEL_INDEX_MASK_19,
+        AUDIO_CHANNEL_INDEX_MASK_20,
+        AUDIO_CHANNEL_INDEX_MASK_21,
+        AUDIO_CHANNEL_INDEX_MASK_22,
+        AUDIO_CHANNEL_INDEX_MASK_23,
+        AUDIO_CHANNEL_INDEX_MASK_24,
+};
+
+constexpr int kReverbConfigChMaskCount = std::size(kReverbConfigChMask);
+
+int reverbCreateEffect(effect_handle_t* pEffectHandle, effect_config_t* pConfig, int sessionId,
+                       int ioId, int auxFlag) {
+    if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.create_effect(&kReverbUuids[auxFlag], sessionId,
+                                                                 ioId, pEffectHandle);
+        status != 0) {
+        ALOGE("Reverb create returned an error = %d\n", status);
+        return EXIT_FAILURE;
+    }
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    (**pEffectHandle)
+            ->command(*pEffectHandle, EFFECT_CMD_SET_CONFIG, sizeof(effect_config_t), pConfig,
+                      &replySize, &reply);
+    return reply;
+}
+
+int reverbSetConfigParam(uint32_t paramType, uint32_t paramValue, effect_handle_t effectHandle) {
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    uint32_t paramData[2] = {paramType, paramValue};
+    effect_param_t* effectParam = (effect_param_t*)malloc(sizeof(*effectParam) + sizeof(paramData));
+    memcpy(&effectParam->data[0], &paramData[0], sizeof(paramData));
+    effectParam->psize = sizeof(paramData[0]);
+    effectParam->vsize = sizeof(paramData[1]);
+    int status = (*effectHandle)
+                         ->command(effectHandle, EFFECT_CMD_SET_PARAM,
+                                   sizeof(effect_param_t) + sizeof(paramData), effectParam,
+                                   &replySize, &reply);
+    free(effectParam);
+    if (status != 0) {
+        ALOGE("Reverb set config returned an error = %d\n", status);
+        return status;
+    }
+    return reply;
+}
+
+void printUsage() {
+    printf("\nUsage: ");
+    printf("\n     <executable> [options]\n");
+    printf("\nwhere options are, ");
+    printf("\n     --input <inputfile>");
+    printf("\n           path to the input file");
+    printf("\n     --output <outputfile>");
+    printf("\n           path to the output file");
+    printf("\n     --help");
+    printf("\n           prints this usage information");
+    printf("\n     --chMask <channel_mask>\n");
+    printf("\n           0  - AUDIO_CHANNEL_OUT_MONO");
+    printf("\n           1  - AUDIO_CHANNEL_OUT_STEREO");
+    printf("\n           2  - AUDIO_CHANNEL_OUT_2POINT1");
+    printf("\n           3  - AUDIO_CHANNEL_OUT_2POINT0POINT2");
+    printf("\n           4  - AUDIO_CHANNEL_OUT_QUAD");
+    printf("\n           5  - AUDIO_CHANNEL_OUT_QUAD_BACK");
+    printf("\n           6  - AUDIO_CHANNEL_OUT_QUAD_SIDE");
+    printf("\n           7  - AUDIO_CHANNEL_OUT_SURROUND");
+    printf("\n           8  - canonical channel index mask for 4 ch: (1 << 4) - 1");
+    printf("\n           9  - AUDIO_CHANNEL_OUT_2POINT1POINT2");
+    printf("\n           10 - AUDIO_CHANNEL_OUT_3POINT0POINT2");
+    printf("\n           11 - AUDIO_CHANNEL_OUT_PENTA");
+    printf("\n           12 - canonical channel index mask for 5 ch: (1 << 5) - 1");
+    printf("\n           13 - AUDIO_CHANNEL_OUT_3POINT1POINT2");
+    printf("\n           14 - AUDIO_CHANNEL_OUT_5POINT1");
+    printf("\n           15 - AUDIO_CHANNEL_OUT_5POINT1_BACK");
+    printf("\n           16 - AUDIO_CHANNEL_OUT_5POINT1_SIDE");
+    printf("\n           17 - canonical channel index mask for 6 ch: (1 << 6) - 1");
+    printf("\n           18 - AUDIO_CHANNEL_OUT_6POINT1");
+    printf("\n           19 - canonical channel index mask for 7 ch: (1 << 7) - 1");
+    printf("\n           20 - AUDIO_CHANNEL_OUT_5POINT1POINT2");
+    printf("\n           21 - AUDIO_CHANNEL_OUT_7POINT1");
+    printf("\n           22 - canonical channel index mask for 8 ch: (1 << 8) - 1");
+    printf("\n           default 0");
+    printf("\n     --fs <sampling_freq>");
+    printf("\n           Sampling frequency in Hz, default 48000.");
+    printf("\n     --preset <preset_value>");
+    printf("\n           0 - None");
+    printf("\n           1 - Small Room");
+    printf("\n           2 - Medium Room");
+    printf("\n           3 - Large Room");
+    printf("\n           4 - Medium Hall");
+    printf("\n           5 - Large Hall");
+    printf("\n           6 - Plate");
+    printf("\n           default 0");
+    printf("\n     --fch <file_channels>");
+    printf("\n           number of channels in input file (1 through 8), default 1");
+    printf("\n     --M");
+    printf("\n           Mono mode (force all input audio channels to be identical)");
+    printf("\n     --aux <auxiliary_flag> ");
+    printf("\n           0 - Insert Mode on");
+    printf("\n           1 - auxiliary Mode on");
+    printf("\n           default 0");
+    printf("\n");
+}
+
+int main(int argc, const char* argv[]) {
+    if (argc == 1) {
+        printUsage();
+        return EXIT_FAILURE;
+    }
+
+    reverbConfigParams_t revConfigParams{};  // default initialize
+    const char* inputFile = nullptr;
+    const char* outputFile = nullptr;
+
+    const option long_opts[] = {
+            {"help", no_argument, nullptr, ARG_HELP},
+            {"input", required_argument, nullptr, ARG_INPUT},
+            {"output", required_argument, nullptr, ARG_OUTPUT},
+            {"fs", required_argument, nullptr, ARG_FS},
+            {"chMask", required_argument, nullptr, ARG_CH_MASK},
+            {"preset", required_argument, nullptr, ARG_PRESET},
+            {"aux", required_argument, nullptr, ARG_AUX},
+            {"M", no_argument, &revConfigParams.monoMode, true},
+            {"fch", required_argument, nullptr, ARG_FILE_CH},
+            {nullptr, 0, nullptr, 0},
+    };
+
+    while (true) {
+        const int opt = getopt_long(argc, (char* const*)argv, "i:o:", long_opts, nullptr);
+        if (opt == -1) {
+            break;
+        }
+        switch (opt) {
+            case ARG_HELP:
+                printUsage();
+                return EXIT_SUCCESS;
+            case ARG_INPUT: {
+                inputFile = (char*)optarg;
+                break;
+            }
+            case ARG_OUTPUT: {
+                outputFile = (char*)optarg;
+                break;
+            }
+            case ARG_FS: {
+                revConfigParams.sampleRate = atoi(optarg);
+                break;
+            }
+            case ARG_CH_MASK: {
+                int chMaskIdx = atoi(optarg);
+                if (chMaskIdx < 0 or chMaskIdx > kReverbConfigChMaskCount) {
+                    ALOGE("Channel Mask index not in correct range\n");
+                    printUsage();
+                    return EXIT_FAILURE;
+                }
+                revConfigParams.chMask = kReverbConfigChMask[chMaskIdx];
+                break;
+            }
+            case ARG_PRESET: {
+                revConfigParams.preset = atoi(optarg);
+                break;
+            }
+            case ARG_AUX: {
+                revConfigParams.auxiliary = atoi(optarg);
+                break;
+            }
+            case ARG_MONO_MODE: {
+                break;
+            }
+            case ARG_FILE_CH: {
+                revConfigParams.fChannels = atoi(optarg);
+                break;
+            }
+            default:
+                break;
+        }
+    }
+
+    if (inputFile == nullptr) {
+        ALOGE("Error: missing input files\n");
+        printUsage();
+        return EXIT_FAILURE;
+    }
+    std::unique_ptr<FILE, decltype(&fclose)> inputFp(fopen(inputFile, "rb"), &fclose);
+
+    if (inputFp == nullptr) {
+        ALOGE("Cannot open input file %s\n", inputFile);
+        return EXIT_FAILURE;
+    }
+
+    if (outputFile == nullptr) {
+        ALOGE("Error: missing output files\n");
+        printUsage();
+        return EXIT_FAILURE;
+    }
+    std::unique_ptr<FILE, decltype(&fclose)> outputFp(fopen(outputFile, "wb"), &fclose);
+
+    if (outputFp == nullptr) {
+        ALOGE("Cannot open output file %s\n", outputFile);
+        return EXIT_FAILURE;
+    }
+
+    int32_t sessionId = 1;
+    int32_t ioId = 1;
+    effect_handle_t effectHandle = nullptr;
+    effect_config_t config;
+    config.inputCfg.samplingRate = config.outputCfg.samplingRate = revConfigParams.sampleRate;
+    config.inputCfg.channels = config.outputCfg.channels = revConfigParams.chMask;
+    config.inputCfg.format = config.outputCfg.format = AUDIO_FORMAT_PCM_FLOAT;
+    if (int status = reverbCreateEffect(&effectHandle, &config, sessionId, ioId,
+                                        revConfigParams.auxiliary);
+        status != 0) {
+        ALOGE("Create effect call returned error %i", status);
+        return EXIT_FAILURE;
+    }
+
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    (*effectHandle)->command(effectHandle, EFFECT_CMD_ENABLE, 0, nullptr, &replySize, &reply);
+    if (reply != 0) {
+        ALOGE("Command enable call returned error %d\n", reply);
+        return EXIT_FAILURE;
+    }
+
+    if (int status = reverbSetConfigParam(REVERB_PARAM_PRESET, (uint32_t)revConfigParams.preset,
+                                          effectHandle);
+        status != 0) {
+        ALOGE("Invalid reverb preset. Error %d\n", status);
+        return EXIT_FAILURE;
+    }
+
+    revConfigParams.nrChannels = audio_channel_count_from_out_mask(revConfigParams.chMask);
+    const int channelCount = revConfigParams.nrChannels;
+    const int frameLength = revConfigParams.frameLength;
+#ifdef BYPASS_EXEC
+    const int frameSize = (int)channelCount * sizeof(float);
+#endif
+    const int ioChannelCount = revConfigParams.fChannels;
+    const int ioFrameSize = ioChannelCount * sizeof(short);
+    const int maxChannelCount = std::max(channelCount, ioChannelCount);
+
+    std::vector<short> in(frameLength * maxChannelCount);
+    std::vector<short> out(frameLength * maxChannelCount);
+    std::vector<float> floatIn(frameLength * channelCount);
+    std::vector<float> floatOut(frameLength * channelCount);
+
+    int frameCounter = 0;
+
+    while (fread(in.data(), ioFrameSize, frameLength, inputFp.get()) == (size_t)frameLength) {
+        if (ioChannelCount != channelCount) {
+            adjust_channels(in.data(), ioChannelCount, in.data(), channelCount, sizeof(short),
+                            frameLength * ioFrameSize);
+        }
+        memcpy_to_float_from_i16(floatIn.data(), in.data(), frameLength * channelCount);
+
+        // Mono mode will replicate the first channel to all other channels.
+        // This ensures all audio channels are identical. This is useful for testing
+        // Bass Boost, which extracts a mono signal for processing.
+        if (revConfigParams.monoMode && channelCount > 1) {
+            for (int i = 0; i < frameLength; ++i) {
+                auto* fp = &floatIn[i * channelCount];
+                std::fill(fp + 1, fp + channelCount, *fp);  // replicate ch 0
+            }
+        }
+
+        audio_buffer_t inputBuffer, outputBuffer;
+        inputBuffer.frameCount = outputBuffer.frameCount = frameLength;
+        inputBuffer.f32 = floatIn.data();
+        outputBuffer.f32 = floatOut.data();
+#ifndef BYPASS_EXEC
+        if (int status = (*effectHandle)->process(effectHandle, &inputBuffer, &outputBuffer);
+            status != 0) {
+            ALOGE("\nError: Process returned with error %d\n", status);
+            return EXIT_FAILURE;
+        }
+#else
+        memcpy(floatOut.data(), floatIn.data(), frameLength * frameSize);
+#endif
+        memcpy_to_i16_from_float(out.data(), floatOut.data(), frameLength * channelCount);
+
+        if (ioChannelCount != channelCount) {
+            adjust_channels(out.data(), channelCount, out.data(), ioChannelCount, sizeof(short),
+                            frameLength * channelCount * sizeof(short));
+        }
+        (void)fwrite(out.data(), ioFrameSize, frameLength, outputFp.get());
+        frameCounter += frameLength;
+    }
+
+    if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.release_effect(effectHandle); status != 0) {
+        ALOGE("Audio Preprocessing release returned an error = %d\n", status);
+        return EXIT_FAILURE;
+    }
+    printf("frameCounter: [%d]\n", frameCounter);
+
+    return EXIT_SUCCESS;
+}
diff --git a/media/libeffects/lvm/tests/snr.cpp b/media/libeffects/lvm/tests/snr.cpp
index 885994c..0fef334 100644
--- a/media/libeffects/lvm/tests/snr.cpp
+++ b/media/libeffects/lvm/tests/snr.cpp
@@ -22,84 +22,83 @@
 #include <vector>
 
 template <typename T, typename A = float>
-std::pair<A, A> getSignalNoise(FILE *finp, FILE *fref) {
-  constexpr size_t framesize = 256;
-  std::vector<T> in(framesize);
-  std::vector<T> ref(framesize);
-  A signal{};
-  A noise{};
+std::pair<A, A> getSignalNoise(FILE* finp, FILE* fref) {
+    constexpr size_t framesize = 256;
+    std::vector<T> in(framesize);
+    std::vector<T> ref(framesize);
+    A signal{};
+    A noise{};
 
-  for (;;) {
-    size_t read_samples_in = fread(&in[0], sizeof(T), framesize, finp);
-    const size_t read_samples_ref = fread(&ref[0], sizeof(T), framesize, fref);
-    if (read_samples_in != read_samples_ref) {
-      printf("file sizes do not match (last %zu %zu)", read_samples_in, read_samples_ref);
-      read_samples_in = std::min(read_samples_in, read_samples_ref);
+    for (;;) {
+        size_t read_samples_in = fread(&in[0], sizeof(T), framesize, finp);
+        const size_t read_samples_ref = fread(&ref[0], sizeof(T), framesize, fref);
+        if (read_samples_in != read_samples_ref) {
+            printf("file sizes do not match (last %zu %zu)", read_samples_in, read_samples_ref);
+            read_samples_in = std::min(read_samples_in, read_samples_ref);
+        }
+        if (read_samples_in == 0) {
+            return {signal, noise};
+        }
+        for (size_t i = 0; i < read_samples_in; ++i) {
+            const A value(ref[i]);
+            const A diff(A(in[i]) - value);
+            signal += value * value;
+            noise += diff * diff;
+        }
     }
-    if (read_samples_in == 0) {
-        return { signal, noise };
-    }
-    for (size_t i = 0; i < read_samples_in; ++i) {
-       const A value(ref[i]);
-       const A diff(A(in[i]) - value);
-       signal += value * value;
-       noise += diff * diff;
-    }
-  }
 }
 
 void printUsage() {
-  printf("\nUsage: ");
-  printf("\n     snr <ref_file> <test_file> [options]\n");
-  printf("\nwhere, \n     <ref_file>  is the reference file name");
-  printf("\n                  on which will be taken as pure signal");
-  printf("\n     <test_file> is test file for snr calculation");
-  printf("\n     and options are mentioned below");
-  printf("\n");
-  printf("\n     -pcm_format:<pcm format of input files>");
-  printf("\n           0 - 16 bit pcm");
-  printf("\n           1 - 32 bit float");
-  printf("\n           default 0");
-  printf("\n     -thr:<threshold value>");
-  printf("\n           default - negative infinity\n\n");
+    printf("\nUsage: ");
+    printf("\n     snr <ref_file> <test_file> [options]\n");
+    printf("\nwhere, \n     <ref_file>  is the reference file name");
+    printf("\n                  on which will be taken as pure signal");
+    printf("\n     <test_file> is test file for snr calculation");
+    printf("\n     and options are mentioned below");
+    printf("\n");
+    printf("\n     -pcm_format:<pcm format of input files>");
+    printf("\n           0 - 16 bit pcm");
+    printf("\n           1 - 32 bit float");
+    printf("\n           default 0");
+    printf("\n     -thr:<threshold value>");
+    printf("\n           default - negative infinity\n\n");
 }
 
-int main(int argc, const char *argv[]) {
-  if (argc < 3) {
-    printUsage();
-    return -1;
-  }
-  int pcm_format = 0;
-  float thr = - std::numeric_limits<float>::infinity();
-  FILE *fref = fopen(argv[1], "rb");
-  FILE *finp = fopen(argv[2], "rb");
-  for (int i = 3; i < argc; i++) {
-    if (!strncmp(argv[i], "-pcm_format:", 12)) {
-      pcm_format = atoi(argv[i] + 12);
-    } else if (!strncmp(argv[i], "-thr:", 5)) {
-      thr = atof(argv[i] + 5);
+int main(int argc, const char* argv[]) {
+    if (argc < 3) {
+        printUsage();
+        return -1;
     }
-  }
-  if (finp == nullptr || fref == nullptr) {
-    printf("\nError: missing input/reference files\n");
-    return -1;
-  }
-  int ret = EXIT_SUCCESS;
-  auto sn = pcm_format == 0
-      ? getSignalNoise<short>(finp, fref)
-      : getSignalNoise<float>(finp, fref);
-  if (sn.first > 0.f && sn.second > 0.f) {
-    float snr = 10.f * log(sn.first / sn.second);
-    // compare the measured snr value with threshold
-    if (snr < thr) {
-      printf("%.6f less than threshold %.6f\n", snr, thr);
-      ret = EXIT_FAILURE;
-    } else {
-      printf("%.6f\n", snr);
+    int pcm_format = 0;
+    float thr = -std::numeric_limits<float>::infinity();
+    FILE* fref = fopen(argv[1], "rb");
+    FILE* finp = fopen(argv[2], "rb");
+    for (int i = 3; i < argc; i++) {
+        if (!strncmp(argv[i], "-pcm_format:", 12)) {
+            pcm_format = atoi(argv[i] + 12);
+        } else if (!strncmp(argv[i], "-thr:", 5)) {
+            thr = atof(argv[i] + 5);
+        }
     }
-  }
-  fclose(finp);
-  fclose(fref);
+    if (finp == nullptr || fref == nullptr) {
+        printf("\nError: missing input/reference files\n");
+        return -1;
+    }
+    int ret = EXIT_SUCCESS;
+    auto sn =
+            pcm_format == 0 ? getSignalNoise<short>(finp, fref) : getSignalNoise<float>(finp, fref);
+    if (sn.first > 0.f && sn.second > 0.f) {
+        float snr = 10.f * log(sn.first / sn.second);
+        // compare the measured snr value with threshold
+        if (snr < thr) {
+            printf("%.6f less than threshold %.6f\n", snr, thr);
+            ret = EXIT_FAILURE;
+        } else {
+            printf("%.6f\n", snr);
+        }
+    }
+    fclose(finp);
+    fclose(fref);
 
-  return ret;
+    return ret;
 }
diff --git a/media/libeffects/lvm/wrapper/Android.bp b/media/libeffects/lvm/wrapper/Android.bp
index afc4220..e169e3c 100644
--- a/media/libeffects/lvm/wrapper/Android.bp
+++ b/media/libeffects/lvm/wrapper/Android.bp
@@ -1,5 +1,24 @@
 // music bundle wrapper
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libeffects_lvm_wrapper_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libeffects_lvm_wrapper_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libbundlewrapper",
 
     arch: {
@@ -9,11 +28,11 @@
     },
 
     vendor: true,
+    host_supported: true,
     srcs: ["Bundle/EffectBundle.cpp"],
 
     cppflags: [
         "-fvisibility=hidden",
-        "-DSUPPORT_MC",
 
         "-Wall",
         "-Werror",
@@ -26,7 +45,6 @@
     shared_libs: [
         "libaudioutils",
         "libcutils",
-        "libdl",
         "liblog",
     ],
 
@@ -39,7 +57,7 @@
 }
 
 // reverb wrapper
-cc_library_shared {
+cc_library {
     name: "libreverbwrapper",
 
     arch: {
@@ -49,6 +67,7 @@
     },
 
     vendor: true,
+    host_supported: true,
     srcs: ["Reverb/EffectReverb.cpp"],
 
     cppflags: [
@@ -65,7 +84,6 @@
     shared_libs: [
         "libaudioutils",
         "libcutils",
-        "libdl",
         "liblog",
     ],
 
diff --git a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
index 6fca0e7..df64676 100644
--- a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
+++ b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
@@ -18,7 +18,7 @@
 typedef float LVM_FLOAT;
 #endif
 #define LOG_TAG "Bundle"
-#define ARRAY_SIZE(array) (sizeof (array) / sizeof (array)[0])
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array)[0])
 //#define LOG_NDEBUG 0
 
 #include <assert.h>
@@ -42,26 +42,33 @@
 #ifdef VERY_VERY_VERBOSE_LOGGING
 #define ALOGVV ALOGV
 #else
-#define ALOGVV(a...) do { } while (false)
+#define ALOGVV(a...) \
+    do {             \
+    } while (false)
 #endif
 
-#define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc){\
-        if ((LvmStatus) == LVM_NULLADDRESS){\
-            ALOGV("\tLVM_ERROR : Parameter error - "\
-                    "null pointer returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
-        }\
-        if ((LvmStatus) == LVM_ALIGNMENTERROR){\
-            ALOGV("\tLVM_ERROR : Parameter error - "\
-                    "bad alignment returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
-        }\
-        if ((LvmStatus) == LVM_INVALIDNUMSAMPLES){\
-            ALOGV("\tLVM_ERROR : Parameter error - "\
-                    "bad number of samples returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
-        }\
-        if ((LvmStatus) == LVM_OUTOFRANGE){\
-            ALOGV("\tLVM_ERROR : Parameter error - "\
-                    "out of range returned by %s in %s\n", callingFunc, calledFunc);\
-        }\
+#define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc)             \
+    {                                                                   \
+        if ((LvmStatus) == LVM_NULLADDRESS) {                           \
+            ALOGV("\tLVM_ERROR : Parameter error - "                    \
+                  "null pointer returned by %s in %s\n\n\n\n",          \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
+        if ((LvmStatus) == LVM_ALIGNMENTERROR) {                        \
+            ALOGV("\tLVM_ERROR : Parameter error - "                    \
+                  "bad alignment returned by %s in %s\n\n\n\n",         \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
+        if ((LvmStatus) == LVM_INVALIDNUMSAMPLES) {                     \
+            ALOGV("\tLVM_ERROR : Parameter error - "                    \
+                  "bad number of samples returned by %s in %s\n\n\n\n", \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
+        if ((LvmStatus) == LVM_OUTOFRANGE) {                            \
+            ALOGV("\tLVM_ERROR : Parameter error - "                    \
+                  "out of range returned by %s in %s\n",                \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
     }
 
 // Namespaces
@@ -74,20 +81,21 @@
 int SessionIndex[LVM_MAX_SESSIONS];
 
 /* local functions */
-#define CHECK_ARG(cond) {                     \
-    if (!(cond)) {                            \
-        ALOGV("\tLVM_ERROR : Invalid argument: "#cond);      \
-        return -EINVAL;                       \
-    }                                         \
-}
+#define CHECK_ARG(cond)                                      \
+    {                                                        \
+        if (!(cond)) {                                       \
+            ALOGV("\tLVM_ERROR : Invalid argument: " #cond); \
+            return -EINVAL;                                  \
+        }                                                    \
+    }
 
 // NXP SW BassBoost UUID
 const effect_descriptor_t gBassBoostDescriptor = {
-        {0x0634f220, 0xddd4, 0x11db, 0xa0fc, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b }},
-        {0x8631f300, 0x72e2, 0x11df, 0xb57e, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}, // uuid
+        {0x0634f220, 0xddd4, 0x11db, 0xa0fc, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        {0x8631f300, 0x72e2, 0x11df, 0xb57e, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // uuid
         EFFECT_CONTROL_API_VERSION,
-        (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_FIRST | EFFECT_FLAG_DEVICE_IND
-        | EFFECT_FLAG_VOLUME_CTRL),
+        (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_FIRST | EFFECT_FLAG_DEVICE_IND |
+         EFFECT_FLAG_VOLUME_CTRL),
         BASS_BOOST_CUP_LOAD_ARM9E,
         BUNDLE_MEM_USAGE,
         "Dynamic Bass Boost",
@@ -99,8 +107,8 @@
         {0x37cc2c00, 0xdddd, 0x11db, 0x8577, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
         {0x1d4033c0, 0x8557, 0x11df, 0x9f2d, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
         EFFECT_CONTROL_API_VERSION,
-        (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_LAST | EFFECT_FLAG_DEVICE_IND
-        | EFFECT_FLAG_VOLUME_CTRL),
+        (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_LAST | EFFECT_FLAG_DEVICE_IND |
+         EFFECT_FLAG_VOLUME_CTRL),
         VIRTUALIZER_CUP_LOAD_ARM9E,
         BUNDLE_MEM_USAGE,
         "Virtualizer",
@@ -109,8 +117,8 @@
 
 // NXP SW Equalizer UUID
 const effect_descriptor_t gEqualizerDescriptor = {
-        {0x0bed4300, 0xddd6, 0x11db, 0x8f34, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}, // type
-        {0xce772f20, 0x847d, 0x11df, 0xbb17, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}}, // uuid Eq NXP
+        {0x0bed4300, 0xddd6, 0x11db, 0x8f34, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // type
+        {0xce772f20, 0x847d, 0x11df, 0xbb17, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // uuid Eq NXP
         EFFECT_CONTROL_API_VERSION,
         (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_FIRST | EFFECT_FLAG_VOLUME_CTRL),
         EQUALIZER_CUP_LOAD_ARM9E,
@@ -121,8 +129,8 @@
 
 // NXP SW Volume UUID
 const effect_descriptor_t gVolumeDescriptor = {
-        {0x09e8ede0, 0xddde, 0x11db, 0xb4f6, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b }},
-        {0x119341a0, 0x8469, 0x11df, 0x81f9, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b }}, //uuid VOL NXP
+        {0x09e8ede0, 0xddde, 0x11db, 0xb4f6, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        {0x119341a0, 0x8469, 0x11df, 0x81f9, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // uuid VOL NXP
         EFFECT_CONTROL_API_VERSION,
         (EFFECT_FLAG_TYPE_INSERT | EFFECT_FLAG_INSERT_LAST | EFFECT_FLAG_VOLUME_CTRL),
         VOLUME_CUP_LOAD_ARM9E,
@@ -132,77 +140,50 @@
 };
 
 //--- local function prototypes
-void LvmGlobalBundle_init      (void);
-int  LvmBundle_init            (EffectContext *pContext);
-int  LvmEffect_enable          (EffectContext *pContext);
-int  LvmEffect_disable         (EffectContext *pContext);
-void LvmEffect_free            (EffectContext *pContext);
-int  Effect_setConfig          (EffectContext *pContext, effect_config_t *pConfig);
-void Effect_getConfig          (EffectContext *pContext, effect_config_t *pConfig);
-int  BassBoost_setParameter    (EffectContext *pContext,
-                                uint32_t       paramSize,
-                                void          *pParam,
-                                uint32_t       valueSize,
-                                void          *pValue);
-int  BassBoost_getParameter    (EffectContext *pContext,
-                                uint32_t       paramSize,
-                                void          *pParam,
-                                uint32_t      *pValueSize,
-                                void          *pValue);
-int  Virtualizer_setParameter  (EffectContext *pContext,
-                                uint32_t       paramSize,
-                                void          *pParam,
-                                uint32_t       valueSize,
-                                void          *pValue);
-int  Virtualizer_getParameter  (EffectContext *pContext,
-                                uint32_t       paramSize,
-                                void          *pParam,
-                                uint32_t      *pValueSize,
-                                void          *pValue);
-int  Equalizer_setParameter    (EffectContext *pContext,
-                                uint32_t       paramSize,
-                                void          *pParam,
-                                uint32_t       valueSize,
-                                void          *pValue);
-int  Equalizer_getParameter    (EffectContext *pContext,
-                                uint32_t       paramSize,
-                                void          *pParam,
-                                uint32_t      *pValueSize,
-                                void          *pValue);
-int  Volume_setParameter       (EffectContext *pContext,
-                                uint32_t       paramSize,
-                                void          *pParam,
-                                uint32_t       valueSize,
-                                void          *pValue);
-int  Volume_getParameter       (EffectContext *pContext,
-                                uint32_t       paramSize,
-                                void          *pParam,
-                                uint32_t      *pValueSize,
-                                void          *pValue);
-int Effect_setEnabled(EffectContext *pContext, bool enabled);
+void LvmGlobalBundle_init(void);
+int LvmBundle_init(EffectContext* pContext);
+int LvmEffect_enable(EffectContext* pContext);
+int LvmEffect_disable(EffectContext* pContext);
+int Effect_setConfig(EffectContext* pContext, effect_config_t* pConfig);
+void Effect_getConfig(EffectContext* pContext, effect_config_t* pConfig);
+int BassBoost_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                           uint32_t valueSize, void* pValue);
+int BassBoost_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                           uint32_t* pValueSize, void* pValue);
+int Virtualizer_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                             uint32_t valueSize, void* pValue);
+int Virtualizer_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                             uint32_t* pValueSize, void* pValue);
+int Equalizer_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                           uint32_t valueSize, void* pValue);
+int Equalizer_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                           uint32_t* pValueSize, void* pValue);
+int Volume_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                        uint32_t valueSize, void* pValue);
+int Volume_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                        uint32_t* pValueSize, void* pValue);
+int Effect_setEnabled(EffectContext* pContext, bool enabled);
 
 /* Effect Library Interface Implementation */
 
-extern "C" int EffectCreate(const effect_uuid_t *uuid,
-                            int32_t             sessionId,
-                            int32_t             ioId __unused,
-                            effect_handle_t  *pHandle){
+extern "C" int EffectCreate(const effect_uuid_t* uuid, int32_t sessionId,
+                            int32_t /* ioId __unused */, effect_handle_t* pHandle) {
     int ret = 0;
     int sessionNo = -1;
     int i;
-    EffectContext *pContext = NULL;
+    EffectContext* pContext = NULL;
     bool newBundle = false;
-    SessionContext *pSessionContext;
+    SessionContext* pSessionContext;
 
     ALOGV("\n\tEffectCreate start session %d", sessionId);
 
-    if (pHandle == NULL || uuid == NULL){
+    if (pHandle == NULL || uuid == NULL) {
         ALOGV("\tLVM_ERROR : EffectCreate() called with NULL pointer");
         ret = -EINVAL;
         goto exit;
     }
 
-    if(LvmInitFlag == LVM_FALSE){
+    if (LvmInitFlag == LVM_FALSE) {
         LvmInitFlag = LVM_TRUE;
         ALOGV("\tEffectCreate - Initializing all global memory");
         LvmGlobalBundle_init();
@@ -210,7 +191,7 @@
 
     // Find sessionNo: if one already exists for the sessionId use it,
     // otherwise choose the first available empty slot.
-    for(i=0; i<LVM_MAX_SESSIONS; i++){
+    for (i = 0; i < LVM_MAX_SESSIONS; i++) {
         if (SessionIndex[i] == sessionId) {
             sessionNo = i;
             break;
@@ -232,106 +213,102 @@
     pContext = new EffectContext;
 
     // If this is the first create in this session
-    if(GlobalSessionMemory[sessionNo].bBundledEffectsEnabled == LVM_FALSE){
+    if (GlobalSessionMemory[sessionNo].bBundledEffectsEnabled == LVM_FALSE) {
         ALOGV("\tEffectCreate - This is the first effect in current sessionId %d sessionNo %d",
-                sessionId, sessionNo);
+              sessionId, sessionNo);
 
         GlobalSessionMemory[sessionNo].bBundledEffectsEnabled = LVM_TRUE;
-        GlobalSessionMemory[sessionNo].pBundledContext        = new BundledEffectContext;
+        GlobalSessionMemory[sessionNo].pBundledContext = new BundledEffectContext;
         newBundle = true;
 
         pContext->pBundledContext = GlobalSessionMemory[sessionNo].pBundledContext;
-        pContext->pBundledContext->SessionNo                = sessionNo;
-        pContext->pBundledContext->SessionId                = sessionId;
-        pContext->pBundledContext->hInstance                = NULL;
-        pContext->pBundledContext->bVolumeEnabled           = LVM_FALSE;
-        pContext->pBundledContext->bEqualizerEnabled        = LVM_FALSE;
-        pContext->pBundledContext->bBassEnabled             = LVM_FALSE;
-        pContext->pBundledContext->bBassTempDisabled        = LVM_FALSE;
-        pContext->pBundledContext->bVirtualizerEnabled      = LVM_FALSE;
+        pContext->pBundledContext->SessionNo = sessionNo;
+        pContext->pBundledContext->SessionId = sessionId;
+        pContext->pBundledContext->hInstance = NULL;
+        pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
+        pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
+        pContext->pBundledContext->bBassEnabled = LVM_FALSE;
+        pContext->pBundledContext->bBassTempDisabled = LVM_FALSE;
+        pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE;
         pContext->pBundledContext->bVirtualizerTempDisabled = LVM_FALSE;
-        pContext->pBundledContext->nOutputDevice            = AUDIO_DEVICE_NONE;
+        pContext->pBundledContext->nOutputDevice = AUDIO_DEVICE_NONE;
         pContext->pBundledContext->nVirtualizerForcedDevice = AUDIO_DEVICE_NONE;
-        pContext->pBundledContext->NumberEffectsEnabled     = 0;
-        pContext->pBundledContext->NumberEffectsCalled      = 0;
-        pContext->pBundledContext->firstVolume              = LVM_TRUE;
-        pContext->pBundledContext->volume                   = 0;
-
+        pContext->pBundledContext->NumberEffectsEnabled = 0;
+        pContext->pBundledContext->NumberEffectsCalled = 0;
+        pContext->pBundledContext->firstVolume = LVM_TRUE;
+        pContext->pBundledContext->volume = 0;
 
         /* Saved strength is used to return the exact strength that was used in the set to the get
          * because we map the original strength range of 0:1000 to 1:15, and this will avoid
          * quantisation like effect when returning
          */
-        pContext->pBundledContext->BassStrengthSaved        = 0;
-        pContext->pBundledContext->VirtStrengthSaved        = 0;
-        pContext->pBundledContext->CurPreset                = PRESET_CUSTOM;
-        pContext->pBundledContext->levelSaved               = 0;
-        pContext->pBundledContext->bMuteEnabled             = LVM_FALSE;
-        pContext->pBundledContext->bStereoPositionEnabled   = LVM_FALSE;
-        pContext->pBundledContext->positionSaved            = 0;
-        pContext->pBundledContext->workBuffer               = NULL;
-        pContext->pBundledContext->frameCount               = -1;
-        pContext->pBundledContext->SamplesToExitCountVirt   = 0;
-        pContext->pBundledContext->SamplesToExitCountBb     = 0;
-        pContext->pBundledContext->SamplesToExitCountEq     = 0;
+        pContext->pBundledContext->BassStrengthSaved = 0;
+        pContext->pBundledContext->VirtStrengthSaved = 0;
+        pContext->pBundledContext->CurPreset = PRESET_CUSTOM;
+        pContext->pBundledContext->levelSaved = 0;
+        pContext->pBundledContext->bMuteEnabled = LVM_FALSE;
+        pContext->pBundledContext->bStereoPositionEnabled = LVM_FALSE;
+        pContext->pBundledContext->positionSaved = 0;
+        pContext->pBundledContext->workBuffer = NULL;
+        pContext->pBundledContext->frameCount = -1;
+        pContext->pBundledContext->SamplesToExitCountVirt = 0;
+        pContext->pBundledContext->SamplesToExitCountBb = 0;
+        pContext->pBundledContext->SamplesToExitCountEq = 0;
         for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
             pContext->pBundledContext->bandGaindB[i] = EQNB_5BandSoftPresets[i];
         }
-        pContext->pBundledContext->effectProcessCalled      = 0;
-        pContext->pBundledContext->effectInDrain            = 0;
+        pContext->pBundledContext->effectProcessCalled = 0;
+        pContext->pBundledContext->effectInDrain = 0;
 
         ALOGV("\tEffectCreate - Calling LvmBundle_init");
         ret = LvmBundle_init(pContext);
 
-        if (ret < 0){
+        if (ret < 0) {
             ALOGV("\tLVM_ERROR : EffectCreate() Bundle init failed");
             goto exit;
         }
-    }
-    else{
+    } else {
         ALOGV("\tEffectCreate - Assigning memory for previously created effect on sessionNo %d",
-                sessionNo);
-        pContext->pBundledContext =
-                GlobalSessionMemory[sessionNo].pBundledContext;
+              sessionNo);
+        pContext->pBundledContext = GlobalSessionMemory[sessionNo].pBundledContext;
     }
     ALOGV("\tEffectCreate - pBundledContext is %p", pContext->pBundledContext);
 
     pSessionContext = &GlobalSessionMemory[pContext->pBundledContext->SessionNo];
 
     // Create each Effect
-    if (memcmp(uuid, &gBassBoostDescriptor.uuid, sizeof(effect_uuid_t)) == 0){
+    if (memcmp(uuid, &gBassBoostDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
         // Create Bass Boost
         ALOGV("\tEffectCreate - Effect to be created is LVM_BASS_BOOST");
         pSessionContext->bBassInstantiated = LVM_TRUE;
         pContext->pBundledContext->SamplesToExitCountBb = 0;
 
-        pContext->itfe       = &gLvmEffectInterface;
+        pContext->itfe = &gLvmEffectInterface;
         pContext->EffectType = LVM_BASS_BOOST;
-    } else if (memcmp(uuid, &gVirtualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0){
+    } else if (memcmp(uuid, &gVirtualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
         // Create Virtualizer
         ALOGV("\tEffectCreate - Effect to be created is LVM_VIRTUALIZER");
-        pSessionContext->bVirtualizerInstantiated=LVM_TRUE;
+        pSessionContext->bVirtualizerInstantiated = LVM_TRUE;
         pContext->pBundledContext->SamplesToExitCountVirt = 0;
 
-        pContext->itfe       = &gLvmEffectInterface;
+        pContext->itfe = &gLvmEffectInterface;
         pContext->EffectType = LVM_VIRTUALIZER;
-    } else if (memcmp(uuid, &gEqualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0){
+    } else if (memcmp(uuid, &gEqualizerDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
         // Create Equalizer
         ALOGV("\tEffectCreate - Effect to be created is LVM_EQUALIZER");
         pSessionContext->bEqualizerInstantiated = LVM_TRUE;
         pContext->pBundledContext->SamplesToExitCountEq = 0;
 
-        pContext->itfe       = &gLvmEffectInterface;
+        pContext->itfe = &gLvmEffectInterface;
         pContext->EffectType = LVM_EQUALIZER;
-    } else if (memcmp(uuid, &gVolumeDescriptor.uuid, sizeof(effect_uuid_t)) == 0){
+    } else if (memcmp(uuid, &gVolumeDescriptor.uuid, sizeof(effect_uuid_t)) == 0) {
         // Create Volume
         ALOGV("\tEffectCreate - Effect to be created is LVM_VOLUME");
         pSessionContext->bVolumeInstantiated = LVM_TRUE;
 
-        pContext->itfe       = &gLvmEffectInterface;
+        pContext->itfe = &gLvmEffectInterface;
         pContext->EffectType = LVM_VOLUME;
-    }
-    else{
+    } else {
         ALOGV("\tLVM_ERROR : EffectCreate() invalid UUID");
         ret = -EINVAL;
         goto exit;
@@ -347,66 +324,64 @@
             }
             delete pContext;
         }
-        if (pHandle != NULL)
-          *pHandle = (effect_handle_t)NULL;
+        if (pHandle != NULL) *pHandle = (effect_handle_t)NULL;
     } else {
-      if (pHandle != NULL)
-        *pHandle = (effect_handle_t)pContext;
+        if (pHandle != NULL) *pHandle = (effect_handle_t)pContext;
     }
     ALOGV("\tEffectCreate end..\n\n");
     return ret;
 } /* end EffectCreate */
 
-extern "C" int EffectRelease(effect_handle_t handle){
+extern "C" int EffectRelease(effect_handle_t handle) {
     ALOGV("\n\tEffectRelease start %p", handle);
-    EffectContext * pContext = (EffectContext *)handle;
+    EffectContext* pContext = (EffectContext*)handle;
 
     ALOGV("\tEffectRelease start handle: %p, context %p", handle, pContext->pBundledContext);
-    if (pContext == NULL){
+    if (pContext == NULL) {
         ALOGV("\tLVM_ERROR : EffectRelease called with NULL pointer");
         return -EINVAL;
     }
 
-    SessionContext *pSessionContext = &GlobalSessionMemory[pContext->pBundledContext->SessionNo];
+    SessionContext* pSessionContext = &GlobalSessionMemory[pContext->pBundledContext->SessionNo];
 
     // Clear the instantiated flag for the effect
     // protect agains the case where an effect is un-instantiated without being disabled
 
-    int &effectInDrain = pContext->pBundledContext->effectInDrain;
-    if(pContext->EffectType == LVM_BASS_BOOST) {
+    int& effectInDrain = pContext->pBundledContext->effectInDrain;
+    if (pContext->EffectType == LVM_BASS_BOOST) {
         ALOGV("\tEffectRelease LVM_BASS_BOOST Clearing global intstantiated flag");
         pSessionContext->bBassInstantiated = LVM_FALSE;
-        if(pContext->pBundledContext->SamplesToExitCountBb > 0){
+        if (pContext->pBundledContext->SamplesToExitCountBb > 0) {
             pContext->pBundledContext->NumberEffectsEnabled--;
         }
         pContext->pBundledContext->SamplesToExitCountBb = 0;
-    } else if(pContext->EffectType == LVM_VIRTUALIZER) {
+    } else if (pContext->EffectType == LVM_VIRTUALIZER) {
         ALOGV("\tEffectRelease LVM_VIRTUALIZER Clearing global intstantiated flag");
         pSessionContext->bVirtualizerInstantiated = LVM_FALSE;
-        if(pContext->pBundledContext->SamplesToExitCountVirt > 0){
+        if (pContext->pBundledContext->SamplesToExitCountVirt > 0) {
             pContext->pBundledContext->NumberEffectsEnabled--;
         }
         pContext->pBundledContext->SamplesToExitCountVirt = 0;
-    } else if(pContext->EffectType == LVM_EQUALIZER) {
+    } else if (pContext->EffectType == LVM_EQUALIZER) {
         ALOGV("\tEffectRelease LVM_EQUALIZER Clearing global intstantiated flag");
-        pSessionContext->bEqualizerInstantiated =LVM_FALSE;
-        if(pContext->pBundledContext->SamplesToExitCountEq > 0){
+        pSessionContext->bEqualizerInstantiated = LVM_FALSE;
+        if (pContext->pBundledContext->SamplesToExitCountEq > 0) {
             pContext->pBundledContext->NumberEffectsEnabled--;
         }
         pContext->pBundledContext->SamplesToExitCountEq = 0;
-    } else if(pContext->EffectType == LVM_VOLUME) {
+    } else if (pContext->EffectType == LVM_VOLUME) {
         ALOGV("\tEffectRelease LVM_VOLUME Clearing global intstantiated flag");
         pSessionContext->bVolumeInstantiated = LVM_FALSE;
         // There is no samplesToExitCount for volume so we also use the drain flag to check
         // if we should decrement the effects enabled.
-        if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE
-                || (effectInDrain & 1 << LVM_VOLUME) != 0) {
+        if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE ||
+            (effectInDrain & 1 << LVM_VOLUME) != 0) {
             pContext->pBundledContext->NumberEffectsEnabled--;
         }
     } else {
         ALOGV("\tLVM_ERROR : EffectRelease : Unsupported effect\n\n\n\n\n\n\n");
     }
-    effectInDrain &= ~(1 << pContext->EffectType); // no need to drain if released
+    effectInDrain &= ~(1 << pContext->EffectType);  // no need to drain if released
 
     // Disable effect, in this case ignore errors (return codes)
     // if an effect has already been disabled
@@ -414,17 +389,15 @@
 
     // if all effects are no longer instantiaed free the lvm memory and delete BundledEffectContext
     if ((pSessionContext->bBassInstantiated == LVM_FALSE) &&
-            (pSessionContext->bVolumeInstantiated == LVM_FALSE) &&
-            (pSessionContext->bEqualizerInstantiated ==LVM_FALSE) &&
-            (pSessionContext->bVirtualizerInstantiated==LVM_FALSE))
-    {
-
+        (pSessionContext->bVolumeInstantiated == LVM_FALSE) &&
+        (pSessionContext->bEqualizerInstantiated == LVM_FALSE) &&
+        (pSessionContext->bVirtualizerInstantiated == LVM_FALSE)) {
         // Clear the SessionIndex
-        for(int i=0; i<LVM_MAX_SESSIONS; i++){
-            if(SessionIndex[i] == pContext->pBundledContext->SessionId){
+        for (int i = 0; i < LVM_MAX_SESSIONS; i++) {
+            if (SessionIndex[i] == pContext->pBundledContext->SessionId) {
                 SessionIndex[i] = LVM_UNUSED_SESSION;
-                ALOGV("\tEffectRelease: Clearing SessionIndex SessionNo %d for SessionId %d\n",
-                        i, pContext->pBundledContext->SessionId);
+                ALOGV("\tEffectRelease: Clearing SessionIndex SessionNo %d for SessionId %d\n", i,
+                      pContext->pBundledContext->SessionId);
                 break;
             }
         }
@@ -433,7 +406,7 @@
         pSessionContext->bBundledEffectsEnabled = LVM_FALSE;
         pSessionContext->pBundledContext = LVM_NULL;
         ALOGV("\tEffectRelease: Freeing LVM Bundle memory\n");
-        LvmEffect_free(pContext);
+        LVM_DelInstanceHandle(&pContext->pBundledContext->hInstance);
         ALOGV("\tEffectRelease: Deleting LVM Bundle context %p\n", pContext->pBundledContext);
         if (pContext->pBundledContext->workBuffer != NULL) {
             free(pContext->pBundledContext->workBuffer);
@@ -449,11 +422,10 @@
 
 } /* end EffectRelease */
 
-extern "C" int EffectGetDescriptor(const effect_uuid_t *uuid,
-                                   effect_descriptor_t *pDescriptor) {
-    const effect_descriptor_t *desc = NULL;
+extern "C" int EffectGetDescriptor(const effect_uuid_t* uuid, effect_descriptor_t* pDescriptor) {
+    const effect_descriptor_t* desc = NULL;
 
-    if (pDescriptor == NULL || uuid == NULL){
+    if (pDescriptor == NULL || uuid == NULL) {
         ALOGV("EffectGetDescriptor() called with NULL pointer");
         return -EINVAL;
     }
@@ -469,7 +441,7 @@
     }
 
     if (desc == NULL) {
-        return  -EINVAL;
+        return -EINVAL;
     }
 
     *pDescriptor = *desc;
@@ -477,15 +449,15 @@
     return 0;
 } /* end EffectGetDescriptor */
 
-void LvmGlobalBundle_init(){
+void LvmGlobalBundle_init() {
     ALOGV("\tLvmGlobalBundle_init start");
-    for(int i=0; i<LVM_MAX_SESSIONS; i++){
-        GlobalSessionMemory[i].bBundledEffectsEnabled   = LVM_FALSE;
-        GlobalSessionMemory[i].bVolumeInstantiated      = LVM_FALSE;
-        GlobalSessionMemory[i].bEqualizerInstantiated   = LVM_FALSE;
-        GlobalSessionMemory[i].bBassInstantiated        = LVM_FALSE;
+    for (int i = 0; i < LVM_MAX_SESSIONS; i++) {
+        GlobalSessionMemory[i].bBundledEffectsEnabled = LVM_FALSE;
+        GlobalSessionMemory[i].bVolumeInstantiated = LVM_FALSE;
+        GlobalSessionMemory[i].bEqualizerInstantiated = LVM_FALSE;
+        GlobalSessionMemory[i].bBassInstantiated = LVM_FALSE;
         GlobalSessionMemory[i].bVirtualizerInstantiated = LVM_FALSE;
-        GlobalSessionMemory[i].pBundledContext          = LVM_NULL;
+        GlobalSessionMemory[i].pBundledContext = LVM_NULL;
 
         SessionIndex[i] = LVM_UNUSED_SESSION;
     }
@@ -504,203 +476,140 @@
 //
 //----------------------------------------------------------------------------
 
-int LvmBundle_init(EffectContext *pContext){
+int LvmBundle_init(EffectContext* pContext) {
     ALOGV("\tLvmBundle_init start");
 
-    pContext->config.inputCfg.accessMode                    = EFFECT_BUFFER_ACCESS_READ;
-    pContext->config.inputCfg.channels                      = AUDIO_CHANNEL_OUT_STEREO;
-    pContext->config.inputCfg.format                        = EFFECT_BUFFER_FORMAT;
-    pContext->config.inputCfg.samplingRate                  = 44100;
-    pContext->config.inputCfg.bufferProvider.getBuffer      = NULL;
-    pContext->config.inputCfg.bufferProvider.releaseBuffer  = NULL;
-    pContext->config.inputCfg.bufferProvider.cookie         = NULL;
-    pContext->config.inputCfg.mask                          = EFFECT_CONFIG_ALL;
-    pContext->config.outputCfg.accessMode                   = EFFECT_BUFFER_ACCESS_ACCUMULATE;
-    pContext->config.outputCfg.channels                     = AUDIO_CHANNEL_OUT_STEREO;
-    pContext->config.outputCfg.format                       = EFFECT_BUFFER_FORMAT;
-    pContext->config.outputCfg.samplingRate                 = 44100;
-    pContext->config.outputCfg.bufferProvider.getBuffer     = NULL;
+    pContext->config.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
+    pContext->config.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
+    pContext->config.inputCfg.format = EFFECT_BUFFER_FORMAT;
+    pContext->config.inputCfg.samplingRate = 44100;
+    pContext->config.inputCfg.bufferProvider.getBuffer = NULL;
+    pContext->config.inputCfg.bufferProvider.releaseBuffer = NULL;
+    pContext->config.inputCfg.bufferProvider.cookie = NULL;
+    pContext->config.inputCfg.mask = EFFECT_CONFIG_ALL;
+    pContext->config.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
+    pContext->config.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
+    pContext->config.outputCfg.format = EFFECT_BUFFER_FORMAT;
+    pContext->config.outputCfg.samplingRate = 44100;
+    pContext->config.outputCfg.bufferProvider.getBuffer = NULL;
     pContext->config.outputCfg.bufferProvider.releaseBuffer = NULL;
-    pContext->config.outputCfg.bufferProvider.cookie        = NULL;
-    pContext->config.outputCfg.mask                         = EFFECT_CONFIG_ALL;
+    pContext->config.outputCfg.bufferProvider.cookie = NULL;
+    pContext->config.outputCfg.mask = EFFECT_CONFIG_ALL;
 
     CHECK_ARG(pContext != NULL);
 
-    if (pContext->pBundledContext->hInstance != NULL){
+    if (pContext->pBundledContext->hInstance != NULL) {
         ALOGV("\tLvmBundle_init pContext->pBassBoost != NULL "
-                "-> Calling pContext->pBassBoost->free()");
-
-        LvmEffect_free(pContext);
+              "-> Calling pContext->pBassBoost->free()");
+        LVM_DelInstanceHandle(&pContext->pBundledContext->hInstance);
 
         ALOGV("\tLvmBundle_init pContext->pBassBoost != NULL "
-                "-> Called pContext->pBassBoost->free()");
+              "-> Called pContext->pBassBoost->free()");
     }
 
-    LVM_ReturnStatus_en     LvmStatus=LVM_SUCCESS;          /* Function call status */
-    LVM_ControlParams_t     params;                         /* Control Parameters */
-    LVM_InstParams_t        InstParams;                     /* Instance parameters */
-    LVM_EQNB_BandDef_t      BandDefs[MAX_NUM_BANDS];        /* Equaliser band definitions */
-    LVM_HeadroomParams_t    HeadroomParams;                 /* Headroom parameters */
-    LVM_HeadroomBandDef_t   HeadroomBandDef[LVM_HEADROOM_MAX_NBANDS];
-    LVM_MemTab_t            MemTab;                         /* Memory allocation table */
-    bool                    bMallocFailure = LVM_FALSE;
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
+    LVM_ControlParams_t params;                  /* Control Parameters */
+    LVM_InstParams_t InstParams;                 /* Instance parameters */
+    LVM_EQNB_BandDef_t BandDefs[MAX_NUM_BANDS];  /* Equaliser band definitions */
+    LVM_HeadroomParams_t HeadroomParams;         /* Headroom parameters */
+    LVM_HeadroomBandDef_t HeadroomBandDef[LVM_HEADROOM_MAX_NBANDS];
 
     /* Set the capabilities */
-    InstParams.BufferMode       = LVM_UNMANAGED_BUFFERS;
-    InstParams.MaxBlockSize     = MAX_CALL_SIZE;
-    InstParams.EQNB_NumBands    = MAX_NUM_BANDS;
-    InstParams.PSA_Included     = LVM_PSA_ON;
+    InstParams.BufferMode = LVM_UNMANAGED_BUFFERS;
+    InstParams.MaxBlockSize = MAX_CALL_SIZE;
+    InstParams.EQNB_NumBands = MAX_NUM_BANDS;
+    InstParams.PSA_Included = LVM_PSA_ON;
 
-    /* Allocate memory, forcing alignment */
-    LvmStatus = LVM_GetMemoryTable(LVM_NULL,
-                                  &MemTab,
-                                  &InstParams);
-
-    LVM_ERROR_CHECK(LvmStatus, "LVM_GetMemoryTable", "LvmBundle_init")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
-
-    ALOGV("\tCreateInstance Succesfully called LVM_GetMemoryTable\n");
-
-    /* Allocate memory */
-    for (int i=0; i<LVM_NR_MEMORY_REGIONS; i++){
-        if (MemTab.Region[i].Size != 0){
-            MemTab.Region[i].pBaseAddress = malloc(MemTab.Region[i].Size);
-
-            if (MemTab.Region[i].pBaseAddress == LVM_NULL){
-                ALOGV("\tLVM_ERROR :LvmBundle_init CreateInstance Failed to allocate %" PRIu32
-                        " bytes for region %u\n", MemTab.Region[i].Size, i );
-                bMallocFailure = LVM_TRUE;
-            }else{
-                ALOGV("\tLvmBundle_init CreateInstance allocated %" PRIu32
-                        " bytes for region %u at %p\n",
-                        MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
-            }
-        }
-    }
-
-    /* If one or more of the memory regions failed to allocate, free the regions that were
-     * succesfully allocated and return with an error
-     */
-    if(bMallocFailure == LVM_TRUE){
-        for (int i=0; i<LVM_NR_MEMORY_REGIONS; i++){
-            if (MemTab.Region[i].pBaseAddress == LVM_NULL){
-                ALOGV("\tLVM_ERROR :LvmBundle_init CreateInstance Failed to allocate %" PRIu32
-                        " bytes for region %u Not freeing\n", MemTab.Region[i].Size, i );
-            }else{
-                ALOGV("\tLVM_ERROR :LvmBundle_init CreateInstance Failed: but allocated %" PRIu32
-                     " bytes for region %u at %p- free\n",
-                     MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
-                free(MemTab.Region[i].pBaseAddress);
-            }
-        }
-        return -EINVAL;
-    }
-    ALOGV("\tLvmBundle_init CreateInstance Succesfully malloc'd memory\n");
-
-    /* Initialise */
-    pContext->pBundledContext->hInstance = LVM_NULL;
-
-    /* Init sets the instance handle */
-    LvmStatus = LVM_GetInstanceHandle(&pContext->pBundledContext->hInstance,
-                                      &MemTab,
-                                      &InstParams);
+    LvmStatus = LVM_GetInstanceHandle(&pContext->pBundledContext->hInstance, &InstParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetInstanceHandle", "LvmBundle_init")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    ALOGV("\tLvmBundle_init CreateInstance Succesfully called LVM_GetInstanceHandle\n");
+    ALOGV("\tLvmBundle_init CreateInstance Successfully called LVM_GetInstanceHandle\n");
 
     /* Set the initial process parameters */
     /* General parameters */
-    params.OperatingMode          = LVM_MODE_ON;
-    params.SampleRate             = LVM_FS_44100;
-    params.SourceFormat           = LVM_STEREO;
-    params.SpeakerType            = LVM_HEADPHONES;
+    params.OperatingMode = LVM_MODE_ON;
+    params.SampleRate = LVM_FS_44100;
+    params.SourceFormat = LVM_STEREO;
+    params.SpeakerType = LVM_HEADPHONES;
 
     pContext->pBundledContext->SampleRate = LVM_FS_44100;
-#ifdef SUPPORT_MC
     pContext->pBundledContext->ChMask = AUDIO_CHANNEL_OUT_STEREO;
-#endif
 
     /* Concert Sound parameters */
-    params.VirtualizerOperatingMode   = LVM_MODE_OFF;
-    params.VirtualizerType            = LVM_CONCERTSOUND;
-    params.VirtualizerReverbLevel     = 100;
-    params.CS_EffectLevel             = LVM_CS_EFFECT_NONE;
+    params.VirtualizerOperatingMode = LVM_MODE_OFF;
+    params.VirtualizerType = LVM_CONCERTSOUND;
+    params.VirtualizerReverbLevel = 100;
+    params.CS_EffectLevel = LVM_CS_EFFECT_NONE;
 
     /* N-Band Equaliser parameters */
-    params.EQNB_OperatingMode     = LVM_EQNB_OFF;
-    params.EQNB_NBands            = FIVEBAND_NUMBANDS;
-    params.pEQNB_BandDefinition   = &BandDefs[0];
+    params.EQNB_OperatingMode = LVM_EQNB_OFF;
+    params.EQNB_NBands = FIVEBAND_NUMBANDS;
+    params.pEQNB_BandDefinition = &BandDefs[0];
 
-    for (int i=0; i<FIVEBAND_NUMBANDS; i++)
-    {
+    for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
         BandDefs[i].Frequency = EQNB_5BandPresetsFrequencies[i];
-        BandDefs[i].QFactor   = EQNB_5BandPresetsQFactors[i];
-        BandDefs[i].Gain      = EQNB_5BandSoftPresets[i];
+        BandDefs[i].QFactor = EQNB_5BandPresetsQFactors[i];
+        BandDefs[i].Gain = EQNB_5BandSoftPresets[i];
     }
 
     /* Volume Control parameters */
-    params.VC_EffectLevel         = 0;
-    params.VC_Balance             = 0;
+    params.VC_EffectLevel = 0;
+    params.VC_Balance = 0;
 
     /* Treble Enhancement parameters */
-    params.TE_OperatingMode       = LVM_TE_OFF;
-    params.TE_EffectLevel         = 0;
+    params.TE_OperatingMode = LVM_TE_OFF;
+    params.TE_EffectLevel = 0;
 
     /* PSA Control parameters */
-    params.PSA_Enable             = LVM_PSA_OFF;
-    params.PSA_PeakDecayRate      = (LVM_PSA_DecaySpeed_en)0;
+    params.PSA_Enable = LVM_PSA_OFF;
+    params.PSA_PeakDecayRate = (LVM_PSA_DecaySpeed_en)0;
 
     /* Bass Enhancement parameters */
-    params.BE_OperatingMode       = LVM_BE_OFF;
-    params.BE_EffectLevel         = 0;
-    params.BE_CentreFreq          = LVM_BE_CENTRE_90Hz;
-    params.BE_HPF                 = LVM_BE_HPF_ON;
+    params.BE_OperatingMode = LVM_BE_OFF;
+    params.BE_EffectLevel = 0;
+    params.BE_CentreFreq = LVM_BE_CENTRE_90Hz;
+    params.BE_HPF = LVM_BE_HPF_ON;
 
     /* PSA Control parameters */
-    params.PSA_Enable             = LVM_PSA_OFF;
-    params.PSA_PeakDecayRate      = LVM_PSA_SPEED_MEDIUM;
+    params.PSA_Enable = LVM_PSA_OFF;
+    params.PSA_PeakDecayRate = LVM_PSA_SPEED_MEDIUM;
 
     /* TE Control parameters */
-    params.TE_OperatingMode       = LVM_TE_OFF;
-    params.TE_EffectLevel         = 0;
+    params.TE_OperatingMode = LVM_TE_OFF;
+    params.TE_EffectLevel = 0;
 
-#ifdef SUPPORT_MC
-    params.NrChannels             =
-        audio_channel_count_from_out_mask(AUDIO_CHANNEL_OUT_STEREO);
-    params.ChMask                 = AUDIO_CHANNEL_OUT_STEREO;
-#endif
+    params.NrChannels = audio_channel_count_from_out_mask(AUDIO_CHANNEL_OUT_STEREO);
+    params.ChMask = AUDIO_CHANNEL_OUT_STEREO;
     /* Activate the initial settings */
-    LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance,
-                                         &params);
+    LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &params);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmBundle_init")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    ALOGV("\tLvmBundle_init CreateInstance Succesfully called LVM_SetControlParameters\n");
+    ALOGV("\tLvmBundle_init CreateInstance Successfully called LVM_SetControlParameters\n");
 
     /* Set the headroom parameters */
-    HeadroomBandDef[0].Limit_Low          = 20;
-    HeadroomBandDef[0].Limit_High         = 4999;
-    HeadroomBandDef[0].Headroom_Offset    = 0;
-    HeadroomBandDef[1].Limit_Low          = 5000;
-    HeadroomBandDef[1].Limit_High         = 24000;
-    HeadroomBandDef[1].Headroom_Offset    = 0;
-    HeadroomParams.pHeadroomDefinition    = &HeadroomBandDef[0];
+    HeadroomBandDef[0].Limit_Low = 20;
+    HeadroomBandDef[0].Limit_High = 4999;
+    HeadroomBandDef[0].Headroom_Offset = 0;
+    HeadroomBandDef[1].Limit_Low = 5000;
+    HeadroomBandDef[1].Limit_High = 24000;
+    HeadroomBandDef[1].Headroom_Offset = 0;
+    HeadroomParams.pHeadroomDefinition = &HeadroomBandDef[0];
     HeadroomParams.Headroom_OperatingMode = LVM_HEADROOM_ON;
-    HeadroomParams.NHeadroomBands         = 2;
+    HeadroomParams.NHeadroomBands = 2;
 
-    LvmStatus = LVM_SetHeadroomParams(pContext->pBundledContext->hInstance,
-                                      &HeadroomParams);
+    LvmStatus = LVM_SetHeadroomParams(pContext->pBundledContext->hInstance, &HeadroomParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_SetHeadroomParams", "LvmBundle_init")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    ALOGV("\tLvmBundle_init CreateInstance Succesfully called LVM_SetHeadroomParams\n");
+    ALOGV("\tLvmBundle_init CreateInstance Successfully called LVM_SetHeadroomParams\n");
     ALOGV("\tLvmBundle_init End");
     return 0;
-}   /* end LvmBundle_init */
+} /* end LvmBundle_init */
 
 //----------------------------------------------------------------------------
 // LvmBundle_process()
@@ -719,25 +628,22 @@
 //  pOut:       pointer to updated stereo 16 bit output data
 //
 //----------------------------------------------------------------------------
-int LvmBundle_process(effect_buffer_t  *pIn,
-                      effect_buffer_t  *pOut,
-                      int              frameCount,
-                      EffectContext    *pContext){
-
-    LVM_ReturnStatus_en     LvmStatus = LVM_SUCCESS;                /* Function call status */
-    effect_buffer_t         *pOutTmp;
+int LvmBundle_process(effect_buffer_t* pIn, effect_buffer_t* pOut, int frameCount,
+                      EffectContext* pContext) {
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
+    effect_buffer_t* pOutTmp;
     const LVM_INT32 NrChannels =
-        audio_channel_count_from_out_mask(pContext->config.inputCfg.channels);
+            audio_channel_count_from_out_mask(pContext->config.inputCfg.channels);
 
-    if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE){
+    if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE) {
         pOutTmp = pOut;
-    } else if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE){
+    } else if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
         if (pContext->pBundledContext->frameCount != frameCount) {
             if (pContext->pBundledContext->workBuffer != NULL) {
                 free(pContext->pBundledContext->workBuffer);
             }
             pContext->pBundledContext->workBuffer =
-                    (effect_buffer_t *)calloc(frameCount, sizeof(effect_buffer_t) * NrChannels);
+                    (effect_buffer_t*)calloc(frameCount, sizeof(effect_buffer_t) * NrChannels);
             if (pContext->pBundledContext->workBuffer == NULL) {
                 return -ENOMEM;
             }
@@ -749,7 +655,6 @@
         return -EINVAL;
     }
 
-
     /* Process the samples */
     LvmStatus = LVM_Process(pContext->pBundledContext->hInstance, /* Instance handle */
                             pIn,                                  /* Input buffer */
@@ -757,16 +662,15 @@
                             (LVM_UINT16)frameCount,               /* Number of samples to read */
                             0);                                   /* Audio Time */
     LVM_ERROR_CHECK(LvmStatus, "LVM_Process", "LvmBundle_process")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-
-    if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE){
+    if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
         for (int i = 0; i < frameCount * NrChannels; i++) {
             pOut[i] = pOut[i] + pOutTmp[i];
         }
     }
     return 0;
-}    /* end LvmBundle_process */
+} /* end LvmBundle_process */
 
 //----------------------------------------------------------------------------
 // EqualizerUpdateActiveParams()
@@ -779,29 +683,28 @@
 // Outputs:
 //
 //----------------------------------------------------------------------------
-void EqualizerUpdateActiveParams(EffectContext *pContext) {
-    LVM_ControlParams_t     ActiveParams;              /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus=LVM_SUCCESS;     /* Function call status */
+void EqualizerUpdateActiveParams(EffectContext* pContext) {
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "EqualizerUpdateActiveParams")
-    //ALOGV("\tEqualizerUpdateActiveParams Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tEqualizerUpdateActiveParams just Got -> %d\n",
+    // ALOGV("\tEqualizerUpdateActiveParams Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tEqualizerUpdateActiveParams just Got -> %d\n",
     //          ActiveParams.pEQNB_BandDefinition[band].Gain);
 
     for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
-           ActiveParams.pEQNB_BandDefinition[i].Frequency = EQNB_5BandPresetsFrequencies[i];
-           ActiveParams.pEQNB_BandDefinition[i].QFactor   = EQNB_5BandPresetsQFactors[i];
-           ActiveParams.pEQNB_BandDefinition[i].Gain = pContext->pBundledContext->bandGaindB[i];
-       }
+        ActiveParams.pEQNB_BandDefinition[i].Frequency = EQNB_5BandPresetsFrequencies[i];
+        ActiveParams.pEQNB_BandDefinition[i].QFactor = EQNB_5BandPresetsQFactors[i];
+        ActiveParams.pEQNB_BandDefinition[i].Gain = pContext->pBundledContext->bandGaindB[i];
+    }
 
     /* Activate the initial settings */
     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "EqualizerUpdateActiveParams")
-    //ALOGV("\tEqualizerUpdateActiveParams just Set -> %d\n",
+    // ALOGV("\tEqualizerUpdateActiveParams just Set -> %d\n",
     //          ActiveParams.pEQNB_BandDefinition[band].Gain);
-
 }
 
 //----------------------------------------------------------------------------
@@ -816,19 +719,19 @@
 // Outputs:
 //
 //----------------------------------------------------------------------------
-void LvmEffect_limitLevel(EffectContext *pContext) {
-    LVM_ControlParams_t     ActiveParams;              /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus=LVM_SUCCESS;     /* Function call status */
+void LvmEffect_limitLevel(EffectContext* pContext) {
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "LvmEffect_limitLevel")
-    //ALOGV("\tLvmEffect_limitLevel Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tLvmEffect_limitLevel just Got -> %d\n",
+    // ALOGV("\tLvmEffect_limitLevel Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tLvmEffect_limitLevel just Got -> %d\n",
     //          ActiveParams.pEQNB_BandDefinition[band].Gain);
 
     int gainCorrection = 0;
-    //Count the energy contribution per band for EQ and BassBoost only if they are active.
+    // Count the energy contribution per band for EQ and BassBoost only if they are active.
     float energyContribution = 0;
     float energyCross = 0;
     float energyBassBoost = 0;
@@ -838,88 +741,83 @@
     bool bbEnabled = pContext->pBundledContext->bBassEnabled == LVM_TRUE;
     bool viEnabled = pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE;
 
-    //EQ contribution
+    // EQ contribution
     if (eqEnabled) {
         for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
-            float bandFactor = pContext->pBundledContext->bandGaindB[i]/15.0;
+            float bandFactor = pContext->pBundledContext->bandGaindB[i] / 15.0;
             float bandCoefficient = LimitLevel_bandEnergyCoefficient[i];
             float bandEnergy = bandFactor * bandCoefficient * bandCoefficient;
-            if (bandEnergy > 0)
-                energyContribution += bandEnergy;
+            if (bandEnergy > 0) energyContribution += bandEnergy;
         }
 
-        //cross EQ coefficients
+        // cross EQ coefficients
         float bandFactorSum = 0;
-        for (int i = 0; i < FIVEBAND_NUMBANDS-1; i++) {
-            float bandFactor1 = pContext->pBundledContext->bandGaindB[i]/15.0;
-            float bandFactor2 = pContext->pBundledContext->bandGaindB[i+1]/15.0;
+        for (int i = 0; i < FIVEBAND_NUMBANDS - 1; i++) {
+            float bandFactor1 = pContext->pBundledContext->bandGaindB[i] / 15.0;
+            float bandFactor2 = pContext->pBundledContext->bandGaindB[i + 1] / 15.0;
 
             if (bandFactor1 > 0 && bandFactor2 > 0) {
-                float crossEnergy = bandFactor1 * bandFactor2 *
-                        LimitLevel_bandEnergyCrossCoefficient[i];
+                float crossEnergy =
+                        bandFactor1 * bandFactor2 * LimitLevel_bandEnergyCrossCoefficient[i];
                 bandFactorSum += bandFactor1 * bandFactor2;
 
-                if (crossEnergy > 0)
-                    energyCross += crossEnergy;
+                if (crossEnergy > 0) energyCross += crossEnergy;
             }
         }
         bandFactorSum -= 1.0;
-        if (bandFactorSum > 0)
-          crossCorrection = bandFactorSum * 0.7;
+        if (bandFactorSum > 0) crossCorrection = bandFactorSum * 0.7;
     }
 
-    //BassBoost contribution
+    // BassBoost contribution
     if (bbEnabled) {
-        float boostFactor = (pContext->pBundledContext->BassStrengthSaved)/1000.0;
+        float boostFactor = (pContext->pBundledContext->BassStrengthSaved) / 1000.0;
         float boostCoefficient = LimitLevel_bassBoostEnergyCoefficient;
 
         energyContribution += boostFactor * boostCoefficient * boostCoefficient;
 
         if (eqEnabled) {
             for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
-                float bandFactor = pContext->pBundledContext->bandGaindB[i]/15.0;
+                float bandFactor = pContext->pBundledContext->bandGaindB[i] / 15.0;
                 float bandCrossCoefficient = LimitLevel_bassBoostEnergyCrossCoefficient[i];
-                float bandEnergy = boostFactor * bandFactor *
-                    bandCrossCoefficient;
-                if (bandEnergy > 0)
-                  energyBassBoost += bandEnergy;
+                float bandEnergy = boostFactor * bandFactor * bandCrossCoefficient;
+                if (bandEnergy > 0) energyBassBoost += bandEnergy;
             }
         }
     }
 
-    //Virtualizer contribution
+    // Virtualizer contribution
     if (viEnabled) {
-        energyContribution += LimitLevel_virtualizerContribution *
-                LimitLevel_virtualizerContribution;
+        energyContribution +=
+                LimitLevel_virtualizerContribution * LimitLevel_virtualizerContribution;
     }
 
-    double totalEnergyEstimation = sqrt(energyContribution + energyCross + energyBassBoost) -
-            crossCorrection;
+    double totalEnergyEstimation =
+            sqrt(energyContribution + energyCross + energyBassBoost) - crossCorrection;
     ALOGV(" TOTAL energy estimation: %0.2f dB", totalEnergyEstimation);
 
-    //roundoff
+    // roundoff
     int maxLevelRound = (int)(totalEnergyEstimation + 0.99);
     if (maxLevelRound + pContext->pBundledContext->volume > 0) {
         gainCorrection = maxLevelRound + pContext->pBundledContext->volume;
     }
 
-    ActiveParams.VC_EffectLevel  = pContext->pBundledContext->volume - gainCorrection;
+    ActiveParams.VC_EffectLevel = pContext->pBundledContext->volume - gainCorrection;
     if (ActiveParams.VC_EffectLevel < -96) {
         ActiveParams.VC_EffectLevel = -96;
     }
     ALOGV("\tVol:%d, GainCorrection: %d, Actual vol: %d", pContext->pBundledContext->volume,
-            gainCorrection, ActiveParams.VC_EffectLevel);
+          gainCorrection, ActiveParams.VC_EffectLevel);
 
     /* Activate the initial settings */
     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmEffect_limitLevel")
 
     ALOGV("LVM_SetControlParameters return:%d", (int)LvmStatus);
-    //ALOGV("\tLvmEffect_limitLevel just Set -> %d\n",
+    // ALOGV("\tLvmEffect_limitLevel just Set -> %d\n",
     //          ActiveParams.pEQNB_BandDefinition[band].Gain);
 
-    //ALOGV("\tLvmEffect_limitLevel just set (-96dB -> 0dB) -> %d\n",ActiveParams.VC_EffectLevel );
-    if (pContext->pBundledContext->firstVolume == LVM_TRUE){
+    // ALOGV("\tLvmEffect_limitLevel just set (-96dB -> 0dB) -> %d\n",ActiveParams.VC_EffectLevel );
+    if (pContext->pBundledContext->firstVolume == LVM_TRUE) {
         LvmStatus = LVM_SetVolumeNoSmoothing(pContext->pBundledContext->hInstance, &ActiveParams);
         LVM_ERROR_CHECK(LvmStatus, "LVM_SetVolumeNoSmoothing", "LvmBundle_process")
         ALOGV("\tLVM_VOLUME: Disabling Smoothing for first volume change to remove spikes/clicks");
@@ -939,42 +837,41 @@
 //
 //----------------------------------------------------------------------------
 
-int LvmEffect_enable(EffectContext *pContext){
-    //ALOGV("\tLvmEffect_enable start");
+int LvmEffect_enable(EffectContext* pContext) {
+    // ALOGV("\tLvmEffect_enable start");
 
-    LVM_ControlParams_t     ActiveParams;                           /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus = LVM_SUCCESS;                /* Function call status */
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
 
     /* Get the current settings */
-    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance,
-                                         &ActiveParams);
+    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "LvmEffect_enable")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
-    //ALOGV("\tLvmEffect_enable Succesfully called LVM_GetControlParameters\n");
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
+    // ALOGV("\tLvmEffect_enable Successfully called LVM_GetControlParameters\n");
 
-    if(pContext->EffectType == LVM_BASS_BOOST) {
+    if (pContext->EffectType == LVM_BASS_BOOST) {
         ALOGV("\tLvmEffect_enable : Enabling LVM_BASS_BOOST");
-        ActiveParams.BE_OperatingMode       = LVM_BE_ON;
+        ActiveParams.BE_OperatingMode = LVM_BE_ON;
     }
-    if(pContext->EffectType == LVM_VIRTUALIZER) {
+    if (pContext->EffectType == LVM_VIRTUALIZER) {
         ALOGV("\tLvmEffect_enable : Enabling LVM_VIRTUALIZER");
-        ActiveParams.VirtualizerOperatingMode   = LVM_MODE_ON;
+        ActiveParams.VirtualizerOperatingMode = LVM_MODE_ON;
     }
-    if(pContext->EffectType == LVM_EQUALIZER) {
+    if (pContext->EffectType == LVM_EQUALIZER) {
         ALOGV("\tLvmEffect_enable : Enabling LVM_EQUALIZER");
-        ActiveParams.EQNB_OperatingMode     = LVM_EQNB_ON;
+        ActiveParams.EQNB_OperatingMode = LVM_EQNB_ON;
     }
-    if(pContext->EffectType == LVM_VOLUME) {
+    if (pContext->EffectType == LVM_VOLUME) {
         ALOGV("\tLvmEffect_enable : Enabling LVM_VOLUME");
     }
 
     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmEffect_enable")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    //ALOGV("\tLvmEffect_enable Succesfully called LVM_SetControlParameters\n");
-    //ALOGV("\tLvmEffect_enable end");
+    // ALOGV("\tLvmEffect_enable Successfully called LVM_SetControlParameters\n");
+    // ALOGV("\tLvmEffect_enable end");
     LvmEffect_limitLevel(pContext);
     return 0;
 }
@@ -991,82 +888,45 @@
 //
 //----------------------------------------------------------------------------
 
-int LvmEffect_disable(EffectContext *pContext){
-    //ALOGV("\tLvmEffect_disable start");
+int LvmEffect_disable(EffectContext* pContext) {
+    // ALOGV("\tLvmEffect_disable start");
 
-    LVM_ControlParams_t     ActiveParams;                           /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus = LVM_SUCCESS;                /* Function call status */
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
     /* Get the current settings */
-    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance,
-                                         &ActiveParams);
+    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "LvmEffect_disable")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
-    //ALOGV("\tLvmEffect_disable Succesfully called LVM_GetControlParameters\n");
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
+    // ALOGV("\tLvmEffect_disable Successfully called LVM_GetControlParameters\n");
 
-    if(pContext->EffectType == LVM_BASS_BOOST) {
+    if (pContext->EffectType == LVM_BASS_BOOST) {
         ALOGV("\tLvmEffect_disable : Disabling LVM_BASS_BOOST");
-        ActiveParams.BE_OperatingMode       = LVM_BE_OFF;
+        ActiveParams.BE_OperatingMode = LVM_BE_OFF;
     }
-    if(pContext->EffectType == LVM_VIRTUALIZER) {
+    if (pContext->EffectType == LVM_VIRTUALIZER) {
         ALOGV("\tLvmEffect_disable : Disabling LVM_VIRTUALIZER");
-        ActiveParams.VirtualizerOperatingMode   = LVM_MODE_OFF;
+        ActiveParams.VirtualizerOperatingMode = LVM_MODE_OFF;
     }
-    if(pContext->EffectType == LVM_EQUALIZER) {
+    if (pContext->EffectType == LVM_EQUALIZER) {
         ALOGV("\tLvmEffect_disable : Disabling LVM_EQUALIZER");
-        ActiveParams.EQNB_OperatingMode     = LVM_EQNB_OFF;
+        ActiveParams.EQNB_OperatingMode = LVM_EQNB_OFF;
     }
-    if(pContext->EffectType == LVM_VOLUME) {
+    if (pContext->EffectType == LVM_VOLUME) {
         ALOGV("\tLvmEffect_disable : Disabling LVM_VOLUME");
     }
 
     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmEffect_disable")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    //ALOGV("\tLvmEffect_disable Succesfully called LVM_SetControlParameters\n");
-    //ALOGV("\tLvmEffect_disable end");
+    // ALOGV("\tLvmEffect_disable Successfully called LVM_SetControlParameters\n");
+    // ALOGV("\tLvmEffect_disable end");
     LvmEffect_limitLevel(pContext);
     return 0;
 }
 
 //----------------------------------------------------------------------------
-// LvmEffect_free()
-//----------------------------------------------------------------------------
-// Purpose: Free all memory associated with the Bundle.
-//
-// Inputs:
-//  pContext:   effect engine context
-//
-// Outputs:
-//
-//----------------------------------------------------------------------------
-
-void LvmEffect_free(EffectContext *pContext){
-    LVM_ReturnStatus_en     LvmStatus=LVM_SUCCESS;         /* Function call status */
-    LVM_MemTab_t            MemTab;
-
-    /* Free the algorithm memory */
-    LvmStatus = LVM_GetMemoryTable(pContext->pBundledContext->hInstance,
-                                   &MemTab,
-                                   LVM_NULL);
-
-    LVM_ERROR_CHECK(LvmStatus, "LVM_GetMemoryTable", "LvmEffect_free")
-
-    for (int i=0; i<LVM_NR_MEMORY_REGIONS; i++){
-        if (MemTab.Region[i].Size != 0){
-            if (MemTab.Region[i].pBaseAddress != NULL){
-                free(MemTab.Region[i].pBaseAddress);
-            }else{
-                ALOGV("\tLVM_ERROR : LvmEffect_free - trying to free with NULL pointer %" PRIu32
-                        " bytes for region %u at %p ERROR\n",
-                        MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
-            }
-        }
-    }
-}    /* end LvmEffect_free */
-
-//----------------------------------------------------------------------------
 // Effect_setConfig()
 //----------------------------------------------------------------------------
 // Purpose: Set input and output audio configuration.
@@ -1080,9 +940,9 @@
 //
 //----------------------------------------------------------------------------
 
-int Effect_setConfig(EffectContext *pContext, effect_config_t *pConfig){
-    LVM_Fs_en   SampleRate;
-    //ALOGV("\tEffect_setConfig start");
+int Effect_setConfig(EffectContext* pContext, effect_config_t* pConfig) {
+    LVM_Fs_en SampleRate;
+    // ALOGV("\tEffect_setConfig start");
 
     CHECK_ARG(pContext != NULL);
     CHECK_ARG(pConfig != NULL);
@@ -1090,107 +950,64 @@
     CHECK_ARG(pConfig->inputCfg.samplingRate == pConfig->outputCfg.samplingRate);
     CHECK_ARG(pConfig->inputCfg.channels == pConfig->outputCfg.channels);
     CHECK_ARG(pConfig->inputCfg.format == pConfig->outputCfg.format);
-#ifdef SUPPORT_MC
     CHECK_ARG(audio_channel_count_from_out_mask(pConfig->inputCfg.channels) <= LVM_MAX_CHANNELS);
-#else
-    CHECK_ARG(pConfig->inputCfg.channels == AUDIO_CHANNEL_OUT_STEREO);
-#endif
-    CHECK_ARG(pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE
-              || pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE);
+    CHECK_ARG(pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE ||
+              pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE);
     CHECK_ARG(pConfig->inputCfg.format == EFFECT_BUFFER_FORMAT);
     pContext->config = *pConfig;
     const LVM_INT16 NrChannels = audio_channel_count_from_out_mask(pConfig->inputCfg.channels);
 
-    switch (pConfig->inputCfg.samplingRate) {
-    case 8000:
-        SampleRate = LVM_FS_8000;
-        pContext->pBundledContext->SamplesPerSecond = 8000 * NrChannels;
-        break;
-    case 16000:
-        SampleRate = LVM_FS_16000;
-        pContext->pBundledContext->SamplesPerSecond = 16000 * NrChannels;
-        break;
-    case 22050:
-        SampleRate = LVM_FS_22050;
-        pContext->pBundledContext->SamplesPerSecond = 22050 * NrChannels;
-        break;
-    case 32000:
-        SampleRate = LVM_FS_32000;
-        pContext->pBundledContext->SamplesPerSecond = 32000 * NrChannels;
-        break;
-    case 44100:
-        SampleRate = LVM_FS_44100;
-        pContext->pBundledContext->SamplesPerSecond = 44100 * NrChannels;
-        break;
-    case 48000:
-        SampleRate = LVM_FS_48000;
-        pContext->pBundledContext->SamplesPerSecond = 48000 * NrChannels;
-        break;
-    case 88200:
-        SampleRate = LVM_FS_88200;
-        pContext->pBundledContext->SamplesPerSecond = 88200 * NrChannels;
-        break;
-    case 96000:
-        SampleRate = LVM_FS_96000;
-        pContext->pBundledContext->SamplesPerSecond = 96000 * NrChannels;
-        break;
-    case 176400:
-        SampleRate = LVM_FS_176400;
-        pContext->pBundledContext->SamplesPerSecond = 176400 * NrChannels;
-        break;
-    case 192000:
-        SampleRate = LVM_FS_192000;
-        pContext->pBundledContext->SamplesPerSecond = 192000 * NrChannels;
-        break;
-    default:
-        ALOGV("\tEffect_setConfig invalid sampling rate %d", pConfig->inputCfg.samplingRate);
+    SampleRate = lvmFsForSampleRate(pConfig->inputCfg.samplingRate);
+    if (SampleRate == LVM_FS_INVALID) {
+        ALOGV("Effect_setConfig invalid sampling rate %d", pConfig->inputCfg.samplingRate);
         return -EINVAL;
     }
+    pContext->pBundledContext->SamplesPerSecond = pConfig->inputCfg.samplingRate * NrChannels;
 
-#ifdef SUPPORT_MC
     if (pContext->pBundledContext->SampleRate != SampleRate ||
         pContext->pBundledContext->ChMask != pConfig->inputCfg.channels) {
-#else
-    if(pContext->pBundledContext->SampleRate != SampleRate){
-#endif
-
-        LVM_ControlParams_t     ActiveParams;
-        LVM_ReturnStatus_en     LvmStatus = LVM_SUCCESS;
+        LVM_ControlParams_t ActiveParams;
+        LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS;
 
         ALOGV("\tEffect_setConfig change sampling rate to %d", SampleRate);
 
         /* Get the current settings */
-        LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance,
-                                         &ActiveParams);
+        LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
         LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "Effect_setConfig")
-        if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+        if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
         ActiveParams.SampleRate = SampleRate;
 
-#ifdef SUPPORT_MC
         ActiveParams.NrChannels = NrChannels;
         ActiveParams.ChMask = pConfig->inputCfg.channels;
-#endif
+
+        if (NrChannels == 1) {
+            ActiveParams.SourceFormat = LVM_MONO;
+        } else if (NrChannels == 2) {
+            ActiveParams.SourceFormat = LVM_STEREO;
+        } else if (NrChannels > 2 && NrChannels <= LVM_MAX_CHANNELS) {
+            ActiveParams.SourceFormat = LVM_MULTICHANNEL;
+        } else {
+            return -EINVAL;
+        }
 
         LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
         LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "Effect_setConfig")
-        ALOGV("\tEffect_setConfig Succesfully called LVM_SetControlParameters\n");
+        ALOGV("\tEffect_setConfig Successfully called LVM_SetControlParameters\n");
         pContext->pBundledContext->SampleRate = SampleRate;
-#ifdef SUPPORT_MC
         pContext->pBundledContext->ChMask = pConfig->inputCfg.channels;
-#endif
 
         LvmEffect_limitLevel(pContext);
 
-    }else{
-        //ALOGV("\tEffect_setConfig keep sampling rate at %d", SampleRate);
+    } else {
+        // ALOGV("\tEffect_setConfig keep sampling rate at %d", SampleRate);
     }
 
-    //ALOGV("\tEffect_setConfig End....");
+    // ALOGV("\tEffect_setConfig End....");
     return 0;
-}   /* end Effect_setConfig */
+} /* end Effect_setConfig */
 
 //----------------------------------------------------------------------------
 // Effect_getConfig()
@@ -1206,10 +1023,9 @@
 //
 //----------------------------------------------------------------------------
 
-void Effect_getConfig(EffectContext *pContext, effect_config_t *pConfig)
-{
+void Effect_getConfig(EffectContext* pContext, effect_config_t* pConfig) {
     *pConfig = pContext->config;
-}   /* end Effect_getConfig */
+} /* end Effect_getConfig */
 
 //----------------------------------------------------------------------------
 // BassGetStrength()
@@ -1225,32 +1041,31 @@
 //
 //----------------------------------------------------------------------------
 
-uint32_t BassGetStrength(EffectContext *pContext){
-    //ALOGV("\tBassGetStrength() (0-1000) -> %d\n", pContext->pBundledContext->BassStrengthSaved);
+uint32_t BassGetStrength(EffectContext* pContext) {
+    // ALOGV("\tBassGetStrength() (0-1000) -> %d\n", pContext->pBundledContext->BassStrengthSaved);
 
-    LVM_ControlParams_t     ActiveParams;                           /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus = LVM_SUCCESS;                /* Function call status */
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
     /* Get the current settings */
-    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance,
-                                         &ActiveParams);
+    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "BassGetStrength")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    //ALOGV("\tBassGetStrength Succesfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tBassGetStrength Successfully returned from LVM_GetControlParameters\n");
 
     /* Check that the strength returned matches the strength that was set earlier */
-    if(ActiveParams.BE_EffectLevel !=
-       (LVM_INT16)((15*pContext->pBundledContext->BassStrengthSaved)/1000)){
+    if (ActiveParams.BE_EffectLevel !=
+        (LVM_INT16)((15 * pContext->pBundledContext->BassStrengthSaved) / 1000)) {
         ALOGV("\tLVM_ERROR : BassGetStrength module strength does not match savedStrength %d %d\n",
-                ActiveParams.BE_EffectLevel, pContext->pBundledContext->BassStrengthSaved);
+              ActiveParams.BE_EffectLevel, pContext->pBundledContext->BassStrengthSaved);
         return -EINVAL;
     }
 
-    //ALOGV("\tBassGetStrength() (0-15)   -> %d\n", ActiveParams.BE_EffectLevel );
-    //ALOGV("\tBassGetStrength() (saved)  -> %d\n", pContext->pBundledContext->BassStrengthSaved );
+    // ALOGV("\tBassGetStrength() (0-15)   -> %d\n", ActiveParams.BE_EffectLevel );
+    // ALOGV("\tBassGetStrength() (saved)  -> %d\n", pContext->pBundledContext->BassStrengthSaved );
     return pContext->pBundledContext->BassStrengthSaved;
-}    /* end BassGetStrength */
+} /* end BassGetStrength */
 
 //----------------------------------------------------------------------------
 // BassSetStrength()
@@ -1264,35 +1079,34 @@
 //
 //----------------------------------------------------------------------------
 
-void BassSetStrength(EffectContext *pContext, uint32_t strength){
-    //ALOGV("\tBassSetStrength(%d)", strength);
+void BassSetStrength(EffectContext* pContext, uint32_t strength) {
+    // ALOGV("\tBassSetStrength(%d)", strength);
 
     pContext->pBundledContext->BassStrengthSaved = (int)strength;
 
-    LVM_ControlParams_t     ActiveParams;              /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus=LVM_SUCCESS;     /* Function call status */
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
 
     /* Get the current settings */
-    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance,
-                                         &ActiveParams);
+    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "BassSetStrength")
-    //ALOGV("\tBassSetStrength Succesfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tBassSetStrength Successfully returned from LVM_GetControlParameters\n");
 
     /* Bass Enhancement parameters */
-    ActiveParams.BE_EffectLevel    = (LVM_INT16)((15*strength)/1000);
-    ActiveParams.BE_CentreFreq     = LVM_BE_CENTRE_90Hz;
+    ActiveParams.BE_EffectLevel = (LVM_INT16)((15 * strength) / 1000);
+    ActiveParams.BE_CentreFreq = LVM_BE_CENTRE_90Hz;
 
-    //ALOGV("\tBassSetStrength() (0-15)   -> %d\n", ActiveParams.BE_EffectLevel );
+    // ALOGV("\tBassSetStrength() (0-15)   -> %d\n", ActiveParams.BE_EffectLevel );
 
     /* Activate the initial settings */
     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "BassSetStrength")
-    //ALOGV("\tBassSetStrength Succesfully called LVM_SetControlParameters\n");
+    // ALOGV("\tBassSetStrength Successfully called LVM_SetControlParameters\n");
 
     LvmEffect_limitLevel(pContext);
-}    /* end BassSetStrength */
+} /* end BassSetStrength */
 
 //----------------------------------------------------------------------------
 // VirtualizerGetStrength()
@@ -1308,21 +1122,23 @@
 //
 //----------------------------------------------------------------------------
 
-uint32_t VirtualizerGetStrength(EffectContext *pContext){
-    //ALOGV("\tVirtualizerGetStrength (0-1000) -> %d\n",pContext->pBundledContext->VirtStrengthSaved);
+uint32_t VirtualizerGetStrength(EffectContext* pContext) {
+    // ALOGV("\tVirtualizerGetStrength (0-1000) ->
+    // %d\n",pContext->pBundledContext->VirtStrengthSaved);
 
-    LVM_ControlParams_t     ActiveParams;                           /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus = LVM_SUCCESS;                /* Function call status */
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
 
     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VirtualizerGetStrength")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    //ALOGV("\tVirtualizerGetStrength Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tVirtualizerGetStrength() (0-100)   -> %d\n", ActiveParams.VirtualizerReverbLevel*10);
+    // ALOGV("\tVirtualizerGetStrength Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tVirtualizerGetStrength() (0-100)   -> %d\n",
+    // ActiveParams.VirtualizerReverbLevel*10);
     return pContext->pBundledContext->VirtStrengthSaved;
-}    /* end getStrength */
+} /* end getStrength */
 
 //----------------------------------------------------------------------------
 // VirtualizerSetStrength()
@@ -1336,31 +1152,31 @@
 //
 //----------------------------------------------------------------------------
 
-void VirtualizerSetStrength(EffectContext *pContext, uint32_t strength){
-    //ALOGV("\tVirtualizerSetStrength(%d)", strength);
-    LVM_ControlParams_t     ActiveParams;              /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus=LVM_SUCCESS;     /* Function call status */
+void VirtualizerSetStrength(EffectContext* pContext, uint32_t strength) {
+    // ALOGV("\tVirtualizerSetStrength(%d)", strength);
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
 
     pContext->pBundledContext->VirtStrengthSaved = (int)strength;
 
     /* Get the current settings */
-    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance,&ActiveParams);
+    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VirtualizerSetStrength")
-    //ALOGV("\tVirtualizerSetStrength Succesfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tVirtualizerSetStrength Successfully returned from LVM_GetControlParameters\n");
 
     /* Virtualizer parameters */
-    ActiveParams.CS_EffectLevel             = (int)((strength*32767)/1000);
+    ActiveParams.CS_EffectLevel = (int)((strength * 32767) / 1000);
 
-    ALOGV("\tVirtualizerSetStrength() (0-1000)   -> %d\n", strength );
-    ALOGV("\tVirtualizerSetStrength() (0- 100)   -> %d\n", ActiveParams.CS_EffectLevel );
+    ALOGV("\tVirtualizerSetStrength() (0-1000)   -> %d\n", strength);
+    ALOGV("\tVirtualizerSetStrength() (0- 100)   -> %d\n", ActiveParams.CS_EffectLevel);
 
     /* Activate the initial settings */
     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VirtualizerSetStrength")
-    //ALOGV("\tVirtualizerSetStrength Succesfully called LVM_SetControlParameters\n\n");
+    // ALOGV("\tVirtualizerSetStrength Successfully called LVM_SetControlParameters\n\n");
     LvmEffect_limitLevel(pContext);
-}    /* end setStrength */
+} /* end setStrength */
 
 //----------------------------------------------------------------------------
 // VirtualizerIsDeviceSupported()
@@ -1376,14 +1192,14 @@
 //----------------------------------------------------------------------------
 int VirtualizerIsDeviceSupported(audio_devices_t deviceType) {
     switch (deviceType) {
-    case AUDIO_DEVICE_OUT_WIRED_HEADSET:
-    case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
-    case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
-    case AUDIO_DEVICE_OUT_USB_HEADSET:
-    // case AUDIO_DEVICE_OUT_USB_DEVICE:  // For USB testing of the virtualizer only.
-        return 0;
-    default :
-        return -EINVAL;
+        case AUDIO_DEVICE_OUT_WIRED_HEADSET:
+        case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
+        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
+        case AUDIO_DEVICE_OUT_USB_HEADSET:
+            // case AUDIO_DEVICE_OUT_USB_DEVICE:  // For USB testing of the virtualizer only.
+            return 0;
+        default:
+            return -EINVAL;
     }
 }
 
@@ -1401,9 +1217,9 @@
 //  0            if the configuration is supported
 //----------------------------------------------------------------------------
 int VirtualizerIsConfigurationSupported(audio_channel_mask_t channelMask,
-        audio_devices_t deviceType) {
+                                        audio_devices_t deviceType) {
     uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
-    if (channelCount < 1 || channelCount > FCC_2) { // TODO: update to 8 channels when supported.
+    if (channelCount < 1 || channelCount > FCC_2) {  // TODO: update to 8 channels when supported.
         return -EINVAL;
     }
     return VirtualizerIsDeviceSupported(deviceType);
@@ -1423,16 +1239,16 @@
 //  0            if the device is supported and the virtualization mode forced
 //
 //----------------------------------------------------------------------------
-int VirtualizerForceVirtualizationMode(EffectContext *pContext, audio_devices_t forcedDevice) {
+int VirtualizerForceVirtualizationMode(EffectContext* pContext, audio_devices_t forcedDevice) {
     ALOGV("VirtualizerForceVirtualizationMode: forcedDev=0x%x enabled=%d tmpDisabled=%d",
-            forcedDevice, pContext->pBundledContext->bVirtualizerEnabled,
-            pContext->pBundledContext->bVirtualizerTempDisabled);
+          forcedDevice, pContext->pBundledContext->bVirtualizerEnabled,
+          pContext->pBundledContext->bVirtualizerTempDisabled);
     int status = 0;
     bool useVirtualizer = false;
 
     if (VirtualizerIsDeviceSupported(forcedDevice) != 0) {
         if (forcedDevice != AUDIO_DEVICE_NONE) {
-            //forced device is not supported, make it behave as a reset of forced mode
+            // forced device is not supported, make it behave as a reset of forced mode
             forcedDevice = AUDIO_DEVICE_NONE;
             // but return an error
             status = -EINVAL;
@@ -1472,8 +1288,8 @@
     }
 
     ALOGV("\tafter VirtualizerForceVirtualizationMode: enabled=%d tmpDisabled=%d",
-            pContext->pBundledContext->bVirtualizerEnabled,
-            pContext->pBundledContext->bVirtualizerTempDisabled);
+          pContext->pBundledContext->bVirtualizerEnabled,
+          pContext->pBundledContext->bVirtualizerTempDisabled);
 
     return status;
 }
@@ -1499,23 +1315,24 @@
 //
 //----------------------------------------------------------------------------
 void VirtualizerGetSpeakerAngles(audio_channel_mask_t channelMask,
-        audio_devices_t deviceType __unused, int32_t *pSpeakerAngles) {
+                                 audio_devices_t /* deviceType __unused */,
+                                 int32_t* pSpeakerAngles) {
     // the channel count is guaranteed to be 1 or 2
     // the device is guaranteed to be of type headphone
     // this virtualizer is always using 2 virtual speakers at -90 and 90deg of azimuth, 0deg of
     // elevation but the return information is sized for nbChannels * 3, so we have to consider
     // the (false here) case of a single channel, and return only 3 fields.
     if (audio_channel_count_from_out_mask(channelMask) == 1) {
-        *pSpeakerAngles++ = (int32_t) AUDIO_CHANNEL_OUT_MONO; // same as FRONT_LEFT
-        *pSpeakerAngles++ = 0; // azimuth
-        *pSpeakerAngles = 0; // elevation
+        *pSpeakerAngles++ = (int32_t)AUDIO_CHANNEL_OUT_MONO;  // same as FRONT_LEFT
+        *pSpeakerAngles++ = 0;                                // azimuth
+        *pSpeakerAngles = 0;                                  // elevation
     } else {
-        *pSpeakerAngles++ = (int32_t) AUDIO_CHANNEL_OUT_FRONT_LEFT;
-        *pSpeakerAngles++ = -90; // azimuth
-        *pSpeakerAngles++ = 0;   // elevation
-        *pSpeakerAngles++ = (int32_t) AUDIO_CHANNEL_OUT_FRONT_RIGHT;
+        *pSpeakerAngles++ = (int32_t)AUDIO_CHANNEL_OUT_FRONT_LEFT;
+        *pSpeakerAngles++ = -90;  // azimuth
+        *pSpeakerAngles++ = 0;    // elevation
+        *pSpeakerAngles++ = (int32_t)AUDIO_CHANNEL_OUT_FRONT_RIGHT;
         *pSpeakerAngles++ = 90;  // azimuth
-        *pSpeakerAngles   = 0;   // elevation
+        *pSpeakerAngles = 0;     // elevation
     }
 }
 
@@ -1529,10 +1346,10 @@
 //   AUDIO_DEVICE_NONE if the effect is not virtualizing
 //   or the device type if the effect is virtualizing
 //----------------------------------------------------------------------------
-audio_devices_t VirtualizerGetVirtualizationMode(EffectContext *pContext) {
+audio_devices_t VirtualizerGetVirtualizationMode(EffectContext* pContext) {
     audio_devices_t virtDevice = AUDIO_DEVICE_NONE;
-    if ((pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE)
-            && (pContext->pBundledContext->bVirtualizerTempDisabled == LVM_FALSE)) {
+    if ((pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) &&
+        (pContext->pBundledContext->bVirtualizerTempDisabled == LVM_FALSE)) {
         if (pContext->pBundledContext->nVirtualizerForcedDevice != AUDIO_DEVICE_NONE) {
             // virtualization mode is forced, return that device
             virtDevice = pContext->pBundledContext->nVirtualizerForcedDevice;
@@ -1557,8 +1374,8 @@
 // Outputs:
 //
 //----------------------------------------------------------------------------
-int32_t EqualizerGetBandLevel(EffectContext *pContext, int32_t band){
-    //ALOGV("\tEqualizerGetBandLevel -> %d\n", pContext->pBundledContext->bandGaindB[band] );
+int32_t EqualizerGetBandLevel(EffectContext* pContext, int32_t band) {
+    // ALOGV("\tEqualizerGetBandLevel -> %d\n", pContext->pBundledContext->bandGaindB[band] );
     return pContext->pBundledContext->bandGaindB[band] * 100;
 }
 
@@ -1576,14 +1393,14 @@
 // Outputs:
 //
 //---------------------------------------------------------------------------
-void EqualizerSetBandLevel(EffectContext *pContext, int band, short Gain){
+void EqualizerSetBandLevel(EffectContext* pContext, int band, short Gain) {
     int gainRounded;
-    if(Gain > 0){
-        gainRounded = (int)((Gain+50)/100);
-    }else{
-        gainRounded = (int)((Gain-50)/100);
+    if (Gain > 0) {
+        gainRounded = (int)((Gain + 50) / 100);
+    } else {
+        gainRounded = (int)((Gain - 50) / 100);
     }
-    //ALOGV("\tEqualizerSetBandLevel(%d)->(%d)", Gain, gainRounded);
+    // ALOGV("\tEqualizerSetBandLevel(%d)->(%d)", Gain, gainRounded);
     pContext->pBundledContext->bandGaindB[band] = gainRounded;
     pContext->pBundledContext->CurPreset = PRESET_CUSTOM;
 
@@ -1603,23 +1420,22 @@
 // Outputs:
 //
 //----------------------------------------------------------------------------
-int32_t EqualizerGetCentreFrequency(EffectContext *pContext, int32_t band){
-    int32_t Frequency =0;
+int32_t EqualizerGetCentreFrequency(EffectContext* pContext, int32_t band) {
+    int32_t Frequency = 0;
 
-    LVM_ControlParams_t     ActiveParams;                           /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus = LVM_SUCCESS;                /* Function call status */
-    LVM_EQNB_BandDef_t      *BandDef;
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
+    LVM_EQNB_BandDef_t* BandDef;
     /* Get the current settings */
-    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance,
-                                         &ActiveParams);
+    LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "EqualizerGetCentreFrequency")
 
-    BandDef   = ActiveParams.pEQNB_BandDefinition;
-    Frequency = (int32_t)BandDef[band].Frequency*1000;     // Convert to millibels
+    BandDef = ActiveParams.pEQNB_BandDefinition;
+    Frequency = (int32_t)BandDef[band].Frequency * 1000;  // Convert to millibels
 
-    //ALOGV("\tEqualizerGetCentreFrequency -> %d\n", Frequency );
-    //ALOGV("\tEqualizerGetCentreFrequency Succesfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tEqualizerGetCentreFrequency -> %d\n", Frequency );
+    // ALOGV("\tEqualizerGetCentreFrequency Successfully returned from LVM_GetControlParameters\n");
     return Frequency;
 }
 
@@ -1641,10 +1457,10 @@
 //  pLow:       lower band range
 //  pLow:       upper band range
 //----------------------------------------------------------------------------
-int32_t EqualizerGetBandFreqRange(EffectContext *pContext __unused, int32_t band, uint32_t *pLow,
-                                  uint32_t *pHi){
+int32_t EqualizerGetBandFreqRange(EffectContext* /* pContext __unused */, int32_t band,
+                                  uint32_t* pLow, uint32_t* pHi) {
     *pLow = bandFreqRange[band][0];
-    *pHi  = bandFreqRange[band][1];
+    *pHi = bandFreqRange[band][1];
     return 0;
 }
 
@@ -1665,16 +1481,16 @@
 //  pLow:       lower band range
 //  pLow:       upper band range
 //----------------------------------------------------------------------------
-int32_t EqualizerGetBand(EffectContext *pContext __unused, uint32_t targetFreq){
+int32_t EqualizerGetBand(EffectContext* /* pContext __unused */, uint32_t targetFreq) {
     int band = 0;
 
-    if(targetFreq < bandFreqRange[0][0]){
+    if (targetFreq < bandFreqRange[0][0]) {
         return -EINVAL;
-    }else if(targetFreq == bandFreqRange[0][0]){
+    } else if (targetFreq == bandFreqRange[0][0]) {
         return 0;
     }
-    for(int i=0; i<FIVEBAND_NUMBANDS;i++){
-        if((targetFreq > bandFreqRange[i][0])&&(targetFreq <= bandFreqRange[i][1])){
+    for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
+        if ((targetFreq > bandFreqRange[i][0]) && (targetFreq <= bandFreqRange[i][1])) {
             band = i;
         }
     }
@@ -1694,7 +1510,7 @@
 //  pContext:    effect engine context
 //
 //----------------------------------------------------------------------------
-int32_t EqualizerGetPreset(EffectContext *pContext){
+int32_t EqualizerGetPreset(EffectContext* pContext) {
     return pContext->pBundledContext->CurPreset;
 }
 
@@ -1711,14 +1527,12 @@
 //  preset       The preset ID.
 //
 //----------------------------------------------------------------------------
-void EqualizerSetPreset(EffectContext *pContext, int preset){
-
-    //ALOGV("\tEqualizerSetPreset(%d)", preset);
+void EqualizerSetPreset(EffectContext* pContext, int preset) {
+    // ALOGV("\tEqualizerSetPreset(%d)", preset);
     pContext->pBundledContext->CurPreset = preset;
 
-    //ActiveParams.pEQNB_BandDefinition = &BandDefs[0];
-    for (int i=0; i<FIVEBAND_NUMBANDS; i++)
-    {
+    // ActiveParams.pEQNB_BandDefinition = &BandDefs[0];
+    for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
         pContext->pBundledContext->bandGaindB[i] =
                 EQNB_5BandSoftPresets[i + preset * FIVEBAND_NUMBANDS];
     }
@@ -1726,11 +1540,11 @@
     EqualizerUpdateActiveParams(pContext);
     LvmEffect_limitLevel(pContext);
 
-    //ALOGV("\tEqualizerSetPreset Succesfully called LVM_SetControlParameters\n");
+    // ALOGV("\tEqualizerSetPreset Successfully called LVM_SetControlParameters\n");
     return;
 }
 
-int32_t EqualizerGetNumPresets(){
+int32_t EqualizerGetNumPresets() {
     return sizeof(gEqualizerPresets) / sizeof(PresetConfig);
 }
 
@@ -1745,14 +1559,14 @@
 // preset       The preset ID. Must be less than number of presets.
 //
 //-------------------------------------------------------------------------
-const char * EqualizerGetPresetName(int32_t preset){
-    //ALOGV("\tEqualizerGetPresetName start(%d)", preset);
+const char* EqualizerGetPresetName(int32_t preset) {
+    // ALOGV("\tEqualizerGetPresetName start(%d)", preset);
     if (preset == PRESET_CUSTOM) {
         return "Custom";
     } else {
         return gEqualizerPresets[preset].name;
     }
-    //ALOGV("\tEqualizerGetPresetName end(%d)", preset);
+    // ALOGV("\tEqualizerGetPresetName end(%d)", preset);
     return 0;
 }
 
@@ -1767,8 +1581,7 @@
 //
 //----------------------------------------------------------------------------
 
-int VolumeSetVolumeLevel(EffectContext *pContext, int16_t level){
-
+int VolumeSetVolumeLevel(EffectContext* pContext, int16_t level) {
     if (level > 0 || level < -9600) {
         return -EINVAL;
     }
@@ -1782,7 +1595,7 @@
     LvmEffect_limitLevel(pContext);
 
     return 0;
-}    /* end VolumeSetVolumeLevel */
+} /* end VolumeSetVolumeLevel */
 
 //----------------------------------------------------------------------------
 // VolumeGetVolumeLevel()
@@ -1794,15 +1607,14 @@
 //
 //----------------------------------------------------------------------------
 
-int VolumeGetVolumeLevel(EffectContext *pContext, int16_t *level){
-
+int VolumeGetVolumeLevel(EffectContext* pContext, int16_t* level) {
     if (pContext->pBundledContext->bMuteEnabled == LVM_TRUE) {
         *level = pContext->pBundledContext->levelSaved * 100;
     } else {
         *level = pContext->pBundledContext->volume * 100;
     }
     return 0;
-}    /* end VolumeGetVolumeLevel */
+} /* end VolumeGetVolumeLevel */
 
 //----------------------------------------------------------------------------
 // VolumeSetMute()
@@ -1815,23 +1627,23 @@
 //
 //----------------------------------------------------------------------------
 
-int32_t VolumeSetMute(EffectContext *pContext, uint32_t mute){
-    //ALOGV("\tVolumeSetMute start(%d)", mute);
+int32_t VolumeSetMute(EffectContext* pContext, uint32_t mute) {
+    // ALOGV("\tVolumeSetMute start(%d)", mute);
 
     pContext->pBundledContext->bMuteEnabled = mute;
 
     /* Set appropriate volume level */
-    if(pContext->pBundledContext->bMuteEnabled == LVM_TRUE){
+    if (pContext->pBundledContext->bMuteEnabled == LVM_TRUE) {
         pContext->pBundledContext->levelSaved = pContext->pBundledContext->volume;
         pContext->pBundledContext->volume = -96;
-    }else{
+    } else {
         pContext->pBundledContext->volume = pContext->pBundledContext->levelSaved;
     }
 
     LvmEffect_limitLevel(pContext);
 
     return 0;
-}    /* end setMute */
+} /* end setMute */
 
 //----------------------------------------------------------------------------
 // VolumeGetMute()
@@ -1845,26 +1657,25 @@
 //  mute:       enable/disable flag
 //----------------------------------------------------------------------------
 
-int32_t VolumeGetMute(EffectContext *pContext, uint32_t *mute){
-    //ALOGV("\tVolumeGetMute start");
-    if((pContext->pBundledContext->bMuteEnabled == LVM_FALSE)||
-       (pContext->pBundledContext->bMuteEnabled == LVM_TRUE)){
+int32_t VolumeGetMute(EffectContext* pContext, uint32_t* mute) {
+    // ALOGV("\tVolumeGetMute start");
+    if ((pContext->pBundledContext->bMuteEnabled == LVM_FALSE) ||
+        (pContext->pBundledContext->bMuteEnabled == LVM_TRUE)) {
         *mute = pContext->pBundledContext->bMuteEnabled;
         return 0;
-    }else{
+    } else {
         ALOGV("\tLVM_ERROR : VolumeGetMute read an invalid value from context %d",
               pContext->pBundledContext->bMuteEnabled);
         return -EINVAL;
     }
-    //ALOGV("\tVolumeGetMute end");
-}    /* end getMute */
+    // ALOGV("\tVolumeGetMute end");
+} /* end getMute */
 
-int16_t VolumeConvertStereoPosition(int16_t position){
+int16_t VolumeConvertStereoPosition(int16_t position) {
     int16_t convertedPosition = 0;
 
-    convertedPosition = (int16_t)(((float)position/1000)*96);
+    convertedPosition = (int16_t)(((float)position / 1000) * 96);
     return convertedPosition;
-
 }
 
 //----------------------------------------------------------------------------
@@ -1879,55 +1690,55 @@
 // Outputs:
 //----------------------------------------------------------------------------
 
-int VolumeSetStereoPosition(EffectContext *pContext, int16_t position){
-
-    LVM_ControlParams_t     ActiveParams;              /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus=LVM_SUCCESS;     /* Function call status */
-    LVM_INT16               Balance = 0;
+int VolumeSetStereoPosition(EffectContext* pContext, int16_t position) {
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
+    LVM_INT16 Balance = 0;
 
     pContext->pBundledContext->positionSaved = position;
     Balance = VolumeConvertStereoPosition(pContext->pBundledContext->positionSaved);
 
-    //ALOGV("\tVolumeSetStereoPosition start pContext->pBundledContext->positionSaved = %d",
-    //pContext->pBundledContext->positionSaved);
+    // ALOGV("\tVolumeSetStereoPosition start pContext->pBundledContext->positionSaved = %d",
+    // pContext->pBundledContext->positionSaved);
 
-    if(pContext->pBundledContext->bStereoPositionEnabled == LVM_TRUE){
-
-        //ALOGV("\tVolumeSetStereoPosition Position to be set is %d %d\n", position, Balance);
+    if (pContext->pBundledContext->bStereoPositionEnabled == LVM_TRUE) {
+        // ALOGV("\tVolumeSetStereoPosition Position to be set is %d %d\n", position, Balance);
         pContext->pBundledContext->positionSaved = position;
         /* Get the current settings */
         LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
         LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeSetStereoPosition")
-        if(LvmStatus != LVM_SUCCESS) return -EINVAL;
-        //ALOGV("\tVolumeSetStereoPosition Succesfully returned from LVM_GetControlParameters got:"
+        if (LvmStatus != LVM_SUCCESS) return -EINVAL;
+        // ALOGV("\tVolumeSetStereoPosition Successfully returned from LVM_GetControlParameters
+        // got:"
         //     " %d\n", ActiveParams.VC_Balance);
 
         /* Volume parameters */
-        ActiveParams.VC_Balance  = Balance;
-        //ALOGV("\tVolumeSetStereoPosition() (-96dB -> +96dB)   -> %d\n", ActiveParams.VC_Balance );
+        ActiveParams.VC_Balance = Balance;
+        // ALOGV("\tVolumeSetStereoPosition() (-96dB -> +96dB)   -> %d\n", ActiveParams.VC_Balance
+        // );
 
         /* Activate the initial settings */
         LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
         LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VolumeSetStereoPosition")
-        if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+        if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-        //ALOGV("\tVolumeSetStereoPosition Succesfully called LVM_SetControlParameters\n");
+        // ALOGV("\tVolumeSetStereoPosition Successfully called LVM_SetControlParameters\n");
 
         /* Get the current settings */
         LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
         LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeSetStereoPosition")
-        if(LvmStatus != LVM_SUCCESS) return -EINVAL;
-        //ALOGV("\tVolumeSetStereoPosition Succesfully returned from LVM_GetControlParameters got: "
+        if (LvmStatus != LVM_SUCCESS) return -EINVAL;
+        // ALOGV("\tVolumeSetStereoPosition Successfully returned from LVM_GetControlParameters got:
+        // "
         //     "%d\n", ActiveParams.VC_Balance);
+    } else {
+        // ALOGV("\tVolumeSetStereoPosition Position attempting to set, but not enabled %d %d\n",
+        // position, Balance);
     }
-    else{
-        //ALOGV("\tVolumeSetStereoPosition Position attempting to set, but not enabled %d %d\n",
-        //position, Balance);
-    }
-    //ALOGV("\tVolumeSetStereoPosition end pContext->pBundledContext->positionSaved = %d\n",
-    //pContext->pBundledContext->positionSaved);
+    // ALOGV("\tVolumeSetStereoPosition end pContext->pBundledContext->positionSaved = %d\n",
+    // pContext->pBundledContext->positionSaved);
     return 0;
-}    /* end VolumeSetStereoPosition */
+} /* end VolumeSetStereoPosition */
 
 //----------------------------------------------------------------------------
 // VolumeGetStereoPosition()
@@ -1941,35 +1752,35 @@
 //  position:       stereo position
 //----------------------------------------------------------------------------
 
-int32_t VolumeGetStereoPosition(EffectContext *pContext, int16_t *position){
-    //ALOGV("\tVolumeGetStereoPosition start");
+int32_t VolumeGetStereoPosition(EffectContext* pContext, int16_t* position) {
+    // ALOGV("\tVolumeGetStereoPosition start");
 
-    LVM_ControlParams_t     ActiveParams;                           /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus = LVM_SUCCESS;                /* Function call status */
-    LVM_INT16               balance;
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
+    LVM_INT16 balance;
 
-    //ALOGV("\tVolumeGetStereoPosition start pContext->pBundledContext->positionSaved = %d",
-    //pContext->pBundledContext->positionSaved);
+    // ALOGV("\tVolumeGetStereoPosition start pContext->pBundledContext->positionSaved = %d",
+    // pContext->pBundledContext->positionSaved);
 
     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeGetStereoPosition")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    //ALOGV("\tVolumeGetStereoPosition -> %d\n", ActiveParams.VC_Balance);
-    //ALOGV("\tVolumeGetStereoPosition Succesfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tVolumeGetStereoPosition -> %d\n", ActiveParams.VC_Balance);
+    // ALOGV("\tVolumeGetStereoPosition Successfully returned from LVM_GetControlParameters\n");
 
     balance = VolumeConvertStereoPosition(pContext->pBundledContext->positionSaved);
 
-    if(pContext->pBundledContext->bStereoPositionEnabled == LVM_TRUE){
-        if(balance != ActiveParams.VC_Balance){
+    if (pContext->pBundledContext->bStereoPositionEnabled == LVM_TRUE) {
+        if (balance != ActiveParams.VC_Balance) {
             return -EINVAL;
         }
     }
-    *position = (LVM_INT16)pContext->pBundledContext->positionSaved;     // Convert dB to millibels
-    //ALOGV("\tVolumeGetStereoPosition end returning pContext->pBundledContext->positionSaved =%d\n",
-    //pContext->pBundledContext->positionSaved);
+    *position = (LVM_INT16)pContext->pBundledContext->positionSaved;  // Convert dB to millibels
+    // ALOGV("\tVolumeGetStereoPosition end returning pContext->pBundledContext->positionSaved
+    // =%d\n", pContext->pBundledContext->positionSaved);
     return 0;
-}    /* end VolumeGetStereoPosition */
+} /* end VolumeGetStereoPosition */
 
 //----------------------------------------------------------------------------
 // VolumeEnableStereoPosition()
@@ -1982,40 +1793,40 @@
 //
 //----------------------------------------------------------------------------
 
-int32_t VolumeEnableStereoPosition(EffectContext *pContext, uint32_t enabled){
-    //ALOGV("\tVolumeEnableStereoPosition start()");
+int32_t VolumeEnableStereoPosition(EffectContext* pContext, uint32_t enabled) {
+    // ALOGV("\tVolumeEnableStereoPosition start()");
 
     pContext->pBundledContext->bStereoPositionEnabled = enabled;
 
-    LVM_ControlParams_t     ActiveParams;              /* Current control Parameters */
-    LVM_ReturnStatus_en     LvmStatus=LVM_SUCCESS;     /* Function call status */
+    LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+    LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeEnableStereoPosition")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    //ALOGV("\tVolumeEnableStereoPosition Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tVolumeEnableStereoPosition to %d, position was %d\n",
+    // ALOGV("\tVolumeEnableStereoPosition Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tVolumeEnableStereoPosition to %d, position was %d\n",
     //     enabled, ActiveParams.VC_Balance );
 
     /* Set appropriate stereo position */
-    if(pContext->pBundledContext->bStereoPositionEnabled == LVM_FALSE){
+    if (pContext->pBundledContext->bStereoPositionEnabled == LVM_FALSE) {
         ActiveParams.VC_Balance = 0;
-    }else{
-        ActiveParams.VC_Balance  =
-                            VolumeConvertStereoPosition(pContext->pBundledContext->positionSaved);
+    } else {
+        ActiveParams.VC_Balance =
+                VolumeConvertStereoPosition(pContext->pBundledContext->positionSaved);
     }
 
     /* Activate the initial settings */
     LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VolumeEnableStereoPosition")
-    if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
-    //ALOGV("\tVolumeEnableStereoPosition Succesfully called LVM_SetControlParameters\n");
-    //ALOGV("\tVolumeEnableStereoPosition end()\n");
+    // ALOGV("\tVolumeEnableStereoPosition Successfully called LVM_SetControlParameters\n");
+    // ALOGV("\tVolumeEnableStereoPosition end()\n");
     return 0;
-}    /* end VolumeEnableStereoPosition */
+} /* end VolumeEnableStereoPosition */
 
 //----------------------------------------------------------------------------
 // BassBoost_getParameter()
@@ -2038,13 +1849,10 @@
 //
 //----------------------------------------------------------------------------
 
-int BassBoost_getParameter(EffectContext *pContext,
-                           uint32_t       paramSize,
-                           void          *pParam,
-                           uint32_t      *pValueSize,
-                           void          *pValue) {
+int BassBoost_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                           uint32_t* pValueSize, void* pValue) {
     int status = 0;
-    int32_t *params = (int32_t *)pParam;
+    int32_t* params = (int32_t*)pParam;
 
     ALOGVV("%s start", __func__);
 
@@ -2055,28 +1863,27 @@
     switch (params[0]) {
         case BASSBOOST_PARAM_STRENGTH_SUPPORTED:
             if (*pValueSize != sizeof(uint32_t)) {  // legacy: check equality here.
-                ALOGV("%s BASSBOOST_PARAM_STRENGTH_SUPPORTED invalid *pValueSize %u",
-                        __func__, *pValueSize);
+                ALOGV("%s BASSBOOST_PARAM_STRENGTH_SUPPORTED invalid *pValueSize %u", __func__,
+                      *pValueSize);
                 status = -EINVAL;
                 break;
             }
             // no need to set *pValueSize
 
-            *(uint32_t *)pValue = 1;
-            ALOGVV("%s BASSBOOST_PARAM_STRENGTH_SUPPORTED %u", __func__, *(uint32_t *)pValue);
+            *(uint32_t*)pValue = 1;
+            ALOGVV("%s BASSBOOST_PARAM_STRENGTH_SUPPORTED %u", __func__, *(uint32_t*)pValue);
             break;
 
         case BASSBOOST_PARAM_STRENGTH:
             if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
-                ALOGV("%s BASSBOOST_PARAM_STRENGTH invalid *pValueSize %u",
-                        __func__, *pValueSize);
+                ALOGV("%s BASSBOOST_PARAM_STRENGTH invalid *pValueSize %u", __func__, *pValueSize);
                 status = -EINVAL;
                 break;
             }
             // no need to set *pValueSize
 
-            *(int16_t *)pValue = BassGetStrength(pContext);
-            ALOGVV("%s BASSBOOST_PARAM_STRENGTH %d", __func__, *(int16_t *)pValue);
+            *(int16_t*)pValue = BassGetStrength(pContext);
+            ALOGVV("%s BASSBOOST_PARAM_STRENGTH %d", __func__, *(int16_t*)pValue);
             break;
 
         default:
@@ -2104,13 +1911,10 @@
 //
 //----------------------------------------------------------------------------
 
-int BassBoost_setParameter(EffectContext *pContext,
-                           uint32_t       paramSize,
-                           void          *pParam,
-                           uint32_t       valueSize,
-                           void          *pValue) {
+int BassBoost_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                           uint32_t valueSize, void* pValue) {
     int status = 0;
-    int32_t *params = (int32_t *)pParam;
+    int32_t* params = (int32_t*)pParam;
 
     ALOGVV("%s start", __func__);
 
@@ -2126,7 +1930,7 @@
                 break;
             }
 
-            const int16_t strength = *(int16_t *)pValue;
+            const int16_t strength = *(int16_t*)pValue;
             ALOGVV("%s BASSBOOST_PARAM_STRENGTH %d", __func__, strength);
             ALOGVV("%s BASSBOOST_PARAM_STRENGTH Calling BassSetStrength", __func__);
             BassSetStrength(pContext, (int32_t)strength);
@@ -2164,13 +1968,10 @@
 //
 //----------------------------------------------------------------------------
 
-int Virtualizer_getParameter(EffectContext *pContext,
-                             uint32_t       paramSize,
-                             void          *pParam,
-                             uint32_t      *pValueSize,
-                             void          *pValue) {
+int Virtualizer_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                             uint32_t* pValueSize, void* pValue) {
     int status = 0;
-    int32_t *params = (int32_t *)pParam;
+    int32_t* params = (int32_t*)pParam;
 
     ALOGVV("%s start", __func__);
 
@@ -2180,47 +1981,47 @@
     }
     switch (params[0]) {
         case VIRTUALIZER_PARAM_STRENGTH_SUPPORTED:
-            if (*pValueSize != sizeof(uint32_t)) { // legacy: check equality here.
-                ALOGV("%s VIRTUALIZER_PARAM_STRENGTH_SUPPORTED invalid *pValueSize %u",
-                        __func__, *pValueSize);
+            if (*pValueSize != sizeof(uint32_t)) {  // legacy: check equality here.
+                ALOGV("%s VIRTUALIZER_PARAM_STRENGTH_SUPPORTED invalid *pValueSize %u", __func__,
+                      *pValueSize);
                 status = -EINVAL;
                 break;
             }
             // no need to set *pValueSize
 
-            *(uint32_t *)pValue = 1;
-            ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH_SUPPORTED %d", __func__, *(uint32_t *)pValue);
+            *(uint32_t*)pValue = 1;
+            ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH_SUPPORTED %d", __func__, *(uint32_t*)pValue);
             break;
 
         case VIRTUALIZER_PARAM_STRENGTH:
-            if (*pValueSize != sizeof(int16_t)) { // legacy: check equality here.
-                ALOGV("%s VIRTUALIZER_PARAM_STRENGTH invalid *pValueSize %u",
-                        __func__, *pValueSize);
+            if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
+                ALOGV("%s VIRTUALIZER_PARAM_STRENGTH invalid *pValueSize %u", __func__,
+                      *pValueSize);
                 status = -EINVAL;
                 break;
             }
             // no need to set *pValueSize
 
-            *(int16_t *)pValue = VirtualizerGetStrength(pContext);
+            *(int16_t*)pValue = VirtualizerGetStrength(pContext);
 
-            ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH %d", __func__, *(int16_t *)pValue);
+            ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH %d", __func__, *(int16_t*)pValue);
             break;
 
         case VIRTUALIZER_PARAM_VIRTUAL_SPEAKER_ANGLES: {
             if (paramSize < 3 * sizeof(int32_t)) {
-                ALOGV("%s VIRTUALIZER_PARAM_SPEAKER_ANGLES invalid paramSize: %u",
-                        __func__, paramSize);
+                ALOGV("%s VIRTUALIZER_PARAM_SPEAKER_ANGLES invalid paramSize: %u", __func__,
+                      paramSize);
                 status = -EINVAL;
                 break;
             }
 
-            const audio_channel_mask_t channelMask = (audio_channel_mask_t) params[1];
-            const audio_devices_t deviceType = (audio_devices_t) params[2];
+            const audio_channel_mask_t channelMask = (audio_channel_mask_t)params[1];
+            const audio_devices_t deviceType = (audio_devices_t)params[2];
             const uint32_t nbChannels = audio_channel_count_from_out_mask(channelMask);
             const uint32_t valueSizeRequired = 3 * nbChannels * sizeof(int32_t);
             if (*pValueSize < valueSizeRequired) {
-                ALOGV("%s VIRTUALIZER_PARAM_SPEAKER_ANGLES invalid *pValueSize %u",
-                        __func__, *pValueSize);
+                ALOGV("%s VIRTUALIZER_PARAM_SPEAKER_ANGLES invalid *pValueSize %u", __func__,
+                      *pValueSize);
                 status = -EINVAL;
                 break;
             }
@@ -2229,23 +2030,23 @@
             // verify the configuration is supported
             status = VirtualizerIsConfigurationSupported(channelMask, deviceType);
             if (status == 0) {
-                ALOGV("%s VIRTUALIZER_PARAM_VIRTUAL_SPEAKER_ANGLES mask=0x%x device=0x%x",
-                        __func__, channelMask, deviceType);
+                ALOGV("%s VIRTUALIZER_PARAM_VIRTUAL_SPEAKER_ANGLES mask=0x%x device=0x%x", __func__,
+                      channelMask, deviceType);
                 // configuration is supported, get the angles
-                VirtualizerGetSpeakerAngles(channelMask, deviceType, (int32_t *)pValue);
+                VirtualizerGetSpeakerAngles(channelMask, deviceType, (int32_t*)pValue);
             }
         } break;
 
         case VIRTUALIZER_PARAM_VIRTUALIZATION_MODE:
-            if (*pValueSize != sizeof(uint32_t)) { // legacy: check equality here.
-                ALOGV("%s VIRTUALIZER_PARAM_VIRTUALIZATION_MODE invalid *pValueSize %u",
-                        __func__, *pValueSize);
+            if (*pValueSize != sizeof(uint32_t)) {  // legacy: check equality here.
+                ALOGV("%s VIRTUALIZER_PARAM_VIRTUALIZATION_MODE invalid *pValueSize %u", __func__,
+                      *pValueSize);
                 status = -EINVAL;
                 break;
             }
             // no need to set *pValueSize
 
-            *(uint32_t *)pValue = (uint32_t) VirtualizerGetVirtualizationMode(pContext);
+            *(uint32_t*)pValue = (uint32_t)VirtualizerGetVirtualizationMode(pContext);
             break;
 
         default:
@@ -2273,17 +2074,14 @@
 //
 //----------------------------------------------------------------------------
 
-int Virtualizer_setParameter(EffectContext *pContext,
-                             uint32_t       paramSize,
-                             void          *pParam,
-                             uint32_t       valueSize,
-                             void          *pValue) {
+int Virtualizer_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                             uint32_t valueSize, void* pValue) {
     int status = 0;
-    int32_t *params = (int32_t *)pParam;
+    int32_t* params = (int32_t*)pParam;
 
     ALOGVV("%s start", __func__);
 
-    if (paramSize != sizeof(int32_t)) { // legacy: check equality here.
+    if (paramSize != sizeof(int32_t)) {  // legacy: check equality here.
         ALOGV("%s invalid paramSize: %u", __func__, paramSize);
         return -EINVAL;
     }
@@ -2295,7 +2093,7 @@
                 break;
             }
 
-            const int16_t strength = *(int16_t *)pValue;
+            const int16_t strength = *(int16_t*)pValue;
             ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH %d", __func__, strength);
             ALOGVV("%s VIRTUALIZER_PARAM_STRENGTH Calling VirtualizerSetStrength", __func__);
             VirtualizerSetStrength(pContext, (int32_t)strength);
@@ -2305,16 +2103,16 @@
         case VIRTUALIZER_PARAM_FORCE_VIRTUALIZATION_MODE: {
             if (valueSize < sizeof(int32_t)) {
                 ALOGV("%s VIRTUALIZER_PARAM_FORCE_VIRTUALIZATION_MODE invalid valueSize: %u",
-                        __func__, valueSize);
+                      __func__, valueSize);
                 android_errorWriteLog(0x534e4554, "64478003");
                 status = -EINVAL;
                 break;
             }
 
-            const audio_devices_t deviceType = (audio_devices_t)*(int32_t *)pValue;
+            const audio_devices_t deviceType = (audio_devices_t) * (int32_t*)pValue;
             status = VirtualizerForceVirtualizationMode(pContext, deviceType);
-            ALOGVV("%s VIRTUALIZER_PARAM_FORCE_VIRTUALIZATION_MODE device=%#x result=%d",
-                    __func__, deviceType, status);
+            ALOGVV("%s VIRTUALIZER_PARAM_FORCE_VIRTUALIZATION_MODE device=%#x result=%d", __func__,
+                   deviceType, status);
         } break;
 
         default:
@@ -2347,13 +2145,10 @@
 // Side Effects:
 //
 //----------------------------------------------------------------------------
-int Equalizer_getParameter(EffectContext *pContext,
-                           uint32_t       paramSize,
-                           void          *pParam,
-                           uint32_t      *pValueSize,
-                           void          *pValue) {
+int Equalizer_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                           uint32_t* pValueSize, void* pValue) {
     int status = 0;
-    int32_t *params = (int32_t *)pParam;
+    int32_t* params = (int32_t*)pParam;
 
     ALOGVV("%s start", __func__);
 
@@ -2362,211 +2157,210 @@
         return -EINVAL;
     }
     switch (params[0]) {
-    case EQ_PARAM_NUM_BANDS:
-        if (*pValueSize < sizeof(uint16_t)) {
-            ALOGV("%s EQ_PARAM_NUM_BANDS invalid *pValueSize %u", __func__, *pValueSize);
-            status = -EINVAL;
-            break;
-        }
-        *pValueSize = sizeof(uint16_t);
-
-        *(uint16_t *)pValue = (uint16_t)FIVEBAND_NUMBANDS;
-        ALOGVV("%s EQ_PARAM_NUM_BANDS %u", __func__, *(uint16_t *)pValue);
-        break;
-
-    case EQ_PARAM_CUR_PRESET:
-        if (*pValueSize < sizeof(uint16_t)) {
-            ALOGV("%s EQ_PARAM_CUR_PRESET invalid *pValueSize %u", __func__, *pValueSize);
-            status = -EINVAL;
-            break;
-        }
-        *pValueSize = sizeof(uint16_t);
-
-        *(uint16_t *)pValue = (uint16_t)EqualizerGetPreset(pContext);
-        ALOGVV("%s EQ_PARAM_CUR_PRESET %u", __func__, *(uint16_t *)pValue);
-        break;
-
-    case EQ_PARAM_GET_NUM_OF_PRESETS:
-        if (*pValueSize < sizeof(uint16_t)) {
-            ALOGV("%s EQ_PARAM_GET_NUM_OF_PRESETS invalid *pValueSize %u", __func__, *pValueSize);
-            status = -EINVAL;
-            break;
-        }
-        *pValueSize = sizeof(uint16_t);
-
-        *(uint16_t *)pValue = (uint16_t)EqualizerGetNumPresets();
-        ALOGVV("%s EQ_PARAM_GET_NUM_OF_PRESETS %u", __func__, *(uint16_t *)pValue);
-        break;
-
-    case EQ_PARAM_GET_BAND: {
-        if (paramSize < 2 * sizeof(int32_t)) {
-            ALOGV("%s EQ_PARAM_GET_BAND invalid paramSize: %u", __func__, paramSize);
-            status = -EINVAL;
-            break;
-        }
-        if (*pValueSize < sizeof(uint16_t)) {
-            ALOGV("%s EQ_PARAM_GET_BAND invalid *pValueSize %u", __func__, *pValueSize);
-            status = -EINVAL;
-            break;
-        }
-        *pValueSize = sizeof(uint16_t);
-
-        const int32_t frequency = params[1];
-        *(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, frequency);
-        ALOGVV("%s EQ_PARAM_GET_BAND frequency %d, band %u",
-                __func__, frequency, *(uint16_t *)pValue);
-    } break;
-
-    case EQ_PARAM_BAND_LEVEL: {
-        if (paramSize < 2 * sizeof(int32_t)) {
-            ALOGV("%s EQ_PARAM_BAND_LEVEL invalid paramSize %u", __func__, paramSize);
-            status = -EINVAL;
-            break;
-        }
-        if (*pValueSize < sizeof(int16_t)) {
-            ALOGV("%s EQ_PARAM_BAND_LEVEL invalid *pValueSize %u", __func__, *pValueSize);
-            status = -EINVAL;
-            break;
-        }
-        *pValueSize = sizeof(int16_t);
-
-        const int32_t band = params[1];
-        if (band < 0 || band >= FIVEBAND_NUMBANDS) {
-            if (band < 0) {
-                android_errorWriteLog(0x534e4554, "32438598");
-                ALOGW("%s EQ_PARAM_BAND_LEVEL invalid band %d", __func__, band);
+        case EQ_PARAM_NUM_BANDS:
+            if (*pValueSize < sizeof(uint16_t)) {
+                ALOGV("%s EQ_PARAM_NUM_BANDS invalid *pValueSize %u", __func__, *pValueSize);
+                status = -EINVAL;
+                break;
             }
-            status = -EINVAL;
-            break;
-        }
-        *(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, band);
-        ALOGVV("%s EQ_PARAM_BAND_LEVEL band %d, level %d",
-                __func__, band, *(int16_t *)pValue);
-    } break;
+            *pValueSize = sizeof(uint16_t);
 
-    case EQ_PARAM_LEVEL_RANGE:
-        if (*pValueSize < 2 * sizeof(int16_t)) {
-            ALOGV("%s EQ_PARAM_LEVEL_RANGE invalid *pValueSize %u", __func__, *pValueSize);
-            status = -EINVAL;
+            *(uint16_t*)pValue = (uint16_t)FIVEBAND_NUMBANDS;
+            ALOGVV("%s EQ_PARAM_NUM_BANDS %u", __func__, *(uint16_t*)pValue);
             break;
-        }
-        *pValueSize = 2 * sizeof(int16_t);
 
-        *(int16_t *)pValue = -1500;
-        *((int16_t *)pValue + 1) = 1500;
-        ALOGVV("%s EQ_PARAM_LEVEL_RANGE min %d, max %d",
-                __func__, *(int16_t *)pValue, *((int16_t *)pValue + 1));
-        break;
-
-    case EQ_PARAM_BAND_FREQ_RANGE: {
-        if (paramSize < 2 * sizeof(int32_t)) {
-            ALOGV("%s EQ_PARAM_BAND_FREQ_RANGE invalid paramSize: %u", __func__, paramSize);
-            status = -EINVAL;
-            break;
-        }
-        if (*pValueSize < 2 * sizeof(int32_t)) {
-            ALOGV("%s EQ_PARAM_BAND_FREQ_RANGE invalid *pValueSize %u", __func__, *pValueSize);
-            status = -EINVAL;
-            break;
-        }
-        *pValueSize = 2 * sizeof(int32_t);
-
-        const int32_t band = params[1];
-        if (band < 0 || band >= FIVEBAND_NUMBANDS) {
-            if (band < 0) {
-                android_errorWriteLog(0x534e4554, "32247948");
-                ALOGW("%s EQ_PARAM_BAND_FREQ_RANGE invalid band %d",
-                        __func__, band);
+        case EQ_PARAM_CUR_PRESET:
+            if (*pValueSize < sizeof(uint16_t)) {
+                ALOGV("%s EQ_PARAM_CUR_PRESET invalid *pValueSize %u", __func__, *pValueSize);
+                status = -EINVAL;
+                break;
             }
-            status = -EINVAL;
-            break;
-        }
-        EqualizerGetBandFreqRange(pContext, band, (uint32_t *)pValue, ((uint32_t *)pValue + 1));
-        ALOGVV("%s EQ_PARAM_BAND_FREQ_RANGE band %d, min %d, max %d",
-                __func__, band, *(int32_t *)pValue, *((int32_t *)pValue + 1));
+            *pValueSize = sizeof(uint16_t);
 
-    } break;
-
-    case EQ_PARAM_CENTER_FREQ: {
-        if (paramSize < 2 * sizeof(int32_t)) {
-            ALOGV("%s EQ_PARAM_CENTER_FREQ invalid paramSize: %u", __func__, paramSize);
-            status = -EINVAL;
+            *(uint16_t*)pValue = (uint16_t)EqualizerGetPreset(pContext);
+            ALOGVV("%s EQ_PARAM_CUR_PRESET %u", __func__, *(uint16_t*)pValue);
             break;
-        }
-        if (*pValueSize < sizeof(int32_t)) {
-            ALOGV("%s EQ_PARAM_CENTER_FREQ invalid *pValueSize %u", __func__, *pValueSize);
-            status = -EINVAL;
-            break;
-        }
-        *pValueSize = sizeof(int32_t);
 
-        const int32_t band = params[1];
-        if (band < 0 || band >= FIVEBAND_NUMBANDS) {
-            status = -EINVAL;
-            if (band < 0) {
-                android_errorWriteLog(0x534e4554, "32436341");
-                ALOGW("%s EQ_PARAM_CENTER_FREQ invalid band %d", __func__, band);
+        case EQ_PARAM_GET_NUM_OF_PRESETS:
+            if (*pValueSize < sizeof(uint16_t)) {
+                ALOGV("%s EQ_PARAM_GET_NUM_OF_PRESETS invalid *pValueSize %u", __func__,
+                      *pValueSize);
+                status = -EINVAL;
+                break;
             }
-            break;
-        }
-        *(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, band);
-        ALOGVV("%s EQ_PARAM_CENTER_FREQ band %d, frequency %d",
-                __func__, band, *(int32_t *)pValue);
-    } break;
+            *pValueSize = sizeof(uint16_t);
 
-    case EQ_PARAM_GET_PRESET_NAME: {
-        if (paramSize < 2 * sizeof(int32_t)) {
-            ALOGV("%s EQ_PARAM_PRESET_NAME invalid paramSize: %u", __func__, paramSize);
-            status = -EINVAL;
+            *(uint16_t*)pValue = (uint16_t)EqualizerGetNumPresets();
+            ALOGVV("%s EQ_PARAM_GET_NUM_OF_PRESETS %u", __func__, *(uint16_t*)pValue);
             break;
-        }
-        if (*pValueSize < 1) {
-            android_errorWriteLog(0x534e4554, "37536407");
-            status = -EINVAL;
-            break;
-        }
 
-        const int32_t preset = params[1];
-        if ((preset < 0 && preset != PRESET_CUSTOM) ||  preset >= EqualizerGetNumPresets()) {
-            if (preset < 0) {
-                android_errorWriteLog(0x534e4554, "32448258");
-                ALOGE("%s EQ_PARAM_GET_PRESET_NAME preset %d", __func__, preset);
+        case EQ_PARAM_GET_BAND: {
+            if (paramSize < 2 * sizeof(int32_t)) {
+                ALOGV("%s EQ_PARAM_GET_BAND invalid paramSize: %u", __func__, paramSize);
+                status = -EINVAL;
+                break;
             }
+            if (*pValueSize < sizeof(uint16_t)) {
+                ALOGV("%s EQ_PARAM_GET_BAND invalid *pValueSize %u", __func__, *pValueSize);
+                status = -EINVAL;
+                break;
+            }
+            *pValueSize = sizeof(uint16_t);
+
+            const int32_t frequency = params[1];
+            *(uint16_t*)pValue = (uint16_t)EqualizerGetBand(pContext, frequency);
+            ALOGVV("%s EQ_PARAM_GET_BAND frequency %d, band %u", __func__, frequency,
+                   *(uint16_t*)pValue);
+        } break;
+
+        case EQ_PARAM_BAND_LEVEL: {
+            if (paramSize < 2 * sizeof(int32_t)) {
+                ALOGV("%s EQ_PARAM_BAND_LEVEL invalid paramSize %u", __func__, paramSize);
+                status = -EINVAL;
+                break;
+            }
+            if (*pValueSize < sizeof(int16_t)) {
+                ALOGV("%s EQ_PARAM_BAND_LEVEL invalid *pValueSize %u", __func__, *pValueSize);
+                status = -EINVAL;
+                break;
+            }
+            *pValueSize = sizeof(int16_t);
+
+            const int32_t band = params[1];
+            if (band < 0 || band >= FIVEBAND_NUMBANDS) {
+                if (band < 0) {
+                    android_errorWriteLog(0x534e4554, "32438598");
+                    ALOGW("%s EQ_PARAM_BAND_LEVEL invalid band %d", __func__, band);
+                }
+                status = -EINVAL;
+                break;
+            }
+            *(int16_t*)pValue = (int16_t)EqualizerGetBandLevel(pContext, band);
+            ALOGVV("%s EQ_PARAM_BAND_LEVEL band %d, level %d", __func__, band, *(int16_t*)pValue);
+        } break;
+
+        case EQ_PARAM_LEVEL_RANGE:
+            if (*pValueSize < 2 * sizeof(int16_t)) {
+                ALOGV("%s EQ_PARAM_LEVEL_RANGE invalid *pValueSize %u", __func__, *pValueSize);
+                status = -EINVAL;
+                break;
+            }
+            *pValueSize = 2 * sizeof(int16_t);
+
+            *(int16_t*)pValue = -1500;
+            *((int16_t*)pValue + 1) = 1500;
+            ALOGVV("%s EQ_PARAM_LEVEL_RANGE min %d, max %d", __func__, *(int16_t*)pValue,
+                   *((int16_t*)pValue + 1));
+            break;
+
+        case EQ_PARAM_BAND_FREQ_RANGE: {
+            if (paramSize < 2 * sizeof(int32_t)) {
+                ALOGV("%s EQ_PARAM_BAND_FREQ_RANGE invalid paramSize: %u", __func__, paramSize);
+                status = -EINVAL;
+                break;
+            }
+            if (*pValueSize < 2 * sizeof(int32_t)) {
+                ALOGV("%s EQ_PARAM_BAND_FREQ_RANGE invalid *pValueSize %u", __func__, *pValueSize);
+                status = -EINVAL;
+                break;
+            }
+            *pValueSize = 2 * sizeof(int32_t);
+
+            const int32_t band = params[1];
+            if (band < 0 || band >= FIVEBAND_NUMBANDS) {
+                if (band < 0) {
+                    android_errorWriteLog(0x534e4554, "32247948");
+                    ALOGW("%s EQ_PARAM_BAND_FREQ_RANGE invalid band %d", __func__, band);
+                }
+                status = -EINVAL;
+                break;
+            }
+            EqualizerGetBandFreqRange(pContext, band, (uint32_t*)pValue, ((uint32_t*)pValue + 1));
+            ALOGVV("%s EQ_PARAM_BAND_FREQ_RANGE band %d, min %d, max %d", __func__, band,
+                   *(int32_t*)pValue, *((int32_t*)pValue + 1));
+
+        } break;
+
+        case EQ_PARAM_CENTER_FREQ: {
+            if (paramSize < 2 * sizeof(int32_t)) {
+                ALOGV("%s EQ_PARAM_CENTER_FREQ invalid paramSize: %u", __func__, paramSize);
+                status = -EINVAL;
+                break;
+            }
+            if (*pValueSize < sizeof(int32_t)) {
+                ALOGV("%s EQ_PARAM_CENTER_FREQ invalid *pValueSize %u", __func__, *pValueSize);
+                status = -EINVAL;
+                break;
+            }
+            *pValueSize = sizeof(int32_t);
+
+            const int32_t band = params[1];
+            if (band < 0 || band >= FIVEBAND_NUMBANDS) {
+                status = -EINVAL;
+                if (band < 0) {
+                    android_errorWriteLog(0x534e4554, "32436341");
+                    ALOGW("%s EQ_PARAM_CENTER_FREQ invalid band %d", __func__, band);
+                }
+                break;
+            }
+            *(int32_t*)pValue = EqualizerGetCentreFrequency(pContext, band);
+            ALOGVV("%s EQ_PARAM_CENTER_FREQ band %d, frequency %d", __func__, band,
+                   *(int32_t*)pValue);
+        } break;
+
+        case EQ_PARAM_GET_PRESET_NAME: {
+            if (paramSize < 2 * sizeof(int32_t)) {
+                ALOGV("%s EQ_PARAM_PRESET_NAME invalid paramSize: %u", __func__, paramSize);
+                status = -EINVAL;
+                break;
+            }
+            if (*pValueSize < 1) {
+                android_errorWriteLog(0x534e4554, "37536407");
+                status = -EINVAL;
+                break;
+            }
+
+            const int32_t preset = params[1];
+            if ((preset < 0 && preset != PRESET_CUSTOM) || preset >= EqualizerGetNumPresets()) {
+                if (preset < 0) {
+                    android_errorWriteLog(0x534e4554, "32448258");
+                    ALOGE("%s EQ_PARAM_GET_PRESET_NAME preset %d", __func__, preset);
+                }
+                status = -EINVAL;
+                break;
+            }
+
+            char* const name = (char*)pValue;
+            strncpy(name, EqualizerGetPresetName(preset), *pValueSize - 1);
+            name[*pValueSize - 1] = 0;
+            *pValueSize = strlen(name) + 1;
+            ALOGVV("%s EQ_PARAM_GET_PRESET_NAME preset %d, name %s len %d", __func__, preset, name,
+                   *pValueSize);
+
+        } break;
+
+        case EQ_PARAM_PROPERTIES: {
+            constexpr uint32_t requiredValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t);
+            if (*pValueSize < requiredValueSize) {
+                ALOGV("%s EQ_PARAM_PROPERTIES invalid *pValueSize %u", __func__, *pValueSize);
+                status = -EINVAL;
+                break;
+            }
+            *pValueSize = requiredValueSize;
+
+            int16_t* p = (int16_t*)pValue;
+            ALOGV("%s EQ_PARAM_PROPERTIES", __func__);
+            p[0] = (int16_t)EqualizerGetPreset(pContext);
+            p[1] = (int16_t)FIVEBAND_NUMBANDS;
+            for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
+                p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i);
+            }
+        } break;
+
+        default:
+            ALOGV("%s invalid param %d", __func__, params[0]);
             status = -EINVAL;
             break;
-        }
-
-        char * const name = (char *)pValue;
-        strncpy(name, EqualizerGetPresetName(preset), *pValueSize - 1);
-        name[*pValueSize - 1] = 0;
-        *pValueSize = strlen(name) + 1;
-        ALOGVV("%s EQ_PARAM_GET_PRESET_NAME preset %d, name %s len %d",
-               __func__, preset, name, *pValueSize);
-
-    } break;
-
-    case EQ_PARAM_PROPERTIES: {
-        constexpr uint32_t requiredValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t);
-        if (*pValueSize < requiredValueSize) {
-            ALOGV("%s EQ_PARAM_PROPERTIES invalid *pValueSize %u", __func__, *pValueSize);
-            status = -EINVAL;
-            break;
-        }
-        *pValueSize = requiredValueSize;
-
-        int16_t *p = (int16_t *)pValue;
-        ALOGV("%s EQ_PARAM_PROPERTIES", __func__);
-        p[0] = (int16_t)EqualizerGetPreset(pContext);
-        p[1] = (int16_t)FIVEBAND_NUMBANDS;
-        for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
-            p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i);
-        }
-    } break;
-
-    default:
-        ALOGV("%s invalid param %d", __func__, params[0]);
-        status = -EINVAL;
-        break;
     }
 
     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
@@ -2589,13 +2383,10 @@
 // Outputs:
 //
 //----------------------------------------------------------------------------
-int Equalizer_setParameter(EffectContext *pContext,
-                           uint32_t       paramSize,
-                           void          *pParam,
-                           uint32_t       valueSize,
-                           void          *pValue) {
+int Equalizer_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                           uint32_t valueSize, void* pValue) {
     int status = 0;
-    int32_t *params = (int32_t *)pParam;
+    int32_t* params = (int32_t*)pParam;
 
     ALOGVV("%s start", __func__);
 
@@ -2604,87 +2395,87 @@
         return -EINVAL;
     }
     switch (params[0]) {
-    case EQ_PARAM_CUR_PRESET: {
-        if (valueSize < sizeof(int16_t)) {
-            ALOGV("%s EQ_PARAM_CUR_PRESET invalid valueSize %u", __func__, valueSize);
-            status = -EINVAL;
-            break;
-        }
-        const int32_t preset = (int32_t)*(uint16_t *)pValue;
-
-        ALOGVV("%s EQ_PARAM_CUR_PRESET %d", __func__, preset);
-        if (preset >= EqualizerGetNumPresets() || preset < 0) {
-            ALOGV("%s EQ_PARAM_CUR_PRESET invalid preset %d", __func__, preset);
-            status = -EINVAL;
-            break;
-        }
-        EqualizerSetPreset(pContext, preset);
-    } break;
-
-    case EQ_PARAM_BAND_LEVEL: {
-        if (paramSize < 2 * sizeof(int32_t)) {
-            ALOGV("%s EQ_PARAM_BAND_LEVEL invalid paramSize: %u", __func__, paramSize);
-            status = -EINVAL;
-            break;
-        }
-        if (valueSize < sizeof(int16_t)) {
-            ALOGV("%s EQ_PARAM_BAND_LEVEL invalid valueSize %u", __func__, valueSize);
-            status = -EINVAL;
-            break;
-        }
-        const int32_t band =  params[1];
-        const int32_t level = (int32_t)*(int16_t *)pValue;
-        ALOGVV("%s EQ_PARAM_BAND_LEVEL band %d, level %d", __func__, band, level);
-        if (band < 0 || band >= FIVEBAND_NUMBANDS) {
-            if (band < 0) {
-                android_errorWriteLog(0x534e4554, "32095626");
-                ALOGE("%s EQ_PARAM_BAND_LEVEL invalid band %d", __func__, band);
-            }
-            status = -EINVAL;
-            break;
-        }
-        EqualizerSetBandLevel(pContext, band, level);
-    } break;
-
-    case EQ_PARAM_PROPERTIES: {
-        ALOGVV("%s EQ_PARAM_PROPERTIES", __func__);
-        if (valueSize < sizeof(int16_t)) {
-            ALOGV("%s EQ_PARAM_PROPERTIES invalid valueSize %u", __func__, valueSize);
-            status = -EINVAL;
-            break;
-        }
-        int16_t *p = (int16_t *)pValue;
-        if ((int)p[0] >= EqualizerGetNumPresets()) {
-            ALOGV("%s EQ_PARAM_PROPERTIES invalid preset %d", __func__, (int)p[0]);
-            status = -EINVAL;
-            break;
-        }
-        if (p[0] >= 0) {
-            EqualizerSetPreset(pContext, (int)p[0]);
-        } else {
-            constexpr uint32_t valueSizeRequired = (2 + FIVEBAND_NUMBANDS) * sizeof(int16_t);
-            if (valueSize < valueSizeRequired) {
-              android_errorWriteLog(0x534e4554, "37563371");
-              ALOGE("%s EQ_PARAM_PROPERTIES invalid valueSize %u < %u",
-                      __func__, valueSize, valueSizeRequired);
-              status = -EINVAL;
-              break;
-            }
-            if ((int)p[1] != FIVEBAND_NUMBANDS) {
-                ALOGV("%s EQ_PARAM_PROPERTIES invalid bands %d", __func__, (int)p[1]);
+        case EQ_PARAM_CUR_PRESET: {
+            if (valueSize < sizeof(int16_t)) {
+                ALOGV("%s EQ_PARAM_CUR_PRESET invalid valueSize %u", __func__, valueSize);
                 status = -EINVAL;
                 break;
             }
-            for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
-                EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
-            }
-        }
-    } break;
+            const int32_t preset = (int32_t) * (uint16_t*)pValue;
 
-    default:
-        ALOGV("%s invalid param %d", __func__, params[0]);
-        status = -EINVAL;
-        break;
+            ALOGVV("%s EQ_PARAM_CUR_PRESET %d", __func__, preset);
+            if (preset >= EqualizerGetNumPresets() || preset < 0) {
+                ALOGV("%s EQ_PARAM_CUR_PRESET invalid preset %d", __func__, preset);
+                status = -EINVAL;
+                break;
+            }
+            EqualizerSetPreset(pContext, preset);
+        } break;
+
+        case EQ_PARAM_BAND_LEVEL: {
+            if (paramSize < 2 * sizeof(int32_t)) {
+                ALOGV("%s EQ_PARAM_BAND_LEVEL invalid paramSize: %u", __func__, paramSize);
+                status = -EINVAL;
+                break;
+            }
+            if (valueSize < sizeof(int16_t)) {
+                ALOGV("%s EQ_PARAM_BAND_LEVEL invalid valueSize %u", __func__, valueSize);
+                status = -EINVAL;
+                break;
+            }
+            const int32_t band = params[1];
+            const int32_t level = (int32_t) * (int16_t*)pValue;
+            ALOGVV("%s EQ_PARAM_BAND_LEVEL band %d, level %d", __func__, band, level);
+            if (band < 0 || band >= FIVEBAND_NUMBANDS) {
+                if (band < 0) {
+                    android_errorWriteLog(0x534e4554, "32095626");
+                    ALOGE("%s EQ_PARAM_BAND_LEVEL invalid band %d", __func__, band);
+                }
+                status = -EINVAL;
+                break;
+            }
+            EqualizerSetBandLevel(pContext, band, level);
+        } break;
+
+        case EQ_PARAM_PROPERTIES: {
+            ALOGVV("%s EQ_PARAM_PROPERTIES", __func__);
+            if (valueSize < sizeof(int16_t)) {
+                ALOGV("%s EQ_PARAM_PROPERTIES invalid valueSize %u", __func__, valueSize);
+                status = -EINVAL;
+                break;
+            }
+            int16_t* p = (int16_t*)pValue;
+            if ((int)p[0] >= EqualizerGetNumPresets()) {
+                ALOGV("%s EQ_PARAM_PROPERTIES invalid preset %d", __func__, (int)p[0]);
+                status = -EINVAL;
+                break;
+            }
+            if (p[0] >= 0) {
+                EqualizerSetPreset(pContext, (int)p[0]);
+            } else {
+                constexpr uint32_t valueSizeRequired = (2 + FIVEBAND_NUMBANDS) * sizeof(int16_t);
+                if (valueSize < valueSizeRequired) {
+                    android_errorWriteLog(0x534e4554, "37563371");
+                    ALOGE("%s EQ_PARAM_PROPERTIES invalid valueSize %u < %u", __func__, valueSize,
+                          valueSizeRequired);
+                    status = -EINVAL;
+                    break;
+                }
+                if ((int)p[1] != FIVEBAND_NUMBANDS) {
+                    ALOGV("%s EQ_PARAM_PROPERTIES invalid bands %d", __func__, (int)p[1]);
+                    status = -EINVAL;
+                    break;
+                }
+                for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
+                    EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
+                }
+            }
+        } break;
+
+        default:
+            ALOGV("%s invalid param %d", __func__, params[0]);
+            status = -EINVAL;
+            break;
     }
 
     ALOGVV("%s end param: %d, status: %d", __func__, params[0], status);
@@ -2712,13 +2503,10 @@
 //
 //----------------------------------------------------------------------------
 
-int Volume_getParameter(EffectContext *pContext,
-                        uint32_t       paramSize,
-                        void          *pParam,
-                        uint32_t      *pValueSize,
-                        void          *pValue) {
+int Volume_getParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                        uint32_t* pValueSize, void* pValue) {
     int status = 0;
-    int32_t *params = (int32_t *)pParam;
+    int32_t* params = (int32_t*)pParam;
 
     ALOGVV("%s start", __func__);
 
@@ -2728,19 +2516,19 @@
     }
     switch (params[0]) {
         case VOLUME_PARAM_LEVEL:
-            if (*pValueSize != sizeof(int16_t)) { // legacy: check equality here.
+            if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
                 ALOGV("%s VOLUME_PARAM_LEVEL invalid *pValueSize %u", __func__, *pValueSize);
                 status = -EINVAL;
                 break;
             }
             // no need to set *pValueSize
 
-            status = VolumeGetVolumeLevel(pContext, (int16_t *)(pValue));
-            ALOGVV("%s VOLUME_PARAM_LEVEL %d", __func__, *(int16_t *)pValue);
+            status = VolumeGetVolumeLevel(pContext, (int16_t*)(pValue));
+            ALOGVV("%s VOLUME_PARAM_LEVEL %d", __func__, *(int16_t*)pValue);
             break;
 
         case VOLUME_PARAM_MAXLEVEL:
-            if (*pValueSize != sizeof(int16_t)) { // legacy: check equality here.
+            if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
                 ALOGV("%s VOLUME_PARAM_MAXLEVEL invalid *pValueSize %u", __func__, *pValueSize);
                 status = -EINVAL;
                 break;
@@ -2748,21 +2536,21 @@
             // no need to set *pValueSize
 
             // in millibel
-            *(int16_t *)pValue = 0;
-            ALOGVV("%s VOLUME_PARAM_MAXLEVEL %d", __func__, *(int16_t *)pValue);
+            *(int16_t*)pValue = 0;
+            ALOGVV("%s VOLUME_PARAM_MAXLEVEL %d", __func__, *(int16_t*)pValue);
             break;
 
         case VOLUME_PARAM_STEREOPOSITION:
-            if (*pValueSize != sizeof(int16_t)) { // legacy: check equality here.
-                ALOGV("%s VOLUME_PARAM_STEREOPOSITION invalid *pValueSize %u",
-                        __func__, *pValueSize);
+            if (*pValueSize != sizeof(int16_t)) {  // legacy: check equality here.
+                ALOGV("%s VOLUME_PARAM_STEREOPOSITION invalid *pValueSize %u", __func__,
+                      *pValueSize);
                 status = -EINVAL;
                 break;
             }
             // no need to set *pValueSize
 
-            VolumeGetStereoPosition(pContext, (int16_t *)pValue);
-            ALOGVV("%s VOLUME_PARAM_STEREOPOSITION %d", __func__, *(int16_t *)pValue);
+            VolumeGetStereoPosition(pContext, (int16_t*)pValue);
+            ALOGVV("%s VOLUME_PARAM_STEREOPOSITION %d", __func__, *(int16_t*)pValue);
             break;
 
         case VOLUME_PARAM_MUTE:
@@ -2773,21 +2561,21 @@
             }
             *pValueSize = sizeof(uint32_t);
 
-            status = VolumeGetMute(pContext, (uint32_t *)pValue);
-            ALOGV("%s VOLUME_PARAM_MUTE %u", __func__, *(uint32_t *)pValue);
+            status = VolumeGetMute(pContext, (uint32_t*)pValue);
+            ALOGV("%s VOLUME_PARAM_MUTE %u", __func__, *(uint32_t*)pValue);
             break;
 
         case VOLUME_PARAM_ENABLESTEREOPOSITION:
             if (*pValueSize < sizeof(int32_t)) {
-                ALOGV("%s VOLUME_PARAM_ENABLESTEREOPOSITION invalid *pValueSize %u",
-                        __func__, *pValueSize);
+                ALOGV("%s VOLUME_PARAM_ENABLESTEREOPOSITION invalid *pValueSize %u", __func__,
+                      *pValueSize);
                 status = -EINVAL;
                 break;
             }
             *pValueSize = sizeof(int32_t);
 
-            *(int32_t *)pValue = pContext->pBundledContext->bStereoPositionEnabled;
-            ALOGVV("%s VOLUME_PARAM_ENABLESTEREOPOSITION %d", __func__, *(int32_t *)pValue);
+            *(int32_t*)pValue = pContext->pBundledContext->bStereoPositionEnabled;
+            ALOGVV("%s VOLUME_PARAM_ENABLESTEREOPOSITION %d", __func__, *(int32_t*)pValue);
 
             break;
 
@@ -2816,13 +2604,10 @@
 //
 //----------------------------------------------------------------------------
 
-int Volume_setParameter(EffectContext *pContext,
-                        uint32_t       paramSize,
-                        void          *pParam,
-                        uint32_t       valueSize,
-                        void          *pValue) {
+int Volume_setParameter(EffectContext* pContext, uint32_t paramSize, void* pParam,
+                        uint32_t valueSize, void* pValue) {
     int status = 0;
-    int32_t *params = (int32_t *)pParam;
+    int32_t* params = (int32_t*)pParam;
 
     ALOGVV("%s start", __func__);
 
@@ -2838,7 +2623,7 @@
                 break;
             }
 
-            const int16_t level = *(int16_t *)pValue;
+            const int16_t level = *(int16_t*)pValue;
             ALOGVV("%s VOLUME_PARAM_LEVEL %d", __func__, level);
             ALOGVV("%s VOLUME_PARAM_LEVEL Calling VolumeSetVolumeLevel", __func__);
             status = VolumeSetVolumeLevel(pContext, level);
@@ -2853,7 +2638,7 @@
                 break;
             }
 
-            const uint32_t mute = *(uint32_t *)pValue;
+            const uint32_t mute = *(uint32_t*)pValue;
             ALOGVV("%s VOLUME_PARAM_MUTE %d", __func__, mute);
             ALOGVV("%s VOLUME_PARAM_MUTE Calling VolumeSetMute", __func__);
             status = VolumeSetMute(pContext, mute);
@@ -2862,15 +2647,16 @@
 
         case VOLUME_PARAM_ENABLESTEREOPOSITION: {
             if (valueSize < sizeof(uint32_t)) {
-                ALOGV("%s VOLUME_PARAM_ENABLESTEREOPOSITION invalid valueSize %u",
-                        __func__, valueSize);
+                ALOGV("%s VOLUME_PARAM_ENABLESTEREOPOSITION invalid valueSize %u", __func__,
+                      valueSize);
                 status = -EINVAL;
                 break;
             }
 
-            const uint32_t positionEnabled = *(uint32_t *)pValue;
+            const uint32_t positionEnabled = *(uint32_t*)pValue;
             status = VolumeEnableStereoPosition(pContext, positionEnabled)
-                    ?: VolumeSetStereoPosition(pContext, pContext->pBundledContext->positionSaved);
+                             ?: VolumeSetStereoPosition(pContext,
+                                                        pContext->pBundledContext->positionSaved);
             ALOGVV("%s VOLUME_PARAM_ENABLESTEREOPOSITION called", __func__);
         } break;
 
@@ -2881,13 +2667,11 @@
                 break;
             }
 
-            const int16_t position = *(int16_t *)pValue;
+            const int16_t position = *(int16_t*)pValue;
             ALOGVV("%s VOLUME_PARAM_STEREOPOSITION %d", __func__, position);
-            ALOGVV("%s VOLUME_PARAM_STEREOPOSITION Calling VolumeSetStereoPosition",
-                    __func__);
+            ALOGVV("%s VOLUME_PARAM_STEREOPOSITION Calling VolumeSetStereoPosition", __func__);
             status = VolumeSetStereoPosition(pContext, position);
-            ALOGVV("%s VOLUME_PARAM_STEREOPOSITION Called VolumeSetStereoPosition",
-                    __func__);
+            ALOGVV("%s VOLUME_PARAM_STEREOPOSITION Called VolumeSetStereoPosition", __func__);
         } break;
 
         default:
@@ -2912,18 +2696,15 @@
  *  Remarks     :
  ****************************************************************************************/
 
-LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix)
-{
-    LVM_INT16   db_fix;
-    LVM_INT16   Shift;
-    LVM_INT16   SmallRemainder;
-    LVM_UINT32  Remainder = (LVM_UINT32)Lin_fix;
+LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix) {
+    LVM_INT16 db_fix;
+    LVM_INT16 Shift;
+    LVM_INT16 SmallRemainder;
+    LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix;
 
     /* Count leading bits, 1 cycle in assembly*/
-    for (Shift = 0; Shift<32; Shift++)
-    {
-        if ((Remainder & 0x80000000U)!=0)
-        {
+    for (Shift = 0; Shift < 32; Shift++) {
+        if ((Remainder & 0x80000000U) != 0) {
             break;
         }
         Remainder = Remainder << 1;
@@ -2934,9 +2715,9 @@
      *
      * dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2)
      */
-    db_fix    = (LVM_INT16)(-96 * Shift);               /* Six dB steps in Q11.4 format*/
+    db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/
     SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24);
-    db_fix = (LVM_INT16)(db_fix + SmallRemainder );
+    db_fix = (LVM_INT16)(db_fix + SmallRemainder);
     SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder);
     db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9));
 
@@ -2960,11 +2741,10 @@
 //
 //----------------------------------------------------------------------------
 
-int Effect_setEnabled(EffectContext *pContext, bool enabled)
-{
-    ALOGV("%s effectType %d, enabled %d, currently enabled %d", __func__,
-            pContext->EffectType, enabled, pContext->pBundledContext->NumberEffectsEnabled);
-    int &effectInDrain = pContext->pBundledContext->effectInDrain;
+int Effect_setEnabled(EffectContext* pContext, bool enabled) {
+    ALOGV("%s effectType %d, enabled %d, currently enabled %d", __func__, pContext->EffectType,
+          enabled, pContext->pBundledContext->NumberEffectsEnabled);
+    int& effectInDrain = pContext->pBundledContext->effectInDrain;
     if (enabled) {
         // Bass boost or Virtualizer can be temporarily disabled if playing over device speaker due
         // to their nature.
@@ -2972,15 +2752,15 @@
         switch (pContext->EffectType) {
             case LVM_BASS_BOOST:
                 if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
-                     ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled");
-                     return -EINVAL;
+                    ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled");
+                    return -EINVAL;
                 }
-                if(pContext->pBundledContext->SamplesToExitCountBb <= 0){
+                if (pContext->pBundledContext->SamplesToExitCountBb <= 0) {
                     pContext->pBundledContext->NumberEffectsEnabled++;
                 }
                 effectInDrain &= ~(1 << LVM_BASS_BOOST);
                 pContext->pBundledContext->SamplesToExitCountBb =
-                     (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
+                        (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond * 0.1);
                 pContext->pBundledContext->bBassEnabled = LVM_TRUE;
                 tempDisabled = pContext->pBundledContext->bBassTempDisabled;
                 break;
@@ -2989,12 +2769,12 @@
                     ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled");
                     return -EINVAL;
                 }
-                if(pContext->pBundledContext->SamplesToExitCountEq <= 0){
+                if (pContext->pBundledContext->SamplesToExitCountEq <= 0) {
                     pContext->pBundledContext->NumberEffectsEnabled++;
                 }
                 effectInDrain &= ~(1 << LVM_EQUALIZER);
                 pContext->pBundledContext->SamplesToExitCountEq =
-                     (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
+                        (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond * 0.1);
                 pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE;
                 break;
             case LVM_VIRTUALIZER:
@@ -3002,12 +2782,12 @@
                     ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled");
                     return -EINVAL;
                 }
-                if(pContext->pBundledContext->SamplesToExitCountVirt <= 0){
+                if (pContext->pBundledContext->SamplesToExitCountVirt <= 0) {
                     pContext->pBundledContext->NumberEffectsEnabled++;
                 }
                 effectInDrain &= ~(1 << LVM_VIRTUALIZER);
                 pContext->pBundledContext->SamplesToExitCountVirt =
-                     (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
+                        (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond * 0.1);
                 pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE;
                 tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled;
                 break;
@@ -3084,41 +2864,39 @@
 //
 //-----------------------------------------------------------------------
 
-int16_t LVC_Convert_VolToDb(uint32_t vol){
-    int16_t  dB;
+int16_t LVC_Convert_VolToDb(uint32_t vol) {
+    int16_t dB;
 
-    dB = LVC_ToDB_s32Tos16(vol <<7);
-    dB = (dB +8)>>4;
-    dB = (dB <-96) ? -96 : dB ;
+    dB = LVC_ToDB_s32Tos16(vol << 7);
+    dB = (dB + 8) >> 4;
+    dB = (dB < -96) ? -96 : dB;
 
     return dB;
 }
 
-} // namespace
-} // namespace
+}  // namespace
+}  // namespace android
 
 extern "C" {
 /* Effect Control Interface Implementation: Process */
-int Effect_process(effect_handle_t     self,
-                              audio_buffer_t         *inBuffer,
-                              audio_buffer_t         *outBuffer){
-    EffectContext * pContext = (EffectContext *) self;
-    int    status = 0;
-    int    processStatus = 0;
+int Effect_process(effect_handle_t self, audio_buffer_t* inBuffer, audio_buffer_t* outBuffer) {
+    EffectContext* pContext = (EffectContext*)self;
+    int status = 0;
+    int processStatus = 0;
     const int NrChannels = audio_channel_count_from_out_mask(pContext->config.inputCfg.channels);
 
-//ALOGV("\tEffect_process Start : Enabled = %d     Called = %d (%8d %8d %8d)",
-//pContext->pBundledContext->NumberEffectsEnabled,pContext->pBundledContext->NumberEffectsCalled,
-//    pContext->pBundledContext->SamplesToExitCountBb,
-//    pContext->pBundledContext->SamplesToExitCountVirt,
-//    pContext->pBundledContext->SamplesToExitCountEq);
+    // ALOGV("\tEffect_process Start : Enabled = %d     Called = %d (%8d %8d %8d)",
+    // pContext->pBundledContext->NumberEffectsEnabled,pContext->pBundledContext->NumberEffectsCalled,
+    //    pContext->pBundledContext->SamplesToExitCountBb,
+    //    pContext->pBundledContext->SamplesToExitCountVirt,
+    //    pContext->pBundledContext->SamplesToExitCountEq);
 
-    if (pContext == NULL){
+    if (pContext == NULL) {
         ALOGV("\tLVM_ERROR : Effect_process() ERROR pContext == NULL");
         return -EINVAL;
     }
 
-    //if(pContext->EffectType == LVM_BASS_BOOST){
+    // if(pContext->EffectType == LVM_BASS_BOOST){
     //  ALOGV("\tEffect_process: Effect type is BASS_BOOST");
     //}else if(pContext->EffectType == LVM_EQUALIZER){
     //  ALOGV("\tEffect_process: Effect type is LVM_EQUALIZER");
@@ -3126,15 +2904,14 @@
     //  ALOGV("\tEffect_process: Effect type is LVM_VIRTUALIZER");
     //}
 
-    if (inBuffer == NULL  || inBuffer->raw == NULL  ||
-            outBuffer == NULL || outBuffer->raw == NULL ||
-            inBuffer->frameCount != outBuffer->frameCount){
+    if (inBuffer == NULL || inBuffer->raw == NULL || outBuffer == NULL || outBuffer->raw == NULL ||
+        inBuffer->frameCount != outBuffer->frameCount) {
         ALOGV("\tLVM_ERROR : Effect_process() ERROR NULL INPUT POINTER OR FRAME COUNT IS WRONG");
         return -EINVAL;
     }
 
-    int &effectProcessCalled = pContext->pBundledContext->effectProcessCalled;
-    int &effectInDrain = pContext->pBundledContext->effectInDrain;
+    int& effectProcessCalled = pContext->pBundledContext->effectProcessCalled;
+    int& effectInDrain = pContext->pBundledContext->effectInDrain;
     if ((effectProcessCalled & 1 << pContext->EffectType) != 0) {
         ALOGW("Effect %d already called", pContext->EffectType);
         const int undrainedEffects = effectInDrain & ~effectProcessCalled;
@@ -3164,12 +2941,12 @@
     }
     effectProcessCalled |= 1 << pContext->EffectType;
 
-    if ((pContext->pBundledContext->bBassEnabled == LVM_FALSE)&&
-        (pContext->EffectType == LVM_BASS_BOOST)){
-        //ALOGV("\tEffect_process() LVM_BASS_BOOST Effect is not enabled");
-        if(pContext->pBundledContext->SamplesToExitCountBb > 0){
+    if ((pContext->pBundledContext->bBassEnabled == LVM_FALSE) &&
+        (pContext->EffectType == LVM_BASS_BOOST)) {
+        // ALOGV("\tEffect_process() LVM_BASS_BOOST Effect is not enabled");
+        if (pContext->pBundledContext->SamplesToExitCountBb > 0) {
             pContext->pBundledContext->SamplesToExitCountBb -= outBuffer->frameCount * NrChannels;
-            //ALOGV("\tEffect_process: Waiting to turn off BASS_BOOST, %d samples left",
+            // ALOGV("\tEffect_process: Waiting to turn off BASS_BOOST, %d samples left",
             //    pContext->pBundledContext->SamplesToExitCountBb);
         }
         if (pContext->pBundledContext->SamplesToExitCountBb <= 0) {
@@ -3181,21 +2958,21 @@
             ALOGV("\tEffect_process() this is the last frame for LVM_BASS_BOOST");
         }
     }
-    if ((pContext->pBundledContext->bVolumeEnabled == LVM_FALSE)&&
-        (pContext->EffectType == LVM_VOLUME)){
-        //ALOGV("\tEffect_process() LVM_VOLUME Effect is not enabled");
+    if ((pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) &&
+        (pContext->EffectType == LVM_VOLUME)) {
+        // ALOGV("\tEffect_process() LVM_VOLUME Effect is not enabled");
         status = -ENODATA;
         if ((effectInDrain & 1 << LVM_VOLUME) != 0) {
             pContext->pBundledContext->NumberEffectsEnabled--;
             effectInDrain &= ~(1 << LVM_VOLUME);
         }
     }
-    if ((pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE)&&
-        (pContext->EffectType == LVM_EQUALIZER)){
-        //ALOGV("\tEffect_process() LVM_EQUALIZER Effect is not enabled");
-        if(pContext->pBundledContext->SamplesToExitCountEq > 0){
+    if ((pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) &&
+        (pContext->EffectType == LVM_EQUALIZER)) {
+        // ALOGV("\tEffect_process() LVM_EQUALIZER Effect is not enabled");
+        if (pContext->pBundledContext->SamplesToExitCountEq > 0) {
             pContext->pBundledContext->SamplesToExitCountEq -= outBuffer->frameCount * NrChannels;
-            //ALOGV("\tEffect_process: Waiting to turn off EQUALIZER, %d samples left",
+            // ALOGV("\tEffect_process: Waiting to turn off EQUALIZER, %d samples left",
             //    pContext->pBundledContext->SamplesToExitCountEq);
         }
         if (pContext->pBundledContext->SamplesToExitCountEq <= 0) {
@@ -3207,13 +2984,12 @@
             ALOGV("\tEffect_process() this is the last frame for LVM_EQUALIZER");
         }
     }
-    if ((pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE)&&
-        (pContext->EffectType == LVM_VIRTUALIZER)){
-        //ALOGV("\tEffect_process() LVM_VIRTUALIZER Effect is not enabled");
-        if(pContext->pBundledContext->SamplesToExitCountVirt > 0){
-            pContext->pBundledContext->SamplesToExitCountVirt -=
-                outBuffer->frameCount * NrChannels;
-            //ALOGV("\tEffect_process: Waiting for to turn off VIRTUALIZER, %d samples left",
+    if ((pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) &&
+        (pContext->EffectType == LVM_VIRTUALIZER)) {
+        // ALOGV("\tEffect_process() LVM_VIRTUALIZER Effect is not enabled");
+        if (pContext->pBundledContext->SamplesToExitCountVirt > 0) {
+            pContext->pBundledContext->SamplesToExitCountVirt -= outBuffer->frameCount * NrChannels;
+            // ALOGV("\tEffect_process: Waiting for to turn off VIRTUALIZER, %d samples left",
             //    pContext->pBundledContext->SamplesToExitCountVirt);
         }
         if (pContext->pBundledContext->SamplesToExitCountVirt <= 0) {
@@ -3226,37 +3002,34 @@
         }
     }
 
-    if(status != -ENODATA){
+    if (status != -ENODATA) {
         pContext->pBundledContext->NumberEffectsCalled++;
     }
 
     if (pContext->pBundledContext->NumberEffectsCalled >=
-            pContext->pBundledContext->NumberEffectsEnabled) {
-
+        pContext->pBundledContext->NumberEffectsEnabled) {
         // We expect the # effects called to be equal to # effects enabled in sequence (including
         // draining effects).  Warn if this is not the case due to inconsistent calls.
         ALOGW_IF(pContext->pBundledContext->NumberEffectsCalled >
-                pContext->pBundledContext->NumberEffectsEnabled,
-                "%s Number of effects called %d is greater than number of effects enabled %d",
-                __func__, pContext->pBundledContext->NumberEffectsCalled,
-                pContext->pBundledContext->NumberEffectsEnabled);
-        effectProcessCalled = 0; // reset our consistency check.
+                         pContext->pBundledContext->NumberEffectsEnabled,
+                 "%s Number of effects called %d is greater than number of effects enabled %d",
+                 __func__, pContext->pBundledContext->NumberEffectsCalled,
+                 pContext->pBundledContext->NumberEffectsEnabled);
+        effectProcessCalled = 0;  // reset our consistency check.
 
-        //ALOGV("\tEffect_process     Calling process with %d effects enabled, %d called: Effect %d",
-        //pContext->pBundledContext->NumberEffectsEnabled,
-        //pContext->pBundledContext->NumberEffectsCalled, pContext->EffectType);
+        // ALOGV("\tEffect_process     Calling process with %d effects enabled, %d called: Effect
+        // %d", pContext->pBundledContext->NumberEffectsEnabled,
+        // pContext->pBundledContext->NumberEffectsCalled, pContext->EffectType);
 
-        if (status == -ENODATA){
+        if (status == -ENODATA) {
             ALOGV("\tEffect_process() processing last frame");
         }
         pContext->pBundledContext->NumberEffectsCalled = 0;
         /* Process all the available frames, block processing is
            handled internalLY by the LVM bundle */
-        processStatus = android::LvmBundle_process(inBuffer->f32,
-                                                   outBuffer->f32,
-                                                   outBuffer->frameCount,
-                                                   pContext);
-        if (processStatus != 0){
+        processStatus = android::LvmBundle_process(inBuffer->f32, outBuffer->f32,
+                                                   outBuffer->frameCount, pContext);
+        if (processStatus != 0) {
             ALOGV("\tLVM_ERROR : LvmBundle_process returned error %d", processStatus);
             if (status == 0) {
                 status = processStatus;
@@ -3264,133 +3037,126 @@
             return status;
         }
     } else {
-        //ALOGV("\tEffect_process Not Calling process with %d effects enabled, %d called: Effect %d",
-        //pContext->pBundledContext->NumberEffectsEnabled,
-        //pContext->pBundledContext->NumberEffectsCalled, pContext->EffectType);
+        // ALOGV("\tEffect_process Not Calling process with %d effects enabled, %d called: Effect
+        // %d", pContext->pBundledContext->NumberEffectsEnabled,
+        // pContext->pBundledContext->NumberEffectsCalled, pContext->EffectType);
 
         if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
             for (size_t i = 0; i < outBuffer->frameCount * NrChannels; ++i) {
                 outBuffer->f32[i] += inBuffer->f32[i];
             }
         } else if (outBuffer->raw != inBuffer->raw) {
-            memcpy(outBuffer->raw,
-                    inBuffer->raw,
-                    outBuffer->frameCount * sizeof(effect_buffer_t) * FCC_2);
+            memcpy(outBuffer->raw, inBuffer->raw,
+                   outBuffer->frameCount * sizeof(effect_buffer_t) * FCC_2);
         }
     }
 
     return status;
-}   /* end Effect_process */
+} /* end Effect_process */
 
 // The value offset of an effect parameter is computed by rounding up
 // the parameter size to the next 32 bit alignment.
-static inline uint32_t computeParamVOffset(const effect_param_t *p) {
-    return ((p->psize + sizeof(int32_t) - 1) / sizeof(int32_t)) *
-            sizeof(int32_t);
+static inline uint32_t computeParamVOffset(const effect_param_t* p) {
+    return ((p->psize + sizeof(int32_t) - 1) / sizeof(int32_t)) * sizeof(int32_t);
 }
 
 /* Effect Control Interface Implementation: Command */
-int Effect_command(effect_handle_t  self,
-                              uint32_t            cmdCode,
-                              uint32_t            cmdSize,
-                              void                *pCmdData,
-                              uint32_t            *replySize,
-                              void                *pReplyData){
-    EffectContext * pContext = (EffectContext *) self;
+int Effect_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void* pCmdData,
+                   uint32_t* replySize, void* pReplyData) {
+    EffectContext* pContext = (EffectContext*)self;
 
-    //ALOGV("\t\nEffect_command start");
+    // ALOGV("\t\nEffect_command start");
 
-    if(pContext->EffectType == LVM_BASS_BOOST){
-        //ALOGV("\tEffect_command setting command for LVM_BASS_BOOST");
+    if (pContext->EffectType == LVM_BASS_BOOST) {
+        // ALOGV("\tEffect_command setting command for LVM_BASS_BOOST");
     }
-    if(pContext->EffectType == LVM_VIRTUALIZER){
-        //ALOGV("\tEffect_command setting command for LVM_VIRTUALIZER");
+    if (pContext->EffectType == LVM_VIRTUALIZER) {
+        // ALOGV("\tEffect_command setting command for LVM_VIRTUALIZER");
     }
-    if(pContext->EffectType == LVM_EQUALIZER){
-        //ALOGV("\tEffect_command setting command for LVM_EQUALIZER");
+    if (pContext->EffectType == LVM_EQUALIZER) {
+        // ALOGV("\tEffect_command setting command for LVM_EQUALIZER");
     }
-    if(pContext->EffectType == LVM_VOLUME){
-        //ALOGV("\tEffect_command setting command for LVM_VOLUME");
+    if (pContext->EffectType == LVM_VOLUME) {
+        // ALOGV("\tEffect_command setting command for LVM_VOLUME");
     }
 
-    if (pContext == NULL){
+    if (pContext == NULL) {
         ALOGV("\tLVM_ERROR : Effect_command ERROR pContext == NULL");
         return -EINVAL;
     }
 
-    //ALOGV("\tEffect_command INPUTS are: command %d cmdSize %d",cmdCode, cmdSize);
+    // ALOGV("\tEffect_command INPUTS are: command %d cmdSize %d",cmdCode, cmdSize);
 
     // Incase we disable an effect, next time process is
     // called the number of effect called could be greater
     // pContext->pBundledContext->NumberEffectsCalled = 0;
 
-    //ALOGV("\tEffect_command NumberEffectsCalled = %d, NumberEffectsEnabled = %d",
+    // ALOGV("\tEffect_command NumberEffectsCalled = %d, NumberEffectsEnabled = %d",
     //        pContext->pBundledContext->NumberEffectsCalled,
     //        pContext->pBundledContext->NumberEffectsEnabled);
 
-    switch (cmdCode){
+    switch (cmdCode) {
         case EFFECT_CMD_INIT:
-            if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){
+            if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
                 ALOGV("\tLVM_ERROR, EFFECT_CMD_INIT: ERROR for effect type %d",
-                        pContext->EffectType);
+                      pContext->EffectType);
                 return -EINVAL;
             }
-            *(int *) pReplyData = 0;
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT start");
-            if(pContext->EffectType == LVM_BASS_BOOST){
-                //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_BASS_BOOST");
+            *(int*)pReplyData = 0;
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT start");
+            if (pContext->EffectType == LVM_BASS_BOOST) {
+                // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_BASS_BOOST");
                 android::BassSetStrength(pContext, 0);
             }
-            if(pContext->EffectType == LVM_VIRTUALIZER){
-                //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_VIRTUALIZER");
+            if (pContext->EffectType == LVM_VIRTUALIZER) {
+                // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_VIRTUALIZER");
                 android::VirtualizerSetStrength(pContext, 0);
             }
-            if(pContext->EffectType == LVM_EQUALIZER){
-                //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_EQUALIZER");
+            if (pContext->EffectType == LVM_EQUALIZER) {
+                // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_EQUALIZER");
                 android::EqualizerSetPreset(pContext, 0);
             }
-            if(pContext->EffectType == LVM_VOLUME){
-                //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_VOLUME");
-                *(int *) pReplyData = android::VolumeSetVolumeLevel(pContext, 0);
+            if (pContext->EffectType == LVM_VOLUME) {
+                // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_INIT for LVM_VOLUME");
+                *(int*)pReplyData = android::VolumeSetVolumeLevel(pContext, 0);
             }
             break;
 
         case EFFECT_CMD_SET_CONFIG:
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_CONFIG start");
-            if (pCmdData    == NULL || cmdSize     != sizeof(effect_config_t) ||
-                    pReplyData  == NULL || replySize == NULL || *replySize  != sizeof(int)) {
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_CONFIG start");
+            if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL ||
+                replySize == NULL || *replySize != sizeof(int)) {
                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: "
-                        "EFFECT_CMD_SET_CONFIG: ERROR");
+                      "EFFECT_CMD_SET_CONFIG: ERROR");
                 return -EINVAL;
             }
-            *(int *) pReplyData = android::Effect_setConfig(pContext, (effect_config_t *) pCmdData);
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_CONFIG end");
+            *(int*)pReplyData = android::Effect_setConfig(pContext, (effect_config_t*)pCmdData);
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_CONFIG end");
             break;
 
         case EFFECT_CMD_GET_CONFIG:
             if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) {
                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: "
-                        "EFFECT_CMD_GET_CONFIG: ERROR");
+                      "EFFECT_CMD_GET_CONFIG: ERROR");
                 return -EINVAL;
             }
 
-            android::Effect_getConfig(pContext, (effect_config_t *)pReplyData);
+            android::Effect_getConfig(pContext, (effect_config_t*)pReplyData);
             break;
 
         case EFFECT_CMD_RESET:
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_RESET start");
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_RESET start");
             android::Effect_setConfig(pContext, &pContext->config);
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_RESET end");
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_RESET end");
             break;
 
-        case EFFECT_CMD_GET_PARAM:{
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_GET_PARAM start");
+        case EFFECT_CMD_GET_PARAM: {
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_GET_PARAM start");
 
-            effect_param_t *p = (effect_param_t *)pCmdData;
+            effect_param_t* p = (effect_param_t*)pCmdData;
             if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
-                    cmdSize < (sizeof(effect_param_t) + p->psize) ||
-                    pReplyData == NULL || replySize == NULL ||
-                    *replySize < (sizeof(effect_param_t) + p->psize)) {
+                cmdSize < (sizeof(effect_param_t) + p->psize) || pReplyData == NULL ||
+                replySize == NULL || *replySize < (sizeof(effect_param_t) + p->psize)) {
                 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: ERROR");
                 return -EINVAL;
             }
@@ -3401,75 +3167,62 @@
             }
             const uint32_t paddedParamSize = computeParamVOffset(p);
             if ((EFFECT_PARAM_SIZE_MAX - sizeof(effect_param_t) < paddedParamSize) ||
-                (EFFECT_PARAM_SIZE_MAX - sizeof(effect_param_t) - paddedParamSize <
-                    p->vsize)) {
+                (EFFECT_PARAM_SIZE_MAX - sizeof(effect_param_t) - paddedParamSize < p->vsize)) {
                 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: padded_psize or vsize too big");
                 return -EINVAL;
             }
             uint32_t expectedReplySize = sizeof(effect_param_t) + paddedParamSize + p->vsize;
             if (*replySize < expectedReplySize) {
                 ALOGV("\tLVM_ERROR : EFFECT_CMD_GET_PARAM: min. replySize %u, got %u bytes",
-                        expectedReplySize, *replySize);
+                      expectedReplySize, *replySize);
                 android_errorWriteLog(0x534e4554, "32705438");
                 return -EINVAL;
             }
 
             memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
 
-            p = (effect_param_t *)pReplyData;
+            p = (effect_param_t*)pReplyData;
 
             uint32_t voffset = paddedParamSize;
-            if(pContext->EffectType == LVM_BASS_BOOST){
-                p->status = android::BassBoost_getParameter(pContext,
-                                                            p->psize,
-                                                            p->data,
-                                                            &p->vsize,
+            if (pContext->EffectType == LVM_BASS_BOOST) {
+                p->status = android::BassBoost_getParameter(pContext, p->psize, p->data, &p->vsize,
                                                             p->data + voffset);
-                //ALOGV("\tBassBoost_command EFFECT_CMD_GET_PARAM "
+                // ALOGV("\tBassBoost_command EFFECT_CMD_GET_PARAM "
                 //        "*pCmdData %d, *replySize %d, *pReplyData %d ",
                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
                 //        *replySize,
                 //        *(int16_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset));
             }
 
-            if(pContext->EffectType == LVM_VIRTUALIZER){
-                p->status = android::Virtualizer_getParameter(pContext,
-                                                              p->psize,
-                                                              (void *)p->data,
-                                                              &p->vsize,
-                                                              p->data + voffset);
+            if (pContext->EffectType == LVM_VIRTUALIZER) {
+                p->status = android::Virtualizer_getParameter(pContext, p->psize, (void*)p->data,
+                                                              &p->vsize, p->data + voffset);
 
-                //ALOGV("\tVirtualizer_command EFFECT_CMD_GET_PARAM "
+                // ALOGV("\tVirtualizer_command EFFECT_CMD_GET_PARAM "
                 //        "*pCmdData %d, *replySize %d, *pReplyData %d ",
                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
                 //        *replySize,
                 //        *(int16_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset));
             }
-            if(pContext->EffectType == LVM_EQUALIZER){
-                //ALOGV("\tEqualizer_command cmdCode Case: "
+            if (pContext->EffectType == LVM_EQUALIZER) {
+                // ALOGV("\tEqualizer_command cmdCode Case: "
                 //        "EFFECT_CMD_GET_PARAM start");
-                p->status = android::Equalizer_getParameter(pContext,
-                                                            p->psize,
-                                                            p->data,
-                                                            &p->vsize,
+                p->status = android::Equalizer_getParameter(pContext, p->psize, p->data, &p->vsize,
                                                             p->data + voffset);
 
-                //ALOGV("\tEqualizer_command EFFECT_CMD_GET_PARAM *pCmdData %d, *replySize %d, "
+                // ALOGV("\tEqualizer_command EFFECT_CMD_GET_PARAM *pCmdData %d, *replySize %d, "
                 //       "*pReplyData %08x %08x",
                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)), *replySize,
                 //        *(int32_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset),
                 //        *(int32_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset +
                 //        sizeof(int32_t)));
             }
-            if(pContext->EffectType == LVM_VOLUME){
-                //ALOGV("\tVolume_command cmdCode Case: EFFECT_CMD_GET_PARAM start");
-                p->status = android::Volume_getParameter(pContext,
-                                                         p->psize,
-                                                         (void *)p->data,
-                                                         &p->vsize,
-                                                         p->data + voffset);
+            if (pContext->EffectType == LVM_VOLUME) {
+                // ALOGV("\tVolume_command cmdCode Case: EFFECT_CMD_GET_PARAM start");
+                p->status = android::Volume_getParameter(pContext, p->psize, (void*)p->data,
+                                                         &p->vsize, p->data + voffset);
 
-                //ALOGV("\tVolume_command EFFECT_CMD_GET_PARAM "
+                // ALOGV("\tVolume_command EFFECT_CMD_GET_PARAM "
                 //        "*pCmdData %d, *replySize %d, *pReplyData %d ",
                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
                 //        *replySize,
@@ -3477,123 +3230,114 @@
             }
             *replySize = sizeof(effect_param_t) + voffset + p->vsize;
 
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_GET_PARAM end");
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_GET_PARAM end");
         } break;
-        case EFFECT_CMD_SET_PARAM:{
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_PARAM start");
-            if(pContext->EffectType == LVM_BASS_BOOST){
-                //ALOGV("\tBassBoost_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d",
+        case EFFECT_CMD_SET_PARAM: {
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_PARAM start");
+            if (pContext->EffectType == LVM_BASS_BOOST) {
+                // ALOGV("\tBassBoost_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value
+                // %d",
                 //       *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
                 //       *replySize,
                 //       *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) + sizeof(int32_t)));
 
-                if (pCmdData   == NULL ||
-                        cmdSize    != (sizeof(effect_param_t) + sizeof(int32_t) +sizeof(int16_t)) ||
-                        pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
+                if (pCmdData == NULL ||
+                    cmdSize != (sizeof(effect_param_t) + sizeof(int32_t) + sizeof(int16_t)) ||
+                    pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
                     ALOGV("\tLVM_ERROR : BassBoost_command cmdCode Case: "
-                            "EFFECT_CMD_SET_PARAM: ERROR");
+                          "EFFECT_CMD_SET_PARAM: ERROR");
                     return -EINVAL;
                 }
 
-                effect_param_t * const p = (effect_param_t *) pCmdData;
+                effect_param_t* const p = (effect_param_t*)pCmdData;
                 const uint32_t voffset = computeParamVOffset(p);
 
-                //ALOGV("\tnBassBoost_command cmdSize is %d\n"
+                // ALOGV("\tnBassBoost_command cmdSize is %d\n"
                 //        "\tsizeof(effect_param_t) is  %d\n"
                 //        "\tp->psize is %d\n"
                 //        "\tp->vsize is %d"
                 //        "\n",
                 //        cmdSize, sizeof(effect_param_t), p->psize, p->vsize );
 
-                *(int *)pReplyData = android::BassBoost_setParameter(pContext,
-                                                                     p->psize,
-                                                                     (void *)p->data,
-                                                                     p->vsize,
-                                                                     p->data + voffset);
+                *(int*)pReplyData = android::BassBoost_setParameter(
+                        pContext, p->psize, (void*)p->data, p->vsize, p->data + voffset);
             }
-            if(pContext->EffectType == LVM_VIRTUALIZER){
-              // Warning this log will fail to properly read an int32_t value, assumes int16_t
-              //ALOGV("\tVirtualizer_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d",
-              //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
-              //        *replySize,
-              //        *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) + sizeof(int32_t)));
+            if (pContext->EffectType == LVM_VIRTUALIZER) {
+                // Warning this log will fail to properly read an int32_t value, assumes int16_t
+                // ALOGV("\tVirtualizer_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value
+                // %d",
+                //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
+                //        *replySize,
+                //        *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) +
+                //        sizeof(int32_t)));
 
-                if (pCmdData   == NULL ||
-                        // legal parameters are int16_t or int32_t
-                        cmdSize    > (sizeof(effect_param_t) + sizeof(int32_t) +sizeof(int32_t)) ||
-                        cmdSize    < (sizeof(effect_param_t) + sizeof(int32_t) +sizeof(int16_t)) ||
-                        pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
+                if (pCmdData == NULL ||
+                    // legal parameters are int16_t or int32_t
+                    cmdSize > (sizeof(effect_param_t) + sizeof(int32_t) + sizeof(int32_t)) ||
+                    cmdSize < (sizeof(effect_param_t) + sizeof(int32_t) + sizeof(int16_t)) ||
+                    pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
                     ALOGV("\tLVM_ERROR : Virtualizer_command cmdCode Case: "
-                            "EFFECT_CMD_SET_PARAM: ERROR");
+                          "EFFECT_CMD_SET_PARAM: ERROR");
                     return -EINVAL;
                 }
 
-                effect_param_t * const p = (effect_param_t *) pCmdData;
+                effect_param_t* const p = (effect_param_t*)pCmdData;
                 const uint32_t voffset = computeParamVOffset(p);
 
-                //ALOGV("\tnVirtualizer_command cmdSize is %d\n"
+                // ALOGV("\tnVirtualizer_command cmdSize is %d\n"
                 //        "\tsizeof(effect_param_t) is  %d\n"
                 //        "\tp->psize is %d\n"
                 //        "\tp->vsize is %d"
                 //        "\n",
                 //        cmdSize, sizeof(effect_param_t), p->psize, p->vsize );
 
-                *(int *)pReplyData = android::Virtualizer_setParameter(pContext,
-                                                                       p->psize,
-                                                                       (void *)p->data,
-                                                                       p->vsize,
-                                                                       p->data + voffset);
+                *(int*)pReplyData = android::Virtualizer_setParameter(
+                        pContext, p->psize, (void*)p->data, p->vsize, p->data + voffset);
             }
-            if(pContext->EffectType == LVM_EQUALIZER){
-               //ALOGV("\tEqualizer_command cmdCode Case: "
-               //        "EFFECT_CMD_SET_PARAM start");
-               //ALOGV("\tEqualizer_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d ",
-               //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
-               //        *replySize,
-               //        *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) + sizeof(int32_t)));
+            if (pContext->EffectType == LVM_EQUALIZER) {
+                // ALOGV("\tEqualizer_command cmdCode Case: "
+                //        "EFFECT_CMD_SET_PARAM start");
+                // ALOGV("\tEqualizer_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d
+                // ",
+                //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
+                //        *replySize,
+                //        *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) +
+                //        sizeof(int32_t)));
 
                 if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) ||
-                        pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
+                    pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
                     ALOGV("\tLVM_ERROR : Equalizer_command cmdCode Case: "
-                            "EFFECT_CMD_SET_PARAM: ERROR");
+                          "EFFECT_CMD_SET_PARAM: ERROR");
                     return -EINVAL;
                 }
 
-                effect_param_t * const p = (effect_param_t *) pCmdData;
+                effect_param_t* const p = (effect_param_t*)pCmdData;
                 const uint32_t voffset = computeParamVOffset(p);
 
-                *(int *)pReplyData = android::Equalizer_setParameter(pContext,
-                                                                     p->psize,
-                                                                     (void *)p->data,
-                                                                     p->vsize,
-                                                                     p->data + voffset);
+                *(int*)pReplyData = android::Equalizer_setParameter(
+                        pContext, p->psize, (void*)p->data, p->vsize, p->data + voffset);
             }
-            if(pContext->EffectType == LVM_VOLUME){
-                //ALOGV("\tVolume_command cmdCode Case: EFFECT_CMD_SET_PARAM start");
-                //ALOGV("\tVolume_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d ",
+            if (pContext->EffectType == LVM_VOLUME) {
+                // ALOGV("\tVolume_command cmdCode Case: EFFECT_CMD_SET_PARAM start");
+                // ALOGV("\tVolume_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d ",
                 //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
                 //        *replySize,
                 //        *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) +sizeof(int32_t)));
 
-                if (pCmdData   == NULL ||
-                        cmdSize    < (sizeof(effect_param_t) + sizeof(int32_t)) ||
-                        pReplyData == NULL || replySize == NULL ||
-                        *replySize != sizeof(int32_t)) {
+                if (pCmdData == NULL || cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) ||
+                    pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
                     ALOGV("\tLVM_ERROR : Volume_command cmdCode Case: "
-                            "EFFECT_CMD_SET_PARAM: ERROR");
+                          "EFFECT_CMD_SET_PARAM: ERROR");
                     return -EINVAL;
                 }
 
-                effect_param_t * const p = (effect_param_t *) pCmdData;
+                effect_param_t* const p = (effect_param_t*)pCmdData;
                 const uint32_t voffset = computeParamVOffset(p);
 
-                *(int *)pReplyData = android::Volume_setParameter(pContext,
-                                                                  p->psize,
-                                                                  (void *)p->data,
-                                                                  p->vsize,
-                                                                  p->data + voffset);
+                *(int*)pReplyData = android::Volume_setParameter(pContext, p->psize, (void*)p->data,
+                                                                 p->vsize, p->data + voffset);
             }
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_PARAM end");
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_PARAM end");
         } break;
 
         case EFFECT_CMD_ENABLE:
@@ -3603,57 +3347,56 @@
                 return -EINVAL;
             }
 
-            *(int *)pReplyData = android::Effect_setEnabled(pContext, LVM_TRUE);
+            *(int*)pReplyData = android::Effect_setEnabled(pContext, LVM_TRUE);
             break;
 
         case EFFECT_CMD_DISABLE:
-            //ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_DISABLE start");
+            // ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_DISABLE start");
             if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_DISABLE: ERROR");
                 return -EINVAL;
             }
-            *(int *)pReplyData = android::Effect_setEnabled(pContext, LVM_FALSE);
+            *(int*)pReplyData = android::Effect_setEnabled(pContext, LVM_FALSE);
             break;
 
-        case EFFECT_CMD_SET_DEVICE:
-        {
+        case EFFECT_CMD_SET_DEVICE: {
             ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_DEVICE start");
-            if (pCmdData   == NULL){
+            if (pCmdData == NULL) {
                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: EFFECT_CMD_SET_DEVICE: ERROR");
                 return -EINVAL;
             }
 
-            uint32_t device = *(uint32_t *)pCmdData;
-            pContext->pBundledContext->nOutputDevice = (audio_devices_t) device;
+            audio_devices_t device = *(audio_devices_t *)pCmdData;
+            pContext->pBundledContext->nOutputDevice = device;
 
             if (pContext->EffectType == LVM_BASS_BOOST) {
-                if((device == AUDIO_DEVICE_OUT_SPEAKER) ||
-                        (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) ||
-                        (device == AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER)){
+                if ((device == AUDIO_DEVICE_OUT_SPEAKER) ||
+                    (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) ||
+                    (device == AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER)) {
                     ALOGV("\tEFFECT_CMD_SET_DEVICE device is invalid for LVM_BASS_BOOST %d",
-                          *(int32_t *)pCmdData);
+                          *(int32_t*)pCmdData);
                     ALOGV("\tEFFECT_CMD_SET_DEVICE temporary disable LVM_BAS_BOOST");
 
-                    // If a device doesnt support bassboost the effect must be temporarily disabled
+                    // If a device doesn't support bassboost the effect must be temporarily disabled
                     // the effect must still report its original state as this can only be changed
                     // by the ENABLE/DISABLE command
 
                     if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
                         ALOGV("\tEFFECT_CMD_SET_DEVICE disable LVM_BASS_BOOST %d",
-                             *(int32_t *)pCmdData);
+                              *(int32_t*)pCmdData);
                         android::LvmEffect_disable(pContext);
                     }
                     pContext->pBundledContext->bBassTempDisabled = LVM_TRUE;
                 } else {
                     ALOGV("\tEFFECT_CMD_SET_DEVICE device is valid for LVM_BASS_BOOST %d",
-                         *(int32_t *)pCmdData);
+                          *(int32_t*)pCmdData);
 
                     // If a device supports bassboost and the effect has been temporarily disabled
                     // previously then re-enable it
 
                     if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
                         ALOGV("\tEFFECT_CMD_SET_DEVICE re-enable LVM_BASS_BOOST %d",
-                             *(int32_t *)pCmdData);
+                              *(int32_t*)pCmdData);
                         android::LvmEffect_enable(pContext);
                     }
                     pContext->pBundledContext->bBassTempDisabled = LVM_FALSE;
@@ -3664,129 +3407,128 @@
                     // default case unless configuration is forced
                     if (android::VirtualizerIsDeviceSupported(device) != 0) {
                         ALOGV("\tEFFECT_CMD_SET_DEVICE device is invalid for LVM_VIRTUALIZER %d",
-                                *(int32_t *)pCmdData);
+                              *(int32_t*)pCmdData);
                         ALOGV("\tEFFECT_CMD_SET_DEVICE temporary disable LVM_VIRTUALIZER");
 
-                        //If a device doesnt support virtualizer the effect must be temporarily
+                        // If a device doesn't support virtualizer the effect must be temporarily
                         // disabled the effect must still report its original state as this can
                         // only be changed by the ENABLE/DISABLE command
 
                         if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) {
                             ALOGV("\tEFFECT_CMD_SET_DEVICE disable LVM_VIRTUALIZER %d",
-                                    *(int32_t *)pCmdData);
+                                  *(int32_t*)pCmdData);
                             android::LvmEffect_disable(pContext);
                         }
                         pContext->pBundledContext->bVirtualizerTempDisabled = LVM_TRUE;
                     } else {
                         ALOGV("\tEFFECT_CMD_SET_DEVICE device is valid for LVM_VIRTUALIZER %d",
-                                *(int32_t *)pCmdData);
+                              *(int32_t*)pCmdData);
 
                         // If a device supports virtualizer and the effect has been temporarily
                         // disabled previously then re-enable it
 
-                        if(pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE){
+                        if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) {
                             ALOGV("\tEFFECT_CMD_SET_DEVICE re-enable LVM_VIRTUALIZER %d",
-                                    *(int32_t *)pCmdData);
+                                  *(int32_t*)pCmdData);
                             android::LvmEffect_enable(pContext);
                         }
                         pContext->pBundledContext->bVirtualizerTempDisabled = LVM_FALSE;
                     }
-                } // else virtualization mode is forced to a certain device, nothing to do
+                }  // else virtualization mode is forced to a certain device, nothing to do
             }
             ALOGV("\tEffect_command cmdCode Case: EFFECT_CMD_SET_DEVICE end");
             break;
         }
-        case EFFECT_CMD_SET_VOLUME:
-        {
+        case EFFECT_CMD_SET_VOLUME: {
             uint32_t leftVolume, rightVolume;
-            int16_t  leftdB, rightdB;
-            int16_t  maxdB, pandB;
-            int32_t  vol_ret[2] = {1<<24,1<<24}; // Apply no volume
-            LVM_ControlParams_t     ActiveParams;           /* Current control Parameters */
-            LVM_ReturnStatus_en     LvmStatus=LVM_SUCCESS;  /* Function call status */
+            int16_t leftdB, rightdB;
+            int16_t maxdB, pandB;
+            int32_t vol_ret[2] = {1 << 24, 1 << 24};     // Apply no volume
+            LVM_ControlParams_t ActiveParams;            /* Current control Parameters */
+            LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */
 
             // if pReplyData is NULL, VOL_CTRL is delegated to another effect
-            if(pReplyData == LVM_NULL){
+            if (pReplyData == LVM_NULL) {
                 break;
             }
 
             if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t) || pReplyData == NULL ||
-                    replySize == NULL || *replySize < 2*sizeof(int32_t)) {
+                replySize == NULL || *replySize < 2 * sizeof(int32_t)) {
                 ALOGV("\tLVM_ERROR : Effect_command cmdCode Case: "
-                        "EFFECT_CMD_SET_VOLUME: ERROR");
+                      "EFFECT_CMD_SET_VOLUME: ERROR");
                 return -EINVAL;
             }
 
-            leftVolume  = ((*(uint32_t *)pCmdData));
-            rightVolume = ((*((uint32_t *)pCmdData + 1)));
+            leftVolume = ((*(uint32_t*)pCmdData));
+            rightVolume = ((*((uint32_t*)pCmdData + 1)));
 
-            if(leftVolume == 0x1000000){
+            if (leftVolume == 0x1000000) {
                 leftVolume -= 1;
             }
-            if(rightVolume == 0x1000000){
+            if (rightVolume == 0x1000000) {
                 rightVolume -= 1;
             }
 
             // Convert volume to dB
-            leftdB  = android::LVC_Convert_VolToDb(leftVolume);
+            leftdB = android::LVC_Convert_VolToDb(leftVolume);
             rightdB = android::LVC_Convert_VolToDb(rightVolume);
 
             pandB = rightdB - leftdB;
 
             // Calculate max volume in dB
             maxdB = leftdB;
-            if(rightdB > maxdB){
+            if (rightdB > maxdB) {
                 maxdB = rightdB;
             }
-            //ALOGV("\tEFFECT_CMD_SET_VOLUME Session: %d, SessionID: %d VOLUME is %d dB, "
+            // ALOGV("\tEFFECT_CMD_SET_VOLUME Session: %d, SessionID: %d VOLUME is %d dB, "
             //      "effect is %d",
-            //pContext->pBundledContext->SessionNo, pContext->pBundledContext->SessionId,
+            // pContext->pBundledContext->SessionNo, pContext->pBundledContext->SessionId,
             //(int32_t)maxdB, pContext->EffectType);
-            //ALOGV("\tEFFECT_CMD_SET_VOLUME: Left is %d, Right is %d", leftVolume, rightVolume);
-            //ALOGV("\tEFFECT_CMD_SET_VOLUME: Left %ddB, Right %ddB, Position %ddB",
+            // ALOGV("\tEFFECT_CMD_SET_VOLUME: Left is %d, Right is %d", leftVolume, rightVolume);
+            // ALOGV("\tEFFECT_CMD_SET_VOLUME: Left %ddB, Right %ddB, Position %ddB",
             //        leftdB, rightdB, pandB);
 
-            memcpy(pReplyData, vol_ret, sizeof(int32_t)*2);
-            android::VolumeSetVolumeLevel(pContext, (int16_t)(maxdB*100));
+            memcpy(pReplyData, vol_ret, sizeof(int32_t) * 2);
+            android::VolumeSetVolumeLevel(pContext, (int16_t)(maxdB * 100));
 
             /* Get the current settings */
-            LvmStatus =LVM_GetControlParameters(pContext->pBundledContext->hInstance,&ActiveParams);
+            LvmStatus =
+                    LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
             LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeSetStereoPosition")
-            if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+            if (LvmStatus != LVM_SUCCESS) return -EINVAL;
 
             /* Volume parameters */
-            ActiveParams.VC_Balance  = pandB;
-            ALOGV("\t\tVolumeSetStereoPosition() (-96dB -> +96dB)-> %d\n", ActiveParams.VC_Balance );
+            ActiveParams.VC_Balance = pandB;
+            ALOGV("\t\tVolumeSetStereoPosition() (-96dB -> +96dB)-> %d\n", ActiveParams.VC_Balance);
 
             /* Activate the initial settings */
-            LvmStatus =LVM_SetControlParameters(pContext->pBundledContext->hInstance,&ActiveParams);
+            LvmStatus =
+                    LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams);
             LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "VolumeSetStereoPosition")
-            if(LvmStatus != LVM_SUCCESS) return -EINVAL;
+            if (LvmStatus != LVM_SUCCESS) return -EINVAL;
             break;
-         }
+        }
         case EFFECT_CMD_SET_AUDIO_MODE:
             break;
         default:
             return -EINVAL;
     }
 
-    //ALOGV("\tEffect_command end...\n\n");
+    // ALOGV("\tEffect_command end...\n\n");
     return 0;
-}    /* end Effect_command */
+} /* end Effect_command */
 
 /* Effect Control Interface Implementation: get_descriptor */
-int Effect_getDescriptor(effect_handle_t   self,
-                                    effect_descriptor_t *pDescriptor)
-{
-    EffectContext * pContext = (EffectContext *) self;
-    const effect_descriptor_t *desc;
+int Effect_getDescriptor(effect_handle_t self, effect_descriptor_t* pDescriptor) {
+    EffectContext* pContext = (EffectContext*)self;
+    const effect_descriptor_t* desc;
 
     if (pContext == NULL || pDescriptor == NULL) {
         ALOGV("Effect_getDescriptor() invalid param");
         return -EINVAL;
     }
 
-    switch(pContext->EffectType) {
+    switch (pContext->EffectType) {
         case LVM_BASS_BOOST:
             desc = &android::gBassBoostDescriptor;
             break;
@@ -3806,26 +3548,24 @@
     *pDescriptor = *desc;
 
     return 0;
-}   /* end Effect_getDescriptor */
+} /* end Effect_getDescriptor */
 
 // effect_handle_t interface implementation for effect
 const struct effect_interface_s gLvmEffectInterface = {
-    Effect_process,
-    Effect_command,
-    Effect_getDescriptor,
-    NULL,
-};    /* end gLvmEffectInterface */
+        Effect_process,
+        Effect_command,
+        Effect_getDescriptor,
+        NULL,
+}; /* end gLvmEffectInterface */
 
 // This is the only symbol that needs to be exported
-__attribute__ ((visibility ("default")))
-audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM = {
-    .tag = AUDIO_EFFECT_LIBRARY_TAG,
-    .version = EFFECT_LIBRARY_API_VERSION,
-    .name = "Effect Bundle Library",
-    .implementor = "NXP Software Ltd.",
-    .create_effect = android::EffectCreate,
-    .release_effect = android::EffectRelease,
-    .get_descriptor = android::EffectGetDescriptor,
+__attribute__((visibility("default"))) audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM = {
+        .tag = AUDIO_EFFECT_LIBRARY_TAG,
+        .version = EFFECT_LIBRARY_API_VERSION,
+        .name = "Effect Bundle Library",
+        .implementor = "NXP Software Ltd.",
+        .create_effect = android::EffectCreate,
+        .release_effect = android::EffectRelease,
+        .get_descriptor = android::EffectGetDescriptor,
 };
-
 }
diff --git a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h
index 524e103..f3e7884 100644
--- a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h
+++ b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h
@@ -23,176 +23,148 @@
 #include <LVM.h>
 #include <limits.h>
 
-#define FIVEBAND_NUMBANDS          5
-#define MAX_NUM_BANDS              5
-#define MAX_CALL_SIZE              256
-#define LVM_MAX_SESSIONS           32
-#define LVM_UNUSED_SESSION         INT_MAX
-#define BASS_BOOST_CUP_LOAD_ARM9E  150    // Expressed in 0.1 MIPS
-#define VIRTUALIZER_CUP_LOAD_ARM9E 120    // Expressed in 0.1 MIPS
-#define EQUALIZER_CUP_LOAD_ARM9E   220    // Expressed in 0.1 MIPS
-#define VOLUME_CUP_LOAD_ARM9E      0      // Expressed in 0.1 MIPS
-#define BUNDLE_MEM_USAGE           25     // Expressed in kB
+#define FIVEBAND_NUMBANDS 5
+#define MAX_NUM_BANDS 5
+#define MAX_CALL_SIZE 256
+#define LVM_MAX_SESSIONS 32
+#define LVM_UNUSED_SESSION INT_MAX
+#define BASS_BOOST_CUP_LOAD_ARM9E 150   // Expressed in 0.1 MIPS
+#define VIRTUALIZER_CUP_LOAD_ARM9E 120  // Expressed in 0.1 MIPS
+#define EQUALIZER_CUP_LOAD_ARM9E 220    // Expressed in 0.1 MIPS
+#define VOLUME_CUP_LOAD_ARM9E 0         // Expressed in 0.1 MIPS
+#define BUNDLE_MEM_USAGE 25             // Expressed in kB
 
 #ifndef OPENSL_ES_H_
-static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
-                                            { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
-const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
-#endif //OPENSL_ES_H_
+static const effect_uuid_t SL_IID_VOLUME_ = {
+        0x09e8ede0, 0xddde, 0x11db, 0xb4f6, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
+const effect_uuid_t* const SL_IID_VOLUME = &SL_IID_VOLUME_;
+#endif  // OPENSL_ES_H_
 
-typedef enum
-{
-    LVM_BASS_BOOST,
-    LVM_VIRTUALIZER,
-    LVM_EQUALIZER,
-    LVM_VOLUME
-} lvm_effect_en;
+typedef enum { LVM_BASS_BOOST, LVM_VIRTUALIZER, LVM_EQUALIZER, LVM_VOLUME } lvm_effect_en;
 
 // Preset configuration.
 struct PresetConfig {
     // Human-readable name.
-    const char * name;
+    const char* name;
     // An array of size nBands where each element is a configuration for the
     // corresponding band.
-    //const BandConfig * bandConfigs;
+    // const BandConfig * bandConfigs;
 };
 
 /* BundledEffectContext : One per session */
-struct BundledEffectContext{
-    LVM_Handle_t                    hInstance;                /* Instance handle */
-    int                             SessionNo;                /* Current session number */
-    int                             SessionId;                /* Current session id */
-    bool                            bVolumeEnabled;           /* Flag for Volume */
-    bool                            bEqualizerEnabled;        /* Flag for EQ */
-    bool                            bBassEnabled;             /* Flag for Bass */
-    bool                            bBassTempDisabled;        /* Flag for Bass to be re-enabled */
-    bool                            bVirtualizerEnabled;      /* Flag for Virtualizer */
-    bool                            bVirtualizerTempDisabled; /* Flag for effect to be re-enabled */
-    audio_devices_t                 nOutputDevice;            /* Output device for the effect */
-    audio_devices_t                 nVirtualizerForcedDevice; /* Forced device virtualization mode*/
-    int                             NumberEffectsEnabled;     /* Effects in this session */
-    int                             NumberEffectsCalled;      /* Effects called so far */
-    bool                            firstVolume;              /* No smoothing on first Vol change */
+struct BundledEffectContext {
+    LVM_Handle_t hInstance;                   /* Instance handle */
+    int SessionNo;                            /* Current session number */
+    int SessionId;                            /* Current session id */
+    bool bVolumeEnabled;                      /* Flag for Volume */
+    bool bEqualizerEnabled;                   /* Flag for EQ */
+    bool bBassEnabled;                        /* Flag for Bass */
+    bool bBassTempDisabled;                   /* Flag for Bass to be re-enabled */
+    bool bVirtualizerEnabled;                 /* Flag for Virtualizer */
+    bool bVirtualizerTempDisabled;            /* Flag for effect to be re-enabled */
+    audio_devices_t nOutputDevice;            /* Output device for the effect */
+    audio_devices_t nVirtualizerForcedDevice; /* Forced device virtualization mode*/
+    int NumberEffectsEnabled;                 /* Effects in this session */
+    int NumberEffectsCalled;                  /* Effects called so far */
+    bool firstVolume;                         /* No smoothing on first Vol change */
     // Saved parameters for each effect */
     // Bass Boost
-    int                             BassStrengthSaved;        /* Conversion between Get/Set */
+    int BassStrengthSaved; /* Conversion between Get/Set */
     // Equalizer
-    int                             CurPreset;                /* Current preset being used */
+    int CurPreset; /* Current preset being used */
     // Virtualzer
-    int                             VirtStrengthSaved;        /* Conversion between Get/Set */
+    int VirtStrengthSaved; /* Conversion between Get/Set */
     // Volume
-    int                             levelSaved;     /* for when mute is set, level must be saved */
-    int                             positionSaved;
-    bool                            bMuteEnabled;   /* Must store as mute = -96dB level */
-    bool                            bStereoPositionEnabled;
-    LVM_Fs_en                       SampleRate;
-    int                             SamplesPerSecond;
-    int                             SamplesToExitCountEq;
-    int                             SamplesToExitCountBb;
-    int                             SamplesToExitCountVirt;
-    effect_buffer_t                 *workBuffer;
-    int                             frameCount;
-    int32_t                         bandGaindB[FIVEBAND_NUMBANDS];
-    int                             volume;
-#ifdef SUPPORT_MC
-    LVM_INT32                       ChMask;
-#endif
+    int levelSaved; /* for when mute is set, level must be saved */
+    int positionSaved;
+    bool bMuteEnabled; /* Must store as mute = -96dB level */
+    bool bStereoPositionEnabled;
+    LVM_Fs_en SampleRate;
+    int SamplesPerSecond;
+    int SamplesToExitCountEq;
+    int SamplesToExitCountBb;
+    int SamplesToExitCountVirt;
+    effect_buffer_t* workBuffer;
+    int frameCount;
+    int32_t bandGaindB[FIVEBAND_NUMBANDS];
+    int volume;
+    LVM_INT32 ChMask;
 
     /* Bitmask whether drain is in progress due to disabling the effect.
        The corresponding bit to an effect is set by 1 << lvm_effect_en. */
-    int                             effectInDrain;
+    int effectInDrain;
 
     /* Bitmask whether process() was called for a particular effect.
        The corresponding bit to an effect is set by 1 << lvm_effect_en. */
-    int                             effectProcessCalled;
+    int effectProcessCalled;
 };
 
 /* SessionContext : One session */
-struct SessionContext{
-    bool                            bBundledEffectsEnabled;
-    bool                            bVolumeInstantiated;
-    bool                            bEqualizerInstantiated;
-    bool                            bBassInstantiated;
-    bool                            bVirtualizerInstantiated;
-    BundledEffectContext            *pBundledContext;
+struct SessionContext {
+    bool bBundledEffectsEnabled;
+    bool bVolumeInstantiated;
+    bool bEqualizerInstantiated;
+    bool bBassInstantiated;
+    bool bVirtualizerInstantiated;
+    BundledEffectContext* pBundledContext;
 };
 
-struct EffectContext{
-    const struct effect_interface_s *itfe;
-    effect_config_t                 config;
-    lvm_effect_en                   EffectType;
-    BundledEffectContext            *pBundledContext;
+struct EffectContext {
+    const struct effect_interface_s* itfe;
+    effect_config_t config;
+    lvm_effect_en EffectType;
+    BundledEffectContext* pBundledContext;
 };
 
 /* enumerated parameter settings for Volume effect */
-typedef enum
-{
-    VOLUME_PARAM_LEVEL,                       // type SLmillibel = typedef SLuint16 (set & get)
-    VOLUME_PARAM_MAXLEVEL,                    // type SLmillibel = typedef SLuint16 (get)
-    VOLUME_PARAM_MUTE,                        // type SLboolean  = typedef SLuint32 (set & get)
-    VOLUME_PARAM_ENABLESTEREOPOSITION,        // type SLboolean  = typedef SLuint32 (set & get)
-    VOLUME_PARAM_STEREOPOSITION,              // type SLpermille = typedef SLuint16 (set & get)
+typedef enum {
+    VOLUME_PARAM_LEVEL,                 // type SLmillibel = typedef SLuint16 (set & get)
+    VOLUME_PARAM_MAXLEVEL,              // type SLmillibel = typedef SLuint16 (get)
+    VOLUME_PARAM_MUTE,                  // type SLboolean  = typedef SLuint32 (set & get)
+    VOLUME_PARAM_ENABLESTEREOPOSITION,  // type SLboolean  = typedef SLuint32 (set & get)
+    VOLUME_PARAM_STEREOPOSITION,        // type SLpermille = typedef SLuint16 (set & get)
 } t_volume_params;
 
 static const int PRESET_CUSTOM = -1;
 
-static const uint32_t bandFreqRange[FIVEBAND_NUMBANDS][2] = {
-                                       {30000, 120000},
-                                       {120001, 460000},
-                                       {460001, 1800000},
-                                       {1800001, 7000000},
-                                       {7000001, 20000000}};
+static const uint32_t bandFreqRange[FIVEBAND_NUMBANDS][2] = {{30000, 120000},
+                                                             {120001, 460000},
+                                                             {460001, 1800000},
+                                                             {1800001, 7000000},
+                                                             {7000001, 20000000}};
 
-//Note: If these frequencies change, please update LimitLevel values accordingly.
-static const LVM_UINT16  EQNB_5BandPresetsFrequencies[] = {
-                                       60,           /* Frequencies in Hz */
-                                       230,
-                                       910,
-                                       3600,
-                                       14000};
+// Note: If these frequencies change, please update LimitLevel values accordingly.
+static const LVM_UINT16 EQNB_5BandPresetsFrequencies[] = {60, /* Frequencies in Hz */
+                                                          230, 910, 3600, 14000};
 
-static const LVM_UINT16 EQNB_5BandPresetsQFactors[] = {
-                                       96,               /* Q factor multiplied by 100 */
-                                       96,
-                                       96,
-                                       96,
-                                       96};
+static const LVM_UINT16 EQNB_5BandPresetsQFactors[] = {96, /* Q factor multiplied by 100 */
+                                                       96, 96, 96, 96};
 
-static const LVM_INT16 EQNB_5BandNormalPresets[] = {
-                                       3, 0, 0, 0, 3,       /* Normal Preset */
-                                       8, 5, -3, 5, 6,      /* Classical Preset */
-                                       15, -6, 7, 13, 10,   /* Dance Preset */
-                                       0, 0, 0, 0, 0,       /* Flat Preset */
-                                       6, -2, -2, 6, -3,    /* Folk Preset */
-                                       8, -8, 13, -1, -4,   /* Heavy Metal Preset */
-                                       10, 6, -4, 5, 8,     /* Hip Hop Preset */
-                                       8, 5, -4, 5, 9,      /* Jazz Preset */
-                                      -6, 4, 9, 4, -5,      /* Pop Preset */
-                                       10, 6, -1, 8, 10};   /* Rock Preset */
+static const LVM_INT16 EQNB_5BandNormalPresets[] = {3,  0,  0,  0,  3,   /* Normal Preset */
+                                                    8,  5,  -3, 5,  6,   /* Classical Preset */
+                                                    15, -6, 7,  13, 10,  /* Dance Preset */
+                                                    0,  0,  0,  0,  0,   /* Flat Preset */
+                                                    6,  -2, -2, 6,  -3,  /* Folk Preset */
+                                                    8,  -8, 13, -1, -4,  /* Heavy Metal Preset */
+                                                    10, 6,  -4, 5,  8,   /* Hip Hop Preset */
+                                                    8,  5,  -4, 5,  9,   /* Jazz Preset */
+                                                    -6, 4,  9,  4,  -5,  /* Pop Preset */
+                                                    10, 6,  -1, 8,  10}; /* Rock Preset */
 
-static const LVM_INT16 EQNB_5BandSoftPresets[] = {
-                                        3, 0, 0, 0, 3,      /* Normal Preset */
-                                        5, 3, -2, 4, 4,     /* Classical Preset */
-                                        6, 0, 2, 4, 1,      /* Dance Preset */
-                                        0, 0, 0, 0, 0,      /* Flat Preset */
-                                        3, 0, 0, 2, -1,     /* Folk Preset */
-                                        4, 1, 9, 3, 0,      /* Heavy Metal Preset */
-                                        5, 3, 0, 1, 3,      /* Hip Hop Preset */
-                                        4, 2, -2, 2, 5,     /* Jazz Preset */
-                                       -1, 2, 5, 1, -2,     /* Pop Preset */
-                                        5, 3, -1, 3, 5};    /* Rock Preset */
+static const LVM_INT16 EQNB_5BandSoftPresets[] = {3,  0, 0,  0, 3,  /* Normal Preset */
+                                                  5,  3, -2, 4, 4,  /* Classical Preset */
+                                                  6,  0, 2,  4, 1,  /* Dance Preset */
+                                                  0,  0, 0,  0, 0,  /* Flat Preset */
+                                                  3,  0, 0,  2, -1, /* Folk Preset */
+                                                  4,  1, 9,  3, 0,  /* Heavy Metal Preset */
+                                                  5,  3, 0,  1, 3,  /* Hip Hop Preset */
+                                                  4,  2, -2, 2, 5,  /* Jazz Preset */
+                                                  -1, 2, 5,  1, -2, /* Pop Preset */
+                                                  5,  3, -1, 3, 5}; /* Rock Preset */
 
-static const PresetConfig gEqualizerPresets[] = {
-                                        {"Normal"},
-                                        {"Classical"},
-                                        {"Dance"},
-                                        {"Flat"},
-                                        {"Folk"},
-                                        {"Heavy Metal"},
-                                        {"Hip Hop"},
-                                        {"Jazz"},
-                                        {"Pop"},
-                                        {"Rock"}};
+static const PresetConfig gEqualizerPresets[] = {{"Normal"}, {"Classical"},   {"Dance"},   {"Flat"},
+                                                 {"Folk"},   {"Heavy Metal"}, {"Hip Hop"}, {"Jazz"},
+                                                 {"Pop"},    {"Rock"}};
 
 /* The following tables have been computed using the actual levels measured by the output of
  * white noise or pink noise (IEC268-1) for the EQ and BassBoost Effects. These are estimates of
@@ -201,14 +173,14 @@
  * updated.
  */
 
-static const float LimitLevel_bandEnergyCoefficient[FIVEBAND_NUMBANDS] = {
-        7.56, 9.69, 9.59, 7.37, 2.88};
+static const float LimitLevel_bandEnergyCoefficient[FIVEBAND_NUMBANDS] = {7.56, 9.69, 9.59, 7.37,
+                                                                          2.88};
 
-static const float LimitLevel_bandEnergyCrossCoefficient[FIVEBAND_NUMBANDS-1] = {
-        126.0, 115.0, 125.0, 104.0 };
+static const float LimitLevel_bandEnergyCrossCoefficient[FIVEBAND_NUMBANDS - 1] = {126.0, 115.0,
+                                                                                   125.0, 104.0};
 
 static const float LimitLevel_bassBoostEnergyCrossCoefficient[FIVEBAND_NUMBANDS] = {
-        221.21, 208.10, 28.16, 0.0, 0.0 };
+        221.21, 208.10, 28.16, 0.0, 0.0};
 
 static const float LimitLevel_bassBoostEnergyCoefficient = 9.00;
 
diff --git a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
index 39f5bb6..3738d62 100644
--- a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
+++ b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.cpp
@@ -18,7 +18,7 @@
 typedef float LVM_FLOAT;
 #endif
 #define LOG_TAG "Reverb"
-#define ARRAY_SIZE(array) (sizeof (array) / sizeof (array)[0])
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array)[0])
 //#define LOG_NDEBUG 0
 
 #include <assert.h>
@@ -33,23 +33,28 @@
 #include "EffectReverb.h"
 // from Reverb/lib
 #include "LVREV.h"
+#include "VectorArithmetic.h"
 
 // effect_handle_t interface implementation for reverb
 extern "C" const struct effect_interface_s gReverbInterface;
 
-#define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc){\
-        if ((LvmStatus) == LVREV_NULLADDRESS){\
-            ALOGV("\tLVREV_ERROR : Parameter error - "\
-                    "null pointer returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
-        }\
-        if ((LvmStatus) == LVREV_INVALIDNUMSAMPLES){\
-            ALOGV("\tLVREV_ERROR : Parameter error - "\
-                    "bad number of samples returned by %s in %s\n\n\n\n", callingFunc, calledFunc);\
-        }\
-        if ((LvmStatus) == LVREV_OUTOFRANGE){\
-            ALOGV("\tLVREV_ERROR : Parameter error - "\
-                    "out of range returned by %s in %s\n", callingFunc, calledFunc);\
-        }\
+#define LVM_ERROR_CHECK(LvmStatus, callingFunc, calledFunc)             \
+    {                                                                   \
+        if ((LvmStatus) == LVREV_NULLADDRESS) {                         \
+            ALOGV("\tLVREV_ERROR : Parameter error - "                  \
+                  "null pointer returned by %s in %s\n\n\n\n",          \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
+        if ((LvmStatus) == LVREV_INVALIDNUMSAMPLES) {                   \
+            ALOGV("\tLVREV_ERROR : Parameter error - "                  \
+                  "bad number of samples returned by %s in %s\n\n\n\n", \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
+        if ((LvmStatus) == LVREV_OUTOFRANGE) {                          \
+            ALOGV("\tLVREV_ERROR : Parameter error - "                  \
+                  "out of range returned by %s in %s\n",                \
+                  callingFunc, calledFunc);                             \
+        }                                                               \
     }
 
 // Namespaces
@@ -81,8 +86,8 @@
 
 // NXP SW auxiliary environmental reverb
 const effect_descriptor_t gAuxEnvReverbDescriptor = {
-        { 0xc2e5d5f0, 0x94bd, 0x4763, 0x9cac, { 0x4e, 0x23, 0x4d, 0x06, 0x83, 0x9e } },
-        { 0x4a387fc0, 0x8ab3, 0x11df, 0x8bad, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } },
+        {0xc2e5d5f0, 0x94bd, 0x4763, 0x9cac, {0x4e, 0x23, 0x4d, 0x06, 0x83, 0x9e}},
+        {0x4a387fc0, 0x8ab3, 0x11df, 0x8bad, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
         EFFECT_CONTROL_API_VERSION,
         EFFECT_FLAG_TYPE_AUXILIARY,
         LVREV_CUP_LOAD_ARM9E,
@@ -128,42 +133,39 @@
 };
 
 // gDescriptors contains pointers to all defined effect descriptor in this library
-static const effect_descriptor_t * const gDescriptors[] = {
-        &gAuxEnvReverbDescriptor,
-        &gInsertEnvReverbDescriptor,
-        &gAuxPresetReverbDescriptor,
-        &gInsertPresetReverbDescriptor
-};
+static const effect_descriptor_t* const gDescriptors[] = {
+        &gAuxEnvReverbDescriptor, &gInsertEnvReverbDescriptor, &gAuxPresetReverbDescriptor,
+        &gInsertPresetReverbDescriptor};
 
-typedef     float               process_buffer_t; // process in float
+typedef float process_buffer_t;  // process in float
 
-struct ReverbContext{
-    const struct effect_interface_s *itfe;
-    effect_config_t                 config;
-    LVREV_Handle_t                  hInstance;
-    int16_t                         SavedRoomLevel;
-    int16_t                         SavedHfLevel;
-    int16_t                         SavedDecayTime;
-    int16_t                         SavedDecayHfRatio;
-    int16_t                         SavedReverbLevel;
-    int16_t                         SavedDiffusion;
-    int16_t                         SavedDensity;
-    bool                            bEnabled;
-    LVM_Fs_en                       SampleRate;
-    process_buffer_t                *InFrames;
-    process_buffer_t                *OutFrames;
-    size_t                          bufferSizeIn;
-    size_t                          bufferSizeOut;
-    bool                            auxiliary;
-    bool                            preset;
-    uint16_t                        curPreset;
-    uint16_t                        nextPreset;
-    int                             SamplesToExitCount;
-    LVM_INT16                       leftVolume;
-    LVM_INT16                       rightVolume;
-    LVM_INT16                       prevLeftVolume;
-    LVM_INT16                       prevRightVolume;
-    int                             volumeMode;
+struct ReverbContext {
+    const struct effect_interface_s* itfe;
+    effect_config_t config;
+    LVREV_Handle_t hInstance;
+    int16_t SavedRoomLevel;
+    int16_t SavedHfLevel;
+    int16_t SavedDecayTime;
+    int16_t SavedDecayHfRatio;
+    int16_t SavedReverbLevel;
+    int16_t SavedDiffusion;
+    int16_t SavedDensity;
+    bool bEnabled;
+    LVM_Fs_en SampleRate;
+    process_buffer_t* InFrames;
+    process_buffer_t* OutFrames;
+    size_t bufferSizeIn;
+    size_t bufferSizeOut;
+    bool auxiliary;
+    bool preset;
+    uint16_t curPreset;
+    uint16_t nextPreset;
+    int SamplesToExitCount;
+    LVM_INT16 leftVolume;
+    LVM_INT16 rightVolume;
+    LVM_INT16 prevLeftVolume;
+    LVM_INT16 prevRightVolume;
+    int volumeMode;
 };
 
 enum {
@@ -174,44 +176,38 @@
 
 #define REVERB_DEFAULT_PRESET REVERB_PRESET_NONE
 
-#define REVERB_SEND_LEVEL   0.75f // 0.75 in 4.12 format
-#define REVERB_UNIT_VOLUME  (0x1000) // 1.0 in 4.12 format
+#define REVERB_SEND_LEVEL 0.75f      // 0.75 in 4.12 format
+#define REVERB_UNIT_VOLUME (0x1000)  // 1.0 in 4.12 format
 
 //--- local function prototypes
-int  Reverb_init            (ReverbContext *pContext);
-void Reverb_free            (ReverbContext *pContext);
-int  Reverb_setConfig       (ReverbContext *pContext, effect_config_t *pConfig);
-void Reverb_getConfig       (ReverbContext *pContext, effect_config_t *pConfig);
-int  Reverb_setParameter    (ReverbContext *pContext, void *pParam, void *pValue, int vsize);
-int  Reverb_getParameter    (ReverbContext *pContext,
-                             void          *pParam,
-                             uint32_t      *pValueSize,
-                             void          *pValue);
-int Reverb_LoadPreset       (ReverbContext   *pContext);
-int Reverb_paramValueSize   (int32_t param);
+int Reverb_init(ReverbContext* pContext);
+void Reverb_free(ReverbContext* pContext);
+int Reverb_setConfig(ReverbContext* pContext, effect_config_t* pConfig);
+void Reverb_getConfig(ReverbContext* pContext, effect_config_t* pConfig);
+int Reverb_setParameter(ReverbContext* pContext, void* pParam, void* pValue, int vsize);
+int Reverb_getParameter(ReverbContext* pContext, void* pParam, uint32_t* pValueSize, void* pValue);
+int Reverb_LoadPreset(ReverbContext* pContext);
+int Reverb_paramValueSize(int32_t param);
 
 /* Effect Library Interface Implementation */
 
-extern "C" int EffectCreate(const effect_uuid_t *uuid,
-                            int32_t             sessionId __unused,
-                            int32_t             ioId __unused,
-                            effect_handle_t  *pHandle){
+extern "C" int EffectCreate(const effect_uuid_t* uuid, int32_t /* sessionId __unused */,
+                            int32_t /* ioId __unused */, effect_handle_t* pHandle) {
     int ret;
     int i;
-    int length = sizeof(gDescriptors) / sizeof(const effect_descriptor_t *);
-    const effect_descriptor_t *desc;
+    int length = sizeof(gDescriptors) / sizeof(const effect_descriptor_t*);
+    const effect_descriptor_t* desc;
 
     ALOGV("\t\nEffectCreate start");
 
-    if (pHandle == NULL || uuid == NULL){
+    if (pHandle == NULL || uuid == NULL) {
         ALOGV("\tLVM_ERROR : EffectCreate() called with NULL pointer");
         return -EINVAL;
     }
 
     for (i = 0; i < length; i++) {
         desc = gDescriptors[i];
-        if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t))
-                == 0) {
+        if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) {
             ALOGV("\tEffectCreate - UUID matched Reverb type %d, UUID = %x", i, desc->uuid.timeLow);
             break;
         }
@@ -221,16 +217,16 @@
         return -ENOENT;
     }
 
-    ReverbContext *pContext = new ReverbContext;
+    ReverbContext* pContext = new ReverbContext;
 
-    pContext->itfe      = &gReverbInterface;
+    pContext->itfe = &gReverbInterface;
     pContext->hInstance = NULL;
 
     pContext->auxiliary = false;
-    if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY){
+    if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
         pContext->auxiliary = true;
         ALOGV("\tEffectCreate - AUX");
-    }else{
+    } else {
         ALOGV("\tEffectCreate - INS");
     }
 
@@ -241,14 +237,14 @@
         pContext->curPreset = REVERB_PRESET_LAST + 1;
         pContext->nextPreset = REVERB_DEFAULT_PRESET;
         ALOGV("\tEffectCreate - PRESET");
-    }else{
+    } else {
         ALOGV("\tEffectCreate - ENVIRONMENTAL");
     }
 
     ALOGV("\tEffectCreate - Calling Reverb_init");
     ret = Reverb_init(pContext);
 
-    if (ret < 0){
+    if (ret < 0) {
         ALOGV("\tLVM_ERROR : EffectCreate() init failed");
         delete pContext;
         return ret;
@@ -256,25 +252,25 @@
 
     *pHandle = (effect_handle_t)pContext;
 
-
     int channels = audio_channel_count_from_out_mask(pContext->config.inputCfg.channels);
 
+    channels = (pContext->auxiliary == true) ? channels : FCC_2;
     // Allocate memory for reverb process (*2 is for STEREO)
     pContext->bufferSizeIn = LVREV_MAX_FRAME_SIZE * sizeof(process_buffer_t) * channels;
     pContext->bufferSizeOut = LVREV_MAX_FRAME_SIZE * sizeof(process_buffer_t) * FCC_2;
-    pContext->InFrames  = (process_buffer_t *)calloc(pContext->bufferSizeIn, 1 /* size */);
-    pContext->OutFrames = (process_buffer_t *)calloc(pContext->bufferSizeOut, 1 /* size */);
+    pContext->InFrames = (process_buffer_t*)calloc(pContext->bufferSizeIn, 1 /* size */);
+    pContext->OutFrames = (process_buffer_t*)calloc(pContext->bufferSizeOut, 1 /* size */);
 
     ALOGV("\tEffectCreate %p, size %zu", pContext, sizeof(ReverbContext));
     ALOGV("\tEffectCreate end\n");
     return 0;
 } /* end EffectCreate */
 
-extern "C" int EffectRelease(effect_handle_t handle){
-    ReverbContext * pContext = (ReverbContext *)handle;
+extern "C" int EffectRelease(effect_handle_t handle) {
+    ReverbContext* pContext = (ReverbContext*)handle;
 
     ALOGV("\tEffectRelease %p", handle);
-    if (pContext == NULL){
+    if (pContext == NULL) {
         ALOGV("\tLVM_ERROR : EffectRelease called with NULL pointer");
         return -EINVAL;
     }
@@ -288,12 +284,11 @@
     return 0;
 } /* end EffectRelease */
 
-extern "C" int EffectGetDescriptor(const effect_uuid_t *uuid,
-                                   effect_descriptor_t *pDescriptor) {
+extern "C" int EffectGetDescriptor(const effect_uuid_t* uuid, effect_descriptor_t* pDescriptor) {
     int i;
-    int length = sizeof(gDescriptors) / sizeof(const effect_descriptor_t *);
+    int length = sizeof(gDescriptors) / sizeof(const effect_descriptor_t*);
 
-    if (pDescriptor == NULL || uuid == NULL){
+    if (pDescriptor == NULL || uuid == NULL) {
         ALOGV("EffectGetDescriptor() called with NULL pointer");
         return -EINVAL;
     }
@@ -301,8 +296,8 @@
     for (i = 0; i < length; i++) {
         if (memcmp(uuid, &gDescriptors[i]->uuid, sizeof(effect_uuid_t)) == 0) {
             *pDescriptor = *gDescriptors[i];
-            ALOGV("EffectGetDescriptor - UUID matched Reverb type %d, UUID = %x",
-                 i, gDescriptors[i]->uuid.timeLow);
+            ALOGV("EffectGetDescriptor - UUID matched Reverb type %d, UUID = %x", i,
+                  gDescriptors[i]->uuid.timeLow);
             return 0;
         }
     }
@@ -311,12 +306,13 @@
 } /* end EffectGetDescriptor */
 
 /* local functions */
-#define CHECK_ARG(cond) {                     \
-    if (!(cond)) {                            \
-        ALOGV("\tLVM_ERROR : Invalid argument: "#cond);      \
-        return -EINVAL;                       \
-    }                                         \
-}
+#define CHECK_ARG(cond)                                      \
+    {                                                        \
+        if (!(cond)) {                                       \
+            ALOGV("\tLVM_ERROR : Invalid argument: " #cond); \
+            return -EINVAL;                                  \
+        }                                                    \
+    }
 
 //----------------------------------------------------------------------------
 // process()
@@ -335,91 +331,101 @@
 //  pOut:       pointer to updated stereo 16 bit output data
 //
 //----------------------------------------------------------------------------
-int process( effect_buffer_t   *pIn,
-             effect_buffer_t   *pOut,
-             int           frameCount,
-             ReverbContext *pContext){
-
+int process(effect_buffer_t* pIn, effect_buffer_t* pOut, int frameCount, ReverbContext* pContext) {
     int channels = audio_channel_count_from_out_mask(pContext->config.inputCfg.channels);
-    LVREV_ReturnStatus_en   LvmStatus = LVREV_SUCCESS;              /* Function call status */
+    int outChannels = audio_channel_count_from_out_mask(pContext->config.outputCfg.channels);
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
-    // Check that the input is either mono or stereo
-    if (!(channels == 1 || channels == FCC_2) ) {
-        ALOGE("\tLVREV_ERROR : process invalid PCM format");
+    // Reverb only effects the stereo channels in multichannel source.
+    if (channels < 1 || channels > LVM_MAX_CHANNELS) {
+        ALOGE("\tLVREV_ERROR : process invalid PCM channels %d", channels);
         return -EINVAL;
     }
 
     size_t inSize = frameCount * sizeof(process_buffer_t) * channels;
     size_t outSize = frameCount * sizeof(process_buffer_t) * FCC_2;
-    if (pContext->InFrames == NULL ||
-            pContext->bufferSizeIn < inSize) {
+    if (pContext->InFrames == NULL || pContext->bufferSizeIn < inSize) {
         free(pContext->InFrames);
         pContext->bufferSizeIn = inSize;
-        pContext->InFrames = (process_buffer_t *)calloc(1, pContext->bufferSizeIn);
+        pContext->InFrames = (process_buffer_t*)calloc(1, pContext->bufferSizeIn);
     }
-    if (pContext->OutFrames == NULL ||
-            pContext->bufferSizeOut < outSize) {
+    if (pContext->OutFrames == NULL || pContext->bufferSizeOut < outSize) {
         free(pContext->OutFrames);
         pContext->bufferSizeOut = outSize;
-        pContext->OutFrames = (process_buffer_t *)calloc(1, pContext->bufferSizeOut);
+        pContext->OutFrames = (process_buffer_t*)calloc(1, pContext->bufferSizeOut);
     }
 
-
     // Check for NULL pointers
     if ((pContext->InFrames == NULL) || (pContext->OutFrames == NULL)) {
         ALOGE("\tLVREV_ERROR : process failed to allocate memory for temporary buffers ");
         return -EINVAL;
     }
 
-
     if (pContext->preset && pContext->nextPreset != pContext->curPreset) {
         Reverb_LoadPreset(pContext);
     }
 
     if (pContext->auxiliary) {
         static_assert(std::is_same<decltype(*pIn), decltype(*pContext->InFrames)>::value,
-                "pIn and InFrames must be same type");
+                      "pIn and InFrames must be same type");
         memcpy(pContext->InFrames, pIn, frameCount * channels * sizeof(*pIn));
+    } else {
+        // mono input is duplicated
+        if (channels >= FCC_2) {
+            for (int i = 0; i < frameCount; i++) {
+                pContext->InFrames[FCC_2 * i] =
+                        (process_buffer_t)pIn[channels * i] * REVERB_SEND_LEVEL;
+                pContext->InFrames[FCC_2 * i + 1] =
+                        (process_buffer_t)pIn[channels * i + 1] * REVERB_SEND_LEVEL;
+            }
         } else {
-        // insert reverb input is always stereo
-        for (int i = 0; i < frameCount; i++) {
-            pContext->InFrames[2 * i] = (process_buffer_t)pIn[2 * i] * REVERB_SEND_LEVEL;
-            pContext->InFrames[2 * i + 1] = (process_buffer_t)pIn[2 * i + 1] * REVERB_SEND_LEVEL;
+            for (int i = 0; i < frameCount; i++) {
+                pContext->InFrames[FCC_2 * i] = pContext->InFrames[FCC_2 * i + 1] =
+                        (process_buffer_t)pIn[i] * REVERB_SEND_LEVEL;
+            }
         }
     }
 
     if (pContext->preset && pContext->curPreset == REVERB_PRESET_NONE) {
         memset(pContext->OutFrames, 0,
-                frameCount * sizeof(*pContext->OutFrames) * FCC_2); //always stereo here
+               frameCount * sizeof(*pContext->OutFrames) * FCC_2);  // always stereo here
     } else {
-        if(pContext->bEnabled == LVM_FALSE && pContext->SamplesToExitCount > 0) {
-            memset(pContext->InFrames, 0,
-                    frameCount * sizeof(*pContext->OutFrames) * channels);
+        if (pContext->bEnabled == LVM_FALSE && pContext->SamplesToExitCount > 0) {
+            memset(pContext->InFrames, 0, frameCount * sizeof(*pContext->OutFrames) * channels);
             ALOGV("\tZeroing %d samples per frame at the end of call", channels);
         }
 
         /* Process the samples, producing a stereo output */
-        LvmStatus = LVREV_Process(pContext->hInstance,      /* Instance handle */
-                                  pContext->InFrames,     /* Input buffer */
-                                  pContext->OutFrames,    /* Output buffer */
-                                  frameCount);              /* Number of samples to read */
+        LvmStatus = LVREV_Process(pContext->hInstance, /* Instance handle */
+                                  pContext->InFrames,  /* Input buffer */
+                                  pContext->OutFrames, /* Output buffer */
+                                  frameCount);         /* Number of samples to read */
     }
 
     LVM_ERROR_CHECK(LvmStatus, "LVREV_Process", "process")
-    if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVREV_SUCCESS) return -EINVAL;
 
     // Convert to 16 bits
     if (pContext->auxiliary) {
         // nothing to do here
     } else {
-        for (int i = 0; i < frameCount * FCC_2; i++) { // always stereo here
-            // Mix with dry input
-            pContext->OutFrames[i] += pIn[i];
+        if (channels >= FCC_2) {
+            for (int i = 0; i < frameCount; i++) {
+                // Mix with dry input
+                pContext->OutFrames[FCC_2 * i] += pIn[channels * i];
+                pContext->OutFrames[FCC_2 * i + 1] += pIn[channels * i + 1];
+            }
+        } else {
+            for (int i = 0; i < frameCount; i++) {
+                // Mix with dry input
+                pContext->OutFrames[FCC_2 * i] += pIn[i];
+                pContext->OutFrames[FCC_2 * i + 1] += pIn[i];
+            }
         }
         // apply volume with ramp if needed
         if ((pContext->leftVolume != pContext->prevLeftVolume ||
-                pContext->rightVolume != pContext->prevRightVolume) &&
-                pContext->volumeMode == REVERB_VOLUME_RAMP) {
+             pContext->rightVolume != pContext->prevRightVolume) &&
+            pContext->volumeMode == REVERB_VOLUME_RAMP) {
             // FIXME: still using int16 volumes.
             // For reference: REVERB_UNIT_VOLUME  (0x1000) // 1.0 in 4.12 format
             float vl = (float)pContext->prevLeftVolume / 4096;
@@ -450,20 +456,51 @@
         }
     }
 
-
-    // Accumulate if required
-    if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE){
-        //ALOGV("\tBuffer access is ACCUMULATE");
-        for (int i = 0; i < frameCount * FCC_2; i++) { // always stereo here
-            pOut[i] += pContext->OutFrames[i];
+    if (outChannels > 2) {
+        // Accumulate if required
+        if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
+            for (int i = 0; i < frameCount; i++) {
+                pOut[outChannels * i] += pContext->OutFrames[FCC_2 * i];
+                pOut[outChannels * i + 1] += pContext->OutFrames[FCC_2 * i + 1];
+            }
+        } else {
+            for (int i = 0; i < frameCount; i++) {
+                pOut[outChannels * i] = pContext->OutFrames[FCC_2 * i];
+                pOut[outChannels * i + 1] = pContext->OutFrames[FCC_2 * i + 1];
+            }
         }
-    }else{
-        //ALOGV("\tBuffer access is WRITE");
-        memcpy(pOut, pContext->OutFrames, frameCount * sizeof(*pOut) * FCC_2);
+        if (!pContext->auxiliary) {
+            for (int i = 0; i < frameCount; i++) {
+                // channels and outChannels are expected to be same.
+                for (int j = FCC_2; j < outChannels; j++) {
+                    pOut[outChannels * i + j] = pIn[outChannels * i + j];
+                }
+            }
+        }
+    } else {
+        if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE) {
+            if (outChannels == FCC_1) {
+                for (int i = 0; i < frameCount; i++) {
+                    pOut[i] +=
+                            ((pContext->OutFrames[i * FCC_2] + pContext->OutFrames[i * FCC_2 + 1]) *
+                             0.5f);
+                }
+            } else {
+                for (int i = 0; i < frameCount * FCC_2; i++) {
+                    pOut[i] += pContext->OutFrames[i];
+                }
+            }
+        } else {
+            if (outChannels == FCC_1) {
+                From2iToMono_Float((const process_buffer_t*)pContext->OutFrames, pOut, frameCount);
+            } else {
+                memcpy(pOut, pContext->OutFrames, frameCount * sizeof(*pOut) * FCC_2);
+            }
+        }
     }
 
     return 0;
-}    /* end process */
+} /* end process */
 
 //----------------------------------------------------------------------------
 // Reverb_free()
@@ -477,30 +514,31 @@
 //
 //----------------------------------------------------------------------------
 
-void Reverb_free(ReverbContext *pContext){
-
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;         /* Function call status */
-    LVREV_MemoryTable_st      MemTab;
+void Reverb_free(ReverbContext* pContext) {
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
+    LVREV_MemoryTable_st MemTab;
 
     /* Free the algorithm memory */
-    LvmStatus = LVREV_GetMemoryTable(pContext->hInstance,
-                                   &MemTab,
-                                   LVM_NULL);
+    LvmStatus = LVREV_GetMemoryTable(pContext->hInstance, &MemTab, LVM_NULL);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetMemoryTable", "Reverb_free")
 
-    for (int i=0; i<LVM_NR_MEMORY_REGIONS; i++){
-        if (MemTab.Region[i].Size != 0){
-            if (MemTab.Region[i].pBaseAddress != NULL){
+    for (int i = 0; i < LVM_NR_MEMORY_REGIONS; i++) {
+        if (MemTab.Region[i].Size != 0) {
+            if (MemTab.Region[i].pBaseAddress != NULL) {
                 free(MemTab.Region[i].pBaseAddress);
-            }else{
-                ALOGV("\tLVM_ERROR : free() - trying to free with NULL pointer %" PRIu32 " bytes "
-                        "for region %u at %p ERROR\n",
-                        MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
+            } else {
+                ALOGV("\tLVM_ERROR : free() - trying to free with NULL pointer %" PRIu32
+                      " bytes "
+                      "for region %u at %p ERROR\n",
+                      MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
             }
         }
     }
-}    /* end Reverb_free */
+
+    LvmStatus = LVREV_FreeInstance(pContext->hInstance);
+    LVM_ERROR_CHECK(LvmStatus, "LVREV_FreeInstance", "Reverb_free")
+} /* end Reverb_free */
 
 //----------------------------------------------------------------------------
 // Reverb_setConfig()
@@ -516,89 +554,59 @@
 //
 //----------------------------------------------------------------------------
 
-int Reverb_setConfig(ReverbContext *pContext, effect_config_t *pConfig){
-    LVM_Fs_en   SampleRate;
-    //ALOGV("\tReverb_setConfig start");
+int Reverb_setConfig(ReverbContext* pContext, effect_config_t* pConfig) {
+    LVM_Fs_en SampleRate;
+    // ALOGV("\tReverb_setConfig start");
 
     CHECK_ARG(pContext != NULL);
     CHECK_ARG(pConfig != NULL);
 
     CHECK_ARG(pConfig->inputCfg.samplingRate == pConfig->outputCfg.samplingRate);
     CHECK_ARG(pConfig->inputCfg.format == pConfig->outputCfg.format);
+    int inputChannels = audio_channel_count_from_out_mask(pConfig->inputCfg.channels);
     CHECK_ARG((pContext->auxiliary && pConfig->inputCfg.channels == AUDIO_CHANNEL_OUT_MONO) ||
-              ((!pContext->auxiliary) && pConfig->inputCfg.channels == AUDIO_CHANNEL_OUT_STEREO));
-    CHECK_ARG(pConfig->outputCfg.channels == AUDIO_CHANNEL_OUT_STEREO);
-    CHECK_ARG(pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE
-              || pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE);
+              ((!pContext->auxiliary) && (inputChannels <= LVM_MAX_CHANNELS)));
+    int outputChannels = audio_channel_count_from_out_mask(pConfig->outputCfg.channels);
+    CHECK_ARG(outputChannels <= LVM_MAX_CHANNELS);
+    CHECK_ARG(pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE ||
+              pConfig->outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE);
     CHECK_ARG(pConfig->inputCfg.format == EFFECT_BUFFER_FORMAT);
-    //ALOGV("\tReverb_setConfig calling memcpy");
+    // ALOGV("\tReverb_setConfig calling memcpy");
     pContext->config = *pConfig;
 
-    switch (pConfig->inputCfg.samplingRate) {
-    case 8000:
-        SampleRate = LVM_FS_8000;
-        break;
-    case 16000:
-        SampleRate = LVM_FS_16000;
-        break;
-    case 22050:
-        SampleRate = LVM_FS_22050;
-        break;
-    case 32000:
-        SampleRate = LVM_FS_32000;
-        break;
-    case 44100:
-        SampleRate = LVM_FS_44100;
-        break;
-    case 48000:
-        SampleRate = LVM_FS_48000;
-        break;
-    case 88200:
-        SampleRate = LVM_FS_88200;
-        break;
-    case 96000:
-        SampleRate = LVM_FS_96000;
-        break;
-    case 176400:
-        SampleRate = LVM_FS_176400;
-        break;
-    case 192000:
-        SampleRate = LVM_FS_192000;
-        break;
-    default:
-        ALOGV("\rReverb_setConfig invalid sampling rate %d", pConfig->inputCfg.samplingRate);
+    SampleRate = lvmFsForSampleRate(pConfig->inputCfg.samplingRate);
+    if (SampleRate == LVM_FS_INVALID) {
+        ALOGE("Reverb_setConfig invalid sampling rate %d", pConfig->inputCfg.samplingRate);
         return -EINVAL;
     }
 
     if (pContext->SampleRate != SampleRate) {
+        LVREV_ControlParams_st ActiveParams;
+        LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS;
 
-        LVREV_ControlParams_st    ActiveParams;
-        LVREV_ReturnStatus_en     LvmStatus = LVREV_SUCCESS;
-
-        //ALOGV("\tReverb_setConfig change sampling rate to %d", SampleRate);
+        // ALOGV("\tReverb_setConfig change sampling rate to %d", SampleRate);
 
         /* Get the current settings */
-        LvmStatus = LVREV_GetControlParameters(pContext->hInstance,
-                                         &ActiveParams);
+        LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
 
         LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "Reverb_setConfig")
-        if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+        if (LvmStatus != LVREV_SUCCESS) return -EINVAL;
 
         ActiveParams.SampleRate = SampleRate;
 
         LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
 
         LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "Reverb_setConfig")
-        if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
-        //ALOGV("\tReverb_setConfig Succesfully called LVREV_SetControlParameters\n");
+        if (LvmStatus != LVREV_SUCCESS) return -EINVAL;
+        // ALOGV("\tReverb_setConfig Successfully called LVREV_SetControlParameters\n");
         pContext->SampleRate = SampleRate;
-    }else{
-        //ALOGV("\tReverb_setConfig keep sampling rate at %d", SampleRate);
+    } else {
+        // ALOGV("\tReverb_setConfig keep sampling rate at %d", SampleRate);
     }
 
-    //ALOGV("\tReverb_setConfig End");
+    // ALOGV("\tReverb_setConfig End");
     return 0;
-}   /* end Reverb_setConfig */
+} /* end Reverb_setConfig */
 
 //----------------------------------------------------------------------------
 // Reverb_getConfig()
@@ -614,10 +622,9 @@
 //
 //----------------------------------------------------------------------------
 
-void Reverb_getConfig(ReverbContext *pContext, effect_config_t *pConfig)
-{
+void Reverb_getConfig(ReverbContext* pContext, effect_config_t* pConfig) {
     *pConfig = pContext->config;
-}   /* end Reverb_getConfig */
+} /* end Reverb_getConfig */
 
 //----------------------------------------------------------------------------
 // Reverb_init()
@@ -631,35 +638,35 @@
 //
 //----------------------------------------------------------------------------
 
-int Reverb_init(ReverbContext *pContext){
+int Reverb_init(ReverbContext* pContext) {
     ALOGV("\tReverb_init start");
 
     CHECK_ARG(pContext != NULL);
 
-    if (pContext->hInstance != NULL){
+    if (pContext->hInstance != NULL) {
         Reverb_free(pContext);
     }
 
-    pContext->config.inputCfg.accessMode                    = EFFECT_BUFFER_ACCESS_READ;
+    pContext->config.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
     if (pContext->auxiliary) {
-        pContext->config.inputCfg.channels                  = AUDIO_CHANNEL_OUT_MONO;
+        pContext->config.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
     } else {
-        pContext->config.inputCfg.channels                  = AUDIO_CHANNEL_OUT_STEREO;
+        pContext->config.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
     }
-    pContext->config.inputCfg.format                        = EFFECT_BUFFER_FORMAT;
-    pContext->config.inputCfg.samplingRate                  = 44100;
-    pContext->config.inputCfg.bufferProvider.getBuffer      = NULL;
-    pContext->config.inputCfg.bufferProvider.releaseBuffer  = NULL;
-    pContext->config.inputCfg.bufferProvider.cookie         = NULL;
-    pContext->config.inputCfg.mask                          = EFFECT_CONFIG_ALL;
-    pContext->config.outputCfg.accessMode                   = EFFECT_BUFFER_ACCESS_ACCUMULATE;
-    pContext->config.outputCfg.channels                     = AUDIO_CHANNEL_OUT_STEREO;
-    pContext->config.outputCfg.format                       = EFFECT_BUFFER_FORMAT;
-    pContext->config.outputCfg.samplingRate                 = 44100;
-    pContext->config.outputCfg.bufferProvider.getBuffer     = NULL;
+    pContext->config.inputCfg.format = EFFECT_BUFFER_FORMAT;
+    pContext->config.inputCfg.samplingRate = 44100;
+    pContext->config.inputCfg.bufferProvider.getBuffer = NULL;
+    pContext->config.inputCfg.bufferProvider.releaseBuffer = NULL;
+    pContext->config.inputCfg.bufferProvider.cookie = NULL;
+    pContext->config.inputCfg.mask = EFFECT_CONFIG_ALL;
+    pContext->config.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
+    pContext->config.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO;
+    pContext->config.outputCfg.format = EFFECT_BUFFER_FORMAT;
+    pContext->config.outputCfg.samplingRate = 44100;
+    pContext->config.outputCfg.bufferProvider.getBuffer = NULL;
     pContext->config.outputCfg.bufferProvider.releaseBuffer = NULL;
-    pContext->config.outputCfg.bufferProvider.cookie        = NULL;
-    pContext->config.outputCfg.mask                         = EFFECT_CONFIG_ALL;
+    pContext->config.outputCfg.bufferProvider.cookie = NULL;
+    pContext->config.outputCfg.mask = EFFECT_CONFIG_ALL;
 
     pContext->leftVolume = REVERB_UNIT_VOLUME;
     pContext->rightVolume = REVERB_UNIT_VOLUME;
@@ -667,40 +674,39 @@
     pContext->prevRightVolume = REVERB_UNIT_VOLUME;
     pContext->volumeMode = REVERB_VOLUME_FLAT;
 
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;        /* Function call status */
-    LVREV_ControlParams_st    params;                         /* Control Parameters */
-    LVREV_InstanceParams_st   InstParams;                     /* Instance parameters */
-    LVREV_MemoryTable_st      MemTab;                         /* Memory allocation table */
-    bool                      bMallocFailure = LVM_FALSE;
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
+    LVREV_ControlParams_st params;                   /* Control Parameters */
+    LVREV_InstanceParams_st InstParams;              /* Instance parameters */
+    LVREV_MemoryTable_st MemTab;                     /* Memory allocation table */
+    bool bMallocFailure = LVM_FALSE;
 
     /* Set the capabilities */
-    InstParams.MaxBlockSize  = MAX_CALL_SIZE;
-    InstParams.SourceFormat  = LVM_STEREO;          // Max format, could be mono during process
-    InstParams.NumDelays     = LVREV_DELAYLINES_4;
+    InstParams.MaxBlockSize = MAX_CALL_SIZE;
+    InstParams.SourceFormat = LVM_STEREO;  // Max format, could be mono during process
+    InstParams.NumDelays = LVREV_DELAYLINES_4;
 
     /* Allocate memory, forcing alignment */
-    LvmStatus = LVREV_GetMemoryTable(LVM_NULL,
-                                  &MemTab,
-                                  &InstParams);
+    LvmStatus = LVREV_GetMemoryTable(LVM_NULL, &MemTab, &InstParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetMemoryTable", "Reverb_init")
-    if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVREV_SUCCESS) return -EINVAL;
 
-    ALOGV("\tCreateInstance Succesfully called LVM_GetMemoryTable\n");
+    ALOGV("\tCreateInstance Successfully called LVM_GetMemoryTable\n");
 
     /* Allocate memory */
-    for (int i=0; i<LVM_NR_MEMORY_REGIONS; i++){
-        if (MemTab.Region[i].Size != 0){
-            MemTab.Region[i].pBaseAddress = malloc(MemTab.Region[i].Size);
+    for (int i = 0; i < LVM_NR_MEMORY_REGIONS; i++) {
+        if (MemTab.Region[i].Size != 0) {
+            MemTab.Region[i].pBaseAddress = calloc(1, MemTab.Region[i].Size);
 
-            if (MemTab.Region[i].pBaseAddress == LVM_NULL){
+            if (MemTab.Region[i].pBaseAddress == LVM_NULL) {
                 ALOGV("\tLVREV_ERROR :Reverb_init CreateInstance Failed to allocate %" PRIu32
-                        " bytes for region %u\n", MemTab.Region[i].Size, i );
+                      " bytes for region %u\n",
+                      MemTab.Region[i].Size, i);
                 bMallocFailure = LVM_TRUE;
-            }else{
+            } else {
                 ALOGV("\tReverb_init CreateInstance allocate %" PRIu32
-                        " bytes for region %u at %p\n",
-                        MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
+                      " bytes for region %u at %p\n",
+                      MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
             }
         }
     }
@@ -708,82 +714,83 @@
     /* If one or more of the memory regions failed to allocate, free the regions that were
      * succesfully allocated and return with an error
      */
-    if(bMallocFailure == LVM_TRUE){
-        for (int i=0; i<LVM_NR_MEMORY_REGIONS; i++){
-            if (MemTab.Region[i].pBaseAddress == LVM_NULL){
+    if (bMallocFailure == LVM_TRUE) {
+        for (int i = 0; i < LVM_NR_MEMORY_REGIONS; i++) {
+            if (MemTab.Region[i].pBaseAddress == LVM_NULL) {
                 ALOGV("\tLVM_ERROR :Reverb_init CreateInstance Failed to allocate %" PRIu32
-                        " bytes for region %u - Not freeing\n", MemTab.Region[i].Size, i );
-            }else{
+                      " bytes for region %u - Not freeing\n",
+                      MemTab.Region[i].Size, i);
+            } else {
                 ALOGV("\tLVM_ERROR :Reverb_init CreateInstance Failed: but allocated %" PRIu32
-                        " bytes for region %u at %p- free\n",
-                        MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
+                      " bytes for region %u at %p- free\n",
+                      MemTab.Region[i].Size, i, MemTab.Region[i].pBaseAddress);
                 free(MemTab.Region[i].pBaseAddress);
             }
         }
         return -EINVAL;
     }
-    ALOGV("\tReverb_init CreateInstance Succesfully malloc'd memory\n");
+    ALOGV("\tReverb_init CreateInstance Successfully malloc'd memory\n");
 
     /* Initialise */
     pContext->hInstance = LVM_NULL;
 
     /* Init sets the instance handle */
-    LvmStatus = LVREV_GetInstanceHandle(&pContext->hInstance,
-                                        &MemTab,
-                                        &InstParams);
+    LvmStatus = LVREV_GetInstanceHandle(&pContext->hInstance, &MemTab, &InstParams);
 
     LVM_ERROR_CHECK(LvmStatus, "LVM_GetInstanceHandle", "Reverb_init")
-    if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVREV_SUCCESS) return -EINVAL;
 
-    ALOGV("\tReverb_init CreateInstance Succesfully called LVM_GetInstanceHandle\n");
+    ALOGV("\tReverb_init CreateInstance Successfully called LVM_GetInstanceHandle\n");
 
     /* Set the initial process parameters */
     /* General parameters */
-    params.OperatingMode  = LVM_MODE_ON;
-    params.SampleRate     = LVM_FS_44100;
-    pContext->SampleRate  = LVM_FS_44100;
+    params.OperatingMode = LVM_MODE_ON;
+    params.SampleRate = LVM_FS_44100;
+    pContext->SampleRate = LVM_FS_44100;
 
-    if(pContext->config.inputCfg.channels == AUDIO_CHANNEL_OUT_MONO){
-        params.SourceFormat   = LVM_MONO;
+    if (pContext->config.inputCfg.channels == AUDIO_CHANNEL_OUT_MONO) {
+        params.SourceFormat = LVM_MONO;
     } else {
-        params.SourceFormat   = LVM_STEREO;
+        params.SourceFormat = LVM_STEREO;
     }
 
+    if ((pContext->auxiliary == false) && (params.SourceFormat == LVM_MONO)) {
+        params.SourceFormat = LVM_STEREO;
+    }
     /* Reverb parameters */
-    params.Level          = 0;
-    params.LPF            = 23999;
-    params.HPF            = 50;
-    params.T60            = 1490;
-    params.Density        = 100;
-    params.Damping        = 21;
-    params.RoomSize       = 100;
+    params.Level = 0;
+    params.LPF = 23999;
+    params.HPF = 50;
+    params.T60 = 1490;
+    params.Density = 100;
+    params.Damping = 21;
+    params.RoomSize = 100;
 
-    pContext->SamplesToExitCount = (params.T60 * pContext->config.inputCfg.samplingRate)/1000;
+    pContext->SamplesToExitCount = (params.T60 * pContext->config.inputCfg.samplingRate) / 1000;
 
     /* Saved strength is used to return the exact strength that was used in the set to the get
      * because we map the original strength range of 0:1000 to 1:15, and this will avoid
      * quantisation like effect when returning
      */
-    pContext->SavedRoomLevel    = -6000;
-    pContext->SavedHfLevel      = 0;
-    pContext->bEnabled          = LVM_FALSE;
-    pContext->SavedDecayTime    = params.T60;
-    pContext->SavedDecayHfRatio = params.Damping*20;
-    pContext->SavedDensity      = params.RoomSize*10;
-    pContext->SavedDiffusion    = params.Density*10;
-    pContext->SavedReverbLevel  = -6000;
+    pContext->SavedRoomLevel = -6000;
+    pContext->SavedHfLevel = 0;
+    pContext->bEnabled = LVM_FALSE;
+    pContext->SavedDecayTime = params.T60;
+    pContext->SavedDecayHfRatio = params.Damping * 20;
+    pContext->SavedDensity = params.RoomSize * 10;
+    pContext->SavedDiffusion = params.Density * 10;
+    pContext->SavedReverbLevel = -6000;
 
     /* Activate the initial settings */
-    LvmStatus = LVREV_SetControlParameters(pContext->hInstance,
-                                         &params);
+    LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &params);
 
     LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "Reverb_init")
-    if(LvmStatus != LVREV_SUCCESS) return -EINVAL;
+    if (LvmStatus != LVREV_SUCCESS) return -EINVAL;
 
-    ALOGV("\tReverb_init CreateInstance Succesfully called LVREV_SetControlParameters\n");
+    ALOGV("\tReverb_init CreateInstance Successfully called LVREV_SetControlParameters\n");
     ALOGV("\tReverb_init End");
     return 0;
-}   /* end Reverb_init */
+} /* end Reverb_init */
 
 //----------------------------------------------------------------------------
 // ReverbConvertLevel()
@@ -796,27 +803,21 @@
 //
 //----------------------------------------------------------------------------
 
-int16_t ReverbConvertLevel(int16_t level){
-    static int16_t LevelArray[101] =
-    {
-       -12000, -4000,  -3398,  -3046,  -2796,  -2603,  -2444,  -2310,  -2194,  -2092,
-       -2000,  -1918,  -1842,  -1773,  -1708,  -1648,  -1592,  -1540,  -1490,  -1443,
-       -1398,  -1356,  -1316,  -1277,  -1240,  -1205,  -1171,  -1138,  -1106,  -1076,
-       -1046,  -1018,  -990,   -963,   -938,   -912,   -888,   -864,   -841,   -818,
-       -796,   -775,   -754,   -734,   -714,   -694,   -675,   -656,   -638,   -620,
-       -603,   -585,   -568,   -552,   -536,   -520,   -504,   -489,   -474,   -459,
-       -444,   -430,   -416,   -402,   -388,   -375,   -361,   -348,   -335,   -323,
-       -310,   -298,   -286,   -274,   -262,   -250,   -239,   -228,   -216,   -205,
-       -194,   -184,   -173,   -162,   -152,   -142,   -132,   -121,   -112,   -102,
-       -92,    -82,    -73,    -64,    -54,    -45,    -36,    -27,    -18,    -9,
-       0
-    };
+int16_t ReverbConvertLevel(int16_t level) {
+    static int16_t LevelArray[101] = {
+            -12000, -4000, -3398, -3046, -2796, -2603, -2444, -2310, -2194, -2092, -2000, -1918,
+            -1842,  -1773, -1708, -1648, -1592, -1540, -1490, -1443, -1398, -1356, -1316, -1277,
+            -1240,  -1205, -1171, -1138, -1106, -1076, -1046, -1018, -990,  -963,  -938,  -912,
+            -888,   -864,  -841,  -818,  -796,  -775,  -754,  -734,  -714,  -694,  -675,  -656,
+            -638,   -620,  -603,  -585,  -568,  -552,  -536,  -520,  -504,  -489,  -474,  -459,
+            -444,   -430,  -416,  -402,  -388,  -375,  -361,  -348,  -335,  -323,  -310,  -298,
+            -286,   -274,  -262,  -250,  -239,  -228,  -216,  -205,  -194,  -184,  -173,  -162,
+            -152,   -142,  -132,  -121,  -112,  -102,  -92,   -82,   -73,   -64,   -54,   -45,
+            -36,    -27,   -18,   -9,    0};
     int16_t i;
 
-    for(i = 0; i < 101; i++)
-    {
-       if(level <= LevelArray[i])
-           break;
+    for (i = 0; i < 101; i++) {
+        if (level <= LevelArray[i]) break;
     }
     return i;
 }
@@ -832,37 +833,31 @@
 //
 //----------------------------------------------------------------------------
 
-int16_t ReverbConvertHfLevel(int16_t Hflevel){
+int16_t ReverbConvertHfLevel(int16_t Hflevel) {
     int16_t i;
 
-    static LPFPair_t LPFArray[97] =
-    {   // Limit range to 50 for LVREV parameter range
-        {-10000, 50}, { -5000, 50 }, { -4000, 50},  { -3000, 158}, { -2000, 502},
-        {-1000, 1666},{ -900, 1897}, { -800, 2169}, { -700, 2496}, { -600, 2895},
-        {-500, 3400}, { -400, 4066}, { -300, 5011}, { -200, 6537}, { -100,  9826},
-        {-99, 9881 }, { -98, 9937 }, { -97, 9994 }, { -96, 10052}, { -95, 10111},
-        {-94, 10171}, { -93, 10231}, { -92, 10293}, { -91, 10356}, { -90, 10419},
-        {-89, 10484}, { -88, 10549}, { -87, 10616}, { -86, 10684}, { -85, 10753},
-        {-84, 10823}, { -83, 10895}, { -82, 10968}, { -81, 11042}, { -80, 11117},
-        {-79, 11194}, { -78, 11272}, { -77, 11352}, { -76, 11433}, { -75, 11516},
-        {-74, 11600}, { -73, 11686}, { -72, 11774}, { -71, 11864}, { -70, 11955},
-        {-69, 12049}, { -68, 12144}, { -67, 12242}, { -66, 12341}, { -65, 12443},
-        {-64, 12548}, { -63, 12654}, { -62, 12763}, { -61, 12875}, { -60, 12990},
-        {-59, 13107}, { -58, 13227}, { -57, 13351}, { -56, 13477}, { -55, 13607},
-        {-54, 13741}, { -53, 13878}, { -52, 14019}, { -51, 14164}, { -50, 14313},
-        {-49, 14467}, { -48, 14626}, { -47, 14789}, { -46, 14958}, { -45, 15132},
-        {-44, 15312}, { -43, 15498}, { -42, 15691}, { -41, 15890}, { -40, 16097},
-        {-39, 16311}, { -38, 16534}, { -37, 16766}, { -36, 17007}, { -35, 17259},
-        {-34, 17521}, { -33, 17795}, { -32, 18081}, { -31, 18381}, { -30, 18696},
-        {-29, 19027}, { -28, 19375}, { -27, 19742}, { -26, 20129}, { -25, 20540},
-        {-24, 20976}, { -23, 21439}, { -22, 21934}, { -21, 22463}, { -20, 23031},
-        {-19, 23643}, { -18, 23999}
-    };
+    static LPFPair_t LPFArray[97] = {
+            // Limit range to 50 for LVREV parameter range
+            {-10000, 50}, {-5000, 50},  {-4000, 50},  {-3000, 158}, {-2000, 502}, {-1000, 1666},
+            {-900, 1897}, {-800, 2169}, {-700, 2496}, {-600, 2895}, {-500, 3400}, {-400, 4066},
+            {-300, 5011}, {-200, 6537}, {-100, 9826}, {-99, 9881},  {-98, 9937},  {-97, 9994},
+            {-96, 10052}, {-95, 10111}, {-94, 10171}, {-93, 10231}, {-92, 10293}, {-91, 10356},
+            {-90, 10419}, {-89, 10484}, {-88, 10549}, {-87, 10616}, {-86, 10684}, {-85, 10753},
+            {-84, 10823}, {-83, 10895}, {-82, 10968}, {-81, 11042}, {-80, 11117}, {-79, 11194},
+            {-78, 11272}, {-77, 11352}, {-76, 11433}, {-75, 11516}, {-74, 11600}, {-73, 11686},
+            {-72, 11774}, {-71, 11864}, {-70, 11955}, {-69, 12049}, {-68, 12144}, {-67, 12242},
+            {-66, 12341}, {-65, 12443}, {-64, 12548}, {-63, 12654}, {-62, 12763}, {-61, 12875},
+            {-60, 12990}, {-59, 13107}, {-58, 13227}, {-57, 13351}, {-56, 13477}, {-55, 13607},
+            {-54, 13741}, {-53, 13878}, {-52, 14019}, {-51, 14164}, {-50, 14313}, {-49, 14467},
+            {-48, 14626}, {-47, 14789}, {-46, 14958}, {-45, 15132}, {-44, 15312}, {-43, 15498},
+            {-42, 15691}, {-41, 15890}, {-40, 16097}, {-39, 16311}, {-38, 16534}, {-37, 16766},
+            {-36, 17007}, {-35, 17259}, {-34, 17521}, {-33, 17795}, {-32, 18081}, {-31, 18381},
+            {-30, 18696}, {-29, 19027}, {-28, 19375}, {-27, 19742}, {-26, 20129}, {-25, 20540},
+            {-24, 20976}, {-23, 21439}, {-22, 21934}, {-21, 22463}, {-20, 23031}, {-19, 23643},
+            {-18, 23999}};
 
-    for(i = 0; i < 96; i++)
-    {
-        if(Hflevel <= LPFArray[i].Room_HF)
-            break;
+    for (i = 0; i < 96; i++) {
+        if (Hflevel <= LPFArray[i].Room_HF) break;
     }
     return LPFArray[i].LPF;
 }
@@ -879,26 +874,26 @@
 //
 //----------------------------------------------------------------------------
 
-void ReverbSetRoomHfLevel(ReverbContext *pContext, int16_t level){
-    //ALOGV("\tReverbSetRoomHfLevel start (%d)", level);
+void ReverbSetRoomHfLevel(ReverbContext* pContext, int16_t level) {
+    // ALOGV("\tReverbSetRoomHfLevel start (%d)", level);
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetRoomHfLevel")
-    //ALOGV("\tReverbSetRoomHfLevel Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbSetRoomHfLevel() just Got -> %d\n", ActiveParams.LPF);
+    // ALOGV("\tReverbSetRoomHfLevel Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbSetRoomHfLevel() just Got -> %d\n", ActiveParams.LPF);
 
     ActiveParams.LPF = ReverbConvertHfLevel(level);
 
     /* Activate the initial settings */
     LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetRoomHfLevel")
-    //ALOGV("\tReverbSetRoomhfLevel() just Set -> %d\n", ActiveParams.LPF);
+    // ALOGV("\tReverbSetRoomhfLevel() just Set -> %d\n", ActiveParams.LPF);
     pContext->SavedHfLevel = level;
-    //ALOGV("\tReverbSetHfRoomLevel end.. saving %d", pContext->SavedHfLevel);
+    // ALOGV("\tReverbSetHfRoomLevel end.. saving %d", pContext->SavedHfLevel);
     return;
 }
 
@@ -913,30 +908,31 @@
 //
 //----------------------------------------------------------------------------
 
-int16_t ReverbGetRoomHfLevel(ReverbContext *pContext){
+int16_t ReverbGetRoomHfLevel(ReverbContext* pContext) {
     int16_t level;
-    //ALOGV("\tReverbGetRoomHfLevel start, saved level is %d", pContext->SavedHfLevel);
+    // ALOGV("\tReverbGetRoomHfLevel start, saved level is %d", pContext->SavedHfLevel);
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetRoomHfLevel")
-    //ALOGV("\tReverbGetRoomHfLevel Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbGetRoomHfLevel() just Got -> %d\n", ActiveParams.LPF);
+    // ALOGV("\tReverbGetRoomHfLevel Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbGetRoomHfLevel() just Got -> %d\n", ActiveParams.LPF);
 
     level = ReverbConvertHfLevel(pContext->SavedHfLevel);
 
-    //ALOGV("\tReverbGetRoomHfLevel() ActiveParams.LPFL %d, pContext->SavedHfLevel: %d, "
+    // ALOGV("\tReverbGetRoomHfLevel() ActiveParams.LPFL %d, pContext->SavedHfLevel: %d, "
     //     "converted level: %d\n", ActiveParams.LPF, pContext->SavedHfLevel, level);
 
-    if((int16_t)ActiveParams.LPF != level){
-        ALOGV("\tLVM_ERROR : (ignore at start up) ReverbGetRoomHfLevel() has wrong level -> %d %d\n",
-               ActiveParams.Level, level);
+    if ((int16_t)ActiveParams.LPF != level) {
+        ALOGV("\tLVM_ERROR : (ignore at start up) ReverbGetRoomHfLevel() has wrong level -> %d "
+              "%d\n",
+              ActiveParams.Level, level);
     }
 
-    //ALOGV("\tReverbGetRoomHfLevel end");
+    // ALOGV("\tReverbGetRoomHfLevel end");
     return pContext->SavedHfLevel;
 }
 
@@ -952,35 +948,35 @@
 //
 //----------------------------------------------------------------------------
 
-void ReverbSetReverbLevel(ReverbContext *pContext, int16_t level){
-    //ALOGV("\n\tReverbSetReverbLevel start (%d)", level);
+void ReverbSetReverbLevel(ReverbContext* pContext, int16_t level) {
+    // ALOGV("\n\tReverbSetReverbLevel start (%d)", level);
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
-    LVM_INT32                 CombinedLevel;             // Sum of room and reverb level controls
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
+    LVM_INT32 CombinedLevel;                         // Sum of room and reverb level controls
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetReverbLevel")
-    //ALOGV("\tReverbSetReverbLevel Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbSetReverbLevel just Got -> %d\n", ActiveParams.Level);
+    // ALOGV("\tReverbSetReverbLevel Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbSetReverbLevel just Got -> %d\n", ActiveParams.Level);
 
     // needs to subtract max levels for both RoomLevel and ReverbLevel
-    CombinedLevel = (level + pContext->SavedRoomLevel)-LVREV_MAX_REVERB_LEVEL;
-    //ALOGV("\tReverbSetReverbLevel() CombinedLevel is %d = %d + %d\n",
+    CombinedLevel = (level + pContext->SavedRoomLevel) - LVREV_MAX_REVERB_LEVEL;
+    // ALOGV("\tReverbSetReverbLevel() CombinedLevel is %d = %d + %d\n",
     //      CombinedLevel, level, pContext->SavedRoomLevel);
 
     ActiveParams.Level = ReverbConvertLevel(CombinedLevel);
 
-    //ALOGV("\tReverbSetReverbLevel() Trying to set -> %d\n", ActiveParams.Level);
+    // ALOGV("\tReverbSetReverbLevel() Trying to set -> %d\n", ActiveParams.Level);
 
     /* Activate the initial settings */
     LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetReverbLevel")
-    //ALOGV("\tReverbSetReverbLevel() just Set -> %d\n", ActiveParams.Level);
+    // ALOGV("\tReverbSetReverbLevel() just Set -> %d\n", ActiveParams.Level);
 
     pContext->SavedReverbLevel = level;
-    //ALOGV("\tReverbSetReverbLevel end pContext->SavedReverbLevel is %d\n\n",
+    // ALOGV("\tReverbSetReverbLevel end pContext->SavedReverbLevel is %d\n\n",
     //     pContext->SavedReverbLevel);
     return;
 }
@@ -996,37 +992,40 @@
 //
 //----------------------------------------------------------------------------
 
-int16_t ReverbGetReverbLevel(ReverbContext *pContext){
+int16_t ReverbGetReverbLevel(ReverbContext* pContext) {
     int16_t level;
-    //ALOGV("\tReverbGetReverbLevel start");
+    // ALOGV("\tReverbGetReverbLevel start");
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
-    LVM_INT32                 CombinedLevel;             // Sum of room and reverb level controls
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
+    LVM_INT32 CombinedLevel;                         // Sum of room and reverb level controls
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetReverbLevel")
-    //ALOGV("\tReverbGetReverbLevel Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbGetReverbLevel() just Got -> %d\n", ActiveParams.Level);
+    // ALOGV("\tReverbGetReverbLevel Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbGetReverbLevel() just Got -> %d\n", ActiveParams.Level);
 
     // needs to subtract max levels for both RoomLevel and ReverbLevel
-    CombinedLevel = (pContext->SavedReverbLevel + pContext->SavedRoomLevel)-LVREV_MAX_REVERB_LEVEL;
+    CombinedLevel =
+            (pContext->SavedReverbLevel + pContext->SavedRoomLevel) - LVREV_MAX_REVERB_LEVEL;
 
-    //ALOGV("\tReverbGetReverbLevel() CombinedLevel is %d = %d + %d\n",
-    //CombinedLevel, pContext->SavedReverbLevel, pContext->SavedRoomLevel);
+    // ALOGV("\tReverbGetReverbLevel() CombinedLevel is %d = %d + %d\n",
+    // CombinedLevel, pContext->SavedReverbLevel, pContext->SavedRoomLevel);
     level = ReverbConvertLevel(CombinedLevel);
 
-    //ALOGV("\tReverbGetReverbLevel(): ActiveParams.Level: %d, pContext->SavedReverbLevel: %d, "
+    // ALOGV("\tReverbGetReverbLevel(): ActiveParams.Level: %d, pContext->SavedReverbLevel: %d, "
     //"pContext->SavedRoomLevel: %d, CombinedLevel: %d, converted level: %d\n",
-    //ActiveParams.Level, pContext->SavedReverbLevel,pContext->SavedRoomLevel, CombinedLevel,level);
+    // ActiveParams.Level, pContext->SavedReverbLevel,pContext->SavedRoomLevel,
+    // CombinedLevel,level);
 
-    if(ActiveParams.Level != level){
-        ALOGV("\tLVM_ERROR : (ignore at start up) ReverbGetReverbLevel() has wrong level -> %d %d\n",
-                ActiveParams.Level, level);
+    if (ActiveParams.Level != level) {
+        ALOGV("\tLVM_ERROR : (ignore at start up) ReverbGetReverbLevel() has wrong level -> %d "
+              "%d\n",
+              ActiveParams.Level, level);
     }
 
-    //ALOGV("\tReverbGetReverbLevel end\n");
+    // ALOGV("\tReverbGetReverbLevel end\n");
 
     return pContext->SavedReverbLevel;
 }
@@ -1043,30 +1042,30 @@
 //
 //----------------------------------------------------------------------------
 
-void ReverbSetRoomLevel(ReverbContext *pContext, int16_t level){
-    //ALOGV("\tReverbSetRoomLevel start (%d)", level);
+void ReverbSetRoomLevel(ReverbContext* pContext, int16_t level) {
+    // ALOGV("\tReverbSetRoomLevel start (%d)", level);
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
-    LVM_INT32                 CombinedLevel;             // Sum of room and reverb level controls
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
+    LVM_INT32 CombinedLevel;                         // Sum of room and reverb level controls
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetRoomLevel")
-    //ALOGV("\tReverbSetRoomLevel Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbSetRoomLevel() just Got -> %d\n", ActiveParams.Level);
+    // ALOGV("\tReverbSetRoomLevel Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbSetRoomLevel() just Got -> %d\n", ActiveParams.Level);
 
     // needs to subtract max levels for both RoomLevel and ReverbLevel
-    CombinedLevel = (level + pContext->SavedReverbLevel)-LVREV_MAX_REVERB_LEVEL;
+    CombinedLevel = (level + pContext->SavedReverbLevel) - LVREV_MAX_REVERB_LEVEL;
     ActiveParams.Level = ReverbConvertLevel(CombinedLevel);
 
     /* Activate the initial settings */
     LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetRoomLevel")
-    //ALOGV("\tReverbSetRoomLevel() just Set -> %d\n", ActiveParams.Level);
+    // ALOGV("\tReverbSetRoomLevel() just Set -> %d\n", ActiveParams.Level);
 
     pContext->SavedRoomLevel = level;
-    //ALOGV("\tReverbSetRoomLevel end");
+    // ALOGV("\tReverbSetRoomLevel end");
     return;
 }
 
@@ -1081,35 +1080,36 @@
 //
 //----------------------------------------------------------------------------
 
-int16_t ReverbGetRoomLevel(ReverbContext *pContext){
+int16_t ReverbGetRoomLevel(ReverbContext* pContext) {
     int16_t level;
-    //ALOGV("\tReverbGetRoomLevel start");
+    // ALOGV("\tReverbGetRoomLevel start");
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
-    LVM_INT32                 CombinedLevel;             // Sum of room and reverb level controls
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
+    LVM_INT32 CombinedLevel;                         // Sum of room and reverb level controls
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetRoomLevel")
-    //ALOGV("\tReverbGetRoomLevel Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbGetRoomLevel() just Got -> %d\n", ActiveParams.Level);
+    // ALOGV("\tReverbGetRoomLevel Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbGetRoomLevel() just Got -> %d\n", ActiveParams.Level);
 
     // needs to subtract max levels for both RoomLevel and ReverbLevel
-    CombinedLevel = (pContext->SavedRoomLevel + pContext->SavedReverbLevel-LVREV_MAX_REVERB_LEVEL);
+    CombinedLevel =
+            (pContext->SavedRoomLevel + pContext->SavedReverbLevel - LVREV_MAX_REVERB_LEVEL);
     level = ReverbConvertLevel(CombinedLevel);
 
-    //ALOGV("\tReverbGetRoomLevel, Level = %d, pContext->SavedRoomLevel = %d, "
+    // ALOGV("\tReverbGetRoomLevel, Level = %d, pContext->SavedRoomLevel = %d, "
     //     "pContext->SavedReverbLevel = %d, CombinedLevel = %d, level = %d",
     //     ActiveParams.Level, pContext->SavedRoomLevel,
     //     pContext->SavedReverbLevel, CombinedLevel, level);
 
-    if(ActiveParams.Level != level){
+    if (ActiveParams.Level != level) {
         ALOGV("\tLVM_ERROR : (ignore at start up) ReverbGetRoomLevel() has wrong level -> %d %d\n",
               ActiveParams.Level, level);
     }
 
-    //ALOGV("\tReverbGetRoomLevel end");
+    // ALOGV("\tReverbGetRoomLevel end");
     return pContext->SavedRoomLevel;
 }
 
@@ -1125,34 +1125,35 @@
 //
 //----------------------------------------------------------------------------
 
-void ReverbSetDecayTime(ReverbContext *pContext, uint32_t time){
-    //ALOGV("\tReverbSetDecayTime start (%d)", time);
+void ReverbSetDecayTime(ReverbContext* pContext, uint32_t time) {
+    // ALOGV("\tReverbSetDecayTime start (%d)", time);
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetDecayTime")
-    //ALOGV("\tReverbSetDecayTime Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbSetDecayTime() just Got -> %d\n", ActiveParams.T60);
+    // ALOGV("\tReverbSetDecayTime Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbSetDecayTime() just Got -> %d\n", ActiveParams.T60);
 
     if (time <= LVREV_MAX_T60) {
         ActiveParams.T60 = (LVM_UINT16)time;
-    }
-    else {
+    } else {
         ActiveParams.T60 = LVREV_MAX_T60;
     }
 
     /* Activate the initial settings */
     LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetDecayTime")
-    //ALOGV("\tReverbSetDecayTime() just Set -> %d\n", ActiveParams.T60);
+    // ALOGV("\tReverbSetDecayTime() just Set -> %d\n", ActiveParams.T60);
 
-    pContext->SamplesToExitCount = (ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
-    //ALOGV("\tReverbSetDecayTime() just Set SamplesToExitCount-> %d\n",pContext->SamplesToExitCount);
+    pContext->SamplesToExitCount =
+            (ActiveParams.T60 * pContext->config.inputCfg.samplingRate) / 1000;
+    // ALOGV("\tReverbSetDecayTime() just Set SamplesToExitCount->
+    // %d\n",pContext->SamplesToExitCount);
     pContext->SavedDecayTime = (int16_t)time;
-    //ALOGV("\tReverbSetDecayTime end");
+    // ALOGV("\tReverbSetDecayTime end");
     return;
 }
 
@@ -1167,25 +1168,25 @@
 //
 //----------------------------------------------------------------------------
 
-uint32_t ReverbGetDecayTime(ReverbContext *pContext){
-    //ALOGV("\tReverbGetDecayTime start");
+uint32_t ReverbGetDecayTime(ReverbContext* pContext) {
+    // ALOGV("\tReverbGetDecayTime start");
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetDecayTime")
-    //ALOGV("\tReverbGetDecayTime Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbGetDecayTime() just Got -> %d\n", ActiveParams.T60);
+    // ALOGV("\tReverbGetDecayTime Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbGetDecayTime() just Got -> %d\n", ActiveParams.T60);
 
-    if(ActiveParams.T60 != pContext->SavedDecayTime){
+    if (ActiveParams.T60 != pContext->SavedDecayTime) {
         // This will fail if the decay time is set to more than 7000
-        ALOGV("\tLVM_ERROR : ReverbGetDecayTime() has wrong level -> %d %d\n",
-         ActiveParams.T60, pContext->SavedDecayTime);
+        ALOGV("\tLVM_ERROR : ReverbGetDecayTime() has wrong level -> %d %d\n", ActiveParams.T60,
+              pContext->SavedDecayTime);
     }
 
-    //ALOGV("\tReverbGetDecayTime end");
+    // ALOGV("\tReverbGetDecayTime end");
     return (uint32_t)ActiveParams.T60;
 }
 
@@ -1201,27 +1202,27 @@
 //
 //----------------------------------------------------------------------------
 
-void ReverbSetDecayHfRatio(ReverbContext *pContext, int16_t ratio){
-    //ALOGV("\tReverbSetDecayHfRatioe start (%d)", ratio);
+void ReverbSetDecayHfRatio(ReverbContext* pContext, int16_t ratio) {
+    // ALOGV("\tReverbSetDecayHfRatioe start (%d)", ratio);
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;   /* Function call status */
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetDecayHfRatio")
-    //ALOGV("\tReverbSetDecayHfRatio Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbSetDecayHfRatio() just Got -> %d\n", ActiveParams.Damping);
+    // ALOGV("\tReverbSetDecayHfRatio Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbSetDecayHfRatio() just Got -> %d\n", ActiveParams.Damping);
 
-    ActiveParams.Damping = (LVM_INT16)(ratio/20);
+    ActiveParams.Damping = (LVM_INT16)(ratio / 20);
 
     /* Activate the initial settings */
     LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetDecayHfRatio")
-    //ALOGV("\tReverbSetDecayHfRatio() just Set -> %d\n", ActiveParams.Damping);
+    // ALOGV("\tReverbSetDecayHfRatio() just Set -> %d\n", ActiveParams.Damping);
 
     pContext->SavedDecayHfRatio = ratio;
-    //ALOGV("\tReverbSetDecayHfRatio end");
+    // ALOGV("\tReverbSetDecayHfRatio end");
     return;
 }
 
@@ -1236,24 +1237,24 @@
 //
 //----------------------------------------------------------------------------
 
-int32_t ReverbGetDecayHfRatio(ReverbContext *pContext){
-    //ALOGV("\tReverbGetDecayHfRatio start");
+int32_t ReverbGetDecayHfRatio(ReverbContext* pContext) {
+    // ALOGV("\tReverbGetDecayHfRatio start");
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;   /* Function call status */
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetDecayHfRatio")
-    //ALOGV("\tReverbGetDecayHfRatio Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbGetDecayHfRatio() just Got -> %d\n", ActiveParams.Damping);
+    // ALOGV("\tReverbGetDecayHfRatio Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbGetDecayHfRatio() just Got -> %d\n", ActiveParams.Damping);
 
-    if(ActiveParams.Damping != (LVM_INT16)(pContext->SavedDecayHfRatio / 20)){
+    if (ActiveParams.Damping != (LVM_INT16)(pContext->SavedDecayHfRatio / 20)) {
         ALOGV("\tLVM_ERROR : ReverbGetDecayHfRatio() has wrong level -> %d %d\n",
-         ActiveParams.Damping, pContext->SavedDecayHfRatio);
+              ActiveParams.Damping, pContext->SavedDecayHfRatio);
     }
 
-    //ALOGV("\tReverbGetDecayHfRatio end");
+    // ALOGV("\tReverbGetDecayHfRatio end");
     return pContext->SavedDecayHfRatio;
 }
 
@@ -1269,27 +1270,27 @@
 //
 //----------------------------------------------------------------------------
 
-void ReverbSetDiffusion(ReverbContext *pContext, int16_t level){
-    //ALOGV("\tReverbSetDiffusion start (%d)", level);
+void ReverbSetDiffusion(ReverbContext* pContext, int16_t level) {
+    // ALOGV("\tReverbSetDiffusion start (%d)", level);
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetDiffusion")
-    //ALOGV("\tReverbSetDiffusion Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbSetDiffusion() just Got -> %d\n", ActiveParams.Density);
+    // ALOGV("\tReverbSetDiffusion Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbSetDiffusion() just Got -> %d\n", ActiveParams.Density);
 
-    ActiveParams.Density = (LVM_INT16)(level/10);
+    ActiveParams.Density = (LVM_INT16)(level / 10);
 
     /* Activate the initial settings */
     LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetDiffusion")
-    //ALOGV("\tReverbSetDiffusion() just Set -> %d\n", ActiveParams.Density);
+    // ALOGV("\tReverbSetDiffusion() just Set -> %d\n", ActiveParams.Density);
 
     pContext->SavedDiffusion = level;
-    //ALOGV("\tReverbSetDiffusion end");
+    // ALOGV("\tReverbSetDiffusion end");
     return;
 }
 
@@ -1304,26 +1305,26 @@
 //
 //----------------------------------------------------------------------------
 
-int32_t ReverbGetDiffusion(ReverbContext *pContext){
-    //ALOGV("\tReverbGetDiffusion start");
+int32_t ReverbGetDiffusion(ReverbContext* pContext) {
+    // ALOGV("\tReverbGetDiffusion start");
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
-    LVM_INT16                 Temp;
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
+    LVM_INT16 Temp;
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetDiffusion")
-    //ALOGV("\tReverbGetDiffusion Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbGetDiffusion just Got -> %d\n", ActiveParams.Density);
+    // ALOGV("\tReverbGetDiffusion Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbGetDiffusion just Got -> %d\n", ActiveParams.Density);
 
-    Temp = (LVM_INT16)(pContext->SavedDiffusion/10);
+    Temp = (LVM_INT16)(pContext->SavedDiffusion / 10);
 
-    if(ActiveParams.Density != Temp){
+    if (ActiveParams.Density != Temp) {
         ALOGV("\tLVM_ERROR : ReverbGetDiffusion invalid value %d %d", Temp, ActiveParams.Density);
     }
 
-    //ALOGV("\tReverbGetDiffusion end");
+    // ALOGV("\tReverbGetDiffusion end");
     return pContext->SavedDiffusion;
 }
 
@@ -1339,27 +1340,27 @@
 //
 //----------------------------------------------------------------------------
 
-void ReverbSetDensity(ReverbContext *pContext, int16_t level){
-    //ALOGV("\tReverbSetDensity start (%d)", level);
+void ReverbSetDensity(ReverbContext* pContext, int16_t level) {
+    // ALOGV("\tReverbSetDensity start (%d)", level);
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbSetDensity")
-    //ALOGV("\tReverbSetDensity Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbSetDensity just Got -> %d\n", ActiveParams.RoomSize);
+    // ALOGV("\tReverbSetDensity Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbSetDensity just Got -> %d\n", ActiveParams.RoomSize);
 
     ActiveParams.RoomSize = (LVM_INT16)(((level * 99) / 1000) + 1);
 
     /* Activate the initial settings */
     LvmStatus = LVREV_SetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_SetControlParameters", "ReverbSetDensity")
-    //ALOGV("\tReverbSetDensity just Set -> %d\n", ActiveParams.RoomSize);
+    // ALOGV("\tReverbSetDensity just Set -> %d\n", ActiveParams.RoomSize);
 
     pContext->SavedDensity = level;
-    //ALOGV("\tReverbSetDensity end");
+    // ALOGV("\tReverbSetDensity end");
     return;
 }
 
@@ -1374,25 +1375,25 @@
 //
 //----------------------------------------------------------------------------
 
-int32_t ReverbGetDensity(ReverbContext *pContext){
-    //ALOGV("\tReverbGetDensity start");
+int32_t ReverbGetDensity(ReverbContext* pContext) {
+    // ALOGV("\tReverbGetDensity start");
 
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
-    LVM_INT16                 Temp;
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
+    LVM_INT16 Temp;
     /* Get the current settings */
     LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
     LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetDensity")
-    //ALOGV("\tReverbGetDensity Succesfully returned from LVM_GetControlParameters\n");
-    //ALOGV("\tReverbGetDensity() just Got -> %d\n", ActiveParams.RoomSize);
+    // ALOGV("\tReverbGetDensity Successfully returned from LVM_GetControlParameters\n");
+    // ALOGV("\tReverbGetDensity() just Got -> %d\n", ActiveParams.RoomSize);
 
     Temp = (LVM_INT16)(((pContext->SavedDensity * 99) / 1000) + 1);
 
-    if(Temp != ActiveParams.RoomSize){
+    if (Temp != ActiveParams.RoomSize) {
         ALOGV("\tLVM_ERROR : ReverbGetDensity invalid value %d %d", Temp, ActiveParams.RoomSize);
     }
 
-    //ALOGV("\tReverbGetDensity end");
+    // ALOGV("\tReverbGetDensity end");
     return pContext->SavedDensity;
 }
 
@@ -1410,20 +1411,19 @@
 // Side Effects:
 //
 //----------------------------------------------------------------------------
-int Reverb_LoadPreset(ReverbContext   *pContext)
-{
-    //TODO: add reflections delay, level and reverb delay when early reflections are
+int Reverb_LoadPreset(ReverbContext* pContext) {
+    // TODO: add reflections delay, level and reverb delay when early reflections are
     // implemented
     pContext->curPreset = pContext->nextPreset;
 
     if (pContext->curPreset != REVERB_PRESET_NONE) {
-        const t_reverb_settings *preset = &sReverbPresets[pContext->curPreset];
+        const t_reverb_settings* preset = &sReverbPresets[pContext->curPreset];
         ReverbSetRoomLevel(pContext, preset->roomLevel);
         ReverbSetRoomHfLevel(pContext, preset->roomHFLevel);
         ReverbSetDecayTime(pContext, preset->decayTime);
         ReverbSetDecayHfRatio(pContext, preset->decayHFRatio);
-        //reflectionsLevel
-        //reflectionsDelay
+        // reflectionsLevel
+        // reflectionsDelay
         ReverbSetReverbLevel(pContext, preset->reverbLevel);
         // reverbDelay
         ReverbSetDiffusion(pContext, preset->diffusion);
@@ -1454,99 +1454,96 @@
 //
 //----------------------------------------------------------------------------
 
-int Reverb_getParameter(ReverbContext *pContext,
-                        void          *pParam,
-                        uint32_t      *pValueSize,
-                        void          *pValue){
+int Reverb_getParameter(ReverbContext* pContext, void* pParam, uint32_t* pValueSize, void* pValue) {
     int status = 0;
-    int32_t *pParamTemp = (int32_t *)pParam;
+    int32_t* pParamTemp = (int32_t*)pParam;
     int32_t param = *pParamTemp++;
-    t_reverb_settings *pProperties;
+    t_reverb_settings* pProperties;
 
-    //ALOGV("\tReverb_getParameter start");
+    // ALOGV("\tReverb_getParameter start");
     if (pContext->preset) {
         if (param != REVERB_PARAM_PRESET || *pValueSize < sizeof(uint16_t)) {
             return -EINVAL;
         }
 
-        *(uint16_t *)pValue = pContext->nextPreset;
+        *(uint16_t*)pValue = pContext->nextPreset;
         ALOGV("get REVERB_PARAM_PRESET, preset %d", pContext->nextPreset);
         return 0;
     }
 
-    switch (param){
+    switch (param) {
         case REVERB_PARAM_ROOM_LEVEL:
-            if (*pValueSize != sizeof(int16_t)){
+            if (*pValueSize != sizeof(int16_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize1 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(int16_t);
             break;
         case REVERB_PARAM_ROOM_HF_LEVEL:
-            if (*pValueSize != sizeof(int16_t)){
+            if (*pValueSize != sizeof(int16_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize12 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(int16_t);
             break;
         case REVERB_PARAM_DECAY_TIME:
-            if (*pValueSize != sizeof(uint32_t)){
+            if (*pValueSize != sizeof(uint32_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize3 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(uint32_t);
             break;
         case REVERB_PARAM_DECAY_HF_RATIO:
-            if (*pValueSize != sizeof(int16_t)){
+            if (*pValueSize != sizeof(int16_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize4 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(int16_t);
             break;
         case REVERB_PARAM_REFLECTIONS_LEVEL:
-            if (*pValueSize != sizeof(int16_t)){
+            if (*pValueSize != sizeof(int16_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize5 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(int16_t);
             break;
         case REVERB_PARAM_REFLECTIONS_DELAY:
-            if (*pValueSize != sizeof(uint32_t)){
+            if (*pValueSize != sizeof(uint32_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize6 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(uint32_t);
             break;
         case REVERB_PARAM_REVERB_LEVEL:
-            if (*pValueSize != sizeof(int16_t)){
+            if (*pValueSize != sizeof(int16_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize7 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(int16_t);
             break;
         case REVERB_PARAM_REVERB_DELAY:
-            if (*pValueSize != sizeof(uint32_t)){
+            if (*pValueSize != sizeof(uint32_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize8 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(uint32_t);
             break;
         case REVERB_PARAM_DIFFUSION:
-            if (*pValueSize != sizeof(int16_t)){
+            if (*pValueSize != sizeof(int16_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize9 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(int16_t);
             break;
         case REVERB_PARAM_DENSITY:
-            if (*pValueSize != sizeof(int16_t)){
+            if (*pValueSize != sizeof(int16_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize10 %d", *pValueSize);
                 return -EINVAL;
             }
             *pValueSize = sizeof(int16_t);
             break;
         case REVERB_PARAM_PROPERTIES:
-            if (*pValueSize != sizeof(t_reverb_settings)){
+            if (*pValueSize != sizeof(t_reverb_settings)) {
                 ALOGV("\tLVM_ERROR : Reverb_getParameter() invalid pValueSize11 %d", *pValueSize);
                 return -EINVAL;
             }
@@ -1558,9 +1555,9 @@
             return -EINVAL;
     }
 
-    pProperties = (t_reverb_settings *) pValue;
+    pProperties = (t_reverb_settings*)pValue;
 
-    switch (param){
+    switch (param) {
         case REVERB_PARAM_PROPERTIES:
             pProperties->roomLevel = ReverbGetRoomLevel(pContext);
             pProperties->roomHFLevel = ReverbGetRoomHfLevel(pContext);
@@ -1574,74 +1571,74 @@
             pProperties->density = ReverbGetDensity(pContext);
 
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is roomLevel        %d",
-                pProperties->roomLevel);
+                  pProperties->roomLevel);
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is roomHFLevel      %d",
-                pProperties->roomHFLevel);
+                  pProperties->roomHFLevel);
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is decayTime        %d",
-                pProperties->decayTime);
+                  pProperties->decayTime);
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is decayHFRatio     %d",
-                pProperties->decayHFRatio);
+                  pProperties->decayHFRatio);
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is reflectionsLevel %d",
-                pProperties->reflectionsLevel);
+                  pProperties->reflectionsLevel);
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is reflectionsDelay %d",
-                pProperties->reflectionsDelay);
+                  pProperties->reflectionsDelay);
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is reverbDelay      %d",
-                pProperties->reverbDelay);
+                  pProperties->reverbDelay);
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is reverbLevel      %d",
-                pProperties->reverbLevel);
+                  pProperties->reverbLevel);
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is diffusion        %d",
-                pProperties->diffusion);
+                  pProperties->diffusion);
             ALOGV("\tReverb_getParameter() REVERB_PARAM_PROPERTIES Value is density          %d",
-                pProperties->density);
+                  pProperties->density);
             break;
 
         case REVERB_PARAM_ROOM_LEVEL:
-            *(int16_t *)pValue = ReverbGetRoomLevel(pContext);
+            *(int16_t*)pValue = ReverbGetRoomLevel(pContext);
 
-            //ALOGV("\tReverb_getParameter() REVERB_PARAM_ROOM_LEVEL Value is %d",
+            // ALOGV("\tReverb_getParameter() REVERB_PARAM_ROOM_LEVEL Value is %d",
             //        *(int16_t *)pValue);
             break;
         case REVERB_PARAM_ROOM_HF_LEVEL:
-            *(int16_t *)pValue = ReverbGetRoomHfLevel(pContext);
+            *(int16_t*)pValue = ReverbGetRoomHfLevel(pContext);
 
-            //ALOGV("\tReverb_getParameter() REVERB_PARAM_ROOM_HF_LEVEL Value is %d",
+            // ALOGV("\tReverb_getParameter() REVERB_PARAM_ROOM_HF_LEVEL Value is %d",
             //        *(int16_t *)pValue);
             break;
         case REVERB_PARAM_DECAY_TIME:
-            *(uint32_t *)pValue = ReverbGetDecayTime(pContext);
+            *(uint32_t*)pValue = ReverbGetDecayTime(pContext);
 
-            //ALOGV("\tReverb_getParameter() REVERB_PARAM_DECAY_TIME Value is %d",
+            // ALOGV("\tReverb_getParameter() REVERB_PARAM_DECAY_TIME Value is %d",
             //        *(int32_t *)pValue);
             break;
         case REVERB_PARAM_DECAY_HF_RATIO:
-            *(int16_t *)pValue = ReverbGetDecayHfRatio(pContext);
+            *(int16_t*)pValue = ReverbGetDecayHfRatio(pContext);
 
-            //ALOGV("\tReverb_getParameter() REVERB_PARAM_DECAY_HF_RATION Value is %d",
+            // ALOGV("\tReverb_getParameter() REVERB_PARAM_DECAY_HF_RATION Value is %d",
             //        *(int16_t *)pValue);
             break;
         case REVERB_PARAM_REVERB_LEVEL:
-             *(int16_t *)pValue = ReverbGetReverbLevel(pContext);
+            *(int16_t*)pValue = ReverbGetReverbLevel(pContext);
 
-            //ALOGV("\tReverb_getParameter() REVERB_PARAM_REVERB_LEVEL Value is %d",
+            // ALOGV("\tReverb_getParameter() REVERB_PARAM_REVERB_LEVEL Value is %d",
             //        *(int16_t *)pValue);
             break;
         case REVERB_PARAM_DIFFUSION:
-            *(int16_t *)pValue = ReverbGetDiffusion(pContext);
+            *(int16_t*)pValue = ReverbGetDiffusion(pContext);
 
-            //ALOGV("\tReverb_getParameter() REVERB_PARAM_DECAY_DIFFUSION Value is %d",
+            // ALOGV("\tReverb_getParameter() REVERB_PARAM_DECAY_DIFFUSION Value is %d",
             //        *(int16_t *)pValue);
             break;
         case REVERB_PARAM_DENSITY:
-            *(int16_t *)pValue = ReverbGetDensity(pContext);
-            //ALOGV("\tReverb_getParameter() REVERB_PARAM_DENSITY Value is %d",
+            *(int16_t*)pValue = ReverbGetDensity(pContext);
+            // ALOGV("\tReverb_getParameter() REVERB_PARAM_DENSITY Value is %d",
             //        *(uint32_t *)pValue);
             break;
         case REVERB_PARAM_REFLECTIONS_LEVEL:
-            *(uint16_t *)pValue = 0;
+            *(uint16_t*)pValue = 0;
             break;
         case REVERB_PARAM_REFLECTIONS_DELAY:
         case REVERB_PARAM_REVERB_DELAY:
-            *(uint32_t *)pValue = 0;
+            *(uint32_t*)pValue = 0;
             break;
 
         default:
@@ -1650,7 +1647,7 @@
             break;
     }
 
-    //ALOGV("\tReverb_getParameter end");
+    // ALOGV("\tReverb_getParameter end");
     return status;
 } /* end Reverb_getParameter */
 
@@ -1670,16 +1667,16 @@
 //
 //----------------------------------------------------------------------------
 
-int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue, int vsize){
+int Reverb_setParameter(ReverbContext* pContext, void* pParam, void* pValue, int vsize) {
     int status = 0;
     int16_t level;
     int16_t ratio;
     uint32_t time;
-    t_reverb_settings *pProperties;
-    int32_t *pParamTemp = (int32_t *)pParam;
+    t_reverb_settings* pProperties;
+    int32_t* pParamTemp = (int32_t*)pParam;
     int32_t param = *pParamTemp++;
 
-    //ALOGV("\tReverb_setParameter start");
+    // ALOGV("\tReverb_setParameter start");
     if (pContext->preset) {
         if (param != REVERB_PARAM_PRESET) {
             return -EINVAL;
@@ -1689,7 +1686,7 @@
             return -EINVAL;
         }
 
-        uint16_t preset = *(uint16_t *)pValue;
+        uint16_t preset = *(uint16_t*)pValue;
         ALOGV("set REVERB_PARAM_PRESET, preset %d", preset);
         if (preset > REVERB_PRESET_LAST) {
             return -EINVAL;
@@ -1703,10 +1700,10 @@
         return -EINVAL;
     }
 
-    switch (param){
+    switch (param) {
         case REVERB_PARAM_PROPERTIES:
             ALOGV("\tReverb_setParameter() REVERB_PARAM_PROPERTIES");
-            pProperties = (t_reverb_settings *) pValue;
+            pProperties = (t_reverb_settings*)pValue;
             ReverbSetRoomLevel(pContext, pProperties->roomLevel);
             ReverbSetRoomHfLevel(pContext, pProperties->roomHFLevel);
             ReverbSetDecayTime(pContext, pProperties->decayTime);
@@ -1716,55 +1713,55 @@
             ReverbSetDensity(pContext, pProperties->density);
             break;
         case REVERB_PARAM_ROOM_LEVEL:
-            level = *(int16_t *)pValue;
-            //ALOGV("\tReverb_setParameter() REVERB_PARAM_ROOM_LEVEL value is %d", level);
-            //ALOGV("\tReverb_setParameter() Calling ReverbSetRoomLevel");
+            level = *(int16_t*)pValue;
+            // ALOGV("\tReverb_setParameter() REVERB_PARAM_ROOM_LEVEL value is %d", level);
+            // ALOGV("\tReverb_setParameter() Calling ReverbSetRoomLevel");
             ReverbSetRoomLevel(pContext, level);
-            //ALOGV("\tReverb_setParameter() Called ReverbSetRoomLevel");
-           break;
-        case REVERB_PARAM_ROOM_HF_LEVEL:
-            level = *(int16_t *)pValue;
-            //ALOGV("\tReverb_setParameter() REVERB_PARAM_ROOM_HF_LEVEL value is %d", level);
-            //ALOGV("\tReverb_setParameter() Calling ReverbSetRoomHfLevel");
-            ReverbSetRoomHfLevel(pContext, level);
-            //ALOGV("\tReverb_setParameter() Called ReverbSetRoomHfLevel");
-           break;
-        case REVERB_PARAM_DECAY_TIME:
-            time = *(uint32_t *)pValue;
-            //ALOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_TIME value is %d", time);
-            //ALOGV("\tReverb_setParameter() Calling ReverbSetDecayTime");
-            ReverbSetDecayTime(pContext, time);
-            //ALOGV("\tReverb_setParameter() Called ReverbSetDecayTime");
-           break;
-        case REVERB_PARAM_DECAY_HF_RATIO:
-            ratio = *(int16_t *)pValue;
-            //ALOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_HF_RATIO value is %d", ratio);
-            //ALOGV("\tReverb_setParameter() Calling ReverbSetDecayHfRatio");
-            ReverbSetDecayHfRatio(pContext, ratio);
-            //ALOGV("\tReverb_setParameter() Called ReverbSetDecayHfRatio");
+            // ALOGV("\tReverb_setParameter() Called ReverbSetRoomLevel");
             break;
-         case REVERB_PARAM_REVERB_LEVEL:
-            level = *(int16_t *)pValue;
-            //ALOGV("\tReverb_setParameter() REVERB_PARAM_REVERB_LEVEL value is %d", level);
-            //ALOGV("\tReverb_setParameter() Calling ReverbSetReverbLevel");
+        case REVERB_PARAM_ROOM_HF_LEVEL:
+            level = *(int16_t*)pValue;
+            // ALOGV("\tReverb_setParameter() REVERB_PARAM_ROOM_HF_LEVEL value is %d", level);
+            // ALOGV("\tReverb_setParameter() Calling ReverbSetRoomHfLevel");
+            ReverbSetRoomHfLevel(pContext, level);
+            // ALOGV("\tReverb_setParameter() Called ReverbSetRoomHfLevel");
+            break;
+        case REVERB_PARAM_DECAY_TIME:
+            time = *(uint32_t*)pValue;
+            // ALOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_TIME value is %d", time);
+            // ALOGV("\tReverb_setParameter() Calling ReverbSetDecayTime");
+            ReverbSetDecayTime(pContext, time);
+            // ALOGV("\tReverb_setParameter() Called ReverbSetDecayTime");
+            break;
+        case REVERB_PARAM_DECAY_HF_RATIO:
+            ratio = *(int16_t*)pValue;
+            // ALOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_HF_RATIO value is %d", ratio);
+            // ALOGV("\tReverb_setParameter() Calling ReverbSetDecayHfRatio");
+            ReverbSetDecayHfRatio(pContext, ratio);
+            // ALOGV("\tReverb_setParameter() Called ReverbSetDecayHfRatio");
+            break;
+        case REVERB_PARAM_REVERB_LEVEL:
+            level = *(int16_t*)pValue;
+            // ALOGV("\tReverb_setParameter() REVERB_PARAM_REVERB_LEVEL value is %d", level);
+            // ALOGV("\tReverb_setParameter() Calling ReverbSetReverbLevel");
             ReverbSetReverbLevel(pContext, level);
-            //ALOGV("\tReverb_setParameter() Called ReverbSetReverbLevel");
-           break;
+            // ALOGV("\tReverb_setParameter() Called ReverbSetReverbLevel");
+            break;
         case REVERB_PARAM_DIFFUSION:
-            ratio = *(int16_t *)pValue;
-            //ALOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_DIFFUSION value is %d", ratio);
-            //ALOGV("\tReverb_setParameter() Calling ReverbSetDiffusion");
+            ratio = *(int16_t*)pValue;
+            // ALOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_DIFFUSION value is %d", ratio);
+            // ALOGV("\tReverb_setParameter() Calling ReverbSetDiffusion");
             ReverbSetDiffusion(pContext, ratio);
-            //ALOGV("\tReverb_setParameter() Called ReverbSetDiffusion");
+            // ALOGV("\tReverb_setParameter() Called ReverbSetDiffusion");
             break;
         case REVERB_PARAM_DENSITY:
-            ratio = *(int16_t *)pValue;
-            //ALOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_DENSITY value is %d", ratio);
-            //ALOGV("\tReverb_setParameter() Calling ReverbSetDensity");
+            ratio = *(int16_t*)pValue;
+            // ALOGV("\tReverb_setParameter() REVERB_PARAM_DECAY_DENSITY value is %d", ratio);
+            // ALOGV("\tReverb_setParameter() Calling ReverbSetDensity");
             ReverbSetDensity(pContext, ratio);
-            //ALOGV("\tReverb_setParameter() Called ReverbSetDensity");
+            // ALOGV("\tReverb_setParameter() Called ReverbSetDensity");
             break;
-           break;
+            break;
         case REVERB_PARAM_REFLECTIONS_LEVEL:
         case REVERB_PARAM_REFLECTIONS_DELAY:
         case REVERB_PARAM_REVERB_DELAY:
@@ -1774,7 +1771,7 @@
             break;
     }
 
-    //ALOGV("\tReverb_setParameter end");
+    // ALOGV("\tReverb_setParameter end");
     return status;
 } /* end Reverb_setParameter */
 
@@ -1783,52 +1780,46 @@
  */
 int Reverb_paramValueSize(int32_t param) {
     switch (param) {
-    case REVERB_PARAM_ROOM_LEVEL:
-    case REVERB_PARAM_ROOM_HF_LEVEL:
-    case REVERB_PARAM_REFLECTIONS_LEVEL:
-    case REVERB_PARAM_REVERB_LEVEL:
-        return sizeof(int16_t); // millibel
-    case REVERB_PARAM_DECAY_TIME:
-    case REVERB_PARAM_REFLECTIONS_DELAY:
-    case REVERB_PARAM_REVERB_DELAY:
-        return sizeof(uint32_t); // milliseconds
-    case REVERB_PARAM_DECAY_HF_RATIO:
-    case REVERB_PARAM_DIFFUSION:
-    case REVERB_PARAM_DENSITY:
-        return sizeof(int16_t); // permille
-    case REVERB_PARAM_PROPERTIES:
-        return sizeof(s_reverb_settings); // struct of all reverb properties
+        case REVERB_PARAM_ROOM_LEVEL:
+        case REVERB_PARAM_ROOM_HF_LEVEL:
+        case REVERB_PARAM_REFLECTIONS_LEVEL:
+        case REVERB_PARAM_REVERB_LEVEL:
+            return sizeof(int16_t);  // millibel
+        case REVERB_PARAM_DECAY_TIME:
+        case REVERB_PARAM_REFLECTIONS_DELAY:
+        case REVERB_PARAM_REVERB_DELAY:
+            return sizeof(uint32_t);  // milliseconds
+        case REVERB_PARAM_DECAY_HF_RATIO:
+        case REVERB_PARAM_DIFFUSION:
+        case REVERB_PARAM_DENSITY:
+            return sizeof(int16_t);  // permille
+        case REVERB_PARAM_PROPERTIES:
+            return sizeof(s_reverb_settings);  // struct of all reverb properties
     }
     return sizeof(int32_t);
 }
 
-} // namespace
-} // namespace
+}  // namespace
+}  // namespace android
 
 extern "C" {
 /* Effect Control Interface Implementation: Process */
-int Reverb_process(effect_handle_t   self,
-                                 audio_buffer_t         *inBuffer,
-                                 audio_buffer_t         *outBuffer){
-    android::ReverbContext * pContext = (android::ReverbContext *) self;
-    int    status = 0;
+int Reverb_process(effect_handle_t self, audio_buffer_t* inBuffer, audio_buffer_t* outBuffer) {
+    android::ReverbContext* pContext = (android::ReverbContext*)self;
+    int status = 0;
 
-    if (pContext == NULL){
+    if (pContext == NULL) {
         ALOGV("\tLVM_ERROR : Reverb_process() ERROR pContext == NULL");
         return -EINVAL;
     }
-    if (inBuffer == NULL  || inBuffer->raw == NULL  ||
-            outBuffer == NULL || outBuffer->raw == NULL ||
-            inBuffer->frameCount != outBuffer->frameCount){
+    if (inBuffer == NULL || inBuffer->raw == NULL || outBuffer == NULL || outBuffer->raw == NULL ||
+        inBuffer->frameCount != outBuffer->frameCount) {
         ALOGV("\tLVM_ERROR : Reverb_process() ERROR NULL INPUT POINTER OR FRAME COUNT IS WRONG");
         return -EINVAL;
     }
-    //ALOGV("\tReverb_process() Calling process with %d frames", outBuffer->frameCount);
+    // ALOGV("\tReverb_process() Calling process with %d frames", outBuffer->frameCount);
     /* Process all the available frames, block processing is handled internalLY by the LVM bundle */
-    status = process(    inBuffer->f32,
-                         outBuffer->f32,
-                         outBuffer->frameCount,
-                         pContext);
+    status = process(inBuffer->f32, outBuffer->f32, outBuffer->frameCount, pContext);
 
     if (pContext->bEnabled == LVM_FALSE) {
         if (pContext->SamplesToExitCount > 0) {
@@ -1840,72 +1831,67 @@
     }
 
     return status;
-}   /* end Reverb_process */
+} /* end Reverb_process */
 
 /* Effect Control Interface Implementation: Command */
-int Reverb_command(effect_handle_t  self,
-                              uint32_t            cmdCode,
-                              uint32_t            cmdSize,
-                              void                *pCmdData,
-                              uint32_t            *replySize,
-                              void                *pReplyData){
-    android::ReverbContext * pContext = (android::ReverbContext *) self;
-    LVREV_ControlParams_st    ActiveParams;              /* Current control Parameters */
-    LVREV_ReturnStatus_en     LvmStatus=LVREV_SUCCESS;     /* Function call status */
+int Reverb_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void* pCmdData,
+                   uint32_t* replySize, void* pReplyData) {
+    android::ReverbContext* pContext = (android::ReverbContext*)self;
+    LVREV_ControlParams_st ActiveParams;             /* Current control Parameters */
+    LVREV_ReturnStatus_en LvmStatus = LVREV_SUCCESS; /* Function call status */
 
-    if (pContext == NULL){
+    if (pContext == NULL) {
         ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
         return -EINVAL;
     }
 
-    //ALOGV("\tReverb_command INPUTS are: command %d cmdSize %d",cmdCode, cmdSize);
+    // ALOGV("\tReverb_command INPUTS are: command %d cmdSize %d",cmdCode, cmdSize);
 
-    switch (cmdCode){
+    switch (cmdCode) {
         case EFFECT_CMD_INIT:
-            //ALOGV("\tReverb_command cmdCode Case: "
+            // ALOGV("\tReverb_command cmdCode Case: "
             //        "EFFECT_CMD_INIT start");
 
-            if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){
+            if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_INIT: ERROR");
+                      "EFFECT_CMD_INIT: ERROR");
                 return -EINVAL;
             }
-            *(int *) pReplyData = 0;
+            *(int*)pReplyData = 0;
             break;
 
         case EFFECT_CMD_SET_CONFIG:
-            //ALOGV("\tReverb_command cmdCode Case: "
+            // ALOGV("\tReverb_command cmdCode Case: "
             //        "EFFECT_CMD_SET_CONFIG start");
-            if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) ||
-                    pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
+            if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL ||
+                replySize == NULL || *replySize != sizeof(int)) {
                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_SET_CONFIG: ERROR");
+                      "EFFECT_CMD_SET_CONFIG: ERROR");
                 return -EINVAL;
             }
-            *(int *) pReplyData = android::Reverb_setConfig(pContext,
-                                                            (effect_config_t *) pCmdData);
+            *(int*)pReplyData = android::Reverb_setConfig(pContext, (effect_config_t*)pCmdData);
             break;
 
         case EFFECT_CMD_GET_CONFIG:
             if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_GET_CONFIG: ERROR");
+                      "EFFECT_CMD_GET_CONFIG: ERROR");
                 return -EINVAL;
             }
 
-            android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
+            android::Reverb_getConfig(pContext, (effect_config_t*)pReplyData);
             break;
 
         case EFFECT_CMD_RESET:
-            //ALOGV("\tReverb_command cmdCode Case: "
+            // ALOGV("\tReverb_command cmdCode Case: "
             //        "EFFECT_CMD_RESET start");
             Reverb_setConfig(pContext, &pContext->config);
             break;
 
-        case EFFECT_CMD_GET_PARAM:{
-            //ALOGV("\tReverb_command cmdCode Case: "
+        case EFFECT_CMD_GET_PARAM: {
+            // ALOGV("\tReverb_command cmdCode Case: "
             //        "EFFECT_CMD_GET_PARAM start");
-            effect_param_t *p = (effect_param_t *)pCmdData;
+            effect_param_t* p = (effect_param_t*)pCmdData;
             if (pCmdData == nullptr) {
                 ALOGW("\tLVM_ERROR : pCmdData is NULL");
                 return -EINVAL;
@@ -1914,163 +1900,156 @@
                 android_errorWriteLog(0x534e4554, "26347509");
                 return -EINVAL;
             }
-            if (cmdSize < sizeof(effect_param_t) ||
-                    cmdSize < (sizeof(effect_param_t) + p->psize) ||
-                    pReplyData == NULL || replySize == NULL ||
-                    *replySize < (sizeof(effect_param_t) + p->psize)) {
+            if (cmdSize < sizeof(effect_param_t) || cmdSize < (sizeof(effect_param_t) + p->psize) ||
+                pReplyData == NULL || replySize == NULL ||
+                *replySize < (sizeof(effect_param_t) + p->psize)) {
                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_GET_PARAM: ERROR");
+                      "EFFECT_CMD_GET_PARAM: ERROR");
                 return -EINVAL;
             }
 
             memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
 
-            p = (effect_param_t *)pReplyData;
+            p = (effect_param_t*)pReplyData;
 
             int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
 
-            p->status = android::Reverb_getParameter(pContext,
-                                                         (void *)p->data,
-                                                          &p->vsize,
-                                                          p->data + voffset);
+            p->status = android::Reverb_getParameter(pContext, (void*)p->data, &p->vsize,
+                                                     p->data + voffset);
 
             *replySize = sizeof(effect_param_t) + voffset + p->vsize;
 
-            //ALOGV("\tReverb_command EFFECT_CMD_GET_PARAM "
+            // ALOGV("\tReverb_command EFFECT_CMD_GET_PARAM "
             //        "*pCmdData %d, *replySize %d, *pReplyData %d ",
             //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
             //        *replySize,
             //        *(int16_t *)((char *)pReplyData + sizeof(effect_param_t) + voffset));
 
         } break;
-        case EFFECT_CMD_SET_PARAM:{
-
-            //ALOGV("\tReverb_command cmdCode Case: "
+        case EFFECT_CMD_SET_PARAM: {
+            // ALOGV("\tReverb_command cmdCode Case: "
             //        "EFFECT_CMD_SET_PARAM start");
-            //ALOGV("\tReverb_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d ",
+            // ALOGV("\tReverb_command EFFECT_CMD_SET_PARAM param %d, *replySize %d, value %d ",
             //        *(int32_t *)((char *)pCmdData + sizeof(effect_param_t)),
             //        *replySize,
             //        *(int16_t *)((char *)pCmdData + sizeof(effect_param_t) + sizeof(int32_t)));
 
             if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) ||
-                    pReplyData == NULL ||  replySize == NULL || *replySize != sizeof(int32_t)) {
+                pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_SET_PARAM: ERROR");
+                      "EFFECT_CMD_SET_PARAM: ERROR");
                 return -EINVAL;
             }
 
-            effect_param_t *p = (effect_param_t *) pCmdData;
+            effect_param_t* p = (effect_param_t*)pCmdData;
 
-            if (p->psize != sizeof(int32_t)){
+            if (p->psize != sizeof(int32_t)) {
                 ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
+                      "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
                 return -EINVAL;
             }
 
-            //ALOGV("\tn5Reverb_command cmdSize is %d\n"
+            // ALOGV("\tn5Reverb_command cmdSize is %d\n"
             //        "\tsizeof(effect_param_t) is  %d\n"
             //        "\tp->psize is %d\n"
             //        "\tp->vsize is %d"
             //        "\n",
             //        cmdSize, sizeof(effect_param_t), p->psize, p->vsize );
 
-            *(int *)pReplyData = android::Reverb_setParameter(pContext,
-                                                             (void *)p->data,
-                                                              p->data + p->psize,
-                                                              p->vsize);
+            *(int*)pReplyData = android::Reverb_setParameter(pContext, (void*)p->data,
+                                                             p->data + p->psize, p->vsize);
         } break;
 
         case EFFECT_CMD_ENABLE:
-            //ALOGV("\tReverb_command cmdCode Case: "
+            // ALOGV("\tReverb_command cmdCode Case: "
             //        "EFFECT_CMD_ENABLE start");
 
-            if (pReplyData == NULL || *replySize != sizeof(int)){
+            if (pReplyData == NULL || *replySize != sizeof(int)) {
                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_ENABLE: ERROR");
+                      "EFFECT_CMD_ENABLE: ERROR");
                 return -EINVAL;
             }
-            if(pContext->bEnabled == LVM_TRUE){
-                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                         "EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
-                 return -EINVAL;
-             }
-            *(int *)pReplyData = 0;
+            if (pContext->bEnabled == LVM_TRUE) {
+                ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+                      "EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
+                return -EINVAL;
+            }
+            *(int*)pReplyData = 0;
             pContext->bEnabled = LVM_TRUE;
             /* Get the current settings */
             LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
             LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE")
             pContext->SamplesToExitCount =
-                    (ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
+                    (ActiveParams.T60 * pContext->config.inputCfg.samplingRate) / 1000;
             // force no volume ramp for first buffer processed after enabling the effect
             pContext->volumeMode = android::REVERB_VOLUME_FLAT;
-            //ALOGV("\tEFFECT_CMD_ENABLE SamplesToExitCount = %d", pContext->SamplesToExitCount);
+            // ALOGV("\tEFFECT_CMD_ENABLE SamplesToExitCount = %d", pContext->SamplesToExitCount);
             break;
         case EFFECT_CMD_DISABLE:
-            //ALOGV("\tReverb_command cmdCode Case: "
+            // ALOGV("\tReverb_command cmdCode Case: "
             //        "EFFECT_CMD_DISABLE start");
 
-            if (pReplyData == NULL || *replySize != sizeof(int)){
+            if (pReplyData == NULL || *replySize != sizeof(int)) {
                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_DISABLE: ERROR");
+                      "EFFECT_CMD_DISABLE: ERROR");
                 return -EINVAL;
             }
-            if(pContext->bEnabled == LVM_FALSE){
-                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                         "EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
-                 return -EINVAL;
-             }
-            *(int *)pReplyData = 0;
+            if (pContext->bEnabled == LVM_FALSE) {
+                ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
+                      "EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
+                return -EINVAL;
+            }
+            *(int*)pReplyData = 0;
             pContext->bEnabled = LVM_FALSE;
             break;
 
         case EFFECT_CMD_SET_VOLUME:
-            if (pCmdData == NULL ||
-                cmdSize != 2 * sizeof(uint32_t)) {
+            if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t)) {
                 ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                        "EFFECT_CMD_SET_VOLUME: ERROR");
+                      "EFFECT_CMD_SET_VOLUME: ERROR");
                 return -EINVAL;
             }
 
-            if (pReplyData != NULL) { // we have volume control
-                pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12);
-                pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12);
-                *(uint32_t *)pReplyData = (1 << 24);
-                *((uint32_t *)pReplyData + 1) = (1 << 24);
+            if (pReplyData != NULL) {  // we have volume control
+                pContext->leftVolume = (LVM_INT16)((*(uint32_t*)pCmdData + (1 << 11)) >> 12);
+                pContext->rightVolume = (LVM_INT16)((*((uint32_t*)pCmdData + 1) + (1 << 11)) >> 12);
+                *(uint32_t*)pReplyData = (1 << 24);
+                *((uint32_t*)pReplyData + 1) = (1 << 24);
                 if (pContext->volumeMode == android::REVERB_VOLUME_OFF) {
                     // force no volume ramp for first buffer processed after getting volume control
                     pContext->volumeMode = android::REVERB_VOLUME_FLAT;
                 }
-            } else { // we don't have volume control
+            } else {  // we don't have volume control
                 pContext->leftVolume = REVERB_UNIT_VOLUME;
                 pContext->rightVolume = REVERB_UNIT_VOLUME;
                 pContext->volumeMode = android::REVERB_VOLUME_OFF;
             }
-            ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d",
-                    pContext->leftVolume, pContext->rightVolume,  pContext->volumeMode);
+            ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d", pContext->leftVolume,
+                  pContext->rightVolume, pContext->volumeMode);
             break;
 
         case EFFECT_CMD_SET_DEVICE:
         case EFFECT_CMD_SET_AUDIO_MODE:
-        //ALOGV("\tReverb_command cmdCode Case: "
-        //        "EFFECT_CMD_SET_DEVICE/EFFECT_CMD_SET_VOLUME/EFFECT_CMD_SET_AUDIO_MODE start");
+            // ALOGV("\tReverb_command cmdCode Case: "
+            //        "EFFECT_CMD_SET_DEVICE/EFFECT_CMD_SET_VOLUME/EFFECT_CMD_SET_AUDIO_MODE
+            //        start");
             break;
 
         default:
             ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
-                    "DEFAULT start %d ERROR",cmdCode);
+                  "DEFAULT start %d ERROR",
+                  cmdCode);
             return -EINVAL;
     }
 
-    //ALOGV("\tReverb_command end\n\n");
+    // ALOGV("\tReverb_command end\n\n");
     return 0;
-}    /* end Reverb_command */
+} /* end Reverb_command */
 
 /* Effect Control Interface Implementation: get_descriptor */
-int Reverb_getDescriptor(effect_handle_t   self,
-                                    effect_descriptor_t *pDescriptor)
-{
-    android::ReverbContext * pContext = (android::ReverbContext *)self;
-    const effect_descriptor_t *desc;
+int Reverb_getDescriptor(effect_handle_t self, effect_descriptor_t* pDescriptor) {
+    android::ReverbContext* pContext = (android::ReverbContext*)self;
+    const effect_descriptor_t* desc;
 
     if (pContext == NULL || pDescriptor == NULL) {
         ALOGV("Reverb_getDescriptor() invalid param");
@@ -2094,26 +2073,24 @@
     *pDescriptor = *desc;
 
     return 0;
-}   /* end Reverb_getDescriptor */
+} /* end Reverb_getDescriptor */
 
 // effect_handle_t interface implementation for Reverb effect
 const struct effect_interface_s gReverbInterface = {
-    Reverb_process,
-    Reverb_command,
-    Reverb_getDescriptor,
-    NULL,
-};    /* end gReverbInterface */
+        Reverb_process,
+        Reverb_command,
+        Reverb_getDescriptor,
+        NULL,
+}; /* end gReverbInterface */
 
 // This is the only symbol that needs to be exported
-__attribute__ ((visibility ("default")))
-audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM = {
-    .tag = AUDIO_EFFECT_LIBRARY_TAG,
-    .version = EFFECT_LIBRARY_API_VERSION,
-    .name = "Reverb Library",
-    .implementor = "NXP Software Ltd.",
-    .create_effect = android::EffectCreate,
-    .release_effect = android::EffectRelease,
-    .get_descriptor = android::EffectGetDescriptor,
+__attribute__((visibility("default"))) audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM = {
+        .tag = AUDIO_EFFECT_LIBRARY_TAG,
+        .version = EFFECT_LIBRARY_API_VERSION,
+        .name = "Reverb Library",
+        .implementor = "NXP Software Ltd.",
+        .create_effect = android::EffectCreate,
+        .release_effect = android::EffectRelease,
+        .get_descriptor = android::EffectGetDescriptor,
 };
-
 }
diff --git a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h
index 96223a8..227d953 100644
--- a/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h
+++ b/media/libeffects/lvm/wrapper/Reverb/EffectReverb.h
@@ -20,16 +20,15 @@
 #include <audio_effects/effect_environmentalreverb.h>
 #include <audio_effects/effect_presetreverb.h>
 
-#define MAX_NUM_BANDS           5
-#define MAX_CALL_SIZE           256
-#define LVREV_MAX_T60           7000
-#define LVREV_MAX_REVERB_LEVEL  2000
-#define LVREV_MAX_FRAME_SIZE    2560
-#define LVREV_CUP_LOAD_ARM9E    470    // Expressed in 0.1 MIPS
-#define LVREV_MEM_USAGE         (71+(LVREV_MAX_FRAME_SIZE>>7))     // Expressed in kB
+#define MAX_NUM_BANDS 5
+#define MAX_CALL_SIZE 256
+#define LVREV_MAX_T60 7000
+#define LVREV_MAX_REVERB_LEVEL 2000
+#define LVREV_MAX_FRAME_SIZE 2560
+#define LVREV_CUP_LOAD_ARM9E 470                            // Expressed in 0.1 MIPS
+#define LVREV_MEM_USAGE (71 + (LVREV_MAX_FRAME_SIZE >> 7))  // Expressed in kB
 
-typedef struct _LPFPair_t
-{
+typedef struct _LPFPair_t {
     int16_t Room_HF;
     int16_t LPF;
 } LPFPair_t;
diff --git a/media/libeffects/preprocessing/.clang-format b/media/libeffects/preprocessing/.clang-format
new file mode 120000
index 0000000..f1b4f69
--- /dev/null
+++ b/media/libeffects/preprocessing/.clang-format
@@ -0,0 +1 @@
+../../../../../build/soong/scripts/system-clang-format
\ No newline at end of file
diff --git a/media/libeffects/preprocessing/Android.bp b/media/libeffects/preprocessing/Android.bp
index c87635f..eb3ce34 100644
--- a/media/libeffects/preprocessing/Android.bp
+++ b/media/libeffects/preprocessing/Android.bp
@@ -1,35 +1,50 @@
 // audio preprocessing wrapper
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libeffects_preprocessing_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libeffects_preprocessing_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
     name: "libaudiopreprocessing",
-
     vendor: true,
-
     relative_install_path: "soundfx",
-
     srcs: ["PreProcessing.cpp"],
-
-    include_dirs: [
-        "external/webrtc",
-        "external/webrtc/webrtc/modules/include",
-        "external/webrtc/webrtc/modules/audio_processing/include",
+    local_include_dirs: [
+        ".",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+        "-Wno-unused-parameter",
     ],
 
     shared_libs: [
-        "libwebrtc_audio_preprocessing",
-        "libspeexresampler",
-        "libutils",
         "liblog",
+        "libutils",
     ],
 
-    cflags: [
-        "-DWEBRTC_POSIX",
-        "-fvisibility=hidden",
-        "-Wall",
-        "-Werror",
+    static_libs: [
+        "webrtc_audio_processing",
     ],
 
     header_libs: [
         "libaudioeffects",
         "libhardware_headers",
+        "libwebrtc_absl_headers",
     ],
 }
diff --git a/media/libeffects/preprocessing/PreProcessing.cpp b/media/libeffects/preprocessing/PreProcessing.cpp
index 5fab5be..03ccc34 100644
--- a/media/libeffects/preprocessing/PreProcessing.cpp
+++ b/media/libeffects/preprocessing/PreProcessing.cpp
@@ -18,15 +18,15 @@
 #include <string.h>
 #define LOG_TAG "PreProcessing"
 //#define LOG_NDEBUG 0
-#include <utils/Log.h>
-#include <utils/Timers.h>
-#include <hardware/audio_effect.h>
 #include <audio_effects/effect_aec.h>
 #include <audio_effects/effect_agc.h>
+#include <hardware/audio_effect.h>
+#include <utils/Log.h>
+#include <utils/Timers.h>
+#include <audio_effects/effect_agc2.h>
 #include <audio_effects/effect_ns.h>
-#include <module_common_types.h>
 #include <audio_processing.h>
-#include "speex/speex_resampler.h"
+#include <module_common_types.h>
 
 // undefine to perform multi channels API functional tests
 //#define DUAL_MIC_TEST
@@ -39,26 +39,26 @@
 #define PREPROC_NUM_SESSIONS 8
 
 // types of pre processing modules
-enum preproc_id
-{
-    PREPROC_AGC,        // Automatic Gain Control
-    PREPROC_AEC,        // Acoustic Echo Canceler
-    PREPROC_NS,         // Noise Suppressor
+enum preproc_id {
+    PREPROC_AGC,  // Automatic Gain Control
+    PREPROC_AGC2,  // Automatic Gain Control 2
+    PREPROC_AEC,  // Acoustic Echo Canceler
+    PREPROC_NS,   // Noise Suppressor
     PREPROC_NUM_EFFECTS
 };
 
 // Session state
 enum preproc_session_state {
-    PREPROC_SESSION_STATE_INIT,        // initialized
-    PREPROC_SESSION_STATE_CONFIG       // configuration received
+    PREPROC_SESSION_STATE_INIT,   // initialized
+    PREPROC_SESSION_STATE_CONFIG  // configuration received
 };
 
 // Effect/Preprocessor state
 enum preproc_effect_state {
-    PREPROC_EFFECT_STATE_INIT,         // initialized
-    PREPROC_EFFECT_STATE_CREATED,      // webRTC engine created
-    PREPROC_EFFECT_STATE_CONFIG,       // configuration received/disabled
-    PREPROC_EFFECT_STATE_ACTIVE        // active/enabled
+    PREPROC_EFFECT_STATE_INIT,     // initialized
+    PREPROC_EFFECT_STATE_CREATED,  // webRTC engine created
+    PREPROC_EFFECT_STATE_CONFIG,   // configuration received/disabled
+    PREPROC_EFFECT_STATE_ACTIVE    // active/enabled
 };
 
 // handle on webRTC engine
@@ -71,74 +71,76 @@
 // Effect operation table. Functions for all pre processors are declared in sPreProcOps[] table.
 // Function pointer can be null if no action required.
 struct preproc_ops_s {
-    int (* create)(preproc_effect_t *fx);
-    int (* init)(preproc_effect_t *fx);
-    int (* reset)(preproc_effect_t *fx);
-    void (* enable)(preproc_effect_t *fx);
-    void (* disable)(preproc_effect_t *fx);
-    int (* set_parameter)(preproc_effect_t *fx, void *param, void *value);
-    int (* get_parameter)(preproc_effect_t *fx, void *param, uint32_t *size, void *value);
-    int (* set_device)(preproc_effect_t *fx, uint32_t device);
+    int (*create)(preproc_effect_t* fx);
+    int (*init)(preproc_effect_t* fx);
+    int (*reset)(preproc_effect_t* fx);
+    void (*enable)(preproc_effect_t* fx);
+    void (*disable)(preproc_effect_t* fx);
+    int (*set_parameter)(preproc_effect_t* fx, void* param, void* value);
+    int (*get_parameter)(preproc_effect_t* fx, void* param, uint32_t* size, void* value);
+    int (*set_device)(preproc_effect_t* fx, uint32_t device);
 };
 
 // Effect context
 struct preproc_effect_s {
-    const struct effect_interface_s *itfe;
-    uint32_t procId;                // type of pre processor (enum preproc_id)
-    uint32_t state;                 // current state (enum preproc_effect_state)
-    preproc_session_t *session;     // session the effect is on
-    const preproc_ops_t *ops;       // effect ops table
-    preproc_fx_handle_t engine;     // handle on webRTC engine
-    uint32_t type;                  // subtype of effect
+    const struct effect_interface_s* itfe;
+    uint32_t procId;             // type of pre processor (enum preproc_id)
+    uint32_t state;              // current state (enum preproc_effect_state)
+    preproc_session_t* session;  // session the effect is on
+    const preproc_ops_t* ops;    // effect ops table
+    preproc_fx_handle_t engine;  // handle on webRTC engine
+    uint32_t type;               // subtype of effect
 #ifdef DUAL_MIC_TEST
-    bool aux_channels_on;           // support auxiliary channels
-    size_t cur_channel_config;      // current auciliary channel configuration
+    bool aux_channels_on;       // support auxiliary channels
+    size_t cur_channel_config;  // current auciliary channel configuration
 #endif
 };
 
 // Session context
 struct preproc_session_s {
-    struct preproc_effect_s effects[PREPROC_NUM_EFFECTS]; // effects in this session
-    uint32_t state;                     // current state (enum preproc_session_state)
-    int id;                             // audio session ID
-    int io;                             // handle of input stream this session is on
-    webrtc::AudioProcessing* apm;       // handle on webRTC audio processing module (APM)
-    size_t apmFrameCount;               // buffer size for webRTC process (10 ms)
-    uint32_t apmSamplingRate;           // webRTC APM sampling rate (8/16 or 32 kHz)
-    size_t frameCount;                  // buffer size before input resampler ( <=> apmFrameCount)
-    uint32_t samplingRate;              // sampling rate at effect process interface
-    uint32_t inChannelCount;            // input channel count
-    uint32_t outChannelCount;           // output channel count
-    uint32_t createdMsk;                // bit field containing IDs of crested pre processors
-    uint32_t enabledMsk;                // bit field containing IDs of enabled pre processors
-    uint32_t processedMsk;              // bit field containing IDs of pre processors already
-                                        // processed in current round
-    webrtc::AudioFrame *procFrame;      // audio frame passed to webRTC AMP ProcessStream()
-    int16_t *inBuf;                     // input buffer used when resampling
-    size_t inBufSize;                   // input buffer size in frames
-    size_t framesIn;                    // number of frames in input buffer
-    SpeexResamplerState *inResampler;   // handle on input speex resampler
-    int16_t *outBuf;                    // output buffer used when resampling
-    size_t outBufSize;                  // output buffer size in frames
-    size_t framesOut;                   // number of frames in output buffer
-    SpeexResamplerState *outResampler;  // handle on output speex resampler
-    uint32_t revChannelCount;           // number of channels on reverse stream
-    uint32_t revEnabledMsk;             // bit field containing IDs of enabled pre processors
-                                        // with reverse channel
-    uint32_t revProcessedMsk;           // bit field containing IDs of pre processors with reverse
-                                        // channel already processed in current round
-    webrtc::AudioFrame *revFrame;       // audio frame passed to webRTC AMP AnalyzeReverseStream()
-    int16_t *revBuf;                    // reverse channel input buffer
-    size_t revBufSize;                  // reverse channel input buffer size
-    size_t framesRev;                   // number of frames in reverse channel input buffer
-    SpeexResamplerState *revResampler;  // handle on reverse channel input speex resampler
+    struct preproc_effect_s effects[PREPROC_NUM_EFFECTS];  // effects in this session
+    uint32_t state;                // current state (enum preproc_session_state)
+    int id;                        // audio session ID
+    int io;                        // handle of input stream this session is on
+    webrtc::AudioProcessing* apm;  // handle on webRTC audio processing module (APM)
+    // Audio Processing module builder
+    webrtc::AudioProcessingBuilder ap_builder;
+    size_t apmFrameCount;      // buffer size for webRTC process (10 ms)
+    uint32_t apmSamplingRate;  // webRTC APM sampling rate (8/16 or 32 kHz)
+    size_t frameCount;         // buffer size before input resampler ( <=> apmFrameCount)
+    uint32_t samplingRate;     // sampling rate at effect process interface
+    uint32_t inChannelCount;   // input channel count
+    uint32_t outChannelCount;  // output channel count
+    uint32_t createdMsk;       // bit field containing IDs of crested pre processors
+    uint32_t enabledMsk;       // bit field containing IDs of enabled pre processors
+    uint32_t processedMsk;     // bit field containing IDs of pre processors already
+                               // processed in current round
+    // audio config strucutre
+    webrtc::AudioProcessing::Config config;
+    webrtc::StreamConfig inputConfig;   // input stream configuration
+    webrtc::StreamConfig outputConfig;  // output stream configuration
+    int16_t* inBuf;    // input buffer used when resampling
+    size_t inBufSize;  // input buffer size in frames
+    size_t framesIn;   // number of frames in input buffer
+    int16_t* outBuf;    // output buffer used when resampling
+    size_t outBufSize;  // output buffer size in frames
+    size_t framesOut;   // number of frames in output buffer
+    uint32_t revChannelCount;  // number of channels on reverse stream
+    uint32_t revEnabledMsk;    // bit field containing IDs of enabled pre processors
+                               // with reverse channel
+    uint32_t revProcessedMsk;  // bit field containing IDs of pre processors with reverse
+                               // channel already processed in current round
+    webrtc::StreamConfig revConfig;     // reverse stream configuration.
+    int16_t* revBuf;    // reverse channel input buffer
+    size_t revBufSize;  // reverse channel input buffer size
+    size_t framesRev;   // number of frames in reverse channel input buffer
 };
 
 #ifdef DUAL_MIC_TEST
 enum {
-    PREPROC_CMD_DUAL_MIC_ENABLE = EFFECT_CMD_FIRST_PROPRIETARY, // enable dual mic mode
-    PREPROC_CMD_DUAL_MIC_PCM_DUMP_START,                        // start pcm capture
-    PREPROC_CMD_DUAL_MIC_PCM_DUMP_STOP                          // stop pcm capture
+    PREPROC_CMD_DUAL_MIC_ENABLE = EFFECT_CMD_FIRST_PROPRIETARY,  // enable dual mic mode
+    PREPROC_CMD_DUAL_MIC_PCM_DUMP_START,                         // start pcm capture
+    PREPROC_CMD_DUAL_MIC_PCM_DUMP_STOP                           // stop pcm capture
 };
 
 enum {
@@ -151,24 +153,22 @@
 };
 
 const channel_config_t sDualMicConfigs[CHANNEL_CFG_CNT] = {
-        {AUDIO_CHANNEL_IN_MONO , 0},
-        {AUDIO_CHANNEL_IN_STEREO , 0},
-        {AUDIO_CHANNEL_IN_FRONT , AUDIO_CHANNEL_IN_BACK},
-        {AUDIO_CHANNEL_IN_STEREO , AUDIO_CHANNEL_IN_RIGHT}
-};
+        {AUDIO_CHANNEL_IN_MONO, 0},
+        {AUDIO_CHANNEL_IN_STEREO, 0},
+        {AUDIO_CHANNEL_IN_FRONT, AUDIO_CHANNEL_IN_BACK},
+        {AUDIO_CHANNEL_IN_STEREO, AUDIO_CHANNEL_IN_RIGHT}};
 
 bool sHasAuxChannels[PREPROC_NUM_EFFECTS] = {
-        false,   // PREPROC_AGC
+        false,  // PREPROC_AGC
         true,   // PREPROC_AEC
         true,   // PREPROC_NS
 };
 
 bool gDualMicEnabled;
-FILE *gPcmDumpFh;
+FILE* gPcmDumpFh;
 static pthread_mutex_t gPcmDumpLock = PTHREAD_MUTEX_INITIALIZER;
 #endif
 
-
 //------------------------------------------------------------------------------
 // Effect descriptors
 //------------------------------------------------------------------------------
@@ -178,68 +178,69 @@
 
 // Automatic Gain Control
 static const effect_descriptor_t sAgcDescriptor = {
-        { 0x0a8abfe0, 0x654c, 0x11e0, 0xba26, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }, // type
-        { 0xaa8130e0, 0x66fc, 0x11e0, 0xbad0, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }, // uuid
+        {0x0a8abfe0, 0x654c, 0x11e0, 0xba26, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // type
+        {0xaa8130e0, 0x66fc, 0x11e0, 0xbad0, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // uuid
         EFFECT_CONTROL_API_VERSION,
-        (EFFECT_FLAG_TYPE_PRE_PROC|EFFECT_FLAG_DEVICE_IND),
-        0, //FIXME indicate CPU load
-        0, //FIXME indicate memory usage
+        (EFFECT_FLAG_TYPE_PRE_PROC | EFFECT_FLAG_DEVICE_IND),
+        0,  // FIXME indicate CPU load
+        0,  // FIXME indicate memory usage
         "Automatic Gain Control",
-        "The Android Open Source Project"
-};
+        "The Android Open Source Project"};
+
+// Automatic Gain Control 2
+static const effect_descriptor_t sAgc2Descriptor = {
+        {0xae3c653b, 0xbe18, 0x4ab8, 0x8938, {0x41, 0x8f, 0x0a, 0x7f, 0x06, 0xac}},  // type
+        {0x89f38e65, 0xd4d2, 0x4d64, 0xad0e, {0x2b, 0x3e, 0x79, 0x9e, 0xa8, 0x86}},  // uuid
+        EFFECT_CONTROL_API_VERSION,
+        (EFFECT_FLAG_TYPE_PRE_PROC | EFFECT_FLAG_DEVICE_IND),
+        0,  // FIXME indicate CPU load
+        0,  // FIXME indicate memory usage
+        "Automatic Gain Control 2",
+        "The Android Open Source Project"};
 
 // Acoustic Echo Cancellation
 static const effect_descriptor_t sAecDescriptor = {
-        { 0x7b491460, 0x8d4d, 0x11e0, 0xbd61, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }, // type
-        { 0xbb392ec0, 0x8d4d, 0x11e0, 0xa896, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }, // uuid
+        {0x7b491460, 0x8d4d, 0x11e0, 0xbd61, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // type
+        {0xbb392ec0, 0x8d4d, 0x11e0, 0xa896, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // uuid
         EFFECT_CONTROL_API_VERSION,
-        (EFFECT_FLAG_TYPE_PRE_PROC|EFFECT_FLAG_DEVICE_IND),
-        0, //FIXME indicate CPU load
-        0, //FIXME indicate memory usage
+        (EFFECT_FLAG_TYPE_PRE_PROC | EFFECT_FLAG_DEVICE_IND),
+        0,  // FIXME indicate CPU load
+        0,  // FIXME indicate memory usage
         "Acoustic Echo Canceler",
-        "The Android Open Source Project"
-};
+        "The Android Open Source Project"};
 
 // Noise suppression
 static const effect_descriptor_t sNsDescriptor = {
-        { 0x58b4b260, 0x8e06, 0x11e0, 0xaa8e, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }, // type
-        { 0xc06c8400, 0x8e06, 0x11e0, 0x9cb6, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }, // uuid
+        {0x58b4b260, 0x8e06, 0x11e0, 0xaa8e, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // type
+        {0xc06c8400, 0x8e06, 0x11e0, 0x9cb6, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // uuid
         EFFECT_CONTROL_API_VERSION,
-        (EFFECT_FLAG_TYPE_PRE_PROC|EFFECT_FLAG_DEVICE_IND),
-        0, //FIXME indicate CPU load
-        0, //FIXME indicate memory usage
+        (EFFECT_FLAG_TYPE_PRE_PROC | EFFECT_FLAG_DEVICE_IND),
+        0,  // FIXME indicate CPU load
+        0,  // FIXME indicate memory usage
         "Noise Suppression",
-        "The Android Open Source Project"
-};
+        "The Android Open Source Project"};
 
-
-static const effect_descriptor_t *sDescriptors[PREPROC_NUM_EFFECTS] = {
-        &sAgcDescriptor,
-        &sAecDescriptor,
-        &sNsDescriptor
-};
+static const effect_descriptor_t* sDescriptors[PREPROC_NUM_EFFECTS] = {&sAgcDescriptor,
+                                                                       &sAgc2Descriptor,
+                                                                       &sAecDescriptor,
+                                                                       &sNsDescriptor};
 
 //------------------------------------------------------------------------------
 // Helper functions
 //------------------------------------------------------------------------------
 
-const effect_uuid_t * const sUuidToPreProcTable[PREPROC_NUM_EFFECTS] = {
-        FX_IID_AGC,
-        FX_IID_AEC,
-        FX_IID_NS
-};
+const effect_uuid_t* const sUuidToPreProcTable[PREPROC_NUM_EFFECTS] = {FX_IID_AGC,
+                                                                       FX_IID_AGC2,
+                                                                       FX_IID_AEC, FX_IID_NS};
 
-
-const effect_uuid_t * ProcIdToUuid(int procId)
-{
+const effect_uuid_t* ProcIdToUuid(int procId) {
     if (procId >= PREPROC_NUM_EFFECTS) {
         return EFFECT_UUID_NULL;
     }
     return sUuidToPreProcTable[procId];
 }
 
-uint32_t UuidToProcId(const effect_uuid_t * uuid)
-{
+uint32_t UuidToProcId(const effect_uuid_t* uuid) {
     size_t i;
     for (i = 0; i < PREPROC_NUM_EFFECTS; i++) {
         if (memcmp(uuid, sUuidToPreProcTable[i], sizeof(*uuid)) == 0) {
@@ -249,15 +250,13 @@
     return i;
 }
 
-bool HasReverseStream(uint32_t procId)
-{
+bool HasReverseStream(uint32_t procId) {
     if (procId == PREPROC_AEC) {
         return true;
     }
     return false;
 }
 
-
 //------------------------------------------------------------------------------
 // Automatic Gain Control (AGC)
 //------------------------------------------------------------------------------
@@ -266,499 +265,538 @@
 static const int kAgcDefaultCompGain = 9;
 static const bool kAgcDefaultLimiter = true;
 
-int  AgcInit (preproc_effect_t *effect)
-{
-    ALOGV("AgcInit");
-    webrtc::GainControl *agc = static_cast<webrtc::GainControl *>(effect->engine);
-    agc->set_mode(webrtc::GainControl::kFixedDigital);
-    agc->set_target_level_dbfs(kAgcDefaultTargetLevel);
-    agc->set_compression_gain_db(kAgcDefaultCompGain);
-    agc->enable_limiter(kAgcDefaultLimiter);
+int Agc2Init(preproc_effect_t* effect) {
+    ALOGV("Agc2Init");
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.gain_controller2.fixed_digital.gain_db = 0.f;
+    effect->session->config.gain_controller2.adaptive_digital.level_estimator =
+            effect->session->config.gain_controller2.kRms;
+    effect->session->config.gain_controller2.adaptive_digital.extra_saturation_margin_db = 2.f;
+    effect->session->apm->ApplyConfig(effect->session->config);
     return 0;
 }
 
-int  AgcCreate(preproc_effect_t *effect)
-{
-    webrtc::GainControl *agc = effect->session->apm->gain_control();
-    ALOGV("AgcCreate got agc %p", agc);
-    if (agc == NULL) {
-        ALOGW("AgcCreate Error");
-        return -ENOMEM;
-    }
-    effect->engine = static_cast<preproc_fx_handle_t>(agc);
+int AgcInit(preproc_effect_t* effect) {
+    ALOGV("AgcInit");
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.gain_controller1.target_level_dbfs = kAgcDefaultTargetLevel;
+    effect->session->config.gain_controller1.compression_gain_db = kAgcDefaultCompGain;
+    effect->session->config.gain_controller1.enable_limiter = kAgcDefaultLimiter;
+    effect->session->apm->ApplyConfig(effect->session->config);
+    return 0;
+}
+
+int Agc2Create(preproc_effect_t* effect) {
+    Agc2Init(effect);
+    return 0;
+}
+
+int AgcCreate(preproc_effect_t* effect) {
     AgcInit(effect);
     return 0;
 }
 
-int AgcGetParameter(preproc_effect_t *effect,
-                    void *pParam,
-                    uint32_t *pValueSize,
-                    void *pValue)
-{
+int Agc2GetParameter(preproc_effect_t* effect, void* pParam, uint32_t* pValueSize, void* pValue) {
     int status = 0;
-    uint32_t param = *(uint32_t *)pParam;
-    t_agc_settings *pProperties = (t_agc_settings *)pValue;
-    webrtc::GainControl *agc = static_cast<webrtc::GainControl *>(effect->engine);
+    uint32_t param = *(uint32_t*)pParam;
+    agc2_settings_t* pProperties = (agc2_settings_t*)pValue;
 
     switch (param) {
-    case AGC_PARAM_TARGET_LEVEL:
-    case AGC_PARAM_COMP_GAIN:
-        if (*pValueSize < sizeof(int16_t)) {
-            *pValueSize = 0;
-            return -EINVAL;
-        }
-        break;
-    case AGC_PARAM_LIMITER_ENA:
-        if (*pValueSize < sizeof(bool)) {
-            *pValueSize = 0;
-            return -EINVAL;
-        }
-        break;
-    case AGC_PARAM_PROPERTIES:
-        if (*pValueSize < sizeof(t_agc_settings)) {
-            *pValueSize = 0;
-            return -EINVAL;
-        }
-        break;
+        case AGC2_PARAM_FIXED_DIGITAL_GAIN:
+            if (*pValueSize < sizeof(float)) {
+                *pValueSize = 0.f;
+                return -EINVAL;
+            }
+            break;
+        case AGC2_PARAM_ADAPT_DIGI_LEVEL_ESTIMATOR:
+            if (*pValueSize < sizeof(int32_t)) {
+                *pValueSize = 0;
+                return -EINVAL;
+            }
+            break;
+        case AGC2_PARAM_ADAPT_DIGI_EXTRA_SATURATION_MARGIN:
+            if (*pValueSize < sizeof(float)) {
+                *pValueSize = 0.f;
+                return -EINVAL;
+            }
+            break;
+        case AGC2_PARAM_PROPERTIES:
+            if (*pValueSize < sizeof(agc2_settings_t)) {
+                *pValueSize = 0;
+                return -EINVAL;
+            }
+            break;
 
-    default:
-        ALOGW("AgcGetParameter() unknown param %08x", param);
-        status = -EINVAL;
-        break;
+        default:
+            ALOGW("Agc2GetParameter() unknown param %08x", param);
+            status = -EINVAL;
+            break;
     }
 
+    effect->session->config = effect->session->apm->GetConfig();
     switch (param) {
-    case AGC_PARAM_TARGET_LEVEL:
-        *(int16_t *) pValue = (int16_t)(agc->target_level_dbfs() * -100);
-        ALOGV("AgcGetParameter() target level %d milliBels", *(int16_t *) pValue);
-        break;
-    case AGC_PARAM_COMP_GAIN:
-        *(int16_t *) pValue = (int16_t)(agc->compression_gain_db() * 100);
-        ALOGV("AgcGetParameter() comp gain %d milliBels", *(int16_t *) pValue);
-        break;
-    case AGC_PARAM_LIMITER_ENA:
-        *(bool *) pValue = (bool)agc->is_limiter_enabled();
-        ALOGV("AgcGetParameter() limiter enabled %s",
-             (*(int16_t *) pValue != 0) ? "true" : "false");
-        break;
-    case AGC_PARAM_PROPERTIES:
-        pProperties->targetLevel = (int16_t)(agc->target_level_dbfs() * -100);
-        pProperties->compGain = (int16_t)(agc->compression_gain_db() * 100);
-        pProperties->limiterEnabled = (bool)agc->is_limiter_enabled();
-        break;
-    default:
-        ALOGW("AgcGetParameter() unknown param %d", param);
-        status = -EINVAL;
-        break;
+        case AGC2_PARAM_FIXED_DIGITAL_GAIN:
+            *(float*)pValue =
+                    (float)(effect->session->config.gain_controller2.fixed_digital.gain_db);
+            ALOGV("Agc2GetParameter() target level %f dB", *(float*)pValue);
+            break;
+        case AGC2_PARAM_ADAPT_DIGI_LEVEL_ESTIMATOR:
+            *(uint32_t*)pValue = (uint32_t)(
+                    effect->session->config.gain_controller2.adaptive_digital.level_estimator);
+            ALOGV("Agc2GetParameter() level estimator %d",
+                  *(webrtc::AudioProcessing::Config::GainController2::LevelEstimator*)pValue);
+            break;
+        case AGC2_PARAM_ADAPT_DIGI_EXTRA_SATURATION_MARGIN:
+            *(float*)pValue = (float)(effect->session->config.gain_controller2.adaptive_digital
+                                              .extra_saturation_margin_db);
+            ALOGV("Agc2GetParameter() extra saturation margin %f dB", *(float*)pValue);
+            break;
+        case AGC2_PARAM_PROPERTIES:
+            pProperties->fixedDigitalGain =
+                    (float)(effect->session->config.gain_controller2.fixed_digital.gain_db);
+            pProperties->level_estimator = (uint32_t)(
+                    effect->session->config.gain_controller2.adaptive_digital.level_estimator);
+            pProperties->extraSaturationMargin =
+                    (float)(effect->session->config.gain_controller2.adaptive_digital
+                                    .extra_saturation_margin_db);
+            break;
+        default:
+            ALOGW("Agc2GetParameter() unknown param %d", param);
+            status = -EINVAL;
+            break;
+    }
+
+    return status;
+}
+
+int AgcGetParameter(preproc_effect_t* effect, void* pParam, uint32_t* pValueSize, void* pValue) {
+    int status = 0;
+    uint32_t param = *(uint32_t*)pParam;
+    t_agc_settings* pProperties = (t_agc_settings*)pValue;
+
+    switch (param) {
+        case AGC_PARAM_TARGET_LEVEL:
+        case AGC_PARAM_COMP_GAIN:
+            if (*pValueSize < sizeof(int16_t)) {
+                *pValueSize = 0;
+                return -EINVAL;
+            }
+            break;
+        case AGC_PARAM_LIMITER_ENA:
+            if (*pValueSize < sizeof(bool)) {
+                *pValueSize = 0;
+                return -EINVAL;
+            }
+            break;
+        case AGC_PARAM_PROPERTIES:
+            if (*pValueSize < sizeof(t_agc_settings)) {
+                *pValueSize = 0;
+                return -EINVAL;
+            }
+            break;
+
+        default:
+            ALOGW("AgcGetParameter() unknown param %08x", param);
+            status = -EINVAL;
+            break;
+    }
+
+    effect->session->config = effect->session->apm->GetConfig();
+    switch (param) {
+        case AGC_PARAM_TARGET_LEVEL:
+            *(int16_t*)pValue =
+                    (int16_t)(effect->session->config.gain_controller1.target_level_dbfs * -100);
+            ALOGV("AgcGetParameter() target level %d milliBels", *(int16_t*)pValue);
+            break;
+        case AGC_PARAM_COMP_GAIN:
+            *(int16_t*)pValue =
+                    (int16_t)(effect->session->config.gain_controller1.compression_gain_db * -100);
+            ALOGV("AgcGetParameter() comp gain %d milliBels", *(int16_t*)pValue);
+            break;
+        case AGC_PARAM_LIMITER_ENA:
+            *(bool*)pValue = (bool)(effect->session->config.gain_controller1.enable_limiter);
+            ALOGV("AgcGetParameter() limiter enabled %s",
+                  (*(int16_t*)pValue != 0) ? "true" : "false");
+            break;
+        case AGC_PARAM_PROPERTIES:
+            pProperties->targetLevel =
+                    (int16_t)(effect->session->config.gain_controller1.target_level_dbfs * -100);
+            pProperties->compGain =
+                    (int16_t)(effect->session->config.gain_controller1.compression_gain_db * -100);
+            pProperties->limiterEnabled =
+                    (bool)(effect->session->config.gain_controller1.enable_limiter);
+            break;
+        default:
+            ALOGW("AgcGetParameter() unknown param %d", param);
+            status = -EINVAL;
+            break;
     }
     return status;
 }
 
-int AgcSetParameter (preproc_effect_t *effect, void *pParam, void *pValue)
-{
+int Agc2SetParameter(preproc_effect_t* effect, void* pParam, void* pValue) {
     int status = 0;
-    uint32_t param = *(uint32_t *)pParam;
-    t_agc_settings *pProperties = (t_agc_settings *)pValue;
-    webrtc::GainControl *agc = static_cast<webrtc::GainControl *>(effect->engine);
-
+    uint32_t param = *(uint32_t*)pParam;
+    float valueFloat = 0.f;
+    agc2_settings_t* pProperties = (agc2_settings_t*)pValue;
+    effect->session->config = effect->session->apm->GetConfig();
     switch (param) {
-    case AGC_PARAM_TARGET_LEVEL:
-        ALOGV("AgcSetParameter() target level %d milliBels", *(int16_t *)pValue);
-        status = agc->set_target_level_dbfs(-(*(int16_t *)pValue / 100));
-        break;
-    case AGC_PARAM_COMP_GAIN:
-        ALOGV("AgcSetParameter() comp gain %d milliBels", *(int16_t *)pValue);
-        status = agc->set_compression_gain_db(*(int16_t *)pValue / 100);
-        break;
-    case AGC_PARAM_LIMITER_ENA:
-        ALOGV("AgcSetParameter() limiter enabled %s", *(bool *)pValue ? "true" : "false");
-        status = agc->enable_limiter(*(bool *)pValue);
-        break;
-    case AGC_PARAM_PROPERTIES:
-        ALOGV("AgcSetParameter() properties level %d, gain %d limiter %d",
-             pProperties->targetLevel,
-             pProperties->compGain,
-             pProperties->limiterEnabled);
-        status = agc->set_target_level_dbfs(-(pProperties->targetLevel / 100));
-        if (status != 0) break;
-        status = agc->set_compression_gain_db(pProperties->compGain / 100);
-        if (status != 0) break;
-        status = agc->enable_limiter(pProperties->limiterEnabled);
-        break;
-    default:
-        ALOGW("AgcSetParameter() unknown param %08x value %08x", param, *(uint32_t *)pValue);
-        status = -EINVAL;
-        break;
+        case AGC2_PARAM_FIXED_DIGITAL_GAIN:
+            valueFloat = (float)(*(int32_t*)pValue);
+            ALOGV("Agc2SetParameter() fixed digital gain %f dB", valueFloat);
+            effect->session->config.gain_controller2.fixed_digital.gain_db = valueFloat;
+            break;
+        case AGC2_PARAM_ADAPT_DIGI_LEVEL_ESTIMATOR:
+            ALOGV("Agc2SetParameter() level estimator %d",
+                  *(webrtc::AudioProcessing::Config::GainController2::LevelEstimator*)pValue);
+            effect->session->config.gain_controller2.adaptive_digital.level_estimator =
+                    (*(webrtc::AudioProcessing::Config::GainController2::LevelEstimator*)pValue);
+            break;
+        case AGC2_PARAM_ADAPT_DIGI_EXTRA_SATURATION_MARGIN:
+            valueFloat = (float)(*(int32_t*)pValue);
+            ALOGV("Agc2SetParameter() extra saturation margin %f dB", valueFloat);
+            effect->session->config.gain_controller2.adaptive_digital.extra_saturation_margin_db =
+                    valueFloat;
+            break;
+        case AGC2_PARAM_PROPERTIES:
+            ALOGV("Agc2SetParameter() properties gain %f, level %d margin %f",
+                  pProperties->fixedDigitalGain, pProperties->level_estimator,
+                  pProperties->extraSaturationMargin);
+            effect->session->config.gain_controller2.fixed_digital.gain_db =
+                    pProperties->fixedDigitalGain;
+            effect->session->config.gain_controller2.adaptive_digital.level_estimator =
+                    (webrtc::AudioProcessing::Config::GainController2::LevelEstimator)
+                            pProperties->level_estimator;
+            effect->session->config.gain_controller2.adaptive_digital.extra_saturation_margin_db =
+                    pProperties->extraSaturationMargin;
+            break;
+        default:
+            ALOGW("Agc2SetParameter() unknown param %08x value %08x", param, *(uint32_t*)pValue);
+            status = -EINVAL;
+            break;
     }
+    effect->session->apm->ApplyConfig(effect->session->config);
+
+    ALOGV("Agc2SetParameter() done status %d", status);
+
+    return status;
+}
+
+int AgcSetParameter(preproc_effect_t* effect, void* pParam, void* pValue) {
+    int status = 0;
+    uint32_t param = *(uint32_t*)pParam;
+    t_agc_settings* pProperties = (t_agc_settings*)pValue;
+    effect->session->config = effect->session->apm->GetConfig();
+    switch (param) {
+        case AGC_PARAM_TARGET_LEVEL:
+            ALOGV("AgcSetParameter() target level %d milliBels", *(int16_t*)pValue);
+            effect->session->config.gain_controller1.target_level_dbfs =
+                    (-(*(int16_t*)pValue / 100));
+            break;
+        case AGC_PARAM_COMP_GAIN:
+            ALOGV("AgcSetParameter() comp gain %d milliBels", *(int16_t*)pValue);
+            effect->session->config.gain_controller1.compression_gain_db =
+                    (*(int16_t*)pValue / 100);
+            break;
+        case AGC_PARAM_LIMITER_ENA:
+            ALOGV("AgcSetParameter() limiter enabled %s", *(bool*)pValue ? "true" : "false");
+            effect->session->config.gain_controller1.enable_limiter = (*(bool*)pValue);
+            break;
+        case AGC_PARAM_PROPERTIES:
+            ALOGV("AgcSetParameter() properties level %d, gain %d limiter %d",
+                  pProperties->targetLevel, pProperties->compGain, pProperties->limiterEnabled);
+            effect->session->config.gain_controller1.target_level_dbfs =
+                    -(pProperties->targetLevel / 100);
+            effect->session->config.gain_controller1.compression_gain_db =
+                    pProperties->compGain / 100;
+            effect->session->config.gain_controller1.enable_limiter = pProperties->limiterEnabled;
+            break;
+        default:
+            ALOGW("AgcSetParameter() unknown param %08x value %08x", param, *(uint32_t*)pValue);
+            status = -EINVAL;
+            break;
+    }
+    effect->session->apm->ApplyConfig(effect->session->config);
 
     ALOGV("AgcSetParameter() done status %d", status);
 
     return status;
 }
 
-void AgcEnable(preproc_effect_t *effect)
-{
-    webrtc::GainControl *agc = static_cast<webrtc::GainControl *>(effect->engine);
-    ALOGV("AgcEnable agc %p", agc);
-    agc->Enable(true);
+void Agc2Enable(preproc_effect_t* effect) {
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.gain_controller2.enabled = true;
+    effect->session->apm->ApplyConfig(effect->session->config);
 }
 
-void AgcDisable(preproc_effect_t *effect)
-{
-    ALOGV("AgcDisable");
-    webrtc::GainControl *agc = static_cast<webrtc::GainControl *>(effect->engine);
-    agc->Enable(false);
+void AgcEnable(preproc_effect_t* effect) {
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.gain_controller1.enabled = true;
+    effect->session->apm->ApplyConfig(effect->session->config);
 }
 
+void Agc2Disable(preproc_effect_t* effect) {
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.gain_controller2.enabled = false;
+    effect->session->apm->ApplyConfig(effect->session->config);
+}
 
-static const preproc_ops_t sAgcOps = {
-        AgcCreate,
-        AgcInit,
-        NULL,
-        AgcEnable,
-        AgcDisable,
-        AgcSetParameter,
-        AgcGetParameter,
-        NULL
-};
+void AgcDisable(preproc_effect_t* effect) {
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.gain_controller1.enabled = false;
+    effect->session->apm->ApplyConfig(effect->session->config);
+}
 
+static const preproc_ops_t sAgcOps = {AgcCreate,       AgcInit,         NULL, AgcEnable, AgcDisable,
+                                      AgcSetParameter, AgcGetParameter, NULL};
+
+static const preproc_ops_t sAgc2Ops = {Agc2Create,       Agc2Init,    NULL,
+                                       Agc2Enable,       Agc2Disable, Agc2SetParameter,
+                                       Agc2GetParameter, NULL};
 
 //------------------------------------------------------------------------------
 // Acoustic Echo Canceler (AEC)
 //------------------------------------------------------------------------------
 
-static const webrtc::EchoControlMobile::RoutingMode kAecDefaultMode =
-        webrtc::EchoControlMobile::kEarpiece;
-static const bool kAecDefaultComfortNoise = true;
 
-int  AecInit (preproc_effect_t *effect)
-{
+int AecInit(preproc_effect_t* effect) {
     ALOGV("AecInit");
-    webrtc::EchoControlMobile *aec = static_cast<webrtc::EchoControlMobile *>(effect->engine);
-    aec->set_routing_mode(kAecDefaultMode);
-    aec->enable_comfort_noise(kAecDefaultComfortNoise);
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.echo_canceller.mobile_mode = true;
+    effect->session->apm->ApplyConfig(effect->session->config);
     return 0;
 }
 
-int  AecCreate(preproc_effect_t *effect)
-{
-    webrtc::EchoControlMobile *aec = effect->session->apm->echo_control_mobile();
-    ALOGV("AecCreate got aec %p", aec);
-    if (aec == NULL) {
-        ALOGW("AgcCreate Error");
-        return -ENOMEM;
-    }
-    effect->engine = static_cast<preproc_fx_handle_t>(aec);
-    AecInit (effect);
+int AecCreate(preproc_effect_t* effect) {
+    AecInit(effect);
     return 0;
 }
 
-int AecGetParameter(preproc_effect_t  *effect,
-                    void              *pParam,
-                    uint32_t          *pValueSize,
-                    void              *pValue)
-{
+int AecGetParameter(preproc_effect_t* effect, void* pParam, uint32_t* pValueSize, void* pValue) {
     int status = 0;
-    uint32_t param = *(uint32_t *)pParam;
+    uint32_t param = *(uint32_t*)pParam;
 
     if (*pValueSize < sizeof(uint32_t)) {
         return -EINVAL;
     }
     switch (param) {
-    case AEC_PARAM_ECHO_DELAY:
-    case AEC_PARAM_PROPERTIES:
-        *(uint32_t *)pValue = 1000 * effect->session->apm->stream_delay_ms();
-        ALOGV("AecGetParameter() echo delay %d us", *(uint32_t *)pValue);
-        break;
-    default:
-        ALOGW("AecGetParameter() unknown param %08x value %08x", param, *(uint32_t *)pValue);
-        status = -EINVAL;
-        break;
+        case AEC_PARAM_ECHO_DELAY:
+        case AEC_PARAM_PROPERTIES:
+            *(uint32_t*)pValue = 1000 * effect->session->apm->stream_delay_ms();
+            ALOGV("AecGetParameter() echo delay %d us", *(uint32_t*)pValue);
+            break;
+        case AEC_PARAM_MOBILE_MODE:
+            effect->session->config = effect->session->apm->GetConfig();
+            *(uint32_t*)pValue = effect->session->config.echo_canceller.mobile_mode;
+            ALOGV("AecGetParameter() mobile mode %d us", *(uint32_t*)pValue);
+            break;
+        default:
+            ALOGW("AecGetParameter() unknown param %08x value %08x", param, *(uint32_t*)pValue);
+            status = -EINVAL;
+            break;
     }
     return status;
 }
 
-int AecSetParameter (preproc_effect_t *effect, void *pParam, void *pValue)
-{
+int AecSetParameter(preproc_effect_t* effect, void* pParam, void* pValue) {
     int status = 0;
-    uint32_t param = *(uint32_t *)pParam;
-    uint32_t value = *(uint32_t *)pValue;
+    uint32_t param = *(uint32_t*)pParam;
+    uint32_t value = *(uint32_t*)pValue;
 
     switch (param) {
-    case AEC_PARAM_ECHO_DELAY:
-    case AEC_PARAM_PROPERTIES:
-        status = effect->session->apm->set_stream_delay_ms(value/1000);
-        ALOGV("AecSetParameter() echo delay %d us, status %d", value, status);
-        break;
-    default:
-        ALOGW("AecSetParameter() unknown param %08x value %08x", param, *(uint32_t *)pValue);
-        status = -EINVAL;
-        break;
+        case AEC_PARAM_ECHO_DELAY:
+        case AEC_PARAM_PROPERTIES:
+            status = effect->session->apm->set_stream_delay_ms(value / 1000);
+            ALOGV("AecSetParameter() echo delay %d us, status %d", value, status);
+            break;
+        case AEC_PARAM_MOBILE_MODE:
+            effect->session->config = effect->session->apm->GetConfig();
+            effect->session->config.echo_canceller.mobile_mode = value;
+            ALOGV("AecSetParameter() mobile mode %d us", value);
+            effect->session->apm->ApplyConfig(effect->session->config);
+            break;
+        default:
+            ALOGW("AecSetParameter() unknown param %08x value %08x", param, *(uint32_t*)pValue);
+            status = -EINVAL;
+            break;
     }
     return status;
 }
 
-void AecEnable(preproc_effect_t *effect)
-{
-    webrtc::EchoControlMobile *aec = static_cast<webrtc::EchoControlMobile *>(effect->engine);
-    ALOGV("AecEnable aec %p", aec);
-    aec->Enable(true);
+void AecEnable(preproc_effect_t* effect) {
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.echo_canceller.enabled = true;
+    effect->session->apm->ApplyConfig(effect->session->config);
 }
 
-void AecDisable(preproc_effect_t *effect)
-{
-    ALOGV("AecDisable");
-    webrtc::EchoControlMobile *aec = static_cast<webrtc::EchoControlMobile *>(effect->engine);
-    aec->Enable(false);
+void AecDisable(preproc_effect_t* effect) {
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.echo_canceller.enabled = false;
+    effect->session->apm->ApplyConfig(effect->session->config);
 }
 
-int AecSetDevice(preproc_effect_t *effect, uint32_t device)
-{
+int AecSetDevice(preproc_effect_t* effect, uint32_t device) {
     ALOGV("AecSetDevice %08x", device);
-    webrtc::EchoControlMobile *aec = static_cast<webrtc::EchoControlMobile *>(effect->engine);
-    webrtc::EchoControlMobile::RoutingMode mode = webrtc::EchoControlMobile::kQuietEarpieceOrHeadset;
 
     if (audio_is_input_device(device)) {
         return 0;
     }
 
-    switch(device) {
-    case AUDIO_DEVICE_OUT_EARPIECE:
-        mode = webrtc::EchoControlMobile::kEarpiece;
-        break;
-    case AUDIO_DEVICE_OUT_SPEAKER:
-        mode = webrtc::EchoControlMobile::kSpeakerphone;
-        break;
-    case AUDIO_DEVICE_OUT_WIRED_HEADSET:
-    case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
-    case AUDIO_DEVICE_OUT_USB_HEADSET:
-    default:
-        break;
-    }
-    aec->set_routing_mode(mode);
     return 0;
 }
 
-static const preproc_ops_t sAecOps = {
-        AecCreate,
-        AecInit,
-        NULL,
-        AecEnable,
-        AecDisable,
-        AecSetParameter,
-        AecGetParameter,
-        AecSetDevice
-};
+static const preproc_ops_t sAecOps = {AecCreate,       AecInit,     NULL,
+                                      AecEnable,       AecDisable,  AecSetParameter,
+                                      AecGetParameter, AecSetDevice};
 
 //------------------------------------------------------------------------------
 // Noise Suppression (NS)
 //------------------------------------------------------------------------------
 
-static const webrtc::NoiseSuppression::Level kNsDefaultLevel = webrtc::NoiseSuppression::kModerate;
+static const webrtc::AudioProcessing::Config::NoiseSuppression::Level kNsDefaultLevel =
+        webrtc::AudioProcessing::Config::NoiseSuppression::kModerate;
 
-int  NsInit (preproc_effect_t *effect)
-{
+int NsInit(preproc_effect_t* effect) {
     ALOGV("NsInit");
-    webrtc::NoiseSuppression *ns = static_cast<webrtc::NoiseSuppression *>(effect->engine);
-    ns->set_level(kNsDefaultLevel);
-    webrtc::Config config;
-    std::vector<webrtc::Point> geometry;
-    // TODO(aluebs): Make the geometry settable.
-    geometry.push_back(webrtc::Point(-0.03f, 0.f, 0.f));
-    geometry.push_back(webrtc::Point(-0.01f, 0.f, 0.f));
-    geometry.push_back(webrtc::Point(0.01f, 0.f, 0.f));
-    geometry.push_back(webrtc::Point(0.03f, 0.f, 0.f));
-    // The geometry needs to be set with Beamforming enabled.
-    config.Set<webrtc::Beamforming>(
-            new webrtc::Beamforming(true, geometry));
-    effect->session->apm->SetExtraOptions(config);
-    config.Set<webrtc::Beamforming>(
-            new webrtc::Beamforming(false, geometry));
-    effect->session->apm->SetExtraOptions(config);
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.noise_suppression.level = kNsDefaultLevel;
+    effect->session->apm->ApplyConfig(effect->session->config);
     effect->type = NS_TYPE_SINGLE_CHANNEL;
     return 0;
 }
 
-int  NsCreate(preproc_effect_t *effect)
-{
-    webrtc::NoiseSuppression *ns = effect->session->apm->noise_suppression();
-    ALOGV("NsCreate got ns %p", ns);
-    if (ns == NULL) {
-        ALOGW("AgcCreate Error");
-        return -ENOMEM;
-    }
-    effect->engine = static_cast<preproc_fx_handle_t>(ns);
-    NsInit (effect);
+int NsCreate(preproc_effect_t* effect) {
+    NsInit(effect);
     return 0;
 }
 
-int NsGetParameter(preproc_effect_t  *effect __unused,
-                   void              *pParam __unused,
-                   uint32_t          *pValueSize __unused,
-                   void              *pValue __unused)
-{
+int NsGetParameter(preproc_effect_t* effect __unused, void* pParam __unused,
+                   uint32_t* pValueSize __unused, void* pValue __unused) {
     int status = 0;
     return status;
 }
 
-int NsSetParameter (preproc_effect_t *effect, void *pParam, void *pValue)
-{
+int NsSetParameter(preproc_effect_t* effect, void* pParam, void* pValue) {
     int status = 0;
-    webrtc::NoiseSuppression *ns = static_cast<webrtc::NoiseSuppression *>(effect->engine);
-    uint32_t param = *(uint32_t *)pParam;
-    uint32_t value = *(uint32_t *)pValue;
-    switch(param) {
+    uint32_t param = *(uint32_t*)pParam;
+    uint32_t value = *(uint32_t*)pValue;
+    effect->session->config = effect->session->apm->GetConfig();
+    switch (param) {
         case NS_PARAM_LEVEL:
-            ns->set_level((webrtc::NoiseSuppression::Level)value);
+            effect->session->config.noise_suppression.level =
+                    (webrtc::AudioProcessing::Config::NoiseSuppression::Level)value;
             ALOGV("NsSetParameter() level %d", value);
             break;
-        case NS_PARAM_TYPE:
-        {
-            webrtc::Config config;
-            std::vector<webrtc::Point> geometry;
-            bool is_beamforming_enabled =
-                    value == NS_TYPE_MULTI_CHANNEL && ns->is_enabled();
-            config.Set<webrtc::Beamforming>(
-                    new webrtc::Beamforming(is_beamforming_enabled, geometry));
-            effect->session->apm->SetExtraOptions(config);
-            effect->type = value;
-            ALOGV("NsSetParameter() type %d", value);
-            break;
-        }
         default:
             ALOGW("NsSetParameter() unknown param %08x value %08x", param, value);
             status = -EINVAL;
     }
+    effect->session->apm->ApplyConfig(effect->session->config);
 
     return status;
 }
 
-void NsEnable(preproc_effect_t *effect)
-{
-    webrtc::NoiseSuppression *ns = static_cast<webrtc::NoiseSuppression *>(effect->engine);
-    ALOGV("NsEnable ns %p", ns);
-    ns->Enable(true);
-    if (effect->type == NS_TYPE_MULTI_CHANNEL) {
-        webrtc::Config config;
-        std::vector<webrtc::Point> geometry;
-        config.Set<webrtc::Beamforming>(new webrtc::Beamforming(true, geometry));
-        effect->session->apm->SetExtraOptions(config);
-    }
+void NsEnable(preproc_effect_t* effect) {
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.noise_suppression.enabled = true;
+    effect->session->apm->ApplyConfig(effect->session->config);
 }
 
-void NsDisable(preproc_effect_t *effect)
-{
+void NsDisable(preproc_effect_t* effect) {
     ALOGV("NsDisable");
-    webrtc::NoiseSuppression *ns = static_cast<webrtc::NoiseSuppression *>(effect->engine);
-    ns->Enable(false);
-    webrtc::Config config;
-    std::vector<webrtc::Point> geometry;
-    config.Set<webrtc::Beamforming>(new webrtc::Beamforming(false, geometry));
-    effect->session->apm->SetExtraOptions(config);
+    effect->session->config = effect->session->apm->GetConfig();
+    effect->session->config.noise_suppression.enabled = false;
+    effect->session->apm->ApplyConfig(effect->session->config);
 }
 
-static const preproc_ops_t sNsOps = {
-        NsCreate,
-        NsInit,
-        NULL,
-        NsEnable,
-        NsDisable,
-        NsSetParameter,
-        NsGetParameter,
-        NULL
-};
+static const preproc_ops_t sNsOps = {NsCreate,  NsInit,         NULL,           NsEnable,
+                                     NsDisable, NsSetParameter, NsGetParameter, NULL};
 
-
-static const preproc_ops_t *sPreProcOps[PREPROC_NUM_EFFECTS] = {
-        &sAgcOps,
-        &sAecOps,
-        &sNsOps
-};
-
+static const preproc_ops_t* sPreProcOps[PREPROC_NUM_EFFECTS] = {&sAgcOps,
+                                                                &sAgc2Ops,
+                                                                &sAecOps, &sNsOps};
 
 //------------------------------------------------------------------------------
 // Effect functions
 //------------------------------------------------------------------------------
 
-void Session_SetProcEnabled(preproc_session_t *session, uint32_t procId, bool enabled);
+void Session_SetProcEnabled(preproc_session_t* session, uint32_t procId, bool enabled);
 
 extern "C" const struct effect_interface_s sEffectInterface;
 extern "C" const struct effect_interface_s sEffectInterfaceReverse;
 
-#define BAD_STATE_ABORT(from, to) \
-        LOG_ALWAYS_FATAL("Bad state transition from %d to %d", from, to);
+#define BAD_STATE_ABORT(from, to) LOG_ALWAYS_FATAL("Bad state transition from %d to %d", from, to);
 
-int Effect_SetState(preproc_effect_t *effect, uint32_t state)
-{
+int Effect_SetState(preproc_effect_t* effect, uint32_t state) {
     int status = 0;
     ALOGV("Effect_SetState proc %d, new %d old %d", effect->procId, state, effect->state);
-    switch(state) {
-    case PREPROC_EFFECT_STATE_INIT:
-        switch(effect->state) {
-        case PREPROC_EFFECT_STATE_ACTIVE:
-            effect->ops->disable(effect);
-            Session_SetProcEnabled(effect->session, effect->procId, false);
+    switch (state) {
+        case PREPROC_EFFECT_STATE_INIT:
+            switch (effect->state) {
+                case PREPROC_EFFECT_STATE_ACTIVE:
+                    effect->ops->disable(effect);
+                    Session_SetProcEnabled(effect->session, effect->procId, false);
+                    break;
+                case PREPROC_EFFECT_STATE_CONFIG:
+                case PREPROC_EFFECT_STATE_CREATED:
+                case PREPROC_EFFECT_STATE_INIT:
+                    break;
+                default:
+                    BAD_STATE_ABORT(effect->state, state);
+            }
+            break;
+        case PREPROC_EFFECT_STATE_CREATED:
+            switch (effect->state) {
+                case PREPROC_EFFECT_STATE_INIT:
+                    status = effect->ops->create(effect);
+                    break;
+                case PREPROC_EFFECT_STATE_CREATED:
+                case PREPROC_EFFECT_STATE_ACTIVE:
+                case PREPROC_EFFECT_STATE_CONFIG:
+                    ALOGE("Effect_SetState invalid transition");
+                    status = -ENOSYS;
+                    break;
+                default:
+                    BAD_STATE_ABORT(effect->state, state);
+            }
             break;
         case PREPROC_EFFECT_STATE_CONFIG:
-        case PREPROC_EFFECT_STATE_CREATED:
-        case PREPROC_EFFECT_STATE_INIT:
+            switch (effect->state) {
+                case PREPROC_EFFECT_STATE_INIT:
+                    ALOGE("Effect_SetState invalid transition");
+                    status = -ENOSYS;
+                    break;
+                case PREPROC_EFFECT_STATE_ACTIVE:
+                    effect->ops->disable(effect);
+                    Session_SetProcEnabled(effect->session, effect->procId, false);
+                    break;
+                case PREPROC_EFFECT_STATE_CREATED:
+                case PREPROC_EFFECT_STATE_CONFIG:
+                    break;
+                default:
+                    BAD_STATE_ABORT(effect->state, state);
+            }
+            break;
+        case PREPROC_EFFECT_STATE_ACTIVE:
+            switch (effect->state) {
+                case PREPROC_EFFECT_STATE_INIT:
+                case PREPROC_EFFECT_STATE_CREATED:
+                    ALOGE("Effect_SetState invalid transition");
+                    status = -ENOSYS;
+                    break;
+                case PREPROC_EFFECT_STATE_ACTIVE:
+                    // enabling an already enabled effect is just ignored
+                    break;
+                case PREPROC_EFFECT_STATE_CONFIG:
+                    effect->ops->enable(effect);
+                    Session_SetProcEnabled(effect->session, effect->procId, true);
+                    break;
+                default:
+                    BAD_STATE_ABORT(effect->state, state);
+            }
             break;
         default:
             BAD_STATE_ABORT(effect->state, state);
-        }
-        break;
-    case PREPROC_EFFECT_STATE_CREATED:
-        switch(effect->state) {
-        case PREPROC_EFFECT_STATE_INIT:
-            status = effect->ops->create(effect);
-            break;
-        case PREPROC_EFFECT_STATE_CREATED:
-        case PREPROC_EFFECT_STATE_ACTIVE:
-        case PREPROC_EFFECT_STATE_CONFIG:
-            ALOGE("Effect_SetState invalid transition");
-            status = -ENOSYS;
-            break;
-        default:
-            BAD_STATE_ABORT(effect->state, state);
-        }
-        break;
-    case PREPROC_EFFECT_STATE_CONFIG:
-        switch(effect->state) {
-        case PREPROC_EFFECT_STATE_INIT:
-            ALOGE("Effect_SetState invalid transition");
-            status = -ENOSYS;
-            break;
-        case PREPROC_EFFECT_STATE_ACTIVE:
-            effect->ops->disable(effect);
-            Session_SetProcEnabled(effect->session, effect->procId, false);
-            break;
-        case PREPROC_EFFECT_STATE_CREATED:
-        case PREPROC_EFFECT_STATE_CONFIG:
-            break;
-        default:
-            BAD_STATE_ABORT(effect->state, state);
-        }
-        break;
-    case PREPROC_EFFECT_STATE_ACTIVE:
-        switch(effect->state) {
-        case PREPROC_EFFECT_STATE_INIT:
-        case PREPROC_EFFECT_STATE_CREATED:
-            ALOGE("Effect_SetState invalid transition");
-            status = -ENOSYS;
-            break;
-        case PREPROC_EFFECT_STATE_ACTIVE:
-            // enabling an already enabled effect is just ignored
-            break;
-        case PREPROC_EFFECT_STATE_CONFIG:
-            effect->ops->enable(effect);
-            Session_SetProcEnabled(effect->session, effect->procId, true);
-            break;
-        default:
-            BAD_STATE_ABORT(effect->state, state);
-        }
-        break;
-    default:
-        BAD_STATE_ABORT(effect->state, state);
     }
     if (status == 0) {
         effect->state = state;
@@ -766,8 +804,7 @@
     return status;
 }
 
-int Effect_Init(preproc_effect_t *effect, uint32_t procId)
-{
+int Effect_Init(preproc_effect_t* effect, uint32_t procId) {
     if (HasReverseStream(procId)) {
         effect->itfe = &sEffectInterfaceReverse;
     } else {
@@ -779,21 +816,17 @@
     return 0;
 }
 
-int Effect_Create(preproc_effect_t *effect,
-               preproc_session_t *session,
-               effect_handle_t  *interface)
-{
+int Effect_Create(preproc_effect_t* effect, preproc_session_t* session,
+                  effect_handle_t* interface) {
     effect->session = session;
     *interface = (effect_handle_t)&effect->itfe;
     return Effect_SetState(effect, PREPROC_EFFECT_STATE_CREATED);
 }
 
-int Effect_Release(preproc_effect_t *effect)
-{
+int Effect_Release(preproc_effect_t* effect) {
     return Effect_SetState(effect, PREPROC_EFFECT_STATE_INIT);
 }
 
-
 //------------------------------------------------------------------------------
 // Session functions
 //------------------------------------------------------------------------------
@@ -803,8 +836,7 @@
 static const int kPreprocDefaultSr = 16000;
 static const int kPreProcDefaultCnl = 1;
 
-int Session_Init(preproc_session_t *session)
-{
+int Session_Init(preproc_session_t* session) {
     size_t i;
     int status = 0;
 
@@ -812,66 +844,45 @@
     session->id = 0;
     session->io = 0;
     session->createdMsk = 0;
-    session->apm = NULL;
     for (i = 0; i < PREPROC_NUM_EFFECTS && status == 0; i++) {
         status = Effect_Init(&session->effects[i], i);
     }
     return status;
 }
 
-
-extern "C" int Session_CreateEffect(preproc_session_t *session,
-                                    int32_t procId,
-                                    effect_handle_t  *interface)
-{
+extern "C" int Session_CreateEffect(preproc_session_t* session, int32_t procId,
+                                    effect_handle_t* interface) {
     int status = -ENOMEM;
 
     ALOGV("Session_CreateEffect procId %d, createdMsk %08x", procId, session->createdMsk);
 
     if (session->createdMsk == 0) {
-        session->apm = webrtc::AudioProcessing::Create();
+        session->apm = session->ap_builder.Create();
         if (session->apm == NULL) {
             ALOGW("Session_CreateEffect could not get apm engine");
             goto error;
         }
-        const webrtc::ProcessingConfig processing_config = {
-            {{kPreprocDefaultSr, kPreProcDefaultCnl},
-             {kPreprocDefaultSr, kPreProcDefaultCnl},
-             {kPreprocDefaultSr, kPreProcDefaultCnl},
-             {kPreprocDefaultSr, kPreProcDefaultCnl}}};
-        session->apm->Initialize(processing_config);
-        session->procFrame = new webrtc::AudioFrame();
-        if (session->procFrame == NULL) {
-            ALOGW("Session_CreateEffect could not allocate audio frame");
-            goto error;
-        }
-        session->revFrame = new webrtc::AudioFrame();
-        if (session->revFrame == NULL) {
-            ALOGW("Session_CreateEffect could not allocate reverse audio frame");
-            goto error;
-        }
         session->apmSamplingRate = kPreprocDefaultSr;
         session->apmFrameCount = (kPreprocDefaultSr) / 100;
         session->frameCount = session->apmFrameCount;
         session->samplingRate = kPreprocDefaultSr;
         session->inChannelCount = kPreProcDefaultCnl;
         session->outChannelCount = kPreProcDefaultCnl;
-        session->procFrame->sample_rate_hz_ = kPreprocDefaultSr;
-        session->procFrame->num_channels_ = kPreProcDefaultCnl;
+        session->inputConfig.set_sample_rate_hz(kPreprocDefaultSr);
+        session->inputConfig.set_num_channels(kPreProcDefaultCnl);
+        session->outputConfig.set_sample_rate_hz(kPreprocDefaultSr);
+        session->outputConfig.set_num_channels(kPreProcDefaultCnl);
         session->revChannelCount = kPreProcDefaultCnl;
-        session->revFrame->sample_rate_hz_ = kPreprocDefaultSr;
-        session->revFrame->num_channels_ = kPreProcDefaultCnl;
+        session->revConfig.set_sample_rate_hz(kPreprocDefaultSr);
+        session->revConfig.set_num_channels(kPreProcDefaultCnl);
         session->enabledMsk = 0;
         session->processedMsk = 0;
         session->revEnabledMsk = 0;
         session->revProcessedMsk = 0;
-        session->inResampler = NULL;
         session->inBuf = NULL;
         session->inBufSize = 0;
-        session->outResampler = NULL;
         session->outBuf = NULL;
         session->outBufSize = 0;
-        session->revResampler = NULL;
         session->revBuf = NULL;
         session->revBufSize = 0;
     }
@@ -880,45 +891,23 @@
         goto error;
     }
     ALOGV("Session_CreateEffect OK");
-    session->createdMsk |= (1<<procId);
+    session->createdMsk |= (1 << procId);
     return status;
 
 error:
     if (session->createdMsk == 0) {
-        delete session->revFrame;
-        session->revFrame = NULL;
-        delete session->procFrame;
-        session->procFrame = NULL;
         delete session->apm;
-        session->apm = NULL; // NOLINT(clang-analyzer-cplusplus.NewDelete)
+        session->apm = NULL;
     }
     return status;
 }
 
-int Session_ReleaseEffect(preproc_session_t *session,
-                          preproc_effect_t *fx)
-{
+int Session_ReleaseEffect(preproc_session_t* session, preproc_effect_t* fx) {
     ALOGW_IF(Effect_Release(fx) != 0, " Effect_Release() failed for proc ID %d", fx->procId);
-    session->createdMsk &= ~(1<<fx->procId);
+    session->createdMsk &= ~(1 << fx->procId);
     if (session->createdMsk == 0) {
         delete session->apm;
         session->apm = NULL;
-        delete session->procFrame;
-        session->procFrame = NULL;
-        delete session->revFrame;
-        session->revFrame = NULL;
-        if (session->inResampler != NULL) {
-            speex_resampler_destroy(session->inResampler);
-            session->inResampler = NULL;
-        }
-        if (session->outResampler != NULL) {
-            speex_resampler_destroy(session->outResampler);
-            session->outResampler = NULL;
-        }
-        if (session->revResampler != NULL) {
-            speex_resampler_destroy(session->revResampler);
-            session->revResampler = NULL;
-        }
         delete session->inBuf;
         session->inBuf = NULL;
         delete session->outBuf;
@@ -932,9 +921,7 @@
     return 0;
 }
 
-
-int Session_SetConfig(preproc_session_t *session, effect_config_t *config)
-{
+int Session_SetConfig(preproc_session_t* session, effect_config_t* config) {
     uint32_t inCnl = audio_channel_count_from_in_mask(config->inputCfg.channels);
     uint32_t outCnl = audio_channel_count_from_in_mask(config->outputCfg.channels);
 
@@ -944,46 +931,37 @@
         return -EINVAL;
     }
 
-    ALOGV("Session_SetConfig sr %d cnl %08x",
-         config->inputCfg.samplingRate, config->inputCfg.channels);
-    int status;
+    ALOGV("Session_SetConfig sr %d cnl %08x", config->inputCfg.samplingRate,
+          config->inputCfg.channels);
 
     // AEC implementation is limited to 16kHz
     if (config->inputCfg.samplingRate >= 32000 && !(session->createdMsk & (1 << PREPROC_AEC))) {
         session->apmSamplingRate = 32000;
-    } else
-    if (config->inputCfg.samplingRate >= 16000) {
+    } else if (config->inputCfg.samplingRate >= 16000) {
         session->apmSamplingRate = 16000;
     } else if (config->inputCfg.samplingRate >= 8000) {
         session->apmSamplingRate = 8000;
     }
 
-    const webrtc::ProcessingConfig processing_config = {
-      {{static_cast<int>(session->apmSamplingRate), inCnl},
-       {static_cast<int>(session->apmSamplingRate), outCnl},
-       {static_cast<int>(session->apmSamplingRate), inCnl},
-       {static_cast<int>(session->apmSamplingRate), inCnl}}};
-    status = session->apm->Initialize(processing_config);
-    if (status < 0) {
-        return -EINVAL;
-    }
 
     session->samplingRate = config->inputCfg.samplingRate;
     session->apmFrameCount = session->apmSamplingRate / 100;
     if (session->samplingRate == session->apmSamplingRate) {
         session->frameCount = session->apmFrameCount;
     } else {
-        session->frameCount = (session->apmFrameCount * session->samplingRate) /
-                session->apmSamplingRate  + 1;
+        session->frameCount =
+                (session->apmFrameCount * session->samplingRate) / session->apmSamplingRate;
     }
     session->inChannelCount = inCnl;
     session->outChannelCount = outCnl;
-    session->procFrame->num_channels_ = inCnl;
-    session->procFrame->sample_rate_hz_ = session->apmSamplingRate;
+    session->inputConfig.set_sample_rate_hz(session->samplingRate);
+    session->inputConfig.set_num_channels(inCnl);
+    session->outputConfig.set_sample_rate_hz(session->samplingRate);
+    session->outputConfig.set_num_channels(inCnl);
 
     session->revChannelCount = inCnl;
-    session->revFrame->num_channels_ = inCnl;
-    session->revFrame->sample_rate_hz_ = session->apmSamplingRate;
+    session->revConfig.set_sample_rate_hz(session->samplingRate);
+    session->revConfig.set_num_channels(inCnl);
 
     // force process buffer reallocation
     session->inBufSize = 0;
@@ -992,64 +970,11 @@
     session->framesOut = 0;
 
 
-    if (session->inResampler != NULL) {
-        speex_resampler_destroy(session->inResampler);
-        session->inResampler = NULL;
-    }
-    if (session->outResampler != NULL) {
-        speex_resampler_destroy(session->outResampler);
-        session->outResampler = NULL;
-    }
-    if (session->revResampler != NULL) {
-        speex_resampler_destroy(session->revResampler);
-        session->revResampler = NULL;
-    }
-    if (session->samplingRate != session->apmSamplingRate) {
-        int error;
-        session->inResampler = speex_resampler_init(session->inChannelCount,
-                                                    session->samplingRate,
-                                                    session->apmSamplingRate,
-                                                    RESAMPLER_QUALITY,
-                                                    &error);
-        if (session->inResampler == NULL) {
-            ALOGW("Session_SetConfig Cannot create speex resampler: %s",
-                 speex_resampler_strerror(error));
-            return -EINVAL;
-        }
-        session->outResampler = speex_resampler_init(session->outChannelCount,
-                                                    session->apmSamplingRate,
-                                                    session->samplingRate,
-                                                    RESAMPLER_QUALITY,
-                                                    &error);
-        if (session->outResampler == NULL) {
-            ALOGW("Session_SetConfig Cannot create speex resampler: %s",
-                 speex_resampler_strerror(error));
-            speex_resampler_destroy(session->inResampler);
-            session->inResampler = NULL;
-            return -EINVAL;
-        }
-        session->revResampler = speex_resampler_init(session->inChannelCount,
-                                                    session->samplingRate,
-                                                    session->apmSamplingRate,
-                                                    RESAMPLER_QUALITY,
-                                                    &error);
-        if (session->revResampler == NULL) {
-            ALOGW("Session_SetConfig Cannot create speex resampler: %s",
-                 speex_resampler_strerror(error));
-            speex_resampler_destroy(session->inResampler);
-            session->inResampler = NULL;
-            speex_resampler_destroy(session->outResampler);
-            session->outResampler = NULL;
-            return -EINVAL;
-        }
-    }
-
     session->state = PREPROC_SESSION_STATE_CONFIG;
     return 0;
 }
 
-void Session_GetConfig(preproc_session_t *session, effect_config_t *config)
-{
+void Session_GetConfig(preproc_session_t* session, effect_config_t* config) {
     memset(config, 0, sizeof(effect_config_t));
     config->inputCfg.samplingRate = config->outputCfg.samplingRate = session->samplingRate;
     config->inputCfg.format = config->outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
@@ -1060,37 +985,25 @@
             (EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT);
 }
 
-int Session_SetReverseConfig(preproc_session_t *session, effect_config_t *config)
-{
+int Session_SetReverseConfig(preproc_session_t* session, effect_config_t* config) {
     if (config->inputCfg.samplingRate != config->outputCfg.samplingRate ||
-            config->inputCfg.format != config->outputCfg.format ||
-            config->inputCfg.format != AUDIO_FORMAT_PCM_16_BIT) {
+        config->inputCfg.format != config->outputCfg.format ||
+        config->inputCfg.format != AUDIO_FORMAT_PCM_16_BIT) {
         return -EINVAL;
     }
 
-    ALOGV("Session_SetReverseConfig sr %d cnl %08x",
-         config->inputCfg.samplingRate, config->inputCfg.channels);
+    ALOGV("Session_SetReverseConfig sr %d cnl %08x", config->inputCfg.samplingRate,
+          config->inputCfg.channels);
 
     if (session->state < PREPROC_SESSION_STATE_CONFIG) {
         return -ENOSYS;
     }
     if (config->inputCfg.samplingRate != session->samplingRate ||
-            config->inputCfg.format != AUDIO_FORMAT_PCM_16_BIT) {
+        config->inputCfg.format != AUDIO_FORMAT_PCM_16_BIT) {
         return -EINVAL;
     }
     uint32_t inCnl = audio_channel_count_from_out_mask(config->inputCfg.channels);
-    const webrtc::ProcessingConfig processing_config = {
-       {{static_cast<int>(session->apmSamplingRate), session->inChannelCount},
-        {static_cast<int>(session->apmSamplingRate), session->outChannelCount},
-        {static_cast<int>(session->apmSamplingRate), inCnl},
-        {static_cast<int>(session->apmSamplingRate), inCnl}}};
-    int status = session->apm->Initialize(processing_config);
-    if (status < 0) {
-        return -EINVAL;
-    }
     session->revChannelCount = inCnl;
-    session->revFrame->num_channels_ = inCnl;
-    session->revFrame->sample_rate_hz_ = session->apmSamplingRate;
     // force process buffer reallocation
     session->revBufSize = 0;
     session->framesRev = 0;
@@ -1098,8 +1011,7 @@
     return 0;
 }
 
-void Session_GetReverseConfig(preproc_session_t *session, effect_config_t *config)
-{
+void Session_GetReverseConfig(preproc_session_t* session, effect_config_t* config) {
     memset(config, 0, sizeof(effect_config_t));
     config->inputCfg.samplingRate = config->outputCfg.samplingRate = session->samplingRate;
     config->inputCfg.format = config->outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
@@ -1109,25 +1021,14 @@
             (EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT);
 }
 
-void Session_SetProcEnabled(preproc_session_t *session, uint32_t procId, bool enabled)
-{
+void Session_SetProcEnabled(preproc_session_t* session, uint32_t procId, bool enabled) {
     if (enabled) {
-        if(session->enabledMsk == 0) {
+        if (session->enabledMsk == 0) {
             session->framesIn = 0;
-            if (session->inResampler != NULL) {
-                speex_resampler_reset_mem(session->inResampler);
-            }
-            session->framesOut = 0;
-            if (session->outResampler != NULL) {
-                speex_resampler_reset_mem(session->outResampler);
-            }
         }
         session->enabledMsk |= (1 << procId);
         if (HasReverseStream(procId)) {
             session->framesRev = 0;
-            if (session->revResampler != NULL) {
-                speex_resampler_reset_mem(session->revResampler);
-            }
             session->revEnabledMsk |= (1 << procId);
         }
     } else {
@@ -1136,8 +1037,8 @@
             session->revEnabledMsk &= ~(1 << procId);
         }
     }
-    ALOGV("Session_SetProcEnabled proc %d, enabled %d enabledMsk %08x revEnabledMsk %08x",
-         procId, enabled, session->enabledMsk, session->revEnabledMsk);
+    ALOGV("Session_SetProcEnabled proc %d, enabled %d enabledMsk %08x revEnabledMsk %08x", procId,
+          enabled, session->enabledMsk, session->revEnabledMsk);
     session->processedMsk = 0;
     if (HasReverseStream(procId)) {
         session->revProcessedMsk = 0;
@@ -1151,8 +1052,7 @@
 static int sInitStatus = 1;
 static preproc_session_t sSessions[PREPROC_NUM_SESSIONS];
 
-preproc_session_t *PreProc_GetSession(int32_t procId, int32_t  sessionId, int32_t  ioId)
-{
+preproc_session_t* PreProc_GetSession(int32_t procId, int32_t sessionId, int32_t ioId) {
     size_t i;
     for (i = 0; i < PREPROC_NUM_SESSIONS; i++) {
         if (sSessions[i].id == sessionId) {
@@ -1172,7 +1072,6 @@
     return NULL;
 }
 
-
 int PreProc_Init() {
     size_t i;
     int status = 0;
@@ -1187,8 +1086,7 @@
     return sInitStatus;
 }
 
-const effect_descriptor_t *PreProc_GetDescriptor(const effect_uuid_t *uuid)
-{
+const effect_descriptor_t* PreProc_GetDescriptor(const effect_uuid_t* uuid) {
     size_t i;
     for (i = 0; i < PREPROC_NUM_EFFECTS; i++) {
         if (memcmp(&sDescriptors[i]->uuid, uuid, sizeof(effect_uuid_t)) == 0) {
@@ -1198,35 +1096,31 @@
     return NULL;
 }
 
-
 extern "C" {
 
 //------------------------------------------------------------------------------
 // Effect Control Interface Implementation
 //------------------------------------------------------------------------------
 
-int PreProcessingFx_Process(effect_handle_t     self,
-                            audio_buffer_t    *inBuffer,
-                            audio_buffer_t    *outBuffer)
-{
-    preproc_effect_t * effect = (preproc_effect_t *)self;
+int PreProcessingFx_Process(effect_handle_t self, audio_buffer_t* inBuffer,
+                            audio_buffer_t* outBuffer) {
+    preproc_effect_t* effect = (preproc_effect_t*)self;
 
-    if (effect == NULL){
+    if (effect == NULL) {
         ALOGV("PreProcessingFx_Process() ERROR effect == NULL");
         return -EINVAL;
     }
-    preproc_session_t * session = (preproc_session_t *)effect->session;
+    preproc_session_t* session = (preproc_session_t*)effect->session;
 
-    if (inBuffer == NULL  || inBuffer->raw == NULL  ||
-            outBuffer == NULL || outBuffer->raw == NULL){
+    if (inBuffer == NULL || inBuffer->raw == NULL || outBuffer == NULL || outBuffer->raw == NULL) {
         ALOGW("PreProcessingFx_Process() ERROR bad pointer");
         return -EINVAL;
     }
 
-    session->processedMsk |= (1<<effect->procId);
+    session->processedMsk |= (1 << effect->procId);
 
-//    ALOGV("PreProcessingFx_Process In %d frames enabledMsk %08x processedMsk %08x",
-//         inBuffer->frameCount, session->enabledMsk, session->processedMsk);
+    //    ALOGV("PreProcessingFx_Process In %d frames enabledMsk %08x processedMsk %08x",
+    //         inBuffer->frameCount, session->enabledMsk, session->processedMsk);
 
     if ((session->processedMsk & session->enabledMsk) == session->enabledMsk) {
         effect->session->processedMsk = 0;
@@ -1237,12 +1131,10 @@
             if (outBuffer->frameCount < fr) {
                 fr = outBuffer->frameCount;
             }
-            memcpy(outBuffer->s16,
-                  session->outBuf,
-                  fr * session->outChannelCount * sizeof(int16_t));
-            memcpy(session->outBuf,
-                  session->outBuf + fr * session->outChannelCount,
-                  (session->framesOut - fr) * session->outChannelCount * sizeof(int16_t));
+            memcpy(outBuffer->s16, session->outBuf,
+                   fr * session->outChannelCount * sizeof(int16_t));
+            memmove(session->outBuf, session->outBuf + fr * session->outChannelCount,
+                    (session->framesOut - fr) * session->outChannelCount * sizeof(int16_t));
             session->framesOut -= fr;
             framesWr += fr;
         }
@@ -1252,95 +1144,33 @@
             return 0;
         }
 
-        if (session->inResampler != NULL) {
-            size_t fr = session->frameCount - session->framesIn;
-            if (inBuffer->frameCount < fr) {
-                fr = inBuffer->frameCount;
-            }
-            if (session->inBufSize < session->framesIn + fr) {
-                int16_t *buf;
-                session->inBufSize = session->framesIn + fr;
-                buf = (int16_t *)realloc(session->inBuf,
-                                 session->inBufSize * session->inChannelCount * sizeof(int16_t));
-                if (buf == NULL) {
-                    session->framesIn = 0;
-                    free(session->inBuf);
-                    session->inBuf = NULL;
-                    return -ENOMEM;
-                }
-                session->inBuf = buf;
-            }
-            memcpy(session->inBuf + session->framesIn * session->inChannelCount,
-                   inBuffer->s16,
-                   fr * session->inChannelCount * sizeof(int16_t));
-#ifdef DUAL_MIC_TEST
-            pthread_mutex_lock(&gPcmDumpLock);
-            if (gPcmDumpFh != NULL) {
-                fwrite(inBuffer->raw,
-                       fr * session->inChannelCount * sizeof(int16_t), 1, gPcmDumpFh);
-            }
-            pthread_mutex_unlock(&gPcmDumpLock);
-#endif
-
-            session->framesIn += fr;
-            inBuffer->frameCount = fr;
-            if (session->framesIn < session->frameCount) {
-                return 0;
-            }
-            spx_uint32_t frIn = session->framesIn;
-            spx_uint32_t frOut = session->apmFrameCount;
-            if (session->inChannelCount == 1) {
-                speex_resampler_process_int(session->inResampler,
-                                            0,
-                                            session->inBuf,
-                                            &frIn,
-                                            session->procFrame->data_,
-                                            &frOut);
-            } else {
-                speex_resampler_process_interleaved_int(session->inResampler,
-                                                        session->inBuf,
-                                                        &frIn,
-                                                        session->procFrame->data_,
-                                                        &frOut);
-            }
-            memcpy(session->inBuf,
-                   session->inBuf + frIn * session->inChannelCount,
-                   (session->framesIn - frIn) * session->inChannelCount * sizeof(int16_t));
-            session->framesIn -= frIn;
-        } else {
-            size_t fr = session->frameCount - session->framesIn;
-            if (inBuffer->frameCount < fr) {
-                fr = inBuffer->frameCount;
-            }
-            memcpy(session->procFrame->data_ + session->framesIn * session->inChannelCount,
-                   inBuffer->s16,
-                   fr * session->inChannelCount * sizeof(int16_t));
-
-#ifdef DUAL_MIC_TEST
-            pthread_mutex_lock(&gPcmDumpLock);
-            if (gPcmDumpFh != NULL) {
-                fwrite(inBuffer->raw,
-                       fr * session->inChannelCount * sizeof(int16_t), 1, gPcmDumpFh);
-            }
-            pthread_mutex_unlock(&gPcmDumpLock);
-#endif
-
-            session->framesIn += fr;
-            inBuffer->frameCount = fr;
-            if (session->framesIn < session->frameCount) {
-                return 0;
-            }
-            session->framesIn = 0;
+        size_t fr = session->frameCount - session->framesIn;
+        if (inBuffer->frameCount < fr) {
+            fr = inBuffer->frameCount;
         }
-        session->procFrame->samples_per_channel_ = session->apmFrameCount;
-
-        effect->session->apm->ProcessStream(session->procFrame);
+        session->framesIn += fr;
+        inBuffer->frameCount = fr;
+        if (session->framesIn < session->frameCount) {
+            return 0;
+        }
+        session->framesIn = 0;
+        if (int status = effect->session->apm->ProcessStream(
+                    (const int16_t* const)inBuffer->s16,
+                    (const webrtc::StreamConfig)effect->session->inputConfig,
+                    (const webrtc::StreamConfig)effect->session->outputConfig,
+                    (int16_t* const)outBuffer->s16);
+            status != 0) {
+            ALOGE("Process Stream failed with error %d\n", status);
+            return status;
+        }
+        outBuffer->frameCount = inBuffer->frameCount;
 
         if (session->outBufSize < session->framesOut + session->frameCount) {
-            int16_t *buf;
+            int16_t* buf;
             session->outBufSize = session->framesOut + session->frameCount;
-            buf = (int16_t *)realloc(session->outBuf,
-                             session->outBufSize * session->outChannelCount * sizeof(int16_t));
+            buf = (int16_t*)realloc(
+                    session->outBuf,
+                    session->outBufSize * session->outChannelCount * sizeof(int16_t));
             if (buf == NULL) {
                 session->framesOut = 0;
                 free(session->outBuf);
@@ -1350,40 +1180,14 @@
             session->outBuf = buf;
         }
 
-        if (session->outResampler != NULL) {
-            spx_uint32_t frIn = session->apmFrameCount;
-            spx_uint32_t frOut = session->frameCount;
-            if (session->inChannelCount == 1) {
-                speex_resampler_process_int(session->outResampler,
-                                    0,
-                                    session->procFrame->data_,
-                                    &frIn,
-                                    session->outBuf + session->framesOut * session->outChannelCount,
-                                    &frOut);
-            } else {
-                speex_resampler_process_interleaved_int(session->outResampler,
-                                    session->procFrame->data_,
-                                    &frIn,
-                                    session->outBuf + session->framesOut * session->outChannelCount,
-                                    &frOut);
-            }
-            session->framesOut += frOut;
-        } else {
-            memcpy(session->outBuf + session->framesOut * session->outChannelCount,
-                   session->procFrame->data_,
-                   session->frameCount * session->outChannelCount * sizeof(int16_t));
-            session->framesOut += session->frameCount;
-        }
-        size_t fr = session->framesOut;
+        fr = session->framesOut;
         if (framesRq - framesWr < fr) {
             fr = framesRq - framesWr;
         }
-        memcpy(outBuffer->s16 + framesWr * session->outChannelCount,
-              session->outBuf,
-              fr * session->outChannelCount * sizeof(int16_t));
-        memcpy(session->outBuf,
-              session->outBuf + fr * session->outChannelCount,
-              (session->framesOut - fr) * session->outChannelCount * sizeof(int16_t));
+        memcpy(outBuffer->s16 + framesWr * session->outChannelCount, session->outBuf,
+               fr * session->outChannelCount * sizeof(int16_t));
+        memmove(session->outBuf, session->outBuf + fr * session->outChannelCount,
+                (session->framesOut - fr) * session->outChannelCount * sizeof(int16_t));
         session->framesOut -= fr;
         outBuffer->frameCount += fr;
 
@@ -1393,39 +1197,32 @@
     }
 }
 
-int PreProcessingFx_Command(effect_handle_t  self,
-                            uint32_t            cmdCode,
-                            uint32_t            cmdSize,
-                            void                *pCmdData,
-                            uint32_t            *replySize,
-                            void                *pReplyData)
-{
-    preproc_effect_t * effect = (preproc_effect_t *) self;
+int PreProcessingFx_Command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
+                            void* pCmdData, uint32_t* replySize, void* pReplyData) {
+    preproc_effect_t* effect = (preproc_effect_t*)self;
 
-    if (effect == NULL){
+    if (effect == NULL) {
         return -EINVAL;
     }
 
-    //ALOGV("PreProcessingFx_Command: command %d cmdSize %d",cmdCode, cmdSize);
+    // ALOGV("PreProcessingFx_Command: command %d cmdSize %d",cmdCode, cmdSize);
 
-    switch (cmdCode){
+    switch (cmdCode) {
         case EFFECT_CMD_INIT:
-            if (pReplyData == NULL || *replySize != sizeof(int)){
+            if (pReplyData == NULL || *replySize != sizeof(int)) {
                 return -EINVAL;
             }
             if (effect->ops->init) {
                 effect->ops->init(effect);
             }
-            *(int *)pReplyData = 0;
+            *(int*)pReplyData = 0;
             break;
 
         case EFFECT_CMD_SET_CONFIG: {
-            if (pCmdData    == NULL||
-                cmdSize     != sizeof(effect_config_t)||
-                pReplyData  == NULL||
-                *replySize  != sizeof(int)){
+            if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL ||
+                *replySize != sizeof(int)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_SET_CONFIG: ERROR");
+                      "EFFECT_CMD_SET_CONFIG: ERROR");
                 return -EINVAL;
             }
 #ifdef DUAL_MIC_TEST
@@ -1436,55 +1233,51 @@
                 effect->session->enabledMsk = 0;
             }
 #endif
-            *(int *)pReplyData = Session_SetConfig(effect->session, (effect_config_t *)pCmdData);
+            *(int*)pReplyData = Session_SetConfig(effect->session, (effect_config_t*)pCmdData);
 #ifdef DUAL_MIC_TEST
             if (gDualMicEnabled) {
                 effect->session->enabledMsk = enabledMsk;
             }
 #endif
-            if (*(int *)pReplyData != 0) {
+            if (*(int*)pReplyData != 0) {
                 break;
             }
             if (effect->state != PREPROC_EFFECT_STATE_ACTIVE) {
-                *(int *)pReplyData = Effect_SetState(effect, PREPROC_EFFECT_STATE_CONFIG);
+                *(int*)pReplyData = Effect_SetState(effect, PREPROC_EFFECT_STATE_CONFIG);
             }
-            } break;
+        } break;
 
         case EFFECT_CMD_GET_CONFIG:
-            if (pReplyData == NULL ||
-                *replySize != sizeof(effect_config_t)) {
+            if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) {
                 ALOGV("\tLVM_ERROR : PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_GET_CONFIG: ERROR");
+                      "EFFECT_CMD_GET_CONFIG: ERROR");
                 return -EINVAL;
             }
 
-            Session_GetConfig(effect->session, (effect_config_t *)pReplyData);
+            Session_GetConfig(effect->session, (effect_config_t*)pReplyData);
             break;
 
         case EFFECT_CMD_SET_CONFIG_REVERSE:
-            if (pCmdData == NULL ||
-                cmdSize != sizeof(effect_config_t) ||
-                pReplyData == NULL ||
+            if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL ||
                 *replySize != sizeof(int)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_SET_CONFIG_REVERSE: ERROR");
+                      "EFFECT_CMD_SET_CONFIG_REVERSE: ERROR");
                 return -EINVAL;
             }
-            *(int *)pReplyData = Session_SetReverseConfig(effect->session,
-                                                          (effect_config_t *)pCmdData);
-            if (*(int *)pReplyData != 0) {
+            *(int*)pReplyData =
+                    Session_SetReverseConfig(effect->session, (effect_config_t*)pCmdData);
+            if (*(int*)pReplyData != 0) {
                 break;
             }
             break;
 
         case EFFECT_CMD_GET_CONFIG_REVERSE:
-            if (pReplyData == NULL ||
-                *replySize != sizeof(effect_config_t)){
+            if (pReplyData == NULL || *replySize != sizeof(effect_config_t)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_GET_CONFIG_REVERSE: ERROR");
+                      "EFFECT_CMD_GET_CONFIG_REVERSE: ERROR");
                 return -EINVAL;
             }
-            Session_GetReverseConfig(effect->session, (effect_config_t *)pCmdData);
+            Session_GetReverseConfig(effect->session, (effect_config_t*)pCmdData);
             break;
 
         case EFFECT_CMD_RESET:
@@ -1494,80 +1287,74 @@
             break;
 
         case EFFECT_CMD_GET_PARAM: {
-            effect_param_t *p = (effect_param_t *)pCmdData;
+            effect_param_t* p = (effect_param_t*)pCmdData;
 
             if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
-                    cmdSize < (sizeof(effect_param_t) + p->psize) ||
-                    pReplyData == NULL || replySize == NULL ||
-                    *replySize < (sizeof(effect_param_t) + p->psize)){
+                cmdSize < (sizeof(effect_param_t) + p->psize) || pReplyData == NULL ||
+                replySize == NULL || *replySize < (sizeof(effect_param_t) + p->psize)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_GET_PARAM: ERROR");
+                      "EFFECT_CMD_GET_PARAM: ERROR");
                 return -EINVAL;
             }
 
             memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
 
-            p = (effect_param_t *)pReplyData;
+            p = (effect_param_t*)pReplyData;
 
             int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
 
             if (effect->ops->get_parameter) {
-                p->status = effect->ops->get_parameter(effect, p->data,
-                                                       &p->vsize,
-                                                       p->data + voffset);
+                p->status =
+                        effect->ops->get_parameter(effect, p->data, &p->vsize, p->data + voffset);
                 *replySize = sizeof(effect_param_t) + voffset + p->vsize;
             }
         } break;
 
-        case EFFECT_CMD_SET_PARAM:{
-            if (pCmdData == NULL||
-                    cmdSize < sizeof(effect_param_t) ||
-                    pReplyData == NULL || replySize == NULL ||
-                    *replySize != sizeof(int32_t)){
+        case EFFECT_CMD_SET_PARAM: {
+            if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) || pReplyData == NULL ||
+                replySize == NULL || *replySize != sizeof(int32_t)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_SET_PARAM: ERROR");
+                      "EFFECT_CMD_SET_PARAM: ERROR");
                 return -EINVAL;
             }
-            effect_param_t *p = (effect_param_t *) pCmdData;
+            effect_param_t* p = (effect_param_t*)pCmdData;
 
-            if (p->psize != sizeof(int32_t)){
+            if (p->psize != sizeof(int32_t)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
+                      "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
                 return -EINVAL;
             }
             if (effect->ops->set_parameter) {
-                *(int *)pReplyData = effect->ops->set_parameter(effect,
-                                                                (void *)p->data,
-                                                                p->data + p->psize);
+                *(int*)pReplyData =
+                        effect->ops->set_parameter(effect, (void*)p->data, p->data + p->psize);
             }
         } break;
 
         case EFFECT_CMD_ENABLE:
-            if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){
+            if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: EFFECT_CMD_ENABLE: ERROR");
                 return -EINVAL;
             }
-            *(int *)pReplyData = Effect_SetState(effect, PREPROC_EFFECT_STATE_ACTIVE);
+            *(int*)pReplyData = Effect_SetState(effect, PREPROC_EFFECT_STATE_ACTIVE);
             break;
 
         case EFFECT_CMD_DISABLE:
-            if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){
+            if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: EFFECT_CMD_DISABLE: ERROR");
                 return -EINVAL;
             }
-            *(int *)pReplyData  = Effect_SetState(effect, PREPROC_EFFECT_STATE_CONFIG);
+            *(int*)pReplyData = Effect_SetState(effect, PREPROC_EFFECT_STATE_CONFIG);
             break;
 
         case EFFECT_CMD_SET_DEVICE:
         case EFFECT_CMD_SET_INPUT_DEVICE:
-            if (pCmdData == NULL ||
-                cmdSize != sizeof(uint32_t)) {
+            if (pCmdData == NULL || cmdSize != sizeof(uint32_t)) {
                 ALOGV("PreProcessingFx_Command cmdCode Case: EFFECT_CMD_SET_DEVICE: ERROR");
                 return -EINVAL;
             }
 
             if (effect->ops->set_device) {
-                effect->ops->set_device(effect, *(uint32_t *)pCmdData);
+                effect->ops->set_device(effect, *(uint32_t*)pCmdData);
             }
             break;
 
@@ -1578,30 +1365,30 @@
 #ifdef DUAL_MIC_TEST
         ///// test commands start
         case PREPROC_CMD_DUAL_MIC_ENABLE: {
-            if (pCmdData == NULL|| cmdSize != sizeof(uint32_t) ||
-                    pReplyData == NULL || replySize == NULL) {
+            if (pCmdData == NULL || cmdSize != sizeof(uint32_t) || pReplyData == NULL ||
+                replySize == NULL) {
                 ALOGE("PreProcessingFx_Command cmdCode Case: "
-                        "PREPROC_CMD_DUAL_MIC_ENABLE: ERROR");
+                      "PREPROC_CMD_DUAL_MIC_ENABLE: ERROR");
                 *replySize = 0;
                 return -EINVAL;
             }
-            gDualMicEnabled = *(bool *)pCmdData;
+            gDualMicEnabled = *(bool*)pCmdData;
             if (gDualMicEnabled) {
                 effect->aux_channels_on = sHasAuxChannels[effect->procId];
             } else {
                 effect->aux_channels_on = false;
             }
-            effect->cur_channel_config = (effect->session->inChannelCount == 1) ?
-                    CHANNEL_CFG_MONO : CHANNEL_CFG_STEREO;
+            effect->cur_channel_config =
+                    (effect->session->inChannelCount == 1) ? CHANNEL_CFG_MONO : CHANNEL_CFG_STEREO;
 
             ALOGV("PREPROC_CMD_DUAL_MIC_ENABLE: %s", gDualMicEnabled ? "enabled" : "disabled");
             *replySize = sizeof(int);
-            *(int *)pReplyData = 0;
-            } break;
+            *(int*)pReplyData = 0;
+        } break;
         case PREPROC_CMD_DUAL_MIC_PCM_DUMP_START: {
-            if (pCmdData == NULL|| pReplyData == NULL || replySize == NULL) {
+            if (pCmdData == NULL || pReplyData == NULL || replySize == NULL) {
                 ALOGE("PreProcessingFx_Command cmdCode Case: "
-                        "PREPROC_CMD_DUAL_MIC_PCM_DUMP_START: ERROR");
+                      "PREPROC_CMD_DUAL_MIC_PCM_DUMP_START: ERROR");
                 *replySize = 0;
                 return -EINVAL;
             }
@@ -1610,20 +1397,19 @@
                 fclose(gPcmDumpFh);
                 gPcmDumpFh = NULL;
             }
-            char *path = strndup((char *)pCmdData, cmdSize);
-            gPcmDumpFh = fopen((char *)path, "wb");
+            char* path = strndup((char*)pCmdData, cmdSize);
+            gPcmDumpFh = fopen((char*)path, "wb");
             pthread_mutex_unlock(&gPcmDumpLock);
-            ALOGV("PREPROC_CMD_DUAL_MIC_PCM_DUMP_START: path %s gPcmDumpFh %p",
-                  path, gPcmDumpFh);
+            ALOGV("PREPROC_CMD_DUAL_MIC_PCM_DUMP_START: path %s gPcmDumpFh %p", path, gPcmDumpFh);
             ALOGE_IF(gPcmDumpFh <= 0, "gPcmDumpFh open error %d %s", errno, strerror(errno));
             free(path);
             *replySize = sizeof(int);
-            *(int *)pReplyData = 0;
-            } break;
+            *(int*)pReplyData = 0;
+        } break;
         case PREPROC_CMD_DUAL_MIC_PCM_DUMP_STOP: {
             if (pReplyData == NULL || replySize == NULL) {
                 ALOGE("PreProcessingFx_Command cmdCode Case: "
-                        "PREPROC_CMD_DUAL_MIC_PCM_DUMP_STOP: ERROR");
+                      "PREPROC_CMD_DUAL_MIC_PCM_DUMP_STOP: ERROR");
                 *replySize = 0;
                 return -EINVAL;
             }
@@ -1635,118 +1421,116 @@
             pthread_mutex_unlock(&gPcmDumpLock);
             ALOGV("PREPROC_CMD_DUAL_MIC_PCM_DUMP_STOP");
             *replySize = sizeof(int);
-            *(int *)pReplyData = 0;
-            } break;
-        ///// test commands end
+            *(int*)pReplyData = 0;
+        } break;
+            ///// test commands end
 
         case EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS: {
-            if(!gDualMicEnabled) {
+            if (!gDualMicEnabled) {
                 return -EINVAL;
             }
-            if (pCmdData == NULL|| cmdSize != 2 * sizeof(uint32_t) ||
-                    pReplyData == NULL || replySize == NULL) {
+            if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t) || pReplyData == NULL ||
+                replySize == NULL) {
                 ALOGE("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS: ERROR");
+                      "EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS: ERROR");
                 *replySize = 0;
                 return -EINVAL;
             }
-            if (*(uint32_t *)pCmdData != EFFECT_FEATURE_AUX_CHANNELS ||
-                  !effect->aux_channels_on) {
+            if (*(uint32_t*)pCmdData != EFFECT_FEATURE_AUX_CHANNELS || !effect->aux_channels_on) {
                 ALOGV("PreProcessingFx_Command feature EFFECT_FEATURE_AUX_CHANNELS not supported by"
-                        " fx %d", effect->procId);
-                *(uint32_t *)pReplyData = -ENOSYS;
+                      " fx %d",
+                      effect->procId);
+                *(uint32_t*)pReplyData = -ENOSYS;
                 *replySize = sizeof(uint32_t);
                 break;
             }
-            size_t num_configs = *((uint32_t *)pCmdData + 1);
-            if (*replySize < (2 * sizeof(uint32_t) +
-                              num_configs * sizeof(channel_config_t))) {
+            size_t num_configs = *((uint32_t*)pCmdData + 1);
+            if (*replySize < (2 * sizeof(uint32_t) + num_configs * sizeof(channel_config_t))) {
                 *replySize = 0;
                 return -EINVAL;
             }
 
-            *((uint32_t *)pReplyData + 1) = CHANNEL_CFG_CNT;
+            *((uint32_t*)pReplyData + 1) = CHANNEL_CFG_CNT;
             if (num_configs < CHANNEL_CFG_CNT ||
-                    *replySize < (2 * sizeof(uint32_t) +
-                                     CHANNEL_CFG_CNT * sizeof(channel_config_t))) {
-                *(uint32_t *)pReplyData = -ENOMEM;
+                *replySize < (2 * sizeof(uint32_t) + CHANNEL_CFG_CNT * sizeof(channel_config_t))) {
+                *(uint32_t*)pReplyData = -ENOMEM;
             } else {
                 num_configs = CHANNEL_CFG_CNT;
-                *(uint32_t *)pReplyData = 0;
+                *(uint32_t*)pReplyData = 0;
             }
             ALOGV("PreProcessingFx_Command EFFECT_CMD_GET_FEATURE_SUPPORTED_CONFIGS num config %d",
                   num_configs);
 
             *replySize = 2 * sizeof(uint32_t) + num_configs * sizeof(channel_config_t);
-            *((uint32_t *)pReplyData + 1) = num_configs;
-            memcpy((uint32_t *)pReplyData + 2, &sDualMicConfigs, num_configs * sizeof(channel_config_t));
-            } break;
+            *((uint32_t*)pReplyData + 1) = num_configs;
+            memcpy((uint32_t*)pReplyData + 2, &sDualMicConfigs,
+                   num_configs * sizeof(channel_config_t));
+        } break;
         case EFFECT_CMD_GET_FEATURE_CONFIG:
-            if(!gDualMicEnabled) {
+            if (!gDualMicEnabled) {
                 return -EINVAL;
             }
-            if (pCmdData == NULL|| cmdSize != sizeof(uint32_t) ||
-                    pReplyData == NULL || replySize == NULL ||
-                    *replySize < sizeof(uint32_t) + sizeof(channel_config_t)) {
+            if (pCmdData == NULL || cmdSize != sizeof(uint32_t) || pReplyData == NULL ||
+                replySize == NULL || *replySize < sizeof(uint32_t) + sizeof(channel_config_t)) {
                 ALOGE("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_GET_FEATURE_CONFIG: ERROR");
+                      "EFFECT_CMD_GET_FEATURE_CONFIG: ERROR");
                 return -EINVAL;
             }
-            if (*(uint32_t *)pCmdData != EFFECT_FEATURE_AUX_CHANNELS || !effect->aux_channels_on) {
-                *(uint32_t *)pReplyData = -ENOSYS;
+            if (*(uint32_t*)pCmdData != EFFECT_FEATURE_AUX_CHANNELS || !effect->aux_channels_on) {
+                *(uint32_t*)pReplyData = -ENOSYS;
                 *replySize = sizeof(uint32_t);
                 break;
             }
             ALOGV("PreProcessingFx_Command EFFECT_CMD_GET_FEATURE_CONFIG");
-            *(uint32_t *)pReplyData = 0;
+            *(uint32_t*)pReplyData = 0;
             *replySize = sizeof(uint32_t) + sizeof(channel_config_t);
-            memcpy((uint32_t *)pReplyData + 1,
-                   &sDualMicConfigs[effect->cur_channel_config],
+            memcpy((uint32_t*)pReplyData + 1, &sDualMicConfigs[effect->cur_channel_config],
                    sizeof(channel_config_t));
             break;
         case EFFECT_CMD_SET_FEATURE_CONFIG: {
             ALOGV("PreProcessingFx_Command EFFECT_CMD_SET_FEATURE_CONFIG: "
-                    "gDualMicEnabled %d effect->aux_channels_on %d",
+                  "gDualMicEnabled %d effect->aux_channels_on %d",
                   gDualMicEnabled, effect->aux_channels_on);
-            if(!gDualMicEnabled) {
+            if (!gDualMicEnabled) {
                 return -EINVAL;
             }
-            if (pCmdData == NULL|| cmdSize != (sizeof(uint32_t) + sizeof(channel_config_t)) ||
-                    pReplyData == NULL || replySize == NULL ||
-                    *replySize < sizeof(uint32_t)) {
+            if (pCmdData == NULL || cmdSize != (sizeof(uint32_t) + sizeof(channel_config_t)) ||
+                pReplyData == NULL || replySize == NULL || *replySize < sizeof(uint32_t)) {
                 ALOGE("PreProcessingFx_Command cmdCode Case: "
-                        "EFFECT_CMD_SET_FEATURE_CONFIG: ERROR\n"
-                        "pCmdData %p cmdSize %d pReplyData %p replySize %p *replySize %d",
-                        pCmdData, cmdSize, pReplyData, replySize, replySize ? *replySize : -1);
+                      "EFFECT_CMD_SET_FEATURE_CONFIG: ERROR\n"
+                      "pCmdData %p cmdSize %d pReplyData %p replySize %p *replySize %d",
+                      pCmdData, cmdSize, pReplyData, replySize, replySize ? *replySize : -1);
                 return -EINVAL;
             }
             *replySize = sizeof(uint32_t);
-            if (*(uint32_t *)pCmdData != EFFECT_FEATURE_AUX_CHANNELS || !effect->aux_channels_on) {
-                *(uint32_t *)pReplyData = -ENOSYS;
+            if (*(uint32_t*)pCmdData != EFFECT_FEATURE_AUX_CHANNELS || !effect->aux_channels_on) {
+                *(uint32_t*)pReplyData = -ENOSYS;
                 ALOGV("PreProcessingFx_Command cmdCode Case: "
-                                        "EFFECT_CMD_SET_FEATURE_CONFIG: ERROR\n"
-                                        "CmdData %d effect->aux_channels_on %d",
-                                        *(uint32_t *)pCmdData, effect->aux_channels_on);
+                      "EFFECT_CMD_SET_FEATURE_CONFIG: ERROR\n"
+                      "CmdData %d effect->aux_channels_on %d",
+                      *(uint32_t*)pCmdData, effect->aux_channels_on);
                 break;
             }
             size_t i;
-            for (i = 0; i < CHANNEL_CFG_CNT;i++) {
-                if (memcmp((uint32_t *)pCmdData + 1,
-                           &sDualMicConfigs[i], sizeof(channel_config_t)) == 0) {
+            for (i = 0; i < CHANNEL_CFG_CNT; i++) {
+                if (memcmp((uint32_t*)pCmdData + 1, &sDualMicConfigs[i],
+                           sizeof(channel_config_t)) == 0) {
                     break;
                 }
             }
             if (i == CHANNEL_CFG_CNT) {
-                *(uint32_t *)pReplyData = -EINVAL;
+                *(uint32_t*)pReplyData = -EINVAL;
                 ALOGW("PreProcessingFx_Command EFFECT_CMD_SET_FEATURE_CONFIG invalid config"
-                        "[%08x].[%08x]", *((uint32_t *)pCmdData + 1), *((uint32_t *)pCmdData + 2));
+                      "[%08x].[%08x]",
+                      *((uint32_t*)pCmdData + 1), *((uint32_t*)pCmdData + 2));
             } else {
                 effect->cur_channel_config = i;
-                *(uint32_t *)pReplyData = 0;
+                *(uint32_t*)pReplyData = 0;
                 ALOGV("PreProcessingFx_Command EFFECT_CMD_SET_FEATURE_CONFIG New config"
-                        "[%08x].[%08x]", sDualMicConfigs[i].main_channels, sDualMicConfigs[i].aux_channels);
+                      "[%08x].[%08x]",
+                      sDualMicConfigs[i].main_channels, sDualMicConfigs[i].aux_channels);
             }
-            } break;
+        } break;
 #endif
         default:
             return -EINVAL;
@@ -1754,11 +1538,8 @@
     return 0;
 }
 
-
-int PreProcessingFx_GetDescriptor(effect_handle_t   self,
-                                  effect_descriptor_t *pDescriptor)
-{
-    preproc_effect_t * effect = (preproc_effect_t *) self;
+int PreProcessingFx_GetDescriptor(effect_handle_t self, effect_descriptor_t* pDescriptor) {
+    preproc_effect_t* effect = (preproc_effect_t*)self;
 
     if (effect == NULL || pDescriptor == NULL) {
         return -EINVAL;
@@ -1769,137 +1550,79 @@
     return 0;
 }
 
-int PreProcessingFx_ProcessReverse(effect_handle_t     self,
-                                   audio_buffer_t    *inBuffer,
-                                   audio_buffer_t    *outBuffer __unused)
-{
-    preproc_effect_t * effect = (preproc_effect_t *)self;
+int PreProcessingFx_ProcessReverse(effect_handle_t self, audio_buffer_t* inBuffer,
+                                   audio_buffer_t* outBuffer __unused) {
+    preproc_effect_t* effect = (preproc_effect_t*)self;
 
-    if (effect == NULL){
+    if (effect == NULL) {
         ALOGW("PreProcessingFx_ProcessReverse() ERROR effect == NULL");
         return -EINVAL;
     }
-    preproc_session_t * session = (preproc_session_t *)effect->session;
+    preproc_session_t* session = (preproc_session_t*)effect->session;
 
-    if (inBuffer == NULL  || inBuffer->raw == NULL){
+    if (inBuffer == NULL || inBuffer->raw == NULL) {
         ALOGW("PreProcessingFx_ProcessReverse() ERROR bad pointer");
         return -EINVAL;
     }
 
-    session->revProcessedMsk |= (1<<effect->procId);
+    session->revProcessedMsk |= (1 << effect->procId);
 
-//    ALOGV("PreProcessingFx_ProcessReverse In %d frames revEnabledMsk %08x revProcessedMsk %08x",
-//         inBuffer->frameCount, session->revEnabledMsk, session->revProcessedMsk);
-
+    //    ALOGV("PreProcessingFx_ProcessReverse In %d frames revEnabledMsk %08x revProcessedMsk
+    //    %08x",
+    //         inBuffer->frameCount, session->revEnabledMsk, session->revProcessedMsk);
 
     if ((session->revProcessedMsk & session->revEnabledMsk) == session->revEnabledMsk) {
         effect->session->revProcessedMsk = 0;
-        if (session->revResampler != NULL) {
-            size_t fr = session->frameCount - session->framesRev;
-            if (inBuffer->frameCount < fr) {
-                fr = inBuffer->frameCount;
-            }
-            if (session->revBufSize < session->framesRev + fr) {
-                int16_t *buf;
-                session->revBufSize = session->framesRev + fr;
-                buf = (int16_t *)realloc(session->revBuf,
-                                 session->revBufSize * session->inChannelCount * sizeof(int16_t));
-                if (buf == NULL) {
-                    session->framesRev = 0;
-                    free(session->revBuf);
-                    session->revBuf = NULL;
-                    return -ENOMEM;
-                }
-                session->revBuf = buf;
-            }
-            memcpy(session->revBuf + session->framesRev * session->inChannelCount,
-                   inBuffer->s16,
-                   fr * session->inChannelCount * sizeof(int16_t));
-
-            session->framesRev += fr;
-            inBuffer->frameCount = fr;
-            if (session->framesRev < session->frameCount) {
-                return 0;
-            }
-            spx_uint32_t frIn = session->framesRev;
-            spx_uint32_t frOut = session->apmFrameCount;
-            if (session->inChannelCount == 1) {
-                speex_resampler_process_int(session->revResampler,
-                                            0,
-                                            session->revBuf,
-                                            &frIn,
-                                            session->revFrame->data_,
-                                            &frOut);
-            } else {
-                speex_resampler_process_interleaved_int(session->revResampler,
-                                                        session->revBuf,
-                                                        &frIn,
-                                                        session->revFrame->data_,
-                                                        &frOut);
-            }
-            memcpy(session->revBuf,
-                   session->revBuf + frIn * session->inChannelCount,
-                   (session->framesRev - frIn) * session->inChannelCount * sizeof(int16_t));
-            session->framesRev -= frIn;
-        } else {
-            size_t fr = session->frameCount - session->framesRev;
-            if (inBuffer->frameCount < fr) {
-                fr = inBuffer->frameCount;
-            }
-            memcpy(session->revFrame->data_ + session->framesRev * session->inChannelCount,
-                   inBuffer->s16,
-                   fr * session->inChannelCount * sizeof(int16_t));
-            session->framesRev += fr;
-            inBuffer->frameCount = fr;
-            if (session->framesRev < session->frameCount) {
-                return 0;
-            }
-            session->framesRev = 0;
+        size_t fr = session->frameCount - session->framesRev;
+        if (inBuffer->frameCount < fr) {
+            fr = inBuffer->frameCount;
         }
-        session->revFrame->samples_per_channel_ = session->apmFrameCount;
-        effect->session->apm->AnalyzeReverseStream(session->revFrame);
+        session->framesRev += fr;
+        inBuffer->frameCount = fr;
+        if (session->framesRev < session->frameCount) {
+            return 0;
+        }
+        session->framesRev = 0;
+        if (int status = effect->session->apm->ProcessReverseStream(
+                    (const int16_t* const)inBuffer->s16,
+                    (const webrtc::StreamConfig)effect->session->revConfig,
+                    (const webrtc::StreamConfig)effect->session->revConfig,
+                    (int16_t* const)outBuffer->s16);
+            status != 0) {
+            ALOGE("Process Reverse Stream failed with error %d\n", status);
+            return status;
+        }
         return 0;
     } else {
         return -ENODATA;
     }
 }
 
-
 // effect_handle_t interface implementation for effect
 const struct effect_interface_s sEffectInterface = {
-    PreProcessingFx_Process,
-    PreProcessingFx_Command,
-    PreProcessingFx_GetDescriptor,
-    NULL
-};
+        PreProcessingFx_Process, PreProcessingFx_Command, PreProcessingFx_GetDescriptor, NULL};
 
 const struct effect_interface_s sEffectInterfaceReverse = {
-    PreProcessingFx_Process,
-    PreProcessingFx_Command,
-    PreProcessingFx_GetDescriptor,
-    PreProcessingFx_ProcessReverse
-};
+        PreProcessingFx_Process, PreProcessingFx_Command, PreProcessingFx_GetDescriptor,
+        PreProcessingFx_ProcessReverse};
 
 //------------------------------------------------------------------------------
 // Effect Library Interface Implementation
 //------------------------------------------------------------------------------
 
-int PreProcessingLib_Create(const effect_uuid_t *uuid,
-                            int32_t             sessionId,
-                            int32_t             ioId,
-                            effect_handle_t  *pInterface)
-{
+int PreProcessingLib_Create(const effect_uuid_t* uuid, int32_t sessionId, int32_t ioId,
+                            effect_handle_t* pInterface) {
     ALOGV("EffectCreate: uuid: %08x session %d IO: %d", uuid->timeLow, sessionId, ioId);
 
     int status;
-    const effect_descriptor_t *desc;
-    preproc_session_t *session;
+    const effect_descriptor_t* desc;
+    preproc_session_t* session;
     uint32_t procId;
 
     if (PreProc_Init() != 0) {
         return sInitStatus;
     }
-    desc =  PreProc_GetDescriptor(uuid);
+    desc = PreProc_GetDescriptor(uuid);
     if (desc == NULL) {
         ALOGW("EffectCreate: fx not found uuid: %08x", uuid->timeLow);
         return -EINVAL;
@@ -1920,14 +1643,13 @@
     return status;
 }
 
-int PreProcessingLib_Release(effect_handle_t interface)
-{
+int PreProcessingLib_Release(effect_handle_t interface) {
     ALOGV("EffectRelease start %p", interface);
     if (PreProc_Init() != 0) {
         return sInitStatus;
     }
 
-    preproc_effect_t *fx = (preproc_effect_t *)interface;
+    preproc_effect_t* fx = (preproc_effect_t*)interface;
 
     if (fx->session->id == 0) {
         return -EINVAL;
@@ -1935,17 +1657,15 @@
     return Session_ReleaseEffect(fx->session, fx);
 }
 
-int PreProcessingLib_GetDescriptor(const effect_uuid_t *uuid,
-                                   effect_descriptor_t *pDescriptor) {
-
-    if (pDescriptor == NULL || uuid == NULL){
+int PreProcessingLib_GetDescriptor(const effect_uuid_t* uuid, effect_descriptor_t* pDescriptor) {
+    if (pDescriptor == NULL || uuid == NULL) {
         return -EINVAL;
     }
 
-    const effect_descriptor_t *desc = PreProc_GetDescriptor(uuid);
+    const effect_descriptor_t* desc = PreProc_GetDescriptor(uuid);
     if (desc == NULL) {
         ALOGV("PreProcessingLib_GetDescriptor() not found");
-        return  -EINVAL;
+        return -EINVAL;
     }
 
     ALOGV("PreProcessingLib_GetDescriptor() got fx %s", desc->name);
@@ -1955,15 +1675,13 @@
 }
 
 // This is the only symbol that needs to be exported
-__attribute__ ((visibility ("default")))
-audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM = {
-    .tag = AUDIO_EFFECT_LIBRARY_TAG,
-    .version = EFFECT_LIBRARY_API_VERSION,
-    .name = "Audio Preprocessing Library",
-    .implementor = "The Android Open Source Project",
-    .create_effect = PreProcessingLib_Create,
-    .release_effect = PreProcessingLib_Release,
-    .get_descriptor = PreProcessingLib_GetDescriptor
-};
+__attribute__((visibility("default"))) audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM = {
+        .tag = AUDIO_EFFECT_LIBRARY_TAG,
+        .version = EFFECT_LIBRARY_API_VERSION,
+        .name = "Audio Preprocessing Library",
+        .implementor = "The Android Open Source Project",
+        .create_effect = PreProcessingLib_Create,
+        .release_effect = PreProcessingLib_Release,
+        .get_descriptor = PreProcessingLib_GetDescriptor};
 
-}; // extern "C"
+};  // extern "C"
diff --git a/media/libeffects/preprocessing/benchmarks/Android.bp b/media/libeffects/preprocessing/benchmarks/Android.bp
new file mode 100644
index 0000000..c1b2295
--- /dev/null
+++ b/media/libeffects/preprocessing/benchmarks/Android.bp
@@ -0,0 +1,37 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libeffects_preprocessing_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libeffects_preprocessing_license",
+    ],
+}
+
+cc_benchmark {
+    name: "preprocessing_benchmark",
+    vendor: true,
+    srcs: ["preprocessing_benchmark.cpp"],
+    shared_libs: [
+        "libaudioutils",
+        "liblog",
+        "libutils",
+    ],
+    static_libs: [
+        "libaudiopreprocessing",
+        "webrtc_audio_processing",
+    ],
+    cflags: [
+        "-DWEBRTC_POSIX",
+        "-fvisibility=default",
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+    header_libs: [
+        "libaudioeffects",
+        "libhardware_headers",
+        "libwebrtc_absl_headers",
+    ],
+}
diff --git a/media/libeffects/preprocessing/benchmarks/preprocessing_benchmark.cpp b/media/libeffects/preprocessing/benchmarks/preprocessing_benchmark.cpp
new file mode 100644
index 0000000..9501d4d
--- /dev/null
+++ b/media/libeffects/preprocessing/benchmarks/preprocessing_benchmark.cpp
@@ -0,0 +1,322 @@
+/*
+ * Copyright 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*******************************************************************
+ * A test result running on Pixel 3 for comparison.
+ * The first parameter indicates the channel mask index.
+ * The second parameter indicates the effect index.
+ * 0: Automatic Gain Control,
+ * 1: Acoustic Echo Canceler,
+ * 2: Noise Suppressor,
+ * 3: Automatic Gain Control 2
+ * ---------------------------------------------------------------
+ * Benchmark                     Time             CPU   Iterations
+ * ---------------------------------------------------------------
+ * BM_PREPROCESSING/1/0       48179 ns        48041 ns        12349
+ * BM_PREPROCESSING/1/1       57559 ns        57403 ns        12270
+ * BM_PREPROCESSING/1/2       17524 ns        17466 ns        39982
+ * BM_PREPROCESSING/1/3        2608 ns         2599 ns       268399
+ * BM_PREPROCESSING/2/0       94198 ns        93926 ns         7470
+ * BM_PREPROCESSING/2/1      109196 ns       108899 ns         6459
+ * BM_PREPROCESSING/2/2       34098 ns        33986 ns        20576
+ * BM_PREPROCESSING/2/3        3231 ns         3221 ns       216606
+ * BM_PREPROCESSING/3/0      141532 ns       141132 ns         5030
+ * BM_PREPROCESSING/3/1      161199 ns       160745 ns         4387
+ * BM_PREPROCESSING/3/2       50663 ns        50535 ns        13619
+ * BM_PREPROCESSING/3/3        3967 ns         3955 ns       177005
+ * BM_PREPROCESSING/4/0      187032 ns       186486 ns         3706
+ * BM_PREPROCESSING/4/1      212872 ns       212264 ns         3304
+ * BM_PREPROCESSING/4/2       67649 ns        67476 ns        10128
+ * BM_PREPROCESSING/4/3        4728 ns         4713 ns       148547
+ * BM_PREPROCESSING/5/0      233874 ns       233188 ns         2954
+ * BM_PREPROCESSING/5/1      262798 ns       262052 ns         2680
+ * BM_PREPROCESSING/5/2       84592 ns        84368 ns         8203
+ * BM_PREPROCESSING/5/3        5472 ns         5455 ns       127784
+ * BM_PREPROCESSING/6/0      284777 ns       283911 ns         2468
+ * BM_PREPROCESSING/6/1      315631 ns       314726 ns         2233
+ * BM_PREPROCESSING/6/2      101200 ns       100931 ns         6802
+ * BM_PREPROCESSING/6/3        6152 ns         6133 ns       113951
+ * BM_PREPROCESSING/7/0      327207 ns       326153 ns         2112
+ * BM_PREPROCESSING/7/1      367510 ns       366410 ns         1915
+ * BM_PREPROCESSING/7/2      118574 ns       118250 ns         5795
+ * BM_PREPROCESSING/7/3        6956 ns         6935 ns       100783
+ * BM_PREPROCESSING/8/0      372603 ns       371470 ns         1880
+ * BM_PREPROCESSING/8/1      418882 ns       417625 ns         1685
+ * BM_PREPROCESSING/8/2      136155 ns       135777 ns         4986
+ * BM_PREPROCESSING/8/3        7734 ns         7711 ns        91581
+ * BM_PREPROCESSING/9/0      424795 ns       423464 ns         1657
+ * BM_PREPROCESSING/9/1      469073 ns       467687 ns         1506
+ * BM_PREPROCESSING/9/2      153170 ns       152737 ns         4519
+ * BM_PREPROCESSING/9/3        8393 ns         8363 ns        83603
+ * BM_PREPROCESSING/10/0     472440 ns       470926 ns         1489
+ * BM_PREPROCESSING/10/1     516984 ns       515480 ns         1000
+ * BM_PREPROCESSING/10/2     168802 ns       168348 ns         4097
+ * BM_PREPROCESSING/10/3       9127 ns         9100 ns        76913
+ * BM_PREPROCESSING/11/0     509690 ns       508113 ns         1360
+ * BM_PREPROCESSING/11/1     569076 ns       567390 ns         1310
+ * BM_PREPROCESSING/11/2     185678 ns       185165 ns         3729
+ * BM_PREPROCESSING/11/3       9789 ns         9760 ns        71342
+ * BM_PREPROCESSING/12/0     563858 ns       562108 ns         1270
+ * BM_PREPROCESSING/12/1     619656 ns       617791 ns         1198
+ * BM_PREPROCESSING/12/2     202882 ns       202316 ns         3406
+ * BM_PREPROCESSING/12/3      10610 ns        10579 ns        66287
+ * BM_PREPROCESSING/13/0     602944 ns       601094 ns         1167
+ * BM_PREPROCESSING/13/1     675401 ns       673293 ns         1107
+ * BM_PREPROCESSING/13/2     220677 ns       220051 ns         3131
+ * BM_PREPROCESSING/13/3      11301 ns        11265 ns        62022
+ * BM_PREPROCESSING/14/0     659495 ns       657375 ns         1071
+ * BM_PREPROCESSING/14/1     726551 ns       724295 ns         1024
+ * BM_PREPROCESSING/14/2     238595 ns       237922 ns         2901
+ * BM_PREPROCESSING/14/3      11941 ns        11906 ns        58788
+ * BM_PREPROCESSING/15/0     698377 ns       696134 ns         1014
+ * BM_PREPROCESSING/15/1     772532 ns       770217 ns          960
+ * BM_PREPROCESSING/15/2     253219 ns       252505 ns         2736
+ * BM_PREPROCESSING/15/3      12669 ns        12632 ns        55452
+ * BM_PREPROCESSING/16/0     742054 ns       739708 ns          936
+ * BM_PREPROCESSING/16/1     828029 ns       825484 ns          902
+ * BM_PREPROCESSING/16/2     272419 ns       271658 ns         2545
+ * BM_PREPROCESSING/16/3      13473 ns        13431 ns        52088
+ * BM_PREPROCESSING/17/0     794444 ns       791916 ns          891
+ * BM_PREPROCESSING/17/1     879429 ns       876704 ns          841
+ * BM_PREPROCESSING/17/2     290059 ns       289216 ns         2391
+ * BM_PREPROCESSING/17/3      14257 ns        14210 ns        49425
+ * BM_PREPROCESSING/18/0     852221 ns       849430 ns          839
+ * BM_PREPROCESSING/18/1     931121 ns       928308 ns          799
+ * BM_PREPROCESSING/18/2     307995 ns       307104 ns         2253
+ * BM_PREPROCESSING/18/3      14947 ns        14900 ns        46872
+ * BM_PREPROCESSING/19/0     888752 ns       885893 ns          781
+ * BM_PREPROCESSING/19/1     983398 ns       980285 ns          756
+ * BM_PREPROCESSING/19/2     325669 ns       324705 ns         2132
+ * BM_PREPROCESSING/19/3      15677 ns        15629 ns        44693
+ * BM_PREPROCESSING/20/0     933651 ns       930697 ns          746
+ * BM_PREPROCESSING/20/1    1033396 ns      1030235 ns          713
+ * BM_PREPROCESSING/20/2     342081 ns       341077 ns         2031
+ * BM_PREPROCESSING/20/3      16422 ns        16370 ns        42622
+ * BM_PREPROCESSING/21/0     982521 ns       979388 ns          706
+ * BM_PREPROCESSING/21/1    1085340 ns      1081926 ns          682
+ * BM_PREPROCESSING/21/2     360862 ns       359810 ns         1926
+ * BM_PREPROCESSING/21/3      17161 ns        17107 ns        40885
+ * BM_PREPROCESSING/22/0    1043560 ns      1040219 ns          678
+ * BM_PREPROCESSING/22/1    1137203 ns      1133687 ns          653
+ * BM_PREPROCESSING/22/2     377421 ns       376315 ns         1841
+ * BM_PREPROCESSING/22/3      17903 ns        17847 ns        38984
+ * BM_PREPROCESSING/23/0    1090097 ns      1086523 ns          650
+ * BM_PREPROCESSING/23/1    1199267 ns      1194231 ns          619
+ * BM_PREPROCESSING/23/2     395429 ns       394263 ns         1759
+ * BM_PREPROCESSING/23/3      18879 ns        18818 ns        37242
+ * BM_PREPROCESSING/24/0    1128638 ns      1125076 ns          629
+ * BM_PREPROCESSING/24/1    1239909 ns      1236019 ns          598
+ * BM_PREPROCESSING/24/2     414294 ns       413055 ns         1680
+ * BM_PREPROCESSING/24/3      19583 ns        19521 ns        35771
+ *******************************************************************/
+
+#include <audio_effects/effect_aec.h>
+#include <audio_effects/effect_agc.h>
+#include <array>
+#include <climits>
+#include <cstdlib>
+#include <random>
+#include <vector>
+#include <audio_effects/effect_agc2.h>
+#include <audio_effects/effect_ns.h>
+#include <benchmark/benchmark.h>
+#include <hardware/audio_effect.h>
+#include <log/log.h>
+#include <sys/stat.h>
+#include <system/audio.h>
+
+extern audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM;
+
+constexpr int kSampleRate = 16000;
+constexpr float kTenMilliSecVal = 0.01;
+constexpr unsigned int kStreamDelayMs = 0;
+constexpr effect_uuid_t kEffectUuids[] = {
+        // agc uuid
+        {0xaa8130e0, 0x66fc, 0x11e0, 0xbad0, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // aec uuid
+        {0xbb392ec0, 0x8d4d, 0x11e0, 0xa896, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // ns  uuid
+        {0xc06c8400, 0x8e06, 0x11e0, 0x9cb6, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},
+        // agc2 uuid
+        {0x89f38e65, 0xd4d2, 0x4d64, 0xad0e, {0x2b, 0x3e, 0x79, 0x9e, 0xa8, 0x86}},
+};
+constexpr size_t kNumEffectUuids = std::size(kEffectUuids);
+constexpr audio_channel_mask_t kChMasks[] = {
+        AUDIO_CHANNEL_INDEX_MASK_1,  AUDIO_CHANNEL_INDEX_MASK_2,  AUDIO_CHANNEL_INDEX_MASK_3,
+        AUDIO_CHANNEL_INDEX_MASK_4,  AUDIO_CHANNEL_INDEX_MASK_5,  AUDIO_CHANNEL_INDEX_MASK_6,
+        AUDIO_CHANNEL_INDEX_MASK_7,  AUDIO_CHANNEL_INDEX_MASK_8,  AUDIO_CHANNEL_INDEX_MASK_9,
+        AUDIO_CHANNEL_INDEX_MASK_10, AUDIO_CHANNEL_INDEX_MASK_11, AUDIO_CHANNEL_INDEX_MASK_12,
+        AUDIO_CHANNEL_INDEX_MASK_13, AUDIO_CHANNEL_INDEX_MASK_14, AUDIO_CHANNEL_INDEX_MASK_15,
+        AUDIO_CHANNEL_INDEX_MASK_16, AUDIO_CHANNEL_INDEX_MASK_17, AUDIO_CHANNEL_INDEX_MASK_18,
+        AUDIO_CHANNEL_INDEX_MASK_19, AUDIO_CHANNEL_INDEX_MASK_20, AUDIO_CHANNEL_INDEX_MASK_21,
+        AUDIO_CHANNEL_INDEX_MASK_22, AUDIO_CHANNEL_INDEX_MASK_23, AUDIO_CHANNEL_INDEX_MASK_24,
+};
+constexpr size_t kNumChMasks = std::size(kChMasks);
+
+// types of pre processing modules
+enum PreProcId {
+    PREPROC_AGC,  // Automatic Gain Control
+    PREPROC_AEC,  // Acoustic Echo Canceler
+    PREPROC_NS,   // Noise Suppressor
+    PREPROC_AGC2,  // Automatic Gain Control 2
+    PREPROC_NUM_EFFECTS
+};
+
+int preProcCreateEffect(effect_handle_t* pEffectHandle, uint32_t effectType,
+                        effect_config_t* pConfig, int sessionId, int ioId) {
+    if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.create_effect(&kEffectUuids[effectType],
+                                                                 sessionId, ioId, pEffectHandle);
+        status != 0) {
+        ALOGE("Audio Preprocessing create returned an error = %d\n", status);
+        return EXIT_FAILURE;
+    }
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    if (effectType == PREPROC_AEC) {
+        if (int status = (**pEffectHandle)
+                                 ->command(*pEffectHandle, EFFECT_CMD_SET_CONFIG_REVERSE,
+                                           sizeof(effect_config_t), pConfig, &replySize, &reply);
+            status != 0) {
+            ALOGE("Set config reverse command returned an error = %d\n", status);
+            return EXIT_FAILURE;
+        }
+    }
+    if (int status = (**pEffectHandle)
+                             ->command(*pEffectHandle, EFFECT_CMD_SET_CONFIG,
+                                       sizeof(effect_config_t), pConfig, &replySize, &reply);
+        status != 0) {
+        ALOGE("Set config command returned an error = %d\n", status);
+        return EXIT_FAILURE;
+    }
+    return reply;
+}
+
+int preProcSetConfigParam(effect_handle_t effectHandle, uint32_t paramType, uint32_t paramValue) {
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    uint32_t paramData[2] = {paramType, paramValue};
+    effect_param_t* effectParam = (effect_param_t*)malloc(sizeof(*effectParam) + sizeof(paramData));
+    memcpy(&effectParam->data[0], &paramData[0], sizeof(paramData));
+    effectParam->psize = sizeof(paramData[0]);
+    (*effectHandle)
+            ->command(effectHandle, EFFECT_CMD_SET_PARAM, sizeof(effect_param_t), effectParam,
+                      &replySize, &reply);
+    free(effectParam);
+    return reply;
+}
+
+short preProcGetShortVal(float paramValue) {
+    return static_cast<short>(paramValue * std::numeric_limits<short>::max());
+}
+
+static void BM_PREPROCESSING(benchmark::State& state) {
+    const size_t chMask = kChMasks[state.range(0) - 1];
+    const size_t channelCount = audio_channel_count_from_in_mask(chMask);
+
+    PreProcId effectType = (PreProcId)state.range(1);
+
+    int32_t sessionId = 1;
+    int32_t ioId = 1;
+    effect_handle_t effectHandle = nullptr;
+    effect_config_t config{};
+    config.inputCfg.samplingRate = config.outputCfg.samplingRate = kSampleRate;
+    config.inputCfg.channels = config.outputCfg.channels = chMask;
+    config.inputCfg.format = config.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
+
+    if (int status = preProcCreateEffect(&effectHandle, state.range(1), &config, sessionId, ioId);
+        status != 0) {
+        ALOGE("Create effect call returned error %i", status);
+        return;
+    }
+
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    if (int status =
+                (*effectHandle)
+                        ->command(effectHandle, EFFECT_CMD_ENABLE, 0, nullptr, &replySize, &reply);
+        status != 0) {
+        ALOGE("Command enable call returned error %d\n", reply);
+        return;
+    }
+
+    // Initialize input buffer with deterministic pseudo-random values
+    const int frameLength = (int)(kSampleRate * kTenMilliSecVal);
+    std::minstd_rand gen(chMask);
+    std::uniform_real_distribution<> dis(-1.0f, 1.0f);
+    std::vector<short> in(frameLength * channelCount);
+    for (auto& i : in) {
+        i = preProcGetShortVal(dis(gen));
+    }
+    std::vector<short> farIn(frameLength * channelCount);
+    for (auto& i : farIn) {
+        i = preProcGetShortVal(dis(gen));
+    }
+    std::vector<short> out(frameLength * channelCount);
+
+    // Run the test
+    for (auto _ : state) {
+        benchmark::DoNotOptimize(in.data());
+        benchmark::DoNotOptimize(out.data());
+        benchmark::DoNotOptimize(farIn.data());
+
+        audio_buffer_t inBuffer = {.frameCount = (size_t)frameLength, .s16 = in.data()};
+        audio_buffer_t outBuffer = {.frameCount = (size_t)frameLength, .s16 = out.data()};
+        audio_buffer_t farInBuffer = {.frameCount = (size_t)frameLength, .s16 = farIn.data()};
+
+        if (PREPROC_AEC == effectType) {
+            if (int status =
+                        preProcSetConfigParam(effectHandle, AEC_PARAM_ECHO_DELAY, kStreamDelayMs);
+                status != 0) {
+                ALOGE("preProcSetConfigParam returned Error %d\n", status);
+                return;
+            }
+        }
+        if (int status = (*effectHandle)->process(effectHandle, &inBuffer, &outBuffer);
+            status != 0) {
+            ALOGE("\nError: Process i = %d returned with error %d\n", (int)state.range(1), status);
+            return;
+        }
+        if (PREPROC_AEC == effectType) {
+            if (int status =
+                        (*effectHandle)->process_reverse(effectHandle, &farInBuffer, &outBuffer);
+                status != 0) {
+                ALOGE("\nError: Process reverse i = %d returned with error %d\n",
+                      (int)state.range(1), status);
+                return;
+            }
+        }
+    }
+    benchmark::ClobberMemory();
+
+    state.SetComplexityN(state.range(0));
+
+    if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.release_effect(effectHandle); status != 0) {
+        ALOGE("release_effect returned an error = %d\n", status);
+        return;
+    }
+}
+
+static void preprocessingArgs(benchmark::internal::Benchmark* b) {
+    for (int i = 1; i <= (int)kNumChMasks; i++) {
+        for (int j = 0; j < (int)kNumEffectUuids; ++j) {
+            b->Args({i, j});
+        }
+    }
+}
+
+BENCHMARK(BM_PREPROCESSING)->Apply(preprocessingArgs);
+
+BENCHMARK_MAIN();
diff --git a/media/libeffects/preprocessing/tests/Android.bp b/media/libeffects/preprocessing/tests/Android.bp
new file mode 100644
index 0000000..8848e79
--- /dev/null
+++ b/media/libeffects/preprocessing/tests/Android.bp
@@ -0,0 +1,43 @@
+// audio preprocessing unit test
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libeffects_preprocessing_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libeffects_preprocessing_license",
+    ],
+}
+
+cc_test {
+    name: "AudioPreProcessingTest",
+    vendor: true,
+    srcs: ["PreProcessingTest.cpp"],
+    shared_libs: [
+        "libaudioutils",
+        "liblog",
+        "libutils",
+    ],
+    static_libs: [
+        "libaudiopreprocessing",
+        "webrtc_audio_processing",
+    ],
+    header_libs: [
+        "libaudioeffects",
+        "libhardware_headers",
+    ],
+    gtest: false,
+}
+
+cc_test {
+    name: "correlation",
+    host_supported: true,
+    srcs: ["correlation.cpp"],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+    gtest: false,
+}
diff --git a/media/libeffects/preprocessing/tests/PreProcessingTest.cpp b/media/libeffects/preprocessing/tests/PreProcessingTest.cpp
new file mode 100644
index 0000000..5f223c9
--- /dev/null
+++ b/media/libeffects/preprocessing/tests/PreProcessingTest.cpp
@@ -0,0 +1,479 @@
+/*
+ * Copyright (C) 2020 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 <getopt.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <sys/stat.h>
+#include <vector>
+
+#include <audio_effects/effect_aec.h>
+#include <audio_effects/effect_agc.h>
+#include <audio_effects/effect_agc2.h>
+#include <audio_effects/effect_ns.h>
+#include <log/log.h>
+
+// This is the only symbol that needs to be imported
+extern audio_effect_library_t AUDIO_EFFECT_LIBRARY_INFO_SYM;
+
+//------------------------------------------------------------------------------
+// local definitions
+//------------------------------------------------------------------------------
+
+// types of pre processing modules
+enum PreProcId {
+    PREPROC_AGC,  // Automatic Gain Control
+    PREPROC_AGC2,  // Automatic Gain Control 2
+    PREPROC_AEC,  // Acoustic Echo Canceler
+    PREPROC_NS,   // Noise Suppressor
+    PREPROC_NUM_EFFECTS
+};
+
+enum PreProcParams {
+    ARG_HELP = 1,
+    ARG_INPUT,
+    ARG_OUTPUT,
+    ARG_FAR,
+    ARG_FS,
+    ARG_CH_MASK,
+    ARG_AGC_TGT_LVL,
+    ARG_AGC_COMP_LVL,
+    ARG_AEC_DELAY,
+    ARG_NS_LVL,
+    ARG_AGC2_GAIN,
+    ARG_AGC2_LVL,
+    ARG_AGC2_SAT_MGN
+};
+
+struct preProcConfigParams_t {
+    int samplingFreq = 16000;
+    audio_channel_mask_t chMask = AUDIO_CHANNEL_IN_MONO;
+    int nsLevel = 0;         // a value between 0-3
+    int agcTargetLevel = 3;  // in dB
+    int agcCompLevel = 9;    // in dB
+    float agc2Gain = 0.f;              // in dB
+    float agc2SaturationMargin = 2.f;  // in dB
+    int agc2Level = 0;                 // either kRms(0) or kPeak(1)
+    int aecDelay = 0;  // in ms
+};
+
+const effect_uuid_t kPreProcUuids[PREPROC_NUM_EFFECTS] = {
+        {0xaa8130e0, 0x66fc, 0x11e0, 0xbad0, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // agc uuid
+        {0x89f38e65, 0xd4d2, 0x4d64, 0xad0e, {0x2b, 0x3e, 0x79, 0x9e, 0xa8, 0x86}},  // agc2 uuid
+        {0xbb392ec0, 0x8d4d, 0x11e0, 0xa896, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // aec uuid
+        {0xc06c8400, 0x8e06, 0x11e0, 0x9cb6, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}},  // ns  uuid
+};
+
+constexpr audio_channel_mask_t kPreProcConfigChMask[] = {
+        AUDIO_CHANNEL_IN_MONO,
+        AUDIO_CHANNEL_IN_STEREO,
+        AUDIO_CHANNEL_IN_FRONT_BACK,
+        AUDIO_CHANNEL_IN_6,
+        AUDIO_CHANNEL_IN_2POINT0POINT2,
+        AUDIO_CHANNEL_IN_2POINT1POINT2,
+        AUDIO_CHANNEL_IN_3POINT0POINT2,
+        AUDIO_CHANNEL_IN_3POINT1POINT2,
+        AUDIO_CHANNEL_IN_5POINT1,
+        AUDIO_CHANNEL_IN_VOICE_UPLINK_MONO,
+        AUDIO_CHANNEL_IN_VOICE_DNLINK_MONO,
+        AUDIO_CHANNEL_IN_VOICE_CALL_MONO,
+};
+
+constexpr int kPreProcConfigChMaskCount = std::size(kPreProcConfigChMask);
+
+void printUsage() {
+    printf("\nUsage: ");
+    printf("\n     <executable> [options]\n");
+    printf("\nwhere options are, ");
+    printf("\n     --input <inputfile>");
+    printf("\n           path to the input file");
+    printf("\n     --output <outputfile>");
+    printf("\n           path to the output file");
+    printf("\n     --help");
+    printf("\n           Prints this usage information");
+    printf("\n     --fs <sampling_freq>");
+    printf("\n           Sampling frequency in Hz, default 16000.");
+    printf("\n     -ch_mask <channel_mask>\n");
+    printf("\n         0  - AUDIO_CHANNEL_IN_MONO");
+    printf("\n         1  - AUDIO_CHANNEL_IN_STEREO");
+    printf("\n         2  - AUDIO_CHANNEL_IN_FRONT_BACK");
+    printf("\n         3  - AUDIO_CHANNEL_IN_6");
+    printf("\n         4  - AUDIO_CHANNEL_IN_2POINT0POINT2");
+    printf("\n         5  - AUDIO_CHANNEL_IN_2POINT1POINT2");
+    printf("\n         6  - AUDIO_CHANNEL_IN_3POINT0POINT2");
+    printf("\n         7  - AUDIO_CHANNEL_IN_3POINT1POINT2");
+    printf("\n         8  - AUDIO_CHANNEL_IN_5POINT1");
+    printf("\n         9  - AUDIO_CHANNEL_IN_VOICE_UPLINK_MONO");
+    printf("\n         10 - AUDIO_CHANNEL_IN_VOICE_DNLINK_MONO ");
+    printf("\n         11 - AUDIO_CHANNEL_IN_VOICE_CALL_MONO ");
+    printf("\n         default 0");
+    printf("\n     --far <farend_file>");
+    printf("\n           Path to far-end file needed for echo cancellation");
+    printf("\n     --aec");
+    printf("\n           Enable Echo Cancellation, default disabled");
+    printf("\n     --ns");
+    printf("\n           Enable Noise Suppression, default disabled");
+    printf("\n     --agc");
+    printf("\n           Enable Gain Control, default disabled");
+    printf("\n     --agc2");
+    printf("\n           Enable Gain Controller 2, default disabled");
+    printf("\n     --ns_lvl <ns_level>");
+    printf("\n           Noise Suppression level in dB, default value 0dB");
+    printf("\n     --agc_tgt_lvl <target_level>");
+    printf("\n           AGC Target Level in dB, default value 3dB");
+    printf("\n     --agc_comp_lvl <comp_level>");
+    printf("\n           AGC Comp Level in dB, default value 9dB");
+    printf("\n     --agc2_gain <fixed_digital_gain>");
+    printf("\n           AGC Fixed Digital Gain in dB, default value 0dB");
+    printf("\n     --agc2_lvl <level_estimator>");
+    printf("\n           AGC Adaptive Digital Level Estimator, default value kRms");
+    printf("\n     --agc2_sat_mgn <saturation_margin>");
+    printf("\n           AGC Adaptive Digital Saturation Margin in dB, default value 2dB");
+    printf("\n     --aec_delay <delay>");
+    printf("\n           AEC delay value in ms, default value 0ms");
+    printf("\n");
+}
+
+constexpr float kTenMilliSecVal = 0.01;
+
+int preProcCreateEffect(effect_handle_t* pEffectHandle, uint32_t effectType,
+                        effect_config_t* pConfig, int sessionId, int ioId) {
+    if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.create_effect(&kPreProcUuids[effectType],
+                                                                 sessionId, ioId, pEffectHandle);
+        status != 0) {
+        ALOGE("Audio Preprocessing create returned an error = %d\n", status);
+        return EXIT_FAILURE;
+    }
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    if (effectType == PREPROC_AEC) {
+        (**pEffectHandle)
+                ->command(*pEffectHandle, EFFECT_CMD_SET_CONFIG_REVERSE, sizeof(effect_config_t),
+                          pConfig, &replySize, &reply);
+    }
+    (**pEffectHandle)
+            ->command(*pEffectHandle, EFFECT_CMD_SET_CONFIG, sizeof(effect_config_t), pConfig,
+                      &replySize, &reply);
+    return reply;
+}
+
+int preProcSetConfigParam(uint32_t paramType, uint32_t paramValue, effect_handle_t effectHandle) {
+    int reply = 0;
+    uint32_t replySize = sizeof(reply);
+    uint32_t paramData[2] = {paramType, paramValue};
+    effect_param_t* effectParam = (effect_param_t*)malloc(sizeof(*effectParam) + sizeof(paramData));
+    memcpy(&effectParam->data[0], &paramData[0], sizeof(paramData));
+    effectParam->psize = sizeof(paramData[0]);
+    (*effectHandle)
+            ->command(effectHandle, EFFECT_CMD_SET_PARAM, sizeof(effect_param_t), effectParam,
+                      &replySize, &reply);
+    free(effectParam);
+    return reply;
+}
+
+int main(int argc, const char* argv[]) {
+    if (argc == 1) {
+        printUsage();
+        return EXIT_FAILURE;
+    }
+    const char* inputFile = nullptr;
+    const char* outputFile = nullptr;
+    const char* farFile = nullptr;
+    int effectEn[PREPROC_NUM_EFFECTS] = {0};
+
+    const option long_opts[] = {
+            {"help", no_argument, nullptr, ARG_HELP},
+            {"input", required_argument, nullptr, ARG_INPUT},
+            {"output", required_argument, nullptr, ARG_OUTPUT},
+            {"far", required_argument, nullptr, ARG_FAR},
+            {"fs", required_argument, nullptr, ARG_FS},
+            {"ch_mask", required_argument, nullptr, ARG_CH_MASK},
+            {"agc_tgt_lvl", required_argument, nullptr, ARG_AGC_TGT_LVL},
+            {"agc_comp_lvl", required_argument, nullptr, ARG_AGC_COMP_LVL},
+            {"agc2_gain", required_argument, nullptr, ARG_AGC2_GAIN},
+            {"agc2_lvl", required_argument, nullptr, ARG_AGC2_LVL},
+            {"agc2_sat_mgn", required_argument, nullptr, ARG_AGC2_SAT_MGN},
+            {"aec_delay", required_argument, nullptr, ARG_AEC_DELAY},
+            {"ns_lvl", required_argument, nullptr, ARG_NS_LVL},
+            {"aec", no_argument, &effectEn[PREPROC_AEC], 1},
+            {"agc", no_argument, &effectEn[PREPROC_AGC], 1},
+            {"agc2", no_argument, &effectEn[PREPROC_AGC2], 1},
+            {"ns", no_argument, &effectEn[PREPROC_NS], 1},
+            {nullptr, 0, nullptr, 0},
+    };
+    struct preProcConfigParams_t preProcCfgParams {};
+
+    while (true) {
+        const int opt = getopt_long(argc, (char* const*)argv, "i:o:", long_opts, nullptr);
+        if (opt == -1) {
+            break;
+        }
+        switch (opt) {
+            case ARG_HELP:
+                printUsage();
+                return 0;
+            case ARG_INPUT: {
+                inputFile = (char*)optarg;
+                break;
+            }
+            case ARG_OUTPUT: {
+                outputFile = (char*)optarg;
+                break;
+            }
+            case ARG_FAR: {
+                farFile = (char*)optarg;
+                break;
+            }
+            case ARG_FS: {
+                preProcCfgParams.samplingFreq = atoi(optarg);
+                break;
+            }
+            case ARG_CH_MASK: {
+                int chMaskIdx = atoi(optarg);
+                if (chMaskIdx < 0 or chMaskIdx > kPreProcConfigChMaskCount) {
+                    ALOGE("Channel Mask index not in correct range\n");
+                    printUsage();
+                    return EXIT_FAILURE;
+                }
+                preProcCfgParams.chMask = kPreProcConfigChMask[chMaskIdx];
+                break;
+            }
+            case ARG_AGC_TGT_LVL: {
+                preProcCfgParams.agcTargetLevel = atoi(optarg);
+                break;
+            }
+            case ARG_AGC_COMP_LVL: {
+                preProcCfgParams.agcCompLevel = atoi(optarg);
+                break;
+            }
+            case ARG_AGC2_GAIN: {
+                preProcCfgParams.agc2Gain = atof(optarg);
+                break;
+            }
+            case ARG_AGC2_LVL: {
+                preProcCfgParams.agc2Level = atoi(optarg);
+                break;
+            }
+            case ARG_AGC2_SAT_MGN: {
+                preProcCfgParams.agc2SaturationMargin = atof(optarg);
+                break;
+            }
+            case ARG_AEC_DELAY: {
+                preProcCfgParams.aecDelay = atoi(optarg);
+                break;
+            }
+            case ARG_NS_LVL: {
+                preProcCfgParams.nsLevel = atoi(optarg);
+                break;
+            }
+            default:
+                break;
+        }
+    }
+
+    if (inputFile == nullptr) {
+        ALOGE("Error: missing input file\n");
+        printUsage();
+        return EXIT_FAILURE;
+    }
+
+    std::unique_ptr<FILE, decltype(&fclose)> inputFp(fopen(inputFile, "rb"), &fclose);
+    if (inputFp == nullptr) {
+        ALOGE("Cannot open input file %s\n", inputFile);
+        return EXIT_FAILURE;
+    }
+
+    std::unique_ptr<FILE, decltype(&fclose)> farFp(fopen(farFile, "rb"), &fclose);
+    std::unique_ptr<FILE, decltype(&fclose)> outputFp(fopen(outputFile, "wb"), &fclose);
+    if (effectEn[PREPROC_AEC]) {
+        if (farFile == nullptr) {
+            ALOGE("Far end signal file required for echo cancellation \n");
+            return EXIT_FAILURE;
+        }
+        if (farFp == nullptr) {
+            ALOGE("Cannot open far end stream file %s\n", farFile);
+            return EXIT_FAILURE;
+        }
+        struct stat statInput, statFar;
+        (void)fstat(fileno(inputFp.get()), &statInput);
+        (void)fstat(fileno(farFp.get()), &statFar);
+        if (statInput.st_size != statFar.st_size) {
+            ALOGE("Near and far end signals are of different sizes");
+            return EXIT_FAILURE;
+        }
+    }
+    if (outputFile != nullptr && outputFp == nullptr) {
+        ALOGE("Cannot open output file %s\n", outputFile);
+        return EXIT_FAILURE;
+    }
+
+    int32_t sessionId = 1;
+    int32_t ioId = 1;
+    effect_handle_t effectHandle[PREPROC_NUM_EFFECTS] = {nullptr};
+    effect_config_t config;
+    config.inputCfg.samplingRate = config.outputCfg.samplingRate = preProcCfgParams.samplingFreq;
+    config.inputCfg.channels = config.outputCfg.channels = preProcCfgParams.chMask;
+    config.inputCfg.format = config.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
+
+    // Create all the effect handles
+    for (int i = 0; i < PREPROC_NUM_EFFECTS; i++) {
+        if (int status = preProcCreateEffect(&effectHandle[i], i, &config, sessionId, ioId);
+            status != 0) {
+            ALOGE("Create effect call returned error %i", status);
+            return EXIT_FAILURE;
+        }
+    }
+
+    for (int i = 0; i < PREPROC_NUM_EFFECTS; i++) {
+        if (effectEn[i] == 1) {
+            int reply = 0;
+            uint32_t replySize = sizeof(reply);
+            (*effectHandle[i])
+                    ->command(effectHandle[i], EFFECT_CMD_ENABLE, 0, nullptr, &replySize, &reply);
+            if (reply != 0) {
+                ALOGE("Command enable call returned error %d\n", reply);
+                return EXIT_FAILURE;
+            }
+        }
+    }
+
+    // Set Config Params of the effects
+    if (effectEn[PREPROC_AGC]) {
+        if (int status = preProcSetConfigParam(AGC_PARAM_TARGET_LEVEL,
+                                               (uint32_t)preProcCfgParams.agcTargetLevel,
+                                               effectHandle[PREPROC_AGC]);
+            status != 0) {
+            ALOGE("Invalid AGC Target Level. Error %d\n", status);
+            return EXIT_FAILURE;
+        }
+        if (int status = preProcSetConfigParam(AGC_PARAM_COMP_GAIN,
+                                               (uint32_t)preProcCfgParams.agcCompLevel,
+                                               effectHandle[PREPROC_AGC]);
+            status != 0) {
+            ALOGE("Invalid AGC Comp Gain. Error %d\n", status);
+            return EXIT_FAILURE;
+        }
+    }
+    if (effectEn[PREPROC_AGC2]) {
+        if (int status = preProcSetConfigParam(AGC2_PARAM_FIXED_DIGITAL_GAIN,
+                                               (float)preProcCfgParams.agc2Gain,
+                                               effectHandle[PREPROC_AGC2]);
+            status != 0) {
+            ALOGE("Invalid AGC2 Fixed Digital Gain. Error %d\n", status);
+            return EXIT_FAILURE;
+        }
+        if (int status = preProcSetConfigParam(AGC2_PARAM_ADAPT_DIGI_LEVEL_ESTIMATOR,
+                                               (uint32_t)preProcCfgParams.agc2Level,
+                                               effectHandle[PREPROC_AGC2]);
+            status != 0) {
+            ALOGE("Invalid AGC2 Level Estimator. Error %d\n", status);
+            return EXIT_FAILURE;
+        }
+        if (int status = preProcSetConfigParam(AGC2_PARAM_ADAPT_DIGI_EXTRA_SATURATION_MARGIN,
+                                               (float)preProcCfgParams.agc2SaturationMargin,
+                                               effectHandle[PREPROC_AGC2]);
+            status != 0) {
+            ALOGE("Invalid AGC2 Saturation Margin. Error %d\n", status);
+            return EXIT_FAILURE;
+        }
+    }
+    if (effectEn[PREPROC_NS]) {
+        if (int status = preProcSetConfigParam(NS_PARAM_LEVEL, (uint32_t)preProcCfgParams.nsLevel,
+                                               effectHandle[PREPROC_NS]);
+            status != 0) {
+            ALOGE("Invalid Noise Suppression level Error %d\n", status);
+            return EXIT_FAILURE;
+        }
+    }
+
+    // Process Call
+    const int frameLength = (int)(preProcCfgParams.samplingFreq * kTenMilliSecVal);
+    const int ioChannelCount = audio_channel_count_from_in_mask(preProcCfgParams.chMask);
+    const int ioFrameSize = ioChannelCount * sizeof(short);
+    int frameCounter = 0;
+    while (true) {
+        std::vector<short> in(frameLength * ioChannelCount);
+        std::vector<short> out(frameLength * ioChannelCount);
+        std::vector<short> farIn(frameLength * ioChannelCount);
+        size_t samplesRead = fread(in.data(), ioFrameSize, frameLength, inputFp.get());
+        if (samplesRead == 0) {
+            break;
+        }
+        audio_buffer_t inputBuffer, outputBuffer;
+        audio_buffer_t farInBuffer{};
+        inputBuffer.frameCount = samplesRead;
+        outputBuffer.frameCount = samplesRead;
+        inputBuffer.s16 = in.data();
+        outputBuffer.s16 = out.data();
+
+        if (farFp != nullptr) {
+            samplesRead = fread(farIn.data(), ioFrameSize, frameLength, farFp.get());
+            if (samplesRead == 0) {
+                break;
+            }
+            farInBuffer.frameCount = samplesRead;
+            farInBuffer.s16 = farIn.data();
+        }
+
+        for (int i = 0; i < PREPROC_NUM_EFFECTS; i++) {
+            if (effectEn[i] == 1) {
+                if (i == PREPROC_AEC) {
+                    if (int status = preProcSetConfigParam(AEC_PARAM_ECHO_DELAY,
+                                                           (uint32_t)preProcCfgParams.aecDelay,
+                                                           effectHandle[PREPROC_AEC]);
+                        status != 0) {
+                        ALOGE("preProcSetConfigParam returned Error %d\n", status);
+                        return EXIT_FAILURE;
+                    }
+                }
+                if (int status = (*effectHandle[i])
+                                         ->process(effectHandle[i], &inputBuffer, &outputBuffer);
+                    status != 0) {
+                    ALOGE("\nError: Process i = %d returned with error %d\n", i, status);
+                    return EXIT_FAILURE;
+                }
+                if (i == PREPROC_AEC) {
+                    if (int status = (*effectHandle[i])
+                                             ->process_reverse(effectHandle[i], &farInBuffer,
+                                                               &outputBuffer);
+                        status != 0) {
+                        ALOGE("\nError: Process reverse i = %d returned with error %d\n", i,
+                              status);
+                        return EXIT_FAILURE;
+                    }
+                }
+            }
+        }
+        if (outputFp != nullptr) {
+            size_t samplesWritten =
+                    fwrite(out.data(), ioFrameSize, outputBuffer.frameCount, outputFp.get());
+            if (samplesWritten != outputBuffer.frameCount) {
+                ALOGE("\nError: Output file writing failed");
+                break;
+            }
+        }
+        frameCounter += frameLength;
+    }
+    // Release all the effect handles created
+    for (int i = 0; i < PREPROC_NUM_EFFECTS; i++) {
+        if (int status = AUDIO_EFFECT_LIBRARY_INFO_SYM.release_effect(effectHandle[i]);
+            status != 0) {
+            ALOGE("Audio Preprocessing release returned an error = %d\n", status);
+            return EXIT_FAILURE;
+        }
+    }
+    return EXIT_SUCCESS;
+}
diff --git a/media/libeffects/preprocessing/tests/correlation.cpp b/media/libeffects/preprocessing/tests/correlation.cpp
new file mode 100644
index 0000000..eb56fc3
--- /dev/null
+++ b/media/libeffects/preprocessing/tests/correlation.cpp
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2021 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 <iostream>
+#include <vector>
+
+constexpr int kMinLoopLimitValue = 1;
+constexpr int kNumPeaks = 3;
+
+/*!
+  \brief           Compute the length normalized correlation of two signals
+
+  \sigX            Pointer to signal 1
+  \sigY            Pointer to signal 2
+  \len             Length of signals
+  \enableCrossCorr Flag to be set to 1 if cross-correlation is needed
+
+  \return          First value is vector of correlation peak indices
+                   Second value is vector of correlation peak values
+*/
+
+static std::pair<std::vector<int>, std::vector<float>> correlation(const int16_t* sigX,
+                                                                   const int16_t* sigY, int len,
+                                                                   int16_t enableCrossCorr) {
+    float maxCorrVal = 0.f, prevCorrVal = 0.f;
+    int delay = 0, peakIndex = 0, flag = 0;
+    int loopLim = (1 == enableCrossCorr) ? len : kMinLoopLimitValue;
+    std::vector<int> peakIndexVect(kNumPeaks, 0);
+    std::vector<float> peakValueVect(kNumPeaks, 0.f);
+    for (int i = 0; i < loopLim; i++) {
+        float corrVal = 0.f;
+        for (int j = i; j < len; j++) {
+            corrVal += (float)(sigX[j] * sigY[j - i]);
+        }
+        corrVal /= len - i;
+        if (corrVal > maxCorrVal) {
+            delay = i;
+            maxCorrVal = corrVal;
+        }
+        // Correlation peaks are expected to be observed at equal intervals. The interval length is
+        // expected to match with wave period.
+        // The following block of code saves the first kNumPeaks number of peaks and the index at
+        // which they occur.
+        if (peakIndex < kNumPeaks) {
+            if (corrVal > prevCorrVal) {
+                peakIndexVect[peakIndex] = i;
+                peakValueVect[peakIndex] = corrVal;
+                flag = 0;
+            } else if (0 == flag) {
+                peakIndex++;
+                flag = 1;
+            }
+        }
+        if (peakIndex == kNumPeaks) break;
+        prevCorrVal = corrVal;
+    }
+    return {peakIndexVect, peakValueVect};
+}
+
+void printUsage() {
+    printf("\nUsage: ");
+    printf("\n     correlation <firstFile> <secondFile> [enableCrossCorr]\n");
+    printf("\nwhere, \n     <firstFile>       is the first file name");
+    printf("\n     <secondFile>      is the second file name");
+    printf("\n     [enableCrossCorr] is flag to set for cross-correlation (Default 1)\n\n");
+}
+
+int main(int argc, const char* argv[]) {
+    if (argc < 3) {
+        printUsage();
+        return EXIT_FAILURE;
+    }
+
+    std::unique_ptr<FILE, decltype(&fclose)> fInput1(fopen(argv[1], "rb"), &fclose);
+    if (fInput1.get() == NULL) {
+        printf("\nError: missing file %s\n", argv[1]);
+        return EXIT_FAILURE;
+    }
+    std::unique_ptr<FILE, decltype(&fclose)> fInput2(fopen(argv[2], "rb"), &fclose);
+    if (fInput2.get() == NULL) {
+        printf("\nError: missing file %s\n", argv[2]);
+        return EXIT_FAILURE;
+    }
+    int16_t enableCrossCorr = (4 == argc) ? atoi(argv[3]) : 1;
+
+    fseek(fInput1.get(), 0L, SEEK_END);
+    unsigned int fileSize1 = ftell(fInput1.get());
+    rewind(fInput1.get());
+    fseek(fInput2.get(), 0L, SEEK_END);
+    unsigned int fileSize2 = ftell(fInput2.get());
+    rewind(fInput2.get());
+    if (fileSize1 != fileSize2) {
+        printf("\nError: File sizes different\n");
+        return EXIT_FAILURE;
+    }
+
+    size_t numFrames = fileSize1 / sizeof(int16_t);
+    std::unique_ptr<int16_t[]> inBuffer1(new int16_t[numFrames]());
+    std::unique_ptr<int16_t[]> inBuffer2(new int16_t[numFrames]());
+
+    if (numFrames != fread(inBuffer1.get(), sizeof(int16_t), numFrames, fInput1.get())) {
+        printf("\nError: Unable to read %zu samples from file %s\n", numFrames, argv[1]);
+        return EXIT_FAILURE;
+    }
+
+    if (numFrames != fread(inBuffer2.get(), sizeof(int16_t), numFrames, fInput2.get())) {
+        printf("\nError: Unable to read %zu samples from file %s\n", numFrames, argv[2]);
+        return EXIT_FAILURE;
+    }
+
+    auto pairAutoCorr1 = correlation(inBuffer1.get(), inBuffer1.get(), numFrames, enableCrossCorr);
+    auto pairAutoCorr2 = correlation(inBuffer2.get(), inBuffer2.get(), numFrames, enableCrossCorr);
+
+    // Following code block checks pitch period difference between two input signals. They must
+    // match as AGC applies only gain, no frequency related computation is done.
+    bool pitchMatch = false;
+    for (unsigned i = 0; i < pairAutoCorr1.first.size() - 1; i++) {
+        if (pairAutoCorr1.first[i + 1] - pairAutoCorr1.first[i] !=
+            pairAutoCorr2.first[i + 1] - pairAutoCorr2.first[i]) {
+            pitchMatch = false;
+            break;
+        }
+        pitchMatch = true;
+    }
+    if (pitchMatch) {
+        printf("Auto-correlation  : Pitch matched\n");
+    } else {
+        printf("Auto-correlation  : Pitch mismatch\n");
+        return EXIT_FAILURE;
+    }
+
+    if (enableCrossCorr) {
+        auto pairCrossCorr =
+                correlation(inBuffer1.get(), inBuffer2.get(), numFrames, enableCrossCorr);
+
+        // Since AGC applies only gain, the pitch information obtained from cross correlation data
+        // of input and output is expected to be same as the input signal's pitch information.
+        pitchMatch = false;
+        for (unsigned i = 0; i < pairCrossCorr.first.size() - 1; i++) {
+            if (pairAutoCorr1.first[i + 1] - pairAutoCorr1.first[i] !=
+                pairCrossCorr.first[i + 1] - pairCrossCorr.first[i]) {
+                pitchMatch = false;
+                break;
+            }
+            pitchMatch = true;
+        }
+        if (pitchMatch) {
+            printf("Cross-correlation : Pitch matched for AGC\n");
+            if (pairAutoCorr1.second[0]) {
+                printf("Expected gain     : (maxCrossCorr / maxAutoCorr1) = %f\n",
+                       pairCrossCorr.second[0] / pairAutoCorr1.second[0]);
+            }
+        } else {
+            printf("Cross-correlation : Pitch mismatch\n");
+            return EXIT_FAILURE;
+        }
+    }
+
+    return EXIT_SUCCESS;
+}
diff --git a/media/libeffects/proxy/Android.bp b/media/libeffects/proxy/Android.bp
index c6abb9e..6256eda 100644
--- a/media/libeffects/proxy/Android.bp
+++ b/media/libeffects/proxy/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libeffectproxy",
     relative_install_path: "soundfx",
diff --git a/media/libeffects/proxy/EffectProxy.cpp b/media/libeffects/proxy/EffectProxy.cpp
index 42e44f0..c010d68 100644
--- a/media/libeffects/proxy/EffectProxy.cpp
+++ b/media/libeffects/proxy/EffectProxy.cpp
@@ -30,7 +30,7 @@
 #include <media/EffectsFactoryApi.h>
 
 namespace android {
-// This is a dummy proxy descriptor just to return to Factory during the initial
+// This is a stub proxy descriptor just to return to Factory during the initial
 // GetDescriptor call. Later in the factory, it is replaced with the
 // SW sub effect descriptor
 // proxy UUID af8da7e0-2ca1-11e3-b71d-0002a5d5c51b
diff --git a/media/libeffects/res/raw/sinesweepraw.raw b/media/libeffects/res/raw/sinesweepraw.raw
new file mode 100644
index 0000000..c0d48ce
--- /dev/null
+++ b/media/libeffects/res/raw/sinesweepraw.raw
Binary files differ
diff --git a/media/libeffects/testlibs/EffectsMath.h b/media/libeffects/testlibs/EffectsMath.h
index 2a44399..dd43b49 100644
--- a/media/libeffects/testlibs/EffectsMath.h
+++ b/media/libeffects/testlibs/EffectsMath.h
@@ -251,22 +251,6 @@
 */
 
 /* use LFO_GAIN_TO_CENTS to convert the LFO gain value to cents */
-#if 0
-#define    DOUBLE_LOG2_10    (double) (3.32192809488736)    /* log2(10) */
-
-#define    DOUBLE_LFO_GAIN_TO_CENTS    (double)                \
-    (                                                        \
-                (DOUBLE_LOG2_10) *                            \
-                1200.0    /                                    \
-                20.0                                        \
-    )
-
-#define    LFO_GAIN_TO_CENTS    (int32_t)                        \
-    (                                                        \
-                DOUBLE_LFO_GAIN_TO_CENTS *                    \
-                (0x1L << NUM_EG1_FRAC_BITS)                    \
-    )
-#endif
 
 #define LFO_GAIN_TO_CENTS (int32_t) (1671981156L >> (23 - NUM_EG1_FRAC_BITS))
 
diff --git a/media/libeffects/visualizer/Android.mk b/media/libeffects/visualizer/Android.mk
index 35e2f3d..68c7cf2 100644
--- a/media/libeffects/visualizer/Android.mk
+++ b/media/libeffects/visualizer/Android.mk
@@ -18,6 +18,9 @@
 
 LOCAL_MODULE_RELATIVE_PATH := soundfx
 LOCAL_MODULE:= libvisualizer
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE
 
 LOCAL_C_INCLUDES := \
 	$(call include-path-for, audio-effects) \
diff --git a/media/libheif/Android.bp b/media/libheif/Android.bp
index 7d5a4eb..6a3427e 100644
--- a/media/libheif/Android.bp
+++ b/media/libheif/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libheif",
 
diff --git a/media/libmedia/Android.bp b/media/libmedia/Android.bp
index 3fd3fc3..48b5391 100644
--- a/media/libmedia/Android.bp
+++ b/media/libmedia/Android.bp
@@ -1,3 +1,20 @@
+package {
+    default_applicable_licenses: ["frameworks_av_media_libmedia_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libmedia_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_headers {
     name: "libmedia_headers",
     vendor_available: true,
@@ -17,6 +34,22 @@
     ],
 }
 
+cc_library_headers {
+    name: "libmedia_datasource_headers",
+    export_include_dirs: ["include"],
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.media",
+    ],
+    min_sdk_version: "29",
+}
+
 filegroup {
     name: "libmedia_omx_aidl",
     srcs: [
@@ -203,7 +236,7 @@
     ],
 
     header_libs: [
-        "libmedia_headers",
+        "libmedia_datasource_headers",
         "media_ndk_headers",
     ],
 
@@ -220,6 +253,14 @@
         ],
         cfi: true,
     },
+
+    host_supported: true,
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
 
 cc_library_shared {
@@ -309,11 +350,13 @@
     header_libs: [
         "libstagefright_headers",
         "media_ndk_headers",
+        "jni_headers",
     ],
 
     export_header_lib_headers: [
         "libstagefright_headers",
         "media_ndk_headers",
+        "jni_headers",
     ],
 
     shared_libs: [
@@ -372,3 +415,36 @@
         cfi: true,
     },
 }
+
+cc_library_static {
+    name: "libmedia_ndkformatpriv",
+
+    host_supported: true,
+
+    srcs: [
+        "NdkMediaFormatPriv.cpp",
+        "NdkMediaErrorPriv.cpp",
+    ],
+
+    header_libs: [
+        "libstagefright_foundation_headers",
+        "libstagefright_headers",
+        "media_ndk_headers",
+    ],
+
+    cflags: [
+        "-DEXPORT=__attribute__((visibility(\"default\")))",
+        "-Werror",
+        "-Wall",
+    ],
+
+    export_include_dirs: ["include"],
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+
+    apex_available: ["com.android.media"],
+}
diff --git a/media/libmedia/CharacterEncodingDetector.cpp b/media/libmedia/CharacterEncodingDetector.cpp
index 5c6b981..64ba977 100644
--- a/media/libmedia/CharacterEncodingDetector.cpp
+++ b/media/libmedia/CharacterEncodingDetector.cpp
@@ -268,7 +268,7 @@
 
                 ucnv_convertEx(mUtf8Conv, conv, &target, target + targetLength,
                         &source, source + strlen(source),
-                        NULL, NULL, NULL, NULL, TRUE, TRUE, &status);
+                        NULL, NULL, NULL, NULL, true, true, &status);
 
                 if (U_FAILURE(status)) {
                     ALOGE("ucnv_convertEx failed: %d", status);
diff --git a/media/libmedia/IMediaPlayer.cpp b/media/libmedia/IMediaPlayer.cpp
index eaa2e63..c89c023 100644
--- a/media/libmedia/IMediaPlayer.cpp
+++ b/media/libmedia/IMediaPlayer.cpp
@@ -35,53 +35,6 @@
 
 using media::VolumeShaper;
 
-enum {
-    DISCONNECT = IBinder::FIRST_CALL_TRANSACTION,
-    SET_DATA_SOURCE_URL,
-    SET_DATA_SOURCE_FD,
-    SET_DATA_SOURCE_STREAM,
-    SET_DATA_SOURCE_CALLBACK,
-    SET_BUFFERING_SETTINGS,
-    GET_BUFFERING_SETTINGS,
-    PREPARE_ASYNC,
-    START,
-    STOP,
-    IS_PLAYING,
-    SET_PLAYBACK_SETTINGS,
-    GET_PLAYBACK_SETTINGS,
-    SET_SYNC_SETTINGS,
-    GET_SYNC_SETTINGS,
-    PAUSE,
-    SEEK_TO,
-    GET_CURRENT_POSITION,
-    GET_DURATION,
-    RESET,
-    NOTIFY_AT,
-    SET_AUDIO_STREAM_TYPE,
-    SET_LOOPING,
-    SET_VOLUME,
-    INVOKE,
-    SET_METADATA_FILTER,
-    GET_METADATA,
-    SET_AUX_EFFECT_SEND_LEVEL,
-    ATTACH_AUX_EFFECT,
-    SET_VIDEO_SURFACETEXTURE,
-    SET_PARAMETER,
-    GET_PARAMETER,
-    SET_RETRANSMIT_ENDPOINT,
-    GET_RETRANSMIT_ENDPOINT,
-    SET_NEXT_PLAYER,
-    APPLY_VOLUME_SHAPER,
-    GET_VOLUME_SHAPER_STATE,
-    // Modular DRM
-    PREPARE_DRM,
-    RELEASE_DRM,
-    // AudioRouting
-    SET_OUTPUT_DEVICE,
-    GET_ROUTED_DEVICE_ID,
-    ENABLE_AUDIO_DEVICE_CALLBACK,
-};
-
 // ModDrm helpers
 static status_t readVector(const Parcel& reply, Vector<uint8_t>& vector) {
     uint32_t size = 0;
@@ -188,6 +141,15 @@
         return reply.readInt32();
     }
 
+    status_t setDataSource(const String8& rtpParams) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IMediaPlayer::getInterfaceDescriptor());
+        data.writeString8(rtpParams);
+        remote()->transact(SET_DATA_SOURCE_RTP, data, &reply);
+
+        return reply.readInt32();
+    }
+
     // pass the buffered IGraphicBufferProducer to the media player service
     status_t setVideoSurfaceTexture(const sp<IGraphicBufferProducer>& bufferProducer)
     {
@@ -712,6 +674,12 @@
             }
             return NO_ERROR;
         }
+        case SET_DATA_SOURCE_RTP: {
+            CHECK_INTERFACE(IMediaPlayer, data, reply);
+            String8 rtpParams = data.readString8();
+            reply->writeInt32(setDataSource(rtpParams));
+            return NO_ERROR;
+        }
         case SET_VIDEO_SURFACETEXTURE: {
             CHECK_INTERFACE(IMediaPlayer, data, reply);
             sp<IGraphicBufferProducer> bufferProducer =
@@ -985,7 +953,7 @@
         case PREPARE_DRM: {
             CHECK_INTERFACE(IMediaPlayer, data, reply);
 
-            uint8_t uuid[16];
+            uint8_t uuid[16] = {};
             data.read(uuid, sizeof(uuid));
             Vector<uint8_t> drmSessionId;
             status_t status = readVector(data, drmSessionId);
diff --git a/media/libmedia/IMediaRecorder.cpp b/media/libmedia/IMediaRecorder.cpp
index ac86f72..154988d 100644
--- a/media/libmedia/IMediaRecorder.cpp
+++ b/media/libmedia/IMediaRecorder.cpp
@@ -66,6 +66,7 @@
     ENABLE_AUDIO_DEVICE_CALLBACK,
     GET_ACTIVE_MICROPHONES,
     GET_PORT_ID,
+    GET_RTP_DATA_USAGE,
     SET_PREFERRED_MICROPHONE_DIRECTION,
     SET_PREFERRED_MICROPHONE_FIELD_DIMENSION,
     SET_PRIVACY_SENSITIVE,
@@ -476,6 +477,23 @@
         *portId = (audio_port_handle_t)reply.readInt32();
         return NO_ERROR;
     }
+
+    status_t getRtpDataUsage(uint64_t *bytes)
+    {
+        ALOGV("getRtpDataUsage");
+        if (bytes == nullptr) {
+            return BAD_VALUE;
+        }
+        Parcel data, reply;
+        data.writeInterfaceToken(IMediaRecorder::getInterfaceDescriptor());
+        status_t status = remote()->transact(GET_RTP_DATA_USAGE, data, &reply);
+        if (status != OK
+                || (status = (status_t)reply.readInt32()) != NO_ERROR) {
+            *bytes = 0;
+            return status;
+        }
+        return reply.readUint64(bytes);
+    }
 };
 
 IMPLEMENT_META_INTERFACE(MediaRecorder, "android.media.IMediaRecorder");
@@ -759,6 +777,17 @@
             }
             return NO_ERROR;
         }
+        case GET_RTP_DATA_USAGE: {
+            ALOGV("GET_RTP_DATA_USAGE");
+            CHECK_INTERFACE(IMediaRecorder, data, reply);
+            uint64_t bytes;
+            status_t status = getRtpDataUsage(&bytes);
+            reply->writeInt32(status);
+            if (status == NO_ERROR) {
+                reply->writeUint64(bytes);
+            }
+            return NO_ERROR;
+        }
         case SET_PREFERRED_MICROPHONE_DIRECTION: {
             ALOGV("SET_PREFERRED_MICROPHONE_DIRECTION");
             CHECK_INTERFACE(IMediaRecorder, data, reply);
diff --git a/media/libmedia/MediaProfiles.cpp b/media/libmedia/MediaProfiles.cpp
index 637322f..8be961c 100644
--- a/media/libmedia/MediaProfiles.cpp
+++ b/media/libmedia/MediaProfiles.cpp
@@ -240,7 +240,10 @@
 
     const size_t nMappings = sizeof(sVideoEncoderNameMap)/sizeof(sVideoEncoderNameMap[0]);
     const int codec = findTagForName(sVideoEncoderNameMap, nMappings, atts[1]);
-    CHECK(codec != -1);
+    if (codec == -1) {
+      ALOGE("MediaProfiles::createVideoCodec failed to locate codec %s", atts[1]);
+      return nullptr;
+    }
 
     MediaProfiles::VideoCodec *videoCodec =
         new MediaProfiles::VideoCodec(static_cast<video_encoder>(codec),
@@ -262,7 +265,10 @@
           !strcmp("channels",   atts[6]));
     const size_t nMappings = sizeof(sAudioEncoderNameMap)/sizeof(sAudioEncoderNameMap[0]);
     const int codec = findTagForName(sAudioEncoderNameMap, nMappings, atts[1]);
-    CHECK(codec != -1);
+    if (codec == -1) {
+      ALOGE("MediaProfiles::createAudioCodec failed to locate codec %s", atts[1]);
+      return nullptr;
+    }
 
     MediaProfiles::AudioCodec *audioCodec =
         new MediaProfiles::AudioCodec(static_cast<audio_encoder>(codec),
@@ -282,7 +288,10 @@
 
     const size_t nMappings = sizeof(sAudioDecoderNameMap)/sizeof(sAudioDecoderNameMap[0]);
     const int codec = findTagForName(sAudioDecoderNameMap, nMappings, atts[1]);
-    CHECK(codec != -1);
+    if (codec == -1) {
+      ALOGE("MediaProfiles::createAudioDecoderCap failed to locate codec %s", atts[1]);
+      return nullptr;
+    }
 
     MediaProfiles::AudioDecoderCap *cap =
         new MediaProfiles::AudioDecoderCap(static_cast<audio_decoder>(codec));
@@ -298,7 +307,10 @@
 
     const size_t nMappings = sizeof(sVideoDecoderNameMap)/sizeof(sVideoDecoderNameMap[0]);
     const int codec = findTagForName(sVideoDecoderNameMap, nMappings, atts[1]);
-    CHECK(codec != -1);
+    if (codec == -1) {
+      ALOGE("MediaProfiles::createVideoDecoderCap failed to locate codec %s", atts[1]);
+      return nullptr;
+    }
 
     MediaProfiles::VideoDecoderCap *cap =
         new MediaProfiles::VideoDecoderCap(static_cast<video_decoder>(codec));
@@ -322,7 +334,10 @@
 
     const size_t nMappings = sizeof(sVideoEncoderNameMap)/sizeof(sVideoEncoderNameMap[0]);
     const int codec = findTagForName(sVideoEncoderNameMap, nMappings, atts[1]);
-    CHECK(codec != -1);
+    if (codec == -1) {
+      ALOGE("MediaProfiles::createVideoEncoderCap failed to locate codec %s", atts[1]);
+      return nullptr;
+    }
 
     MediaProfiles::VideoEncoderCap *cap =
         new MediaProfiles::VideoEncoderCap(static_cast<video_encoder>(codec),
@@ -346,7 +361,10 @@
 
     const size_t nMappings = sizeof(sAudioEncoderNameMap)/sizeof(sAudioEncoderNameMap[0]);
     const int codec = findTagForName(sAudioEncoderNameMap, nMappings, atts[1]);
-    CHECK(codec != -1);
+    if (codec == -1) {
+      ALOGE("MediaProfiles::createAudioEncoderCap failed to locate codec %s", atts[1]);
+      return nullptr;
+    }
 
     MediaProfiles::AudioEncoderCap *cap =
         new MediaProfiles::AudioEncoderCap(static_cast<audio_encoder>(codec), atoi(atts[5]),
@@ -386,11 +404,17 @@
     const size_t nProfileMappings = sizeof(sCamcorderQualityNameMap)/
             sizeof(sCamcorderQualityNameMap[0]);
     const int quality = findTagForName(sCamcorderQualityNameMap, nProfileMappings, atts[1]);
-    CHECK(quality != -1);
+    if (quality == -1) {
+      ALOGE("MediaProfiles::createCamcorderProfile failed to locate quality %s", atts[1]);
+      return nullptr;
+    }
 
     const size_t nFormatMappings = sizeof(sFileFormatMap)/sizeof(sFileFormatMap[0]);
     const int fileFormat = findTagForName(sFileFormatMap, nFormatMappings, atts[3]);
-    CHECK(fileFormat != -1);
+    if (fileFormat == -1) {
+      ALOGE("MediaProfiles::createCamcorderProfile failed to locate file format %s", atts[1]);
+      return nullptr;
+    }
 
     MediaProfiles::CamcorderProfile *profile = new MediaProfiles::CamcorderProfile;
     profile->mCameraId = cameraId;
@@ -462,24 +486,39 @@
         createAudioCodec(atts, profiles);
     } else if (strcmp("VideoEncoderCap", name) == 0 &&
                strcmp("true", atts[3]) == 0) {
-        profiles->mVideoEncoders.add(createVideoEncoderCap(atts));
+        MediaProfiles::VideoEncoderCap* cap = createVideoEncoderCap(atts);
+        if (cap != nullptr) {
+          profiles->mVideoEncoders.add(cap);
+        }
     } else if (strcmp("AudioEncoderCap", name) == 0 &&
                strcmp("true", atts[3]) == 0) {
-        profiles->mAudioEncoders.add(createAudioEncoderCap(atts));
+        MediaProfiles::AudioEncoderCap* cap = createAudioEncoderCap(atts);
+        if (cap != nullptr) {
+          profiles->mAudioEncoders.add(cap);
+        }
     } else if (strcmp("VideoDecoderCap", name) == 0 &&
                strcmp("true", atts[3]) == 0) {
-        profiles->mVideoDecoders.add(createVideoDecoderCap(atts));
+        MediaProfiles::VideoDecoderCap* cap = createVideoDecoderCap(atts);
+        if (cap != nullptr) {
+          profiles->mVideoDecoders.add(cap);
+        }
     } else if (strcmp("AudioDecoderCap", name) == 0 &&
                strcmp("true", atts[3]) == 0) {
-        profiles->mAudioDecoders.add(createAudioDecoderCap(atts));
+        MediaProfiles::AudioDecoderCap* cap = createAudioDecoderCap(atts);
+        if (cap != nullptr) {
+          profiles->mAudioDecoders.add(cap);
+        }
     } else if (strcmp("EncoderOutputFileFormat", name) == 0) {
         profiles->mEncoderOutputFileFormats.add(createEncoderOutputFileFormat(atts));
     } else if (strcmp("CamcorderProfiles", name) == 0) {
         profiles->mCurrentCameraId = getCameraId(atts);
         profiles->addStartTimeOffset(profiles->mCurrentCameraId, atts);
     } else if (strcmp("EncoderProfile", name) == 0) {
-        profiles->mCamcorderProfiles.add(
-            createCamcorderProfile(profiles->mCurrentCameraId, atts, profiles->mCameraIds));
+      MediaProfiles::CamcorderProfile* profile = createCamcorderProfile(
+          profiles->mCurrentCameraId, atts, profiles->mCameraIds);
+      if (profile != nullptr) {
+        profiles->mCamcorderProfiles.add(profile);
+      }
     } else if (strcmp("ImageEncoding", name) == 0) {
         profiles->addImageEncodingQualityLevel(profiles->mCurrentCameraId, atts);
     }
diff --git a/media/libmedia/MediaResource.cpp b/media/libmedia/MediaResource.cpp
index 0936a99..fe86d27 100644
--- a/media/libmedia/MediaResource.cpp
+++ b/media/libmedia/MediaResource.cpp
@@ -35,7 +35,7 @@
     this->value = value;
 }
 
-MediaResource::MediaResource(Type type, const std::vector<int8_t> &id, int64_t value) {
+MediaResource::MediaResource(Type type, const std::vector<uint8_t> &id, int64_t value) {
     this->type = type;
     this->subType = SubType::kUnspecifiedSubType;
     this->id = id;
@@ -66,11 +66,11 @@
 }
 
 //static
-MediaResource MediaResource::DrmSessionResource(const std::vector<int8_t> &id, int64_t value) {
+MediaResource MediaResource::DrmSessionResource(const std::vector<uint8_t> &id, int64_t value) {
     return MediaResource(Type::kDrmSession, id, value);
 }
 
-static String8 bytesToHexString(const std::vector<int8_t> &bytes) {
+static String8 bytesToHexString(const std::vector<uint8_t> &bytes) {
     String8 str;
     for (auto &b : bytes) {
         str.appendFormat("%02x", b);
diff --git a/media/libmedia/MidiIoWrapper.cpp b/media/libmedia/MidiIoWrapper.cpp
index e71ea2c..f682b6e 100644
--- a/media/libmedia/MidiIoWrapper.cpp
+++ b/media/libmedia/MidiIoWrapper.cpp
@@ -18,8 +18,10 @@
 #define LOG_TAG "MidiIoWrapper"
 #include <utils/Log.h>
 
-#include <sys/stat.h>
 #include <fcntl.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <algorithm>
 
 #include <media/MidiIoWrapper.h>
 #include <media/MediaExtractorPluginApi.h>
@@ -32,6 +34,8 @@
 }
 
 namespace android {
+int MidiIoWrapper::sCacheBufferSize = 0;
+Mutex MidiIoWrapper::mCacheLock;
 
 MidiIoWrapper::MidiIoWrapper(const char *path) {
     ALOGV("MidiIoWrapper(%s)", path);
@@ -39,6 +43,8 @@
     mBase = 0;
     mLength = lseek(mFd, 0, SEEK_END);
     mDataSource = nullptr;
+    mCacheBuffer = NULL;
+    mCacheBufRangeLength = 0;
 }
 
 MidiIoWrapper::MidiIoWrapper(int fd, off64_t offset, int64_t size) {
@@ -47,6 +53,8 @@
     mBase = offset;
     mLength = size;
     mDataSource = nullptr;
+    mCacheBuffer = NULL;
+    mCacheBufRangeLength = 0;
 }
 
 class MidiIoWrapper::DataSourceUnwrapper {
@@ -96,6 +104,8 @@
     } else {
         mLength = 0;
     }
+    mCacheBuffer = NULL;
+    mCacheBufRangeLength = 0;
 }
 
 MidiIoWrapper::~MidiIoWrapper() {
@@ -104,11 +114,80 @@
         close(mFd);
     }
     delete mDataSource;
+
+    if (NULL != mCacheBuffer) {
+        delete [] mCacheBuffer;
+        mCacheBuffer = NULL;
+        {
+            Mutex::Autolock _l(mCacheLock);
+            sCacheBufferSize -= mLength;
+        }
+    }
 }
 
 int MidiIoWrapper::readAt(void *buffer, int offset, int size) {
     ALOGV("readAt(%p, %d, %d)", buffer, offset, size);
 
+    if (offset < 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    if (offset + size > mLength) {
+        size = mLength - offset;
+    }
+
+    if (mCacheBuffer == NULL) {
+        Mutex::Autolock _l(mCacheLock);
+        if (sCacheBufferSize + mLength <= kTotalCacheSize) {
+            mCacheBuffer = new (std::nothrow) unsigned char[mLength];
+            if (NULL != mCacheBuffer) {
+                sCacheBufferSize += mLength;
+                ALOGV("sCacheBufferSize : %d", sCacheBufferSize);
+            } else {
+                ALOGE("failed to allocate memory for mCacheBuffer");
+            }
+        } else {
+            ALOGV("not allocate memory for mCacheBuffer");
+        }
+    }
+
+    if (mCacheBuffer != NULL) {
+        if (mCacheBufRangeLength > 0 && mCacheBufRangeLength >= (offset + size)) {
+            /* Use buffered data */
+            memcpy(buffer, (void*)(mCacheBuffer + offset), size);
+            return size;
+        } else {
+            /* Buffer new data */
+            int64_t beyondCacheBufRangeLength = (offset + size) - mCacheBufRangeLength;
+            int64_t numRequiredBytesToCache =
+                  std::max((int64_t)kSingleCacheSize, beyondCacheBufRangeLength);
+            int64_t availableReadLength = mLength - mCacheBufRangeLength;
+            int64_t readSize = std::min(availableReadLength, numRequiredBytesToCache);
+            int actualNumBytesRead =
+                unbufferedReadAt(mCacheBuffer + mCacheBufRangeLength,
+                        mCacheBufRangeLength, readSize);
+            if(actualNumBytesRead > 0) {
+                mCacheBufRangeLength += actualNumBytesRead;
+                if (offset >= mCacheBufRangeLength) {
+                    return 0;
+                } else if (offset + size >= mCacheBufRangeLength) {
+                    memcpy(buffer, (void*)(mCacheBuffer + offset), mCacheBufRangeLength - offset);
+                    return mCacheBufRangeLength - offset;
+                } else {
+                    memcpy(buffer, (void*)(mCacheBuffer + offset), size);
+                    return size;
+                }
+            } else {
+                return actualNumBytesRead;
+            }
+        }
+    } else {
+        return unbufferedReadAt(buffer, offset, size);
+    }
+}
+
+int MidiIoWrapper::unbufferedReadAt(void *buffer, int offset, int size) {
+    ALOGV("unbufferedReadAt(%p, %d, %d)", buffer, offset, size);
     if (mDataSource != NULL) {
         return mDataSource->readAt(offset, buffer, size);
     }
diff --git a/media/libmedia/NdkMediaFormatPriv.cpp b/media/libmedia/NdkMediaFormatPriv.cpp
index 3a9fb8b..7983184 100644
--- a/media/libmedia/NdkMediaFormatPriv.cpp
+++ b/media/libmedia/NdkMediaFormatPriv.cpp
@@ -24,8 +24,6 @@
 #include <media/NdkMediaFormatPriv.h>
 #include <media/stagefright/foundation/AMessage.h>
 
-#include <jni.h>
-
 using namespace android;
 
 namespace android {
diff --git a/media/libmedia/include/media/IMediaPlayer.h b/media/libmedia/include/media/IMediaPlayer.h
index a4c0ec6..28684d1 100644
--- a/media/libmedia/include/media/IMediaPlayer.h
+++ b/media/libmedia/include/media/IMediaPlayer.h
@@ -59,6 +59,7 @@
     virtual status_t        setDataSource(int fd, int64_t offset, int64_t length) = 0;
     virtual status_t        setDataSource(const sp<IStreamSource>& source) = 0;
     virtual status_t        setDataSource(const sp<IDataSource>& source) = 0;
+    virtual status_t        setDataSource(const String8& rtpParams) = 0;
     virtual status_t        setVideoSurfaceTexture(
                                     const sp<IGraphicBufferProducer>& bufferProducer) = 0;
     virtual status_t        getBufferingSettings(
@@ -136,6 +137,56 @@
     virtual status_t        setOutputDevice(audio_port_handle_t deviceId) = 0;
     virtual status_t        getRoutedDeviceId(audio_port_handle_t *deviceId) = 0;
     virtual status_t        enableAudioDeviceCallback(bool enabled) = 0;
+protected:
+
+    friend class IMediaPlayerTest;
+    enum {
+        DISCONNECT = IBinder::FIRST_CALL_TRANSACTION,
+        SET_DATA_SOURCE_URL,
+        SET_DATA_SOURCE_FD,
+        SET_DATA_SOURCE_STREAM,
+        SET_DATA_SOURCE_CALLBACK,
+        SET_DATA_SOURCE_RTP,
+        SET_BUFFERING_SETTINGS,
+        GET_BUFFERING_SETTINGS,
+        PREPARE_ASYNC,
+        START,
+        STOP,
+        IS_PLAYING,
+        SET_PLAYBACK_SETTINGS,
+        GET_PLAYBACK_SETTINGS,
+        SET_SYNC_SETTINGS,
+        GET_SYNC_SETTINGS,
+        PAUSE,
+        SEEK_TO,
+        GET_CURRENT_POSITION,
+        GET_DURATION,
+        RESET,
+        NOTIFY_AT,
+        SET_AUDIO_STREAM_TYPE,
+        SET_LOOPING,
+        SET_VOLUME,
+        INVOKE,
+        SET_METADATA_FILTER,
+        GET_METADATA,
+        SET_AUX_EFFECT_SEND_LEVEL,
+        ATTACH_AUX_EFFECT,
+        SET_VIDEO_SURFACETEXTURE,
+        SET_PARAMETER,
+        GET_PARAMETER,
+        SET_RETRANSMIT_ENDPOINT,
+        GET_RETRANSMIT_ENDPOINT,
+        SET_NEXT_PLAYER,
+        APPLY_VOLUME_SHAPER,
+        GET_VOLUME_SHAPER_STATE,
+        // Modular DRM
+        PREPARE_DRM,
+        RELEASE_DRM,
+        // AudioRouting
+        SET_OUTPUT_DEVICE,
+        GET_ROUTED_DEVICE_ID,
+        ENABLE_AUDIO_DEVICE_CALLBACK,
+    };
 };
 
 // ----------------------------------------------------------------------------
diff --git a/media/libmedia/include/media/IMediaRecorder.h b/media/libmedia/include/media/IMediaRecorder.h
index 651bd5e..6e69782 100644
--- a/media/libmedia/include/media/IMediaRecorder.h
+++ b/media/libmedia/include/media/IMediaRecorder.h
@@ -78,6 +78,7 @@
     virtual status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) = 0;
     virtual status_t setPreferredMicrophoneFieldDimension(float zoom) = 0;
     virtual status_t getPortId(audio_port_handle_t *portId) = 0;
+    virtual status_t getRtpDataUsage(uint64_t *bytes) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/media/libmedia/include/media/MediaRecorderBase.h b/media/libmedia/include/media/MediaRecorderBase.h
index 8493f64..d9a7efb 100644
--- a/media/libmedia/include/media/MediaRecorderBase.h
+++ b/media/libmedia/include/media/MediaRecorderBase.h
@@ -77,6 +77,7 @@
     virtual status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction) = 0;
     virtual status_t setPreferredMicrophoneFieldDimension(float zoom) = 0;
     virtual status_t getPortId(audio_port_handle_t *portId) const = 0;
+    virtual status_t getRtpDataUsage(uint64_t *bytes) = 0;
 
 
 
diff --git a/media/libmedia/include/media/MediaResource.h b/media/libmedia/include/media/MediaResource.h
index e7362c1..4927d28 100644
--- a/media/libmedia/include/media/MediaResource.h
+++ b/media/libmedia/include/media/MediaResource.h
@@ -35,13 +35,13 @@
     MediaResource() = delete;
     MediaResource(Type type, int64_t value);
     MediaResource(Type type, SubType subType, int64_t value);
-    MediaResource(Type type, const std::vector<int8_t> &id, int64_t value);
+    MediaResource(Type type, const std::vector<uint8_t> &id, int64_t value);
 
     static MediaResource CodecResource(bool secure, bool video);
     static MediaResource GraphicMemoryResource(int64_t value);
     static MediaResource CpuBoostResource();
     static MediaResource VideoBatteryResource();
-    static MediaResource DrmSessionResource(const std::vector<int8_t> &id, int64_t value);
+    static MediaResource DrmSessionResource(const std::vector<uint8_t> &id, int64_t value);
 };
 
 inline static const char *asString(MediaResource::Type i, const char *def = "??") {
diff --git a/media/libmedia/include/media/MidiIoWrapper.h b/media/libmedia/include/media/MidiIoWrapper.h
index 0cdd4ad..5fa745c 100644
--- a/media/libmedia/include/media/MidiIoWrapper.h
+++ b/media/libmedia/include/media/MidiIoWrapper.h
@@ -18,6 +18,7 @@
 #define MIDI_IO_WRAPPER_H_
 
 #include <libsonivox/eas_types.h>
+#include <utils/Mutex.h>
 
 namespace android {
 
@@ -32,17 +33,27 @@
     ~MidiIoWrapper();
 
     int readAt(void *buffer, int offset, int size);
+    int unbufferedReadAt(void *buffer, int offset, int size);
     int size();
 
     EAS_FILE_LOCATOR getLocator();
 
 private:
+    enum {
+        kTotalCacheSize      = 1024 * 1024 + 512 * 1024,
+        kSingleCacheSize     = 65536,
+    };
+
     int mFd;
     off64_t mBase;
     int64_t  mLength;
     class DataSourceUnwrapper;
     DataSourceUnwrapper *mDataSource;
     EAS_FILE mEasFile;
+    unsigned char *mCacheBuffer;
+    int64_t mCacheBufRangeLength;
+    static int sCacheBufferSize;
+    static Mutex mCacheLock;
 };
 
 
diff --git a/media/libmedia/include/media/mediaplayer.h b/media/libmedia/include/media/mediaplayer.h
index 7c29e50..71c0bc5 100644
--- a/media/libmedia/include/media/mediaplayer.h
+++ b/media/libmedia/include/media/mediaplayer.h
@@ -62,6 +62,7 @@
     MEDIA_META_DATA         = 202,
     MEDIA_DRM_INFO          = 210,
     MEDIA_TIME_DISCONTINUITY = 211,
+    MEDIA_IMS_RX_NOTICE     = 300,
     MEDIA_AUDIO_ROUTING_CHANGED = 10000,
 };
 
@@ -179,7 +180,10 @@
     KEY_PARAMETER_PLAYBACK_RATE_PERMILLE = 1300,                // set only
 
     // Set a Parcel containing the value of a parcelled Java AudioAttribute instance
-    KEY_PARAMETER_AUDIO_ATTRIBUTES = 1400                       // set only
+    KEY_PARAMETER_AUDIO_ATTRIBUTES = 1400,                       // set only
+
+    // Set a Parcel containing the values of RTP attribute
+    KEY_PARAMETER_RTP_ATTRIBUTES = 2000                       // set only
 };
 
 // Keep INVOKE_ID_* in sync with MediaPlayer.java.
@@ -219,6 +223,7 @@
 
             status_t        setDataSource(int fd, int64_t offset, int64_t length);
             status_t        setDataSource(const sp<IDataSource> &source);
+            status_t        setDataSource(const String8& rtpParams);
             status_t        setVideoSurfaceTexture(
                                     const sp<IGraphicBufferProducer>& bufferProducer);
             status_t        setListener(const sp<MediaPlayerListener>& listener);
diff --git a/media/libmedia/include/media/mediarecorder.h b/media/libmedia/include/media/mediarecorder.h
index 6e2d94d..84c92f6 100644
--- a/media/libmedia/include/media/mediarecorder.h
+++ b/media/libmedia/include/media/mediarecorder.h
@@ -270,6 +270,7 @@
     status_t    setPreferredMicrophoneFieldDimension(float zoom);
 
     status_t    getPortId(audio_port_handle_t *portId) const;
+    status_t    getRtpDataUsage(uint64_t *bytes);
 
 private:
     void                    doCleanUp();
@@ -291,6 +292,8 @@
     bool                        mIsOutputFileSet;
     Mutex                       mLock;
     Mutex                       mNotifyLock;
+
+    output_format               mOutputFormat;
 };
 
 };  // namespace android
diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp
index 6079a2d..1554920 100644
--- a/media/libmedia/mediaplayer.cpp
+++ b/media/libmedia/mediaplayer.cpp
@@ -195,6 +195,22 @@
     return err;
 }
 
+status_t MediaPlayer::setDataSource(const String8& rtpParams)
+{
+    ALOGV("setDataSource(rtpParams)");
+    status_t err = UNKNOWN_ERROR;
+    const sp<IMediaPlayerService> service(getMediaPlayerService());
+    if (service != 0) {
+        sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
+        if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
+            (NO_ERROR != player->setDataSource(rtpParams))) {
+            player.clear();
+        }
+        err = attachNewPlayer(player);
+    }
+    return err;
+}
+
 status_t MediaPlayer::invoke(const Parcel& request, Parcel *reply)
 {
     Mutex::Autolock _l(mLock);
@@ -943,6 +959,9 @@
     case MEDIA_META_DATA:
         ALOGV("Received timed metadata message");
         break;
+    case MEDIA_IMS_RX_NOTICE:
+        ALOGV("Received IMS Rx notice message");
+        break;
     default:
         ALOGV("unrecognized message: (%d, %d, %d)", msg, ext1, ext2);
         break;
diff --git a/media/libmedia/mediarecorder.cpp b/media/libmedia/mediarecorder.cpp
index 70655d5..e3cd9d8 100644
--- a/media/libmedia/mediarecorder.cpp
+++ b/media/libmedia/mediarecorder.cpp
@@ -244,6 +244,7 @@
         mCurrentState = MEDIA_RECORDER_ERROR;
         return ret;
     }
+    mOutputFormat = (output_format)of;
     mCurrentState = MEDIA_RECORDER_DATASOURCE_CONFIGURED;
     return ret;
 }
@@ -479,6 +480,13 @@
                            (MEDIA_RECORDER_PREPARED |
                             MEDIA_RECORDER_RECORDING |
                             MEDIA_RECORDER_ERROR));
+
+    // For RTP video, parameter should be set dynamically.
+    if (isInvalidState) {
+        if (mCurrentState == MEDIA_RECORDER_RECORDING &&
+            mOutputFormat == OUTPUT_FORMAT_RTP_AVP)
+            isInvalidState = false;
+    }
     if (isInvalidState) {
         ALOGE("setParameters is called in an invalid state: %d", mCurrentState);
         return INVALID_OPERATION;
@@ -737,6 +745,7 @@
     mIsAudioEncoderSet = false;
     mIsVideoEncoderSet = false;
     mIsOutputFileSet   = false;
+    mOutputFormat      = OUTPUT_FORMAT_DEFAULT;
 }
 
 // Release should be OK in any state
@@ -904,4 +913,14 @@
     return mMediaRecorder->getPortId(portId);
 }
 
+status_t MediaRecorder::getRtpDataUsage(uint64_t *bytes)
+{
+    ALOGV("getRtpDataUsage");
+
+    if (mMediaRecorder == NULL) {
+        ALOGE("media recorder is not initialized yet");
+        return INVALID_OPERATION;
+    }
+    return mMediaRecorder->getRtpDataUsage(bytes);
+}
 } // namespace android
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp b/media/libmedia/tests/codeclist/Android.bp
similarity index 63%
copy from media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
copy to media/libmedia/tests/codeclist/Android.bp
index 655491a..89dddc4 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
+++ b/media/libmedia/tests/codeclist/Android.bp
@@ -14,21 +14,31 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libmedia_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libmedia_license"],
+}
+
 cc_test {
-    name: "Mpeg4H263DecoderTest",
+    name: "CodecListTest",
     gtest: true,
 
     srcs: [
-        "Mpeg4H263DecoderTest.cpp",
+        "CodecListTest.cpp",
     ],
 
     shared_libs: [
+        "libbinder",
         "liblog",
-    ],
-
-    static_libs: [
-        "libstagefright_m4vh263dec",
+        "libmedia_codeclist",
+        "libstagefright",
         "libstagefright_foundation",
+        "libstagefright_xmlparser",
+        "libutils",
     ],
 
     cflags: [
@@ -37,10 +47,10 @@
     ],
 
     sanitize: {
+        cfi: true,
         misc_undefined: [
             "unsigned-integer-overflow",
             "signed-integer-overflow",
         ],
-        cfi: true,
     },
 }
diff --git a/media/libmedia/tests/codeclist/CodecListTest.cpp b/media/libmedia/tests/codeclist/CodecListTest.cpp
new file mode 100644
index 0000000..bd2adf7
--- /dev/null
+++ b/media/libmedia/tests/codeclist/CodecListTest.cpp
@@ -0,0 +1,222 @@
+/*
+ * Copyright (C) 2020 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 "CodecListTest"
+#include <utils/Log.h>
+
+#include <gtest/gtest.h>
+
+#include <binder/Parcel.h>
+#include <media/stagefright/MediaCodecConstants.h>
+#include <media/stagefright/MediaCodecList.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/AString.h>
+#include <media/stagefright/xmlparser/MediaCodecsXmlParser.h>
+
+#define kSwCodecXmlPath "/apex/com.android.media.swcodec/etc/"
+
+using namespace android;
+
+struct CddReq {
+    CddReq(const char *type, bool encoder) {
+        mediaType = type;
+        isEncoder = encoder;
+    }
+
+    const char *mediaType;
+    bool isEncoder;
+};
+
+TEST(CodecListTest, CodecListSanityTest) {
+    sp<IMediaCodecList> list = MediaCodecList::getInstance();
+    ASSERT_NE(list, nullptr) << "Unable to get MediaCodecList instance.";
+    EXPECT_GT(list->countCodecs(), 0) << "No codecs in CodecList";
+    for (size_t i = 0; i < list->countCodecs(); ++i) {
+        sp<MediaCodecInfo> info = list->getCodecInfo(i);
+        ASSERT_NE(info, nullptr) << "CodecInfo is null";
+        ssize_t index = list->findCodecByName(info->getCodecName());
+        EXPECT_GE(index, 0) << "Wasn't able to find existing codec: " << info->getCodecName();
+    }
+}
+
+TEST(CodecListTest, CodecListByTypeTest) {
+    sp<IMediaCodecList> list = MediaCodecList::getInstance();
+    ASSERT_NE(list, nullptr) << "Unable to get MediaCodecList instance.";
+
+    std::vector<CddReq> cddReq{
+            // media type, isEncoder
+            CddReq(MIMETYPE_AUDIO_AAC, false),
+            CddReq(MIMETYPE_AUDIO_AAC, true),
+
+            CddReq(MIMETYPE_VIDEO_AVC, false),
+            CddReq(MIMETYPE_VIDEO_HEVC, false),
+            CddReq(MIMETYPE_VIDEO_MPEG4, false),
+            CddReq(MIMETYPE_VIDEO_VP8, false),
+            CddReq(MIMETYPE_VIDEO_VP9, false),
+
+            CddReq(MIMETYPE_VIDEO_AVC, true),
+            CddReq(MIMETYPE_VIDEO_VP8, true),
+    };
+
+    for (CddReq codecReq : cddReq) {
+        ssize_t index = list->findCodecByType(codecReq.mediaType, codecReq.isEncoder);
+        EXPECT_GE(index, 0) << "Wasn't able to find codec for media type: " << codecReq.mediaType
+                            << (codecReq.isEncoder ? " encoder" : " decoder");
+    }
+}
+
+TEST(CodecInfoTest, ListInfoTest) {
+    ALOGV("Compare CodecInfo with info in XML");
+    MediaCodecsXmlParser parser;
+    status_t status = parser.parseXmlFilesInSearchDirs();
+    ASSERT_EQ(status, OK) << "XML Parsing failed for default paths";
+
+    const std::vector<std::string> &xmlFiles = MediaCodecsXmlParser::getDefaultXmlNames();
+    const std::vector<std::string> &searchDirsApex{std::string(kSwCodecXmlPath)};
+    status = parser.parseXmlFilesInSearchDirs(xmlFiles, searchDirsApex);
+    ASSERT_EQ(status, OK) << "XML Parsing of " << kSwCodecXmlPath << " failed";
+
+    MediaCodecsXmlParser::CodecMap codecMap = parser.getCodecMap();
+
+    sp<IMediaCodecList> list = MediaCodecList::getInstance();
+    ASSERT_NE(list, nullptr) << "Unable to get MediaCodecList instance";
+
+    // Compare CodecMap from XML to CodecList
+    for (auto mapIter : codecMap) {
+        ssize_t index = list->findCodecByName(mapIter.first.c_str());
+        if (index < 0) {
+            std::cout << "[   WARN   ] " << mapIter.first << " not found in CodecList \n";
+            continue;
+        }
+
+        sp<MediaCodecInfo> info = list->getCodecInfo(index);
+        ASSERT_NE(info, nullptr) << "CodecInfo is null";
+
+        MediaCodecsXmlParser::CodecProperties codecProperties = mapIter.second;
+        ASSERT_EQ(codecProperties.isEncoder, info->isEncoder()) << "Encoder property mismatch";
+
+        ALOGV("codec name: %s", info->getCodecName());
+        ALOGV("codec rank: %d", info->getRank());
+        ALOGV("codec ownername: %s", info->getOwnerName());
+        ALOGV("codec isEncoder: %d", info->isEncoder());
+
+        ALOGV("attributeFlags: kFlagIsHardwareAccelerated, kFlagIsSoftwareOnly, kFlagIsVendor, "
+              "kFlagIsEncoder");
+        std::bitset<4> attr(info->getAttributes());
+        ALOGV("codec attributes: %s", attr.to_string().c_str());
+
+        Vector<AString> mediaTypes;
+        info->getSupportedMediaTypes(&mediaTypes);
+        ALOGV("supported media types count: %zu", mediaTypes.size());
+        ASSERT_FALSE(mediaTypes.isEmpty())
+                << "no media type supported by codec: " << info->getCodecName();
+
+        MediaCodecsXmlParser::TypeMap typeMap = codecProperties.typeMap;
+        for (auto mediaType : mediaTypes) {
+            ALOGV("codec mediaTypes: %s", mediaType.c_str());
+            auto searchTypeMap = typeMap.find(mediaType.c_str());
+            ASSERT_NE(searchTypeMap, typeMap.end())
+                    << "CodecList doesn't contain codec media type: " << mediaType.c_str();
+            MediaCodecsXmlParser::AttributeMap attributeMap = searchTypeMap->second;
+
+            const sp<MediaCodecInfo::Capabilities> &capabilities =
+                    info->getCapabilitiesFor(mediaType.c_str());
+
+            Vector<uint32_t> colorFormats;
+            capabilities->getSupportedColorFormats(&colorFormats);
+            for (auto colorFormat : colorFormats) {
+                ALOGV("supported color formats: %d", colorFormat);
+            }
+
+            Vector<MediaCodecInfo::ProfileLevel> profileLevels;
+            capabilities->getSupportedProfileLevels(&profileLevels);
+            if (!profileLevels.empty()) {
+                ALOGV("supported profilelevel for media type: %s", mediaType.c_str());
+            }
+            for (auto profileLevel : profileLevels) {
+                ALOGV("profile: %d, level: %d", profileLevel.mProfile, profileLevel.mLevel);
+            }
+
+            sp<AMessage> details = capabilities->getDetails();
+            ASSERT_NE(details, nullptr) << "Details in codec capabilities is null";
+            ALOGV("no. of entries in details: %zu", details->countEntries());
+
+            for (size_t idxDetail = 0; idxDetail < details->countEntries(); idxDetail++) {
+                AMessage::Type type;
+                const char *name = details->getEntryNameAt(idxDetail, &type);
+                ALOGV("details entry name: %s", name);
+                AMessage::ItemData itemData = details->getEntryAt(idxDetail);
+                switch (type) {
+                    case AMessage::kTypeInt32:
+                        int32_t val32;
+                        if (itemData.find(&val32)) {
+                            ALOGV("entry int val: %d", val32);
+                            auto searchAttr = attributeMap.find(name);
+                            if (searchAttr == attributeMap.end()) {
+                                ALOGW("Parser doesn't have key: %s", name);
+                            } else if (stoi(searchAttr->second) != val32) {
+                                ALOGW("Values didn't match for key: %s", name);
+                                ALOGV("Values act/exp: %d / %d", val32, stoi(searchAttr->second));
+                            }
+                        }
+                        break;
+                    case AMessage::kTypeString:
+                        if (AString valStr; itemData.find(&valStr)) {
+                            ALOGV("entry str val: %s", valStr.c_str());
+                            auto searchAttr = attributeMap.find(name);
+                            if (searchAttr == attributeMap.end()) {
+                                ALOGW("Parser doesn't have key: %s", name);
+                            } else if (searchAttr->second != valStr.c_str()) {
+                                ALOGW("Values didn't match for key: %s", name);
+                                ALOGV("Values act/exp: %s / %s", valStr.c_str(),
+                                      searchAttr->second.c_str());
+                            }
+                        }
+                        break;
+                    default:
+                        ALOGV("data type: %d shouldn't be present in details", type);
+                        break;
+                }
+            }
+        }
+
+        Parcel *codecInfoParcel = new Parcel();
+        ASSERT_NE(codecInfoParcel, nullptr) << "Unable to create parcel";
+
+        status_t status = info->writeToParcel(codecInfoParcel);
+        ASSERT_EQ(status, OK) << "Writing to parcel failed";
+
+        codecInfoParcel->setDataPosition(0);
+        sp<MediaCodecInfo> parcelCodecInfo = info->FromParcel(*codecInfoParcel);
+        ASSERT_NE(parcelCodecInfo, nullptr) << "CodecInfo from parcel is null";
+        delete codecInfoParcel;
+
+        EXPECT_STREQ(info->getCodecName(), parcelCodecInfo->getCodecName())
+                << "Returned codec name in info doesn't match";
+        EXPECT_EQ(info->getRank(), parcelCodecInfo->getRank())
+                << "Returned component rank in info doesn't match";
+    }
+}
+
+TEST(CodecListTest, CodecListGlobalSettingsTest) {
+    sp<IMediaCodecList> list = MediaCodecList::getInstance();
+    ASSERT_NE(list, nullptr) << "Unable to get MediaCodecList instance";
+
+    sp<AMessage> globalSettings = list->getGlobalSettings();
+    ASSERT_NE(globalSettings, nullptr) << "GlobalSettings AMessage is null";
+    ALOGV("global settings: %s", globalSettings->debugString(0).c_str());
+}
diff --git a/media/libmedia/tests/mediaplayer/Android.bp b/media/libmedia/tests/mediaplayer/Android.bp
new file mode 100644
index 0000000..0fff7b4
--- /dev/null
+++ b/media/libmedia/tests/mediaplayer/Android.bp
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2021 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 {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libmedia_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libmedia_license"],
+}
+
+cc_test {
+    name: "IMediaPlayerTest",
+    test_suites: ["device-tests", "mts"],
+    gtest: true,
+
+    srcs: [
+        "IMediaPlayerTest.cpp",
+    ],
+
+    shared_libs: [
+        "libbinder",
+        "liblog",
+        "libmedia",
+        "libstagefright",
+        "libstagefright_foundation",
+        "libutils",
+    ],
+    compile_multilib: "first",
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+}
diff --git a/media/libmedia/tests/mediaplayer/IMediaPlayerTest.cpp b/media/libmedia/tests/mediaplayer/IMediaPlayerTest.cpp
new file mode 100644
index 0000000..097e8ef
--- /dev/null
+++ b/media/libmedia/tests/mediaplayer/IMediaPlayerTest.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <binder/IServiceManager.h>
+#include <binder/Parcel.h>
+#include <gtest/gtest.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/IMediaPlayer.h>
+#include <media/IMediaPlayerService.h>
+#include <media/mediaplayer.h>
+
+namespace android {
+
+constexpr uint8_t kMockByteArray[16] = {};
+
+ class IMediaPlayerTest : public testing::Test {
+  protected:
+   static constexpr uint32_t PREPARE_DRM = IMediaPlayer::PREPARE_DRM;
+
+   void SetUp() override {
+    mediaPlayer_ = new MediaPlayer();
+    sp<IServiceManager> serviceManager = defaultServiceManager();
+    sp<IBinder> mediaPlayerService = serviceManager->getService(String16("media.player"));
+    sp<IMediaPlayerService> iMediaPlayerService =
+            IMediaPlayerService::asInterface(mediaPlayerService);
+    iMediaPlayer_ = iMediaPlayerService->create(mediaPlayer_);
+   }
+
+   sp<MediaPlayer> mediaPlayer_;
+   sp<IMediaPlayer> iMediaPlayer_;
+ };
+
+TEST_F(IMediaPlayerTest, PrepareDrmInvalidTransaction) {
+    Parcel data, reply;
+    data.writeInterfaceToken(iMediaPlayer_->getInterfaceDescriptor());
+    data.write(kMockByteArray, 16);
+
+    // We write a length greater than the following session id array. Should be discarded.
+    data.writeUint32(2);
+    data.writeUnpadded(kMockByteArray, 1);
+
+    status_t result = IMediaPlayer::asBinder(iMediaPlayer_)
+            ->transact(PREPARE_DRM, data, &reply);
+    ASSERT_EQ(result, BAD_VALUE);
+}
+
+TEST_F(IMediaPlayerTest, PrepareDrmValidTransaction) {
+    Parcel data, reply;
+    data.writeInterfaceToken(iMediaPlayer_->getInterfaceDescriptor());
+    data.write(kMockByteArray, 16);
+
+    // We write a length equal to the length of the following data. The transaction should be valid.
+    data.writeUint32(1);
+    data.write(kMockByteArray, 1);
+
+    status_t result = IMediaPlayer::asBinder(iMediaPlayer_)
+            ->transact(PREPARE_DRM, data, &reply);
+    ASSERT_EQ(result, OK);
+}
+}  // namespace android
diff --git a/media/libmedia/xsd/Android.bp b/media/libmedia/xsd/Android.bp
index 1635f70..36e2808 100644
--- a/media/libmedia/xsd/Android.bp
+++ b/media/libmedia/xsd/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libmedia_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libmedia_license"],
+}
+
 xsd_config {
     name: "media_profiles",
     srcs: ["media_profiles.xsd"],
diff --git a/media/libmedia/xsd/vts/Android.bp b/media/libmedia/xsd/vts/Android.bp
index 598e41b..83ab977 100644
--- a/media/libmedia/xsd/vts/Android.bp
+++ b/media/libmedia/xsd/vts/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libmedia_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libmedia_license"],
+}
+
 cc_test {
     name: "vts_mediaProfiles_validate_test",
     srcs: [
diff --git a/media/libmedia/xsd/vts/Android.mk b/media/libmedia/xsd/vts/Android.mk
deleted file mode 100644
index 52c3779..0000000
--- a/media/libmedia/xsd/vts/Android.mk
+++ /dev/null
@@ -1,22 +0,0 @@
-#
-# Copyright (C) 2019 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := VtsValidateMediaProfiles
-include test/vts/tools/build/Android.host_config.mk
diff --git a/media/libmedia/xsd/vts/AndroidTest.xml b/media/libmedia/xsd/vts/AndroidTest.xml
deleted file mode 100644
index e68721b..0000000
--- a/media/libmedia/xsd/vts/AndroidTest.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2019 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.
--->
-<configuration description="Config for VTS VtsValidateMediaProfiles.">
-    <option name="config-descriptor:metadata" key="plan" value="vts-treble" />
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.VtsFilePusher">
-        <option name="abort-on-push-failure" value="false"/>
-        <option name="push-group" value="HostDrivenTest.push"/>
-        <option name="push" value="DATA/etc/media_profiles.xsd->/data/local/tmp/media_profiles.xsd"/>
-    </target_preparer>
-    <test class="com.android.tradefed.testtype.VtsMultiDeviceTest">
-        <option name="test-module-name" value="VtsValidateMediaProfiles"/>
-        <option name="binary-test-source" value="_32bit::DATA/nativetest/vts_mediaProfiles_validate_test/vts_mediaProfiles_validate_test" />
-        <option name="binary-test-source" value="_64bit::DATA/nativetest64/vts_mediaProfiles_validate_test/vts_mediaProfiles_validate_test" />
-        <option name="binary-test-type" value="gtest"/>
-        <option name="test-timeout" value="30s"/>
-    </test>
-</configuration>
diff --git a/media/libmediahelper/Android.bp b/media/libmediahelper/Android.bp
index fbe7f87..64ec91b 100644
--- a/media/libmediahelper/Android.bp
+++ b/media/libmediahelper/Android.bp
@@ -1,8 +1,23 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libmedia_helper_headers",
     vendor_available: true,
     min_sdk_version: "29",
     export_include_dirs: ["include"],
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
 
 cc_library {
@@ -30,4 +45,10 @@
         "libmedia_helper_headers",
     ],
     clang: true,
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
diff --git a/media/libmediahelper/AudioParameter.cpp b/media/libmediahelper/AudioParameter.cpp
index fc8306c..73c1e41 100644
--- a/media/libmediahelper/AudioParameter.cpp
+++ b/media/libmediahelper/AudioParameter.cpp
@@ -57,6 +57,10 @@
 //        AUDIO_PARAMETER_DEVICE_SUP_ENCAPSULATION_MODES;
 // const char * const AudioParameter::keyDeviceSupportedEncapsulationMetadataTypes =
 //        AUDIO_PARAMETER_DEVICE_SUP_ENCAPSULATION_METADATA_TYPES;
+// const char * const AudioParameter::keyAdditionalOutputDeviceDelay =
+//        AUDIO_PARAMETER_DEVICE_ADDITIONAL_OUTPUT_DELAY;
+// const char * const AudioParameter::keyMaxAdditionalOutputDeviceDelay =
+//        AUDIO_PARAMETER_DEVICE_MAX_ADDITIONAL_OUTPUT_DELAY;
 
 AudioParameter::AudioParameter(const String8& keyValuePairs)
 {
diff --git a/media/libmediahelper/TEST_MAPPING b/media/libmediahelper/TEST_MAPPING
new file mode 100644
index 0000000..f9594bd
--- /dev/null
+++ b/media/libmediahelper/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "libmedia_helper_tests"
+    }
+  ]
+}
diff --git a/media/libmediahelper/TypeConverter.cpp b/media/libmediahelper/TypeConverter.cpp
index 6382ce4..d3a517f 100644
--- a/media/libmediahelper/TypeConverter.cpp
+++ b/media/libmediahelper/TypeConverter.cpp
@@ -18,307 +18,9 @@
 
 namespace android {
 
-#define MAKE_STRING_FROM_ENUM(string) { #string, string }
+#define MAKE_STRING_FROM_ENUM(enumval) { #enumval, enumval }
 #define TERMINATOR { .literal = nullptr }
 
-template <>
-const OutputDeviceConverter::Table OutputDeviceConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_NONE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_HDMI),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_LINE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_SPDIF),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_FM),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_IP),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_BUS),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_PROXY),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_USB_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_HEARING_AID),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_ECHO_CANCELLER),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_DEFAULT),
-    // STUB must be after DEFAULT, so the latter is picked up by toString first.
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_OUT_STUB),
-    TERMINATOR
-};
-
-template <>
-const InputDeviceConverter::Table InputDeviceConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_NONE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_COMMUNICATION),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_AMBIENT),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_HDMI),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_HDMI_ARC),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_ALL_USB),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_LINE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_SPDIF),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_IP),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_BUS),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_PROXY),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_USB_HEADSET),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_BLE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_ECHO_REFERENCE),
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_DEFAULT),
-    // STUB must be after DEFAULT, so the latter is picked up by toString first.
-    MAKE_STRING_FROM_ENUM(AUDIO_DEVICE_IN_STUB),
-    TERMINATOR
-};
-
-
-template <>
-const OutputFlagConverter::Table OutputFlagConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_NONE),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_FAST),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_TTS),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_RAW),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_SYNC),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_DIRECT_PCM),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_VOIP_RX),
-    MAKE_STRING_FROM_ENUM(AUDIO_OUTPUT_FLAG_INCALL_MUSIC),
-    TERMINATOR
-};
-
-
-template <>
-const InputFlagConverter::Table InputFlagConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_INPUT_FLAG_NONE),
-    MAKE_STRING_FROM_ENUM(AUDIO_INPUT_FLAG_FAST),
-    MAKE_STRING_FROM_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
-    MAKE_STRING_FROM_ENUM(AUDIO_INPUT_FLAG_RAW),
-    MAKE_STRING_FROM_ENUM(AUDIO_INPUT_FLAG_SYNC),
-    MAKE_STRING_FROM_ENUM(AUDIO_INPUT_FLAG_MMAP_NOIRQ),
-    MAKE_STRING_FROM_ENUM(AUDIO_INPUT_FLAG_VOIP_TX),
-    MAKE_STRING_FROM_ENUM(AUDIO_INPUT_FLAG_HW_AV_SYNC),
-    MAKE_STRING_FROM_ENUM(AUDIO_INPUT_FLAG_DIRECT),
-    TERMINATOR
-};
-
-
-template <>
-const FormatConverter::Table FormatConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_PCM_16_BIT),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_PCM_8_BIT),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_PCM_32_BIT),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_PCM_FLOAT),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_MP3),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AMR_NB),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AMR_WB),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_MAIN),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_LC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_SSR),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_LTP),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_HE_V1),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ERLC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_LD),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_HE_V2),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ELD),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_XHE),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_MAIN),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_LC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_SSR),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_LTP),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_HE_V1),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_SCALABLE),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_ERLC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_LD),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_HE_V2),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_ELD),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS_XHE),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_VORBIS),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_HE_AAC_V1),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_HE_AAC_V2),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_OPUS),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AC3),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_E_AC3),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_DTS),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_DTS_HD),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_IEC61937),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_DOLBY_TRUEHD),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_EVRC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_EVRCB),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_EVRCWB),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_EVRCNW),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADIF),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_WMA),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_WMA_PRO),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AMR_WB_PLUS),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_MP2),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_QCELP),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_DSD),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_FLAC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_ALAC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_APE),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_ADTS),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_SBC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_APTX),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_APTX_HD),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AC4),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_LDAC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_MAT),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_E_AC3_JOC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_MAT_1_0),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_MAT_2_0),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_MAT_2_1),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_LATM),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_LATM_LC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_LATM_HE_V1),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_AAC_LATM_HE_V2),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_CELT),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_APTX_ADAPTIVE),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_LHDC),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_LHDC_LL),
-    MAKE_STRING_FROM_ENUM(AUDIO_FORMAT_APTX_TWSP),
-    TERMINATOR
-};
-
-
-template <>
-const OutputChannelConverter::Table OutputChannelConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_MONO),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_STEREO),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_2POINT1),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_2POINT0POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_2POINT1POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_TRI),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_TRI_BACK),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_3POINT1),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_3POINT0POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_3POINT1POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_QUAD),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_QUAD_BACK),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_QUAD_SIDE),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_SURROUND),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_PENTA),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_5POINT1_BACK),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_5POINT1_SIDE),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_5POINT1POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_5POINT1POINT4),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_6POINT1),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_7POINT1POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_7POINT1POINT4),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_HAPTIC_A),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_MONO_HAPTIC_A),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_STEREO_HAPTIC_A),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_HAPTIC_AB),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_MONO_HAPTIC_AB),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_OUT_STEREO_HAPTIC_AB),
-    TERMINATOR
-};
-
-
-template <>
-const InputChannelConverter::Table InputChannelConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_MONO),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_STEREO),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_6),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_2POINT0POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_2POINT1POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_3POINT0POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_3POINT1POINT2),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_5POINT1),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_VOICE_UPLINK_MONO),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_VOICE_DNLINK_MONO),
-    MAKE_STRING_FROM_ENUM(AUDIO_CHANNEL_IN_VOICE_CALL_MONO),
-    TERMINATOR
-};
-
-template <>
-const ChannelIndexConverter::Table ChannelIndexConverter::mTable[] = {
-    {"AUDIO_CHANNEL_INDEX_MASK_1", static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_INDEX_MASK_1)},
-    {"AUDIO_CHANNEL_INDEX_MASK_2", static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_INDEX_MASK_2)},
-    {"AUDIO_CHANNEL_INDEX_MASK_3", static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_INDEX_MASK_3)},
-    {"AUDIO_CHANNEL_INDEX_MASK_4", static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_INDEX_MASK_4)},
-    {"AUDIO_CHANNEL_INDEX_MASK_5", static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_INDEX_MASK_5)},
-    {"AUDIO_CHANNEL_INDEX_MASK_6", static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_INDEX_MASK_6)},
-    {"AUDIO_CHANNEL_INDEX_MASK_7", static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_INDEX_MASK_7)},
-    {"AUDIO_CHANNEL_INDEX_MASK_8", static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_INDEX_MASK_8)},
-    TERMINATOR
-};
-
-
-template <>
-const GainModeConverter::Table GainModeConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_GAIN_MODE_JOINT),
-    MAKE_STRING_FROM_ENUM(AUDIO_GAIN_MODE_CHANNELS),
-    MAKE_STRING_FROM_ENUM(AUDIO_GAIN_MODE_RAMP),
-    TERMINATOR
-};
-
-
-template <>
-const StreamTypeConverter::Table StreamTypeConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_DEFAULT),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_VOICE_CALL),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_SYSTEM),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_RING),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_MUSIC),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_ALARM),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_NOTIFICATION),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_BLUETOOTH_SCO ),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_ENFORCED_AUDIBLE),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_DTMF),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_TTS),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_ACCESSIBILITY),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_ASSISTANT),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_REROUTING),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_PATCH),
-    MAKE_STRING_FROM_ENUM(AUDIO_STREAM_CALL_ASSISTANT),
-    TERMINATOR
-};
-
 template<>
 const AudioModeConverter::Table AudioModeConverter::mTable[] = {
     MAKE_STRING_FROM_ENUM(AUDIO_MODE_INVALID),
@@ -331,62 +33,6 @@
     TERMINATOR
 };
 
-template<>
-const AudioContentTypeConverter::Table AudioContentTypeConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_CONTENT_TYPE_UNKNOWN),
-    MAKE_STRING_FROM_ENUM(AUDIO_CONTENT_TYPE_SPEECH),
-    MAKE_STRING_FROM_ENUM(AUDIO_CONTENT_TYPE_MUSIC),
-    MAKE_STRING_FROM_ENUM(AUDIO_CONTENT_TYPE_MOVIE),
-    MAKE_STRING_FROM_ENUM(AUDIO_CONTENT_TYPE_SONIFICATION),
-    TERMINATOR
-};
-
-template <>
-const UsageTypeConverter::Table UsageTypeConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_UNKNOWN),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_MEDIA),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_VOICE_COMMUNICATION),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_ALARM),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_NOTIFICATION),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_NOTIFICATION_EVENT),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_ASSISTANCE_SONIFICATION),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_GAME),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_VIRTUAL_SOURCE),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_ASSISTANT),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_CALL_ASSISTANT),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_EMERGENCY),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_SAFETY),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_VEHICLE_STATUS),
-    MAKE_STRING_FROM_ENUM(AUDIO_USAGE_ANNOUNCEMENT),
-    TERMINATOR
-};
-
-template <>
-const SourceTypeConverter::Table SourceTypeConverter::mTable[] = {
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_DEFAULT),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_MIC),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_VOICE_UPLINK),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_VOICE_DOWNLINK),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_VOICE_CALL),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_CAMCORDER),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_VOICE_RECOGNITION),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_VOICE_COMMUNICATION),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_REMOTE_SUBMIX),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_UNPROCESSED),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_VOICE_PERFORMANCE),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_ECHO_REFERENCE),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_FM_TUNER),
-    MAKE_STRING_FROM_ENUM(AUDIO_SOURCE_HOTWORD),
-    TERMINATOR
-};
-
 template <>
 const AudioFlagConverter::Table AudioFlagConverter::mTable[] = {
     MAKE_STRING_FROM_ENUM(AUDIO_FLAG_NONE),
@@ -409,6 +55,7 @@
 
 template class TypeConverter<OutputDeviceTraits>;
 template class TypeConverter<InputDeviceTraits>;
+template class TypeConverter<DeviceTraits>;
 template class TypeConverter<OutputFlagTraits>;
 template class TypeConverter<InputFlagTraits>;
 template class TypeConverter<FormatTraits>;
@@ -422,11 +69,6 @@
 template class TypeConverter<SourceTraits>;
 template class TypeConverter<AudioFlagTraits>;
 
-bool deviceFromString(const std::string& literalDevice, audio_devices_t& device) {
-    return InputDeviceConverter::fromString(literalDevice, device) ||
-            OutputDeviceConverter::fromString(literalDevice, device);
-}
-
 SampleRateTraits::Collection samplingRatesFromString(
         const std::string &samplingRates, const char *del)
 {
@@ -446,21 +88,20 @@
 audio_format_t formatFromString(const std::string &literalFormat, audio_format_t defaultFormat)
 {
     audio_format_t format;
-    if (literalFormat.empty()) {
-        return defaultFormat;
+    if (!literalFormat.empty() && FormatConverter::fromString(literalFormat, format)) {
+        return format;
     }
-    FormatConverter::fromString(literalFormat, format);
-    return format;
+    return defaultFormat;
 }
 
 audio_channel_mask_t channelMaskFromString(const std::string &literalChannels)
 {
     audio_channel_mask_t channels;
-    if (!OutputChannelConverter::fromString(literalChannels, channels) &&
-            !InputChannelConverter::fromString(literalChannels, channels)) {
-        return AUDIO_CHANNEL_INVALID;
+    if (!literalChannels.empty() &&
+            audio_channel_mask_from_string(literalChannels.c_str(), &channels)) {
+        return channels;
     }
-    return channels;
+    return AUDIO_CHANNEL_INVALID;
 }
 
 ChannelTraits::Collection channelMasksFromString(
diff --git a/media/libmediahelper/include/media/AudioParameter.h b/media/libmediahelper/include/media/AudioParameter.h
index 66d8dfb..b72d0d5 100644
--- a/media/libmediahelper/include/media/AudioParameter.h
+++ b/media/libmediahelper/include/media/AudioParameter.h
@@ -104,6 +104,9 @@
     // static const char * const keyDeviceSupportedEncapsulationModes;
     // static const char * const keyDeviceSupportedEncapsulationMetadataTypes;
 
+    // static const char * const keyAdditionalOutputDeviceDelay;
+    // static const char * const keyMaxAdditionalOutputDeviceDelay;
+
     String8 toString() const { return toStringImpl(true); }
     String8 keysToString() const { return toStringImpl(false); }
 
diff --git a/media/libmediahelper/include/media/TypeConverter.h b/media/libmediahelper/include/media/TypeConverter.h
index 011498a..42ccb5f 100644
--- a/media/libmediahelper/include/media/TypeConverter.h
+++ b/media/libmediahelper/include/media/TypeConverter.h
@@ -24,8 +24,6 @@
 
 #include <system/audio.h>
 #include <utils/Log.h>
-#include <utils/Vector.h>
-#include <utils/SortedVector.h>
 
 #include <media/AudioParameter.h>
 #include "convert.h"
@@ -43,16 +41,6 @@
     }
 };
 template <typename T>
-struct SortedVectorTraits
-{
-    typedef T Type;
-    typedef SortedVector<Type> Collection;
-    static void add(Collection &collection, Type value)
-    {
-        collection.add(value);
-    }
-};
-template <typename T>
 struct SetTraits
 {
     typedef T Type;
@@ -108,13 +96,20 @@
                                      typename Traits::Collection &collection,
                                      const char *del = AudioParameter::valueListSeparator);
 
-    static uint32_t maskFromString(
+    static typename Traits::Type maskFromString(
             const std::string &str, const char *del = AudioParameter::valueListSeparator);
 
     static void maskToString(
-            uint32_t mask, std::string &str, const char *del = AudioParameter::valueListSeparator);
+            typename Traits::Type mask, std::string &str,
+            const char *del = AudioParameter::valueListSeparator);
 
 protected:
+    // Default implementations use mTable for to/from string conversions
+    // of each individual enum value.
+    // These functions may be specialized to use external converters instead.
+    static bool toStringImpl(const typename Traits::Type &value, std::string &str);
+    static bool fromStringImpl(const std::string &str, typename Traits::Type &result);
+
     struct Table {
         const char *literal;
         typename Traits::Type value;
@@ -124,26 +119,22 @@
 };
 
 template <class Traits>
-inline bool TypeConverter<Traits>::toString(const typename Traits::Type &value, std::string &str)
-{
+inline bool TypeConverter<Traits>::toStringImpl(
+        const typename Traits::Type &value, std::string &str) {
     for (size_t i = 0; mTable[i].literal; i++) {
         if (mTable[i].value == value) {
             str = mTable[i].literal;
             return true;
         }
     }
-    char result[64];
-    snprintf(result, sizeof(result), "Unknown enum value %d", value);
-    str = result;
     return false;
 }
 
 template <class Traits>
-inline bool TypeConverter<Traits>::fromString(const std::string &str, typename Traits::Type &result)
-{
+inline bool TypeConverter<Traits>::fromStringImpl(
+        const std::string &str, typename Traits::Type &result) {
     for (size_t i = 0; mTable[i].literal; i++) {
         if (strcmp(mTable[i].literal, str.c_str()) == 0) {
-            ALOGV("stringToEnum() found %s", mTable[i].literal);
             result = mTable[i].value;
             return true;
         }
@@ -152,6 +143,26 @@
 }
 
 template <class Traits>
+inline bool TypeConverter<Traits>::toString(const typename Traits::Type &value, std::string &str)
+{
+    const bool success = toStringImpl(value, str);
+    if (!success) {
+        char result[64];
+        snprintf(result, sizeof(result), "Unknown enum value %d", value);
+        str = result;
+    }
+    return success;
+}
+
+template <class Traits>
+inline bool TypeConverter<Traits>::fromString(const std::string &str, typename Traits::Type &result)
+{
+    const bool success = fromStringImpl(str, result);
+    ALOGV_IF(success, "stringToEnum() found %s", str.c_str());
+    return success;
+}
+
+template <class Traits>
 inline void TypeConverter<Traits>::collectionFromString(const std::string &str,
         typename Traits::Collection &collection,
         const char *del)
@@ -168,7 +179,8 @@
 }
 
 template <class Traits>
-inline uint32_t TypeConverter<Traits>::maskFromString(const std::string &str, const char *del)
+inline typename Traits::Type TypeConverter<Traits>::maskFromString(
+        const std::string &str, const char *del)
 {
     char *literal = strdup(str.c_str());
     uint32_t value = 0;
@@ -179,20 +191,24 @@
         }
     }
     free(literal);
-    return value;
+    return static_cast<typename Traits::Type>(value);
 }
 
 template <class Traits>
-inline void TypeConverter<Traits>::maskToString(uint32_t mask, std::string &str, const char *del)
+inline void TypeConverter<Traits>::maskToString(
+        typename Traits::Type mask, std::string &str, const char *del)
 {
     if (mask != 0) {
         bool first_flag = true;
-        for (size_t i = 0; mTable[i].literal; i++) {
-            uint32_t value = static_cast<uint32_t>(mTable[i].value);
-            if (mTable[i].value != 0 && ((mask & value) == value)) {
-                if (!first_flag) str += del;
-                first_flag = false;
-                str += mTable[i].literal;
+        for (size_t bit = 0; bit < sizeof(uint32_t) * 8; ++bit) {
+            uint32_t flag = 1u << bit;
+            if ((flag & mask) == flag) {
+                std::string flag_str;
+                if (toString(static_cast<typename Traits::Type>(flag), flag_str)) {
+                    if (!first_flag) str += del;
+                    first_flag = false;
+                    str += flag_str;
+                }
             }
         }
     } else {
@@ -200,6 +216,7 @@
     }
 }
 
+typedef TypeConverter<DeviceTraits> DeviceConverter;
 typedef TypeConverter<OutputDeviceTraits> OutputDeviceConverter;
 typedef TypeConverter<InputDeviceTraits> InputDeviceConverter;
 typedef TypeConverter<OutputFlagTraits> OutputFlagConverter;
@@ -216,23 +233,227 @@
 typedef TypeConverter<SourceTraits> SourceTypeConverter;
 typedef TypeConverter<AudioFlagTraits> AudioFlagConverter;
 
-template<> const OutputDeviceConverter::Table OutputDeviceConverter::mTable[];
-template<> const InputDeviceConverter::Table InputDeviceConverter::mTable[];
-template<> const OutputFlagConverter::Table OutputFlagConverter::mTable[];
-template<> const InputFlagConverter::Table InputFlagConverter::mTable[];
-template<> const FormatConverter::Table FormatConverter::mTable[];
-template<> const OutputChannelConverter::Table OutputChannelConverter::mTable[];
-template<> const InputChannelConverter::Table InputChannelConverter::mTable[];
-template<> const ChannelIndexConverter::Table ChannelIndexConverter::mTable[];
-template<> const GainModeConverter::Table GainModeConverter::mTable[];
-template<> const StreamTypeConverter::Table StreamTypeConverter::mTable[];
 template<> const AudioModeConverter::Table AudioModeConverter::mTable[];
-template<> const AudioContentTypeConverter::Table AudioContentTypeConverter::mTable[];
-template<> const UsageTypeConverter::Table UsageTypeConverter::mTable[];
-template<> const SourceTypeConverter::Table SourceTypeConverter::mTable[];
 template<> const AudioFlagConverter::Table AudioFlagConverter::mTable[];
 
-bool deviceFromString(const std::string& literalDevice, audio_devices_t& device);
+template <>
+inline bool TypeConverter<DeviceTraits>::toStringImpl(
+        const DeviceTraits::Type &value, std::string &str) {
+    str = audio_device_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<DeviceTraits>::fromStringImpl(
+        const std::string &str, DeviceTraits::Type &result) {
+    return audio_device_from_string(str.c_str(), &result);
+}
+
+template <>
+inline bool TypeConverter<OutputDeviceTraits>::toStringImpl(
+        const OutputDeviceTraits::Type &value, std::string &str) {
+    if (audio_is_output_device(value)) {
+        str = audio_device_to_string(value);
+        return !str.empty();
+    }
+    return false;
+}
+
+template <>
+inline bool TypeConverter<OutputDeviceTraits>::fromStringImpl(
+        const std::string &str, OutputDeviceTraits::Type &result) {
+    OutputDeviceTraits::Type temp;
+    if (audio_device_from_string(str.c_str(), &temp) &&
+            audio_is_output_device(temp)) {
+        result = temp;
+        return true;
+    }
+    return false;
+}
+
+template <>
+inline bool TypeConverter<InputDeviceTraits>::toStringImpl(
+        const InputDeviceTraits::Type &value, std::string &str) {
+    if (audio_is_input_device(value)) {
+        str = audio_device_to_string(value);
+        return !str.empty();
+    }
+    return false;
+}
+
+template <>
+inline bool TypeConverter<InputDeviceTraits>::fromStringImpl(
+        const std::string &str, InputDeviceTraits::Type &result) {
+    InputDeviceTraits::Type temp;
+    if (audio_device_from_string(str.c_str(), &temp) &&
+            audio_is_input_device(temp)) {
+        result = temp;
+        return true;
+    }
+    return false;
+}
+
+template <>
+inline bool TypeConverter<InputFlagTraits>::toStringImpl(
+        const audio_input_flags_t &value, std::string &str) {
+    str = audio_input_flag_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<InputFlagTraits>::fromStringImpl(
+        const std::string &str, audio_input_flags_t &result) {
+    return audio_input_flag_from_string(str.c_str(), &result);
+}
+
+template <>
+inline bool TypeConverter<OutputFlagTraits>::toStringImpl(
+        const audio_output_flags_t &value, std::string &str) {
+    str = audio_output_flag_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<OutputFlagTraits>::fromStringImpl(
+        const std::string &str, audio_output_flags_t &result) {
+    return audio_output_flag_from_string(str.c_str(), &result);
+}
+
+template <>
+inline bool TypeConverter<FormatTraits>::toStringImpl(
+        const audio_format_t &value, std::string &str) {
+    str = audio_format_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<FormatTraits>::fromStringImpl(
+        const std::string &str, audio_format_t &result) {
+    return audio_format_from_string(str.c_str(), &result);
+}
+
+template <>
+inline bool TypeConverter<OutputChannelTraits>::toStringImpl(
+        const audio_channel_mask_t &value, std::string &str) {
+    str = audio_channel_out_mask_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<OutputChannelTraits>::fromStringImpl(
+        const std::string &str, audio_channel_mask_t &result) {
+    OutputChannelTraits::Type temp;
+    if (audio_channel_mask_from_string(str.c_str(), &temp) &&
+            audio_is_output_channel(temp)) {
+        result = temp;
+        return true;
+    }
+    return false;
+}
+
+template <>
+inline bool TypeConverter<InputChannelTraits>::toStringImpl(
+        const audio_channel_mask_t &value, std::string &str) {
+    str = audio_channel_in_mask_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<InputChannelTraits>::fromStringImpl(
+        const std::string &str, audio_channel_mask_t &result) {
+    InputChannelTraits::Type temp;
+    if (audio_channel_mask_from_string(str.c_str(), &temp) &&
+            audio_is_input_channel(temp)) {
+        result = temp;
+        return true;
+    }
+    return false;
+}
+
+template <>
+inline bool TypeConverter<ChannelIndexTraits>::toStringImpl(
+        const audio_channel_mask_t &value, std::string &str) {
+    str = audio_channel_index_mask_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<ChannelIndexTraits>::fromStringImpl(
+        const std::string &str, audio_channel_mask_t &result) {
+    ChannelIndexTraits::Type temp;
+    if (audio_channel_mask_from_string(str.c_str(), &temp) &&
+            audio_channel_mask_get_representation(temp) == AUDIO_CHANNEL_REPRESENTATION_INDEX) {
+        result = temp;
+        return true;
+    }
+    return false;
+}
+
+template <>
+inline bool TypeConverter<StreamTraits>::toStringImpl(
+        const audio_stream_type_t &value, std::string &str) {
+    str = audio_stream_type_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<StreamTraits>::fromStringImpl(
+        const std::string &str, audio_stream_type_t &result)
+{
+    return audio_stream_type_from_string(str.c_str(), &result);
+}
+
+template <>
+inline bool TypeConverter<GainModeTraits>::toStringImpl(
+        const audio_gain_mode_t &value, std::string &str) {
+    str = audio_gain_mode_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<GainModeTraits>::fromStringImpl(
+        const std::string &str, audio_gain_mode_t &result) {
+    return audio_gain_mode_from_string(str.c_str(), &result);
+}
+
+template <>
+inline bool TypeConverter<AudioContentTraits>::toStringImpl(
+        const audio_content_type_t &value, std::string &str) {
+    str = audio_content_type_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<AudioContentTraits>::fromStringImpl(
+        const std::string &str, audio_content_type_t &result) {
+    return audio_content_type_from_string(str.c_str(), &result);
+}
+
+template <>
+inline bool TypeConverter<UsageTraits>::toStringImpl(const audio_usage_t &value, std::string &str)
+{
+    str = audio_usage_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<UsageTraits>::fromStringImpl(
+        const std::string &str, audio_usage_t &result) {
+    return audio_usage_from_string(str.c_str(), &result);
+}
+
+template <>
+inline bool TypeConverter<SourceTraits>::toStringImpl(const audio_source_t &value, std::string &str)
+{
+    str = audio_source_to_string(value);
+    return !str.empty();
+}
+
+template <>
+inline bool TypeConverter<SourceTraits>::fromStringImpl(
+        const std::string &str, audio_source_t &result) {
+    return audio_source_from_string(str.c_str(), &result);
+}
 
 SampleRateTraits::Collection samplingRatesFromString(
         const std::string &samplingRates, const char *del = AudioParameter::valueListSeparator);
@@ -256,6 +477,7 @@
 
 // counting enumerations
 template <typename T, std::enable_if_t<std::is_same<T, audio_content_type_t>::value
+                                    || std::is_same<T, audio_devices_t>::value
                                     || std::is_same<T, audio_mode_t>::value
                                     || std::is_same<T, audio_source_t>::value
                                     || std::is_same<T, audio_stream_type_t>::value
@@ -282,17 +504,6 @@
     return result;
 }
 
-static inline std::string toString(const audio_devices_t& devices)
-{
-    std::string result;
-    if ((devices & AUDIO_DEVICE_BIT_IN) != 0) {
-        InputDeviceConverter::maskToString(devices, result);
-    } else {
-        OutputDeviceConverter::maskToString(devices, result);
-    }
-    return result;
-}
-
 static inline std::string toString(const audio_attributes_t& attributes)
 {
     std::ostringstream result;
diff --git a/media/libmediahelper/tests/Android.bp b/media/libmediahelper/tests/Android.bp
new file mode 100644
index 0000000..a5f2819
--- /dev/null
+++ b/media/libmediahelper/tests/Android.bp
@@ -0,0 +1,31 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_test {
+    name: "libmedia_helper_tests",
+
+    generated_headers: ["audio_policy_configuration_V7_0"],
+    generated_sources: ["audio_policy_configuration_V7_0"],
+    header_libs: ["libxsdc-utils"],
+    shared_libs: [
+        "libbase",
+        "liblog",
+        "libmedia_helper",
+        "libxml2",
+    ],
+
+    srcs: ["typeconverter_tests.cpp"],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+
+    test_suites: ["device-tests"],
+}
diff --git a/media/libmediahelper/tests/typeconverter_tests.cpp b/media/libmediahelper/tests/typeconverter_tests.cpp
new file mode 100644
index 0000000..181d636
--- /dev/null
+++ b/media/libmediahelper/tests/typeconverter_tests.cpp
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2020 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>
+
+#define LOG_TAG "TypeConverter_Test"
+#include <log/log.h>
+
+#include <android_audio_policy_configuration_V7_0.h>
+#include <media/TypeConverter.h>
+#include <system/audio.h>
+#include <xsdc/XsdcSupport.h>
+
+using namespace android;
+namespace xsd {
+using namespace android::audio::policy::configuration::V7_0;
+}
+
+TEST(TypeConverter, ParseChannelMasks) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioChannelMask>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_channel_mask_t channelMask = channelMaskFromString(stringVal);
+        EXPECT_EQ(enumVal != xsd::AudioChannelMask::AUDIO_CHANNEL_NONE,
+                audio_channel_mask_is_valid(channelMask))
+                << "Validity of \"" << stringVal << "\" is not as expected";
+    }
+}
+
+TEST(TypeConverter, ParseInputOutputIndexChannelMask) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioChannelMask>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_channel_mask_t channelMask, channelMaskBack;
+        std::string stringValBack;
+        if (stringVal.find("_CHANNEL_IN_") != std::string::npos) {
+            EXPECT_TRUE(InputChannelConverter::fromString(stringVal, channelMask))
+                    << "Conversion of \"" << stringVal << "\" failed (as input channel mask)";
+            EXPECT_TRUE(InputChannelConverter::toString(channelMask, stringValBack))
+                    << "Conversion of input channel mask " << channelMask << " failed";
+            // Due to aliased values, the result of 'toString' might not be the same
+            // as 'stringVal', thus we need to compare the results of parsing instead.
+            EXPECT_TRUE(InputChannelConverter::fromString(stringValBack, channelMaskBack))
+                    << "Conversion of \"" << stringValBack << "\" failed (as input channel mask)";
+            EXPECT_EQ(channelMask, channelMaskBack);
+        } else if (stringVal.find("_CHANNEL_OUT_") != std::string::npos) {
+            EXPECT_TRUE(OutputChannelConverter::fromString(stringVal, channelMask))
+                    << "Conversion of \"" << stringVal << "\" failed (as output channel mask)";
+            EXPECT_TRUE(OutputChannelConverter::toString(channelMask, stringValBack))
+                    << "Conversion of output channel mask " << channelMask << " failed";
+            EXPECT_TRUE(OutputChannelConverter::fromString(stringValBack, channelMaskBack))
+                    << "Conversion of \"" << stringValBack << "\" failed (as output channel mask)";
+            EXPECT_EQ(channelMask, channelMaskBack);
+        } else if (stringVal.find("_CHANNEL_INDEX_") != std::string::npos) {
+            EXPECT_TRUE(ChannelIndexConverter::fromString(stringVal, channelMask))
+                    << "Conversion of \"" << stringVal << "\" failed (as indexed channel mask)";
+            EXPECT_TRUE(ChannelIndexConverter::toString(channelMask, stringValBack))
+                    << "Conversion of indexed channel mask " << channelMask << " failed";
+            EXPECT_EQ(stringVal, stringValBack);
+        } else if (stringVal == toString(xsd::AudioChannelMask::AUDIO_CHANNEL_NONE)) {
+            EXPECT_FALSE(InputChannelConverter::fromString(stringVal, channelMask))
+                    << "Conversion of \"" << stringVal << "\" succeeded (as input channel mask)";
+            EXPECT_FALSE(OutputChannelConverter::fromString(stringVal, channelMask))
+                    << "Conversion of \"" << stringVal << "\" succeeded (as output channel mask)";
+            EXPECT_FALSE(ChannelIndexConverter::fromString(stringVal, channelMask))
+                    << "Conversion of \"" << stringVal << "\" succeeded (as index channel mask)";
+            // None of Converters could parse this because 'NONE' isn't a 'valid' channel mask.
+            channelMask = AUDIO_CHANNEL_NONE;
+            // However they all must succeed in converting it back.
+            EXPECT_TRUE(InputChannelConverter::toString(channelMask, stringValBack))
+                    << "Conversion of input channel mask " << channelMask << " failed";
+            EXPECT_EQ(stringVal, stringValBack);
+            EXPECT_TRUE(OutputChannelConverter::toString(channelMask, stringValBack))
+                    << "Conversion of output channel mask " << channelMask << " failed";
+            EXPECT_EQ(stringVal, stringValBack);
+            EXPECT_TRUE(ChannelIndexConverter::toString(channelMask, stringValBack))
+                    << "Conversion of indexed channel mask " << channelMask << " failed";
+            EXPECT_EQ(stringVal, stringValBack);
+        } else {
+            FAIL() << "Unrecognized channel mask \"" << stringVal << "\"";
+        }
+    }
+}
+
+TEST(TypeConverter, ParseContentTypes) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioContentType>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_content_type_t contentType;
+        EXPECT_TRUE(AudioContentTypeConverter::fromString(stringVal, contentType))
+                << "Conversion of \"" << stringVal << "\" failed";
+        EXPECT_EQ(stringVal, toString(contentType));
+    }
+}
+
+TEST(TypeConverter, ParseDevices) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioDevice>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_devices_t device, deviceBack;
+        std::string stringValBack;
+        EXPECT_TRUE(DeviceConverter::fromString(stringVal, device))
+                << "Conversion of \"" << stringVal << "\" failed";
+        if (enumVal != xsd::AudioDevice::AUDIO_DEVICE_NONE) {
+            EXPECT_TRUE(audio_is_input_device(device) || audio_is_output_device(device))
+                    << "Device \"" << stringVal << "\" is neither input, nor output device";
+        } else {
+            EXPECT_FALSE(audio_is_input_device(device));
+            EXPECT_FALSE(audio_is_output_device(device));
+        }
+        // Due to aliased values, the result of 'toString' might not be the same
+        // as 'stringVal', thus we need to compare the results of parsing instead.
+        stringValBack = toString(device);
+        EXPECT_TRUE(DeviceConverter::fromString(stringValBack, deviceBack))
+                << "Conversion of \"" << stringValBack << "\" failed";
+        EXPECT_EQ(device, deviceBack);
+    }
+}
+
+TEST(TypeConverter, ParseInOutDevices) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioDevice>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_devices_t device, deviceBack;
+        std::string stringValBack;
+        if (stringVal.find("_DEVICE_IN_") != std::string::npos) {
+            EXPECT_TRUE(InputDeviceConverter::fromString(stringVal, device))
+                    << "Conversion of \"" << stringVal << "\" failed (as input device)";
+            // Due to aliased values, the result of 'toString' might not be the same
+            // as 'stringVal', thus we need to compare the results of parsing instead.
+            stringValBack = toString(device);
+            EXPECT_TRUE(InputDeviceConverter::fromString(stringValBack, deviceBack))
+                    << "Conversion of \"" << stringValBack << "\" failed";
+            EXPECT_EQ(device, deviceBack);
+        } else if (stringVal.find("_DEVICE_OUT_") != std::string::npos) {
+            EXPECT_TRUE(OutputDeviceConverter::fromString(stringVal, device))
+                    << "Conversion of \"" << stringVal << "\" failed (as output device)";
+            stringValBack = toString(device);
+            EXPECT_TRUE(OutputDeviceConverter::fromString(stringValBack, deviceBack))
+                    << "Conversion of \"" << stringValBack << "\" failed";
+            EXPECT_EQ(device, deviceBack);
+        } else if (stringVal == toString(xsd::AudioDevice::AUDIO_DEVICE_NONE)) {
+            EXPECT_FALSE(InputDeviceConverter::fromString(stringVal, device))
+                    << "Conversion of \"" << stringVal << "\" succeeded (as input device)";
+            EXPECT_FALSE(OutputDeviceConverter::fromString(stringVal, device))
+                    << "Conversion of \"" << stringVal << "\" succeeded (as output device)";
+            EXPECT_EQ(stringVal, toString(device));
+        } else {
+            FAIL() << "Unrecognized audio device \"" << stringVal << "\"";
+        }
+    }
+}
+
+TEST(TypeConverter, ParseInOutFlags) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioInOutFlag>{}) {
+        const std::string stringVal = toString(enumVal);
+        if (stringVal.find("_INPUT_FLAG_") != std::string::npos) {
+            audio_input_flags_t flag;
+            EXPECT_TRUE(InputFlagConverter::fromString(stringVal, flag))
+                    << "Conversion of \"" << stringVal << "\" failed (as input flag)";
+            EXPECT_EQ(stringVal, toString(flag));
+        } else {
+            audio_output_flags_t flag;
+            EXPECT_TRUE(OutputFlagConverter::fromString(stringVal, flag))
+                    << "Conversion of \"" << stringVal << "\" failed (as output flag)";
+            EXPECT_EQ(stringVal, toString(flag));
+        }
+    }
+}
+
+TEST(TypeConverter, ParseFormats) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioFormat>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_format_t format;
+        EXPECT_TRUE(FormatConverter::fromString(stringVal, format))
+                << "Conversion of \"" << stringVal << "\" failed";
+        EXPECT_EQ(enumVal != xsd::AudioFormat::AUDIO_FORMAT_DEFAULT,
+                audio_is_valid_format(format))
+                << "Validity of \"" << stringVal << "\" is not as expected";
+        EXPECT_EQ(stringVal, toString(format));
+    }
+}
+
+TEST(TypeConverter, ParseGainModes) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioGainMode>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_gain_mode_t gainMode;
+        EXPECT_TRUE(GainModeConverter::fromString(stringVal, gainMode))
+                << "Conversion of \"" << stringVal << "\" failed";
+        EXPECT_EQ(stringVal, toString(gainMode));
+    }
+}
+
+TEST(TypeConverter, ParseSources) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioSource>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_source_t source;
+        EXPECT_TRUE(SourceTypeConverter::fromString(stringVal, source))
+                << "Conversion of \"" << stringVal << "\" failed";
+        EXPECT_EQ(source != AUDIO_SOURCE_DEFAULT, audio_is_valid_audio_source(source))
+                << "Validity of \"" << stringVal << "\" is not as expected";
+        EXPECT_EQ(stringVal, toString(source));
+    }
+}
+
+TEST(TypeConverter, ParseStreamTypes) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioStreamType>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_stream_type_t streamType;
+        EXPECT_TRUE(StreamTypeConverter::fromString(stringVal, streamType))
+                << "Conversion of \"" << stringVal << "\" failed";
+        EXPECT_EQ(stringVal, toString(streamType));
+    }
+}
+
+TEST(TypeConverter, ParseUsages) {
+    for (const auto enumVal : xsdc_enum_range<xsd::AudioUsage>{}) {
+        const std::string stringVal = toString(enumVal);
+        audio_usage_t usage;
+        EXPECT_TRUE(UsageTypeConverter::fromString(stringVal, usage))
+                << "Conversion of \"" << stringVal << "\" failed";
+        EXPECT_EQ(stringVal, toString(usage));
+    }
+}
diff --git a/media/libmediametrics/Android.bp b/media/libmediametrics/Android.bp
index a63b8b4..3843e70 100644
--- a/media/libmediametrics/Android.bp
+++ b/media/libmediametrics/Android.bp
@@ -1,9 +1,18 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libmediametrics_headers",
     export_include_dirs: ["include"],
 }
 
-cc_library_shared {
+cc_library {
     name: "libmediametrics",
 
     srcs: [
diff --git a/media/libmediaplayerservice/Android.bp b/media/libmediaplayerservice/Android.bp
index 5301f5c..9ab117a 100644
--- a/media/libmediaplayerservice/Android.bp
+++ b/media/libmediaplayerservice/Android.bp
@@ -1,4 +1,23 @@
-cc_library_shared {
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libmediaplayerservice_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libmediaplayerservice_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_library {
 
     srcs: [
         "ActivityManager.cpp",
@@ -16,6 +35,7 @@
         "android.hardware.media.c2@1.0",
         "android.hardware.media.omx@1.0",
         "libbase",
+        "libandroid_net",
         "libaudioclient",
         "libbinder",
         "libcamera_client",
@@ -76,4 +96,3 @@
     },
 
 }
-
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index 016f622..4d90d98 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -1063,6 +1063,17 @@
     return mStatus = setDataSource_post(p, p->setDataSource(dataSource));
 }
 
+status_t MediaPlayerService::Client::setDataSource(
+        const String8& rtpParams) {
+    player_type playerType = NU_PLAYER;
+    sp<MediaPlayerBase> p = setDataSource_pre(playerType);
+    if (p == NULL) {
+        return NO_INIT;
+    }
+    // now set data source
+    return mStatus = setDataSource_post(p, p->setDataSource(rtpParams));
+}
+
 void MediaPlayerService::Client::disconnectNativeWindow_l() {
     if (mConnectedWindow != NULL) {
         status_t err = nativeWindowDisconnect(
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index a7de3f3..b2f1b9b 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -372,6 +372,7 @@
 
         virtual status_t        setDataSource(const sp<IStreamSource> &source);
         virtual status_t        setDataSource(const sp<IDataSource> &source);
+        virtual status_t        setDataSource(const String8& rtpParams);
 
 
         sp<MediaPlayerBase>     setDataSource_pre(player_type playerType);
diff --git a/media/libmediaplayerservice/MediaRecorderClient.cpp b/media/libmediaplayerservice/MediaRecorderClient.cpp
index 1cc255d..9f16a22 100644
--- a/media/libmediaplayerservice/MediaRecorderClient.cpp
+++ b/media/libmediaplayerservice/MediaRecorderClient.cpp
@@ -591,4 +591,13 @@
     }
     return NO_INIT;
 }
+
+status_t MediaRecorderClient::getRtpDataUsage(uint64_t *bytes) {
+    ALOGV("getRtpDataUsage");
+    Mutex::Autolock lock(mLock);
+    if (mRecorder != NULL) {
+        return mRecorder->getRtpDataUsage(bytes);
+    }
+    return NO_INIT;
+}
 }; // namespace android
diff --git a/media/libmediaplayerservice/MediaRecorderClient.h b/media/libmediaplayerservice/MediaRecorderClient.h
index 12257e5..e041855 100644
--- a/media/libmediaplayerservice/MediaRecorderClient.h
+++ b/media/libmediaplayerservice/MediaRecorderClient.h
@@ -86,6 +86,7 @@
     virtual     status_t   setPreferredMicrophoneDirection(audio_microphone_direction_t direction);
     virtual     status_t   setPreferredMicrophoneFieldDimension(float zoom);
                 status_t   getPortId(audio_port_handle_t *portId) override;
+    virtual     status_t   getRtpDataUsage(uint64_t *bytes);
 
 private:
     friend class           MediaPlayerService;  // for accessing private constructor
diff --git a/media/libmediaplayerservice/StagefrightRecorder.cpp b/media/libmediaplayerservice/StagefrightRecorder.cpp
index 7897959..ecbdf61 100644
--- a/media/libmediaplayerservice/StagefrightRecorder.cpp
+++ b/media/libmediaplayerservice/StagefrightRecorder.cpp
@@ -17,6 +17,9 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "StagefrightRecorder"
 #include <inttypes.h>
+// TODO/workaround: including base logging now as it conflicts with ADebug.h
+// and it must be included first.
+#include <android-base/logging.h>
 #include <utils/Log.h>
 
 #include "WebmWriter.h"
@@ -44,6 +47,7 @@
 #include <media/stagefright/CameraSourceTimeLapse.h>
 #include <media/stagefright/MPEG2TSWriter.h>
 #include <media/stagefright/MPEG4Writer.h>
+#include <media/stagefright/MediaCodecConstants.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/MediaCodecSource.h>
@@ -117,6 +121,11 @@
       mAudioSource((audio_source_t)AUDIO_SOURCE_CNT), // initialize with invalid value
       mPrivacySensitive(PRIVACY_SENSITIVE_DEFAULT),
       mVideoSource(VIDEO_SOURCE_LIST_END),
+      mRTPCVOExtMap(-1),
+      mRTPCVODegrees(0),
+      mRTPSockDscp(0),
+      mRTPSockNetwork(0),
+      mLastSeqNo(0),
       mStarted(false),
       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
       mDeviceCallbackEnabled(false),
@@ -125,6 +134,7 @@
 
     ALOGV("Constructor");
 
+    mMetricsItem = NULL;
     mAnalyticsDirty = false;
     reset();
 }
@@ -199,10 +209,12 @@
 void StagefrightRecorder::flushAndResetMetrics(bool reinitialize) {
     ALOGV("flushAndResetMetrics");
     // flush anything we have, maybe setup a new record
-    if (mAnalyticsDirty && mMetricsItem != NULL) {
-        updateMetrics();
-        if (mMetricsItem->count() > 0) {
-            mMetricsItem->selfrecord();
+    if (mMetricsItem != NULL) {
+        if (mAnalyticsDirty) {
+            updateMetrics();
+            if (mMetricsItem->count() > 0) {
+                mMetricsItem->selfrecord();
+            }
         }
         delete mMetricsItem;
         mMetricsItem = NULL;
@@ -567,6 +579,32 @@
     // range that a specific encoder supports. The mismatch between the
     // the target and requested bit rate will NOT be treated as an error.
     mVideoBitRate = bitRate;
+
+    // A new bitrate(TMMBR) should be applied on runtime as well if OutputFormat is RTP_AVP
+    if (mOutputFormat == OUTPUT_FORMAT_RTP_AVP) {
+        // Regular I frames may overload the network so we reduce the bitrate to allow
+        // margins for the I frame overruns.
+        // Still send requested bitrate (TMMBR) in the reply (TMMBN).
+        const float coefficient = 0.8f;
+        mVideoBitRate = (bitRate * coefficient) / 1000 * 1000;
+    }
+    if (mOutputFormat == OUTPUT_FORMAT_RTP_AVP && mStarted && mPauseStartTimeUs == 0) {
+        mVideoEncoderSource->setEncodingBitrate(mVideoBitRate);
+        ARTPWriter* rtpWriter  = static_cast<ARTPWriter*>(mWriter.get());
+        rtpWriter->setTMMBNInfo(mOpponentID, bitRate);
+    }
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setParamVideoBitRateMode(int32_t bitRateMode) {
+    ALOGV("setParamVideoBitRateMode: %d", bitRateMode);
+    // TODO: clarify what bitrate mode of -1 is as these start from 0
+    if (bitRateMode < -1) {
+        ALOGE("Unsupported video bitrate mode: %d", bitRateMode);
+        return BAD_VALUE;
+    }
+    mVideoBitRateMode = bitRateMode;
     return OK;
 }
 
@@ -776,6 +814,105 @@
     return OK;
 }
 
+status_t StagefrightRecorder::setParamRtpLocalIp(const String8 &localIp) {
+    ALOGV("setParamVideoLocalIp: %s", localIp.string());
+
+    mLocalIp.setTo(localIp.string());
+    return OK;
+}
+
+status_t StagefrightRecorder::setParamRtpLocalPort(int32_t localPort) {
+    ALOGV("setParamVideoLocalPort: %d", localPort);
+
+    mLocalPort = localPort;
+    return OK;
+}
+
+status_t StagefrightRecorder::setParamRtpRemoteIp(const String8 &remoteIp) {
+    ALOGV("setParamVideoRemoteIp: %s", remoteIp.string());
+
+    mRemoteIp.setTo(remoteIp.string());
+    return OK;
+}
+
+status_t StagefrightRecorder::setParamRtpRemotePort(int32_t remotePort) {
+    ALOGV("setParamVideoRemotePort: %d", remotePort);
+
+    mRemotePort = remotePort;
+    return OK;
+}
+
+status_t StagefrightRecorder::setParamSelfID(int32_t selfID) {
+    ALOGV("setParamSelfID: %x", selfID);
+
+    mSelfID = selfID;
+    return OK;
+}
+
+status_t StagefrightRecorder::setParamVideoOpponentID(int32_t opponentID) {
+    mOpponentID = opponentID;
+    return OK;
+}
+
+status_t StagefrightRecorder::setParamPayloadType(int32_t payloadType) {
+    ALOGV("setParamPayloadType: %d", payloadType);
+
+    mPayloadType = payloadType;
+
+    if (mStarted && mOutputFormat == OUTPUT_FORMAT_RTP_AVP) {
+        mWriter->updatePayloadType(mPayloadType);
+    }
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setRTPCVOExtMap(int32_t extmap) {
+    ALOGV("setRtpCvoExtMap: %d", extmap);
+
+    mRTPCVOExtMap = extmap;
+    return OK;
+}
+
+status_t StagefrightRecorder::setRTPCVODegrees(int32_t cvoDegrees) {
+    Mutex::Autolock autolock(mLock);
+    ALOGV("setRtpCvoDegrees: %d", cvoDegrees);
+
+    mRTPCVODegrees = cvoDegrees;
+
+    if (mStarted && mOutputFormat == OUTPUT_FORMAT_RTP_AVP) {
+        mWriter->updateCVODegrees(mRTPCVODegrees);
+    }
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setParamRtpDscp(int32_t dscp) {
+    ALOGV("setParamRtpDscp: %d", dscp);
+
+    mRTPSockDscp = dscp;
+    return OK;
+}
+
+status_t StagefrightRecorder::setSocketNetwork(int64_t networkHandle) {
+    ALOGV("setSocketNetwork: %llu", (unsigned long long) networkHandle);
+
+    mRTPSockNetwork = networkHandle;
+    if (mStarted && mOutputFormat == OUTPUT_FORMAT_RTP_AVP) {
+        mWriter->updateSocketNetwork(mRTPSockNetwork);
+    }
+    return OK;
+}
+
+status_t StagefrightRecorder::requestIDRFrame() {
+    status_t ret = BAD_VALUE;
+    if (mVideoEncoderSource != NULL) {
+        ret = mVideoEncoderSource->requestIDRFrame();
+    } else {
+        ALOGV("requestIDRFrame: Encoder not ready");
+    }
+    return ret;
+}
+
 status_t StagefrightRecorder::setParameter(
         const String8 &key, const String8 &value) {
     ALOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
@@ -844,6 +981,11 @@
         if (safe_strtoi32(value.string(), &video_bitrate)) {
             return setParamVideoEncodingBitRate(video_bitrate);
         }
+    } else if (key == "video-param-bitrate-mode") {
+        int32_t video_bitrate_mode;
+        if (safe_strtoi32(value.string(), &video_bitrate_mode)) {
+            return setParamVideoBitRateMode(video_bitrate_mode);
+        }
     } else if (key == "video-param-rotation-angle-degrees") {
         int32_t degrees;
         if (safe_strtoi32(value.string(), &degrees)) {
@@ -884,6 +1026,61 @@
         if (safe_strtod(value.string(), &fps)) {
             return setParamCaptureFps(fps);
         }
+    } else if (key == "rtp-param-local-ip") {
+        return setParamRtpLocalIp(value);
+    } else if (key == "rtp-param-local-port") {
+        int32_t localPort;
+        if (safe_strtoi32(value.string(), &localPort)) {
+            return setParamRtpLocalPort(localPort);
+        }
+    } else if (key == "rtp-param-remote-ip") {
+        return setParamRtpRemoteIp(value);
+    } else if (key == "rtp-param-remote-port") {
+        int32_t remotePort;
+        if (safe_strtoi32(value.string(), &remotePort)) {
+            return setParamRtpRemotePort(remotePort);
+        }
+    } else if (key == "rtp-param-self-id") {
+        int32_t selfID;
+        int64_t temp;
+        if (safe_strtoi64(value.string(), &temp)) {
+            selfID = static_cast<int32_t>(temp);
+            return setParamSelfID(selfID);
+        }
+    } else if (key == "rtp-param-opponent-id") {
+        int32_t opnId;
+        int64_t temp;
+        if (safe_strtoi64(value.string(), &temp)) {
+            opnId = static_cast<int32_t>(temp);
+            return setParamVideoOpponentID(opnId);
+        }
+    } else if (key == "rtp-param-payload-type") {
+        int32_t payloadType;
+        if (safe_strtoi32(value.string(), &payloadType)) {
+            return setParamPayloadType(payloadType);
+        }
+    } else if (key == "rtp-param-ext-cvo-extmap") {
+        int32_t extmap;
+        if (safe_strtoi32(value.string(), &extmap)) {
+            return setRTPCVOExtMap(extmap);
+        }
+    } else if (key == "rtp-param-ext-cvo-degrees") {
+        int32_t degrees;
+        if (safe_strtoi32(value.string(), &degrees)) {
+            return setRTPCVODegrees(degrees);
+        }
+    } else if (key == "video-param-request-i-frame") {
+        return requestIDRFrame();
+    } else if (key == "rtp-param-set-socket-dscp") {
+        int32_t dscp;
+        if (safe_strtoi32(value.string(), &dscp)) {
+            return setParamRtpDscp(dscp);
+        }
+    } else if (key == "rtp-param-set-socket-network") {
+        int64_t networkHandle;
+        if (safe_strtoi64(value.string(), &networkHandle)) {
+            return setSocketNetwork(networkHandle);
+        }
     } else {
         ALOGE("setParameter: failed to find key %s", key.string());
     }
@@ -1050,6 +1247,17 @@
             sp<MetaData> meta = new MetaData;
             int64_t startTimeUs = systemTime() / 1000;
             meta->setInt64(kKeyTime, startTimeUs);
+            meta->setInt32(kKeySelfID, mSelfID);
+            meta->setInt32(kKeyPayloadType, mPayloadType);
+            meta->setInt64(kKeySocketNetwork, mRTPSockNetwork);
+            if (mRTPCVOExtMap > 0) {
+                meta->setInt32(kKeyRtpExtMap, mRTPCVOExtMap);
+                meta->setInt32(kKeyRtpCvoDegrees, mRTPCVODegrees);
+            }
+            if (mRTPSockDscp > 0) {
+                meta->setInt32(kKeyRtpDscp, mRTPSockDscp);
+            }
+
             status = mWriter->start(meta.get());
             break;
         }
@@ -1113,7 +1321,7 @@
     if (mPrivacySensitive == PRIVACY_SENSITIVE_DEFAULT) {
         if (attr.source == AUDIO_SOURCE_VOICE_COMMUNICATION
                 || attr.source == AUDIO_SOURCE_CAMCORDER) {
-            attr.flags |= AUDIO_FLAG_CAPTURE_PRIVATE;
+            attr.flags = static_cast<audio_flags_mask_t>(attr.flags | AUDIO_FLAG_CAPTURE_PRIVATE);
             mPrivacySensitive = PRIVACY_SENSITIVE_ENABLED;
         } else {
             mPrivacySensitive = PRIVACY_SENSITIVE_DISABLED;
@@ -1129,7 +1337,7 @@
             return NULL;
         }
         if (mPrivacySensitive == PRIVACY_SENSITIVE_ENABLED) {
-            attr.flags |= AUDIO_FLAG_CAPTURE_PRIVATE;
+            attr.flags = static_cast<audio_flags_mask_t>(attr.flags | AUDIO_FLAG_CAPTURE_PRIVATE);
         }
     }
 
@@ -1330,7 +1538,7 @@
         mVideoEncoderSource = source;
     }
 
-    mWriter = new ARTPWriter(mOutputFd);
+    mWriter = new ARTPWriter(mOutputFd, mLocalIp, mLocalPort, mRemoteIp, mRemotePort, mLastSeqNo);
     mWriter->addSource(source);
     mWriter->setListener(mListener);
 
@@ -1784,7 +1992,13 @@
         }
     }
 
+    if (mOutputFormat == OUTPUT_FORMAT_RTP_AVP) {
+        // This indicates that a raw image provided to encoder needs to be rotated.
+        format->setInt32("rotation-degrees", mRotationDegrees);
+    }
+
     format->setInt32("bitrate", mVideoBitRate);
+    format->setInt32("bitrate-mode", mVideoBitRateMode);
     format->setInt32("frame-rate", mFrameRate);
     format->setInt32("i-frame-interval", mIFramesIntervalSec);
 
@@ -2130,6 +2344,7 @@
 
     if (mWriter != NULL) {
         err = mWriter->stop();
+        mLastSeqNo = mWriter->getSequenceNum();
         mWriter.clear();
     }
 
@@ -2206,6 +2421,8 @@
     mVideoHeight   = 144;
     mFrameRate     = -1;
     mVideoBitRate  = 192000;
+    // Following MediaCodec's default
+    mVideoBitRateMode = BITRATE_MODE_VBR;
     mSampleRate    = 8000;
     mAudioChannels = 1;
     mAudioBitRate  = 12200;
@@ -2351,6 +2568,14 @@
     return NO_INIT;
 }
 
+status_t StagefrightRecorder::getRtpDataUsage(uint64_t *bytes) {
+    if (mWriter != 0) {
+        *bytes = mWriter->getAccumulativeBytes();
+        return OK;
+    }
+    return NO_INIT;
+}
+
 status_t StagefrightRecorder::dump(
         int fd, const Vector<String16>& args) const {
     ALOGV("dump");
diff --git a/media/libmediaplayerservice/StagefrightRecorder.h b/media/libmediaplayerservice/StagefrightRecorder.h
index a725bee..4bba869 100644
--- a/media/libmediaplayerservice/StagefrightRecorder.h
+++ b/media/libmediaplayerservice/StagefrightRecorder.h
@@ -82,6 +82,7 @@
     virtual status_t setPreferredMicrophoneDirection(audio_microphone_direction_t direction);
     virtual status_t setPreferredMicrophoneFieldDimension(float zoom);
             status_t getPortId(audio_port_handle_t *portId) const override;
+    virtual status_t getRtpDataUsage(uint64_t *bytes);
 
 private:
 
@@ -119,6 +120,7 @@
     int32_t mVideoWidth, mVideoHeight;
     int32_t mFrameRate;
     int32_t mVideoBitRate;
+    int32_t mVideoBitRateMode;
     int32_t mAudioBitRate;
     int32_t mAudioChannels;
     int32_t mSampleRate;
@@ -138,6 +140,18 @@
     int32_t mLongitudex10000;
     int32_t mStartTimeOffsetMs;
     int32_t mTotalBitRate;
+    String8 mLocalIp;
+    String8 mRemoteIp;
+    int32_t mLocalPort;
+    int32_t mRemotePort;
+    int32_t mSelfID;
+    int32_t mOpponentID;
+    int32_t mPayloadType;
+    int32_t mRTPCVOExtMap;
+    int32_t mRTPCVODegrees;
+    int32_t mRTPSockDscp;
+    int64_t mRTPSockNetwork;
+    uint32_t mLastSeqNo;
 
     int64_t mDurationRecordedUs;
     int64_t mStartedRecordingUs;
@@ -205,6 +219,7 @@
     status_t setParamCaptureFpsEnable(int32_t timeLapseEnable);
     status_t setParamCaptureFps(double fps);
     status_t setParamVideoEncodingBitRate(int32_t bitRate);
+    status_t setParamVideoBitRateMode(int32_t bitRateMode);
     status_t setParamVideoIFramesInterval(int32_t seconds);
     status_t setParamVideoEncoderProfile(int32_t profile);
     status_t setParamVideoEncoderLevel(int32_t level);
@@ -219,6 +234,18 @@
     status_t setParamMovieTimeScale(int32_t timeScale);
     status_t setParamGeoDataLongitude(int64_t longitudex10000);
     status_t setParamGeoDataLatitude(int64_t latitudex10000);
+    status_t setParamRtpLocalIp(const String8 &localIp);
+    status_t setParamRtpLocalPort(int32_t localPort);
+    status_t setParamRtpRemoteIp(const String8 &remoteIp);
+    status_t setParamRtpRemotePort(int32_t remotePort);
+    status_t setParamSelfID(int32_t selfID);
+    status_t setParamVideoOpponentID(int32_t opponentID);
+    status_t setParamPayloadType(int32_t payloadType);
+    status_t setRTPCVOExtMap(int32_t extmap);
+    status_t setRTPCVODegrees(int32_t cvoDegrees);
+    status_t setParamRtpDscp(int32_t dscp);
+    status_t setSocketNetwork(int64_t networkHandle);
+    status_t requestIDRFrame();
     void clipVideoBitRate();
     void clipVideoFrameRate();
     void clipVideoFrameWidth();
diff --git a/media/libmediaplayerservice/datasource/Android.bp b/media/libmediaplayerservice/datasource/Android.bp
index 71fa50b..19fc172 100644
--- a/media/libmediaplayerservice/datasource/Android.bp
+++ b/media/libmediaplayerservice/datasource/Android.bp
@@ -1,3 +1,14 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libmediaplayerservice_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libmediaplayerservice_license",
+    ],
+}
+
 cc_library_static {
     name: "libplayerservice_datasource",
 
diff --git a/media/libmediaplayerservice/include/MediaPlayerInterface.h b/media/libmediaplayerservice/include/MediaPlayerInterface.h
index 436cb31..8d94698 100644
--- a/media/libmediaplayerservice/include/MediaPlayerInterface.h
+++ b/media/libmediaplayerservice/include/MediaPlayerInterface.h
@@ -60,7 +60,7 @@
 #define DEFAULT_AUDIOSINK_SAMPLERATE 44100
 
 // when the channel mask isn't known, use the channel count to derive a mask in AudioSink::open()
-#define CHANNEL_MASK_USE_CHANNEL_ORDER 0
+#define CHANNEL_MASK_USE_CHANNEL_ORDER AUDIO_CHANNEL_NONE
 
 // duration below which we do not allow deep audio buffering
 #define AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US 5000000
@@ -183,6 +183,10 @@
         return INVALID_OPERATION;
     }
 
+    virtual status_t    setDataSource(const String8& /* rtpParams */) {
+        return INVALID_OPERATION;
+    }
+
     // pass the buffered IGraphicBufferProducer to the media player service
     virtual status_t    setVideoSurfaceTexture(
                                 const sp<IGraphicBufferProducer>& bufferProducer) = 0;
diff --git a/media/libmediaplayerservice/nuplayer/Android.bp b/media/libmediaplayerservice/nuplayer/Android.bp
index 32c97cf..6d338db 100644
--- a/media/libmediaplayerservice/nuplayer/Android.bp
+++ b/media/libmediaplayerservice/nuplayer/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libmediaplayerservice_nuplayer_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libmediaplayerservice_nuplayer_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_static {
 
     srcs: [
@@ -14,6 +33,7 @@
         "NuPlayerRenderer.cpp",
         "NuPlayerStreamListener.cpp",
         "RTSPSource.cpp",
+        "RTPSource.cpp",
         "StreamingSource.cpp",
     ],
 
@@ -30,6 +50,7 @@
         "frameworks/av/media/libstagefright/mpeg2ts",
         "frameworks/av/media/libstagefright/rtsp",
         "frameworks/av/media/libstagefright/timedtext",
+        "frameworks/native/include/android",
     ],
 
     cflags: [
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index c1c4b55..389249e 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -31,6 +31,7 @@
 #include "NuPlayerDriver.h"
 #include "NuPlayerRenderer.h"
 #include "NuPlayerSource.h"
+#include "RTPSource.h"
 #include "RTSPSource.h"
 #include "StreamingSource.h"
 #include "GenericSource.h"
@@ -368,6 +369,18 @@
     return err;
 }
 
+void NuPlayer::setDataSourceAsync(const String8& rtpParams) {
+    ALOGD("setDataSourceAsync for RTP = %s", rtpParams.string());
+    sp<AMessage> msg = new AMessage(kWhatSetDataSource, this);
+
+    sp<AMessage> notify = new AMessage(kWhatSourceNotify, this);
+    sp<Source> source = new RTPSource(notify, rtpParams);
+
+    msg->setObject("source", source);
+    msg->post();
+    mDataSourceType = DATA_SOURCE_TYPE_RTP;
+}
+
 void NuPlayer::prepareAsync() {
     ALOGV("prepareAsync");
 
@@ -1689,6 +1702,12 @@
     updateRebufferingTimer(false /* stopping */, false /* exiting */);
 }
 
+void NuPlayer::setTargetBitrate(int bitrate) {
+    if (mSource != NULL) {
+        mSource->setTargetBitrate(bitrate);
+    }
+}
+
 void NuPlayer::onPause() {
 
     updatePlaybackTimer(true /* stopping */, "onPause");
@@ -1915,6 +1934,11 @@
 
     format->setInt32("priority", 0 /* realtime */);
 
+    if (mDataSourceType == DATA_SOURCE_TYPE_RTP) {
+        ALOGV("instantiateDecoder: set decoder error free on stream corrupt.");
+        format->setInt32("corrupt-free", true);
+    }
+
     if (!audio) {
         AString mime;
         CHECK(format->findString("mime", &mime));
@@ -2715,6 +2739,14 @@
             break;
         }
 
+        case Source::kWhatIMSRxNotice:
+        {
+            sp<AMessage> IMSRxNotice;
+            CHECK(msg->findMessage("message", &IMSRxNotice));
+            sendIMSRxNotice(IMSRxNotice);
+            break;
+        }
+
         default:
             TRESPASS();
     }
@@ -2817,11 +2849,75 @@
     }
 }
 
+void NuPlayer::sendIMSRxNotice(const sp<AMessage> &msg) {
+    int32_t payloadType;
+
+    CHECK(msg->findInt32("payload-type", &payloadType));
+
+    Parcel in;
+    in.writeInt32(payloadType);
+
+    switch (payloadType) {
+        case ARTPSource::RTCP_TSFB:   // RTCP TSFB
+        case ARTPSource::RTCP_PSFB:   // RTCP PSFB
+        case ARTPSource::RTP_AUTODOWN:
+        {
+            int32_t feedbackType, id;
+            CHECK(msg->findInt32("feedback-type", &feedbackType));
+            CHECK(msg->findInt32("sender", &id));
+            in.writeInt32(feedbackType);
+            in.writeInt32(id);
+            if (payloadType == ARTPSource::RTCP_TSFB) {
+                int32_t bitrate;
+                CHECK(msg->findInt32("bit-rate", &bitrate));
+                in.writeInt32(bitrate);
+            }
+            break;
+        }
+        case ARTPSource::RTP_QUALITY:
+        case ARTPSource::RTP_QUALITY_EMC:
+        {
+            int32_t feedbackType, bitrate;
+            int32_t highestSeqNum, baseSeqNum, prevExpected;
+            int32_t numBufRecv, prevNumBufRecv;
+            CHECK(msg->findInt32("feedback-type", &feedbackType));
+            CHECK(msg->findInt32("bit-rate", &bitrate));
+            CHECK(msg->findInt32("highest-seq-num", &highestSeqNum));
+            CHECK(msg->findInt32("base-seq-num", &baseSeqNum));
+            CHECK(msg->findInt32("prev-expected", &prevExpected));
+            CHECK(msg->findInt32("num-buf-recv", &numBufRecv));
+            CHECK(msg->findInt32("prev-num-buf-recv", &prevNumBufRecv));
+            in.writeInt32(feedbackType);
+            in.writeInt32(bitrate);
+            in.writeInt32(highestSeqNum);
+            in.writeInt32(baseSeqNum);
+            in.writeInt32(prevExpected);
+            in.writeInt32(numBufRecv);
+            in.writeInt32(prevNumBufRecv);
+            break;
+        }
+        case ARTPSource::RTP_CVO:
+        {
+            int32_t cvo;
+            CHECK(msg->findInt32("cvo", &cvo));
+            in.writeInt32(cvo);
+            break;
+        }
+        default:
+        break;
+    }
+
+    notifyListener(MEDIA_IMS_RX_NOTICE, 0, 0, &in);
+}
+
 const char *NuPlayer::getDataSourceType() {
     switch (mDataSourceType) {
         case DATA_SOURCE_TYPE_HTTP_LIVE:
             return "HTTPLive";
 
+        case DATA_SOURCE_TYPE_RTP:
+            return "RTP";
+
         case DATA_SOURCE_TYPE_RTSP:
             return "RTSP";
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.h b/media/libmediaplayerservice/nuplayer/NuPlayer.h
index ef4354c..adb7075 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.h
@@ -51,6 +51,8 @@
 
     void setDataSourceAsync(const sp<DataSource> &source);
 
+    void setDataSourceAsync(const String8& rtpParams);
+
     status_t getBufferingSettings(BufferingSettings* buffering /* nonnull */);
     status_t setBufferingSettings(const BufferingSettings& buffering);
 
@@ -100,6 +102,8 @@
 
     void updateInternalTimers();
 
+    void setTargetBitrate(int bitrate /* bps */);
+
 protected:
     virtual ~NuPlayer();
 
@@ -117,6 +121,7 @@
     struct GenericSource;
     struct HTTPLiveSource;
     struct Renderer;
+    struct RTPSource;
     struct RTSPSource;
     struct StreamingSource;
     struct Action;
@@ -257,6 +262,7 @@
     typedef enum {
         DATA_SOURCE_TYPE_NONE,
         DATA_SOURCE_TYPE_HTTP_LIVE,
+        DATA_SOURCE_TYPE_RTP,
         DATA_SOURCE_TYPE_RTSP,
         DATA_SOURCE_TYPE_GENERIC_URL,
         DATA_SOURCE_TYPE_GENERIC_FD,
@@ -334,6 +340,7 @@
     void sendSubtitleData(const sp<ABuffer> &buffer, int32_t baseIndex);
     void sendTimedMetaData(const sp<ABuffer> &buffer);
     void sendTimedTextData(const sp<ABuffer> &buffer);
+    void sendIMSRxNotice(const sp<AMessage> &msg);
 
     void writeTrackInfo(Parcel* reply, const sp<AMessage>& format) const;
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
index f734439..5b60bbf 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDecoder.cpp
@@ -746,9 +746,15 @@
 
     mOutputBuffers.editItemAt(index) = buffer;
 
+    int64_t frameIndex;
+    bool frameIndexFound = buffer->meta()->findInt64("frameIndex", &frameIndex);
+
     buffer->setRange(offset, size);
     buffer->meta()->clear();
     buffer->meta()->setInt64("timeUs", timeUs);
+    if (frameIndexFound) {
+        buffer->meta()->setInt64("frameIndex", frameIndex);
+    }
 
     bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
     // we do not expect CODECCONFIG or SYNCFRAME for decoder
@@ -1050,7 +1056,7 @@
         uint32_t flags = 0;
         CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
 
-        int32_t eos, csd;
+        int32_t eos, csd, cvo;
         // we do not expect SYNCFRAME for decoder
         if (buffer->meta()->findInt32("eos", &eos) && eos) {
             flags |= MediaCodec::BUFFER_FLAG_EOS;
@@ -1058,6 +1064,24 @@
             flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
         }
 
+        if (buffer->meta()->findInt32("cvo", (int32_t*)&cvo)) {
+            ALOGV("[%s] cvo(%d) found at %lld us", mComponentName.c_str(), cvo, (long long)timeUs);
+            switch (cvo) {
+                case 0:
+                    codecBuffer->meta()->setInt32("cvo", MediaCodec::CVO_DEGREE_0);
+                    break;
+                case 1:
+                    codecBuffer->meta()->setInt32("cvo", MediaCodec::CVO_DEGREE_90);
+                    break;
+                case 2:
+                    codecBuffer->meta()->setInt32("cvo", MediaCodec::CVO_DEGREE_180);
+                    break;
+                case 3:
+                    codecBuffer->meta()->setInt32("cvo", MediaCodec::CVO_DEGREE_270);
+                    break;
+            }
+        }
+
         // Modular DRM
         MediaBufferBase *mediaBuf = NULL;
         NuPlayerDrm::CryptoInfo *cryptInfo = NULL;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
index dc144b2..2a50fc2 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
@@ -218,6 +218,26 @@
     return mAsyncResult;
 }
 
+status_t NuPlayerDriver::setDataSource(const String8& rtpParams) {
+    ALOGV("setDataSource(%p) rtp source", this);
+    Mutex::Autolock autoLock(mLock);
+
+    if (mState != STATE_IDLE) {
+        return INVALID_OPERATION;
+    }
+
+    mState = STATE_SET_DATASOURCE_PENDING;
+
+    mPlayer->setDataSourceAsync(rtpParams);
+
+    while (mState == STATE_SET_DATASOURCE_PENDING) {
+        mCondition.wait(mLock);
+    }
+
+    return mAsyncResult;
+}
+
+
 status_t NuPlayerDriver::setVideoSurfaceTexture(
         const sp<IGraphicBufferProducer> &bufferProducer) {
     ALOGV("setVideoSurfaceTexture(%p)", this);
@@ -797,7 +817,11 @@
 }
 
 status_t NuPlayerDriver::setParameter(
-        int /* key */, const Parcel & /* request */) {
+        int key, const Parcel &request ) {
+    if (key == KEY_PARAMETER_RTP_ATTRIBUTES) {
+        mPlayer->setTargetBitrate(request.readInt32());
+        return OK;
+    }
     return INVALID_OPERATION;
 }
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h
index f4b1968..55a0fad 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.h
@@ -43,6 +43,8 @@
 
     virtual status_t setDataSource(const sp<DataSource>& dataSource);
 
+    virtual status_t setDataSource(const String8& rtpParams);
+
     virtual status_t setVideoSurfaceTexture(
             const sp<IGraphicBufferProducer> &bufferProducer);
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
index c30f048..6a8c708 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
@@ -922,6 +922,11 @@
             firstEntry = false;
             int64_t mediaTimeUs;
             CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
+            if (mediaTimeUs < 0) {
+                ALOGD("fillAudioBuffer: reset negative media time %.2f secs to zero",
+                       mediaTimeUs / 1E6);
+                mediaTimeUs = 0;
+            }
             ALOGV("fillAudioBuffer: rendering audio at media time %.2f secs", mediaTimeUs / 1E6);
             setAudioFirstAnchorTimeIfNeeded_l(mediaTimeUs);
         }
@@ -1928,11 +1933,12 @@
     int32_t numChannels;
     CHECK(format->findInt32("channel-count", &numChannels));
 
-    int32_t channelMask;
-    if (!format->findInt32("channel-mask", &channelMask)) {
-        // signal to the AudioSink to derive the mask from count.
-        channelMask = CHANNEL_MASK_USE_CHANNEL_ORDER;
-    }
+    int32_t rawChannelMask;
+    audio_channel_mask_t channelMask =
+            format->findInt32("channel-mask", &rawChannelMask) ?
+                    static_cast<audio_channel_mask_t>(rawChannelMask)
+                    // signal to the AudioSink to derive the mask from count.
+                    : CHANNEL_MASK_USE_CHANNEL_ORDER;
 
     int32_t sampleRate;
     CHECK(format->findInt32("sample-rate", &sampleRate));
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerSource.h b/media/libmediaplayerservice/nuplayer/NuPlayerSource.h
index f137c52..bf6b539 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerSource.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerSource.h
@@ -58,6 +58,7 @@
         kWhatInstantiateSecureDecoders,
         // Modular DRM
         kWhatDrmInfo,
+        kWhatIMSRxNotice,
     };
 
     // The provides message is used to notify the player about various
@@ -131,6 +132,8 @@
 
     virtual void setOffloadAudio(bool /* offload */) {}
 
+    virtual void setTargetBitrate(int32_t) {}
+
     // Modular DRM
     virtual status_t prepareDrm(
             const uint8_t /*uuid*/[16], const Vector<uint8_t> &/*drmSessionId*/,
diff --git a/media/libmediaplayerservice/nuplayer/RTPSource.cpp b/media/libmediaplayerservice/nuplayer/RTPSource.cpp
new file mode 100644
index 0000000..b43df38
--- /dev/null
+++ b/media/libmediaplayerservice/nuplayer/RTPSource.cpp
@@ -0,0 +1,801 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "RTPSource"
+#include <utils/Log.h>
+
+#include "RTPSource.h"
+
+
+
+
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaData.h>
+#include <string.h>
+
+namespace android {
+
+const int64_t kNearEOSTimeoutUs = 2000000ll; // 2 secs
+static int32_t kMaxAllowedStaleAccessUnits = 20;
+
+NuPlayer::RTPSource::RTPSource(
+        const sp<AMessage> &notify,
+        const String8& rtpParams)
+    : Source(notify),
+      mRTPParams(rtpParams),
+      mFlags(0),
+      mState(DISCONNECTED),
+      mFinalResult(OK),
+      mBuffering(false),
+      mInPreparationPhase(true),
+      mRTPConn(new ARTPConnection(ARTPConnection::kViLTEConnection)),
+      mEOSTimeoutAudio(0),
+      mEOSTimeoutVideo(0),
+      mFirstAccessUnit(true),
+      mAllTracksHaveTime(false),
+      mNTPAnchorUs(-1),
+      mMediaAnchorUs(-1),
+      mLastMediaTimeUs(-1),
+      mNumAccessUnitsReceived(0),
+      mLastCVOUpdated(-1),
+      mReceivedFirstRTCPPacket(false),
+      mReceivedFirstRTPPacket(false),
+      mPausing(false),
+      mPauseGeneration(0) {
+    ALOGD("RTPSource initialized with rtpParams=%s", rtpParams.string());
+}
+
+NuPlayer::RTPSource::~RTPSource() {
+    if (mLooper != NULL) {
+        mLooper->unregisterHandler(id());
+        mLooper->unregisterHandler(mRTPConn->id());
+        mLooper->stop();
+    }
+}
+
+status_t NuPlayer::RTPSource::getBufferingSettings(
+            BufferingSettings* buffering /* nonnull */) {
+    Mutex::Autolock _l(mBufferingSettingsLock);
+    *buffering = mBufferingSettings;
+    return OK;
+}
+
+status_t NuPlayer::RTPSource::setBufferingSettings(const BufferingSettings& buffering) {
+    Mutex::Autolock _l(mBufferingSettingsLock);
+    mBufferingSettings = buffering;
+    return OK;
+}
+
+void NuPlayer::RTPSource::prepareAsync() {
+    if (mLooper == NULL) {
+        mLooper = new ALooper;
+        mLooper->setName("rtp");
+        mLooper->start();
+
+        mLooper->registerHandler(this);
+        mLooper->registerHandler(mRTPConn);
+    }
+
+    CHECK_EQ(mState, (int)DISCONNECTED);
+    mState = CONNECTING;
+
+    setParameters(mRTPParams);
+
+    TrackInfo *info = NULL;
+    unsigned i;
+    for (i = 0; i < mTracks.size(); i++) {
+        info = &mTracks.editItemAt(i);
+
+        if (info == NULL)
+            break;
+
+        AString sdp;
+        ASessionDescription::SDPStringFactory(sdp, info->mLocalIp,
+                info->mIsAudio, info->mLocalPort, info->mPayloadType, info->mAS, info->mCodecName,
+                NULL, info->mWidth, info->mHeight, info->mCVOExtMap);
+        ALOGD("RTPSource SDP =>\n%s", sdp.c_str());
+
+        sp<ASessionDescription> desc = new ASessionDescription;
+        bool isValidSdp = desc->setTo(sdp.c_str(), sdp.size());
+        ALOGV("RTPSource isValidSdp => %d", isValidSdp);
+
+        int sockRtp, sockRtcp;
+        ARTPConnection::MakeRTPSocketPair(&sockRtp, &sockRtcp, info->mLocalIp, info->mRemoteIp,
+                info->mLocalPort, info->mRemotePort, info->mSocketNetwork);
+
+        sp<AMessage> notify = new AMessage('accu', this);
+
+        ALOGV("RTPSource addStream. track-index=%d", i);
+        notify->setSize("trackIndex", i);
+        // index(i) should be started from 1. 0 is reserved for [root]
+        mRTPConn->addStream(sockRtp, sockRtcp, desc, i + 1, notify, false);
+        mRTPConn->setSelfID(info->mSelfID);
+        mRTPConn->setJbTime(
+                (info->mJbTimeMs <= 3000 && info->mJbTimeMs >= 40) ? info->mJbTimeMs : 300);
+
+        info->mRTPSocket = sockRtp;
+        info->mRTCPSocket = sockRtcp;
+        info->mFirstSeqNumInSegment = 0;
+        info->mNewSegment = true;
+        info->mAllowedStaleAccessUnits = kMaxAllowedStaleAccessUnits;
+        info->mRTPAnchor = 0;
+        info->mNTPAnchorUs = -1;
+        info->mNormalPlayTimeRTP = 0;
+        info->mNormalPlayTimeUs = 0ll;
+
+        // index(i) should be started from 1. 0 is reserved for [root]
+        info->mPacketSource = new APacketSource(desc, i + 1);
+
+        int32_t timeScale;
+        sp<MetaData> format = getTrackFormat(i, &timeScale);
+        sp<AnotherPacketSource> source = new AnotherPacketSource(format);
+
+        if (info->mIsAudio) {
+            mAudioTrack = source;
+            info->mTimeScale = 16000;
+        } else {
+            mVideoTrack = source;
+            info->mTimeScale = 90000;
+        }
+
+        info->mSource = source;
+        info->mRTPTime = 0;
+        info->mNormalPlaytimeUs = 0;
+        info->mNPTMappingValid = false;
+    }
+
+    if (mInPreparationPhase) {
+        mInPreparationPhase = false;
+        notifyPrepared();
+    }
+}
+
+void NuPlayer::RTPSource::start() {
+}
+
+void NuPlayer::RTPSource::pause() {
+    mState = PAUSED;
+}
+
+void NuPlayer::RTPSource::resume() {
+    mState = CONNECTING;
+}
+
+void NuPlayer::RTPSource::stop() {
+    if (mLooper == NULL) {
+        return;
+    }
+    sp<AMessage> msg = new AMessage(kWhatDisconnect, this);
+
+    sp<AMessage> dummy;
+    msg->postAndAwaitResponse(&dummy);
+}
+
+status_t NuPlayer::RTPSource::feedMoreTSData() {
+    Mutex::Autolock _l(mBufferingLock);
+    return mFinalResult;
+}
+
+sp<MetaData> NuPlayer::RTPSource::getFormatMeta(bool audio) {
+    sp<AnotherPacketSource> source = getSource(audio);
+
+    if (source == NULL) {
+        return NULL;
+    }
+
+    return source->getFormat();
+}
+
+bool NuPlayer::RTPSource::haveSufficientDataOnAllTracks() {
+    // We're going to buffer at least 2 secs worth data on all tracks before
+    // starting playback (both at startup and after a seek).
+
+    static const int64_t kMinDurationUs = 2000000ll;
+
+    int64_t mediaDurationUs = 0;
+    getDuration(&mediaDurationUs);
+    if ((mAudioTrack != NULL && mAudioTrack->isFinished(mediaDurationUs))
+            || (mVideoTrack != NULL && mVideoTrack->isFinished(mediaDurationUs))) {
+        return true;
+    }
+
+    status_t err;
+    int64_t durationUs;
+    if (mAudioTrack != NULL
+            && (durationUs = mAudioTrack->getBufferedDurationUs(&err))
+                    < kMinDurationUs
+            && err == OK) {
+        ALOGV("audio track doesn't have enough data yet. (%.2f secs buffered)",
+              durationUs / 1E6);
+        return false;
+    }
+
+    if (mVideoTrack != NULL
+            && (durationUs = mVideoTrack->getBufferedDurationUs(&err))
+                    < kMinDurationUs
+            && err == OK) {
+        ALOGV("video track doesn't have enough data yet. (%.2f secs buffered)",
+              durationUs / 1E6);
+        return false;
+    }
+
+    return true;
+}
+
+status_t NuPlayer::RTPSource::dequeueAccessUnit(
+        bool audio, sp<ABuffer> *accessUnit) {
+
+    sp<AnotherPacketSource> source = getSource(audio);
+
+    if (mState == PAUSED) {
+        ALOGV("-EWOULDBLOCK");
+        return -EWOULDBLOCK;
+    }
+
+    status_t finalResult;
+    if (!source->hasBufferAvailable(&finalResult)) {
+        if (finalResult == OK) {
+            int64_t mediaDurationUs = 0;
+            getDuration(&mediaDurationUs);
+            sp<AnotherPacketSource> otherSource = getSource(!audio);
+            status_t otherFinalResult;
+
+            // If other source already signaled EOS, this source should also signal EOS
+            if (otherSource != NULL &&
+                    !otherSource->hasBufferAvailable(&otherFinalResult) &&
+                    otherFinalResult == ERROR_END_OF_STREAM) {
+                source->signalEOS(ERROR_END_OF_STREAM);
+                return ERROR_END_OF_STREAM;
+            }
+
+            // If this source has detected near end, give it some time to retrieve more
+            // data before signaling EOS
+            if (source->isFinished(mediaDurationUs)) {
+                int64_t eosTimeout = audio ? mEOSTimeoutAudio : mEOSTimeoutVideo;
+                if (eosTimeout == 0) {
+                    setEOSTimeout(audio, ALooper::GetNowUs());
+                } else if ((ALooper::GetNowUs() - eosTimeout) > kNearEOSTimeoutUs) {
+                    setEOSTimeout(audio, 0);
+                    source->signalEOS(ERROR_END_OF_STREAM);
+                    return ERROR_END_OF_STREAM;
+                }
+                return -EWOULDBLOCK;
+            }
+
+            if (!(otherSource != NULL && otherSource->isFinished(mediaDurationUs))) {
+                // We should not enter buffering mode
+                // if any of the sources already have detected EOS.
+                // TODO: needs to be checked whether below line is needed or not.
+                // startBufferingIfNecessary();
+            }
+
+            return -EWOULDBLOCK;
+        }
+        return finalResult;
+    }
+
+    setEOSTimeout(audio, 0);
+
+    finalResult = source->dequeueAccessUnit(accessUnit);
+    if (finalResult != OK) {
+        return finalResult;
+    }
+
+    int32_t cvo;
+    if ((*accessUnit) != NULL && (*accessUnit)->meta()->findInt32("cvo", &cvo) &&
+            cvo != mLastCVOUpdated) {
+        sp<AMessage> msg = new AMessage();
+        msg->setInt32("payload-type", ARTPSource::RTP_CVO);
+        msg->setInt32("cvo", cvo);
+
+        sp<AMessage> notify = dupNotify();
+        notify->setInt32("what", kWhatIMSRxNotice);
+        notify->setMessage("message", msg);
+        notify->post();
+
+        ALOGV("notify cvo updated (%d)->(%d) to upper layer", mLastCVOUpdated, cvo);
+        mLastCVOUpdated = cvo;
+    }
+
+    return finalResult;
+}
+
+sp<AnotherPacketSource> NuPlayer::RTPSource::getSource(bool audio) {
+    return audio ? mAudioTrack : mVideoTrack;
+}
+
+void NuPlayer::RTPSource::setEOSTimeout(bool audio, int64_t timeout) {
+    if (audio) {
+        mEOSTimeoutAudio = timeout;
+    } else {
+        mEOSTimeoutVideo = timeout;
+    }
+}
+
+status_t NuPlayer::RTPSource::getDuration(int64_t *durationUs) {
+    *durationUs = 0ll;
+
+    int64_t audioDurationUs;
+    if (mAudioTrack != NULL
+            && mAudioTrack->getFormat()->findInt64(
+                kKeyDuration, &audioDurationUs)
+            && audioDurationUs > *durationUs) {
+        *durationUs = audioDurationUs;
+    }
+
+    int64_t videoDurationUs;
+    if (mVideoTrack != NULL
+            && mVideoTrack->getFormat()->findInt64(
+                kKeyDuration, &videoDurationUs)
+            && videoDurationUs > *durationUs) {
+        *durationUs = videoDurationUs;
+    }
+
+    return OK;
+}
+
+status_t NuPlayer::RTPSource::seekTo(int64_t seekTimeUs, MediaPlayerSeekMode mode) {
+    ALOGV("RTPSource::seekTo=%d, mode=%d", (int)seekTimeUs, mode);
+    return OK;
+}
+
+void NuPlayer::RTPSource::schedulePollBuffering() {
+    sp<AMessage> msg = new AMessage(kWhatPollBuffering, this);
+    msg->post(kBufferingPollIntervalUs); // 1 second intervals
+}
+
+void NuPlayer::RTPSource::onPollBuffering() {
+    schedulePollBuffering();
+}
+
+bool NuPlayer::RTPSource::isRealTime() const {
+    ALOGD("RTPSource::isRealTime=%d", true);
+    return true;
+}
+
+void NuPlayer::RTPSource::onMessageReceived(const sp<AMessage> &msg) {
+    ALOGV("onMessageReceived =%d", msg->what());
+
+    switch (msg->what()) {
+        case kWhatAccessUnitComplete:
+        {
+            if (mState == CONNECTING) {
+                mState = CONNECTED;
+            }
+
+            int32_t timeUpdate;
+            //"time-update" raised from ARTPConnection::parseSR()
+            if (msg->findInt32("time-update", &timeUpdate) && timeUpdate) {
+                size_t trackIndex;
+                CHECK(msg->findSize("trackIndex", &trackIndex));
+
+                uint32_t rtpTime;
+                uint64_t ntpTime;
+                CHECK(msg->findInt32("rtp-time", (int32_t *)&rtpTime));
+                CHECK(msg->findInt64("ntp-time", (int64_t *)&ntpTime));
+
+                onTimeUpdate(trackIndex, rtpTime, ntpTime);
+                break;
+            }
+
+            int32_t firstRTCP;
+            if (msg->findInt32("first-rtcp", &firstRTCP)) {
+                // There won't be an access unit here, it's just a notification
+                // that the data communication worked since we got the first
+                // rtcp packet.
+                ALOGV("first-rtcp");
+                break;
+            }
+
+            int32_t IMSRxNotice;
+            if (msg->findInt32("rtcp-event", &IMSRxNotice)) {
+                int32_t payloadType, feedbackType;
+                CHECK(msg->findInt32("payload-type", &payloadType));
+                CHECK(msg->findInt32("feedback-type", &feedbackType));
+
+                sp<AMessage> notify = dupNotify();
+                notify->setInt32("what", kWhatIMSRxNotice);
+                notify->setMessage("message", msg);
+                notify->post();
+
+                ALOGV("IMSRxNotice \t\t payload : %d feedback : %d",
+                      payloadType, feedbackType);
+                break;
+            }
+
+            size_t trackIndex;
+            CHECK(msg->findSize("trackIndex", &trackIndex));
+
+            sp<ABuffer> accessUnit;
+            if (msg->findBuffer("access-unit", &accessUnit) == false) {
+                break;
+            }
+
+            int32_t damaged;
+            if (accessUnit->meta()->findInt32("damaged", &damaged)
+                    && damaged) {
+                ALOGD("dropping damaged access unit.");
+                break;
+            }
+
+            // Implicitly assert on valid trackIndex here, which we ensure by
+            // never removing tracks.
+            TrackInfo *info = &mTracks.editItemAt(trackIndex);
+
+            sp<AnotherPacketSource> source = info->mSource;
+            if (source != NULL) {
+                uint32_t rtpTime;
+                CHECK(accessUnit->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
+
+                /* AnotherPacketSource make an assertion if there is no ntp provided
+                   RTPSource should provide ntpUs all the times.
+                if (!info->mNPTMappingValid) {
+                    // This is a live stream, we didn't receive any normal
+                    // playtime mapping. We won't map to npt time.
+                    source->queueAccessUnit(accessUnit);
+                    break;
+                }
+
+                int64_t nptUs =
+                    ((double)rtpTime - (double)info->mRTPTime)
+                        / info->mTimeScale
+                        * 1000000ll
+                        + info->mNormalPlaytimeUs;
+
+                */
+                accessUnit->meta()->setInt64("timeUs", ALooper::GetNowUs());
+
+                source->queueAccessUnit(accessUnit);
+            }
+
+            break;
+        }
+        case kWhatDisconnect:
+        {
+            sp<AReplyToken> replyID;
+            CHECK(msg->senderAwaitsResponse(&replyID));
+
+            for (size_t i = 0; i < mTracks.size(); ++i) {
+                TrackInfo *info = &mTracks.editItemAt(i);
+
+                if (info->mIsAudio) {
+                    mAudioTrack->signalEOS(ERROR_END_OF_STREAM);
+                    mAudioTrack = NULL;
+                    ALOGV("mAudioTrack disconnected");
+                } else {
+                    mVideoTrack->signalEOS(ERROR_END_OF_STREAM);
+                    mVideoTrack = NULL;
+                    ALOGV("mVideoTrack disconnected");
+                }
+
+                mRTPConn->removeStream(info->mRTPSocket, info->mRTCPSocket);
+                close(info->mRTPSocket);
+                close(info->mRTCPSocket);
+            }
+
+            mTracks.clear();
+            mFirstAccessUnit = true;
+            mAllTracksHaveTime = false;
+            mNTPAnchorUs = -1;
+            mMediaAnchorUs = -1;
+            mLastMediaTimeUs = -1;
+            mNumAccessUnitsReceived = 0;
+            mReceivedFirstRTCPPacket = false;
+            mReceivedFirstRTPPacket = false;
+            mPausing = false;
+            mPauseGeneration = 0;
+
+            (new AMessage)->postReply(replyID);
+
+            break;
+        }
+        case kWhatPollBuffering:
+            break;
+        default:
+            TRESPASS();
+    }
+}
+
+void NuPlayer::RTPSource::setTargetBitrate(int32_t bitrate) {
+    mRTPConn->setTargetBitrate(bitrate);
+}
+
+void NuPlayer::RTPSource::onTimeUpdate(int32_t trackIndex, uint32_t rtpTime, uint64_t ntpTime) {
+    ALOGV("onTimeUpdate track %d, rtpTime = 0x%08x, ntpTime = %#016llx",
+         trackIndex, rtpTime, (long long)ntpTime);
+
+    // convert ntpTime in Q32 seconds to microseconds. Note: this will not lose precision
+    // because ntpTimeUs is at most 52 bits (double holds 53 bits)
+    int64_t ntpTimeUs = (int64_t)(ntpTime * 1E6 / (1ll << 32));
+
+    TrackInfo *track = &mTracks.editItemAt(trackIndex);
+
+    track->mRTPAnchor = rtpTime;
+    track->mNTPAnchorUs = ntpTimeUs;
+
+    if (mNTPAnchorUs < 0) {
+        mNTPAnchorUs = ntpTimeUs;
+        mMediaAnchorUs = mLastMediaTimeUs;
+    }
+
+    if (!mAllTracksHaveTime) {
+        bool allTracksHaveTime = (mTracks.size() > 0);
+        for (size_t i = 0; i < mTracks.size(); ++i) {
+            TrackInfo *track = &mTracks.editItemAt(i);
+            if (track->mNTPAnchorUs < 0) {
+                allTracksHaveTime = false;
+                break;
+            }
+        }
+        if (allTracksHaveTime) {
+            mAllTracksHaveTime = true;
+            ALOGI("Time now established for all tracks.");
+        }
+    }
+    if (mAllTracksHaveTime && dataReceivedOnAllChannels()) {
+        // Time is now established, lets start timestamping immediately
+        for (size_t i = 0; i < mTracks.size(); ++i) {
+            TrackInfo *trackInfo = &mTracks.editItemAt(i);
+            while (!trackInfo->mPackets.empty()) {
+                sp<ABuffer> accessUnit = *trackInfo->mPackets.begin();
+                trackInfo->mPackets.erase(trackInfo->mPackets.begin());
+
+                if (addMediaTimestamp(i, trackInfo, accessUnit)) {
+                    postQueueAccessUnit(i, accessUnit);
+                }
+            }
+        }
+    }
+}
+
+bool NuPlayer::RTPSource::addMediaTimestamp(
+        int32_t trackIndex, const TrackInfo *track,
+        const sp<ABuffer> &accessUnit) {
+
+    uint32_t rtpTime;
+    CHECK(accessUnit->meta()->findInt32(
+                "rtp-time", (int32_t *)&rtpTime));
+
+    int64_t relRtpTimeUs =
+        (((int64_t)rtpTime - (int64_t)track->mRTPAnchor) * 1000000ll)
+        / track->mTimeScale;
+
+    int64_t ntpTimeUs = track->mNTPAnchorUs + relRtpTimeUs;
+
+    int64_t mediaTimeUs = mMediaAnchorUs + ntpTimeUs - mNTPAnchorUs;
+
+    if (mediaTimeUs > mLastMediaTimeUs) {
+        mLastMediaTimeUs = mediaTimeUs;
+    }
+
+    if (mediaTimeUs < 0) {
+        ALOGV("dropping early accessUnit.");
+        return false;
+    }
+
+    ALOGV("track %d rtpTime=%u mediaTimeUs = %lld us (%.2f secs)",
+            trackIndex, rtpTime, (long long)mediaTimeUs, mediaTimeUs / 1E6);
+
+    accessUnit->meta()->setInt64("timeUs", mediaTimeUs);
+
+    return true;
+}
+
+bool NuPlayer::RTPSource::dataReceivedOnAllChannels() {
+    TrackInfo *track;
+    for (size_t i = 0; i < mTracks.size(); ++i) {
+        track = &mTracks.editItemAt(i);
+        if (track->mPackets.empty()) {
+            return false;
+        }
+    }
+    return true;
+}
+
+void NuPlayer::RTPSource::postQueueAccessUnit(
+        size_t trackIndex, const sp<ABuffer> &accessUnit) {
+    sp<AMessage> msg = new AMessage(kWhatAccessUnit, this);
+    msg->setInt32("what", kWhatAccessUnit);
+    msg->setSize("trackIndex", trackIndex);
+    msg->setBuffer("accessUnit", accessUnit);
+    msg->post();
+}
+
+void NuPlayer::RTPSource::postQueueEOS(size_t trackIndex, status_t finalResult) {
+    sp<AMessage> msg = new AMessage(kWhatEOS, this);
+    msg->setInt32("what", kWhatEOS);
+    msg->setSize("trackIndex", trackIndex);
+    msg->setInt32("finalResult", finalResult);
+    msg->post();
+}
+
+sp<MetaData> NuPlayer::RTPSource::getTrackFormat(size_t index, int32_t *timeScale) {
+    CHECK_GE(index, 0u);
+    CHECK_LT(index, mTracks.size());
+
+    const TrackInfo &info = mTracks.itemAt(index);
+
+    *timeScale = info.mTimeScale;
+
+    return info.mPacketSource->getFormat();
+}
+
+void NuPlayer::RTPSource::onConnected() {
+    ALOGV("onConnected");
+    mState = CONNECTED;
+}
+
+void NuPlayer::RTPSource::onDisconnected(const sp<AMessage> &msg) {
+    if (mState == DISCONNECTED) {
+        return;
+    }
+
+    status_t err;
+    CHECK(msg->findInt32("result", &err));
+    CHECK_NE(err, (status_t)OK);
+
+//    mLooper->unregisterHandler(mHandler->id());
+//    mHandler.clear();
+
+    if (mState == CONNECTING) {
+        // We're still in the preparation phase, signal that it
+        // failed.
+        notifyPrepared(err);
+    }
+
+    mState = DISCONNECTED;
+//    setError(err);
+
+}
+
+status_t NuPlayer::RTPSource::setParameter(const String8 &key, const String8 &value) {
+    ALOGV("setParameter: key (%s) => value (%s)", key.string(), value.string());
+
+    bool isAudioKey = key.contains("audio");
+    TrackInfo *info = NULL;
+    for (unsigned i = 0; i < mTracks.size(); ++i) {
+        info = &mTracks.editItemAt(i);
+        if (info != NULL && info->mIsAudio == isAudioKey) {
+            ALOGV("setParameter: %s track (%d) found", isAudioKey ? "audio" : "video" , i);
+            break;
+        }
+    }
+
+    if (info == NULL) {
+        TrackInfo newTrackInfo;
+        newTrackInfo.mIsAudio = isAudioKey;
+        mTracks.push(newTrackInfo);
+        info = &mTracks.editTop();
+        info->mJbTimeMs = 300;
+    }
+
+    if (key == "rtp-param-mime-type") {
+        info->mMimeType = value;
+
+        const char *mime = value.string();
+        const char *delimiter = strchr(mime, '/');
+        info->mCodecName = delimiter ? (delimiter + 1) : "<none>";
+
+        ALOGV("rtp-param-mime-type: mMimeType (%s) => mCodecName (%s)",
+                info->mMimeType.string(), info->mCodecName.string());
+    } else if (key == "video-param-decoder-profile") {
+        info->mCodecProfile = atoi(value);
+    } else if (key == "video-param-decoder-level") {
+        info->mCodecLevel = atoi(value);
+    } else if (key == "video-param-width") {
+        info->mWidth = atoi(value);
+    } else if (key == "video-param-height") {
+        info->mHeight = atoi(value);
+    } else if (key == "rtp-param-local-ip") {
+        info->mLocalIp = value;
+    } else if (key == "rtp-param-local-port") {
+        info->mLocalPort = atoi(value);
+    } else if (key == "rtp-param-remote-ip") {
+        info->mRemoteIp = value;
+    } else if (key == "rtp-param-remote-port") {
+        info->mRemotePort = atoi(value);
+    } else if (key == "rtp-param-payload-type") {
+        info->mPayloadType = atoi(value);
+    } else if (key == "rtp-param-as") {
+        //AS means guaranteed bit rate that negotiated from sdp.
+        info->mAS = atoi(value);
+    } else if (key == "rtp-param-rtp-timeout") {
+    } else if (key == "rtp-param-rtcp-timeout") {
+    } else if (key == "rtp-param-time-scale") {
+    } else if (key == "rtp-param-self-id") {
+        info->mSelfID = atoi(value);
+    } else if (key == "rtp-param-ext-cvo-extmap") {
+        info->mCVOExtMap = atoi(value);
+    } else if (key == "rtp-param-set-socket-network") {
+        int64_t networkHandle = atoll(value);
+        setSocketNetwork(networkHandle);
+    } else if (key == "rtp-param-jitter-buffer-time") {
+        info->mJbTimeMs = atoi(value);
+    }
+
+    return OK;
+}
+
+status_t NuPlayer::RTPSource::setParameters(const String8 &params) {
+    ALOGV("setParameters: %s", params.string());
+    const char *cparams = params.string();
+    const char *key_start = cparams;
+    for (;;) {
+        const char *equal_pos = strchr(key_start, '=');
+        if (equal_pos == NULL) {
+            ALOGE("Parameters %s miss a value", cparams);
+            return BAD_VALUE;
+        }
+        String8 key(key_start, equal_pos - key_start);
+        TrimString(&key);
+        if (key.length() == 0) {
+            ALOGE("Parameters %s contains an empty key", cparams);
+            return BAD_VALUE;
+        }
+        const char *value_start = equal_pos + 1;
+        const char *semicolon_pos = strchr(value_start, ';');
+        String8 value;
+        if (semicolon_pos == NULL) {
+            value.setTo(value_start);
+        } else {
+            value.setTo(value_start, semicolon_pos - value_start);
+        }
+        if (setParameter(key, value) != OK) {
+            return BAD_VALUE;
+        }
+        if (semicolon_pos == NULL) {
+            break;  // Reaches the end
+        }
+        key_start = semicolon_pos + 1;
+    }
+    return OK;
+}
+
+void NuPlayer::RTPSource::setSocketNetwork(int64_t networkHandle) {
+    ALOGV("setSocketNetwork: %llu", (unsigned long long)networkHandle);
+
+    TrackInfo *info = NULL;
+    for (size_t i = 0; i < mTracks.size(); ++i) {
+        info = &mTracks.editItemAt(i);
+
+        if (info == NULL)
+            break;
+
+        info->mSocketNetwork = networkHandle;
+    }
+}
+
+// Trim both leading and trailing whitespace from the given string.
+//static
+void NuPlayer::RTPSource::TrimString(String8 *s) {
+    size_t num_bytes = s->bytes();
+    const char *data = s->string();
+
+    size_t leading_space = 0;
+    while (leading_space < num_bytes && isspace(data[leading_space])) {
+        ++leading_space;
+    }
+
+    size_t i = num_bytes;
+    while (i > leading_space && isspace(data[i - 1])) {
+        --i;
+    }
+
+    s->setTo(String8(&data[leading_space], i - leading_space));
+}
+
+}  // namespace android
diff --git a/media/libmediaplayerservice/nuplayer/RTPSource.h b/media/libmediaplayerservice/nuplayer/RTPSource.h
new file mode 100644
index 0000000..3b4f9e9
--- /dev/null
+++ b/media/libmediaplayerservice/nuplayer/RTPSource.h
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef RTP_SOURCE_H_
+
+#define RTP_SOURCE_H_
+
+#include <media/stagefright/foundation/ABase.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/foundation/AMessage.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/Utils.h>
+#include <media/BufferingSettings.h>
+
+#include <utils/KeyedVector.h>
+#include <utils/Vector.h>
+#include <utils/RefBase.h>
+
+#include "AnotherPacketSource.h"
+#include "APacketSource.h"
+#include "ARTPConnection.h"
+#include "ARTPSource.h"
+#include "ASessionDescription.h"
+#include "NuPlayerSource.h"
+
+
+
+
+
+
+namespace android {
+
+struct ALooper;
+struct AnotherPacketSource;
+
+struct NuPlayer::RTPSource : public NuPlayer::Source {
+    RTPSource(
+            const sp<AMessage> &notify,
+            const String8& rtpParams);
+
+    virtual status_t getBufferingSettings(
+            BufferingSettings* buffering /* nonnull */) override;
+    virtual status_t setBufferingSettings(const BufferingSettings& buffering) override;
+
+    virtual void prepareAsync();
+    virtual void start();
+    virtual void stop();
+    virtual void pause();
+    virtual void resume();
+
+    virtual status_t feedMoreTSData();
+
+    virtual status_t dequeueAccessUnit(bool audio, sp<ABuffer> *accessUnit);
+
+    virtual status_t getDuration(int64_t *durationUs);
+    virtual status_t seekTo(
+            int64_t seekTimeUs,
+            MediaPlayerSeekMode mode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC) override;
+
+    virtual bool isRealTime() const;
+
+    void onMessageReceived(const sp<AMessage> &msg);
+
+    virtual void setTargetBitrate(int32_t bitrate) override;
+
+protected:
+    virtual ~RTPSource();
+
+    virtual sp<MetaData> getFormatMeta(bool audio);
+
+private:
+    enum {
+        kWhatAccessUnit = 'accU',
+        kWhatAccessUnitComplete = 'accu',
+        kWhatDisconnect = 'disc',
+        kWhatEOS = 'eos!',
+        kWhatPollBuffering = 'poll',
+        kWhatSetBufferingSettings = 'sBuS',
+    };
+
+    const int64_t kBufferingPollIntervalUs = 1000000ll;
+
+    enum State {
+        DISCONNECTED,
+        CONNECTING,
+        CONNECTED,
+        PAUSED,
+    };
+
+    struct TrackInfo {
+
+        /* SDP of track */
+        bool mIsAudio;
+        int32_t mPayloadType;
+        String8 mMimeType;
+        String8 mCodecName;
+        int32_t mCodecProfile;
+        int32_t mCodecLevel;
+        int32_t mWidth;
+        int32_t mHeight;
+        String8 mLocalIp;
+        String8 mRemoteIp;
+        int32_t mLocalPort;
+        int32_t mRemotePort;
+        int64_t mSocketNetwork;
+        int32_t mTimeScale;
+        int32_t mAS;
+
+        /* RTP jitter buffer time in milliseconds */
+        uint32_t mJbTimeMs;
+        /* Unique ID indicates itself */
+        uint32_t mSelfID;
+        /* extmap:<value> for CVO will be set to here */
+        int32_t mCVOExtMap;
+
+        /* a copy of TrackInfo in RTSPSource */
+        sp<AnotherPacketSource> mSource;
+        uint32_t mRTPTime;
+        int64_t mNormalPlaytimeUs;
+        bool mNPTMappingValid;
+
+        /* a copy of TrackInfo in MyHandler.h */
+        int mRTPSocket;
+        int mRTCPSocket;
+        uint32_t mFirstSeqNumInSegment;
+        bool mNewSegment;
+        int32_t mAllowedStaleAccessUnits;
+        uint32_t mRTPAnchor;
+        int64_t mNTPAnchorUs;
+        bool mEOSReceived;
+        uint32_t mNormalPlayTimeRTP;
+        int64_t mNormalPlayTimeUs;
+        sp<APacketSource> mPacketSource;
+        List<sp<ABuffer>> mPackets;
+    };
+
+    const String8 mRTPParams;
+    uint32_t mFlags;
+    State mState;
+    status_t mFinalResult;
+
+    // below 3 parameters need to be checked whether it needed or not.
+    Mutex mBufferingLock;
+    bool mBuffering;
+    bool mInPreparationPhase;
+    Mutex mBufferingSettingsLock;
+    BufferingSettings mBufferingSettings;
+
+    sp<ALooper> mLooper;
+
+    sp<ARTPConnection> mRTPConn;
+
+    Vector<TrackInfo> mTracks;
+    sp<AnotherPacketSource> mAudioTrack;
+    sp<AnotherPacketSource> mVideoTrack;
+
+    int64_t mEOSTimeoutAudio;
+    int64_t mEOSTimeoutVideo;
+
+    /* MyHandler.h */
+    bool mFirstAccessUnit;
+    bool mAllTracksHaveTime;
+    int64_t mNTPAnchorUs;
+    int64_t mMediaAnchorUs;
+    int64_t mLastMediaTimeUs;
+    int64_t mNumAccessUnitsReceived;
+    int32_t mLastCVOUpdated;
+    bool mReceivedFirstRTCPPacket;
+    bool mReceivedFirstRTPPacket;
+    bool mPausing;
+    int32_t mPauseGeneration;
+
+    sp<AnotherPacketSource> getSource(bool audio);
+
+    /* MyHandler.h */
+    void onTimeUpdate(int32_t trackIndex, uint32_t rtpTime, uint64_t ntpTime);
+    bool addMediaTimestamp(int32_t trackIndex, const TrackInfo *track,
+            const sp<ABuffer> &accessUnit);
+    bool dataReceivedOnAllChannels();
+    void postQueueAccessUnit(size_t trackIndex, const sp<ABuffer> &accessUnit);
+    void postQueueEOS(size_t trackIndex, status_t finalResult);
+    sp<MetaData> getTrackFormat(size_t index, int32_t *timeScale);
+    void onConnected();
+    void onDisconnected(const sp<AMessage> &msg);
+
+    void schedulePollBuffering();
+    void onPollBuffering();
+
+    bool haveSufficientDataOnAllTracks();
+
+    void setEOSTimeout(bool audio, int64_t timeout);
+
+    status_t setParameters(const String8 &params);
+    status_t setParameter(const String8 &key, const String8 &value);
+    void setSocketNetwork(int64_t networkHandle);
+    static void TrimString(String8 *s);
+
+    DISALLOW_EVIL_CONSTRUCTORS(RTPSource);
+};
+
+}  // namespace android
+
+#endif  // RTP_SOURCE_H_
diff --git a/media/libmediaplayerservice/tests/Android.bp b/media/libmediaplayerservice/tests/Android.bp
index e845c33..98626fd 100644
--- a/media/libmediaplayerservice/tests/Android.bp
+++ b/media/libmediaplayerservice/tests/Android.bp
@@ -1,3 +1,14 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libmediaplayerservice_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libmediaplayerservice_license",
+    ],
+}
+
 cc_test {
 
     name: "DrmSessionManager_test",
diff --git a/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp b/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp
new file mode 100644
index 0000000..b84d64b
--- /dev/null
+++ b/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2020 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 {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libmediaplayerservice_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libmediaplayerservice_license",
+    ],
+}
+
+cc_test {
+    name: "StagefrightRecorderTest",
+    gtest: true,
+
+    srcs: [
+        "StagefrightRecorderTest.cpp",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libmediaplayerservice",
+    ],
+
+    static_libs: [
+        "libmediaplayerservice",
+        "libstagefright_httplive",
+        "libstagefright_rtsp",
+    ],
+
+    shared_libs: [
+        "android.hardware.media.c2@1.0",
+        "android.hardware.media.omx@1.0",
+        "libbase",
+        "libandroid_net",
+        "libaudioclient",
+        "libbinder",
+        "libcamera_client",
+        "libcodec2_client",
+        "libcrypto",
+        "libcutils",
+        "libdatasource",
+        "libdl",
+        "libdrmframework",
+        "libgui",
+        "libhidlbase",
+        "liblog",
+        "libmedia",
+        "libmedia_codeclist",
+        "libmedia_omx",
+        "libmediadrm",
+        "libmediandk",
+        "libmediametrics",
+        "libmediautils",
+        "libmemunreachable",
+        "libnetd_client",
+        "libpowermanager",
+        "libstagefright",
+        "libstagefright_foundation",
+        "libutils",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+    },
+}
diff --git a/media/libmediaplayerservice/tests/stagefrightRecorder/AndroidTest.xml b/media/libmediaplayerservice/tests/stagefrightRecorder/AndroidTest.xml
new file mode 100644
index 0000000..427026d
--- /dev/null
+++ b/media/libmediaplayerservice/tests/stagefrightRecorder/AndroidTest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2021 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.
+-->
+<configuration description="Test module config for StagefrightRecorder unit tests">
+    <option name="test-suite-tag" value="StagefrightRecorderTest" />
+    <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer">
+        <option name="force-root" value="true" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push"
+                value="StagefrightRecorderTest->/data/local/tmp/StagefrightRecorderTest" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="StagefrightRecorderTest" />
+    </test>
+</configuration>
diff --git a/media/libmediaplayerservice/tests/stagefrightRecorder/StagefrightRecorderTest.cpp b/media/libmediaplayerservice/tests/stagefrightRecorder/StagefrightRecorderTest.cpp
new file mode 100644
index 0000000..5751631
--- /dev/null
+++ b/media/libmediaplayerservice/tests/stagefrightRecorder/StagefrightRecorderTest.cpp
@@ -0,0 +1,318 @@
+/*
+ * Copyright (C) 2020 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 "StagefrightRecorderTest"
+#include <utils/Log.h>
+
+#include <gtest/gtest.h>
+
+#include <chrono>
+#include <ctime>
+#include <iostream>
+#include <string>
+#include <thread>
+
+#include <MediaPlayerService.h>
+#include <media/NdkMediaExtractor.h>
+#include <media/stagefright/MediaCodec.h>
+#include <system/audio.h>
+
+#include "StagefrightRecorder.h"
+
+#define OUTPUT_INFO_FILE_NAME "/data/local/tmp/stfrecorder_audio.info"
+#define OUTPUT_FILE_NAME_AUDIO "/data/local/tmp/stfrecorder_audio.raw"
+
+const bool kDebug = false;
+constexpr int32_t kMaxLoopCount = 10;
+constexpr int32_t kClipDurationInSec = 4;
+constexpr int32_t kPauseTimeInSec = 2;
+// Tolerance value for extracted clipduration is maximum 10% of total clipduration
+constexpr int32_t kToleranceValueInUs = kClipDurationInSec * 100000;
+
+using namespace android;
+
+class StagefrightRecorderTest
+    : public ::testing::TestWithParam<std::pair<output_format, audio_encoder>> {
+  public:
+    StagefrightRecorderTest() : mStfRecorder(nullptr), mOutputAudioFp(nullptr) {
+        mExpectedDurationInMs = 0;
+        mExpectedPauseInMs = 0;
+    }
+
+    ~StagefrightRecorderTest() {
+        if (mStfRecorder) free(mStfRecorder);
+        if (mOutputAudioFp) fclose(mOutputAudioFp);
+    }
+
+    void SetUp() override {
+        mStfRecorder = new StagefrightRecorder(String16(LOG_TAG));
+        ASSERT_NE(mStfRecorder, nullptr) << "Failed to create the instance of recorder";
+
+        mOutputAudioFp = fopen(OUTPUT_FILE_NAME_AUDIO, "wb");
+        ASSERT_NE(mOutputAudioFp, nullptr) << "Failed to open output file "
+                                           << OUTPUT_FILE_NAME_AUDIO << " for stagefright recorder";
+
+        int32_t fd = fileno(mOutputAudioFp);
+        ASSERT_GE(fd, 0) << "Failed to get the file descriptor of the output file for "
+                         << OUTPUT_FILE_NAME_AUDIO;
+
+        status_t status = mStfRecorder->setOutputFile(fd);
+        ASSERT_EQ(status, OK) << "Failed to set the output file " << OUTPUT_FILE_NAME_AUDIO
+                              << " for stagefright recorder";
+    }
+
+    void TearDown() override {
+        if (mOutputAudioFp) {
+            fclose(mOutputAudioFp);
+            mOutputAudioFp = nullptr;
+        }
+        if (!kDebug) {
+            int32_t status = remove(OUTPUT_FILE_NAME_AUDIO);
+            ASSERT_EQ(status, 0) << "Unable to delete the output file " << OUTPUT_FILE_NAME_AUDIO;
+        }
+    }
+
+    void setAudioRecorderFormat(output_format outputFormat, audio_encoder encoder,
+                                audio_source_t audioSource = AUDIO_SOURCE_DEFAULT);
+    void recordMedia(bool isPaused = false, int32_t numStart = 0, int32_t numPause = 0);
+    void dumpInfo();
+    void setupExtractor(AMediaExtractor *extractor, int32_t &trackCount);
+    void validateOutput();
+
+    MediaRecorderBase *mStfRecorder;
+    FILE *mOutputAudioFp;
+    double mExpectedDurationInMs;
+    double mExpectedPauseInMs;
+};
+
+void StagefrightRecorderTest::setAudioRecorderFormat(output_format outputFormat,
+                                                     audio_encoder encoder,
+                                                     audio_source_t audioSource) {
+    status_t status = mStfRecorder->setAudioSource(audioSource);
+    ASSERT_EQ(status, OK) << "Failed to set the audio source: " << audioSource;
+
+    status = mStfRecorder->setOutputFormat(outputFormat);
+    ASSERT_EQ(status, OK) << "Failed to set the output format: " << outputFormat;
+
+    status = mStfRecorder->setAudioEncoder(encoder);
+    ASSERT_EQ(status, OK) << "Failed to set the audio encoder: " << encoder;
+}
+
+void StagefrightRecorderTest::recordMedia(bool isPause, int32_t numStart, int32_t numPause) {
+    status_t status = mStfRecorder->init();
+    ASSERT_EQ(status, OK) << "Failed to initialize stagefright recorder";
+
+    status = mStfRecorder->prepare();
+    ASSERT_EQ(status, OK) << "Failed to preapre the reorder";
+
+    // first start should succeed.
+    status = mStfRecorder->start();
+    ASSERT_EQ(status, OK) << "Failed to start the recorder";
+
+    for (int32_t count = 0; count < numStart; count++) {
+        status = mStfRecorder->start();
+    }
+
+    auto tStart = std::chrono::high_resolution_clock::now();
+    // Recording media for 4 secs
+    std::this_thread::sleep_for(std::chrono::seconds(kClipDurationInSec));
+    auto tEnd = std::chrono::high_resolution_clock::now();
+    mExpectedDurationInMs = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
+
+    if (isPause) {
+        // first pause should succeed.
+        status = mStfRecorder->pause();
+        ASSERT_EQ(status, OK) << "Failed to pause the recorder";
+
+        tStart = std::chrono::high_resolution_clock::now();
+        // Paused recorder for 2 secs
+        std::this_thread::sleep_for(std::chrono::seconds(kPauseTimeInSec));
+
+        for (int32_t count = 0; count < numPause; count++) {
+            status = mStfRecorder->pause();
+        }
+
+        tEnd = std::chrono::high_resolution_clock::now();
+        mExpectedPauseInMs = std::chrono::duration<double, std::milli>(tEnd - tStart).count();
+
+        status = mStfRecorder->resume();
+        ASSERT_EQ(status, OK) << "Failed to resume the recorder";
+
+        auto tStart = std::chrono::high_resolution_clock::now();
+        // Recording media for 4 secs
+        std::this_thread::sleep_for(std::chrono::seconds(kClipDurationInSec));
+        auto tEnd = std::chrono::high_resolution_clock::now();
+        mExpectedDurationInMs += std::chrono::duration<double, std::milli>(tEnd - tStart).count();
+    }
+    status = mStfRecorder->stop();
+    ASSERT_EQ(status, OK) << "Failed to stop the recorder";
+}
+
+void StagefrightRecorderTest::dumpInfo() {
+    FILE *dumpOutput = fopen(OUTPUT_INFO_FILE_NAME, "wb");
+    int32_t dumpFd = fileno(dumpOutput);
+    Vector<String16> args;
+    status_t status = mStfRecorder->dump(dumpFd, args);
+    ASSERT_EQ(status, OK) << "Failed to dump the info for the recorder";
+    fclose(dumpOutput);
+}
+
+void StagefrightRecorderTest::setupExtractor(AMediaExtractor *extractor, int32_t &trackCount) {
+    int32_t fd = open(OUTPUT_FILE_NAME_AUDIO, O_RDONLY);
+    ASSERT_GE(fd, 0) << "Failed to open recorder's output file " << OUTPUT_FILE_NAME_AUDIO
+                     << " to validate";
+
+    struct stat buf;
+    int32_t status = fstat(fd, &buf);
+    ASSERT_EQ(status, 0) << "Failed to get properties of input file " << OUTPUT_FILE_NAME_AUDIO
+                         << " for extractor";
+
+    size_t fileSize = buf.st_size;
+    ASSERT_GT(fileSize, 0) << "Size of input file " << OUTPUT_FILE_NAME_AUDIO
+                           << " to extractor cannot be zero";
+    ALOGV("Size of input file to extractor: %zu", fileSize);
+
+    status = AMediaExtractor_setDataSourceFd(extractor, fd, 0, fileSize);
+    ASSERT_EQ(status, AMEDIA_OK) << "Failed to set data source for extractor";
+
+    trackCount = AMediaExtractor_getTrackCount(extractor);
+    ALOGV("Number of tracks reported by extractor : %d", trackCount);
+}
+
+// Validate recoder's output using extractor
+void StagefrightRecorderTest::validateOutput() {
+    int32_t trackCount = -1;
+    AMediaExtractor *extractor = AMediaExtractor_new();
+    ASSERT_NE(extractor, nullptr) << "Failed to create extractor";
+    ASSERT_NO_FATAL_FAILURE(setupExtractor(extractor, trackCount));
+    ASSERT_EQ(trackCount, 1) << "Expected 1 track, saw " << trackCount;
+
+    for (int32_t idx = 0; idx < trackCount; idx++) {
+        AMediaExtractor_selectTrack(extractor, idx);
+        AMediaFormat *format = AMediaExtractor_getTrackFormat(extractor, idx);
+        ASSERT_NE(format, nullptr) << "Track format is NULL";
+        ALOGI("Track format = %s", AMediaFormat_toString(format));
+
+        int64_t clipDurationUs;
+        AMediaFormat_getInt64(format, AMEDIAFORMAT_KEY_DURATION, &clipDurationUs);
+        int32_t diff = abs((mExpectedDurationInMs * 1000) - clipDurationUs);
+        ASSERT_LE(diff, kToleranceValueInUs)
+                << "Expected duration: " << (mExpectedDurationInMs * 1000)
+                << " Actual duration: " << clipDurationUs << " Difference: " << diff
+                << " Difference is expected to be less than tolerance value: " << kToleranceValueInUs;
+
+        const char *mime = nullptr;
+        AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime);
+        ASSERT_NE(mime, nullptr) << "Track mime is NULL";
+        ALOGI("Track mime = %s", mime);
+
+        int32_t sampleRate, channelCount, bitRate;
+        AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, &channelCount);
+        ALOGI("Channel count reported by extractor: %d", channelCount);
+        AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, &sampleRate);
+        ALOGI("Sample Rate reported by extractor: %d", sampleRate);
+        AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_BIT_RATE, &bitRate);
+        ALOGI("Bit Rate reported by extractor: %d", bitRate);
+    }
+}
+
+TEST_F(StagefrightRecorderTest, RecordingAudioSanityTest) {
+    ASSERT_NO_FATAL_FAILURE(setAudioRecorderFormat(OUTPUT_FORMAT_DEFAULT, AUDIO_ENCODER_DEFAULT));
+
+    int32_t maxAmplitude = -1;
+    status_t status = mStfRecorder->getMaxAmplitude(&maxAmplitude);
+    ASSERT_EQ(maxAmplitude, 0) << "Invalid value of max amplitude";
+
+    ASSERT_NO_FATAL_FAILURE(recordMedia());
+
+    // Verify getMetrics() behavior
+    Parcel parcel;
+    status = mStfRecorder->getMetrics(&parcel);
+    ASSERT_EQ(status, OK) << "Failed to get the parcel from getMetrics";
+    ALOGV("Size of the Parcel returned by getMetrics: %zu", parcel.dataSize());
+    ASSERT_GT(parcel.dataSize(), 0) << "Parcel size reports empty record";
+    ASSERT_NO_FATAL_FAILURE(validateOutput());
+    if (kDebug) {
+        ASSERT_NO_FATAL_FAILURE(dumpInfo());
+    }
+}
+
+TEST_P(StagefrightRecorderTest, MultiFormatAudioRecordTest) {
+    output_format outputFormat = GetParam().first;
+    audio_encoder audioEncoder = GetParam().second;
+    ASSERT_NO_FATAL_FAILURE(setAudioRecorderFormat(outputFormat, audioEncoder));
+    ASSERT_NO_FATAL_FAILURE(recordMedia());
+    // TODO(b/161687761)
+    // Skip for AMR-NB/WB output format
+    if (!(outputFormat == OUTPUT_FORMAT_AMR_NB || outputFormat == OUTPUT_FORMAT_AMR_WB)) {
+        ASSERT_NO_FATAL_FAILURE(validateOutput());
+    }
+    if (kDebug) {
+        ASSERT_NO_FATAL_FAILURE(dumpInfo());
+    }
+}
+
+TEST_F(StagefrightRecorderTest, GetActiveMicrophonesTest) {
+    ASSERT_NO_FATAL_FAILURE(
+            setAudioRecorderFormat(OUTPUT_FORMAT_DEFAULT, AUDIO_ENCODER_DEFAULT, AUDIO_SOURCE_MIC));
+
+    status_t status = mStfRecorder->init();
+    ASSERT_EQ(status, OK) << "Init failed for stagefright recorder";
+
+    status = mStfRecorder->prepare();
+    ASSERT_EQ(status, OK) << "Failed to preapre the reorder";
+
+    status = mStfRecorder->start();
+    ASSERT_EQ(status, OK) << "Failed to start the recorder";
+
+    // Record media for 4 secs
+    std::this_thread::sleep_for(std::chrono::seconds(kClipDurationInSec));
+
+    std::vector<media::MicrophoneInfo> activeMicrophones{};
+    status = mStfRecorder->getActiveMicrophones(&activeMicrophones);
+    ASSERT_EQ(status, OK) << "Failed to get Active Microphones";
+    ASSERT_GT(activeMicrophones.size(), 0) << "No active microphones are found";
+
+    status = mStfRecorder->stop();
+    ASSERT_EQ(status, OK) << "Failed to stop the recorder";
+    if (kDebug) {
+        ASSERT_NO_FATAL_FAILURE(dumpInfo());
+    }
+}
+
+TEST_F(StagefrightRecorderTest, MultiStartPauseTest) {
+    ASSERT_NO_FATAL_FAILURE(setAudioRecorderFormat(OUTPUT_FORMAT_DEFAULT, AUDIO_ENCODER_DEFAULT));
+    ASSERT_NO_FATAL_FAILURE(recordMedia(true, kMaxLoopCount, kMaxLoopCount));
+    ASSERT_NO_FATAL_FAILURE(validateOutput());
+    if (kDebug) {
+        ASSERT_NO_FATAL_FAILURE(dumpInfo());
+    }
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        StagefrightRecorderTestAll, StagefrightRecorderTest,
+        ::testing::Values(std::make_pair(OUTPUT_FORMAT_AMR_NB, AUDIO_ENCODER_AMR_NB),
+                          std::make_pair(OUTPUT_FORMAT_AMR_WB, AUDIO_ENCODER_AMR_WB),
+                          std::make_pair(OUTPUT_FORMAT_AAC_ADTS, AUDIO_ENCODER_AAC),
+                          std::make_pair(OUTPUT_FORMAT_OGG, AUDIO_ENCODER_OPUS)));
+
+int main(int argc, char **argv) {
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = RUN_ALL_TESTS();
+    ALOGV("Test result = %d\n", status);
+    return status;
+}
diff --git a/media/libmediatranscoding/Android.bp b/media/libmediatranscoding/Android.bp
index f948bd8..9375e4e 100644
--- a/media/libmediatranscoding/Android.bp
+++ b/media/libmediatranscoding/Android.bp
@@ -15,6 +15,15 @@
  */
 
 // AIDL interfaces of MediaTranscoding.
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 aidl_interface {
     name: "mediatranscoding_aidl_interface",
     unstable: true,
diff --git a/media/libmediatranscoding/tests/Android.bp b/media/libmediatranscoding/tests/Android.bp
index 8191b00..17a43df 100644
--- a/media/libmediatranscoding/tests/Android.bp
+++ b/media/libmediatranscoding/tests/Android.bp
@@ -1,4 +1,13 @@
 // Build the unit tests for libmediatranscoding.
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "libmediatranscoding_test_defaults",
 
@@ -45,4 +54,4 @@
     defaults: ["libmediatranscoding_test_defaults"],
 
     srcs: ["AdjustableMaxPriorityQueue_tests.cpp"],
-}
\ No newline at end of file
+}
diff --git a/media/libnbaio/Android.bp b/media/libnbaio/Android.bp
index 04ddcff..e9422cc 100644
--- a/media/libnbaio/Android.bp
+++ b/media/libnbaio/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_defaults {
     name: "libnbaio_mono_defaults",
     srcs: [
diff --git a/media/libnbaio/include/media/nbaio/Pipe.h b/media/libnbaio/include/media/nbaio/Pipe.h
index 0431976..54dc08f 100644
--- a/media/libnbaio/include/media/nbaio/Pipe.h
+++ b/media/libnbaio/include/media/nbaio/Pipe.h
@@ -23,7 +23,7 @@
 namespace android {
 
 // Pipe is multi-thread safe for readers (see PipeReader), but safe for only a single writer thread.
-// It cannot UNDERRUN on write, unless we allow designation of a master reader that provides the
+// It cannot UNDERRUN on write, unless we allow designation of a primary reader that provides the
 // time-base. Readers can be added and removed dynamically, and it's OK to have no readers.
 class Pipe : public NBAIO_Sink {
 
diff --git a/media/libnblog/Android.bp b/media/libnblog/Android.bp
index 1188320..8cfece6 100644
--- a/media/libnblog/Android.bp
+++ b/media/libnblog/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
 
     name: "libnblog",
diff --git a/media/libnblog/ReportPerformance.cpp b/media/libnblog/ReportPerformance.cpp
index aa678ba..4c78b01 100644
--- a/media/libnblog/ReportPerformance.cpp
+++ b/media/libnblog/ReportPerformance.cpp
@@ -92,8 +92,8 @@
         (*dataJson)["threadNum"] = item.first;
         root.append(*dataJson);
     }
-    Json::StyledWriter writer;
-    std::string rootStr = writer.write(root);
+    Json::StreamWriterBuilder factory;
+    std::string rootStr = Json::writeString(factory, root);
     write(fd, rootStr.c_str(), rootStr.size());
 }
 
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index 8e480bf..71a4ad8 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -279,6 +279,13 @@
 
     void postFillThisBuffer(BufferInfo *info);
 
+    void maybePostExtraOutputMetadataBufferRequest() {
+        if (!mPendingExtraOutputMetadataBufferRequest) {
+            (new AMessage(kWhatSubmitExtraOutputMetadataBuffer, mCodec))->post();
+            mPendingExtraOutputMetadataBufferRequest = true;
+        }
+    }
+
 private:
     // Handles an OMX message. Returns true iff message was handled.
     bool onOMXMessage(const sp<AMessage> &msg);
@@ -302,6 +309,8 @@
 
     void getMoreInputDataIfPossible();
 
+    bool mPendingExtraOutputMetadataBufferRequest;
+
     DISALLOW_EVIL_CONSTRUCTORS(BaseState);
 };
 
@@ -555,6 +564,8 @@
       mShutdownInProgress(false),
       mExplicitShutdown(false),
       mIsLegacyVP9Decoder(false),
+      mIsStreamCorruptFree(false),
+      mIsLowLatency(false),
       mEncoderDelay(0),
       mEncoderPadding(0),
       mRotationDegrees(0),
@@ -887,7 +898,7 @@
 
             sp<DataConverter> converter = mConverter[portIndex];
             if (converter != NULL) {
-                // here we assume sane conversions of max 4:1, so result fits in int32
+                // here we assume conversions of max 4:1, so result fits in int32
                 if (portIndex == kPortIndexInput) {
                     conversionBufferSize = converter->sourceSize(bufSize);
                 } else {
@@ -2237,6 +2248,12 @@
             }
             err = setupG711Codec(encoder, sampleRate, numChannels);
         }
+    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_OPUS)) {
+        int32_t numChannels = 1, sampleRate = 48000;
+        if (msg->findInt32("channel-count", &numChannels) &&
+            msg->findInt32("sample-rate", &sampleRate)) {
+            err = setupOpusCodec(encoder, sampleRate, numChannels);
+        }
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_FLAC)) {
         // numChannels needs to be set to properly communicate PCM values.
         int32_t numChannels = 2, sampleRate = 44100, compressionLevel = -1;
@@ -2323,6 +2340,12 @@
         mChannelMaskPresent = false;
     }
 
+    int32_t isCorruptFree = 0;
+    if (msg->findInt32("corrupt-free", &isCorruptFree)) {
+        mIsStreamCorruptFree = isCorruptFree == 1 ? true : false;
+        ALOGV("corrupt-free=[%d]", mIsStreamCorruptFree);
+    }
+
     int32_t maxInputSize;
     if (msg->findInt32("max-input-size", &maxInputSize)) {
         err = setMinBufferSize(kPortIndexInput, (size_t)maxInputSize);
@@ -2409,6 +2432,7 @@
     if (err != OK) {
         ALOGE("decoder can not set low-latency to %d (err %d)", lowLatency, err);
     }
+    mIsLowLatency = (lowLatency && err == OK);
     return err;
 }
 
@@ -2602,15 +2626,15 @@
     unsigned int numLayers = 0;
     unsigned int numBLayers = 0;
     int tags;
-    char dummy;
+    char tmp;
     OMX_VIDEO_ANDROID_TEMPORALLAYERINGPATTERNTYPE pattern =
         OMX_VIDEO_AndroidTemporalLayeringPatternNone;
-    if (sscanf(tsSchema.c_str(), "webrtc.vp8.%u-layer%c", &numLayers, &dummy) == 1
+    if (sscanf(tsSchema.c_str(), "webrtc.vp8.%u-layer%c", &numLayers, &tmp) == 1
             && numLayers > 0) {
         pattern = OMX_VIDEO_AndroidTemporalLayeringPatternWebRTC;
     } else if ((tags = sscanf(tsSchema.c_str(), "android.generic.%u%c%u%c",
-                    &numLayers, &dummy, &numBLayers, &dummy))
-            && (tags == 1 || (tags == 3 && dummy == '+'))
+                    &numLayers, &tmp, &numBLayers, &tmp))
+            && (tags == 1 || (tags == 3 && tmp == '+'))
             && numLayers > 0 && numLayers < UINT32_MAX - numBLayers) {
         numLayers += numBLayers;
         pattern = OMX_VIDEO_AndroidTemporalLayeringPatternAndroid;
@@ -3110,6 +3134,26 @@
             kPortIndexInput, sampleRate, numChannels);
 }
 
+status_t ACodec::setupOpusCodec(bool encoder, int32_t sampleRate, int32_t numChannels) {
+    if (encoder) {
+        return INVALID_OPERATION;
+    }
+    OMX_AUDIO_PARAM_ANDROID_OPUSTYPE def;
+    InitOMXParams(&def);
+    def.nPortIndex = kPortIndexInput;
+    status_t err = mOMXNode->getParameter(
+            (OMX_INDEXTYPE)OMX_IndexParamAudioAndroidOpus, &def, sizeof(def));
+    if (err != OK) {
+        ALOGE("setupOpusCodec(): Error %d getting OMX_IndexParamAudioAndroidOpus parameter", err);
+        return err;
+    }
+    def.nSampleRate = sampleRate;
+    def.nChannels = numChannels;
+    err = mOMXNode->setParameter(
+           (OMX_INDEXTYPE)OMX_IndexParamAudioAndroidOpus, &def, sizeof(def));
+    return err;
+}
+
 status_t ACodec::setupFlacCodec(
         bool encoder, int32_t numChannels, int32_t sampleRate, int32_t compressionLevel,
         AudioEncoding encoding) {
@@ -4127,6 +4171,29 @@
         ALOGI("setupVideoEncoder succeeded");
     }
 
+    // Video should be encoded as stand straight because RTP protocol
+    // can provide rotation information only if CVO is supported.
+    // This needs to be added to support non-CVO case for video streaming scenario.
+    int32_t rotation = 0;
+    if (msg->findInt32("rotation-degrees", &rotation)) {
+        OMX_CONFIG_ROTATIONTYPE config;
+        InitOMXParams(&config);
+        config.nPortIndex = kPortIndexOutput;
+        status_t err = mOMXNode->getConfig(
+                (OMX_INDEXTYPE)OMX_IndexConfigCommonRotate, &config, sizeof(config));
+        if (err != OK) {
+            ALOGW("Failed to getConfig of OMX_IndexConfigCommonRotate(err %d)", err);
+        }
+        config.nRotation = rotation;
+        err = mOMXNode->setConfig(
+                (OMX_INDEXTYPE)OMX_IndexConfigCommonRotate, &config, sizeof(config));
+
+        ALOGD("Applying encoder-rotation=[%d] to video encoder.", config.nRotation);
+        if (err != OK) {
+            ALOGW("Failed to setConfig of OMX_IndexConfigCommonRotate(err %d)", err);
+        }
+    }
+
     return err;
 }
 
@@ -4757,15 +4824,15 @@
         unsigned int numLayers = 0;
         unsigned int numBLayers = 0;
         int tags;
-        char dummy;
-        if (sscanf(tsSchema.c_str(), "webrtc.vp8.%u-layer%c", &numLayers, &dummy) == 1
+        char tmp;
+        if (sscanf(tsSchema.c_str(), "webrtc.vp8.%u-layer%c", &numLayers, &tmp) == 1
                 && numLayers > 0) {
             pattern = OMX_VIDEO_VPXTemporalLayerPatternWebRTC;
             tsType = OMX_VIDEO_AndroidTemporalLayeringPatternWebRTC;
             tsLayers = numLayers;
         } else if ((tags = sscanf(tsSchema.c_str(), "android.generic.%u%c%u%c",
-                        &numLayers, &dummy, &numBLayers, &dummy))
-                && (tags == 1 || (tags == 3 && dummy == '+'))
+                        &numLayers, &tmp, &numBLayers, &tmp))
+                && (tags == 1 || (tags == 3 && tmp == '+'))
                 && numLayers > 0 && numLayers < UINT32_MAX - numBLayers) {
             pattern = OMX_VIDEO_VPXTemporalLayerPatternWebRTC;
             // VPX does not have a concept of B-frames, so just count all layers
@@ -5750,7 +5817,8 @@
 
 ACodec::BaseState::BaseState(ACodec *codec, const sp<AState> &parentState)
     : AState(parentState),
-      mCodec(codec) {
+      mCodec(codec),
+      mPendingExtraOutputMetadataBufferRequest(false) {
 }
 
 ACodec::BaseState::PortMode ACodec::BaseState::getPortMode(
@@ -5794,17 +5862,19 @@
 
         case ACodec::kWhatSetSurface:
         {
-            sp<AReplyToken> replyID;
-            CHECK(msg->senderAwaitsResponse(&replyID));
-
             sp<RefBase> obj;
             CHECK(msg->findObject("surface", &obj));
 
             status_t err = mCodec->handleSetSurface(static_cast<Surface *>(obj.get()));
 
-            sp<AMessage> response = new AMessage;
-            response->setInt32("err", err);
-            response->postReply(replyID);
+            sp<AReplyToken> replyID;
+            if (msg->senderAwaitsResponse(&replyID)) {
+                sp<AMessage> response = new AMessage;
+                response->setInt32("err", err);
+                response->postReply(replyID);
+            } else if (err != OK) {
+                mCodec->signalError(OMX_ErrorUndefined, err);
+            }
             break;
         }
 
@@ -5851,6 +5921,21 @@
             break;
         }
 
+        case kWhatSubmitExtraOutputMetadataBuffer: {
+            mPendingExtraOutputMetadataBufferRequest = false;
+            if (getPortMode(kPortIndexOutput) == RESUBMIT_BUFFERS && mCodec->mIsLowLatency) {
+                // Decoders often need more than one output buffer to be
+                // submitted before processing a single input buffer.
+                // For low latency codecs, we don't want to wait for more input
+                // to be queued to get those output buffers submitted.
+                if (mCodec->submitOutputMetadataBuffer() == OK
+                        && mCodec->mMetadataBuffersToSubmit > 0) {
+                    maybePostExtraOutputMetadataBufferRequest();
+                }
+            }
+            break;
+        }
+
         default:
             return false;
     }
@@ -6002,6 +6087,12 @@
         return false;
     }
 
+    if (mCodec->mIsStreamCorruptFree && data1 == (OMX_U32)OMX_ErrorStreamCorrupt) {
+        ALOGV("[%s] handle OMX_ErrorStreamCorrupt as a normal operation",
+                mCodec->mComponentName.c_str());
+        return true;
+    }
+
     ALOGE("[%s] ERROR(0x%08x)", mCodec->mComponentName.c_str(), data1);
 
     // verify OMX component sends back an error we expect.
@@ -6109,6 +6200,13 @@
         return;
     }
 
+    int32_t cvo;
+    if (mCodec->mNativeWindow != NULL && buffer != NULL &&
+            buffer->meta()->findInt32("cvo", &cvo)) {
+        ALOGV("cvo(%d) found in buffer #%u", cvo, bufferID);
+        setNativeWindowRotation(mCodec->mNativeWindow.get(), cvo);
+    }
+
     info->mStatus = BufferInfo::OWNED_BY_US;
     info->mData = buffer;
 
@@ -6207,7 +6305,12 @@
                             (outputMode == FREE_BUFFERS ? "FREE" :
                              outputMode == KEEP_BUFFERS ? "KEEP" : "RESUBMIT"));
                     if (outputMode == RESUBMIT_BUFFERS) {
-                        mCodec->submitOutputMetadataBuffer();
+                        status_t err = mCodec->submitOutputMetadataBuffer();
+                        if (mCodec->mIsLowLatency
+                                && err == OK
+                                && mCodec->mMetadataBuffersToSubmit > 0) {
+                            maybePostExtraOutputMetadataBufferRequest();
+                        }
                     }
                 }
                 info->checkReadFence("onInputBufferFilled");
@@ -6757,6 +6860,7 @@
     ALOGV("onAllocateComponent");
 
     CHECK(mCodec->mOMXNode == NULL);
+    mCodec->mFatalError = false;
 
     sp<AMessage> notify = new AMessage(kWhatOMXMessageList, mCodec);
     notify->setInt32("generation", mCodec->mNodeGeneration + 1);
@@ -7352,6 +7456,9 @@
                 break;
         }
     }
+    if (mCodec->mIsLowLatency) {
+        maybePostExtraOutputMetadataBufferRequest();
+    }
 
     // *** NOTE: THE FOLLOWING WORKAROUND WILL BE REMOVED ***
     mCodec->signalSubmitOutputMetadataBufferIfEOS_workaround();
@@ -7658,8 +7765,8 @@
         mInputFormat->setInt64("android._stop-time-offset-us", stopTimeOffsetUs);
     }
 
-    int32_t dummy;
-    if (params->findInt32("request-sync", &dummy)) {
+    int32_t tmp;
+    if (params->findInt32("request-sync", &tmp)) {
         status_t err = requestIDRFrame();
 
         if (err != OK) {
@@ -8286,17 +8393,38 @@
             FALLTHROUGH_INTENDED;
         }
         case kWhatResume:
-        case kWhatSetParameters:
         {
-            if (msg->what() == kWhatResume) {
-                ALOGV("[%s] Deferring resume", mCodec->mComponentName.c_str());
-            }
+            ALOGV("[%s] Deferring resume", mCodec->mComponentName.c_str());
 
             mCodec->deferMessage(msg);
             handled = true;
             break;
         }
 
+        case kWhatSetParameters:
+        {
+            sp<AMessage> params;
+            CHECK(msg->findMessage("params", &params));
+
+            sp<ABuffer> hdr10PlusInfo;
+            if (params->findBuffer("hdr10-plus-info", &hdr10PlusInfo)) {
+                if (hdr10PlusInfo != nullptr && hdr10PlusInfo->size() > 0) {
+                    (void)mCodec->setHdr10PlusInfo(hdr10PlusInfo);
+                }
+                params->removeEntryAt(params->findEntryByName("hdr10-plus-info"));
+
+                if (params->countEntries() == 0) {
+                    msg->removeEntryAt(msg->findEntryByName("params"));
+                }
+            }
+
+            if (msg->countEntries() > 0) {
+                mCodec->deferMessage(msg);
+            }
+            handled = true;
+            break;
+        }
+
         case kWhatForceStateTransition:
         {
             int32_t generation = 0;
@@ -8307,6 +8435,23 @@
             break;
         }
 
+        case kWhatSetSurface:
+        {
+            ALOGV("[%s] Deferring setSurface", mCodec->mComponentName.c_str());
+
+            sp<AReplyToken> replyID;
+            CHECK(msg->senderAwaitsResponse(&replyID));
+
+            mCodec->deferMessage(msg);
+
+            sp<AMessage> response = new AMessage;
+            response->setInt32("err", OK);
+            response->postReply(replyID);
+
+            handled = true;
+            break;
+        }
+
         case kWhatCheckIfStuck:
         {
             int32_t generation = 0;
@@ -8407,6 +8552,15 @@
             return false;
         }
 
+        case OMX_EventConfigUpdate:
+        {
+            CHECK_EQ(data1, (OMX_U32)kPortIndexOutput);
+
+            mCodec->onConfigUpdate((OMX_INDEXTYPE)data2);
+
+            return true;
+        }
+
         default:
             return BaseState::onOMXEvent(event, data1, data2);
     }
diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp
index 3bccb7b..5d959cb 100644
--- a/media/libstagefright/Android.bp
+++ b/media/libstagefright/Android.bp
@@ -1,3 +1,20 @@
+package {
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_headers {
     name: "libstagefright_headers",
     export_include_dirs: ["include"],
@@ -8,6 +25,12 @@
         "com.android.media.swcodec",
     ],
     min_sdk_version: "29",
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
 
 cc_library_static {
@@ -34,6 +57,12 @@
         "libstagefright_foundation",
         "libutils"
     ],
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
 
 cc_library_static {
@@ -58,9 +87,18 @@
     },
 
     header_libs: [
+        "libaudioclient_headers",
         "libstagefright_foundation_headers",
+        "media_ndk_headers",
     ],
-    shared_libs: ["libmediandk"],
+
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+
     export_include_dirs: ["include"],
 }
 
@@ -132,8 +170,10 @@
 
     header_libs: [
         "libaudioclient_headers",
-        "libmedia_headers",
+        "libbase_headers",
+        "libmedia_datasource_headers",
         "media_ndk_headers",
+        "media_plugin_headers",
     ],
 
     cflags: [
@@ -150,6 +190,18 @@
             "signed-integer-overflow",
         ],
     },
+
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+        linux: {
+            cflags: [
+                "-DDISABLE_AUDIO_SYSTEM_OFFLOAD",
+            ],
+        }
+    },
 }
 
 cc_library_shared {
diff --git a/media/libstagefright/FrameDecoder.cpp b/media/libstagefright/FrameDecoder.cpp
index 734f5bb..4ba85ba 100644
--- a/media/libstagefright/FrameDecoder.cpp
+++ b/media/libstagefright/FrameDecoder.cpp
@@ -43,7 +43,7 @@
 namespace android {
 
 static const int64_t kBufferTimeOutUs = 10000LL; // 10 msec
-static const size_t kRetryCount = 50; // must be >0
+static const size_t kRetryCount = 100; // must be >0
 static const int64_t kDefaultSampleDurationUs = 33333LL; // 33ms
 
 sp<IMemory> allocVideoFrame(const sp<MetaData>& trackMeta,
diff --git a/media/libstagefright/HevcUtils.cpp b/media/libstagefright/HevcUtils.cpp
index b347453..e4794dd 100644
--- a/media/libstagefright/HevcUtils.cpp
+++ b/media/libstagefright/HevcUtils.cpp
@@ -30,6 +30,8 @@
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/Utils.h>
 
+#define UNUSED_PARAM __attribute__((unused))
+
 namespace android {
 
 static const uint8_t kHevcNalUnitTypes[5] = {
@@ -375,8 +377,56 @@
     return reader.overRead() ? ERROR_MALFORMED : OK;
 }
 
+void HevcParameterSets::FindHEVCDimensions(const sp<ABuffer> &SpsBuffer, int32_t *width, int32_t *height)
+{
+    ALOGD("FindHEVCDimensions");
+    // See Rec. ITU-T H.265 v3 (04/2015) Chapter 7.3.2.2 for reference
+    ABitReader reader(SpsBuffer->data() + 1, SpsBuffer->size() - 1);
+    // Skip sps_video_parameter_set_id
+    reader.skipBits(4);
+    uint8_t maxSubLayersMinus1 = reader.getBitsWithFallback(3, 0);
+    // Skip sps_temporal_id_nesting_flag;
+    reader.skipBits(1);
+    // Skip general profile
+    reader.skipBits(96);
+    if (maxSubLayersMinus1 > 0) {
+        bool subLayerProfilePresentFlag[8];
+        bool subLayerLevelPresentFlag[8];
+        for (int i = 0; i < maxSubLayersMinus1; ++i) {
+            subLayerProfilePresentFlag[i] = reader.getBitsWithFallback(1, 0);
+            subLayerLevelPresentFlag[i] = reader.getBitsWithFallback(1, 0);
+        }
+        // Skip reserved
+        reader.skipBits(2 * (8 - maxSubLayersMinus1));
+        for (int i = 0; i < maxSubLayersMinus1; ++i) {
+            if (subLayerProfilePresentFlag[i]) {
+                // Skip profile
+                reader.skipBits(88);
+            }
+            if (subLayerLevelPresentFlag[i]) {
+                // Skip sub_layer_level_idc[i]
+                reader.skipBits(8);
+            }
+        }
+    }
+    // Skip sps_seq_parameter_set_id
+    skipUE(&reader);
+    uint8_t chromaFormatIdc = parseUEWithFallback(&reader, 0);
+    if (chromaFormatIdc == 3) {
+        // Skip separate_colour_plane_flag
+        reader.skipBits(1);
+    }
+    skipUE(&reader);
+    skipUE(&reader);
+
+    // pic_width_in_luma_samples
+    *width = parseUEWithFallback(&reader, 0);
+    // pic_height_in_luma_samples
+    *height = parseUEWithFallback(&reader, 0);
+}
+
 status_t HevcParameterSets::parsePps(
-        const uint8_t* data __unused, size_t size __unused) {
+        const uint8_t* data UNUSED_PARAM, size_t size UNUSED_PARAM) {
     return OK;
 }
 
diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp
index 553f59a..49f1685 100644
--- a/media/libstagefright/MediaCodec.cpp
+++ b/media/libstagefright/MediaCodec.cpp
@@ -357,11 +357,24 @@
         BufferQueue::createBufferQueue(&mProducer, &mConsumer);
         mSurface = new Surface(mProducer, false /* controlledByApp */);
         struct ConsumerListener : public BnConsumerListener {
-            void onFrameAvailable(const BufferItem&) override {}
+            ConsumerListener(const sp<IGraphicBufferConsumer> &consumer) {
+                mConsumer = consumer;
+            }
+            void onFrameAvailable(const BufferItem&) override {
+                BufferItem buffer;
+                // consume buffer
+                sp<IGraphicBufferConsumer> consumer = mConsumer.promote();
+                if (consumer != nullptr && consumer->acquireBuffer(&buffer, 0) == NO_ERROR) {
+                    consumer->releaseBuffer(buffer.mSlot, buffer.mFrameNumber,
+                                            EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, buffer.mFence);
+                }
+            }
+
+            wp<IGraphicBufferConsumer> mConsumer;
             void onBuffersReleased() override {}
             void onSidebandStreamChanged() override {}
         };
-        sp<ConsumerListener> listener{new ConsumerListener};
+        sp<ConsumerListener> listener{new ConsumerListener(mConsumer)};
         mConsumer->consumerConnect(listener, false);
         mConsumer->setConsumerName(String8{"MediaCodec.release"});
         mConsumer->setConsumerUsageBits(usage);
@@ -674,6 +687,9 @@
       mDequeueInputReplyID(0),
       mDequeueOutputTimeoutGeneration(0),
       mDequeueOutputReplyID(0),
+      mTunneledInputWidth(0),
+      mTunneledInputHeight(0),
+      mTunneled(false),
       mHaveInputSurface(false),
       mHavePendingInputBuffers(false),
       mCpuBoostRequested(false),
@@ -1344,6 +1360,8 @@
     // save msg for reset
     mConfigureMsg = msg;
 
+    sp<AMessage> callback = mCallback;
+
     status_t err;
     std::vector<MediaResourceParcel> resources;
     resources.push_back(MediaResource::CodecResource(mFlags & kFlagIsSecure, mIsVideo));
@@ -1368,7 +1386,18 @@
             // the configure failure is due to wrong state.
 
             ALOGE("configure failed with err 0x%08x, resetting...", err);
-            reset();
+            status_t err2 = reset();
+            if (err2 != OK) {
+                ALOGE("retrying configure: failed to reset codec (%08x)", err2);
+                break;
+            }
+            if (callback != nullptr) {
+                err2 = setCallback(callback);
+                if (err2 != OK) {
+                    ALOGE("retrying configure: failed to set callback (%08x)", err2);
+                    break;
+                }
+            }
         }
         if (!isResourceError(err)) {
             break;
@@ -1477,6 +1506,8 @@
 status_t MediaCodec::start() {
     sp<AMessage> msg = new AMessage(kWhatStart, this);
 
+    sp<AMessage> callback;
+
     status_t err;
     std::vector<MediaResourceParcel> resources;
     resources.push_back(MediaResource::CodecResource(mFlags & kFlagIsSecure, mIsVideo));
@@ -1501,6 +1532,20 @@
                 ALOGE("retrying start: failed to configure codec");
                 break;
             }
+            if (callback != nullptr) {
+                err = setCallback(callback);
+                if (err != OK) {
+                    ALOGE("retrying start: failed to set callback");
+                    break;
+                }
+                ALOGD("succeed to set callback for reclaim");
+            }
+        }
+
+        // Keep callback message after the first iteration if necessary.
+        if (i == 0 && mCallback != nullptr && mFlags & kFlagIsAsync) {
+            callback = mCallback;
+            ALOGD("keep callback message for reclaim");
         }
 
         sp<AMessage> response;
@@ -2899,6 +2944,14 @@
 
             extractCSD(format);
 
+            int32_t tunneled;
+            if (format->findInt32("feature-tunneled-playback", &tunneled) && tunneled != 0) {
+                ALOGI("Configuring TUNNELED video playback.");
+                mTunneled = true;
+            } else {
+                mTunneled = false;
+            }
+
             mCodec->initiateConfigureComponent(format);
             break;
         }
@@ -3112,16 +3165,21 @@
                 break;
             }
 
-            // If we're flushing, stopping, configuring or starting  but
+            // If we're flushing, configuring or starting  but
             // received a release request, post the reply for the pending call
             // first, and consider it done. The reply token will be replaced
             // after this, and we'll no longer be able to reply.
-            if (mState == FLUSHING || mState == STOPPING
-                    || mState == CONFIGURING || mState == STARTING) {
+            if (mState == FLUSHING || mState == CONFIGURING || mState == STARTING) {
                 // mReply is always set if in these states.
                 postPendingRepliesAndDeferredMessages(
                         std::string("kWhatRelease:") + stateString(mState));
             }
+            // If we're stopping but received a release request, post the reply
+            // for the pending call if necessary. Note that the reply may have been
+            // already posted due to an error.
+            if (mState == STOPPING && mReplyID) {
+                postPendingRepliesAndDeferredMessages("kWhatRelease:STOPPING");
+            }
 
             if (mFlags & kFlagSawMediaServerDie) {
                 // It's dead, Jim. Don't expect initiateShutdown to yield
@@ -3982,7 +4040,18 @@
     if (hasCryptoOrDescrambler() && !c2Buffer && !memory) {
         AString *errorDetailMsg;
         CHECK(msg->findPointer("errorDetailMsg", (void **)&errorDetailMsg));
-
+        // Notify mCrypto of video resolution changes
+        if (mTunneled && mCrypto != NULL) {
+            int32_t width, height;
+            if (mInputFormat->findInt32("width", &width) &&
+                mInputFormat->findInt32("height", &height) && width > 0 && height > 0) {
+                if (width != mTunneledInputWidth || height != mTunneledInputHeight) {
+                    mTunneledInputWidth = width;
+                    mTunneledInputHeight = height;
+                    mCrypto->notifyResolution(width, height);
+                }
+            }
+        }
         err = mBufferChannel->queueSecureInputBuffer(
                 buffer,
                 (mFlags & kFlagIsSecure),
@@ -4102,7 +4171,15 @@
                 }
             }
         }
-        mBufferChannel->renderOutputBuffer(buffer, renderTimeNs);
+        status_t err = mBufferChannel->renderOutputBuffer(buffer, renderTimeNs);
+
+        if (err == NO_INIT) {
+            ALOGE("rendering to non-initilized(obsolete) surface");
+            return err;
+        }
+        if (err != OK) {
+            ALOGI("rendring output error %d", err);
+        }
     } else {
         mBufferChannel->discardBuffer(buffer);
     }
diff --git a/media/libstagefright/MediaCodecList.cpp b/media/libstagefright/MediaCodecList.cpp
index ac54fa1..799ca0d 100644
--- a/media/libstagefright/MediaCodecList.cpp
+++ b/media/libstagefright/MediaCodecList.cpp
@@ -209,9 +209,12 @@
             ALOGD("ignored a null builder");
             continue;
         }
-        mInitCheck = builder->buildMediaCodecList(&writer);
-        if (mInitCheck != OK) {
-            break;
+        auto currentCheck = builder->buildMediaCodecList(&writer);
+        if (currentCheck != OK) {
+            ALOGD("ignored failed builder");
+            continue;
+        } else {
+            mInitCheck = currentCheck;
         }
     }
     writer.writeGlobalSettings(mGlobalSettings);
diff --git a/media/libstagefright/MediaCodecSource.cpp b/media/libstagefright/MediaCodecSource.cpp
index 1395c27..bc656a2 100644
--- a/media/libstagefright/MediaCodecSource.cpp
+++ b/media/libstagefright/MediaCodecSource.cpp
@@ -435,6 +435,30 @@
     buffer->release();
 }
 
+status_t MediaCodecSource::setEncodingBitrate(int32_t bitRate) {
+    ALOGV("setEncodingBitrate (%d)", bitRate);
+
+    if (mEncoder == NULL) {
+        ALOGW("setEncodingBitrate (%d) : mEncoder is null", bitRate);
+        return BAD_VALUE;
+    }
+
+    sp<AMessage> params = new AMessage;
+    params->setInt32("video-bitrate", bitRate);
+
+    return mEncoder->setParameters(params);
+}
+
+status_t MediaCodecSource::requestIDRFrame() {
+    if (mEncoder == NULL) {
+        ALOGW("requestIDRFrame : mEncoder is null");
+        return BAD_VALUE;
+    } else {
+        mEncoder->requestIDRFrame();
+        return OK;
+    }
+}
+
 MediaCodecSource::MediaCodecSource(
         const sp<ALooper> &looper,
         const sp<AMessage> &outputFormat,
diff --git a/media/libstagefright/MediaExtractorFactory.cpp b/media/libstagefright/MediaExtractorFactory.cpp
index c6e753d..7c981b3 100644
--- a/media/libstagefright/MediaExtractorFactory.cpp
+++ b/media/libstagefright/MediaExtractorFactory.cpp
@@ -59,7 +59,7 @@
             sp<IMediaExtractor> ex;
             mediaExService->makeExtractor(
                     CreateIDataSourceFromDataSource(source),
-                    mime ? std::make_unique<std::string>(mime) : nullptr,
+                    mime ? std::optional<std::string>(mime) : std::nullopt,
                     &ex);
             return ex;
         } else {
diff --git a/media/libstagefright/OWNERS b/media/libstagefright/OWNERS
new file mode 100644
index 0000000..819389d
--- /dev/null
+++ b/media/libstagefright/OWNERS
@@ -0,0 +1,7 @@
+set noparent
+chz@google.com
+essick@google.com
+lajos@google.com
+marcone@google.com
+taklee@google.com
+wonsik@google.com
\ No newline at end of file
diff --git a/media/libstagefright/SurfaceUtils.cpp b/media/libstagefright/SurfaceUtils.cpp
index c284ef7..1f569ef 100644
--- a/media/libstagefright/SurfaceUtils.cpp
+++ b/media/libstagefright/SurfaceUtils.cpp
@@ -175,6 +175,22 @@
     }
 }
 
+status_t setNativeWindowRotation(
+        ANativeWindow *nativeWindow /* nonnull */, int rotation) {
+
+    int transform = 0;
+    if ((rotation % 90) == 0) {
+        switch ((rotation / 90) & 3) {
+            case 1:  transform = HAL_TRANSFORM_ROT_90;  break;
+            case 2:  transform = HAL_TRANSFORM_ROT_180; break;
+            case 3:  transform = HAL_TRANSFORM_ROT_270; break;
+            default: transform = 0;                     break;
+        }
+    }
+
+    return native_window_set_buffers_transform(nativeWindow, transform);
+}
+
 status_t pushBlankBuffersToNativeWindow(ANativeWindow *nativeWindow /* nonnull */) {
     status_t err = NO_ERROR;
     ANativeWindowBuffer* anb = NULL;
diff --git a/media/libstagefright/Utils.cpp b/media/libstagefright/Utils.cpp
index ece79c4..1c4f5ac 100644
--- a/media/libstagefright/Utils.cpp
+++ b/media/libstagefright/Utils.cpp
@@ -1135,7 +1135,7 @@
         // assertion, let's be lenient for now...
         // CHECK((ptr[4] >> 2) == 0x3f);  // reserved
 
-        size_t lengthSize __unused = 1 + (ptr[4] & 3);
+        // we can get lengthSize value from 1 + (ptr[4] & 3)
 
         // commented out check below as H264_QVGA_500_NO_AUDIO.3gp
         // violates it...
@@ -2142,8 +2142,10 @@
     }
     info->sample_rate = srate;
 
-    int32_t cmask = 0;
-    if (!meta->findInt32(kKeyChannelMask, &cmask) || cmask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
+    int32_t rawChannelMask;
+    audio_channel_mask_t cmask = meta->findInt32(kKeyChannelMask, &rawChannelMask) ?
+            static_cast<audio_channel_mask_t>(rawChannelMask) : CHANNEL_MASK_USE_CHANNEL_ORDER;
+    if (cmask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
         ALOGV("track of type '%s' does not publish channel mask", mime);
 
         // Try a channel count instead
@@ -2184,7 +2186,11 @@
     }
     // Check if offload is possible for given format, stream type, sample rate,
     // bit rate, duration, video and streaming
+#ifdef DISABLE_AUDIO_SYSTEM_OFFLOAD
+    return false;
+#else
     return AudioSystem::isOffloadSupported(info);
+#endif
 }
 
 HLSTime::HLSTime(const sp<AMessage>& meta) :
diff --git a/media/libstagefright/bqhelper/Android.bp b/media/libstagefright/bqhelper/Android.bp
index 8698d33..e4fc128 100644
--- a/media/libstagefright/bqhelper/Android.bp
+++ b/media/libstagefright/bqhelper/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_defaults {
     name: "libstagefright_bufferqueue-defaults",
     double_loadable: true,
diff --git a/media/libstagefright/bqhelper/tests/Android.bp b/media/libstagefright/bqhelper/tests/Android.bp
index 2fbc3d6..86ab62a 100644
--- a/media/libstagefright/bqhelper/tests/Android.bp
+++ b/media/libstagefright/bqhelper/tests/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_test {
     name: "FrameDropper_test",
 
diff --git a/media/libstagefright/codecs/aacdec/Android.bp b/media/libstagefright/codecs/aacdec/Android.bp
index 46b3b8f..5ab49a7 100644
--- a/media/libstagefright/codecs/aacdec/Android.bp
+++ b/media/libstagefright/codecs/aacdec/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_aacdec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_aacdec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_aacdec",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/aacdec/DrcPresModeWrap.cpp b/media/libstagefright/codecs/aacdec/DrcPresModeWrap.cpp
index 168d140..157cab6 100644
--- a/media/libstagefright/codecs/aacdec/DrcPresModeWrap.cpp
+++ b/media/libstagefright/codecs/aacdec/DrcPresModeWrap.cpp
@@ -217,7 +217,7 @@
         }
         else { // handle other used encoder target levels
 
-            // Sanity check: DRC presentation mode is only specified for max. 5.1 channels
+            // Validation check: DRC presentation mode is only specified for max. 5.1 channels
             if (mStreamNrAACChan > 6) {
                 drcPresMode = 0;
             }
@@ -308,7 +308,7 @@
             } // switch()
         } // if (mEncoderTarget  == GPM_ENCODER_TARGET_LEVEL)
 
-        // sanity again
+        // validation check again
         if (newHeavy == 1) {
             newBoostFactor=127; // not really needed as the same would be done by the decoder anyway
             newAttFactor = 127;
diff --git a/media/libstagefright/codecs/aacdec/SoftAAC2.cpp b/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
index 28a7a1e..92ec94f 100644
--- a/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
+++ b/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
@@ -1247,6 +1247,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/aacenc/Android.bp b/media/libstagefright/codecs/aacenc/Android.bp
index bf789c4..793125f 100644
--- a/media/libstagefright/codecs/aacenc/Android.bp
+++ b/media/libstagefright/codecs/aacenc/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_aacenc_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_aacenc_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_aacenc",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/aacenc/SoftAACEncoder2.cpp b/media/libstagefright/codecs/aacenc/SoftAACEncoder2.cpp
index 6e437cf..90421b9 100644
--- a/media/libstagefright/codecs/aacenc/SoftAACEncoder2.cpp
+++ b/media/libstagefright/codecs/aacenc/SoftAACEncoder2.cpp
@@ -732,6 +732,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/amrnb/dec/Android.bp b/media/libstagefright/codecs/amrnb/dec/Android.bp
index b8e00b3..2c0954d 100644
--- a/media/libstagefright/codecs/amrnb/dec/Android.bp
+++ b/media/libstagefright/codecs/amrnb/dec/Android.bp
@@ -1,86 +1,20 @@
-cc_library_static {
-    name: "libstagefright_amrnbdec",
-    vendor_available: true,
-    host_supported: true,
-    min_sdk_version: "29",
-
-    srcs: [
-        "src/a_refl.cpp",
-        "src/agc.cpp",
-        "src/amrdecode.cpp",
-        "src/b_cn_cod.cpp",
-        "src/bgnscd.cpp",
-        "src/c_g_aver.cpp",
-        "src/d1035pf.cpp",
-        "src/d2_11pf.cpp",
-        "src/d2_9pf.cpp",
-        "src/d3_14pf.cpp",
-        "src/d4_17pf.cpp",
-        "src/d8_31pf.cpp",
-        "src/d_gain_c.cpp",
-        "src/d_gain_p.cpp",
-        "src/d_plsf.cpp",
-        "src/d_plsf_3.cpp",
-        "src/d_plsf_5.cpp",
-        "src/dec_amr.cpp",
-        "src/dec_gain.cpp",
-        "src/dec_input_format_tab.cpp",
-        "src/dec_lag3.cpp",
-        "src/dec_lag6.cpp",
-        "src/dtx_dec.cpp",
-        "src/ec_gains.cpp",
-        "src/ex_ctrl.cpp",
-        "src/if2_to_ets.cpp",
-        "src/int_lsf.cpp",
-        "src/lsp_avg.cpp",
-        "src/ph_disp.cpp",
-        "src/post_pro.cpp",
-        "src/preemph.cpp",
-        "src/pstfilt.cpp",
-        "src/qgain475_tab.cpp",
-        "src/sp_dec.cpp",
-        "src/wmf_to_ets.cpp",
-    ],
-
-    export_include_dirs: ["src"],
-
-    cflags: [
-        "-DOSCL_UNUSED_ARG(x)=(void)(x)",
-        "-DOSCL_IMPORT_REF=",
-
-        "-Werror",
-    ],
-
-    version_script: "exports.lds",
-
-    //sanitize: {
-    //    misc_undefined: [
-    //        "signed-integer-overflow",
-    //    ],
-    //},
-
-    shared_libs: [
-        "libstagefright_amrnb_common",
-        "liblog",
-    ],
-
-    target: {
-        darwin: {
-            enabled: false,
-        },
-    },
-}
-
 //###############################################################################
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_amrdec",
     defaults: ["libstagefright_softomx-defaults"],
 
     srcs: ["SoftAMR.cpp"],
 
-    local_include_dirs: ["src"],
-
     cflags: [
         "-DOSCL_IMPORT_REF=",
     ],
@@ -103,39 +37,3 @@
         "libstagefright_amrnb_common",
     ],
 }
-
-//###############################################################################
-cc_test {
-    name: "libstagefright_amrnbdec_test",
-    gtest: false,
-    host_supported: true,
-
-    srcs: ["test/amrnbdec_test.cpp"],
-
-    cflags: ["-Wall", "-Werror"],
-
-    local_include_dirs: ["src"],
-
-    static_libs: [
-        "libstagefright_amrnbdec",
-        "libsndfile",
-    ],
-
-    shared_libs: [
-        "libstagefright_amrnb_common",
-        "libaudioutils",
-        "liblog",
-    ],
-
-    target: {
-        darwin: {
-            enabled: false,
-        },
-    },
-
-    //sanitize: {
-    //    misc_undefined: [
-    //        "signed-integer-overflow",
-    //    ],
-    //},
-}
diff --git a/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp b/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
index cdfc03a..01da3f8 100644
--- a/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
+++ b/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
@@ -576,6 +576,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/amrnb/dec/test/README.md b/media/libstagefright/codecs/amrnb/dec/test/README.md
deleted file mode 100644
index 62e13ae..0000000
--- a/media/libstagefright/codecs/amrnb/dec/test/README.md
+++ /dev/null
@@ -1,34 +0,0 @@
-## Media Testing ##
----
-#### AMR-NB Decoder :
-The Amr-Nb Decoder Test Suite validates the amrnb decoder available in libstagefright.
-
-Run the following steps to build the test suite:
-```
-m AmrnbDecoderTest
-```
-
-The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
-
-The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
-
-To test 64-bit binary push binaries from nativetest64.
-```
-adb push ${OUT}/data/nativetest64/AmrnbDecoderTest/AmrnbDecoderTest /data/local/tmp/
-```
-
-To test 32-bit binary push binaries from nativetest.
-```
-adb push ${OUT}/data/nativetest/AmrnbDecoderTest/AmrnbDecoderTest /data/local/tmp/
-```
-
-The resource file for the tests is taken from [here](https://drive.google.com/drive/folders/13cM4tAaVFrmr-zGFqaAzFBbKs75pnm9b). Push these files into device for testing.
-Download amr-nb folder and push all the files in this folder to /data/local/tmp/ on the device.
-```
-adb push amr-nb/. /data/local/tmp/
-```
-
-usage: AmrnbDecoderTest -P \<path_to_folder\>
-```
-adb shell /data/local/tmp/AmrnbDecoderTest -P /data/local/tmp/
-```
diff --git a/media/libstagefright/codecs/amrnb/enc/Android.bp b/media/libstagefright/codecs/amrnb/enc/Android.bp
index 73a1d4b..6bf2d39 100644
--- a/media/libstagefright/codecs/amrnb/enc/Android.bp
+++ b/media/libstagefright/codecs/amrnb/enc/Android.bp
@@ -1,98 +1,21 @@
-cc_library_static {
-    name: "libstagefright_amrnbenc",
-    vendor_available: true,
-    min_sdk_version: "29",
-
-    srcs: [
-        "src/amrencode.cpp",
-        "src/autocorr.cpp",
-        "src/c1035pf.cpp",
-        "src/c2_11pf.cpp",
-        "src/c2_9pf.cpp",
-        "src/c3_14pf.cpp",
-        "src/c4_17pf.cpp",
-        "src/c8_31pf.cpp",
-        "src/calc_cor.cpp",
-        "src/calc_en.cpp",
-        "src/cbsearch.cpp",
-        "src/cl_ltp.cpp",
-        "src/cod_amr.cpp",
-        "src/convolve.cpp",
-        "src/cor_h.cpp",
-        "src/cor_h_x.cpp",
-        "src/cor_h_x2.cpp",
-        "src/corrwght_tab.cpp",
-        "src/dtx_enc.cpp",
-        "src/enc_lag3.cpp",
-        "src/enc_lag6.cpp",
-        "src/enc_output_format_tab.cpp",
-        "src/ets_to_if2.cpp",
-        "src/ets_to_wmf.cpp",
-        "src/g_adapt.cpp",
-        "src/g_code.cpp",
-        "src/g_pitch.cpp",
-        "src/gain_q.cpp",
-        "src/hp_max.cpp",
-        "src/inter_36.cpp",
-        "src/inter_36_tab.cpp",
-        "src/l_comp.cpp",
-        "src/l_extract.cpp",
-        "src/l_negate.cpp",
-        "src/lag_wind.cpp",
-        "src/lag_wind_tab.cpp",
-        "src/levinson.cpp",
-        "src/lpc.cpp",
-        "src/ol_ltp.cpp",
-        "src/p_ol_wgh.cpp",
-        "src/pitch_fr.cpp",
-        "src/pitch_ol.cpp",
-        "src/pre_big.cpp",
-        "src/pre_proc.cpp",
-        "src/prm2bits.cpp",
-        "src/q_gain_c.cpp",
-        "src/q_gain_p.cpp",
-        "src/qgain475.cpp",
-        "src/qgain795.cpp",
-        "src/qua_gain.cpp",
-        "src/s10_8pf.cpp",
-        "src/set_sign.cpp",
-        "src/sid_sync.cpp",
-        "src/sp_enc.cpp",
-        "src/spreproc.cpp",
-        "src/spstproc.cpp",
-        "src/ton_stab.cpp",
-    ],
-
-    header_libs: ["libstagefright_headers"],
-    export_include_dirs: ["src"],
-
-    cflags: [
-        "-DOSCL_UNUSED_ARG(x)=(void)(x)",
-        "-Werror",
-    ],
-
-    version_script: "exports.lds",
-
-    //addressing b/25409744
-    //sanitize: {
-    //    misc_undefined: [
-    //        "signed-integer-overflow",
-    //    ],
-    //},
-
-    shared_libs: ["libstagefright_amrnb_common"],
-}
 
 //###############################################################################
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_amrnbenc",
     defaults: ["libstagefright_softomx-defaults"],
 
     srcs: ["SoftAMRNBEncoder.cpp"],
 
-    local_include_dirs: ["src"],
-
     //addressing b/25409744
     //sanitize: {
     //    misc_undefined: [
@@ -106,27 +29,3 @@
         "libstagefright_amrnb_common",
     ],
 }
-
-//###############################################################################
-
-cc_test {
-    name: "libstagefright_amrnbenc_test",
-    gtest: false,
-
-    srcs: ["test/amrnb_enc_test.cpp"],
-
-    cflags: ["-Wall", "-Werror"],
-
-    local_include_dirs: ["src"],
-
-    static_libs: ["libstagefright_amrnbenc"],
-
-    shared_libs: ["libstagefright_amrnb_common"],
-
-    //addressing b/25409744
-    //sanitize: {
-    //    misc_undefined: [
-    //        "signed-integer-overflow",
-    //    ],
-    //},
-}
diff --git a/media/libstagefright/codecs/amrnb/enc/SoftAMRNBEncoder.cpp b/media/libstagefright/codecs/amrnb/enc/SoftAMRNBEncoder.cpp
index 85ab64e..a1f6686 100644
--- a/media/libstagefright/codecs/amrnb/enc/SoftAMRNBEncoder.cpp
+++ b/media/libstagefright/codecs/amrnb/enc/SoftAMRNBEncoder.cpp
@@ -421,6 +421,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/amrwb/MODULE_LICENSE_APACHE2 b/media/libstagefright/codecs/amrwb/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29..0000000
--- a/media/libstagefright/codecs/amrwb/MODULE_LICENSE_APACHE2
+++ /dev/null
diff --git a/media/libstagefright/codecs/amrwb/NOTICE b/media/libstagefright/codecs/amrwb/NOTICE
deleted file mode 100644
index c5b1efa..0000000
--- a/media/libstagefright/codecs/amrwb/NOTICE
+++ /dev/null
@@ -1,190 +0,0 @@
-
-   Copyright (c) 2005-2008, The Android Open Source Project
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
diff --git a/media/libstagefright/codecs/amrwb/patent_disclaimer.txt b/media/libstagefright/codecs/amrwb/patent_disclaimer.txt
deleted file mode 100644
index b4bf11d..0000000
--- a/media/libstagefright/codecs/amrwb/patent_disclaimer.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-
-THIS IS NOT A GRANT OF PATENT RIGHTS.
-
-Google makes no representation or warranty that the codecs for which
-source code is made available hereunder are unencumbered by
-third-party patents.  Those intending to use this source code in
-hardware or software products are advised that implementations of
-these codecs, including in open source software or shareware, may
-require patent licenses from the relevant patent holders.
diff --git a/media/libstagefright/codecs/amrwbenc/Android.bp b/media/libstagefright/codecs/amrwbenc/Android.bp
index 64f302c..00e7bc9 100644
--- a/media/libstagefright/codecs/amrwbenc/Android.bp
+++ b/media/libstagefright/codecs/amrwbenc/Android.bp
@@ -1,147 +1,13 @@
-cc_library_static {
-    name: "libstagefright_amrwbenc",
-    vendor_available: true,
-    min_sdk_version: "29",
 
-    srcs: [
-        "src/autocorr.c",
-        "src/az_isp.c",
-        "src/bits.c",
-        "src/c2t64fx.c",
-        "src/c4t64fx.c",
-        "src/convolve.c",
-        "src/cor_h_x.c",
-        "src/decim54.c",
-        "src/deemph.c",
-        "src/dtx.c",
-        "src/g_pitch.c",
-        "src/gpclip.c",
-        "src/homing.c",
-        "src/hp400.c",
-        "src/hp50.c",
-        "src/hp6k.c",
-        "src/hp_wsp.c",
-        "src/int_lpc.c",
-        "src/isp_az.c",
-        "src/isp_isf.c",
-        "src/lag_wind.c",
-        "src/levinson.c",
-        "src/log2.c",
-        "src/lp_dec2.c",
-        "src/math_op.c",
-        "src/oper_32b.c",
-        "src/p_med_ol.c",
-        "src/pit_shrp.c",
-        "src/pitch_f4.c",
-        "src/pred_lt4.c",
-        "src/preemph.c",
-        "src/q_gain2.c",
-        "src/q_pulse.c",
-        "src/qisf_ns.c",
-        "src/qpisf_2s.c",
-        "src/random.c",
-        "src/residu.c",
-        "src/scale.c",
-        "src/stream.c",
-        "src/syn_filt.c",
-        "src/updt_tar.c",
-        "src/util.c",
-        "src/voAMRWBEnc.c",
-        "src/voicefac.c",
-        "src/wb_vad.c",
-        "src/weight_a.c",
-        "src/mem_align.c",
-    ],
-
-    arch: {
-        arm: {
-            srcs: [
-                "src/asm/ARMV5E/convolve_opt.s",
-                "src/asm/ARMV5E/cor_h_vec_opt.s",
-                "src/asm/ARMV5E/Deemph_32_opt.s",
-                "src/asm/ARMV5E/Dot_p_opt.s",
-                "src/asm/ARMV5E/Filt_6k_7k_opt.s",
-                "src/asm/ARMV5E/Norm_Corr_opt.s",
-                "src/asm/ARMV5E/pred_lt4_1_opt.s",
-                "src/asm/ARMV5E/residu_asm_opt.s",
-                "src/asm/ARMV5E/scale_sig_opt.s",
-                "src/asm/ARMV5E/Syn_filt_32_opt.s",
-                "src/asm/ARMV5E/syn_filt_opt.s",
-            ],
-
-            cflags: [
-                "-DARM",
-                "-DASM_OPT",
-            ],
-            local_include_dirs: ["src/asm/ARMV5E"],
-
-            instruction_set: "arm",
-
-            neon: {
-                exclude_srcs: [
-                    "src/asm/ARMV5E/convolve_opt.s",
-                    "src/asm/ARMV5E/cor_h_vec_opt.s",
-                    "src/asm/ARMV5E/Deemph_32_opt.s",
-                    "src/asm/ARMV5E/Dot_p_opt.s",
-                    "src/asm/ARMV5E/Filt_6k_7k_opt.s",
-                    "src/asm/ARMV5E/Norm_Corr_opt.s",
-                    "src/asm/ARMV5E/pred_lt4_1_opt.s",
-                    "src/asm/ARMV5E/residu_asm_opt.s",
-                    "src/asm/ARMV5E/scale_sig_opt.s",
-                    "src/asm/ARMV5E/Syn_filt_32_opt.s",
-                    "src/asm/ARMV5E/syn_filt_opt.s",
-                ],
-
-                srcs: [
-                    "src/asm/ARMV7/convolve_neon.s",
-                    "src/asm/ARMV7/cor_h_vec_neon.s",
-                    "src/asm/ARMV7/Deemph_32_neon.s",
-                    "src/asm/ARMV7/Dot_p_neon.s",
-                    "src/asm/ARMV7/Filt_6k_7k_neon.s",
-                    "src/asm/ARMV7/Norm_Corr_neon.s",
-                    "src/asm/ARMV7/pred_lt4_1_neon.s",
-                    "src/asm/ARMV7/residu_asm_neon.s",
-                    "src/asm/ARMV7/scale_sig_neon.s",
-                    "src/asm/ARMV7/Syn_filt_32_neon.s",
-                    "src/asm/ARMV7/syn_filt_neon.s",
-                ],
-
-                // don't actually generate neon instructions, see bug 26932980
-                cflags: [
-                    "-DARMV7",
-                    "-mfpu=vfpv3",
-                ],
-                local_include_dirs: [
-                    "src/asm/ARMV5E",
-                    "src/asm/ARMV7",
-                ],
-            },
-
-        },
-    },
-
-    include_dirs: [
-        "frameworks/av/include",
-        "frameworks/av/media/libstagefright/include",
-    ],
-
-    local_include_dirs: ["src"],
-    export_include_dirs: ["inc"],
-
-    shared_libs: [
-        "libstagefright_enc_common",
-        "liblog",
-    ],
-
-    cflags: ["-Werror"],
-    sanitize: {
-        cfi: true,
-    },
-
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
 }
 
-//###############################################################################
-
 cc_library_shared {
     name: "libstagefright_soft_amrwbenc",
     defaults: ["libstagefright_softomx-defaults"],
@@ -163,4 +29,3 @@
         "libstagefright_enc_common",
     ],
 }
-
diff --git a/media/libstagefright/codecs/amrwbenc/MODULE_LICENSE_APACHE2 b/media/libstagefright/codecs/amrwbenc/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29..0000000
--- a/media/libstagefright/codecs/amrwbenc/MODULE_LICENSE_APACHE2
+++ /dev/null
diff --git a/media/libstagefright/codecs/amrwbenc/NOTICE b/media/libstagefright/codecs/amrwbenc/NOTICE
deleted file mode 100644
index c5b1efa..0000000
--- a/media/libstagefright/codecs/amrwbenc/NOTICE
+++ /dev/null
@@ -1,190 +0,0 @@
-
-   Copyright (c) 2005-2008, The Android Open Source Project
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-
-
-                                 Apache License
-                           Version 2.0, January 2004
-                        http://www.apache.org/licenses/
-
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-   1. Definitions.
-
-      "License" shall mean the terms and conditions for use, reproduction,
-      and distribution as defined by Sections 1 through 9 of this document.
-
-      "Licensor" shall mean the copyright owner or entity authorized by
-      the copyright owner that is granting the License.
-
-      "Legal Entity" shall mean the union of the acting entity and all
-      other entities that control, are controlled by, or are under common
-      control with that entity. For the purposes of this definition,
-      "control" means (i) the power, direct or indirect, to cause the
-      direction or management of such entity, whether by contract or
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
-      outstanding shares, or (iii) beneficial ownership of such entity.
-
-      "You" (or "Your") shall mean an individual or Legal Entity
-      exercising permissions granted by this License.
-
-      "Source" form shall mean the preferred form for making modifications,
-      including but not limited to software source code, documentation
-      source, and configuration files.
-
-      "Object" form shall mean any form resulting from mechanical
-      transformation or translation of a Source form, including but
-      not limited to compiled object code, generated documentation,
-      and conversions to other media types.
-
-      "Work" shall mean the work of authorship, whether in Source or
-      Object form, made available under the License, as indicated by a
-      copyright notice that is included in or attached to the work
-      (an example is provided in the Appendix below).
-
-      "Derivative Works" shall mean any work, whether in Source or Object
-      form, that is based on (or derived from) the Work and for which the
-      editorial revisions, annotations, elaborations, or other modifications
-      represent, as a whole, an original work of authorship. For the purposes
-      of this License, Derivative Works shall not include works that remain
-      separable from, or merely link (or bind by name) to the interfaces of,
-      the Work and Derivative Works thereof.
-
-      "Contribution" shall mean any work of authorship, including
-      the original version of the Work and any modifications or additions
-      to that Work or Derivative Works thereof, that is intentionally
-      submitted to Licensor for inclusion in the Work by the copyright owner
-      or by an individual or Legal Entity authorized to submit on behalf of
-      the copyright owner. For the purposes of this definition, "submitted"
-      means any form of electronic, verbal, or written communication sent
-      to the Licensor or its representatives, including but not limited to
-      communication on electronic mailing lists, source code control systems,
-      and issue tracking systems that are managed by, or on behalf of, the
-      Licensor for the purpose of discussing and improving the Work, but
-      excluding communication that is conspicuously marked or otherwise
-      designated in writing by the copyright owner as "Not a Contribution."
-
-      "Contributor" shall mean Licensor and any individual or Legal Entity
-      on behalf of whom a Contribution has been received by Licensor and
-      subsequently incorporated within the Work.
-
-   2. Grant of Copyright License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      copyright license to reproduce, prepare Derivative Works of,
-      publicly display, publicly perform, sublicense, and distribute the
-      Work and such Derivative Works in Source or Object form.
-
-   3. Grant of Patent License. Subject to the terms and conditions of
-      this License, each Contributor hereby grants to You a perpetual,
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
-      (except as stated in this section) patent license to make, have made,
-      use, offer to sell, sell, import, and otherwise transfer the Work,
-      where such license applies only to those patent claims licensable
-      by such Contributor that are necessarily infringed by their
-      Contribution(s) alone or by combination of their Contribution(s)
-      with the Work to which such Contribution(s) was submitted. If You
-      institute patent litigation against any entity (including a
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
-      or a Contribution incorporated within the Work constitutes direct
-      or contributory patent infringement, then any patent licenses
-      granted to You under this License for that Work shall terminate
-      as of the date such litigation is filed.
-
-   4. Redistribution. You may reproduce and distribute copies of the
-      Work or Derivative Works thereof in any medium, with or without
-      modifications, and in Source or Object form, provided that You
-      meet the following conditions:
-
-      (a) You must give any other recipients of the Work or
-          Derivative Works a copy of this License; and
-
-      (b) You must cause any modified files to carry prominent notices
-          stating that You changed the files; and
-
-      (c) You must retain, in the Source form of any Derivative Works
-          that You distribute, all copyright, patent, trademark, and
-          attribution notices from the Source form of the Work,
-          excluding those notices that do not pertain to any part of
-          the Derivative Works; and
-
-      (d) If the Work includes a "NOTICE" text file as part of its
-          distribution, then any Derivative Works that You distribute must
-          include a readable copy of the attribution notices contained
-          within such NOTICE file, excluding those notices that do not
-          pertain to any part of the Derivative Works, in at least one
-          of the following places: within a NOTICE text file distributed
-          as part of the Derivative Works; within the Source form or
-          documentation, if provided along with the Derivative Works; or,
-          within a display generated by the Derivative Works, if and
-          wherever such third-party notices normally appear. The contents
-          of the NOTICE file are for informational purposes only and
-          do not modify the License. You may add Your own attribution
-          notices within Derivative Works that You distribute, alongside
-          or as an addendum to the NOTICE text from the Work, provided
-          that such additional attribution notices cannot be construed
-          as modifying the License.
-
-      You may add Your own copyright statement to Your modifications and
-      may provide additional or different license terms and conditions
-      for use, reproduction, or distribution of Your modifications, or
-      for any such Derivative Works as a whole, provided Your use,
-      reproduction, and distribution of the Work otherwise complies with
-      the conditions stated in this License.
-
-   5. Submission of Contributions. Unless You explicitly state otherwise,
-      any Contribution intentionally submitted for inclusion in the Work
-      by You to the Licensor shall be under the terms and conditions of
-      this License, without any additional terms or conditions.
-      Notwithstanding the above, nothing herein shall supersede or modify
-      the terms of any separate license agreement you may have executed
-      with Licensor regarding such Contributions.
-
-   6. Trademarks. This License does not grant permission to use the trade
-      names, trademarks, service marks, or product names of the Licensor,
-      except as required for reasonable and customary use in describing the
-      origin of the Work and reproducing the content of the NOTICE file.
-
-   7. Disclaimer of Warranty. Unless required by applicable law or
-      agreed to in writing, Licensor provides the Work (and each
-      Contributor provides its Contributions) on an "AS IS" BASIS,
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-      implied, including, without limitation, any warranties or conditions
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
-      PARTICULAR PURPOSE. You are solely responsible for determining the
-      appropriateness of using or redistributing the Work and assume any
-      risks associated with Your exercise of permissions under this License.
-
-   8. Limitation of Liability. In no event and under no legal theory,
-      whether in tort (including negligence), contract, or otherwise,
-      unless required by applicable law (such as deliberate and grossly
-      negligent acts) or agreed to in writing, shall any Contributor be
-      liable to You for damages, including any direct, indirect, special,
-      incidental, or consequential damages of any character arising as a
-      result of this License or out of the use or inability to use the
-      Work (including but not limited to damages for loss of goodwill,
-      work stoppage, computer failure or malfunction, or any and all
-      other commercial damages or losses), even if such Contributor
-      has been advised of the possibility of such damages.
-
-   9. Accepting Warranty or Additional Liability. While redistributing
-      the Work or Derivative Works thereof, You may choose to offer,
-      and charge a fee for, acceptance of support, warranty, indemnity,
-      or other liability obligations and/or rights consistent with this
-      License. However, in accepting such obligations, You may act only
-      on Your own behalf and on Your sole responsibility, not on behalf
-      of any other Contributor, and only if You agree to indemnify,
-      defend, and hold each Contributor harmless for any liability
-      incurred by, or claims asserted against, such Contributor by reason
-      of your accepting any such warranty or additional liability.
-
-   END OF TERMS AND CONDITIONS
-
diff --git a/media/libstagefright/codecs/amrwbenc/SampleCode/Android.bp b/media/libstagefright/codecs/amrwbenc/SampleCode/Android.bp
deleted file mode 100644
index 9442fc4..0000000
--- a/media/libstagefright/codecs/amrwbenc/SampleCode/Android.bp
+++ /dev/null
@@ -1,28 +0,0 @@
-cc_test {
-    name: "AMRWBEncTest",
-    gtest: false,
-
-    srcs: ["AMRWB_E_SAMPLE.c"],
-
-    cflags: ["-Wall", "-Werror"],
-
-    arch: {
-        arm: {
-            instruction_set: "arm",
-        },
-    },
-
-    shared_libs: [
-        "libdl",
-        "liblog",
-    ],
-
-    static_libs: [
-        "libstagefright_amrwbenc",
-        "libstagefright_enc_common",
-    ],
-
-    sanitize: {
-        cfi: true,
-    },
-}
diff --git a/media/libstagefright/codecs/amrwbenc/SoftAMRWBEncoder.cpp b/media/libstagefright/codecs/amrwbenc/SoftAMRWBEncoder.cpp
index 7fb8a4c..657a5ce 100644
--- a/media/libstagefright/codecs/amrwbenc/SoftAMRWBEncoder.cpp
+++ b/media/libstagefright/codecs/amrwbenc/SoftAMRWBEncoder.cpp
@@ -476,6 +476,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/avcdec/Android.bp b/media/libstagefright/codecs/avcdec/Android.bp
index 0bb6bb0..1c2f9be 100644
--- a/media/libstagefright/codecs/avcdec/Android.bp
+++ b/media/libstagefright/codecs/avcdec/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_avcdec",
     defaults: ["libstagefright_softomx-defaults"],
@@ -16,6 +25,9 @@
             "signed-integer-overflow",
         ],
         cfi: true,
+        config: {
+            cfi_assembly_support: true,
+        },
     },
 
     ldflags: ["-Wl,-Bsymbolic"],
diff --git a/media/libstagefright/codecs/avcdec/SoftAVCDec.cpp b/media/libstagefright/codecs/avcdec/SoftAVCDec.cpp
index 5a4b2f8..3891f23 100644
--- a/media/libstagefright/codecs/avcdec/SoftAVCDec.cpp
+++ b/media/libstagefright/codecs/avcdec/SoftAVCDec.cpp
@@ -724,6 +724,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks, OMX_PTR appData,
         OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/avcenc/Android.bp b/media/libstagefright/codecs/avcenc/Android.bp
index 980261c..586088c 100644
--- a/media/libstagefright/codecs/avcenc/Android.bp
+++ b/media/libstagefright/codecs/avcenc/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_avcenc",
     defaults: ["libstagefright_softomx-defaults"],
@@ -10,6 +19,9 @@
             "signed-integer-overflow",
         ],
         cfi: true,
+        config: {
+            cfi_assembly_support: true,
+        },
     },
 
     cflags: [
diff --git a/media/libstagefright/codecs/avcenc/SoftAVCEnc.cpp b/media/libstagefright/codecs/avcenc/SoftAVCEnc.cpp
index 9db6465..01174c9 100644
--- a/media/libstagefright/codecs/avcenc/SoftAVCEnc.cpp
+++ b/media/libstagefright/codecs/avcenc/SoftAVCEnc.cpp
@@ -1507,6 +1507,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/common/Android.bp b/media/libstagefright/codecs/common/Android.bp
index 260a60a..08691e7 100644
--- a/media/libstagefright/codecs/common/Android.bp
+++ b/media/libstagefright/codecs/common/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_common_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_common_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libstagefright_enc_common",
     vendor_available: true,
@@ -14,4 +33,11 @@
     export_include_dirs: ["include"],
 
     cflags: ["-Werror"],
+
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
diff --git a/media/libstagefright/codecs/flac/dec/Android.bp b/media/libstagefright/codecs/flac/dec/Android.bp
index 4064751..d06e0b7 100644
--- a/media/libstagefright/codecs/flac/dec/Android.bp
+++ b/media/libstagefright/codecs/flac/dec/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_flac_dec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_flac_dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_flacdec",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/flac/dec/SoftFlacDecoder.cpp b/media/libstagefright/codecs/flac/dec/SoftFlacDecoder.cpp
index 842a7ce..d6448d3 100644
--- a/media/libstagefright/codecs/flac/dec/SoftFlacDecoder.cpp
+++ b/media/libstagefright/codecs/flac/dec/SoftFlacDecoder.cpp
@@ -491,6 +491,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/flac/enc/Android.bp b/media/libstagefright/codecs/flac/enc/Android.bp
index f35bce1..59a4675 100644
--- a/media/libstagefright/codecs/flac/enc/Android.bp
+++ b/media/libstagefright/codecs/flac/enc/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_flac_enc_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_flac_enc_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_flacenc",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp b/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp
index 078c8e3..24216a2 100644
--- a/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp
+++ b/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp
@@ -592,6 +592,7 @@
 }  // namespace android
 
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/g711/dec/Android.bp b/media/libstagefright/codecs/g711/dec/Android.bp
index f5357f4..1dc34c3 100644
--- a/media/libstagefright/codecs/g711/dec/Android.bp
+++ b/media/libstagefright/codecs/g711/dec/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_g711_dec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_g711_dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_g711dec",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/g711/dec/SoftG711.cpp b/media/libstagefright/codecs/g711/dec/SoftG711.cpp
index 877cb5a..fe91510 100644
--- a/media/libstagefright/codecs/g711/dec/SoftG711.cpp
+++ b/media/libstagefright/codecs/g711/dec/SoftG711.cpp
@@ -382,6 +382,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/gsm/dec/Android.bp b/media/libstagefright/codecs/gsm/dec/Android.bp
index 5672d89..efa2f83 100644
--- a/media/libstagefright/codecs/gsm/dec/Android.bp
+++ b/media/libstagefright/codecs/gsm/dec/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_gsm_dec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_gsm_dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_gsmdec",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/gsm/dec/SoftGSM.cpp b/media/libstagefright/codecs/gsm/dec/SoftGSM.cpp
index d777229..330cb8a 100644
--- a/media/libstagefright/codecs/gsm/dec/SoftGSM.cpp
+++ b/media/libstagefright/codecs/gsm/dec/SoftGSM.cpp
@@ -354,6 +354,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/gsm/dec/SoftGSM.h b/media/libstagefright/codecs/gsm/dec/SoftGSM.h
index ef86915..d5885a6 100644
--- a/media/libstagefright/codecs/gsm/dec/SoftGSM.h
+++ b/media/libstagefright/codecs/gsm/dec/SoftGSM.h
@@ -20,9 +20,7 @@
 
 #include <media/stagefright/omx/SimpleSoftOMXComponent.h>
 
-extern "C" {
 #include "gsm.h"
-}
 
 namespace android {
 
diff --git a/media/libstagefright/codecs/hevcdec/Android.bp b/media/libstagefright/codecs/hevcdec/Android.bp
index ec436ce..2c4091b 100644
--- a/media/libstagefright/codecs/hevcdec/Android.bp
+++ b/media/libstagefright/codecs/hevcdec/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_hevcdec",
     defaults: ["libstagefright_softomx-defaults"],
@@ -17,6 +26,9 @@
             "signed-integer-overflow",
         ],
         cfi: true,
+        config: {
+            cfi_assembly_support: true,
+        },
     },
 
     // We need this because the current asm generates the following link error:
diff --git a/media/libstagefright/codecs/hevcdec/SoftHEVC.cpp b/media/libstagefright/codecs/hevcdec/SoftHEVC.cpp
index f6ae1f4..176da47 100644
--- a/media/libstagefright/codecs/hevcdec/SoftHEVC.cpp
+++ b/media/libstagefright/codecs/hevcdec/SoftHEVC.cpp
@@ -713,6 +713,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(const char *name,
         const OMX_CALLBACKTYPE *callbacks, OMX_PTR appData,
         OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/m4v_h263/dec/Android.bp b/media/libstagefright/codecs/m4v_h263/dec/Android.bp
index 4303565..725c79c 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/Android.bp
+++ b/media/libstagefright/codecs/m4v_h263/dec/Android.bp
@@ -1,80 +1,19 @@
-cc_library_static {
-    name: "libstagefright_m4vh263dec",
-    vendor_available: true,
-    apex_available: [
-        "//apex_available:platform",
-        "com.android.media.swcodec",
-    ],
-    min_sdk_version: "29",
-    shared_libs: ["liblog"],
 
-    srcs: [
-        "src/adaptive_smooth_no_mmx.cpp",
-        "src/bitstream.cpp",
-        "src/block_idct.cpp",
-        "src/cal_dc_scaler.cpp",
-        "src/chvr_filter.cpp",
-        "src/chv_filter.cpp",
-        "src/combined_decode.cpp",
-        "src/conceal.cpp",
-        "src/datapart_decode.cpp",
-        "src/dcac_prediction.cpp",
-        "src/dec_pred_intra_dc.cpp",
-        "src/deringing_chroma.cpp",
-        "src/deringing_luma.cpp",
-        "src/find_min_max.cpp",
-        "src/get_pred_adv_b_add.cpp",
-        "src/get_pred_outside.cpp",
-        "src/idct.cpp",
-        "src/idct_vca.cpp",
-        "src/mb_motion_comp.cpp",
-        "src/mb_utils.cpp",
-        "src/packet_util.cpp",
-        "src/post_filter.cpp",
-        "src/post_proc_semaphore.cpp",
-        "src/pp_semaphore_chroma_inter.cpp",
-        "src/pp_semaphore_luma.cpp",
-        "src/pvdec_api.cpp",
-        "src/scaling_tab.cpp",
-        "src/vlc_decode.cpp",
-        "src/vlc_dequant.cpp",
-        "src/vlc_tab.cpp",
-        "src/vop.cpp",
-        "src/zigzag_tab.cpp",
-    ],
-
-    header_libs: [
-        "media_plugin_headers",
-        "libstagefright_headers"
-    ],
-
-    local_include_dirs: ["src"],
-    export_include_dirs: ["include"],
-
-    cflags: [
-        "-Werror",
-    ],
-
-    version_script: "exports.lds",
-
-    sanitize: {
-        misc_undefined: [
-            "signed-integer-overflow",
-        ],
-        cfi: true,
-    },
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
 }
 
-//###############################################################################
-
 cc_library_shared {
     name: "libstagefright_soft_mpeg4dec",
     defaults: ["libstagefright_softomx-defaults"],
 
     srcs: ["SoftMPEG4.cpp"],
 
-    local_include_dirs: ["src"],
-
     cflags: [
     ],
 
diff --git a/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp b/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp
index 60750d9..a4b3e2f 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp
+++ b/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp
@@ -412,6 +412,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/adaptive_smooth_no_mmx.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/adaptive_smooth_no_mmx.cpp
deleted file mode 100644
index e2761eb..0000000
--- a/media/libstagefright/codecs/m4v_h263/dec/src/adaptive_smooth_no_mmx.cpp
+++ /dev/null
@@ -1,421 +0,0 @@
-/* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
- *
- * 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.
- * -------------------------------------------------------------------
- */
-/*
-
- Description: Separated modules into one function per file and put into
-    new template.
-
- Description: Optimizing C code and adding comments.  Also changing variable
-    names to make them more meaningful.
-
- Who:                   Date:
- Description:
-
-------------------------------------------------------------------------------
- INPUT AND OUTPUT DEFINITIONS
-
- Inputs:
-
-    Rec_Y = pointer to 0th position in buffer containing luminance values
-        of type uint8.
-    y_start = value of y coordinate of type int that specifies the first
-        row of pixels to be used in the filter algorithm.
-    x_start = value of x coordinate of type int that specifies the first
-        column of pixels to be used in the filter algorithm.
-    y_blk_start = value of the y coordinate of type int that specifies the
-        row of pixels which contains the start of a block. The row
-        specified by y_blk_start+BLK_SIZE is the last row of pixels
-        that are used in the filter algorithm.
-    x_blk_start = value of the x coordinate of type int that specifies the
-        column of pixels which contains the start of a block.  The
-        column specified by x_blk_start+BLK_SIZE is the last column of
-        pixels that are used in the filter algorithm.
-    thr = value of type int that is compared to the elements in Rec_Y to
-        determine if a particular value in Rec_Y will be modified by
-        the filter or not
-    width = value of type int that specifies the width of the display
-        in pixels (or pels, equivalently).
-    max_diff = value of type int that specifies the value that may be added
-        or subtracted from the pixel in Rec_Y that is being filtered
-        if the filter algorithm decides to change that particular
-        pixel's luminance value.
-
-
- Local Stores/Buffers/Pointers Needed:
-    None
-
- Global Stores/Buffers/Pointers Needed:
-    None
-
- Outputs:
-    None
-
- Pointers and Buffers Modified:
-    Buffer pointed to by Rec_Y is modified with the filtered
-    luminance values.
-
- Local Stores Modified:
-    None
-
- Global Stores Modified:
-    None
-
-------------------------------------------------------------------------------
- FUNCTION DESCRIPTION
-
- This function implements a motion compensated noise filter using adaptive
- weighted averaging of luminance values.  *Rec_Y contains the luminance values
- that are being filtered.
-
- The picture below depicts a 3x3 group of pixel luminance values.  The "u", "c",
- and "l" stand for "upper", "center" and "lower", respectively.  The location
- of pelc0 is specified by x_start and y_start in the 1-D array "Rec_Y" as
- follows (assuming x_start=0):
-
- location of pelc0 = [(y_start+1) * width] + x_start
-
- Moving up or down 1 row (moving from pelu2 to pelc2, for example) is done by
- incrementing or decrementing "width" elements within Rec_Y.
-
- The coordinates of the upper left hand corner of a block (not the group of
- 9 pixels depicted in the figure below) is specified by
- (y_blk_start, x_blk_start).  The width and height of the block is BLKSIZE.
- (y_start,x_start) may be specified independently of (y_blk_start, x_blk_start).
-
-    (y_start,x_start)
- -----------|--------------------------
-    |   |   |   |   |
-    |   X   | pelu1 | pelu2 |
-    | pelu0 |   |   |
-    |   |   |   |
- --------------------------------------
-    |   |   |   |
-    | pelc0 | pelc1 | pelc2 |
-    |   |   |   |
-    |   |   |   |
- --------------------------------------
-    |   |   |   |
-    | pell0 | pell1 | pell2 |
-    |   |   |   |
-    |   |   |   |
- --------------------------------------
-
- The filtering of the luminance values is achieved by comparing the 9
- luminance values to a threshold value ("thr") and then changing the
- luminance value of pelc1 if all of the values are above or all of the values
- are below the threshold.  The amount that the luminance value is changed
- depends on a weighted sum of the 9 luminance values. The position of Pelc1
- is then advanced to the right by one (as well as all of the surrounding pixels)
- and the same calculation is performed again for the luminance value of the new
- Pelc1. This continues row-wise until pixels in the last row of the block are
- filtered.
-
-
-------------------------------------------------------------------------------
- REQUIREMENTS
-
- None.
-
-------------------------------------------------------------------------------
- REFERENCES
-
- ..\corelibs\decoder\common\src\post_proc.c
-
-------------------------------------------------------------------------------
- PSEUDO-CODE
-
-------------------------------------------------------------------------------
- RESOURCES USED
-   When the code is written for a specific target processor the
-     the resources used should be documented below.
-
- STACK USAGE: [stack count for this module] + [variable to represent
-          stack usage for each subroutine called]
-
-     where: [stack usage variable] = stack usage for [subroutine
-         name] (see [filename].ext)
-
- DATA MEMORY USED: x words
-
- PROGRAM MEMORY USED: x words
-
- CLOCK CYCLES: [cycle count equation for this module] + [variable
-           used to represent cycle count for each subroutine
-           called]
-
-     where: [cycle count variable] = cycle count for [subroutine
-        name] (see [filename].ext)
-
-------------------------------------------------------------------------------
-*/
-
-
-/*----------------------------------------------------------------------------
-; INCLUDES
-----------------------------------------------------------------------------*/
-#include    "mp4dec_lib.h"
-#include    "post_proc.h"
-#include    "mp4def.h"
-
-#define OSCL_DISABLE_WARNING_CONV_POSSIBLE_LOSS_OF_DATA
-
-/*----------------------------------------------------------------------------
-; MACROS
-; Define module specific macros here
-----------------------------------------------------------------------------*/
-
-
-/*----------------------------------------------------------------------------
-; DEFINES
-; Include all pre-processor statements here. Include conditional
-; compile variables also.
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL FUNCTION DEFINITIONS
-; Function Prototype declaration
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL STORE/BUFFER/POINTER DEFINITIONS
-; Variable declaration - defined here and used outside this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL FUNCTION REFERENCES
-; Declare functions defined elsewhere and referenced in this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
-; Declare variables used in this module but defined elsewhere
-----------------------------------------------------------------------------*/
-#ifdef PV_POSTPROC_ON
-/*----------------------------------------------------------------------------
-; FUNCTION CODE
-----------------------------------------------------------------------------*/
-void AdaptiveSmooth_NoMMX(
-    uint8 *Rec_Y,       /* i/o  */
-    int y_start,        /* i    */
-    int x_start,        /* i    */
-    int y_blk_start,    /* i    */
-    int x_blk_start,    /* i    */
-    int thr,        /* i    */
-    int width,      /* i    */
-    int max_diff        /* i    */
-)
-{
-
-    /*----------------------------------------------------------------------------
-    ; Define all local variables
-    ----------------------------------------------------------------------------*/
-    int  sign_v[15];
-    int sum_v[15];
-    int *sum_V_ptr;
-    int *sign_V_ptr;
-    uint8 pelu;
-    uint8 pelc;
-    uint8 pell;
-    uint8 *pelp;
-    uint8 oldrow[15];
-    int  sum;
-    int sum1;
-    uint8 *Rec_Y_ptr;
-    int32  addr_v;
-    int row_cntr;
-    int col_cntr;
-
-    /*----------------------------------------------------------------------------
-    ; Function body here
-    ----------------------------------------------------------------------------*/
-    /*  first row
-    */
-    addr_v = (int32)(y_start + 1) * width;  /* y coord of 1st element in the row  /
-                     /containing pelc pixel /     */
-    Rec_Y_ptr = &Rec_Y[addr_v + x_start];  /* initializing pointer to
-                           /  pelc0 position  */
-    sum_V_ptr = &sum_v[0];  /* initializing pointer to 0th element of array
-                /   that will contain weighted sums of pixel
-                /   luminance values */
-    sign_V_ptr = &sign_v[0];  /*  initializing pointer to 0th element of
-                  /   array that will contain sums that indicate
-                  /    how many of the 9 pixels are above or below
-                  /    the threshold value (thr)    */
-    pelp = &oldrow[0];  /* initializing pointer to the 0th element of array
-                /    that will contain current values of pelc that
-                /   are saved and used as values of pelu when the
-                /   next row of pixels are filtered */
-
-    pelu = *(Rec_Y_ptr - width);  /* assigning value of pelu0 to pelu  */
-    *pelp++ = pelc = *Rec_Y_ptr; /* assigning value of pelc0 to pelc and
-                     /  storing this value in pelp which
-                     /   will be used as value of pelu0 when
-                     /  next row is filtered */
-    pell = *(Rec_Y_ptr + width);  /* assigning value of pell0 to pell */
-    Rec_Y_ptr++; /* advancing pointer from pelc0 to pelc1 */
-    *sum_V_ptr++ = pelu + (pelc << 1) + pell;  /* weighted sum of pelu0,
-                         /  pelc0 and pell0  */
-    /* sum of 0's and 1's (0 if pixel value is below thr, 1 if value
-    /is above thr)  */
-    *sign_V_ptr++ = INDEX(pelu, thr) + INDEX(pelc, thr) + INDEX(pell, thr);
-
-
-    pelu = *(Rec_Y_ptr - width);  /* assigning value of pelu1 to pelu */
-    *pelp++ = pelc = *Rec_Y_ptr; /* assigning value of pelc1 to pelc and
-                     /  storing this value in pelp which
-                     /  will be used as the value of pelu1 when
-                     /  next row is filtered */
-    pell = *(Rec_Y_ptr + width);  /* assigning value of pell1 to pell */
-    Rec_Y_ptr++;  /* advancing pointer from pelc1 to pelc2 */
-    *sum_V_ptr++ = pelu + (pelc << 1) + pell; /* weighted sum of pelu1,
-                        / pelc1 and pell1  */
-    /* sum of 0's and 1's (0 if pixel value is below thr, 1 if value
-    /is above thr)  */
-    *sign_V_ptr++ = INDEX(pelu, thr) + INDEX(pelc, thr) + INDEX(pell, thr);
-
-    /* The loop below performs the filtering for the first row of
-    /   pixels in the region.  It steps across the remaining pixels in
-    /   the row and alters the luminance value of pelc1 if necessary,
-    /   depending on the luminance values of the adjacent pixels*/
-
-    for (col_cntr = (x_blk_start + BLKSIZE - 1) - x_start; col_cntr > 0; col_cntr--)
-    {
-        pelu = *(Rec_Y_ptr - width);  /* assigning value of pelu2 to
-                        /   pelu */
-        *pelp++ = pelc = *Rec_Y_ptr; /* assigning value of pelc2 to pelc
-                         / and storing this value in pelp
-                         / which will be used   as value of pelu2
-                         / when next row is filtered */
-        pell = *(Rec_Y_ptr + width); /* assigning value of pell2 to pell */
-
-        /* weighted sum of pelu1, pelc1 and pell1  */
-        *sum_V_ptr = pelu + (pelc << 1) + pell;
-        /* sum of 0's and 1's (0 if pixel value is below thr,
-        /1 if value is above thr)  */
-        *sign_V_ptr = INDEX(pelu, thr) + INDEX(pelc, thr) +
-                      INDEX(pell, thr);
-        /* the value of sum1 indicates how many of the 9 pixels'
-        /luminance values are above or equal to thr */
-        sum1 = *(sign_V_ptr - 2) + *(sign_V_ptr - 1) + *sign_V_ptr;
-
-        /* alter the luminance value of pelc1 if all 9 luminance values
-        /are above or equal to thr or if all 9 values are below thr */
-        if (sum1 == 0 || sum1 == 9)
-        {
-            /* sum is a weighted average of the 9 pixel luminance
-            /values   */
-            sum = (*(sum_V_ptr - 2) + (*(sum_V_ptr - 1) << 1) +
-                   *sum_V_ptr + 8) >> 4;
-
-            Rec_Y_ptr--;  /* move pointer back to pelc1  */
-            /* If luminance value of pelc1 is larger than
-            / sum by more than max_diff, then subract max_diff
-            / from luminance value of pelc1*/
-            if ((int)(*Rec_Y_ptr - sum) > max_diff)
-            {
-                sum = *Rec_Y_ptr - max_diff;
-            }
-            /* If luminance value of pelc1 is smaller than
-            / sum by more than max_diff, then add max_diff
-            / to luminance value of pelc1*/
-            else if ((int)(*Rec_Y_ptr - sum) < -max_diff)
-            {
-                sum = *Rec_Y_ptr + max_diff;
-            }
-            *Rec_Y_ptr++ = sum; /* assign value of sum to pelc1
-                         and advance pointer to pelc2 */
-        }
-        Rec_Y_ptr++; /* advance pointer to new value of pelc2
-                 /   old pelc2 is now treated as pelc1*/
-        sum_V_ptr++; /* pointer is advanced so next weighted sum may
-                 /  be saved */
-        sign_V_ptr++; /* pointer is advanced so next sum of 0's and
-                  / 1's may be saved  */
-    }
-
-    /* The nested loops below perform the filtering for the remaining rows */
-
-    addr_v = (y_start + 2) * width;  /* advance addr_v to the next row
-                     /   (corresponding to pell0)*/
-    /* The outer loop steps throught the rows.   */
-    for (row_cntr = (y_blk_start + BLKSIZE) - (y_start + 2); row_cntr > 0; row_cntr--)
-    {
-        Rec_Y_ptr = &Rec_Y[addr_v + x_start]; /* advance pointer to
-            /the old pell0, which has become the new pelc0 */
-        addr_v += width;  /* move addr_v down 1 row */
-        sum_V_ptr = &sum_v[0];  /* re-initializing pointer */
-        sign_V_ptr = &sign_v[0];  /* re-initilaizing pointer */
-        pelp = &oldrow[0]; /* re-initializing pointer */
-
-        pelu = *pelp; /* setting pelu0 to old value of pelc0 */
-        *pelp++ = pelc = *Rec_Y_ptr;
-        pell = *(Rec_Y_ptr + width);
-        Rec_Y_ptr++;
-        *sum_V_ptr++ = pelu + (pelc << 1) + pell;
-        *sign_V_ptr++ = INDEX(pelu, thr) + INDEX(pelc, thr) +
-                        INDEX(pell, thr);
-
-        pelu = *pelp; /* setting pelu1 to old value of pelc1 */
-        *pelp++ = pelc = *Rec_Y_ptr;
-        pell = *(Rec_Y_ptr + width);
-        Rec_Y_ptr++;
-        *sum_V_ptr++ = pelu + (pelc << 1) + pell;
-        *sign_V_ptr++ = INDEX(pelu, thr) + INDEX(pelc, thr) +
-                        INDEX(pell, thr);
-        /* The inner loop steps through the columns */
-        for (col_cntr = (x_blk_start + BLKSIZE - 1) - x_start; col_cntr > 0; col_cntr--)
-        {
-            pelu = *pelp; /* setting pelu2 to old value of pelc2 */
-            *pelp++ = pelc = *Rec_Y_ptr;
-            pell = *(Rec_Y_ptr + width);
-
-            *sum_V_ptr = pelu + (pelc << 1) + pell;
-            *sign_V_ptr = INDEX(pelu, thr) + INDEX(pelc, thr) +
-                          INDEX(pell, thr);
-
-            sum1 = *(sign_V_ptr - 2) + *(sign_V_ptr - 1) + *sign_V_ptr;
-            /* the "if" statement below is the same as the one in
-            / the first loop */
-            if (sum1 == 0 || sum1 == 9)
-            {
-                sum = (*(sum_V_ptr - 2) + (*(sum_V_ptr - 1) << 1) +
-                       *sum_V_ptr + 8) >> 4;
-
-                Rec_Y_ptr--;
-                if ((int)(*Rec_Y_ptr - sum) > max_diff)
-                {
-                    sum = *Rec_Y_ptr - max_diff;
-                }
-                else if ((int)(*Rec_Y_ptr - sum) < -max_diff)
-                {
-                    sum = *Rec_Y_ptr + max_diff;
-                }
-                *Rec_Y_ptr++ = (uint8) sum;
-            }
-            Rec_Y_ptr++;
-            sum_V_ptr++;
-            sign_V_ptr++;
-        }
-    }
-
-    /*----------------------------------------------------------------------------
-    ; Return nothing or data or data pointer
-    ----------------------------------------------------------------------------*/
-    return;
-}
-#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/chv_filter.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/chv_filter.cpp
deleted file mode 100644
index 6593b48..0000000
--- a/media/libstagefright/codecs/m4v_h263/dec/src/chv_filter.cpp
+++ /dev/null
@@ -1,654 +0,0 @@
-/* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
- *
- * 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.
- * -------------------------------------------------------------------
- */
-/*
-------------------------------------------------------------------------------
- INPUT AND OUTPUT DEFINITIONS
-
- Inputs:
-    [input_variable_name] = [description of the input to module, its type
-                 definition, and length (when applicable)]
-
- Local Stores/Buffers/Pointers Needed:
-    [local_store_name] = [description of the local store, its type
-                  definition, and length (when applicable)]
-    [local_buffer_name] = [description of the local buffer, its type
-                   definition, and length (when applicable)]
-    [local_ptr_name] = [description of the local pointer, its type
-                definition, and length (when applicable)]
-
- Global Stores/Buffers/Pointers Needed:
-    [global_store_name] = [description of the global store, its type
-                   definition, and length (when applicable)]
-    [global_buffer_name] = [description of the global buffer, its type
-                definition, and length (when applicable)]
-    [global_ptr_name] = [description of the global pointer, its type
-                 definition, and length (when applicable)]
-
- Outputs:
-    [return_variable_name] = [description of data/pointer returned
-                  by module, its type definition, and length
-                  (when applicable)]
-
- Pointers and Buffers Modified:
-    [variable_bfr_ptr] points to the [describe where the
-      variable_bfr_ptr points to, its type definition, and length
-      (when applicable)]
-    [variable_bfr] contents are [describe the new contents of
-      variable_bfr]
-
- Local Stores Modified:
-    [local_store_name] = [describe new contents, its type
-                  definition, and length (when applicable)]
-
- Global Stores Modified:
-    [global_store_name] = [describe new contents, its type
-                   definition, and length (when applicable)]
-
-------------------------------------------------------------------------------
- FUNCTION DESCRIPTION
-
-   For fast Deblock filtering
-   Newer version (macroblock based processing)
-
-------------------------------------------------------------------------------
- REQUIREMENTS
-
- [List requirements to be satisfied by this module.]
-
-------------------------------------------------------------------------------
- REFERENCES
-
- [List all references used in designing this module.]
-
-------------------------------------------------------------------------------
- PSEUDO-CODE
-
-------------------------------------------------------------------------------
- RESOURCES USED
-   When the code is written for a specific target processor the
-     the resources used should be documented below.
-
- STACK USAGE: [stack count for this module] + [variable to represent
-          stack usage for each subroutine called]
-
-     where: [stack usage variable] = stack usage for [subroutine
-         name] (see [filename].ext)
-
- DATA MEMORY USED: x words
-
- PROGRAM MEMORY USED: x words
-
- CLOCK CYCLES: [cycle count equation for this module] + [variable
-           used to represent cycle count for each subroutine
-           called]
-
-     where: [cycle count variable] = cycle count for [subroutine
-        name] (see [filename].ext)
-
-------------------------------------------------------------------------------
-*/
-
-
-/*----------------------------------------------------------------------------
-; INCLUDES
-----------------------------------------------------------------------------*/
-#include    "mp4dec_lib.h"
-#include    "post_proc.h"
-
-#define OSCL_DISABLE_WARNING_CONV_POSSIBLE_LOSS_OF_DATA
-
-/*----------------------------------------------------------------------------
-; MACROS
-; Define module specific macros here
-----------------------------------------------------------------------------*/
-//#define FILTER_LEN_8
-
-/*----------------------------------------------------------------------------
-; DEFINES
-; Include all pre-processor statements here. Include conditional
-; compile variables also.
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL FUNCTION DEFINITIONS
-; Function Prototype declaration
-
-----------------------------------------------------------------------------
-; LOCAL STORE/BUFFER/POINTER DEFINITIONS
-; Variable declaration - defined here and used outside this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL FUNCTION REFERENCES
-; Declare functions defined elsewhere and referenced in this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
-; Declare variables used in this module but defined elsewhere
-----------------------------------------------------------------------------*/
-#ifdef PV_POSTPROC_ON
-
-/*************************************************************************
-    Function prototype : void CombinedHorzVertFilter(   uint8 *rec,
-                                                        int width,
-                                                        int height,
-                                                        int *QP_store,
-                                                        int chr,
-                                                        uint8 *pp_mod)
-    Parameters  :
-        rec     :   pointer to the decoded frame buffer.
-        width   :   width of decoded frame.
-        height  :   height of decoded frame
-        QP_store:   pointer to the array of QP corresponding to the decoded frame.
-                    It had only one value for each MB.
-        chr     :   luma or color indication
-                    == 0 luma
-                    == 1 color
-        pp_mod  :   The semphore used for deblocking
-
-    Remark      :   The function do the deblocking on decoded frames.
-                    First based on the semaphore info., it is divided into hard and soft filtering.
-                    To differentiate real and fake edge, it then check the difference with QP to
-                    decide whether to do the filtering or not.
-
-*************************************************************************/
-
-
-/*----------------------------------------------------------------------------
-; FUNCTION CODE
-----------------------------------------------------------------------------*/
-void CombinedHorzVertFilter(
-    uint8 *rec,
-    int width,
-    int height,
-    int16 *QP_store,
-    int chr,
-    uint8 *pp_mod)
-{
-
-    /*----------------------------------------------------------------------------
-    ; Define all local variables
-    ----------------------------------------------------------------------------*/
-    int br, bc, mbr, mbc;
-    int QP = 1;
-    uint8 *ptr, *ptr_e;
-    int pp_w, pp_h;
-    int brwidth;
-
-    int jVal0, jVal1, jVal2;
-    /*----------------------------------------------------------------------------
-    ; Function body here
-    ----------------------------------------------------------------------------*/
-    pp_w = (width >> 3);
-    pp_h = (height >> 3);
-
-    for (mbr = 0; mbr < pp_h; mbr += 2)         /* row of blocks */
-    {
-        brwidth = mbr * pp_w;               /* number of blocks above current block row */
-        for (mbc = 0; mbc < pp_w; mbc += 2)     /* col of blocks */
-        {
-            if (!chr)
-                QP = QP_store[(brwidth>>2) + (mbc>>1)]; /* QP is per MB based value */
-
-            /********* for each block **************/
-            /****************** Horiz. Filtering ********************/
-            for (br = mbr + 1; br < mbr + 3; br++)  /* 2x2 blocks */
-            {
-                brwidth += pp_w;                    /* number of blocks above & left current block row */
-                /* the profile on ARM920T shows separate these two boundary check is faster than combine them */
-                if (br < pp_h)                  /* boundary : don't do it on the lowest row block */
-                    for (bc = mbc; bc < mbc + 2; bc++)
-                    {
-                        /****** check boundary for deblocking ************/
-                        if (bc < pp_w)              /* boundary : don't do it on the most right col block */
-                        {
-                            ptr = rec + (brwidth << 6) + (bc << 3);
-                            jVal0 = brwidth + bc;
-                            if (chr)    QP = QP_store[jVal0];
-
-                            ptr_e = ptr + 8;        /* pointer to where the loop ends */
-
-                            if (((pp_mod[jVal0]&0x02)) && ((pp_mod[jVal0-pp_w]&0x02)))
-                            {
-                                /* Horiz Hard filter */
-                                do
-                                {
-                                    jVal0 = *(ptr - width);     /* C */
-                                    jVal1 = *ptr;               /* D */
-                                    jVal2 = jVal1 - jVal0;
-
-                                    if (((jVal2 > 0) && (jVal2 < (QP << 1)))
-                                            || ((jVal2 < 0) && (jVal2 > -(QP << 1)))) /* (D-C) compared with 2QP */
-                                    {
-                                        /* differentiate between real and fake edge */
-                                        jVal0 = ((jVal0 + jVal1) >> 1);     /* (D+C)/2 */
-                                        *(ptr - width) = (uint8)(jVal0);    /*  C */
-                                        *ptr = (uint8)(jVal0);          /*  D */
-
-                                        jVal0 = *(ptr - (width << 1));      /* B */
-                                        jVal1 = *(ptr + width);         /* E */
-                                        jVal2 = jVal1 - jVal0;      /* E-B */
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal0 += ((jVal2 + 3) >> 2);
-                                            jVal1 -= ((jVal2 + 3) >> 2);
-                                            *(ptr - (width << 1)) = (uint8)jVal0;       /*  store B */
-                                            *(ptr + width) = (uint8)jVal1;          /* store E */
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal0 -= ((3 - jVal2) >> 2);
-                                            jVal1 += ((3 - jVal2) >> 2);
-                                            *(ptr - (width << 1)) = (uint8)jVal0;       /*  store B */
-                                            *(ptr + width) = (uint8)jVal1;          /* store E */
-                                        }
-
-                                        jVal0 = *(ptr - (width << 1) - width);  /* A */
-                                        jVal1 = *(ptr + (width << 1));      /* F */
-                                        jVal2 = jVal1 - jVal0;              /* (F-A) */
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal0 += ((jVal2 + 7) >> 3);
-                                            jVal1 -= ((jVal2 + 7) >> 3);
-                                            *(ptr - (width << 1) - width) = (uint8)(jVal0);
-                                            *(ptr + (width << 1)) = (uint8)(jVal1);
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal0 -= ((7 - jVal2) >> 3);
-                                            jVal1 += ((7 - jVal2) >> 3);
-                                            *(ptr - (width << 1) - width) = (uint8)(jVal0);
-                                            *(ptr + (width << 1)) = (uint8)(jVal1);
-                                        }
-                                    }/* a3_0 > 2QP */
-                                }
-                                while (++ptr < ptr_e);
-                            }
-                            else   /* Horiz soft filter*/
-                            {
-                                do
-                                {
-                                    jVal0 = *(ptr - width); /* B */
-                                    jVal1 = *ptr;           /* C */
-                                    jVal2 = jVal1 - jVal0;  /* C-B */
-
-                                    if (((jVal2 > 0) && (jVal2 < (QP)))
-                                            || ((jVal2 < 0) && (jVal2 > -(QP)))) /* (C-B) compared with QP */
-                                    {
-
-                                        jVal0 = ((jVal0 + jVal1) >> 1);     /* (B+C)/2 cannot overflow; ceil() */
-                                        *(ptr - width) = (uint8)(jVal0);    /* B = (B+C)/2 */
-                                        *ptr = (uint8)jVal0;            /* C = (B+C)/2 */
-
-                                        jVal0 = *(ptr - (width << 1));      /* A */
-                                        jVal1 = *(ptr + width);         /* D */
-                                        jVal2 = jVal1 - jVal0;          /* D-A */
-
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal1 -= ((jVal2 + 7) >> 3);
-                                            jVal0 += ((jVal2 + 7) >> 3);
-                                            *(ptr - (width << 1)) = (uint8)jVal0;       /* A */
-                                            *(ptr + width) = (uint8)jVal1;          /* D */
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal1 += ((7 - jVal2) >> 3);
-                                            jVal0 -= ((7 - jVal2) >> 3);
-                                            *(ptr - (width << 1)) = (uint8)jVal0;       /* A */
-                                            *(ptr + width) = (uint8)jVal1;          /* D */
-                                        }
-                                    }
-                                }
-                                while (++ptr < ptr_e);
-                            } /* Soft filter*/
-                        }/* boundary checking*/
-                    }/*bc*/
-            }/*br*/
-            brwidth -= (pp_w << 1);
-            /****************** Vert. Filtering ********************/
-            for (br = mbr; br < mbr + 2; br++)
-            {
-                if (br < pp_h)
-                    for (bc = mbc + 1; bc < mbc + 3; bc++)
-                    {
-                        /****** check boundary for deblocking ************/
-                        if (bc < pp_w)
-                        {
-                            ptr = rec + (brwidth << 6) + (bc << 3);
-                            jVal0 = brwidth + bc;
-                            if (chr)    QP = QP_store[jVal0];
-
-                            ptr_e = ptr + (width << 3);
-
-                            if (((pp_mod[jVal0-1]&0x01)) && ((pp_mod[jVal0]&0x01)))
-                            {
-                                /* Vert Hard filter */
-                                do
-                                {
-                                    jVal1 = *ptr;       /* D */
-                                    jVal0 = *(ptr - 1); /* C */
-                                    jVal2 = jVal1 - jVal0;  /* D-C */
-
-                                    if (((jVal2 > 0) && (jVal2 < (QP << 1)))
-                                            || ((jVal2 < 0) && (jVal2 > -(QP << 1))))
-                                    {
-                                        jVal1 = (jVal0 + jVal1) >> 1;   /* (C+D)/2 */
-                                        *ptr        =   jVal1;
-                                        *(ptr - 1)  =   jVal1;
-
-                                        jVal1 = *(ptr + 1);     /* E */
-                                        jVal0 = *(ptr - 2);     /* B */
-                                        jVal2 = jVal1 - jVal0;      /* E-B */
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal1 -= ((jVal2 + 3) >> 2);        /* E = E -(E-B)/4 */
-                                            jVal0 += ((jVal2 + 3) >> 2);        /* B = B +(E-B)/4 */
-                                            *(ptr + 1) = jVal1;
-                                            *(ptr - 2) = jVal0;
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal1 += ((3 - jVal2) >> 2);        /* E = E -(E-B)/4 */
-                                            jVal0 -= ((3 - jVal2) >> 2);        /* B = B +(E-B)/4 */
-                                            *(ptr + 1) = jVal1;
-                                            *(ptr - 2) = jVal0;
-                                        }
-
-                                        jVal1 = *(ptr + 2);     /* F */
-                                        jVal0 = *(ptr - 3);     /* A */
-
-                                        jVal2 = jVal1 - jVal0;          /* (F-A) */
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal1 -= ((jVal2 + 7) >> 3);    /* F -= (F-A)/8 */
-                                            jVal0 += ((jVal2 + 7) >> 3);    /* A += (F-A)/8 */
-                                            *(ptr + 2) = jVal1;
-                                            *(ptr - 3) = jVal0;
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal1 -= ((jVal2 - 7) >> 3);    /* F -= (F-A)/8 */
-                                            jVal0 += ((jVal2 - 7) >> 3);    /* A += (F-A)/8 */
-                                            *(ptr + 2) = jVal1;
-                                            *(ptr - 3) = jVal0;
-                                        }
-                                    }   /* end of ver hard filetering */
-                                }
-                                while ((ptr += width) < ptr_e);
-                            }
-                            else   /* Vert soft filter*/
-                            {
-                                do
-                                {
-                                    jVal1 = *ptr;               /* C */
-                                    jVal0 = *(ptr - 1);         /* B */
-                                    jVal2 = jVal1 - jVal0;
-
-                                    if (((jVal2 > 0) && (jVal2 < (QP)))
-                                            || ((jVal2 < 0) && (jVal2 > -(QP))))
-                                    {
-
-                                        jVal1 = (jVal0 + jVal1 + 1) >> 1;
-                                        *ptr = jVal1;           /* C */
-                                        *(ptr - 1) = jVal1;     /* B */
-
-                                        jVal1 = *(ptr + 1);     /* D */
-                                        jVal0 = *(ptr - 2);     /* A */
-                                        jVal2 = (jVal1 - jVal0);        /* D- A */
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal1 -= (((jVal2) + 7) >> 3);      /* D -= (D-A)/8 */
-                                            jVal0 += (((jVal2) + 7) >> 3);      /* A += (D-A)/8 */
-                                            *(ptr + 1) = jVal1;
-                                            *(ptr - 2) = jVal0;
-
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal1 += ((7 - (jVal2)) >> 3);      /* D -= (D-A)/8 */
-                                            jVal0 -= ((7 - (jVal2)) >> 3);      /* A += (D-A)/8 */
-                                            *(ptr + 1) = jVal1;
-                                            *(ptr - 2) = jVal0;
-                                        }
-                                    }
-                                }
-                                while ((ptr += width) < ptr_e);
-                            } /* Soft filter*/
-                        } /* boundary*/
-                    } /*bc*/
-                brwidth += pp_w;
-            }/*br*/
-            brwidth -= (pp_w << 1);
-        }/*mbc*/
-        brwidth += (pp_w << 1);
-    }/*mbr*/
-    /*----------------------------------------------------------------------------
-    ; Return nothing or data or data pointer
-    ----------------------------------------------------------------------------*/
-    return;
-}
-void CombinedHorzVertFilter_NoSoftDeblocking(
-    uint8 *rec,
-    int width,
-    int height,
-    int16 *QP_store,
-    int chr,
-    uint8 *pp_mod)
-{
-
-    /*----------------------------------------------------------------------------
-    ; Define all local variables
-    ----------------------------------------------------------------------------*/
-    int br, bc, mbr, mbc;
-    int QP = 1;
-    uint8 *ptr, *ptr_e;
-    int pp_w, pp_h;
-    int brwidth;
-
-    int jVal0, jVal1, jVal2;
-    /*----------------------------------------------------------------------------
-    ; Function body here
-    ----------------------------------------------------------------------------*/
-    pp_w = (width >> 3);
-    pp_h = (height >> 3);
-
-    for (mbr = 0; mbr < pp_h; mbr += 2)         /* row of blocks */
-    {
-        brwidth = mbr * pp_w;               /* number of blocks above current block row */
-        for (mbc = 0; mbc < pp_w; mbc += 2)     /* col of blocks */
-        {
-            if (!chr)
-                QP = QP_store[(brwidth>>2) + (mbc>>1)]; /* QP is per MB based value */
-
-            /********* for each block **************/
-            /****************** Horiz. Filtering ********************/
-            for (br = mbr + 1; br < mbr + 3; br++)  /* 2x2 blocks */
-            {
-                brwidth += pp_w;                    /* number of blocks above & left current block row */
-                /* the profile on ARM920T shows separate these two boundary check is faster than combine them */
-                if (br < pp_h)                  /* boundary : don't do it on the lowest row block */
-                    for (bc = mbc; bc < mbc + 2; bc++)
-                    {
-                        /****** check boundary for deblocking ************/
-                        if (bc < pp_w)              /* boundary : don't do it on the most right col block */
-                        {
-                            ptr = rec + (brwidth << 6) + (bc << 3);
-                            jVal0 = brwidth + bc;
-                            if (chr)    QP = QP_store[jVal0];
-
-                            ptr_e = ptr + 8;        /* pointer to where the loop ends */
-
-                            if (((pp_mod[jVal0]&0x02)) && ((pp_mod[jVal0-pp_w]&0x02)))
-                            {
-                                /* Horiz Hard filter */
-                                do
-                                {
-                                    jVal0 = *(ptr - width);     /* C */
-                                    jVal1 = *ptr;               /* D */
-                                    jVal2 = jVal1 - jVal0;
-
-                                    if (((jVal2 > 0) && (jVal2 < (QP << 1)))
-                                            || ((jVal2 < 0) && (jVal2 > -(QP << 1)))) /* (D-C) compared with 2QP */
-                                    {
-                                        /* differentiate between real and fake edge */
-                                        jVal0 = ((jVal0 + jVal1) >> 1);     /* (D+C)/2 */
-                                        *(ptr - width) = (uint8)(jVal0);    /*  C */
-                                        *ptr = (uint8)(jVal0);          /*  D */
-
-                                        jVal0 = *(ptr - (width << 1));      /* B */
-                                        jVal1 = *(ptr + width);         /* E */
-                                        jVal2 = jVal1 - jVal0;      /* E-B */
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal0 += ((jVal2 + 3) >> 2);
-                                            jVal1 -= ((jVal2 + 3) >> 2);
-                                            *(ptr - (width << 1)) = (uint8)jVal0;       /*  store B */
-                                            *(ptr + width) = (uint8)jVal1;          /* store E */
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal0 -= ((3 - jVal2) >> 2);
-                                            jVal1 += ((3 - jVal2) >> 2);
-                                            *(ptr - (width << 1)) = (uint8)jVal0;       /*  store B */
-                                            *(ptr + width) = (uint8)jVal1;          /* store E */
-                                        }
-
-                                        jVal0 = *(ptr - (width << 1) - width);  /* A */
-                                        jVal1 = *(ptr + (width << 1));      /* F */
-                                        jVal2 = jVal1 - jVal0;              /* (F-A) */
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal0 += ((jVal2 + 7) >> 3);
-                                            jVal1 -= ((jVal2 + 7) >> 3);
-                                            *(ptr - (width << 1) - width) = (uint8)(jVal0);
-                                            *(ptr + (width << 1)) = (uint8)(jVal1);
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal0 -= ((7 - jVal2) >> 3);
-                                            jVal1 += ((7 - jVal2) >> 3);
-                                            *(ptr - (width << 1) - width) = (uint8)(jVal0);
-                                            *(ptr + (width << 1)) = (uint8)(jVal1);
-                                        }
-                                    }/* a3_0 > 2QP */
-                                }
-                                while (++ptr < ptr_e);
-                            }
-
-                        }/* boundary checking*/
-                    }/*bc*/
-            }/*br*/
-            brwidth -= (pp_w << 1);
-            /****************** Vert. Filtering ********************/
-            for (br = mbr; br < mbr + 2; br++)
-            {
-                if (br < pp_h)
-                    for (bc = mbc + 1; bc < mbc + 3; bc++)
-                    {
-                        /****** check boundary for deblocking ************/
-                        if (bc < pp_w)
-                        {
-                            ptr = rec + (brwidth << 6) + (bc << 3);
-                            jVal0 = brwidth + bc;
-                            if (chr)    QP = QP_store[jVal0];
-
-                            ptr_e = ptr + (width << 3);
-
-                            if (((pp_mod[jVal0-1]&0x01)) && ((pp_mod[jVal0]&0x01)))
-                            {
-                                /* Vert Hard filter */
-                                do
-                                {
-                                    jVal1 = *ptr;       /* D */
-                                    jVal0 = *(ptr - 1); /* C */
-                                    jVal2 = jVal1 - jVal0;  /* D-C */
-
-                                    if (((jVal2 > 0) && (jVal2 < (QP << 1)))
-                                            || ((jVal2 < 0) && (jVal2 > -(QP << 1))))
-                                    {
-                                        jVal1 = (jVal0 + jVal1) >> 1;   /* (C+D)/2 */
-                                        *ptr        =   jVal1;
-                                        *(ptr - 1)  =   jVal1;
-
-                                        jVal1 = *(ptr + 1);     /* E */
-                                        jVal0 = *(ptr - 2);     /* B */
-                                        jVal2 = jVal1 - jVal0;      /* E-B */
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal1 -= ((jVal2 + 3) >> 2);        /* E = E -(E-B)/4 */
-                                            jVal0 += ((jVal2 + 3) >> 2);        /* B = B +(E-B)/4 */
-                                            *(ptr + 1) = jVal1;
-                                            *(ptr - 2) = jVal0;
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal1 += ((3 - jVal2) >> 2);        /* E = E -(E-B)/4 */
-                                            jVal0 -= ((3 - jVal2) >> 2);        /* B = B +(E-B)/4 */
-                                            *(ptr + 1) = jVal1;
-                                            *(ptr - 2) = jVal0;
-                                        }
-
-                                        jVal1 = *(ptr + 2);     /* F */
-                                        jVal0 = *(ptr - 3);     /* A */
-
-                                        jVal2 = jVal1 - jVal0;          /* (F-A) */
-
-                                        if (jVal2 > 0)
-                                        {
-                                            jVal1 -= ((jVal2 + 7) >> 3);    /* F -= (F-A)/8 */
-                                            jVal0 += ((jVal2 + 7) >> 3);    /* A += (F-A)/8 */
-                                            *(ptr + 2) = jVal1;
-                                            *(ptr - 3) = jVal0;
-                                        }
-                                        else if (jVal2)
-                                        {
-                                            jVal1 -= ((jVal2 - 7) >> 3);    /* F -= (F-A)/8 */
-                                            jVal0 += ((jVal2 - 7) >> 3);    /* A += (F-A)/8 */
-                                            *(ptr + 2) = jVal1;
-                                            *(ptr - 3) = jVal0;
-                                        }
-                                    }   /* end of ver hard filetering */
-                                }
-                                while ((ptr += width) < ptr_e);
-                            }
-
-                        } /* boundary*/
-                    } /*bc*/
-                brwidth += pp_w;
-            }/*br*/
-            brwidth -= (pp_w << 1);
-        }/*mbc*/
-        brwidth += (pp_w << 1);
-    }/*mbr*/
-    /*----------------------------------------------------------------------------
-    ; Return nothing or data or data pointer
-    ----------------------------------------------------------------------------*/
-    return;
-}
-#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/chvr_filter.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/chvr_filter.cpp
deleted file mode 100644
index 795cf71..0000000
--- a/media/libstagefright/codecs/m4v_h263/dec/src/chvr_filter.cpp
+++ /dev/null
@@ -1,565 +0,0 @@
-/* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
- *
- * 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    "mp4dec_lib.h"
-#include    "post_proc.h"
-
-#ifdef PV_POSTPROC_ON
-
-void CombinedHorzVertRingFilter(
-    uint8 *rec,
-    int width,
-    int height,
-    int16 *QP_store,
-    int chr,
-    uint8 *pp_mod)
-{
-
-    /*----------------------------------------------------------------------------
-    ; Define all local variables
-    ----------------------------------------------------------------------------*/
-    int index, counter;
-    int br, bc, incr, mbr, mbc;
-    int QP = 1;
-    int v[5];
-    uint8 *ptr, *ptr_c, *ptr_n;
-    int w1, w2, w3, w4;
-    int pp_w, pp_h, brwidth;
-    int sum, delta;
-    int a3_0, a3_1, a3_2, A3_0;
-    /* for Deringing Threshold approach (MPEG4)*/
-    int max_diff, thres, v0, h0, min_blk, max_blk;
-    int cnthflag;
-
-    /*----------------------------------------------------------------------------
-    ; Function body here
-    ----------------------------------------------------------------------------*/
-    /* Calculate the width and height of the area in blocks (divide by 8) */
-    pp_w = (width >> 3);
-    pp_h = (height >> 3);
-
-    /* Set up various values needed for updating pointers into rec */
-    w1 = width;             /* Offset to next row in pixels */
-    w2 = width << 1;        /* Offset to two rows in pixels */
-    w3 = w1 + w2;           /* Offset to three rows in pixels */
-    w4 = w2 << 1;           /* Offset to four rows in pixels */
-    incr = width - BLKSIZE; /* Offset to next row after processing block */
-
-    /* Work through the area hortizontally by two rows per step */
-    for (mbr = 0; mbr < pp_h; mbr += 2)
-    {
-        /* brwidth contains the block number of the leftmost block
-         * of the current row */
-        brwidth = mbr * pp_w;
-
-        /* Work through the area vertically by two columns per step */
-        for (mbc = 0; mbc < pp_w; mbc += 2)
-        {
-            /* if the data is luminance info, get the correct
-                    * quantization paramenter. One parameter per macroblock */
-            if (!chr)
-            {
-                /* brwidth/4 is the macroblock number and mbc/2 is the macroblock col number*/
-                QP = QP_store[(brwidth>>2) + (mbc>>1)];
-            }
-
-            /****************** Horiz. Filtering ********************/
-            /* Process four blocks for the filtering        */
-            /********************************************************/
-            /* Loop over two rows of blocks */
-            for (br = mbr + 1; br < mbr + 3; br++)    /* br is the row counter in blocks */
-            {
-                /* Set brwidth to the first (leftmost) block number of the next row */
-                /* brwidth is used as an index when counting blocks */
-                brwidth += pp_w;
-
-                /* Loop over two columns of blocks in the row */
-                for (bc = mbc; bc < mbc + 2; bc++)    /* bc is the column counter in blocks */
-                {
-                    /****** check boundary for deblocking ************/
-                    /* Execute if the row and column counters are within the area */
-                    if (br < pp_h && bc < pp_w)
-                    {
-                        /* Set the ptr to the first pixel of the first block of the second row
-                        * brwidth * 64 is the pixel row offset
-                        * bc * 8 is the pixel column offset */
-                        ptr = rec + (brwidth << 6) + (bc << 3);
-
-                        /* Set the index to the current block of the second row counting in blocks */
-                        index = brwidth + bc;
-
-                        /* if the data is chrominance info, get the correct
-                         * quantization paramenter. One parameter per block. */
-                        if (chr)
-                        {
-                            QP = QP_store[index];
-                        }
-
-                        /* Execute hard horizontal filter if semaphore for horizontal deblocking
-                          * is set for the current block and block immediately above it */
-                        if (((pp_mod[index]&0x02) != 0) && ((pp_mod[index-pp_w]&0x02) != 0))
-                        {   /* Hard filter */
-
-                            /* Set HorzHflag (bit 4) in the pp_mod location */
-                            pp_mod[index-pp_w] |= 0x10; /*  4/26/00 reuse pp_mod for HorzHflag*/
-
-                            /* Filter across the 8 pixels of the block */
-                            for (index = BLKSIZE; index > 0; index--)
-                            {
-                                /* Difference between the current pixel and the pixel above it */
-                                a3_0 = *ptr - *(ptr - w1);
-
-                                /* if the magnitude of the difference is greater than the KThH threshold
-                                 * and within the quantization parameter, apply hard filter */
-                                if ((a3_0 > KThH || a3_0 < -KThH) && a3_0<QP && a3_0> -QP)
-                                {
-                                    ptr_c = ptr - w3;   /* Points to pixel three rows above */
-                                    ptr_n = ptr + w1;   /* Points to pixel one row below */
-                                    v[0] = (int)(*(ptr_c - w3));
-                                    v[1] = (int)(*(ptr_c - w2));
-                                    v[2] = (int)(*(ptr_c - w1));
-                                    v[3] = (int)(*ptr_c);
-                                    v[4] = (int)(*(ptr_c + w1));
-
-                                    sum = v[0]
-                                          + v[1]
-                                          + v[2]
-                                          + *ptr_c
-                                          + v[4]
-                                          + (*(ptr_c + w2))
-                                          + (*(ptr_c + w3));  /* Current pixel */
-
-                                    delta = (sum + *ptr_c + 4) >> 3;   /* Average pixel values with rounding */
-                                    *(ptr_c) = (uint8) delta;
-
-                                    /* Move pointer down one row of pixels (points to pixel two rows
-                                     * above current pixel) */
-                                    ptr_c += w1;
-
-                                    for (counter = 0; counter < 5; counter++)
-                                    {
-                                        /* Subtract off highest pixel and add in pixel below */
-                                        sum = sum - v[counter] + *ptr_n;
-                                        /* Average the pixel values with rounding */
-                                        delta = (sum + *ptr_c + 4) >> 3;
-                                        *ptr_c = (uint8)(delta);
-
-                                        /* Increment pointers to next pixel row */
-                                        ptr_c += w1;
-                                        ptr_n += w1;
-                                    }
-                                }
-                                /* Increment pointer to next pixel */
-                                ++ptr;
-                            } /* index*/
-                        }
-                        else
-                        { /* soft filter*/
-
-                            /* Clear HorzHflag (bit 4) in the pp_mod location */
-                            pp_mod[index-pp_w] &= 0xef; /* reset 1110,1111 */
-
-                            for (index = BLKSIZE; index > 0; index--)
-                            {
-                                /* Difference between the current pixel and the pixel above it */
-                                a3_0 = *(ptr) - *(ptr - w1);
-
-                                /* if the magnitude of the difference is greater than the KTh threshold,
-                                 * apply soft filter */
-                                if ((a3_0 > KTh || a3_0 < -KTh))
-                                {
-
-                                    /* Sum of weighted differences */
-                                    a3_0 += ((*(ptr - w2) - *(ptr + w1)) << 1) + (a3_0 << 2);
-
-                                    /* Check if sum is less than the quantization parameter */
-                                    if (PV_ABS(a3_0) < (QP << 3))
-                                    {
-                                        a3_1 = *(ptr - w2) - *(ptr - w3);
-                                        a3_1 += ((*(ptr - w4) - *(ptr - w1)) << 1) + (a3_1 << 2);
-
-                                        a3_2  = *(ptr + w2) - *(ptr + w1);
-                                        a3_2 += ((*(ptr) - *(ptr + w3)) << 1) + (a3_2 << 2);
-
-                                        A3_0 = PV_ABS(a3_0) - PV_MIN(PV_ABS(a3_1), PV_ABS(a3_2));
-
-                                        if (A3_0 > 0)
-                                        {
-                                            A3_0 += A3_0 << 2;
-                                            A3_0 = (A3_0 + 32) >> 6;
-                                            if (a3_0 > 0)
-                                            {
-                                                A3_0 = -A3_0;
-                                            }
-
-                                            delta = (*(ptr - w1) - *(ptr)) >> 1;
-                                            if (delta >= 0)
-                                            {
-                                                if (delta >= A3_0)
-                                                {
-                                                    delta = PV_MAX(A3_0, 0);
-                                                }
-                                            }
-                                            else
-                                            {
-                                                if (A3_0 > 0)
-                                                {
-                                                    delta = 0;
-                                                }
-                                                else
-                                                {
-                                                    delta = PV_MAX(A3_0, delta);
-                                                }
-                                            }
-
-                                            *(ptr - w1) = (uint8)(*(ptr - w1) - delta);
-                                            *(ptr) = (uint8)(*(ptr) + delta);
-                                        }
-                                    } /*threshold*/
-                                }
-                                /* Increment pointer to next pixel */
-                                ++ptr;
-                            } /*index*/
-                        } /* Soft filter*/
-                    }/* boundary checking*/
-                }/*bc*/
-            }/*br*/
-            brwidth -= (pp_w << 1);
-
-
-            /****************** Vert. Filtering *********************/
-            /* Process four blocks for the filtering        */
-            /********************************************************/
-            /* Loop over two rows of blocks */
-            for (br = mbr; br < mbr + 2; br++)      /* br is the row counter in blocks */
-            {
-                for (bc = mbc + 1; bc < mbc + 3; bc++)  /* bc is the column counter in blocks */
-                {
-                    /****** check boundary for deblocking ************/
-                    /* Execute if the row and column counters are within the area */
-                    if (br < pp_h && bc < pp_w)
-                    {
-                        /* Set the ptr to the first pixel of the first block of the second row
-                        * brwidth * 64 is the pixel row offset
-                        * bc * 8 is the pixel column offset */
-                        ptr = rec + (brwidth << 6) + (bc << 3);
-
-                        /* Set the index to the current block of the second row counting in blocks */
-                        index = brwidth + bc;
-
-                        /* if the data is chrominance info, get the correct
-                         * quantization paramenter. One parameter per block. */
-                        if (chr)
-                        {
-                            QP = QP_store[index];
-                        }
-
-                        /* Execute hard vertical filter if semaphore for vertical deblocking
-                          * is set for the current block and block immediately left of it */
-                        if (((pp_mod[index-1]&0x01) != 0) && ((pp_mod[index]&0x01) != 0))
-                        {   /* Hard filter */
-
-                            /* Set VertHflag (bit 5) in the pp_mod location of previous block*/
-                            pp_mod[index-1] |= 0x20; /*  4/26/00 reuse pp_mod for VertHflag*/
-
-                            /* Filter across the 8 pixels of the block */
-                            for (index = BLKSIZE; index > 0; index--)
-                            {
-                                /* Difference between the current pixel
-                                * and the pixel to left of it */
-                                a3_0 = *ptr - *(ptr - 1);
-
-                                /* if the magnitude of the difference is greater than the KThH threshold
-                                 * and within the quantization parameter, apply hard filter */
-                                if ((a3_0 > KThH || a3_0 < -KThH) && a3_0<QP && a3_0> -QP)
-                                {
-                                    ptr_c = ptr - 3;
-                                    ptr_n = ptr + 1;
-                                    v[0] = (int)(*(ptr_c - 3));
-                                    v[1] = (int)(*(ptr_c - 2));
-                                    v[2] = (int)(*(ptr_c - 1));
-                                    v[3] = (int)(*ptr_c);
-                                    v[4] = (int)(*(ptr_c + 1));
-
-                                    sum = v[0]
-                                          + v[1]
-                                          + v[2]
-                                          + *ptr_c
-                                          + v[4]
-                                          + (*(ptr_c + 2))
-                                          + (*(ptr_c + 3));
-
-                                    delta = (sum + *ptr_c + 4) >> 3;
-                                    *(ptr_c) = (uint8) delta;
-
-                                    /* Move pointer down one pixel to the right */
-                                    ptr_c += 1;
-                                    for (counter = 0; counter < 5; counter++)
-                                    {
-                                        /* Subtract off highest pixel and add in pixel below */
-                                        sum = sum - v[counter] + *ptr_n;
-                                        /* Average the pixel values with rounding */
-                                        delta = (sum + *ptr_c + 4) >> 3;
-                                        *ptr_c = (uint8)(delta);
-
-                                        /* Increment pointers to next pixel */
-                                        ptr_c += 1;
-                                        ptr_n += 1;
-                                    }
-                                }
-                                /* Increment pointers to next pixel row */
-                                ptr += w1;
-                            } /* index*/
-                        }
-                        else
-                        { /* soft filter*/
-
-                            /* Clear VertHflag (bit 5) in the pp_mod location */
-                            pp_mod[index-1] &= 0xdf; /* reset 1101,1111 */
-                            for (index = BLKSIZE; index > 0; index--)
-                            {
-                                /* Difference between the current pixel and the pixel above it */
-                                a3_0 = *(ptr) - *(ptr - 1);
-
-                                /* if the magnitude of the difference is greater than the KTh threshold,
-                                 * apply soft filter */
-                                if ((a3_0 > KTh || a3_0 < -KTh))
-                                {
-
-                                    /* Sum of weighted differences */
-                                    a3_0 += ((*(ptr - 2) - *(ptr + 1)) << 1) + (a3_0 << 2);
-
-                                    /* Check if sum is less than the quantization parameter */
-                                    if (PV_ABS(a3_0) < (QP << 3))
-                                    {
-                                        a3_1 = *(ptr - 2) - *(ptr - 3);
-                                        a3_1 += ((*(ptr - 4) - *(ptr - 1)) << 1) + (a3_1 << 2);
-
-                                        a3_2  = *(ptr + 2) - *(ptr + 1);
-                                        a3_2 += ((*(ptr) - *(ptr + 3)) << 1) + (a3_2 << 2);
-
-                                        A3_0 = PV_ABS(a3_0) - PV_MIN(PV_ABS(a3_1), PV_ABS(a3_2));
-
-                                        if (A3_0 > 0)
-                                        {
-                                            A3_0 += A3_0 << 2;
-                                            A3_0 = (A3_0 + 32) >> 6;
-                                            if (a3_0 > 0)
-                                            {
-                                                A3_0 = -A3_0;
-                                            }
-
-                                            delta = (*(ptr - 1) - *(ptr)) >> 1;
-                                            if (delta >= 0)
-                                            {
-                                                if (delta >= A3_0)
-                                                {
-                                                    delta = PV_MAX(A3_0, 0);
-                                                }
-                                            }
-                                            else
-                                            {
-                                                if (A3_0 > 0)
-                                                {
-                                                    delta = 0;
-                                                }
-                                                else
-                                                {
-                                                    delta = PV_MAX(A3_0, delta);
-                                                }
-                                            }
-
-                                            *(ptr - 1) = (uint8)(*(ptr - 1) - delta);
-                                            *(ptr) = (uint8)(*(ptr) + delta);
-                                        }
-                                    } /*threshold*/
-                                }
-                                ptr += w1;
-                            } /*index*/
-                        } /* Soft filter*/
-                    } /* boundary*/
-                } /*bc*/
-                /* Increment pointer to next row of pixels */
-                brwidth += pp_w;
-            }/*br*/
-            brwidth -= (pp_w << 1);
-
-            /****************** Deringing ***************************/
-            /* Process four blocks for the filtering        */
-            /********************************************************/
-            /* Loop over two rows of blocks */
-            for (br = mbr; br < mbr + 2; br++)
-            {
-                /* Loop over two columns of blocks in the row */
-                for (bc = mbc; bc < mbc + 2; bc++)
-                {
-                    /* Execute if the row and column counters are within the area */
-                    if (br < pp_h && bc < pp_w)
-                    {
-                        /* Set the index to the current block */
-                        index = brwidth + bc;
-
-                        /* Execute deringing if semaphore for deringing (bit-3 of pp_mod)
-                         * is set for the current block */
-                        if ((pp_mod[index]&0x04) != 0)
-                        {
-                            /* Don't process deringing if on an edge block */
-                            if (br > 0 && bc > 0 && br < pp_h - 1 && bc < pp_w - 1)
-                            {
-                                /* cnthflag = weighted average of HorzHflag of current,
-                                 * one above, previous blocks*/
-                                cnthflag = ((pp_mod[index] & 0x10) +
-                                            (pp_mod[index-pp_w] & 0x10) +
-                                            ((pp_mod[index-1] >> 1) & 0x10) +
-                                            ((pp_mod[index] >> 1) & 0x10)) >> 4; /* 4/26/00*/
-
-                                /* Do the deringing if decision flags indicate it's necessary */
-                                if (cnthflag < 3)
-                                {
-                                    /* if the data is chrominance info, get the correct
-                                     * quantization paramenter. One parameter per block. */
-                                    if (chr)
-                                    {
-                                        QP = QP_store[index];
-                                    }
-
-                                    /* Set amount to change luminance if it needs to be changed
-                                     * based on quantization parameter */
-                                    max_diff = (QP >> 2) + 4;
-
-                                    /* Set pointer to first pixel of current block */
-                                    ptr = rec + (brwidth << 6) + (bc << 3);
-
-                                    /* Find minimum and maximum value of pixel block */
-                                    FindMaxMin(ptr, &min_blk, &max_blk, incr);
-
-                                    /* threshold determination */
-                                    thres = (max_blk + min_blk + 1) >> 1;
-
-                                    /* If pixel range is greater or equal than DERING_THR, smooth the region */
-                                    if ((max_blk - min_blk) >= DERING_THR) /*smooth 8x8 region*/
-#ifndef NoMMX
-                                    {
-                                        /* smooth all pixels in the block*/
-                                        DeringAdaptiveSmoothMMX(ptr, width, thres, max_diff);
-                                    }
-#else
-                                    {
-                                        /* Setup the starting point of the region to smooth */
-                                        v0 = (br << 3) - 1;
-                                        h0 = (bc << 3) - 1;
-
-                                        /*smooth 8x8 region*/
-                                        AdaptiveSmooth_NoMMX(rec, v0, h0, v0 + 1, h0 + 1, thres, width, max_diff);
-                                    }
-#endif
-                                }/*cnthflag*/
-                            } /*dering br==1 or bc==1 (boundary block)*/
-                            else    /* Process the boundary blocks */
-                            {
-                                /* Decide to perform deblocking based on the semaphore flags
-                                   * of the neighboring blocks in each case. A certain number of
-                                 * hard filtering flags have to be set in order to signal need
-                                 * for smoothing */
-                                if (br > 0 && br < pp_h - 1)
-                                {
-                                    if (bc > 0)
-                                    {
-                                        cnthflag = ((pp_mod[index-pp_w] & 0x10) +
-                                                    (pp_mod[index] & 0x10) +
-                                                    ((pp_mod[index-1] >> 1) & 0x10)) >> 4;
-                                    }
-                                    else
-                                    {
-                                        cnthflag = ((pp_mod[index] & 0x10) +
-                                                    (pp_mod[index-pp_w] & 0x10) +
-                                                    ((pp_mod[index] >> 1) & 0x10)) >> 4;
-                                    }
-                                }
-                                else if (bc > 0 && bc < pp_w - 1)
-                                {
-                                    if (br > 0)
-                                    {
-                                        cnthflag = ((pp_mod[index-pp_w] & 0x10) +
-                                                    ((pp_mod[index-1] >> 1) & 0x10) +
-                                                    ((pp_mod[index] >> 1) & 0x10)) >> 4;
-                                    }
-                                    else
-                                    {
-                                        cnthflag = ((pp_mod[index] & 0x10) +
-                                                    ((pp_mod[index-1] >> 1) & 0x10) +
-                                                    ((pp_mod[index] >> 1) & 0x10)) >> 4;
-                                    }
-                                }
-                                else /* at the corner do default*/
-                                {
-                                    cnthflag = 0;
-                                }
-
-                                /* Do the deringing if decision flags indicate it's necessary */
-                                if (cnthflag < 2)
-                                {
-
-                                    /* if the data is chrominance info, get the correct
-                                                         * quantization paramenter. One parameter per block. */
-                                    if (chr)
-                                    {
-                                        QP = QP_store[index];
-                                    }
-
-                                    /* Set amount to change luminance if it needs to be changed
-                                     * based on quantization parameter */
-                                    max_diff = (QP >> 2) + 4;
-
-                                    /* Set pointer to first pixel of current block */
-                                    ptr = rec + (brwidth << 6) + (bc << 3);
-
-                                    /* Find minimum and maximum value of pixel block */
-                                    FindMaxMin(ptr, &min_blk, &max_blk, incr);
-
-                                    /* threshold determination */
-                                    thres = (max_blk + min_blk + 1) >> 1;
-
-                                    /* Setup the starting point of the region to smooth
-                                     * This is going to be a 4x4 region */
-                                    v0 = (br << 3) + 1;
-                                    h0 = (bc << 3) + 1;
-
-                                    /* If pixel range is greater or equal than DERING_THR, smooth the region */
-                                    if ((max_blk - min_blk) >= DERING_THR)
-                                    {
-                                        /* Smooth 4x4 region */
-                                        AdaptiveSmooth_NoMMX(rec, v0, h0, v0 - 3, h0 - 3, thres, width, max_diff);
-                                    }
-                                }/*cnthflag*/
-                            } /* br==0, bc==0*/
-                        }  /* dering*/
-                    } /*boundary condition*/
-                }/*bc*/
-                brwidth += pp_w;
-            }/*br*/
-            brwidth -= (pp_w << 1);
-        }/*mbc*/
-        brwidth += (pp_w << 1);
-    }/*mbr*/
-
-    /*----------------------------------------------------------------------------
-    ; Return nothing or data or data pointer
-    ----------------------------------------------------------------------------*/
-    return ;
-}
-#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/deringing_chroma.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/deringing_chroma.cpp
deleted file mode 100644
index ce779b0..0000000
--- a/media/libstagefright/codecs/m4v_h263/dec/src/deringing_chroma.cpp
+++ /dev/null
@@ -1,215 +0,0 @@
-/* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
- *
- * 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    "mp4dec_lib.h"
-#include    "post_proc.h"
-
-#ifdef PV_POSTPROC_ON
-
-void Deringing_Chroma(
-    uint8 *Rec_C,
-    int width,
-    int height,
-    int16 *QP_store,
-    int,
-    uint8 *pp_mod
-)
-{
-    /*----------------------------------------------------------------------------
-    ; Define all local variables
-    ----------------------------------------------------------------------------*/
-    int thres;
-    int v_blk, h_blk;
-    int max_diff;
-    int v_pel, h_pel;
-    int max_blk, min_blk;
-    int v0, h0;
-    uint8 *ptr;
-    int sum, sum1, incr;
-    int32 addr_v;
-    int sign_v[10], sum_v[10];
-    int *ptr2, *ptr3;
-    uint8 pelu, pelc, pell;
-    incr = width - BLKSIZE;
-
-    /*----------------------------------------------------------------------------
-    ; Function body here
-    ----------------------------------------------------------------------------*/
-    /* chrominance */
-    /* Do the first line (7 pixels at a time => Don't use MMX)*/
-    for (h_blk = 0; h_blk < width; h_blk += BLKSIZE)
-    {
-        max_diff = (QP_store[h_blk>>3] >> 2) + 4;
-        ptr = &Rec_C[h_blk];
-        max_blk = min_blk = *ptr;
-        FindMaxMin(ptr, &min_blk, &max_blk, width);
-        h0 = ((h_blk - 1) >= 1) ? (h_blk - 1) : 1;
-
-        if (max_blk - min_blk >= 4)
-        {
-            thres = (max_blk + min_blk + 1) >> 1;
-
-
-            for (v_pel = 1; v_pel < BLKSIZE - 1; v_pel++)
-            {
-                addr_v = (int32)v_pel * width;
-                ptr = &Rec_C[addr_v + h0 - 1];
-                ptr2 = &sum_v[0];
-                ptr3 = &sign_v[0];
-
-                pelu = *(ptr - width);
-                pelc = *ptr;
-                pell = *(ptr + width);
-                ptr++;
-                *ptr2++ = pelu + (pelc << 1) + pell;
-                *ptr3++ = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
-
-                pelu = *(ptr - width);
-                pelc = *ptr;
-                pell = *(ptr + width);
-                ptr++;
-                *ptr2++ = pelu + (pelc << 1) + pell;
-                *ptr3++ = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
-
-                for (h_pel = h0; h_pel < h_blk + BLKSIZE - 1; h_pel++)
-                {
-                    pelu = *(ptr - width);
-                    pelc = *ptr;
-                    pell = *(ptr + width);
-
-                    *ptr2 = pelu + (pelc << 1) + pell;
-                    *ptr3 = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
-
-                    sum1 = *(ptr3 - 2) + *(ptr3 - 1) + *ptr3;
-                    if (sum1 == 0 || sum1 == 9)
-                    {
-                        sum = (*(ptr2 - 2) + (*(ptr2 - 1) << 1) + *ptr2 + 8) >> 4;
-
-                        ptr--;
-                        if (PV_ABS(*ptr - sum) > max_diff)
-                        {
-                            if (sum > *ptr)
-                                sum = *ptr + max_diff;
-                            else
-                                sum = *ptr - max_diff;
-                        }
-                        *ptr++ = (uint8) sum;
-                    }
-                    ptr++;
-                    ptr2++;
-                    ptr3++;
-                }
-            }
-        }
-    }
-
-    for (v_blk = BLKSIZE; v_blk < height; v_blk += BLKSIZE)
-    {
-        v0 = v_blk - 1;
-        /* Do the first block (pixels=7 => No MMX) */
-        max_diff = (QP_store[((((int32)v_blk*width)>>3))>>3] >> 2) + 4;
-        ptr = &Rec_C[(int32)v_blk * width];
-        max_blk = min_blk = *ptr;
-        FindMaxMin(ptr, &min_blk, &max_blk, incr);
-
-        if (max_blk - min_blk >= 4)
-        {
-            thres = (max_blk + min_blk + 1) >> 1;
-
-            for (v_pel = v0; v_pel < v_blk + BLKSIZE - 1; v_pel++)
-            {
-                addr_v = v_pel * width;
-                ptr = &Rec_C[addr_v];
-                ptr2 = &sum_v[0];
-                ptr3 = &sign_v[0];
-
-                pelu = *(ptr - width);
-                pelc = *ptr;
-                pell = *(ptr + width);
-                ptr++;
-                *ptr2++ = pelu + (pelc << 1) + pell;
-                *ptr3++ = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
-
-                pelu = *(ptr - width);
-                pelc = *ptr;
-                pell = *(ptr + width);
-                ptr++;
-                *ptr2++ = pelu + (pelc << 1) + pell;
-                *ptr3++ = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
-
-                for (h_pel = 1; h_pel < BLKSIZE - 1; h_pel++)
-                {
-                    pelu = *(ptr - width);
-                    pelc = *ptr;
-                    pell = *(ptr + width);
-
-                    *ptr2 = pelu + (pelc << 1) + pell;
-                    *ptr3 = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
-
-                    sum1 = *(ptr3 - 2) + *(ptr3 - 1) + *ptr3;
-                    if (sum1 == 0 || sum1 == 9)
-                    {
-                        sum = (*(ptr2 - 2) + (*(ptr2 - 1) << 1) + *ptr2 + 8) >> 4;
-
-                        ptr--;
-                        if (PV_ABS(*ptr - sum) > max_diff)
-                        {
-                            if (sum > *ptr)
-                                sum = *ptr + max_diff;
-                            else
-                                sum = *ptr - max_diff;
-                        }
-                        *ptr++ = (uint8) sum;
-                    }
-                    ptr++;
-                    ptr2++;
-                    ptr3++;
-                }
-            }
-        }
-
-
-        /* Do the rest in MMX */
-        for (h_blk = BLKSIZE; h_blk < width; h_blk += BLKSIZE)
-        {
-            if ((pp_mod[(v_blk/8)*(width/8)+h_blk/8]&0x4) != 0)
-            {
-                max_diff = (QP_store[((((int32)v_blk*width)>>3)+h_blk)>>3] >> 2) + 4;
-                ptr = &Rec_C[(int32)v_blk * width + h_blk];
-                max_blk = min_blk = *ptr;
-                FindMaxMin(ptr, &min_blk, &max_blk, incr);
-                h0 = h_blk - 1;
-
-                if (max_blk - min_blk >= 4)
-                {
-                    thres = (max_blk + min_blk + 1) >> 1;
-#ifdef NoMMX
-                    AdaptiveSmooth_NoMMX(Rec_C, v0, h0, v_blk, h_blk, thres, width, max_diff);
-#else
-                    DeringAdaptiveSmoothMMX(&Rec_C[(int32)v0*width+h0], width, thres, max_diff);
-#endif
-                }
-            }
-        }
-    } /* macroblock level */
-
-    /*----------------------------------------------------------------------------
-    ; Return nothing or data or data pointer
-    ----------------------------------------------------------------------------*/
-    return;
-}
-#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/deringing_luma.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/deringing_luma.cpp
deleted file mode 100644
index b5574b4..0000000
--- a/media/libstagefright/codecs/m4v_h263/dec/src/deringing_luma.cpp
+++ /dev/null
@@ -1,231 +0,0 @@
-/* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
- *
- * 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    "mp4dec_lib.h"
-#include    "post_proc.h"
-
-#ifdef PV_POSTPROC_ON
-
-void Deringing_Luma(
-    uint8 *Rec_Y,
-    int width,
-    int height,
-    int16 *QP_store,
-    int,
-    uint8 *pp_mod)
-{
-    /*----------------------------------------------------------------------------
-    ; Define all local variables
-    ----------------------------------------------------------------------------*/
-    int thres[4], range[4], max_range_blk, max_thres_blk;
-    int MB_V, MB_H, BLK_V, BLK_H;
-    int v_blk, h_blk;
-    int max_diff;
-    int max_blk, min_blk;
-    int v0, h0;
-    uint8 *ptr;
-    int thr, blks, incr;
-    int mb_indx, blk_indx;
-
-    /*----------------------------------------------------------------------------
-    ; Function body here
-    ----------------------------------------------------------------------------*/
-    incr = width - BLKSIZE;
-
-    /* Dering the first line of macro blocks */
-    for (MB_H = 0; MB_H < width; MB_H += MBSIZE)
-    {
-        max_diff = (QP_store[(MB_H)>>4] >> 2) + 4;
-
-        /* threshold determination */
-        max_range_blk = max_thres_blk = 0;
-        blks = 0;
-
-        for (BLK_V = 0; BLK_V < MBSIZE; BLK_V += BLKSIZE)
-        {
-            for (BLK_H = 0; BLK_H < MBSIZE; BLK_H += BLKSIZE)
-            {
-                ptr = &Rec_Y[(int32)(BLK_V) * width + MB_H + BLK_H];
-                FindMaxMin(ptr, &min_blk, &max_blk, incr);
-
-                thres[blks] = (max_blk + min_blk + 1) >> 1;
-                range[blks] = max_blk - min_blk;
-
-                if (range[blks] >= max_range_blk)
-                {
-                    max_range_blk = range[blks];
-                    max_thres_blk = thres[blks];
-                }
-                blks++;
-            }
-        }
-
-        blks = 0;
-        for (v_blk = 0; v_blk < MBSIZE; v_blk += BLKSIZE)
-        {
-            v0 = ((v_blk - 1) >= 1) ? (v_blk - 1) : 1;
-            for (h_blk = MB_H; h_blk < MB_H + MBSIZE; h_blk += BLKSIZE)
-            {
-                h0 = ((h_blk - 1) >= 1) ? (h_blk - 1) : 1;
-
-                /* threshold rearrangement for flat region adjacent to non-flat region */
-                if (range[blks]<32 && max_range_blk >= 64)
-                    thres[blks] = max_thres_blk;
-
-                /* threshold rearrangement for deblocking
-                (blockiness annoying at DC dominant region) */
-                if (max_range_blk >= 16)
-                {
-                    /* adaptive smoothing */
-                    thr = thres[blks];
-
-                    AdaptiveSmooth_NoMMX(Rec_Y, v0, h0, v_blk, h_blk,
-                                         thr, width, max_diff);
-                }
-                blks++;
-            } /* block level (Luminance) */
-        }
-    } /* macroblock level */
-
-
-    /* Do the rest of the macro-block-lines */
-    for (MB_V = MBSIZE; MB_V < height; MB_V += MBSIZE)
-    {
-        /* First macro-block */
-        max_diff = (QP_store[((((int32)MB_V*width)>>4))>>4] >> 2) + 4;
-        /* threshold determination */
-        max_range_blk = max_thres_blk = 0;
-        blks = 0;
-        for (BLK_V = 0; BLK_V < MBSIZE; BLK_V += BLKSIZE)
-        {
-            for (BLK_H = 0; BLK_H < MBSIZE; BLK_H += BLKSIZE)
-            {
-                ptr = &Rec_Y[(int32)(MB_V + BLK_V) * width + BLK_H];
-                FindMaxMin(ptr, &min_blk, &max_blk, incr);
-                thres[blks] = (max_blk + min_blk + 1) >> 1;
-                range[blks] = max_blk - min_blk;
-
-                if (range[blks] >= max_range_blk)
-                {
-                    max_range_blk = range[blks];
-                    max_thres_blk = thres[blks];
-                }
-                blks++;
-            }
-        }
-
-        blks = 0;
-        for (v_blk = MB_V; v_blk < MB_V + MBSIZE; v_blk += BLKSIZE)
-        {
-            v0 = v_blk - 1;
-            for (h_blk = 0; h_blk < MBSIZE; h_blk += BLKSIZE)
-            {
-                h0 = ((h_blk - 1) >= 1) ? (h_blk - 1) : 1;
-
-                /* threshold rearrangement for flat region adjacent to non-flat region */
-                if (range[blks]<32 && max_range_blk >= 64)
-                    thres[blks] = max_thres_blk;
-
-                /* threshold rearrangement for deblocking
-                (blockiness annoying at DC dominant region) */
-                if (max_range_blk >= 16)
-                {
-                    /* adaptive smoothing */
-                    thr = thres[blks];
-
-                    AdaptiveSmooth_NoMMX(Rec_Y, v0, h0, v_blk, h_blk,
-                                         thr, width, max_diff);
-                }
-                blks++;
-            }
-        } /* block level (Luminance) */
-
-        /* Rest of the macro-blocks */
-        for (MB_H = MBSIZE; MB_H < width; MB_H += MBSIZE)
-        {
-            max_diff = (QP_store[((((int32)MB_V*width)>>4)+MB_H)>>4] >> 2) + 4;
-
-            /* threshold determination */
-            max_range_blk = max_thres_blk = 0;
-            blks = 0;
-
-            mb_indx = (MB_V / 8) * (width / 8) + MB_H / 8;
-            for (BLK_V = 0; BLK_V < MBSIZE; BLK_V += BLKSIZE)
-            {
-                for (BLK_H = 0; BLK_H < MBSIZE; BLK_H += BLKSIZE)
-                {
-                    blk_indx = mb_indx + (BLK_V / 8) * width / 8 + BLK_H / 8;
-                    /* Update based on pp_mod only */
-                    if ((pp_mod[blk_indx]&0x4) != 0)
-                    {
-                        ptr = &Rec_Y[(int32)(MB_V + BLK_V) * width + MB_H + BLK_H];
-                        FindMaxMin(ptr, &min_blk, &max_blk, incr);
-                        thres[blks] = (max_blk + min_blk + 1) >> 1;
-                        range[blks] = max_blk - min_blk;
-
-                        if (range[blks] >= max_range_blk)
-                        {
-                            max_range_blk = range[blks];
-                            max_thres_blk = thres[blks];
-                        }
-                    }
-                    blks++;
-                }
-            }
-
-            blks = 0;
-            for (v_blk = MB_V; v_blk < MB_V + MBSIZE; v_blk += BLKSIZE)
-            {
-                v0 = v_blk - 1;
-                mb_indx = (v_blk / 8) * (width / 8);
-                for (h_blk = MB_H; h_blk < MB_H + MBSIZE; h_blk += BLKSIZE)
-                {
-                    h0 = h_blk - 1;
-                    blk_indx = mb_indx + h_blk / 8;
-                    if ((pp_mod[blk_indx]&0x4) != 0)
-                    {
-                        /* threshold rearrangement for flat region adjacent to non-flat region */
-                        if (range[blks]<32 && max_range_blk >= 64)
-                            thres[blks] = max_thres_blk;
-
-                        /* threshold rearrangement for deblocking
-                        (blockiness annoying at DC dominant region) */
-                        if (max_range_blk >= 16)
-                        {
-                            /* adaptive smoothing */
-                            thr = thres[blks];
-#ifdef NoMMX
-                            AdaptiveSmooth_NoMMX(Rec_Y, v0, h0, v_blk, h_blk,
-                                                 thr, width, max_diff);
-#else
-                            DeringAdaptiveSmoothMMX(&Rec_Y[v0*width+h0],
-                                                    width, thr, max_diff);
-#endif
-                        }
-                    }
-                    blks++;
-                }
-            } /* block level (Luminance) */
-        } /* macroblock level */
-    } /* macroblock level */
-
-    /*----------------------------------------------------------------------------
-    ; Return nothing or data or data pointer
-    ----------------------------------------------------------------------------*/
-    return;
-}
-#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/find_min_max.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/find_min_max.cpp
deleted file mode 100644
index 1ac88a1..0000000
--- a/media/libstagefright/codecs/m4v_h263/dec/src/find_min_max.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-/* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
- *
- * 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.
- * -------------------------------------------------------------------
- */
-/*
-------------------------------------------------------------------------------
- INPUT AND OUTPUT DEFINITIONS
-
- Inputs:
-    input_ptr = pointer to the buffer containing values of type UChar
-            in a 2D block of data.
-    min_ptr = pointer to the minimum value of type Int to be found in a
-          square block of size BLKSIZE contained in 2D block of data.
-    max_ptr = pointer to the maximum value of type Int to be found in a
-          square block of size BLKSIZE contained in 2D block of data.
-    incr = value of type Int representing the width of 2D block of data.
-
- Local Stores/Buffers/Pointers Needed:
-    None
-
- Global Stores/Buffers/Pointers Needed:
-    None
-
- Outputs:
-    None
-
- Pointers and Buffers Modified:
-    min_ptr points to the found minimum value in the square block of
-    size BLKSIZE contained in 2D block of data.
-
-    max_ptr points to the found maximum value in the square block of
-    size BLKSIZE contained in 2D block of data.
-
- Local Stores Modified:
-    None
-
- Global Stores Modified:
-    None
-
-------------------------------------------------------------------------------
- FUNCTION DESCRIPTION
-
- This function finds the maximum and the minimum values in a square block of
- data of size BLKSIZE * BLKSIZE. The data is contained in the buffer which
- represents a 2D block of data that is larger than BLKSIZE * BLKSIZE.
- This is illustrated below.
-
-    mem loc x + 00h -> o o o o o o o o o o o o o o o o
-    mem loc x + 10h -> o o o o o X X X X X X X X o o o
-    mem loc x + 20h -> o o o o o X X X X X X X X o o o
-    mem loc x + 30h -> o o o o o X X X X X X X X o o o
-    mem loc x + 40h -> o o o o o X X X X X X X X o o o
-    mem loc x + 50h -> o o o o o X X X X X X X X o o o
-    mem loc x + 60h -> o o o o o X X X X X X X X o o o
-    mem loc x + 70h -> o o o o o X X X X X X X X o o o
-    mem loc x + 80h -> o o o o o X X X X X X X X o o o
-    mem loc x + 90h -> o o o o o o o o o o o o o o o o
-    mem loc x + A0h -> o o o o o o o o o o o o o o o o
-    mem loc x + B0h -> o o o o o o o o o o o o o o o o
-
-For illustration purposes, the diagram assumes that BLKSIZE is equal to 8
-but this is not a requirement. In this diagram, the buffer starts at
-location x but the input pointer, input_ptr, passed into this function
-would be the first row of data to be searched which is at x + 15h. The
-value of incr passed onto this function represents the amount the input_ptr
-needs to be incremented to point to the next row of data.
-
-This function compares each value in a row to the current maximum and
-minimum. After each row, input_ptr is incremented to point to the next row.
-This is repeated until all rows have been processed. When the search is
-complete the location pointed to by min_ptr contains the minimum value
-found and the location pointed to by max_ptr contains the maximum value found.
-
-------------------------------------------------------------------------------
-*/
-
-
-/*----------------------------------------------------------------------------
-; INCLUDES
-----------------------------------------------------------------------------*/
-#include    "mp4dec_lib.h"
-#include    "post_proc.h"
-
-/*----------------------------------------------------------------------------
-; MACROS
-; Define module specific macros here
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; DEFINES
-; Include all pre-processor statements here. Include conditional
-; compile variables also.
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL FUNCTION DEFINITIONS
-; Function Prototype declaration
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL STORE/BUFFER/POINTER DEFINITIONS
-; Variable declaration - defined here and used outside this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL FUNCTION REFERENCES
-; Declare functions defined elsewhere and referenced in this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
-; Declare variables used in this module but defined elsewhere
-----------------------------------------------------------------------------*/
-
-#ifdef PV_POSTPROC_ON
-/*----------------------------------------------------------------------------
-; FUNCTION CODE
-----------------------------------------------------------------------------*/
-void  FindMaxMin(
-    uint8 *input_ptr,
-    int *min_ptr,
-    int *max_ptr,
-    int incr)
-{
-    /*----------------------------------------------------------------------------
-    ; Define all local variables
-    ----------------------------------------------------------------------------*/
-    uint    i, j;
-    int min, max;
-
-    /*----------------------------------------------------------------------------
-    ; Function body here
-    ----------------------------------------------------------------------------*/
-    max = min = *input_ptr;
-    /*  incr = incr - BLKSIZE; */   /*  09/06/2001, already passed in as width - BLKSIZE */
-
-    for (i = BLKSIZE; i > 0; i--)
-    {
-        for (j = BLKSIZE; j > 0; j--)
-        {
-            if (*input_ptr > max)
-            {
-                max = *input_ptr;
-            }
-            else if (*input_ptr < min)
-            {
-                min = *input_ptr;
-            }
-            input_ptr += 1;
-        }
-
-        /* set pointer to the beginning of the next row*/
-        input_ptr += incr;
-    }
-
-    *max_ptr = max;
-    *min_ptr = min;
-    /*----------------------------------------------------------------------------
-    ; Return nothing or data or data pointer
-    ----------------------------------------------------------------------------*/
-    return;
-}
-#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/post_proc_semaphore.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/post_proc_semaphore.cpp
deleted file mode 100644
index 3abc6be..0000000
--- a/media/libstagefright/codecs/m4v_h263/dec/src/post_proc_semaphore.cpp
+++ /dev/null
@@ -1,247 +0,0 @@
-/* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
- *
- * 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.
- * -------------------------------------------------------------------
- */
-/*
-------------------------------------------------------------------------------
- INPUT AND OUTPUT DEFINITIONS
-
- Inputs:
-    q_block = pointer to buffer of inverse quantized DCT coefficients of type
-              int for intra-VOP mode or buffer of residual data of type int
-              for inter-VOP mode
-
- Local Stores/Buffers/Pointers Needed:
-    None
-
- Global Stores/Buffers/Pointers Needed:
-    None
-
- Outputs:
-    postmode = post processing semaphore with the vertical deblocking,
-               horizontal deblocking, and deringing bits set up accordingly
-
- Pointers and Buffers Modified:
-    None
-
- Local Stores Modified:
-    None
-
- Global Stores Modified:
-    None
-
-------------------------------------------------------------------------------
- FUNCTION DESCRIPTION
-
- This function sets up the postmode semaphore based on the contents of the
- buffer pointed to by q_block. The function starts out with the assumption
- that all entries of q_block, except for the first entry (q_block[0]), are
- zero. This case can induce horizontal and vertical blocking artifacts,
- therefore, both horizontal and vertical deblocking bits are enabled.
-
- The following conditions are tested when setting up the horizontal/vertical
- deblocking and deringing bits:
- 1. When only the elements of the top row of the B_SIZE x B_SIZE block
-    (q_block[n], n = 0,..., B_SIZE-1) are non-zero, vertical blocking artifacts
-    may result, therefore, only the vertical deblocking bit is enabled.
-    Otherwise, the vertical deblocking bit is disabled.
- 2. When only the elements of the far left column of the B_SIZE x B_SIZE block
-    (q_block[n*B_SIZE], n = 0, ..., B_SIZE-1) are non-zero, horizontal blocking
-    artifacts may result, therefore, only the horizontal deblocking bit is
-    enabled. Otherwise, the horizontal deblocking bit is disabled.
- 3. If any non-zero elements exist in positions other than q_block[0],
-    q_block[1], or q_block[B_SIZE], the deringing bit is enabled. Otherwise,
-    it is disabled.
-
- The 3 least significant bits of postmode defines vertical or horizontal
- deblocking and deringing.
-
- The valid values are shown below:
- -------------------------------------------------------
- |           Type                 | Enabled | Disabled |
- -------------------------------------------------------
- | Vertical Deblocking (Bit #0)   |    1    |     0    |
- -------------------------------------------------------
- | Horizontal Deblocking (Bit #1) |    1    |     0    |
- -------------------------------------------------------
- | Deringing (Bit #2)             |    1    |     0    |
- -------------------------------------------------------
-
-*/
-
-
-/*----------------------------------------------------------------------------
-; INCLUDES
-----------------------------------------------------------------------------*/
-#include    "mp4dec_lib.h"
-#include    "mp4def.h"
-#include    "post_proc.h"
-
-/*----------------------------------------------------------------------------
-; MACROS
-; Define module specific macros here
-----------------------------------------------------------------------------*/
-
-
-/*----------------------------------------------------------------------------
-; DEFINES
-; Include all pre-processor statements here. Include conditional
-; compile variables also.
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL FUNCTION DEFINITIONS
-; Function Prototype declaration
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL STORE/BUFFER/POINTER DEFINITIONS
-; Variable declaration - defined here and used outside this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL FUNCTION REFERENCES
-; Declare functions defined elsewhere and referenced in this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
-; Declare variables used in this module but defined elsewhere
-----------------------------------------------------------------------------*/
-#ifdef PV_POSTPROC_ON
-/*----------------------------------------------------------------------------
-; FUNCTION CODE
-----------------------------------------------------------------------------*/
-int PostProcSemaphore(
-    int16 *q_block)
-{
-    /*----------------------------------------------------------------------------
-    ; Define all local variables
-    ----------------------------------------------------------------------------*/
-    int i, j;
-
-    /* Set default value to vertical and horizontal deblocking enabled */
-    /* Initial assumption is that only q_block[0] element is non-zero, */
-    /* therefore, vertical and horizontal deblocking bits are set to 1 */
-    int postmode = 0x3;
-
-    /*----------------------------------------------------------------------------
-    ; Function body here
-    ----------------------------------------------------------------------------*/
-    /* Vertical deblocking bit is enabled when only the entire top row of   */
-    /* the B_SIZE x B_SIZE block, i.e., q_block[n], n = 0,..., B_SIZE-1,    */
-    /* are non-zero. Since initial assumption is that all elements, except  */
-    /* q_block[0], is zero, we need to check the remaining elements in the  */
-    /* top row to  determine if all or some are non-zero.                   */
-    if (q_block[1] != 0)
-    {
-        /* At this point, q_block[0] and q_block[1] are non-zero, while */
-        /* q_block[n], n = 2,..., B_SIZE-1, are zero. Therefore, we     */
-        /* need to disable vertical deblocking                          */
-        postmode &= 0xE;
-    }
-
-    for (i = 2; i < B_SIZE; i++)
-    {
-        if (q_block[i])
-        {
-            /* Check if q_block[n], n = 2,..., B_SIZE-1, are non-zero.*/
-            /* If any of them turn out to be non-zero, we need to     */
-            /* disable vertical deblocking.                           */
-            postmode &= 0xE;
-
-            /* Deringing is enabled if any nonzero elements exist in */
-            /* positions other than q_block[0], q_block[1] or        */
-            /* q_block[B_SIZE].                                      */
-            postmode |= 0x4;
-
-            break;
-        }
-    }
-
-    /* Horizontal deblocking bit is enabled when only the entire far */
-    /* left column, i.e., q_block[n*B_SIZE], n = 0, ..., B_SIZE-1,   */
-    /* are non-zero. Since initial assumption is that all elements,  */
-    /* except q_block[0], is zero, we need to check the remaining    */
-    /* elements in the far left column to determine if all or some   */
-    /* are non-zero.                                                 */
-    if (q_block[B_SIZE])
-    {
-        /* At this point, only q_block[0] and q_block[B_SIZE] are non-zero, */
-        /* while q_block[n*B_SIZE], n = 2, 3,..., B_SIZE-1, are zero.       */
-        /* Therefore, we need to disable horizontal deblocking.             */
-        postmode &= 0xD;
-    }
-
-    for (i = 16; i < NCOEFF_BLOCK; i += B_SIZE)
-    {
-        if (q_block[i])
-        {
-            /* Check if q_block[n], n = 2*B_SIZE,...,(B_SIZE-1)*B_SIZE,  */
-            /* are non-zero. If any of them turn out to be non-zero,     */
-            /* we need to disable horizontal deblocking.                 */
-            postmode &= 0xD;
-
-            /* Deringing is enabled if any nonzero elements exist in */
-            /* positions other than q_block[0], q_block[1] or        */
-            /* q_block[B_SIZE].                                      */
-            postmode |= 0x4;
-
-            break;
-        }
-    }
-
-    /* At this point, only the first row and far left column elements */
-    /* have been tested. If deringing bit is still not set at this    */
-    /* point, check the rest of q_block to determine if the elements  */
-    /* are non-zero. If all elements, besides q_block[0], q_block[1], */
-    /* or q_block[B_SIZE] are non-zero, deringing bit must be set     */
-    if ((postmode & 0x4) == 0)
-    {
-        for (i = 1; i < B_SIZE; i++)
-        {
-            for (j = 1; j < B_SIZE; j++)
-            {
-                if (q_block[(i<<3)+j])
-                {
-                    /* At this point, q_block[0] and another q_block */
-                    /* element are non-zero, therefore, we need to   */
-                    /* disable vertical and horizontal deblocking    */
-                    postmode &= 0xC;
-
-                    /* Deringing is enabled if any nonzero elements exist in */
-                    /* positions other than q_block[0], q_block[1] or        */
-                    /* q_block[B_SIZE].                                      */
-                    postmode |= 0x4;
-
-                    /* Set outer FOR loop count to B_SIZE to get out of */
-                    /* outer FOR loop                                   */
-                    i = B_SIZE;
-
-                    /* Get out of inner FOR loop */
-                    break;
-                }
-            }
-        }
-    }
-
-    /*----------------------------------------------------------------------------
-    ; Return nothing or data or data pointer
-    ----------------------------------------------------------------------------*/
-    return (postmode);
-}
-
-#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_chroma_inter.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_chroma_inter.cpp
deleted file mode 100644
index 7c20222..0000000
--- a/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_chroma_inter.cpp
+++ /dev/null
@@ -1,262 +0,0 @@
-/* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
- *
- * 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.
- * -------------------------------------------------------------------
- */
-/*
-------------------------------------------------------------------------------
- INPUT AND OUTPUT DEFINITIONS
-
- Inputs:
-    xpred = x-axis coordinate of the block used for prediction (int)
-    ypred = y-axis coordinate of the block used for prediction (int)
-    pp_dec_u = pointer to the post processing semaphore for chrominance
-               (uint8)
-    pstprcTypPrv = pointer the previous frame's post processing type
-                   (uint8)
-    dx = horizontal component of the motion vector (int)
-    dy = vertical component of the motion vector (int)
-    mvwidth = number of blocks per row in the luminance VOP (int)
-    height = luminance VOP height in pixels (int)
-    size = total number of pixel in the current luminance VOP (int)
-    mv_loc = flag indicating location of the motion compensated
-         (x,y) position with respect to the luminance MB (int);
-         0 -> inside MB, 1 -> outside MB
-    msk_deblock = flag indicating whether to perform deblocking
-              (msk_deblock = 0) or not (msk_deblock = 1) (uint8)
-
- Local Stores/Buffers/Pointers Needed:
-    None
-
- Global Stores/Buffers/Pointers Needed:
-    None
-
- Outputs:
-    None
-
- Pointers and Buffers Modified:
-    pp_dec_u contents are the updated semaphore propagation data
-
- Local Stores Modified:
-    None
-
- Global Stores Modified:
-    None
-
-------------------------------------------------------------------------------
- FUNCTION DESCRIPTION
-
- This functions performs post processing semaphore propagation processing
- after chrominance prediction in interframe processing mode.
-
-*/
-
-
-/*----------------------------------------------------------------------------
-; INCLUDES
-----------------------------------------------------------------------------*/
-#include    "mp4dec_api.h"
-#include    "mp4def.h"
-
-/*----------------------------------------------------------------------------
-; MACROS
-; Define module specific macros here
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; DEFINES
-; Include all pre-processor statements here. Include conditional
-; compile variables also.
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL FUNCTION DEFINITIONS
-; Function Prototype declaration
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL STORE/BUFFER/POINTER DEFINITIONS
-; Variable declaration - defined here and used outside this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL FUNCTION REFERENCES
-; Declare functions defined elsewhere and referenced in this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
-; Declare variables used in this module but defined elsewhere
-----------------------------------------------------------------------------*/
-#ifdef PV_POSTPROC_ON
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-    /*----------------------------------------------------------------------------
-    ; FUNCTION CODE
-    ----------------------------------------------------------------------------*/
-    void pp_semaphore_chroma_inter(
-        int xpred,      /* i */
-        int ypred,      /* i */
-        uint8   *pp_dec_u,  /* i/o */
-        uint8   *pstprcTypPrv,  /* i */
-        int dx,     /* i */
-        int dy,     /* i */
-        int mvwidth,    /* i */
-        int height,     /* i */
-        int32   size,       /* i */
-        int mv_loc,     /* i */
-        uint8   msk_deblock /* i */
-    )
-    {
-        /*----------------------------------------------------------------------------
-        ; Define all local variables
-        ----------------------------------------------------------------------------*/
-        int mmvy, mmvx, nmvy, nmvx;
-        uint8 *pp_prev1, *pp_prev2, *pp_prev3, *pp_prev4;
-
-        /*----------------------------------------------------------------------------
-        ; Function body here
-        ----------------------------------------------------------------------------*/
-
-        /* 09/28/2000, modify semaphore propagation to */
-        /* accommodate smart indexing */
-        mmvx = xpred >> 4;  /* block x coor */
-        nmvx = mmvx;
-
-        mmvy = ypred >> 4;  /* block y coor */
-        nmvy = mmvy;
-
-        /* Check if MV is outside the frame */
-        if (mv_loc == 1)
-        {
-            /* Perform boundary check */
-            if (nmvx < 0)
-            {
-                nmvx = 0;
-            }
-            else if (nmvx > mvwidth - 1)
-            {
-                nmvx = mvwidth - 1;
-            }
-
-            if (nmvy < 0)
-            {
-                nmvy = 0;
-            }
-            else if (nmvy > (height >> 4) - 1)
-            {
-                nmvy = (height >> 4) - 1;
-            }
-        }
-
-        /* Calculate pointer to first chrominance b semaphores in       */
-        /* pstprcTypPrv, i.e., first chrominance b semaphore is in      */
-        /* (pstprcTypPrv + (size>>6)).                  */
-        /* Since total number of chrominance blocks per row in a VOP    */
-        /* is half of the total number of luminance blocks per row in a */
-        /* VOP, we use (mvwidth >> 1) when calculating the row offset.  */
-        pp_prev1 = pstprcTypPrv + (size >> 6) + nmvx + nmvy * (mvwidth >> 1) ;
-
-        /* Check if MV is a multiple of 16 */
-        /*  1/5/01, make sure it doesn't go out of bound */
-        if (((dy&0xF) != 0) && (mmvy + 1 < (height >> 4) - 1))
-        {   /* dy is not a multiple of 16 */
-
-            /* pp_prev3 is the block below pp_prev1 block */
-            pp_prev3 = pp_prev1 + (mvwidth >> 1);
-        }
-        else
-        {   /* dy is a multiple of 16 */
-            pp_prev3 = pp_prev1;
-        }
-
-        /*  1/5/01, make sure it doesn't go out of bound */
-        if (((dx&0xF) != 0) && (mmvx + 1 < (mvwidth >> 1) - 1))
-        {   /* dx is not a multiple of 16 */
-
-            /* pp_prev2 is the block to the right of pp_prev1 block */
-            pp_prev2 = pp_prev1 + 1;
-
-            /* pp_prev4 is the block to the right of the block */
-            /* below pp_prev1 block                */
-            pp_prev4 = pp_prev3 + 1;
-        }
-        else
-        {   /* dx is a multiple of 16 */
-
-            pp_prev2 = pp_prev1;
-            pp_prev4 = pp_prev3;
-        }
-
-        /* Advance offset to location of first Chrominance R semaphore in */
-        /* pstprcTypPrv. Since the number of pixels in a Chrominance VOP  */
-        /* is (number of pixels in Luminance VOP/4), and there are 64     */
-        /* pixels in an 8x8 Chrominance block, the offset can be      */
-        /* calculated as:                         */
-        /*  mv_loc = (number of pixels in Luminance VOP/(4*64))   */
-        /*         = size/256 = size>>8               */
-        mv_loc = (size >> 8);
-
-        /*  11/3/00, change the propagation for deblocking */
-        if (msk_deblock == 0)
-        {
-
-            /* Deblocking semaphore propagation for Chrominance */
-            /* b semaphores                     */
-            *(pp_dec_u) = 0;
-
-            /* Advance offset to point to Chrominance r semaphores */
-            pp_dec_u += mv_loc;
-
-            /* Deblocking semaphore propagation for Chrominance */
-            /* r semaphores                     */
-            *(pp_dec_u) = 0;
-        }
-        else
-        {
-            /* Deringing semaphore propagation for Chrominance B block */
-            if ((*(pp_dec_u)&4) == 0)
-            {
-                *(pp_dec_u) |= ((*(pp_prev1) | *(pp_prev2) |
-                                 *(pp_prev3) | *(pp_prev4)) & 0x4);
-            }
-
-            /* Advance offset to point to Chrominance r semaphores */
-            pp_dec_u += mv_loc;
-            pp_prev1 += mv_loc;
-            pp_prev2 += mv_loc;
-            pp_prev3 += mv_loc;
-            pp_prev4 += mv_loc;
-
-            /* Deringing semaphore propagation for Chrominance R */
-            if ((*(pp_dec_u)&4) == 0)
-            {
-                *(pp_dec_u) |= ((*(pp_prev1) | *(pp_prev2) |
-                                 *(pp_prev3) | *(pp_prev4)) & 0x4);
-            }
-        }
-
-        /*----------------------------------------------------------------------------
-        ; Return nothing or data or data pointer
-        ----------------------------------------------------------------------------*/
-        return;
-    }
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_luma.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_luma.cpp
deleted file mode 100644
index b3a1ebd..0000000
--- a/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_luma.cpp
+++ /dev/null
@@ -1,378 +0,0 @@
-/* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
- *
- * 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.
- * -------------------------------------------------------------------
- */
-/*
-------------------------------------------------------------------------------
- INPUT AND OUTPUT DEFINITIONS
-
- Inputs:
-    xpred = x-axis coordinate of the MB used for prediction (int)
-    ypred = y-axis coordinate of the MB used for prediction (int)
-    pp_dec_y = pointer to the post processing semaphore for current
-           luminance frame (uint8)
-    pstprcTypPrv = pointer the previous frame's post processing type
-                   (uint8)
-    ll = pointer to the buffer (int)
-    mv_loc = flag indicating location of the motion compensated
-         (x,y) position with respect to the luminance MB (int);
-         0 -> inside MB, 1 -> outside MB
-    dx = horizontal component of the motion vector (int)
-    dy = vertical component of the motion vector (int)
-    mvwidth = number of blocks per row (int)
-    width = luminance VOP width in pixels (int)
-    height = luminance VOP height in pixels (int)
-
- Local Stores/Buffers/Pointers Needed:
-    None
-
- Global Stores/Buffers/Pointers Needed:
-    None
-
- Outputs:
-    msk_deblock = flag that indicates whether deblocking is to be
-              performed (msk_deblock = 0) or not (msk_deblock =
-              1) (uint8)
-
- Pointers and Buffers Modified:
-    pp_dec_y contents are the updated semapohore propagation data
-
- Local Stores Modified:
-    None
-
- Global Stores Modified:
-    None
-
-------------------------------------------------------------------------------
- FUNCTION DESCRIPTION
-
- This functions performs post processing semaphore propagation processing
- after luminance prediction.
-
-*/
-
-
-/*----------------------------------------------------------------------------
-; INCLUDES
-----------------------------------------------------------------------------*/
-#include    "mp4dec_api.h"
-#include    "mp4def.h"
-
-/*----------------------------------------------------------------------------
-; MACROS
-; Define module specific macros here
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; DEFINES
-; Include all pre-processor statements here. Include conditional
-; compile variables also.
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL FUNCTION DEFINITIONS
-; Function Prototype declaration
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; LOCAL STORE/BUFFER/POINTER DEFINITIONS
-; Variable declaration - defined here and used outside this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL FUNCTION REFERENCES
-; Declare functions defined elsewhere and referenced in this module
-----------------------------------------------------------------------------*/
-
-/*----------------------------------------------------------------------------
-; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
-; Declare variables used in this module but defined elsewhere
-----------------------------------------------------------------------------*/
-#ifdef PV_POSTPROC_ON
-#ifdef __cplusplus
-extern "C"
-{
-#endif
-    /*----------------------------------------------------------------------------
-    ; FUNCTION CODE
-    ----------------------------------------------------------------------------*/
-    uint8 pp_semaphore_luma(
-        int xpred,      /* i */
-        int ypred,      /* i */
-        uint8   *pp_dec_y,  /* i/o */
-        uint8   *pstprcTypPrv,  /* i */
-        int *ll,        /* i */
-        int *mv_loc,    /* i/o */
-        int dx,     /* i */
-        int dy,     /* i */
-        int mvwidth,    /* i */
-        int width,      /* i */
-        int height      /* i */
-    )
-    {
-        /*----------------------------------------------------------------------------
-        ; Define all local variables
-        ----------------------------------------------------------------------------*/
-        int kk, mmvy, mmvx, nmvx, nmvy;
-        uint8   *pp_prev1, *pp_prev2, *pp_prev3, *pp_prev4;
-        uint8   msk_deblock = 0;        /*  11/3/00 */
-
-        /*----------------------------------------------------------------------------
-        ; Function body here
-        ----------------------------------------------------------------------------*/
-        /* Interframe Processing - 1 MV per MB */
-
-        /* check whether the MV points outside the frame */
-        if (xpred >= 0 && xpred <= ((width << 1) - (2*MB_SIZE)) && ypred >= 0 &&
-                ypred <= ((height << 1) - (2*MB_SIZE)))
-        {   /*****************************/
-            /* (x,y) is inside the frame */
-            /*****************************/
-
-            /*  10/24/2000 post_processing semaphore */
-            /* generation */
-
-            /*  10/23/2000 no boundary checking*/
-            *mv_loc = 0;
-
-            /* Calculate block x coordinate. Divide by 16 is for  */
-            /* converting half-pixel resolution to block          */
-            mmvx = xpred >> 4;
-
-            /* Calculate block y coordinate. Divide by 16 is for */
-            /* converting half-pixel resolution to block         */
-            mmvy = ypred >> 4;
-
-            /* Find post processing semaphore location for block */
-            /* used for prediction, i.e.,                */
-            /* pp_prev1 = &pstprcTypPrv[mmvy*mvwidth][mmvx]      */
-            pp_prev1 = pstprcTypPrv + mmvx + mmvy * mvwidth;
-
-            /* Check if MV is a multiple of 16 */
-            if ((dx&0xF) != 0)
-            {   /* dx is not a multiple of 16 */
-
-                /* pp_prev2 is the block to the right of */
-                /* pp_prev1 block            */
-                pp_prev2 = pp_prev1 + 1;
-
-                if ((dy&0xF) != 0)
-                {   /* dy is not a multiple of 16 */
-
-                    /* pp_prev3 is the block below */
-                    /* pp_prev1 block          */
-                    pp_prev3 = pp_prev1 + mvwidth;
-                }
-                else
-                {   /* dy is a multiple of 16 */
-
-                    pp_prev3 = pp_prev1;
-                }
-
-                /* pp_prev4 is the block to the right of */
-                /* pp_prev3 block.           */
-                pp_prev4 = pp_prev3 + 1;
-            }
-            else
-            {   /* dx is a multiple of 16 */
-
-                pp_prev2 = pp_prev1;
-
-                if ((dy&0xF) != 0)
-                {   /* dy is not a multiple of 16 */
-
-                    /* pp_prev3 is the block below */
-                    /* pp_prev1 block.         */
-                    pp_prev3 = pp_prev1 + mvwidth;
-                }
-                else
-                {   /* dy is a multiple of 16 */
-
-                    pp_prev3 = pp_prev1;
-                    msk_deblock = 0x3;
-                }
-
-                pp_prev4 = pp_prev3;
-            }
-
-            /* Perform post processing semaphore propagation for each */
-            /* of the 4 blocks in a MB.               */
-            for (kk = 0; kk < 4; kk++)
-            {
-                /* Deringing semaphore propagation */
-                if ((*(pp_dec_y) & 4) == 0)
-                {
-                    *(pp_dec_y) |= ((*(pp_prev1) | *(pp_prev2) |
-                                     *(pp_prev3) | *(pp_prev4)) & 0x4);
-                }
-                /* Deblocking semaphore propagation */
-                /*  11/3/00, change the propagation for deblocking */
-                if (msk_deblock == 0)
-                {
-                    *(pp_dec_y) = 0;
-                }
-
-                pp_dec_y += ll[kk];
-                pp_prev1 += ll[kk];
-                pp_prev2 += ll[kk];
-                pp_prev3 += ll[kk];
-                pp_prev4 += ll[kk];
-            }
-
-        }
-        else
-        {   /******************************/
-            /* (x,y) is outside the frame */
-            /******************************/
-
-            /*  10/24/2000 post_processing semaphore */
-            /* generation */
-
-            /*  10/23/2000 boundary checking*/
-            *mv_loc = 1;
-
-            /* Perform post processing semaphore propagation for each */
-            /* of the 4 blocks in a MB.               */
-            for (kk = 0; kk < 4; kk++)
-            {
-                /* Calculate block x coordinate and round (?).  */
-                /* Divide by 16 is for converting half-pixel    */
-                /* resolution to block.             */
-                mmvx = (xpred + ((kk & 1) << 3)) >> 4;
-                nmvx = mmvx;
-
-                /* Calculate block y coordinate and round (?).  */
-                /* Divide by 16 is for converting half-pixel    */
-                /* resolution to block.             */
-                mmvy = (ypred + ((kk & 2) << 2)) >> 4;
-                nmvy = mmvy;
-
-                /* Perform boundary checking */
-                if (nmvx < 0)
-                {
-                    nmvx = 0;
-                }
-                else if (nmvx > mvwidth - 1)
-                {
-                    nmvx = mvwidth - 1;
-                }
-
-                if (nmvy < 0)
-                {
-                    nmvy = 0;
-                }
-                else if (nmvy > (height >> 3) - 1)
-                {
-                    nmvy = (height >> 3) - 1;
-                }
-
-                /* Find post processing semaphore location for block */
-                /* used for prediction, i.e.,                */
-                /* pp_prev1 = &pstprcTypPrv[nmvy*mvwidth][nmvx]      */
-                pp_prev1 = pstprcTypPrv + nmvx + nmvy * mvwidth;
-
-                /* Check if x component of MV is a multiple of 16    */
-                /* and check if block x coordinate is out of bounds  */
-                if (((dx&0xF) != 0) && (mmvx + 1 < mvwidth - 1))
-                {   /* dx is not a multiple of 16 and the block */
-                    /* x coordinate is within the bounds        */
-
-                    /* pp_prev2 is the block to the right of */
-                    /* pp_prev1 block            */
-                    pp_prev2 = pp_prev1 + 1;
-
-                    /* Check if y component of MV is a multiple */
-                    /* of 16 and check if block y coordinate is */
-                    /* out of bounds                */
-                    if (((dy&0xF) != 0) && (mmvy + 1 < (height >> 3) - 1))
-                    {   /* dy is not a multiple of 16 and */
-                        /* the block y coordinate is      */
-                        /* within the bounds              */
-
-                        /* pp_prev3 is the block below */
-                        /* pp_prev1 block          */
-                        pp_prev3 = pp_prev1 + mvwidth;
-
-                        /* all prediction are from different blocks */
-                        msk_deblock = 0x3;
-                    }
-                    else
-                    {   /* dy is a multiple of 16 or the block */
-                        /* y coordinate is out of bounds       */
-
-                        pp_prev3 = pp_prev1;
-                    }
-
-                    /* pp_prev4 is the block to the right of */
-                    /* pp_prev3 block.           */
-                    pp_prev4 = pp_prev3 + 1;
-                }
-                else
-                {   /* dx is a multiple of 16 or the block x */
-                    /* coordinate is out of bounds           */
-
-                    pp_prev2 = pp_prev1;
-
-                    /* Check if y component of MV is a multiple */
-                    /* of 16 and check if block y coordinate is */
-                    /* out of bounds                */
-                    if (((dy&0xF) != 0) && (mmvy + 1 < (height >> 3) - 1))
-                    {   /* dy is not a multiple of 16 and */
-                        /* the block y coordinate is      */
-                        /* within the bounds              */
-
-                        /* pp_prev3 is the block below */
-                        /* pp_prev1 block.         */
-                        pp_prev3 = pp_prev1 + mvwidth;
-                    }
-                    else
-                    {   /* dy is a multiple of 16 or the block */
-                        /* y coordinate is out of bounds       */
-
-                        pp_prev3 = pp_prev1;
-                    }
-
-                    pp_prev4 = pp_prev3;
-                }
-
-                /* Deringing semaphore propagation */
-                if ((*(pp_dec_y)&4) == 0)
-                {
-                    *(pp_dec_y) |= ((*(pp_prev1) |
-                                     *(pp_prev2) | *(pp_prev3) |
-                                     *(pp_prev4)) & 0x4);
-                }
-                /* Deblocking semaphore propagation */
-                /*  11/3/00, change the propaga= */
-                /* tion for deblocking */
-                if (msk_deblock == 0)
-                {
-                    *(pp_dec_y) = 0;
-                }
-
-                pp_dec_y += ll[kk];
-            }
-        }
-
-        /*----------------------------------------------------------------------------
-        ; Return nothing or data or data pointer
-        ----------------------------------------------------------------------------*/
-        return (msk_deblock);
-    }
-#ifdef __cplusplus
-}
-#endif
-#endif
diff --git a/media/libstagefright/codecs/m4v_h263/enc/Android.bp b/media/libstagefright/codecs/m4v_h263/enc/Android.bp
index b8bc24e..d10e40d 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/Android.bp
+++ b/media/libstagefright/codecs/m4v_h263/enc/Android.bp
@@ -1,59 +1,20 @@
-cc_library_static {
-    name: "libstagefright_m4vh263enc",
-    vendor_available: true,
-    apex_available: [
-        "//apex_available:platform",
-        "com.android.media.swcodec",
-    ],
-    min_sdk_version: "29",
-
-    srcs: [
-        "src/bitstream_io.cpp",
-        "src/combined_encode.cpp", "src/datapart_encode.cpp",
-        "src/dct.cpp",
-        "src/findhalfpel.cpp",
-        "src/fastcodemb.cpp",
-        "src/fastidct.cpp",
-        "src/fastquant.cpp",
-        "src/me_utils.cpp",
-        "src/mp4enc_api.cpp",
-        "src/rate_control.cpp",
-        "src/motion_est.cpp",
-        "src/motion_comp.cpp",
-        "src/sad.cpp",
-        "src/sad_halfpel.cpp",
-        "src/vlc_encode.cpp",
-        "src/vop.cpp",
-    ],
-
-    cflags: [
-        "-DBX_RC",
-        "-Werror",
-    ],
-
-    version_script: "exports.lds",
-
-    local_include_dirs: ["src"],
-    export_include_dirs: ["include"],
-
-    sanitize: {
-        misc_undefined: [
-            "signed-integer-overflow",
-        ],
-        cfi: true,
-    },
-}
-
 //###############################################################################
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_mpeg4enc",
     defaults: ["libstagefright_softomx-defaults"],
 
     srcs: ["SoftMPEG4Encoder.cpp"],
 
-    local_include_dirs: ["src"],
-
     cflags: [
         "-DBX_RC",
     ],
@@ -67,29 +28,3 @@
         cfi: true,
     },
 }
-
-//###############################################################################
-
-cc_test {
-    name: "libstagefright_m4vh263enc_test",
-    gtest: false,
-
-    srcs: ["test/m4v_h263_enc_test.cpp"],
-
-    local_include_dirs: ["src"],
-
-    cflags: [
-        "-DBX_RC",
-        "-Wall",
-        "-Werror",
-    ],
-
-    sanitize: {
-        misc_undefined: [
-            "signed-integer-overflow",
-        ],
-        cfi: true,
-    },
-
-    static_libs: ["libstagefright_m4vh263enc"],
-}
diff --git a/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp b/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp
index fa7db81..fb6c4e2 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp
+++ b/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp
@@ -528,6 +528,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/mp3dec/Android.bp b/media/libstagefright/codecs/mp3dec/Android.bp
index 96106f1..b669c84 100644
--- a/media/libstagefright/codecs/mp3dec/Android.bp
+++ b/media/libstagefright/codecs/mp3dec/Android.bp
@@ -1,93 +1,19 @@
-cc_library_static {
-    name: "libstagefright_mp3dec",
-    vendor_available: true,
-    min_sdk_version: "29",
 
-    srcs: [
-        "src/pvmp3_normalize.cpp",
-        "src/pvmp3_alias_reduction.cpp",
-        "src/pvmp3_crc.cpp",
-        "src/pvmp3_decode_header.cpp",
-        "src/pvmp3_decode_huff_cw.cpp",
-        "src/pvmp3_getbits.cpp",
-        "src/pvmp3_dequantize_sample.cpp",
-        "src/pvmp3_framedecoder.cpp",
-        "src/pvmp3_get_main_data_size.cpp",
-        "src/pvmp3_get_side_info.cpp",
-        "src/pvmp3_get_scale_factors.cpp",
-        "src/pvmp3_mpeg2_get_scale_data.cpp",
-        "src/pvmp3_mpeg2_get_scale_factors.cpp",
-        "src/pvmp3_mpeg2_stereo_proc.cpp",
-        "src/pvmp3_huffman_decoding.cpp",
-        "src/pvmp3_huffman_parsing.cpp",
-        "src/pvmp3_tables.cpp",
-        "src/pvmp3_imdct_synth.cpp",
-        "src/pvmp3_mdct_6.cpp",
-        "src/pvmp3_dct_6.cpp",
-        "src/pvmp3_poly_phase_synthesis.cpp",
-        "src/pvmp3_equalizer.cpp",
-        "src/pvmp3_seek_synch.cpp",
-        "src/pvmp3_stereo_proc.cpp",
-        "src/pvmp3_reorder.cpp",
-
-        "src/pvmp3_polyphase_filter_window.cpp",
-        "src/pvmp3_mdct_18.cpp",
-        "src/pvmp3_dct_9.cpp",
-        "src/pvmp3_dct_16.cpp",
-    ],
-
-    arch: {
-        arm: {
-            exclude_srcs: [
-                "src/pvmp3_polyphase_filter_window.cpp",
-                "src/pvmp3_mdct_18.cpp",
-                "src/pvmp3_dct_9.cpp",
-                "src/pvmp3_dct_16.cpp",
-            ],
-            srcs: [
-                "src/asm/pvmp3_polyphase_filter_window_gcc.s",
-                "src/asm/pvmp3_mdct_18_gcc.s",
-                "src/asm/pvmp3_dct_9_gcc.s",
-                "src/asm/pvmp3_dct_16_gcc.s",
-            ],
-
-            instruction_set: "arm",
-        },
-    },
-
-    sanitize: {
-        misc_undefined: [
-            "signed-integer-overflow",
-        ],
-        cfi: true,
-    },
-
-    include_dirs: ["frameworks/av/media/libstagefright/include"],
-
-    export_include_dirs: [
-        "include",
-        "src",
-    ],
-
-    cflags: [
-        "-DOSCL_UNUSED_ARG(x)=(void)(x)",
-        "-Werror",
-    ],
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
 }
 
-//###############################################################################
-
 cc_library_shared {
     name: "libstagefright_soft_mp3dec",
     defaults: ["libstagefright_softomx-defaults"],
 
     srcs: ["SoftMP3.cpp"],
 
-    local_include_dirs: [
-        "src",
-        "include",
-    ],
-
     version_script: "exports.lds",
 
     sanitize: {
@@ -99,35 +25,3 @@
 
     static_libs: ["libstagefright_mp3dec"],
 }
-
-//###############################################################################
-cc_test {
-    name: "libstagefright_mp3dec_test",
-    gtest: false,
-
-    srcs: [
-        "test/mp3dec_test.cpp",
-        "test/mp3reader.cpp",
-    ],
-
-    cflags: ["-Wall", "-Werror"],
-
-    local_include_dirs: [
-        "src",
-        "include",
-    ],
-
-    sanitize: {
-        misc_undefined: [
-            "signed-integer-overflow",
-        ],
-        cfi: true,
-    },
-
-    static_libs: [
-        "libstagefright_mp3dec",
-        "libsndfile",
-    ],
-
-    shared_libs: ["libaudioutils"],
-}
diff --git a/media/libstagefright/codecs/mp3dec/SoftMP3.cpp b/media/libstagefright/codecs/mp3dec/SoftMP3.cpp
index b5d32ed..07bb45a 100644
--- a/media/libstagefright/codecs/mp3dec/SoftMP3.cpp
+++ b/media/libstagefright/codecs/mp3dec/SoftMP3.cpp
@@ -23,7 +23,7 @@
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/MediaDefs.h>
 
-#include "include/pvmp3decoder_api.h"
+#include <pvmp3decoder_api.h>
 
 namespace android {
 
@@ -498,6 +498,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/mpeg2dec/Android.bp b/media/libstagefright/codecs/mpeg2dec/Android.bp
index e849410..abd1379 100644
--- a/media/libstagefright/codecs/mpeg2dec/Android.bp
+++ b/media/libstagefright/codecs/mpeg2dec/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_mpeg2dec",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.cpp b/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.cpp
index 9d5f342..9f8001f 100644
--- a/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.cpp
+++ b/media/libstagefright/codecs/mpeg2dec/SoftMPEG2.cpp
@@ -864,6 +864,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks, OMX_PTR appData,
         OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/on2/dec/Android.bp b/media/libstagefright/codecs/on2/dec/Android.bp
index 82bb8d1..ba6dc2a 100644
--- a/media/libstagefright/codecs/on2/dec/Android.bp
+++ b/media/libstagefright/codecs/on2/dec/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_on2_dec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_on2_dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_vpxdec",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/on2/dec/SoftVPX.cpp b/media/libstagefright/codecs/on2/dec/SoftVPX.cpp
index 0f2ff17..bffc23a 100644
--- a/media/libstagefright/codecs/on2/dec/SoftVPX.cpp
+++ b/media/libstagefright/codecs/on2/dec/SoftVPX.cpp
@@ -355,6 +355,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/on2/enc/Android.bp b/media/libstagefright/codecs/on2/enc/Android.bp
index 705e554..e85ff98 100644
--- a/media/libstagefright/codecs/on2/enc/Android.bp
+++ b/media/libstagefright/codecs/on2/enc/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_on2_enc_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_on2_enc_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_vpxenc",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp b/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
index d0cb071..e9b4341 100644
--- a/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
+++ b/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
@@ -775,6 +775,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/opus/dec/Android.bp b/media/libstagefright/codecs/opus/dec/Android.bp
index 71a2a0d..3d8af69 100644
--- a/media/libstagefright/codecs/opus/dec/Android.bp
+++ b/media/libstagefright/codecs/opus/dec/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_opusdec",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/opus/dec/SoftOpus.cpp b/media/libstagefright/codecs/opus/dec/SoftOpus.cpp
index 4f61aa8..dcd8dda 100644
--- a/media/libstagefright/codecs/opus/dec/SoftOpus.cpp
+++ b/media/libstagefright/codecs/opus/dec/SoftOpus.cpp
@@ -58,6 +58,8 @@
       mInputBufferCount(0),
       mDecoder(NULL),
       mHeader(NULL),
+      mNumChannels(1),
+      mSamplingRate(kRate),
       mCodecDelay(0),
       mSeekPreRoll(0),
       mAnchorTimeUs(0),
@@ -169,11 +171,11 @@
             }
 
             opusParams->nAudioBandWidth = 0;
-            opusParams->nSampleRate = kRate;
+            opusParams->nSampleRate = mSamplingRate;
             opusParams->nBitRate = 0;
 
             if (!isConfigured()) {
-                opusParams->nChannels = 1;
+                opusParams->nChannels = mNumChannels;
             } else {
                 opusParams->nChannels = mHeader->channels;
             }
@@ -274,7 +276,8 @@
             if (opusParams->nPortIndex != 0) {
                 return OMX_ErrorUndefined;
             }
-
+            mNumChannels = opusParams->nChannels;
+            mSamplingRate = opusParams->nSampleRate;
             return OMX_ErrorNone;
         }
 
@@ -496,6 +499,8 @@
                                    *(reinterpret_cast<int64_t*>(inHeader->pBuffer +
                                                                 inHeader->nOffset)),
                                    kRate);
+                mSamplingRate = kRate;
+                mNumChannels = mHeader->channels;
                 notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
                 mOutputPortSettingsChange = AWAITING_DISABLED;
             }
@@ -661,6 +666,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/opus/dec/SoftOpus.h b/media/libstagefright/codecs/opus/dec/SoftOpus.h
index 91cafa1..00058c8 100644
--- a/media/libstagefright/codecs/opus/dec/SoftOpus.h
+++ b/media/libstagefright/codecs/opus/dec/SoftOpus.h
@@ -70,6 +70,8 @@
     OpusMSDecoder *mDecoder;
     OpusHeader *mHeader;
 
+    int32_t mNumChannels;
+    int32_t mSamplingRate;
     int64_t mCodecDelay;
     int64_t mSeekPreRoll;
     int64_t mSamplesToDiscard;
diff --git a/media/libstagefright/codecs/raw/Android.bp b/media/libstagefright/codecs/raw/Android.bp
index fcc7a0a..3673786 100644
--- a/media/libstagefright/codecs/raw/Android.bp
+++ b/media/libstagefright/codecs/raw/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_raw_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_raw_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_rawdec",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/raw/SoftRaw.cpp b/media/libstagefright/codecs/raw/SoftRaw.cpp
index 0e31804..82dd171 100644
--- a/media/libstagefright/codecs/raw/SoftRaw.cpp
+++ b/media/libstagefright/codecs/raw/SoftRaw.cpp
@@ -273,6 +273,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/vorbis/dec/Android.bp b/media/libstagefright/codecs/vorbis/dec/Android.bp
index 3efb952..7764294 100644
--- a/media/libstagefright/codecs/vorbis/dec/Android.bp
+++ b/media/libstagefright/codecs/vorbis/dec/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_codecs_vorbis_dec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_codecs_vorbis_dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_vorbisdec",
     defaults: ["libstagefright_softomx-defaults"],
diff --git a/media/libstagefright/codecs/vorbis/dec/SoftVorbis.cpp b/media/libstagefright/codecs/vorbis/dec/SoftVorbis.cpp
index 08e20cc..3daed10 100644
--- a/media/libstagefright/codecs/vorbis/dec/SoftVorbis.cpp
+++ b/media/libstagefright/codecs/vorbis/dec/SoftVorbis.cpp
@@ -636,6 +636,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent *createSoftOMXComponent(
         const char *name, const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
diff --git a/media/libstagefright/codecs/xaacdec/Android.bp b/media/libstagefright/codecs/xaacdec/Android.bp
index 5385dbc..1d03c16 100644
--- a/media/libstagefright/codecs/xaacdec/Android.bp
+++ b/media/libstagefright/codecs/xaacdec/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_soft_xaacdec",
     defaults: ["libstagefright_softomx-defaults"],
@@ -14,6 +23,9 @@
         // integer_overflow: true,
         misc_undefined: [ "signed-integer-overflow", "unsigned-integer-overflow", ],
         cfi: true,
+        config: {
+            cfi_assembly_support: true,
+        },
     },
 
     static_libs: ["libxaacdec"],
diff --git a/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp b/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp
index 87e8fd4..a478642 100644
--- a/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp
+++ b/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp
@@ -1693,6 +1693,7 @@
 
 }  // namespace android
 
+__attribute__((cfi_canonical_jump_table))
 android::SoftOMXComponent* createSoftOMXComponent(const char* name,
                                                   const OMX_CALLBACKTYPE* callbacks,
                                                   OMX_PTR appData, OMX_COMPONENTTYPE** component) {
diff --git a/media/libstagefright/colorconversion/Android.bp b/media/libstagefright/colorconversion/Android.bp
index 6b08b08..06cebd3 100644
--- a/media/libstagefright/colorconversion/Android.bp
+++ b/media/libstagefright/colorconversion/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_colorconversion_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_colorconversion_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_static {
     name: "libstagefright_color_conversion",
 
diff --git a/media/libstagefright/data/Android.bp b/media/libstagefright/data/Android.bp
index 616b4b3..6da2ccb 100644
--- a/media/libstagefright/data/Android.bp
+++ b/media/libstagefright/data/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 prebuilt_etc {
     name: "mediaswcodec.xml",
     src: "media_codecs_sw.xml",
diff --git a/media/libstagefright/data/media_codecs_sw.xml b/media/libstagefright/data/media_codecs_sw.xml
index 6571162..dd2eed3 100644
--- a/media/libstagefright/data/media_codecs_sw.xml
+++ b/media/libstagefright/data/media_codecs_sw.xml
@@ -295,12 +295,12 @@
             <Feature name="bitrate-modes" value="VBR,CBR" />
         </MediaCodec>
         <MediaCodec name="c2.android.hevc.encoder" type="video/hevc" variant="!slow-cpu">
-            <!-- profiles and levels:  ProfileMain : MainTierLevel3 -->
-            <Limit name="size" min="2x2" max="960x544" />
+            <!-- profiles and levels:  ProfileMain : MainTierLevel51 -->
+            <Limit name="size" min="2x2" max="512x512" />
             <Limit name="alignment" value="2x2" />
             <Limit name="block-size" value="8x8" />
-            <Limit name="block-count" range="1-8160" /> <!-- max 960x544 -->
-            <Limit name="blocks-per-second" range="1-244880" />
+            <Limit name="block-count" range="1-4096" /> <!-- max 512x512 -->
+            <Limit name="blocks-per-second" range="1-122880" />
             <Limit name="frame-rate" range="1-120" />
             <Limit name="bitrate" range="1-10000000" />
             <Limit name="complexity" range="0-10"  default="0" />
diff --git a/media/libstagefright/filters/Android.bp b/media/libstagefright/filters/Android.bp
index 88f30c4..acc9e87 100644
--- a/media/libstagefright/filters/Android.bp
+++ b/media/libstagefright/filters/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_static {
     name: "libstagefright_mediafilter",
 
diff --git a/media/libstagefright/flac/dec/Android.bp b/media/libstagefright/flac/dec/Android.bp
index 32b2075..225c930 100644
--- a/media/libstagefright/flac/dec/Android.bp
+++ b/media/libstagefright/flac/dec/Android.bp
@@ -1,7 +1,27 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_flac_dec_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_flac_dec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libstagefright_flacdec",
     vendor_available: true,
     min_sdk_version: "29",
+    host_supported: true,
 
     srcs: [
         "FLACDecoder.cpp",
@@ -33,6 +53,13 @@
     ],
 
     header_libs: [
-        "libmedia_headers",
+        "libstagefright_foundation_headers",
+        "libstagefright_headers",
     ],
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
diff --git a/media/libstagefright/flac/dec/FLACDecoder.cpp b/media/libstagefright/flac/dec/FLACDecoder.cpp
index cef0bc6..f5e9532 100644
--- a/media/libstagefright/flac/dec/FLACDecoder.cpp
+++ b/media/libstagefright/flac/dec/FLACDecoder.cpp
@@ -433,7 +433,7 @@
             if (mBuffer == nullptr) {
                 mBufferDataSize = 0;
                 mBufferLen = 0;
-                ALOGE("decodeOneFrame: failed to allocate memory for input buffer");
+                ALOGE("addDataToBuffer: failed to allocate memory for input buffer");
                 return NO_MEMORY;
             }
             mBufferLen = mBufferDataSize + inBufferLen;
diff --git a/media/libstagefright/flac/dec/test/Android.bp b/media/libstagefright/flac/dec/test/Android.bp
index 70ca80a..a4c2735 100644
--- a/media/libstagefright/flac/dec/test/Android.bp
+++ b/media/libstagefright/flac/dec/test/Android.bp
@@ -14,6 +14,17 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_flac_dec_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_flac_dec_license",
+    ],
+}
+
 cc_test {
     name: "FlacDecoderTest",
     gtest: true,
diff --git a/media/libstagefright/foundation/ALooperRoster.cpp b/media/libstagefright/foundation/ALooperRoster.cpp
index 8a7c3eb..0a4e598 100644
--- a/media/libstagefright/foundation/ALooperRoster.cpp
+++ b/media/libstagefright/foundation/ALooperRoster.cpp
@@ -166,7 +166,7 @@
         }
         s.append("\n");
     }
-    write(fd, s.string(), s.size());
+    (void)write(fd, s.string(), s.size());
 }
 
 }  // namespace android
diff --git a/media/libstagefright/foundation/AString.cpp b/media/libstagefright/foundation/AString.cpp
index 4bd186c..8722e14 100644
--- a/media/libstagefright/foundation/AString.cpp
+++ b/media/libstagefright/foundation/AString.cpp
@@ -387,10 +387,14 @@
     va_start(ap, format);
 
     char *buffer;
-    vasprintf(&buffer, format, ap);
+    int bufferSize = vasprintf(&buffer, format, ap);
 
     va_end(ap);
 
+    if(bufferSize < 0) {
+        return AString();
+    }
+
     AString result(buffer);
 
     free(buffer);
diff --git a/media/libstagefright/foundation/Android.bp b/media/libstagefright/foundation/Android.bp
index f440e00..407f609 100644
--- a/media/libstagefright/foundation/Android.bp
+++ b/media/libstagefright/foundation/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_foundation_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_foundation_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_headers {
     name: "libstagefright_foundation_headers",
     export_include_dirs: ["include"],
@@ -12,6 +31,7 @@
     vndk: {
         enabled: true,
     },
+    host_supported: true,
     double_loadable: true,
     include_dirs: [
         "frameworks/av/include",
@@ -25,7 +45,6 @@
     ],
 
     header_libs: [
-        "libhardware_headers",
         "libstagefright_foundation_headers",
         "media_ndk_headers",
         "media_plugin_headers",
@@ -86,6 +105,9 @@
                 "-DNO_IMEMORY",
             ],
         },
+        darwin: {
+            enabled: false,
+        },
     },
 
     clang: true,
diff --git a/media/libstagefright/foundation/avc_utils.cpp b/media/libstagefright/foundation/avc_utils.cpp
index f53d2c9..9d6887c 100644
--- a/media/libstagefright/foundation/avc_utils.cpp
+++ b/media/libstagefright/foundation/avc_utils.cpp
@@ -559,11 +559,9 @@
     CHECK_NE(video_object_type_indication,
              0x21u /* Fine Granularity Scalable */);
 
-    unsigned video_object_layer_verid __unused;
-    unsigned video_object_layer_priority __unused;
     if (br.getBits(1)) {
-        video_object_layer_verid = br.getBits(4);
-        video_object_layer_priority = br.getBits(3);
+        br.skipBits(4); //video_object_layer_verid
+        br.skipBits(3); //video_object_layer_priority
     }
     unsigned aspect_ratio_info = br.getBits(4);
     if (aspect_ratio_info == 0x0f /* extended PAR */) {
@@ -622,7 +620,7 @@
     unsigned video_object_layer_height = br.getBits(13);
     CHECK(br.getBits(1));  // marker_bit
 
-    unsigned interlaced __unused = br.getBits(1);
+    br.skipBits(1); // interlaced
 
     *width = video_object_layer_width;
     *height = video_object_layer_height;
@@ -668,7 +666,7 @@
         return false;
     }
 
-    unsigned protection __unused = (header >> 16) & 1;
+    // we can get protection value from (header >> 16) & 1
 
     unsigned bitrate_index = (header >> 12) & 0x0f;
 
diff --git a/media/libstagefright/foundation/include/media/stagefright/foundation/ADebug.h b/media/libstagefright/foundation/include/media/stagefright/foundation/ADebug.h
index ab17a02..e4b99bf 100644
--- a/media/libstagefright/foundation/include/media/stagefright/foundation/ADebug.h
+++ b/media/libstagefright/foundation/include/media/stagefright/foundation/ADebug.h
@@ -148,7 +148,8 @@
     static char *GetDebugName(const char *name);
 
     inline static bool isExperimentEnabled(
-            const char *name __unused /* nonnull */, bool allow __unused = true) {
+            const char *name __attribute__((unused)) /* nonnull */,
+            bool allow __attribute__((unused)) = true) {
 #ifdef ENABLE_STAGEFRIGHT_EXPERIMENTS
         if (!strcmp(name, "legacy-adaptive")) {
             return getExperimentFlag(allow, name, 2, 1); // every other day
diff --git a/media/libstagefright/foundation/include/media/stagefright/foundation/AUtils.h b/media/libstagefright/foundation/include/media/stagefright/foundation/AUtils.h
index af6b357..3b646dc 100644
--- a/media/libstagefright/foundation/include/media/stagefright/foundation/AUtils.h
+++ b/media/libstagefright/foundation/include/media/stagefright/foundation/AUtils.h
@@ -63,7 +63,7 @@
 
 template<class T>
 void ENSURE_UNSIGNED_TYPE() {
-    T TYPE_MUST_BE_UNSIGNED[(T)-1 < 0 ? -1 : 0] __unused;
+    T TYPE_MUST_BE_UNSIGNED[(T)-1 < 0 ? -1 : 0] __attribute__((unused));
 }
 
 // needle is in range [hayStart, hayStart + haySize)
diff --git a/media/libstagefright/foundation/tests/AVCUtils/AVCUtilsTestEnvironment.h b/media/libstagefright/foundation/tests/AVCUtils/AVCUtilsTestEnvironment.h
new file mode 100644
index 0000000..b28a7bc
--- /dev/null
+++ b/media/libstagefright/foundation/tests/AVCUtils/AVCUtilsTestEnvironment.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2020 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 __AVC_UTILS_TEST_ENVIRONMENT_H__
+#define __AVC_UTILS_TEST_ENVIRONMENT_H__
+
+#include <gtest/gtest.h>
+
+#include <getopt.h>
+
+using namespace std;
+
+class AVCUtilsTestEnvironment : public::testing::Environment {
+  public:
+    AVCUtilsTestEnvironment() : res("/data/local/tmp/") {}
+
+    // Parses the command line arguments
+    int initFromOptions(int argc, char **argv);
+
+    void setRes(const char *_res) { res = _res; }
+
+    const string getRes() const { return res; }
+
+  private:
+    string res;
+};
+
+int AVCUtilsTestEnvironment::initFromOptions(int argc, char **argv) {
+    static struct option options[] = {{"path", required_argument, 0, 'P'}, {0, 0, 0, 0}};
+
+    while (true) {
+        int index = 0;
+        int c = getopt_long(argc, argv, "P:", options, &index);
+        if (c == -1) {
+            break;
+        }
+
+        switch (c) {
+            case 'P': {
+                setRes(optarg);
+                break;
+            }
+            default:
+                break;
+        }
+    }
+
+    if (optind < argc) {
+        fprintf(stderr,
+                "unrecognized option: %s\n\n"
+                "usage: %s <gtest options> <test options>\n\n"
+                "test options are:\n\n"
+                "-P, --path: Resource files directory location\n",
+                argv[optind ?: 1], argv[0]);
+        return 2;
+    }
+    return 0;
+}
+
+#endif  // __AVC_UTILS_TEST_ENVIRONMENT_H__
diff --git a/media/libstagefright/foundation/tests/AVCUtils/AVCUtilsUnitTest.cpp b/media/libstagefright/foundation/tests/AVCUtils/AVCUtilsUnitTest.cpp
new file mode 100644
index 0000000..77a8599
--- /dev/null
+++ b/media/libstagefright/foundation/tests/AVCUtils/AVCUtilsUnitTest.cpp
@@ -0,0 +1,411 @@
+/*
+ * Copyright (C) 2020 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 "AVCUtilsUnitTest"
+#include <utils/Log.h>
+
+#include <fstream>
+
+#include "media/stagefright/foundation/ABitReader.h"
+#include "media/stagefright/foundation/avc_utils.h"
+
+#include "AVCUtilsTestEnvironment.h"
+
+constexpr size_t kSmallBufferSize = 2;
+constexpr uint8_t kSPSmask = 0x1f;
+constexpr uint8_t kSPSStartCode = 0x07;
+constexpr uint8_t kConfigVersion = 0x01;
+
+using namespace android;
+
+static AVCUtilsTestEnvironment *gEnv = nullptr;
+
+class MpegAudioUnitTest
+    : public ::testing::TestWithParam<
+              tuple</*audioHeader*/ uint32_t, /*frameSize*/ int32_t, /*sampleRate*/ int32_t,
+                    /*numChannels*/ int32_t, /*bitRate*/ int32_t, /*numSamples*/ int32_t>> {};
+
+class VOLDimensionTest
+    : public ::testing::TestWithParam<
+              tuple</*fileName*/ string, /*volWidth*/ int32_t, /*volHeight*/ int32_t>> {};
+
+class AVCUtils {
+  public:
+    bool SetUpAVCUtils(string fileName, string infoFileName) {
+        mInputFile = gEnv->getRes() + fileName;
+        mInputFileStream.open(mInputFile, ifstream::in);
+        if (!mInputFileStream.is_open()) return false;
+
+        mInfoFile = gEnv->getRes() + infoFileName;
+        mInfoFileStream.open(mInfoFile, ifstream::in);
+        if (!mInputFileStream.is_open()) return false;
+        return true;
+    }
+
+    ~AVCUtils() {
+        if (mInputFileStream.is_open()) mInputFileStream.close();
+        if (mInfoFileStream.is_open()) mInfoFileStream.close();
+    }
+
+    string mInputFile;
+    string mInfoFile;
+
+    ifstream mInputFileStream;
+    ifstream mInfoFileStream;
+};
+
+class AVCDimensionTest
+    : public AVCUtils,
+      public ::testing::TestWithParam<
+              tuple</*fileName*/ string, /*infoFileName*/ string,
+                    /*avcWidth*/ size_t, /*avcHeight*/ size_t, /*numberOfNALUnits*/ int32_t>> {
+  public:
+    virtual void SetUp() override {
+        tuple<string, string, size_t, size_t, size_t> params = GetParam();
+        string fileName = get<0>(params);
+        string infoFileName = get<1>(params);
+        AVCUtils::SetUpAVCUtils(fileName, infoFileName);
+
+        mFrameWidth = get<2>(params);
+        mFrameHeight = get<3>(params);
+        mNalUnitsExpected = get<4>(params);
+    }
+
+    size_t mFrameWidth;
+    size_t mFrameHeight;
+    int32_t mNalUnitsExpected;
+};
+
+class AvccBoxTest : public AVCDimensionTest {
+  public:
+    virtual void SetUp() override { AVCDimensionTest::SetUp(); }
+};
+
+class AVCFrameTest
+    : public AVCUtils,
+      public ::testing::TestWithParam<pair</*fileName*/ string, /*infoFileName*/ string>> {
+  public:
+    virtual void SetUp() override {
+        string fileName = GetParam().first;
+        string infoFileName = GetParam().second;
+        AVCUtils::SetUpAVCUtils(fileName, infoFileName);
+    }
+};
+
+TEST_P(MpegAudioUnitTest, AudioProfileTest) {
+    tuple<uint32_t, size_t, int, int, int, int> params = GetParam();
+    uint32_t header = get<0>(params);
+
+    size_t audioFrameSize = get<1>(params);
+    int audioSampleRate = get<2>(params);
+    int audioNumChannels = get<3>(params);
+    int audioBitRate = get<4>(params);
+    int audioNumSamples = get<5>(params);
+
+    size_t frameSize = 0;
+    int sampleRate = 0;
+    int numChannels = 0;
+    int bitRate = 0;
+    int numSamples = 0;
+
+    bool status = GetMPEGAudioFrameSize(header, &frameSize, &sampleRate, &numChannels, &bitRate,
+                                        &numSamples);
+    ASSERT_TRUE(status) << "Failed to get Audio properties";
+
+    ASSERT_EQ(frameSize, audioFrameSize) << "Wrong frame size found";
+
+    ASSERT_EQ(sampleRate, audioSampleRate) << "Wrong sample rate found";
+
+    ASSERT_EQ(numChannels, audioNumChannels) << "Wrong number of channels found";
+
+    ASSERT_EQ(bitRate, audioBitRate) << "Wrong bit rate found";
+
+    ASSERT_EQ(numSamples, audioNumSamples) << "Wrong number of samples found";
+}
+
+TEST_P(VOLDimensionTest, DimensionTest) {
+    tuple<string, int32_t, int32_t> params = GetParam();
+    string inputFile = gEnv->getRes() + get<0>(params);
+    ifstream inputFileStream;
+    inputFileStream.open(inputFile, ifstream::in);
+    ASSERT_TRUE(inputFileStream.is_open()) << "Failed to open: " << inputFile;
+
+    struct stat buf;
+    int8_t err = stat(inputFile.c_str(), &buf);
+    ASSERT_EQ(err, 0) << "Failed to get information for file: " << inputFile;
+
+    size_t fileSize = buf.st_size;
+    ASSERT_NE(fileSize, 0) << "Invalid file size found";
+
+    const uint8_t *volBuffer = new uint8_t[fileSize];
+    ASSERT_NE(volBuffer, nullptr) << "Failed to allocate VOL buffer of size: " << fileSize;
+
+    inputFileStream.read((char *)(volBuffer), fileSize);
+    ASSERT_EQ(inputFileStream.gcount(), fileSize)
+            << "Failed to read complete file, bytes read: " << inputFileStream.gcount();
+
+    int32_t width = get<1>(params);
+    int32_t height = get<2>(params);
+    int32_t volWidth = -1;
+    int32_t volHeight = -1;
+
+    bool status = ExtractDimensionsFromVOLHeader(volBuffer, fileSize, &volWidth, &volHeight);
+    ASSERT_TRUE(status)
+            << "Failed to get VOL dimensions from function: ExtractDimensionsFromVOLHeader()";
+
+    ASSERT_EQ(volWidth, width) << "Expected width: " << width << "Found: " << volWidth;
+
+    ASSERT_EQ(volHeight, height) << "Expected height: " << height << "Found: " << volHeight;
+
+    delete[] volBuffer;
+}
+
+TEST_P(AVCDimensionTest, DimensionTest) {
+    int32_t numNalUnits = 0;
+    int32_t avcWidth = -1;
+    int32_t avcHeight = -1;
+    string line;
+    string type;
+    size_t chunkLength;
+    while (getline(mInfoFileStream, line)) {
+        istringstream stringLine(line);
+        stringLine >> type >> chunkLength;
+        ASSERT_GT(chunkLength, 0) << "Length of the data chunk must be greater than zero";
+
+        const uint8_t *data = new uint8_t[chunkLength];
+        ASSERT_NE(data, nullptr) << "Failed to create a data buffer of size: " << chunkLength;
+
+        const uint8_t *nalStart;
+        size_t nalSize;
+
+        mInputFileStream.read((char *)data, chunkLength);
+        ASSERT_EQ(mInputFileStream.gcount(), chunkLength)
+                << "Failed to read complete file, bytes read: " << mInputFileStream.gcount();
+
+        size_t smallBufferSize = kSmallBufferSize;
+        const uint8_t *sanityData = new uint8_t[smallBufferSize];
+        memcpy((void *)sanityData, (void *)data, smallBufferSize);
+
+        status_t result = getNextNALUnit(&sanityData, &smallBufferSize, &nalStart, &nalSize, true);
+        ASSERT_EQ(result, -EAGAIN) << "Invalid result found when wrong NAL unit passed";
+
+        while (!getNextNALUnit(&data, &chunkLength, &nalStart, &nalSize, true)) {
+            numNalUnits++;
+            // Check if it's an SPS
+            if ((nalStart[0] & kSPSmask) != kSPSStartCode) continue;
+            ASSERT_TRUE(nalSize > 0) << "NAL unit size must be greater than 0";
+
+            sp<ABuffer> spsBuffer = new ABuffer(nalSize);
+            ASSERT_NE(spsBuffer, nullptr) << "ABuffer returned null for size: " << nalSize;
+
+            memcpy(spsBuffer->data(), nalStart, nalSize);
+            FindAVCDimensions(spsBuffer, &avcWidth, &avcHeight);
+            spsBuffer.clear();
+            ASSERT_EQ(avcWidth, mFrameWidth)
+                    << "Expected width: " << mFrameWidth << "Found: " << avcWidth;
+
+            ASSERT_EQ(avcHeight, mFrameHeight)
+                    << "Expected height: " << mFrameHeight << "Found: " << avcHeight;
+        }
+        delete[] data;
+    }
+    if (mNalUnitsExpected < 0) {
+        ASSERT_GT(numNalUnits, 0) << "Failed to find an NAL Unit";
+    } else {
+        ASSERT_EQ(numNalUnits, mNalUnitsExpected)
+                << "Expected number of NAL units: " << mNalUnitsExpected
+                << " found: " << numNalUnits;
+    }
+}
+
+TEST_P(AvccBoxTest, AvccBoxValidationTest) {
+    int32_t avcWidth = -1;
+    int32_t avcHeight = -1;
+    int32_t accessUnitLength = 0;
+    int32_t profile = -1;
+    int32_t level = -1;
+    string line;
+    string type;
+    size_t chunkLength;
+    while (getline(mInfoFileStream, line)) {
+        istringstream stringLine(line);
+        stringLine >> type >> chunkLength;
+
+        if (type.compare("SPS") && type.compare("PPS")) continue;
+        ASSERT_GT(chunkLength, 0) << "Length of the data chunk must be greater than zero";
+
+        accessUnitLength += chunkLength;
+
+        if (!type.compare("SPS")) {
+            const uint8_t *data = new uint8_t[chunkLength];
+            ASSERT_NE(data, nullptr) << "Failed to create a data buffer of size: " << chunkLength;
+
+            const uint8_t *nalStart;
+            size_t nalSize;
+
+            mInputFileStream.read((char *)data, (uint32_t)chunkLength);
+            ASSERT_EQ(mInputFileStream.gcount(), chunkLength)
+                    << "Failed to read complete file, bytes read: " << mInputFileStream.gcount();
+
+            while (!getNextNALUnit(&data, &chunkLength, &nalStart, &nalSize, true)) {
+                // Check if it's an SPS
+                ASSERT_TRUE(nalSize > 0 && (nalStart[0] & kSPSmask) == kSPSStartCode)
+                        << "Failed to get SPS";
+
+                ASSERT_GE(nalSize, 4) << "SPS size must be greater than or equal to 4";
+
+                profile = nalStart[1];
+                level = nalStart[3];
+            }
+            delete[] data;
+        }
+    }
+    const uint8_t *accessUnitData = new uint8_t[accessUnitLength];
+    ASSERT_NE(accessUnitData, nullptr) << "Failed to create a buffer of size: " << accessUnitLength;
+
+    mInputFileStream.seekg(0, ios::beg);
+    mInputFileStream.read((char *)accessUnitData, accessUnitLength);
+    ASSERT_EQ(mInputFileStream.gcount(), accessUnitLength)
+            << "Failed to read complete file, bytes read: " << mInputFileStream.gcount();
+
+    sp<ABuffer> accessUnit = new ABuffer(accessUnitLength);
+    ASSERT_NE(accessUnit, nullptr)
+            << "Failed to create an android data buffer of size: " << accessUnitLength;
+
+    memcpy(accessUnit->data(), accessUnitData, accessUnitLength);
+    sp<ABuffer> csdDataBuffer = MakeAVCCodecSpecificData(accessUnit, &avcWidth, &avcHeight);
+    ASSERT_NE(csdDataBuffer, nullptr) << "No data returned from MakeAVCCodecSpecificData()";
+
+    ASSERT_EQ(avcWidth, mFrameWidth) << "Expected width: " << mFrameWidth << "Found: " << avcWidth;
+
+    ASSERT_EQ(avcHeight, mFrameHeight)
+            << "Expected height: " << mFrameHeight << "Found: " << avcHeight;
+
+    uint8_t *csdData = csdDataBuffer->data();
+    ASSERT_EQ(*csdData, kConfigVersion) << "Invalid configuration version";
+
+    ASSERT_GE(csdDataBuffer->size(), 4) << "CSD data size must be greater than or equal to 4";
+
+    ASSERT_EQ(*(csdData + 1), profile)
+            << "Expected AVC profile: " << profile << " found: " << *(csdData + 1);
+
+    ASSERT_EQ(*(csdData + 3), level)
+            << "Expected AVC level: " << level << " found: " << *(csdData + 3);
+    csdDataBuffer.clear();
+    delete[] accessUnitData;
+    accessUnit.clear();
+}
+
+TEST_P(AVCFrameTest, FrameTest) {
+    string line;
+    string type;
+    size_t chunkLength;
+    int32_t frameLayerID;
+    while (getline(mInfoFileStream, line)) {
+        uint32_t layerID = 0;
+        istringstream stringLine(line);
+        stringLine >> type >> chunkLength >> frameLayerID;
+        ASSERT_GT(chunkLength, 0) << "Length of the data chunk must be greater than zero";
+
+        char *data = new char[chunkLength];
+        ASSERT_NE(data, nullptr) << "Failed to allocation data buffer of size: " << chunkLength;
+
+        mInputFileStream.read(data, chunkLength);
+        ASSERT_EQ(mInputFileStream.gcount(), chunkLength)
+                << "Failed to read complete file, bytes read: " << mInputFileStream.gcount();
+
+        if (!type.compare("IDR")) {
+            bool isIDR = IsIDR((uint8_t *)data, chunkLength);
+            ASSERT_TRUE(isIDR);
+
+            layerID = FindAVCLayerId((uint8_t *)data, chunkLength);
+            ASSERT_EQ(layerID, frameLayerID) << "Wrong layer ID found";
+        } else if (!type.compare("P") || !type.compare("B")) {
+            sp<ABuffer> accessUnit = new ABuffer(chunkLength);
+            ASSERT_NE(accessUnit, nullptr) << "Unable to create access Unit";
+
+            memcpy(accessUnit->data(), data, chunkLength);
+            bool isReferenceFrame = IsAVCReferenceFrame(accessUnit);
+            ASSERT_TRUE(isReferenceFrame);
+
+            accessUnit.clear();
+            layerID = FindAVCLayerId((uint8_t *)data, chunkLength);
+            ASSERT_EQ(layerID, frameLayerID) << "Wrong layer ID found";
+        }
+        delete[] data;
+    }
+}
+
+INSTANTIATE_TEST_SUITE_P(AVCUtilsTestAll, MpegAudioUnitTest,
+                         ::testing::Values(make_tuple(0xFFFB9204, 418, 44100, 2, 128, 1152),
+                                           make_tuple(0xFFFB7604, 289, 48000, 2, 96, 1152),
+                                           make_tuple(0xFFFE5604, 164, 48000, 2, 160, 384)));
+
+// Info File contains the type and length for each chunk/frame
+INSTANTIATE_TEST_SUITE_P(
+        AVCUtilsTestAll, AVCDimensionTest,
+        ::testing::Values(make_tuple("crowd_8x8p50f32_200kbps_bp.h264",
+                                     "crowd_8x8p50f32_200kbps_bp.info", 8, 8, 11),
+                          make_tuple("crowd_640x360p24f300_1000kbps_bp.h264",
+                                     "crowd_640x360p24f300_1000kbps_bp.info", 640, 360, 11),
+                          make_tuple("crowd_1280x720p30f300_5000kbps_bp.h264",
+                                     "crowd_1280x720p30f300_5000kbps_bp.info", 1280, 720, 12),
+                          make_tuple("crowd_1920x1080p50f300_12000kbps_bp.h264",
+                                     "crowd_1920x1080p50f300_12000kbps_bp.info", 1920, 1080, 14),
+                          make_tuple("crowd_3840x2160p60f300_68000kbps_bp.h264",
+                                     "crowd_3840x2160p60f300_68000kbps_bp.info", 3840, 2160, 14)));
+
+// Info File contains the type and length for each chunk/frame
+INSTANTIATE_TEST_SUITE_P(
+        AVCUtilsTestAll, AvccBoxTest,
+        ::testing::Values(make_tuple("crowd_8x8p50f32_200kbps_bp.h264",
+                                     "crowd_8x8p50f32_200kbps_bp.info", 8, 8, 11),
+                          make_tuple("crowd_1280x720p30f300_5000kbps_bp.h264",
+                                     "crowd_1280x720p30f300_5000kbps_bp.info", 1280, 720, 12),
+                          make_tuple("crowd_1920x1080p50f300_12000kbps_bp.h264",
+                                     "crowd_1920x1080p50f300_12000kbps_bp.info", 1920, 1080, 14)));
+
+// Info File contains the type and length for each chunk/frame
+INSTANTIATE_TEST_SUITE_P(AVCUtilsTestAll, VOLDimensionTest,
+                         ::testing::Values(make_tuple("volData_720_480", 720, 480),
+                                           make_tuple("volData_1280_720", 1280, 720),
+                                           make_tuple("volData_1920_1080", 1920, 1080)));
+
+// Info File contains the type, length and layer ID for each chunk/frame
+INSTANTIATE_TEST_SUITE_P(AVCUtilsTestAll, AVCFrameTest,
+                         ::testing::Values(make_tuple("crowd_8x8p50f32_200kbps_bp.h264",
+                                                      "crowd_8x8p50f32_200kbps_bp.info"),
+                                           make_tuple("crowd_640x360p24f300_1000kbps_bp.h264",
+                                                      "crowd_640x360p24f300_1000kbps_bp.info"),
+                                           make_tuple("crowd_1280x720p30f300_5000kbps_bp.h264",
+                                                      "crowd_1280x720p30f300_5000kbps_bp.info"),
+                                           make_tuple("crowd_1920x1080p50f300_12000kbps_bp.h264",
+                                                      "crowd_1920x1080p50f300_12000kbps_bp.info"),
+                                           make_tuple("crowd_3840x2160p60f300_68000kbps_bp.h264",
+                                                      "crowd_3840x2160p60f300_68000kbps_bp.info")));
+
+int main(int argc, char **argv) {
+    gEnv = new AVCUtilsTestEnvironment();
+    ::testing::AddGlobalTestEnvironment(gEnv);
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = gEnv->initFromOptions(argc, argv);
+    if (status == 0) {
+        status = RUN_ALL_TESTS();
+        ALOGV("Test result = %d\n", status);
+    }
+    return status;
+}
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp b/media/libstagefright/foundation/tests/AVCUtils/Android.bp
similarity index 62%
copy from media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
copy to media/libstagefright/foundation/tests/AVCUtils/Android.bp
index 655491a..594da56 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
+++ b/media/libstagefright/foundation/tests/AVCUtils/Android.bp
@@ -14,33 +14,49 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_foundation_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_foundation_license",
+    ],
+}
+
 cc_test {
-    name: "Mpeg4H263DecoderTest",
+    name: "AVCUtilsUnitTest",
     gtest: true,
 
     srcs: [
-        "Mpeg4H263DecoderTest.cpp",
+        "AVCUtilsUnitTest.cpp",
     ],
 
     shared_libs: [
+        "libutils",
         "liblog",
     ],
 
     static_libs: [
-        "libstagefright_m4vh263dec",
+        "libstagefright",
         "libstagefright_foundation",
     ],
 
+    include_dirs: [
+        "frameworks/av/media/libstagefright/foundation",
+    ],
+
     cflags: [
         "-Werror",
         "-Wall",
     ],
 
     sanitize: {
+        cfi: true,
         misc_undefined: [
             "unsigned-integer-overflow",
             "signed-integer-overflow",
         ],
-        cfi: true,
     },
 }
diff --git a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml b/media/libstagefright/foundation/tests/AVCUtils/AndroidTest.xml
similarity index 68%
copy from media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
copy to media/libstagefright/foundation/tests/AVCUtils/AndroidTest.xml
index 7ff9732..6a088a8 100644
--- a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
+++ b/media/libstagefright/foundation/tests/AVCUtils/AndroidTest.xml
@@ -13,19 +13,19 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Test module config for Mp3 Decoder unit test">
-    <option name="test-suite-tag" value="Mp3DecoderTest" />
+<configuration description="Test module config for AVC Utils unit tests">
+    <option name="test-suite-tag" value="AVCUtilsUnitTest" />
     <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
-        <option name="cleanup" value="true" />
-        <option name="push" value="Mp3DecoderTest->/data/local/tmp/Mp3DecoderTest" />
+        <option name="cleanup" value="false" />
+        <option name="push" value="AVCUtilsUnitTest->/data/local/tmp/AVCUtilsUnitTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest.zip?unzip=true"
-            value="/data/local/tmp/Mp3DecoderTestRes/" />
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/foundation/tests/AVCUtils/AVCUtilsUnitTest.zip?unzip=true"
+            value="/data/local/tmp/AVCUtilsUnitTest/" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.GTest" >
         <option name="native-test-device-path" value="/data/local/tmp" />
-        <option name="module-name" value="Mp3DecoderTest" />
-        <option name="native-test-flag" value="-P /data/local/tmp/Mp3DecoderTestRes/" />
+        <option name="module-name" value="AVCUtilsUnitTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/AVCUtilsUnitTest/" />
     </test>
 </configuration>
diff --git a/media/libstagefright/foundation/tests/AVCUtils/README.md b/media/libstagefright/foundation/tests/AVCUtils/README.md
new file mode 100644
index 0000000..609d72e
--- /dev/null
+++ b/media/libstagefright/foundation/tests/AVCUtils/README.md
@@ -0,0 +1,39 @@
+## Media Testing ##
+---
+#### AVCUtils Test
+The AVC Utility Unit Test Suite validates the avc_utils librariy available in libstagefright/foundation.
+
+Run the following steps to build the test suite:
+```
+m AVCUtilsUnitTest
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+```
+adb push ${OUT}/data/nativetest64/AVCUtilsUnitTest/AVCUtilsUnitTest /data/local/tmp/
+```
+
+To test 32-bit binary push binaries from nativetest.
+```
+adb push ${OUT}/data/nativetest/AVCUtilsUnitTest/AVCUtilsUnitTest /data/local/tmp/
+```
+
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/foundation/tests/AVCUtils/AVCUtilsUnitTest.zip). Download, unzip and push these files into device for testing.
+
+```
+adb push AVCUtilsUnitTest /data/local/tmp/
+```
+
+usage: AVCUtilsUnitTest -P \<path_to_folder\>
+```
+adb shell /data/local/tmp/AVCUtilsUnitTest -P /data/local/tmp/AVCUtilsUnitTest/
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest AVCUtilsUnitTest -- --enable-module-dynamic-download=true
+```
diff --git a/media/libstagefright/foundation/tests/Android.bp b/media/libstagefright/foundation/tests/Android.bp
index f2157c9..801e216 100644
--- a/media/libstagefright/foundation/tests/Android.bp
+++ b/media/libstagefright/foundation/tests/Android.bp
@@ -1,3 +1,14 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_foundation_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_foundation_license",
+    ],
+}
+
 cc_test {
     name: "sf_foundation_test",
     test_suites: ["device-tests"],
@@ -25,3 +36,31 @@
         "Utils_test.cpp",
     ],
 }
+
+cc_test {
+    name: "MetaDataBaseUnitTest",
+    gtest: true,
+
+    srcs: [
+        "MetaDataBaseUnitTest.cpp",
+    ],
+
+    shared_libs: [
+        "libutils",
+        "liblog",
+    ],
+
+    static_libs: [
+        "libstagefright",
+        "libstagefright_foundation",
+    ],
+
+    header_libs: [
+        "libmedia_headers",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+}
diff --git a/media/libstagefright/foundation/tests/MetaDataBaseUnitTest.cpp b/media/libstagefright/foundation/tests/MetaDataBaseUnitTest.cpp
new file mode 100644
index 0000000..0aed4d2
--- /dev/null
+++ b/media/libstagefright/foundation/tests/MetaDataBaseUnitTest.cpp
@@ -0,0 +1,288 @@
+/*
+ * Copyright (C) 2020 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 <stdio.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <fstream>
+
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaDataBase.h>
+
+constexpr int32_t kWidth1 = 1920;
+constexpr int32_t kHeight1 = 1080;
+constexpr int32_t kWidth2 = 1280;
+constexpr int32_t kHeight2 = 920;
+constexpr int32_t kWidth3 = 720;
+constexpr int32_t kHeight3 = 480;
+constexpr int32_t kProfile = 1;
+constexpr int32_t kLevel = 1;
+constexpr int32_t kPlatformValue = 1;
+
+// Rectangle margins
+constexpr int32_t kLeft = 100;
+constexpr int32_t kTop = 100;
+constexpr int32_t kRight = 100;
+constexpr int32_t kBottom = 100;
+
+constexpr int64_t kDurationUs = 60000000;
+
+constexpr float kCaptureRate = 30.0;
+
+namespace android {
+
+class MetaDataBaseUnitTest : public ::testing::Test {};
+
+TEST_F(MetaDataBaseUnitTest, CreateMetaDataBaseTest) {
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create meta data";
+
+    // Testing copy constructor
+    MetaDataBase *metaDataCopy = metaData;
+    ASSERT_NE(metaDataCopy, nullptr) << "Failed to create meta data copy";
+
+    delete metaData;
+}
+
+TEST_F(MetaDataBaseUnitTest, SetAndFindDataTest) {
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create meta data";
+
+    // Setting the different key-value pair type for first time, overwrite
+    // expected to be false
+    bool status = metaData->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
+    ASSERT_FALSE(status) << "Initializing kKeyMIMEType, overwrite is expected to be false";
+
+    status = metaData->setInt32(kKeyWidth, kWidth1);
+    ASSERT_FALSE(status) << "Initializing kKeyWidth, overwrite is expected to be false";
+    status = metaData->setInt32(kKeyHeight, kHeight1);
+    ASSERT_FALSE(status) << "Initializing kKeyHeight, overwrite is expected to be false";
+    status = metaData->setInt32(kKeyVideoProfile, kProfile);
+    ASSERT_FALSE(status) << "Initializing kKeyVideoProfile, overwrite is expected to be false";
+    status = metaData->setInt32(kKeyVideoLevel, kLevel);
+    ASSERT_FALSE(status) << "Initializing kKeyVideoLevel, overwrite is expected to be false";
+
+    status = metaData->setInt64(kKeyDuration, kDurationUs);
+    ASSERT_FALSE(status) << "Initializing kKeyDuration, overwrite is expected to be false";
+
+    status = metaData->setFloat(kKeyCaptureFramerate, kCaptureRate);
+    ASSERT_FALSE(status) << "Initializing kKeyCaptureFramerate, overwrite is expected to be false";
+
+    const int32_t *platform = &kPlatformValue;
+    status = metaData->setPointer(kKeyPlatformPrivate, (void *)platform);
+    ASSERT_FALSE(status) << "Initializing kKeyPlatformPrivate, overwrite is expected to be false";
+
+    status = metaData->setRect(kKeyCropRect, kLeft, kTop, kRight, kBottom);
+    ASSERT_FALSE(status) << "Initializing kKeyCropRect, overwrite is expected to be false";
+
+    // Dump to log for reference
+    metaData->dumpToLog();
+
+    // Find the data which was set
+    const char *mime;
+    status = metaData->findCString(kKeyMIMEType, &mime);
+    ASSERT_TRUE(status) << "kKeyMIMEType key does not exists in metadata";
+    ASSERT_STREQ(mime, MEDIA_MIMETYPE_VIDEO_AVC) << "Incorrect mime type returned";
+
+    int32_t width, height, profile, level;
+    status = metaData->findInt32(kKeyWidth, &width);
+    ASSERT_TRUE(status) << "kKeyWidth key does not exists in metadata";
+    ASSERT_EQ(width, kWidth1) << "Incorrect value of width returned";
+
+    status = metaData->findInt32(kKeyHeight, &height);
+    ASSERT_TRUE(status) << "kKeyHeight key does not exists in metadata";
+    ASSERT_EQ(height, kHeight1) << "Incorrect value of height returned";
+
+    status = metaData->findInt32(kKeyVideoProfile, &profile);
+    ASSERT_TRUE(status) << "kKeyVideoProfile key does not exists in metadata";
+    ASSERT_EQ(profile, kProfile) << "Incorrect value of profile returned";
+
+    status = metaData->findInt32(kKeyVideoLevel, &level);
+    ASSERT_TRUE(status) << "kKeyVideoLevel key does not exists in metadata";
+    ASSERT_EQ(level, kLevel) << "Incorrect value of level returned";
+
+    int64_t duration;
+    status = metaData->findInt64(kKeyDuration, &duration);
+    ASSERT_TRUE(status) << "kKeyDuration key does not exists in metadata";
+    ASSERT_EQ(duration, kDurationUs) << "Incorrect value of duration returned";
+
+    float frameRate;
+    status = metaData->findFloat(kKeyCaptureFramerate, &frameRate);
+    ASSERT_TRUE(status) << "kKeyCaptureFramerate key does not exists in metadata";
+    ASSERT_EQ(frameRate, kCaptureRate) << "Incorrect value of captureFrameRate returned";
+
+    int32_t top, bottom, left, right;
+    status = metaData->findRect(kKeyCropRect, &left, &top, &right, &bottom);
+    ASSERT_TRUE(status) << "kKeyCropRect key does not exists in metadata";
+    ASSERT_EQ(left, kLeft) << "Incorrect value of left margin returned";
+    ASSERT_EQ(top, kTop) << "Incorrect value of top margin returned";
+    ASSERT_EQ(right, kRight) << "Incorrect value of right margin returned";
+    ASSERT_EQ(bottom, kBottom) << "Incorrect value of bottom margin returned";
+
+    void *platformValue;
+    status = metaData->findPointer(kKeyPlatformPrivate, &platformValue);
+    ASSERT_TRUE(status) << "kKeyPlatformPrivate key does not exists in metadata";
+    ASSERT_EQ(platformValue, &kPlatformValue) << "Incorrect value of pointer returned";
+
+    // Check for the key which is not added to metadata
+    int32_t angle;
+    status = metaData->findInt32(kKeyRotation, &angle);
+    ASSERT_FALSE(status) << "Value for an invalid key is returned when the key is not set";
+
+    delete (metaData);
+}
+
+TEST_F(MetaDataBaseUnitTest, OverWriteFunctionalityTest) {
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create meta data";
+
+    // set/set/read to check first overwrite operation
+    bool status = metaData->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
+    ASSERT_FALSE(status) << "Initializing kKeyMIMEType, overwrite is expected to be false";
+    // Overwrite the value
+    status = metaData->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_HEVC);
+    ASSERT_TRUE(status) << "Setting kKeyMIMEType again, overwrite is expected to be true";
+    // Check the value
+    const char *mime;
+    status = metaData->findCString(kKeyMIMEType, &mime);
+    ASSERT_TRUE(status) << "kKeyMIMEType key does not exists in metadata";
+    ASSERT_STREQ(mime, MEDIA_MIMETYPE_VIDEO_HEVC) << "Mime value is not overwritten";
+
+    // set/set/set/read to check second overwrite operation
+    status = metaData->setInt32(kKeyWidth, kWidth1);
+    ASSERT_FALSE(status) << "Initializing kKeyWidth, overwrite is expected to be false";
+    status = metaData->setInt32(kKeyHeight, kHeight1);
+    ASSERT_FALSE(status) << "Initializing kKeyHeight, overwrite is expected to be false";
+    // Overwrite the value
+    status = metaData->setInt32(kKeyWidth, kWidth2);
+    ASSERT_TRUE(status) << "Setting kKeyWidth again, overwrite is expected to be true";
+    status = metaData->setInt32(kKeyHeight, kHeight2);
+    ASSERT_TRUE(status) << "Setting kKeyHeight again, overwrite is expected to be true";
+    // Overwrite the value again
+    status = metaData->setInt32(kKeyWidth, kWidth3);
+    ASSERT_TRUE(status) << "Setting kKeyWidth again, overwrite is expected to be true";
+    status = metaData->setInt32(kKeyHeight, kHeight3);
+    ASSERT_TRUE(status) << "Setting kKeyHeight again, overwrite is expected to be true";
+    // Check the value
+    int32_t width, height;
+    status = metaData->findInt32(kKeyWidth, &width);
+    ASSERT_TRUE(status) << "kKeyWidth key does not exists in metadata";
+    ASSERT_EQ(width, kWidth3) << "Value of width is not overwritten";
+
+    status = metaData->findInt32(kKeyHeight, &height);
+    ASSERT_TRUE(status) << "kKeyHeight key does not exists in metadata";
+    ASSERT_EQ(height, kHeight3) << "Value of height is not overwritten";
+
+    delete (metaData);
+}
+
+TEST_F(MetaDataBaseUnitTest, RemoveKeyTest) {
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create meta data";
+
+    bool status = metaData->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
+    ASSERT_FALSE(status) << "Initializing kKeyMIMEType, overwrite is expected to be false";
+    // Query the key
+    status = metaData->hasData(kKeyMIMEType);
+    ASSERT_TRUE(status) << "MetaData does not have the mime key";
+
+    status = metaData->remove(kKeyMIMEType);
+    ASSERT_TRUE(status) << "Failed to remove the kKeyMIMEType key";
+
+    // Query the key
+    status = metaData->hasData(kKeyMIMEType);
+    ASSERT_FALSE(status) << "MetaData has mime key after removing it, expected to be false";
+
+    // Remove the non existing key
+    status = metaData->remove(kKeyMIMEType);
+    ASSERT_FALSE(status) << "Removed the non existing key";
+
+    // Check overwriting the removed key
+    metaData->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_HEVC);
+    ASSERT_FALSE(status) << "Overwrite should be false since the key was removed";
+
+    status = metaData->setInt32(kKeyWidth, kWidth1);
+    ASSERT_FALSE(status) << "Initializing kKeyWidth, overwrite is expected to be false";
+
+    // Clear whole metadata
+    metaData->clear();
+
+    // Check finding key after clearing the metadata
+    int32_t width;
+    status = metaData->findInt32(kKeyWidth, &width);
+    ASSERT_FALSE(status) << "MetaData found kKeyWidth key after clearing all the items in it, "
+                            "expected to be false";
+
+    // Query the key
+    status = metaData->hasData(kKeyWidth);
+    ASSERT_FALSE(status)
+            << "MetaData has width key after clearing all the items in it, expected to be false";
+
+    status = metaData->hasData(kKeyMIMEType);
+    ASSERT_FALSE(status)
+            << "MetaData has mime key after clearing all the items in it, expected to be false";
+
+    // Check removing key after clearing the metadata
+    status = metaData->remove(kKeyMIMEType);
+    ASSERT_FALSE(status) << "Removed the key, after clearing the metadata";
+
+    // Checking set after clearing the metadata
+    status = metaData->setInt32(kKeyWidth, kWidth1);
+    ASSERT_FALSE(status) << "Overwrite should be false since the metadata was cleared";
+
+    metaData->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_HEVC);
+    ASSERT_FALSE(status) << "Overwrite should be false since the metadata was cleared";
+
+    delete (metaData);
+}
+
+TEST_F(MetaDataBaseUnitTest, ConvertToStringTest) {
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create meta data";
+
+    String8 info = metaData->toString();
+    ASSERT_EQ(info.length(), 0) << "Empty MetaData length is non-zero: " << info.length();
+
+    bool status = metaData->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
+    ASSERT_FALSE(status) << "Initializing kKeyMIMEType, overwrite is expected to be false";
+
+    status = metaData->setInt32(kKeyWidth, kWidth1);
+    ASSERT_FALSE(status) << "Initializing kKeyWidth, overwrite is expected to be false";
+    status = metaData->setInt32(kKeyHeight, kHeight1);
+    ASSERT_FALSE(status) << "Initializing kKeyHeight, overwrite is expected to be false";
+    status = metaData->setInt32(kKeyVideoProfile, kProfile);
+    ASSERT_FALSE(status) << "Initializing kKeyVideoProfile, overwrite is expected to be false";
+    status = metaData->setInt32(kKeyVideoLevel, kLevel);
+    ASSERT_FALSE(status) << "Initializing kKeyVideoLevel, overwrite is expected to be false";
+
+    info = metaData->toString();
+    ASSERT_GT(info.length(), 0) << "MetaData contains no information";
+
+    // Dump to log for reference
+    metaData->dumpToLog();
+
+    // Clear whole metadata
+    metaData->clear();
+
+    info = metaData->toString();
+    ASSERT_EQ(info.length(), 0) << "MetaData length is non-zero after clearing it: "
+                                << info.length();
+
+    delete (metaData);
+}
+
+}  // namespace android
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp b/media/libstagefright/foundation/tests/OpusHeader/Android.bp
similarity index 67%
copy from media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
copy to media/libstagefright/foundation/tests/OpusHeader/Android.bp
index 655491a..6c64ef3 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
+++ b/media/libstagefright/foundation/tests/OpusHeader/Android.bp
@@ -14,12 +14,23 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_foundation_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_foundation_license",
+    ],
+}
+
 cc_test {
-    name: "Mpeg4H263DecoderTest",
+    name: "OpusHeaderTest",
     gtest: true,
 
     srcs: [
-        "Mpeg4H263DecoderTest.cpp",
+        "OpusHeaderTest.cpp",
     ],
 
     shared_libs: [
@@ -27,7 +38,6 @@
     ],
 
     static_libs: [
-        "libstagefright_m4vh263dec",
         "libstagefright_foundation",
     ],
 
diff --git a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml b/media/libstagefright/foundation/tests/OpusHeader/AndroidTest.xml
similarity index 71%
copy from media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
copy to media/libstagefright/foundation/tests/OpusHeader/AndroidTest.xml
index 7ff9732..afee16a 100644
--- a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
+++ b/media/libstagefright/foundation/tests/OpusHeader/AndroidTest.xml
@@ -13,19 +13,19 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Test module config for Mp3 Decoder unit test">
-    <option name="test-suite-tag" value="Mp3DecoderTest" />
+<configuration description="Test module config for opus header unit tests">
+    <option name="test-suite-tag" value="OpusHeaderTest" />
     <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
         <option name="cleanup" value="true" />
-        <option name="push" value="Mp3DecoderTest->/data/local/tmp/Mp3DecoderTest" />
+        <option name="push" value="OpusHeaderTest->/data/local/tmp/OpusHeaderTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest.zip?unzip=true"
-            value="/data/local/tmp/Mp3DecoderTestRes/" />
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/foundation/tests/OpusHeader/OpusHeader.zip?unzip=true"
+            value="/data/local/tmp/OpusHeaderTestRes/" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.GTest" >
         <option name="native-test-device-path" value="/data/local/tmp" />
-        <option name="module-name" value="Mp3DecoderTest" />
-        <option name="native-test-flag" value="-P /data/local/tmp/Mp3DecoderTestRes/" />
+        <option name="module-name" value="OpusHeaderTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/OpusHeaderTestRes/" />
     </test>
-</configuration>
+</configuration>
\ No newline at end of file
diff --git a/media/libstagefright/foundation/tests/OpusHeader/OpusHeaderTest.cpp b/media/libstagefright/foundation/tests/OpusHeader/OpusHeaderTest.cpp
new file mode 100644
index 0000000..e39c915
--- /dev/null
+++ b/media/libstagefright/foundation/tests/OpusHeader/OpusHeaderTest.cpp
@@ -0,0 +1,342 @@
+/*
+ * Copyright (C) 2020 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 "OpusHeaderTest"
+#include <utils/Log.h>
+
+#include <fstream>
+#include <stdio.h>
+#include <string.h>
+
+#include <media/stagefright/foundation/OpusHeader.h>
+
+#include "OpusHeaderTestEnvironment.h"
+
+using namespace android;
+
+#define OUTPUT_FILE_NAME "/data/local/tmp/OpusOutput"
+
+// Opus in WebM is a well-known, yet under-documented, format. The codec private data
+// of the track is an Opus Ogg header (https://tools.ietf.org/html/rfc7845#section-5.1)
+// channel mapping offset in opus header
+constexpr size_t kOpusHeaderStreamMapOffset = 21;
+constexpr size_t kMaxOpusHeaderSize = 100;
+// AOPUSHDR + AOPUSHDRLength +
+// (8 + 8 ) +
+// Header(csd) + num_streams + num_coupled + 1
+// (19 + 1 + 1 + 1) +
+// AOPUSDLY + AOPUSDLYLength + DELAY + AOPUSPRL + AOPUSPRLLength + PRL
+// (8 + 8 + 8 + 8 + 8 + 8)
+// = 86
+constexpr size_t kOpusHeaderChannelMapOffset = 86;
+constexpr uint32_t kOpusSampleRate = 48000;
+constexpr uint64_t kOpusSeekPrerollNs = 80000000;
+constexpr int64_t kNsecPerSec = 1000000000ll;
+
+// Opus uses Vorbis channel mapping, and Vorbis channel mapping specifies
+// mappings for up to 8 channels. This information is part of the Vorbis I
+// Specification:
+// http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html
+constexpr int kMaxChannels = 8;
+constexpr uint8_t kOpusChannelMap[kMaxChannels][kMaxChannels] = {
+        {0},
+        {0, 1},
+        {0, 2, 1},
+        {0, 1, 2, 3},
+        {0, 4, 1, 2, 3},
+        {0, 4, 1, 2, 3, 5},
+        {0, 4, 1, 2, 3, 5, 6},
+        {0, 6, 1, 2, 3, 4, 5, 7},
+};
+
+static OpusHeaderTestEnvironment *gEnv = nullptr;
+
+class OpusHeaderTest {
+  public:
+    OpusHeaderTest() : mInputBuffer(nullptr) {}
+
+    ~OpusHeaderTest() {
+        if (mEleStream.is_open()) mEleStream.close();
+        if (mInputBuffer) {
+            free(mInputBuffer);
+            mInputBuffer = nullptr;
+        }
+    }
+    ifstream mEleStream;
+    uint8_t *mInputBuffer;
+};
+
+class OpusHeaderParseTest : public OpusHeaderTest,
+                            public ::testing::TestWithParam<
+                                    tuple<string /* InputFileName */, int32_t /* ChannelCount */,
+                                          bool /* isHeaderValid */, bool /* isCodecDelayValid */,
+                                          bool /* isSeekPreRollValid */, bool /* isInputValid */>> {
+};
+
+class OpusHeaderWriteTest
+    : public OpusHeaderTest,
+      public ::testing::TestWithParam<tuple<int32_t /* ChannelCount */, int32_t /* skipSamples */,
+                                            string /* referenceFile */>> {};
+
+TEST_P(OpusHeaderWriteTest, WriteTest) {
+    tuple<int32_t, int32_t, string> params = GetParam();
+    OpusHeader writtenHeader;
+    memset(&writtenHeader, 0, sizeof(writtenHeader));
+    int32_t channels = get<0>(params);
+    writtenHeader.channels = channels;
+    writtenHeader.num_streams = channels;
+    writtenHeader.channel_mapping = ((channels > 8) ? 255 : (channels > 2));
+    int32_t skipSamples = get<1>(params);
+    string referenceFileName = gEnv->getRes() + get<2>(params);
+    writtenHeader.skip_samples = skipSamples;
+    uint64_t codecDelayNs = skipSamples * kNsecPerSec / kOpusSampleRate;
+    uint8_t headerData[kMaxOpusHeaderSize];
+    int32_t headerSize = WriteOpusHeaders(writtenHeader, kOpusSampleRate, headerData,
+                                          sizeof(headerData), codecDelayNs, kOpusSeekPrerollNs);
+    ASSERT_GT(headerSize, 0) << "failed to generate Opus header";
+    ASSERT_LE(headerSize, kMaxOpusHeaderSize)
+            << "Invalid header written. Header size can't exceed kMaxOpusHeaderSize";
+
+    ofstream ostrm;
+    ostrm.open(OUTPUT_FILE_NAME, ofstream::binary);
+    ASSERT_TRUE(ostrm.is_open()) << "Failed to open output file " << OUTPUT_FILE_NAME;
+    ostrm.write(reinterpret_cast<char *>(headerData), headerSize);
+    ostrm.close();
+
+    mEleStream.open(referenceFileName, ifstream::binary);
+    ASSERT_EQ(mEleStream.is_open(), true) << "Failed to open referenceFileName " << get<2>(params);
+
+    struct stat buf;
+    int32_t statStatus = stat(referenceFileName.c_str(), &buf);
+    ASSERT_EQ(statStatus, 0) << "Unable to get file properties";
+
+    size_t fileSize = buf.st_size;
+    mInputBuffer = (uint8_t *)malloc(fileSize);
+    ASSERT_NE(mInputBuffer, nullptr) << "Insufficient memory. Malloc failed for size " << fileSize;
+
+    mEleStream.read(reinterpret_cast<char *>(mInputBuffer), fileSize);
+    ASSERT_EQ(mEleStream.gcount(), fileSize) << "mEleStream.gcount() != bytesCount";
+
+    ASSERT_EQ(fileSize, headerSize)
+            << "Mismatch in size between header generated and reference header";
+    int32_t match = memcmp(reinterpret_cast<char *>(mInputBuffer),
+                           reinterpret_cast<char *>(headerData), fileSize);
+    ASSERT_EQ(match, 0) << "Opus header does not match reference file: " << referenceFileName;
+
+    size_t opusHeadSize = 0;
+    size_t codecDelayBufSize = 0;
+    size_t seekPreRollBufSize = 0;
+    void *opusHeadBuf = nullptr;
+    void *codecDelayBuf = nullptr;
+    void *seekPreRollBuf = nullptr;
+    bool status = GetOpusHeaderBuffers(headerData, headerSize, &opusHeadBuf, &opusHeadSize,
+                                       &codecDelayBuf, &codecDelayBufSize, &seekPreRollBuf,
+                                       &seekPreRollBufSize);
+    ASSERT_TRUE(status) << "Encountered error in GetOpusHeaderBuffers";
+
+    uint64_t value = *((uint64_t *)codecDelayBuf);
+    ASSERT_EQ(value, codecDelayNs);
+
+    value = *((uint64_t *)seekPreRollBuf);
+    ASSERT_EQ(value, kOpusSeekPrerollNs);
+
+    OpusHeader parsedHeader;
+    status = ParseOpusHeader((uint8_t *)opusHeadBuf, opusHeadSize, &parsedHeader);
+    ASSERT_TRUE(status) << "Encountered error while Parsing Opus Header.";
+
+    ASSERT_EQ(writtenHeader.channels, parsedHeader.channels)
+            << "Invalid header generated. Mismatch between channel counts";
+
+    ASSERT_EQ(writtenHeader.skip_samples, parsedHeader.skip_samples)
+            << "Mismatch between no of skipSamples written "
+               "and no of skipSamples got after parsing";
+
+    ASSERT_EQ(writtenHeader.channel_mapping, parsedHeader.channel_mapping)
+            << "Mismatch between channelMapping written "
+               "and channelMapping got after parsing";
+
+    if (parsedHeader.channel_mapping) {
+        ASSERT_GT(parsedHeader.channels, 2);
+        ASSERT_EQ(writtenHeader.num_streams, parsedHeader.num_streams)
+                << "Invalid header generated. Mismatch between channel counts";
+
+        ASSERT_EQ(writtenHeader.num_coupled, parsedHeader.num_coupled)
+                << "Invalid header generated. Mismatch between channel counts";
+
+        ASSERT_EQ(parsedHeader.num_coupled + parsedHeader.num_streams, parsedHeader.channels);
+
+        ASSERT_LE(parsedHeader.num_coupled, parsedHeader.num_streams)
+                << "Invalid header generated. Number of coupled streams cannot be greater than "
+                   "number "
+                   "of streams.";
+
+        ASSERT_EQ(headerSize, kOpusHeaderChannelMapOffset + writtenHeader.channels)
+                << "Invalid header written. Header size should be equal to 86 + "
+                   "writtenHeader.channels";
+
+        uint8_t mappedChannelNumber;
+        for (int32_t channelNumber = 0; channelNumber < channels; channelNumber++) {
+            mappedChannelNumber = *(reinterpret_cast<uint8_t *>(opusHeadBuf) +
+                                    kOpusHeaderStreamMapOffset + channelNumber);
+            ASSERT_LT(mappedChannelNumber, channels) << "Invalid header generated. Channel mapping "
+                                                        "cannot be greater than channel count.";
+
+            ASSERT_EQ(mappedChannelNumber, kOpusChannelMap[channels - 1][channelNumber])
+                    << "Invalid header generated. Channel mapping is not as per specification.";
+        }
+    } else {
+        ASSERT_LE(parsedHeader.channels, 2);
+    }
+}
+
+TEST_P(OpusHeaderParseTest, ParseTest) {
+    tuple<string, int32_t, bool, bool, bool, bool> params = GetParam();
+    string inputFileName = gEnv->getRes() + get<0>(params);
+    mEleStream.open(inputFileName, ifstream::binary);
+    ASSERT_EQ(mEleStream.is_open(), true) << "Failed to open inputfile " << get<0>(params);
+    bool isHeaderValid = get<2>(params);
+    bool isCodecDelayValid = get<3>(params);
+    bool isSeekPreRollValid = get<4>(params);
+    bool isInputValid = get<5>(params);
+
+    struct stat buf;
+    stat(inputFileName.c_str(), &buf);
+    size_t fileSize = buf.st_size;
+    mInputBuffer = (uint8_t *)malloc(fileSize);
+    ASSERT_NE(mInputBuffer, nullptr) << "Insufficient memory. Malloc failed for size " << fileSize;
+
+    mEleStream.read(reinterpret_cast<char *>(mInputBuffer), fileSize);
+    ASSERT_EQ(mEleStream.gcount(), fileSize) << "mEleStream.gcount() != bytesCount";
+
+    OpusHeader header;
+    size_t opusHeadSize = 0;
+    size_t codecDelayBufSize = 0;
+    size_t seekPreRollBufSize = 0;
+    void *opusHeadBuf = nullptr;
+    void *codecDelayBuf = nullptr;
+    void *seekPreRollBuf = nullptr;
+    bool status = GetOpusHeaderBuffers(mInputBuffer, fileSize, &opusHeadBuf, &opusHeadSize,
+                                       &codecDelayBuf, &codecDelayBufSize, &seekPreRollBuf,
+                                       &seekPreRollBufSize);
+    if (!isHeaderValid) {
+        ASSERT_EQ(opusHeadBuf, nullptr);
+    } else {
+        ASSERT_NE(opusHeadBuf, nullptr);
+    }
+    if (!isCodecDelayValid) {
+        ASSERT_EQ(codecDelayBuf, nullptr);
+    } else {
+        ASSERT_NE(codecDelayBuf, nullptr);
+    }
+    if (!isSeekPreRollValid) {
+        ASSERT_EQ(seekPreRollBuf, nullptr);
+    } else {
+        ASSERT_NE(seekPreRollBuf, nullptr);
+    }
+    if (!status) {
+        ASSERT_FALSE(isInputValid) << "GetOpusHeaderBuffers failed";
+        return;
+    }
+
+    status = ParseOpusHeader((uint8_t *)opusHeadBuf, opusHeadSize, &header);
+
+    if (status) {
+        ASSERT_TRUE(isInputValid) << "Parse opus header didn't fail for invalid input";
+    } else {
+        ASSERT_FALSE(isInputValid);
+        return;
+    }
+
+    int32_t channels = get<1>(params);
+    ASSERT_EQ(header.channels, channels) << "Parser returned invalid channel count";
+    ASSERT_LE(header.channels, kMaxChannels);
+
+    ASSERT_LE(header.num_coupled, header.num_streams)
+            << "Invalid header generated. Number of coupled streams cannot be greater than number "
+               "of streams.";
+
+    ASSERT_EQ(header.num_coupled + header.num_streams, header.channels);
+
+    if (header.channel_mapping) {
+        uint8_t mappedChannelNumber;
+        for (int32_t channelNumber = 0; channelNumber < channels; channelNumber++) {
+            mappedChannelNumber = *(reinterpret_cast<uint8_t *>(opusHeadBuf) +
+                                    kOpusHeaderStreamMapOffset + channelNumber);
+            ASSERT_LT(mappedChannelNumber, channels)
+                    << "Invalid header. Channel mapping cannot be greater than channel count.";
+
+            ASSERT_EQ(mappedChannelNumber, kOpusChannelMap[channels - 1][channelNumber])
+                    << "Invalid header generated. Channel mapping "
+                       "is not as per specification.";
+        }
+    }
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        OpusHeaderTestAll, OpusHeaderWriteTest,
+        ::testing::Values(make_tuple(1, 312, "output_channels_1skipSamples_312.opus"),
+                          make_tuple(2, 312, "output_channels_2skipSamples_312.opus"),
+                          make_tuple(5, 312, "output_channels_5skipSamples_312.opus"),
+                          make_tuple(6, 312, "output_channels_6skipSamples_312.opus"),
+                          make_tuple(1, 0, "output_channels_1skipSamples_0.opus"),
+                          make_tuple(2, 0, "output_channels_2skipSamples_0.opus"),
+                          make_tuple(5, 0, "output_channels_5skipSamples_0.opus"),
+                          make_tuple(6, 0, "output_channels_6skipSamples_0.opus"),
+                          make_tuple(1, 624, "output_channels_1skipSamples_624.opus"),
+                          make_tuple(2, 624, "output_channels_2skipSamples_624.opus"),
+                          make_tuple(5, 624, "output_channels_5skipSamples_624.opus"),
+                          make_tuple(6, 624, "output_channels_6skipSamples_624.opus")));
+
+INSTANTIATE_TEST_SUITE_P(
+        OpusHeaderTestAll, OpusHeaderParseTest,
+        ::testing::Values(
+                make_tuple("2ch_valid_size83B.opus", 2, true, true, true, true),
+                make_tuple("3ch_valid_size88B.opus", 3, true, true, true, true),
+                make_tuple("5ch_valid.opus", 5, true, false, false, true),
+                make_tuple("6ch_valid.opus", 6, true, false, false, true),
+                make_tuple("1ch_valid.opus", 1, true, false, false, true),
+                make_tuple("2ch_valid.opus", 2, true, false, false, true),
+                make_tuple("3ch_invalid_size.opus", 3, true, true, true, false),
+                make_tuple("3ch_invalid_streams.opus", 3, true, true, true, false),
+                make_tuple("5ch_invalid_channelmapping.opus", 5, true, false, false, false),
+                make_tuple("5ch_invalid_coupledstreams.opus", 5, true, false, false, false),
+                make_tuple("6ch_invalid_channelmapping.opus", 6, true, false, false, false),
+                make_tuple("9ch_invalid_channels.opus", 9, true, true, true, false),
+                make_tuple("2ch_invalid_header.opus", 2, false, false, false, false),
+                make_tuple("2ch_invalid_headerlength_16.opus", 2, false, false, false, false),
+                make_tuple("2ch_invalid_headerlength_256.opus", 2, false, false, false, false),
+                make_tuple("2ch_invalid_size.opus", 2, false, false, false, false),
+                make_tuple("3ch_invalid_channelmapping_0.opus", 3, true, true, true, false),
+                make_tuple("3ch_invalid_coupledstreams.opus", 3, true, true, true, false),
+                make_tuple("3ch_invalid_headerlength.opus", 3, true, true, true, false),
+                make_tuple("3ch_invalid_headerSize1.opus", 3, false, false, false, false),
+                make_tuple("3ch_invalid_headerSize2.opus", 3, false, false, false, false),
+                make_tuple("3ch_invalid_headerSize3.opus", 3, false, false, false, false),
+                make_tuple("3ch_invalid_nodelay.opus", 3, false, false, false, false),
+                make_tuple("3ch_invalid_nopreroll.opus", 3, false, false, false, false)));
+
+int main(int argc, char **argv) {
+    gEnv = new OpusHeaderTestEnvironment();
+    ::testing::AddGlobalTestEnvironment(gEnv);
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = gEnv->initFromOptions(argc, argv);
+    if (status == 0) {
+        status = RUN_ALL_TESTS();
+        ALOGD("Opus Header Test Result = %d\n", status);
+    }
+    return status;
+}
diff --git a/media/libstagefright/foundation/tests/OpusHeader/OpusHeaderTestEnvironment.h b/media/libstagefright/foundation/tests/OpusHeader/OpusHeaderTestEnvironment.h
new file mode 100644
index 0000000..d0163c3
--- /dev/null
+++ b/media/libstagefright/foundation/tests/OpusHeader/OpusHeaderTestEnvironment.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2020 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 __OPUS_HEADER_TEST_ENVIRONMENT_H__
+#define __OPUS_HEADER_TEST_ENVIRONMENT_H__
+
+#include <gtest/gtest.h>
+
+#include <getopt.h>
+
+using namespace std;
+
+class OpusHeaderTestEnvironment : public ::testing::Environment {
+  public:
+    OpusHeaderTestEnvironment() : res("/data/local/tmp/") {}
+
+    // Parses the command line arguments
+    int initFromOptions(int argc, char **argv);
+
+    void setRes(const char *_res) { res = _res; }
+
+    const string getRes() const { return res; }
+
+  private:
+    string res;
+};
+
+int OpusHeaderTestEnvironment::initFromOptions(int argc, char **argv) {
+    static struct option options[] = {{"path", required_argument, 0, 'P'}, {0, 0, 0, 0}};
+
+    while (true) {
+        int index = 0;
+        int c = getopt_long(argc, argv, "P:", options, &index);
+        if (c == -1) {
+            break;
+        }
+
+        switch (c) {
+            case 'P': {
+                setRes(optarg);
+                break;
+            }
+            default:
+                break;
+        }
+    }
+
+    if (optind < argc) {
+        fprintf(stderr,
+                "unrecognized option: %s\n\n"
+                "usage: %s <gtest options> <test options>\n\n"
+                "test options are:\n\n"
+                "-P, --path: Resource files directory location\n",
+                argv[optind ?: 1], argv[0]);
+        return 2;
+    }
+    return 0;
+}
+
+#endif  // __OPUS_HEADER_TEST_ENVIRONMENT_H__
diff --git a/media/libstagefright/foundation/tests/OpusHeader/README.md b/media/libstagefright/foundation/tests/OpusHeader/README.md
new file mode 100644
index 0000000..860c827
--- /dev/null
+++ b/media/libstagefright/foundation/tests/OpusHeader/README.md
@@ -0,0 +1,39 @@
+## Media Testing ##
+---
+#### Opus Header
+The OpusHeader Test Suite validates the OPUS header available in libstagefright.
+
+Run the following steps to build the test suite:
+```
+m OpusHeaderTest
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+```
+adb push ${OUT}/data/nativetest64/OpusHeaderTest/OpusHeaderTest /data/local/tmp/
+```
+
+To test 32-bit binary push binaries from nativetest.
+```
+adb push ${OUT}/data/nativetest/OpusHeaderTest/OpusHeaderTest /data/local/tmp/
+```
+
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/foundation/tests/OpusHeader/OpusHeader.zip). Download, unzip and push these files into device for testing.
+
+```
+adb push OpusHeader /data/local/tmp/
+```
+
+usage: OpusHeaderTest -P \<path_to_folder\>
+```
+adb shell /data/local/tmp/OpusHeaderTest -P /data/local/tmp/OpusHeader/
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest OpusHeaderTest -- --enable-module-dynamic-download=true
+```
diff --git a/media/libstagefright/foundation/tests/TypeTraits_test.cpp b/media/libstagefright/foundation/tests/TypeTraits_test.cpp
index 1e2049d..d5383d1 100644
--- a/media/libstagefright/foundation/tests/TypeTraits_test.cpp
+++ b/media/libstagefright/foundation/tests/TypeTraits_test.cpp
@@ -30,7 +30,7 @@
     enum IA : int32_t { };
 };
 
-// =========== basic sanity tests for type-support templates
+// =========== basic tests for type-support templates
 TEST_F(TypeTraitsTest, StaticTests) {
 
     // ============ is_integral_or_enum
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp b/media/libstagefright/foundation/tests/colorutils/Android.bp
similarity index 65%
copy from media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
copy to media/libstagefright/foundation/tests/colorutils/Android.bp
index 655491a..5a17e4b 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
+++ b/media/libstagefright/foundation/tests/colorutils/Android.bp
@@ -14,20 +14,32 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_foundation_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_foundation_license",
+    ],
+}
+
 cc_test {
-    name: "Mpeg4H263DecoderTest",
+    name: "ColorUtilsTest",
     gtest: true,
 
     srcs: [
-        "Mpeg4H263DecoderTest.cpp",
+        "ColorUtilsTest.cpp",
     ],
 
     shared_libs: [
         "liblog",
+        "libutils",
+        "libmediandk",
     ],
 
     static_libs: [
-        "libstagefright_m4vh263dec",
         "libstagefright_foundation",
     ],
 
@@ -37,10 +49,10 @@
     ],
 
     sanitize: {
+        cfi: true,
         misc_undefined: [
             "unsigned-integer-overflow",
             "signed-integer-overflow",
         ],
-        cfi: true,
     },
 }
diff --git a/media/libstagefright/foundation/tests/colorutils/ColorUtilsTest.cpp b/media/libstagefright/foundation/tests/colorutils/ColorUtilsTest.cpp
new file mode 100644
index 0000000..0d802b4
--- /dev/null
+++ b/media/libstagefright/foundation/tests/colorutils/ColorUtilsTest.cpp
@@ -0,0 +1,773 @@
+/*
+ * Copyright (C) 2020 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 "ColorUtilsTest"
+#include <utils/Log.h>
+
+#include <gtest/gtest.h>
+
+#include <stdio.h>
+
+#include <media/NdkMediaFormat.h>
+#include <media/NdkMediaFormatPriv.h>
+#include <media/stagefright/MediaCodecConstants.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/ColorUtils.h>
+
+const size_t kHDRBufferSize = 25;
+const uint16_t kHDRInfoTestValue1 = 420;
+const uint16_t kHDRInfoTestValue2 = 42069;
+
+using namespace android;
+
+typedef ColorAspects CA;
+
+class ColorRangeTest : public ::testing::TestWithParam</* ColorRange */ CA::Range> {
+  public:
+    ColorRangeTest() { mRange = GetParam(); };
+
+    CA::Range mRange;
+};
+
+class ColorTransferTest : public ::testing::TestWithParam</* ColorTransfer */ CA::Transfer> {
+  public:
+    ColorTransferTest() { mTransfer = GetParam(); };
+
+    CA::Transfer mTransfer;
+};
+
+class ColorStandardTest : public ::testing::TestWithParam<std::pair<
+                                  /* Primaries */ CA::Primaries,
+                                  /* MatrixCoeffs */ CA::MatrixCoeffs>> {
+  public:
+    ColorStandardTest() {
+        mPrimaries = GetParam().first;
+        mMatrixCoeffs = GetParam().second;
+    };
+
+    CA::Primaries mPrimaries;
+    CA::MatrixCoeffs mMatrixCoeffs;
+};
+
+class IsoToPlatformAspectsTest : public ::testing::TestWithParam<std::tuple<
+                                         /* Primaries */ CA::Primaries,
+                                         /* Transfer */ CA::Transfer,
+                                         /* MatrixCoeffs */ CA::MatrixCoeffs,
+                                         /* Standard */ int32_t,
+                                         /* Transfer */ int32_t>> {
+  public:
+    IsoToPlatformAspectsTest() {
+        mPrimaries = std::get<0>(GetParam());
+        mTransfer = std::get<1>(GetParam());
+        mMatrixCoeffs = std::get<2>(GetParam());
+        mPlatformStandard = std::get<3>(GetParam());
+        mPlatformTransfer = std::get<4>(GetParam());
+    };
+
+    CA::Primaries mPrimaries;
+    CA::Transfer mTransfer;
+    CA::MatrixCoeffs mMatrixCoeffs;
+    int32_t mPlatformStandard;
+    int32_t mPlatformTransfer;
+};
+
+class ColorAspectsTest : public ::testing::TestWithParam<std::tuple<
+                                 /* Primaries */ CA::Primaries,
+                                 /* ColorTransfer */ CA::Transfer,
+                                 /* MatrixCoeffs */ CA::MatrixCoeffs,
+                                 /* ColorRange */ CA::Range,
+                                 /* ColorStandard */ CA::Standard>> {
+  public:
+    ColorAspectsTest() {
+        mPrimaries = std::get<0>(GetParam());
+        mTransfer = std::get<1>(GetParam());
+        mMatrixCoeffs = std::get<2>(GetParam());
+        mRange = std::get<3>(GetParam());
+        mStandard = std::get<4>(GetParam());
+    };
+
+    CA::Primaries mPrimaries;
+    CA::Transfer mTransfer;
+    CA::MatrixCoeffs mMatrixCoeffs;
+    CA::Range mRange;
+    CA::Standard mStandard;
+};
+
+class DefaultColorAspectsTest : public ::testing::TestWithParam<std::tuple<
+                                        /* Width */ int32_t,
+                                        /* Height */ int32_t,
+                                        /* Primaries */ CA::Primaries,
+                                        /* MatrixCoeffs */ CA::MatrixCoeffs>> {
+  public:
+    DefaultColorAspectsTest() {
+        mWidth = std::get<0>(GetParam());
+        mHeight = std::get<1>(GetParam());
+        mPrimaries = std::get<2>(GetParam());
+        mMatrixCoeffs = std::get<3>(GetParam());
+    };
+
+    int32_t mWidth;
+    int32_t mHeight;
+    CA::Primaries mPrimaries;
+    CA::MatrixCoeffs mMatrixCoeffs;
+};
+
+class DataSpaceTest : public ::testing::TestWithParam<std::tuple<
+                              /* ColorRange */ CA::Range,
+                              /* Primaries */ CA::Primaries,
+                              /* ColorTransfer */ CA::Transfer,
+                              /* MatrixCoeffs */ CA::MatrixCoeffs,
+                              /* v0_android_dataspace */ android_dataspace,
+                              /* android_dataspace */ android_dataspace>> {
+  public:
+    DataSpaceTest() {
+        mRange = std::get<0>(GetParam());
+        mPrimaries = std::get<1>(GetParam());
+        mTransfer = std::get<2>(GetParam());
+        mMatrixCoeffs = std::get<3>(GetParam());
+        mDataSpaceV0 = std::get<4>(GetParam());
+        mDataSpace = std::get<5>(GetParam());
+    };
+
+    CA::Range mRange;
+    CA::Primaries mPrimaries;
+    CA::Transfer mTransfer;
+    CA::MatrixCoeffs mMatrixCoeffs;
+    android_dataspace mDataSpaceV0;
+    android_dataspace mDataSpace;
+};
+
+TEST_P(ColorRangeTest, WrapColorRangeTest) {
+    int32_t range = ColorUtils::wrapColorAspectsIntoColorRange(mRange);
+    CA::Range unwrappedRange;
+    status_t status = ColorUtils::unwrapColorAspectsFromColorRange(range, &unwrappedRange);
+    ASSERT_EQ(status, OK) << "unwrapping ColorAspects from ColorRange failed";
+    EXPECT_EQ(unwrappedRange, mRange) << "Returned ColorRange doesn't match";
+    ALOGV("toString test: Range: %s", asString(mRange, "default"));
+}
+
+TEST_P(ColorTransferTest, WrapColorTransferTest) {
+    int32_t transfer = ColorUtils::wrapColorAspectsIntoColorTransfer(mTransfer);
+    CA::Transfer unwrappedTransfer;
+    status_t status = ColorUtils::unwrapColorAspectsFromColorTransfer(transfer, &unwrappedTransfer);
+    ASSERT_EQ(status, OK) << "unwrapping ColorAspects from ColorTransfer failed";
+    EXPECT_EQ(unwrappedTransfer, mTransfer) << "Returned ColorTransfer doesn't match";
+    ALOGV("toString test: Transfer: %s", asString(mTransfer, "default"));
+}
+
+TEST_P(ColorStandardTest, WrapColorStandardTest) {
+    int32_t standard = ColorUtils::wrapColorAspectsIntoColorStandard(mPrimaries, mMatrixCoeffs);
+    CA::Primaries unwrappedPrimaries;
+    CA::MatrixCoeffs unwrappedMatrixCoeffs;
+    status_t status = ColorUtils::unwrapColorAspectsFromColorStandard(standard, &unwrappedPrimaries,
+                                                                      &unwrappedMatrixCoeffs);
+    ASSERT_EQ(status, OK) << "unwrapping ColorAspects from ColorStandard failed";
+    EXPECT_EQ(unwrappedPrimaries, mPrimaries) << "Returned primaries doesn't match";
+    EXPECT_EQ(unwrappedMatrixCoeffs, mMatrixCoeffs) << "Returned  matrixCoeffs doesn't match";
+}
+
+TEST_P(ColorAspectsTest, PlatformAspectsTest) {
+    CA aspects;
+    aspects.mRange = mRange;
+    aspects.mPrimaries = mPrimaries;
+    aspects.mTransfer = mTransfer;
+    aspects.mMatrixCoeffs = mMatrixCoeffs;
+
+    int32_t range = -1;
+    int32_t standard = -1;
+    int32_t transfer = -1;
+    status_t status = ColorUtils::convertCodecColorAspectsToPlatformAspects(aspects, &range,
+                                                                            &standard, &transfer);
+    ASSERT_EQ(status, OK) << "Conversion of ColorAspects to PlatformAspects failed";
+
+    CA returnedAspects;
+    status = ColorUtils::convertPlatformColorAspectsToCodecAspects(range, standard, transfer,
+                                                                   returnedAspects);
+    ASSERT_EQ(status, OK) << "Conversion of PlatformAspects to ColorAspects failed";
+    EXPECT_EQ(returnedAspects.mRange, aspects.mRange)
+            << "range mismatch for conversion between PlatformAspects";
+    EXPECT_EQ(returnedAspects.mPrimaries, aspects.mPrimaries)
+            << "primaries mismatch for conversion between PlatformAspects";
+    EXPECT_EQ(returnedAspects.mTransfer, aspects.mTransfer)
+            << "transfer mismatch for conversion between PlatformAspects";
+    EXPECT_EQ(returnedAspects.mMatrixCoeffs, aspects.mMatrixCoeffs)
+            << "matrixCoeffs mismatch for conversion between PlatformAspects";
+}
+
+TEST_P(ColorAspectsTest, IsoAspectsTest) {
+    CA aspects;
+    aspects.mRange = mRange;
+    aspects.mPrimaries = mPrimaries;
+    aspects.mTransfer = mTransfer;
+    aspects.mMatrixCoeffs = mMatrixCoeffs;
+
+    int32_t primaries = -1;
+    int32_t colorTransfer = -1;
+    int32_t matrixCoeffs = -1;
+    bool fullRange = false;
+    ColorUtils::convertCodecColorAspectsToIsoAspects(aspects, &primaries, &colorTransfer,
+                                                     &matrixCoeffs, &fullRange);
+
+    CA returnedAspects;
+    ColorUtils::convertIsoColorAspectsToCodecAspects(primaries, colorTransfer, matrixCoeffs,
+                                                     fullRange, returnedAspects);
+    EXPECT_EQ(returnedAspects.mRange, aspects.mRange)
+            << "range mismatch for conversion between IsoAspects";
+    EXPECT_EQ(returnedAspects.mPrimaries, aspects.mPrimaries)
+            << "primaries mismatch for conversion between IsoAspects";
+    EXPECT_EQ(returnedAspects.mTransfer, aspects.mTransfer)
+            << "transfer mismatch for conversion between IsoAspects";
+    EXPECT_EQ(returnedAspects.mMatrixCoeffs, aspects.mMatrixCoeffs)
+            << "matrixCoeffs mismatch for conversion between IsoAspects";
+}
+
+TEST_P(IsoToPlatformAspectsTest, IsoAspectsToPlatformAspectsTest) {
+    CA aspects;
+    aspects.mPrimaries = mPrimaries;
+    aspects.mTransfer = mTransfer;
+    aspects.mMatrixCoeffs = mMatrixCoeffs;
+
+    int32_t isoPrimaries = -1;
+    int32_t isoTransfer = -1;
+    int32_t isoMatrixCoeffs = -1;
+    bool fullrange = false;
+    ColorUtils::convertCodecColorAspectsToIsoAspects(aspects, &isoPrimaries, &isoTransfer,
+                                                     &isoMatrixCoeffs, &fullrange);
+
+    int32_t range = -1;
+    int32_t standard = -1;
+    int32_t transfer = -1;
+    ColorUtils::convertIsoColorAspectsToPlatformAspects(isoPrimaries, isoTransfer, isoMatrixCoeffs,
+                                                        fullrange, &range, &standard, &transfer);
+    if (fullrange) {
+        EXPECT_EQ(range, ColorUtils::kColorRangeFull)
+                << "range incorrect converting to PlatformAspects";
+    }
+    EXPECT_EQ(standard, mPlatformStandard) << "standard incorrect converting to PlatformAspects";
+    EXPECT_EQ(transfer, mPlatformTransfer) << "transfer incorrect converting to PlatformAspects";
+}
+
+TEST_P(ColorAspectsTest, PackColorAspectsTest) {
+    CA aspects;
+    aspects.mRange = mRange;
+    aspects.mPrimaries = mPrimaries;
+    aspects.mTransfer = mTransfer;
+    aspects.mMatrixCoeffs = mMatrixCoeffs;
+    uint32_t packedColorAspects = ColorUtils::packToU32(aspects);
+
+    CA unpackedAspects = ColorUtils::unpackToColorAspects(packedColorAspects);
+    EXPECT_EQ(unpackedAspects.mRange, mRange) << "range mismatch after unpacking";
+    EXPECT_EQ(unpackedAspects.mPrimaries, mPrimaries) << "primaries mismatch after unpacking";
+    EXPECT_EQ(unpackedAspects.mTransfer, mTransfer) << "transfer mismatch after unpacking";
+    EXPECT_EQ(unpackedAspects.mMatrixCoeffs, mMatrixCoeffs)
+            << "matrixCoeffs mismatch after unpacking";
+    ALOGV("toString test: Standard: %s", asString(mStandard, "default"));
+}
+
+TEST_P(DefaultColorAspectsTest, DefaultColorAspectsTest) {
+    CA aspects;
+    aspects.mRange = CA::RangeUnspecified;
+    aspects.mPrimaries = CA::PrimariesUnspecified;
+    aspects.mMatrixCoeffs = CA::MatrixUnspecified;
+    aspects.mTransfer = CA::TransferUnspecified;
+
+    ColorUtils::setDefaultCodecColorAspectsIfNeeded(aspects, mWidth, mHeight);
+    EXPECT_EQ(aspects.mRange, CA::RangeLimited) << "range not set to default";
+    EXPECT_EQ(aspects.mPrimaries, mPrimaries) << "primaries not set to default";
+    EXPECT_EQ(aspects.mMatrixCoeffs, mMatrixCoeffs) << "matrixCoeffs not set to default";
+    EXPECT_EQ(aspects.mTransfer, CA::TransferSMPTE170M) << "transfer not set to default";
+}
+
+TEST_P(DataSpaceTest, DataSpaceTest) {
+    CA aspects;
+    aspects.mRange = mRange;
+    aspects.mPrimaries = mPrimaries;
+    aspects.mTransfer = mTransfer;
+    aspects.mMatrixCoeffs = mMatrixCoeffs;
+
+    android_dataspace dataSpace = ColorUtils::getDataSpaceForColorAspects(aspects, false);
+    EXPECT_EQ(dataSpace, mDataSpace) << "Returned incorrect dataspace";
+
+    bool status = ColorUtils::convertDataSpaceToV0(dataSpace);
+    ASSERT_TRUE(status) << "Returned v0 dataspace is not aspect-only";
+    EXPECT_EQ(dataSpace, mDataSpaceV0) << "Returned incorrect v0 dataspace";
+}
+
+TEST(ColorUtilsUnitTest, AspectsChangedTest) {
+    CA origAspects;
+    origAspects.mRange = CA::Range::RangeFull;
+    origAspects.mPrimaries = CA::Primaries::PrimariesBT709_5;
+    origAspects.mTransfer = CA::Transfer::TransferLinear;
+    origAspects.mMatrixCoeffs = CA::MatrixCoeffs::MatrixBT709_5;
+
+    CA aspects;
+    aspects.mRange = CA::Range::RangeFull;
+    aspects.mPrimaries = CA::Primaries::PrimariesBT709_5;
+    aspects.mTransfer = CA::Transfer::TransferLinear;
+    aspects.mMatrixCoeffs = CA::MatrixCoeffs::MatrixBT709_5;
+
+    bool status = ColorUtils::checkIfAspectsChangedAndUnspecifyThem(aspects, origAspects);
+    ASSERT_FALSE(status) << "ColorAspects comparison check failed";
+
+    aspects.mRange = CA::Range::RangeLimited;
+    status = ColorUtils::checkIfAspectsChangedAndUnspecifyThem(aspects, origAspects);
+    ASSERT_TRUE(status) << "ColorAspects comparison check failed";
+    EXPECT_EQ(aspects.mRange, CA::Range::RangeUnspecified) << "range should have been unspecified";
+    aspects.mRange = CA::Range::RangeFull;
+
+    aspects.mTransfer = CA::Transfer::TransferSRGB;
+    status = ColorUtils::checkIfAspectsChangedAndUnspecifyThem(aspects, origAspects);
+    ASSERT_TRUE(status) << "ColorAspects comparison check failed";
+    EXPECT_EQ(aspects.mTransfer, CA::Transfer::TransferUnspecified)
+            << "transfer should have been unspecified";
+    aspects.mTransfer = CA::Transfer::TransferLinear;
+
+    aspects.mPrimaries = CA::Primaries::PrimariesBT2020;
+    status = ColorUtils::checkIfAspectsChangedAndUnspecifyThem(aspects, origAspects, true);
+    ASSERT_TRUE(status) << "ColorAspects comparison check failed";
+    EXPECT_EQ(aspects.mPrimaries, CA::Primaries::PrimariesUnspecified)
+            << "primaries should have been unspecified";
+    EXPECT_EQ(aspects.mMatrixCoeffs, CA::MatrixCoeffs::MatrixUnspecified)
+            << "matrixCoeffs should have been unspecified";
+
+    aspects.mMatrixCoeffs = CA::MatrixCoeffs::MatrixSMPTE240M;
+    status = ColorUtils::checkIfAspectsChangedAndUnspecifyThem(aspects, origAspects, true);
+    ASSERT_TRUE(status) << "ColorAspects comparison check failed";
+    EXPECT_EQ(aspects.mPrimaries, CA::Primaries::PrimariesUnspecified)
+            << "primaries should have been unspecified";
+    EXPECT_EQ(aspects.mMatrixCoeffs, CA::MatrixCoeffs::MatrixUnspecified)
+            << "matrixCoeffs should have been unspecified";
+}
+
+TEST(ColorUtilsUnitTest, ColorConfigFromFormatTest) {
+    int range = -1;
+    int standard = -1;
+    int transfer = -1;
+    sp<AMessage> format = new AMessage();
+    ASSERT_NE(format, nullptr) << "failed to create AMessage";
+    ColorUtils::getColorConfigFromFormat(format, &range, &standard, &transfer);
+    EXPECT_EQ(range | standard | transfer, 0) << "color config didn't default to 0";
+
+    format->setInt32(KEY_COLOR_RANGE, CA::Range::RangeFull);
+    format->setInt32(KEY_COLOR_STANDARD, CA::Standard::StandardBT709);
+    format->setInt32(KEY_COLOR_TRANSFER, CA::Transfer::TransferLinear);
+    ColorUtils::getColorConfigFromFormat(format, &range, &standard, &transfer);
+    EXPECT_EQ(range, CA::Range::RangeFull) << "range mismatch";
+    EXPECT_EQ(standard, CA::Standard::StandardBT709) << "standard mismatch";
+    EXPECT_EQ(transfer, CA::Transfer::TransferLinear) << "transfer mismatch";
+
+    range = standard = transfer = -1;
+    sp<AMessage> copyFormat = new AMessage();
+    ASSERT_NE(copyFormat, nullptr) << "failed to create AMessage";
+    ColorUtils::copyColorConfig(format, copyFormat);
+    bool status = copyFormat->findInt32(KEY_COLOR_RANGE, &range);
+    ASSERT_TRUE(status) << "ColorConfig range entry missing";
+    status = copyFormat->findInt32(KEY_COLOR_STANDARD, &standard);
+    ASSERT_TRUE(status) << "ColorConfig standard entry missing";
+    status = copyFormat->findInt32(KEY_COLOR_TRANSFER, &transfer);
+    ASSERT_TRUE(status) << "ColorConfig transfer entry missing";
+    EXPECT_EQ(range, CA::Range::RangeFull) << "range mismatch";
+    EXPECT_EQ(standard, CA::Standard::StandardBT709) << "standard mismatch";
+    EXPECT_EQ(transfer, CA::Transfer::TransferLinear) << "transfer mismatchd";
+
+    range = standard = transfer = -1;
+    ColorUtils::getColorConfigFromFormat(copyFormat, &range, &standard, &transfer);
+    EXPECT_EQ(range, CA::Range::RangeFull) << "range mismatch";
+    EXPECT_EQ(standard, CA::Standard::StandardBT709) << "standard mismatch";
+    EXPECT_EQ(transfer, CA::Transfer::TransferLinear) << "transfer mismatch";
+}
+
+TEST_P(ColorAspectsTest, FormatTest) {
+    CA aspects;
+    sp<AMessage> format = new AMessage();
+    ASSERT_NE(format, nullptr) << "failed to create AMessage";
+    ColorUtils::setColorAspectsIntoFormat(aspects, format, true);
+
+    CA returnedAspects;
+    ColorUtils::getColorAspectsFromFormat(format, returnedAspects);
+    EXPECT_EQ(returnedAspects.mRange, aspects.mRange) << "range mismatch";
+    EXPECT_EQ(returnedAspects.mPrimaries, aspects.mPrimaries) << "primaries mismatch";
+    EXPECT_EQ(returnedAspects.mTransfer, aspects.mTransfer) << "transfer mismatch";
+    EXPECT_EQ(returnedAspects.mMatrixCoeffs, aspects.mMatrixCoeffs) << "matrixCoeffs mismatch";
+
+    aspects.mRange = mRange;
+    aspects.mPrimaries = mPrimaries;
+    aspects.mTransfer = mTransfer;
+    aspects.mMatrixCoeffs = mMatrixCoeffs;
+    ColorUtils::setColorAspectsIntoFormat(aspects, format);
+
+    memset(&returnedAspects, 0, sizeof(returnedAspects));
+    ColorUtils::getColorAspectsFromFormat(format, returnedAspects);
+    EXPECT_EQ(returnedAspects.mRange, aspects.mRange) << "range mismatch";
+    EXPECT_EQ(returnedAspects.mPrimaries, aspects.mPrimaries) << "primaries mismatch";
+    EXPECT_EQ(returnedAspects.mTransfer, aspects.mTransfer) << "transfer mismatch";
+    EXPECT_EQ(returnedAspects.mMatrixCoeffs, aspects.mMatrixCoeffs) << "matrixCoeffs mismatch";
+}
+
+TEST(ColorUtilsUnitTest, HDRStaticInfoTest) {
+    sp<AMessage> format = new AMessage();
+    ASSERT_NE(format, nullptr) << "failed to create AMessage";
+
+    HDRStaticInfo returnedInfoHDR;
+    bool status = ColorUtils::getHDRStaticInfoFromFormat(format, &returnedInfoHDR);
+    ASSERT_FALSE(status) << "HDR info should be absent in empty format";
+
+    HDRStaticInfo infoHDR;
+    infoHDR.sType1.mMaxDisplayLuminance = kHDRInfoTestValue2;
+    infoHDR.sType1.mMinDisplayLuminance = kHDRInfoTestValue1;
+    infoHDR.sType1.mMaxContentLightLevel = kHDRInfoTestValue2;
+    infoHDR.sType1.mMaxFrameAverageLightLevel = kHDRInfoTestValue1;
+    infoHDR.sType1.mR.x = kHDRInfoTestValue1;
+    infoHDR.sType1.mR.y = kHDRInfoTestValue2;
+    infoHDR.sType1.mG.x = kHDRInfoTestValue1;
+    infoHDR.sType1.mG.y = kHDRInfoTestValue2;
+    infoHDR.sType1.mB.x = kHDRInfoTestValue1;
+    infoHDR.sType1.mB.y = kHDRInfoTestValue2;
+    infoHDR.sType1.mW.x = kHDRInfoTestValue1;
+    infoHDR.sType1.mW.y = kHDRInfoTestValue2;
+    ColorUtils::setHDRStaticInfoIntoFormat(infoHDR, format);
+
+    status = ColorUtils::getHDRStaticInfoFromFormat(format, &returnedInfoHDR);
+    ASSERT_TRUE(status) << "Failed to get HDR info from format";
+    ASSERT_EQ(0, memcmp(&returnedInfoHDR, &infoHDR, sizeof(infoHDR))) << " HDRStaticInfo mismatch";
+
+    AMediaFormat *mediaFormat = AMediaFormat_new();
+    ASSERT_NE(mediaFormat, nullptr) << "Unable to create AMediaFormat";
+    ColorUtils::setHDRStaticInfoIntoAMediaFormat(infoHDR, mediaFormat);
+    memset(&returnedInfoHDR, 0, sizeof(returnedInfoHDR));
+    status = ColorUtils::getHDRStaticInfoFromFormat(mediaFormat->mFormat, &returnedInfoHDR);
+    AMediaFormat_delete(mediaFormat);
+    ASSERT_TRUE(status) << "Failed to get HDR info from media format";
+    ASSERT_EQ(0, memcmp(&returnedInfoHDR, &infoHDR, sizeof(infoHDR))) << " HDRStaticInfo mismatch";
+}
+
+TEST(ColorUtilsUnitTest, SanityTest) {
+    CA::Primaries unmappedPrimaries = (CA::Primaries)(CA::Primaries::PrimariesOther + 1);
+    CA::MatrixCoeffs unmappedMatrixCoeffs = (CA::MatrixCoeffs)(CA::MatrixOther + 1);
+    int32_t colorStandard =
+            ColorUtils::wrapColorAspectsIntoColorStandard(unmappedPrimaries, CA::MatrixUnspecified);
+    EXPECT_EQ(colorStandard, ColorUtils::kColorStandardUnspecified)
+            << "Standard unspecified expected";
+    colorStandard =
+            ColorUtils::wrapColorAspectsIntoColorStandard(CA::PrimariesOther, unmappedMatrixCoeffs);
+    EXPECT_EQ(colorStandard, ColorUtils::kColorStandardUnspecified)
+            << "Standard unspecified expected";
+    colorStandard = ColorUtils::wrapColorAspectsIntoColorStandard(CA::PrimariesBT601_6_525,
+                                                                  CA::MatrixBT2020);
+    EXPECT_GE(colorStandard, ColorUtils::kColorStandardExtendedStart)
+            << "Standard greater than extended start expected";
+    unmappedPrimaries = (CA::Primaries)(CA::Primaries::PrimariesBT2020 + 1);
+    unmappedMatrixCoeffs = (CA::MatrixCoeffs)(CA::MatrixBT2020Constant + 1);
+    colorStandard =
+            ColorUtils::wrapColorAspectsIntoColorStandard(unmappedPrimaries, unmappedMatrixCoeffs);
+    EXPECT_GE(colorStandard, ColorUtils::kColorStandardExtendedStart)
+            << "Standard greater than extended start expected";
+
+    CA aspects;
+    int32_t colorRange = -1;
+    colorStandard = -1;
+    int32_t colorTransfer = -1;
+    aspects.mPrimaries = (CA::Primaries)(CA::Primaries::PrimariesOther + 1);
+    status_t status = ColorUtils::convertCodecColorAspectsToPlatformAspects(
+            aspects, &colorRange, &colorStandard, &colorTransfer);
+    EXPECT_NE(status, OK) << "invalid colorAspects value accepted";
+
+    int32_t colorPrimaries = -1;
+    colorTransfer = -1;
+    int32_t colorMatrixCoeffs = -1;
+    bool fullRange = false;
+    aspects.mPrimaries = CA::PrimariesOther;
+    aspects.mTransfer = CA::TransferOther;
+    aspects.mMatrixCoeffs = CA::MatrixOther;
+    ColorUtils::convertCodecColorAspectsToIsoAspects(aspects, &colorPrimaries, &colorTransfer,
+                                                     &colorMatrixCoeffs, &fullRange);
+    CA returnedAspects;
+    ColorUtils::convertIsoColorAspectsToCodecAspects(colorPrimaries, colorTransfer,
+                                                     colorMatrixCoeffs, fullRange, returnedAspects);
+    EXPECT_EQ(returnedAspects.mPrimaries, CA::PrimariesUnspecified)
+            << "expected unspecified Primaries";
+    EXPECT_EQ(returnedAspects.mTransfer, CA::TransferUnspecified)
+            << "expected unspecified Transfer";
+    EXPECT_EQ(returnedAspects.mMatrixCoeffs, CA::MatrixUnspecified)
+            << "expected unspecified MatrixCoeffs";
+
+    // invalid values, other value equals 0xFF
+    colorPrimaries = CA::PrimariesOther;
+    colorTransfer = CA::TransferOther;
+    colorMatrixCoeffs = CA::MatrixOther;
+    fullRange = false;
+    memset(&returnedAspects, 0, sizeof(returnedAspects));
+    ColorUtils::convertIsoColorAspectsToCodecAspects(colorPrimaries, colorTransfer,
+                                                     colorMatrixCoeffs, fullRange, returnedAspects);
+    EXPECT_EQ(returnedAspects.mPrimaries, CA::PrimariesUnspecified)
+            << "expected unspecified Primaries";
+    EXPECT_EQ(returnedAspects.mTransfer, CA::TransferUnspecified)
+            << "expected unspecified Transfer";
+    EXPECT_EQ(returnedAspects.mMatrixCoeffs, CA::MatrixUnspecified)
+            << "expected unspecified MatrixCoeffs";
+
+    CA::Primaries primaries = CA::PrimariesUnspecified;
+    CA::MatrixCoeffs matrixCoeffs = CA::MatrixUnspecified;
+    status = ColorUtils::unwrapColorAspectsFromColorStandard(ColorUtils::kColorStandardVendorStart,
+                                                             &primaries, &matrixCoeffs);
+    EXPECT_EQ(status, OK) << "unwrapping aspects from color standard failed";
+
+    primaries = CA::PrimariesUnspecified;
+    matrixCoeffs = CA::MatrixUnspecified;
+    status = ColorUtils::unwrapColorAspectsFromColorStandard(
+            ColorUtils::kColorStandardVendorStart * 4, &primaries, &matrixCoeffs);
+    EXPECT_NE(status, OK) << "unwrapping aspects from color standard failed";
+
+    colorRange = ColorUtils::wrapColorAspectsIntoColorRange((CA::Range)(CA::RangeOther + 1));
+    EXPECT_EQ(colorRange, ColorUtils::kColorRangeUnspecified) << "expected unspecified color range";
+
+    CA::Range range;
+    status = ColorUtils::unwrapColorAspectsFromColorRange(
+            ColorUtils::kColorRangeVendorStart + CA::RangeOther + 1, &range);
+    EXPECT_NE(status, OK) << "invalid range value accepted";
+    EXPECT_EQ(range, CA::RangeOther) << "returned unexpected range value";
+
+    colorTransfer =
+            ColorUtils::wrapColorAspectsIntoColorTransfer((CA::Transfer)(CA::TransferOther + 1));
+    EXPECT_EQ(colorTransfer, ColorUtils::kColorTransferUnspecified)
+            << "expected unspecified color transfer";
+
+    CA::Transfer transfer;
+    status = ColorUtils::unwrapColorAspectsFromColorTransfer(
+            ColorUtils::kColorTransferVendorStart + CA::TransferOther + 1, &transfer);
+    EXPECT_NE(status, OK) << "invalid transfer value accepted";
+    EXPECT_EQ(transfer, CA::TransferOther) << "expected other color transfer";
+}
+
+TEST(ColorUtilsUnitTest, HDRInfoSanityTest) {
+    HDRStaticInfo hdrInfo;
+    sp<AMessage> format = new AMessage();
+    ASSERT_NE(format, nullptr) << "failed to create AMessage";
+
+    bool boolStatus = ColorUtils::getHDRStaticInfoFromFormat(format, &hdrInfo);
+    EXPECT_FALSE(boolStatus) << "HDRStaticInfo should not be present";
+
+    sp<ABuffer> invalidSizeHDRInfoBuffer = new ABuffer(kHDRBufferSize - 1);
+    ASSERT_NE(invalidSizeHDRInfoBuffer, nullptr) << "failed to create ABuffer";
+    format->setBuffer(KEY_HDR_STATIC_INFO, invalidSizeHDRInfoBuffer);
+    memset(&hdrInfo, 0, sizeof(hdrInfo));
+    boolStatus = ColorUtils::getHDRStaticInfoFromFormat(format, &hdrInfo);
+    EXPECT_FALSE(boolStatus) << "incorrect HDRStaticInfo buffer accepted";
+
+    sp<ABuffer> invalidHDRInfoBuffer = new ABuffer(kHDRBufferSize);
+    ASSERT_NE(invalidHDRInfoBuffer, nullptr) << "failed to create ABuffer";
+    uint8_t *data = invalidHDRInfoBuffer->data();
+    *data = HDRStaticInfo::kType1 + 1;
+    format->setBuffer(KEY_HDR_STATIC_INFO, invalidHDRInfoBuffer);
+    memset(&hdrInfo, 0, sizeof(hdrInfo));
+    boolStatus = ColorUtils::getHDRStaticInfoFromFormat(format, &hdrInfo);
+    EXPECT_FALSE(boolStatus) << "incorrect HDRStaticInfo buffer accepted";
+
+    CA aspects;
+    format->setInt32(KEY_COLOR_RANGE, ColorUtils::kColorRangeVendorStart + CA::RangeOther + 1);
+    format->setInt32(KEY_COLOR_STANDARD, CA::Standard::StandardBT709);
+    format->setInt32(KEY_COLOR_TRANSFER, CA::Transfer::TransferLinear);
+    ColorUtils::getColorAspectsFromFormat(format, aspects);
+    EXPECT_EQ(aspects.mRange, CA::RangeOther) << "unexpected range";
+}
+
+TEST(ColorUtilsUnitTest, DataSpaceSanityTest) {
+    CA aspects;
+    aspects.mRange = CA::RangeUnspecified;
+    aspects.mPrimaries = CA::PrimariesUnspecified;
+    aspects.mMatrixCoeffs = CA::MatrixUnspecified;
+    aspects.mTransfer = CA::TransferUnspecified;
+    android_dataspace dataSpace = ColorUtils::getDataSpaceForColorAspects(aspects, true);
+    EXPECT_EQ(dataSpace, 0) << "expected invalid dataspace";
+    aspects.mPrimaries = CA::PrimariesUnspecified;
+    aspects.mMatrixCoeffs = CA::MatrixBT2020Constant;
+    dataSpace = ColorUtils::getDataSpaceForColorAspects(aspects, true);
+    EXPECT_NE(dataSpace, 0) << "unexpected value";
+}
+
+INSTANTIATE_TEST_SUITE_P(ColorUtilsUnitTest, ColorRangeTest,
+                         ::testing::Values(
+                                 // ColorRange
+                                 CA::Range::RangeLimited, CA::Range::RangeFull,
+                                 CA::Range::RangeUnspecified, CA::Range::RangeOther));
+
+INSTANTIATE_TEST_SUITE_P(ColorUtilsUnitTest, ColorTransferTest,
+                         ::testing::Values(
+                                 // ColorTransfer
+                                 CA::Transfer::TransferUnspecified, CA::Transfer::TransferLinear,
+                                 CA::Transfer::TransferSRGB, CA::Transfer::TransferSMPTE170M,
+                                 CA::Transfer::TransferGamma22, CA::Transfer::TransferGamma28,
+                                 CA::Transfer::TransferST2084, CA::Transfer::TransferHLG,
+                                 CA::Transfer::TransferSMPTE240M, CA::Transfer::TransferXvYCC,
+                                 CA::Transfer::TransferBT1361, CA::Transfer::TransferST428,
+                                 CA::Transfer::TransferOther));
+
+INSTANTIATE_TEST_SUITE_P(
+        ColorUtilsUnitTest, ColorStandardTest,
+        ::testing::Values(
+                // Primaries, MatrixCoeffs
+                std::make_pair(CA::Primaries::PrimariesUnspecified,
+                               CA::MatrixCoeffs::MatrixUnspecified),
+                std::make_pair(CA::Primaries::PrimariesBT709_5,
+                               CA::MatrixCoeffs::MatrixBT709_5),
+                std::make_pair(CA::Primaries::PrimariesBT601_6_625,
+                               CA::MatrixCoeffs::MatrixBT601_6),
+                std::make_pair(CA::Primaries::PrimariesBT601_6_625,
+                               CA::MatrixCoeffs::MatrixBT709_5),
+                std::make_pair(CA::Primaries::PrimariesBT601_6_525,
+                               CA::MatrixCoeffs::MatrixBT601_6),
+                std::make_pair(CA::Primaries::PrimariesBT601_6_525,
+                               CA::MatrixCoeffs::MatrixSMPTE240M),
+                std::make_pair(CA::Primaries::PrimariesBT2020,
+                               CA::MatrixCoeffs::MatrixBT2020),
+                std::make_pair(CA::Primaries::PrimariesBT2020,
+                               CA::MatrixCoeffs::MatrixBT2020Constant),
+                std::make_pair(CA::Primaries::PrimariesBT470_6M,
+                               CA::MatrixCoeffs::MatrixBT470_6M),
+                std::make_pair(CA::Primaries::PrimariesGenericFilm,
+                               CA::MatrixCoeffs::MatrixBT2020)));
+
+INSTANTIATE_TEST_SUITE_P(
+        ColorUtilsUnitTest, ColorAspectsTest,
+        ::testing::Values(
+                // Primaries, ColorTransfer, MatrixCoeffs, ColorRange, ColorStandard
+                std::make_tuple(CA::Primaries::PrimariesUnspecified,
+                                CA::Transfer::TransferUnspecified,
+                                CA::MatrixCoeffs::MatrixUnspecified, CA::Range::RangeFull,
+                                CA::Standard::StandardUnspecified),
+                std::make_tuple(CA::Primaries::PrimariesBT709_5, CA::Transfer::TransferLinear,
+                                CA::MatrixCoeffs::MatrixBT709_5, CA::Range::RangeFull,
+                                CA::Standard::StandardBT709),
+                std::make_tuple(CA::Primaries::PrimariesBT601_6_625, CA::Transfer::TransferSRGB,
+                                CA::MatrixCoeffs::MatrixBT601_6, CA::Range::RangeFull,
+                                CA::Standard::StandardUnspecified),
+                std::make_tuple(CA::Primaries::PrimariesBT601_6_625,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT709_5,
+                                CA::Range::RangeFull, CA::Standard::StandardUnspecified),
+                std::make_tuple(CA::Primaries::PrimariesBT601_6_525, CA::Transfer::TransferGamma22,
+                                CA::MatrixCoeffs::MatrixBT601_6, CA::Range::RangeFull,
+                                CA::Standard::StandardUnspecified),
+                std::make_tuple(CA::Primaries::PrimariesBT601_6_525, CA::Transfer::TransferGamma28,
+                                CA::MatrixCoeffs::MatrixSMPTE240M, CA::Range::RangeFull,
+                                CA::Standard::StandardBT470M),
+                std::make_tuple(CA::Primaries::PrimariesBT2020, CA::Transfer::TransferST2084,
+                                CA::MatrixCoeffs::MatrixBT2020, CA::Range::RangeFull,
+                                CA::Standard::StandardBT601_525),
+                std::make_tuple(CA::Primaries::PrimariesBT2020, CA::Transfer::TransferHLG,
+                                CA::MatrixCoeffs::MatrixBT2020Constant, CA::Range::RangeFull,
+                                CA::Standard::StandardBT601_525),
+                std::make_tuple(CA::Primaries::PrimariesBT470_6M, CA::Transfer::TransferLinear,
+                                CA::MatrixCoeffs::MatrixBT470_6M, CA::Range::RangeFull,
+                                CA::Standard::StandardUnspecified),
+                std::make_tuple(CA::Primaries::PrimariesGenericFilm, CA::Transfer::TransferLinear,
+                                CA::MatrixCoeffs::MatrixBT2020, CA::Range::RangeFull,
+                                CA::Standard::StandardBT601_625)));
+
+INSTANTIATE_TEST_SUITE_P(
+        ColorUtilsUnitTest, IsoToPlatformAspectsTest,
+        ::testing::Values(
+                // Primaries, Transfer, MatrixCoeffs, Standard, Transfer
+                std::make_tuple(CA::PrimariesUnspecified, CA::TransferUnspecified,
+                                CA::MatrixUnspecified, ColorUtils::kColorStandardUnspecified,
+                                ColorUtils::kColorTransferUnspecified),
+                std::make_tuple(CA::PrimariesBT709_5, CA::TransferLinear, CA::MatrixBT709_5,
+                                ColorUtils::kColorStandardBT709, ColorUtils::kColorTransferLinear),
+                std::make_tuple(CA::PrimariesBT601_6_625, CA::TransferSRGB, CA::MatrixBT601_6,
+                                ColorUtils::kColorStandardBT601_625,
+                                ColorUtils::kColorTransferSRGB),
+                std::make_tuple(CA::PrimariesBT601_6_625, CA::TransferSMPTE170M, CA::MatrixBT709_5,
+                                ColorUtils::kColorStandardBT601_625_Unadjusted,
+                                ColorUtils::kColorTransferSMPTE_170M),
+                std::make_tuple(CA::PrimariesBT601_6_525, CA::TransferGamma22, CA::MatrixBT601_6,
+                                ColorUtils::kColorStandardBT601_525,
+                                ColorUtils::kColorTransferGamma22),
+                std::make_tuple(CA::PrimariesBT601_6_525, CA::TransferGamma28, CA::MatrixSMPTE240M,
+                                ColorUtils::kColorStandardBT601_525_Unadjusted,
+                                ColorUtils::kColorTransferGamma28),
+                std::make_tuple(CA::PrimariesBT2020, CA::TransferST2084, CA::MatrixBT2020,
+                                ColorUtils::kColorStandardBT2020, ColorUtils::kColorTransferST2084),
+                std::make_tuple(CA::PrimariesBT2020, CA::TransferHLG, CA::MatrixBT2020Constant,
+                                ColorUtils::kColorStandardBT2020Constant,
+                                ColorUtils::kColorTransferHLG),
+                std::make_tuple(CA::PrimariesBT470_6M, CA::TransferUnspecified, CA::MatrixBT470_6M,
+                                ColorUtils::kColorStandardBT470M,
+                                ColorUtils::kColorTransferUnspecified),
+                std::make_tuple(CA::PrimariesGenericFilm, CA::TransferLinear, CA::MatrixBT2020,
+                                ColorUtils::kColorStandardFilm, ColorUtils::kColorTransferLinear)));
+
+INSTANTIATE_TEST_SUITE_P(
+        ColorUtilsUnitTest, DefaultColorAspectsTest,
+        ::testing::Values(
+                // Width, Height, Primaries, MatrixCoeffs
+                std::make_tuple(3840, 3840, CA::PrimariesBT2020, CA::MatrixBT2020),
+                std::make_tuple(720, 576, CA::PrimariesBT601_6_625, CA::MatrixBT601_6),
+                std::make_tuple(480, 360, CA::PrimariesBT601_6_525, CA::MatrixBT601_6),
+                std::make_tuple(480, 1920, CA::PrimariesBT709_5, CA::MatrixBT709_5)));
+
+INSTANTIATE_TEST_SUITE_P(
+        ColorUtilsUnitTest, DataSpaceTest,
+        ::testing::Values(
+                // ColorRange, Primaries, ColorTransfer, MatrixCoeffs, v0_android_dataspace,
+                // android_dataspace
+                std::make_tuple(CA::Range::RangeFull, CA::Primaries::PrimariesBT709_5,
+                                CA::Transfer::TransferSRGB, CA::MatrixCoeffs::MatrixBT709_5,
+                                HAL_DATASPACE_V0_SRGB, HAL_DATASPACE_SRGB),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT709_5,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT709_5,
+                                HAL_DATASPACE_V0_BT709, HAL_DATASPACE_BT709),
+                std::make_tuple(CA::Range::RangeFull, CA::Primaries::PrimariesBT709_5,
+                                CA::Transfer::TransferLinear, CA::MatrixCoeffs::MatrixBT709_5,
+                                HAL_DATASPACE_V0_SRGB_LINEAR, HAL_DATASPACE_SRGB_LINEAR),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT601_6_525,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT601_6,
+                                HAL_DATASPACE_V0_BT601_525, HAL_DATASPACE_BT601_525),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT601_6_625,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT601_6,
+                                HAL_DATASPACE_V0_BT601_625, HAL_DATASPACE_BT601_625),
+                std::make_tuple(CA::Range::RangeFull, CA::Primaries::PrimariesBT601_6_625,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT601_6,
+                                HAL_DATASPACE_V0_JFIF, HAL_DATASPACE_JFIF),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT709_5,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT470_6M,
+                                HAL_DATASPACE_V0_BT601_625, HAL_DATASPACE_BT601_625),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT709_5,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT601_6,
+                                HAL_DATASPACE_V0_BT601_625, HAL_DATASPACE_BT601_625),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT709_5,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixSMPTE240M,
+                                HAL_DATASPACE_V0_BT709, HAL_DATASPACE_BT709),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT709_5,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT2020,
+                                HAL_DATASPACE_V0_BT709, HAL_DATASPACE_BT709),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT709_5,
+                                CA::Transfer::TransferSMPTE170M,
+                                CA::MatrixCoeffs::MatrixBT2020Constant, HAL_DATASPACE_V0_BT601_525,
+                                HAL_DATASPACE_BT601_525),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT601_6_625,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT470_6M,
+                                HAL_DATASPACE_V0_BT601_625, HAL_DATASPACE_BT601_625),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT601_6_625,
+                                CA::Transfer::TransferSMPTE170M,
+                                CA::MatrixCoeffs::MatrixBT2020Constant, HAL_DATASPACE_V0_BT601_525,
+                                HAL_DATASPACE_BT601_525),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT601_6_525,
+                                CA::Transfer::TransferSMPTE170M, CA::MatrixCoeffs::MatrixBT470_6M,
+                                HAL_DATASPACE_V0_BT601_525, HAL_DATASPACE_BT601_525),
+                std::make_tuple(CA::Range::RangeLimited, CA::Primaries::PrimariesBT601_6_525,
+                                CA::Transfer::TransferSMPTE170M,
+                                CA::MatrixCoeffs::MatrixBT2020Constant, HAL_DATASPACE_V0_BT601_525,
+                                HAL_DATASPACE_BT601_525)));
diff --git a/media/libstagefright/http/Android.bp b/media/libstagefright/http/Android.bp
index 8655caf..f4d6d99 100644
--- a/media/libstagefright/http/Android.bp
+++ b/media/libstagefright/http/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_shared {
     name: "libstagefright_http_support",
 
diff --git a/media/libstagefright/httplive/Android.bp b/media/libstagefright/httplive/Android.bp
index 12e7ca6..0b0acbf 100644
--- a/media/libstagefright/httplive/Android.bp
+++ b/media/libstagefright/httplive/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_httplive_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_httplive_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library {
     name: "libstagefright_httplive",
 
diff --git a/media/libstagefright/id3/Android.bp b/media/libstagefright/id3/Android.bp
index db37fe9..3f5ba47 100644
--- a/media/libstagefright/id3/Android.bp
+++ b/media/libstagefright/id3/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_id3_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_id3_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_static {
     name: "libstagefright_id3",
     min_sdk_version: "29",
@@ -5,7 +24,9 @@
     srcs: ["ID3.cpp"],
 
     header_libs: [
-        "libmedia_headers",
+        "libmedia_datasource_headers",
+        "libstagefright_foundation_headers",
+        "libstagefright_headers",
         "media_ndk_headers",
     ],
 
@@ -19,6 +40,12 @@
         ],
         cfi: true,
     },
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
 
 //###############################################################################
diff --git a/media/libstagefright/id3/test/Android.bp b/media/libstagefright/id3/test/Android.bp
index 9d26eec..3cd8565 100644
--- a/media/libstagefright/id3/test/Android.bp
+++ b/media/libstagefright/id3/test/Android.bp
@@ -14,6 +14,17 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_id3_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_id3_license",
+    ],
+}
+
 cc_test {
     name: "ID3Test",
     gtest: true,
diff --git a/media/libstagefright/id3/test/AndroidTest.xml b/media/libstagefright/id3/test/AndroidTest.xml
index 6c6697d..d6ea470 100644
--- a/media/libstagefright/id3/test/AndroidTest.xml
+++ b/media/libstagefright/id3/test/AndroidTest.xml
@@ -19,7 +19,7 @@
         <option name="cleanup" value="true" />
         <option name="push" value="ID3Test->/data/local/tmp/ID3Test" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/id3/test/ID3Test.zip?unzip=true"
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/id3/test/ID3Test-1.1.zip?unzip=true"
             value="/data/local/tmp/ID3TestRes/" />
     </target_preparer>
 
diff --git a/media/libstagefright/id3/test/ID3Test.cpp b/media/libstagefright/id3/test/ID3Test.cpp
index cd5cd9e..8db83cb 100644
--- a/media/libstagefright/id3/test/ID3Test.cpp
+++ b/media/libstagefright/id3/test/ID3Test.cpp
@@ -51,7 +51,7 @@
     while (!it.done()) {
         String8 id;
         it.getID(&id);
-        ASSERT_GT(id.length(), 0) << "No ID tag found! \n";
+        ASSERT_GT(id.length(), 0) << "Found an ID3 tag of 0 size";
         ALOGV("Found ID tag: %s\n", String8(id).c_str());
         it.next();
     }
@@ -66,8 +66,8 @@
     DataSourceHelper helper(file->wrap());
     ID3 tag(&helper);
     ASSERT_TRUE(tag.isValid()) << "No valid ID3 tag found for " << path.c_str() << "\n";
-    ASSERT_TRUE(tag.version() >= versionNumber)
-            << "Expected version: " << tag.version() << " Found version: " << versionNumber;
+    ASSERT_EQ(tag.version(), versionNumber)
+            << "Found version: " << tag.version() << " Expected version: " << versionNumber;
 }
 
 TEST_P(ID3textTagTest, TextTagTest) {
@@ -81,17 +81,34 @@
     ASSERT_TRUE(tag.isValid()) << "No valid ID3 tag found for " << path.c_str() << "\n";
     int countTextFrames = 0;
     ID3::Iterator it(tag, nullptr);
-    while (!it.done()) {
-        String8 id;
-        it.getID(&id);
-        ASSERT_GT(id.length(), 0);
-        if (id[0] == 'T') {
-            String8 text;
-            countTextFrames++;
-            it.getString(&text);
-            ALOGV("Found text frame %s : %s \n", id.string(), text.string());
+    if (tag.version() != ID3::ID3_V1 && tag.version() != ID3::ID3_V1_1) {
+        while (!it.done()) {
+            String8 id;
+            it.getID(&id);
+            ASSERT_GT(id.length(), 0) << "Found an ID3 tag of 0 size";
+            if (id[0] == 'T') {
+                String8 text;
+                countTextFrames++;
+                it.getString(&text);
+                ALOGV("Found text frame %s : %s \n", id.string(), text.string());
+            }
+            it.next();
         }
-        it.next();
+    } else {
+        while (!it.done()) {
+            String8 id;
+            String8 text;
+            it.getID(&id);
+            ASSERT_GT(id.length(), 0) << "Found an ID3 tag of 0 size";
+            it.getString(&text);
+            // if the tag has a value
+            if (strcmp(text.string(), "")) {
+                countTextFrames++;
+                ALOGV("ID: %s\n", id.c_str());
+                ALOGV("Text string: %s\n", text.string());
+            }
+            it.next();
+        }
     }
     ASSERT_EQ(countTextFrames, numTextFrames)
             << "Expected " << numTextFrames << " text frames, found " << countTextFrames;
@@ -114,7 +131,7 @@
         if (data) {
             ALOGV("Found album art: size = %zu mime = %s \n", dataSize, mime.string());
         }
-        ASSERT_NE(data, nullptr) << "Expected album art, found none!" << path;
+        ASSERT_NE(data, nullptr) << "Expected album art, found none! " << path;
     } else {
         ASSERT_EQ(data, nullptr) << "Found album art when expected none!";
     }
@@ -137,7 +154,7 @@
     while (!it.done()) {
         String8 id;
         it.getID(&id);
-        ASSERT_GT(id.length(), 0);
+        ASSERT_GT(id.length(), 0) << "Found an ID3 tag of 0 size";
         // Check if the tag is an "APIC/PIC" tag.
         if (String8(id) == "APIC" || String8(id) == "PIC") {
             count++;
@@ -150,7 +167,7 @@
                 hexdump(data, dataSize > 128 ? 128 : dataSize);
 #endif
             }
-            ASSERT_NE(data, nullptr) << "Expected album art, found none!" << path;
+            ASSERT_NE(data, nullptr) << "Expected album art, found none! " << path;
         }
         it.next();
     }
@@ -159,56 +176,67 @@
 }
 
 INSTANTIATE_TEST_SUITE_P(id3TestAll, ID3tagTest,
-                         ::testing::Values("bbb_44100hz_2ch_128kbps_mp3_30sec.mp3",
-                                           "bbb_44100hz_2ch_128kbps_mp3_30sec_1_image.mp3",
-                                           "bbb_44100hz_2ch_128kbps_mp3_30sec_2_image.mp3",
-                                           "bbb_44100hz_2ch_128kbps_mp3_5mins.mp3",
-                                           "bbb_44100hz_2ch_128kbps_mp3_5mins_1_image.mp3",
-                                           "bbb_44100hz_2ch_128kbps_mp3_5mins_2_image.mp3",
-                                           "bbb_44100hz_2ch_128kbps_mp3_5mins_largeSize.mp3",
-                                           "bbb_44100hz_2ch_128kbps_mp3_30sec_moreTextFrames.mp3"));
+                         ::testing::Values("bbb_1sec_v23.mp3",
+                                           "bbb_1sec_1_image.mp3",
+                                           "bbb_1sec_2_image.mp3",
+                                           "bbb_2sec_v24.mp3",
+                                           "bbb_2sec_1_image.mp3",
+                                           "bbb_2sec_2_image.mp3",
+                                           "bbb_2sec_largeSize.mp3",
+                                           "bbb_1sec_v23_3tags.mp3",
+                                           "bbb_1sec_v1_5tags.mp3",
+                                           "bbb_2sec_v24_unsynchronizedOneFrame.mp3",
+                                           "bbb_2sec_v24_unsynchronizedAllFrames.mp3"));
 
 INSTANTIATE_TEST_SUITE_P(
         id3TestAll, ID3versionTest,
-        ::testing::Values(make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec.mp3", 4),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_1_image.mp3", 4),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_2_image.mp3", 4),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins.mp3", 4),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_1_image.mp3", 4),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_2_image.mp3", 4),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_largeSize.mp3", 4),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_moreTextFrames.mp3", 4)));
+        ::testing::Values(make_pair("bbb_1sec_v23.mp3", ID3::ID3_V2_3),
+                          make_pair("bbb_1sec_1_image.mp3", ID3::ID3_V2_3),
+                          make_pair("bbb_1sec_2_image.mp3", ID3::ID3_V2_3),
+                          make_pair("bbb_2sec_v24.mp3", ID3::ID3_V2_4),
+                          make_pair("bbb_2sec_1_image.mp3", ID3::ID3_V2_4),
+                          make_pair("bbb_2sec_2_image.mp3", ID3::ID3_V2_4),
+                          make_pair("bbb_2sec_largeSize.mp3", ID3::ID3_V2_4),
+                          make_pair("bbb_1sec_v23_3tags.mp3", ID3::ID3_V2_3),
+                          make_pair("bbb_1sec_v1_5tags.mp3", ID3::ID3_V1_1),
+                          make_pair("bbb_1sec_v1_3tags.mp3", ID3::ID3_V1_1),
+                          make_pair("bbb_2sec_v24_unsynchronizedOneFrame.mp3", ID3::ID3_V2_4),
+                          make_pair("bbb_2sec_v24_unsynchronizedAllFrames.mp3", ID3::ID3_V2_4)));
 
 INSTANTIATE_TEST_SUITE_P(
         id3TestAll, ID3textTagTest,
-        ::testing::Values(make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec.mp3", 1),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_1_image.mp3", 1),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_2_image.mp3", 1),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins.mp3", 1),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_1_image.mp3", 1),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_2_image.mp3", 1),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_largeSize.mp3", 1),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_moreTextFrames.mp3", 5)));
+        ::testing::Values(
+                make_pair("bbb_1sec_v23.mp3", 1),
+                make_pair("bbb_1sec_1_image.mp3", 1),
+                make_pair("bbb_1sec_2_image.mp3", 1),
+                make_pair("bbb_2sec_v24.mp3", 1),
+                make_pair("bbb_2sec_1_image.mp3", 1),
+                make_pair("bbb_2sec_2_image.mp3", 1),
+                make_pair("bbb_2sec_largeSize.mp3", 1),
+                make_pair("bbb_1sec_v23_3tags.mp3", 3),
+                make_pair("bbb_1sec_v1_5tags.mp3", 5),
+                make_pair("bbb_1sec_v1_3tags.mp3", 3),
+                make_pair("bbb_2sec_v24_unsynchronizedOneFrame.mp3", 3),
+                make_pair("bbb_2sec_v24_unsynchronizedAllFrames.mp3", 3)));
 
-INSTANTIATE_TEST_SUITE_P(
-        id3TestAll, ID3albumArtTest,
-        ::testing::Values(make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec.mp3", false),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_1_image.mp3", true),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_2_image.mp3", true),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins.mp3", false),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_1_image.mp3", true),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_2_image.mp3", true),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_largeSize.mp3", true)));
+INSTANTIATE_TEST_SUITE_P(id3TestAll, ID3albumArtTest,
+                         ::testing::Values(make_pair("bbb_1sec_v23.mp3", false),
+                                           make_pair("bbb_1sec_1_image.mp3", true),
+                                           make_pair("bbb_1sec_2_image.mp3", true),
+                                           make_pair("bbb_2sec_v24.mp3", false),
+                                           make_pair("bbb_2sec_1_image.mp3", true),
+                                           make_pair("bbb_2sec_2_image.mp3", true),
+                                           make_pair("bbb_2sec_largeSize.mp3", true),
+                                           make_pair("bbb_1sec_v1_5tags.mp3", false)));
 
-INSTANTIATE_TEST_SUITE_P(
-        id3TestAll, ID3multiAlbumArtTest,
-        ::testing::Values(make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec.mp3", 0),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins.mp3", 0),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_1_image.mp3", 1),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_1_image.mp3", 1),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec_2_image.mp3", 2),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_2_image.mp3", 2),
-                          make_pair("bbb_44100hz_2ch_128kbps_mp3_5mins_largeSize.mp3", 3)));
+INSTANTIATE_TEST_SUITE_P(id3TestAll, ID3multiAlbumArtTest,
+                         ::testing::Values(make_pair("bbb_1sec_v23.mp3", 0),
+                                           make_pair("bbb_2sec_v24.mp3", 0),
+                                           make_pair("bbb_1sec_1_image.mp3", 1),
+                                           make_pair("bbb_2sec_1_image.mp3", 1),
+                                           make_pair("bbb_1sec_2_image.mp3", 2),
+                                           make_pair("bbb_2sec_2_image.mp3", 2),
+                                           make_pair("bbb_2sec_largeSize.mp3", 3)));
 
 int main(int argc, char **argv) {
     gEnv = new ID3TestEnvironment();
diff --git a/media/libstagefright/include/HevcUtils.h b/media/libstagefright/include/HevcUtils.h
index 0f59631..335de2f 100644
--- a/media/libstagefright/include/HevcUtils.h
+++ b/media/libstagefright/include/HevcUtils.h
@@ -90,6 +90,8 @@
     // Note that this method does not write the start code.
     bool write(size_t index, uint8_t* dest, size_t size);
     status_t makeHvcc(uint8_t *hvcc, size_t *hvccSize, size_t nalSizeLength);
+    void FindHEVCDimensions(
+            const sp<ABuffer> &SpsBuffer, int32_t *width, int32_t *height);
 
     Info getInfo() const { return mInfo; }
 
diff --git a/media/libstagefright/include/media/stagefright/ACodec.h b/media/libstagefright/include/media/stagefright/ACodec.h
index 83e92b9..4c97b4d 100644
--- a/media/libstagefright/include/media/stagefright/ACodec.h
+++ b/media/libstagefright/include/media/stagefright/ACodec.h
@@ -147,6 +147,7 @@
         kWhatReleaseCodecInstance    = 'relC',
         kWhatForceStateTransition    = 'fstt',
         kWhatCheckIfStuck            = 'Cstk',
+        kWhatSubmitExtraOutputMetadataBuffer = 'sbxo',
     };
 
     enum {
@@ -272,6 +273,8 @@
     bool mShutdownInProgress;
     bool mExplicitShutdown;
     bool mIsLegacyVP9Decoder;
+    bool mIsStreamCorruptFree;
+    bool mIsLowLatency;
 
     // If "mKeepComponentAllocated" we only transition back to Loaded state
     // and do not release the component instance.
@@ -499,6 +502,7 @@
     status_t setupAMRCodec(bool encoder, bool isWAMR, int32_t bitRate);
     status_t setupG711Codec(bool encoder, int32_t sampleRate, int32_t numChannels);
 
+    status_t setupOpusCodec(bool encoder, int32_t sampleRate, int32_t numChannels);
     status_t setupFlacCodec(
             bool encoder, int32_t numChannels, int32_t sampleRate, int32_t compressionLevel,
             AudioEncoding encoding);
diff --git a/media/libstagefright/include/media/stagefright/MediaCodec.h b/media/libstagefright/include/media/stagefright/MediaCodec.h
index 7614ba5..a28d479 100644
--- a/media/libstagefright/include/media/stagefright/MediaCodec.h
+++ b/media/libstagefright/include/media/stagefright/MediaCodec.h
@@ -81,6 +81,13 @@
         BUFFER_FLAG_MUXER_DATA    = 16,
     };
 
+    enum CVODegree {
+        CVO_DEGREE_0   = 0,
+        CVO_DEGREE_90  = 90,
+        CVO_DEGREE_180 = 180,
+        CVO_DEGREE_270 = 270,
+    };
+
     enum {
         CB_INPUT_AVAILABLE = 1,
         CB_OUTPUT_AVAILABLE = 2,
@@ -418,6 +425,10 @@
 
     sp<ICrypto> mCrypto;
 
+    int32_t mTunneledInputWidth;
+    int32_t mTunneledInputHeight;
+    bool mTunneled;
+
     sp<IDescrambler> mDescrambler;
 
     List<sp<ABuffer> > mCSD;
diff --git a/media/libstagefright/include/media/stagefright/MediaCodecConstants.h b/media/libstagefright/include/media/stagefright/MediaCodecConstants.h
index 178d334..6cf1ba0 100644
--- a/media/libstagefright/include/media/stagefright/MediaCodecConstants.h
+++ b/media/libstagefright/include/media/stagefright/MediaCodecConstants.h
@@ -619,6 +619,7 @@
 constexpr int32_t COLOR_FormatYUV422SemiPlanar        = 24;
 constexpr int32_t COLOR_FormatYUV444Flexible          = 0x7F444888;
 constexpr int32_t COLOR_FormatYUV444Interleaved       = 29;
+constexpr int32_t COLOR_FormatYUVP010                 = 54;
 constexpr int32_t COLOR_QCOM_FormatYUV420SemiPlanar   = 0x7fa30c00;
 constexpr int32_t COLOR_TI_FormatYUV420PackedSemiPlanar = 0x7f000100;
 
diff --git a/media/libstagefright/include/media/stagefright/MediaCodecList.h b/media/libstagefright/include/media/stagefright/MediaCodecList.h
index e681d25..78d1005 100644
--- a/media/libstagefright/include/media/stagefright/MediaCodecList.h
+++ b/media/libstagefright/include/media/stagefright/MediaCodecList.h
@@ -88,7 +88,7 @@
     static sp<IMediaCodecList> sCodecList;
     static sp<IMediaCodecList> sRemoteList;
 
-    status_t mInitCheck;
+    status_t mInitCheck{NO_INIT};
 
     sp<AMessage> mGlobalSettings;
     std::vector<sp<MediaCodecInfo> > mCodecInfos;
diff --git a/media/libstagefright/include/media/stagefright/MediaCodecSource.h b/media/libstagefright/include/media/stagefright/MediaCodecSource.h
index 2f98af1..0f7b535 100644
--- a/media/libstagefright/include/media/stagefright/MediaCodecSource.h
+++ b/media/libstagefright/include/media/stagefright/MediaCodecSource.h
@@ -64,12 +64,15 @@
 
     // MediaBufferObserver
     virtual void signalBufferReturned(MediaBufferBase *buffer);
+    virtual status_t setEncodingBitrate(int32_t bitRate /* bps */);
 
     // for AHandlerReflector
     void onMessageReceived(const sp<AMessage> &msg);
 
 
 
+    status_t requestIDRFrame();
+
 protected:
     virtual ~MediaCodecSource();
 
diff --git a/media/libstagefright/include/media/stagefright/MediaWriter.h b/media/libstagefright/include/media/stagefright/MediaWriter.h
index 1f4fbcb..9f20185 100644
--- a/media/libstagefright/include/media/stagefright/MediaWriter.h
+++ b/media/libstagefright/include/media/stagefright/MediaWriter.h
@@ -54,6 +54,11 @@
     virtual void setStartTimeOffsetMs(int /*ms*/) {}
     virtual int32_t getStartTimeOffsetMs() const { return 0; }
     virtual status_t setNextFd(int /*fd*/) { return INVALID_OPERATION; }
+    virtual void updateCVODegrees(int32_t /*cvoDegrees*/) {}
+    virtual void updatePayloadType(int32_t /*payloadType*/) {}
+    virtual void updateSocketNetwork(int64_t /*socketNetwork*/) {}
+    virtual uint32_t getSequenceNum() { return 0; }
+    virtual uint64_t getAccumulativeBytes() { return 0; }
 
 protected:
     virtual ~MediaWriter() {}
diff --git a/media/libstagefright/include/media/stagefright/MetaDataBase.h b/media/libstagefright/include/media/stagefright/MetaDataBase.h
index 64eb8b4..6f21a80 100644
--- a/media/libstagefright/include/media/stagefright/MetaDataBase.h
+++ b/media/libstagefright/include/media/stagefright/MetaDataBase.h
@@ -247,6 +247,15 @@
 
     // Treat empty track as malformed for MediaRecorder.
     kKeyEmptyTrackMalFormed = 'nemt', // bool (int32_t)
+    kKeyVps              = 'sVps', // int32_t, indicates that a buffer has vps.
+    kKeySps              = 'sSps', // int32_t, indicates that a buffer has sps.
+    kKeyPps              = 'sPps', // int32_t, indicates that a buffer has pps.
+    kKeySelfID           = 'sfid', // int32_t, source ID to identify itself on RTP protocol.
+    kKeyPayloadType      = 'pTyp', // int32_t, SDP negotiated payload type.
+    kKeyRtpExtMap        = 'extm', // int32_t, rtp extension ID for cvo on RTP protocol.
+    kKeyRtpCvoDegrees    = 'cvod', // int32_t, rtp cvo degrees as per 3GPP 26.114.
+    kKeyRtpDscp          = 'dscp', // int32_t, DSCP(Differentiated services codepoint) of RFC 2474.
+    kKeySocketNetwork    = 'sNet', // int64_t, socket will be bound to network handle.
 };
 
 enum {
diff --git a/media/libstagefright/include/media/stagefright/SurfaceUtils.h b/media/libstagefright/include/media/stagefright/SurfaceUtils.h
index ae55c65..35b3fa2 100644
--- a/media/libstagefright/include/media/stagefright/SurfaceUtils.h
+++ b/media/libstagefright/include/media/stagefright/SurfaceUtils.h
@@ -38,6 +38,8 @@
         int width, int height, int format, int rotation, int usage, bool reconnect);
 void setNativeWindowHdrMetadata(
         ANativeWindow *nativeWindow /* nonnull */, HDRStaticInfo *info /* nonnull */);
+status_t setNativeWindowRotation(
+        ANativeWindow *nativeWindow /* nonnull */, int rotation);
 status_t pushBlankBuffersToNativeWindow(ANativeWindow *nativeWindow /* nonnull */);
 status_t nativeWindowConnect(ANativeWindow *surface, const char *reason);
 status_t nativeWindowDisconnect(ANativeWindow *surface, const char *reason);
diff --git a/media/libstagefright/mpeg2ts/Android.bp b/media/libstagefright/mpeg2ts/Android.bp
index fbb2d0c..a970224 100644
--- a/media/libstagefright/mpeg2ts/Android.bp
+++ b/media/libstagefright/mpeg2ts/Android.bp
@@ -1,12 +1,30 @@
-cc_library_static {
-    name: "libstagefright_mpeg2support",
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_mpeg2ts_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_mpeg2ts_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
+cc_defaults {
+    name: "libstagefright_mpeg2support_defaults",
 
     srcs: [
         "AnotherPacketSource.cpp",
         "ATSParser.cpp",
         "CasManager.cpp",
         "ESQueue.cpp",
-        "HlsSampleDecryptor.cpp",
     ],
 
     include_dirs: [
@@ -28,7 +46,6 @@
     },
 
     shared_libs: [
-        "libcrypto",
         "libhidlmemory",
         "android.hardware.cas.native@1.0",
         "android.hidl.memory@1.0",
@@ -36,9 +53,10 @@
     ],
 
     header_libs: [
-        "libmedia_headers",
+        "libmedia_datasource_headers",
         "libaudioclient_headers",
         "media_ndk_headers",
+        "libstagefright_foundation_headers",
     ],
 
     export_include_dirs: ["."],
@@ -48,4 +66,39 @@
     ],
 
     min_sdk_version: "29",
+
+    host_supported: true,
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+}
+
+
+cc_library_static {
+    name: "libstagefright_mpeg2support",
+    defaults: [
+        "libstagefright_mpeg2support_defaults",
+    ],
+    cflags: [
+        "-DENABLE_CRYPTO",
+    ],
+    shared_libs: [
+        "libcrypto",
+    ],
+    srcs: [
+        "HlsSampleDecryptor.cpp",
+    ],
+}
+
+cc_library_static {
+    name: "libstagefright_mpeg2support_nocrypto",
+    defaults: [
+        "libstagefright_mpeg2support_defaults",
+    ],
+    apex_available: [
+        "com.android.media",
+    ],
 }
diff --git a/media/libstagefright/mpeg2ts/ESQueue.cpp b/media/libstagefright/mpeg2ts/ESQueue.cpp
index ea5d2de..192ba77 100644
--- a/media/libstagefright/mpeg2ts/ESQueue.cpp
+++ b/media/libstagefright/mpeg2ts/ESQueue.cpp
@@ -36,7 +36,7 @@
 #include <inttypes.h>
 #include <netinet/in.h>
 
-#ifndef __ANDROID_APEX__
+#ifdef ENABLE_CRYPTO
 #include "HlsSampleDecryptor.h"
 #endif
 
@@ -55,10 +55,10 @@
     // Create the decryptor anyway since we don't know the use-case unless key is provided
     // Won't decrypt if key info not available (e.g., scanner/extractor just parsing ts files)
     mSampleDecryptor = isSampleEncrypted() ?
-#ifdef __ANDROID_APEX__
-        new SampleDecryptor
-#else
+#ifdef ENABLE_CRYPTO
         new HlsSampleDecryptor
+#else
+        new SampleDecryptor
 #endif
         : NULL;
 }
@@ -172,29 +172,26 @@
         return 0;
     }
 
-    unsigned bsmod __unused = bits.getBits(3);
+    bits.skipBits(3); // bsmod
     unsigned acmod = bits.getBits(3);
-    unsigned cmixlev __unused = 0;
-    unsigned surmixlev __unused = 0;
-    unsigned dsurmod __unused = 0;
 
     if ((acmod & 1) > 0 && acmod != 1) {
         if (bits.numBitsLeft() < 2) {
             return 0;
         }
-        cmixlev = bits.getBits(2);
+        bits.skipBits(2); //cmixlev
     }
     if ((acmod & 4) > 0) {
         if (bits.numBitsLeft() < 2) {
             return 0;
         }
-        surmixlev = bits.getBits(2);
+        bits.skipBits(2); //surmixlev
     }
     if (acmod == 2) {
         if (bits.numBitsLeft() < 2) {
             return 0;
         }
-        dsurmod = bits.getBits(2);
+        bits.skipBits(2); //dsurmod
     }
 
     if (bits.numBitsLeft() < 1) {
@@ -269,7 +266,7 @@
         samplingRate = samplingRateTable2[fscod2];
     } else {
         samplingRate = samplingRateTable[fscod];
-        unsigned numblkscod __unused = bits.getBits(2);
+        bits.skipBits(2); // numblkscod
     }
 
     unsigned acmod = bits.getBits(3);
@@ -1087,7 +1084,7 @@
     }
     unsigned numAUs = bits.getBits(8);
     bits.skipBits(8);
-    unsigned quantization_word_length __unused = bits.getBits(2);
+    bits.skipBits(2); // quantization_word_length
     unsigned audio_sampling_frequency = bits.getBits(3);
     unsigned num_channels = bits.getBits(3);
 
diff --git a/media/libstagefright/mpeg2ts/test/Android.bp b/media/libstagefright/mpeg2ts/test/Android.bp
new file mode 100644
index 0000000..db2794f
--- /dev/null
+++ b/media/libstagefright/mpeg2ts/test/Android.bp
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2020 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 {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_mpeg2ts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_mpeg2ts_license",
+    ],
+}
+
+cc_test{
+    name: "Mpeg2tsUnitTest",
+    gtest: true,
+
+    srcs: [
+        "Mpeg2tsUnitTest.cpp"
+    ],
+
+    shared_libs: [
+        "android.hardware.cas@1.0",
+        "android.hardware.cas.native@1.0",
+        "android.hidl.token@1.0-utils",
+        "android.hidl.allocator@1.0",
+        "libcrypto",
+        "libhidlbase",
+        "libhidlmemory",
+        "liblog",
+        "libmedia",
+        "libbinder",
+        "libbinder_ndk",
+        "libutils",
+    ],
+
+    static_libs: [
+        "libdatasource",
+        "libstagefright",
+        "libstagefright_foundation",
+        "libstagefright_metadatautils",
+        "libstagefright_mpeg2support",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/extractors/",
+        "frameworks/av/media/libstagefright/",
+    ],
+
+    header_libs: [
+        "libmedia_headers",
+        "libaudioclient_headers",
+    ],
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+
+    sanitize: {
+        cfi: true,
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+    },
+}
diff --git a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml b/media/libstagefright/mpeg2ts/test/AndroidTest.xml
similarity index 71%
copy from media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
copy to media/libstagefright/mpeg2ts/test/AndroidTest.xml
index 7ff9732..ac1294d 100644
--- a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
+++ b/media/libstagefright/mpeg2ts/test/AndroidTest.xml
@@ -13,19 +13,19 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Test module config for Mp3 Decoder unit test">
-    <option name="test-suite-tag" value="Mp3DecoderTest" />
+<configuration description="Test module config for Mpeg2ts unit tests">
+    <option name="test-suite-tag" value="Mpeg2tsUnitTest" />
     <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
         <option name="cleanup" value="true" />
-        <option name="push" value="Mp3DecoderTest->/data/local/tmp/Mp3DecoderTest" />
+        <option name="push" value="Mpeg2tsUnitTest->/data/local/tmp/Mpeg2tsUnitTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest.zip?unzip=true"
-            value="/data/local/tmp/Mp3DecoderTestRes/" />
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTest.zip?unzip=true"
+            value="/data/local/tmp/Mpeg2tsUnitTestRes/" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.GTest" >
         <option name="native-test-device-path" value="/data/local/tmp" />
-        <option name="module-name" value="Mp3DecoderTest" />
-        <option name="native-test-flag" value="-P /data/local/tmp/Mp3DecoderTestRes/" />
+        <option name="module-name" value="Mpeg2tsUnitTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/Mpeg2tsUnitTestRes/" />
     </test>
 </configuration>
diff --git a/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTest.cpp b/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTest.cpp
new file mode 100644
index 0000000..79c233b
--- /dev/null
+++ b/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTest.cpp
@@ -0,0 +1,236 @@
+/*
+ * Copyright (C) 2020 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 "Mpeg2tsUnitTest"
+
+#include <utils/Log.h>
+
+#include <stdint.h>
+#include <sys/stat.h>
+
+#include <datasource/FileSource.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaDataBase.h>
+#include <media/stagefright/foundation/AUtils.h>
+
+#include "mpeg2ts/ATSParser.h"
+#include "mpeg2ts/AnotherPacketSource.h"
+
+#include "Mpeg2tsUnitTestEnvironment.h"
+
+constexpr size_t kTSPacketSize = 188;
+constexpr uint16_t kPIDMask = 0x1FFF;
+// Max value of PID which is also used for Null packets
+constexpr uint16_t kPIDMaxValue = 8191;
+constexpr uint8_t kTSSyncByte = 0x47;
+constexpr uint8_t kVideoPresent = 0x01;
+constexpr uint8_t kAudioPresent = 0x02;
+constexpr uint8_t kMetaDataPresent = 0x04;
+
+static Mpeg2tsUnitTestEnvironment *gEnv = nullptr;
+
+using namespace android;
+
+class Mpeg2tsUnitTest
+    : public ::testing ::TestWithParam<
+              tuple</*fileName*/ string, /*sourceType*/ char, /*numSource*/ uint16_t>> {
+  public:
+    Mpeg2tsUnitTest()
+        : mInputBuffer(nullptr), mSource(nullptr), mFpInput(nullptr), mParser(nullptr) {}
+
+    ~Mpeg2tsUnitTest() {
+        if (mInputBuffer) free(mInputBuffer);
+        if (mFpInput) fclose(mFpInput);
+        mSource.clear();
+    }
+
+    void SetUp() override {
+        mOffset = 0;
+        mNumDataSource = 0;
+        tuple<string, char, uint16_t> params = GetParam();
+        char sourceType = get<1>(params);
+        /* mSourceType = 0b x x x x x M A V
+                                     /  |  \
+                            metaData  audio  video */
+        mMediaType = (sourceType & 0x07);
+        mNumDataSource = get<2>(params);
+        string inputFile = gEnv->getRes() + get<0>(params);
+        mFpInput = fopen(inputFile.c_str(), "rb");
+        ASSERT_NE(mFpInput, nullptr) << "Failed to open file: " << inputFile;
+
+        struct stat buf;
+        int8_t err = stat(inputFile.c_str(), &buf);
+        ASSERT_EQ(err, 0) << "Failed to get information for file: " << inputFile;
+
+        long fileSize = buf.st_size;
+        mTotalPackets = fileSize / kTSPacketSize;
+        int32_t fd = fileno(mFpInput);
+        ASSERT_GE(fd, 0) << "Failed to get the integer file descriptor";
+
+        mSource = new FileSource(dup(fd), 0, buf.st_size);
+        ASSERT_NE(mSource, nullptr) << "Failed to get the data source!";
+
+        mParser = new ATSParser();
+        ASSERT_NE(mParser, nullptr) << "Unable to create ATS parser!";
+        mInputBuffer = (uint8_t *)malloc(kTSPacketSize);
+        ASSERT_NE(mInputBuffer, nullptr) << "Failed to allocate memory for TS packet!";
+    }
+
+    uint64_t mOffset;
+    uint64_t mTotalPackets;
+    uint16_t mNumDataSource;
+
+    int8_t mMediaType;
+
+    uint8_t *mInputBuffer;
+    string mInputFile;
+    sp<DataSource> mSource;
+    FILE *mFpInput;
+    ATSParser *mParser;
+};
+
+TEST_P(Mpeg2tsUnitTest, MediaInfoTest) {
+    bool videoFound = false;
+    bool audioFound = false;
+    bool metaDataFound = false;
+    bool syncPointPresent = false;
+
+    int16_t totalDataSource = 0;
+    int32_t val32 = 0;
+    uint8_t numDataSource = 0;
+    uint8_t packet[kTSPacketSize];
+    ssize_t numBytesRead = -1;
+
+    ATSParser::SyncEvent event(mOffset);
+    static const ATSParser::SourceType mediaType[] = {ATSParser::VIDEO, ATSParser::AUDIO,
+                                                      ATSParser::META, ATSParser::NUM_SOURCE_TYPES};
+    const uint32_t nMediaTypes = sizeof(mediaType) / sizeof(mediaType[0]);
+
+    while ((numBytesRead = mSource->readAt(mOffset, packet, kTSPacketSize)) == kTSPacketSize) {
+        ASSERT_TRUE(packet[0] == kTSSyncByte) << "Sync byte error!";
+
+        // pid is 13 bits
+        uint16_t pid = (packet[1] + (packet[2] << 8)) & kPIDMask;
+        ASSERT_TRUE(pid <= kPIDMaxValue) << "Invalid PID: " << pid;
+
+        status_t err = mParser->feedTSPacket(packet, kTSPacketSize, &event);
+        ASSERT_EQ(err, (status_t)OK) << "Unable to feed TS packet!";
+
+        mOffset += numBytesRead;
+        for (int i = 0; i < nMediaTypes; i++) {
+            if (mParser->hasSource(mediaType[i])) {
+                switch (mediaType[i]) {
+                    case ATSParser::VIDEO:
+                        videoFound = true;
+                        break;
+                    case ATSParser::AUDIO:
+                        audioFound = true;
+                        break;
+                    case ATSParser::META:
+                        metaDataFound = true;
+                        break;
+                    case ATSParser::NUM_SOURCE_TYPES:
+                        numDataSource = 3;
+                        break;
+                    default:
+                        break;
+                }
+            }
+        }
+        if (videoFound && audioFound && metaDataFound && (numDataSource == 3)) break;
+    }
+
+    for (int i = 0; i < nMediaTypes; i++) {
+        ATSParser::SourceType currentMediaType = mediaType[i];
+        if (mParser->hasSource(currentMediaType)) {
+            if (event.hasReturnedData()) {
+                syncPointPresent = true;
+                sp<AnotherPacketSource> syncPacketSource = event.getMediaSource();
+                ASSERT_NE(syncPacketSource, nullptr)
+                        << "Cannot get sync source for media type: " << currentMediaType;
+
+                status_t err = syncPacketSource->start();
+                ASSERT_EQ(err, (status_t)OK) << "Error returned while starting!";
+
+                sp<MetaData> format = syncPacketSource->getFormat();
+                ASSERT_NE(format, nullptr) << "Unable to get the format of the source packet!";
+
+                MediaBufferBase *buf;
+                syncPacketSource->read(&buf, nullptr);
+                ASSERT_NE(buf, nullptr) << "Failed to read sync packet source data";
+
+                MetaDataBase &inMeta = buf->meta_data();
+                bool status = inMeta.findInt32(kKeyIsSyncFrame, &val32);
+                ASSERT_EQ(status, true) << "Sync frame key is not set";
+
+                status = inMeta.findInt32(kKeyCryptoMode, &val32);
+                ASSERT_EQ(status, false) << "Invalid packet, found scrambled packets!";
+
+                err = syncPacketSource->stop();
+                ASSERT_EQ(err, (status_t)OK) << "Error returned while stopping!";
+            }
+            sp<AnotherPacketSource> packetSource = mParser->getSource(currentMediaType);
+            ASSERT_NE(packetSource, nullptr)
+                    << "Cannot get source for media type: " << currentMediaType;
+
+            status_t err = packetSource->start();
+            ASSERT_EQ(err, (status_t)OK) << "Error returned while starting!";
+            sp<MetaData> format = packetSource->getFormat();
+            ASSERT_NE(format, nullptr) << "Unable to get the format of the packet!";
+
+            err = packetSource->stop();
+            ASSERT_EQ(err, (status_t)OK) << "Error returned while stopping!";
+        }
+    }
+
+    ASSERT_EQ(videoFound, bool(mMediaType & kVideoPresent)) << "No Video packets found!";
+    ASSERT_EQ(audioFound, bool(mMediaType & kAudioPresent)) << "No Audio packets found!";
+    ASSERT_EQ(metaDataFound, bool(mMediaType & kMetaDataPresent)) << "No meta data found!";
+
+    if (videoFound || audioFound) {
+        ASSERT_TRUE(syncPointPresent) << "No sync points found for audio/video";
+    }
+
+    if (videoFound) totalDataSource += 1;
+    if (audioFound) totalDataSource += 1;
+    if (metaDataFound) totalDataSource += 1;
+
+    ASSERT_TRUE(totalDataSource == mNumDataSource)
+            << "Expected " << mNumDataSource << " data sources, found " << totalDataSource;
+    if (numDataSource == 3) {
+        ASSERT_EQ(numDataSource, mNumDataSource)
+                << "Expected " << mNumDataSource << " data sources, found " << totalDataSource;
+    }
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        infoTest, Mpeg2tsUnitTest,
+        ::testing::Values(make_tuple("crowd_1920x1080_25fps_6700kbps_h264.ts", 0x01, 1),
+                          make_tuple("segment000001.ts", 0x03, 2),
+                          make_tuple("bbb_44100hz_2ch_128kbps_mp3_5mins.ts", 0x02, 1)));
+
+int32_t main(int argc, char **argv) {
+    gEnv = new Mpeg2tsUnitTestEnvironment();
+    ::testing::AddGlobalTestEnvironment(gEnv);
+    ::testing::InitGoogleTest(&argc, argv);
+    uint8_t status = gEnv->initFromOptions(argc, argv);
+    if (status == 0) {
+        status = RUN_ALL_TESTS();
+        ALOGV("Mpeg2tsUnit Test Result = %d\n", status);
+    }
+    return status;
+}
diff --git a/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTestEnvironment.h b/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTestEnvironment.h
new file mode 100644
index 0000000..9e41db7
--- /dev/null
+++ b/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTestEnvironment.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2020 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 __MPEG2TS_UNIT_TEST_ENVIRONMENT_H__
+#define __MPEG2TS_UNIT_TEST_ENVIRONMENT_H__
+
+#include <gtest/gtest.h>
+
+#include <getopt.h>
+
+using namespace std;
+
+class Mpeg2tsUnitTestEnvironment : public::testing::Environment {
+  public:
+    Mpeg2tsUnitTestEnvironment() : res("/data/local/tmp/") {}
+
+    // Parses the command line arguments
+    int initFromOptions(int argc, char **argv);
+
+    void setRes(const char *_res) { res = _res; }
+
+    const string getRes() const { return res; }
+
+  private:
+    string res;
+};
+
+int Mpeg2tsUnitTestEnvironment::initFromOptions(int argc, char **argv) {
+    static struct option options[] = {{"path", required_argument, 0, 'P'}, {0, 0, 0, 0}};
+
+    while (true) {
+        int index = 0;
+        int c = getopt_long(argc, argv, "P:", options, &index);
+        if (c == -1) {
+            break;
+        }
+
+        switch (c) {
+            case 'P': {
+                setRes(optarg);
+                break;
+            }
+            default:
+                break;
+        }
+    }
+
+    if (optind < argc) {
+        fprintf(stderr,
+                "unrecognized option: %s\n\n"
+                "usage: %s <gtest options> <test options>\n\n"
+                "test options are:\n\n"
+                "-P, --path: Resource files directory location\n",
+                argv[optind ?: 1], argv[0]);
+        return 2;
+    }
+    return 0;
+}
+
+#endif  // __MPEG2TS_UNIT_TEST_ENVIRONMENT_H__
diff --git a/media/libstagefright/mpeg2ts/test/README.md b/media/libstagefright/mpeg2ts/test/README.md
new file mode 100644
index 0000000..237ce72
--- /dev/null
+++ b/media/libstagefright/mpeg2ts/test/README.md
@@ -0,0 +1,38 @@
+## Media Testing ##
+---
+#### Mpeg2TS Unit Test :
+The Mpeg2TS Unit Test Suite validates the functionality of the libraries present in Mpeg2TS.
+
+Run the following steps to build the test suite:
+```
+mmm frameworks/av/media/libstagefright/mpeg2ts/test/
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+
+adb push ${OUT}/data/nativetest64/Mpeg2tsUnitTest/Mpeg2tsUnitTest /data/local/tmp/
+
+To test 32-bit binary push binaries from nativetest.
+
+adb push ${OUT}/data/nativetest/Mpeg2tsUnitTest/Mpeg2tsUnitTest /data/local/tmp/
+
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTest.zip ).
+Download, unzip and push these files into device for testing.
+
+```
+adb push Mpeg2tsUnitTestRes/. /data/local/tmp/
+```
+
+usage: Mpeg2tsUnitTest -P \<path_to_folder\>
+```
+adb shell /data/local/tmp/Mpeg2tsUnitTest -P /data/local/tmp/Mpeg2tsUnitTestRes/
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest Mpeg2tsUnitTest -- --enable-module-dynamic-download=true
+```
diff --git a/media/libstagefright/omx/1.0/Omx.cpp b/media/libstagefright/omx/1.0/Omx.cpp
index eef9ce3..eb15039 100644
--- a/media/libstagefright/omx/1.0/Omx.cpp
+++ b/media/libstagefright/omx/1.0/Omx.cpp
@@ -22,7 +22,7 @@
 #include <media/openmax/OMX_AsString.h>
 
 #include <media/stagefright/omx/OMXUtils.h>
-#include <media/stagefright/omx/OMXMaster.h>
+#include <media/stagefright/omx/OMXStore.h>
 #include <media/stagefright/omx/OmxGraphicBufferSource.h>
 
 #include <media/stagefright/omx/1.0/WOmxNode.h>
@@ -41,21 +41,21 @@
 constexpr size_t kMaxNodeInstances = (1 << 16);
 
 Omx::Omx() :
-    mMaster(new OMXMaster()),
+    mStore(new OMXStore()),
     mParser() {
     (void)mParser.parseXmlFilesInSearchDirs();
     (void)mParser.parseXmlPath(mParser.defaultProfilingResultsXmlPath);
 }
 
 Omx::~Omx() {
-    delete mMaster;
+    delete mStore;
 }
 
 Return<void> Omx::listNodes(listNodes_cb _hidl_cb) {
     std::list<::android::IOMX::ComponentInfo> list;
     char componentName[256];
     for (OMX_U32 index = 0;
-            mMaster->enumerateComponents(
+            mStore->enumerateComponents(
             componentName, sizeof(componentName), index) == OMX_ErrorNone;
             ++index) {
         list.push_back(::android::IOMX::ComponentInfo());
@@ -63,7 +63,7 @@
         info.mName = componentName;
         ::android::Vector<::android::String8> roles;
         OMX_ERRORTYPE err =
-                mMaster->getRolesOfComponent(componentName, &roles);
+                mStore->getRolesOfComponent(componentName, &roles);
         if (err == OMX_ErrorNone) {
             for (OMX_U32 i = 0; i < roles.size(); ++i) {
                 info.mRoles.push_back(roles[i]);
@@ -101,7 +101,7 @@
                 this, new LWOmxObserver(observer), name.c_str());
 
         OMX_COMPONENTTYPE *handle;
-        OMX_ERRORTYPE err = mMaster->makeComponentInstance(
+        OMX_ERRORTYPE err = mStore->makeComponentInstance(
                 name.c_str(), &OMXNodeInstance::kCallbacks,
                 instance.get(), &handle);
 
@@ -208,7 +208,7 @@
 
     OMX_ERRORTYPE err = OMX_ErrorNone;
     if (instance->handle() != NULL) {
-        err = mMaster->destroyComponentInstance(
+        err = mStore->destroyComponentInstance(
                 static_cast<OMX_COMPONENTTYPE*>(instance->handle()));
     }
     return StatusFromOMXError(err);
diff --git a/media/libstagefright/omx/1.0/OmxStore.cpp b/media/libstagefright/omx/1.0/OmxStore.cpp
index 67f478e..b5c1166 100644
--- a/media/libstagefright/omx/1.0/OmxStore.cpp
+++ b/media/libstagefright/omx/1.0/OmxStore.cpp
@@ -54,6 +54,24 @@
         });
     }
 
+    if (!nodes.empty()) {
+        auto anyNode = nodes.cbegin();
+        std::string::const_iterator first = anyNode->cbegin();
+        std::string::const_iterator last = anyNode->cend();
+        for (const std::string &name : nodes) {
+            std::string::const_iterator it1 = first;
+            for (std::string::const_iterator it2 = name.cbegin();
+                    it1 != last && it2 != name.cend() && tolower(*it1) == tolower(*it2);
+                    ++it1, ++it2) {
+            }
+            last = it1;
+        }
+        mPrefix = std::string(first, last);
+        LOG(INFO) << "omx common prefix: '" << mPrefix.c_str() << "'";
+    } else {
+        LOG(INFO) << "omx common prefix: no nodes";
+    }
+
     MediaCodecsXmlParser parser;
     parser.parseXmlFilesInSearchDirs(xmlNames, searchDirs);
     if (profilingResultsXmlPath != nullptr) {
@@ -112,8 +130,6 @@
         mRoleList[i] = std::move(role);
         ++i;
     }
-
-    mPrefix = parser.getCommonPrefix();
 }
 
 OmxStore::~OmxStore() {
diff --git a/media/libstagefright/omx/Android.bp b/media/libstagefright/omx/Android.bp
index 78b4f19..54c5697 100644
--- a/media/libstagefright/omx/Android.bp
+++ b/media/libstagefright/omx/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_omx_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_omx_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libstagefright_omx",
     vendor_available: true,
@@ -7,7 +26,7 @@
     double_loadable: true,
 
     srcs: [
-        "OMXMaster.cpp",
+        "OMXStore.cpp",
         "OMXNodeInstance.cpp",
         "OMXUtils.cpp",
         "OmxGraphicBufferSource.cpp",
@@ -227,4 +246,3 @@
     },
     cflags: ["-Wall", "-Werror"],
 }
-
diff --git a/media/libstagefright/omx/OMXNodeInstance.cpp b/media/libstagefright/omx/OMXNodeInstance.cpp
index ac42373..bebd516 100644
--- a/media/libstagefright/omx/OMXNodeInstance.cpp
+++ b/media/libstagefright/omx/OMXNodeInstance.cpp
@@ -22,7 +22,7 @@
 #include <inttypes.h>
 
 #include <media/stagefright/omx/OMXNodeInstance.h>
-#include <media/stagefright/omx/OMXMaster.h>
+#include <media/stagefright/omx/OMXStore.h>
 #include <media/stagefright/omx/OMXUtils.h>
 #include <android/IOMXBufferSource.h>
 
diff --git a/media/libstagefright/omx/OMXMaster.cpp b/media/libstagefright/omx/OMXStore.cpp
similarity index 91%
rename from media/libstagefright/omx/OMXMaster.cpp
rename to media/libstagefright/omx/OMXStore.cpp
index 094b1f5..e8fee42 100644
--- a/media/libstagefright/omx/OMXMaster.cpp
+++ b/media/libstagefright/omx/OMXStore.cpp
@@ -15,11 +15,11 @@
  */
 
 //#define LOG_NDEBUG 0
-#define LOG_TAG "OMXMaster"
+#define LOG_TAG "OMXStore"
 #include <android-base/properties.h>
 #include <utils/Log.h>
 
-#include <media/stagefright/omx/OMXMaster.h>
+#include <media/stagefright/omx/OMXStore.h>
 #include <media/stagefright/omx/SoftOMXPlugin.h>
 #include <media/stagefright/foundation/ADebug.h>
 
@@ -30,7 +30,7 @@
 
 namespace android {
 
-OMXMaster::OMXMaster() {
+OMXStore::OMXStore() {
 
     pid_t pid = getpid();
     char filename[20];
@@ -55,19 +55,19 @@
     addPlatformPlugin();
 }
 
-OMXMaster::~OMXMaster() {
+OMXStore::~OMXStore() {
     clearPlugins();
 }
 
-void OMXMaster::addVendorPlugin() {
+void OMXStore::addVendorPlugin() {
     addPlugin("libstagefrighthw.so");
 }
 
-void OMXMaster::addPlatformPlugin() {
+void OMXStore::addPlatformPlugin() {
     addPlugin("libstagefright_softomx_plugin.so");
 }
 
-void OMXMaster::addPlugin(const char *libname) {
+void OMXStore::addPlugin(const char *libname) {
     if (::android::base::GetIntProperty("vendor.media.omx", int64_t(1)) == 0) {
         return;
     }
@@ -99,7 +99,7 @@
     }
 }
 
-void OMXMaster::addPlugin(OMXPluginBase *plugin) {
+void OMXStore::addPlugin(OMXPluginBase *plugin) {
     Mutex::Autolock autoLock(mLock);
 
     OMX_U32 index = 0;
@@ -126,7 +126,7 @@
     }
 }
 
-void OMXMaster::clearPlugins() {
+void OMXStore::clearPlugins() {
     Mutex::Autolock autoLock(mLock);
 
     mPluginByComponentName.clear();
@@ -148,7 +148,7 @@
     mPlugins.clear();
 }
 
-OMX_ERRORTYPE OMXMaster::makeComponentInstance(
+OMX_ERRORTYPE OMXStore::makeComponentInstance(
         const char *name,
         const OMX_CALLBACKTYPE *callbacks,
         OMX_PTR appData,
@@ -177,7 +177,7 @@
     return err;
 }
 
-OMX_ERRORTYPE OMXMaster::destroyComponentInstance(
+OMX_ERRORTYPE OMXStore::destroyComponentInstance(
         OMX_COMPONENTTYPE *component) {
     Mutex::Autolock autoLock(mLock);
 
@@ -193,7 +193,7 @@
     return plugin->destroyComponentInstance(component);
 }
 
-OMX_ERRORTYPE OMXMaster::enumerateComponents(
+OMX_ERRORTYPE OMXStore::enumerateComponents(
         OMX_STRING name,
         size_t size,
         OMX_U32 index) {
@@ -213,7 +213,7 @@
     return OMX_ErrorNone;
 }
 
-OMX_ERRORTYPE OMXMaster::getRolesOfComponent(
+OMX_ERRORTYPE OMXStore::getRolesOfComponent(
         const char *name,
         Vector<String8> *roles) {
     Mutex::Autolock autoLock(mLock);
diff --git a/media/libstagefright/omx/OMXUtils.cpp b/media/libstagefright/omx/OMXUtils.cpp
index 1b8493a..d6d280f 100644
--- a/media/libstagefright/omx/OMXUtils.cpp
+++ b/media/libstagefright/omx/OMXUtils.cpp
@@ -354,7 +354,7 @@
     DescribeColorFormat2Params describeParams;
     InitOMXParams(&describeParams);
     describeParams.eColorFormat = (OMX_COLOR_FORMATTYPE)colorFormat;
-    // reasonable dummy values
+    // reasonable initial values (that will be overwritten)
     describeParams.nFrameWidth = 128;
     describeParams.nFrameHeight = 128;
     describeParams.nStride = 128;
diff --git a/media/libstagefright/omx/include/media/stagefright/omx/1.0/Omx.h b/media/libstagefright/omx/include/media/stagefright/omx/1.0/Omx.h
index 5a46b26..84ae511 100644
--- a/media/libstagefright/omx/include/media/stagefright/omx/1.0/Omx.h
+++ b/media/libstagefright/omx/include/media/stagefright/omx/1.0/Omx.h
@@ -27,7 +27,7 @@
 
 namespace android {
 
-struct OMXMaster;
+struct OMXStore;
 struct OMXNodeInstance;
 
 namespace hardware {
@@ -51,7 +51,7 @@
 using ::android::sp;
 using ::android::wp;
 
-using ::android::OMXMaster;
+using ::android::OMXStore;
 using ::android::OMXNodeInstance;
 
 struct Omx : public IOmx, public hidl_death_recipient {
@@ -73,7 +73,7 @@
     status_t freeNode(sp<OMXNodeInstance> const& instance);
 
 protected:
-    OMXMaster* mMaster;
+    OMXStore* mStore;
     Mutex mLock;
     KeyedVector<wp<IBase>, sp<OMXNodeInstance> > mLiveNodes;
     KeyedVector<OMXNodeInstance*, wp<IBase> > mNode2Observer;
diff --git a/media/libstagefright/omx/include/media/stagefright/omx/OMXNodeInstance.h b/media/libstagefright/omx/include/media/stagefright/omx/OMXNodeInstance.h
index a761ef6..5f32c9e 100644
--- a/media/libstagefright/omx/include/media/stagefright/omx/OMXNodeInstance.h
+++ b/media/libstagefright/omx/include/media/stagefright/omx/OMXNodeInstance.h
@@ -33,7 +33,7 @@
 class GraphicBuffer;
 class IOMXBufferSource;
 class IOMXObserver;
-struct OMXMaster;
+struct OMXStore;
 class OMXBuffer;
 using IHidlMemory = hidl::memory::V1_0::IMemory;
 using hardware::media::omx::V1_0::implementation::Omx;
diff --git a/media/libstagefright/omx/include/media/stagefright/omx/OMXMaster.h b/media/libstagefright/omx/include/media/stagefright/omx/OMXStore.h
similarity index 88%
rename from media/libstagefright/omx/include/media/stagefright/omx/OMXMaster.h
rename to media/libstagefright/omx/include/media/stagefright/omx/OMXStore.h
index 93eaef1..5d6c3ed 100644
--- a/media/libstagefright/omx/include/media/stagefright/omx/OMXMaster.h
+++ b/media/libstagefright/omx/include/media/stagefright/omx/OMXStore.h
@@ -14,9 +14,9 @@
  * limitations under the License.
  */
 
-#ifndef OMX_MASTER_H_
+#ifndef OMX_STORE_H_
 
-#define OMX_MASTER_H_
+#define OMX_STORE_H_
 
 #include <media/hardware/OMXPluginBase.h>
 
@@ -27,9 +27,9 @@
 
 namespace android {
 
-struct OMXMaster : public OMXPluginBase {
-    OMXMaster();
-    virtual ~OMXMaster();
+struct OMXStore : public OMXPluginBase {
+    OMXStore();
+    virtual ~OMXStore();
 
     virtual OMX_ERRORTYPE makeComponentInstance(
             const char *name,
@@ -66,10 +66,10 @@
     void addPlugin(OMXPluginBase *plugin);
     void clearPlugins();
 
-    OMXMaster(const OMXMaster &);
-    OMXMaster &operator=(const OMXMaster &);
+    OMXStore(const OMXStore &);
+    OMXStore &operator=(const OMXStore &);
 };
 
 }  // namespace android
 
-#endif  // OMX_MASTER_H_
+#endif  // OMX_STORE_H_
diff --git a/media/libstagefright/omx/tests/Android.bp b/media/libstagefright/omx/tests/Android.bp
index fefb3bb..83cc80e 100644
--- a/media/libstagefright/omx/tests/Android.bp
+++ b/media/libstagefright/omx/tests/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_omx_tests_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_omx_tests_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_test {
     name: "omx_tests",
     gtest: false,
diff --git a/media/libstagefright/rtsp/AAVCAssembler.cpp b/media/libstagefright/rtsp/AAVCAssembler.cpp
index 4bc67e8..2f93d5d 100644
--- a/media/libstagefright/rtsp/AAVCAssembler.cpp
+++ b/media/libstagefright/rtsp/AAVCAssembler.cpp
@@ -25,8 +25,11 @@
 #include <media/stagefright/foundation/ABuffer.h>
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/AMessage.h>
+#include <media/stagefright/foundation/avc_utils.h>
 #include <media/stagefright/foundation/hexdump.h>
 
+#include <android-base/properties.h>
+
 #include <stdint.h>
 
 namespace android {
@@ -37,36 +40,142 @@
       mAccessUnitRTPTime(0),
       mNextExpectedSeqNoValid(false),
       mNextExpectedSeqNo(0),
-      mAccessUnitDamaged(false) {
+      mAccessUnitDamaged(false),
+      mFirstIFrameProvided(false),
+      mLastIFrameProvidedAtMs(0),
+      mWidth(0),
+      mHeight(0) {
 }
 
 AAVCAssembler::~AAVCAssembler() {
 }
 
+int32_t AAVCAssembler::addNack(
+        const sp<ARTPSource> &source) {
+    List<sp<ABuffer>> *queue = source->queue();
+    int32_t nackCount = 0;
+
+    List<sp<ABuffer> >::iterator it = queue->begin();
+
+    if (it == queue->end()) {
+        return nackCount /* 0 */;
+    }
+
+    uint16_t queueHeadSeqNum = (*it)->int32Data();
+
+    // move to the packet after which RTCP:NACK was sent.
+    for (; it != queue->end(); ++it) {
+        int32_t seqNum = (*it)->int32Data();
+        if (seqNum >= source->mHighestNackNumber) {
+            break;
+        }
+    }
+
+    int32_t nackStartAt = -1;
+
+    while (it != queue->end()) {
+        int32_t seqBeforeLast = (*it)->int32Data();
+        // increase iterator.
+        if ((++it) == queue->end()) {
+            break;
+        }
+        int32_t seqLast = (*it)->int32Data();
+
+        if ((seqLast - seqBeforeLast) < 0) {
+            ALOGD("addNack: found end of seqNum from(%d) to(%d)", seqBeforeLast, seqLast);
+            source->mHighestNackNumber = 0;
+        }
+
+        // missed packet found
+        if (seqLast > (seqBeforeLast + 1) &&
+                // we didn't send RTCP:NACK for this packet yet.
+                (seqLast - 1) > source->mHighestNackNumber) {
+            source->mHighestNackNumber = seqLast - 1;
+            nackStartAt = seqBeforeLast + 1;
+            break;
+        }
+
+    }
+
+    if (nackStartAt != -1) {
+        nackCount = source->mHighestNackNumber - nackStartAt + 1;
+        ALOGD("addNack: nackCount=%d, nackFrom=%d, nackTo=%d", nackCount,
+                nackStartAt, source->mHighestNackNumber);
+
+        uint16_t mask = (uint16_t)(0xffff) >> (16 - nackCount + 1);
+        source->setSeqNumToNACK(nackStartAt, mask, queueHeadSeqNum);
+    }
+
+    return nackCount;
+}
+
 ARTPAssembler::AssemblyStatus AAVCAssembler::addNALUnit(
         const sp<ARTPSource> &source) {
     List<sp<ABuffer> > *queue = source->queue();
+    const uint32_t firstRTPTime = source->mFirstRtpTime;
 
     if (queue->empty()) {
         return NOT_ENOUGH_DATA;
     }
 
+    sp<ABuffer> buffer = *queue->begin();
+    buffer->meta()->setObject("source", source);
+
+    int64_t rtpTime = findRTPTime(firstRTPTime, buffer);
+
+    int64_t startTime = source->mFirstSysTime / 1000;
+    int64_t nowTime = ALooper::GetNowUs() / 1000;
+    int64_t playedTime = nowTime - startTime;
+
+    int64_t playedTimeRtp = source->mFirstRtpTime + playedTime * (int64_t)source->mClockRate / 1000;
+    const int64_t jitterTime = source->mJbTimeMs * (int64_t)source->mClockRate / 1000;
+
+    int64_t expiredTimeInJb = rtpTime + jitterTime;
+    bool isExpired = expiredTimeInJb <= (playedTimeRtp);
+    bool isTooLate200 = expiredTimeInJb < (playedTimeRtp - jitterTime);
+    bool isTooLate300 = expiredTimeInJb < (playedTimeRtp - (jitterTime * 3 / 2));
+
+    if (mShowQueue && mShowQueueCnt < 20) {
+        showCurrentQueue(queue);
+        printNowTimeUs(startTime, nowTime, playedTime);
+        printRTPTime(rtpTime, playedTimeRtp, expiredTimeInJb, isExpired);
+        mShowQueueCnt++;
+    }
+
+    AAVCAssembler::addNack(source);
+
+    if (!isExpired) {
+        ALOGV("buffering in jitter buffer.");
+        return NOT_ENOUGH_DATA;
+    }
+
+    if (isTooLate200) {
+        ALOGW("=== WARNING === buffer arrived 200ms late. === WARNING === ");
+    }
+
+    if (isTooLate300) {
+        ALOGW("buffer arrived after 300ms ... \t Diff in Jb=%lld \t Seq# %d",
+                (long long)(playedTimeRtp - expiredTimeInJb), buffer->int32Data());
+        printNowTimeUs(startTime, nowTime, playedTime);
+        printRTPTime(rtpTime, playedTimeRtp, expiredTimeInJb, isExpired);
+
+        mNextExpectedSeqNo = pickProperSeq(queue, firstRTPTime, playedTimeRtp, jitterTime);
+    }
+
     if (mNextExpectedSeqNoValid) {
-        List<sp<ABuffer> >::iterator it = queue->begin();
-        while (it != queue->end()) {
-            if ((uint32_t)(*it)->int32Data() >= mNextExpectedSeqNo) {
-                break;
-            }
+        int32_t size = queue->size();
+        int32_t cntRemove = deleteUnitUnderSeq(queue, mNextExpectedSeqNo);
 
-            it = queue->erase(it);
+        if (cntRemove > 0) {
+            source->noticeAbandonBuffer(cntRemove);
+            ALOGW("delete %d of %d buffers", cntRemove, size);
         }
-
         if (queue->empty()) {
             return NOT_ENOUGH_DATA;
         }
     }
 
-    sp<ABuffer> buffer = *queue->begin();
+    buffer = *queue->begin();
 
     if (!mNextExpectedSeqNoValid) {
         mNextExpectedSeqNoValid = true;
@@ -123,15 +232,72 @@
     }
 }
 
+void AAVCAssembler::checkSpsUpdated(const sp<ABuffer> &buffer) {
+    const uint8_t *data = buffer->data();
+    unsigned nalType = data[0] & 0x1f;
+    if (nalType == 0x7) {
+        int32_t width = 0, height = 0;
+        FindAVCDimensions(buffer, &width, &height);
+        if (width != mWidth || height != mHeight) {
+            mFirstIFrameProvided = false;
+            mWidth = width;
+            mHeight = height;
+            ALOGD("found a new resolution (%u x %u)", mWidth, mHeight);
+        }
+    }
+}
+
+void AAVCAssembler::checkIFrameProvided(const sp<ABuffer> &buffer) {
+    if (buffer->size() == 0) {
+        return;
+    }
+    const uint8_t *data = buffer->data();
+    unsigned nalType = data[0] & 0x1f;
+    if (nalType == 0x5) {
+        mLastIFrameProvidedAtMs = ALooper::GetNowUs() / 1000;
+        if (!mFirstIFrameProvided) {
+            mFirstIFrameProvided = true;
+
+            uint32_t rtpTime;
+            CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
+            ALOGD("got First I-frame to be decoded. rtpTime=%d, size=%zu", rtpTime, buffer->size());
+        }
+    }
+}
+
+bool AAVCAssembler::dropFramesUntilIframe(const sp<ABuffer> &buffer) {
+    const uint8_t *data = buffer->data();
+    unsigned nalType = data[0] & 0x1f;
+    if (!mFirstIFrameProvided && nalType < 0x5) {
+        return true;
+    }
+
+    return false;
+}
+
 void AAVCAssembler::addSingleNALUnit(const sp<ABuffer> &buffer) {
     ALOGV("addSingleNALUnit of size %zu", buffer->size());
 #if !LOG_NDEBUG
     hexdump(buffer->data(), buffer->size());
 #endif
 
+    checkSpsUpdated(buffer);
+    checkIFrameProvided(buffer);
+
     uint32_t rtpTime;
     CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
 
+    if (dropFramesUntilIframe(buffer)) {
+        sp<ARTPSource> source = nullptr;
+        buffer->meta()->findObject("source", (sp<android::RefBase>*)&source);
+        if (source != nullptr) {
+            ALOGD("Issued FIR to get the I-frame");
+            source->onIssueFIRByAssembler();
+        }
+        ALOGV("Dropping P-frame till I-frame provided. rtpTime %u", rtpTime);
+        return;
+    }
+
     if (!mNALUnits.empty() && rtpTime != mAccessUnitRTPTime) {
         submitAccessUnit();
     }
@@ -216,6 +382,11 @@
     size_t totalCount = 1;
     bool complete = false;
 
+    uint32_t rtpTimeStartAt;
+    CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTimeStartAt));
+    uint32_t startSeqNo = buffer->int32Data();
+    bool pFrame = nalType == 0x1;
+
     if (data[1] & 0x40) {
         // Huh? End bit also set on the first buffer.
 
@@ -224,6 +395,8 @@
         complete = true;
     } else {
         List<sp<ABuffer> >::iterator it = ++queue->begin();
+        int32_t connected = 1;
+        bool snapped = false;
         while (it != queue->end()) {
             ALOGV("sequence length %zu", totalCount);
 
@@ -233,26 +406,32 @@
             size_t size = buffer->size();
 
             if ((uint32_t)buffer->int32Data() != expectedSeqNo) {
-                ALOGV("sequence not complete, expected seqNo %d, got %d",
-                     expectedSeqNo, (uint32_t)buffer->int32Data());
+                ALOGD("sequence not complete, expected seqNo %u, got %u, nalType %u",
+                     expectedSeqNo, (unsigned)buffer->int32Data(), nalType);
+                snapped = true;
 
-                return WRONG_SEQUENCE_NUMBER;
+                if (!pFrame) {
+                    return WRONG_SEQUENCE_NUMBER;
+                }
             }
 
+            if (!snapped) {
+                connected++;
+            }
+
+            uint32_t rtpTime;
+            CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
             if (size < 2
                     || data[0] != indicator
                     || (data[1] & 0x1f) != nalType
-                    || (data[1] & 0x80)) {
+                    || (data[1] & 0x80)
+                    || rtpTime != rtpTimeStartAt) {
                 ALOGV("Ignoring malformed FU buffer.");
 
                 // Delete the whole start of the FU.
 
-                it = queue->begin();
-                for (size_t i = 0; i <= totalCount; ++i) {
-                    it = queue->erase(it);
-                }
-
                 mNextExpectedSeqNo = expectedSeqNo + 1;
+                deleteUnitUnderSeq(queue, mNextExpectedSeqNo);
 
                 return MALFORMED_PACKET;
             }
@@ -260,9 +439,17 @@
             totalSize += size - 2;
             ++totalCount;
 
-            expectedSeqNo = expectedSeqNo + 1;
+            expectedSeqNo = (uint32_t)buffer->int32Data() + 1;
 
             if (data[1] & 0x40) {
+                if (pFrame && !recycleUnit(startSeqNo, expectedSeqNo,
+                            connected, totalCount, 0.5f)) {
+                    mNextExpectedSeqNo = expectedSeqNo;
+                    deleteUnitUnderSeq(queue, mNextExpectedSeqNo);
+
+                    return MALFORMED_PACKET;
+                }
+
                 // This is the last fragment.
                 complete = true;
                 break;
@@ -290,6 +477,8 @@
     unit->data()[0] = (nri << 5) | nalType;
 
     size_t offset = 1;
+    int32_t cvo = -1;
+    sp<ARTPSource> source = nullptr;
     List<sp<ABuffer> >::iterator it = queue->begin();
     for (size_t i = 0; i < totalCount; ++i) {
         const sp<ABuffer> &buffer = *it;
@@ -300,6 +489,9 @@
 #endif
 
         memcpy(unit->data() + offset, buffer->data() + 2, buffer->size() - 2);
+
+        buffer->meta()->findObject("source", (sp<android::RefBase>*)&source);
+        buffer->meta()->findInt32("cvo", &cvo);
         offset += buffer->size() - 2;
 
         it = queue->erase(it);
@@ -307,6 +499,13 @@
 
     unit->setRange(0, totalSize);
 
+    if (cvo >= 0) {
+        unit->meta()->setInt32("cvo", cvo);
+    }
+    if (source != nullptr) {
+        unit->meta()->setObject("source", source);
+    }
+
     addSingleNALUnit(unit);
 
     ALOGV("successfully assembled a NAL unit from fragments.");
@@ -317,7 +516,11 @@
 void AAVCAssembler::submitAccessUnit() {
     CHECK(!mNALUnits.empty());
 
-    ALOGV("Access unit complete (%zu nal units)", mNALUnits.size());
+    if(android::base::GetBoolProperty("debug.stagefright.fps", false)) {
+        ALOGD("Access unit complete (%zu nal units)", mNALUnits.size());
+    } else {
+        ALOGV("Access unit complete (%zu nal units)", mNALUnits.size());
+    }
 
     size_t totalSize = 0;
     for (List<sp<ABuffer> >::iterator it = mNALUnits.begin();
@@ -327,6 +530,7 @@
 
     sp<ABuffer> accessUnit = new ABuffer(totalSize);
     size_t offset = 0;
+    int32_t cvo = -1;
     for (List<sp<ABuffer> >::iterator it = mNALUnits.begin();
          it != mNALUnits.end(); ++it) {
         memcpy(accessUnit->data() + offset, "\x00\x00\x00\x01", 4);
@@ -335,6 +539,8 @@
         sp<ABuffer> nal = *it;
         memcpy(accessUnit->data() + offset, nal->data(), nal->size());
         offset += nal->size();
+
+        nal->meta()->findInt32("cvo", &cvo);
     }
 
     CopyTimes(accessUnit, *mNALUnits.begin());
@@ -343,6 +549,9 @@
     printf(mAccessUnitDamaged ? "X" : ".");
     fflush(stdout);
 #endif
+    if (cvo >= 0) {
+        accessUnit->meta()->setInt32("cvo", cvo);
+    }
 
     if (mAccessUnitDamaged) {
         accessUnit->meta()->setInt32("damaged", true);
@@ -356,22 +565,89 @@
     msg->post();
 }
 
+inline int64_t AAVCAssembler::findRTPTime(
+        const uint32_t& firstRTPTime, const sp<ABuffer>& buffer) {
+    /* If you want to +, -, * rtpTime, recommend to declare rtpTime as int64_t.
+       Because rtpTime can be near UINT32_MAX. Beware the overflow. */
+    int64_t rtpTime = 0;
+    CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
+    // If the first overs 2^31 and rtp unders 2^31, the rtp value is overflowed one.
+    int64_t overflowMask = (firstRTPTime & 0x80000000 & ~rtpTime) << 1;
+    return rtpTime | overflowMask;
+}
+
+int32_t AAVCAssembler::pickProperSeq(const Queue *queue,
+        uint32_t first, int64_t play, int64_t jit) {
+    sp<ABuffer> buffer = *(queue->begin());
+    int32_t nextSeqNo = buffer->int32Data();
+
+    Queue::const_iterator it = queue->begin();
+    while (it != queue->end()) {
+        int64_t rtpTime = findRTPTime(first, *it);
+        // if pkt in time exists, that should be the next pivot
+        if (rtpTime + jit >= play) {
+            nextSeqNo = (*it)->int32Data();
+            break;
+        }
+        it++;
+    }
+    return nextSeqNo;
+}
+
+bool AAVCAssembler::recycleUnit(uint32_t start, uint32_t end, uint32_t connected,
+        size_t avail, float goodRatio) {
+    float total = end - start;
+    float valid = connected;
+    float exist = avail;
+    bool isRecycle = (valid / total) >= goodRatio;
+
+    ALOGV("checking p-frame losses.. recvBufs %f valid %f diff %f recycle? %d",
+            exist, valid, total, isRecycle);
+
+    return isRecycle;
+}
+
+int32_t AAVCAssembler::deleteUnitUnderSeq(Queue *queue, uint32_t seq) {
+    int32_t initSize = queue->size();
+    Queue::iterator it = queue->begin();
+    while (it != queue->end()) {
+        if ((uint32_t)(*it)->int32Data() >= seq) {
+            break;
+        }
+        it++;
+    }
+    queue->erase(queue->begin(), it);
+    return initSize - queue->size();
+}
+
+inline void AAVCAssembler::printNowTimeUs(int64_t start, int64_t now, int64_t play) {
+    ALOGD("start=%lld, now=%lld, played=%lld",
+            (long long)start, (long long)now, (long long)play);
+}
+
+inline void AAVCAssembler::printRTPTime(int64_t rtp, int64_t play, int64_t exp, bool isExp) {
+    ALOGD("rtp-time(JB)=%lld, played-rtp-time(JB)=%lld, expired-rtp-time(JB)=%lld expired=%d",
+            (long long)rtp, (long long)play, (long long)exp, isExp);
+}
+
 ARTPAssembler::AssemblyStatus AAVCAssembler::assembleMore(
         const sp<ARTPSource> &source) {
     AssemblyStatus status = addNALUnit(source);
     if (status == MALFORMED_PACKET) {
-        mAccessUnitDamaged = true;
+        uint64_t msecsSinceLastIFrame = (ALooper::GetNowUs() / 1000) - mLastIFrameProvidedAtMs;
+        if (msecsSinceLastIFrame > 1000) {
+            ALOGV("request FIR to get a new I-Frame, time since "
+                    "last I-Frame %llu ms", (unsigned long long)msecsSinceLastIFrame);
+            source->onIssueFIRByAssembler();
+        }
     }
     return status;
 }
 
 void AAVCAssembler::packetLost() {
     CHECK(mNextExpectedSeqNoValid);
-    ALOGV("packetLost (expected %d)", mNextExpectedSeqNo);
-
+    ALOGD("packetLost (expected %u)", mNextExpectedSeqNo);
     ++mNextExpectedSeqNo;
-
-    mAccessUnitDamaged = true;
 }
 
 void AAVCAssembler::onByeReceived() {
diff --git a/media/libstagefright/rtsp/AAVCAssembler.h b/media/libstagefright/rtsp/AAVCAssembler.h
index e19480c..9d71e2f 100644
--- a/media/libstagefright/rtsp/AAVCAssembler.h
+++ b/media/libstagefright/rtsp/AAVCAssembler.h
@@ -31,6 +31,7 @@
 struct AAVCAssembler : public ARTPAssembler {
     explicit AAVCAssembler(const sp<AMessage> &notify);
 
+    typedef List<sp<ABuffer> > Queue;
 protected:
     virtual ~AAVCAssembler();
 
@@ -45,8 +46,16 @@
     bool mNextExpectedSeqNoValid;
     uint32_t mNextExpectedSeqNo;
     bool mAccessUnitDamaged;
+    bool mFirstIFrameProvided;
+    uint64_t mLastIFrameProvidedAtMs;
+    int32_t mWidth;
+    int32_t mHeight;
     List<sp<ABuffer> > mNALUnits;
 
+    int32_t addNack(const sp<ARTPSource> &source);
+    void checkSpsUpdated(const sp<ABuffer> &buffer);
+    void checkIFrameProvided(const sp<ABuffer> &buffer);
+    bool dropFramesUntilIframe(const sp<ABuffer> &buffer);
     AssemblyStatus addNALUnit(const sp<ARTPSource> &source);
     void addSingleNALUnit(const sp<ABuffer> &buffer);
     AssemblyStatus addFragmentedNALUnit(List<sp<ABuffer> > *queue);
@@ -54,6 +63,14 @@
 
     void submitAccessUnit();
 
+    inline int64_t findRTPTime(const uint32_t& firstRTPTime, const sp<ABuffer>& buffer);
+    int32_t pickProperSeq(const Queue *q, uint32_t first, int64_t play, int64_t jit);
+    bool recycleUnit(uint32_t start, uint32_t end, uint32_t connected,
+            size_t avail, float goodRatio);
+    int32_t deleteUnitUnderSeq(Queue *q, uint32_t seq);
+    void printNowTimeUs(int64_t start, int64_t now, int64_t play);
+    void printRTPTime(int64_t rtp, int64_t play, int64_t exp, bool isExp);
+
     DISALLOW_EVIL_CONSTRUCTORS(AAVCAssembler);
 };
 
diff --git a/media/libstagefright/rtsp/AHEVCAssembler.cpp b/media/libstagefright/rtsp/AHEVCAssembler.cpp
new file mode 100644
index 0000000..553ea08
--- /dev/null
+++ b/media/libstagefright/rtsp/AHEVCAssembler.cpp
@@ -0,0 +1,673 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "AHEVCAssembler"
+#include <utils/Log.h>
+
+#include "AHEVCAssembler.h"
+
+#include "ARTPSource.h"
+
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/foundation/AMessage.h>
+#include <include/HevcUtils.h>
+#include <media/stagefright/foundation/hexdump.h>
+
+#include <stdint.h>
+
+#define H265_NALU_MASK 0x3F
+#define H265_NALU_VPS 0x20
+#define H265_NALU_SPS 0x21
+#define H265_NALU_PPS 0x22
+#define H265_NALU_AP 0x30
+#define H265_NALU_FU 0x31
+#define H265_NALU_PACI 0x32
+
+
+namespace android {
+
+// static
+AHEVCAssembler::AHEVCAssembler(const sp<AMessage> &notify)
+    : mNotifyMsg(notify),
+      mAccessUnitRTPTime(0),
+      mNextExpectedSeqNoValid(false),
+      mNextExpectedSeqNo(0),
+      mAccessUnitDamaged(false),
+      mFirstIFrameProvided(false),
+      mLastIFrameProvidedAtMs(0),
+      mWidth(0),
+      mHeight(0) {
+
+      ALOGV("Constructor");
+}
+
+AHEVCAssembler::~AHEVCAssembler() {
+}
+
+int32_t AHEVCAssembler::addNack(
+        const sp<ARTPSource> &source) {
+    List<sp<ABuffer>> *queue = source->queue();
+    int32_t nackCount = 0;
+
+    List<sp<ABuffer> >::iterator it = queue->begin();
+
+    if (it == queue->end()) {
+        return nackCount /* 0 */;
+    }
+
+    uint16_t queueHeadSeqNum = (*it)->int32Data();
+
+    // move to the packet after which RTCP:NACK was sent.
+    for (; it != queue->end(); ++it) {
+        int32_t seqNum = (*it)->int32Data();
+        if (seqNum >= source->mHighestNackNumber) {
+            break;
+        }
+    }
+
+    int32_t nackStartAt = -1;
+
+    while (it != queue->end()) {
+        int32_t seqBeforeLast = (*it)->int32Data();
+        // increase iterator.
+        if ((++it) == queue->end()) {
+            break;
+        }
+
+        int32_t seqLast = (*it)->int32Data();
+
+        if ((seqLast - seqBeforeLast) < 0) {
+            ALOGD("addNack: found end of seqNum from(%d) to(%d)", seqBeforeLast, seqLast);
+            source->mHighestNackNumber = 0;
+        }
+
+        // missed packet found
+        if (seqLast > (seqBeforeLast + 1) &&
+            // we didn't send RTCP:NACK for this packet yet.
+            (seqLast - 1) > source->mHighestNackNumber) {
+            source->mHighestNackNumber = seqLast -1;
+            nackStartAt = seqBeforeLast + 1;
+            break;
+        }
+
+    }
+
+    if (nackStartAt != -1) {
+        nackCount = source->mHighestNackNumber - nackStartAt + 1;
+        ALOGD("addNack: nackCount=%d, nackFrom=%d, nackTo=%d", nackCount,
+            nackStartAt, source->mHighestNackNumber);
+
+        uint16_t mask = (uint16_t)(0xffff) >> (16 - nackCount + 1);
+        source->setSeqNumToNACK(nackStartAt, mask, queueHeadSeqNum);
+    }
+
+    return nackCount;
+}
+
+ARTPAssembler::AssemblyStatus AHEVCAssembler::addNALUnit(
+        const sp<ARTPSource> &source) {
+    List<sp<ABuffer> > *queue = source->queue();
+    const uint32_t firstRTPTime = source->mFirstRtpTime;
+
+    if (queue->empty()) {
+        return NOT_ENOUGH_DATA;
+    }
+
+    sp<ABuffer> buffer = *queue->begin();
+    buffer->meta()->setObject("source", source);
+    int64_t rtpTime = findRTPTime(firstRTPTime, buffer);
+
+    int64_t startTime = source->mFirstSysTime / 1000;
+    int64_t nowTime = ALooper::GetNowUs() / 1000;
+    int64_t playedTime = nowTime - startTime;
+    int64_t playedTimeRtp = source->mFirstRtpTime + playedTime * (int64_t)source->mClockRate / 1000;
+    const int64_t jitterTime = source->mJbTimeMs * (int64_t)source->mClockRate / 1000;
+
+    int64_t expiredTimeInJb = rtpTime + jitterTime;
+    bool isExpired = expiredTimeInJb <= (playedTimeRtp);
+    bool isTooLate200 = expiredTimeInJb < (playedTimeRtp - jitterTime);
+    bool isTooLate300 = expiredTimeInJb < (playedTimeRtp - (jitterTime * 3 / 2));
+
+    if (mShowQueueCnt < 20) {
+        showCurrentQueue(queue);
+        printNowTimeUs(startTime, nowTime, playedTime);
+        printRTPTime(rtpTime, playedTimeRtp, expiredTimeInJb, isExpired);
+        mShowQueueCnt++;
+    }
+
+    AHEVCAssembler::addNack(source);
+
+    if (!isExpired) {
+        ALOGV("buffering in jitter buffer.");
+        return NOT_ENOUGH_DATA;
+    }
+
+    if (isTooLate200) {
+        ALOGW("=== WARNING === buffer arrived 200ms late. === WARNING === ");
+    }
+
+    if (isTooLate300) {
+        ALOGW("buffer arrived after 300ms ... \t Diff in Jb=%lld \t Seq# %d",
+                (long long)(playedTimeRtp - expiredTimeInJb), buffer->int32Data());
+        printNowTimeUs(startTime, nowTime, playedTime);
+        printRTPTime(rtpTime, playedTimeRtp, expiredTimeInJb, isExpired);
+
+        mNextExpectedSeqNo = pickProperSeq(queue, firstRTPTime, playedTimeRtp, jitterTime);
+    }
+
+    if (mNextExpectedSeqNoValid) {
+        int32_t size = queue->size();
+        int32_t cntRemove = deleteUnitUnderSeq(queue, mNextExpectedSeqNo);
+
+        if (cntRemove > 0) {
+            source->noticeAbandonBuffer(cntRemove);
+            ALOGW("delete %d of %d buffers", cntRemove, size);
+        }
+
+        if (queue->empty()) {
+            return NOT_ENOUGH_DATA;
+        }
+    }
+
+    buffer = *queue->begin();
+
+    if (!mNextExpectedSeqNoValid) {
+        mNextExpectedSeqNoValid = true;
+        mNextExpectedSeqNo = (uint32_t)buffer->int32Data();
+    } else if ((uint32_t)buffer->int32Data() != mNextExpectedSeqNo) {
+        ALOGV("Not the sequence number I expected");
+
+        return WRONG_SEQUENCE_NUMBER;
+    }
+
+    const uint8_t *data = buffer->data();
+    size_t size = buffer->size();
+
+    if (size < 1 || (data[0] & 0x80)) {
+        // Corrupt.
+
+        ALOGV("Ignoring corrupt buffer.");
+        queue->erase(queue->begin());
+
+        ++mNextExpectedSeqNo;
+        return MALFORMED_PACKET;
+    }
+
+    unsigned nalType = (data[0] >> 1) & H265_NALU_MASK;
+    if (nalType > 0 && nalType < H265_NALU_AP) {
+        addSingleNALUnit(buffer);
+        queue->erase(queue->begin());
+        ++mNextExpectedSeqNo;
+        return OK;
+    } else if (nalType == H265_NALU_FU) {
+        // FU-A
+        return addFragmentedNALUnit(queue);
+    } else if (nalType == H265_NALU_AP) {
+        // STAP-A
+        bool success = addSingleTimeAggregationPacket(buffer);
+        queue->erase(queue->begin());
+        ++mNextExpectedSeqNo;
+
+        return success ? OK : MALFORMED_PACKET;
+    } else if (nalType == 0) {
+        ALOGV("Ignoring undefined nal type.");
+
+        queue->erase(queue->begin());
+        ++mNextExpectedSeqNo;
+
+        return OK;
+    } else {
+        ALOGV("Ignoring unsupported buffer (nalType=%d)", nalType);
+
+        queue->erase(queue->begin());
+        ++mNextExpectedSeqNo;
+
+        return MALFORMED_PACKET;
+    }
+}
+
+void AHEVCAssembler::checkSpsUpdated(const sp<ABuffer> &buffer) {
+    if (buffer->size() == 0) {
+        return;
+    }
+    const uint8_t *data = buffer->data();
+    HevcParameterSets paramSets;
+    unsigned nalType = (data[0] >> 1) & H265_NALU_MASK;
+    if (nalType == H265_NALU_SPS) {
+        int32_t width = 0, height = 0;
+        paramSets.FindHEVCDimensions(buffer, &width, &height);
+        ALOGV("existing resolution (%u x %u)", mWidth, mHeight);
+        if (width != mWidth || height != mHeight) {
+            mFirstIFrameProvided = false;
+            mWidth = width;
+            mHeight = height;
+            ALOGD("found a new resolution (%u x %u)", mWidth, mHeight);
+        }
+    }
+}
+
+void AHEVCAssembler::checkIFrameProvided(const sp<ABuffer> &buffer) {
+    if (buffer->size() == 0) {
+        return;
+    }
+    const uint8_t *data = buffer->data();
+    unsigned nalType = (data[0] >> 1) & H265_NALU_MASK;
+    if (nalType > 0x0F && nalType < 0x18) {
+        mLastIFrameProvidedAtMs = ALooper::GetNowUs() / 1000;
+        if (!mFirstIFrameProvided) {
+            mFirstIFrameProvided = true;
+            uint32_t rtpTime;
+            CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
+            ALOGD("got First I-frame to be decoded. rtpTime=%d, size=%zu", rtpTime, buffer->size());
+        }
+    }
+}
+
+bool AHEVCAssembler::dropFramesUntilIframe(const sp<ABuffer> &buffer) {
+    if (buffer->size() == 0) {
+        return false;
+    }
+    const uint8_t *data = buffer->data();
+    unsigned nalType = (data[0] >> 1) & H265_NALU_MASK;
+    return !mFirstIFrameProvided && nalType < 0x10;
+}
+
+void AHEVCAssembler::addSingleNALUnit(const sp<ABuffer> &buffer) {
+    ALOGV("addSingleNALUnit of size %zu", buffer->size());
+#if !LOG_NDEBUG
+    hexdump(buffer->data(), buffer->size());
+#endif
+    checkSpsUpdated(buffer);
+    checkIFrameProvided(buffer);
+
+    uint32_t rtpTime;
+    CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
+
+    if (dropFramesUntilIframe(buffer)) {
+        sp<ARTPSource> source = nullptr;
+        buffer->meta()->findObject("source", (sp<android::RefBase>*)&source);
+        if (source != nullptr) {
+            ALOGD("Issued FIR to get the I-frame");
+            source->onIssueFIRByAssembler();
+        }
+        ALOGD("drop P-frames till an I-frame provided. rtpTime %u", rtpTime);
+        return;
+    }
+
+    if (!mNALUnits.empty() && rtpTime != mAccessUnitRTPTime) {
+        submitAccessUnit();
+    }
+    mAccessUnitRTPTime = rtpTime;
+
+    mNALUnits.push_back(buffer);
+}
+
+bool AHEVCAssembler::addSingleTimeAggregationPacket(const sp<ABuffer> &buffer) {
+    const uint8_t *data = buffer->data();
+    size_t size = buffer->size();
+
+    if (size < 3) {
+        ALOGV("Discarding too small STAP-A packet.");
+        return false;
+    }
+
+    ++data;
+    --size;
+    while (size >= 2) {
+        size_t nalSize = (data[0] << 8) | data[1];
+
+        if (size < nalSize + 2) {
+            ALOGV("Discarding malformed STAP-A packet.");
+            return false;
+        }
+
+        sp<ABuffer> unit = new ABuffer(nalSize);
+        memcpy(unit->data(), &data[2], nalSize);
+
+        CopyTimes(unit, buffer);
+
+        addSingleNALUnit(unit);
+
+        data += 2 + nalSize;
+        size -= 2 + nalSize;
+    }
+
+    if (size != 0) {
+        ALOGV("Unexpected padding at end of STAP-A packet.");
+    }
+
+    return true;
+}
+
+ARTPAssembler::AssemblyStatus AHEVCAssembler::addFragmentedNALUnit(
+        List<sp<ABuffer> > *queue) {
+    CHECK(!queue->empty());
+
+    sp<ABuffer> buffer = *queue->begin();
+    const uint8_t *data = buffer->data();
+    size_t size = buffer->size();
+
+    CHECK(size > 0);
+    /*   H265 payload header is 16 bit
+        0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+       |F|     Type  |  Layer ID | TID |
+       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+     */
+    unsigned indicator = (data[0] >> 1);
+
+    CHECK((indicator & H265_NALU_MASK) == H265_NALU_FU);
+
+    if (size < 3) {
+        ALOGV("Ignoring malformed FU buffer (size = %zu)", size);
+
+        queue->erase(queue->begin());
+        ++mNextExpectedSeqNo;
+        return MALFORMED_PACKET;
+    }
+
+    if (!(data[2] & 0x80)) {
+        // Start bit not set on the first buffer.
+
+        ALOGV("Start bit not set on first buffer");
+
+        queue->erase(queue->begin());
+        ++mNextExpectedSeqNo;
+        return MALFORMED_PACKET;
+    }
+
+    /*  FU INDICATOR HDR
+        0 1 2 3 4 5 6 7
+       +-+-+-+-+-+-+-+-+
+       |S|E|   Type    |
+       +-+-+-+-+-+-+-+-+
+     */
+    uint32_t nalType = data[2] & H265_NALU_MASK;
+    uint32_t tid = data[1] & 0x7;
+    ALOGV("nalType =%u, tid =%u", nalType, tid);
+
+    uint32_t expectedSeqNo = (uint32_t)buffer->int32Data() + 1;
+    size_t totalSize = size - 3;
+    size_t totalCount = 1;
+    bool complete = false;
+
+    uint32_t rtpTimeStartAt;
+    CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTimeStartAt));
+    uint32_t startSeqNo = buffer->int32Data();
+    bool pFrame = (nalType < 0x10);
+
+    if (data[2] & 0x40) {
+        // Huh? End bit also set on the first buffer.
+
+        ALOGV("Grrr. This isn't fragmented at all.");
+
+        complete = true;
+    } else {
+        List<sp<ABuffer> >::iterator it = ++queue->begin();
+        int32_t connected = 1;
+        bool snapped = false;
+        while (it != queue->end()) {
+            ALOGV("sequence length %zu", totalCount);
+
+            const sp<ABuffer> &buffer = *it;
+
+            const uint8_t *data = buffer->data();
+            size_t size = buffer->size();
+
+            if ((uint32_t)buffer->int32Data() != expectedSeqNo) {
+                ALOGV("sequence not complete, expected seqNo %u, got %u, nalType %u",
+                     expectedSeqNo, (uint32_t)buffer->int32Data(), nalType);
+                snapped = true;
+
+                if (!pFrame) {
+                    return WRONG_SEQUENCE_NUMBER;
+                }
+            }
+
+            if (!snapped) {
+                connected++;
+            }
+
+            uint32_t rtpTime;
+            CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
+            if (size < 3
+                    || ((data[0] >> 1) & H265_NALU_MASK) != indicator
+                    || (data[2] & H265_NALU_MASK) != nalType
+                    || (data[2] & 0x80)
+                    || rtpTime != rtpTimeStartAt) {
+                ALOGV("Ignoring malformed FU buffer.");
+
+                // Delete the whole start of the FU.
+
+                mNextExpectedSeqNo = expectedSeqNo + 1;
+                deleteUnitUnderSeq(queue, mNextExpectedSeqNo);
+
+                return MALFORMED_PACKET;
+            }
+
+            totalSize += size - 3;
+            ++totalCount;
+
+            expectedSeqNo = (uint32_t)buffer->int32Data() + 1;
+
+            if (data[2] & 0x40) {
+                if (pFrame && !recycleUnit(startSeqNo, expectedSeqNo,
+                        connected, totalCount, 0.5f)) {
+                    mNextExpectedSeqNo = expectedSeqNo;
+                    deleteUnitUnderSeq(queue, mNextExpectedSeqNo);
+
+                    return MALFORMED_PACKET;
+                }
+                // This is the last fragment.
+                complete = true;
+                break;
+            }
+
+            ++it;
+        }
+    }
+
+    if (!complete) {
+        return NOT_ENOUGH_DATA;
+    }
+
+    mNextExpectedSeqNo = expectedSeqNo;
+
+    // We found all the fragments that make up the complete NAL unit.
+
+    // Leave room for the header. So far totalSize did not include the
+    // header byte.
+    totalSize += 2;
+
+    sp<ABuffer> unit = new ABuffer(totalSize);
+    CopyTimes(unit, *queue->begin());
+
+    unit->data()[0] = (nalType << 1);
+    unit->data()[1] = tid;
+
+    size_t offset = 2;
+    int32_t cvo = -1;
+    List<sp<ABuffer> >::iterator it = queue->begin();
+    for (size_t i = 0; i < totalCount; ++i) {
+        const sp<ABuffer> &buffer = *it;
+
+        ALOGV("piece #%zu/%zu", i + 1, totalCount);
+#if !LOG_NDEBUG
+        hexdump(buffer->data(), buffer->size());
+#endif
+
+        memcpy(unit->data() + offset, buffer->data() + 3, buffer->size() - 3);
+        buffer->meta()->findInt32("cvo", &cvo);
+        offset += buffer->size() - 3;
+
+        it = queue->erase(it);
+    }
+
+    unit->setRange(0, totalSize);
+
+    if (cvo >= 0) {
+        unit->meta()->setInt32("cvo", cvo);
+    }
+
+    addSingleNALUnit(unit);
+
+    ALOGV("successfully assembled a NAL unit from fragments.");
+
+    return OK;
+}
+
+void AHEVCAssembler::submitAccessUnit() {
+    CHECK(!mNALUnits.empty());
+
+    ALOGV("Access unit complete (%zu nal units)", mNALUnits.size());
+
+    size_t totalSize = 0;
+    for (List<sp<ABuffer> >::iterator it = mNALUnits.begin();
+         it != mNALUnits.end(); ++it) {
+        totalSize += 4 + (*it)->size();
+    }
+
+    sp<ABuffer> accessUnit = new ABuffer(totalSize);
+    size_t offset = 0;
+    int32_t cvo = -1;
+    for (List<sp<ABuffer> >::iterator it = mNALUnits.begin();
+         it != mNALUnits.end(); ++it) {
+        memcpy(accessUnit->data() + offset, "\x00\x00\x00\x01", 4);
+        offset += 4;
+
+        sp<ABuffer> nal = *it;
+        memcpy(accessUnit->data() + offset, nal->data(), nal->size());
+        offset += nal->size();
+        nal->meta()->findInt32("cvo", &cvo);
+    }
+
+    CopyTimes(accessUnit, *mNALUnits.begin());
+
+#if 0
+    printf(mAccessUnitDamaged ? "X" : ".");
+    fflush(stdout);
+#endif
+    if (cvo >= 0) {
+        accessUnit->meta()->setInt32("cvo", cvo);
+    }
+
+    if (mAccessUnitDamaged) {
+        accessUnit->meta()->setInt32("damaged", true);
+    }
+
+    mNALUnits.clear();
+    mAccessUnitDamaged = false;
+
+    sp<AMessage> msg = mNotifyMsg->dup();
+    msg->setBuffer("access-unit", accessUnit);
+    msg->post();
+}
+
+inline int64_t AHEVCAssembler::findRTPTime(
+        const uint32_t& firstRTPTime, const sp<ABuffer>& buffer) {
+    /* If you want to +, -, * rtpTime, recommend to declare rtpTime as int64_t.
+       Because rtpTime can be near UINT32_MAX. Beware the overflow. */
+    int64_t rtpTime = 0;
+    CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
+    // If the first overs 2^31 and rtp unders 2^31, the rtp value is overflowed one.
+    int64_t overflowMask = (firstRTPTime & 0x80000000 & ~rtpTime) << 1;
+    return rtpTime | overflowMask;
+}
+
+int32_t AHEVCAssembler::pickProperSeq(const Queue *queue,
+        uint32_t first, int64_t play, int64_t jit) {
+    sp<ABuffer> buffer = *(queue->begin());
+    int32_t nextSeqNo = buffer->int32Data();
+
+    Queue::const_iterator it = queue->begin();
+    while (it != queue->end()) {
+        int64_t rtpTime = findRTPTime(first, *it);
+        // if pkt in time exists, that should be the next pivot
+        if (rtpTime + jit >= play) {
+            nextSeqNo = (*it)->int32Data();
+            break;
+        }
+        it++;
+    }
+    return nextSeqNo;
+}
+
+bool AHEVCAssembler::recycleUnit(uint32_t start, uint32_t end,  uint32_t connected,
+         size_t avail, float goodRatio) {
+    float total = end - start;
+    float valid = connected;
+    float exist = avail;
+    bool isRecycle = (valid / total) >= goodRatio;
+
+    ALOGV("checking p-frame losses.. recvBufs %f valid %f diff %f recycle? %d",
+            exist, valid, total, isRecycle);
+
+    return isRecycle;
+}
+
+int32_t AHEVCAssembler::deleteUnitUnderSeq(Queue *queue, uint32_t seq) {
+    int32_t initSize = queue->size();
+    Queue::iterator it = queue->begin();
+    while (it != queue->end()) {
+        if ((uint32_t)(*it)->int32Data() >= seq) {
+            break;
+        }
+        it++;
+    }
+    queue->erase(queue->begin(), it);
+    return initSize - queue->size();
+}
+
+inline void AHEVCAssembler::printNowTimeUs(int64_t start, int64_t now, int64_t play) {
+    ALOGD("start=%lld, now=%lld, played=%lld",
+            (long long)start, (long long)now, (long long)play);
+}
+
+inline void AHEVCAssembler::printRTPTime(int64_t rtp, int64_t play, int64_t exp, bool isExp) {
+    ALOGD("rtp-time(JB)=%lld, played-rtp-time(JB)=%lld, expired-rtp-time(JB)=%lld expired=%d",
+            (long long)rtp, (long long)play, (long long)exp, isExp);
+}
+
+ARTPAssembler::AssemblyStatus AHEVCAssembler::assembleMore(
+        const sp<ARTPSource> &source) {
+    AssemblyStatus status = addNALUnit(source);
+    if (status == MALFORMED_PACKET) {
+        uint64_t msecsSinceLastIFrame = (ALooper::GetNowUs() / 1000) - mLastIFrameProvidedAtMs;
+        if (msecsSinceLastIFrame > 1000) {
+            ALOGV("request FIR to get a new I-Frame, time after "
+                    "last I-Frame in %llu ms", (unsigned long long)msecsSinceLastIFrame);
+            source->onIssueFIRByAssembler();
+        }
+    }
+    return status;
+}
+
+void AHEVCAssembler::packetLost() {
+    CHECK(mNextExpectedSeqNoValid);
+    ALOGD("packetLost (expected %u)", mNextExpectedSeqNo);
+
+    ++mNextExpectedSeqNo;
+}
+
+void AHEVCAssembler::onByeReceived() {
+    sp<AMessage> msg = mNotifyMsg->dup();
+    msg->setInt32("eos", true);
+    msg->post();
+}
+
+}  // namespace android
diff --git a/media/libstagefright/rtsp/AHEVCAssembler.h b/media/libstagefright/rtsp/AHEVCAssembler.h
new file mode 100644
index 0000000..bf1cded
--- /dev/null
+++ b/media/libstagefright/rtsp/AHEVCAssembler.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef A_HEVC_ASSEMBLER_H_
+
+#define A_HEVC_ASSEMBLER_H_
+
+#include "ARTPAssembler.h"
+
+#include <utils/List.h>
+#include <utils/RefBase.h>
+
+namespace android {
+
+struct ABuffer;
+struct AMessage;
+
+struct AHEVCAssembler : public ARTPAssembler {
+    AHEVCAssembler(const sp<AMessage> &notify);
+
+    typedef List<sp<ABuffer> > Queue;
+
+protected:
+    virtual ~AHEVCAssembler();
+
+    virtual AssemblyStatus assembleMore(const sp<ARTPSource> &source);
+    virtual void onByeReceived();
+    virtual void packetLost();
+
+private:
+    sp<AMessage> mNotifyMsg;
+
+    uint32_t mAccessUnitRTPTime;
+    bool mNextExpectedSeqNoValid;
+    uint32_t mNextExpectedSeqNo;
+    bool mAccessUnitDamaged;
+    bool mFirstIFrameProvided;
+    uint64_t mLastIFrameProvidedAtMs;
+    int32_t mWidth;
+    int32_t mHeight;
+    List<sp<ABuffer> > mNALUnits;
+
+    int32_t addNack(const sp<ARTPSource> &source);
+    void checkSpsUpdated(const sp<ABuffer> &buffer);
+    void checkIFrameProvided(const sp<ABuffer> &buffer);
+    bool dropFramesUntilIframe(const sp<ABuffer> &buffer);
+    AssemblyStatus addNALUnit(const sp<ARTPSource> &source);
+    void addSingleNALUnit(const sp<ABuffer> &buffer);
+    AssemblyStatus addFragmentedNALUnit(List<sp<ABuffer> > *queue);
+    bool addSingleTimeAggregationPacket(const sp<ABuffer> &buffer);
+
+    void submitAccessUnit();
+
+    inline int64_t findRTPTime(const uint32_t& firstRTPTime, const sp<ABuffer>& buffer);
+    int32_t pickProperSeq(const Queue *q, uint32_t first, int64_t play, int64_t jit);
+    bool recycleUnit(uint32_t start, uint32_t end, uint32_t connected,
+             size_t avail, float goodRatio);
+    int32_t deleteUnitUnderSeq(Queue *queue, uint32_t seq);
+    void printNowTimeUs(int64_t start, int64_t now, int64_t play);
+    void printRTPTime(int64_t rtp, int64_t play, int64_t exp, bool isExp);
+
+    DISALLOW_EVIL_CONSTRUCTORS(AHEVCAssembler);
+};
+
+}  // namespace android
+
+#endif  // A_HEVC_ASSEMBLER_H_
diff --git a/media/libstagefright/rtsp/APacketSource.cpp b/media/libstagefright/rtsp/APacketSource.cpp
index 574bd7a..8f4df8e 100644
--- a/media/libstagefright/rtsp/APacketSource.cpp
+++ b/media/libstagefright/rtsp/APacketSource.cpp
@@ -454,6 +454,17 @@
 
         mFormat->setInt32(kKeyWidth, width);
         mFormat->setInt32(kKeyHeight, height);
+    } else if (!strncmp(desc.c_str(), "H265/", 5)) {
+        mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_HEVC);
+
+        int32_t width, height;
+        if (!sessionDesc->getDimensions(index, PT, &width, &height)) {
+            width = -1;
+            height = -1;
+        }
+
+        mFormat->setInt32(kKeyWidth, width);
+        mFormat->setInt32(kKeyHeight, height);
     } else if (!strncmp(desc.c_str(), "H263-2000/", 10)
             || !strncmp(desc.c_str(), "H263-1998/", 10)) {
         mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
diff --git a/media/libstagefright/rtsp/ARTPAssembler.cpp b/media/libstagefright/rtsp/ARTPAssembler.cpp
index befc226..52aa3a0 100644
--- a/media/libstagefright/rtsp/ARTPAssembler.cpp
+++ b/media/libstagefright/rtsp/ARTPAssembler.cpp
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "ARTPAssembler"
 #include "ARTPAssembler.h"
 
 #include <media/stagefright/foundation/ABuffer.h>
@@ -21,12 +22,16 @@
 #include <media/stagefright/foundation/ALooper.h>
 #include <media/stagefright/foundation/AMessage.h>
 
+#include <android-base/properties.h>
+
 #include <stdint.h>
 
 namespace android {
 
 ARTPAssembler::ARTPAssembler()
-    : mFirstFailureTimeUs(-1) {
+    : mShowQueueCnt(0),
+      mFirstFailureTimeUs(-1) {
+    mShowQueue = android::base::GetBoolProperty("debug.stagefright.rtp", false);
 }
 
 void ARTPAssembler::onPacketReceived(const sp<ARTPSource> &source) {
@@ -141,4 +146,15 @@
     return accessUnit;
 }
 
+void ARTPAssembler::showCurrentQueue(List<sp<ABuffer> > *queue) {
+    AString temp("Queue elem size : ");
+    List<sp<ABuffer> >::iterator it = queue->begin();
+    while (it != queue->end()) {
+        temp.append((*it)->size());
+        temp.append("  \t");
+        it++;
+    }
+    ALOGD("%s",temp.c_str());
+};
+
 }  // namespace android
diff --git a/media/libstagefright/rtsp/ARTPAssembler.h b/media/libstagefright/rtsp/ARTPAssembler.h
index 4082d4c..191f08e 100644
--- a/media/libstagefright/rtsp/ARTPAssembler.h
+++ b/media/libstagefright/rtsp/ARTPAssembler.h
@@ -56,6 +56,11 @@
     static sp<ABuffer> MakeCompoundFromPackets(
             const List<sp<ABuffer> > &frames);
 
+    void showCurrentQueue(List<sp<ABuffer> > *queue);
+
+    bool mShowQueue;
+    int32_t mShowQueueCnt;
+
 private:
     int64_t mFirstFailureTimeUs;
 
diff --git a/media/libstagefright/rtsp/ARTPConnection.cpp b/media/libstagefright/rtsp/ARTPConnection.cpp
index 6a4706d..61c06d1 100644
--- a/media/libstagefright/rtsp/ARTPConnection.cpp
+++ b/media/libstagefright/rtsp/ARTPConnection.cpp
@@ -30,6 +30,8 @@
 #include <media/stagefright/foundation/AString.h>
 #include <media/stagefright/foundation/hexdump.h>
 
+#include <android/multinetwork.h>
+
 #include <arpa/inet.h>
 #include <sys/socket.h>
 
@@ -53,6 +55,7 @@
 const int64_t ARTPConnection::kSelectTimeoutUs = 1000LL;
 
 struct ARTPConnection::StreamInfo {
+    bool isIPv6;
     int mRTPSocket;
     int mRTCPSocket;
     sp<ASessionDescription> mSessionDesc;
@@ -63,14 +66,21 @@
     int64_t mNumRTCPPacketsReceived;
     int64_t mNumRTPPacketsReceived;
     struct sockaddr_in mRemoteRTCPAddr;
+    struct sockaddr_in6 mRemoteRTCPAddr6;
 
     bool mIsInjected;
+
+    // RTCP Extension for CVO
+    int mCVOExtMap; // will be set to 0 if cvo is not negotiated in sdp
 };
 
 ARTPConnection::ARTPConnection(uint32_t flags)
     : mFlags(flags),
       mPollEventPending(false),
-      mLastReceiverReportTimeUs(-1) {
+      mLastReceiverReportTimeUs(-1),
+      mLastBitrateReportTimeUs(-1),
+      mTargetBitrate(-1),
+      mJbTimeMs(300) {
 }
 
 ARTPConnection::~ARTPConnection() {
@@ -121,7 +131,7 @@
     unsigned start = (unsigned)((rand()* 1000LL)/RAND_MAX) + 15550;
     start &= ~1;
 
-    for (unsigned port = start; port < 65536; port += 2) {
+    for (unsigned port = start; port < 65535; port += 2) {
         struct sockaddr_in addr;
         memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
         addr.sin_family = AF_INET;
@@ -139,12 +149,130 @@
                  (const struct sockaddr *)&addr, sizeof(addr)) == 0) {
             *rtpPort = port;
             return;
+        } else {
+            // we should recreate a RTP socket to avoid bind other port in same RTP socket
+            close(*rtpSocket);
+
+            *rtpSocket = socket(AF_INET, SOCK_DGRAM, 0);
+            CHECK_GE(*rtpSocket, 0);
+            bumpSocketBufferSize(*rtpSocket);
         }
     }
 
     TRESPASS();
 }
 
+// static
+void ARTPConnection::MakeRTPSocketPair(
+        int *rtpSocket, int *rtcpSocket, const char *localIp, const char *remoteIp,
+        unsigned localPort, unsigned remotePort, int64_t socketNetwork) {
+    bool isIPv6 = false;
+    if (strchr(localIp, ':') != NULL)
+        isIPv6 = true;
+
+    *rtpSocket = socket(isIPv6 ? AF_INET6 : AF_INET, SOCK_DGRAM, 0);
+    CHECK_GE(*rtpSocket, 0);
+
+    bumpSocketBufferSize(*rtpSocket);
+
+    *rtcpSocket = socket(isIPv6 ? AF_INET6 : AF_INET, SOCK_DGRAM, 0);
+    CHECK_GE(*rtcpSocket, 0);
+
+    if (socketNetwork != 0) {
+        ALOGD("trying to bind rtp socket(%d) to network(%llu).",
+                *rtpSocket, (unsigned long long)socketNetwork);
+
+        int result = android_setsocknetwork((net_handle_t)socketNetwork, *rtpSocket);
+        if (result != 0) {
+            ALOGW("failed(%d) to bind rtp socket(%d) to network(%llu)",
+                    result, *rtpSocket, (unsigned long long)socketNetwork);
+        }
+        result = android_setsocknetwork((net_handle_t)socketNetwork, *rtcpSocket);
+        if (result != 0) {
+            ALOGW("failed(%d) to bind rtcp socket(%d) to network(%llu)",
+                    result, *rtcpSocket, (unsigned long long)socketNetwork);
+        }
+    }
+
+    bumpSocketBufferSize(*rtcpSocket);
+
+    struct sockaddr *addr;
+    struct sockaddr_in addr4;
+    struct sockaddr_in6 addr6;
+
+    if (isIPv6) {
+        addr = (struct sockaddr *)&addr6;
+        memset(&addr6, 0, sizeof(addr6));
+        addr6.sin6_family = AF_INET6;
+        inet_pton(AF_INET6, localIp, &addr6.sin6_addr);
+        addr6.sin6_port = htons((uint16_t)localPort);
+    } else {
+        addr = (struct sockaddr *)&addr4;
+        memset(&addr4, 0, sizeof(addr4));
+        addr4.sin_family = AF_INET;
+        addr4.sin_addr.s_addr = inet_addr(localIp);
+        addr4.sin_port = htons((uint16_t)localPort);
+    }
+
+    int sockopt = 1;
+    setsockopt(*rtpSocket, SOL_SOCKET, SO_REUSEADDR, (int *)&sockopt, sizeof(sockopt));
+    setsockopt(*rtcpSocket, SOL_SOCKET, SO_REUSEADDR, (int *)&sockopt, sizeof(sockopt));
+
+    int sizeSockSt = isIPv6 ? sizeof(addr6) : sizeof(addr4);
+
+    if (bind(*rtpSocket, addr, sizeSockSt) == 0) {
+        ALOGI("rtp socket successfully binded. addr=%s:%d", localIp, localPort);
+    } else {
+        ALOGE("failed to bind rtp socket addr=%s:%d err=%s", localIp, localPort, strerror(errno));
+        return;
+    }
+
+    if (isIPv6)
+        addr6.sin6_port = htons(localPort + 1);
+    else
+        addr4.sin_port = htons(localPort + 1);
+
+    if (bind(*rtcpSocket, addr, sizeSockSt) == 0) {
+        ALOGI("rtcp socket successfully binded. addr=%s:%d", localIp, localPort + 1);
+    } else {
+        ALOGE("failed to bind rtcp socket addr=%s:%d err=%s", localIp,
+                localPort + 1, strerror(errno));
+    }
+
+    // Re uses addr variable as remote addr.
+    if (isIPv6) {
+        memset(&addr6, 0, sizeof(addr6));
+        addr6.sin6_family = AF_INET6;
+        inet_pton(AF_INET6, remoteIp, &addr6.sin6_addr);
+        addr6.sin6_port = htons((uint16_t)remotePort);
+    } else {
+        memset(&addr4, 0, sizeof(addr4));
+        addr4.sin_family = AF_INET;
+        addr4.sin_addr.s_addr = inet_addr(remoteIp);
+        addr4.sin_port = htons((uint16_t)remotePort);
+    }
+    if (connect(*rtpSocket, addr, sizeSockSt) == 0) {
+        ALOGI("rtp socket successfully connected to remote=%s:%d", remoteIp, remotePort);
+    } else {
+        ALOGE("failed to connect rtp socket to remote addr=%s:%d err=%s", remoteIp,
+                remotePort, strerror(errno));
+        return;
+    }
+
+    if (isIPv6)
+        addr6.sin6_port = htons(remotePort + 1);
+    else
+        addr4.sin_port = htons(remotePort + 1);
+
+    if (connect(*rtcpSocket, addr, sizeSockSt) == 0) {
+        ALOGI("rtcp socket successfully connected to remote=%s:%d", remoteIp, remotePort + 1);
+    } else {
+        ALOGE("failed to connect rtcp socket addr=%s:%d err=%s", remoteIp,
+                remotePort + 1, strerror(errno));
+        return;
+    }
+}
+
 void ARTPConnection::onMessageReceived(const sp<AMessage> &msg) {
     switch (msg->what()) {
         case kWhatAddStream:
@@ -204,6 +332,19 @@
     info->mNumRTCPPacketsReceived = 0;
     info->mNumRTPPacketsReceived = 0;
     memset(&info->mRemoteRTCPAddr, 0, sizeof(info->mRemoteRTCPAddr));
+    memset(&info->mRemoteRTCPAddr6, 0, sizeof(info->mRemoteRTCPAddr6));
+
+    sp<ASessionDescription> sessionDesc = info->mSessionDesc;
+    info->mCVOExtMap = 0;
+    for (size_t i = 1; i < sessionDesc->countTracks(); ++i) {
+        int32_t cvoExtMap;
+        if (sessionDesc->getCvoExtMap(i, &cvoExtMap)) {
+            info->mCVOExtMap = cvoExtMap;
+            ALOGI("urn:3gpp:video-orientation(cvo) found as extmap:%d", info->mCVOExtMap);
+        } else {
+            ALOGI("urn:3gpp:video-orientation(cvo) not found :%d", info->mCVOExtMap);
+        }
+    }
 
     if (!injected) {
         postPollEvent();
@@ -295,17 +436,59 @@
 
             if (err == -ECONNRESET) {
                 // socket failure, this stream is dead, Jim.
+                sp<AMessage> notify = it->mNotifyMsg->dup();
+                notify->setInt32("rtcp-event", 1);
+                notify->setInt32("payload-type", 400);
+                notify->setInt32("feedback-type", 1);
+                notify->setInt32("sender", it->mSources.valueAt(0)->getSelfID());
+                notify->post();
 
                 ALOGW("failed to receive RTP/RTCP datagram.");
                 it = mStreams.erase(it);
                 continue;
             }
 
+            // add NACK and FIR that needs to be sent immediately.
+            sp<ABuffer> buffer = new ABuffer(kMaxUDPSize);
+            for (size_t i = 0; i < it->mSources.size(); ++i) {
+                buffer->setRange(0, 0);
+                int cnt = it->mSources.valueAt(i)->addNACK(buffer);
+                if (cnt > 0) {
+                    ALOGV("Send NACK for lost %d Packets", cnt);
+                    send(&*it, buffer);
+                }
+
+                buffer->setRange(0, 0);
+                it->mSources.valueAt(i)->addFIR(buffer);
+                if (buffer->size() > 0) {
+                    ALOGD("Send FIR immediately for lost Packets");
+                    send(&*it, buffer);
+                }
+
+                buffer->setRange(0, 0);
+                it->mSources.valueAt(i)->addTMMBR(buffer, mTargetBitrate);
+                mTargetBitrate = -1;
+                if (buffer->size() > 0) {
+                    ALOGV("Sending TMMBR...");
+                    ssize_t n = send(&*it, buffer);
+
+                    if (n != (ssize_t)buffer->size()) {
+                        ALOGW("failed to send RTCP TMMBR (%s).",
+                                n >= 0 ? "connection gone" : strerror(errno));
+
+                        it = mStreams.erase(it);
+                        continue;
+                    }
+                }
+            }
+
             ++it;
         }
     }
 
     int64_t nowUs = ALooper::GetNowUs();
+    checkRxBitrate(nowUs);
+
     if (mLastReceiverReportTimeUs <= 0
             || mLastReceiverReportTimeUs + 5000000LL <= nowUs) {
         sp<ABuffer> buffer = new ABuffer(kMaxUDPSize);
@@ -340,24 +523,16 @@
             if (buffer->size() > 0) {
                 ALOGV("Sending RR...");
 
-                ssize_t n;
-                do {
-                    n = sendto(
-                        s->mRTCPSocket, buffer->data(), buffer->size(), 0,
-                        (const struct sockaddr *)&s->mRemoteRTCPAddr,
-                        sizeof(s->mRemoteRTCPAddr));
-                } while (n < 0 && errno == EINTR);
+                ssize_t n = send(s, buffer);
 
-                if (n <= 0) {
+                if (n != (ssize_t)buffer->size()) {
                     ALOGW("failed to send RTCP receiver report (%s).",
-                         n == 0 ? "connection gone" : strerror(errno));
+                            n >= 0 ? "connection gone" : strerror(errno));
 
                     it = mStreams.erase(it);
                     continue;
                 }
 
-                CHECK_EQ(n, (ssize_t)buffer->size());
-
                 mLastReceiverReportTimeUs = nowUs;
             }
 
@@ -377,9 +552,22 @@
 
     sp<ABuffer> buffer = new ABuffer(65536);
 
+    struct sockaddr *pRemoteRTCPAddr;
+    int sizeSockSt;
+    if (s->isIPv6) {
+        pRemoteRTCPAddr = (struct sockaddr *)&s->mRemoteRTCPAddr6;
+        sizeSockSt = sizeof(struct sockaddr_in6);
+    } else {
+        pRemoteRTCPAddr = (struct sockaddr *)&s->mRemoteRTCPAddr;
+        sizeSockSt = sizeof(struct sockaddr_in);
+    }
     socklen_t remoteAddrLen =
         (!receiveRTP && s->mNumRTCPPacketsReceived == 0)
-            ? sizeof(s->mRemoteRTCPAddr) : 0;
+            ? sizeSockSt : 0;
+
+    if (mFlags & kViLTEConnection) {
+        remoteAddrLen = 0;
+    }
 
     ssize_t nbytes;
     do {
@@ -388,8 +576,9 @@
             buffer->data(),
             buffer->capacity(),
             0,
-            remoteAddrLen > 0 ? (struct sockaddr *)&s->mRemoteRTCPAddr : NULL,
+            remoteAddrLen > 0 ? pRemoteRTCPAddr : NULL,
             remoteAddrLen > 0 ? &remoteAddrLen : NULL);
+        mCumulativeBytes += nbytes;
     } while (nbytes < 0 && errno == EINTR);
 
     if (nbytes <= 0) {
@@ -410,6 +599,36 @@
     return err;
 }
 
+ssize_t ARTPConnection::send(const StreamInfo *info, const sp<ABuffer> buffer) {
+        struct sockaddr* pRemoteRTCPAddr;
+        int sizeSockSt;
+
+        /* It seems this isIPv6 variable is useless.
+         * We should remove it to prevent confusion */
+        if (info->isIPv6) {
+            pRemoteRTCPAddr = (struct sockaddr *)&info->mRemoteRTCPAddr6;
+            sizeSockSt = sizeof(struct sockaddr_in6);
+        } else {
+            pRemoteRTCPAddr = (struct sockaddr *)&info->mRemoteRTCPAddr;
+            sizeSockSt = sizeof(struct sockaddr_in);
+        }
+
+        if (mFlags & kViLTEConnection) {
+            ALOGV("ViLTE RTCP");
+            pRemoteRTCPAddr = NULL;
+            sizeSockSt = 0;
+        }
+
+        ssize_t n;
+        do {
+            n = sendto(
+                    info->mRTCPSocket, buffer->data(), buffer->size(), 0,
+                    pRemoteRTCPAddr, sizeSockSt);
+        } while (n < 0 && errno == EINTR);
+
+        return n;
+}
+
 status_t ARTPConnection::parseRTP(StreamInfo *s, const sp<ABuffer> &buffer) {
     if (s->mNumRTPPacketsReceived++ == 0) {
         sp<AMessage> notify = s->mNotifyMsg->dup();
@@ -431,6 +650,11 @@
         return -1;
     }
 
+    if ((data[1] & 0x7f) == 20 /* decimal */) {
+        // Unassigned payload type
+        return -1;
+    }
+
     if (data[0] & 0x20) {
         // Padding present.
 
@@ -454,6 +678,7 @@
         return -1;
     }
 
+    int32_t cvoDegrees = -1;
     if (data[0] & 0x10) {
         // Header eXtension present.
 
@@ -467,13 +692,14 @@
         const uint8_t *extensionData = &data[payloadOffset];
 
         size_t extensionLength =
-            4 * (extensionData[2] << 8 | extensionData[3]);
+            (4 * (extensionData[2] << 8 | extensionData[3])) + 4;
 
-        if (size < payloadOffset + 4 + extensionLength) {
+        if (size < payloadOffset + extensionLength) {
             return -1;
         }
 
-        payloadOffset += 4 + extensionLength;
+        parseRTPExt(s, (const uint8_t *)extensionData, extensionLength, &cvoDegrees);
+        payloadOffset += extensionLength;
     }
 
     uint32_t srcId = u32at(&data[8]);
@@ -487,6 +713,9 @@
     meta->setInt32("rtp-time", rtpTime);
     meta->setInt32("PT", data[1] & 0x7f);
     meta->setInt32("M", data[1] >> 7);
+    if (cvoDegrees >= 0) {
+        meta->setInt32("cvo", cvoDegrees);
+    }
 
     buffer->setInt32Data(u16at(&data[2]));
     buffer->setRange(payloadOffset, size - payloadOffset);
@@ -496,11 +725,65 @@
     return OK;
 }
 
+status_t ARTPConnection::parseRTPExt(StreamInfo *s,
+        const uint8_t *extHeader, size_t extLen, int32_t *cvoDegrees) {
+    if (extLen < 4)
+        return -1;
+
+    uint16_t header = (extHeader[0] << 8) | (extHeader[1]);
+    bool isOnebyteHeader = false;
+
+    if (header == 0xBEDE) {
+        isOnebyteHeader = true;
+    } else if (header == 0x1000) {
+        ALOGW("parseRTPExt: two-byte header is not implemented yet");
+        return -1;
+    } else {
+        ALOGW("parseRTPExt: can not recognize header");
+        return -1;
+    }
+
+    const uint8_t *extPayload = extHeader + 4;
+    extLen -= 4;
+    size_t offset = 0; //start from first payload of rtp extension.
+    // one-byte header parser
+    while (isOnebyteHeader && offset < extLen) {
+        uint8_t extmapId = extPayload[offset] >> 4;
+        uint8_t length = (extPayload[offset] & 0xF) + 1;
+        offset++;
+
+        // padding case
+        if (extmapId == 0)
+            continue;
+
+        uint8_t data[16]; // maximum length value
+        for (uint8_t j = 0; offset + j <= extLen && j < length; j++) {
+            data[j] = extPayload[offset + j];
+        }
+
+        offset += length;
+
+        if (extmapId == s->mCVOExtMap) {
+            *cvoDegrees = (int32_t)data[0];
+            return OK;
+        }
+    }
+
+    return BAD_VALUE;
+}
+
 status_t ARTPConnection::parseRTCP(StreamInfo *s, const sp<ABuffer> &buffer) {
     if (s->mNumRTCPPacketsReceived++ == 0) {
         sp<AMessage> notify = s->mNotifyMsg->dup();
         notify->setInt32("first-rtcp", true);
         notify->post();
+
+        ALOGI("send first-rtcp event to upper layer as ImsRxNotice");
+        sp<AMessage> imsNotify = s->mNotifyMsg->dup();
+        imsNotify->setInt32("rtcp-event", 1);
+        imsNotify->setInt32("payload-type", 101);
+        imsNotify->setInt32("feedback-type", 0);
+        imsNotify->post();
     }
 
     const uint8_t *data = buffer->data();
@@ -551,8 +834,12 @@
                 break;
 
             case 205:  // TSFB (transport layer specific feedback)
+                parseTSFB(s, data, headerLength);
+                break;
             case 206:  // PSFB (payload specific feedback)
                 // hexdump(data, headerLength);
+                parsePSFB(s, data, headerLength);
+                ALOGI("RTCP packet type %u of size %zu", (unsigned)data[1], headerLength);
                 break;
 
             case 203:
@@ -589,6 +876,12 @@
 
     sp<ARTPSource> source = findSource(s, id);
 
+    // Report a final stastics to be used for rtp data usage.
+    int64_t nowUs = ALooper::GetNowUs();
+    int32_t timeDiff = (nowUs - mLastBitrateReportTimeUs) / 1000000ll;
+    int32_t bitrate = mCumulativeBytes * 8 / timeDiff;
+    source->notifyPktInfo(bitrate, true /* isRegular */);
+
     source->byeReceived();
 
     return OK;
@@ -621,6 +914,144 @@
     return 0;
 }
 
+status_t ARTPConnection::parseTSFB(
+        StreamInfo *s, const uint8_t *data, size_t size) {
+    if (size < 12) {
+        // broken packet
+        return -1;
+    }
+
+    uint8_t msgType = data[0] & 0x1f;
+    uint32_t id = u32at(&data[4]);
+
+    const uint8_t *ptr = &data[12];
+    size -= 12;
+
+    using namespace std;
+    size_t FCISize;
+    switch(msgType) {
+        case 1:     // Generic NACK
+        {
+            FCISize = 4;
+            while (size >= FCISize) {
+                uint16_t PID = u16at(&ptr[0]);  // lost packet RTP number
+                uint16_t BLP = u16at(&ptr[2]);  // Bitmask of following Lost Packets
+
+                size -= FCISize;
+                ptr += FCISize;
+
+                AString list_of_losts;
+                list_of_losts.append(PID);
+                for (int i=0 ; i<16 ; i++) {
+                    bool is_lost = BLP & (0x1 << i);
+                    if (is_lost) {
+                        list_of_losts.append(", ");
+                        list_of_losts.append(PID + i);
+                    }
+                }
+                ALOGI("Opponent losts packet of RTP %s", list_of_losts.c_str());
+            }
+            break;
+        }
+        case 3:     // TMMBR
+        case 4:     // TMMBN
+        {
+            FCISize = 8;
+            while (size >= FCISize) {
+                uint32_t MxTBR = u32at(&ptr[4]);
+                uint32_t MxTBRExp = MxTBR >> 26;
+                uint32_t MxTBRMantissa = (MxTBR >> 9) & 0x01FFFF;
+                uint32_t overhead = MxTBR & 0x01FF;
+
+                size -= FCISize;
+                ptr += FCISize;
+
+                uint32_t bitRate = (1 << MxTBRExp) * MxTBRMantissa;
+
+                if (msgType == 3)
+                    ALOGI("Op -> UE Req Tx bitrate : %d X 2^%d = %d",
+                        MxTBRMantissa, MxTBRExp, bitRate);
+                else if (msgType == 4)
+                    ALOGI("OP -> UE Noti Rx bitrate : %d X 2^%d = %d",
+                        MxTBRMantissa, MxTBRExp, bitRate);
+
+                sp<AMessage> notify = s->mNotifyMsg->dup();
+                notify->setInt32("rtcp-event", 1);
+                notify->setInt32("payload-type", 205);
+                notify->setInt32("feedback-type", msgType);
+                notify->setInt32("sender", id);
+                notify->setInt32("bit-rate", bitRate);
+                notify->post();
+                ALOGI("overhead : %d", overhead);
+            }
+            break;
+        }
+        default:
+        {
+            ALOGI("Not supported TSFB type %d", msgType);
+            break;
+        }
+    }
+
+    return 0;
+}
+
+status_t ARTPConnection::parsePSFB(
+        StreamInfo *s, const uint8_t *data, size_t size) {
+    if (size < 12) {
+        // broken packet
+        return -1;
+    }
+
+    uint8_t msgType = data[0] & 0x1f;
+    uint32_t id = u32at(&data[4]);
+
+    const uint8_t *ptr = &data[12];
+    size -= 12;
+
+    using namespace std;
+    switch(msgType) {
+        case 1:     // Picture Loss Indication (PLI)
+        {
+            if (size > 0) {
+                // PLI does not need parameters
+                break;
+            };
+            sp<AMessage> notify = s->mNotifyMsg->dup();
+            notify->setInt32("rtcp-event", 1);
+            notify->setInt32("payload-type", 206);
+            notify->setInt32("feedback-type", msgType);
+            notify->setInt32("sender", id);
+            notify->post();
+            ALOGI("PLI detected.");
+            break;
+        }
+        case 4:     // Full Intra Request (FIR)
+        {
+            if (size < 4) {
+                break;
+            }
+            uint32_t requestedId = u32at(&ptr[0]);
+            if (requestedId == (uint32_t)mSelfID) {
+                sp<AMessage> notify = s->mNotifyMsg->dup();
+                notify->setInt32("rtcp-event", 1);
+                notify->setInt32("payload-type", 206);
+                notify->setInt32("feedback-type", msgType);
+                notify->setInt32("sender", id);
+                notify->post();
+                ALOGI("FIR detected.");
+            }
+            break;
+        }
+        default:
+        {
+            ALOGI("Not supported PSFB type %d", msgType);
+            break;
+        }
+    }
+
+    return 0;
+}
 sp<ARTPSource> ARTPConnection::findSource(StreamInfo *info, uint32_t srcId) {
     sp<ARTPSource> source;
     ssize_t index = info->mSources.indexOfKey(srcId);
@@ -630,6 +1061,12 @@
         source = new ARTPSource(
                 srcId, info->mSessionDesc, info->mIndex, info->mNotifyMsg);
 
+        if (mFlags & kViLTEConnection) {
+            source->setPeriodicFIR(false);
+        }
+
+        source->setSelfID(mSelfID);
+        source->setJbTime(mJbTimeMs > 0 ? mJbTimeMs : 300);
         info->mSources.add(srcId, source);
     } else {
         source = info->mSources.valueAt(index);
@@ -645,6 +1082,78 @@
     msg->post();
 }
 
+void ARTPConnection::setSelfID(const uint32_t selfID) {
+    mSelfID = selfID;
+}
+
+void ARTPConnection::setJbTime(const uint32_t jbTimeMs) {
+    mJbTimeMs = jbTimeMs;
+}
+
+void ARTPConnection::setTargetBitrate(int32_t targetBitrate) {
+    mTargetBitrate = targetBitrate;
+}
+
+void ARTPConnection::checkRxBitrate(int64_t nowUs) {
+    if (mLastBitrateReportTimeUs <= 0) {
+        mCumulativeBytes = 0;
+        mLastBitrateReportTimeUs = nowUs;
+    }
+    else if (mLastEarlyNotifyTimeUs + 100000ll <= nowUs) {
+        int32_t timeDiff = (nowUs - mLastBitrateReportTimeUs) / 1000000ll;
+        int32_t bitrate = mCumulativeBytes * 8 / timeDiff;
+        mLastEarlyNotifyTimeUs = nowUs;
+
+        List<StreamInfo>::iterator it = mStreams.begin();
+        while (it != mStreams.end()) {
+            StreamInfo *s = &*it;
+            if (s->mIsInjected) {
+                ++it;
+                continue;
+            }
+            for (size_t i = 0; i < s->mSources.size(); ++i) {
+                sp<ARTPSource> source = s->mSources.valueAt(i);
+                if (source->isNeedToEarlyNotify()) {
+                    source->notifyPktInfo(bitrate, false /* isRegular */);
+                    mLastEarlyNotifyTimeUs = nowUs + (1000000ll * 3600 * 24); // after 1 day
+                }
+            }
+            ++it;
+        }
+    }
+    else if (mLastBitrateReportTimeUs + 1000000ll <= nowUs) {
+        int32_t timeDiff = (nowUs - mLastBitrateReportTimeUs) / 1000000ll;
+        int32_t bitrate = mCumulativeBytes * 8 / timeDiff;
+        ALOGI("Actual Rx bitrate : %d bits/sec", bitrate);
+
+        sp<ABuffer> buffer = new ABuffer(kMaxUDPSize);
+        List<StreamInfo>::iterator it = mStreams.begin();
+        while (it != mStreams.end()) {
+            StreamInfo *s = &*it;
+            if (s->mIsInjected) {
+                ++it;
+                continue;
+            }
+
+            if (s->mNumRTCPPacketsReceived == 0) {
+                // We have never received any RTCP packets on this stream,
+                // we don't even know where to send a report.
+                ++it;
+                continue;
+            }
+
+            buffer->setRange(0, 0);
+            for (size_t i = 0; i < s->mSources.size(); ++i) {
+                sp<ARTPSource> source = s->mSources.valueAt(i);
+                source->notifyPktInfo(bitrate, true /* isRegular */);
+            }
+            ++it;
+        }
+        mCumulativeBytes = 0;
+        mLastBitrateReportTimeUs = nowUs;
+        mLastEarlyNotifyTimeUs = nowUs;
+    }
+}
 void ARTPConnection::onInjectPacket(const sp<AMessage> &msg) {
     int32_t index;
     CHECK(msg->findInt32("index", &index));
@@ -672,4 +1181,3 @@
 }
 
 }  // namespace android
-
diff --git a/media/libstagefright/rtsp/ARTPConnection.h b/media/libstagefright/rtsp/ARTPConnection.h
index d5f7c2e..a37ac0e 100644
--- a/media/libstagefright/rtsp/ARTPConnection.h
+++ b/media/libstagefright/rtsp/ARTPConnection.h
@@ -30,6 +30,7 @@
 struct ARTPConnection : public AHandler {
     enum Flags {
         kRegularlyRequestFIR = 2,
+        kViLTEConnection = 4,
     };
 
     explicit ARTPConnection(uint32_t flags = 0);
@@ -44,11 +45,22 @@
 
     void injectPacket(int index, const sp<ABuffer> &buffer);
 
+    void setSelfID(const uint32_t selfID);
+    void setJbTime(const uint32_t jbTimeMs);
+    void setTargetBitrate(int32_t targetBitrate);
+
     // Creates a pair of UDP datagram sockets bound to adjacent ports
     // (the rtpSocket is bound to an even port, the rtcpSocket to the
     // next higher port).
     static void MakePortPair(
             int *rtpSocket, int *rtcpSocket, unsigned *rtpPort);
+    // Creates a pair of UDP datagram sockets bound to assigned ip and
+    // ports (the rtpSocket is bound to an even port, the rtcpSocket
+    // to the next higher port).
+    static void MakeRTPSocketPair(
+            int *rtpSocket, int *rtcpSocket,
+            const char *localIp, const char *remoteIp,
+            unsigned localPort, unsigned remotePort, int64_t socketNetwork = 0);
 
 protected:
     virtual ~ARTPConnection();
@@ -71,18 +83,32 @@
 
     bool mPollEventPending;
     int64_t mLastReceiverReportTimeUs;
+    int64_t mLastBitrateReportTimeUs;
+    int64_t mLastEarlyNotifyTimeUs;
+
+    int32_t mSelfID;
+    int32_t mTargetBitrate;
+
+    uint32_t mJbTimeMs;
+
+    int32_t mCumulativeBytes;
 
     void onAddStream(const sp<AMessage> &msg);
     void onRemoveStream(const sp<AMessage> &msg);
     void onPollStreams();
     void onInjectPacket(const sp<AMessage> &msg);
     void onSendReceiverReports();
+    void checkRxBitrate(int64_t nowUs);
 
     status_t receive(StreamInfo *info, bool receiveRTP);
+    ssize_t send(const StreamInfo *info, const sp<ABuffer> buffer);
 
     status_t parseRTP(StreamInfo *info, const sp<ABuffer> &buffer);
+    status_t parseRTPExt(StreamInfo *s, const uint8_t *extData, size_t extLen, int32_t *cvoDegrees);
     status_t parseRTCP(StreamInfo *info, const sp<ABuffer> &buffer);
     status_t parseSR(StreamInfo *info, const uint8_t *data, size_t size);
+    status_t parseTSFB(StreamInfo *info, const uint8_t *data, size_t size);
+    status_t parsePSFB(StreamInfo *info, const uint8_t *data, size_t size);
     status_t parseBYE(StreamInfo *info, const uint8_t *data, size_t size);
 
     sp<ARTPSource> findSource(StreamInfo *info, uint32_t id);
diff --git a/media/libstagefright/rtsp/ARTPSource.cpp b/media/libstagefright/rtsp/ARTPSource.cpp
index f5f8128..3fdf8e4 100644
--- a/media/libstagefright/rtsp/ARTPSource.cpp
+++ b/media/libstagefright/rtsp/ARTPSource.cpp
@@ -22,6 +22,7 @@
 
 #include "AAMRAssembler.h"
 #include "AAVCAssembler.h"
+#include "AHEVCAssembler.h"
 #include "AH263Assembler.h"
 #include "AMPEG2TSAssembler.h"
 #include "AMPEG4AudioAssembler.h"
@@ -33,23 +34,35 @@
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/AMessage.h>
 
+#include <strings.h>
+
 namespace android {
 
-static const uint32_t kSourceID = 0xdeadbeef;
+static uint32_t kSourceID = 0xdeadbeef;
 
 ARTPSource::ARTPSource(
         uint32_t id,
         const sp<ASessionDescription> &sessionDesc, size_t index,
         const sp<AMessage> &notify)
-    : mID(id),
+    : mFirstSeqNumber(0),
+      mFirstRtpTime(0),
+      mFirstSysTime(0),
+      mClockRate(0),
+      mJbTimeMs(300), // default jitter buffer time is 300ms.
+      mFirstSsrc(0),
+      mHighestNackNumber(0),
+      mID(id),
       mHighestSeqNumber(0),
       mPrevExpected(0),
       mBaseSeqNumber(0),
       mNumBuffersReceived(0),
       mPrevNumBuffersReceived(0),
+      mPrevExpectedForRR(0),
+      mPrevNumBuffersReceivedForRR(0),
       mLastNTPTime(0),
       mLastNTPTimeUpdateUs(0),
       mIssueFIRRequests(false),
+      mIssueFIRByAssembler(false),
       mLastFIRRequestUs(-1),
       mNextFIRSeqNo((rand() * 256.0) / RAND_MAX),
       mNotify(notify) {
@@ -61,6 +74,9 @@
     if (!strncmp(desc.c_str(), "H264/", 5)) {
         mAssembler = new AAVCAssembler(notify);
         mIssueFIRRequests = true;
+    } else if (!strncmp(desc.c_str(), "H265/", 5)) {
+        mAssembler = new AHEVCAssembler(notify);
+        mIssueFIRRequests = true;
     } else if (!strncmp(desc.c_str(), "MP4A-LATM/", 10)) {
         mAssembler = new AMPEG4AudioAssembler(notify, params);
     } else if (!strncmp(desc.c_str(), "H263-1998/", 10)
@@ -112,13 +128,29 @@
 bool ARTPSource::queuePacket(const sp<ABuffer> &buffer) {
     uint32_t seqNum = (uint32_t)buffer->int32Data();
 
-    if (mNumBuffersReceived++ == 0) {
+    int32_t ssrc = 0;
+    buffer->meta()->findInt32("ssrc", &ssrc);
+
+    if (mNumBuffersReceived++ == 0 && mFirstSysTime == 0) {
+        uint32_t firstRtpTime;
+        CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&firstRtpTime));
+        mFirstSysTime = ALooper::GetNowUs();
         mHighestSeqNumber = seqNum;
         mBaseSeqNumber = seqNum;
+        mFirstRtpTime = firstRtpTime;
+        mFirstSsrc = ssrc;
+        ALOGD("first-rtp arrived: first-rtp-time=%d, sys-time=%lld, seq-num=%u, ssrc=%d",
+                mFirstRtpTime, (long long)mFirstSysTime, mHighestSeqNumber, mFirstSsrc);
+        mClockRate = 90000;
         mQueue.push_back(buffer);
         return true;
     }
 
+    if (mFirstSsrc != ssrc) {
+        ALOGW("Discarding a buffer due to unexpected ssrc");
+        return false;
+    }
+
     // Only the lower 16-bit of the sequence numbers are transmitted,
     // derive the high-order bits by choosing the candidate closest
     // to the highest sequence number (extended to 32 bits) received so far.
@@ -181,20 +213,34 @@
 }
 
 void ARTPSource::addFIR(const sp<ABuffer> &buffer) {
-    if (!mIssueFIRRequests) {
+    if (!mIssueFIRRequests && !mIssueFIRByAssembler) {
         return;
     }
 
+    bool send = false;
     int64_t nowUs = ALooper::GetNowUs();
-    if (mLastFIRRequestUs >= 0 && mLastFIRRequestUs + 5000000LL > nowUs) {
-        // Send FIR requests at most every 5 secs.
+    int64_t usecsSinceLastFIR = nowUs - mLastFIRRequestUs;
+    if (mLastFIRRequestUs < 0) {
+        // A first FIR, just send it.
+        send = true;
+    }  else if (mIssueFIRByAssembler && (usecsSinceLastFIR > 1000000)) {
+        // A FIR issued by Assembler.
+        // Send it if last FIR is not sent within a sec.
+        send = true;
+    } else if (mIssueFIRRequests && (usecsSinceLastFIR > 5000000)) {
+        // A FIR issued periodically regardless packet loss.
+        // Send it if last FIR is not sent within 5 secs.
+        send = true;
+    }
+
+    if (!send) {
         return;
     }
 
     mLastFIRRequestUs = nowUs;
 
     if (buffer->size() + 20 > buffer->capacity()) {
-        ALOGW("RTCP buffer too small to accomodate FIR.");
+        ALOGW("RTCP buffer too small to accommodate FIR.");
         return;
     }
 
@@ -203,7 +249,7 @@
     data[0] = 0x80 | 4;
     data[1] = 206;  // PSFB
     data[2] = 0;
-    data[3] = 4;
+    data[3] = 4;    // total (4+1) * sizeof(int32_t) = 20 bytes
     data[4] = kSourceID >> 24;
     data[5] = (kSourceID >> 16) & 0xff;
     data[6] = (kSourceID >> 8) & 0xff;
@@ -225,14 +271,16 @@
     data[18] = 0x00;
     data[19] = 0x00;
 
-    buffer->setRange(buffer->offset(), buffer->size() + 20);
+    buffer->setRange(buffer->offset(), buffer->size() + (data[3] + 1) * sizeof(int32_t));
+
+    mIssueFIRByAssembler = false;
 
     ALOGV("Added FIR request.");
 }
 
 void ARTPSource::addReceiverReport(const sp<ABuffer> &buffer) {
     if (buffer->size() + 32 > buffer->capacity()) {
-        ALOGW("RTCP buffer too small to accomodate RR.");
+        ALOGW("RTCP buffer too small to accommodate RR.");
         return;
     }
 
@@ -240,16 +288,16 @@
 
     // According to appendix A.3 in RFC 3550
     uint32_t expected = mHighestSeqNumber - mBaseSeqNumber + 1;
-    int64_t intervalExpected = expected - mPrevExpected;
-    int64_t intervalReceived = mNumBuffersReceived - mPrevNumBuffersReceived;
+    int64_t intervalExpected = expected - mPrevExpectedForRR;
+    int64_t intervalReceived = mNumBuffersReceived - mPrevNumBuffersReceivedForRR;
     int64_t intervalPacketLost = intervalExpected - intervalReceived;
 
     if (intervalExpected > 0 && intervalPacketLost > 0) {
         fraction = (intervalPacketLost << 8) / intervalExpected;
     }
 
-    mPrevExpected = expected;
-    mPrevNumBuffersReceived = mNumBuffersReceived;
+    mPrevExpectedForRR = expected;
+    mPrevNumBuffersReceivedForRR = mNumBuffersReceived;
     int32_t cumulativePacketLost = (int32_t)expected - mNumBuffersReceived;
 
     uint8_t *data = buffer->data() + buffer->size();
@@ -257,7 +305,7 @@
     data[0] = 0x80 | 1;
     data[1] = 201;  // RR
     data[2] = 0;
-    data[3] = 7;
+    data[3] = 7;    // total (7+1) * sizeof(int32_t) = 32 bytes
     data[4] = kSourceID >> 24;
     data[5] = (kSourceID >> 16) & 0xff;
     data[6] = (kSourceID >> 8) & 0xff;
@@ -303,9 +351,210 @@
     data[30] = (DLSR >> 8) & 0xff;
     data[31] = DLSR & 0xff;
 
-    buffer->setRange(buffer->offset(), buffer->size() + 32);
+    buffer->setRange(buffer->offset(), buffer->size() + (data[3] + 1) * sizeof(int32_t));
 }
 
+void ARTPSource::addTMMBR(const sp<ABuffer> &buffer, int32_t targetBitrate) {
+    if (buffer->size() + 20 > buffer->capacity()) {
+        ALOGW("RTCP buffer too small to accommodate RR.");
+        return;
+    }
+
+    if (targetBitrate <= 0) {
+        return;
+    }
+
+    uint8_t *data = buffer->data() + buffer->size();
+
+    data[0] = 0x80 | 3; // TMMBR
+    data[1] = 205;      // TSFB
+    data[2] = 0;
+    data[3] = 4;        // total (4+1) * sizeof(int32_t) = 20 bytes
+    data[4] = kSourceID >> 24;
+    data[5] = (kSourceID >> 16) & 0xff;
+    data[6] = (kSourceID >> 8) & 0xff;
+    data[7] = kSourceID & 0xff;
+
+    *(int32_t*)(&data[8]) = 0;  // 4 bytes blank
+
+    data[12] = mID >> 24;
+    data[13] = (mID >> 16) & 0xff;
+    data[14] = (mID >> 8) & 0xff;
+    data[15] = mID & 0xff;
+
+    // Find the first bit '1' from left & right side of the value.
+    int32_t leftEnd = 31 - __builtin_clz(targetBitrate);
+    int32_t rightEnd = ffs(targetBitrate) - 1;
+
+    // Mantissa have only 17bit space by RTCP specification.
+    if ((leftEnd - rightEnd) > 16) {
+        rightEnd = leftEnd - 16;
+    }
+    int32_t mantissa = targetBitrate >> rightEnd;
+
+    data[16] = ((rightEnd << 2) & 0xfc) | ((mantissa & 0x18000) >> 15);
+    data[17] =                             (mantissa & 0x07f80) >> 7;
+    data[18] =                             (mantissa & 0x0007f) << 1;
+    data[19] = 40;              // 40 bytes overhead;
+
+    buffer->setRange(buffer->offset(), buffer->size() + (data[3] + 1) * sizeof(int32_t));
+
+    ALOGI("UE -> Op Req Rx bitrate : %d ", mantissa << rightEnd);
+}
+
+int ARTPSource::addNACK(const sp<ABuffer> &buffer) {
+    constexpr size_t kMaxFCIs = 10; // max number of FCIs
+    if (buffer->size() + (3 + kMaxFCIs) * sizeof(int32_t) > buffer->capacity()) {
+        ALOGW("RTCP buffer too small to accommodate NACK.");
+        return -1;
+    }
+
+    uint8_t *data = buffer->data() + buffer->size();
+
+    data[0] = 0x80 | 1; // Generic NACK
+    data[1] = 205;      // TSFB
+    data[2] = 0;
+    data[3] = 0;        // will be decided later
+    data[4] = kSourceID >> 24;
+    data[5] = (kSourceID >> 16) & 0xff;
+    data[6] = (kSourceID >> 8) & 0xff;
+    data[7] = kSourceID & 0xff;
+
+    data[8] = mID >> 24;
+    data[9] = (mID >> 16) & 0xff;
+    data[10] = (mID >> 8) & 0xff;
+    data[11] = mID & 0xff;
+
+    List<int> list;
+    List<int>::iterator it;
+    getSeqNumToNACK(list, kMaxFCIs);
+    size_t cnt = 0;
+
+    int *FCI = (int *)(data + 12);
+    for (it = list.begin(); it != list.end() && cnt < kMaxFCIs; it++) {
+        *(FCI + cnt) = *it;
+        cnt++;
+    }
+
+    data[3] = (3 + cnt) - 1;  // total (3 + #ofFCI) * sizeof(int32_t) byte
+
+    buffer->setRange(buffer->offset(), buffer->size() + (data[3] + 1) * sizeof(int32_t));
+
+    return cnt;
+}
+
+int ARTPSource::getSeqNumToNACK(List<int>& list, int size) {
+    AutoMutex _l(mMapLock);
+    int cnt = 0;
+
+    std::map<uint16_t, infoNACK>::iterator it;
+    for(it = mNACKMap.begin(); it != mNACKMap.end() && cnt < size; it++) {
+        infoNACK &info_it = it->second;
+        if (info_it.needToNACK) {
+            info_it.needToNACK = false;
+            // switch LSB to MSB for sending N/W
+            uint32_t FCI;
+            uint8_t *temp = (uint8_t *)&FCI;
+            temp[0] = (info_it.seqNum >> 8) & 0xff;
+            temp[1] = (info_it.seqNum)      & 0xff;
+            temp[2] = (info_it.mask >> 8)   & 0xff;
+            temp[3] = (info_it.mask)        & 0xff;
+
+            list.push_back(FCI);
+            cnt++;
+        }
+    }
+
+    return cnt;
+}
+
+void ARTPSource::setSeqNumToNACK(uint16_t seqNum, uint16_t mask, uint16_t nowJitterHeadSeqNum) {
+    AutoMutex _l(mMapLock);
+    infoNACK info = {seqNum, mask, nowJitterHeadSeqNum, true};
+    std::map<uint16_t, infoNACK>::iterator it;
+
+    it = mNACKMap.find(seqNum);
+    if (it != mNACKMap.end()) {
+        infoNACK &info_it = it->second;
+        // renew if (mask or head seq) is changed
+        if ((info_it.mask != mask) || (info_it.nowJitterHeadSeqNum != nowJitterHeadSeqNum)) {
+            info_it = info;
+        }
+    } else {
+        mNACKMap[seqNum] = info;
+    }
+
+    // delete all NACK far from current Jitter's first sequence number
+    it = mNACKMap.begin();
+    while (it != mNACKMap.end()) {
+        infoNACK &info_it = it->second;
+
+        int diff = nowJitterHeadSeqNum - info_it.nowJitterHeadSeqNum;
+        if (diff > 100) {
+            ALOGV("Delete %d pkt from NACK map ", info_it.seqNum);
+            it = mNACKMap.erase(it);
+        } else {
+            it++;
+        }
+    }
+
+}
+
+uint32_t ARTPSource::getSelfID() {
+    return kSourceID;
+}
+
+void ARTPSource::setSelfID(const uint32_t selfID) {
+    kSourceID = selfID;
+}
+
+void ARTPSource::setJbTime(const uint32_t jbTimeMs) {
+    mJbTimeMs = jbTimeMs;
+}
+
+void ARTPSource::setPeriodicFIR(bool enable) {
+    ALOGD("setPeriodicFIR %d", enable);
+    mIssueFIRRequests = enable;
+}
+
+bool ARTPSource::isNeedToEarlyNotify() {
+    uint32_t expected = mHighestSeqNumber - mBaseSeqNumber + 1;
+    int32_t intervalExpectedInNow = expected - mPrevExpected;
+    int32_t intervalReceivedInNow = mNumBuffersReceived - mPrevNumBuffersReceived;
+
+    if (intervalExpectedInNow - intervalReceivedInNow > 5)
+        return true;
+    return false;
+}
+
+void ARTPSource::notifyPktInfo(int32_t bitrate, bool isRegular) {
+    int32_t payloadType = isRegular ? RTP_QUALITY : RTP_QUALITY_EMC;
+
+    sp<AMessage> notify = mNotify->dup();
+    notify->setInt32("rtcp-event", 1);
+    notify->setInt32("payload-type", payloadType);
+    notify->setInt32("feedback-type", 0);
+    // sending target bitrate up to application to share rtp quality.
+    notify->setInt32("bit-rate", bitrate);
+    notify->setInt32("highest-seq-num", mHighestSeqNumber);
+    notify->setInt32("base-seq-num", mBaseSeqNumber);
+    notify->setInt32("prev-expected", mPrevExpected);
+    notify->setInt32("num-buf-recv", mNumBuffersReceived);
+    notify->setInt32("prev-num-buf-recv", mPrevNumBuffersReceived);
+    notify->post();
+
+    if (isRegular) {
+        uint32_t expected = mHighestSeqNumber - mBaseSeqNumber + 1;
+        mPrevExpected = expected;
+        mPrevNumBuffersReceived = mNumBuffersReceived;
+    }
+}
+
+void ARTPSource::onIssueFIRByAssembler() {
+    mIssueFIRByAssembler = true;
+}
+
+void ARTPSource::noticeAbandonBuffer(int cnt) {
+    mNumBuffersReceived -= cnt;
+}
 }  // namespace android
-
-
diff --git a/media/libstagefright/rtsp/ARTPSource.h b/media/libstagefright/rtsp/ARTPSource.h
index f44e83f..c51fd8a 100644
--- a/media/libstagefright/rtsp/ARTPSource.h
+++ b/media/libstagefright/rtsp/ARTPSource.h
@@ -23,6 +23,9 @@
 #include <media/stagefright/foundation/ABase.h>
 #include <utils/List.h>
 #include <utils/RefBase.h>
+#include <utils/Thread.h>
+
+#include <map>
 
 namespace android {
 
@@ -37,6 +40,17 @@
             const sp<ASessionDescription> &sessionDesc, size_t index,
             const sp<AMessage> &notify);
 
+    enum {
+        RTP_FIRST_PACKET = 100,
+        RTCP_FIRST_PACKET = 101,
+        RTP_QUALITY = 102,
+        RTP_QUALITY_EMC = 103,
+        RTCP_TSFB = 205,
+        RTCP_PSFB = 206,
+        RTP_CVO = 300,
+        RTP_AUTODOWN = 400,
+    };
+
     void processRTPPacket(const sp<ABuffer> &buffer);
     void timeUpdate(uint32_t rtpTime, uint64_t ntpTime);
     void byeReceived();
@@ -45,22 +59,59 @@
 
     void addReceiverReport(const sp<ABuffer> &buffer);
     void addFIR(const sp<ABuffer> &buffer);
+    void addTMMBR(const sp<ABuffer> &buffer, int32_t targetBitrate);
+    int addNACK(const sp<ABuffer> &buffer);
+    void setSeqNumToNACK(uint16_t seqNum, uint16_t mask, uint16_t nowJitterHeadSeqNum);
+    uint32_t getSelfID();
+    void setSelfID(const uint32_t selfID);
+    void setJbTime(const uint32_t jbTimeMs);
+    void setPeriodicFIR(bool enable);
+    bool isNeedToEarlyNotify();
+    void notifyPktInfo(int32_t bitrate, bool isRegular);
+    // FIR needs to be sent by missing packet or broken video image.
+    void onIssueFIRByAssembler();
+
+    void noticeAbandonBuffer(int cnt=1);
+
+    int32_t mFirstSeqNumber;
+    uint32_t mFirstRtpTime;
+    int64_t mFirstSysTime;
+    int32_t mClockRate;
+
+    uint32_t mJbTimeMs;
+    int32_t mFirstSsrc;
+    int32_t mHighestNackNumber;
 
 private:
+
     uint32_t mID;
     uint32_t mHighestSeqNumber;
     uint32_t mPrevExpected;
     uint32_t mBaseSeqNumber;
     int32_t mNumBuffersReceived;
     int32_t mPrevNumBuffersReceived;
+    uint32_t mPrevExpectedForRR;
+    int32_t mPrevNumBuffersReceivedForRR;
 
     List<sp<ABuffer> > mQueue;
     sp<ARTPAssembler> mAssembler;
 
+    typedef struct infoNACK {
+        uint16_t seqNum;
+        uint16_t mask;
+        uint16_t nowJitterHeadSeqNum;
+        bool    needToNACK;
+    } infoNACK;
+
+    Mutex mMapLock;
+    std::map<uint16_t, infoNACK> mNACKMap;
+    int getSeqNumToNACK(List<int>& list, int size);
+
     uint64_t mLastNTPTime;
     int64_t mLastNTPTimeUpdateUs;
 
     bool mIssueFIRRequests;
+    bool mIssueFIRByAssembler;
     int64_t mLastFIRRequestUs;
     uint8_t mNextFIRSeqNo;
 
diff --git a/media/libstagefright/rtsp/ARTPWriter.cpp b/media/libstagefright/rtsp/ARTPWriter.cpp
index 58d6086..ec70952 100644
--- a/media/libstagefright/rtsp/ARTPWriter.cpp
+++ b/media/libstagefright/rtsp/ARTPWriter.cpp
@@ -20,8 +20,6 @@
 
 #include "ARTPWriter.h"
 
-#include <fcntl.h>
-
 #include <media/stagefright/MediaSource.h>
 #include <media/stagefright/foundation/ABuffer.h>
 #include <media/stagefright/foundation/ADebug.h>
@@ -32,13 +30,43 @@
 #include <media/stagefright/MetaData.h>
 #include <utils/ByteOrder.h>
 
+#include <fcntl.h>
+#include <strings.h>
+
 #define PT      97
 #define PT_STR  "97"
 
+#define H264_NALU_MASK 0x1F
+#define H264_NALU_SPS 0x7
+#define H264_NALU_PPS 0x8
+#define H264_NALU_IFRAME 0x5
+#define H264_NALU_PFRAME 0x1
+
+#define H265_NALU_MASK 0x3F
+#define H265_NALU_VPS 0x20
+#define H265_NALU_SPS 0x21
+#define H265_NALU_PPS 0x22
+
+#define IPV4_HEADER_SIZE 20
+#define IPV6_HEADER_SIZE 40
+#define UDP_HEADER_SIZE 8
+#define TCPIPV4_HEADER_SIZE (IPV4_HEADER_SIZE + UDP_HEADER_SIZE)
+#define TCPIPV6_HEADER_SIZE (IPV6_HEADER_SIZE + UDP_HEADER_SIZE)
+#define TCPIP_HEADER_SIZE TCPIPV4_HEADER_SIZE
+#define RTP_HEADER_SIZE 12
+#define RTP_HEADER_EXT_SIZE 8
+#define RTP_FU_HEADER_SIZE 2
+#define RTP_PAYLOAD_ROOM_SIZE 100 // ROOM size for IPv6 header, ESP and etc.
+
+
 namespace android {
 
 // static const size_t kMaxPacketSize = 65507;  // maximum payload in UDP over IP
-static const size_t kMaxPacketSize = 1500;
+static const size_t kMaxPacketSize = 1280;
+static char kCNAME[255] = "someone@somewhere";
+
+static const size_t kTrafficRecorderMaxEntries = 128;
+static const size_t kTrafficRecorderMaxTimeSpanMs = 2000;
 
 static int UniformRand(int limit) {
     return ((double)rand() * limit) / RAND_MAX;
@@ -48,15 +76,20 @@
     : mFlags(0),
       mFd(dup(fd)),
       mLooper(new ALooper),
-      mReflector(new AHandlerReflector<ARTPWriter>(this)) {
+      mReflector(new AHandlerReflector<ARTPWriter>(this)),
+      mTrafficRec(new TrafficRecorder<uint32_t /* Time */, Bytes>(
+              kTrafficRecorderMaxEntries, kTrafficRecorderMaxTimeSpanMs)) {
     CHECK_GE(fd, 0);
+    mIsIPv6 = false;
 
     mLooper->setName("rtp writer");
     mLooper->registerHandler(mReflector);
     mLooper->start();
 
-    mSocket = socket(AF_INET, SOCK_DGRAM, 0);
-    CHECK_GE(mSocket, 0);
+    mRTPSocket = socket(AF_INET, SOCK_DGRAM, 0);
+    CHECK_GE(mRTPSocket, 0);
+    mRTCPSocket = socket(AF_INET, SOCK_DGRAM, 0);
+    CHECK_GE(mRTCPSocket, 0);
 
     memset(mRTPAddr.sin_zero, 0, sizeof(mRTPAddr.sin_zero));
     mRTPAddr.sin_family = AF_INET;
@@ -72,6 +105,46 @@
 
     mRTCPAddr = mRTPAddr;
     mRTCPAddr.sin_port = htons(ntohs(mRTPAddr.sin_port) | 1);
+    mSPSBuf = NULL;
+    mPPSBuf = NULL;
+
+#if LOG_TO_FILES
+    mRTPFd = open(
+            "/data/misc/rtpout.bin",
+            O_WRONLY | O_CREAT | O_TRUNC,
+            0644);
+    CHECK_GE(mRTPFd, 0);
+
+    mRTCPFd = open(
+            "/data/misc/rtcpout.bin",
+            O_WRONLY | O_CREAT | O_TRUNC,
+            0644);
+    CHECK_GE(mRTCPFd, 0);
+#endif
+}
+
+ARTPWriter::ARTPWriter(int fd, String8& localIp, int localPort, String8& remoteIp,
+    int remotePort, uint32_t seqNo)
+    : mFlags(0),
+      mFd(dup(fd)),
+      mLooper(new ALooper),
+      mReflector(new AHandlerReflector<ARTPWriter>(this)),
+      mTrafficRec(new TrafficRecorder<uint32_t /* Time */, Bytes>(
+              kTrafficRecorderMaxEntries, kTrafficRecorderMaxTimeSpanMs)) {
+    CHECK_GE(fd, 0);
+    mIsIPv6 = false;
+
+    mLooper->setName("rtp writer");
+    mLooper->registerHandler(mReflector);
+    mLooper->start();
+
+    makeSocketPairAndBind(localIp, localPort, remoteIp , remotePort);
+    mVPSBuf = NULL;
+    mSPSBuf = NULL;
+    mPPSBuf = NULL;
+
+    initState();
+    mSeqNo = seqNo;     // Must use explicit # of seq for RTP continuity
 
 #if LOG_TO_FILES
     mRTPFd = open(
@@ -89,6 +162,21 @@
 }
 
 ARTPWriter::~ARTPWriter() {
+    if (mVPSBuf != NULL) {
+        mVPSBuf->release();
+        mVPSBuf = NULL;
+    }
+
+    if (mSPSBuf != NULL) {
+        mSPSBuf->release();
+        mSPSBuf = NULL;
+    }
+
+    if (mPPSBuf != NULL) {
+        mPPSBuf->release();
+        mPPSBuf = NULL;
+    }
+
 #if LOG_TO_FILES
     close(mRTCPFd);
     mRTCPFd = -1;
@@ -97,13 +185,39 @@
     mRTPFd = -1;
 #endif
 
-    close(mSocket);
-    mSocket = -1;
+    close(mRTPSocket);
+    mRTPSocket = -1;
+
+    close(mRTCPSocket);
+    mRTCPSocket = -1;
 
     close(mFd);
     mFd = -1;
 }
 
+void ARTPWriter::initState() {
+    if (mSourceID == 0)
+        mSourceID = rand();
+    mPayloadType = 0;
+    if (mSeqNo == 0)
+        mSeqNo = UniformRand(65536);
+    mRTPTimeBase = 0;
+    mNumRTPSent = 0;
+    mNumRTPOctetsSent = 0;
+    mLastRTPTime = 0;
+    mLastNTPTime = 0;
+
+    mOpponentID = 0;
+    mBitrate = 192000;
+
+    mNumSRsSent = 0;
+    mRTPCVOExtMap = -1;
+    mRTPCVODegrees = 0;
+    mRTPSockNetwork = 0;
+
+    mMode = INVALID;
+}
+
 status_t ARTPWriter::addSource(const sp<MediaSource> &source) {
     mSource = source;
     return OK;
@@ -114,28 +228,46 @@
     return (mFlags & kFlagEOS) != 0;
 }
 
-status_t ARTPWriter::start(MetaData * /* params */) {
+status_t ARTPWriter::start(MetaData * params) {
     Mutex::Autolock autoLock(mLock);
     if (mFlags & kFlagStarted) {
         return INVALID_OPERATION;
     }
 
     mFlags &= ~kFlagEOS;
-    mSourceID = rand();
-    mSeqNo = UniformRand(65536);
-    mRTPTimeBase = rand();
-    mNumRTPSent = 0;
-    mNumRTPOctetsSent = 0;
-    mLastRTPTime = 0;
-    mLastNTPTime = 0;
-    mNumSRsSent = 0;
+    initState();
 
     const char *mime;
     CHECK(mSource->getFormat()->findCString(kKeyMIMEType, &mime));
 
-    mMode = INVALID;
+    int32_t selfID = 0;
+    if (params->findInt32(kKeySelfID, &selfID))
+        mSourceID = selfID;
+
+    int32_t payloadType = 0;
+    if (params->findInt32(kKeyPayloadType, &payloadType))
+        mPayloadType = payloadType;
+
+    int32_t rtpExtMap = 0;
+    if (params->findInt32(kKeyRtpExtMap, &rtpExtMap))
+        mRTPCVOExtMap = rtpExtMap;
+
+    int32_t rtpCVODegrees = 0;
+    if (params->findInt32(kKeyRtpCvoDegrees, &rtpCVODegrees))
+        mRTPCVODegrees = rtpCVODegrees;
+
+    int32_t dscp = 0;
+    if (params->findInt32(kKeyRtpDscp, &dscp))
+        updateSocketDscp(dscp);
+
+    int64_t sockNetwork = 0;
+    if (params->findInt64(kKeySocketNetwork, &sockNetwork))
+        updateSocketNetwork(sockNetwork);
+
     if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
         mMode = H264;
+    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_HEVC)) {
+        mMode = H265;
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_H263)) {
         mMode = H263;
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AMR_NB)) {
@@ -187,11 +319,137 @@
     }
 }
 
+static const uint8_t SPCSize = 4;      // Start Prefix Code Size
+static const uint8_t startPrefixCode[SPCSize] = {0, 0, 0, 1};
+static const uint8_t spcKMPidx[SPCSize] = {0, 0, 2, 0};
+static void SpsPpsParser(MediaBufferBase *buffer,
+        MediaBufferBase **spsBuffer, MediaBufferBase **ppsBuffer) {
+
+    while (buffer->range_length() > 0) {
+        const uint8_t *NALPtr = (const uint8_t *)buffer->data() + buffer->range_offset();
+
+        MediaBufferBase **targetPtr = NULL;
+        if ((*NALPtr & H264_NALU_MASK) == H264_NALU_SPS) {
+            targetPtr = spsBuffer;
+        } else if ((*NALPtr & H264_NALU_MASK) == H264_NALU_PPS) {
+            targetPtr = ppsBuffer;
+        } else {
+            return;
+        }
+        ALOGV("SPS(7) or PPS(8) found. Type %d", *NALPtr & H264_NALU_MASK);
+
+        uint32_t bufferSize = buffer->range_length();
+        MediaBufferBase *&target = *targetPtr;
+        uint32_t i = 0, j = 0;
+        bool isBoundFound = false;
+        for (i = 0; i < bufferSize; i++) {
+            while (j > 0 && NALPtr[i] != startPrefixCode[j]) {
+                j = spcKMPidx[j - 1];
+            }
+            if (NALPtr[i] == startPrefixCode[j]) {
+                j++;
+                if (j == SPCSize) {
+                    isBoundFound = true;
+                    break;
+                }
+            }
+        }
+
+        uint32_t targetSize;
+        if (target != NULL) {
+            target->release();
+        }
+        // note that targetSize is never 0 as the first byte is never part
+        // of a start prefix
+        if (isBoundFound) {
+            targetSize = i - SPCSize + 1;
+            target = MediaBufferBase::Create(targetSize);
+            memcpy(target->data(),
+                   (const uint8_t *)buffer->data() + buffer->range_offset(),
+                   targetSize);
+            buffer->set_range(buffer->range_offset() + targetSize + SPCSize,
+                              buffer->range_length() - targetSize - SPCSize);
+        } else {
+            targetSize = bufferSize;
+            target = MediaBufferBase::Create(targetSize);
+            memcpy(target->data(),
+                   (const uint8_t *)buffer->data() + buffer->range_offset(),
+                   targetSize);
+            buffer->set_range(buffer->range_offset() + bufferSize, 0);
+            return;
+        }
+    }
+}
+
+static void VpsSpsPpsParser(MediaBufferBase *buffer,
+        MediaBufferBase **vpsBuffer, MediaBufferBase **spsBuffer, MediaBufferBase **ppsBuffer) {
+
+    while (buffer->range_length() > 0) {
+        const uint8_t *NALPtr = (const uint8_t *)buffer->data() + buffer->range_offset();
+        uint8_t nalType = ((*NALPtr) >> 1) & H265_NALU_MASK;
+
+        MediaBufferBase **targetPtr = NULL;
+        if (nalType == H265_NALU_VPS) {
+            targetPtr = vpsBuffer;
+        } else if (nalType == H265_NALU_SPS) {
+            targetPtr = spsBuffer;
+        } else if (nalType == H265_NALU_PPS) {
+            targetPtr = ppsBuffer;
+        } else {
+            return;
+        }
+        ALOGV("VPS(32) SPS(33) or PPS(34) found. Type %d", nalType);
+
+        uint32_t bufferSize = buffer->range_length();
+        MediaBufferBase *&target = *targetPtr;
+        uint32_t i = 0, j = 0;
+        bool isBoundFound = false;
+        for (i = 0; i < bufferSize; i++) {
+            while (j > 0 && NALPtr[i] != startPrefixCode[j]) {
+                j = spcKMPidx[j - 1];
+            }
+            if (NALPtr[i] == startPrefixCode[j]) {
+                j++;
+                if (j == SPCSize) {
+                    isBoundFound = true;
+                    break;
+                }
+            }
+        }
+
+        if (target != NULL) {
+            target->release();
+        }
+        uint32_t targetSize;
+        // note that targetSize is never 0 as the first byte is never part
+        // of a start prefix
+        if (isBoundFound) {
+            targetSize = i - SPCSize + 1;
+            target = MediaBufferBase::Create(j);
+            memcpy(target->data(),
+                   (const uint8_t *)buffer->data() + buffer->range_offset(),
+                   j);
+            buffer->set_range(buffer->range_offset() + targetSize + SPCSize,
+                              buffer->range_length() - targetSize - SPCSize);
+        } else {
+            targetSize = bufferSize;
+            target = MediaBufferBase::Create(targetSize);
+            memcpy(target->data(),
+                   (const uint8_t *)buffer->data() + buffer->range_offset(),
+                   targetSize);
+            buffer->set_range(buffer->range_offset() + bufferSize, 0);
+            return;
+        }
+    }
+}
+
 void ARTPWriter::onMessageReceived(const sp<AMessage> &msg) {
     switch (msg->what()) {
         case kWhatStart:
         {
-            CHECK_EQ(mSource->start(), (status_t)OK);
+            sp<MetaData> meta = new MetaData();
+            meta->setInt64(kKeyTime, 10ll);
+            CHECK_EQ(mSource->start(meta.get()), (status_t)OK);
 
 #if 0
             if (mMode == H264) {
@@ -264,6 +522,18 @@
     }
 }
 
+void ARTPWriter::setTMMBNInfo(uint32_t opponentID, uint32_t bitrate) {
+    mOpponentID = opponentID;
+    mBitrate = bitrate;
+
+    sp<ABuffer> buffer = new ABuffer(65536);
+    buffer->setRange(0, 0);
+
+    addTMMBN(buffer);
+
+    send(buffer, true /* isRTCP */);
+}
+
 void ARTPWriter::onRead(const sp<AMessage> &msg) {
     MediaBufferBase *mediaBuf;
     status_t err = mSource->read(&mediaBuf);
@@ -281,7 +551,16 @@
 
         if (mMode == H264) {
             StripStartcode(mediaBuf);
-            sendAVCData(mediaBuf);
+            SpsPpsParser(mediaBuf, &mSPSBuf, &mPPSBuf);
+            if (mediaBuf->range_length() > 0) {
+                sendAVCData(mediaBuf);
+            }
+        } else if (mMode == H265) {
+            StripStartcode(mediaBuf);
+            VpsSpsPpsParser(mediaBuf, &mVPSBuf, &mSPSBuf, &mPPSBuf);
+            if (mediaBuf->range_length() > 0) {
+                sendHEVCData(mediaBuf);
+            }
         } else if (mMode == H263) {
             sendH263Data(mediaBuf);
         } else if (mMode == AMR_NB || mMode == AMR_WB) {
@@ -309,12 +588,39 @@
 }
 
 void ARTPWriter::send(const sp<ABuffer> &buffer, bool isRTCP) {
-    ssize_t n = sendto(
-            mSocket, buffer->data(), buffer->size(), 0,
-            (const struct sockaddr *)(isRTCP ? &mRTCPAddr : &mRTPAddr),
-            sizeof(mRTCPAddr));
+    int sizeSockSt;
+    struct sockaddr *remAddr;
 
-    CHECK_EQ(n, (ssize_t)buffer->size());
+    if (mIsIPv6) {
+        sizeSockSt = sizeof(struct sockaddr_in6);
+        if (isRTCP)
+            remAddr = (struct sockaddr *)&mRTCPAddr6;
+        else
+            remAddr = (struct sockaddr *)&mRTPAddr6;
+    } else {
+        sizeSockSt = sizeof(struct sockaddr_in);
+        if (isRTCP)
+            remAddr = (struct sockaddr *)&mRTCPAddr;
+        else
+            remAddr = (struct sockaddr *)&mRTPAddr;
+    }
+
+    // Unseal code if moderator is needed (prevent overflow of instant bandwidth)
+    // Set limit bits per period through the moderator.
+    // ex) 6KByte/10ms = 48KBit/10ms = 4.8MBit/s instant limit
+    // ModerateInstantTraffic(10, 6 * 1024);
+
+    ssize_t n = sendto(isRTCP ? mRTCPSocket : mRTPSocket,
+            buffer->data(), buffer->size(), 0, remAddr, sizeSockSt);
+
+    if (n != (ssize_t)buffer->size()) {
+        ALOGW("packets can not be sent. ret=%d, buf=%d", (int)n, (int)buffer->size());
+    } else {
+        // Record current traffic & Print bits while last 1sec (1000ms)
+        mTrafficRec->writeBytes(buffer->size() +
+                (mIsIPv6 ? TCPIPV6_HEADER_SIZE : TCPIPV4_HEADER_SIZE));
+        mTrafficRec->printAccuBitsForLastPeriod(1000, 1000);
+    }
 
 #if LOG_TO_FILES
     int fd = isRTCP ? mRTCPFd : mRTPFd;
@@ -379,7 +685,6 @@
 
     data[offset++] = 1;  // CNAME
 
-    static const char *kCNAME = "someone@somewhere";
     data[offset++] = strlen(kCNAME);
 
     memcpy(&data[offset], kCNAME, strlen(kCNAME));
@@ -416,9 +721,55 @@
     buffer->setRange(buffer->offset(), buffer->size() + offset);
 }
 
+void ARTPWriter::addTMMBN(const sp<ABuffer> &buffer) {
+    if (buffer->size() + 20 > buffer->capacity()) {
+        ALOGW("RTCP buffer too small to accommodate SR.");
+        return;
+    }
+    if (mOpponentID == 0)
+        return;
+
+    uint8_t *data = buffer->data() + buffer->size();
+
+    data[0] = 0x80 | 4; // TMMBN
+    data[1] = 205;      // TSFB
+    data[2] = 0;
+    data[3] = 4;        // total (4+1) * sizeof(int32_t) = 20 bytes
+    data[4] = mSourceID >> 24;
+    data[5] = (mSourceID >> 16) & 0xff;
+    data[6] = (mSourceID >> 8) & 0xff;
+    data[7] = mSourceID & 0xff;
+
+    *(int32_t*)(&data[8]) = 0;  // 4 bytes blank
+
+    data[12] = mOpponentID >> 24;
+    data[13] = (mOpponentID >> 16) & 0xff;
+    data[14] = (mOpponentID >> 8) & 0xff;
+    data[15] = mOpponentID & 0xff;
+
+    // Find the first bit '1' from left & right side of the value.
+    int32_t leftEnd = 31 - __builtin_clz(mBitrate);
+    int32_t rightEnd = ffs(mBitrate) - 1;
+
+    // Mantissa have only 17bit space by RTCP specification.
+    if ((leftEnd - rightEnd) > 16) {
+        rightEnd = leftEnd - 16;
+    }
+    int32_t mantissa = mBitrate >> rightEnd;
+
+    data[16] = ((rightEnd << 2) & 0xfc) | ((mantissa & 0x18000) >> 15);
+    data[17] =                             (mantissa & 0x07f80) >> 7;
+    data[18] =                             (mantissa & 0x0007f) << 1;
+    data[19] = 40;              // 40 bytes overhead;
+
+    buffer->setRange(buffer->offset(), buffer->size() + 20);
+
+    ALOGI("UE -> Op Noti Tx bitrate : %d ", mantissa << rightEnd);
+}
+
 // static
 uint64_t ARTPWriter::GetNowNTP() {
-    uint64_t nowUs = ALooper::GetNowUs();
+    uint64_t nowUs = systemTime(SYSTEM_TIME_REALTIME) / 1000ll;
 
     nowUs += ((70LL * 365 + 17) * 24) * 60 * 60 * 1000000LL;
 
@@ -463,7 +814,7 @@
         sdp.append("m=audio ");
     }
 
-    sdp.append(AStringPrintf("%d", ntohs(mRTPAddr.sin_port)));
+    sdp.append(AStringPrintf("%d", mIsIPv6 ? ntohs(mRTPAddr6.sin6_port) : ntohs(mRTPAddr.sin_port)));
     sdp.append(
           " RTP/AVP " PT_STR "\r\n"
           "b=AS 320000\r\n"
@@ -569,24 +920,91 @@
     send(buffer, true /* isRTCP */);
 }
 
-void ARTPWriter::sendAVCData(MediaBufferBase *mediaBuf) {
+void ARTPWriter::sendSPSPPSIfIFrame(MediaBufferBase *mediaBuf, int64_t timeUs) {
+    CHECK(mediaBuf->range_length() > 0);
+    const uint8_t *mediaData =
+        (const uint8_t *)mediaBuf->data() + mediaBuf->range_offset();
+
+    if ((mediaData[0] & H264_NALU_MASK) != H264_NALU_IFRAME) {
+        return;
+    }
+
+    if (mSPSBuf != NULL) {
+        mSPSBuf->meta_data().setInt64(kKeyTime, timeUs);
+        mSPSBuf->meta_data().setInt32(kKeySps, 1);
+        sendAVCData(mSPSBuf);
+    }
+
+    if (mPPSBuf != NULL) {
+        mPPSBuf->meta_data().setInt64(kKeyTime, timeUs);
+        mPPSBuf->meta_data().setInt32(kKeyPps, 1);
+        sendAVCData(mPPSBuf);
+    }
+}
+
+void ARTPWriter::sendVPSSPSPPSIfIFrame(MediaBufferBase *mediaBuf, int64_t timeUs) {
+    CHECK(mediaBuf->range_length() > 0);
+    const uint8_t *mediaData =
+        (const uint8_t *)mediaBuf->data() + mediaBuf->range_offset();
+
+    int nalType = ((mediaData[0] >> 1) & H265_NALU_MASK);
+    if (!(nalType >= 16 && nalType <= 21) /*H265_NALU_IFRAME*/) {
+        return;
+    }
+
+    if (mVPSBuf != NULL) {
+        mVPSBuf->meta_data().setInt64(kKeyTime, timeUs);
+        mVPSBuf->meta_data().setInt32(kKeyVps, 1);
+        sendHEVCData(mVPSBuf);
+    }
+
+    if (mSPSBuf != NULL) {
+        mSPSBuf->meta_data().setInt64(kKeyTime, timeUs);
+        mSPSBuf->meta_data().setInt32(kKeySps, 1);
+        sendHEVCData(mSPSBuf);
+    }
+
+    if (mPPSBuf != NULL) {
+        mPPSBuf->meta_data().setInt64(kKeyTime, timeUs);
+        mPPSBuf->meta_data().setInt32(kKeyPps, 1);
+        sendHEVCData(mPPSBuf);
+    }
+}
+
+void ARTPWriter::sendHEVCData(MediaBufferBase *mediaBuf) {
     // 12 bytes RTP header + 2 bytes for the FU-indicator and FU-header.
     CHECK_GE(kMaxPacketSize, 12u + 2u);
 
     int64_t timeUs;
     CHECK(mediaBuf->meta_data().findInt64(kKeyTime, &timeUs));
 
-    uint32_t rtpTime = mRTPTimeBase + (timeUs * 9 / 100LL);
+    sendVPSSPSPPSIfIFrame(mediaBuf, timeUs);
 
+    uint32_t rtpTime = mRTPTimeBase + (timeUs * 9 / 100ll);
+
+    CHECK(mediaBuf->range_length() > 0);
     const uint8_t *mediaData =
         (const uint8_t *)mediaBuf->data() + mediaBuf->range_offset();
 
+    int32_t isNonVCL = 0;
+    if (mediaBuf->meta_data().findInt32(kKeyVps, &isNonVCL) ||
+            mediaBuf->meta_data().findInt32(kKeySps, &isNonVCL) ||
+            mediaBuf->meta_data().findInt32(kKeyPps, &isNonVCL)) {
+        isNonVCL = 1;
+    }
+
     sp<ABuffer> buffer = new ABuffer(kMaxPacketSize);
-    if (mediaBuf->range_length() + 12 <= buffer->capacity()) {
+
+    if (mediaBuf->range_length() + TCPIP_HEADER_SIZE + RTP_HEADER_SIZE + RTP_HEADER_EXT_SIZE
+            + RTP_PAYLOAD_ROOM_SIZE <= buffer->capacity()) {
         // The data fits into a single packet
         uint8_t *data = buffer->data();
         data[0] = 0x80;
-        data[1] = (1 << 7) | PT;  // M-bit
+        if (isNonVCL) {
+            data[1] = mPayloadType;  // Marker bit should not be set in case of Non-VCL
+        } else {
+            data[1] = (1 << 7) | mPayloadType;  // M-bit
+        }
         data[2] = (mSeqNo >> 8) & 0xff;
         data[3] = mSeqNo & 0xff;
         data[4] = rtpTime >> 24;
@@ -611,21 +1029,24 @@
     } else {
         // FU-A
 
-        unsigned nalType = mediaData[0];
-        size_t offset = 1;
+        unsigned nalType = (mediaData[0] >> 1) & H265_NALU_MASK;
+        ALOGV("H265 nalType 0x%x, data[0]=0x%x", nalType, mediaData[0]);
+        size_t offset = 2; //H265 payload header is 16 bit.
 
         bool firstPacket = true;
         while (offset < mediaBuf->range_length()) {
             size_t size = mediaBuf->range_length() - offset;
             bool lastPacket = true;
-            if (size + 12 + 2 > buffer->capacity()) {
+            if (size + TCPIP_HEADER_SIZE + RTP_HEADER_SIZE + RTP_HEADER_EXT_SIZE +
+                    RTP_FU_HEADER_SIZE + RTP_PAYLOAD_ROOM_SIZE > buffer->capacity()) {
                 lastPacket = false;
-                size = buffer->capacity() - 12 - 2;
+                size = buffer->capacity() - TCPIP_HEADER_SIZE - RTP_HEADER_SIZE -
+                    RTP_HEADER_EXT_SIZE - RTP_FU_HEADER_SIZE - RTP_PAYLOAD_ROOM_SIZE;
             }
 
             uint8_t *data = buffer->data();
             data[0] = 0x80;
-            data[1] = (lastPacket ? (1 << 7) : 0x00) | PT;  // M-bit
+            data[1] = (lastPacket ? (1 << 7) : 0x00) | mPayloadType;  // M-bit
             data[2] = (mSeqNo >> 8) & 0xff;
             data[3] = mSeqNo & 0xff;
             data[4] = rtpTime >> 24;
@@ -637,18 +1058,39 @@
             data[10] = (mSourceID >> 8) & 0xff;
             data[11] = mSourceID & 0xff;
 
-            data[12] = 28 | (nalType & 0xe0);
+            /*  H265 payload header is 16 bit
+                 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+                |F|     Type  |  Layer ID | TID |
+                +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+            */
+            ALOGV("H265 payload header 0x%x %x", mediaData[0], mediaData[1]);
+            // excludes Type from 1st byte of H265 payload header.
+            data[12] = mediaData[0] & 0x81;
+            // fills Type as FU (49 == 0x31)
+            data[12] = data[12] | (0x31 << 1);
+            data[13] = mediaData[1];
+
+            ALOGV("H265 FU header 0x%x %x", data[12], data[13]);
 
             CHECK(!firstPacket || !lastPacket);
+            /*
+                FU INDICATOR HDR
+                0 1 2 3 4 5 6 7
+                +-+-+-+-+-+-+-+
+                |S|E|   Type  |
+                +-+-+-+-+-+-+-+
+            */
 
-            data[13] =
+            data[14] =
                 (firstPacket ? 0x80 : 0x00)
                 | (lastPacket ? 0x40 : 0x00)
-                | (nalType & 0x1f);
+                | (nalType & H265_NALU_MASK);
+            ALOGV("H265 FU indicator 0x%x", data[14]);
 
-            memcpy(&data[14], &mediaData[offset], size);
+            memcpy(&data[15], &mediaData[offset], size);
 
-            buffer->setRange(0, 14 + size);
+            buffer->setRange(0, 15 + size);
 
             send(buffer, false /* isRTCP */);
 
@@ -663,6 +1105,172 @@
 
     mLastRTPTime = rtpTime;
     mLastNTPTime = GetNowNTP();
+
+}
+
+void ARTPWriter::sendAVCData(MediaBufferBase *mediaBuf) {
+    // 12 bytes RTP header + 2 bytes for the FU-indicator and FU-header.
+    CHECK_GE(kMaxPacketSize, 12u + 2u);
+
+    int64_t timeUs;
+    CHECK(mediaBuf->meta_data().findInt64(kKeyTime, &timeUs));
+
+    sendSPSPPSIfIFrame(mediaBuf, timeUs);
+
+    uint32_t rtpTime = mRTPTimeBase + (timeUs * 9 / 100LL);
+
+    CHECK(mediaBuf->range_length() > 0);
+    const uint8_t *mediaData =
+        (const uint8_t *)mediaBuf->data() + mediaBuf->range_offset();
+
+    int32_t sps, pps;
+    bool isSpsPps = false;
+    if (mediaBuf->meta_data().findInt32(kKeySps, &sps) ||
+            mediaBuf->meta_data().findInt32(kKeyPps, &pps)) {
+        isSpsPps = true;
+    }
+
+    mTrafficRec->updateClock(ALooper::GetNowUs() / 1000);
+    sp<ABuffer> buffer = new ABuffer(kMaxPacketSize);
+    if (mediaBuf->range_length() + TCPIP_HEADER_SIZE + RTP_HEADER_SIZE + RTP_HEADER_EXT_SIZE
+            + RTP_PAYLOAD_ROOM_SIZE <= buffer->capacity()) {
+        // The data fits into a single packet
+        uint8_t *data = buffer->data();
+        data[0] = 0x80;
+        if (mRTPCVOExtMap > 0)
+            data[0] |= 0x10;
+        if (isSpsPps)
+            data[1] = mPayloadType;  // Marker bit should not be set in case of sps/pps
+        else
+            data[1] = (1 << 7) | mPayloadType;
+        data[2] = (mSeqNo >> 8) & 0xff;
+        data[3] = mSeqNo & 0xff;
+        data[4] = rtpTime >> 24;
+        data[5] = (rtpTime >> 16) & 0xff;
+        data[6] = (rtpTime >> 8) & 0xff;
+        data[7] = rtpTime & 0xff;
+        data[8] = mSourceID >> 24;
+        data[9] = (mSourceID >> 16) & 0xff;
+        data[10] = (mSourceID >> 8) & 0xff;
+        data[11] = mSourceID & 0xff;
+
+        int rtpExtIndex = 0;
+        if (mRTPCVOExtMap > 0) {
+            /*
+                0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+               |       0xBE    |    0xDE       |           length=3            |
+               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+               |  ID   | L=0   |     data      |  ID   |  L=1  |   data...
+               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+                     ...data   |    0 (pad)    |    0 (pad)    |  ID   | L=3   |
+               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+               |                          data                                 |
+               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+
+
+              In the one-byte header form of extensions, the 16-bit value required
+              by the RTP specification for a header extension, labeled in the RTP
+              specification as "defined by profile", takes the fixed bit pattern
+              0xBEDE (the first version of this specification was written on the
+              feast day of the Venerable Bede).
+            */
+            data[12] = 0xBE;
+            data[13] = 0xDE;
+            // put a length of RTP Extension.
+            data[14] = 0x00;
+            data[15] = 0x01;
+            // put extmap of RTP assigned for CVO.
+            data[16] = (mRTPCVOExtMap << 4) | 0x0;
+            // put image degrees as per CVO specification.
+            data[17] = mRTPCVODegrees;
+            data[18] = 0x0;
+            data[19] = 0x0;
+            rtpExtIndex = 8;
+        }
+
+        memcpy(&data[12 + rtpExtIndex],
+               mediaData, mediaBuf->range_length());
+
+        buffer->setRange(0, mediaBuf->range_length() + (12 + rtpExtIndex));
+
+        send(buffer, false /* isRTCP */);
+
+        ++mSeqNo;
+        ++mNumRTPSent;
+        mNumRTPOctetsSent += buffer->size() - (12 + rtpExtIndex);
+    } else {
+        // FU-A
+
+        unsigned nalType = mediaData[0];
+        size_t offset = 1;
+
+        bool firstPacket = true;
+        while (offset < mediaBuf->range_length()) {
+            size_t size = mediaBuf->range_length() - offset;
+            bool lastPacket = true;
+            if (size + TCPIP_HEADER_SIZE + RTP_HEADER_SIZE + RTP_HEADER_EXT_SIZE +
+                    RTP_FU_HEADER_SIZE + RTP_PAYLOAD_ROOM_SIZE > buffer->capacity()) {
+                lastPacket = false;
+                size = buffer->capacity() - TCPIP_HEADER_SIZE - RTP_HEADER_SIZE -
+                    RTP_HEADER_EXT_SIZE - RTP_FU_HEADER_SIZE - RTP_PAYLOAD_ROOM_SIZE;
+            }
+
+            uint8_t *data = buffer->data();
+            data[0] = 0x80;
+            if (lastPacket && mRTPCVOExtMap > 0)
+                data[0] |= 0x10;
+            data[1] = (lastPacket ? (1 << 7) : 0x00) | mPayloadType;  // M-bit
+            data[2] = (mSeqNo >> 8) & 0xff;
+            data[3] = mSeqNo & 0xff;
+            data[4] = rtpTime >> 24;
+            data[5] = (rtpTime >> 16) & 0xff;
+            data[6] = (rtpTime >> 8) & 0xff;
+            data[7] = rtpTime & 0xff;
+            data[8] = mSourceID >> 24;
+            data[9] = (mSourceID >> 16) & 0xff;
+            data[10] = (mSourceID >> 8) & 0xff;
+            data[11] = mSourceID & 0xff;
+
+            int rtpExtIndex = 0;
+            if (lastPacket && mRTPCVOExtMap > 0) {
+                data[12] = 0xBE;
+                data[13] = 0xDE;
+                data[14] = 0x00;
+                data[15] = 0x01;
+                data[16] = (mRTPCVOExtMap << 4) | 0x0;
+                data[17] = mRTPCVODegrees;
+                data[18] = 0x0;
+                data[19] = 0x0;
+                rtpExtIndex = 8;
+            }
+
+            data[12 + rtpExtIndex] = 28 | (nalType & 0xe0);
+
+            CHECK(!firstPacket || !lastPacket);
+
+            data[13 + rtpExtIndex] =
+                (firstPacket ? 0x80 : 0x00)
+                | (lastPacket ? 0x40 : 0x00)
+                | (nalType & 0x1f);
+
+            memcpy(&data[14 + rtpExtIndex], &mediaData[offset], size);
+
+            buffer->setRange(0, 14 + rtpExtIndex + size);
+
+            send(buffer, false /* isRTCP */);
+
+            ++mSeqNo;
+            ++mNumRTPSent;
+            mNumRTPOctetsSent += buffer->size() - (12 + rtpExtIndex);
+
+            firstPacket = false;
+            offset += size;
+        }
+    }
+
+    mLastRTPTime = rtpTime;
+    mLastNTPTime = GetNowNTP();
 }
 
 void ARTPWriter::sendH263Data(MediaBufferBase *mediaBuf) {
@@ -696,7 +1304,7 @@
 
         uint8_t *data = buffer->data();
         data[0] = 0x80;
-        data[1] = (lastPacket ? 0x80 : 0x00) | PT;  // M-bit
+        data[1] = (lastPacket ? 0x80 : 0x00) | mPayloadType;  // M-bit
         data[2] = (mSeqNo >> 8) & 0xff;
         data[3] = mSeqNo & 0xff;
         data[4] = rtpTime >> 24;
@@ -727,6 +1335,58 @@
     mLastNTPTime = GetNowNTP();
 }
 
+void ARTPWriter::updateCVODegrees(int32_t cvoDegrees) {
+    Mutex::Autolock autoLock(mLock);
+    mRTPCVODegrees = cvoDegrees;
+}
+
+void ARTPWriter::updatePayloadType(int32_t payloadType) {
+    Mutex::Autolock autoLock(mLock);
+    mPayloadType = payloadType;
+}
+
+void ARTPWriter::updateSocketDscp(int32_t dscp) {
+    mRtpLayer3Dscp = dscp << 2;
+
+    /* mRtpLayer3Dscp will be mapped to WMM(Wifi) as per operator's requirement */
+    if (setsockopt(mRTPSocket, IPPROTO_IP, IP_TOS,
+                (int *)&mRtpLayer3Dscp, sizeof(mRtpLayer3Dscp)) < 0) {
+        ALOGE("failed to set dscp on rtpsock. err=%s", strerror(errno));
+    } else {
+        ALOGD("successfully set dscp on rtpsock. opt=%d", mRtpLayer3Dscp);
+        setsockopt(mRTCPSocket, IPPROTO_IP, IP_TOS,
+                (int *)&mRtpLayer3Dscp, sizeof(mRtpLayer3Dscp));
+        ALOGD("successfully set dscp on rtcpsock. opt=%d", mRtpLayer3Dscp);
+    }
+}
+
+void ARTPWriter::updateSocketNetwork(int64_t socketNetwork) {
+    mRTPSockNetwork = (net_handle_t)socketNetwork;
+    ALOGI("trying to bind rtp socket(%d) to network(%llu).",
+                mRTPSocket, (unsigned long long)mRTPSockNetwork);
+
+    int result = android_setsocknetwork(mRTPSockNetwork, mRTPSocket);
+    if (result != 0) {
+        ALOGW("failed(%d) to bind rtp socket(%d) to network(%llu)",
+                result, mRTPSocket, (unsigned long long)mRTPSockNetwork);
+    }
+    result = android_setsocknetwork(mRTPSockNetwork, mRTCPSocket);
+    if (result != 0) {
+        ALOGW("failed(%d) to bind rtcp socket(%d) to network(%llu)",
+                result, mRTCPSocket, (unsigned long long)mRTPSockNetwork);
+    }
+    ALOGI("done. bind rtp socket(%d) to network(%llu)",
+                mRTPSocket, (unsigned long long)mRTPSockNetwork);
+}
+
+uint32_t ARTPWriter::getSequenceNum() {
+    return mSeqNo;
+}
+
+uint64_t ARTPWriter::getAccumulativeBytes() {
+    return mTrafficRec->readBytesForTotal();
+}
+
 static size_t getFrameSize(bool isWide, unsigned FT) {
     static const size_t kFrameSizeNB[8] = {
         95, 103, 118, 134, 148, 159, 204, 244
@@ -778,7 +1438,7 @@
     // The data fits into a single packet
     uint8_t *data = buffer->data();
     data[0] = 0x80;
-    data[1] = PT;
+    data[1] = mPayloadType;
     if (mNumRTPSent == 0) {
         // Signal start of talk-spurt.
         data[1] |= 0x80;  // M-bit
@@ -834,5 +1494,91 @@
     mLastNTPTime = GetNowNTP();
 }
 
-}  // namespace android
+void ARTPWriter::makeSocketPairAndBind(String8& localIp, int localPort,
+        String8& remoteIp, int remotePort) {
+    static char kSomeone[16] = "someone@";
+    int nameLength = strlen(kSomeone);
+    memcpy(kCNAME, kSomeone, nameLength);
+    memcpy(kCNAME + nameLength, localIp.c_str(), localIp.length() + 1);
 
+    if (localIp.contains(":"))
+        mIsIPv6 = true;
+    else
+        mIsIPv6 = false;
+
+    mRTPSocket = socket(mIsIPv6 ? AF_INET6 : AF_INET, SOCK_DGRAM, 0);
+    CHECK_GE(mRTPSocket, 0);
+    mRTCPSocket = socket(mIsIPv6 ? AF_INET6 : AF_INET, SOCK_DGRAM, 0);
+    CHECK_GE(mRTCPSocket, 0);
+
+    int sockopt = 1;
+    setsockopt(mRTPSocket, SOL_SOCKET, SO_REUSEADDR, (int *)&sockopt, sizeof(sockopt));
+    setsockopt(mRTCPSocket, SOL_SOCKET, SO_REUSEADDR, (int *)&sockopt, sizeof(sockopt));
+
+    if (mIsIPv6) {
+        memset(&mLocalAddr6, 0, sizeof(mLocalAddr6));
+        memset(&mRTPAddr6, 0, sizeof(mRTPAddr6));
+        memset(&mRTCPAddr6, 0, sizeof(mRTCPAddr6));
+
+        mLocalAddr6.sin6_family = AF_INET6;
+        inet_pton(AF_INET6, localIp.string(), &mLocalAddr6.sin6_addr);
+        mLocalAddr6.sin6_port = htons((uint16_t)localPort);
+
+        mRTPAddr6.sin6_family = AF_INET6;
+        inet_pton(AF_INET6, remoteIp.string(), &mRTPAddr6.sin6_addr);
+        mRTPAddr6.sin6_port = htons((uint16_t)remotePort);
+
+        mRTCPAddr6 = mRTPAddr6;
+        mRTCPAddr6.sin6_port = htons((uint16_t)(remotePort + 1));
+    } else {
+        memset(&mLocalAddr, 0, sizeof(mLocalAddr));
+        memset(&mRTPAddr, 0, sizeof(mRTPAddr));
+        memset(&mRTCPAddr, 0, sizeof(mRTCPAddr));
+
+        mLocalAddr.sin_family = AF_INET;
+        mLocalAddr.sin_addr.s_addr = inet_addr(localIp.string());
+        mLocalAddr.sin_port = htons((uint16_t)localPort);
+
+        mRTPAddr.sin_family = AF_INET;
+        mRTPAddr.sin_addr.s_addr = inet_addr(remoteIp.string());
+        mRTPAddr.sin_port = htons((uint16_t)remotePort);
+
+        mRTCPAddr = mRTPAddr;
+        mRTCPAddr.sin_port = htons((uint16_t)(remotePort + 1));
+    }
+
+    struct sockaddr *localAddr = mIsIPv6 ?
+        (struct sockaddr*)&mLocalAddr6 : (struct sockaddr*)&mLocalAddr;
+
+    int sizeSockSt = mIsIPv6 ? sizeof(mLocalAddr6) : sizeof(mLocalAddr);
+
+    if (bind(mRTPSocket, localAddr, sizeSockSt) == -1) {
+        ALOGE("failed to bind rtp %s:%d err=%s", localIp.string(), localPort, strerror(errno));
+    } else {
+        ALOGD("succeed to bind rtp %s:%d", localIp.string(), localPort);
+    }
+
+    if (mIsIPv6)
+        mLocalAddr6.sin6_port = htons((uint16_t)(localPort + 1));
+    else
+        mLocalAddr.sin_port = htons((uint16_t)(localPort + 1));
+
+    if (bind(mRTCPSocket, localAddr, sizeSockSt) == -1) {
+        ALOGE("failed to bind rtcp %s:%d err=%s", localIp.string(), localPort + 1, strerror(errno));
+    } else {
+        ALOGD("succeed to bind rtcp %s:%d", localIp.string(), localPort + 1);
+    }
+}
+
+// TODO : Develop more advanced moderator based on AS & TMMBR value
+void ARTPWriter::ModerateInstantTraffic(uint32_t samplePeriod, uint32_t limitBytes) {
+    unsigned int bytes =  mTrafficRec->readBytesForLastPeriod(samplePeriod);
+    if (bytes > limitBytes) {
+        ALOGI("Nuclear moderator. #seq = %d \t\t %d bits / 10ms",
+              mSeqNo, bytes * 8);
+        usleep(4000);
+        mTrafficRec->updateClock(ALooper::GetNowUs() / 1000);
+    }
+}
+
+}  // namespace android
diff --git a/media/libstagefright/rtsp/ARTPWriter.h b/media/libstagefright/rtsp/ARTPWriter.h
index 2f13486..28d6ec5 100644
--- a/media/libstagefright/rtsp/ARTPWriter.h
+++ b/media/libstagefright/rtsp/ARTPWriter.h
@@ -27,6 +27,9 @@
 #include <arpa/inet.h>
 #include <sys/socket.h>
 
+#include <android/multinetwork.h>
+#include "TrafficRecorder.h"
+
 #define LOG_TO_FILES    0
 
 namespace android {
@@ -36,14 +39,24 @@
 
 struct ARTPWriter : public MediaWriter {
     explicit ARTPWriter(int fd);
+    explicit ARTPWriter(int fd, String8& localIp, int localPort,
+                                String8& remoteIp, int remotePort,
+                                uint32_t seqNo);
 
     virtual status_t addSource(const sp<MediaSource> &source);
     virtual bool reachedEOS();
     virtual status_t start(MetaData *params);
     virtual status_t stop();
     virtual status_t pause();
+    void updateCVODegrees(int32_t cvoDegrees);
+    void updatePayloadType(int32_t payloadType);
+    void updateSocketDscp(int32_t dscp);
+    void updateSocketNetwork(int64_t socketNetwork);
+    uint32_t getSequenceNum();
+    virtual uint64_t getAccumulativeBytes() override;
 
     virtual void onMessageReceived(const sp<AMessage> &msg);
+    virtual void setTMMBNInfo(uint32_t opponentID, uint32_t bitrate);
 
 protected:
     virtual ~ARTPWriter();
@@ -76,15 +89,27 @@
     sp<ALooper> mLooper;
     sp<AHandlerReflector<ARTPWriter> > mReflector;
 
-    int mSocket;
+    bool mIsIPv6;
+    int mRTPSocket, mRTCPSocket;
+    struct sockaddr_in mLocalAddr;
     struct sockaddr_in mRTPAddr;
     struct sockaddr_in mRTCPAddr;
+    struct sockaddr_in6 mLocalAddr6;
+    struct sockaddr_in6 mRTPAddr6;
+    struct sockaddr_in6 mRTCPAddr6;
+    int32_t mRtpLayer3Dscp;
+    net_handle_t mRTPSockNetwork;
 
     AString mProfileLevel;
     AString mSeqParamSet;
     AString mPicParamSet;
 
+    MediaBufferBase *mVPSBuf;
+    MediaBufferBase *mSPSBuf;
+    MediaBufferBase *mPPSBuf;
+
     uint32_t mSourceID;
+    uint32_t mPayloadType;
     uint32_t mSeqNo;
     uint32_t mRTPTimeBase;
     uint32_t mNumRTPSent;
@@ -92,10 +117,18 @@
     uint32_t mLastRTPTime;
     uint64_t mLastNTPTime;
 
+    uint32_t mOpponentID;
+    uint32_t mBitrate;
+    typedef uint64_t Bytes;
+    sp<TrafficRecorder<uint32_t /* Time */, Bytes> > mTrafficRec;
+
     int32_t mNumSRsSent;
+    int32_t mRTPCVOExtMap;
+    int32_t mRTPCVODegrees;
 
     enum {
         INVALID,
+        H265,
         H264,
         H263,
         AMR_NB,
@@ -104,22 +137,29 @@
 
     static uint64_t GetNowNTP();
 
+    void initState();
     void onRead(const sp<AMessage> &msg);
     void onSendSR(const sp<AMessage> &msg);
 
     void addSR(const sp<ABuffer> &buffer);
     void addSDES(const sp<ABuffer> &buffer);
+    void addTMMBN(const sp<ABuffer> &buffer);
 
     void makeH264SPropParamSets(MediaBufferBase *buffer);
     void dumpSessionDesc();
 
     void sendBye();
+    void sendVPSSPSPPSIfIFrame(MediaBufferBase *mediaBuf, int64_t timeUs);
+    void sendSPSPPSIfIFrame(MediaBufferBase *mediaBuf, int64_t timeUs);
+    void sendHEVCData(MediaBufferBase *mediaBuf);
     void sendAVCData(MediaBufferBase *mediaBuf);
     void sendH263Data(MediaBufferBase *mediaBuf);
     void sendAMRData(MediaBufferBase *mediaBuf);
 
     void send(const sp<ABuffer> &buffer, bool isRTCP);
+    void makeSocketPairAndBind(String8& localIp, int localPort, String8& remoteIp, int remotePort);
 
+    void ModerateInstantTraffic(uint32_t samplePeriod, uint32_t limitBytes);
     DISALLOW_EVIL_CONSTRUCTORS(ARTPWriter);
 };
 
diff --git a/media/libstagefright/rtsp/ARTSPConnection.cpp b/media/libstagefright/rtsp/ARTSPConnection.cpp
index bb66f4c..c33bf3f 100644
--- a/media/libstagefright/rtsp/ARTSPConnection.cpp
+++ b/media/libstagefright/rtsp/ARTSPConnection.cpp
@@ -329,6 +329,7 @@
     mPass.clear();
     mAuthType = NONE;
     mNonce.clear();
+    mRealm.clear();
 
     mState = DISCONNECTED;
 }
@@ -911,6 +912,14 @@
         CHECK_GE(j, 0);
 
         mNonce.setTo(value, i + 7, j - i - 7);
+
+        i = value.find("realm=");
+        CHECK_GE(i, 0);
+        CHECK_EQ(value.c_str()[i + 6], '\"');
+        j = value.find("\"", i + 7);
+        CHECK_GE(j, 0);
+
+        mRealm.setTo(value, i + 7, j - i - 7);
     }
 
     return true;
@@ -993,7 +1002,7 @@
     AString A1;
     A1.append(mUser);
     A1.append(":");
-    A1.append("Streaming Server");
+    A1.append(mRealm);
     A1.append(":");
     A1.append(mPass);
 
@@ -1029,6 +1038,9 @@
     fragment.append("\", ");
     fragment.append("response=\"");
     fragment.append(digest);
+    fragment.append("\", ");
+    fragment.append("realm=\"");
+    fragment.append(mRealm);
     fragment.append("\"");
     fragment.append("\r\n");
 
diff --git a/media/libstagefright/rtsp/ARTSPConnection.h b/media/libstagefright/rtsp/ARTSPConnection.h
index 56b604d..7cdd4c0 100644
--- a/media/libstagefright/rtsp/ARTSPConnection.h
+++ b/media/libstagefright/rtsp/ARTSPConnection.h
@@ -84,6 +84,7 @@
     AString mUser, mPass;
     AuthType mAuthType;
     AString mNonce;
+    AString mRealm;
     int mSocket;
     int32_t mConnectionID;
     int32_t mNextCSeq;
diff --git a/media/libstagefright/rtsp/ASessionDescription.cpp b/media/libstagefright/rtsp/ASessionDescription.cpp
index 2b42040..5b5b4b1 100644
--- a/media/libstagefright/rtsp/ASessionDescription.cpp
+++ b/media/libstagefright/rtsp/ASessionDescription.cpp
@@ -27,6 +27,8 @@
 
 namespace android {
 
+constexpr unsigned kDefaultAs = 960; // kbps?
+
 ASessionDescription::ASessionDescription()
     : mIsValid(false) {
 }
@@ -103,7 +105,7 @@
                     key.setTo(line, 0, colonPos);
 
                     if (key == "a=fmtp" || key == "a=rtpmap"
-                            || key == "a=framesize") {
+                            || key == "a=framesize" || key == "a=extmap") {
                         ssize_t spacePos = line.find(" ", colonPos + 1);
                         if (spacePos < 0) {
                             return false;
@@ -201,6 +203,33 @@
     return true;
 }
 
+bool ASessionDescription::getCvoExtMap(
+        size_t index, int32_t *cvoExtMap) const {
+    CHECK_GE(index, 0u);
+    CHECK_LT(index, mTracks.size());
+
+    AString key, value;
+    *cvoExtMap = 0;
+
+    const Attribs &track = mTracks.itemAt(index);
+    for (size_t i = 0; i < track.size(); i++) {
+        value = track.valueAt(i);
+        if (value.size() > 0 && strcmp(value.c_str(), "urn:3gpp:video-orientation") == 0) {
+            key = track.keyAt(i);
+            break;
+        }
+    }
+
+    if (key.size() > 0) {
+        const char *colonPos = strrchr(key.c_str(), ':');
+        colonPos++;
+        *cvoExtMap = atoi(colonPos);
+        return true;
+    }
+
+    return false;
+}
+
 void ASessionDescription::getFormatType(
         size_t index, unsigned long *PT,
         AString *desc, AString *params) const {
@@ -345,5 +374,74 @@
     return *npt2 > *npt1;
 }
 
+// static
+void ASessionDescription::SDPStringFactory(AString &sdp,
+        const char *ip, bool isAudio, unsigned port, unsigned payloadType,
+        unsigned as, const char *codec, const char *fmtp,
+        int32_t width, int32_t height, int32_t cvoExtMap)
+{
+    bool isIPv4 = (AString(ip).find("::") == -1) ? true : false;
+    sdp.clear();
+    sdp.append("v=0\r\n");
+
+    sdp.append("a=range:npt=now-\r\n");
+
+    sdp.append("m=");
+    sdp.append(isAudio ? "audio " : "video ");
+    sdp.append(port);
+    sdp.append(" RTP/AVP ");
+    sdp.append(payloadType);
+    sdp.append("\r\n");
+
+    sdp.append("c= IN IP");
+    if (isIPv4) {
+        sdp.append("4 ");
+    } else {
+        sdp.append("6 ");
+    }
+    sdp.append(ip);
+    sdp.append("\r\n");
+
+    sdp.append("b=AS:");
+    sdp.append(as > 0 ? as : kDefaultAs);
+    sdp.append("\r\n");
+
+    sdp.append("a=rtpmap:");
+    sdp.append(payloadType);
+    sdp.append(" ");
+    sdp.append(codec);
+    sdp.append("/");
+    sdp.append(isAudio ? "8000" : "90000");
+    sdp.append("\r\n");
+
+    if (fmtp != NULL) {
+        sdp.append("a=fmtp:");
+        sdp.append(payloadType);
+        sdp.append(" ");
+        sdp.append(fmtp);
+        sdp.append("\r\n");
+    }
+
+    if (!isAudio && width > 0 && height > 0) {
+        sdp.append("a=framesize:");
+        sdp.append(payloadType);
+        sdp.append(" ");
+        sdp.append(width);
+        sdp.append("-");
+        sdp.append(height);
+        sdp.append("\r\n");
+    }
+
+    if (cvoExtMap > 0) {
+        sdp.append("a=extmap:");
+        sdp.append(cvoExtMap);
+        sdp.append(" ");
+        sdp.append("urn:3gpp:video-orientation");
+        sdp.append("\r\n");
+    }
+
+    ALOGV("SDPStringFactory => %s", sdp.c_str());
+}
+
 }  // namespace android
 
diff --git a/media/libstagefright/rtsp/ASessionDescription.h b/media/libstagefright/rtsp/ASessionDescription.h
index b462983..91f5442 100644
--- a/media/libstagefright/rtsp/ASessionDescription.h
+++ b/media/libstagefright/rtsp/ASessionDescription.h
@@ -40,6 +40,8 @@
     size_t countTracks() const;
     void getFormat(size_t index, AString *value) const;
 
+    bool getCvoExtMap(size_t index, int32_t *cvoExtMap) const;
+
     void getFormatType(
             size_t index, unsigned long *PT,
             AString *desc, AString *params) const;
@@ -63,6 +65,9 @@
     // i.e. we have a fixed duration, otherwise this is live streaming.
     static bool parseNTPRange(const char *s, float *npt1, float *npt2);
 
+    static void SDPStringFactory(AString &sdp, const char *ip, bool isAudio, unsigned port,
+        unsigned payloadType, unsigned as, const char *codec, const char *fmtp = NULL,
+        int32_t width = 0, int32_t height = 0, int32_t cvoExtMap = 0);
 protected:
     virtual ~ASessionDescription();
 
diff --git a/media/libstagefright/rtsp/Android.bp b/media/libstagefright/rtsp/Android.bp
index a5a895e..dcadbaf 100644
--- a/media/libstagefright/rtsp/Android.bp
+++ b/media/libstagefright/rtsp/Android.bp
@@ -1,9 +1,29 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_rtsp_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_rtsp_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_defaults {
     name: "libstagefright_rtsp_defaults",
 
     srcs: [
         "AAMRAssembler.cpp",
         "AAVCAssembler.cpp",
+        "AHEVCAssembler.cpp",
         "AH263Assembler.cpp",
         "AMPEG2TSAssembler.cpp",
         "AMPEG4AudioAssembler.cpp",
@@ -20,6 +40,7 @@
     ],
 
     shared_libs: [
+        "libandroid_net",
         "libcrypto",
         "libdatasource",
         "libmedia",
@@ -28,6 +49,7 @@
     include_dirs: [
         "frameworks/av/media/libstagefright",
         "frameworks/native/include/media/openmax",
+        "frameworks/native/include/android",
     ],
 
     arch: {
diff --git a/media/libstagefright/rtsp/MyHandler.h b/media/libstagefright/rtsp/MyHandler.h
index 7f025a5..0fdf431 100644
--- a/media/libstagefright/rtsp/MyHandler.h
+++ b/media/libstagefright/rtsp/MyHandler.h
@@ -1032,6 +1032,11 @@
                     break;
                 }
 
+                int32_t rtcpEvent;
+                if (msg->findInt32("rtcp-event", &rtcpEvent)) {
+                    break;
+                }
+
                 ++mNumAccessUnitsReceived;
                 postAccessUnitTimeoutCheck();
 
diff --git a/media/libstagefright/rtsp/NetworkUtils.cpp b/media/libstagefright/rtsp/NetworkUtils.cpp
index cc36b78..c053be8 100644
--- a/media/libstagefright/rtsp/NetworkUtils.cpp
+++ b/media/libstagefright/rtsp/NetworkUtils.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <unistd.h>
+
 //#define LOG_NDEBUG 0
 #define LOG_TAG "NetworkUtils"
 #include <utils/Log.h>
diff --git a/media/libstagefright/rtsp/QualManager.cpp b/media/libstagefright/rtsp/QualManager.cpp
new file mode 100644
index 0000000..37aa326
--- /dev/null
+++ b/media/libstagefright/rtsp/QualManager.cpp
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2018 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 "QualManager"
+
+#include <algorithm>
+
+#include <sys/prctl.h>
+#include <utils/Log.h>
+
+#include "QualManager.h"
+
+namespace android {
+
+QualManager::Watcher::Watcher(int32_t timeLimit)
+    : Thread(false), mWatching(false), mSwitch(false),
+      mTimeLimit(timeLimit * 1000000LL)     // timeLimit ms
+{
+}
+
+bool QualManager::Watcher::isExpired() const
+{
+    return mSwitch;
+}
+
+void QualManager::Watcher::setup() {
+    AutoMutex _l(mMyLock);
+    if (mWatching == false) {
+        mWatching = true;
+        mMyCond.signal();
+    }
+}
+
+void QualManager::Watcher::release() {
+    AutoMutex _l(mMyLock);
+    if (mSwitch) {
+        ALOGW("%s DISARMED", name);
+        mSwitch = false;
+    }
+    if (mWatching == true) {
+        ALOGW("%s DISARMED", name);
+        mWatching = false;
+        mMyCond.signal();
+    }
+}
+
+void QualManager::Watcher::exit() {
+    AutoMutex _l(mMyLock);
+    // The order is important to avoid dead lock.
+    Thread::requestExit();
+    mMyCond.signal();
+}
+
+QualManager::Watcher::~Watcher() {
+    ALOGI("%s thread dead", name);
+}
+
+bool QualManager::Watcher::threadLoop() {
+    AutoMutex _l(mMyLock);
+#if defined(__linux__)
+    prctl(PR_GET_NAME, name, 0, 0, 0);
+#endif
+    while (!exitPending()) {
+        ALOGW("%s Timer init", name);
+        mMyCond.wait(mMyLock);                      // waits as non-watching state
+        if (exitPending())
+            return false;
+        ALOGW("%s timer BOOM after %d msec", name, (int)(mTimeLimit / 1000000LL));
+        mMyCond.waitRelative(mMyLock, mTimeLimit);  // waits as watching satte
+        if (mWatching == true) {
+            mSwitch = true;
+            ALOGW("%s BOOM!!!!", name);
+        }
+        mWatching = false;
+    }
+    return false;
+}
+
+
+QualManager::QualManager()
+    : mMinBitrate(-1), mMaxBitrate(-1),
+      mTargetBitrate(512000), mLastTargetBitrate(-1),
+      mLastSetBitrateTime(0), mIsNewTargetBitrate(false)
+{
+    VFPWatcher = new Watcher(3000);     //Very Few Packet Watcher
+    VFPWatcher->run("VeryFewPtk");
+    LBRWatcher = new Watcher(10000);    //Low Bit Rate Watcher
+    LBRWatcher->run("LowBitRate");
+}
+
+QualManager::~QualManager() {
+    VFPWatcher->exit();
+    LBRWatcher->exit();
+}
+
+int32_t QualManager::getTargetBitrate() {
+    if (mIsNewTargetBitrate) {
+        mIsNewTargetBitrate = false;
+        mLastTargetBitrate = clampingBitrate(mTargetBitrate);
+        mTargetBitrate = mLastTargetBitrate;
+        return mTargetBitrate;
+    } else {
+        return -1;
+    }
+}
+
+bool QualManager::isNeedToDowngrade() {
+    return LBRWatcher->isExpired();
+}
+
+void QualManager::setTargetBitrate(uint8_t fraction, int64_t nowUs, bool isTooLowPkts) {
+    /* Too Low Packet. Maybe opponent is switching camera.
+     * If this condition goes longer, we should down bitrate.
+     */
+    if (isTooLowPkts) {
+        VFPWatcher->setup();
+    } else {
+        VFPWatcher->release();
+    }
+
+    if ((fraction > (256 * 5 / 100) && !isTooLowPkts) || VFPWatcher->isExpired()) {
+        // loss more than 5%                          or  VFPWatcher BOOMED
+        mTargetBitrate -= mBitrateStep * 3;
+    } else if (fraction <= (256 * 2 /100)) {
+        // loss less than 2%
+        mTargetBitrate += mBitrateStep;
+    }
+
+    if (mTargetBitrate > mMaxBitrate) {
+        mTargetBitrate = mMaxBitrate + mBitrateStep;
+    } else if (mTargetBitrate < mMinBitrate) {
+        LBRWatcher->setup();
+        mTargetBitrate = mMinBitrate - mBitrateStep;
+    }
+
+    if (mLastTargetBitrate != clampingBitrate(mTargetBitrate) ||
+        nowUs - mLastSetBitrateTime > 5000000ll) {
+        mIsNewTargetBitrate = true;
+        mLastSetBitrateTime = nowUs;
+    }
+}
+
+void QualManager::setMinMaxBitrate(int32_t min, int32_t max) {
+    mMinBitrate = min;
+    mMaxBitrate = max;
+    mBitrateStep = (max - min) / 8;
+}
+
+void QualManager::setBitrateData(int32_t bitrate, int64_t /*now*/) {
+    // A bitrate that is considered packetloss also should be good.
+    if (bitrate >= mMinBitrate && mTargetBitrate >= mMinBitrate) {
+        LBRWatcher->release();
+    } else if (bitrate < mMinBitrate){
+        LBRWatcher->setup();
+    }
+}
+
+int32_t QualManager::clampingBitrate(int32_t bitrate) {
+    return std::min(std::max(mMinBitrate, bitrate), mMaxBitrate);
+}
+} // namespace android
diff --git a/media/libstagefright/rtsp/QualManager.h b/media/libstagefright/rtsp/QualManager.h
new file mode 100644
index 0000000..a7dc921
--- /dev/null
+++ b/media/libstagefright/rtsp/QualManager.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2018 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 QUAL_MANAGER_H_
+
+#define QUAL_MANAGER_H_
+
+#include <stdint.h>
+#include <utils/Thread.h>
+
+namespace android {
+class QualManager {
+public:
+    QualManager();
+    ~QualManager();
+
+    int32_t getTargetBitrate();
+    bool isNeedToDowngrade();
+
+    void setTargetBitrate(uint8_t fraction, int64_t nowUs, bool isTooLowPkts);
+    void setMinMaxBitrate(int32_t min, int32_t max);
+    void setBitrateData(int32_t bitrate, int64_t now);
+private:
+    class Watcher : public Thread
+    {
+    public:
+        Watcher(int32_t timeLimit);
+
+        void setup();
+        void release();
+        void exit();
+        bool isExpired() const;
+    private:
+        virtual ~Watcher();
+        virtual bool threadLoop();
+
+        char name[32] = {0,};
+
+        Condition mMyCond;
+        Mutex mMyLock;
+
+        bool mWatching;
+        bool mSwitch;
+        const nsecs_t mTimeLimit;
+    };
+    sp<Watcher> VFPWatcher;
+    sp<Watcher> LBRWatcher;
+    int32_t mMinBitrate;
+    int32_t mMaxBitrate;
+    int32_t mBitrateStep;
+
+    int32_t mTargetBitrate;
+    int32_t mLastTargetBitrate;
+    int64_t mLastSetBitrateTime;
+
+    bool mIsNewTargetBitrate;
+
+    int32_t clampingBitrate(int32_t bitrate);
+};
+} //namespace android
+
+#endif  // QUAL_MANAGER_H_
diff --git a/media/libstagefright/rtsp/TrafficRecorder.h b/media/libstagefright/rtsp/TrafficRecorder.h
new file mode 100644
index 0000000..8ba8f90
--- /dev/null
+++ b/media/libstagefright/rtsp/TrafficRecorder.h
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef A_TRAFFIC_RECORDER_H_
+
+#define A_TRAFFIC_RECORDER_H_
+
+#include <android-base/logging.h>
+#include <utils/RefBase.h>
+
+namespace android {
+
+// Circular array to save recent amount of bytes
+template <class Time, class Bytes>
+class TrafficRecorder : public RefBase {
+private:
+    constexpr static size_t kMinNumEntries = 4;
+    constexpr static size_t kMaxNumEntries = 1024;
+
+    size_t mSize;
+    size_t mSizeMask;
+    Time *mTimeArray = NULL;
+    Bytes *mBytesArray = NULL;
+    size_t mHeadIdx;
+    size_t mTailIdx;
+
+    int mLastReadIdx;
+
+    const Time mRecordLimit;
+    Time mClock;
+    Time mLastTimeOfPrint;
+    Bytes mAccuBytes;
+
+public:
+    TrafficRecorder(size_t size, Time accuTimeLimit);
+    virtual ~TrafficRecorder();
+
+    void init();
+    void updateClock(Time now);
+    Bytes readBytesForTotal();
+    Bytes readBytesForLastPeriod(Time period);
+    void writeBytes(Bytes bytes);
+    void printAccuBitsForLastPeriod(Time period, Time unit);
+};
+
+template <class Time, class Bytes>
+TrafficRecorder<Time, Bytes>::TrafficRecorder(size_t size, Time recordLimit)
+    : mRecordLimit(recordLimit) {
+    if (size > kMaxNumEntries) {
+        LOG(VERBOSE) << "Limiting TrafficRecorder size to " << kMaxNumEntries;
+        size = kMaxNumEntries;
+    } else if (size < kMinNumEntries) {
+        LOG(VERBOSE) << "Limiting TrafficRecorder size to " << kMaxNumEntries;
+        size = kMinNumEntries;
+    }
+
+    size_t exp = ((sizeof(size_t) == 8) ?
+                  64 - __builtin_clzl(size - 1) :
+                  32 - __builtin_clz(size - 1));
+    mSize = (1ul << exp);         // size = 2^exp
+    mSizeMask = mSize - 1;
+
+    LOG(VERBOSE) << "TrafficRecorder Init size " << mSize;
+    mTimeArray = new Time[mSize];
+    mBytesArray = new Bytes[mSize];
+
+    init();
+}
+
+template <class Time, class Bytes>
+TrafficRecorder<Time, Bytes>::~TrafficRecorder() {
+    delete[] mTimeArray;
+    delete[] mBytesArray;
+}
+
+template <class Time, class Bytes>
+void TrafficRecorder<Time, Bytes>::init() {
+    mHeadIdx = 0;
+    mTailIdx = mSizeMask;
+    for (int i = 0 ; i < mSize ; i++) {
+        mTimeArray[i] = 0;
+        mBytesArray[i] = 0;
+    }
+    mClock = 0;
+    mLastReadIdx = 0;
+    mLastTimeOfPrint = 0;
+    mAccuBytes = 0;
+}
+
+template <class Time, class Bytes>
+void TrafficRecorder<Time, Bytes>::updateClock(Time now) {
+    mClock = now;
+}
+
+template <class Time, class Bytes>
+Bytes TrafficRecorder<Time, Bytes>::readBytesForTotal() {
+    return mAccuBytes;
+}
+
+template <class Time, class Bytes>
+Bytes TrafficRecorder<Time, Bytes>::readBytesForLastPeriod(Time period) {
+    // Not enough data
+    if (period > mClock)
+        return 0;
+
+    Bytes bytes = 0;
+    int i = mHeadIdx;
+    while (i != mTailIdx) {
+        LOG(VERBOSE) << "READ " << i << " time " << mTimeArray[i]
+                << " \t EndOfPeriod " << mClock - period
+                << "\t\t Bytes:" << mBytesArray[i] << "\t\t Accu: " << bytes;
+        if (mTimeArray[i] < mClock - period) {
+            break;
+        }
+        bytes += mBytesArray[i];
+        i = (i - 1) & mSizeMask;
+    }
+    mLastReadIdx = (i + 1) & mSizeMask;
+
+    return bytes;
+}
+
+template <class Time, class Bytes>
+void TrafficRecorder<Time, Bytes>::writeBytes(Bytes bytes) {
+    int writeIdx;
+    if (mClock == mTimeArray[mHeadIdx]) {
+        writeIdx = mHeadIdx;
+        mBytesArray[writeIdx] += bytes;
+    } else {
+        writeIdx = (mHeadIdx + 1) & mSizeMask;
+        mTimeArray[writeIdx] = mClock;
+        mBytesArray[writeIdx] = bytes;
+    }
+
+    LOG(VERBOSE) << "WRITE " << writeIdx << " time " << mClock;
+    if (writeIdx == mTailIdx) {
+        mTailIdx = (mTailIdx + 1) & mSizeMask;
+    }
+
+    mHeadIdx = writeIdx;
+    mAccuBytes += bytes;
+}
+
+template <class Time, class Bytes>
+void TrafficRecorder<Time, Bytes>::printAccuBitsForLastPeriod(Time period, Time unit) {
+    Time timeSinceLastPrint = mClock - mLastTimeOfPrint;
+    if (timeSinceLastPrint < period)
+        return;
+
+    Bytes sum = readBytesForLastPeriod(period);
+    Time readPeriod = mClock - mTimeArray[mLastReadIdx];
+
+    float numOfUnit = (float)(readPeriod) / (unit + FLT_MIN);
+    ALOGD("Actual Tx period %.3f unit \t %.0f bytes (%.0f Kbits)/Unit",
+          numOfUnit, sum / numOfUnit, sum * 8.f / numOfUnit / 1000.f);
+    mLastTimeOfPrint = mClock;
+
+    if (mClock - mTimeArray[mTailIdx] < mRecordLimit) {
+        // Size is not enough to record bytes for mRecordLimit period
+        ALOGW("Traffic recorder size is not enough. mRecordLimit %d", mRecordLimit);
+    }
+}
+
+}  // namespace android
+
+#endif  // A_TRAFFIC_RECORDER_H_
diff --git a/media/libstagefright/tests/Android.bp b/media/libstagefright/tests/Android.bp
index a7f94c1..a799a13 100644
--- a/media/libstagefright/tests/Android.bp
+++ b/media/libstagefright/tests/Android.bp
@@ -1,5 +1,24 @@
 // Build the unit tests.
 
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_tests_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_tests_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_test {
     name: "MediaCodecListOverrides_test",
 
@@ -9,7 +28,6 @@
         "libmedia",
         "libstagefright",
         "libstagefright_foundation",
-        "libstagefright_omx",
         "libutils",
         "liblog",
     ],
@@ -17,11 +35,8 @@
     include_dirs: [
         "frameworks/av/media/libstagefright",
         "frameworks/av/media/libstagefright/include",
-        "frameworks/native/include/media/openmax",
     ],
 
-    compile_multilib: "32",
-
     cflags: [
         "-Werror",
         "-Wall",
@@ -44,4 +59,4 @@
         "-Werror",
         "-Wall",
     ],
-}
\ No newline at end of file
+}
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp b/media/libstagefright/tests/ESDS/Android.bp
similarity index 62%
copy from media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
copy to media/libstagefright/tests/ESDS/Android.bp
index 655491a..04e9b29 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
+++ b/media/libstagefright/tests/ESDS/Android.bp
@@ -14,21 +14,37 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_tests_license",
+    ],
+}
+
 cc_test {
-    name: "Mpeg4H263DecoderTest",
+    name: "ESDSTest",
     gtest: true,
 
     srcs: [
-        "Mpeg4H263DecoderTest.cpp",
+        "ESDSTest.cpp",
     ],
 
     shared_libs: [
+        "libbinder",
+        "libdatasource",
         "liblog",
+        "libmedia",
+        "libstagefright",
+        "libstagefright_foundation",
+        "libutils",
     ],
 
     static_libs: [
-        "libstagefright_m4vh263dec",
-        "libstagefright_foundation",
+        "libstagefright_esds",
     ],
 
     cflags: [
@@ -37,10 +53,10 @@
     ],
 
     sanitize: {
+        cfi: true,
         misc_undefined: [
             "unsigned-integer-overflow",
             "signed-integer-overflow",
         ],
-        cfi: true,
     },
 }
diff --git a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml b/media/libstagefright/tests/ESDS/AndroidTest.xml
similarity index 72%
copy from media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
copy to media/libstagefright/tests/ESDS/AndroidTest.xml
index 7ff9732..a4fbc7f 100644
--- a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
+++ b/media/libstagefright/tests/ESDS/AndroidTest.xml
@@ -13,19 +13,19 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Test module config for Mp3 Decoder unit test">
-    <option name="test-suite-tag" value="Mp3DecoderTest" />
+<configuration description="Test module config for ESDS unit test">
+    <option name="test-suite-tag" value="ESDSTest" />
     <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
         <option name="cleanup" value="true" />
-        <option name="push" value="Mp3DecoderTest->/data/local/tmp/Mp3DecoderTest" />
+        <option name="push" value="ESDSTest->/data/local/tmp/ESDSTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest.zip?unzip=true"
-            value="/data/local/tmp/Mp3DecoderTestRes/" />
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/tests/ESDS/ESDSTestRes-1.0.zip?unzip=true"
+            value="/data/local/tmp/ESDSTestRes/" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.GTest" >
         <option name="native-test-device-path" value="/data/local/tmp" />
-        <option name="module-name" value="Mp3DecoderTest" />
-        <option name="native-test-flag" value="-P /data/local/tmp/Mp3DecoderTestRes/" />
+        <option name="module-name" value="ESDSTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/ESDSTestRes/" />
     </test>
 </configuration>
diff --git a/media/libstagefright/tests/ESDS/ESDSTest.cpp b/media/libstagefright/tests/ESDS/ESDSTest.cpp
new file mode 100644
index 0000000..101e00c
--- /dev/null
+++ b/media/libstagefright/tests/ESDS/ESDSTest.cpp
@@ -0,0 +1,210 @@
+/*
+ * Copyright (C) 2020 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 "ESDSTest"
+#include <utils/Log.h>
+
+#include <stdio.h>
+#include <string.h>
+#include <fstream>
+
+#include <ESDS.h>
+#include <binder/ProcessState.h>
+#include <datasource/FileSource.h>
+#include <media/stagefright/MediaExtractorFactory.h>
+#include <media/stagefright/MetaData.h>
+
+#include "ESDSTestEnvironment.h"
+
+using namespace android;
+
+static ESDSTestEnvironment *gEnv = nullptr;
+
+struct ESDSParams {
+    const char *inputFile;
+    int32_t objectTypeIndication;
+    const char *codecSpecificInfoData;
+    int32_t codecSpecificInfoDataSize;
+    int32_t bitrateMax;
+    int32_t bitrateAvg;
+};
+
+class ESDSUnitTest : public ::testing::TestWithParam<tuple<
+                             /* InputFile */ const char *,
+                             /* ObjectTypeIndication */ int32_t,
+                             /* CodecSpecificInfoData */ const char *,
+                             /* CodecSpecificInfoDataSize */ int32_t,
+                             /* BitrateMax */ int32_t,
+                             /* BitrateAvg */ int32_t>> {
+  public:
+    ESDSUnitTest() : mESDSData(nullptr) {
+        mESDSParams.inputFile = get<0>(GetParam());
+        mESDSParams.objectTypeIndication = get<1>(GetParam());
+        mESDSParams.codecSpecificInfoData = get<2>(GetParam());
+        mESDSParams.codecSpecificInfoDataSize = get<3>(GetParam());
+        mESDSParams.bitrateMax = get<4>(GetParam());
+        mESDSParams.bitrateAvg = get<5>(GetParam());
+    };
+
+    virtual void TearDown() override {
+        if (mDataSource) mDataSource.clear();
+        if (mInputFp) {
+            fclose(mInputFp);
+            mInputFp = nullptr;
+        }
+    }
+
+    virtual void SetUp() override { ASSERT_NO_FATAL_FAILURE(readESDSData()); }
+    const void *mESDSData;
+    size_t mESDSSize;
+    ESDSParams mESDSParams;
+
+  private:
+    void readESDSData() {
+        string inputFile = gEnv->getRes() + mESDSParams.inputFile;
+        mInputFp = fopen(inputFile.c_str(), "rb");
+        ASSERT_NE(mInputFp, nullptr) << "File open failed for file: " << inputFile;
+        int32_t fd = fileno(mInputFp);
+        ASSERT_GE(fd, 0) << "File descriptor invalid for file: " << inputFile;
+
+        struct stat buf;
+        status_t status = stat(inputFile.c_str(), &buf);
+        ASSERT_EQ(status, 0) << "Failed to get properties of input file: " << mESDSParams.inputFile;
+        size_t fileSize = buf.st_size;
+
+        mDataSource = new FileSource(dup(fd), 0, fileSize);
+        ASSERT_NE(mDataSource, nullptr) << "Unable to create data source for file: " << inputFile;
+
+        sp<IMediaExtractor> extractor = MediaExtractorFactory::Create(mDataSource);
+        if (extractor == nullptr) {
+            mDataSource.clear();
+            ASSERT_TRUE(false) << "Unable to create extractor for file: " << inputFile;
+        }
+
+        size_t numTracks = extractor->countTracks();
+        ASSERT_GT(numTracks, 0) << "No tracks in file: " << inputFile;
+        ASSERT_TRUE(esdsDataPresent(numTracks, extractor))
+                << "Unable to find esds in any track in file: " << inputFile;
+    }
+
+    bool esdsDataPresent(size_t numTracks, sp<IMediaExtractor> extractor) {
+        bool foundESDS = false;
+        uint32_t type;
+        for (size_t i = 0; i < numTracks; ++i) {
+            sp<MetaData> trackMeta = extractor->getTrackMetaData(i);
+            if (trackMeta != nullptr &&
+                trackMeta->findData(kKeyESDS, &type, &mESDSData, &mESDSSize)) {
+                trackMeta->clear();
+                foundESDS = true;
+                break;
+            }
+        }
+        return foundESDS;
+    }
+
+    FILE *mInputFp;
+    sp<DataSource> mDataSource;
+};
+
+TEST_P(ESDSUnitTest, InvalidDataTest) {
+    void *invalidData = calloc(mESDSSize, 1);
+    ASSERT_NE(invalidData, nullptr) << "Unable to allocate memory";
+    ESDS esds(invalidData, mESDSSize);
+    free(invalidData);
+    ASSERT_NE(esds.InitCheck(), OK) << "invalid ESDS data accepted";
+}
+
+TEST(ESDSSanityUnitTest, ConstructorSanityTest) {
+    void *invalidData = malloc(1);
+    ASSERT_NE(invalidData, nullptr) << "Unable to allocate memory";
+    ESDS esds_zero(invalidData, 0);
+    free(invalidData);
+    ASSERT_NE(esds_zero.InitCheck(), OK) << "invalid ESDS data accepted";
+
+    ESDS esds_null(NULL, 0);
+    ASSERT_NE(esds_null.InitCheck(), OK) << "invalid ESDS data accepted";
+}
+
+TEST_P(ESDSUnitTest, CreateAndDestroyTest) {
+    ESDS esds(mESDSData, mESDSSize);
+    ASSERT_EQ(esds.InitCheck(), OK) << "ESDS data invalid";
+}
+
+TEST_P(ESDSUnitTest, ObjectTypeIndicationTest) {
+    ESDS esds(mESDSData, mESDSSize);
+    ASSERT_EQ(esds.InitCheck(), OK) << "ESDS data invalid";
+    uint8_t objectTypeIndication;
+    status_t status = esds.getObjectTypeIndication(&objectTypeIndication);
+    ASSERT_EQ(status, OK) << "ESDS objectTypeIndication data invalid";
+    ASSERT_EQ(objectTypeIndication, mESDSParams.objectTypeIndication)
+            << "ESDS objectTypeIndication data doesn't match";
+}
+
+TEST_P(ESDSUnitTest, CodecSpecificInfoTest) {
+    ESDS esds(mESDSData, mESDSSize);
+    ASSERT_EQ(esds.InitCheck(), OK) << "ESDS data invalid";
+    status_t status;
+    const void *codecSpecificInfo;
+    size_t codecSpecificInfoSize;
+    status = esds.getCodecSpecificInfo(&codecSpecificInfo, &codecSpecificInfoSize);
+    ASSERT_EQ(status, OK) << "ESDS getCodecSpecificInfo data invalid";
+    ASSERT_EQ(mESDSParams.codecSpecificInfoDataSize, codecSpecificInfoSize)
+            << "CodecSpecificInfo data doesn't match";
+    status = memcmp(codecSpecificInfo, mESDSParams.codecSpecificInfoData, codecSpecificInfoSize);
+    ASSERT_EQ(status, 0) << "CodecSpecificInfo data doesn't match";
+}
+
+TEST_P(ESDSUnitTest, GetBitrateTest) {
+    ESDS esds(mESDSData, mESDSSize);
+    ASSERT_EQ(esds.InitCheck(), OK) << "ESDS data invalid";
+    uint32_t bitrateMax;
+    uint32_t bitrateAvg;
+    status_t status = esds.getBitRate(&bitrateMax, &bitrateAvg);
+    ASSERT_EQ(status, OK) << "ESDS bitRate data invalid";
+    ASSERT_EQ(bitrateMax, mESDSParams.bitrateMax) << "ESDS bitrateMax doesn't match";
+    ASSERT_EQ(bitrateAvg, mESDSParams.bitrateAvg) << "ESDS bitrateAvg doesn't match";
+    ASSERT_LE(bitrateAvg, bitrateMax) << "ESDS bitrateMax is less than bitrateAvg";
+}
+
+INSTANTIATE_TEST_SUITE_P(
+        ESDSUnitTestAll, ESDSUnitTest,
+        ::testing::Values(
+                // InputFile, ObjectTypeIndication, CodecSpecificInfoData,
+                // CodecSpecificInfoDataSize, BitrateMax, BitrateAvg
+                make_tuple("video_176x144_3gp_h263_56kbps_12fps_aac_stereo_128kbps_22050hz.3gp", 64,
+                           "\x13\x90", 2, 131072, 0),
+                make_tuple("video_1280x720_mp4_mpeg2_3000kbps_30fps_aac_stereo_128kbps_48000hz.mp4",
+                           97,
+                           "\x00\x00\x01\xB3\x50\x02\xD0\x35\xFF\xFF\xE1\xA0\x00\x00\x01\xB5\x15"
+                           "\x6A\x00\x01\x00\x00",
+                           22, 3415452, 3415452),
+                make_tuple("video_176x144_3gp_h263_56kbps_25fps_aac_mono_24kbps_11025hz.3gp", 64,
+                           "\x15\x08", 2, 24576, 0)));
+
+int main(int argc, char **argv) {
+    // MediaExtractor needs binder thread pool
+    ProcessState::self()->startThreadPool();
+    gEnv = new ESDSTestEnvironment();
+    ::testing::AddGlobalTestEnvironment(gEnv);
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = gEnv->initFromOptions(argc, argv);
+    if (status == 0) {
+        status = RUN_ALL_TESTS();
+        ALOGV("Test result = %d\n", status);
+    }
+    return status;
+}
diff --git a/media/libstagefright/tests/ESDS/ESDSTestEnvironment.h b/media/libstagefright/tests/ESDS/ESDSTestEnvironment.h
new file mode 100644
index 0000000..4ca2303
--- /dev/null
+++ b/media/libstagefright/tests/ESDS/ESDSTestEnvironment.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2020 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 __ESDS_TEST_ENVIRONMENT_H__
+#define __ESDS_TEST_ENVIRONMENT_H__
+
+#include <gtest/gtest.h>
+
+#include <getopt.h>
+
+using namespace std;
+
+class ESDSTestEnvironment : public ::testing::Environment {
+  public:
+    ESDSTestEnvironment() : res("/data/local/tmp/") {}
+
+    // Parses the command line arguments
+    int initFromOptions(int argc, char **argv);
+
+    void setRes(const char *_res) { res = _res; }
+
+    const string getRes() const { return res; }
+
+  private:
+    string res;
+};
+
+int ESDSTestEnvironment::initFromOptions(int argc, char **argv) {
+    static struct option options[] = {{"res", required_argument, 0, 'P'}, {0, 0, 0, 0}};
+
+    while (true) {
+        int index = 0;
+        int c = getopt_long(argc, argv, "P:", options, &index);
+        if (c == -1) {
+            break;
+        }
+
+        switch (c) {
+            case 'P':
+                setRes(optarg);
+                break;
+            default:
+                break;
+        }
+    }
+
+    if (optind < argc) {
+        fprintf(stderr,
+                "unrecognized option: %s\n\n"
+                "usage: %s <gtest options> <test options>\n\n"
+                "test options are:\n\n"
+                "-P, --path: Resource files directory location\n",
+                argv[optind ?: 1], argv[0]);
+        return 2;
+    }
+    return 0;
+}
+
+#endif  // __ESDS_TEST_ENVIRONMENT_H__
diff --git a/media/libstagefright/tests/ESDS/README.md b/media/libstagefright/tests/ESDS/README.md
new file mode 100644
index 0000000..100fb86
--- /dev/null
+++ b/media/libstagefright/tests/ESDS/README.md
@@ -0,0 +1,40 @@
+## Media Testing ##
+---
+#### ESDS Unit Test :
+The ESDS Unit Test Suite validates the ESDS class available in libstagefright.
+
+Run the following steps to build the test suite:
+```
+m ESDSTest
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+```
+adb push ${OUT}/data/nativetest64/ESDSTest/ESDSTest /data/local/tmp/
+```
+
+To test 32-bit binary push binaries from nativetest.
+```
+adb push ${OUT}/data/nativetest/ESDSTest/ESDSTest /data/local/tmp/
+```
+
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/tests/ESDS/ESDSTestRes-1.0.zip)
+Download, unzip and push these files into device for testing.
+
+```
+adb push ESDSTestRes /data/local/tmp/
+```
+
+usage: ESDSTest -P \<path_to_folder\>
+```
+adb shell /data/local/tmp/ESDSTest -P /data/local/tmp/ESDSTestRes/
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest ESDSTest -- --enable-module-dynamic-download=true
+```
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp b/media/libstagefright/tests/HEVC/Android.bp
similarity index 62%
copy from media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
copy to media/libstagefright/tests/HEVC/Android.bp
index 655491a..501478c 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
+++ b/media/libstagefright/tests/HEVC/Android.bp
@@ -14,33 +14,49 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_tests_license",
+    ],
+}
+
 cc_test {
-    name: "Mpeg4H263DecoderTest",
+    name: "HEVCUtilsUnitTest",
     gtest: true,
 
     srcs: [
-        "Mpeg4H263DecoderTest.cpp",
+        "HEVCUtilsUnitTest.cpp",
     ],
 
     shared_libs: [
+        "libutils",
         "liblog",
     ],
 
     static_libs: [
-        "libstagefright_m4vh263dec",
+        "libstagefright",
         "libstagefright_foundation",
     ],
 
+    include_dirs: [
+        "frameworks/av/media/libstagefright",
+    ],
+
     cflags: [
         "-Werror",
         "-Wall",
     ],
 
     sanitize: {
+        cfi: true,
         misc_undefined: [
             "unsigned-integer-overflow",
             "signed-integer-overflow",
         ],
-        cfi: true,
     },
 }
diff --git a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml b/media/libstagefright/tests/HEVC/AndroidTest.xml
similarity index 67%
copy from media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
copy to media/libstagefright/tests/HEVC/AndroidTest.xml
index 7ff9732..ff850a2 100644
--- a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
+++ b/media/libstagefright/tests/HEVC/AndroidTest.xml
@@ -13,19 +13,19 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Test module config for Mp3 Decoder unit test">
-    <option name="test-suite-tag" value="Mp3DecoderTest" />
+<configuration description="Test module config for HEVC Utils unit tests">
+    <option name="test-suite-tag" value="HEVCUtilsUnitTest" />
     <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
-        <option name="cleanup" value="true" />
-        <option name="push" value="Mp3DecoderTest->/data/local/tmp/Mp3DecoderTest" />
+        <option name="cleanup" value="false" />
+        <option name="push" value="HEVCUtilsUnitTest->/data/local/tmp/HEVCUtilsUnitTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest.zip?unzip=true"
-            value="/data/local/tmp/Mp3DecoderTestRes/" />
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/foundation/tests/HEVCUtils/HEVCUtilsUnitTest.zip?unzip=true"
+            value="/data/local/tmp/HEVCUtilsUnitTest/" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.GTest" >
         <option name="native-test-device-path" value="/data/local/tmp" />
-        <option name="module-name" value="Mp3DecoderTest" />
-        <option name="native-test-flag" value="-P /data/local/tmp/Mp3DecoderTestRes/" />
+        <option name="module-name" value="HEVCUtilsUnitTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/HEVCUtilsUnitTest/" />
     </test>
 </configuration>
diff --git a/media/libstagefright/tests/HEVC/HEVCUtilsTestEnvironment.h b/media/libstagefright/tests/HEVC/HEVCUtilsTestEnvironment.h
new file mode 100644
index 0000000..e4481e1
--- /dev/null
+++ b/media/libstagefright/tests/HEVC/HEVCUtilsTestEnvironment.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2020 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 __HEVC_UTILS_TEST_ENVIRONMENT_H__
+#define __HEVC_UTILS_TEST_ENVIRONMENT_H__
+
+#include <gtest/gtest.h>
+
+#include <getopt.h>
+
+using namespace std;
+
+class HEVCUtilsTestEnvironment : public::testing::Environment {
+  public:
+    HEVCUtilsTestEnvironment() : res("/data/local/tmp/") {}
+
+    // Parses the command line arguments
+    int initFromOptions(int argc, char **argv);
+
+    void setRes(const char *_res) { res = _res; }
+
+    const string getRes() const { return res; }
+
+  private:
+    string res;
+};
+
+int HEVCUtilsTestEnvironment::initFromOptions(int argc, char **argv) {
+    static struct option options[] = {{"path", required_argument, 0, 'P'}, {0, 0, 0, 0}};
+
+    while (true) {
+        int index = 0;
+        int c = getopt_long(argc, argv, "P:", options, &index);
+        if (c == -1) {
+            break;
+        }
+
+        switch (c) {
+            case 'P': {
+                setRes(optarg);
+                break;
+            }
+            default:
+                break;
+        }
+    }
+
+    if (optind < argc) {
+        fprintf(stderr,
+                "unrecognized option: %s\n\n"
+                "usage: %s <gtest options> <test options>\n\n"
+                "test options are:\n\n"
+                "-P, --path: Resource files directory location\n",
+                argv[optind ?: 1], argv[0]);
+        return 2;
+    }
+    return 0;
+}
+
+#endif  // __HEVC_UTILS_TEST_ENVIRONMENT_H__
diff --git a/media/libstagefright/tests/HEVC/HEVCUtilsUnitTest.cpp b/media/libstagefright/tests/HEVC/HEVCUtilsUnitTest.cpp
new file mode 100644
index 0000000..324a042
--- /dev/null
+++ b/media/libstagefright/tests/HEVC/HEVCUtilsUnitTest.cpp
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2020 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 "HevcUtilityTest"
+#include <utils/Log.h>
+
+#include <fstream>
+
+#include <media/stagefright/foundation/ABitReader.h>
+#include "include/HevcUtils.h"
+
+#include "HEVCUtilsTestEnvironment.h"
+
+using namespace android;
+
+// max size of hvcc box is 2 KB
+constexpr uint32_t kHvccBoxMaxSize = 2048;
+constexpr uint32_t kHvccBoxMinSize = 20;
+constexpr uint32_t kVPSCode = 32;
+constexpr uint32_t kSPSCode = 33;
+constexpr uint32_t kPPSCode = 34;
+constexpr uint32_t kNALSizeLength = 2;
+
+static HEVCUtilsTestEnvironment *gEnv = nullptr;
+
+class HEVCUtilsUnitTest
+    : public ::testing::TestWithParam<
+              tuple</*fileName*/ string, /*infoFileName*/ string, /*numVPSNals*/ size_t,
+                    /*numSPSNals*/ size_t, /*numPPSNals*/ size_t, /*frameRate*/ int16_t,
+                    /*isHdr*/ bool>> {
+  public:
+    ~HEVCUtilsUnitTest() {
+        if (mMediaFileStream.is_open()) mMediaFileStream.close();
+        if (mInfoFileStream.is_open()) mInfoFileStream.close();
+    }
+
+    virtual void SetUp() override {
+        tuple<string, string, size_t, size_t, size_t, int16_t, bool> params = GetParam();
+        string inputMediaFile = gEnv->getRes() + get<0>(params);
+        mMediaFileStream.open(inputMediaFile, ifstream::in);
+        ASSERT_TRUE(mMediaFileStream.is_open()) << "Failed to open media file: " << inputMediaFile;
+
+        string inputInfoFile = gEnv->getRes() + get<1>(params);
+        mInfoFileStream.open(inputInfoFile, ifstream::in);
+        ASSERT_TRUE(mInfoFileStream.is_open()) << "Failed to open info file: " << inputInfoFile;
+
+        mNumVPSNals = get<2>(params);
+        mNumSPSNals = get<3>(params);
+        mNumPPSNals = get<4>(params);
+        mFrameRate = get<5>(params);
+        mIsHDR = get<6>(params);
+    }
+
+    size_t mNumVPSNals;
+    size_t mNumSPSNals;
+    size_t mNumPPSNals;
+    int16_t mFrameRate;
+    bool mIsHDR;
+    ifstream mMediaFileStream;
+    ifstream mInfoFileStream;
+};
+
+TEST_P(HEVCUtilsUnitTest, NALUnitTest) {
+    HevcParameterSets hevcParams;
+
+    string line;
+    int32_t index = 0;
+    status_t err;
+    while (getline(mInfoFileStream, line)) {
+        string type;
+        int32_t chunkLength;
+
+        istringstream stringLine(line);
+        stringLine >> type >> chunkLength;
+        ASSERT_GT(chunkLength, 0) << "Length of data chunk must be greater than 0";
+
+        char *data = (char *)malloc(chunkLength);
+        ASSERT_NE(data, nullptr) << "Failed to allocate data buffer of size: " << chunkLength;
+
+        mMediaFileStream.read(data, chunkLength);
+        ASSERT_EQ(mMediaFileStream.gcount(), chunkLength)
+                << "Failed to read complete file, bytes read: " << mMediaFileStream.gcount();
+
+        // A valid startcode consists of at least two 0x00 bytes followed by 0x01.
+        int32_t offset = 0;
+        for (; offset + 2 < chunkLength; ++offset) {
+            if (data[offset + 2] == 0x01 && data[offset + 1] == 0x00 && data[offset] == 0x00) {
+                break;
+            }
+        }
+        offset += 3;
+        ASSERT_LE(offset, chunkLength) << "NAL unit offset must not exceed the chunk length";
+
+        uint8_t *nalUnit = (uint8_t *)(data + offset);
+        size_t nalUnitLength = chunkLength - offset;
+
+        // Add NAL units only if they're of type: VPS/SPS/PPS/SEI
+        if (!((type.compare("VPS") && type.compare("SPS") && type.compare("PPS") &&
+               type.compare("SEI")))) {
+            err = hevcParams.addNalUnit(nalUnit, nalUnitLength);
+            ASSERT_EQ(err, (status_t)OK)
+                    << "Failed to add NAL Unit type: " << type << " Size: " << nalUnitLength;
+
+            size_t sizeNalUnit = hevcParams.getSize(index);
+            ASSERT_EQ(sizeNalUnit, nalUnitLength) << "Invalid size returned for NAL: " << type;
+
+            uint8_t *destination = (uint8_t *)malloc(nalUnitLength);
+            ASSERT_NE(destination, nullptr)
+                    << "Failed to allocate buffer of size: " << nalUnitLength;
+
+            bool status = hevcParams.write(index, destination, nalUnitLength);
+            ASSERT_TRUE(status) << "Unable to write NAL Unit data";
+
+            free(destination);
+            index++;
+        } else {
+            err = hevcParams.addNalUnit(nalUnit, nalUnitLength);
+            ASSERT_NE(err, (status_t)OK) << "Invalid NAL Unit added, type: " << type;
+        }
+        free(data);
+    }
+
+    size_t numNalUnits = hevcParams.getNumNalUnitsOfType(kVPSCode);
+    ASSERT_EQ(numNalUnits, mNumVPSNals) << "Wrong number of VPS NAL Units";
+
+    numNalUnits = hevcParams.getNumNalUnitsOfType(kSPSCode);
+    ASSERT_EQ(numNalUnits, mNumSPSNals) << "Wrong number of SPS NAL Units";
+
+    numNalUnits = hevcParams.getNumNalUnitsOfType(kPPSCode);
+    ASSERT_EQ(numNalUnits, mNumPPSNals) << "Wrong number of PPS NAL Units";
+
+    HevcParameterSets::Info info = hevcParams.getInfo();
+    ASSERT_EQ(info & HevcParameterSets::kInfoIsHdr,
+              (mIsHDR ? HevcParameterSets::kInfoIsHdr : HevcParameterSets::kInfoNone))
+            << "Wrong info about HDR";
+
+    ASSERT_EQ(info & HevcParameterSets::kInfoHasColorDescription,
+              (mIsHDR ? HevcParameterSets::kInfoHasColorDescription : HevcParameterSets::kInfoNone))
+            << "Wrong info about color description";
+
+    // an HEVC file starts with VPS, SPS and PPS NAL units in sequence.
+    uint8_t typeNalUnit = hevcParams.getType(0);
+    ASSERT_EQ(typeNalUnit, kHevcNalUnitTypeVps)
+            << "Expected NAL type: 32(VPS), found: " << typeNalUnit;
+
+    typeNalUnit = hevcParams.getType(1);
+    ASSERT_EQ(typeNalUnit, kHevcNalUnitTypeSps)
+            << "Expected NAL type: 33(SPS), found: " << typeNalUnit;
+
+    typeNalUnit = hevcParams.getType(2);
+    ASSERT_EQ(typeNalUnit, kHevcNalUnitTypePps)
+            << "Expected NAL type: 34(PPS), found: " << typeNalUnit;
+
+    size_t hvccBoxSize = kHvccBoxMaxSize;
+    uint8_t *hvcc = (uint8_t *)malloc(kHvccBoxMaxSize);
+    ASSERT_NE(hvcc, nullptr) << "Failed to allocate a hvcc buffer of size: " << kHvccBoxMaxSize;
+
+    err = hevcParams.makeHvcc(hvcc, &hvccBoxSize, kNALSizeLength);
+    ASSERT_EQ(err, (status_t)OK) << "Unable to create hvcc box";
+
+    ASSERT_GT(hvccBoxSize, kHvccBoxMinSize)
+            << "Hvcc box size must be greater than " << kHvccBoxMinSize;
+
+    int16_t frameRate = hvcc[kHvccBoxMinSize - 1] | (hvcc[kHvccBoxMinSize] << 8);
+    if (frameRate != mFrameRate)
+        cout << "[   WARN   ] Expected frame rate: " << mFrameRate << " Found: " << frameRate
+             << endl;
+
+    free(hvcc);
+}
+
+// Info File contains the type and length for each chunk/frame
+INSTANTIATE_TEST_SUITE_P(
+        HEVCUtilsUnitTestAll, HEVCUtilsUnitTest,
+        ::testing::Values(make_tuple("crowd_3840x2160p50f300_32500kbps.hevc",
+                                     "crowd_3840x2160p50f300_32500kbps.info", 1, 1, 1, 50, false),
+                          make_tuple("crowd_1920x1080p24f300_4500kbps.hevc",
+                                     "crowd_1920x1080p24f300_4500kbps.info", 1, 1, 1, 24, false),
+                          make_tuple("crowd_1280x720p24f300_3000kbps.hevc",
+                                     "crowd_1280x720p24f300_3000kbps.info", 1, 1, 1, 24, false),
+                          make_tuple("crowd_640x360p24f300_500kbps.hevc",
+                                     "crowd_640x360p24f300_500kbps.info", 1, 1, 1, 24, false)));
+
+int main(int argc, char **argv) {
+    gEnv = new HEVCUtilsTestEnvironment();
+    ::testing::AddGlobalTestEnvironment(gEnv);
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = gEnv->initFromOptions(argc, argv);
+    if (status == 0) {
+        status = RUN_ALL_TESTS();
+        ALOGV("Test result = %d\n", status);
+    }
+    return status;
+}
diff --git a/media/libstagefright/tests/HEVC/README.md b/media/libstagefright/tests/HEVC/README.md
new file mode 100644
index 0000000..fa0e99c
--- /dev/null
+++ b/media/libstagefright/tests/HEVC/README.md
@@ -0,0 +1,39 @@
+## Media Testing ##
+---
+#### HEVC Utils Test
+The HEVC Utility Unit Test Suite validates the HevcUtils library available in libstagefright.
+
+Run the following steps to build the test suite:
+```
+m HEVCUtilsUnitTest
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+```
+adb push ${OUT}/data/nativetest64/HEVCUtilsUnitTest/HEVCUtilsUnitTest /data/local/tmp/
+```
+
+To test 32-bit binary push binaries from nativetest.
+```
+adb push ${OUT}/data/nativetest/HEVCUtilsUnitTest/HEVCUtilsUnitTest /data/local/tmp/
+```
+
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/foundation/tests/HEVCUtils/HEVCUtilsUnitTest.zip). Download, unzip and push these files into device for testing.
+
+```
+adb push HEVCUtilsUnitTest /data/local/tmp/
+```
+
+usage: HEVCUtilsUnitTest -P \<path_to_folder\>
+```
+adb shell /data/local/tmp/HEVCUtilsUnitTest -P /data/local/tmp/HEVCUtilsUnitTest/
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest HEVCUtilsUnitTest -- --enable-module-dynamic-download=true
+```
diff --git a/media/libstagefright/tests/extractorFactory/Android.bp b/media/libstagefright/tests/extractorFactory/Android.bp
index e3e61d7..171755f 100644
--- a/media/libstagefright/tests/extractorFactory/Android.bp
+++ b/media/libstagefright/tests/extractorFactory/Android.bp
@@ -14,6 +14,17 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_tests_license",
+    ],
+}
+
 cc_test {
     name: "ExtractorFactoryTest",
     gtest: true,
diff --git a/media/libstagefright/tests/fuzzers/Android.bp b/media/libstagefright/tests/fuzzers/Android.bp
new file mode 100644
index 0000000..65e74e6
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/Android.bp
@@ -0,0 +1,93 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_tests_license",
+    ],
+}
+
+cc_defaults {
+    name: "libstagefright_fuzzer_defaults",
+    cflags: [
+        "-Wno-multichar",
+        "-Werror",
+        "-Wno-error=deprecated-declarations",
+        "-Wall",
+    ],
+    shared_libs: [
+        "libstagefright",
+        "libstagefright_codecbase",
+        "libbase",
+        "libcutils",
+        "libutils",
+        "libstagefright_foundation",
+        "libmedia",
+        "libaudioclient",
+        "libmedia_omx",
+        "libgui",
+        "libbinder",
+        "liblog",
+    ],
+    include_dirs: [
+        "frameworks/av/media/libstagefright",
+    ],
+}
+
+cc_fuzz {
+    name: "libstagefright_mediaclock_fuzzer",
+    srcs: [
+        "MediaClockFuzzer.cpp",
+    ],
+    defaults: ["libstagefright_fuzzer_defaults"],
+}
+
+cc_fuzz {
+    name: "libstagefright_mediascanner_fuzzer",
+    srcs: [
+        "StagefrightMediaScannerFuzzer.cpp",
+    ],
+    defaults: ["libstagefright_fuzzer_defaults"],
+}
+
+cc_fuzz {
+    name: "libstagefright_skipcutbuffer_fuzzer",
+    srcs: [
+        "SkipCutBufferFuzzer.cpp",
+    ],
+    defaults: ["libstagefright_fuzzer_defaults"],
+}
+
+cc_fuzz {
+    name: "libstagefright_mediamuxer_fuzzer",
+    srcs: [
+        "MediaMuxerFuzzer.cpp",
+    ],
+    defaults: ["libstagefright_fuzzer_defaults"],
+}
+
+cc_fuzz {
+    name: "libstagefright_frameDecoder_fuzzer",
+    srcs: [
+        "FrameDecoderFuzzer.cpp",
+    ],
+    defaults: ["libstagefright_fuzzer_defaults"],
+}
+
+cc_fuzz {
+    name: "libstagefright_writer_fuzzer",
+    srcs: [
+        "FuzzerMediaUtility.cpp",
+        "WriterFuzzer.cpp",
+    ],
+    dictionary: "dictionaries/formats.dict",
+    defaults: ["libstagefright_fuzzer_defaults"],
+    static_libs: [
+        "libstagefright_webm",
+        "libdatasource",
+        "libstagefright_esds",
+        "libogg",
+    ],
+}
diff --git a/media/libstagefright/tests/fuzzers/FrameDecoderFuzzer.cpp b/media/libstagefright/tests/fuzzers/FrameDecoderFuzzer.cpp
new file mode 100644
index 0000000..a628c70
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/FrameDecoderFuzzer.cpp
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "include/FrameDecoder.h"
+#include <fuzzer/FuzzedDataProvider.h>
+#include <media/IMediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/foundation/AString.h>
+#include "FrameDecoderHelpers.h"
+#include "IMediaSourceFuzzImpl.h"
+
+namespace android {
+
+#define MAX_MEDIA_BUFFER_SIZE 2048
+
+// Fuzzer entry point.
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    // Init our wrapper
+    FuzzedDataProvider fdp(data, size);
+
+    std::string name = fdp.ConsumeRandomLengthString(fdp.remaining_bytes());
+    AString componentName(name.c_str());
+    sp<MetaData> trackMeta = generateMetaData(&fdp);
+    sp<IMediaSource> source = new IMediaSourceFuzzImpl(&fdp, MAX_MEDIA_BUFFER_SIZE);
+
+    // Image or video Decoder?
+    sp<FrameDecoder> decoder;
+    bool isVideoDecoder = fdp.ConsumeBool();
+    if (isVideoDecoder) {
+        decoder = new VideoFrameDecoder(componentName, trackMeta, source);
+    } else {
+        decoder = new ImageDecoder(componentName, trackMeta, source);
+    }
+
+    while (fdp.remaining_bytes()) {
+        switch (fdp.ConsumeIntegralInRange<uint8_t>(0, 3)) {
+            case 0:
+                decoder->init(/*frameTimeUs*/ fdp.ConsumeIntegral<int64_t>(),
+                              /*option*/ fdp.ConsumeIntegral<int>(),
+                              /*colorFormat*/ fdp.ConsumeIntegral<int>());
+                break;
+            case 1:
+                decoder->extractFrame();
+                break;
+            case 2: {
+                FrameRect rect;
+                rect.left = fdp.ConsumeIntegral<int32_t>();
+                rect.top = fdp.ConsumeIntegral<int32_t>();
+                rect.right = fdp.ConsumeIntegral<int32_t>();
+                rect.bottom = fdp.ConsumeIntegral<int32_t>();
+                decoder->extractFrame(&rect);
+                break;
+            }
+            case 3: {
+                sp<MetaData> trackMeta = generateMetaData(&fdp);
+                decoder->getMetadataOnly(trackMeta,
+                                         /*colorFormat*/ fdp.ConsumeIntegral<int>(),
+                                         /*thumbnail*/ fdp.ConsumeBool());
+                break;
+            }
+        }
+    }
+
+    generated_mime_types.clear();
+
+    return 0;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/tests/fuzzers/FrameDecoderHelpers.h b/media/libstagefright/tests/fuzzers/FrameDecoderHelpers.h
new file mode 100644
index 0000000..228c04a
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/FrameDecoderHelpers.h
@@ -0,0 +1,90 @@
+
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#pragma once
+
+#include <media/stagefright/MetaData.h>
+#include "MediaMimeTypes.h"
+
+#define MAX_METADATA_BUF_SIZE 512
+
+namespace android {
+
+std::vector<std::shared_ptr<char>> generated_mime_types;
+
+sp<MetaData> generateMetaData(FuzzedDataProvider *fdp) {
+    sp<MetaData> newMeta = new MetaData();
+
+    // random MIME Type
+    const char *mime_type;
+    size_t index = fdp->ConsumeIntegralInRange<size_t>(0, kMimeTypes.size());
+    // Let there be a chance of a true random string
+    if (index == kMimeTypes.size()) {
+        std::string mime_str = fdp->ConsumeRandomLengthString(64);
+        std::shared_ptr<char> mime_cstr(new char[mime_str.length()+1]);
+        generated_mime_types.push_back(mime_cstr);
+        strncpy(mime_cstr.get(), mime_str.c_str(), mime_str.length()+1);
+        mime_type = mime_cstr.get();
+    } else {
+        mime_type = kMimeTypes[index];
+    }
+    newMeta->setCString(kKeyMIMEType, mime_type);
+
+    // Thumbnail time
+    newMeta->setInt64(kKeyThumbnailTime, fdp->ConsumeIntegral<int64_t>());
+
+    // Values used by allocVideoFrame
+    newMeta->setInt32(kKeyRotation, fdp->ConsumeIntegral<int32_t>());
+    size_t profile_size =
+        fdp->ConsumeIntegralInRange<size_t>(0, MAX_METADATA_BUF_SIZE);
+    std::vector<uint8_t> profile_bytes =
+        fdp->ConsumeBytes<uint8_t>(profile_size);
+    newMeta->setData(kKeyIccProfile,
+                     fdp->ConsumeIntegral<int32_t>(),
+                     profile_bytes.empty() ? nullptr : profile_bytes.data(),
+                     profile_bytes.size());
+    newMeta->setInt32(kKeySARWidth, fdp->ConsumeIntegral<int32_t>());
+    newMeta->setInt32(kKeySARHeight, fdp->ConsumeIntegral<int32_t>());
+    newMeta->setInt32(kKeyDisplayWidth, fdp->ConsumeIntegral<int32_t>());
+    newMeta->setInt32(kKeyDisplayHeight, fdp->ConsumeIntegral<int32_t>());
+
+    // Values used by findThumbnailInfo
+    newMeta->setInt32(kKeyThumbnailWidth, fdp->ConsumeIntegral<int32_t>());
+    newMeta->setInt32(kKeyThumbnailHeight, fdp->ConsumeIntegral<int32_t>());
+    size_t thumbnail_size =
+        fdp->ConsumeIntegralInRange<size_t>(0, MAX_METADATA_BUF_SIZE);
+    std::vector<uint8_t> thumb_bytes =
+        fdp->ConsumeBytes<uint8_t>(thumbnail_size);
+    newMeta->setData(kKeyThumbnailHVCC,
+                     fdp->ConsumeIntegral<int32_t>(),
+                     thumb_bytes.empty() ? nullptr : thumb_bytes.data(),
+                     thumb_bytes.size());
+
+    // Values used by findGridInfo
+    newMeta->setInt32(kKeyTileWidth, fdp->ConsumeIntegral<int32_t>());
+    newMeta->setInt32(kKeyTileHeight, fdp->ConsumeIntegral<int32_t>());
+    newMeta->setInt32(kKeyGridRows, fdp->ConsumeIntegral<int32_t>());
+    newMeta->setInt32(kKeyGridCols, fdp->ConsumeIntegral<int32_t>());
+
+    // A few functions perform a CHECK() that height/width are set
+    newMeta->setInt32(kKeyHeight, fdp->ConsumeIntegral<int32_t>());
+    newMeta->setInt32(kKeyWidth, fdp->ConsumeIntegral<int32_t>());
+
+    return newMeta;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/tests/fuzzers/FuzzerMediaUtility.cpp b/media/libstagefright/tests/fuzzers/FuzzerMediaUtility.cpp
new file mode 100644
index 0000000..810ae95
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/FuzzerMediaUtility.cpp
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2020 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 "FuzzerMediaUtility.h"
+
+#include <media/stagefright/AACWriter.h>
+#include <media/stagefright/AMRWriter.h>
+#include <media/stagefright/MPEG2TSWriter.h>
+#include <media/stagefright/MPEG4Writer.h>
+#include <media/stagefright/OggWriter.h>
+
+#include "MediaMimeTypes.h"
+#include "webm/WebmWriter.h"
+
+namespace android {
+std::string genMimeType(FuzzedDataProvider *dataProvider) {
+    uint8_t idx = dataProvider->ConsumeIntegralInRange<uint8_t>(0, kMimeTypes.size() - 1);
+    return std::string(kMimeTypes[idx]);
+}
+
+sp<IMediaExtractor> genMediaExtractor(FuzzedDataProvider *dataProvider, std::string mimeType,
+                                      uint16_t maxDataAmount) {
+    uint32_t dataBlobSize = dataProvider->ConsumeIntegralInRange<uint16_t>(0, maxDataAmount);
+    std::vector<uint8_t> data = dataProvider->ConsumeBytes<uint8_t>(dataBlobSize);
+    // data:[<mediatype>][;base64],<data>
+    std::string uri("data:");
+    uri += mimeType;
+    // Currently libstagefright only accepts base64 uris
+    uri += ";base64,";
+    android::AString out;
+    android::encodeBase64(data.data(), data.size(), &out);
+    uri += out.c_str();
+
+    sp<DataSource> source =
+        DataSourceFactory::getInstance()->CreateFromURI(NULL /* httpService */, uri.c_str());
+
+    if (source == NULL) {
+        return NULL;
+    }
+
+    return MediaExtractorFactory::Create(source);
+}
+
+sp<MediaSource> genMediaSource(FuzzedDataProvider *dataProvider, uint16_t maxMediaBlobSize) {
+    std::string mime = genMimeType(dataProvider);
+    sp<IMediaExtractor> extractor = genMediaExtractor(dataProvider, mime, maxMediaBlobSize);
+
+    if (extractor == NULL) {
+        return NULL;
+    }
+
+    for (size_t i = 0; i < extractor->countTracks(); ++i) {
+        sp<MetaData> meta = extractor->getTrackMetaData(i);
+
+        const char *trackMime;
+        if (!strcasecmp(mime.c_str(), trackMime)) {
+            sp<IMediaSource> track = extractor->getTrack(i);
+            if (track == NULL) {
+                return NULL;
+            }
+            return new CallbackMediaSource(track);
+        }
+    }
+
+    return NULL;
+}
+
+sp<MediaWriter> createWriter(int fd, StandardWriters writerType, sp<MetaData> fileMeta) {
+    sp<MediaWriter> writer;
+    switch (writerType) {
+        case OGG:
+            writer = new OggWriter(fd);
+            fileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_OGG);
+            break;
+        case AAC:
+            writer = new AACWriter(fd);
+            fileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_AAC_ADIF);
+            break;
+        case AAC_ADTS:
+            writer = new AACWriter(fd);
+            fileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_AAC_ADTS);
+            break;
+        case WEBM:
+            writer = new WebmWriter(fd);
+            fileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_WEBM);
+            break;
+        case MPEG4:
+            writer = new MPEG4Writer(fd);
+            fileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_MPEG_4);
+            break;
+        case AMR_NB:
+            writer = new AMRWriter(fd);
+            fileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_AMR_NB);
+            break;
+        case AMR_WB:
+            writer = new AMRWriter(fd);
+            fileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_AMR_WB);
+            break;
+        case MPEG2TS:
+            writer = new MPEG2TSWriter(fd);
+            fileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_MPEG2TS);
+            break;
+        default:
+            return nullptr;
+    }
+    if (writer != nullptr) {
+        fileMeta->setInt32(kKeyRealTimeRecording, false);
+    }
+    return writer;
+}
+}  // namespace android
\ No newline at end of file
diff --git a/media/libstagefright/tests/fuzzers/FuzzerMediaUtility.h b/media/libstagefright/tests/fuzzers/FuzzerMediaUtility.h
new file mode 100644
index 0000000..98bfb94
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/FuzzerMediaUtility.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2020 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.
+ */
+
+#pragma once
+#include <datasource/DataSourceFactory.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include <android/IMediaExtractor.h>
+#include <media/IMediaHTTPService.h>
+#include <media/mediarecorder.h>
+#include <media/stagefright/CallbackMediaSource.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MediaExtractorFactory.h>
+#include <media/stagefright/MediaWriter.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/foundation/base64.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+enum StandardWriters {
+    OGG,
+    AAC,
+    AAC_ADTS,
+    WEBM,
+    MPEG4,
+    AMR_NB,
+    AMR_WB,
+    MPEG2TS,
+    // Allows FuzzedDataProvider to find the end of this enum.
+    kMaxValue = MPEG2TS,
+};
+
+std::string genMimeType(FuzzedDataProvider *dataProvider);
+sp<IMediaExtractor> genMediaExtractor(FuzzedDataProvider *dataProvider, uint16_t dataAmount);
+sp<MediaSource> genMediaSource(FuzzedDataProvider *dataProvider, uint16_t maxMediaBlobSize);
+
+sp<MediaWriter> createWriter(int32_t fd, StandardWriters writerType, sp<MetaData> fileMeta);
+}  // namespace android
diff --git a/media/libstagefright/tests/fuzzers/IMediaSourceFuzzImpl.h b/media/libstagefright/tests/fuzzers/IMediaSourceFuzzImpl.h
new file mode 100644
index 0000000..e769950
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/IMediaSourceFuzzImpl.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2020 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 IMEDIASOURCEFUZZIMPL_H
+#define IMEDIASOURCEFUZZIMPL_H
+
+#include <media/stagefright/MediaSource.h>
+
+namespace android {
+
+class IMediaSourceFuzzImpl : public IMediaSource {
+ public:
+    IMediaSourceFuzzImpl(FuzzedDataProvider *_fdp, size_t _max_buffer_size) :
+        fdp(_fdp),
+        max_buffer_size(_max_buffer_size) {}
+    status_t start(MetaData*) override { return 0; }
+    status_t stop() override { return 0; }
+    sp<MetaData> getFormat() override { return nullptr; }
+    status_t read(MediaBufferBase**,
+        const MediaSource::ReadOptions*) override;
+    status_t readMultiple(Vector<MediaBufferBase*>*, uint32_t,
+        const MediaSource::ReadOptions*) override;
+    bool supportReadMultiple() override { return true; }
+    bool supportNonblockingRead() override { return true; }
+    status_t pause() override { return 0; }
+
+ protected:
+    IBinder* onAsBinder() { return nullptr; }
+
+ private:
+    FuzzedDataProvider *fdp;
+    std::vector<std::shared_ptr<MediaBufferBase>> buffer_bases;
+    const size_t max_buffer_size;
+};
+
+// This class is simply to expose the destructor
+class MediaBufferFuzzImpl : public MediaBuffer {
+ public:
+    MediaBufferFuzzImpl(void *data, size_t size) : MediaBuffer(data, size) {}
+    ~MediaBufferFuzzImpl() {}
+};
+
+status_t IMediaSourceFuzzImpl::read(MediaBufferBase **buffer,
+        const MediaSource::ReadOptions *options) {
+    Vector<MediaBufferBase*> buffers;
+    status_t ret = readMultiple(&buffers, 1, options);
+    *buffer = buffers.empty() ? nullptr : buffers[0];
+
+    return ret;
+}
+
+status_t IMediaSourceFuzzImpl::readMultiple(Vector<MediaBufferBase*>* buffers,
+        uint32_t maxNumBuffers, const MediaSource::ReadOptions*) {
+    uint32_t num_buffers =
+        fdp->ConsumeIntegralInRange<uint32_t>(0, maxNumBuffers);
+    for(uint32_t i = 0; i < num_buffers; i++) {
+        std::vector<uint8_t> buf = fdp->ConsumeBytes<uint8_t>(
+            fdp->ConsumeIntegralInRange<size_t>(0, max_buffer_size));
+
+        std::shared_ptr<MediaBufferBase> mbb(
+            new MediaBufferFuzzImpl(buf.data(), buf.size()));
+
+        buffer_bases.push_back(mbb);
+        buffers->push_back(mbb.get());
+    }
+
+    // STATUS_OK
+    return 0;
+}
+
+} // namespace android
+
+#endif // IMEDIASOURCEFUZZIMPL_H
+
diff --git a/media/libstagefright/tests/fuzzers/MediaClockFuzzer.cpp b/media/libstagefright/tests/fuzzers/MediaClockFuzzer.cpp
new file mode 100644
index 0000000..9b26f0b
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/MediaClockFuzzer.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2020 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.
+ */
+// Authors: corbin.souffrant@leviathansecurity.com
+//          dylan.katz@leviathansecurity.com
+
+#include <fuzzer/FuzzedDataProvider.h>
+#include <media/stagefright/foundation/AMessage.h>
+#include <media/stagefright/MediaClock.h>
+
+namespace android {
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+    sp<MediaClock> mClock(new MediaClock);
+
+    bool registered = false;
+    while (fdp.remaining_bytes() > 0) {
+        switch (fdp.ConsumeIntegralInRange<uint8_t>(0, 5)) {
+            case 0: {
+                if (registered == false) {
+                    mClock->init();
+                    registered = true;
+                }
+                break;
+                }
+            case 1: {
+                int64_t startingTimeMediaUs = fdp.ConsumeIntegral<int64_t>();
+                mClock->setStartingTimeMedia(startingTimeMediaUs);
+                break;
+            }
+            case 2: {
+                mClock->clearAnchor();
+                break;
+            }
+            case 3: {
+                int64_t anchorTimeRealUs = fdp.ConsumeIntegral<int64_t>();
+                int64_t anchorTimeMediaUs = fdp.ConsumeIntegral<int64_t>();
+                int64_t maxTimeMediaUs = fdp.ConsumeIntegral<int64_t>();
+                mClock->updateAnchor(anchorTimeMediaUs, anchorTimeRealUs,
+                                     maxTimeMediaUs);
+                break;
+            }
+            case 4: {
+                int64_t maxTimeMediaUs = fdp.ConsumeIntegral<int64_t>();
+                mClock->updateMaxTimeMedia(maxTimeMediaUs);
+                break;
+                }
+            case 5: {
+                wp<AMessage> msg(new AMessage);
+                mClock->setNotificationMessage(msg.promote());
+            }
+        }
+    }
+
+    return 0;
+}
+}  // namespace android
diff --git a/media/libstagefright/tests/fuzzers/MediaMimeTypes.h b/media/libstagefright/tests/fuzzers/MediaMimeTypes.h
new file mode 100644
index 0000000..9f337ac
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/MediaMimeTypes.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2020 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 FUZZER_MEDIAMIMETYPES_H_
+#define FUZZER_MEDIAMIMETYPES_H_
+
+#include <media/stagefright/foundation/MediaDefs.h>
+
+namespace android {
+
+static const std::vector<const char*> kMimeTypes {
+    MEDIA_MIMETYPE_IMAGE_JPEG,
+    MEDIA_MIMETYPE_IMAGE_ANDROID_HEIC,
+    MEDIA_MIMETYPE_VIDEO_VP8,
+    MEDIA_MIMETYPE_VIDEO_VP9,
+    MEDIA_MIMETYPE_VIDEO_AV1,
+    MEDIA_MIMETYPE_VIDEO_AVC,
+    MEDIA_MIMETYPE_VIDEO_HEVC,
+    MEDIA_MIMETYPE_VIDEO_MPEG4,
+    MEDIA_MIMETYPE_VIDEO_H263,
+    MEDIA_MIMETYPE_VIDEO_MPEG2,
+    MEDIA_MIMETYPE_VIDEO_RAW,
+    MEDIA_MIMETYPE_VIDEO_DOLBY_VISION,
+    MEDIA_MIMETYPE_VIDEO_SCRAMBLED,
+    MEDIA_MIMETYPE_VIDEO_DIVX,
+    MEDIA_MIMETYPE_VIDEO_DIVX3,
+    MEDIA_MIMETYPE_VIDEO_XVID,
+    MEDIA_MIMETYPE_VIDEO_MJPEG,
+    MEDIA_MIMETYPE_AUDIO_AMR_NB,
+    MEDIA_MIMETYPE_AUDIO_AMR_WB,
+    MEDIA_MIMETYPE_AUDIO_MPEG,
+    MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I,
+    MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II,
+    MEDIA_MIMETYPE_AUDIO_MIDI,
+    MEDIA_MIMETYPE_AUDIO_AAC,
+    MEDIA_MIMETYPE_AUDIO_QCELP,
+    MEDIA_MIMETYPE_AUDIO_VORBIS,
+    MEDIA_MIMETYPE_AUDIO_OPUS,
+    MEDIA_MIMETYPE_AUDIO_G711_ALAW,
+    MEDIA_MIMETYPE_AUDIO_G711_MLAW,
+    MEDIA_MIMETYPE_AUDIO_RAW,
+    MEDIA_MIMETYPE_AUDIO_FLAC,
+    MEDIA_MIMETYPE_AUDIO_AAC_ADTS,
+    MEDIA_MIMETYPE_AUDIO_MSGSM,
+    MEDIA_MIMETYPE_AUDIO_AC3,
+    MEDIA_MIMETYPE_AUDIO_EAC3,
+    MEDIA_MIMETYPE_AUDIO_EAC3_JOC,
+    MEDIA_MIMETYPE_AUDIO_AC4,
+    MEDIA_MIMETYPE_AUDIO_SCRAMBLED,
+    MEDIA_MIMETYPE_AUDIO_ALAC,
+    MEDIA_MIMETYPE_AUDIO_WMA,
+    MEDIA_MIMETYPE_AUDIO_MS_ADPCM,
+    MEDIA_MIMETYPE_AUDIO_DVI_IMA_ADPCM,
+    MEDIA_MIMETYPE_CONTAINER_MPEG4,
+    MEDIA_MIMETYPE_CONTAINER_WAV,
+    MEDIA_MIMETYPE_CONTAINER_OGG,
+    MEDIA_MIMETYPE_CONTAINER_MATROSKA,
+    MEDIA_MIMETYPE_CONTAINER_MPEG2TS,
+    MEDIA_MIMETYPE_CONTAINER_AVI,
+    MEDIA_MIMETYPE_CONTAINER_MPEG2PS,
+    MEDIA_MIMETYPE_CONTAINER_HEIF,
+    MEDIA_MIMETYPE_TEXT_3GPP,
+    MEDIA_MIMETYPE_TEXT_SUBRIP,
+    MEDIA_MIMETYPE_TEXT_VTT,
+    MEDIA_MIMETYPE_TEXT_CEA_608,
+    MEDIA_MIMETYPE_TEXT_CEA_708,
+    MEDIA_MIMETYPE_DATA_TIMED_ID3
+};
+
+}  // namespace android
+
+#endif  // FUZZER_MEDIAMIMETYPES_H_
diff --git a/media/libstagefright/tests/fuzzers/MediaMuxerFuzzer.cpp b/media/libstagefright/tests/fuzzers/MediaMuxerFuzzer.cpp
new file mode 100644
index 0000000..5df3267
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/MediaMuxerFuzzer.cpp
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2020 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.
+ */
+// Authors: corbin.souffrant@leviathansecurity.com
+//          dylan.katz@leviathansecurity.com
+
+#include <MediaMuxerFuzzer.h>
+#include <cutils/ashmem.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include <media/stagefright/MediaMuxer.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/AMessage.h>
+
+namespace android {
+
+// Can't seem to get setBuffer or setString working. It always segfaults on a
+// null pointer read or memleaks. So that functionality is missing.
+void createMessage(AMessage *msg, FuzzedDataProvider *fdp) {
+  size_t count = fdp->ConsumeIntegralInRange<size_t>(0, 32);
+  while (fdp->remaining_bytes() > 0 && count > 0) {
+    uint8_t function_id =
+        fdp->ConsumeIntegralInRange<uint8_t>(0, amessage_setvals.size() - 1);
+    amessage_setvals[function_id](msg, fdp);
+    count--;
+  }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+  FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+
+  size_t data_size = fdp.ConsumeIntegralInRange<size_t>(0, size);
+  int fd = ashmem_create_region("mediamuxer_fuzz_region", data_size);
+  if (fd < 0)
+    return 0;
+
+  uint8_t *sh_data = static_cast<uint8_t *>(
+      mmap(NULL, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
+  if (sh_data == MAP_FAILED)
+    return 0;
+
+  MediaMuxer::OutputFormat format =
+      (MediaMuxer::OutputFormat)fdp.ConsumeIntegralInRange<int32_t>(0, 4);
+  sp<MediaMuxer> mMuxer(new MediaMuxer(fd, format));
+
+  while (fdp.remaining_bytes() > 1) {
+    switch (fdp.ConsumeIntegralInRange<uint8_t>(0, 4)) {
+    case 0: {
+      // For some reason it only likes mp4s here...
+      if (format == 1 || format == 4)
+        break;
+
+      sp<AMessage> a_format(new AMessage);
+      createMessage(a_format.get(), &fdp);
+      mMuxer->addTrack(a_format);
+      break;
+    }
+    case 1: {
+      mMuxer->start();
+      break;
+    }
+    case 2: {
+      int degrees = fdp.ConsumeIntegral<int>();
+      mMuxer->setOrientationHint(degrees);
+      break;
+    }
+    case 3: {
+      int latitude = fdp.ConsumeIntegral<int>();
+      int longitude = fdp.ConsumeIntegral<int>();
+      mMuxer->setLocation(latitude, longitude);
+      break;
+    }
+    case 4: {
+      size_t buf_size = fdp.ConsumeIntegralInRange<size_t>(0, data_size);
+      sp<ABuffer> a_buffer(new ABuffer(buf_size));
+
+      size_t trackIndex = fdp.ConsumeIntegral<size_t>();
+      int64_t timeUs = fdp.ConsumeIntegral<int64_t>();
+      uint32_t flags = fdp.ConsumeIntegral<uint32_t>();
+      mMuxer->writeSampleData(a_buffer, trackIndex, timeUs, flags);
+    }
+    }
+  }
+
+  if (fdp.ConsumeBool())
+    mMuxer->stop();
+
+  munmap(sh_data, data_size);
+  close(fd);
+  return 0;
+}
+} // namespace android
diff --git a/media/libstagefright/tests/fuzzers/MediaMuxerFuzzer.h b/media/libstagefright/tests/fuzzers/MediaMuxerFuzzer.h
new file mode 100644
index 0000000..7d4421d
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/MediaMuxerFuzzer.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2020 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.
+ */
+// Authors: corbin.souffrant@leviathansecurity.com
+//          dylan.katz@leviathansecurity.com
+
+#pragma once
+
+#include <fuzzer/FuzzedDataProvider.h>
+#include <media/stagefright/foundation/AMessage.h>
+
+namespace android {
+
+// Mappings vectors are the list of attributes that the MediaMuxer
+// class looks for in the message.
+static std::vector<const char *> floatMappings{
+    "capture-rate",
+    "time-lapse-fps",
+    "frame-rate",
+};
+
+static std::vector<const char *> int64Mappings{
+    "exif-offset",    "exif-size", "target-time",
+    "thumbnail-time", "timeUs",    "durationUs",
+};
+
+static std::vector<const char *> int32Mappings{"loop",
+                                               "time-scale",
+                                               "crypto-mode",
+                                               "crypto-default-iv-size",
+                                               "crypto-encrypted-byte-block",
+                                               "crypto-skip-byte-block",
+                                               "frame-count",
+                                               "max-bitrate",
+                                               "pcm-big-endian",
+                                               "temporal-layer-count",
+                                               "temporal-layer-id",
+                                               "thumbnail-width",
+                                               "thumbnail-height",
+                                               "track-id",
+                                               "valid-samples",
+                                               "color-format",
+                                               "ca-system-id",
+                                               "is-sync-frame",
+                                               "bitrate",
+                                               "max-bitrate",
+                                               "width",
+                                               "height",
+                                               "sar-width",
+                                               "sar-height",
+                                               "display-width",
+                                               "display-height",
+                                               "is-default",
+                                               "tile-width",
+                                               "tile-height",
+                                               "grid-rows",
+                                               "grid-cols",
+                                               "rotation-degrees",
+                                               "channel-count",
+                                               "sample-rate",
+                                               "bits-per-sample",
+                                               "channel-mask",
+                                               "encoder-delay",
+                                               "encoder-padding",
+                                               "is-adts",
+                                               "frame-rate",
+                                               "max-height",
+                                               "max-width",
+                                               "max-input-size",
+                                               "haptic-channel-count",
+                                               "pcm-encoding",
+                                               "aac-profile"};
+
+static const std::vector<std::function<void(AMessage *, FuzzedDataProvider *)>>
+    amessage_setvals = {
+        [](AMessage *msg, FuzzedDataProvider *fdp) -> void {
+          msg->setRect("crop", fdp->ConsumeIntegral<int32_t>(),
+                       fdp->ConsumeIntegral<int32_t>(),
+                       fdp->ConsumeIntegral<int32_t>(),
+                       fdp->ConsumeIntegral<int32_t>());
+        },
+        [](AMessage *msg, FuzzedDataProvider *fdp) -> void {
+          msg->setFloat(floatMappings[fdp->ConsumeIntegralInRange<size_t>(
+                            0, floatMappings.size() - 1)],
+                        fdp->ConsumeFloatingPoint<float>());
+        },
+        [](AMessage *msg, FuzzedDataProvider *fdp) -> void {
+          msg->setInt64(int64Mappings[fdp->ConsumeIntegralInRange<size_t>(
+                            0, int64Mappings.size() - 1)],
+                        fdp->ConsumeIntegral<int64_t>());
+        },
+        [](AMessage *msg, FuzzedDataProvider *fdp) -> void {
+          msg->setInt32(int32Mappings[fdp->ConsumeIntegralInRange<size_t>(
+                            0, int32Mappings.size() - 1)],
+                        fdp->ConsumeIntegral<int32_t>());
+        }};
+} // namespace android
diff --git a/media/libstagefright/tests/fuzzers/SkipCutBufferFuzzer.cpp b/media/libstagefright/tests/fuzzers/SkipCutBufferFuzzer.cpp
new file mode 100644
index 0000000..1f78e6d
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/SkipCutBufferFuzzer.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2020 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.
+ */
+// Authors: corbin.souffrant@leviathansecurity.com
+//          dylan.katz@leviathansecurity.com
+
+#include <fuzzer/FuzzedDataProvider.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/SkipCutBuffer.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/AMessage.h>
+
+namespace android {
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+  FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+  size_t skip = fdp.ConsumeIntegral<size_t>();
+  size_t cut = fdp.ConsumeIntegral<size_t>();
+  size_t num16Channels = fdp.ConsumeIntegral<size_t>();
+  sp<SkipCutBuffer> sBuffer(new SkipCutBuffer(skip, cut, num16Channels));
+
+  while (fdp.remaining_bytes() > 0) {
+    // Cap size to 1024 to limit max amount allocated.
+    size_t buf_size = fdp.ConsumeIntegralInRange<size_t>(0, 1024);
+    size_t range = fdp.ConsumeIntegralInRange<size_t>(0, buf_size);
+    size_t length = fdp.ConsumeIntegralInRange<size_t>(0, buf_size - range);
+
+    switch (fdp.ConsumeIntegralInRange<uint8_t>(0, 4)) {
+    case 0: {
+      sp<ABuffer> a_buffer(new ABuffer(buf_size));
+      sp<AMessage> format(new AMessage);
+      sp<MediaCodecBuffer> s_buffer(new MediaCodecBuffer(format, a_buffer));
+      s_buffer->setRange(range, length);
+      sBuffer->submit(s_buffer);
+      break;
+    }
+    case 1: {
+      std::unique_ptr<MediaBufferBase> m_buffer(new MediaBuffer(buf_size));
+      m_buffer->set_range(range, length);
+      sBuffer->submit(reinterpret_cast<MediaBuffer *>(m_buffer.get()));
+      break;
+    }
+    case 2: {
+      sp<ABuffer> a_buffer(new ABuffer(buf_size));
+      sp<AMessage> format(new AMessage);
+      sp<MediaCodecBuffer> s_buffer(new MediaCodecBuffer(format, a_buffer));
+      a_buffer->setRange(range, length);
+      sBuffer->submit(a_buffer);
+      break;
+    }
+    case 3: {
+      sBuffer->clear();
+      break;
+    }
+    case 4: {
+      sBuffer->size();
+    }
+    }
+  }
+  return 0;
+}
+} // namespace android
diff --git a/media/libstagefright/tests/fuzzers/StagefrightMediaScannerFuzzer.cpp b/media/libstagefright/tests/fuzzers/StagefrightMediaScannerFuzzer.cpp
new file mode 100644
index 0000000..c50c951
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/StagefrightMediaScannerFuzzer.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2020 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.
+ */
+// Authors: corbin.souffrant@leviathansecurity.com
+//          dylan.katz@leviathansecurity.com
+
+#include <fuzzer/FuzzedDataProvider.h>
+#include <media/stagefright/StagefrightMediaScanner.h>
+
+#include <cstdio>
+
+namespace android {
+class FuzzMediaScannerClient : public MediaScannerClient {
+ public:
+    virtual status_t scanFile(const char*, long long, long long, bool, bool) {
+        return 0;
+    }
+
+    virtual status_t handleStringTag(const char*, const char*) { return 0; }
+
+    virtual status_t setMimeType(const char*) { return 0; }
+};
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+    StagefrightMediaScanner mScanner = StagefrightMediaScanner();
+    // Without this, the fuzzer crashes for some reason.
+    mScanner.setLocale("");
+
+    while (fdp.remaining_bytes() > 0) {
+        switch (fdp.ConsumeIntegralInRange<uint8_t>(0, 1)) {
+            case 0: {
+                std::string path = fdp.ConsumeRandomLengthString(fdp.remaining_bytes());
+                std::string mimeType =
+                    fdp.ConsumeRandomLengthString(fdp.remaining_bytes());
+                std::shared_ptr<MediaScannerClient> client(new FuzzMediaScannerClient());
+                mScanner.processFile(path.c_str(), mimeType.c_str(), *client);
+                break;
+            }
+            case 1: {
+                int fd = fdp.ConsumeIntegral<int>();
+                if (fd >= 0 && fd <= 2) fd = 3;
+                mScanner.extractAlbumArt(fd);
+            }
+        }
+    }
+    return 0;
+}
+}  // namespace android
diff --git a/media/libstagefright/tests/fuzzers/WriterFuzzer.cpp b/media/libstagefright/tests/fuzzers/WriterFuzzer.cpp
new file mode 100644
index 0000000..03e9b43
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/WriterFuzzer.cpp
@@ -0,0 +1,222 @@
+/*
+ * Copyright 2020 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.
+ */
+// Authors: corbin.souffrant@leviathansecurity.com
+//          dylan.katz@leviathansecurity.com
+
+#include <android-base/file.h>
+#include <ctype.h>
+#include <media/mediarecorder.h>
+#include <media/stagefright/MPEG4Writer.h>
+#include <media/stagefright/MediaDefs.h>
+#include <stdlib.h>
+#include <utils/StrongPointer.h>
+#include <utils/Vector.h>
+
+#include <functional>
+#include <string>
+
+#include "FuzzerMediaUtility.h"
+#include "fuzzer/FuzzedDataProvider.h"
+
+static constexpr uint16_t kMaxOperations = 5000;
+static constexpr uint8_t kMaxPackageNameLen = 50;
+// For other strings in mpeg we want a higher limit.
+static constexpr uint16_t kMaxMPEGStrLen = 1000;
+static constexpr uint16_t kMaxMediaBlobSize = 1000;
+
+namespace android {
+
+std::string getFourCC(FuzzedDataProvider *fdp) {
+    std::string fourCC = fdp->ConsumeRandomLengthString(4);
+    // Replace any existing nulls
+    for (size_t pos = 0; pos < fourCC.length(); pos++) {
+        if (fourCC.at(pos) == '\0') {
+            fourCC.replace(pos, 1, "a");
+        }
+    }
+
+    // If our string is too short, fill the remainder with "a"s.
+    while (fourCC.length() < 4) {
+        fourCC += 'a';
+    }
+    return fourCC;
+}
+
+typedef std::vector<std::function<void(FuzzedDataProvider*,
+                                    sp<MediaWriter>, sp<MetaData>, int tmpFileFd)>> OperationVec;
+typedef std::vector<std::function<void(FuzzedDataProvider*, MPEG4Writer*)>> MPEG4OperationVec;
+static const OperationVec operations = {
+    [](FuzzedDataProvider*, sp<MediaWriter> mediaWriter, sp<MetaData>, int) {
+        mediaWriter->pause();
+    },
+    [](FuzzedDataProvider *dataProvider, sp<MediaWriter> mediaWriter, sp<MetaData>, int tmpFd) {
+        bool valid_fd = dataProvider->ConsumeBool();
+        int fd = -1;
+        if (valid_fd) {
+            fd = tmpFd;
+        }
+        // Args don't seem to be used
+        Vector<String16> args;
+        mediaWriter->dump(fd, args);
+    },
+    [](FuzzedDataProvider *dataProvider, sp<MediaWriter> mediaWriter, sp<MetaData>, int tmpFd) {
+        bool valid_fd = dataProvider->ConsumeBool();
+        int fd = -1;
+        if (valid_fd) {
+            fd = tmpFd;
+        }
+        mediaWriter->setNextFd(fd);
+    },
+    [](FuzzedDataProvider *dataProvider, sp<MediaWriter> mediaWriter, sp<MetaData>, int) {
+        mediaWriter->setCaptureRate(dataProvider->ConsumeFloatingPoint<float>());
+    },
+    [](FuzzedDataProvider *dataProvider, sp<MediaWriter> mediaWriter, sp<MetaData>, int) {
+        mediaWriter->setMaxFileDuration(dataProvider->ConsumeIntegral<int64_t>());
+    },
+    [](FuzzedDataProvider *dataProvider, sp<MediaWriter> mediaWriter, sp<MetaData>, int) {
+        mediaWriter->setStartTimeOffsetMs(dataProvider->ConsumeIntegral<int>());
+
+        // Likely won't do much, but might as well as do a quick check
+        // while we're here.
+        mediaWriter->getStartTimeOffsetMs();
+    },
+    [](FuzzedDataProvider *dataProvider, sp<MediaWriter> mediaWriter, sp<MetaData>, int) {
+        mediaWriter->setMaxFileDuration(dataProvider->ConsumeIntegral<int64_t>());
+    },
+    [](FuzzedDataProvider *dataProvider, sp<MediaWriter> mediaWriter, sp<MetaData>, int) {
+        mediaWriter->setMaxFileDuration(dataProvider->ConsumeIntegral<int64_t>());
+    },
+};
+
+static const MPEG4OperationVec mpeg4Operations = {
+    [](FuzzedDataProvider*, MPEG4Writer *mediaWriter) { mediaWriter->notifyApproachingLimit(); },
+    // Lower level write methods.
+    // High-level startBox/endBox/etc are all called elsewhere,
+    [](FuzzedDataProvider *dataProvider, MPEG4Writer *mediaWriter) {
+        uint8_t val = dataProvider->ConsumeIntegral<uint8_t>();
+        mediaWriter->writeInt8(val);
+    },
+    [](FuzzedDataProvider *dataProvider, MPEG4Writer *mediaWriter) {
+        uint16_t val = dataProvider->ConsumeIntegral<uint16_t>();
+        mediaWriter->writeInt16(val);
+    },
+    [](FuzzedDataProvider *dataProvider, MPEG4Writer *mediaWriter) {
+        uint32_t val = dataProvider->ConsumeIntegral<uint32_t>();
+        mediaWriter->writeInt32(val);
+    },
+    [](FuzzedDataProvider *dataProvider, MPEG4Writer *mediaWriter) {
+        uint64_t val = dataProvider->ConsumeIntegral<uint64_t>();
+        mediaWriter->writeInt64(val);
+    },
+    [](FuzzedDataProvider *dataProvider, MPEG4Writer *mediaWriter) {
+        std::string strVal = dataProvider->ConsumeRandomLengthString(kMaxMPEGStrLen);
+        mediaWriter->writeCString(strVal.c_str());
+    },
+    [](FuzzedDataProvider *dataProvider, MPEG4Writer *mediaWriter) {
+        std::string fourCC = getFourCC(dataProvider);
+        mediaWriter->writeFourcc(fourCC.c_str());
+    },
+
+    // Misc setters
+    [](FuzzedDataProvider *dataProvider, MPEG4Writer *mediaWriter) {
+        uint32_t layers = dataProvider->ConsumeIntegral<uint32_t>();
+        mediaWriter->setTemporalLayerCount(layers);
+    },
+    [](FuzzedDataProvider *dataProvider, MPEG4Writer *mediaWriter) {
+        uint32_t duration = dataProvider->ConsumeIntegral<uint32_t>();
+        mediaWriter->setInterleaveDuration(duration);
+    },
+    [](FuzzedDataProvider *dataProvider, MPEG4Writer *mediaWriter) {
+        int lat = dataProvider->ConsumeIntegral<int>();
+        int lon = dataProvider->ConsumeIntegral<int>();
+        mediaWriter->setGeoData(lat, lon);
+    },
+};
+
+// Not all writers can always add new sources, so we'll need additional checks.
+void addSource(FuzzedDataProvider *dataProvider, sp<MediaWriter> mediaWriter) {
+    sp<MediaSource> mediaSource = genMediaSource(dataProvider, kMaxMediaBlobSize);
+    if (mediaSource == NULL) {
+        // There's a static check preventing NULLs in addSource.
+        return;
+    }
+    mediaWriter->addSource(mediaSource);
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    FuzzedDataProvider dataProvider(data, size);
+    TemporaryFile tf;
+    sp<MetaData> fileMeta = new MetaData;
+    StandardWriters writerType = dataProvider.ConsumeEnum<StandardWriters>();
+    sp<MediaWriter> writer = createWriter(tf.fd, writerType, fileMeta);
+
+    std::string packageName = dataProvider.ConsumeRandomLengthString(kMaxPackageNameLen);
+
+    sp<MediaRecorder> mr = new MediaRecorder(String16(packageName.c_str()));
+    writer->setListener(mr);
+
+    uint8_t baseOpLen = operations.size();
+    uint8_t totalLen = baseOpLen;
+    uint8_t maxSources;
+    // Different writers support different amounts of sources.
+    switch (writerType) {
+        case StandardWriters::AAC:
+        case StandardWriters::AAC_ADTS:
+        case StandardWriters::AMR_NB:
+        case StandardWriters::AMR_WB:
+        case StandardWriters::OGG:
+            maxSources = 1;
+            break;
+        case StandardWriters::WEBM:
+            maxSources = 2;
+            break;
+        default:
+            maxSources = UINT8_MAX;
+            break;
+    }
+    // Initialize some number of sources and add them to our writer.
+    uint8_t sourceCount = dataProvider.ConsumeIntegralInRange<uint8_t>(0, maxSources);
+    for (uint8_t i = 0; i < sourceCount; i++) {
+        addSource(&dataProvider, writer);
+    }
+
+    // Increase our range if additional operations are implemented.
+    // Currently only MPEG4 has additiona public operations on their writer.
+    if (writerType == StandardWriters::MPEG4) {
+        totalLen += mpeg4Operations.size();
+    }
+
+    // Many operations require the writer to be started.
+    writer->start(fileMeta.get());
+    for (size_t ops_run = 0; dataProvider.remaining_bytes() > 0 && ops_run < kMaxOperations - 1;
+            ops_run++) {
+        uint8_t op = dataProvider.ConsumeIntegralInRange<uint8_t>(0, totalLen - 1);
+        if (op < baseOpLen) {
+            operations[op](&dataProvider, writer, fileMeta, tf.fd);
+        } else if (writerType == StandardWriters::MPEG4) {
+            mpeg4Operations[op - baseOpLen](&dataProvider, (MPEG4Writer*)writer.get());
+        } else {
+            // Here just in case, will error out.
+            operations[op](&dataProvider, writer, fileMeta, tf.fd);
+        }
+    }
+    writer->stop();
+
+    writer.clear();
+    writer = nullptr;
+    return 0;
+}
+}  // namespace android
diff --git a/media/libstagefright/tests/fuzzers/dictionaries/formats.dict b/media/libstagefright/tests/fuzzers/dictionaries/formats.dict
new file mode 100644
index 0000000..4ab22de
--- /dev/null
+++ b/media/libstagefright/tests/fuzzers/dictionaries/formats.dict
@@ -0,0 +1,299 @@
+############################################################################################################
+# This file is a combination of these dictionaries:                                                        #
+# https://github.com/google/fuzzing/blob/0c48531c4d317cea9479b3ec1b0ddb9edc438c3a/dictionaries/mp4.dict    #
+# https://github.com/google/fuzzing/blob/0c48531c4d317cea9479b3ec1b0ddb9edc438c3a/dictionaries/webm.dict   #
+# https://github.com/google/fuzzing/blob/0c48531c4d317cea9479b3ec1b0ddb9edc438c3a/dictionaries/ogg.dict    #
+# MPEG4, OGG, and WEBM are all formats used by MediaWriter.                                                #
+############################################################################################################
+# mp4.dict
+# Taken from https://chromium.googlesource.com/chromium/src/+/master/media/test/mp4.dict
+FOURCC_NULL="\x00\x00\x00\x00"
+FOURCC_AC3 ="\x61\x63\x2d\x33"
+FOURCC_EAC3="\x65\x63\x2d\x33"
+FOURCC_AVC1="\x61\x76\x63\x31"
+FOURCC_AVC3="\x61\x76\x63\x33"
+FOURCC_AVCC="\x61\x76\x63\x43"
+FOURCC_BLOC="\x62\x6C\x6F\x63"
+FOURCC_CENC="\x63\x65\x6e\x63"
+FOURCC_CO64="\x63\x6f\x36\x34"
+FOURCC_CTTS="\x63\x74\x74\x73"
+FOURCC_DINF="\x64\x69\x6e\x66"
+FOURCC_EDTS="\x65\x64\x74\x73"
+FOURCC_EMSG="\x65\x6d\x73\x67"
+FOURCC_ELST="\x65\x6c\x73\x74"
+FOURCC_ENCA="\x65\x6e\x63\x61"
+FOURCC_ENCV="\x65\x6e\x63\x76"
+FOURCC_ESDS="\x65\x73\x64\x73"
+FOURCC_FREE="\x66\x72\x65\x65"
+FOURCC_FRMA="\x66\x72\x6d\x61"
+FOURCC_FTYP="\x66\x74\x79\x70"
+FOURCC_HDLR="\x68\x64\x6c\x72"
+FOURCC_HINT="\x68\x69\x6e\x74"
+FOURCC_HVC1="\x68\x76\x63\x31"
+FOURCC_HVCC="\x68\x76\x63\x43"
+FOURCC_IODS="\x69\x6f\x64\x73"
+FOURCC_MDAT="\x6d\x64\x61\x74"
+FOURCC_MDHD="\x6d\x64\x68\x64"
+FOURCC_MDIA="\x6d\x64\x69\x61"
+FOURCC_MECO="\x6d\x65\x63\x6f"
+FOURCC_MEHD="\x6d\x65\x68\x64"
+FOURCC_META="\x6d\x65\x74\x61"
+FOURCC_MFHD="\x6d\x66\x68\x64"
+FOURCC_MFRA="\x6d\x66\x72\x61"
+FOURCC_MINF="\x6d\x69\x6e\x66"
+FOURCC_MOOF="\x6d\x6f\x6f\x66"
+FOURCC_MOOV="\x6d\x6f\x6f\x76"
+FOURCC_MP4A="\x6d\x70\x34\x61"
+FOURCC_MP4V="\x6d\x70\x34\x76"
+FOURCC_MVEX="\x6d\x76\x65\x78"
+FOURCC_MVHD="\x6d\x76\x68\x64"
+FOURCC_PASP="\x70\x61\x73\x70"
+FOURCC_PDIN="\x70\x64\x69\x6e"
+FOURCC_PRFT="\x70\x72\x66\x74"
+FOURCC_PSSH="\x70\x73\x73\x68"
+FOURCC_SAIO="\x73\x61\x69\x6f"
+FOURCC_SAIZ="\x73\x61\x69\x7a"
+FOURCC_SBGP="\x73\x62\x67\x70"
+FOURCC_SCHI="\x73\x63\x68\x69"
+FOURCC_SCHM="\x73\x63\x68\x6d"
+FOURCC_SDTP="\x73\x64\x74\x70"
+FOURCC_SEIG="\x73\x65\x69\x67"
+FOURCC_SENC="\x73\x65\x6e\x63"
+FOURCC_SGPD="\x73\x67\x70\x64"
+FOURCC_SIDX="\x73\x69\x64\x78"
+FOURCC_SINF="\x73\x69\x6e\x66"
+FOURCC_SKIP="\x73\x6b\x69\x70"
+FOURCC_SMHD="\x73\x6d\x68\x64"
+FOURCC_SOUN="\x73\x6f\x75\x6e"
+FOURCC_SSIX="\x73\x73\x69\x78"
+FOURCC_STBL="\x73\x74\x62\x6c"
+FOURCC_STCO="\x73\x74\x63\x6f"
+FOURCC_STSC="\x73\x74\x73\x63"
+FOURCC_STSD="\x73\x74\x73\x64"
+FOURCC_STSS="\x73\x74\x73\x73"
+FOURCC_STSZ="\x73\x74\x73\x7a"
+FOURCC_STTS="\x73\x74\x74\x73"
+FOURCC_STYP="\x73\x74\x79\x70"
+FOURCC_TENC="\x74\x65\x6e\x63"
+FOURCC_TFDT="\x74\x66\x64\x74"
+FOURCC_TFHD="\x74\x66\x68\x64"
+FOURCC_TKHD="\x74\x6b\x68\x64"
+FOURCC_TRAF="\x74\x72\x61\x66"
+FOURCC_TRAK="\x74\x72\x61\x6b"
+FOURCC_TREX="\x74\x72\x65\x78"
+FOURCC_TRUN="\x74\x72\x75\x6e"
+FOURCC_UDTA="\x75\x64\x74\x61"
+FOURCC_UUID="\x75\x75\x69\x64"
+FOURCC_VIDE="\x76\x69\x64\x65"
+FOURCC_VMHD="\x76\x6d\x68\x64"
+FOURCC_WIDE="\x77\x69\x64\x65"
+
+# ogg.dict
+# https://xiph.org/vorbis/doc/Vorbis_I_spec.html
+
+header="OggS"
+
+# Codecs
+"BBCD\x00"
+"\x7fFLAC"
+"\x80theora"
+"\x01vorbis"
+"CELT    "
+"CMML\x00\x00\x00\x00"
+"\x8bJNG\x0d\x0a\x1a\x0a"
+"\x80kate\x00\x00\x00"
+"OggMIDI\x00"
+"\x8aMNG\x0d\x0a\x1a\x0a"
+"PCM     "
+"\x89PNG\x0d\x0a\x1a\x0a"
+"Speex   "
+"YUV4MPEG"
+
+# Metadata
+"TITLE="
+"VERSION="
+"ALBUM="
+"TRACKNUMBER="
+"ARTIST="
+"PERFORMER="
+"COPYRIGHT="
+"LICENSE="
+"ORGANIZATION="
+"DESCRIPTION="
+"GENRE="
+"DATE="
+"LOCATION="
+"CONTACT="
+"ISRC="
+
+# webm.dict
+# Element IDs.
+IdAesSettingsCipherMode = "\x47\xE8"
+IdAlphaMode = "\x53\xC0"
+IdAspectRatioType = "\x54\xB3"
+IdAudio = "\xE1"
+IdBitDepth = "\x62\x64"
+IdBitsPerChannel = "\x55\xB2"
+IdBlock = "\xA1"
+IdBlockAddId = "\xEE"
+IdBlockAdditional = "\xA5"
+IdBlockAdditions = "\x75\xA1"
+IdBlockDuration = "\x9B"
+IdBlockGroup = "\xA0"
+IdBlockMore = "\xA6"
+IdBlockVirtual = "\xA2"
+IdCbSubsamplingHorz = "\x55\xB5"
+IdCbSubsamplingVert = "\x55\xB6"
+IdChannels = "\x9F"
+IdChapCountry = "\x43\x7E"
+IdChapLanguage = "\x43\x7C"
+IdChapString = "\x85"
+IdChapterAtom = "\xB6"
+IdChapterDisplay = "\x80"
+IdChapterStringUID = "\x56\x54"
+IdChapterStringUid = "\x56\x54"
+IdChapterTimeEnd = "\x92"
+IdChapterTimeStart = "\x91"
+IdChapterUID = "\x73\xC4"
+IdChapterUid = "\x73\xC4"
+IdChapters = "\x10\x43\xA7\x70"
+IdChromaSitingHorz = "\x55\xB7"
+IdChromaSitingVert = "\x55\xB8"
+IdChromaSubsamplingHorz = "\x55\xB3"
+IdChromaSubsamplingVert = "\x55\xB4"
+IdCluster = "\x1F\x43\xB6\x75"
+IdCodecDelay = "\x56\xAA"
+IdCodecID = "\x86"
+IdCodecName = "\x25\x86\x88"
+IdCodecPrivate = "\x63\xA2"
+IdColour = "\x55\xB0"
+IdContentEncAESSettings = "\x47\xE7"
+IdContentEncAesSettings = "\x47\xE7"
+IdContentEncAlgo = "\x47\xE1"
+IdContentEncKeyId = "\x47\xE2"
+IdContentEncoding = "\x62\x40"
+IdContentEncodingOrder = "\x50\x31"
+IdContentEncodingScope = "\x50\x32"
+IdContentEncodingType = "\x50\x33"
+IdContentEncodings = "\x6D\x80"
+IdContentEncryption = "\x50\x35"
+IdCueBlockNumber = "\x53\x78"
+IdCueClusterPosition = "\xF1"
+IdCueDuration = "\xB2"
+IdCuePoint = "\xBB"
+IdCueRelativePosition = "\xF0"
+IdCueTime = "\xB3"
+IdCueTrack = "\xF7"
+IdCueTrackPositions = "\xB7"
+IdCues = "\x1C\x53\xBB\x6B"
+IdDateUTC = "\x44\x61"
+IdDateUtc = "\x44\x61"
+IdDefaultDuration = "\x23\xE3\x83"
+IdDiscardPadding = "\x75\xA2"
+IdDisplayHeight = "\x54\xBA"
+IdDisplayUnit = "\x54\xB2"
+IdDisplayWidth = "\x54\xB0"
+IdDocType = "\x42\x82"
+IdDocTypeReadVersion = "\x42\x85"
+IdDocTypeVersion = "\x42\x87"
+IdDuration = "\x44\x89"
+IdEBML = "\x1A\x45\xDF\xA3"
+IdEBMLMaxIDLength = "\x42\xF2"
+IdEBMLMaxSizeLength = "\x42\xF3"
+IdEBMLReadVersion = "\x42\xF7"
+IdEBMLVersion = "\x42\x86"
+IdEbml = "\x1A\x45\xDF\xA3"
+IdEbmlMaxIdLength = "\x42\xF2"
+IdEbmlMaxSizeLength = "\x42\xF3"
+IdEbmlReadVersion = "\x42\xF7"
+IdEbmlVersion = "\x42\x86"
+IdEditionEntry = "\x45\xB9"
+IdFileUsedEndTime = "\x46\x62"
+IdFileUsedStartTime = "\x46\x61"
+IdFlagDefault = "\x88"
+IdFlagEnabled = "\xB9"
+IdFlagForced = "\x55\xAA"
+IdFlagInterlaced = "\x9A"
+IdFlagLacing = "\x9C"
+IdFrameRate = "\x23\x83\xE3"
+IdInfo = "\x15\x49\xA9\x66"
+IdLaceNumber = "\xCC"
+IdLanguage = "\x22\xB5\x9C"
+IdLuminanceMax = "\x55\xD9"
+IdLuminanceMin = "\x55\xDA"
+IdMasteringMetadata = "\x55\xD0"
+IdMatrixCoefficients = "\x55\xB1"
+IdMaxCll = "\x55\xBC"
+IdMaxFall = "\x55\xBD"
+IdMuxingApp = "\x4D\x80"
+IdName = "\x53\x6E"
+IdOutputSamplingFrequency = "\x78\xB5"
+IdPixelCropBottom = "\x54\xAA"
+IdPixelCropLeft = "\x54\xCC"
+IdPixelCropRight = "\x54\xDD"
+IdPixelCropTop = "\x54\xBB"
+IdPixelHeight = "\xBA"
+IdPixelWidth = "\xB0"
+IdPrevSize = "\xAB"
+IdPrimaries = "\x55\xBB"
+IdPrimaryBChromaticityX = "\x55\xD5"
+IdPrimaryBChromaticityY = "\x55\xD6"
+IdPrimaryGChromaticityX = "\x55\xD3"
+IdPrimaryGChromaticityY = "\x55\xD4"
+IdPrimaryRChromaticityX = "\x55\xD1"
+IdPrimaryRChromaticityY = "\x55\xD2"
+IdProjection = "\x76\x70"
+IdProjectionPosePitch = "\x76\x74"
+IdProjectionPoseRoll = "\x76\x75"
+IdProjectionPoseYaw = "\x76\x73"
+IdProjectionPrivate = "\x76\x72"
+IdProjectionType = "\x76\x71"
+IdRange = "\x55\xB9"
+IdReferenceBlock = "\xFB"
+IdSamplingFrequency = "\xB5"
+IdSeek = "\x4D\xBB"
+IdSeekHead = "\x11\x4D\x9B\x74"
+IdSeekID = "\x53\xAB"
+IdSeekPosition = "\x53\xAC"
+IdSeekPreRoll = "\x56\xBB"
+IdSegment = "\x18\x53\x80\x67"
+IdSimpleBlock = "\xA3"
+IdSimpleTag = "\x67\xC8"
+IdSliceDuration = "\xCF"
+IdSlices = "\x8E"
+IdStereoMode = "\x53\xB8"
+IdTag = "\x73\x73"
+IdTagBinary = "\x44\x85"
+IdTagDefault = "\x44\x84"
+IdTagLanguage = "\x44\x7A"
+IdTagName = "\x45\xA3"
+IdTagString = "\x44\x87"
+IdTagTrackUid = "\x63\xC5"
+IdTags = "\x12\x54\xC3\x67"
+IdTargetType = "\x63\xCA"
+IdTargetTypeValue = "\x68\xCA"
+IdTargets = "\x63\xC0"
+IdTimeSlice = "\xE8"
+IdTimecode = "\xE7"
+IdTimecodeScale = "\x2A\xD7\xB1"
+IdTitle = "\x7B\xA9"
+IdTrackEntry = "\xAE"
+IdTrackNumber = "\xD7"
+IdTrackType = "\x83"
+IdTrackUID = "\x73\xC5"
+IdTracks = "\x16\x54\xAE\x6B"
+IdTransferCharacteristics = "\x55\xBA"
+IdTrickMasterTrackSegmentUID = "\xC4"
+IdTrickMasterTrackUID = "\xC7"
+IdTrickTrackFlag = "\xC6"
+IdTrickTrackSegmentUID = "\xC1"
+IdTrickTrackUID = "\xC0"
+IdVideo = "\xE0"
+IdVoid = "\xEC"
+IdWhitePointChromaticityX = "\x55\xD7"
+IdWhitePointChromaticityY = "\x55\xD8"
+IdWritingApp = "\x57\x41"
+
+# Interesting sizes.
+SizeUnknown = "\xFF"
+
diff --git a/media/libstagefright/tests/mediacodec/Android.bp b/media/libstagefright/tests/mediacodec/Android.bp
index 0bd0639..9cdc6d4 100644
--- a/media/libstagefright/tests/mediacodec/Android.bp
+++ b/media/libstagefright/tests/mediacodec/Android.bp
@@ -14,6 +14,17 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_tests_license",
+    ],
+}
+
 cc_test {
     name: "mediacodecTest",
     gtest: true,
diff --git a/media/libstagefright/tests/mediacodec/MediaCodecTest.cpp b/media/libstagefright/tests/mediacodec/MediaCodecTest.cpp
index d00a50f..6facbd8 100644
--- a/media/libstagefright/tests/mediacodec/MediaCodecTest.cpp
+++ b/media/libstagefright/tests/mediacodec/MediaCodecTest.cpp
@@ -286,16 +286,18 @@
     //    initiateShutdown(); shutdown is being handled at the component thread.
     // 2) Error occurred, but the shutdown operation is still being done.
     // 3) MediaCodec looper thread handles the error.
-    // 4) Component thread completes shutdown and posts onStopCompleted()
+    // 4) Client releases the codec upon the error; previous shutdown is still
+    //    going on.
+    // 5) Component thread completes shutdown and posts onStopCompleted();
+    //    Shutdown from release also completes.
 
     static const AString kCodecName{"test.codec"};
     static const AString kCodecOwner{"nobody"};
     static const AString kMediaType{"video/x-test"};
 
-    std::promise<void> errorOccurred;
     sp<MockCodec> mockCodec;
     std::function<sp<CodecBase>(const AString &name, const char *owner)> getCodecBase =
-        [&mockCodec, &errorOccurred](const AString &, const char *) {
+        [&mockCodec](const AString &, const char *) {
             mockCodec = new MockCodec([](const std::shared_ptr<MockBufferChannel> &) {
                 // No mock setup, as we don't expect any buffer operations
                 // in this scenario.
@@ -314,13 +316,14 @@
                     mockCodec->callback()->onStartCompleted();
                 });
             ON_CALL(*mockCodec, initiateShutdown(true))
-                .WillByDefault([mockCodec, &errorOccurred](bool) {
+                .WillByDefault([mockCodec](bool) {
                     mockCodec->callback()->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
-                    // Mark that 1) and 2) are complete.
-                    errorOccurred.set_value();
                 });
             ON_CALL(*mockCodec, initiateShutdown(false))
                 .WillByDefault([mockCodec](bool) {
+                    // Previous stop finished now.
+                    mockCodec->callback()->onStopCompleted();
+                    // Release also finished.
                     mockCodec->callback()->onReleaseCompleted();
                 });
             return mockCodec;
@@ -332,19 +335,11 @@
     ASSERT_NE(nullptr, codec) << "Codec must not be null";
     ASSERT_NE(nullptr, mockCodec) << "MockCodec must not be null";
 
-    std::thread([mockCodec, &errorOccurred]{
-        // Simulate component thread that handles stop()
-        errorOccurred.get_future().wait();
-        // Error occurred but shutdown request still got processed.
-        mockCodec->callback()->onStopCompleted();
-    }).detach();
-
     codec->configure(new AMessage, nullptr, nullptr, 0);
     codec->start();
-    codec->stop();
-    // Sleep here to give time for the MediaCodec looper thread
-    // to process the messages.
-    std::this_thread::sleep_for(std::chrono::milliseconds(100));
+    // stop() will fail because of the error
+    EXPECT_NE(OK, codec->stop());
+    // upon receiving the error, client tries to release the codec.
     codec->release();
     looper->stop();
 }
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp b/media/libstagefright/tests/metadatautils/Android.bp
similarity index 62%
copy from media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
copy to media/libstagefright/tests/metadatautils/Android.bp
index 655491a..ecdf89b 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
+++ b/media/libstagefright/tests/metadatautils/Android.bp
@@ -14,20 +14,35 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_tests_license",
+    ],
+}
+
 cc_test {
-    name: "Mpeg4H263DecoderTest",
+    name: "MetaDataUtilsTest",
     gtest: true,
 
     srcs: [
-        "Mpeg4H263DecoderTest.cpp",
+        "MetaDataUtilsTest.cpp",
+    ],
+
+    static_libs: [
+        "libstagefright_metadatautils",
+        "libstagefright_esds",
     ],
 
     shared_libs: [
         "liblog",
-    ],
-
-    static_libs: [
-        "libstagefright_m4vh263dec",
+        "libutils",
+        "libmediandk",
+        "libstagefright",
         "libstagefright_foundation",
     ],
 
@@ -37,10 +52,10 @@
     ],
 
     sanitize: {
+        cfi: true,
         misc_undefined: [
             "unsigned-integer-overflow",
             "signed-integer-overflow",
         ],
-        cfi: true,
     },
 }
diff --git a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml b/media/libstagefright/tests/metadatautils/AndroidTest.xml
similarity index 67%
copy from media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
copy to media/libstagefright/tests/metadatautils/AndroidTest.xml
index 7ff9732..d6497f3 100644
--- a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
+++ b/media/libstagefright/tests/metadatautils/AndroidTest.xml
@@ -13,19 +13,18 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Test module config for Mp3 Decoder unit test">
-    <option name="test-suite-tag" value="Mp3DecoderTest" />
+<configuration description="Test module config for MetaDataUtils unit test">
+    <option name="test-suite-tag" value="MetaDataUtilsTest" />
     <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
-        <option name="cleanup" value="true" />
-        <option name="push" value="Mp3DecoderTest->/data/local/tmp/Mp3DecoderTest" />
+        <option name="cleanup" value="false" />
+        <option name="push" value="MetaDataUtilsTest->/data/local/tmp/MetaDataUtilsTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest.zip?unzip=true"
-            value="/data/local/tmp/Mp3DecoderTestRes/" />
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/tests/metadatautils/MetaDataUtilsTestRes-1.0.zip?unzip=true"
+            value="/data/local/tmp/MetaDataUtilsTestRes/" />
     </target_preparer>
-
     <test class="com.android.tradefed.testtype.GTest" >
         <option name="native-test-device-path" value="/data/local/tmp" />
-        <option name="module-name" value="Mp3DecoderTest" />
-        <option name="native-test-flag" value="-P /data/local/tmp/Mp3DecoderTestRes/" />
+        <option name="module-name" value="MetaDataUtilsTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/MetaDataUtilsTestRes/" />
     </test>
 </configuration>
diff --git a/media/libstagefright/tests/metadatautils/MetaDataUtilsTest.cpp b/media/libstagefright/tests/metadatautils/MetaDataUtilsTest.cpp
new file mode 100644
index 0000000..9fd5fdb
--- /dev/null
+++ b/media/libstagefright/tests/metadatautils/MetaDataUtilsTest.cpp
@@ -0,0 +1,490 @@
+/*
+ * Copyright (C) 2020 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 "MetaDataUtilsTest"
+#include <utils/Log.h>
+
+#include <fstream>
+#include <string>
+
+#include <ESDS.h>
+#include <media/NdkMediaFormat.h>
+#include <media/stagefright/MediaCodecConstants.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaDataBase.h>
+#include <media/stagefright/MetaDataUtils.h>
+#include <media/stagefright/foundation/ABitReader.h>
+
+#include "MetaDataUtilsTestEnvironment.h"
+
+constexpr uint8_t kAdtsCsdSize = 7;
+// from AAC specs: https://www.iso.org/standard/43345.html
+constexpr int32_t kSamplingFreq[] = {96000, 88200, 64000, 48000, 44100, 32000,
+                                     24000, 22050, 16000, 12000, 11025, 8000};
+constexpr uint8_t kMaxSamplingFreqIndex = sizeof(kSamplingFreq) / sizeof(kSamplingFreq[0]);
+
+static MetaDataUtilsTestEnvironment *gEnv = nullptr;
+
+using namespace android;
+
+class MetaDataValidate {
+  public:
+    MetaDataValidate() : mInputBuffer(nullptr) {}
+
+    ~MetaDataValidate() {
+        if (mInputBuffer) {
+            delete[] mInputBuffer;
+            mInputBuffer = nullptr;
+        }
+    }
+
+    void SetUpMetaDataValidate(string fileName) {
+        struct stat buf;
+        int8_t err = stat(fileName.c_str(), &buf);
+        ASSERT_EQ(err, 0) << "Failed to get file information for file: " << fileName;
+
+        mInputBufferSize = buf.st_size;
+        FILE *inputFilePtr = fopen(fileName.c_str(), "rb+");
+        ASSERT_NE(inputFilePtr, nullptr) << "Failed to open file: " << fileName;
+
+        mInputBuffer = new uint8_t[mInputBufferSize];
+        ASSERT_NE(mInputBuffer, nullptr)
+                << "Failed to allocate memory of size: " << mInputBufferSize;
+
+        int32_t numBytes =
+                fread((char *)mInputBuffer, sizeof(uint8_t), mInputBufferSize, inputFilePtr);
+        ASSERT_EQ(numBytes, mInputBufferSize) << numBytes << " of " << mInputBufferSize << " read";
+
+        fclose(inputFilePtr);
+    }
+
+    size_t mInputBufferSize;
+    const uint8_t *mInputBuffer;
+};
+
+class AvcCSDTest : public ::testing::TestWithParam<
+                           tuple<string /*inputFile*/, size_t /*avcWidth*/, size_t /*avcHeight*/>> {
+  public:
+    AvcCSDTest() : mInputBuffer(nullptr) {}
+
+    ~AvcCSDTest() {
+        if (mInputBuffer) {
+            delete[] mInputBuffer;
+            mInputBuffer = nullptr;
+        }
+    }
+    virtual void SetUp() override {
+        tuple<string, size_t, size_t> params = GetParam();
+        string inputFile = gEnv->getRes() + get<0>(params);
+        mFrameWidth = get<1>(params);
+        mFrameHeight = get<2>(params);
+
+        struct stat buf;
+        int8_t err = stat(inputFile.c_str(), &buf);
+        ASSERT_EQ(err, 0) << "Failed to get information for file: " << inputFile;
+
+        mInputBufferSize = buf.st_size;
+        FILE *inputFilePtr = fopen(inputFile.c_str(), "rb+");
+        ASSERT_NE(inputFilePtr, nullptr) << "Failed to open file: " << inputFile;
+
+        mInputBuffer = new uint8_t[mInputBufferSize];
+        ASSERT_NE(mInputBuffer, nullptr)
+                << "Failed to create a buffer of size: " << mInputBufferSize;
+
+        int32_t numBytes =
+                fread((char *)mInputBuffer, sizeof(uint8_t), mInputBufferSize, inputFilePtr);
+        ASSERT_EQ(numBytes, mInputBufferSize) << numBytes << " of " << mInputBufferSize << " read";
+
+        fclose(inputFilePtr);
+    }
+
+    size_t mFrameWidth;
+    size_t mFrameHeight;
+    size_t mInputBufferSize;
+    const uint8_t *mInputBuffer;
+};
+
+class AvcCSDValidateTest : public MetaDataValidate,
+                           public ::testing::TestWithParam<string /*inputFile*/> {
+  public:
+    virtual void SetUp() override {
+        string inputFile = gEnv->getRes() + GetParam();
+
+        ASSERT_NO_FATAL_FAILURE(SetUpMetaDataValidate(inputFile));
+    }
+};
+
+class AacCSDTest
+    : public ::testing::TestWithParam<tuple<uint32_t /*profile*/, uint32_t /*samplingFreqIndex*/,
+                                            uint32_t /*channelConfig*/>> {
+  public:
+    virtual void SetUp() override {
+        tuple<uint32_t, uint32_t, uint32_t> params = GetParam();
+        mAacProfile = get<0>(params);
+        mAacSamplingFreqIndex = get<1>(params);
+        mAacChannelConfig = get<2>(params);
+    }
+
+    uint32_t mAacProfile;
+    uint32_t mAacSamplingFreqIndex;
+    uint32_t mAacChannelConfig;
+};
+
+class AacADTSTest
+    : public ::testing::TestWithParam<
+              tuple<string /*adtsFile*/, uint32_t /*channelCount*/, uint32_t /*sampleRate*/>> {
+  public:
+    AacADTSTest() : mInputBuffer(nullptr) {}
+
+    virtual void SetUp() override {
+        tuple<string, uint32_t, uint32_t> params = GetParam();
+        string fileName = gEnv->getRes() + get<0>(params);
+        mAacChannelCount = get<1>(params);
+        mAacSampleRate = get<2>(params);
+
+        FILE *filePtr = fopen(fileName.c_str(), "r");
+        ASSERT_NE(filePtr, nullptr) << "Failed to open file: " << fileName;
+
+        mInputBuffer = new uint8_t[kAdtsCsdSize];
+        ASSERT_NE(mInputBuffer, nullptr) << "Failed to allocate a memory of size: " << kAdtsCsdSize;
+
+        int32_t numBytes = fread((void *)mInputBuffer, sizeof(uint8_t), kAdtsCsdSize, filePtr);
+        ASSERT_EQ(numBytes, kAdtsCsdSize)
+                << "Failed to read complete file, bytes read: " << numBytes;
+
+        fclose(filePtr);
+    }
+    int32_t mAacChannelCount;
+    int32_t mAacSampleRate;
+    const uint8_t *mInputBuffer;
+};
+
+class AacCSDValidateTest : public MetaDataValidate,
+                           public ::testing::TestWithParam<string /*inputFile*/> {
+  public:
+    virtual void SetUp() override {
+        string inputFile = gEnv->getRes() + GetParam();
+
+        ASSERT_NO_FATAL_FAILURE(SetUpMetaDataValidate(inputFile));
+    }
+};
+
+class VorbisTest : public ::testing::TestWithParam<pair<string /*fileName*/, string /*infoFile*/>> {
+  public:
+    virtual void SetUp() override {
+        pair<string, string> params = GetParam();
+        string inputMediaFile = gEnv->getRes() + params.first;
+        mInputFileStream.open(inputMediaFile, ifstream::in);
+        ASSERT_TRUE(mInputFileStream.is_open()) << "Failed to open data file: " << inputMediaFile;
+
+        string inputInfoFile = gEnv->getRes() + params.second;
+        mInfoFileStream.open(inputInfoFile, ifstream::in);
+        ASSERT_TRUE(mInputFileStream.is_open()) << "Failed to open data file: " << inputInfoFile;
+        ASSERT_FALSE(inputInfoFile.empty()) << "Empty info file: " << inputInfoFile;
+    }
+
+    ~VorbisTest() {
+        if (mInputFileStream.is_open()) mInputFileStream.close();
+        if (mInfoFileStream.is_open()) mInfoFileStream.close();
+    }
+
+    ifstream mInputFileStream;
+    ifstream mInfoFileStream;
+};
+
+TEST_P(AvcCSDTest, AvcCSDValidationTest) {
+    AMediaFormat *csdData = AMediaFormat_new();
+    ASSERT_NE(csdData, nullptr) << "Failed to create AMedia format";
+
+    bool status = MakeAVCCodecSpecificData(csdData, mInputBuffer, mInputBufferSize);
+    ASSERT_TRUE(status) << "Failed to make AVC CSD from AMediaFormat";
+
+    int32_t avcWidth = -1;
+    status = AMediaFormat_getInt32(csdData, AMEDIAFORMAT_KEY_WIDTH, &avcWidth);
+    ASSERT_TRUE(status) << "Failed to get avc width";
+    ASSERT_EQ(avcWidth, mFrameWidth);
+
+    int32_t avcHeight = -1;
+    status = AMediaFormat_getInt32(csdData, AMEDIAFORMAT_KEY_HEIGHT, &avcHeight);
+    ASSERT_TRUE(status) << "Failed to get avc height";
+    ASSERT_EQ(avcHeight, mFrameHeight);
+
+    const char *mimeType = "";
+    status = AMediaFormat_getString(csdData, AMEDIAFORMAT_KEY_MIME, &mimeType);
+    ASSERT_TRUE(status) << "Failed to get the mime type";
+    ASSERT_STREQ(mimeType, MEDIA_MIMETYPE_VIDEO_AVC);
+
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create MetaData Base";
+
+    status = MakeAVCCodecSpecificData(*metaData, mInputBuffer, mInputBufferSize);
+    ASSERT_TRUE(status) << "Failed to make AVC CSD from MetaDataBase";
+
+    avcWidth = -1;
+    status = metaData->findInt32(kKeyWidth, &avcWidth);
+    ASSERT_TRUE(status) << "Failed to find the width";
+    ASSERT_EQ(avcWidth, mFrameWidth);
+
+    avcHeight = -1;
+    status = metaData->findInt32(kKeyHeight, &avcHeight);
+    ASSERT_TRUE(status) << "Failed to find the height";
+    ASSERT_EQ(avcHeight, mFrameHeight);
+
+    void *csdAMediaFormatBuffer = nullptr;
+    size_t csdAMediaFormatSize;
+    status = AMediaFormat_getBuffer(csdData, AMEDIAFORMAT_KEY_CSD_AVC, &csdAMediaFormatBuffer,
+                                    &csdAMediaFormatSize);
+    ASSERT_TRUE(status) << "Failed to get the CSD from AMediaFormat";
+    ASSERT_NE(csdAMediaFormatBuffer, nullptr) << "Invalid CSD from AMediaFormat";
+
+    const void *csdMetaDataBaseBuffer = nullptr;
+    size_t csdMetaDataBaseSize = 0;
+    uint32_t mediaType;
+    status = metaData->findData(kKeyAVCC, &mediaType, &csdMetaDataBaseBuffer, &csdMetaDataBaseSize);
+    ASSERT_TRUE(status) << "Failed to get the CSD from MetaDataBase";
+    ASSERT_NE(csdMetaDataBaseBuffer, nullptr) << "Invalid CSD from MetaDataBase";
+    ASSERT_GT(csdMetaDataBaseSize, 0) << "CSD size must be greater than 0";
+    ASSERT_EQ(csdMetaDataBaseSize, csdAMediaFormatSize)
+            << "CSD size of MetaData type and AMediaFormat type must be same";
+
+    int32_t result = memcmp(csdAMediaFormatBuffer, csdMetaDataBaseBuffer, csdAMediaFormatSize);
+    ASSERT_EQ(result, 0) << "CSD from AMediaFormat and MetaDataBase do not match";
+
+    delete metaData;
+    AMediaFormat_delete(csdData);
+}
+
+TEST_P(AvcCSDValidateTest, AvcValidateTest) {
+    AMediaFormat *csdData = AMediaFormat_new();
+    ASSERT_NE(csdData, nullptr) << "Failed to create AMedia format";
+
+    bool status = MakeAVCCodecSpecificData(csdData, mInputBuffer, mInputBufferSize);
+    ASSERT_FALSE(status) << "MakeAVCCodecSpecificData with AMediaFormat succeeds with invalid data";
+
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create MetaData Base";
+
+    status = MakeAVCCodecSpecificData(*metaData, mInputBuffer, mInputBufferSize);
+    ASSERT_FALSE(status) << "MakeAVCCodecSpecificData with MetaDataBase succeeds with invalid data";
+}
+
+TEST_P(AacCSDTest, AacCSDValidationTest) {
+    AMediaFormat *csdData = AMediaFormat_new();
+    ASSERT_NE(csdData, nullptr) << "Failed to create AMedia format";
+
+    ASSERT_GE(mAacSamplingFreqIndex, 0);
+    ASSERT_LT(mAacSamplingFreqIndex, kMaxSamplingFreqIndex);
+    bool status = MakeAACCodecSpecificData(csdData, mAacProfile, mAacSamplingFreqIndex,
+                                           mAacChannelConfig);
+    ASSERT_TRUE(status) << "Failed to make AAC CSD from AMediaFormat";
+
+    int32_t sampleRate = -1;
+    status = AMediaFormat_getInt32(csdData, AMEDIAFORMAT_KEY_SAMPLE_RATE, &sampleRate);
+    ASSERT_TRUE(status) << "Failed to get sample rate";
+    ASSERT_EQ(kSamplingFreq[mAacSamplingFreqIndex], sampleRate);
+
+    int32_t channelCount = -1;
+    status = AMediaFormat_getInt32(csdData, AMEDIAFORMAT_KEY_CHANNEL_COUNT, &channelCount);
+    ASSERT_TRUE(status) << "Failed to get channel count";
+    ASSERT_EQ(channelCount, mAacChannelConfig);
+
+    const char *mimeType = "";
+    status = AMediaFormat_getString(csdData, AMEDIAFORMAT_KEY_MIME, &mimeType);
+    ASSERT_TRUE(status) << "Failed to get the mime type";
+    ASSERT_STREQ(mimeType, MEDIA_MIMETYPE_AUDIO_AAC);
+
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create MetaData Base";
+
+    status = MakeAACCodecSpecificData(*metaData, mAacProfile, mAacSamplingFreqIndex,
+                                      mAacChannelConfig);
+    ASSERT_TRUE(status) << "Failed to make AAC CSD from MetaDataBase";
+
+    sampleRate = -1;
+    status = metaData->findInt32(kKeySampleRate, &sampleRate);
+    ASSERT_TRUE(status) << "Failed to get sampling rate";
+    ASSERT_EQ(kSamplingFreq[mAacSamplingFreqIndex], sampleRate);
+
+    channelCount = -1;
+    status = metaData->findInt32(kKeyChannelCount, &channelCount);
+    ASSERT_TRUE(status) << "Failed to get channel count";
+    ASSERT_EQ(channelCount, mAacChannelConfig);
+
+    mimeType = "";
+    status = metaData->findCString(kKeyMIMEType, &mimeType);
+    ASSERT_TRUE(status) << "Failed to get mime type";
+    ASSERT_STREQ(mimeType, MEDIA_MIMETYPE_AUDIO_AAC);
+
+    void *csdAMediaFormatBuffer = nullptr;
+    size_t csdAMediaFormatSize = 0;
+    status = AMediaFormat_getBuffer(csdData, AMEDIAFORMAT_KEY_CSD_0, &csdAMediaFormatBuffer,
+                                    &csdAMediaFormatSize);
+    ASSERT_TRUE(status) << "Failed to get the AMediaFormat CSD";
+    ASSERT_GT(csdAMediaFormatSize, 0) << "CSD size must be greater than 0";
+    ASSERT_NE(csdAMediaFormatBuffer, nullptr) << "Invalid CSD found";
+
+    const void *csdMetaDataBaseBuffer;
+    size_t csdMetaDataBaseSize = 0;
+    uint32_t mediaType;
+    status = metaData->findData(kKeyESDS, &mediaType, &csdMetaDataBaseBuffer, &csdMetaDataBaseSize);
+    ASSERT_TRUE(status) << "Failed to get the ESDS data from MetaDataBase";
+    ASSERT_GT(csdMetaDataBaseSize, 0) << "CSD size must be greater than 0";
+
+    ESDS esds(csdMetaDataBaseBuffer, csdMetaDataBaseSize);
+    status_t result = esds.getCodecSpecificInfo(&csdMetaDataBaseBuffer, &csdMetaDataBaseSize);
+    ASSERT_EQ(result, (status_t)OK) << "Failed to get CSD from ESDS data";
+    ASSERT_NE(csdMetaDataBaseBuffer, nullptr) << "Invalid CSD found";
+    ASSERT_EQ(csdAMediaFormatSize, csdMetaDataBaseSize)
+            << "CSD size do not match between AMediaFormat type and MetaDataBase type";
+
+    int32_t memcmpResult =
+            memcmp(csdAMediaFormatBuffer, csdMetaDataBaseBuffer, csdAMediaFormatSize);
+    ASSERT_EQ(memcmpResult, 0) << "AMediaFormat and MetaDataBase CSDs do not match";
+
+    AMediaFormat_delete(csdData);
+    delete metaData;
+}
+
+TEST_P(AacADTSTest, AacADTSValidationTest) {
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create meta data";
+
+    bool status = MakeAACCodecSpecificData(*metaData, mInputBuffer, kAdtsCsdSize);
+    ASSERT_TRUE(status) << "Failed to make AAC CSD from MetaDataBase";
+
+    int32_t sampleRate = -1;
+    status = metaData->findInt32(kKeySampleRate, &sampleRate);
+    ASSERT_TRUE(status) << "Failed to get sampling rate";
+    ASSERT_EQ(sampleRate, mAacSampleRate);
+
+    int32_t channelCount = -1;
+    status = metaData->findInt32(kKeyChannelCount, &channelCount);
+    ASSERT_TRUE(status) << "Failed to get channel count";
+    ASSERT_EQ(channelCount, mAacChannelCount);
+
+    const char *mimeType = "";
+    status = metaData->findCString(kKeyMIMEType, &mimeType);
+    ASSERT_TRUE(status) << "Failed to get mime type";
+    ASSERT_STREQ(mimeType, MEDIA_MIMETYPE_AUDIO_AAC);
+
+    delete metaData;
+}
+
+TEST_P(AacCSDValidateTest, AacInvalidInputTest) {
+    MetaDataBase *metaData = new MetaDataBase();
+    ASSERT_NE(metaData, nullptr) << "Failed to create meta data";
+
+    bool status = MakeAACCodecSpecificData(*metaData, mInputBuffer, kAdtsCsdSize);
+    ASSERT_FALSE(status) << "MakeAACCodecSpecificData succeeds with invalid data";
+}
+
+TEST_P(VorbisTest, VorbisCommentTest) {
+    string line;
+    string tag;
+    string key;
+    string value;
+    size_t commentLength;
+    bool status;
+
+    while (getline(mInfoFileStream, line)) {
+        istringstream stringLine(line);
+        stringLine >> tag >> key >> value >> commentLength;
+        ASSERT_GT(commentLength, 0) << "Vorbis comment size must be greater than 0";
+
+        string comment;
+        string dataLine;
+
+        getline(mInputFileStream, dataLine);
+        istringstream dataStringLine(dataLine);
+        dataStringLine >> comment;
+
+        char *buffer = strndup(comment.c_str(), commentLength);
+        ASSERT_NE(buffer, nullptr) << "Failed to allocate buffer of size: " << commentLength;
+
+        AMediaFormat *fileMeta = AMediaFormat_new();
+        ASSERT_NE(fileMeta, nullptr) << "Failed to create AMedia format";
+
+        parseVorbisComment(fileMeta, buffer, commentLength);
+        free(buffer);
+
+        if (!strncasecmp(tag.c_str(), "ANDROID_HAPTIC", sizeof(tag))) {
+            int32_t numChannelExpected = stoi(value);
+            int32_t numChannelFound = -1;
+            status = AMediaFormat_getInt32(fileMeta, key.c_str(), &numChannelFound);
+            ASSERT_TRUE(status) << "Failed to get the channel count";
+            ASSERT_EQ(numChannelExpected, numChannelFound);
+        } else if (!strncasecmp(tag.c_str(), "ANDROID_LOOP", sizeof(tag))) {
+            int32_t loopExpected = !value.compare("true");
+            int32_t loopFound = -1;
+
+            status = AMediaFormat_getInt32(fileMeta, "loop", &loopFound);
+            ASSERT_TRUE(status) << "Failed to get the loop count";
+            ASSERT_EQ(loopExpected, loopFound);
+        } else {
+            const char *tagValue = "";
+            status = AMediaFormat_getString(fileMeta, key.c_str(), &tagValue);
+            ASSERT_TRUE(status) << "Failed to get the tag value";
+            ASSERT_STREQ(value.c_str(), tagValue);
+        }
+        AMediaFormat_delete(fileMeta);
+    }
+}
+
+INSTANTIATE_TEST_SUITE_P(MetaDataUtilsTestAll, AvcCSDTest,
+                         ::testing::Values(make_tuple("sps_pps_userdata.h264", 8, 8),
+                                           make_tuple("sps_userdata_pps.h264", 8, 8),
+                                           make_tuple("sps_pps_sps_pps.h264", 8, 8)));
+
+// TODO(b/158067691): Add invalid test vectors with incomplete PPS or no PPS
+INSTANTIATE_TEST_SUITE_P(MetaDataUtilsTestAll, AvcCSDValidateTest,
+                         ::testing::Values("sps_pps_only_startcode.h264",
+                                           "sps_incomplete_pps.h264",
+                                           // TODO(b/158067691) "sps_pps_incomplete.h264",
+                                           "randomdata.h264",
+                                           // TODO(b/158067691) "sps.h264",
+                                           "pps.h264"));
+
+INSTANTIATE_TEST_SUITE_P(MetaDataUtilsTestAll, AacCSDTest,
+                         ::testing::Values(make_tuple(AACObjectMain, 1, 1)));
+
+INSTANTIATE_TEST_SUITE_P(MetaDataUtilsTestAll, AacADTSTest,
+                         ::testing::Values(make_tuple("loudsoftaacadts", 1, 44100)));
+
+INSTANTIATE_TEST_SUITE_P(MetaDataUtilsTestAll, AacCSDValidateTest,
+                         ::testing::Values("loudsoftaacadts_invalidheader",
+                                           "loudsoftaacadts_invalidprofile",
+                                           "loudsoftaacadts_invalidchannelconfig"));
+
+// TODO(b/157974508) Add test vector for vorbis thumbnail tag
+// Info file contains TAG, Key, Value and size of the vorbis comment
+INSTANTIATE_TEST_SUITE_P(
+        MetaDataUtilsTestAll, VorbisTest,
+        ::testing::Values(make_pair("vorbiscomment_sintel.dat", "vorbiscomment_sintel.info"),
+                          make_pair("vorbiscomment_album.dat", "vorbiscomment_album.info"),
+                          make_pair("vorbiscomment_loop.dat", "vorbiscomment_loop.info")));
+
+int main(int argc, char **argv) {
+    gEnv = new MetaDataUtilsTestEnvironment();
+    ::testing::AddGlobalTestEnvironment(gEnv);
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = gEnv->initFromOptions(argc, argv);
+    if (status == 0) {
+        status = RUN_ALL_TESTS();
+        ALOGV("Test result = %d\n", status);
+    }
+    return status;
+}
diff --git a/media/libstagefright/tests/metadatautils/MetaDataUtilsTestEnvironment.h b/media/libstagefright/tests/metadatautils/MetaDataUtilsTestEnvironment.h
new file mode 100644
index 0000000..4d642bc
--- /dev/null
+++ b/media/libstagefright/tests/metadatautils/MetaDataUtilsTestEnvironment.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2020 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 __METADATA_UTILS_TEST_ENVIRONMENT_H__
+#define __METADATA_UTILS_TEST_ENVIRONMENT_H__
+
+#include <gtest/gtest.h>
+
+#include <getopt.h>
+
+using namespace std;
+
+class MetaDataUtilsTestEnvironment : public::testing::Environment {
+  public:
+    MetaDataUtilsTestEnvironment() : res("/data/local/tmp/") {}
+
+    // Parses the command line arguments
+    int initFromOptions(int argc, char **argv);
+
+    void setRes(const char *_res) { res = _res; }
+
+    const string getRes() const { return res; }
+
+  private:
+    string res;
+};
+
+int MetaDataUtilsTestEnvironment::initFromOptions(int argc, char **argv) {
+    static struct option options[] = {{"path", required_argument, 0, 'P'}, {0, 0, 0, 0}};
+
+    while (true) {
+        int index = 0;
+        int c = getopt_long(argc, argv, "P:", options, &index);
+        if (c == -1) {
+            break;
+        }
+
+        switch (c) {
+            case 'P': {
+                setRes(optarg);
+                break;
+            }
+            default:
+                break;
+        }
+    }
+
+    if (optind < argc) {
+        fprintf(stderr,
+                "unrecognized option: %s\n\n"
+                "usage: %s <gtest options> <test options>\n\n"
+                "test options are:\n\n"
+                "-P, --path: Resource files directory location\n",
+                argv[optind ?: 1], argv[0]);
+        return 2;
+    }
+    return 0;
+}
+
+#endif  // __METADATA_UTILS_TEST_ENVIRONMENT_H__
diff --git a/media/libstagefright/tests/metadatautils/README.md b/media/libstagefright/tests/metadatautils/README.md
new file mode 100644
index 0000000..0862a07
--- /dev/null
+++ b/media/libstagefright/tests/metadatautils/README.md
@@ -0,0 +1,39 @@
+## Media Testing ##
+---
+#### MetaDataUtils Test
+The MetaDataUtils Unit Test Suite validates the libstagefright_metadatautils library available in libstagefright.
+
+Run the following steps to build the test suite:
+```
+m MetaDataUtilsTest
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+```
+adb push ${OUT}/data/nativetest64/MetaDataUtilsTest/MetaDataUtilsTest /data/local/tmp/
+```
+
+To test 32-bit binary push binaries from nativetest.
+```
+adb push ${OUT}/data/nativetest/MetaDataUtilsTest/MetaDataUtilsTest /data/local/tmp/
+```
+
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/tests/metadatautils/MetaDataUtilsTestRes-1.0.zip). Download, unzip and push these files into device for testing.
+
+```
+adb push MetaDataUtilsTestRes-1.0 /data/local/tmp/
+```
+
+usage: MetaDataUtilsTest -P \<path_to_folder\>
+```
+adb shell /data/local/tmp/MetaDataUtilsTest -P /data/local/tmp/MetaDataUtilsTestRes-1.0/
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest MetaDataUtilsTest -- --enable-module-dynamic-download=true
+```
diff --git a/media/libstagefright/tests/writer/Android.bp b/media/libstagefright/tests/writer/Android.bp
index 7e169cb..38d5ecc 100644
--- a/media/libstagefright/tests/writer/Android.bp
+++ b/media/libstagefright/tests/writer/Android.bp
@@ -14,6 +14,17 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_tests_license",
+    ],
+}
+
 cc_test {
     name: "writerTest",
     gtest: true,
@@ -28,13 +39,15 @@
         "libcutils",
         "liblog",
         "libutils",
+        "libmedia",
+        "libmediandk",
+        "libstagefright",
     ],
 
     static_libs: [
         "libstagefright_webm",
-        "libdatasource",
-        "libstagefright",
         "libstagefright_foundation",
+        "libdatasource",
         "libstagefright_esds",
         "libogg",
     ],
diff --git a/media/libstagefright/tests/writer/AndroidTest.xml b/media/libstagefright/tests/writer/AndroidTest.xml
index d831555..cc890fe 100644
--- a/media/libstagefright/tests/writer/AndroidTest.xml
+++ b/media/libstagefright/tests/writer/AndroidTest.xml
@@ -19,12 +19,13 @@
         <option name="cleanup" value="true" />
         <option name="push" value="writerTest->/data/local/tmp/writerTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/tests/writer/Writer.zip?unzip=true"
-            value="/data/local/tmp/writerTestRes/" />
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/tests/writer/WriterTestRes-1.1.zip?unzip=true"
+            value="/data/local/tmp/WriterTestRes/" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.GTest" >
         <option name="native-test-device-path" value="/data/local/tmp" />
         <option name="module-name" value="writerTest" />
-        <option name="native-test-flag" value="-P /data/local/tmp/writerTestRes/" />
+        <option name="native-test-flag" value="-P /data/local/tmp/WriterTestRes/" />
+        <option name="native-test-flag" value="-C true" />
     </test>
 </configuration>
diff --git a/media/libstagefright/tests/writer/README.md b/media/libstagefright/tests/writer/README.md
index ae07917..0e54ca7 100644
--- a/media/libstagefright/tests/writer/README.md
+++ b/media/libstagefright/tests/writer/README.md
@@ -19,13 +19,18 @@
 
 adb push ${OUT}/data/nativetest/writerTest/writerTest /data/local/tmp/
 
-The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/tests/writer/writerTestRes.zip).
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/tests/writer/WriterTestRes-1.1.zip).
 Download and extract the folder. Push all the files in this folder to /data/local/tmp/ on the device.
 ```
-adb push writerTestRes /data/local/tmp/
+adb push WriterTestRes-1.1/. /data/local/tmp/WriterTestRes/
 ```
 
-usage: writerTest -P \<path_to_res_folder\>
+usage: writerTest -P \<path_to_res_folder\> -C <remove_output_file>
 ```
-adb shell /data/local/tmp/writerTest -P /data/local/tmp/
+adb shell /data/local/tmp/writerTest -P /data/local/tmp/WriterTestRes/ -C true
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest writerTest -- --enable-module-dynamic-download=true
 ```
diff --git a/media/libstagefright/tests/writer/WriterListener.h b/media/libstagefright/tests/writer/WriterListener.h
new file mode 100644
index 0000000..81f0a7c
--- /dev/null
+++ b/media/libstagefright/tests/writer/WriterListener.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2020 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 WRITER_LISTENER_H_
+#define WRITER_LISTENER_H_
+
+#include <mutex>
+
+#include <media/IMediaRecorderClient.h>
+#include <media/mediarecorder.h>
+
+using namespace android;
+using namespace std;
+
+class WriterListener : public BnMediaRecorderClient {
+  public:
+    WriterListener() : mSignaledSize(false), mSignaledDuration(false) {}
+
+    virtual void notify(int32_t msg, int32_t ext1, int32_t ext2) {
+        ALOGV("msg : %d, ext1 : %d, ext2 : %d", msg, ext1, ext2);
+        if (ext1 == MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
+            mSignaledSize = true;
+        } else if (ext1 == MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
+            mSignaledDuration = true;
+        }
+    }
+
+    volatile bool mSignaledSize;
+    volatile bool mSignaledDuration;
+};
+
+#endif  // WRITER_LISTENER_H_
diff --git a/media/libstagefright/tests/writer/WriterTest.cpp b/media/libstagefright/tests/writer/WriterTest.cpp
index ff063e3..d170e7c 100644
--- a/media/libstagefright/tests/writer/WriterTest.cpp
+++ b/media/libstagefright/tests/writer/WriterTest.cpp
@@ -18,9 +18,13 @@
 #define LOG_TAG "WriterTest"
 #include <utils/Log.h>
 
+#include <binder/ProcessState.h>
+
+#include <inttypes.h>
 #include <fstream>
 #include <iostream>
 
+#include <media/NdkMediaExtractor.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/Utils.h>
@@ -39,18 +43,40 @@
 
 #define OUTPUT_FILE_NAME "/data/local/tmp/writer.out"
 
+// Stts values within 0.1ms(100us) difference are fudged to save too
+// many stts entries in MPEG4Writer.
+constexpr int32_t kMpeg4MuxToleranceTimeUs = 100;
+// Tolerance value for other writers
+constexpr int32_t kMuxToleranceTimeUs = 1;
+
 static WriterTestEnvironment *gEnv = nullptr;
 
-struct configFormat {
-    char mime[128];
-    int32_t width;
-    int32_t height;
-    int32_t sampleRate;
-    int32_t channelCount;
+enum inputId {
+    // audio streams
+    AAC_1,
+    AAC_ADTS_1,
+    AMR_NB_1,
+    AMR_WB_1,
+    FLAC_1,
+    OPUS_1,
+    VORBIS_1,
+    // video streams
+    AV1_1,
+    AVC_1,
+    H263_1,
+    HEVC_1,
+    MPEG4_1,
+    VP8_1,
+    VP9_1,
+    // heif stream
+    HEIC_1,
+    UNUSED_ID,
+    UNKNOWN_ID,
 };
 
 // LookUpTable of clips and metadata for component testing
 static const struct InputData {
+    inputId inpId;
     const char *mime;
     string inputFile;
     string info;
@@ -58,65 +84,73 @@
     int32_t secondParam;
     bool isAudio;
 } kInputData[] = {
-        {MEDIA_MIMETYPE_AUDIO_OPUS, "bbb_opus_stereo_128kbps_48000hz.opus",
-         "bbb_opus_stereo_128kbps_48000hz.info", 48000, 2, true},
-        {MEDIA_MIMETYPE_AUDIO_AAC, "bbb_aac_stereo_128kbps_48000hz.aac",
-         "bbb_aac_stereo_128kbps_48000hz.info", 48000, 2, true},
-        {MEDIA_MIMETYPE_AUDIO_AAC_ADTS, "Mps_2_c2_fr1_Sc1_Dc2_0x03_raw.adts",
+        {AAC_1, MEDIA_MIMETYPE_AUDIO_AAC, "audio_aac_stereo_8kbps_11025hz.aac",
+         "audio_aac_stereo_8kbps_11025hz.info", 11025, 2, true},
+        {AAC_ADTS_1, MEDIA_MIMETYPE_AUDIO_AAC_ADTS, "Mps_2_c2_fr1_Sc1_Dc2_0x03_raw.adts",
          "Mps_2_c2_fr1_Sc1_Dc2_0x03_raw.info", 48000, 2, true},
-        {MEDIA_MIMETYPE_AUDIO_AMR_NB, "sine_amrnb_1ch_12kbps_8000hz.amrnb",
+        {AMR_NB_1, MEDIA_MIMETYPE_AUDIO_AMR_NB, "sine_amrnb_1ch_12kbps_8000hz.amrnb",
          "sine_amrnb_1ch_12kbps_8000hz.info", 8000, 1, true},
-        {MEDIA_MIMETYPE_AUDIO_AMR_WB, "bbb_amrwb_1ch_14kbps_16000hz.amrwb",
+        {AMR_WB_1, MEDIA_MIMETYPE_AUDIO_AMR_WB, "bbb_amrwb_1ch_14kbps_16000hz.amrwb",
          "bbb_amrwb_1ch_14kbps_16000hz.info", 16000, 1, true},
-        {MEDIA_MIMETYPE_AUDIO_VORBIS, "bbb_vorbis_stereo_128kbps_48000hz.vorbis",
-         "bbb_vorbis_stereo_128kbps_48000hz.info", 48000, 2, true},
-        {MEDIA_MIMETYPE_AUDIO_FLAC, "bbb_flac_stereo_680kbps_48000hz.flac",
+        {FLAC_1, MEDIA_MIMETYPE_AUDIO_FLAC, "bbb_flac_stereo_680kbps_48000hz.flac",
          "bbb_flac_stereo_680kbps_48000hz.info", 48000, 2, true},
-        {MEDIA_MIMETYPE_VIDEO_VP9, "bbb_vp9_176x144_285kbps_60fps.vp9",
-         "bbb_vp9_176x144_285kbps_60fps.info", 176, 144, false},
-        {MEDIA_MIMETYPE_VIDEO_VP8, "bbb_vp8_176x144_240kbps_60fps.vp8",
-         "bbb_vp8_176x144_240kbps_60fps.info", 176, 144, false},
-        {MEDIA_MIMETYPE_VIDEO_AVC, "bbb_avc_176x144_300kbps_60fps.h264",
-         "bbb_avc_176x144_300kbps_60fps.info", 176, 144, false},
-        {MEDIA_MIMETYPE_VIDEO_HEVC, "bbb_hevc_176x144_176kbps_60fps.hevc",
-         "bbb_hevc_176x144_176kbps_60fps.info", 176, 144, false},
-        {MEDIA_MIMETYPE_VIDEO_AV1, "bbb_av1_176_144.av1", "bbb_av1_176_144.info", 176, 144, false},
-        {MEDIA_MIMETYPE_VIDEO_H263, "bbb_h263_352x288_300kbps_12fps.h263",
+        {OPUS_1, MEDIA_MIMETYPE_AUDIO_OPUS, "bbb_opus_stereo_128kbps_48000hz.opus",
+         "bbb_opus_stereo_128kbps_48000hz.info", 48000, 2, true},
+        {VORBIS_1, MEDIA_MIMETYPE_AUDIO_VORBIS, "bbb_vorbis_1ch_64kbps_16kHz.vorbis",
+         "bbb_vorbis_1ch_64kbps_16kHz.info", 16000, 1, true},
+
+        {AV1_1, MEDIA_MIMETYPE_VIDEO_AV1, "bbb_av1_176_144.av1", "bbb_av1_176_144.info", 176, 144,
+         false},
+        {AVC_1, MEDIA_MIMETYPE_VIDEO_AVC, "bbb_avc_352x288_768kbps_30fps.avc",
+         "bbb_avc_352x288_768kbps_30fps.info", 352, 288, false},
+        {H263_1, MEDIA_MIMETYPE_VIDEO_H263, "bbb_h263_352x288_300kbps_12fps.h263",
          "bbb_h263_352x288_300kbps_12fps.info", 352, 288, false},
-        {MEDIA_MIMETYPE_VIDEO_MPEG4, "bbb_mpeg4_352x288_512kbps_30fps.m4v",
+        {HEVC_1, MEDIA_MIMETYPE_VIDEO_HEVC, "bbb_hevc_340x280_768kbps_30fps.hevc",
+         "bbb_hevc_340x280_768kbps_30fps.info", 340, 280, false},
+        {MPEG4_1, MEDIA_MIMETYPE_VIDEO_MPEG4, "bbb_mpeg4_352x288_512kbps_30fps.m4v",
          "bbb_mpeg4_352x288_512kbps_30fps.info", 352, 288, false},
+        {VP8_1, MEDIA_MIMETYPE_VIDEO_VP8, "bbb_vp8_176x144_240kbps_60fps.vp8",
+         "bbb_vp8_176x144_240kbps_60fps.info", 176, 144, false},
+        {VP9_1, MEDIA_MIMETYPE_VIDEO_VP9, "bbb_vp9_176x144_285kbps_60fps.vp9",
+         "bbb_vp9_176x144_285kbps_60fps.info", 176, 144, false},
+
+        {HEIC_1, MEDIA_MIMETYPE_IMAGE_ANDROID_HEIC, "bbb_hevc_176x144_176kbps_60fps.hevc",
+         "bbb_heic_176x144_176kbps_60fps.info", 176, 144, false},
 };
 
-class WriterTest : public ::testing::TestWithParam<pair<string, int32_t>> {
+class WriterTest {
   public:
-    WriterTest() : mWriter(nullptr), mFileMeta(nullptr), mCurrentTrack(nullptr) {}
+    WriterTest() : mWriter(nullptr), mFileMeta(nullptr) {}
 
     ~WriterTest() {
-        if (mWriter) {
-            mWriter.clear();
-            mWriter = nullptr;
-        }
         if (mFileMeta) {
             mFileMeta.clear();
             mFileMeta = nullptr;
         }
-        if (mCurrentTrack) {
-            mCurrentTrack.clear();
-            mCurrentTrack = nullptr;
+        if (mWriter) {
+            mWriter.clear();
+            mWriter = nullptr;
+        }
+        if (gEnv->cleanUp()) remove(OUTPUT_FILE_NAME);
+
+        for (int32_t idx = 0; idx < kMaxTrackCount; idx++) {
+            mBufferInfo[idx].clear();
+            if (mCurrentTrack[idx]) {
+                mCurrentTrack[idx]->stop();
+                mCurrentTrack[idx].clear();
+                mCurrentTrack[idx] = nullptr;
+            }
+            if (mInputStream[idx].is_open()) mInputStream[idx].close();
         }
     }
 
-    virtual void SetUp() override {
-        mNumCsds = 0;
-        mInputFrameId = 0;
+    void setupWriterType(string writerFormat) {
         mWriterName = unknown_comp;
         mDisableTest = false;
-
         static const std::map<std::string, standardWriters> mapWriter = {
                 {"ogg", OGG},     {"aac", AAC},      {"aac_adts", AAC_ADTS}, {"webm", WEBM},
                 {"mpeg4", MPEG4}, {"amrnb", AMR_NB}, {"amrwb", AMR_WB},      {"mpeg2Ts", MPEG2TS}};
         // Find the component type
-        string writerFormat = GetParam().first;
         if (mapWriter.find(writerFormat) != mapWriter.end()) {
             mWriterName = mapWriter.at(writerFormat);
         }
@@ -126,16 +160,19 @@
         }
     }
 
-    virtual void TearDown() override {
-        mBufferInfo.clear();
-        if (mInputStream.is_open()) mInputStream.close();
-    }
-
-    void getInputBufferInfo(string inputFileName, string inputInfo);
+    void getInputBufferInfo(string inputFileName, string inputInfo, int32_t idx = 0);
 
     int32_t createWriter(int32_t fd);
 
-    int32_t addWriterSource(bool isAudio, configFormat params);
+    int32_t addWriterSource(bool isAudio, configFormat params, int32_t idx = 0);
+
+    void setupExtractor(AMediaExtractor *extractor, string inputFileName, int32_t &trackCount);
+
+    void extract(AMediaExtractor *extractor, configFormat &params, vector<BufferInfo> &bufferInfo,
+                 uint8_t *buffer, size_t bufSize, size_t *bytesExtracted, int32_t idx);
+
+    void compareParams(configFormat srcParam, configFormat dstParam, vector<BufferInfo> dstBufInfo,
+                       int32_t index);
 
     enum standardWriters {
         OGG,
@@ -152,32 +189,42 @@
     standardWriters mWriterName;
     sp<MediaWriter> mWriter;
     sp<MetaData> mFileMeta;
-    sp<MediaAdapter> mCurrentTrack;
+    sp<MediaAdapter> mCurrentTrack[kMaxTrackCount]{};
 
     bool mDisableTest;
-    int32_t mNumCsds;
-    int32_t mInputFrameId;
-    ifstream mInputStream;
-    vector<BufferInfo> mBufferInfo;
+    int32_t mNumCsds[kMaxTrackCount]{};
+    int32_t mInputFrameId[kMaxTrackCount]{};
+    ifstream mInputStream[kMaxTrackCount]{};
+    vector<BufferInfo> mBufferInfo[kMaxTrackCount];
 };
 
-void WriterTest::getInputBufferInfo(string inputFileName, string inputInfo) {
+class WriteFunctionalityTest
+    : public WriterTest,
+      public ::testing::TestWithParam<tuple<string /* writerFormat*/, inputId /* inputId0*/,
+                                            inputId /* inputId1*/, float /* BufferInterval*/>> {
+  public:
+    virtual void SetUp() override { setupWriterType(get<0>(GetParam())); }
+};
+
+void WriterTest::getInputBufferInfo(string inputFileName, string inputInfo, int32_t idx) {
     std::ifstream eleInfo;
     eleInfo.open(inputInfo.c_str());
     ASSERT_EQ(eleInfo.is_open(), true);
     int32_t bytesCount = 0;
     uint32_t flags = 0;
     int64_t timestamp = 0;
+    int32_t numCsds = 0;
     while (1) {
         if (!(eleInfo >> bytesCount)) break;
         eleInfo >> flags;
         eleInfo >> timestamp;
-        mBufferInfo.push_back({bytesCount, flags, timestamp});
-        if (flags == CODEC_CONFIG_FLAG) mNumCsds++;
+        mBufferInfo[idx].push_back({bytesCount, flags, timestamp});
+        if (flags == CODEC_CONFIG_FLAG) numCsds++;
     }
     eleInfo.close();
-    mInputStream.open(inputFileName.c_str(), std::ifstream::binary);
-    ASSERT_EQ(mInputStream.is_open(), true);
+    mNumCsds[idx] = numCsds;
+    mInputStream[idx].open(inputFileName.c_str(), std::ifstream::binary);
+    ASSERT_EQ(mInputStream[idx].is_open(), true);
 }
 
 int32_t WriterTest::createWriter(int32_t fd) {
@@ -223,10 +270,10 @@
     return 0;
 }
 
-int32_t WriterTest::addWriterSource(bool isAudio, configFormat params) {
-    if (mInputFrameId) return -1;
+int32_t WriterTest::addWriterSource(bool isAudio, configFormat params, int32_t idx) {
+    if (mInputFrameId[idx]) return -1;
     sp<AMessage> format = new AMessage;
-    if (mInputStream.is_open()) {
+    if (mInputStream[idx].is_open()) {
         format->setString("mime", params.mime);
         if (isAudio) {
             format->setInt32("channel-count", params.channelCount);
@@ -235,25 +282,34 @@
             format->setInt32("width", params.width);
             format->setInt32("height", params.height);
         }
-
-        int32_t status =
-                writeHeaderBuffers(mInputStream, mBufferInfo, mInputFrameId, format, mNumCsds);
-        if (status != 0) return -1;
+        if (mNumCsds[idx]) {
+            int32_t status = writeHeaderBuffers(mInputStream[idx], mBufferInfo[idx],
+                                                mInputFrameId[idx], format, mNumCsds[idx]);
+            if (status != 0) return -1;
+        }
     }
+
     sp<MetaData> trackMeta = new MetaData;
     convertMessageToMetaData(format, trackMeta);
-    mCurrentTrack = new MediaAdapter(trackMeta);
-    if (mCurrentTrack == nullptr) {
+    mCurrentTrack[idx] = new MediaAdapter(trackMeta);
+    if (mCurrentTrack[idx] == nullptr) {
         ALOGE("MediaAdapter returned nullptr");
         return -1;
     }
-    status_t result = mWriter->addSource(mCurrentTrack);
+    status_t result = mWriter->addSource(mCurrentTrack[idx]);
     return result;
 }
 
 void getFileDetails(string &inputFilePath, string &info, configFormat &params, bool &isAudio,
-                    int32_t streamIndex = 0) {
-    if (streamIndex >= sizeof(kInputData) / sizeof(kInputData[0])) {
+                    inputId inpId) {
+    int32_t inputDataSize = sizeof(kInputData) / sizeof(kInputData[0]);
+    int32_t streamIndex = 0;
+    for (; streamIndex < inputDataSize; streamIndex++) {
+        if (inpId == kInputData[streamIndex].inpId) {
+            break;
+        }
+    }
+    if (streamIndex == inputDataSize) {
         return;
     }
     inputFilePath += kInputData[streamIndex].inputFile;
@@ -270,7 +326,147 @@
     return;
 }
 
-TEST_P(WriterTest, CreateWriterTest) {
+void WriterTest::setupExtractor(AMediaExtractor *extractor, string inputFileName,
+                                int32_t &trackCount) {
+    ALOGV("Input file for extractor: %s", inputFileName.c_str());
+
+    int32_t fd = open(inputFileName.c_str(), O_RDONLY);
+    ASSERT_GE(fd, 0) << "Failed to open writer's output file to validate";
+
+    struct stat buf;
+    int32_t status = fstat(fd, &buf);
+    ASSERT_EQ(status, 0) << "Failed to get properties of input file for extractor";
+
+    size_t fileSize = buf.st_size;
+    ALOGV("Size of input file to extractor: %zu", fileSize);
+
+    status = AMediaExtractor_setDataSourceFd(extractor, fd, 0, fileSize);
+    ASSERT_EQ(status, AMEDIA_OK) << "Failed to set data source for extractor";
+
+    trackCount = AMediaExtractor_getTrackCount(extractor);
+    ASSERT_GT(trackCount, 0) << "No tracks reported by extractor";
+    ALOGV("Number of tracks reported by extractor : %d", trackCount);
+    return;
+}
+
+void WriterTest::extract(AMediaExtractor *extractor, configFormat &params,
+                         vector<BufferInfo> &bufferInfo, uint8_t *buffer, size_t bufSize,
+                         size_t *bytesExtracted, int32_t idx) {
+    AMediaExtractor_selectTrack(extractor, idx);
+    AMediaFormat *format = AMediaExtractor_getTrackFormat(extractor, idx);
+    ASSERT_NE(format, nullptr) << "Track format is NULL";
+    ALOGI("Track format = %s", AMediaFormat_toString(format));
+
+    const char *mime = nullptr;
+    AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime);
+    ASSERT_NE(mime, nullptr) << "Track mime is NULL";
+    ALOGI("Track mime = %s", mime);
+    strlcpy(params.mime, mime, kMimeSize);
+
+    if (!strncmp(mime, "audio/", 6)) {
+        ASSERT_TRUE(
+                AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, &params.channelCount))
+                << "Extractor did not report channel count";
+        ASSERT_TRUE(AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, &params.sampleRate))
+                << "Extractor did not report sample rate";
+    } else if (!strncmp(mime, "video/", 6) || !strncmp(mime, "image/", 6)) {
+        ASSERT_TRUE(AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_WIDTH, &params.width))
+                << "Extractor did not report width";
+        ASSERT_TRUE(AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_HEIGHT, &params.height))
+                << "Extractor did not report height";
+    } else {
+        ASSERT_TRUE(false) << "Invalid mime " << mime;
+    }
+
+    int32_t bufferOffset = 0;
+    // Get CSD data
+    int index = 0;
+    void *csdBuf;
+    while (1) {
+        csdBuf = nullptr;
+        char csdName[16];
+        snprintf(csdName, 16, "csd-%d", index);
+        size_t csdSize = 0;
+        bool csdFound = AMediaFormat_getBuffer(format, csdName, &csdBuf, &csdSize);
+        if (!csdFound || !csdBuf || !csdSize) break;
+
+        bufferInfo.push_back({static_cast<int32_t>(csdSize), CODEC_CONFIG_FLAG, 0});
+        memcpy(buffer + bufferOffset, csdBuf, csdSize);
+        bufferOffset += csdSize;
+        index++;
+    }
+
+    // Get frame data
+    while (1) {
+        ssize_t sampleSize = AMediaExtractor_getSampleSize(extractor);
+        if (sampleSize < 0) break;
+
+        uint8_t *sampleBuffer = (uint8_t *)malloc(sampleSize);
+        ASSERT_NE(sampleBuffer, nullptr) << "Failed to allocate the buffer of size " << sampleSize;
+
+        int bytesRead = AMediaExtractor_readSampleData(extractor, sampleBuffer, sampleSize);
+        ASSERT_EQ(bytesRead, sampleSize)
+                << "Number of bytes extracted does not match with sample size";
+        int64_t pts = AMediaExtractor_getSampleTime(extractor);
+        uint32_t flag = AMediaExtractor_getSampleFlags(extractor);
+
+        if (mime == MEDIA_MIMETYPE_AUDIO_VORBIS) {
+            // Removing 4 bytes of AMEDIAFORMAT_KEY_VALID_SAMPLES from sample size
+            bytesRead = bytesRead - 4;
+        }
+
+        ASSERT_LE(bufferOffset + bytesRead, bufSize)
+                << "Size of the buffer is insufficient to store the extracted data";
+        bufferInfo.push_back({bytesRead, flag, pts});
+        memcpy(buffer + bufferOffset, sampleBuffer, bytesRead);
+        bufferOffset += bytesRead;
+
+        AMediaExtractor_advance(extractor);
+        free(sampleBuffer);
+    }
+    *bytesExtracted = bufferOffset;
+    return;
+}
+
+void WriterTest::compareParams(configFormat srcParam, configFormat dstParam,
+                               vector<BufferInfo> dstBufInfo, int32_t index) {
+    ASSERT_STREQ(srcParam.mime, dstParam.mime)
+            << "Extracted mime type does not match with input mime type";
+
+    if (!strncmp(srcParam.mime, "audio/", 6)) {
+        ASSERT_EQ(srcParam.channelCount, dstParam.channelCount)
+                << "Extracted channel count does not match with input channel count";
+        ASSERT_EQ(srcParam.sampleRate, dstParam.sampleRate)
+                << "Extracted sample rate does not match with input sample rate";
+    } else if (!strncmp(srcParam.mime, "video/", 6) || !strncmp(srcParam.mime, "image/", 6)) {
+        ASSERT_EQ(srcParam.width, dstParam.width)
+                << "Extracted width does not match with input width";
+        ASSERT_EQ(srcParam.height, dstParam.height)
+                << "Extracted height does not match with input height";
+    } else {
+        ASSERT_TRUE(false) << "Invalid mime type" << srcParam.mime;
+    }
+
+    int32_t toleranceValueUs = kMuxToleranceTimeUs;
+    if (mWriterName == MPEG4) {
+        toleranceValueUs = kMpeg4MuxToleranceTimeUs;
+    }
+    for (int32_t i = 0; i < dstBufInfo.size(); i++) {
+        ASSERT_EQ(mBufferInfo[index][i].size, dstBufInfo[i].size)
+                << "Input size " << mBufferInfo[index][i].size << " mismatched with extracted size "
+                << dstBufInfo[i].size;
+        ASSERT_EQ(mBufferInfo[index][i].flags, dstBufInfo[i].flags)
+                << "Input flag " << mBufferInfo[index][i].flags
+                << " mismatched with extracted size " << dstBufInfo[i].flags;
+        ASSERT_LE(abs(mBufferInfo[index][i].timeUs - dstBufInfo[i].timeUs), toleranceValueUs)
+                << "Difference between original timestamp " << mBufferInfo[index][i].timeUs
+                << " and extracted timestamp " << dstBufInfo[i].timeUs
+                << "is greater than tolerance value = " << toleranceValueUs << " micro seconds";
+    }
+    return;
+}
+
+TEST_P(WriteFunctionalityTest, CreateWriterTest) {
     if (mDisableTest) return;
     ALOGV("Tests the creation of writers");
 
@@ -281,14 +477,14 @@
 
     // Creating writer within a test scope. Destructor should be called when the test ends
     ASSERT_EQ((status_t)OK, createWriter(fd))
-            << "Failed to create writer for output format:" << GetParam().first;
+            << "Failed to create writer for output format:" << get<0>(GetParam());
 }
 
-TEST_P(WriterTest, WriterTest) {
+TEST_P(WriteFunctionalityTest, WriterTest) {
     if (mDisableTest) return;
     ALOGV("Checks if for a given input, a valid muxed file has been created or not");
 
-    string writerFormat = GetParam().first;
+    string writerFormat = get<0>(GetParam());
     string outputFile = OUTPUT_FILE_NAME;
     int32_t fd =
             open(outputFile.c_str(), O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
@@ -297,35 +493,110 @@
     int32_t status = createWriter(fd);
     ASSERT_EQ((status_t)OK, status) << "Failed to create writer for output format:" << writerFormat;
 
-    string inputFile = gEnv->getRes();
-    string inputInfo = gEnv->getRes();
-    configFormat param;
-    bool isAudio;
-    int32_t inputFileIdx = GetParam().second;
-    getFileDetails(inputFile, inputInfo, param, isAudio, inputFileIdx);
-    ASSERT_NE(inputFile.compare(gEnv->getRes()), 0) << "No input file specified";
+    inputId inpId[] = {get<1>(GetParam()), get<2>(GetParam())};
+    ASSERT_NE(inpId[0], UNUSED_ID) << "Test expects first inputId to be a valid id";
 
-    ASSERT_NO_FATAL_FAILURE(getInputBufferInfo(inputFile, inputInfo));
-    status = addWriterSource(isAudio, param);
-    ASSERT_EQ((status_t)OK, status) << "Failed to add source for " << writerFormat << "Writer";
+    int32_t numTracks = 1;
+    if (inpId[1] != UNUSED_ID) {
+        numTracks++;
+    }
+
+    size_t fileSize[numTracks];
+    configFormat param[numTracks];
+    for (int32_t idx = 0; idx < numTracks; idx++) {
+        string inputFile = gEnv->getRes();
+        string inputInfo = gEnv->getRes();
+        bool isAudio;
+        getFileDetails(inputFile, inputInfo, param[idx], isAudio, inpId[idx]);
+        ASSERT_NE(inputFile.compare(gEnv->getRes()), 0) << "No input file specified";
+
+        struct stat buf;
+        status = stat(inputFile.c_str(), &buf);
+        ASSERT_EQ(status, 0) << "Failed to get properties of input file:" << inputFile;
+        fileSize[idx] = buf.st_size;
+
+        ASSERT_NO_FATAL_FAILURE(getInputBufferInfo(inputFile, inputInfo, idx));
+        status = addWriterSource(isAudio, param[idx], idx);
+        ASSERT_EQ((status_t)OK, status) << "Failed to add source for " << writerFormat << "Writer";
+    }
 
     status = mWriter->start(mFileMeta.get());
     ASSERT_EQ((status_t)OK, status);
-    status = sendBuffersToWriter(mInputStream, mBufferInfo, mInputFrameId, mCurrentTrack, 0,
-                                 mBufferInfo.size());
-    ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
-    mCurrentTrack->stop();
+    float interval = get<3>(GetParam());
+    ASSERT_LE(interval, 1.0f) << "Buffer interval invalid. Should be less than or equal to 1.0";
 
+    size_t range = 0;
+    int32_t loopCount = 0;
+    int32_t offset[kMaxTrackCount]{};
+    while (loopCount < ceil(1.0 / interval)) {
+        for (int32_t idx = 0; idx < numTracks; idx++) {
+            range = mBufferInfo[idx].size() * interval;
+            status = sendBuffersToWriter(mInputStream[idx], mBufferInfo[idx], mInputFrameId[idx],
+                                         mCurrentTrack[idx], offset[idx], range);
+            ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
+            offset[idx] += range;
+        }
+        loopCount++;
+    }
+    for (int32_t idx = 0; idx < kMaxTrackCount; idx++) {
+        if (mCurrentTrack[idx]) {
+            mCurrentTrack[idx]->stop();
+        }
+    }
     status = mWriter->stop();
     ASSERT_EQ((status_t)OK, status) << "Failed to stop the writer";
     close(fd);
+
+    // Validate the output muxed file created by writer
+    // TODO(b/146423022): Skip validating output for webm writer
+    // TODO(b/146421018): Skip validating output for ogg writer
+    if (mWriterName != OGG && mWriterName != WEBM) {
+        configFormat extractorParams[numTracks];
+        vector<BufferInfo> extractorBufferInfo[numTracks];
+        int32_t trackCount = -1;
+
+        AMediaExtractor *extractor = AMediaExtractor_new();
+        ASSERT_NE(extractor, nullptr) << "Failed to create extractor";
+        ASSERT_NO_FATAL_FAILURE(setupExtractor(extractor, outputFile, trackCount));
+        ASSERT_EQ(trackCount, numTracks)
+                << "Tracks reported by extractor does not match with input number of tracks";
+
+        for (int32_t idx = 0; idx < numTracks; idx++) {
+            char *inputBuffer = (char *)malloc(fileSize[idx]);
+            ASSERT_NE(inputBuffer, nullptr)
+                    << "Failed to allocate the buffer of size " << fileSize[idx];
+            mInputStream[idx].seekg(0, mInputStream[idx].beg);
+            mInputStream[idx].read(inputBuffer, fileSize[idx]);
+            ASSERT_EQ(mInputStream[idx].gcount(), fileSize[idx]);
+
+            uint8_t *extractedBuffer = (uint8_t *)malloc(fileSize[idx]);
+            ASSERT_NE(extractedBuffer, nullptr)
+                    << "Failed to allocate the buffer of size " << fileSize[idx];
+            size_t bytesExtracted = 0;
+
+            ASSERT_NO_FATAL_FAILURE(extract(extractor, extractorParams[idx],
+                                            extractorBufferInfo[idx], extractedBuffer,
+                                            fileSize[idx], &bytesExtracted, idx));
+            ASSERT_GT(bytesExtracted, 0) << "Total bytes extracted by extractor cannot be zero";
+
+            ASSERT_NO_FATAL_FAILURE(
+                    compareParams(param[idx], extractorParams[idx], extractorBufferInfo[idx], idx));
+
+            ASSERT_EQ(memcmp(extractedBuffer, (uint8_t *)inputBuffer, bytesExtracted), 0)
+                    << "Extracted bit stream does not match with input bit stream";
+
+            free(inputBuffer);
+            free(extractedBuffer);
+        }
+        AMediaExtractor_delete(extractor);
+    }
 }
 
-TEST_P(WriterTest, PauseWriterTest) {
+TEST_P(WriteFunctionalityTest, PauseWriterTest) {
     if (mDisableTest) return;
     ALOGV("Validates the pause() api of writers");
 
-    string writerFormat = GetParam().first;
+    string writerFormat = get<0>(GetParam());
     string outputFile = OUTPUT_FILE_NAME;
     int32_t fd =
             open(outputFile.c_str(), O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
@@ -338,8 +609,10 @@
     string inputInfo = gEnv->getRes();
     configFormat param;
     bool isAudio;
-    int32_t inputFileIdx = GetParam().second;
-    getFileDetails(inputFile, inputInfo, param, isAudio, inputFileIdx);
+    inputId inpId = get<1>(GetParam());
+    ASSERT_NE(inpId, UNUSED_ID) << "Test expects first inputId to be a valid id";
+
+    getFileDetails(inputFile, inputInfo, param, isAudio, inpId);
     ASSERT_NE(inputFile.compare(gEnv->getRes()), 0) << "No input file specified";
 
     ASSERT_NO_FATAL_FAILURE(getInputBufferInfo(inputFile, inputInfo));
@@ -348,8 +621,8 @@
 
     status = mWriter->start(mFileMeta.get());
     ASSERT_EQ((status_t)OK, status);
-    status = sendBuffersToWriter(mInputStream, mBufferInfo, mInputFrameId, mCurrentTrack, 0,
-                                 mBufferInfo.size() / 4);
+    status = sendBuffersToWriter(mInputStream[0], mBufferInfo[0], mInputFrameId[0],
+                                 mCurrentTrack[0], 0, mBufferInfo[0].size() / 4);
     ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
 
     bool isPaused = false;
@@ -359,26 +632,26 @@
         isPaused = true;
     }
     // In the pause state, writers shouldn't write anything. Testing the writers for the same
-    int32_t numFramesPaused = mBufferInfo.size() / 4;
-    status = sendBuffersToWriter(mInputStream, mBufferInfo, mInputFrameId, mCurrentTrack,
-                                  mInputFrameId, numFramesPaused, isPaused);
+    int32_t numFramesPaused = mBufferInfo[0].size() / 4;
+    status = sendBuffersToWriter(mInputStream[0], mBufferInfo[0], mInputFrameId[0],
+                                 mCurrentTrack[0], mInputFrameId[0], numFramesPaused, isPaused);
     ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
 
     if (isPaused) {
         status = mWriter->start(mFileMeta.get());
         ASSERT_EQ((status_t)OK, status);
     }
-    status = sendBuffersToWriter(mInputStream, mBufferInfo, mInputFrameId, mCurrentTrack,
-                                  mInputFrameId, mBufferInfo.size());
+    status = sendBuffersToWriter(mInputStream[0], mBufferInfo[0], mInputFrameId[0],
+                                 mCurrentTrack[0], mInputFrameId[0], mBufferInfo[0].size());
     ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
-    mCurrentTrack->stop();
+    mCurrentTrack[0]->stop();
 
     status = mWriter->stop();
     ASSERT_EQ((status_t)OK, status) << "Failed to stop the writer";
     close(fd);
 }
 
-TEST_P(WriterTest, MultiStartStopPauseTest) {
+TEST_P(WriteFunctionalityTest, MultiStartStopPauseTest) {
     // TODO: (b/144821804)
     // Enable the test for MPE2TS writer
     if (mDisableTest || mWriterName == standardWriters::MPEG2TS) return;
@@ -389,7 +662,7 @@
             open(outputFile.c_str(), O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
     ASSERT_GE(fd, 0) << "Failed to open output file to dump writer's data";
 
-    string writerFormat = GetParam().first;
+    string writerFormat = get<0>(GetParam());
     int32_t status = createWriter(fd);
     ASSERT_EQ(status, (status_t)OK) << "Failed to create writer for output format:" << writerFormat;
 
@@ -397,8 +670,10 @@
     string inputInfo = gEnv->getRes();
     configFormat param;
     bool isAudio;
-    int32_t inputFileIdx = GetParam().second;
-    getFileDetails(inputFile, inputInfo, param, isAudio, inputFileIdx);
+    inputId inpId = get<1>(GetParam());
+    ASSERT_NE(inpId, UNUSED_ID) << "Test expects first inputId to be a valid id";
+
+    getFileDetails(inputFile, inputInfo, param, isAudio, inpId);
     ASSERT_NE(inputFile.compare(gEnv->getRes()), 0) << "No input file specified";
 
     ASSERT_NO_FATAL_FAILURE(getInputBufferInfo(inputFile, inputInfo));
@@ -415,8 +690,8 @@
         mWriter->start(mFileMeta.get());
     }
 
-    status = sendBuffersToWriter(mInputStream, mBufferInfo, mInputFrameId, mCurrentTrack, 0,
-                              mBufferInfo.size() / 4);
+    status = sendBuffersToWriter(mInputStream[0], mBufferInfo[0], mInputFrameId[0],
+                                 mCurrentTrack[0], 0, mBufferInfo[0].size() / 4);
     ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
 
     for (int32_t count = 0; count < kMaxCount; count++) {
@@ -425,20 +700,20 @@
     }
 
     mWriter->pause();
-    int32_t numFramesPaused = mBufferInfo.size() / 4;
-    status = sendBuffersToWriter(mInputStream, mBufferInfo, mInputFrameId, mCurrentTrack,
-                              mInputFrameId, numFramesPaused, true);
+    int32_t numFramesPaused = mBufferInfo[0].size() / 4;
+    status = sendBuffersToWriter(mInputStream[0], mBufferInfo[0], mInputFrameId[0],
+                                 mCurrentTrack[0], mInputFrameId[0], numFramesPaused, true);
     ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
 
     for (int32_t count = 0; count < kMaxCount; count++) {
         mWriter->start(mFileMeta.get());
     }
 
-    status = sendBuffersToWriter(mInputStream, mBufferInfo, mInputFrameId, mCurrentTrack,
-                              mInputFrameId, mBufferInfo.size());
+    status = sendBuffersToWriter(mInputStream[0], mBufferInfo[0], mInputFrameId[0],
+                                 mCurrentTrack[0], mInputFrameId[0], mBufferInfo[0].size());
     ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
 
-    mCurrentTrack->stop();
+    mCurrentTrack[0]->stop();
 
     // first stop should succeed.
     status = mWriter->stop();
@@ -451,19 +726,380 @@
     close(fd);
 }
 
+class WriterValidityTest
+    : public WriterTest,
+      public ::testing::TestWithParam<
+              tuple<string /* writerFormat*/, inputId /* inputId0*/, bool /* addSourceFail*/>> {
+  public:
+    virtual void SetUp() override { setupWriterType(get<0>(GetParam())); }
+};
+
+TEST_P(WriterValidityTest, InvalidInputTest) {
+    if (mDisableTest) return;
+    ALOGV("Validates writer's behavior for invalid inputs");
+
+    string writerFormat = get<0>(GetParam());
+    inputId inpId = get<1>(GetParam());
+    bool addSourceFailExpected = get<2>(GetParam());
+
+    // Test writers for invalid FD value
+    int32_t fd = -1;
+    int32_t status = createWriter(fd);
+    if (status != OK) {
+        ALOGV("createWriter failed for invalid FD, this is expected behavior");
+        return;
+    }
+
+    // If writer was created for invalid fd, test it further.
+    string inputFile = gEnv->getRes();
+    string inputInfo = gEnv->getRes();
+    configFormat param;
+    bool isAudio;
+    ASSERT_NE(inpId, UNUSED_ID) << "Test expects first inputId to be a valid id";
+
+    getFileDetails(inputFile, inputInfo, param, isAudio, inpId);
+    ASSERT_NE(inputFile.compare(gEnv->getRes()), 0) << "No input file specified";
+
+    ASSERT_NO_FATAL_FAILURE(getInputBufferInfo(inputFile, inputInfo));
+    status = addWriterSource(isAudio, param);
+    if (status != OK) {
+        ASSERT_TRUE(addSourceFailExpected)
+                << "Failed to add source for " << writerFormat << " writer";
+        ALOGV("addWriterSource failed for invalid FD, this is expected behavior");
+        return;
+    }
+
+    // start the writer with valid argument but invalid FD
+    status = mWriter->start(mFileMeta.get());
+    ASSERT_NE((status_t)OK, status) << "Writer did not fail for invalid FD";
+
+    status = sendBuffersToWriter(mInputStream[0], mBufferInfo[0], mInputFrameId[0],
+                                 mCurrentTrack[0], 0, mBufferInfo[0].size());
+    ASSERT_NE((status_t)OK, status) << "Writer did not report error for invalid FD";
+
+    status = mCurrentTrack[0]->stop();
+    ASSERT_EQ((status_t)OK, status) << "Failed to stop the track";
+
+    status = mWriter->stop();
+    ASSERT_EQ((status_t)OK, status) << "Failed to stop " << writerFormat << " writer";
+}
+
+TEST_P(WriterValidityTest, MalFormedDataTest) {
+    if (mDisableTest) return;
+    // Enable test for Ogg writer
+    ASSERT_NE(mWriterName, OGG) << "TODO(b/160105646)";
+    ALOGV("Test writer for malformed inputs");
+
+    string writerFormat = get<0>(GetParam());
+    inputId inpId = get<1>(GetParam());
+    bool addSourceFailExpected = get<2>(GetParam());
+    int32_t fd =
+            open(OUTPUT_FILE_NAME, O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
+    ASSERT_GE(fd, 0) << "Failed to open output file to dump writer's data";
+
+    int32_t status = createWriter(fd);
+    ASSERT_EQ(status, (status_t)OK)
+            << "Failed to create writer for " << writerFormat << " output format";
+
+    string inputFile = gEnv->getRes();
+    string inputInfo = gEnv->getRes();
+    configFormat param;
+    bool isAudio;
+    ASSERT_NE(inpId, UNUSED_ID) << "Test expects first inputId to be a valid id";
+
+    getFileDetails(inputFile, inputInfo, param, isAudio, inpId);
+    ASSERT_NE(inputFile.compare(gEnv->getRes()), 0) << "No input file specified";
+
+    ASSERT_NO_FATAL_FAILURE(getInputBufferInfo(inputFile, inputInfo));
+    // Remove CSD data from input
+    mNumCsds[0] = 0;
+    status = addWriterSource(isAudio, param);
+    if (status != OK) {
+        ASSERT_TRUE(addSourceFailExpected)
+                << "Failed to add source for " << writerFormat << " writer";
+        ALOGV("%s writer failed to addSource after removing CSD from input", writerFormat.c_str());
+        return;
+    }
+
+    status = mWriter->start(mFileMeta.get());
+    ASSERT_EQ((status_t)OK, status) << "Could not start " << writerFormat << "writer";
+
+    // Skip first few frames. These may contain sync frames also.
+    int32_t frameID = mInputFrameId[0] + mBufferInfo[0].size() / 4;
+    status = sendBuffersToWriter(mInputStream[0], mBufferInfo[0], frameID, mCurrentTrack[0], 0,
+                                 mBufferInfo[0].size());
+    ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
+
+    status = mCurrentTrack[0]->stop();
+    ASSERT_EQ((status_t)OK, status) << "Failed to stop the track";
+
+    Vector<String16> args;
+    status = mWriter->dump(fd, args);
+    ASSERT_EQ((status_t)OK, status) << "Failed to dump statistics from writer";
+
+    status = mWriter->stop();
+    ASSERT_EQ((status_t)OK, status) << "Failed to stop " << writerFormat << " writer";
+    close(fd);
+}
+
+// This test is specific to MPEG4Writer to test more APIs
+TEST_P(WriteFunctionalityTest, Mpeg4WriterTest) {
+    if (mDisableTest) return;
+    if (mWriterName != standardWriters::MPEG4) return;
+    ALOGV("Test MPEG4 writer specific APIs");
+
+    inputId inpId = get<1>(GetParam());
+    int32_t fd =
+            open(OUTPUT_FILE_NAME, O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
+    ASSERT_GE(fd, 0) << "Failed to open output file to dump writer's data";
+
+    int32_t status = createWriter(fd);
+    ASSERT_EQ(status, (status_t)OK) << "Failed to create writer for mpeg4 output format";
+
+    string inputFile = gEnv->getRes();
+    string inputInfo = gEnv->getRes();
+    configFormat param;
+    bool isAudio;
+    ASSERT_NE(inpId, UNUSED_ID) << "Test expects first inputId to be a valid id";
+
+    getFileDetails(inputFile, inputInfo, param, isAudio, inpId);
+    ASSERT_NE(inputFile.compare(gEnv->getRes()), 0) << "No input file specified";
+
+    ASSERT_NO_FATAL_FAILURE(getInputBufferInfo(inputFile, inputInfo));
+    status = addWriterSource(isAudio, param);
+    ASSERT_EQ((status_t)OK, status) << "Failed to add source for mpeg4 Writer";
+
+    // signal meta data for the writer
+    sp<MPEG4Writer> mp4writer = static_cast<MPEG4Writer *>(mWriter.get());
+    status = mp4writer->setInterleaveDuration(kDefaultInterleaveDuration);
+    ASSERT_EQ((status_t)OK, status) << "setInterleaveDuration failed";
+
+    status = mp4writer->setGeoData(kDefaultLatitudex10000, kDefaultLongitudex10000);
+    ASSERT_EQ((status_t)OK, status) << "setGeoData failed";
+
+    status = mp4writer->setCaptureRate(kDefaultFPS);
+    ASSERT_EQ((status_t)OK, status) << "setCaptureRate failed";
+
+    status = mWriter->start(mFileMeta.get());
+    ASSERT_EQ((status_t)OK, status) << "Could not start the writer";
+
+    status = sendBuffersToWriter(mInputStream[0], mBufferInfo[0], mInputFrameId[0],
+                                 mCurrentTrack[0], 0, mBufferInfo[0].size());
+    ASSERT_EQ((status_t)OK, status) << "mpeg4 writer failed";
+
+    status = mCurrentTrack[0]->stop();
+    ASSERT_EQ((status_t)OK, status) << "Failed to stop the track";
+
+    status = mWriter->stop();
+    ASSERT_EQ((status_t)OK, status) << "Failed to stop the writer";
+    mp4writer.clear();
+    close(fd);
+}
+
+class ListenerTest
+    : public WriterTest,
+      public ::testing::TestWithParam<tuple<
+              string /* writerFormat*/, inputId /* inputId0*/, inputId /* inputId1*/,
+              float /* FileSizeLimit*/, float /* FileDurationLimit*/, float /* BufferInterval*/>> {
+  public:
+    virtual void SetUp() override { setupWriterType(get<0>(GetParam())); }
+};
+
+TEST_P(ListenerTest, SetMaxFileLimitsTest) {
+    // TODO(b/151892414): Enable test for other writers
+    if (mDisableTest || mWriterName != MPEG4) return;
+    ALOGV("Validates writer when max file limits are set");
+
+    string writerFormat = get<0>(GetParam());
+    string outputFile = OUTPUT_FILE_NAME;
+    int32_t fd =
+            open(outputFile.c_str(), O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
+    ASSERT_GE(fd, 0) << "Failed to open output file to dump writer's data";
+
+    int32_t status = createWriter(fd);
+    ASSERT_EQ((status_t)OK, status) << "Failed to create writer for output format:" << writerFormat;
+
+    inputId inpId[] = {get<1>(GetParam()), get<2>(GetParam())};
+    ASSERT_NE(inpId[0], UNUSED_ID) << "Test expects first inputId to be a valid id";
+
+    size_t inputFileSize = 0;
+    int64_t lastFrameTimeStampUs = INT_MAX;
+    int32_t numTracks = 1;
+    if (inpId[1] != UNUSED_ID) {
+        numTracks++;
+    }
+    for (int32_t idx = 0; idx < numTracks; idx++) {
+        string inputFile = gEnv->getRes();
+        string inputInfo = gEnv->getRes();
+        configFormat param;
+        bool isAudio;
+        getFileDetails(inputFile, inputInfo, param, isAudio, inpId[idx]);
+        ASSERT_NE(inputFile.compare(gEnv->getRes()), 0) << "No input file specified";
+
+        ASSERT_NO_FATAL_FAILURE(getInputBufferInfo(inputFile, inputInfo, idx));
+        status = addWriterSource(isAudio, param, idx);
+        ASSERT_EQ((status_t)OK, status) << "Failed to add source for " << writerFormat << "Writer";
+
+        // Read file properties
+        struct stat buf;
+        status = stat(inputFile.c_str(), &buf);
+        ASSERT_EQ(0, status);
+
+        inputFileSize += buf.st_size;
+        if (lastFrameTimeStampUs > mBufferInfo[idx][mBufferInfo[idx].size() - 1].timeUs) {
+            lastFrameTimeStampUs = mBufferInfo[idx][mBufferInfo[idx].size() - 1].timeUs;
+        }
+    }
+
+    float fileSizeLimit = get<3>(GetParam());
+    float fileDurationLimit = get<4>(GetParam());
+    int64_t maxFileSize = 0;
+    int64_t maxFileDuration = 0;
+    if (fileSizeLimit > 0) {
+        maxFileSize = (int64_t)(fileSizeLimit * inputFileSize);
+        mWriter->setMaxFileSize(maxFileSize);
+    }
+    if (fileDurationLimit > 0) {
+        maxFileDuration = (int64_t)(fileDurationLimit * lastFrameTimeStampUs);
+        mWriter->setMaxFileDuration(maxFileDuration);
+    }
+
+    sp<WriterListener> listener = new WriterListener();
+    ASSERT_NE(listener, nullptr) << "unable to allocate listener";
+
+    mWriter->setListener(listener);
+    status = mWriter->start(mFileMeta.get());
+    ASSERT_EQ((status_t)OK, status);
+
+    float interval = get<5>(GetParam());
+    ASSERT_LE(interval, 1.0f) << "Buffer interval invalid. Should be less than or equal to 1.0";
+
+    size_t range = 0;
+    int32_t loopCount = 0;
+    int32_t offset[kMaxTrackCount]{};
+    while (loopCount < ceil(1.0 / interval)) {
+        for (int32_t idx = 0; idx < numTracks; idx++) {
+            range = mBufferInfo[idx].size() * interval;
+            status = sendBuffersToWriter(mInputStream[idx], mBufferInfo[idx], mInputFrameId[idx],
+                                         mCurrentTrack[idx], offset[idx], range, false, listener);
+            ASSERT_EQ((status_t)OK, status) << writerFormat << " writer failed";
+            offset[idx] += range;
+        }
+        loopCount++;
+    }
+
+    ASSERT_TRUE(mWriter->reachedEOS()) << "EOS not signalled.";
+
+    for (int32_t idx = 0; idx < kMaxTrackCount; idx++) {
+        if (mCurrentTrack[idx]) {
+            mCurrentTrack[idx]->stop();
+        }
+    }
+
+    status = mWriter->stop();
+    ASSERT_EQ((status_t)OK, status) << "Failed to stop the writer";
+    close(fd);
+
+    if (maxFileSize <= 0) {
+        ASSERT_FALSE(listener->mSignaledSize);
+    } else if (maxFileDuration <= 0) {
+        ASSERT_FALSE(listener->mSignaledDuration);
+    } else if (maxFileSize > 0 && maxFileDuration <= 0) {
+        ASSERT_TRUE(listener->mSignaledSize);
+    } else if (maxFileDuration > 0 && maxFileSize <= 0) {
+        ASSERT_TRUE(listener->mSignaledDuration);
+    } else {
+        ASSERT_TRUE(listener->mSignaledSize || listener->mSignaledDuration);
+    }
+
+    if (maxFileSize > 0) {
+        struct stat buf;
+        status = stat(outputFile.c_str(), &buf);
+        ASSERT_EQ(0, status);
+        ASSERT_LE(buf.st_size, maxFileSize);
+    }
+}
+
+// TODO: (b/150923387)
+// Add WEBM input
+INSTANTIATE_TEST_SUITE_P(ListenerTestAll, ListenerTest,
+                         ::testing::Values(make_tuple("aac", AAC_1, UNUSED_ID, 0.6, 0.7, 1),
+                                           make_tuple("amrnb", AMR_NB_1, UNUSED_ID, 0.2, 0.6, 1),
+                                           make_tuple("amrwb", AMR_WB_1, UNUSED_ID, 0.5, 0.5, 1),
+                                           make_tuple("mpeg2Ts", AAC_1, UNUSED_ID, 0.2, 1, 1),
+                                           make_tuple("mpeg4", AAC_1, UNUSED_ID, 0.4, 0.3, 0.25),
+                                           make_tuple("mpeg4", AAC_1, UNUSED_ID, 0.3, 1, 0.5),
+                                           make_tuple("ogg", OPUS_1, UNUSED_ID, 0.7, 0.3, 1)));
+
 // TODO: (b/144476164)
 // Add AAC_ADTS, FLAC, AV1 input
-INSTANTIATE_TEST_SUITE_P(WriterTestAll, WriterTest,
-                         ::testing::Values(make_pair("ogg", 0), make_pair("webm", 0),
-                                           make_pair("aac", 1), make_pair("mpeg4", 1),
-                                           make_pair("amrnb", 3), make_pair("amrwb", 4),
-                                           make_pair("webm", 5), make_pair("webm", 7),
-                                           make_pair("webm", 8), make_pair("mpeg4", 9),
-                                           make_pair("mpeg4", 10), make_pair("mpeg4", 12),
-                                           make_pair("mpeg4", 13), make_pair("mpeg2Ts", 1),
-                                           make_pair("mpeg2Ts", 9)));
+INSTANTIATE_TEST_SUITE_P(
+        WriterTestAll, WriteFunctionalityTest,
+        ::testing::Values(
+                make_tuple("aac", AAC_1, UNUSED_ID, 1),
+
+                make_tuple("amrnb", AMR_NB_1, UNUSED_ID, 1),
+                make_tuple("amrwb", AMR_WB_1, UNUSED_ID, 1),
+
+                // TODO(b/144902018): Enable test for mpeg2ts
+                // make_tuple("mpeg2Ts", AAC_1, UNUSED_ID, 1),
+                // make_tuple("mpeg2Ts", AVC_1, UNUSED_ID, 1),
+                // TODO(b/156355857): Add multitrack for mpeg2ts
+                // make_tuple("mpeg2Ts", AAC_1, AVC_1, 0.50),
+                // make_tuple("mpeg2Ts", AVC_1, AAC_1, 0.25),
+
+                make_tuple("mpeg4", AAC_1, UNUSED_ID, 1),
+                make_tuple("mpeg4", AMR_NB_1, UNUSED_ID, 1),
+                make_tuple("mpeg4", AMR_WB_1, UNUSED_ID, 1),
+                make_tuple("mpeg4", AVC_1, UNUSED_ID, 1),
+                make_tuple("mpeg4", H263_1, UNUSED_ID, 1),
+                make_tuple("mpeg4", HEIC_1, UNUSED_ID, 1),
+                make_tuple("mpeg4", HEVC_1, UNUSED_ID, 1),
+                make_tuple("mpeg4", MPEG4_1, UNUSED_ID, 1),
+                make_tuple("mpeg4", AAC_1, AVC_1, 0.25),
+                make_tuple("mpeg4", AVC_1, AAC_1, 0.75),
+                make_tuple("mpeg4", AMR_WB_1, AAC_1, 0.75),
+                make_tuple("mpeg4", HEVC_1, AMR_WB_1, 0.25),
+                make_tuple("mpeg4", H263_1, AMR_NB_1, 0.50),
+                make_tuple("mpeg4", MPEG4_1, AAC_1, 0.75),
+                make_tuple("mpeg4", AMR_NB_1, AMR_WB_1, 0.25),
+                make_tuple("mpeg4", H263_1, AMR_NB_1, 0.50),
+                make_tuple("mpeg4", MPEG4_1, HEVC_1, 0.75),
+
+                make_tuple("ogg", OPUS_1, UNUSED_ID, 1),
+
+                make_tuple("webm", OPUS_1, UNUSED_ID, 1),
+                make_tuple("webm", VORBIS_1, UNUSED_ID, 1),
+                make_tuple("webm", VP8_1, UNUSED_ID, 1),
+                make_tuple("webm", VP9_1, UNUSED_ID, 1),
+                make_tuple("webm", VP8_1, OPUS_1, 0.50),
+                make_tuple("webm", VORBIS_1, VP8_1, 0.25)));
+
+INSTANTIATE_TEST_SUITE_P(
+        WriterValidityTest, WriterValidityTest,
+        ::testing::Values(
+                make_tuple("aac", AAC_1, true),
+
+                make_tuple("amrnb", AMR_NB_1, true),
+                make_tuple("amrwb", AMR_WB_1, true),
+
+                make_tuple("mpeg4", AAC_1, false),
+                make_tuple("mpeg4", AMR_NB_1, false),
+                make_tuple("mpeg4", AVC_1, false),
+                make_tuple("mpeg4", H263_1, false),
+                make_tuple("mpeg4", HEIC_1, false),
+                make_tuple("mpeg4", HEVC_1, false),
+                make_tuple("mpeg4", MPEG4_1, false),
+
+                make_tuple("ogg", OPUS_1, true),
+
+                make_tuple("webm", OPUS_1, false),
+                make_tuple("webm", VORBIS_1, true),
+                make_tuple("webm", VP8_1, false),
+                make_tuple("webm", VP9_1, false)));
 
 int main(int argc, char **argv) {
+    ProcessState::self()->startThreadPool();
     gEnv = new WriterTestEnvironment();
     ::testing::AddGlobalTestEnvironment(gEnv);
     ::testing::InitGoogleTest(&argc, argv);
diff --git a/media/libstagefright/tests/writer/WriterTestEnvironment.h b/media/libstagefright/tests/writer/WriterTestEnvironment.h
index 99e686f..7da0a62 100644
--- a/media/libstagefright/tests/writer/WriterTestEnvironment.h
+++ b/media/libstagefright/tests/writer/WriterTestEnvironment.h
@@ -25,7 +25,7 @@
 
 class WriterTestEnvironment : public ::testing::Environment {
   public:
-    WriterTestEnvironment() : res("/data/local/tmp/") {}
+    WriterTestEnvironment() : res("/data/local/tmp/"), deleteOutput(true) {}
 
     // Parses the command line arguments
     int initFromOptions(int argc, char **argv);
@@ -34,16 +34,21 @@
 
     const string getRes() const { return res; }
 
+    bool cleanUp() const { return deleteOutput; }
+
   private:
     string res;
+    bool deleteOutput;
 };
 
 int WriterTestEnvironment::initFromOptions(int argc, char **argv) {
-    static struct option options[] = {{"res", required_argument, 0, 'P'}, {0, 0, 0, 0}};
+    static struct option options[] = {{"res", required_argument, 0, 'P'},
+                                      {"cleanUp", optional_argument, 0, 'C'},
+                                      {0, 0, 0, 0}};
 
     while (true) {
         int index = 0;
-        int c = getopt_long(argc, argv, "P:", options, &index);
+        int c = getopt_long(argc, argv, "P:C:", options, &index);
         if (c == -1) {
             break;
         }
@@ -52,6 +57,11 @@
             case 'P':
                 setRes(optarg);
                 break;
+            case 'C':
+                if (!strcmp(optarg, "false")) {
+                    deleteOutput = false;
+                }
+                break;
             default:
                 break;
         }
@@ -62,7 +72,8 @@
                 "unrecognized option: %s\n\n"
                 "usage: %s <gtest options> <test options>\n\n"
                 "test options are:\n\n"
-                "-P, --path: Resource files directory location\n",
+                "-P, --path: Resource files directory location\n"
+                "-C, default:true. Delete output file after test completes\n",
                 argv[optind ?: 1], argv[0]);
         return 2;
     }
diff --git a/media/libstagefright/tests/writer/WriterUtility.cpp b/media/libstagefright/tests/writer/WriterUtility.cpp
index f24ccb6..a3043fe 100644
--- a/media/libstagefright/tests/writer/WriterUtility.cpp
+++ b/media/libstagefright/tests/writer/WriterUtility.cpp
@@ -24,9 +24,16 @@
 
 int32_t sendBuffersToWriter(ifstream &inputStream, vector<BufferInfo> &bufferInfo,
                             int32_t &inputFrameId, sp<MediaAdapter> &currentTrack, int32_t offset,
-                            int32_t range, bool isPaused) {
+                            int32_t range, bool isPaused, sp<WriterListener> listener) {
     while (1) {
         if (inputFrameId >= (int)bufferInfo.size() || inputFrameId >= (offset + range)) break;
+        if (listener != nullptr) {
+            if (listener->mSignaledDuration || listener->mSignaledSize) {
+                ALOGV("Max File limit reached. No more buffers will be sent to the writer");
+                break;
+            }
+        }
+
         int32_t size = bufferInfo[inputFrameId].size;
         char *data = (char *)malloc(size);
         if (!data) {
diff --git a/media/libstagefright/tests/writer/WriterUtility.h b/media/libstagefright/tests/writer/WriterUtility.h
index cdd6246..6b456fb 100644
--- a/media/libstagefright/tests/writer/WriterUtility.h
+++ b/media/libstagefright/tests/writer/WriterUtility.h
@@ -27,13 +27,19 @@
 
 #include <media/stagefright/MediaAdapter.h>
 
-using namespace android;
-using namespace std;
+#include "WriterListener.h"
 
 #define CODEC_CONFIG_FLAG 32
 
+constexpr uint32_t kMaxTrackCount = 2;
 constexpr uint32_t kMaxCSDStrlen = 16;
 constexpr uint32_t kMaxCount = 20;
+constexpr int32_t kMimeSize = 128;
+constexpr int32_t kDefaultInterleaveDuration = 0;
+// Geodata is set according to ISO-6709 standard.
+constexpr int32_t kDefaultLatitudex10000 = 500000;
+constexpr int32_t kDefaultLongitudex10000 = 1000000;
+constexpr float kDefaultFPS = 30.0f;
 
 struct BufferInfo {
     int32_t size;
@@ -41,9 +47,18 @@
     int64_t timeUs;
 };
 
+struct configFormat {
+    char mime[kMimeSize];
+    int32_t width;
+    int32_t height;
+    int32_t sampleRate;
+    int32_t channelCount;
+};
+
 int32_t sendBuffersToWriter(ifstream &inputStream, vector<BufferInfo> &bufferInfo,
                             int32_t &inputFrameId, sp<MediaAdapter> &currentTrack, int32_t offset,
-                            int32_t range, bool isPaused = false);
+                            int32_t range, bool isPaused = false,
+                            sp<WriterListener> listener = nullptr);
 
 int32_t writeHeaderBuffers(ifstream &inputStream, vector<BufferInfo> &bufferInfo,
                            int32_t &inputFrameId, sp<AMessage> &format, int32_t numCsds);
diff --git a/media/libstagefright/timedtext/Android.bp b/media/libstagefright/timedtext/Android.bp
index 4f4ceb1..6590ef7 100644
--- a/media/libstagefright/timedtext/Android.bp
+++ b/media/libstagefright/timedtext/Android.bp
@@ -1,3 +1,22 @@
+package {
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_timedtext_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_libstagefright_timedtext_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_static {
     name: "libstagefright_timedtext",
 
@@ -22,5 +41,3 @@
 
     shared_libs: ["libmedia"],
 }
-
-
diff --git a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp b/media/libstagefright/timedtext/test/Android.bp
similarity index 60%
copy from media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
copy to media/libstagefright/timedtext/test/Android.bp
index 655491a..e8ee2ee 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/test/Android.bp
+++ b/media/libstagefright/timedtext/test/Android.bp
@@ -14,33 +14,51 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_timedtext_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_media_libstagefright_timedtext_license",
+    ],
+}
+
 cc_test {
-    name: "Mpeg4H263DecoderTest",
+    name: "TimedTextUnitTest",
     gtest: true,
 
     srcs: [
-        "Mpeg4H263DecoderTest.cpp",
+        "TimedTextUnitTest.cpp",
+    ],
+
+    static_libs: [
+        "libstagefright_timedtext",
+        "libstagefright_foundation",
+    ],
+
+    include_dirs: [
+        "frameworks/av/media/libstagefright",
     ],
 
     shared_libs: [
         "liblog",
-    ],
-
-    static_libs: [
-        "libstagefright_m4vh263dec",
-        "libstagefright_foundation",
+        "libmedia",
+        "libbinder",
     ],
 
     cflags: [
+        "-Wno-multichar",
         "-Werror",
         "-Wall",
     ],
 
     sanitize: {
+        cfi: true,
         misc_undefined: [
             "unsigned-integer-overflow",
             "signed-integer-overflow",
         ],
-        cfi: true,
     },
 }
diff --git a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml b/media/libstagefright/timedtext/test/AndroidTest.xml
similarity index 71%
copy from media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
copy to media/libstagefright/timedtext/test/AndroidTest.xml
index 7ff9732..3654e23 100644
--- a/media/libstagefright/codecs/mp3dec/test/AndroidTest.xml
+++ b/media/libstagefright/timedtext/test/AndroidTest.xml
@@ -13,19 +13,19 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Test module config for Mp3 Decoder unit test">
-    <option name="test-suite-tag" value="Mp3DecoderTest" />
+<configuration description="Test module config for TimedText unit test">
+    <option name="test-suite-tag" value="TimedTextUnitTest" />
     <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
         <option name="cleanup" value="true" />
-        <option name="push" value="Mp3DecoderTest->/data/local/tmp/Mp3DecoderTest" />
+        <option name="push" value="TimedTextUnitTest->/data/local/tmp/TimedTextUnitTest" />
         <option name="push-file"
-            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/mp3dec/test/Mp3DecoderTest.zip?unzip=true"
-            value="/data/local/tmp/Mp3DecoderTestRes/" />
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/timedtext/test/TimedTextUnitTest.zip?unzip=true"
+            value="/data/local/tmp/TimedTextUnitTestRes/" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.GTest" >
         <option name="native-test-device-path" value="/data/local/tmp" />
-        <option name="module-name" value="Mp3DecoderTest" />
-        <option name="native-test-flag" value="-P /data/local/tmp/Mp3DecoderTestRes/" />
+        <option name="module-name" value="TimedTextUnitTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/TimedTextUnitTestRes/" />
     </test>
 </configuration>
diff --git a/media/libstagefright/timedtext/test/README.md b/media/libstagefright/timedtext/test/README.md
new file mode 100644
index 0000000..3a774bd
--- /dev/null
+++ b/media/libstagefright/timedtext/test/README.md
@@ -0,0 +1,40 @@
+## Media Testing ##
+---
+#### TimedText Unit Test :
+The TimedText Unit Test Suite validates the TextDescription class available in libstagefright.
+
+Run the following steps to build the test suite:
+```
+m TimedTextUnitTest
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+```
+adb push ${OUT}/data/nativetest64/TimedTextUnitTest/TimedTextUnitTest /data/local/tmp/
+```
+
+To test 32-bit binary push binaries from nativetest.
+```
+adb push ${OUT}/data/nativetest/TimedTextUnitTest/TimedTextUnitTest /data/local/tmp/
+```
+
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/timedtext/test/TimedTextUnitTest.zip).
+Download, unzip and push these files into device for testing.
+
+```
+adb push TimedTextUnitTestRes/. /data/local/tmp/
+```
+
+usage: TimedTextUnitTest -P \<path_to_folder\>
+```
+adb shell /data/local/tmp/TimedTextUnitTest -P /data/local/tmp/TimedTextUnitTestRes/
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest TimedTextUnitTest -- --enable-module-dynamic-download=true
+```
diff --git a/media/libstagefright/timedtext/test/TimedTextTestEnvironment.h b/media/libstagefright/timedtext/test/TimedTextTestEnvironment.h
new file mode 100644
index 0000000..52280c1
--- /dev/null
+++ b/media/libstagefright/timedtext/test/TimedTextTestEnvironment.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __TIMEDTEXT_TEST_ENVIRONMENT_H__
+#define __TIMEDTEXT_TEST_ENVIRONMENT_H__
+
+#include <gtest/gtest.h>
+
+#include <getopt.h>
+
+using namespace std;
+
+class TimedTextTestEnvironment : public ::testing::Environment {
+  public:
+    TimedTextTestEnvironment() : res("/data/local/tmp/") {}
+
+    // Parses the command line arguments
+    int initFromOptions(int argc, char **argv);
+
+    void setRes(const char *_res) { res = _res; }
+
+    const string getRes() const { return res; }
+
+  private:
+    string res;
+};
+
+int TimedTextTestEnvironment::initFromOptions(int argc, char **argv) {
+    static struct option options[] = {{"res", required_argument, 0, 'P'}, {0, 0, 0, 0}};
+
+    while (true) {
+        int index = 0;
+        int c = getopt_long(argc, argv, "P:", options, &index);
+        if (c == -1) {
+            break;
+        }
+
+        switch (c) {
+            case 'P':
+                setRes(optarg);
+                break;
+            default:
+                break;
+        }
+    }
+
+    if (optind < argc) {
+        fprintf(stderr,
+                "unrecognized option: %s\n\n"
+                "usage: %s <gtest options> <test options>\n\n"
+                "test options are:\n\n"
+                "-P, --path: Resource files directory location\n",
+                argv[optind ?: 1], argv[0]);
+        return 2;
+    }
+    return 0;
+}
+
+#endif  // __TIMEDTEXT_TEST_ENVIRONMENT_H__
diff --git a/media/libstagefright/timedtext/test/TimedTextUnitTest.cpp b/media/libstagefright/timedtext/test/TimedTextUnitTest.cpp
new file mode 100644
index 0000000..d85ae39
--- /dev/null
+++ b/media/libstagefright/timedtext/test/TimedTextUnitTest.cpp
@@ -0,0 +1,379 @@
+/*
+ * Copyright (C) 2020 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 "TimedTextUnitTest"
+#include <utils/Log.h>
+
+#include <stdio.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <fstream>
+
+#include <binder/Parcel.h>
+#include <media/stagefright/foundation/AString.h>
+#include <media/stagefright/foundation/ByteUtils.h>
+
+#include "timedtext/TextDescriptions.h"
+
+#include "TimedTextTestEnvironment.h"
+
+constexpr int32_t kStartTimeMs = 10000;
+
+enum {
+    // These keys must be in sync with the keys in
+    // frameworks/av/media/libstagefright/timedtext/TextDescriptions.h
+    KEY_DISPLAY_FLAGS = 1,
+    KEY_STYLE_FLAGS = 2,
+    KEY_BACKGROUND_COLOR_RGBA = 3,
+    KEY_HIGHLIGHT_COLOR_RGBA = 4,
+    KEY_SCROLL_DELAY = 5,
+    KEY_WRAP_TEXT = 6,
+    KEY_START_TIME = 7,
+    KEY_STRUCT_BLINKING_TEXT_LIST = 8,
+    KEY_STRUCT_FONT_LIST = 9,
+    KEY_STRUCT_HIGHLIGHT_LIST = 10,
+    KEY_STRUCT_HYPER_TEXT_LIST = 11,
+    KEY_STRUCT_KARAOKE_LIST = 12,
+    KEY_STRUCT_STYLE_LIST = 13,
+    KEY_STRUCT_TEXT_POS = 14,
+    KEY_STRUCT_JUSTIFICATION = 15,
+    KEY_STRUCT_TEXT = 16,
+
+    KEY_GLOBAL_SETTING = 101,
+    KEY_LOCAL_SETTING = 102,
+    KEY_START_CHAR = 103,
+    KEY_END_CHAR = 104,
+    KEY_FONT_ID = 105,
+    KEY_FONT_SIZE = 106,
+    KEY_TEXT_COLOR_RGBA = 107,
+};
+
+struct FontInfo {
+    int32_t displayFlag = -1;
+    int32_t horizontalJustification = -1;
+    int32_t verticalJustification = -1;
+    int32_t rgbaBackground = -1;
+    int32_t leftPos = -1;
+    int32_t topPos = -1;
+    int32_t bottomPos = -1;
+    int32_t rightPos = -1;
+    int32_t startchar = -1;
+    int32_t endChar = -1;
+    int32_t fontId = -1;
+    int32_t faceStyle = -1;
+    int32_t fontSize = -1;
+    int32_t rgbaText = -1;
+    int32_t entryCount = -1;
+};
+
+struct FontRecord {
+    int32_t fontID = -1;
+    int32_t fontNameLength = -1;
+    const uint8_t *font = nullptr;
+};
+
+using namespace android;
+
+static TimedTextTestEnvironment *gEnv = nullptr;
+
+class TimedTextUnitTest : public ::testing::TestWithParam</*filename*/ string> {
+  public:
+    TimedTextUnitTest(){};
+
+    ~TimedTextUnitTest() {
+        if (mEleStream) mEleStream.close();
+    }
+
+    virtual void SetUp() override {
+        mInputFileName = gEnv->getRes() + GetParam();
+        mEleStream.open(mInputFileName, ifstream::binary);
+        ASSERT_EQ(mEleStream.is_open(), true) << "Failed to open " << GetParam();
+
+        struct stat buf;
+        status_t status = stat(mInputFileName.c_str(), &buf);
+        ASSERT_EQ(status, 0) << "Failed to get properties of input file: " << GetParam();
+        mFileSize = buf.st_size;
+        ALOGI("Size of the input file %s = %zu", GetParam().c_str(), mFileSize);
+    }
+
+    string mInputFileName;
+    size_t mFileSize;
+    ifstream mEleStream;
+};
+
+class SRTDescriptionTest : public TimedTextUnitTest {
+  public:
+    virtual void SetUp() override { TimedTextUnitTest::SetUp(); }
+};
+
+class Text3GPPDescriptionTest : public TimedTextUnitTest {
+  public:
+    virtual void SetUp() override { TimedTextUnitTest::SetUp(); }
+};
+
+TEST_P(SRTDescriptionTest, extractSRTDescriptionTest) {
+    char data[mFileSize];
+    mEleStream.read(data, sizeof(data));
+    ASSERT_EQ(mEleStream.gcount(), mFileSize);
+
+    Parcel parcel;
+    int32_t flag = TextDescriptions::OUT_OF_BAND_TEXT_SRT | TextDescriptions::LOCAL_DESCRIPTIONS;
+    status_t status = TextDescriptions::getParcelOfDescriptions((const uint8_t *)data, mFileSize,
+                                                                flag, kStartTimeMs, &parcel);
+    ASSERT_EQ(status, 0) << "getParcelOfDescriptions returned error";
+    ALOGI("Size of the Parcel: %zu", parcel.dataSize());
+    ASSERT_GT(parcel.dataSize(), 0) << "Parcel is empty";
+
+    parcel.setDataPosition(0);
+    int32_t key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_LOCAL_SETTING) << "Parcel has invalid key";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_START_TIME) << "Parcel has invalid start time key";
+    ASSERT_EQ(parcel.readInt32(), kStartTimeMs) << "Parcel has invalid timings";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_STRUCT_TEXT) << "Parcel has invalid struct text key";
+    ASSERT_EQ(parcel.readInt32(), mFileSize) << "Parcel has invalid text data";
+    int32_t fileSize = parcel.readInt32();
+    ASSERT_EQ(fileSize, mFileSize) << "Parcel has invalid file size value";
+    uint8_t tmpData[fileSize];
+    status = parcel.read((void *)tmpData, fileSize);
+    ASSERT_EQ(status, 0) << "Failed to read the data from parcel";
+    // To make sure end of parcel is reached
+    ASSERT_EQ(parcel.dataAvail(), 0) << "Parcel has some data left to read";
+}
+
+// This test uses the properties of tx3g box mentioned in 3GPP Timed Text Format
+// Specification#: 26.245 / Section: 5.16(Sample Description Format)
+// https://www.3gpp.org/ftp/Specs/archive/26_series/26.245/
+
+TEST_P(Text3GPPDescriptionTest, Text3GPPGlobalDescriptionTest) {
+    char data[mFileSize];
+    mEleStream.read(data, sizeof(data));
+    ASSERT_EQ(mEleStream.gcount(), mFileSize);
+
+    const uint8_t *tmpData = (const uint8_t *)data;
+    int32_t remaining = mFileSize;
+    FontInfo fontInfo;
+    vector<FontRecord> fontRecordEntries;
+
+    // Skipping the bytes containing information about the type of subbox(tx3g)
+    tmpData += 16;
+    remaining -= 16;
+
+    fontInfo.displayFlag = U32_AT(tmpData);
+    ALOGI("Display flag: %d", fontInfo.displayFlag);
+    fontInfo.horizontalJustification = tmpData[4];
+    ALOGI("Horizontal Justification: %d", fontInfo.horizontalJustification);
+    fontInfo.verticalJustification = tmpData[5];
+    ALOGI("Vertical Justification: %d", fontInfo.verticalJustification);
+    fontInfo.rgbaBackground =
+            *(tmpData + 6) << 24 | *(tmpData + 7) << 16 | *(tmpData + 8) << 8 | *(tmpData + 9);
+    ALOGI("rgba value of background: %d", fontInfo.rgbaBackground);
+
+    tmpData += 10;
+    remaining -= 10;
+
+    if (remaining >= 8) {
+        fontInfo.leftPos = U16_AT(tmpData);
+        ALOGI("Left: %d", fontInfo.leftPos);
+        fontInfo.topPos = U16_AT(tmpData + 2);
+        ALOGI("Top: %d", fontInfo.topPos);
+        fontInfo.bottomPos = U16_AT(tmpData + 4);
+        ALOGI("Bottom: %d", fontInfo.bottomPos);
+        fontInfo.rightPos = U16_AT(tmpData + 6);
+        ALOGI("Right: %d", fontInfo.rightPos);
+
+        tmpData += 8;
+        remaining -= 8;
+
+        if (remaining >= 12) {
+            fontInfo.startchar = U16_AT(tmpData);
+            ALOGI("Start character: %d", fontInfo.startchar);
+            fontInfo.endChar = U16_AT(tmpData + 2);
+            ALOGI("End character: %d", fontInfo.endChar);
+            fontInfo.fontId = U16_AT(tmpData + 4);
+            ALOGI("Value of font Identifier: %d", fontInfo.fontId);
+            fontInfo.faceStyle = *(tmpData + 6);
+            ALOGI("Face style flag : %d", fontInfo.faceStyle);
+            fontInfo.fontSize = *(tmpData + 7);
+            ALOGI("Size of the font: %d", fontInfo.fontSize);
+            fontInfo.rgbaText = *(tmpData + 8) << 24 | *(tmpData + 9) << 16 | *(tmpData + 10) << 8 |
+                                *(tmpData + 11);
+            ALOGI("rgba value of the text: %d", fontInfo.rgbaText);
+
+            tmpData += 12;
+            remaining -= 12;
+
+            if (remaining >= 10) {
+                // Skipping the bytes containing information about the type of subbox(ftab)
+                fontInfo.entryCount = U16_AT(tmpData + 8);
+                ALOGI("Value of entry count: %d", fontInfo.entryCount);
+
+                tmpData += 10;
+                remaining -= 10;
+
+                for (int32_t i = 0; i < fontInfo.entryCount; i++) {
+                    if (remaining < 3) break;
+                    int32_t tempFontID = U16_AT(tmpData);
+                    ALOGI("Font Id: %d", tempFontID);
+                    int32_t tempFontNameLength = *(tmpData + 2);
+                    ALOGI("Length of font name: %d", tempFontNameLength);
+
+                    tmpData += 3;
+                    remaining -= 3;
+
+                    if (remaining < tempFontNameLength) break;
+                    const uint8_t *tmpFont = tmpData;
+                    char *tmpFontName = strndup((const char *)tmpFont, tempFontNameLength);
+                    ASSERT_NE(tmpFontName, nullptr) << "Font Name is null";
+                    ALOGI("FontName = %s", tmpFontName);
+                    free(tmpFontName);
+                    tmpData += tempFontNameLength;
+                    remaining -= tempFontNameLength;
+                    fontRecordEntries.push_back({tempFontID, tempFontNameLength, tmpFont});
+                }
+            }
+        }
+    }
+
+    Parcel parcel;
+    int32_t flag = TextDescriptions::IN_BAND_TEXT_3GPP | TextDescriptions::GLOBAL_DESCRIPTIONS;
+    status_t status = TextDescriptions::getParcelOfDescriptions((const uint8_t *)data, mFileSize,
+                                                                flag, kStartTimeMs, &parcel);
+    ASSERT_EQ(status, 0) << "getParcelOfDescriptions returned error";
+    ALOGI("Size of the Parcel: %zu", parcel.dataSize());
+    ASSERT_GT(parcel.dataSize(), 0) << "Parcel is empty";
+
+    parcel.setDataPosition(0);
+    int32_t key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_GLOBAL_SETTING) << "Parcel has invalid key";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_DISPLAY_FLAGS) << "Parcel has invalid DISPLAY FLAGS Key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.displayFlag)
+            << "Parcel has invalid value of display flag";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_STRUCT_JUSTIFICATION) << "Parcel has invalid STRUCT JUSTIFICATION key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.horizontalJustification)
+            << "Parcel has invalid value of Horizontal justification";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.verticalJustification)
+            << "Parcel has invalid value of Vertical justification";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_BACKGROUND_COLOR_RGBA) << "Parcel has invalid BACKGROUND COLOR key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.rgbaBackground)
+            << "Parcel has invalid rgba background color value";
+
+    if (parcel.dataAvail() == 0) {
+        ALOGV("Completed reading the parcel");
+        return;
+    }
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_STRUCT_TEXT_POS) << "Parcel has invalid STRUCT TEXT POSITION key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.leftPos)
+            << "Parcel has invalid rgba background color value";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.topPos)
+            << "Parcel has invalid rgba background color value";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.bottomPos)
+            << "Parcel has invalid rgba background color value";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.rightPos)
+            << "Parcel has invalid rgba background color value";
+
+    if (parcel.dataAvail() == 0) {
+        ALOGV("Completed reading the parcel");
+        return;
+    }
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_STRUCT_STYLE_LIST) << "Parcel has invalid STRUCT STYLE LIST key";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_START_CHAR) << "Parcel has invalid START CHAR key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.startchar)
+            << "Parcel has invalid value of start character";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_END_CHAR) << "Parcel has invalid END CHAR key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.endChar) << "Parcel has invalid value of end character";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_FONT_ID) << "Parcel has invalid FONT ID key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.fontId) << "Parcel has invalid value of font Id";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_STYLE_FLAGS) << "Parcel has invalid STYLE FLAGS key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.faceStyle) << "Parcel has invalid value of style flags";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_FONT_SIZE) << "Parcel has invalid FONT SIZE key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.fontSize) << "Parcel has invalid value of font size";
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_TEXT_COLOR_RGBA) << "Parcel has invalid TEXT COLOR RGBA key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.rgbaText) << "Parcel has invalid rgba text color value";
+
+    if (parcel.dataAvail() == 0) {
+        ALOGV("Completed reading the parcel");
+        return;
+    }
+
+    key = parcel.readInt32();
+    ASSERT_EQ(key, KEY_STRUCT_FONT_LIST) << "Parcel has invalid STRUCT FONT LIST key";
+    ASSERT_EQ(parcel.readInt32(), fontInfo.entryCount) << "Parcel has invalid value of entry count";
+    ASSERT_EQ(fontInfo.entryCount, fontRecordEntries.size())
+            << "Array size does not match expected number of entries";
+    for (int32_t i = 0; i < fontInfo.entryCount; i++) {
+        ASSERT_EQ(parcel.readInt32(), fontRecordEntries[i].fontID)
+                << "Parcel has invalid value of font Id";
+        ASSERT_EQ(parcel.readInt32(), fontRecordEntries[i].fontNameLength)
+                << "Parcel has invalid value of font name length";
+        uint8_t fontName[fontRecordEntries[i].fontNameLength];
+        // written with writeByteArray() writes count, then the actual data
+        ASSERT_EQ(parcel.readInt32(), fontRecordEntries[i].fontNameLength);
+        status = parcel.read((void *)fontName, fontRecordEntries[i].fontNameLength);
+        ASSERT_EQ(status, 0) << "Failed to read the font name from parcel";
+        ASSERT_EQ(memcmp(fontName, fontRecordEntries[i].font, fontRecordEntries[i].fontNameLength),
+                  0)
+                << "Parcel has invalid font";
+    }
+    // To make sure end of parcel is reached
+    ASSERT_EQ(parcel.dataAvail(), 0) << "Parcel has some data left to read";
+}
+
+INSTANTIATE_TEST_SUITE_P(TimedTextUnitTestAll, SRTDescriptionTest,
+                         ::testing::Values(("sampleTest1.srt"),
+                                           ("sampleTest2.srt")));
+
+INSTANTIATE_TEST_SUITE_P(TimedTextUnitTestAll, Text3GPPDescriptionTest,
+                         ::testing::Values(("tx3gBox1"),
+                                           ("tx3gBox2")));
+
+int main(int argc, char **argv) {
+    gEnv = new TimedTextTestEnvironment();
+    ::testing::AddGlobalTestEnvironment(gEnv);
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = gEnv->initFromOptions(argc, argv);
+    if (status == 0) {
+        status = RUN_ALL_TESTS();
+        ALOGV("Test result = %d\n", status);
+    }
+    return status;
+}
diff --git a/media/libstagefright/webm/Android.bp b/media/libstagefright/webm/Android.bp
index 2cebe8f..68752cd 100644
--- a/media/libstagefright/webm/Android.bp
+++ b/media/libstagefright/webm/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_static {
     name: "libstagefright_webm",
 
diff --git a/media/libstagefright/webm/tests/Android.bp b/media/libstagefright/webm/tests/Android.bp
index 5183a49..4443766 100644
--- a/media/libstagefright/webm/tests/Android.bp
+++ b/media/libstagefright/webm/tests/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_test {
     name: "WebmFrameThreadUnitTest",
     gtest: true,
diff --git a/media/libstagefright/writer_fuzzers/Android.bp b/media/libstagefright/writer_fuzzers/Android.bp
new file mode 100644
index 0000000..a33b888
--- /dev/null
+++ b/media/libstagefright/writer_fuzzers/Android.bp
@@ -0,0 +1,125 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
+cc_defaults {
+    name: "writer-fuzzerbase-defaults",
+    local_include_dirs: [
+        "include",
+    ],
+    export_include_dirs: [
+        "include",
+    ],
+    static_libs: [
+        "liblog",
+        "libstagefright_foundation",
+        "libstagefright",
+    ],
+    shared_libs: [
+        "libbinder",
+        "libcutils",
+        "libutils",
+    ],
+}
+
+cc_defaults {
+    name: "writer-fuzzer-defaults",
+    defaults: ["writer-fuzzerbase-defaults"],
+    static_libs: [
+        "libwriterfuzzerbase",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
+
+cc_library_static {
+    name: "libwriterfuzzerbase",
+    defaults: ["writer-fuzzerbase-defaults"],
+    srcs: [
+        "WriterFuzzerBase.cpp",
+    ],
+}
+
+cc_fuzz {
+    name: "amrnb_writer_fuzzer",
+    defaults: ["writer-fuzzer-defaults"],
+    srcs: [
+        "amr_writer_fuzzer.cpp",
+    ],
+    cflags: [
+        "-DAMRNB",
+    ],
+}
+
+cc_fuzz {
+    name: "amrwb_writer_fuzzer",
+    defaults: ["writer-fuzzer-defaults"],
+    srcs: [
+        "amr_writer_fuzzer.cpp",
+    ],
+}
+
+cc_fuzz {
+    name : "mpeg4_writer_fuzzer",
+    defaults : ["writer-fuzzer-defaults"],
+    srcs : [
+        "mpeg4_writer_fuzzer.cpp",
+    ],
+    static_libs: [
+        "libstagefright_esds",
+    ],
+}
+
+cc_fuzz {
+    name : "ogg_writer_fuzzer",
+    defaults : ["writer-fuzzer-defaults"],
+    srcs : [
+        "ogg_writer_fuzzer.cpp",
+    ],
+    static_libs: [
+        "libogg",
+    ],
+}
+
+cc_fuzz {
+    name : "webm_writer_fuzzer",
+    defaults : ["writer-fuzzer-defaults"],
+    srcs : [
+        "webm_writer_fuzzer.cpp",
+    ],
+    static_libs: [
+        "libstagefright_webm",
+        "libdatasource",
+    ],
+    include_dirs: [
+        "frameworks/av/media/libstagefright",
+    ],
+}
diff --git a/media/libstagefright/writer_fuzzers/README.md b/media/libstagefright/writer_fuzzers/README.md
new file mode 100644
index 0000000..6f95ecc
--- /dev/null
+++ b/media/libstagefright/writer_fuzzers/README.md
@@ -0,0 +1,100 @@
+# Fuzzer for writers
+
+## Table of contents
++  [libwriterfuzzerbase](#WriterFuzzerBase)
++  [Amr Writer](#amrWriterFuzzer)
++  [MPEG4 Writer](#mpeg4WriterFuzzer)
++  [OGG Writer](#oggWriterFuzzer)
++  [WEBM Writer](#webmWriterFuzzer)
+
+# <a name="WriterFuzzerBase"></a> Fuzzer for libwriterfuzzerbase
+All the writers have a common API - creating a writer, adding a source for
+all the tracks, etc. These common APIs have been abstracted in a base class
+called `WriterFuzzerBase` to ensure code is reused between fuzzer plugins.
+
+## Plugin Design Considerations
+The fuzzer plugin for writers is designed based on the understanding of the
+writer and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+Fuzzer for writers supports the following parameters:
+1. Track Mime (parameter name: `mime`)
+2. Channel Count (parameter name: `channel-count`)
+3. Sample Rate (parameter name: `sample-rate`)
+4. Frame Height (parameter name: `height`)
+5. Frame Width (parameter name: `width`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `mime` | 0. `audio/3gpp` 1. `audio/amr-wb` 2. `audio/vorbis` 3. `audio/opus` 4. `audio/mp4a-latm` 5. `audio/mpeg` 6. `audio/mpeg-L1` 7. `audio/mpeg-L2` 8. `audio/midi` 9. `audio/qcelp` 10. `audio/g711-alaw` 11. `audio/g711-mlaw` 12. `audio/flac` 13. `audio/aac-adts` 14. `audio/gsm` 15. `audio/ac3` 16. `audio/eac3` 17. `audio/eac3-joc` 18. `audio/ac4` 19. `audio/scrambled` 20. `audio/alac` 21. `audio/x-ms-wma` 22. `audio/x-adpcm-ms` 23. `audio/x-adpcm-dvi-ima` 24. `video/avc` 25. `video/hevc` 26. `video/mp4v-es` 27. `video/3gpp` 28. `video/x-vnd.on2.vp8` 29. `video/x-vnd.on2.vp9` 30. `video/av01` 31. `video/mpeg2` 32. `video/dolby-vision` 33. `video/scrambled` 34. `video/divx` 35. `video/divx3` 36. `video/xvid` 37. `video/x-motion-jpeg` 38. `text/3gpp-tt` 39. `application/x-subrip` 40. `text/vtt` 41. `text/cea-608` 42. `text/cea-708` 43. `application/x-id3v4` | All the bits of 2nd byte of data for first track and 11th byte of data for second track and 20th byte of data for third track(if present) modulus 44 |
+| `channel-count` | In the range `0 to INT32_MAX` | All the bits of 3rd byte to 6th bytes of data if first track is audio and 12th to 15th bytes of data if second track is audio |
+| `sample-rate` | In the range `1 to INT32_MAX` | All the bits of 7th byte to 10th bytes of data if first track is audio and 16th to 19th bytes of data if second track is audio |
+| `height` | In the range `0 to INT32_MAX` | All the bits of 3rd byte to 6th bytes of data if first track is video and 12th to 15th bytes of data if second track is video |
+| `width` | In the range `0 to INT32_MAX` | All the bits of 7th byte to 10th bytes of data if first track is video and 16th to 19th bytes of data if second track is video |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+##### Maximize utilization of input data
+The plugin divides the entire input data into frames based on frame markers.
+If no frame marker is found then the entire input data is treated as single frame.
+
+This ensures that the plugin tolerates any kind of input (huge,
+malformed, etc) and thereby increasing the chance of identifying vulnerabilities.
+
+# <a name="amrWriterFuzzer"></a> Fuzzer for Amr Writer
+
+## Plugin Design Considerations
+The fuzzer plugin for AMR writer uses the `WriterFuzzerBase` class and
+implements only the `createWriter` to create the AMR writer class.
+
+##### Other considerations
+ * Two fuzzer binaries - amrnb_writer_fuzzer and amrwb_writer_fuzzer are generated based on the presence of a flag - 'AMRNB'
+
+# <a name="mpeg4WriterFuzzer"></a> Fuzzer for MPEG4 Writer
+
+## Plugin Design Considerations
+The fuzzer plugin for MPEG4 writer uses the `WriterFuzzerBase` class and
+implements only the `createWriter` to create the MPEG4 writer class.
+
+# <a name="oggWriterFuzzer"></a> Fuzzer for OGG Writer
+
+## Plugin Design Considerations
+The fuzzer plugin for OGG writer uses the `WriterFuzzerBase` class and
+implements only the `createWriter` to create the OGG writer class.
+
+# <a name="webmWriterFuzzer"></a> Fuzzer for WEBM Writer
+
+## Plugin Design Considerations
+The fuzzer plugin for WEBM writer uses the `WriterFuzzerBase` class and
+implements only the `createWriter` to create the WEBM writer class.
+
+## Build
+
+This describes steps to build writer fuzzer binaries.
+
+### Android
+
+`*` = amrnb/amrwb/mpeg4/ogg/webm
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) *_writer_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some media files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/*_writer_fuzzer/*_writer_fuzzer CORPUS_DIR
+```
+
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/media/libstagefright/writer_fuzzers/WriterFuzzerBase.cpp b/media/libstagefright/writer_fuzzers/WriterFuzzerBase.cpp
new file mode 100644
index 0000000..ee7af70
--- /dev/null
+++ b/media/libstagefright/writer_fuzzers/WriterFuzzerBase.cpp
@@ -0,0 +1,291 @@
+/*
+ * Copyright (C) 2020 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 <utils/Log.h>
+
+#include "WriterFuzzerBase.h"
+
+using namespace android;
+
+/**
+ * Buffer source implementations to parse input file
+ */
+
+uint32_t WriterFuzzerBase::BufferSource::getNumTracks() {
+    uint32_t numTracks = 0;
+    if (mSize > sizeof(uint8_t)) {
+        numTracks = min(mData[0], kMaxTrackCount);
+        mReadIndex += sizeof(uint8_t);
+    }
+    return numTracks;
+}
+
+bool WriterFuzzerBase::BufferSource::searchForMarker(size_t startIndex) {
+    while (true) {
+        if (isMarker()) {
+            return true;
+        }
+        --mReadIndex;
+        if (mReadIndex < startIndex) {
+            break;
+        }
+    }
+    return false;
+}
+
+ConfigFormat WriterFuzzerBase::BufferSource::getConfigFormat(int32_t trackIndex) {
+    return mParams[trackIndex];
+}
+
+int32_t WriterFuzzerBase::BufferSource::getNumCsds(int32_t trackIndex) {
+    return mNumCsds[trackIndex];
+}
+
+vector<FrameData> &WriterFuzzerBase::BufferSource::getFrameList(int32_t trackIndex) {
+    return mFrameList[trackIndex];
+}
+
+void WriterFuzzerBase::BufferSource::getFrameInfo() {
+    size_t readIndexStart = mReadIndex;
+    if (mSize - mReadIndex > kMarkerSize + kMarkerSuffixSize) {
+        bool isFrameAvailable = true;
+        size_t bytesRemaining = mSize;
+        mReadIndex = mSize - kMarkerSize;
+        while (isFrameAvailable) {
+            isFrameAvailable = searchForMarker(readIndexStart);
+            if (isFrameAvailable) {
+                size_t location = mReadIndex + kMarkerSize;
+                if (location + kMarkerSuffixSize >= bytesRemaining) {
+                    break;
+                }
+                bool isCSD = isCSDMarker(location);
+                location += kMarkerSuffixSize;
+                uint8_t *framePtr = const_cast<uint8_t *>(&mData[location]);
+                size_t frameSize = bytesRemaining - location, bufferSize = 0;
+                uint8_t trackIndex = framePtr[0] % kMaxTrackCount;
+                ++framePtr;
+                uint8_t flags = 0;
+                int64_t pts = 0;
+                if (isCSD && frameSize > 1) {
+                    flags |= kCodecConfigFlag;
+                    pts = 0;
+                    ++mNumCsds[trackIndex];
+                    bufferSize = frameSize - 1;
+                } else if (frameSize > sizeof(uint8_t) + sizeof(int64_t) + 1) {
+                    flags = flagTypes[framePtr[0] % size(flagTypes)];
+                    ++framePtr;
+                    copy(framePtr, framePtr + sizeof(int64_t), reinterpret_cast<uint8_t *>(&pts));
+                    framePtr += sizeof(int64_t);
+                    bufferSize = frameSize - (sizeof(uint8_t) + sizeof(int64_t)) - 1;
+                } else {
+                    break;
+                }
+                mFrameList[trackIndex].insert(mFrameList[trackIndex].begin(),
+                                              FrameData{bufferSize, flags, pts, framePtr});
+                bytesRemaining -= (frameSize + kMarkerSize + kMarkerSuffixSize);
+                --mReadIndex;
+            }
+        }
+    }
+    if (mFrameList[0].empty() && mFrameList[1].empty()) {
+        /**
+         * Scenario where input data does not contain the custom frame markers.
+         * Hence feed the entire data as single frame.
+         */
+        mFrameList[0].emplace_back(FrameData{mSize - readIndexStart, 0, 0, mData + readIndexStart});
+    }
+}
+bool WriterFuzzerBase::BufferSource::getTrackInfo(int32_t trackIndex) {
+    if (mSize <= mReadIndex + sizeof(uint8_t)) {
+        return false;
+    }
+    size_t mimeTypeIdx = mData[mReadIndex] % kSupportedMimeTypes;
+    char *mime = (char *)supportedMimeTypes[mimeTypeIdx].c_str();
+    mParams[trackIndex].mime = mime;
+    mReadIndex += sizeof(uint8_t);
+
+    if (mSize > mReadIndex + 2 * sizeof(int32_t)) {
+        if (!strncmp(mime, "audio/", 6)) {
+            copy(mData + mReadIndex, mData + mReadIndex + sizeof(int32_t),
+                 reinterpret_cast<char *>(&mParams[trackIndex].channelCount));
+            copy(mData + mReadIndex + sizeof(int32_t), mData + mReadIndex + 2 * sizeof(int32_t),
+                 reinterpret_cast<char *>(&mParams[trackIndex].sampleRate));
+        } else if (!strncmp(mime, "video/", 6)) {
+            copy(mData + mReadIndex, mData + mReadIndex + sizeof(int32_t),
+                 reinterpret_cast<char *>(&mParams[trackIndex].height));
+            copy(mData + mReadIndex + sizeof(int32_t), mData + mReadIndex + 2 * sizeof(int32_t),
+                 reinterpret_cast<char *>(&mParams[trackIndex].width));
+        }
+        mReadIndex += 2 * sizeof(int32_t);
+    } else {
+        if (strncmp(mime, "text/", 5) && strncmp(mime, "application/", 12)) {
+            return false;
+        }
+    }
+    return true;
+}
+
+void writeHeaderBuffers(vector<FrameData> &bufferInfo, sp<AMessage> &format, int32_t numCsds) {
+    char csdName[kMaxCSDStrlen];
+    for (int csdId = 0; csdId < numCsds; ++csdId) {
+        int32_t flags = bufferInfo[csdId].flags;
+        if (flags == kCodecConfigFlag) {
+            sp<ABuffer> csdBuffer =
+                ABuffer::CreateAsCopy((void *)bufferInfo[csdId].buf, bufferInfo[csdId].size);
+            if (csdBuffer.get() == nullptr || csdBuffer->base() == nullptr) {
+                return;
+            }
+            snprintf(csdName, sizeof(csdName), "csd-%d", csdId);
+            format->setBuffer(csdName, csdBuffer);
+        }
+    }
+}
+
+bool WriterFuzzerBase::createOutputFile() {
+    mFd = memfd_create(mOutputFileName.c_str(), MFD_ALLOW_SEALING);
+    if (mFd == -1) {
+        return false;
+    }
+    return true;
+}
+
+void WriterFuzzerBase::addWriterSource(int32_t trackIndex) {
+    ConfigFormat params = mBufferSource->getConfigFormat(trackIndex);
+    sp<AMessage> format = new AMessage;
+    format->setString("mime", params.mime);
+    if (!strncmp(params.mime, "audio/", 6)) {
+        if (!strncmp(params.mime, "audio/3gpp", 10)) {
+            params.channelCount = 1;
+            params.sampleRate = 8000;
+        } else if (!strncmp(params.mime, "audio/amr-wb", 12)) {
+            params.channelCount = 1;
+            params.sampleRate = 16000;
+        } else {
+            params.sampleRate = max(1, params.sampleRate);
+        }
+        format->setInt32("channel-count", params.channelCount);
+        format->setInt32("sample-rate", params.sampleRate);
+    } else if (!strncmp(params.mime, "video/", 6)) {
+        format->setInt32("width", params.width);
+        format->setInt32("height", params.height);
+    }
+    int32_t numCsds = mBufferSource->getNumCsds(trackIndex);
+    if (numCsds) {
+        vector<FrameData> mFrames = mBufferSource->getFrameList(trackIndex);
+        writeHeaderBuffers(mFrames, format, numCsds);
+    }
+    sp<MetaData> trackMeta = new MetaData;
+    convertMessageToMetaData(format, trackMeta);
+    mCurrentTrack[trackIndex] = new MediaAdapter(trackMeta);
+    mWriter->addSource(mCurrentTrack[trackIndex]);
+}
+
+void WriterFuzzerBase::start() {
+    mFileMeta->setInt32(kKeyRealTimeRecording, false);
+    mWriter->start(mFileMeta.get());
+}
+
+void WriterFuzzerBase::sendBuffersToWriter(sp<MediaAdapter> &currentTrack, int32_t trackIndex,
+                                           int32_t startFrameIndex, int32_t endFrameIndex) {
+    vector<FrameData> bufferInfo = mBufferSource->getFrameList(trackIndex);
+    for (int idx = startFrameIndex; idx < endFrameIndex; ++idx) {
+        sp<ABuffer> buffer = new ABuffer((void *)bufferInfo[idx].buf, bufferInfo[idx].size);
+        MediaBuffer *mediaBuffer = new MediaBuffer(buffer);
+
+        // Released in MediaAdapter::signalBufferReturned().
+        mediaBuffer->add_ref();
+        mediaBuffer->set_range(buffer->offset(), buffer->size());
+        MetaDataBase &sampleMetaData = mediaBuffer->meta_data();
+        sampleMetaData.setInt64(kKeyTime, bufferInfo[idx].timeUs);
+
+        // Just set the kKeyDecodingTime as the presentation time for now.
+        sampleMetaData.setInt64(kKeyDecodingTime, bufferInfo[idx].timeUs);
+        if (bufferInfo[idx].flags == SampleFlag::SYNC_FLAG) {
+            sampleMetaData.setInt32(kKeyIsSyncFrame, true);
+        }
+
+        // This pushBuffer will wait until the mediaBuffer is consumed.
+        currentTrack->pushBuffer(mediaBuffer);
+    }
+}
+
+void WriterFuzzerBase::sendBuffersInterleave(int32_t numTracks, uint8_t numBuffersInterleave) {
+    int32_t currentFrameIndex[numTracks], remainingNumFrames[numTracks], numTrackFramesDone;
+    for (int32_t idx = 0; idx < numTracks; ++idx) {
+        currentFrameIndex[idx] = mBufferSource->getNumCsds(idx);
+        remainingNumFrames[idx] = mBufferSource->getFrameList(idx).size() - currentFrameIndex[idx];
+    }
+    do {
+        numTrackFramesDone = numTracks;
+        for (int32_t idx = 0; idx < numTracks; ++idx) {
+            if (remainingNumFrames[idx] > 0) {
+                int32_t numFramesInterleave =
+                    min(remainingNumFrames[idx], static_cast<int32_t>(numBuffersInterleave));
+                sendBuffersToWriter(mCurrentTrack[idx], idx, currentFrameIndex[idx],
+                                    currentFrameIndex[idx] + numFramesInterleave);
+                currentFrameIndex[idx] += numFramesInterleave;
+                remainingNumFrames[idx] -= numFramesInterleave;
+                --numTrackFramesDone;
+            }
+        }
+    } while (numTrackFramesDone < numTracks);
+}
+
+void WriterFuzzerBase::initFileWriterAndProcessData(const uint8_t *data, size_t size) {
+    if (!createOutputFile()) {
+        return;
+    }
+    if (!createWriter()) {
+        return;
+    }
+
+    if (size < 1) {
+        return;
+    }
+    uint8_t numBuffersInterleave = (data[0] == 0 ? 1 : data[0]);
+    ++data;
+    --size;
+
+    mBufferSource = new BufferSource(data, size);
+    if (!mBufferSource) {
+        return;
+    }
+    mNumTracks = mBufferSource->getNumTracks();
+    if (mNumTracks > 0) {
+        for (int32_t idx = 0; idx < mNumTracks; ++idx) {
+            if (!mBufferSource->getTrackInfo(idx)) {
+                if (idx == 0) {
+                    delete mBufferSource;
+                    return;
+                }
+                mNumTracks = idx;
+                break;
+            }
+        }
+        mBufferSource->getFrameInfo();
+        for (int32_t idx = 0; idx < mNumTracks; ++idx) {
+            addWriterSource(idx);
+        }
+        start();
+        sendBuffersInterleave(mNumTracks, numBuffersInterleave);
+        for (int32_t idx = 0; idx < mNumTracks; ++idx) {
+            if (mCurrentTrack[idx]) {
+                mCurrentTrack[idx]->stop();
+            }
+        }
+    }
+    delete mBufferSource;
+    mWriter->stop();
+}
diff --git a/media/libstagefright/writer_fuzzers/amr_writer_fuzzer.cpp b/media/libstagefright/writer_fuzzers/amr_writer_fuzzer.cpp
new file mode 100644
index 0000000..bbb6f9f
--- /dev/null
+++ b/media/libstagefright/writer_fuzzers/amr_writer_fuzzer.cpp
@@ -0,0 +1,50 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "WriterFuzzerBase.h"
+
+#include <media/stagefright/AMRWriter.h>
+
+using namespace android;
+
+class AmrWriterFuzzer : public WriterFuzzerBase {
+   public:
+    bool createWriter();
+};
+
+bool AmrWriterFuzzer::createWriter() {
+    mWriter = new AMRWriter(mFd);
+    if (!mWriter) {
+        return false;
+    }
+    mFileMeta = new MetaData;
+#ifdef AMRNB
+    mFileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_AMR_NB);
+#else
+    mFileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_AMR_WB);
+#endif
+    return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    AmrWriterFuzzer writerFuzzer;
+    writerFuzzer.initFileWriterAndProcessData(data, size);
+    return 0;
+}
diff --git a/media/libstagefright/writer_fuzzers/include/WriterFuzzerBase.h b/media/libstagefright/writer_fuzzers/include/WriterFuzzerBase.h
new file mode 100644
index 0000000..4315322
--- /dev/null
+++ b/media/libstagefright/writer_fuzzers/include/WriterFuzzerBase.h
@@ -0,0 +1,211 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#ifndef __WRITER_FUZZER_BASE_H__
+#define __WRITER_FUZZER_BASE_H__
+
+#include <media/stagefright/MediaAdapter.h>
+#include <media/stagefright/MediaWriter.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/Utils.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/AMessage.h>
+#include <algorithm>
+#include <cstring>
+#include <vector>
+
+using namespace std;
+
+constexpr uint32_t kMimeSize = 128;
+constexpr uint8_t kMaxTrackCount = 3;
+constexpr uint32_t kMaxCSDStrlen = 16;
+constexpr uint32_t kCodecConfigFlag = 32;
+
+namespace android {
+
+struct ConfigFormat {
+    char* mime;
+    int32_t width;
+    int32_t height;
+    int32_t sampleRate;
+    int32_t channelCount;
+};
+
+struct FrameData {
+    size_t size;
+    uint8_t flags;
+    int64_t timeUs;
+    const uint8_t* buf;
+};
+
+static string supportedMimeTypes[] = {"audio/3gpp",
+                                      "audio/amr-wb",
+                                      "audio/vorbis",
+                                      "audio/opus",
+                                      "audio/mp4a-latm",
+                                      "audio/mpeg",
+                                      "audio/mpeg-L1",
+                                      "audio/mpeg-L2",
+                                      "audio/midi",
+                                      "audio/qcelp",
+                                      "audio/g711-alaw",
+                                      "audio/g711-mlaw",
+                                      "audio/flac",
+                                      "audio/aac-adts",
+                                      "audio/gsm",
+                                      "audio/ac3",
+                                      "audio/eac3",
+                                      "audio/eac3-joc",
+                                      "audio/ac4",
+                                      "audio/scrambled",
+                                      "audio/alac",
+                                      "audio/x-ms-wma",
+                                      "audio/x-adpcm-ms",
+                                      "audio/x-adpcm-dvi-ima",
+                                      "video/avc",
+                                      "video/hevc",
+                                      "video/mp4v-es",
+                                      "video/3gpp",
+                                      "video/x-vnd.on2.vp8",
+                                      "video/x-vnd.on2.vp9",
+                                      "video/av01",
+                                      "video/mpeg2",
+                                      "video/dolby-vision",
+                                      "video/scrambled",
+                                      "video/divx",
+                                      "video/divx3",
+                                      "video/xvid",
+                                      "video/x-motion-jpeg",
+                                      "text/3gpp-tt",
+                                      "application/x-subrip",
+                                      "text/vtt",
+                                      "text/cea-608",
+                                      "text/cea-708",
+                                      "application/x-id3v4"};
+
+enum SampleFlag {
+    DEFAULT_FLAG = 0,
+    SYNC_FLAG = 1,
+    ENCRYPTED_FLAG = 2,
+};
+
+static uint8_t flagTypes[] = {SampleFlag::DEFAULT_FLAG, SampleFlag::SYNC_FLAG,
+                              SampleFlag::ENCRYPTED_FLAG};
+
+class WriterFuzzerBase {
+   public:
+    WriterFuzzerBase() = default;
+    virtual ~WriterFuzzerBase() {
+        if (mFileMeta) {
+            mFileMeta.clear();
+            mFileMeta = nullptr;
+        }
+        if (mWriter) {
+            mWriter.clear();
+            mWriter = nullptr;
+        }
+        for (int32_t idx = 0; idx < kMaxTrackCount; ++idx) {
+            if (mCurrentTrack[idx]) {
+                mCurrentTrack[idx]->stop();
+                mCurrentTrack[idx].clear();
+                mCurrentTrack[idx] = nullptr;
+            }
+        }
+        close(mFd);
+    };
+
+    /** Function to create the media writer component.
+     * To be implemented by the derived class.
+     */
+    virtual bool createWriter() = 0;
+
+    /** Parent class functions to be reused by derived class.
+     * These are common for all media writer components.
+     */
+    bool createOutputFile();
+
+    void addWriterSource(int32_t trackIndex);
+
+    void start();
+
+    void sendBuffersToWriter(sp<MediaAdapter>& currentTrack, int32_t trackIndex,
+                             int32_t startFrameIndex, int32_t endFrameIndex);
+
+    void sendBuffersInterleave(int32_t numTracks, uint8_t numBuffersInterleave);
+
+    void initFileWriterAndProcessData(const uint8_t* data, size_t size);
+
+   protected:
+    class BufferSource {
+       public:
+        BufferSource(const uint8_t* data, size_t size) : mData(data), mSize(size), mReadIndex(0) {}
+        ~BufferSource() {
+            mData = nullptr;
+            mSize = 0;
+            mReadIndex = 0;
+            for (int32_t idx = 0; idx < kMaxTrackCount; ++idx) {
+                mFrameList[idx].clear();
+            }
+        }
+        uint32_t getNumTracks();
+        bool getTrackInfo(int32_t trackIndex);
+        void getFrameInfo();
+        ConfigFormat getConfigFormat(int32_t trackIndex);
+        int32_t getNumCsds(int32_t trackIndex);
+        vector<FrameData>& getFrameList(int32_t trackIndex);
+
+       private:
+        bool isMarker() { return (memcmp(&mData[mReadIndex], kMarker, kMarkerSize) == 0); }
+
+        bool isCSDMarker(size_t position) {
+            return (memcmp(&mData[position], kCsdMarkerSuffix, kMarkerSuffixSize) == 0);
+        }
+
+        bool searchForMarker(size_t startIndex);
+
+        const uint8_t* mData = nullptr;
+        size_t mSize = 0;
+        size_t mReadIndex = 0;
+        ConfigFormat mParams[kMaxTrackCount] = {};
+        int32_t mNumCsds[kMaxTrackCount] = {0};
+        vector<FrameData> mFrameList[kMaxTrackCount];
+
+        static constexpr int kSupportedMimeTypes = size(supportedMimeTypes);
+        static constexpr uint8_t kMarker[] = "_MARK";
+        static constexpr uint8_t kCsdMarkerSuffix[] = "_H_";
+        static constexpr uint8_t kFrameMarkerSuffix[] = "_F_";
+        // All markers should be 5 bytes long ( sizeof '_MARK' which is 5)
+        static constexpr size_t kMarkerSize = (sizeof(kMarker) - 1);
+        // All marker types should be 3 bytes long ('_H_', '_F_')
+        static constexpr size_t kMarkerSuffixSize = 3;
+    };
+
+    BufferSource* mBufferSource = nullptr;
+    int32_t mFd = -1;
+    uint32_t mNumTracks = 0;
+    string mOutputFileName = "writer.out";
+    sp<MediaWriter> mWriter = nullptr;
+    sp<MetaData> mFileMeta = nullptr;
+    sp<MediaAdapter> mCurrentTrack[kMaxTrackCount] = {};
+};
+
+}  // namespace android
+
+#endif  // __WRITER_FUZZER_BASE_H__
diff --git a/media/libstagefright/writer_fuzzers/mpeg4_writer_fuzzer.cpp b/media/libstagefright/writer_fuzzers/mpeg4_writer_fuzzer.cpp
new file mode 100644
index 0000000..99bd2b6
--- /dev/null
+++ b/media/libstagefright/writer_fuzzers/mpeg4_writer_fuzzer.cpp
@@ -0,0 +1,46 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "WriterFuzzerBase.h"
+
+#include <media/stagefright/MPEG4Writer.h>
+
+using namespace android;
+
+class Mpeg4WriterFuzzer : public WriterFuzzerBase {
+   public:
+    bool createWriter();
+};
+
+bool Mpeg4WriterFuzzer::createWriter() {
+    mWriter = new MPEG4Writer(mFd);
+    if (!mWriter) {
+        return false;
+    }
+    mFileMeta = new MetaData;
+    mFileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_MPEG_4);
+    return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    Mpeg4WriterFuzzer writerFuzzer;
+    writerFuzzer.initFileWriterAndProcessData(data, size);
+    return 0;
+}
diff --git a/media/libstagefright/writer_fuzzers/ogg_writer_fuzzer.cpp b/media/libstagefright/writer_fuzzers/ogg_writer_fuzzer.cpp
new file mode 100644
index 0000000..ae9c94c
--- /dev/null
+++ b/media/libstagefright/writer_fuzzers/ogg_writer_fuzzer.cpp
@@ -0,0 +1,46 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "WriterFuzzerBase.h"
+
+#include <media/stagefright/OggWriter.h>
+
+using namespace android;
+
+class OGGWriterFuzzer : public WriterFuzzerBase {
+   public:
+    bool createWriter();
+};
+
+bool OGGWriterFuzzer::createWriter() {
+    mWriter = new OggWriter(mFd);
+    if (!mWriter) {
+        return false;
+    }
+    mFileMeta = new MetaData;
+    mFileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_OGG);
+    return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    OGGWriterFuzzer writerFuzzer;
+    writerFuzzer.initFileWriterAndProcessData(data, size);
+    return 0;
+}
diff --git a/media/libstagefright/writer_fuzzers/webm_writer_fuzzer.cpp b/media/libstagefright/writer_fuzzers/webm_writer_fuzzer.cpp
new file mode 100644
index 0000000..0a91b72
--- /dev/null
+++ b/media/libstagefright/writer_fuzzers/webm_writer_fuzzer.cpp
@@ -0,0 +1,46 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include "WriterFuzzerBase.h"
+
+#include <webm/WebmWriter.h>
+
+using namespace android;
+
+class WEBMWriterFuzzer : public WriterFuzzerBase {
+   public:
+    bool createWriter();
+};
+
+bool WEBMWriterFuzzer::createWriter() {
+    mWriter = new WebmWriter(mFd);
+    if (!mWriter) {
+        return false;
+    }
+    mFileMeta = new MetaData;
+    mFileMeta->setInt32(kKeyFileType, output_format::OUTPUT_FORMAT_WEBM);
+    return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    WEBMWriterFuzzer writerFuzzer;
+    writerFuzzer.initFileWriterAndProcessData(data, size);
+    return 0;
+}
diff --git a/media/libstagefright/xmlparser/Android.bp b/media/libstagefright/xmlparser/Android.bp
index 7ed0e88..055dd80 100644
--- a/media/libstagefright/xmlparser/Android.bp
+++ b/media/libstagefright/xmlparser/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_library_headers {
     name: "libstagefright_xmlparser_headers",
     export_include_dirs: ["include"],
@@ -49,4 +58,3 @@
     srcs: ["media_codecs.xsd"],
     package_name: "media.codecs",
 }
-
diff --git a/media/libstagefright/xmlparser/MediaCodecsXmlParser.cpp b/media/libstagefright/xmlparser/MediaCodecsXmlParser.cpp
index a232150..dbdb43c 100644
--- a/media/libstagefright/xmlparser/MediaCodecsXmlParser.cpp
+++ b/media/libstagefright/xmlparser/MediaCodecsXmlParser.cpp
@@ -493,7 +493,7 @@
       mPath(path),
       mStatus(NO_INIT) {
     // determine href_base
-    std::string::size_type end = path.rfind("/");
+    std::string::size_type end = path.rfind('/');
     if (end != std::string::npos) {
         mHrefBase = path.substr(0, end + 1);
     }
@@ -1525,7 +1525,7 @@
                 nodeInfo.attributeList.push_back(Attribute{"rank", rank});
             }
             nodeList->insert(std::make_pair(
-                    std::move(order), std::move(nodeInfo)));
+                    order, std::move(nodeInfo)));
         }
     }
 }
diff --git a/media/libstagefright/xmlparser/test/Android.bp b/media/libstagefright/xmlparser/test/Android.bp
new file mode 100644
index 0000000..2fd577c
--- /dev/null
+++ b/media/libstagefright/xmlparser/test/Android.bp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2020 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 {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
+cc_test {
+    name: "XMLParserTest",
+    gtest: true,
+
+    srcs: [
+        "XMLParserTest.cpp",
+    ],
+
+    shared_libs: [
+        "liblog",
+        "libstagefright_xmlparser",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+
+    data: [":xmlparsertest_test_files",],
+
+    sanitize: {
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+    },
+}
+
+filegroup {
+    name: "xmlparsertest_test_files",
+    srcs: [
+        "testdata/media_codecs_unit_test.xml",
+        "testdata/media_codecs_unit_test_caller.xml",
+    ],
+}
diff --git a/media/libstagefright/xmlparser/test/AndroidTest.xml b/media/libstagefright/xmlparser/test/AndroidTest.xml
new file mode 100644
index 0000000..2e11b1b
--- /dev/null
+++ b/media/libstagefright/xmlparser/test/AndroidTest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+<configuration description="Test module config for xml parser unit test">
+    <option name="test-suite-tag" value="XMLParserTest" />
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push" value="media_codecs_unit_test.xml->/data/local/tmp/media_codecs_unit_test.xml" />
+        <option name="push" value="media_codecs_unit_test_caller.xml->/data/local/tmp/media_codecs_unit_test_caller.xml" />
+        <option name="push" value="XMLParserTest->/data/local/tmp/XMLParserTest" />
+    </target_preparer>
+   <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="XMLParserTest" />
+    </test>
+</configuration>
diff --git a/media/libstagefright/xmlparser/test/README.md b/media/libstagefright/xmlparser/test/README.md
new file mode 100644
index 0000000..e9363fd
--- /dev/null
+++ b/media/libstagefright/xmlparser/test/README.md
@@ -0,0 +1,33 @@
+## Media Testing ##
+---
+#### XML Parser
+The XMLParser Test Suite validates the XMLParser available in libstagefright.
+
+Run the following steps to build the test suite:
+```
+m XMLParserTest
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+```
+adb push ${OUT}/data/nativetest64/XMLParserTest/XMLParserTest /data/local/tmp/
+```
+
+To test 32-bit binary push binaries from nativetest.
+```
+adb push ${OUT}/data/nativetest/XMLParserTest/XMLParserTest /data/local/tmp/
+```
+
+usage: XMLParserTest
+```
+adb shell /data/local/tmp/XMLParserTest
+```
+Alternatively, the test can also be run using atest command.
+
+```
+atest XMLParserTest
+```
diff --git a/media/libstagefright/xmlparser/test/XMLParserTest.cpp b/media/libstagefright/xmlparser/test/XMLParserTest.cpp
new file mode 100644
index 0000000..9ddd374
--- /dev/null
+++ b/media/libstagefright/xmlparser/test/XMLParserTest.cpp
@@ -0,0 +1,392 @@
+/*
+ * Copyright (C) 2020 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 "XMLParserTest"
+
+#include <utils/Log.h>
+
+#include <fstream>
+
+#include <media/stagefright/xmlparser/MediaCodecsXmlParser.h>
+
+#include "XMLParserTestEnvironment.h"
+
+#define XML_FILE_NAME "media_codecs_unit_test_caller.xml"
+
+using namespace android;
+
+static XMLParserTestEnvironment *gEnv = nullptr;
+
+struct CodecProperties {
+    string codecName;
+    MediaCodecsXmlParser::CodecProperties codecProp;
+};
+
+struct RoleProperties {
+    string roleName;
+    string typeName;
+    string codecName;
+    bool isEncoder;
+    size_t order;
+    vector<pair<string, string>> attributeMap;
+};
+
+class XMLParseTest : public ::testing::Test {
+  public:
+    ~XMLParseTest() {
+        if (mEleStream.is_open()) mEleStream.close();
+        mInputDataVector.clear();
+        mInputRoleVector.clear();
+    }
+
+    virtual void SetUp() override { setUpDatabase(); }
+
+    void setUpDatabase();
+
+    void setCodecProperties(string codecName, bool isEncoder, int32_t order, set<string> quirkSet,
+                            set<string> domainSet, set<string> variantSet, string typeName,
+                            vector<pair<string, string>> domain, vector<string> aliases,
+                            string rank);
+
+    void setRoleProperties(string roleName, bool isEncoder, int32_t order, string typeName,
+                           string codecName, vector<pair<string, string>> domain);
+
+    void setServiceAttribute(map<string, string> serviceAttributeNameValuePair);
+
+    void printCodecMap(const MediaCodecsXmlParser::Codec mcodec);
+
+    void checkRoleMap(int32_t index, bool isEncoder, string typeName, string codecName,
+                      vector<pair<string, string>> attrMap);
+
+    bool compareMap(const map<string, string> &lhs, const map<string, string> &rhs);
+
+    ifstream mEleStream;
+    MediaCodecsXmlParser mParser;
+    vector<CodecProperties> mInputDataVector;
+    vector<RoleProperties> mInputRoleVector;
+    map<string, string> mInputServiceAttributeMap;
+};
+
+void XMLParseTest::setUpDatabase() {
+    // The values set below are specific to test vector testdata/media_codecs_unit_test.xml
+    setCodecProperties("test1.decoder", false, 1, {"attribute::disabled", "quirk::quirk1"},
+                       {"telephony"}, {}, "audio/mpeg", {}, {"alias1.decoder"}, "4");
+
+    setCodecProperties("test2.decoder", false, 2, {"quirk::quirk1"}, {}, {}, "audio/3gpp", {}, {},
+                       "");
+
+    setCodecProperties("test3.decoder", false, 3, {}, {}, {}, "audio/amr-wb",
+                       {
+                               pair<string, string>("feature-feature1", "feature1Val"),
+                               pair<string, string>("feature-feature2", "0"),
+                               pair<string, string>("feature-feature3", "0"),
+                       },
+                       {}, "");
+
+    setCodecProperties("test4.decoder", false, 4, {}, {}, {}, "audio/flac",
+                       {pair<string, string>("feature-feature1", "feature1Val")}, {}, "");
+
+    setCodecProperties("test5.decoder", false, 5, {"attribute::attributeQuirk1"}, {}, {},
+                       "audio/g711-mlaw", {}, {}, "");
+
+    setCodecProperties("test6.decoder", false, 6, {}, {}, {"variant1", "variant2"},
+                       "audio/mp4a-latm",
+                       {pair<string, string>("variant1:::variant1Limit1-range",
+                                             "variant1Limit1Min-variant1Limit1Max"),
+                        pair<string, string>("variant1:::variant1Limit2-range",
+                                             "variant1Limit2Low-variant1Limit2High"),
+                        pair<string, string>("variant2:::variant2Limit1", "variant2Limit1Value")},
+                       {}, "");
+
+    setCodecProperties(
+            "test7.decoder", false, 7, {}, {}, {}, "audio/vorbis",
+            {
+                    pair<string, string>("-min-limit1", "limit1Min"),
+                    /*pair<string, string>("limit1-in", "limit1In"),*/
+                    pair<string, string>("limit2-range", "limit2Min-limit2Max"),
+                    pair<string, string>("limit2-scale", "limit2Scale"),
+                    pair<string, string>("limit3-default", "limit3Val3"),
+                    pair<string, string>("limit3-ranges", "limit3Val1,limit3Val2,limit3Val3"),
+            },
+            {}, "");
+
+    setCodecProperties("test8.encoder", true, 8, {}, {}, {}, "audio/opus",
+                       {pair<string, string>("max-limit1", "limit1Max")}, {}, "");
+
+    setRoleProperties("audio_decoder.mp3", false, 1, "audio/mpeg", "test1.decoder",
+                      {pair<string, string>("attribute::disabled", "present"),
+                       pair<string, string>("rank", "4")});
+
+    setRoleProperties("audio_decoder.amrnb", false, 2, "audio/3gpp", "test2.decoder", {});
+
+    setRoleProperties("audio_decoder.amrwb", false, 3, "audio/amr-wb", "test3.decoder",
+                      {pair<string, string>("feature-feature1", "feature1Val"),
+                       pair<string, string>("feature-feature2", "0"),
+                       pair<string, string>("feature-feature3", "0")});
+
+    setRoleProperties("audio/flac", false, 4, "audio/flac", "test4.decoder",
+                      {pair<string, string>("feature-feature1", "feature1Val")});
+
+    setRoleProperties("audio_decoder.g711mlaw", false, 5, "audio/g711-mlaw", "test5.decoder",
+                      {pair<string, string>("attribute::attributeQuirk1", "present")});
+
+    setRoleProperties("audio_decoder.aac", false, 6, "audio/mp4a-latm", "test6.decoder",
+                      {pair<string, string>("variant1:::variant1Limit1-range",
+                                            "variant1Limit1Min-variant1Limit1Max"),
+                       pair<string, string>("variant1:::variant1Limit2-range",
+                                            "variant1Limit2Low-variant1Limit2High"),
+                       pair<string, string>("variant2:::variant2Limit1", "variant2Limit1Value")});
+
+    setRoleProperties("audio_decoder.vorbis", false, 7, "audio/vorbis", "test7.decoder",
+                      {pair<string, string>("-min-limit1", "limit1Min"),
+                       /*pair<string, string>("limit1-in", "limit1In"),*/
+                       pair<string, string>("limit2-range", "limit2Min-limit2Max"),
+                       pair<string, string>("limit2-scale", "limit2Scale"),
+                       pair<string, string>("limit3-default", "limit3Val3"),
+                       pair<string, string>("limit3-ranges", "limit3Val1,limit3Val2,limit3Val3")});
+
+    setRoleProperties("audio_encoder.opus", true, 8, "audio/opus", "test8.encoder",
+                      {pair<string, string>("max-limit1", "limit1Max")});
+
+    setServiceAttribute(
+            {pair<string, string>("domain-telephony", "0"), pair<string, string>("domain-tv", "0"),
+             pair<string, string>("setting2", "0"), pair<string, string>("variant-variant1", "0")});
+}
+
+bool XMLParseTest::compareMap(const map<string, string> &lhs, const map<string, string> &rhs) {
+    return lhs.size() == rhs.size() && equal(lhs.begin(), lhs.end(), rhs.begin());
+}
+
+void XMLParseTest::setCodecProperties(string codecName, bool isEncoder, int32_t order,
+                                      set<string> quirkSet, set<string> domainSet,
+                                      set<string> variantSet, string typeName,
+                                      vector<pair<string, string>> domain, vector<string> aliases,
+                                      string rank) {
+    map<string, string> AttributeMapDB;
+    for (const auto &AttrStr : domain) {
+        AttributeMapDB.insert(AttrStr);
+    }
+    map<string, MediaCodecsXmlParser::AttributeMap> TypeMapDataBase;
+    TypeMapDataBase.insert(
+            pair<string, MediaCodecsXmlParser::AttributeMap>(typeName, AttributeMapDB));
+    CodecProperties codecProperty;
+    codecProperty.codecName = codecName;
+    codecProperty.codecProp.isEncoder = isEncoder;
+    codecProperty.codecProp.order = order;
+    codecProperty.codecProp.quirkSet = quirkSet;
+    codecProperty.codecProp.domainSet = domainSet;
+    codecProperty.codecProp.variantSet = variantSet;
+    codecProperty.codecProp.typeMap = TypeMapDataBase;
+    codecProperty.codecProp.aliases = aliases;
+    codecProperty.codecProp.rank = rank;
+    mInputDataVector.push_back(codecProperty);
+}
+
+void XMLParseTest::setRoleProperties(string roleName, bool isEncoder, int32_t order,
+                                     string typeName, string codecName,
+                                     vector<pair<string, string>> attributeNameValuePair) {
+    struct RoleProperties roleProperty;
+    roleProperty.roleName = roleName;
+    roleProperty.typeName = typeName;
+    roleProperty.codecName = codecName;
+    roleProperty.isEncoder = isEncoder;
+    roleProperty.order = order;
+    roleProperty.attributeMap = attributeNameValuePair;
+    mInputRoleVector.push_back(roleProperty);
+}
+
+void XMLParseTest::setServiceAttribute(map<string, string> serviceAttributeNameValuePair) {
+    for (const auto &serviceAttrStr : serviceAttributeNameValuePair) {
+        mInputServiceAttributeMap.insert(serviceAttrStr);
+    }
+}
+
+void XMLParseTest::printCodecMap(const MediaCodecsXmlParser::Codec mcodec) {
+    const string &name = mcodec.first;
+    ALOGV("codec name = %s\n", name.c_str());
+    const MediaCodecsXmlParser::CodecProperties &properties = mcodec.second;
+    bool isEncoder = properties.isEncoder;
+    ALOGV("isEncoder = %d\n", isEncoder);
+    size_t order = properties.order;
+    ALOGV("order = %zu\n", order);
+    string rank = properties.rank;
+    ALOGV("rank = %s\n", rank.c_str());
+
+    for (auto &itrQuirkSet : properties.quirkSet) {
+        ALOGV("quirkSet= %s", itrQuirkSet.c_str());
+    }
+
+    for (auto &itrDomainSet : properties.domainSet) {
+        ALOGV("domainSet= %s", itrDomainSet.c_str());
+    }
+
+    for (auto &itrVariantSet : properties.variantSet) {
+        ALOGV("variantSet= %s", itrVariantSet.c_str());
+    }
+
+    map<string, MediaCodecsXmlParser::AttributeMap> TypeMap = properties.typeMap;
+    ALOGV("The TypeMap is :");
+
+    for (auto &itrTypeMap : TypeMap) {
+        ALOGV("itrTypeMap->first\t%s\t", itrTypeMap.first.c_str());
+
+        for (auto &itrAttributeMap : itrTypeMap.second) {
+            ALOGV("AttributeMap->first = %s", itrAttributeMap.first.c_str());
+            ALOGV("AttributeMap->second = %s", itrAttributeMap.second.c_str());
+        }
+    }
+}
+
+void XMLParseTest::checkRoleMap(int32_t index, bool isEncoder, string typeName, string codecName,
+                                vector<pair<string, string>> AttributePairMap) {
+    ASSERT_EQ(isEncoder, mInputRoleVector.at(index).isEncoder)
+            << "Invalid RoleMap data. IsEncoder mismatch";
+    ASSERT_EQ(typeName, mInputRoleVector.at(index).typeName)
+            << "Invalid RoleMap data. typeName mismatch";
+    ASSERT_EQ(codecName, mInputRoleVector.at(index).codecName)
+            << "Invalid RoleMap data. codecName mismatch";
+
+    vector<pair<string, string>>::iterator itr_attributeMapDB =
+            (mInputRoleVector.at(index).attributeMap).begin();
+    vector<pair<string, string>>::iterator itr_attributeMap = AttributePairMap.begin();
+    for (; itr_attributeMap != AttributePairMap.end() &&
+           itr_attributeMapDB != mInputRoleVector.at(index).attributeMap.end();
+         ++itr_attributeMap, ++itr_attributeMapDB) {
+        string attributeName = itr_attributeMap->first;
+        string attributeNameDB = itr_attributeMapDB->first;
+        string attributevalue = itr_attributeMap->second;
+        string attributeValueDB = itr_attributeMapDB->second;
+        ASSERT_EQ(attributeName, attributeNameDB)
+                << "Invalid RoleMap data. Attribute name mismatch\t" << attributeName << " != "
+                << "attributeNameDB";
+        ASSERT_EQ(attributevalue, attributeValueDB)
+                << "Invalid RoleMap data. Attribute value mismatch\t" << attributevalue << " != "
+                << "attributeValueDB";
+    }
+}
+
+TEST_F(XMLParseTest, CodecMapParseTest) {
+    string inputFileName = gEnv->getRes() + XML_FILE_NAME;
+    mEleStream.open(inputFileName, ifstream::binary);
+    ASSERT_EQ(mEleStream.is_open(), true) << "Failed to open inputfile " << inputFileName;
+
+    mParser.parseXmlPath(inputFileName);
+    for (const MediaCodecsXmlParser::Codec &mcodec : mParser.getCodecMap()) {
+        printCodecMap(mcodec);
+        const MediaCodecsXmlParser::CodecProperties &properties = mcodec.second;
+        int32_t index = properties.order - 1;
+        ASSERT_GE(index, 0) << "Invalid order";
+        ASSERT_EQ(mInputDataVector.at(index).codecName, mcodec.first.c_str())
+                << "Invalid CodecMap data. codecName mismatch";
+        ASSERT_EQ(properties.isEncoder, mInputDataVector.at(index).codecProp.isEncoder)
+                << "Invalid CodecMap data. isEncoder mismatch";
+        ASSERT_EQ(properties.order, mInputDataVector.at(index).codecProp.order)
+                << "Invalid CodecMap data. order mismatch";
+
+        set<string> quirkSetDB = mInputDataVector.at(index).codecProp.quirkSet;
+        set<string> quirkSet = properties.quirkSet;
+        set<string> quirkDifference;
+        set_difference(quirkSetDB.begin(), quirkSetDB.end(), quirkSet.begin(), quirkSet.end(),
+                       inserter(quirkDifference, quirkDifference.end()));
+        ASSERT_EQ(quirkDifference.size(), 0) << "CodecMap:quirk mismatch";
+
+        map<string, MediaCodecsXmlParser::AttributeMap> TypeMapDB =
+                mInputDataVector.at(index).codecProp.typeMap;
+        map<string, MediaCodecsXmlParser::AttributeMap> TypeMap = properties.typeMap;
+        map<string, MediaCodecsXmlParser::AttributeMap>::iterator itr_TypeMapDB = TypeMapDB.begin();
+        map<string, MediaCodecsXmlParser::AttributeMap>::iterator itr_TypeMap = TypeMap.begin();
+
+        ASSERT_EQ(TypeMapDB.size(), TypeMap.size())
+                << "Invalid CodecMap data. Typemap size mismatch";
+
+        for (; itr_TypeMap != TypeMap.end() && itr_TypeMapDB != TypeMapDB.end();
+             ++itr_TypeMap, ++itr_TypeMapDB) {
+            ASSERT_EQ(itr_TypeMap->first, itr_TypeMapDB->first)
+                    << "Invalid CodecMap data. type mismatch";
+            bool flag = compareMap(itr_TypeMap->second, itr_TypeMapDB->second);
+            ASSERT_TRUE(flag) << "typeMap mismatch";
+        }
+        ASSERT_EQ(mInputDataVector.at(index).codecProp.rank, properties.rank)
+                << "Invalid CodecMap data. rank mismatch";
+    }
+}
+
+TEST_F(XMLParseTest, RoleMapParseTest) {
+    string inputFileName = gEnv->getRes() + XML_FILE_NAME;
+    mEleStream.open(inputFileName, ifstream::binary);
+    ASSERT_EQ(mEleStream.is_open(), true) << "Failed to open inputfile " << inputFileName;
+
+    mParser.parseXmlPath(inputFileName);
+
+    for (auto &mRole : mParser.getRoleMap()) {
+        typedef pair<string, string> Attribute;
+        const string &roleName = mRole.first;
+        ALOGV("Role map:name = %s\n", roleName.c_str());
+        const MediaCodecsXmlParser::RoleProperties &properties = mRole.second;
+        string type = properties.type;
+        ALOGV("Role map: type = %s\n", type.c_str());
+
+        bool isEncoder = properties.isEncoder;
+        ALOGV("Role map: isEncoder = %d\n", isEncoder);
+
+        multimap<size_t, MediaCodecsXmlParser::NodeInfo> nodeList = properties.nodeList;
+        multimap<size_t, MediaCodecsXmlParser::NodeInfo>::iterator itr_Node;
+        ALOGV("\nThe multimap nodeList is : \n");
+        for (itr_Node = nodeList.begin(); itr_Node != nodeList.end(); ++itr_Node) {
+            ALOGV("itr_Node->first=ORDER=\t%zu\t", itr_Node->first);
+            int32_t index = itr_Node->first - 1;
+            MediaCodecsXmlParser::NodeInfo nodePtr = itr_Node->second;
+            ALOGV("Role map:itr_Node->second.name = %s\n", nodePtr.name.c_str());
+            vector<Attribute> attrList = nodePtr.attributeList;
+            for (auto attrNameValueList = attrList.begin(); attrNameValueList != attrList.end();
+                 ++attrNameValueList) {
+                ALOGV("Role map:nodePtr.attributeList->first = %s\n",
+                      attrNameValueList->first.c_str());
+                ALOGV("Role map:nodePtr.attributeList->second = %s\n",
+                      attrNameValueList->second.c_str());
+            }
+            checkRoleMap(index, isEncoder, properties.type, nodePtr.name.c_str(), attrList);
+        }
+    }
+}
+
+TEST_F(XMLParseTest, ServiceAttributeMapParseTest) {
+    string inputFileName = gEnv->getRes() + XML_FILE_NAME;
+    mEleStream.open(inputFileName, ifstream::binary);
+    ASSERT_EQ(mEleStream.is_open(), true) << "Failed to open inputfile " << inputFileName;
+
+    mParser.parseXmlPath(inputFileName);
+    const auto serviceAttributeMap = mParser.getServiceAttributeMap();
+    for (const auto &attributePair : serviceAttributeMap) {
+        ALOGV("serviceAttribute.key = %s \t serviceAttribute.value = %s",
+              attributePair.first.c_str(), attributePair.second.c_str());
+    }
+    bool flag = compareMap(mInputServiceAttributeMap, serviceAttributeMap);
+    ASSERT_TRUE(flag) << "ServiceMapParseTest: typeMap mismatch";
+}
+
+int main(int argc, char **argv) {
+    gEnv = new XMLParserTestEnvironment();
+    ::testing::AddGlobalTestEnvironment(gEnv);
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = gEnv->initFromOptions(argc, argv);
+    if (status == 0) {
+        status = RUN_ALL_TESTS();
+        ALOGD("XML Parser Test Result = %d\n", status);
+    }
+    return status;
+}
diff --git a/media/libstagefright/xmlparser/test/XMLParserTestEnvironment.h b/media/libstagefright/xmlparser/test/XMLParserTestEnvironment.h
new file mode 100644
index 0000000..61a09e6
--- /dev/null
+++ b/media/libstagefright/xmlparser/test/XMLParserTestEnvironment.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2020 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 __XML_PARSER_TEST_ENVIRONMENT_H__
+#define __XML_PARSER_TEST_ENVIRONMENT_H__
+
+#include <gtest/gtest.h>
+
+#include <getopt.h>
+
+using namespace std;
+
+class XMLParserTestEnvironment : public ::testing::Environment {
+  public:
+    XMLParserTestEnvironment() : res("/data/local/tmp/") {}
+
+    // Parses the command line arguments
+    int initFromOptions(int argc, char **argv);
+
+    void setRes(const char *_res) { res = _res; }
+
+    const string getRes() const { return res; }
+
+  private:
+    string res;
+};
+
+int XMLParserTestEnvironment::initFromOptions(int argc, char **argv) {
+    static struct option options[] = {{"path", required_argument, 0, 'P'}, {0, 0, 0, 0}};
+
+    while (true) {
+        int index = 0;
+        int c = getopt_long(argc, argv, "P:", options, &index);
+        if (c == -1) {
+            break;
+        }
+
+        switch (c) {
+            case 'P': {
+                setRes(optarg);
+                break;
+            }
+            default:
+                break;
+        }
+    }
+
+    if (optind < argc) {
+        fprintf(stderr,
+                "unrecognized option: %s\n\n"
+                "usage: %s <gtest options> <test options>\n\n"
+                "test options are:\n\n"
+                "-P, --path: Resource files directory location\n",
+                argv[optind ?: 1], argv[0]);
+        return 2;
+    }
+    return 0;
+}
+
+#endif  // __XML_PARSER_TEST_ENVIRONMENT_H__
diff --git a/media/libstagefright/xmlparser/test/testdata/media_codecs_unit_test.xml b/media/libstagefright/xmlparser/test/testdata/media_codecs_unit_test.xml
new file mode 100644
index 0000000..a7299d3
--- /dev/null
+++ b/media/libstagefright/xmlparser/test/testdata/media_codecs_unit_test.xml
@@ -0,0 +1,80 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<!-- REFERENCE : frameworks/av/media/libstagefright/xmlparser/media_codecs.xsd -->
+<Included>
+    <Settings>
+        <Domain name="telephony" enabled="false" />
+        <Domain name="tv" enabled="false" />
+        <Variant name="variant1" enabled="false" />
+        <Setting name="setting1" value="settingValue1" update="true" />
+        <Setting name="setting2" enabled="false" />
+    </Settings>
+    <Decoders>
+        <!-- entry for enabled, domain, rank and update properties -->
+        <MediaCodec name="test1.decoder" type="audio/mpeg" update="false" domain="telephony" enabled="false" rank="4">
+            <Alias name="alias1.decoder" />
+            <Quirk name="quirk1" value="quirk1Value"/>
+        </MediaCodec>
+        <!-- entry for testing Quirk -->
+        <MediaCodec name="test2.decoder" type="audio/3gpp" enabled="true" >
+            <Quirk name="quirk1" value="quirk1Value"/>
+        </MediaCodec>
+        <!-- entry for testing Feature -->
+        <!-- feature2 takes value 0 (feature with same name takes lower feature's value) -->
+        <!-- feature3 gives value as 0 since it's optional -->
+        <!-- optional="true" required="true" is not a valid combination. -->
+        <!-- optional="false" required="false" is not a valid combination. -->
+        <MediaCodec name="test3.decoder" type="audio/amr-wb" >
+            <Feature name="feature1" value="feature1Val" />
+            <Feature name="feature2" value="feature2Val"/>
+            <Feature name="feature2" />
+            <Feature name="feature3" optional="true" required="false" />
+        </MediaCodec>
+        <!-- entry for testing Type -->
+        <MediaCodec name="test4.decoder">
+            <Type name="audio/flac">
+                <Feature name="feature1" value="feature1Val" />
+            </Type>
+        </MediaCodec>
+        <!-- entry for testing Attribute -->
+        <MediaCodec name="test5.decoder" type="audio/g711-mlaw" >
+            <Attribute name="attributeQuirk1" />
+        </MediaCodec>
+        <!-- entry for testing Variant -->
+        <MediaCodec name="test6.decoder" type="audio/mp4a-latm" variant="variant1,variant2" >
+            <Variant name="variant1">
+                <Limit name="variant1Limit1" min="variant1Limit1Min" max="variant1Limit1Max" />
+                <Limit name="variant1Limit2" range="variant1Limit2Low-variant1Limit2High" />
+            </Variant>
+            <Variant name="variant2">
+                <Limit name="variant2Limit1" value="variant2Limit1Value" />
+            </Variant>
+        </MediaCodec>
+        <!-- entry for testing Limit -->
+        <!-- 'in' is present in xsd file but not handled in MediaCodecsXmlParser -->
+        <MediaCodec name="test7.decoder" type="audio/vorbis" >
+            <Limit name="limit1" in="limit1In" min="limit1Min"/>
+            <Limit name="limit2" min="limit2Min" max="limit2Max" scale="limit2Scale" />
+            <Limit name="limit3" ranges="limit3Val1,limit3Val2,limit3Val3" default="limit3Val3" />
+        </MediaCodec>
+    </Decoders>
+    <Encoders>
+        <MediaCodec name="test8.encoder" type="audio/opus">
+            <Limit name="limit1" max="limit1Max" />
+        </MediaCodec>
+    </Encoders>
+</Included>
diff --git a/media/libstagefright/xmlparser/test/testdata/media_codecs_unit_test_caller.xml b/media/libstagefright/xmlparser/test/testdata/media_codecs_unit_test_caller.xml
new file mode 100644
index 0000000..d864ce9
--- /dev/null
+++ b/media/libstagefright/xmlparser/test/testdata/media_codecs_unit_test_caller.xml
@@ -0,0 +1,4 @@
+<!-- entry for testing Include -->
+<MediaCodecs>
+    <Include href="media_codecs_unit_test.xml" />
+</MediaCodecs>
diff --git a/media/libstagefright/xmlparser/vts/Android.bp b/media/libstagefright/xmlparser/vts/Android.bp
index 132ce82..1e36c8f 100644
--- a/media/libstagefright/xmlparser/vts/Android.bp
+++ b/media/libstagefright/xmlparser/vts/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_libstagefright_license"],
+}
+
 cc_test {
     name: "vts_mediaCodecs_validate_test",
     srcs: [
diff --git a/media/libstagefright/xmlparser/vts/Android.mk b/media/libstagefright/xmlparser/vts/Android.mk
deleted file mode 100644
index d5290ba..0000000
--- a/media/libstagefright/xmlparser/vts/Android.mk
+++ /dev/null
@@ -1,22 +0,0 @@
-#
-# Copyright (C) 2019 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := VtsValidateMediaCodecs
-include test/vts/tools/build/Android.host_config.mk
diff --git a/media/libstagefright/xmlparser/vts/AndroidTest.xml b/media/libstagefright/xmlparser/vts/AndroidTest.xml
deleted file mode 100644
index 97ee107..0000000
--- a/media/libstagefright/xmlparser/vts/AndroidTest.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2019 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.
--->
-<configuration description="Config for VTS VtsValidateMediaCodecs.">
-    <option name="config-descriptor:metadata" key="plan" value="vts-treble" />
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.VtsFilePusher">
-        <option name="abort-on-push-failure" value="false"/>
-        <option name="push-group" value="HostDrivenTest.push"/>
-        <option name="push" value="DATA/etc/media_codecs.xsd->/data/local/tmp/media_codecs.xsd"/>
-    </target_preparer>
-    <test class="com.android.tradefed.testtype.VtsMultiDeviceTest">
-        <option name="test-module-name" value="VtsValidateMediaCodecs"/>
-        <option name="binary-test-source" value="_32bit::DATA/nativetest/vts_mediaCodecs_validate_test/vts_mediaCodecs_validate_test" />
-        <option name="binary-test-source" value="_64bit::DATA/nativetest64/vts_mediaCodecs_validate_test/vts_mediaCodecs_validate_test" />
-        <option name="binary-test-type" value="gtest"/>
-        <option name="test-timeout" value="30s"/>
-    </test>
-</configuration>
diff --git a/media/libwatchdog/Android.bp b/media/libwatchdog/Android.bp
index 1a87824..fe717b1 100644
--- a/media/libwatchdog/Android.bp
+++ b/media/libwatchdog/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libwatchdog",
     srcs: [
diff --git a/media/mediaserver/Android.bp b/media/mediaserver/Android.bp
index afca7c4..38bb791 100644
--- a/media/mediaserver/Android.bp
+++ b/media/mediaserver/Android.bp
@@ -1,4 +1,21 @@
 
+package {
+    default_applicable_licenses: ["frameworks_av_media_mediaserver_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_mediaserver_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_static {
     name: "libregistermsext",
     srcs: ["register.cpp"],
@@ -34,8 +51,10 @@
         "frameworks/av/services/mediaresourcemanager",
     ],
 
-    // back to 32-bit, b/126502613
-    compile_multilib: "32",
+    // mediaserver has only been verified on 32-bit, see b/126502613
+    // use "prefer32" to *only* enable 64-bit builds on 64-bit-only lunch
+    // targets, which allows them to reach 'boot_complete'.
+    compile_multilib: "prefer32",
 
     init_rc: ["mediaserver.rc"],
 
diff --git a/media/mediaserver/main_mediaserver.cpp b/media/mediaserver/main_mediaserver.cpp
index 316732b..58e2d2a 100644
--- a/media/mediaserver/main_mediaserver.cpp
+++ b/media/mediaserver/main_mediaserver.cpp
@@ -18,7 +18,6 @@
 #define LOG_TAG "mediaserver"
 //#define LOG_NDEBUG 0
 
-#include <aicu/AIcu.h>
 #include <binder/IPCThreadState.h>
 #include <binder/ProcessState.h>
 #include <binder/IServiceManager.h>
@@ -39,7 +38,6 @@
     sp<ProcessState> proc(ProcessState::self());
     sp<IServiceManager> sm(defaultServiceManager());
     ALOGI("ServiceManager: %p", sm.get());
-    AIcu_initializeIcuOrDie();
     MediaPlayerService::instantiate();
     ResourceManagerService::instantiate();
     registerExtensions();
diff --git a/media/mtp/Android.bp b/media/mtp/Android.bp
index 66a3139..97e2a22 100644
--- a/media/mtp/Android.bp
+++ b/media/mtp/Android.bp
@@ -14,6 +14,23 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["frameworks_av_media_mtp_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_mtp_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libmtp",
     srcs: [
@@ -52,5 +69,5 @@
         "liblog",
         "libusbhost",
     ],
+    header_libs: ["libcutils_headers"],
 }
-
diff --git a/media/mtp/MtpFfsHandle.cpp b/media/mtp/MtpFfsHandle.cpp
index bd6a6c6..c8b4a03 100644
--- a/media/mtp/MtpFfsHandle.cpp
+++ b/media/mtp/MtpFfsHandle.cpp
@@ -114,11 +114,11 @@
 void MtpFfsHandle::advise(int fd) {
     for (unsigned i = 0; i < NUM_IO_BUFS; i++) {
         if (posix_madvise(mIobuf[i].bufs.data(), MAX_FILE_CHUNK_SIZE,
-                POSIX_MADV_SEQUENTIAL | POSIX_MADV_WILLNEED) < 0)
+                POSIX_MADV_SEQUENTIAL | POSIX_MADV_WILLNEED) != 0)
             PLOG(ERROR) << "Failed to madvise";
     }
     if (posix_fadvise(fd, 0, 0,
-                POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE | POSIX_FADV_WILLNEED) < 0)
+                POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE | POSIX_FADV_WILLNEED) != 0)
         PLOG(ERROR) << "Failed to fadvise";
 }
 
diff --git a/media/mtp/tests/Android.bp b/media/mtp/tests/Android.bp
index 0750208..6ed94ac 100644
--- a/media/mtp/tests/Android.bp
+++ b/media/mtp/tests/Android.bp
@@ -14,6 +14,15 @@
 // limitations under the License.
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_media_mtp_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_media_mtp_license"],
+}
+
 cc_test {
     name: "mtp_ffs_handle_test",
     test_suites: ["device-tests"],
diff --git a/media/ndk/Android.bp b/media/ndk/Android.bp
index 43989bb..e9ea386 100644
--- a/media/ndk/Android.bp
+++ b/media/ndk/Android.bp
@@ -16,6 +16,37 @@
 // to refer to headers in parent directories and the headers live in
 // frameworks/av/include.
 
+package {
+    default_applicable_licenses: ["frameworks_av_media_ndk_license"],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_media_ndk_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-MIT",
+        "SPDX-license-identifier-Unicode-DFS",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 ndk_library {
     name: "libmediandk",
     symbol_file: "libmediandk.map.txt",
@@ -43,11 +74,18 @@
         "com.android.media.swcodec",
     ],
     min_sdk_version: "29",
-    export_include_dirs: ["include"]
+    export_include_dirs: ["include"],
+    host_supported: true,
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
 }
 
 cc_library_shared {
     name: "libmediandk",
+    llndk_stubs: "libmediandk.llndk",
 
     srcs: [
         "NdkJavaVMHelper.cpp",
@@ -76,9 +114,11 @@
 
     static_libs: [
         "libgrallocusage",
+        "libnativehelper_lazy",
     ],
 
     header_libs: [
+        "jni_headers",
         "libmediadrm_headers",
         "libmediametrics_headers",
     ],
@@ -103,9 +143,10 @@
         "libgui",
         "libui",
         "libmediandk_utils",
-        "libnativehelper",
     ],
 
+    export_header_lib_headers: ["jni_headers"],
+
     export_include_dirs: ["include"],
 
     export_shared_lib_headers: [
@@ -125,7 +166,7 @@
 }
 
 llndk_library {
-    name: "libmediandk",
+    name: "libmediandk.llndk",
     symbol_file: "libmediandk.map.txt",
     export_include_dirs: [
         "include",
@@ -195,3 +236,41 @@
         "frameworks/av/media/ndk/",
     ],
 }
+
+cc_library_static {
+    name: "libmediandk_format",
+
+    host_supported: true,
+
+    srcs: [
+        "NdkMediaFormat.cpp",
+    ],
+
+    header_libs: [
+        "libstagefright_foundation_headers",
+    ],
+
+    cflags: [
+        "-DEXPORT=__attribute__((visibility(\"default\")))",
+        "-Werror",
+        "-Wall",
+    ],
+
+    export_include_dirs: ["include"],
+
+    sanitize: {
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+    },
+
+    target: {
+        darwin: {
+            enabled: false,
+        },
+    },
+
+    apex_available: ["com.android.media"],
+}
diff --git a/media/ndk/NdkImage.cpp b/media/ndk/NdkImage.cpp
index 1145b7b..5fdd45a 100644
--- a/media/ndk/NdkImage.cpp
+++ b/media/ndk/NdkImage.cpp
@@ -58,7 +58,7 @@
     if (mIsClosed) {
         return;
     }
-    if (!mReader->mIsClosed) {
+    if (mReader->mIsOpen) {
         mReader->releaseImageLocked(this, releaseFenceFd);
     }
     // Should have been set to nullptr in releaseImageLocked
diff --git a/media/ndk/NdkImageReader.cpp b/media/ndk/NdkImageReader.cpp
index c0ceb3d..051466a 100644
--- a/media/ndk/NdkImageReader.cpp
+++ b/media/ndk/NdkImageReader.cpp
@@ -274,7 +274,7 @@
 
 AImageReader::~AImageReader() {
     Mutex::Autolock _l(mLock);
-    LOG_FATAL_IF("AImageReader not closed before destruction", mIsClosed != true);
+    LOG_FATAL_IF(mIsOpen, "AImageReader not closed before destruction");
 }
 
 media_status_t
@@ -348,16 +348,16 @@
     }
     mHandler = new CallbackHandler(this);
     mCbLooper->registerHandler(mHandler);
-
+    mIsOpen = true;
     return AMEDIA_OK;
 }
 
 void AImageReader::close() {
     Mutex::Autolock _l(mLock);
-    if (mIsClosed) {
+    if (!mIsOpen) {
         return;
     }
-    mIsClosed = true;
+    mIsOpen = false;
     AImageReader_ImageListener nullListener = {nullptr, nullptr};
     setImageListenerLocked(&nullListener);
 
diff --git a/media/ndk/NdkImageReaderPriv.h b/media/ndk/NdkImageReaderPriv.h
index 0779a71..37c606e 100644
--- a/media/ndk/NdkImageReaderPriv.h
+++ b/media/ndk/NdkImageReaderPriv.h
@@ -166,7 +166,7 @@
     native_handle_t*           mWindowHandle = nullptr;
 
     List<AImage*>              mAcquiredImages;
-    bool                       mIsClosed = false;
+    bool                       mIsOpen = false;
 
     Mutex                      mLock;
 };
diff --git a/media/ndk/NdkMediaFormat.cpp b/media/ndk/NdkMediaFormat.cpp
index ab0cb63..8680641 100644
--- a/media/ndk/NdkMediaFormat.cpp
+++ b/media/ndk/NdkMediaFormat.cpp
@@ -26,9 +26,6 @@
 #include <utils/StrongPointer.h>
 #include <media/stagefright/foundation/ABuffer.h>
 #include <media/stagefright/foundation/AMessage.h>
-#include <android_util_Binder.h>
-
-#include <jni.h>
 
 using namespace android;
 
diff --git a/media/ndk/include/media/NdkImage.h b/media/ndk/include/media/NdkImage.h
index 62b8624..e19dd3a 100644
--- a/media/ndk/include/media/NdkImage.h
+++ b/media/ndk/include/media/NdkImage.h
@@ -559,8 +559,6 @@
     int32_t bottom;
 } AImageCropRect;
 
-#if __ANDROID_API__ >= 24
-
 /**
  * Return the image back the the system and delete the AImage object from memory.
  *
@@ -777,10 +775,6 @@
         const AImage* image, int planeIdx,
         /*out*/uint8_t** data, /*out*/int* dataLength) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 26
-
 /**
  * Return the image back the the system and delete the AImage object from memory asynchronously.
  *
@@ -829,8 +823,6 @@
  */
 media_status_t AImage_getHardwareBuffer(const AImage* image, /*out*/AHardwareBuffer** buffer) __INTRODUCED_IN(26);
 
-#endif /* __ANDROID_API__ >= 26 */
-
 __END_DECLS
 
 #endif //_NDK_IMAGE_H
diff --git a/media/ndk/include/media/NdkImageReader.h b/media/ndk/include/media/NdkImageReader.h
index 600ffc9..d86f3c7 100644
--- a/media/ndk/include/media/NdkImageReader.h
+++ b/media/ndk/include/media/NdkImageReader.h
@@ -53,8 +53,6 @@
  */
 typedef struct AImageReader AImageReader;
 
-#if __ANDROID_API__ >= 24
-
 /**
  * Create a new reader for images of the desired size and format.
  *
@@ -320,10 +318,6 @@
 media_status_t AImageReader_setImageListener(
         AImageReader* reader, AImageReader_ImageListener* listener) __INTRODUCED_IN(24);
 
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 26
-
 /**
  * AImageReader constructor similar to {@link AImageReader_new} that takes an additional parameter
  * for the consumer usage. All other parameters and the return values are identical to those passed
@@ -510,8 +504,6 @@
     AImageReader *reader, /* out */native_handle_t **handle);
 #endif
 
-#endif /* __ANDROID_API__ >= 26 */
-
 __END_DECLS
 
 #endif //_NDK_IMAGE_READER_H
diff --git a/media/ndk/include/media/NdkMediaCodec.h b/media/ndk/include/media/NdkMediaCodec.h
index 8fb6a87..60cdd32 100644
--- a/media/ndk/include/media/NdkMediaCodec.h
+++ b/media/ndk/include/media/NdkMediaCodec.h
@@ -114,14 +114,12 @@
         int32_t actionCode,
         const char *detail);
 
-struct AMediaCodecOnAsyncNotifyCallback {
+typedef struct AMediaCodecOnAsyncNotifyCallback {
       AMediaCodecOnAsyncInputAvailable  onAsyncInputAvailable;
       AMediaCodecOnAsyncOutputAvailable onAsyncOutputAvailable;
       AMediaCodecOnAsyncFormatChanged   onAsyncFormatChanged;
       AMediaCodecOnAsyncError           onAsyncError;
-};
-
-#if __ANDROID_API__ >= 21
+} AMediaCodecOnAsyncNotifyCallback;
 
 /**
  * Create codec by name. Use this if you know the exact codec you want to use.
@@ -311,8 +309,6 @@
 media_status_t AMediaCodec_releaseOutputBufferAtTime(
         AMediaCodec *mData, size_t idx, int64_t timestampNs) __INTRODUCED_IN(21);
 
-#if __ANDROID_API__ >= 26
-
 /**
  * Creates a Surface that can be used as the input to encoder, in place of input buffers
  *
@@ -393,10 +389,6 @@
  */
 media_status_t AMediaCodec_signalEndOfInputStream(AMediaCodec *mData) __INTRODUCED_IN(26);
 
-#endif /* __ANDROID_API__ >= 26 */
-
-#if __ANDROID_API__ >= 28
-
 /**
  * Get format of the buffer. The specified buffer index must have been previously obtained from
  * dequeueOutputBuffer.
@@ -482,8 +474,6 @@
  */
 bool AMediaCodecActionCode_isTransient(int32_t actionCode) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
 typedef enum {
     AMEDIACODECRYPTOINFO_MODE_CLEAR = 0,
     AMEDIACODECRYPTOINFO_MODE_AES_CTR = 1,
@@ -580,8 +570,6 @@
  */
 media_status_t AMediaCodecCryptoInfo_getEncryptedBytes(AMediaCodecCryptoInfo*, size_t *dst) __INTRODUCED_IN(21);
 
-#endif /* __ANDROID_API__ >= 21 */
-
 __END_DECLS
 
 #endif //_NDK_MEDIA_CODEC_H
diff --git a/media/ndk/include/media/NdkMediaCrypto.h b/media/ndk/include/media/NdkMediaCrypto.h
index 3fa07c7..590d51d 100644
--- a/media/ndk/include/media/NdkMediaCrypto.h
+++ b/media/ndk/include/media/NdkMediaCrypto.h
@@ -47,8 +47,6 @@
 
 typedef uint8_t AMediaUUID[16];
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Available since API level 21.
  */
@@ -69,8 +67,6 @@
  */
 void AMediaCrypto_delete(AMediaCrypto* crypto) __INTRODUCED_IN(21);
 
-#endif /* __ANDROID_API__ >= 21 */
-
 __END_DECLS
 
 #endif // _NDK_MEDIA_CRYPTO_H
diff --git a/media/ndk/include/media/NdkMediaDataSource.h b/media/ndk/include/media/NdkMediaDataSource.h
index 0577df2..4158a97 100644
--- a/media/ndk/include/media/NdkMediaDataSource.h
+++ b/media/ndk/include/media/NdkMediaDataSource.h
@@ -38,8 +38,6 @@
 struct AMediaDataSource;
 typedef struct AMediaDataSource AMediaDataSource;
 
-#if __ANDROID_API__ >= 28
-
 /*
  * AMediaDataSource's callbacks will be invoked on an implementation-defined thread
  * or thread pool. No guarantees are provided about which thread(s) will be used for
@@ -93,8 +91,6 @@
  */
 AMediaDataSource* AMediaDataSource_new() __INTRODUCED_IN(28);
 
-#if __ANDROID_API__ >= 29
-
 /**
  * Called to get an estimate of the number of bytes that can be read from this data source
  * starting at |offset| without blocking for I/O.
@@ -124,8 +120,6 @@
         int numheaders,
         const char * const *key_values) __INTRODUCED_IN(29);
 
-#endif  /*__ANDROID_API__ >= 29 */
-
 /**
  * Delete a previously created media data source.
  *
@@ -185,10 +179,6 @@
         AMediaDataSource*,
         AMediaDataSourceClose) __INTRODUCED_IN(28);
 
-#endif  /*__ANDROID_API__ >= 28 */
-
-#if __ANDROID_API__ >= 29
-
 /**
  * Close the data source, unblock reads, and release associated resources.
  *
@@ -213,8 +203,6 @@
         AMediaDataSource*,
         AMediaDataSourceGetAvailableSize) __INTRODUCED_IN(29);
 
-#endif  /*__ANDROID_API__ >= 29 */
-
 __END_DECLS
 
 #endif // _NDK_MEDIA_DATASOURCE_H
diff --git a/media/ndk/include/media/NdkMediaDrm.h b/media/ndk/include/media/NdkMediaDrm.h
index 31f5c7d..849a8f9 100644
--- a/media/ndk/include/media/NdkMediaDrm.h
+++ b/media/ndk/include/media/NdkMediaDrm.h
@@ -165,8 +165,6 @@
         const AMediaDrmSessionId *sessionId, const AMediaDrmKeyStatus *keyStatus,
         size_t numKeys, bool hasNewUsableKey);
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Query if the given scheme identified by its UUID is supported on this device, and
  * whether the drm plugin is able to handle the media container format specified by mimeType.
@@ -576,8 +574,6 @@
         const char *macAlgorithm, uint8_t *keyId, const uint8_t *message, size_t messageSize,
         const uint8_t *signature, size_t signatureSize) __INTRODUCED_IN(21);
 
-#endif /* __ANDROID_API__ >= 21 */
-
 __END_DECLS
 
 #endif //_NDK_MEDIA_DRM_H
diff --git a/media/ndk/include/media/NdkMediaExtractor.h b/media/ndk/include/media/NdkMediaExtractor.h
index 14319c4..e429820 100644
--- a/media/ndk/include/media/NdkMediaExtractor.h
+++ b/media/ndk/include/media/NdkMediaExtractor.h
@@ -36,6 +36,7 @@
 #ifndef _NDK_MEDIA_EXTRACTOR_H
 #define _NDK_MEDIA_EXTRACTOR_H
 
+#include <stdbool.h>
 #include <sys/cdefs.h>
 #include <sys/types.h>
 
@@ -49,8 +50,6 @@
 struct AMediaExtractor;
 typedef struct AMediaExtractor AMediaExtractor;
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Create new media extractor.
  *
@@ -81,8 +80,6 @@
 media_status_t AMediaExtractor_setDataSource(AMediaExtractor*,
         const char *location) __INTRODUCED_IN(21);
 
-#if __ANDROID_API__ >= 28
-
 /**
  * Set the custom data source implementation from which the extractor will read.
  *
@@ -91,8 +88,6 @@
 media_status_t AMediaExtractor_setDataSourceCustom(AMediaExtractor*,
         AMediaDataSource *src) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
 /**
  * Return the number of tracks in the previously specified media file
  *
@@ -210,8 +205,6 @@
     AMEDIAEXTRACTOR_SAMPLE_FLAG_ENCRYPTED = 2,
 };
 
-#if __ANDROID_API__ >= 28
-
 /**
  * Returns the format of the extractor. The caller must free the returned format
  * using AMediaFormat_delete(format).
@@ -265,10 +258,6 @@
 media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex,
         AMediaFormat *fmt) __INTRODUCED_IN(28);
 
-#endif /* __ANDROID_API__ >= 28 */
-
-#endif /* __ANDROID_API__ >= 21 */
-
 __END_DECLS
 
 #endif // _NDK_MEDIA_EXTRACTOR_H
diff --git a/media/ndk/include/media/NdkMediaFormat.h b/media/ndk/include/media/NdkMediaFormat.h
index 49d8b4a..0ce08c1 100644
--- a/media/ndk/include/media/NdkMediaFormat.h
+++ b/media/ndk/include/media/NdkMediaFormat.h
@@ -36,9 +36,14 @@
 #ifndef _NDK_MEDIA_FORMAT_H
 #define _NDK_MEDIA_FORMAT_H
 
+#include <stdbool.h>
 #include <sys/cdefs.h>
 #include <sys/types.h>
 
+#if !defined(__INTRODUCED_IN)
+#define __INTRODUCED_IN(__api_level) /* nothing */
+#endif
+
 #include "NdkMediaError.h"
 
 __BEGIN_DECLS
@@ -46,8 +51,6 @@
 struct AMediaFormat;
 typedef struct AMediaFormat AMediaFormat;
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Available since API level 21.
  */
@@ -190,9 +193,7 @@
 extern const char* AMEDIAFORMAT_KEY_TRACK_ID __INTRODUCED_IN(28);
 extern const char* AMEDIAFORMAT_KEY_TRACK_INDEX __INTRODUCED_IN(28);
 extern const char* AMEDIAFORMAT_KEY_WIDTH __INTRODUCED_IN(21);
-#endif /* __ANDROID_API__ >= 21 */
 
-#if __ANDROID_API__ >= 28
 /**
  * Available since API level 28.
  */
@@ -216,9 +217,7 @@
  */
 void AMediaFormat_setRect(AMediaFormat*, const char* name,
         int32_t left, int32_t top, int32_t right, int32_t bottom) __INTRODUCED_IN(28);
-#endif /* __ANDROID_API__ >= 28 */
 
-#if __ANDROID_API__ >= 29
 /**
  * Remove all key/value pairs from the given AMediaFormat.
  *
@@ -292,9 +291,6 @@
 extern const char* AMEDIAFORMAT_KEY_VALID_SAMPLES __INTRODUCED_IN(29);
 extern const char* AMEDIAFORMAT_KEY_YEAR __INTRODUCED_IN(29);
 
-#endif /* __ANDROID_API__ >= 29 */
-
-#if __ANDROID_API__ >= 30
 /**
  * An optional key describing the low latency decoding mode. This is an optional parameter
  * that applies only to decoders. If enabled, the decoder doesn't hold input and output
@@ -305,7 +301,6 @@
  * Available since API level 30.
  */
 extern const char* AMEDIAFORMAT_KEY_LOW_LATENCY __INTRODUCED_IN(30);
-#endif /* __ANDROID_API__ >= 30 */
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaMuxer.h b/media/ndk/include/media/NdkMediaMuxer.h
index 9de3fbf..519e249 100644
--- a/media/ndk/include/media/NdkMediaMuxer.h
+++ b/media/ndk/include/media/NdkMediaMuxer.h
@@ -54,8 +54,6 @@
     AMEDIAMUXER_OUTPUT_FORMAT_THREE_GPP   = 2,
 } OutputFormat;
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Create new media muxer.
  *
@@ -140,8 +138,6 @@
         size_t trackIdx, const uint8_t *data,
         const AMediaCodecBufferInfo *info) __INTRODUCED_IN(21);
 
-#endif /* __ANDROID_API__ >= 21 */
-
 __END_DECLS
 
 #endif // _NDK_MEDIA_MUXER_H
diff --git a/media/tests/benchmark/Android.bp b/media/tests/benchmark/Android.bp
index de408dd..8503a9c 100644
--- a/media/tests/benchmark/Android.bp
+++ b/media/tests/benchmark/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 subdirs = [
     "src",
     "tests",
diff --git a/media/tests/benchmark/MediaBenchmarkTest/Android.bp b/media/tests/benchmark/MediaBenchmarkTest/Android.bp
index d80d9a5..2e06da5 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/Android.bp
+++ b/media/tests/benchmark/MediaBenchmarkTest/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 android_test {
     name: "MediaBenchmarkTest",
 
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/EncoderTest.java b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/EncoderTest.java
index 48e1422..4202732 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/EncoderTest.java
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/EncoderTest.java
@@ -34,6 +34,7 @@
 import com.android.media.benchmark.library.Native;
 import com.android.media.benchmark.library.Stats;
 
+import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -57,40 +58,87 @@
 public class EncoderTest {
     private static final Context mContext =
             InstrumentationRegistry.getInstrumentation().getTargetContext();
+    private static final String mFileDirPath = mContext.getFilesDir() + "/";
     private static final String mInputFilePath = mContext.getString(R.string.input_file_path);
     private static final String mOutputFilePath = mContext.getString(R.string.output_file_path);
     private static final String mStatsFile =
             mContext.getExternalFilesDir(null) + "/Encoder." + System.currentTimeMillis() + ".csv";
     private static final String TAG = "EncoderTest";
-    private static final long PER_TEST_TIMEOUT_MS = 120000;
     private static final boolean DEBUG = false;
     private static final boolean WRITE_OUTPUT = false;
+    private static final long PER_TEST_TIMEOUT_MS = 120000;
     private static final int ENCODE_DEFAULT_FRAME_RATE = 25;
-    private static final int ENCODE_DEFAULT_BIT_RATE = 8000000 /* 8 Mbps */;
-    private static final int ENCODE_MIN_BIT_RATE = 600000 /* 600 Kbps */;
+    private static final int ENCODE_DEFAULT_VIDEO_BIT_RATE = 8000000 /* 8 Mbps */;
+    private static final int ENCODE_MIN_VIDEO_BIT_RATE = 600000 /* 600 Kbps */;
     private static final int ENCODE_DEFAULT_AUDIO_BIT_RATE = 128000 /* 128 Kbps */;
+    private static int mColorFormat = COLOR_FormatYUV420Flexible;
+    private static File mDecodedFileQcif;
+    private static File mDecodedFileFullHd;
+    private static File mDecodedFileAudio;
     private String mInputFile;
+    private String mMime;
+    private int mBitRate;
+    private int mIFrameInterval;
+    private int mWidth;
+    private int mHeight;
+    private int mProfile;
+    private int mLevel;
+    private int mSampleRate;
+    private int mNumChannel;
+    private static final String DECODE_FULLHD_INPUT = "crowd_1920x1080_25fps_4000kbps_h265.mkv";
+    private static final String DECODE_QCIF_INPUT = "crowd_176x144_25fps_6000kbps_mpeg4.mp4";
+    private static final String DECODE_AUDIO_INPUT = "bbb_48000hz_2ch_100kbps_opus_30sec.webm";
+    private static final String DECODE_FULLHD_UNPACKED = "crowd_1920x1080_25fps_4000kbps_h265.yuv";
+    private static final String DECODE_QCIF_UNPACKED = "crowd_176x144_25fps_6000kbps_mpeg4.yuv";
+    private static final String DECODE_AUDIO_UNPACKED = "bbb_48000hz_2ch_100kbps_opus_30sec.raw";
 
     @Parameterized.Parameters
     public static Collection<Object[]> inputFiles() {
         return Arrays.asList(new Object[][]{
                 // Audio Test
-                {"bbb_44100hz_2ch_128kbps_aac_30sec.mp4"},
-                {"bbb_8000hz_1ch_8kbps_amrnb_30sec.3gp"},
-                {"bbb_16000hz_1ch_9kbps_amrwb_30sec.3gp"},
-                {"bbb_44100hz_2ch_600kbps_flac_30sec.mp4"},
-                {"bbb_48000hz_2ch_100kbps_opus_30sec.webm"},
+                // Parameters: Filename, mimeType, bitrate, width, height, iFrameInterval,
+                // profile, level, sampleRate, channelCount
+                {DECODE_AUDIO_UNPACKED, MediaFormat.MIMETYPE_AUDIO_AAC,
+                        ENCODE_DEFAULT_AUDIO_BIT_RATE, -1, -1, -1, -1, -1, 44100, 2},
+                {DECODE_AUDIO_UNPACKED, MediaFormat.MIMETYPE_AUDIO_AMR_NB,
+                        ENCODE_DEFAULT_AUDIO_BIT_RATE, -1, -1, -1, -1, -1, 8000, 1},
+                {DECODE_AUDIO_UNPACKED, MediaFormat.MIMETYPE_AUDIO_AMR_WB,
+                        ENCODE_DEFAULT_AUDIO_BIT_RATE, -1, -1, -1, -1, -1, 16000, 1},
+                {DECODE_AUDIO_UNPACKED, MediaFormat.MIMETYPE_AUDIO_FLAC,
+                        ENCODE_DEFAULT_AUDIO_BIT_RATE, -1, -1, -1, -1, -1, 44100, 2},
+                {DECODE_AUDIO_UNPACKED, MediaFormat.MIMETYPE_AUDIO_OPUS,
+                        ENCODE_DEFAULT_AUDIO_BIT_RATE, -1, -1, -1, -1, -1, 48000, 2},
+
                 // Video Test
-                {"crowd_1920x1080_25fps_4000kbps_vp8.webm"},
-                {"crowd_1920x1080_25fps_6700kbps_h264.ts"},
-                {"crowd_1920x1080_25fps_4000kbps_h265.mkv"},
-                {"crowd_1920x1080_25fps_4000kbps_vp9.webm"},
-                {"crowd_176x144_25fps_6000kbps_mpeg4.mp4"},
-                {"crowd_176x144_25fps_6000kbps_h263.3gp"}});
+                // Parameters: Filename, mimeType, bitrate, width, height, iFrameInterval,
+                // profile, level, sampleRate, channelCount
+                {DECODE_FULLHD_UNPACKED, MediaFormat.MIMETYPE_VIDEO_VP8,
+                        ENCODE_DEFAULT_VIDEO_BIT_RATE, 1920, 1080, 1, -1, -1, -1, -1},
+                {DECODE_FULLHD_UNPACKED, MediaFormat.MIMETYPE_VIDEO_AVC,
+                        ENCODE_DEFAULT_VIDEO_BIT_RATE, 1920, 1080, 1, -1, -1, -1, -1},
+                {DECODE_FULLHD_UNPACKED, MediaFormat.MIMETYPE_VIDEO_HEVC,
+                        ENCODE_DEFAULT_VIDEO_BIT_RATE, 1920, 1080, 1, -1, -1, -1, -1},
+                {DECODE_FULLHD_UNPACKED, MediaFormat.MIMETYPE_VIDEO_VP9,
+                        ENCODE_DEFAULT_VIDEO_BIT_RATE, 1920, 1080, 1, -1, -1, -1, -1},
+                {DECODE_QCIF_UNPACKED, MediaFormat.MIMETYPE_VIDEO_MPEG4, ENCODE_MIN_VIDEO_BIT_RATE,
+                        176, 144, 1, -1, -1, -1, -1},
+                {DECODE_QCIF_UNPACKED, MediaFormat.MIMETYPE_VIDEO_H263, ENCODE_MIN_VIDEO_BIT_RATE,
+                        176, 144, 1, -1, -1, -1, -1}});
     }
 
-    public EncoderTest(String inputFileName) {
-        this.mInputFile = inputFileName;
+    public EncoderTest(String filename, String mime, int bitrate, int width, int height,
+                       int frameInterval, int profile, int level, int samplerate,
+                       int channelCount) {
+        this.mInputFile = filename;
+        this.mMime = mime;
+        this.mBitRate = bitrate;
+        this.mIFrameInterval = frameInterval;
+        this.mWidth = width;
+        this.mHeight = height;
+        this.mProfile = profile;
+        this.mLevel = level;
+        this.mSampleRate = samplerate;
+        this.mNumChannel = channelCount;
     }
 
     @BeforeClass
@@ -101,33 +149,36 @@
         Log.d(TAG, "Saving Benchmark results in: " + mStatsFile);
     }
 
-    @Test(timeout = PER_TEST_TIMEOUT_MS)
-    public void testEncoder() throws Exception {
-        int status;
-        int frameSize;
-        //Parameters for video
-        int width = 0;
-        int height = 0;
-        int profile = 0;
-        int level = 0;
-        int frameRate = 0;
+    @BeforeClass
+    public static void prepareInput() throws IOException {
 
-        //Parameters for audio
-        int bitRate = 0;
-        int sampleRate = 0;
-        int numChannels = 0;
-        File inputFile = new File(mInputFilePath + mInputFile);
-        assertTrue("Cannot find " + mInputFile + " in directory " + mInputFilePath,
-                inputFile.exists());
+        mDecodedFileFullHd = new File(mFileDirPath + DECODE_FULLHD_UNPACKED);
+        int status = decodeFile(mInputFilePath + DECODE_FULLHD_INPUT, mDecodedFileFullHd);
+        assertEquals("Decoder returned error " + status, 0, status);
+
+        mDecodedFileQcif = new File(mFileDirPath + DECODE_QCIF_UNPACKED);
+        status = decodeFile(mInputFilePath + DECODE_QCIF_INPUT, mDecodedFileQcif);
+        assertEquals("Decoder returned error " + status, 0, status);
+
+        mDecodedFileAudio = new File(mFileDirPath + DECODE_AUDIO_UNPACKED);
+        status = decodeFile(mInputFilePath + DECODE_AUDIO_INPUT, mDecodedFileAudio);
+        assertEquals("Decoder returned error " + status, 0, status);
+    }
+
+    private static int decodeFile(String inputFileName, File outputDecodeFile) throws IOException {
+        int status = -1;
+        File inputFile = new File(inputFileName);
+        assertTrue("Cannot open input file " + inputFileName, inputFile.exists());
         FileInputStream fileInput = new FileInputStream(inputFile);
         FileDescriptor fileDescriptor = fileInput.getFD();
+        FileOutputStream decodeOutputStream = new FileOutputStream(outputDecodeFile);
+
         Extractor extractor = new Extractor();
         int trackCount = extractor.setUpExtractor(fileDescriptor);
-        assertTrue("Extraction failed. No tracks for file: " + mInputFile, (trackCount > 0));
+        assertTrue("Extraction failed. No tracks for the given input file", (trackCount > 0));
         ArrayList<ByteBuffer> inputBuffer = new ArrayList<>();
         ArrayList<MediaCodec.BufferInfo> frameInfo = new ArrayList<>();
         for (int currentTrack = 0; currentTrack < trackCount; currentTrack++) {
-            int colorFormat = COLOR_FormatYUV420Flexible;
             extractor.selectExtractorTrack(currentTrack);
             MediaFormat format = extractor.getFormat(currentTrack);
             // Get samples from extractor
@@ -146,163 +197,135 @@
                             bufInfo.presentationTimeUs + " size = " + bufInfo.size);
                 }
             } while (sampleSize > 0);
-            int tid = android.os.Process.myTid();
-            File decodedFile = new File(mContext.getFilesDir() + "/decoder_" + tid + ".out");
-            FileOutputStream decodeOutputStream = new FileOutputStream(decodedFile);
             Decoder decoder = new Decoder();
             decoder.setupDecoder(decodeOutputStream);
             status = decoder.decode(inputBuffer, frameInfo, false, format, "");
-            assertEquals("Decoder returned error " + status + " for file: " + mInputFile, 0,
-                    status);
             MediaFormat decoderFormat = decoder.getFormat();
+            if (decoderFormat.containsKey(MediaFormat.KEY_COLOR_FORMAT)) {
+                mColorFormat = decoderFormat.getInteger(MediaFormat.KEY_COLOR_FORMAT);
+            }
             decoder.deInitCodec();
             extractor.unselectExtractorTrack(currentTrack);
             inputBuffer.clear();
             frameInfo.clear();
-            if (decodeOutputStream != null) {
-                decodeOutputStream.close();
-            }
-            String mime = format.getString(MediaFormat.KEY_MIME);
-            ArrayList<String> mediaCodecs = CodecUtils.selectCodecs(mime, true);
-            assertTrue("No suitable codecs found for file: " + mInputFile + " track : " +
-                    currentTrack + " mime: " + mime, (mediaCodecs.size() > 0));
-            Boolean[] encodeMode = {true, false};
-            /* Encoding the decoder's output */
-            for (Boolean asyncMode : encodeMode) {
-                for (String codecName : mediaCodecs) {
-                    FileOutputStream encodeOutputStream = null;
-                    if (WRITE_OUTPUT) {
-                        File outEncodeFile = new File(mOutputFilePath + "encoder.out");
-                        if (outEncodeFile.exists()) {
-                            assertTrue(" Unable to delete existing file" + outEncodeFile.toString(),
-                                    outEncodeFile.delete());
-                        }
-                        assertTrue("Unable to create file to write encoder output: " +
-                                outEncodeFile.toString(), outEncodeFile.createNewFile());
-                        encodeOutputStream = new FileOutputStream(outEncodeFile);
-                    }
-                    File rawFile = new File(mContext.getFilesDir() + "/decoder_" + tid + ".out");
-                    assertTrue("Cannot open file to write decoded output", rawFile.exists());
-                    if (DEBUG) {
-                        Log.i(TAG, "Path of decoded input file: " + rawFile.toString());
-                    }
-                    FileInputStream eleStream = new FileInputStream(rawFile);
-                    if (mime.startsWith("video/")) {
-                        width = format.getInteger(MediaFormat.KEY_WIDTH);
-                        height = format.getInteger(MediaFormat.KEY_HEIGHT);
-                        if (format.containsKey(MediaFormat.KEY_FRAME_RATE)) {
-                            frameRate = format.getInteger(MediaFormat.KEY_FRAME_RATE);
-                        } else if (frameRate <= 0) {
-                            frameRate = ENCODE_DEFAULT_FRAME_RATE;
-                        }
-                        if (format.containsKey(MediaFormat.KEY_BIT_RATE)) {
-                            bitRate = format.getInteger(MediaFormat.KEY_BIT_RATE);
-                        } else if (bitRate <= 0) {
-                            if (mime.contains("video/3gpp") || mime.contains("video/mp4v-es")) {
-                                bitRate = ENCODE_MIN_BIT_RATE;
-                            } else {
-                                bitRate = ENCODE_DEFAULT_BIT_RATE;
-                            }
-                        }
-                        if (format.containsKey(MediaFormat.KEY_PROFILE)) {
-                            profile = format.getInteger(MediaFormat.KEY_PROFILE);
-                        }
-                        if (format.containsKey(MediaFormat.KEY_PROFILE)) {
-                            level = format.getInteger(MediaFormat.KEY_LEVEL);
-                        }
-                        if (decoderFormat.containsKey(MediaFormat.KEY_COLOR_FORMAT)) {
-                            colorFormat = decoderFormat.getInteger(MediaFormat.KEY_COLOR_FORMAT);
-                        }
-                    } else {
-                        sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
-                        numChannels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
-                        if (decoderFormat.containsKey(MediaFormat.KEY_BIT_RATE)) {
-                            bitRate = decoderFormat.getInteger(MediaFormat.KEY_BIT_RATE);
-                        } else {
-                            bitRate = ENCODE_DEFAULT_AUDIO_BIT_RATE;
-                        }
-                    }
-                    /*Setup Encode Format*/
-                    MediaFormat encodeFormat;
-                    if (mime.startsWith("video/")) {
-                        frameSize = width * height * 3 / 2;
-                        encodeFormat = MediaFormat.createVideoFormat(mime, width, height);
-                        encodeFormat.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
-                        encodeFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
-                        encodeFormat.setInteger(MediaFormat.KEY_PROFILE, profile);
-                        encodeFormat.setInteger(MediaFormat.KEY_LEVEL, level);
-                        encodeFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
-                        encodeFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, frameSize);
-                        encodeFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat);
-                    } else {
-                        encodeFormat = MediaFormat.createAudioFormat(mime, sampleRate, numChannels);
-                        encodeFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
-                        frameSize = 4096;
-                    }
-                    Encoder encoder = new Encoder();
-                    encoder.setupEncoder(encodeOutputStream, eleStream);
-                    status = encoder.encode(codecName, encodeFormat, mime, frameRate, sampleRate,
-                            frameSize, asyncMode);
-                    encoder.deInitEncoder();
-                    assertEquals(
-                            codecName + " encoder returned error " + status + " for " + "file:" +
-                                    " " + mInputFile, 0, status);
-                    encoder.dumpStatistics(mInputFile, codecName, (asyncMode ? "async" : "sync"),
-                            extractor.getClipDuration(), mStatsFile);
-                    Log.i(TAG, "Encoding complete for file: " + mInputFile + " with codec: " +
-                            codecName + " for aSyncMode = " + asyncMode);
-                    encoder.resetEncoder();
-                    eleStream.close();
-                    if (encodeOutputStream != null) {
-                        encodeOutputStream.close();
-                    }
-
-                }
-            }
-            //Cleanup temporary input file
-            if (decodedFile.exists()) {
-                assertTrue(" Unable to delete decoded file" + decodedFile.toString(),
-                        decodedFile.delete());
-                Log.i(TAG, "Successfully deleted decoded file");
-            }
         }
         extractor.deinitExtractor();
         fileInput.close();
+        decodeOutputStream.close();
+        return status;
     }
 
     @Test(timeout = PER_TEST_TIMEOUT_MS)
-    public void testNativeEncoder() throws Exception {
-        File inputFile = new File(mInputFilePath + mInputFile);
-        assertTrue("Cannot find " + mInputFile + " in directory " + mInputFilePath,
-                inputFile.exists());
-        int tid = android.os.Process.myTid();
-        final String mDecodedFile = mContext.getFilesDir() + "/decoder_" + tid + ".out";
-        FileInputStream fileInput = new FileInputStream(inputFile);
-        FileDescriptor fileDescriptor = fileInput.getFD();
-        Extractor extractor = new Extractor();
-        int trackCount = extractor.setUpExtractor(fileDescriptor);
-        assertTrue("Extraction failed. No tracks for file: ", trackCount > 0);
-        for (int currentTrack = 0; currentTrack < trackCount; currentTrack++) {
-            extractor.selectExtractorTrack(currentTrack);
-            MediaFormat format = extractor.getFormat(currentTrack);
-            String mime = format.getString(MediaFormat.KEY_MIME);
-            ArrayList<String> mediaCodecs = CodecUtils.selectCodecs(mime, true);
-            // Encoding the decoder's output
+    public void testEncoder() throws Exception {
+        int status;
+        int frameSize;
+
+        ArrayList<String> mediaCodecs = CodecUtils.selectCodecs(mMime, true);
+        assertTrue("No suitable codecs found for mimetype: " + mMime, (mediaCodecs.size() > 0));
+        Boolean[] encodeMode = {true, false};
+        // Encoding the decoded input file
+        for (Boolean asyncMode : encodeMode) {
             for (String codecName : mediaCodecs) {
-                Native nativeEncoder = new Native();
-                int status = nativeEncoder
-                        .Encode(mInputFilePath, mInputFile, mDecodedFile, mStatsFile, codecName);
+                FileOutputStream encodeOutputStream = null;
+                if (WRITE_OUTPUT) {
+                    File outEncodeFile = new File(mOutputFilePath + "encoder.out");
+                    if (outEncodeFile.exists()) {
+                        assertTrue(" Unable to delete existing file" + outEncodeFile.toString(),
+                                outEncodeFile.delete());
+                    }
+                    assertTrue("Unable to create file to write encoder output: " +
+                            outEncodeFile.toString(), outEncodeFile.createNewFile());
+                    encodeOutputStream = new FileOutputStream(outEncodeFile);
+                }
+                File rawFile = new File(mFileDirPath + mInputFile);
+                assertTrue("Cannot open decoded input file", rawFile.exists());
+                if (DEBUG) {
+                    Log.i(TAG, "Path of decoded input file: " + rawFile.toString());
+                }
+                FileInputStream eleStream = new FileInputStream(rawFile);
+                // Setup Encode Format
+                MediaFormat encodeFormat;
+                if (mMime.startsWith("video/")) {
+                    frameSize = mWidth * mHeight * 3 / 2;
+                    encodeFormat = MediaFormat.createVideoFormat(mMime, mWidth, mHeight);
+                    encodeFormat.setInteger(MediaFormat.KEY_FRAME_RATE, ENCODE_DEFAULT_FRAME_RATE);
+                    encodeFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, mIFrameInterval);
+                    encodeFormat.setInteger(MediaFormat.KEY_BIT_RATE, mBitRate);
+                    encodeFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, mColorFormat);
+                    if (mProfile != -1 && mLevel != -1) {
+                        encodeFormat.setInteger(MediaFormat.KEY_PROFILE, mProfile);
+                        encodeFormat.setInteger(MediaFormat.KEY_LEVEL, mLevel);
+                    }
+                } else {
+                    frameSize = 4096;
+                    encodeFormat = MediaFormat.createAudioFormat(mMime, mSampleRate, mNumChannel);
+                    encodeFormat.setInteger(MediaFormat.KEY_BIT_RATE, mBitRate);
+                }
+                Encoder encoder = new Encoder();
+                encoder.setupEncoder(encodeOutputStream, eleStream);
+                status = encoder.encode(codecName, encodeFormat, mMime, ENCODE_DEFAULT_FRAME_RATE,
+                        mSampleRate, frameSize, asyncMode);
+                encoder.deInitEncoder();
                 assertEquals(
-                        codecName + " encoder returned error " + status + " for " + "file:" + " " +
-                                mInputFile, 0, status);
+                        codecName + " encoder returned error " + status + " for " + "mime:" + " " +
+                                mMime, 0, status);
+                String inputReference;
+                long durationUs;
+                if (mMime.startsWith("video/")) {
+                    inputReference =
+                            mInputFile + "_" + mWidth + "x" + mHeight + "_" + mBitRate + "bps";
+                    durationUs = (((eleStream.getChannel().size() + frameSize - 1) / frameSize) /
+                            ENCODE_DEFAULT_FRAME_RATE) * 1000000;
+                } else {
+                    inputReference = mInputFile + "_" + mSampleRate + "hz_" + mNumChannel + "ch_" +
+                            mBitRate + "bps";
+                    durationUs =
+                            (eleStream.getChannel().size() / (mSampleRate * mNumChannel)) * 1000000;
+                }
+                encoder.dumpStatistics(inputReference, codecName, (asyncMode ? "async" : "sync"),
+                        durationUs, mStatsFile);
+                Log.i(TAG, "Encoding complete for mime: " + mMime + " with codec: " + codecName +
+                        " for aSyncMode = " + asyncMode);
+                encoder.resetEncoder();
+                eleStream.close();
+                if (encodeOutputStream != null) {
+                    encodeOutputStream.close();
+                }
             }
         }
-        File decodedFile = new File(mDecodedFile);
-        // Cleanup temporary input file
-        if (decodedFile.exists()) {
-            assertTrue("Unable to delete - " + mDecodedFile, decodedFile.delete());
-            Log.i(TAG, "Successfully deleted - " + mDecodedFile);
+    }
+
+    @Test(timeout = PER_TEST_TIMEOUT_MS)
+    public void testNativeEncoder() {
+        ArrayList<String> mediaCodecs = CodecUtils.selectCodecs(mMime, true);
+        assertTrue("No suitable codecs found for mimetype: " + mMime, (mediaCodecs.size() > 0));
+        for (String codecName : mediaCodecs) {
+            Native nativeEncoder = new Native();
+            int status = nativeEncoder
+                    .Encode(mFileDirPath, mInputFile, mStatsFile, codecName, mMime, mBitRate,
+                            mColorFormat, mIFrameInterval, mWidth, mHeight, mProfile, mLevel,
+                            mSampleRate, mNumChannel);
+            assertEquals(codecName + " encoder returned error " + status + " for " + "mime:" + " " +
+                    mMime, 0, status);
         }
-        fileInput.close();
+    }
+
+    @AfterClass
+    public static void deleteDecodedFiles() {
+        if (mDecodedFileFullHd.exists()) {
+            assertTrue(" Unable to delete decoded file" + mDecodedFileFullHd.toString(),
+                    mDecodedFileFullHd.delete());
+            Log.i(TAG, "Successfully deleted decoded file" + mDecodedFileFullHd.toString());
+        }
+        if (mDecodedFileQcif.exists()) {
+            assertTrue(" Unable to delete decoded file" + mDecodedFileQcif.toString(),
+                    mDecodedFileQcif.delete());
+            Log.i(TAG, "Successfully deleted decoded file" + mDecodedFileQcif.toString());
+        }
+        if (mDecodedFileAudio.exists()) {
+            assertTrue(" Unable to delete decoded file" + mDecodedFileAudio.toString(),
+                    mDecodedFileAudio.delete());
+            Log.i(TAG, "Successfully deleted decoded file" + mDecodedFileAudio.toString());
+        }
     }
 }
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/Android.bp b/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/Android.bp
index 3e5e4c8..af92424 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/Android.bp
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test_library {
     name: "libmediabenchmark_jni",
     sdk_version: "current",
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/NativeEncoder.cpp b/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/NativeEncoder.cpp
index 1277c8b..2f658e3 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/NativeEncoder.cpp
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/NativeEncoder.cpp
@@ -30,189 +30,81 @@
 #include <stdio.h>
 
 constexpr int32_t ENCODE_DEFAULT_FRAME_RATE = 25;
-constexpr int32_t ENCODE_DEFAULT_AUDIO_BIT_RATE = 128000 /* 128 Kbps */;
-constexpr int32_t ENCODE_DEFAULT_BIT_RATE = 8000000 /* 8 Mbps */;
-constexpr int32_t ENCODE_MIN_BIT_RATE = 600000 /* 600 Kbps */;
 
 extern "C" JNIEXPORT int JNICALL Java_com_android_media_benchmark_library_Native_Encode(
-        JNIEnv *env, jobject thiz, jstring jFilePath, jstring jFileName, jstring jOutFilePath,
-        jstring jStatsFile, jstring jCodecName) {
+        JNIEnv *env, jobject thiz, jstring jFilePath, jstring jFileName, jstring jStatsFile,
+        jstring jCodecName, jstring jMime, jint jBitRate, jint jColorFormat, jint jFrameInterval,
+        jint jWidth, jint jHeight, jint jProfile, jint jLevel, jint jSampleRate,
+        jint jNumChannels) {
+    UNUSED(thiz);
     const char *filePath = env->GetStringUTFChars(jFilePath, nullptr);
     const char *fileName = env->GetStringUTFChars(jFileName, nullptr);
-    string sFilePath = string(filePath) + string(fileName);
-    UNUSED(thiz);
-    FILE *inputFp = fopen(sFilePath.c_str(), "rb");
-    env->ReleaseStringUTFChars(jFileName, fileName);
-    env->ReleaseStringUTFChars(jFilePath, filePath);
-    if (!inputFp) {
-        ALOGE("Unable to open input file for reading");
+    string inputFile = string(filePath) + string(fileName);
+    const char *codecName = env->GetStringUTFChars(jCodecName, nullptr);
+    string sCodecName = string(codecName);
+    const char *mime = env->GetStringUTFChars(jMime, nullptr);
+
+    ifstream eleStream;
+    eleStream.open(inputFile, ifstream::binary | ifstream::ate);
+    if (!eleStream.is_open()) {
+        ALOGE("%s - File failed to open for reading!", fileName);
+        env->ReleaseStringUTFChars(jFileName, fileName);
         return -1;
     }
 
-    Decoder *decoder = new Decoder();
-    Extractor *extractor = decoder->getExtractor();
-    if (!extractor) {
-        ALOGE("Extractor creation failed");
-        return -1;
-    }
+    bool asyncMode[2] = {true, false};
+    for (bool mode : asyncMode) {
+        size_t eleSize = eleStream.tellg();
+        eleStream.seekg(0, ifstream::beg);
 
-    // Read file properties
-    struct stat buf;
-    stat(sFilePath.c_str(), &buf);
-    size_t fileSize = buf.st_size;
-    if (fileSize > kMaxBufferSize) {
-        ALOGE("File size greater than maximum buffer size");
-        return -1;
-    }
-    int32_t fd = fileno(inputFp);
-    int32_t trackCount = extractor->initExtractor(fd, fileSize);
-    if (trackCount <= 0) {
-        ALOGE("initExtractor failed");
-        return -1;
-    }
+        // Set encoder params
+        encParameter encParams;
+        encParams.width = jWidth;
+        encParams.height = jHeight;
+        encParams.bitrate = jBitRate;
+        encParams.iFrameInterval = jFrameInterval;
+        encParams.sampleRate = jSampleRate;
+        encParams.numChannels = jNumChannels;
+        encParams.frameRate = ENCODE_DEFAULT_FRAME_RATE;
+        encParams.colorFormat = jColorFormat;
+        encParams.profile = jProfile;
+        encParams.level = jLevel;
 
-    for (int curTrack = 0; curTrack < trackCount; curTrack++) {
-        int32_t status = extractor->setupTrackFormat(curTrack);
-        if (status != 0) {
-            ALOGE("Track Format invalid");
-            return -1;
-        }
-        uint8_t *inputBuffer = (uint8_t *)malloc(fileSize);
-        if (!inputBuffer) {
-            ALOGE("Insufficient memory");
-            return -1;
-        }
-        vector<AMediaCodecBufferInfo> frameInfo;
-        AMediaCodecBufferInfo info;
-        uint32_t inputBufferOffset = 0;
-
-        // Get frame data
-        while (1) {
-            status = extractor->getFrameSample(info);
-            if (status || !info.size) break;
-            // copy the meta data and buffer to be passed to decoder
-            if (inputBufferOffset + info.size > kMaxBufferSize) {
-                ALOGE("Memory allocated not sufficient");
-                free(inputBuffer);
-                return -1;
-            }
-            memcpy(inputBuffer + inputBufferOffset, extractor->getFrameBuf(), info.size);
-            frameInfo.push_back(info);
-            inputBufferOffset += info.size;
-        }
-        string decName = "";
-        const char *outputFilePath = env->GetStringUTFChars(jOutFilePath, nullptr);
-        FILE *outFp = fopen(outputFilePath, "wb");
-        if (outFp == nullptr) {
-            ALOGE("%s - File failed to open for writing!", outputFilePath);
-            free(inputBuffer);
-            return -1;
-        }
-        decoder->setupDecoder();
-        status = decoder->decode(inputBuffer, frameInfo, decName, false /*asyncMode */, outFp);
+        Encoder *encoder = new Encoder();
+        encoder->setupEncoder();
+        auto status = encoder->encode(sCodecName, eleStream, eleSize, mode, encParams,
+                                      const_cast<char *>(mime));
         if (status != AMEDIA_OK) {
-            ALOGE("Decode returned error");
-            free(inputBuffer);
+            ALOGE("Encoder returned error");
             return -1;
         }
-
-        AMediaFormat *decoderFormat = decoder->getFormat();
-        AMediaFormat *format = extractor->getFormat();
-        if (inputBuffer) {
-            free(inputBuffer);
-            inputBuffer = nullptr;
+        ALOGV("Encoding complete with codec %s for asyncMode = %d", sCodecName.c_str(), mode);
+        encoder->deInitCodec();
+        const char *statsFile = env->GetStringUTFChars(jStatsFile, nullptr);
+        string inputReference;
+        int64_t clipDurationUs;
+        if (!strncmp(mime, "video/", 6)) {
+            inputReference = string(fileName) + "_" + to_string(jWidth) + "x" + to_string(jHeight) +
+                             "_" + to_string(jBitRate) + "bps";
+            int32_t frameSize = jWidth * jHeight * 3 / 2;
+            clipDurationUs =
+                    (((eleSize + frameSize - 1) / frameSize) / ENCODE_DEFAULT_FRAME_RATE) * 1000000;
+        } else {
+            inputReference = string(fileName) + "_" + to_string(jSampleRate) + "hz_" +
+                             to_string(jNumChannels) + "ch_" + to_string(jBitRate) + "bps";
+            clipDurationUs = (eleSize / (jSampleRate * jNumChannels)) * 1000000;
         }
-        const char *mime = nullptr;
-        AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime);
-        if (!mime) {
-            ALOGE("Error in AMediaFormat_getString");
-            return -1;
-        }
-        ifstream eleStream;
-        eleStream.open(outputFilePath, ifstream::binary | ifstream::ate);
-        if (!eleStream.is_open()) {
-            ALOGE("%s - File failed to open for reading!", outputFilePath);
-            env->ReleaseStringUTFChars(jOutFilePath, outputFilePath);
-            return -1;
-        }
-        const char *codecName = env->GetStringUTFChars(jCodecName, NULL);
-        const char *inputReference = env->GetStringUTFChars(jFileName, nullptr);
-        string sCodecName = string(codecName);
-        string sInputReference = string(inputReference);
-
-        bool asyncMode[2] = {true, false};
-        for (int i = 0; i < 2; i++) {
-            size_t eleSize = eleStream.tellg();
-            eleStream.seekg(0, ifstream::beg);
-
-            // Get encoder params
-            encParameter encParams;
-            if (!strncmp(mime, "video/", 6)) {
-                AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_WIDTH, &encParams.width);
-                AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_HEIGHT, &encParams.height);
-                AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_FRAME_RATE, &encParams.frameRate);
-                AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_BIT_RATE, &encParams.bitrate);
-                if (encParams.bitrate <= 0 || encParams.frameRate <= 0) {
-                    encParams.frameRate = ENCODE_DEFAULT_FRAME_RATE;
-                    if (!strcmp(mime, "video/3gpp") || !strcmp(mime, "video/mp4v-es")) {
-                        encParams.bitrate = ENCODE_MIN_BIT_RATE /* 600 Kbps */;
-                    } else {
-                        encParams.bitrate = ENCODE_DEFAULT_BIT_RATE /* 8 Mbps */;
-                    }
-                }
-                AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_PROFILE, &encParams.profile);
-                AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_LEVEL, &encParams.level);
-                AMediaFormat_getInt32(decoderFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT,
-                                      &encParams.colorFormat);
-            } else {
-                AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, &encParams.sampleRate);
-                AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT,
-                                      &encParams.numChannels);
-                encParams.bitrate = ENCODE_DEFAULT_AUDIO_BIT_RATE;
-            }
-            Encoder *encoder = new Encoder();
-            encoder->setupEncoder();
-            status = encoder->encode(sCodecName, eleStream, eleSize, asyncMode[i], encParams,
-                                     (char *)mime);
-            if (status != AMEDIA_OK) {
-                ALOGE("Encoder returned error");
-                return -1;
-            }
-            ALOGV("Encoding complete with codec %s for asyncMode = %d", sCodecName.c_str(),
-                  asyncMode[i]);
-            encoder->deInitCodec();
-            const char *statsFile = env->GetStringUTFChars(jStatsFile, nullptr);
-            encoder->dumpStatistics(sInputReference, extractor->getClipDuration(), sCodecName,
-                                    (asyncMode[i] ? "async" : "sync"), statsFile);
-            env->ReleaseStringUTFChars(jStatsFile, statsFile);
-            encoder->resetEncoder();
-            delete encoder;
-            encoder = nullptr;
-        }
-        eleStream.close();
-        if (outFp) {
-            fclose(outFp);
-            outFp = nullptr;
-        }
-        env->ReleaseStringUTFChars(jFileName, inputReference);
-        env->ReleaseStringUTFChars(jCodecName, codecName);
-        env->ReleaseStringUTFChars(jOutFilePath, outputFilePath);
-        if (format) {
-            AMediaFormat_delete(format);
-            format = nullptr;
-        }
-        if (decoderFormat) {
-            AMediaFormat_delete(decoderFormat);
-            decoderFormat = nullptr;
-        }
-        decoder->deInitCodec();
-        decoder->resetDecoder();
+        encoder->dumpStatistics(inputReference, clipDurationUs, sCodecName,
+                                (mode ? "async" : "sync"), statsFile);
+        env->ReleaseStringUTFChars(jStatsFile, statsFile);
+        encoder->resetEncoder();
+        delete encoder;
+        encoder = nullptr;
     }
-    if (inputFp) {
-        fclose(inputFp);
-        inputFp = nullptr;
-    }
-    extractor->deInitExtractor();
-    delete decoder;
+    eleStream.close();
+    env->ReleaseStringUTFChars(jFilePath, filePath);
+    env->ReleaseStringUTFChars(jFileName, fileName);
+    env->ReleaseStringUTFChars(jMime, mime);
+    env->ReleaseStringUTFChars(jCodecName, codecName);
     return 0;
 }
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Encoder.java b/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Encoder.java
index 45e5574..754cd8e 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Encoder.java
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Encoder.java
@@ -175,10 +175,10 @@
 
                 @Override
                 public void onError(@NonNull MediaCodec mediaCodec, @NonNull CodecException e) {
-                    mediaCodec.stop();
-                    mediaCodec.release();
-                    Log.e(TAG, "CodecError: " + e.toString());
+                    mSignalledError = true;
+                    Log.e(TAG, "Codec Error: " + e.toString());
                     e.printStackTrace();
+                    synchronized (mLock) { mLock.notify(); }
                 }
 
                 @Override
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Native.java b/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Native.java
index 38b608a..3e3969c 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Native.java
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Native.java
@@ -27,6 +27,7 @@
     public native int Decode(String inputFilePath, String inputFileName, String statsFile,
             String codecName, boolean asyncMode);
 
-    public native int Encode(String inputFilePath, String inputFileName, String outputFilePath,
-            String statsFile, String codecName);
+    public native int Encode(String inputFilePath, String inputFileName, String statsFile,
+            String codecName, String mime, int bitRate, int colorFormat, int frameInterval,
+            int width, int height, int profile, int level, int sampleRate, int numChannel);
 }
diff --git a/media/tests/benchmark/README.md b/media/tests/benchmark/README.md
index 05fbe6f..047c289 100644
--- a/media/tests/benchmark/README.md
+++ b/media/tests/benchmark/README.md
@@ -1,7 +1,7 @@
 # Benchmark tests
 
 Benchmark app analyses the time taken by MediaCodec, MediaExtractor and MediaMuxer for given set of inputs. It is used to benchmark these modules on android devices.
-Benchmark results are emitted to logcat.
+Benchmark results are published as a CSV report.
 
 This page describes steps to run the NDK and SDK layer test.
 
@@ -10,35 +10,49 @@
 mmm frameworks/av/media/tests/benchmark/
 ```
 
-# NDK
-
-To run the test suite for measuring performance of the native layer, follow the following steps:
-
-The binaries will be created in the following path : $OUT/data/nativetest64/
-
-adb push $OUT/data/nativetest64/* /data/local/tmp/
-
-Eg. adb push $OUT/data/nativetest64/extractorTest/extractorTest /data/local/tmp/
-
-To run the binary, follow the commands mentioned below under each module.
-
-The resource file for the tests is taken from [here](https://drive.google.com/open?id=1ghMr17BBJ7n0pqbm7oREiTN_MNemJUqy)
+# Resources
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/tests/benchmark/MediaBenchmark.zip)
 
 Download the MediaBenchmark.zip file, unzip and push it to /data/local/tmp/ on the device.
 
 ```
 unzip MediaBenchmark.zip
-adb push MediaBenchmark /data/local/tmp
+adb push MediaBenchmark /data/local/tmp/MediaBenchmark/res/
 ```
 
+The resource files are assumed to be at /data/local/tmp/MediaBenchmark/res/. You can use a different location, but you have to modify the rest of the instructions to replace /data/local/tmp/MediaBenchmark/res/ with wherever you chose to put the files.
+
+# NDK CLI Tests
+Note: [Benchmark Application](#BenchmarkApplication) now supports profiling both SDK and NDK APIs and that is the preferred way to benchmark codecs
+
+To run the test suite for measuring performance of the native layer, follow the following steps:
+
+The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
+
+To test 64-bit binary push binaries from nativetest64.
+
+adb push $OUT/data/nativetest64/* /data/local/tmp/. For example
+
+```
+adb push $OUT/data/nativetest64/extractorTest/extractorTest /data/local/tmp/
+```
+
+The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
+To test 32-bit binary push binaries from nativetest.
+
+adb push $OUT/data/nativetest/* /data/local/tmp/. For example
+
+```
+adb push $OUT/data/nativetest/extractorTest/extractorTest /data/local/tmp/
+```
+
+To run the binary, follow the commands mentioned below under each module.
+
 ## Extractor
 
 The test extracts elementary stream and benchmarks the extractors available in NDK.
 
-The resource files are assumed to be at /data/local/tmp/MediaBenchmark/res/. You can use a different location, but you have to modify the rest of the instructions to replace /data/local/tmp/MediaBenchmark/res/ with wherever you chose to put the files.
-
-The path to these files on the device is required to be given for the test.
-
 ```
 adb shell /data/local/tmp/extractorTest -P /data/local/tmp/MediaBenchmark/res/
 ```
@@ -47,8 +61,6 @@
 
 The test decodes input stream and benchmarks the decoders available in NDK.
 
-Setup steps are same as extractor.
-
 ```
 adb shell /data/local/tmp/decoderTest -P /data/local/tmp/MediaBenchmark/res/
 ```
@@ -57,8 +69,6 @@
 
 The test muxes elementary stream and benchmarks the muxers available in NDK.
 
-Setup steps are same as extractor.
-
 ```
 adb shell /data/local/tmp/muxerTest -P /data/local/tmp/MediaBenchmark/res/
 ```
@@ -67,55 +77,82 @@
 
 The test encodes input stream and benchmarks the encoders available in NDK.
 
-Setup steps are same as extractor.
-
 ```
 adb shell /data/local/tmp/encoderTest -P /data/local/tmp/MediaBenchmark/res/
 ```
 
-# SDK
+# <a name="BenchmarkApplication"></a> Benchmark Application
+To run the test suite for measuring performance of the SDK and NDK APIs, follow the following steps:
+Benchmark Application can be run in two ways.
 
-To run the test suite for measuring performance of the SDK APIs, follow the following steps:
+## Steps to run with atest
+Note that atest command will install Benchmark application and push the required test files to the device as well.
+
+For running all the tests, run the following command
+```
+atest com.android.media.benchmark.tests -- --enable-module-dynamic-download=true
+```
+
+For running the tests individually, run the following atest commands:
+
+```
+atest com.android.media.benchmark.tests.ExtractorTest -- --enable-module-dynamic-download=true
+atest com.android.media.benchmark.tests.DecoderTest -- --enable-module-dynamic-download=true
+atest com.android.media.benchmark.tests.MuxerTest -- --enable-module-dynamic-download=true
+atest com.android.media.benchmark.tests.EncoderTest -- --enable-module-dynamic-download=true
+```
+
+## Steps to run without atest
 
 The apk will be created at the following path:
-$OUT/testcases/MediaBenchmarkTest/arm64/
 
-To get the resorce files for the test follow instructions given in [NDK](#NDK)
+The 64-bit apk will be created in the following path :
+$OUT/testcases/MediaBenchmarkTest/arm64/
 
 For installing the apk, run the command:
 ```
 adb install -f -r $OUT/testcases/MediaBenchmarkTest/arm64/MediaBenchmarkTest.apk
 ```
 
-For running all the tests, run the command:
+The 32-bit apk will be created in the following path :
+$OUT/testcases/MediaBenchmarkTest/arm/
+
+For installing the apk, run the command:
+```
+adb install -f -r $OUT/testcases/MediaBenchmarkTest/arm/MediaBenchmarkTest.apk
+```
+
+To get the resource files for the test follow instructions given in [Resources](#Resources)
+
+For running all the tests, run the following command
 ```
 adb shell am instrument -w -r -e package com.android.media.benchmark.tests com.android.media.benchmark/androidx.test.runner.AndroidJUnitRunner
 ```
 
 ## Extractor
 
-The test extracts elementary stream and benchmarks the extractors available in SDK.
+The test extracts elementary stream and benchmarks the extractors available in SDK and NDK.
 ```
 adb shell am instrument -w -r -e class 'com.android.media.benchmark.tests.ExtractorTest' com.android.media.benchmark/androidx.test.runner.AndroidJUnitRunner
 ```
 
 ## Decoder
 
-The test decodes input stream and benchmarks the decoders available in SDK.
+The test decodes input stream and benchmarks the decoders available in SDK and NDK.
 ```
 adb shell am instrument -w -r -e class 'com.android.media.benchmark.tests.DecoderTest' com.android.media.benchmark/androidx.test.runner.AndroidJUnitRunner
 ```
 
 ## Muxer
 
-The test muxes elementary stream and benchmarks different writers available in SDK.
+The test muxes elementary stream and benchmarks different writers available in SDK and NDK.
 ```
 adb shell am instrument -w -r -e class 'com.android.media.benchmark.tests.MuxerTest' com.android.media.benchmark/androidx.test.runner.AndroidJUnitRunner
 ```
 
 ## Encoder
 
-The test encodes input stream and benchmarks the encoders available in SDK.
+The test encodes input stream and benchmarks the encoders available in SDK and NDK.
 ```
 adb shell am instrument -w -r -e class 'com.android.media.benchmark.tests.EncoderTest' com.android.media.benchmark/androidx.test.runner.AndroidJUnitRunner
 ```
@@ -124,24 +161,27 @@
 To run the test suite for measuring performance of the codec2 layer, follow the following steps:
 
 The 32-bit binaries will be created in the following path : ${OUT}/data/nativetest/
+
 The 64-bit binaries will be created in the following path : ${OUT}/data/nativetest64/
 
 To test 64-bit binary push binaries from nativetest64.
 adb push $(OUT)/data/nativetest64/* /data/local/tmp/
-Eg. adb push $(OUT)/data/nativetest64/C2DecoderTest/C2DecoderTest /data/local/tmp/
+```
+adb push $(OUT)/data/nativetest64/C2DecoderTest/C2DecoderTest /data/local/tmp/
+```
 
 To test 32-bit binary push binaries from nativetest.
 adb push $(OUT)/data/nativetest/* /data/local/tmp/
-Eg. adb push $(OUT)/data/nativetest/C2DecoderTest/C2DecoderTest /data/local/tmp/
+```
+adb push $(OUT)/data/nativetest/C2DecoderTest/C2DecoderTest /data/local/tmp/
+```
 
-To get the resource files for the test follow instructions given in [NDK](#NDK)
+To get the resource files for the test follow instructions given in [Resources](#Resources)
 
 ## C2 Decoder
 
 The test decodes input stream and benchmarks the codec2 decoders available in device.
 
-Setup steps are same as [extractor](#extractor).
-
 ```
 adb shell /data/local/tmp/C2DecoderTest -P /data/local/tmp/MediaBenchmark/res/
 ```
@@ -149,8 +189,95 @@
 
 The test encodes input stream and benchmarks the codec2 encoders available in device.
 
-Setup steps are same as [extractor](#extractor).
-
 ```
 adb shell /data/local/tmp/C2EncoderTest -P /data/local/tmp/MediaBenchmark/res/
 ```
+
+# Analysis
+
+The benchmark results are stored in a CSV file which can be used for analysis. These results are stored in following format:
+<app directory>/<module_name>.<timestamp>.csv
+
+Note: This timestamp is in nano seconds and will change based on current system time.
+
+To find the location of the CSV file, look for the path in logs. Example log below -
+
+```
+com.android.media.benchmark D/DecoderTest: Saving Benchmark results in: /storage/emulated/0/Android/data/com.android.media.benchmark/files/Decoder.1587732395387.csv
+```
+
+This file can be pulled from the device using "adb pull" command.
+```
+adb pull /storage/emulated/0/Android/data/com.android.media.benchmark/files/Decoder.1587732395387.csv ./Decoder.1587732395387.csv
+```
+
+## CSV Columns
+
+Following columns are available in CSV.
+
+Note: All time values are in nano seconds
+
+1. **currentTime** : The time recorded at the creation of the stats. This may be used to estimate time between consecutive test clips.
+
+2. **fileName**: The file being used as an input for the benchmark test.
+
+3. **operation**: The current operation on the input test vector i.e. Extract/Mux/Encode/Decode.
+
+4. **NDK/SDK**: The target APIs i.e. AMedia vs Media calls for the operation being performed.
+
+5. **sync/async**: This is specific to MediaCodec objects (i.e. Encoder and Decoder). It specifies the mode in which MediaCodec APIs are working. For async mode, callbacks are set. For sync mode, we have to poll the dequeueBuffer APIs to queue and dequeue input output buffers respectively.
+
+6. **setupTime**: The time taken to set up the MediaExtractor/Muxer/Codec instance.
+
+    * MediaCodec: includes setting async/sync mode, configuring with a format and codec.start
+
+    * MediaExtractor: includes AMediaExtractor_new and setDataSource.
+
+    * MediaMuxer: includes creating the object, adding track, and starting the muxer.
+
+7. **destroyTime**: The time taken to stop and close MediaExtractor/Muxer/Codec instance.
+
+8. **minimumTime**: The minimum time taken to extract/mux/encode/decode a frame.
+
+9. **maximumTime**: The maximum time taken to extract/mux/encode/decode a frame.
+
+10. **averageTime**: Average time taken to extract/mux/encode/decode per frame.
+
+    * MediaCodec: computed as the total time taken to encode/decode all frames divided by the number of frames encoded/decoded.
+
+    * MediaExtractor: computed as the total time taken to extract all frames divided by the number of frames extracted.
+
+    * MediaMuxer: computed as the total time taken to mux all frames divided by the number of frames muxed.
+
+11. **timeToProcess1SecContent**: The time required to process one second worth input data.
+
+12. **totalBytesProcessedPerSec**: The number of bytes extracted/muxed/decoded/encoded per second.
+
+13. **timeToFirstFrame**: The time taken to receive the first output frame.
+
+14. **totalSizeInBytes**: The total output size of the operation (in bytes).
+
+15. **totalTime**: The time taken to perform the complete operation (i.e. Extract/Mux/Decode/Encode) for respective test vector.
+
+
+## Muxer
+1. **componentName**: The format of the output Media file. Following muxers are currently supported:
+     * Ogg, Webm, 3gpp, and mp4.
+
+## Decoder
+1. **componentName**: Includes all supported codecs on the device. Aliased components are skipped.
+    *   Video: H263, H264, H265, VPx, Mpeg4, Mpeg2, AV1
+    *   Audio: AAC, Flac, Opus, MP3, Vorbis, GSM, AMR-NB/WB
+
+## Encoder
+1. **componentName**: Includes all supported codecs on the device. Aliased components are skipped.
+    *   Video: H263, H264, H265, VPx, Mpeg4
+    *   Audio: AAC, Flac, Opus, AMR-NB/WB
+
+## Common Failures
+On some devices, if a codec isn't supported some tests may report a failure like "codec not found for"
+
+For example: On mobile devices without support for mpeg2 decoder, following failure is observed:
+```
+Unable to create codec by mime: video/mpeg2
+```
diff --git a/media/tests/benchmark/src/native/common/Android.bp b/media/tests/benchmark/src/native/common/Android.bp
index d4389da..6b54c6a 100644
--- a/media/tests/benchmark/src/native/common/Android.bp
+++ b/media/tests/benchmark/src/native/common/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_static {
     name: "libmediabenchmark_common",
     defaults: [
diff --git a/media/tests/benchmark/src/native/decoder/Android.bp b/media/tests/benchmark/src/native/decoder/Android.bp
index 9791c11..601b2f6 100644
--- a/media/tests/benchmark/src/native/decoder/Android.bp
+++ b/media/tests/benchmark/src/native/decoder/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_static {
     name: "libmediabenchmark_decoder",
     defaults: [
diff --git a/media/tests/benchmark/src/native/decoder/C2Decoder.cpp b/media/tests/benchmark/src/native/decoder/C2Decoder.cpp
index 20a1468..46c4a7c 100644
--- a/media/tests/benchmark/src/native/decoder/C2Decoder.cpp
+++ b/media/tests/benchmark/src/native/decoder/C2Decoder.cpp
@@ -156,9 +156,11 @@
     mStats->setDeInitTime(timeTaken);
 }
 
-void C2Decoder::dumpStatistics(string inputReference, int64_t durationUs) {
+void C2Decoder::dumpStatistics(string inputReference, int64_t durationUs, string componentName,
+                               string statsFile) {
     string operation = "c2decode";
-    mStats->dumpStatistics(operation, inputReference, durationUs);
+    string mode = "async";
+    mStats->dumpStatistics(operation, inputReference, durationUs, componentName, mode, statsFile);
 }
 
 void C2Decoder::resetDecoder() {
diff --git a/media/tests/benchmark/src/native/decoder/C2Decoder.h b/media/tests/benchmark/src/native/decoder/C2Decoder.h
index 4a3eb96..fb35a66 100644
--- a/media/tests/benchmark/src/native/decoder/C2Decoder.h
+++ b/media/tests/benchmark/src/native/decoder/C2Decoder.h
@@ -31,7 +31,8 @@
 
     void deInitCodec();
 
-    void dumpStatistics(string inputReference, int64_t durationUs);
+    void dumpStatistics(string inputReference, int64_t durationUs, string componentName,
+                        string statsFile);
 
     void resetDecoder();
 
diff --git a/media/tests/benchmark/src/native/encoder/Android.bp b/media/tests/benchmark/src/native/encoder/Android.bp
index 8de7823..a787068 100644
--- a/media/tests/benchmark/src/native/encoder/Android.bp
+++ b/media/tests/benchmark/src/native/encoder/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_static {
     name: "libmediabenchmark_encoder",
     defaults: [
diff --git a/media/tests/benchmark/src/native/encoder/C2Encoder.cpp b/media/tests/benchmark/src/native/encoder/C2Encoder.cpp
index 33429ef..6a50d40 100644
--- a/media/tests/benchmark/src/native/encoder/C2Encoder.cpp
+++ b/media/tests/benchmark/src/native/encoder/C2Encoder.cpp
@@ -251,9 +251,11 @@
     mStats->setDeInitTime(timeTaken);
 }
 
-void C2Encoder::dumpStatistics(string inputReference, int64_t durationUs) {
+void C2Encoder::dumpStatistics(string inputReference, int64_t durationUs, string componentName,
+                               string statsFile) {
     string operation = "c2encode";
-    mStats->dumpStatistics(operation, inputReference, durationUs);
+    string mode = "async";
+    mStats->dumpStatistics(operation, inputReference, durationUs, componentName, mode, statsFile);
 }
 
 void C2Encoder::resetEncoder() {
diff --git a/media/tests/benchmark/src/native/encoder/C2Encoder.h b/media/tests/benchmark/src/native/encoder/C2Encoder.h
index a4ca097..7a021f4 100644
--- a/media/tests/benchmark/src/native/encoder/C2Encoder.h
+++ b/media/tests/benchmark/src/native/encoder/C2Encoder.h
@@ -44,7 +44,8 @@
 
     void deInitCodec();
 
-    void dumpStatistics(string inputReference, int64_t durationUs);
+    void dumpStatistics(string inputReference, int64_t durationUs, string componentName,
+                        string statsFile);
 
     void resetEncoder();
 
diff --git a/media/tests/benchmark/src/native/encoder/Encoder.cpp b/media/tests/benchmark/src/native/encoder/Encoder.cpp
index 26fb1b9..15c479d 100644
--- a/media/tests/benchmark/src/native/encoder/Encoder.cpp
+++ b/media/tests/benchmark/src/native/encoder/Encoder.cpp
@@ -203,13 +203,13 @@
         AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_WIDTH, mParams.width);
         AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_HEIGHT, mParams.height);
         AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_FRAME_RATE, mParams.frameRate);
+        AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, mParams.iFrameInterval);
         AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_BIT_RATE, mParams.bitrate);
-        AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, 1);
-        if (mParams.profile && mParams.level) {
+        AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT, mParams.colorFormat);
+        if (mParams.profile != -1 && mParams.level != -1) {
             AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_PROFILE, mParams.profile);
             AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_LEVEL, mParams.level);
         }
-        AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT, mParams.colorFormat);
     } else {
         AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_SAMPLE_RATE, mParams.sampleRate);
         AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_CHANNEL_COUNT, mParams.numChannels);
diff --git a/media/tests/benchmark/src/native/encoder/Encoder.h b/media/tests/benchmark/src/native/encoder/Encoder.h
index 5ad142b..324317c 100644
--- a/media/tests/benchmark/src/native/encoder/Encoder.h
+++ b/media/tests/benchmark/src/native/encoder/Encoder.h
@@ -23,10 +23,11 @@
 #include <queue>
 #include <thread>
 
-#include "media/NdkImage.h"
 #include "BenchmarkCommon.h"
 #include "Stats.h"
 
+// constant not defined in NDK api
+constexpr int32_t COLOR_FormatYUV420Flexible = 0x7F420888;
 
 struct encParameter {
     int32_t bitrate = -1;
@@ -38,9 +39,10 @@
     int32_t width = 0;
     int32_t height = 0;
     int32_t frameRate = -1;
-    int32_t profile = 0;
-    int32_t level = 0;
-    int32_t colorFormat = AIMAGE_FORMAT_YUV_420_888;
+    int32_t iFrameInterval = 0;
+    int32_t profile = -1;
+    int32_t level = -1;
+    int32_t colorFormat = COLOR_FormatYUV420Flexible;
 };
 
 class Encoder : public CallBackHandle {
diff --git a/media/tests/benchmark/src/native/extractor/Android.bp b/media/tests/benchmark/src/native/extractor/Android.bp
index 7ed9476..4946990 100644
--- a/media/tests/benchmark/src/native/extractor/Android.bp
+++ b/media/tests/benchmark/src/native/extractor/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_static {
     name: "libmediabenchmark_extractor",
     defaults: [
diff --git a/media/tests/benchmark/src/native/muxer/Android.bp b/media/tests/benchmark/src/native/muxer/Android.bp
index f669d4a..84985e4 100644
--- a/media/tests/benchmark/src/native/muxer/Android.bp
+++ b/media/tests/benchmark/src/native/muxer/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_static {
     name: "libmediabenchmark_muxer",
     defaults: [
diff --git a/media/tests/benchmark/tests/Android.bp b/media/tests/benchmark/tests/Android.bp
index f46fa4a..0fbd20d 100644
--- a/media/tests/benchmark/tests/Android.bp
+++ b/media/tests/benchmark/tests/Android.bp
@@ -14,6 +14,15 @@
  * limitations under the License.
  */
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "extractorTest",
     gtest: true,
diff --git a/media/tests/benchmark/tests/BenchmarkTestEnvironment.h b/media/tests/benchmark/tests/BenchmarkTestEnvironment.h
index ae2eee1..4edb048 100644
--- a/media/tests/benchmark/tests/BenchmarkTestEnvironment.h
+++ b/media/tests/benchmark/tests/BenchmarkTestEnvironment.h
@@ -25,7 +25,9 @@
 
 class BenchmarkTestEnvironment : public ::testing::Environment {
   public:
-    BenchmarkTestEnvironment() : res("/sdcard/media/") {}
+    BenchmarkTestEnvironment()
+        : res("/data/local/tmp/MediaBenchmark/res/"),
+          statsFile("/data/local/tmp/MediaBenchmark/res/stats.csv") {}
 
     // Parses the command line argument
     int initFromOptions(int argc, char **argv);
@@ -34,8 +36,15 @@
 
     const string getRes() const { return res; }
 
+    void setStatsFile(const string module) { statsFile = getRes() + module; }
+
+    const string getStatsFile() const { return statsFile; }
+
+    bool writeStatsHeader();
+
   private:
     string res;
+    string statsFile;
 };
 
 int BenchmarkTestEnvironment::initFromOptions(int argc, char **argv) {
@@ -70,4 +79,26 @@
     return 0;
 }
 
+/**
+ * Writes the stats header to a file
+ * <p>
+ * \param statsFile    file where the stats data is to be written
+ **/
+bool BenchmarkTestEnvironment::writeStatsHeader() {
+    char statsHeader[] =
+        "currentTime, fileName, operation, componentName, NDK/SDK, sync/async, setupTime, "
+        "destroyTime, minimumTime, maximumTime, averageTime, timeToProcess1SecContent, "
+        "totalBytesProcessedPerSec, timeToFirstFrame, totalSizeInBytes, totalTime\n";
+    FILE *fpStats = fopen(statsFile.c_str(), "w");
+    if(!fpStats) {
+        return false;
+    }
+    int32_t numBytes = fwrite(statsHeader, sizeof(char), sizeof(statsHeader), fpStats);
+    fclose(fpStats);
+    if(numBytes != sizeof(statsHeader)) {
+        return false;
+    }
+    return true;
+}
+
 #endif  // __BENCHMARK_TEST_ENVIRONMENT_H__
diff --git a/media/tests/benchmark/tests/C2DecoderTest.cpp b/media/tests/benchmark/tests/C2DecoderTest.cpp
index dedc743..85dcbc1 100644
--- a/media/tests/benchmark/tests/C2DecoderTest.cpp
+++ b/media/tests/benchmark/tests/C2DecoderTest.cpp
@@ -136,7 +136,8 @@
                 mDecoder->deInitCodec();
                 int64_t durationUs = extractor->getClipDuration();
                 ALOGV("codec : %s", codecName.c_str());
-                mDecoder->dumpStatistics(GetParam().first, durationUs);
+                mDecoder->dumpStatistics(GetParam().first, durationUs, codecName,
+                                         gEnv->getStatsFile());
                 mDecoder->resetDecoder();
             }
         }
@@ -178,6 +179,9 @@
     ::testing::InitGoogleTest(&argc, argv);
     int status = gEnv->initFromOptions(argc, argv);
     if (status == 0) {
+        gEnv->setStatsFile("C2Decoder.csv");
+        status = gEnv->writeStatsHeader();
+        ALOGV("Stats file = %d\n", status);
         status = RUN_ALL_TESTS();
         ALOGV("C2 Decoder Test result = %d\n", status);
     }
diff --git a/media/tests/benchmark/tests/C2EncoderTest.cpp b/media/tests/benchmark/tests/C2EncoderTest.cpp
index 98eb17a..b18d856 100644
--- a/media/tests/benchmark/tests/C2EncoderTest.cpp
+++ b/media/tests/benchmark/tests/C2EncoderTest.cpp
@@ -108,7 +108,7 @@
         }
 
         string decName = "";
-        string outputFileName = "decode.out";
+        string outputFileName = "/data/local/tmp/decode.out";
         FILE *outFp = fopen(outputFileName.c_str(), "wb");
         ASSERT_NE(outFp, nullptr) << "Unable to open output file" << outputFileName
                                   << " for dumping decoder's output";
@@ -140,7 +140,8 @@
                 mEncoder->deInitCodec();
                 int64_t durationUs = extractor->getClipDuration();
                 ALOGV("codec : %s", codecName.c_str());
-                mEncoder->dumpStatistics(GetParam().first, durationUs);
+                mEncoder->dumpStatistics(GetParam().first, durationUs, codecName,
+                                         gEnv->getStatsFile());
                 mEncoder->resetEncoder();
             }
         }
@@ -180,6 +181,9 @@
     ::testing::InitGoogleTest(&argc, argv);
     int status = gEnv->initFromOptions(argc, argv);
     if (status == 0) {
+        gEnv->setStatsFile("C2Encoder.csv");
+        status = gEnv->writeStatsHeader();
+        ALOGV("Stats file = %d\n", status);
         status = RUN_ALL_TESTS();
         ALOGV("C2 Encoder Test result = %d\n", status);
     }
diff --git a/media/tests/benchmark/tests/DecoderTest.cpp b/media/tests/benchmark/tests/DecoderTest.cpp
index 9f96d3b..81ef02a 100644
--- a/media/tests/benchmark/tests/DecoderTest.cpp
+++ b/media/tests/benchmark/tests/DecoderTest.cpp
@@ -84,7 +84,8 @@
         decoder->deInitCodec();
         ALOGV("codec : %s", codecName.c_str());
         string inputReference = get<0>(params);
-        decoder->dumpStatistics(inputReference);
+        decoder->dumpStatistics(inputReference, codecName, (asyncMode ? "async" : "sync"),
+                                gEnv->getStatsFile());
         free(inputBuffer);
         decoder->resetDecoder();
     }
@@ -179,8 +180,11 @@
     ::testing::InitGoogleTest(&argc, argv);
     int status = gEnv->initFromOptions(argc, argv);
     if (status == 0) {
+        gEnv->setStatsFile("Decoder.csv");
+        status = gEnv->writeStatsHeader();
+        ALOGV("Stats file = %d\n", status);
         status = RUN_ALL_TESTS();
-        ALOGD("Decoder Test result = %d\n", status);
+        ALOGV("Decoder Test result = %d\n", status);
     }
     return status;
 }
\ No newline at end of file
diff --git a/media/tests/benchmark/tests/EncoderTest.cpp b/media/tests/benchmark/tests/EncoderTest.cpp
index dc2a2dd..7e1681d 100644
--- a/media/tests/benchmark/tests/EncoderTest.cpp
+++ b/media/tests/benchmark/tests/EncoderTest.cpp
@@ -23,6 +23,10 @@
 #include "Decoder.h"
 #include "Encoder.h"
 
+constexpr int32_t kEncodeDefaultVideoBitRate = 8000000 /* 8 Mbps */;
+constexpr int32_t kEncodeMinVideoBitRate = 600000 /* 600 Kbps */;
+constexpr int32_t kEncodeDefaultAudioBitRate = 128000 /* 128 Kbps */;
+
 static BenchmarkTestEnvironment *gEnv = nullptr;
 
 class EncoderTest : public ::testing::TestWithParam<tuple<string, string, bool>> {};
@@ -78,7 +82,7 @@
         }
 
         string decName = "";
-        string outputFileName = "decode.out";
+        string outputFileName = "/data/local/tmp/decode.out";
         FILE *outFp = fopen(outputFileName.c_str(), "wb");
         ASSERT_NE(outFp, nullptr) << "Unable to open output file" << outputFileName
                                   << " for dumping decoder's output";
@@ -86,6 +90,7 @@
         decoder->setupDecoder();
         status = decoder->decode(inputBuffer, frameInfo, decName, false /*asyncMode */, outFp);
         ASSERT_EQ(status, AMEDIA_OK) << "Decode returned error : " << status;
+        AMediaFormat *decoderFormat = decoder->getFormat();
 
         ifstream eleStream;
         eleStream.open(outputFileName.c_str(), ifstream::binary | ifstream::ate);
@@ -108,11 +113,13 @@
             if (encParams.bitrate <= 0 || encParams.frameRate <= 0) {
                 encParams.frameRate = 25;
                 if (!strcmp(mime, "video/3gpp") || !strcmp(mime, "video/mp4v-es")) {
-                    encParams.bitrate = 600000 /* 600 Kbps */;
+                    encParams.bitrate = kEncodeMinVideoBitRate;
                 } else {
-                    encParams.bitrate = 8000000 /* 8 Mbps */;
+                    encParams.bitrate = kEncodeDefaultVideoBitRate;
                 }
             }
+            AMediaFormat_getInt32(decoderFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT,
+                                  &encParams.colorFormat);
             AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_PROFILE, &encParams.profile);
             AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_LEVEL, &encParams.level);
         } else {
@@ -120,8 +127,7 @@
                                               &encParams.sampleRate));
             ASSERT_TRUE(AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT,
                                               &encParams.numChannels));
-            encParams.bitrate =
-                    encParams.sampleRate * encParams.numChannels * 16 /* bitsPerSample */;
+            encParams.bitrate = kEncodeDefaultAudioBitRate;
         }
 
         encoder->setupEncoder();
@@ -133,7 +139,8 @@
         encoder->deInitCodec();
         ALOGV("codec : %s", codecName.c_str());
         string inputReference = get<0>(params);
-        encoder->dumpStatistics(inputReference, extractor->getClipDuration());
+        encoder->dumpStatistics(inputReference, extractor->getClipDuration(), codecName,
+                                (asyncMode ? "async" : "sync"), gEnv->getStatsFile());
         eleStream.close();
         if (outFp) fclose(outFp);
 
@@ -141,6 +148,10 @@
             AMediaFormat_delete(format);
             format = nullptr;
         }
+        if (decoderFormat) {
+            AMediaFormat_delete(decoderFormat);
+            decoderFormat = nullptr;
+        }
         encoder->resetEncoder();
         decoder->deInitCodec();
         free(inputBuffer);
@@ -214,8 +225,11 @@
     ::testing::InitGoogleTest(&argc, argv);
     int status = gEnv->initFromOptions(argc, argv);
     if (status == 0) {
+        gEnv->setStatsFile("Encoder.csv");
+        status = gEnv->writeStatsHeader();
+        ALOGV("Stats file = %d\n", status);
         status = RUN_ALL_TESTS();
-        ALOGD("Encoder Test result = %d\n", status);
+        ALOGV("Encoder Test result = %d\n", status);
     }
     return status;
 }
diff --git a/media/tests/benchmark/tests/ExtractorTest.cpp b/media/tests/benchmark/tests/ExtractorTest.cpp
index ad8f1e6..d14d15b 100644
--- a/media/tests/benchmark/tests/ExtractorTest.cpp
+++ b/media/tests/benchmark/tests/ExtractorTest.cpp
@@ -48,8 +48,7 @@
     ASSERT_EQ(status, AMEDIA_OK) << "Extraction failed \n";
 
     extractObj->deInitExtractor();
-
-    extractObj->dumpStatistics(GetParam().first);
+    extractObj->dumpStatistics(GetParam().first, "", gEnv->getStatsFile());
 
     fclose(inputFp);
     delete extractObj;
@@ -79,8 +78,11 @@
     ::testing::InitGoogleTest(&argc, argv);
     int status = gEnv->initFromOptions(argc, argv);
     if (status == 0) {
+        gEnv->setStatsFile("Extractor.csv");
+        status = gEnv->writeStatsHeader();
+        ALOGV("Stats file = %d\n", status);
         status = RUN_ALL_TESTS();
-        ALOGD(" Extractor Test result = %d\n", status);
+        ALOGV("Extractor Test result = %d\n", status);
     }
     return status;
 }
diff --git a/media/tests/benchmark/tests/MuxerTest.cpp b/media/tests/benchmark/tests/MuxerTest.cpp
index fa2635d..991644b 100644
--- a/media/tests/benchmark/tests/MuxerTest.cpp
+++ b/media/tests/benchmark/tests/MuxerTest.cpp
@@ -113,7 +113,7 @@
         ASSERT_EQ(status, 0) << "Mux failed";
 
         muxerObj->deInitMuxer();
-        muxerObj->dumpStatistics(GetParam().first + "." + fmt.c_str());
+        muxerObj->dumpStatistics(GetParam().first + "." + fmt.c_str(), fmt, gEnv->getStatsFile());
         free(inputBuffer);
         fclose(outputFp);
         muxerObj->resetMuxer();
@@ -151,8 +151,11 @@
     ::testing::InitGoogleTest(&argc, argv);
     int status = gEnv->initFromOptions(argc, argv);
     if (status == 0) {
+        gEnv->setStatsFile("Muxer.csv");
+        status = gEnv->writeStatsHeader();
+        ALOGV("Stats file = %d\n", status);
         status = RUN_ALL_TESTS();
-        ALOGV("Test result = %d\n", status);
+        ALOGV("Muxer Test result = %d\n", status);
     }
     return status;
 }
diff --git a/media/utils/Android.bp b/media/utils/Android.bp
index e3f1e44..748afeb 100644
--- a/media/utils/Android.bp
+++ b/media/utils/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libmediautils",
 
diff --git a/media/utils/EventLogTags.logtags b/media/utils/EventLogTags.logtags
index 67f0ea8..c397f34 100644
--- a/media/utils/EventLogTags.logtags
+++ b/media/utils/EventLogTags.logtags
@@ -31,7 +31,7 @@
 # 6: Percent
 # Default value for data of type int/long is 2 (bytes).
 #
-# See system/core/logcat/event.logtags for the master copy of the tags.
+# See system/core/logcat/event.logtags for the original definition of the tags.
 
 # 61000 - 61199 reserved for audioserver
 
diff --git a/media/utils/ServiceUtilities.cpp b/media/utils/ServiceUtilities.cpp
index 7699700..1b1717f 100644
--- a/media/utils/ServiceUtilities.cpp
+++ b/media/utils/ServiceUtilities.cpp
@@ -266,7 +266,7 @@
     return NO_ERROR;
 }
 
-sp<content::pm::IPackageManagerNative> MediaPackageManager::retreivePackageManager() {
+sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
     const sp<IServiceManager> sm = defaultServiceManager();
     if (sm == nullptr) {
         ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
@@ -283,27 +283,27 @@
 std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
     if (mPackageManager == nullptr) {
         /** Can not fetch package manager at construction it may not yet be registered. */
-        mPackageManager = retreivePackageManager();
+        mPackageManager = retrievePackageManager();
         if (mPackageManager == nullptr) {
             ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
             return std::nullopt;
         }
     }
 
+    // Retrieve package names for the UID and transform to a std::vector<std::string>.
+    Vector<String16> str16PackageNames;
+    PermissionController{}.getPackagesForUid(uid, str16PackageNames);
     std::vector<std::string> packageNames;
-    auto status = mPackageManager->getNamesForUids({(int32_t)uid}, &packageNames);
-    if (!status.isOk()) {
-        ALOGW("%s: Playback capture is denied for uid %u as the package names could not be "
-              "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
-        return std::nullopt;
+    for (const auto& str16PackageName : str16PackageNames) {
+        packageNames.emplace_back(String8(str16PackageName).string());
     }
     if (packageNames.empty()) {
         ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
-              "from the package manager: %s", __func__, uid, status.toString8().c_str());
+              "from the package manager.", __func__, uid);
         return std::nullopt;
     }
     std::vector<bool> isAllowed;
-    status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
+    auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
     if (!status.isOk()) {
         ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
               "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
diff --git a/media/utils/fuzzers/Android.bp b/media/utils/fuzzers/Android.bp
new file mode 100644
index 0000000..80882b2
--- /dev/null
+++ b/media/utils/fuzzers/Android.bp
@@ -0,0 +1,60 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_defaults {
+    name: "libmediautils_fuzzer_defaults",
+    shared_libs: [
+        "libbinder",
+        "libcutils",
+        "liblog",
+        "libmediautils",
+        "libutils",
+    ],
+
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+        "-Wno-c++2a-extensions",
+    ],
+
+    header_libs: [
+        "bionic_libc_platform_headers",
+        "libmedia_headers",
+    ],
+
+    include_dirs: [
+        // For DEBUGGER_SIGNAL
+        "system/core/debuggerd/include",
+    ],
+}
+
+cc_fuzz {
+    name: "libmediautils_fuzzer_battery_notifier",
+    defaults: ["libmediautils_fuzzer_defaults"],
+    srcs: ["BatteryNotifierFuzz.cpp"],
+}
+
+cc_fuzz {
+    name: "libmediautils_fuzzer_scheduling_policy_service",
+    defaults: ["libmediautils_fuzzer_defaults"],
+    srcs: ["SchedulingPolicyServiceFuzz.cpp"],
+}
+
+cc_fuzz {
+    name: "libmediautils_fuzzer_service_utilities",
+    defaults: ["libmediautils_fuzzer_defaults"],
+    srcs: ["ServiceUtilitiesFuzz.cpp"],
+}
+
+cc_fuzz {
+    name: "libmediautils_fuzzer_time_check",
+    defaults: ["libmediautils_fuzzer_defaults"],
+    srcs: ["TimeCheckFuzz.cpp"],
+}
diff --git a/media/utils/fuzzers/BatteryNotifierFuzz.cpp b/media/utils/fuzzers/BatteryNotifierFuzz.cpp
new file mode 100644
index 0000000..00b3cce
--- /dev/null
+++ b/media/utils/fuzzers/BatteryNotifierFuzz.cpp
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2020 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 <functional>
+#include <string>
+#include <vector>
+
+#include <utils/String8.h>
+
+#include "fuzzer/FuzzedDataProvider.h"
+#include "mediautils/BatteryNotifier.h"
+
+static constexpr int kMaxOperations = 30;
+static constexpr int kMaxStringLength = 500;
+using android::BatteryNotifier;
+
+std::vector<std::function<void(std::string /*flashlight_name*/, std::string /*camera_name*/,
+                               uid_t /*video_id*/, uid_t /*audio_id*/, uid_t /*light_id*/,
+                               uid_t /*camera_id*/)>>
+    operations = {
+        [](std::string, std::string, uid_t, uid_t, uid_t, uid_t) -> void {
+            BatteryNotifier::getInstance().noteResetVideo();
+        },
+        [](std::string, std::string, uid_t, uid_t, uid_t, uid_t) -> void {
+            BatteryNotifier::getInstance().noteResetAudio();
+        },
+        [](std::string, std::string, uid_t, uid_t, uid_t, uid_t) -> void {
+            BatteryNotifier::getInstance().noteResetFlashlight();
+        },
+        [](std::string, std::string, uid_t, uid_t, uid_t, uid_t) -> void {
+            BatteryNotifier::getInstance().noteResetCamera();
+        },
+        [](std::string, std::string, uid_t video_id, uid_t, uid_t, uid_t) -> void {
+            BatteryNotifier::getInstance().noteStartVideo(video_id);
+        },
+        [](std::string, std::string, uid_t video_id, uid_t, uid_t, uid_t) -> void {
+            BatteryNotifier::getInstance().noteStopVideo(video_id);
+        },
+        [](std::string, std::string, uid_t, uid_t audio_id, uid_t, uid_t) -> void {
+            BatteryNotifier::getInstance().noteStartAudio(audio_id);
+        },
+        [](std::string, std::string, uid_t, uid_t audio_id, uid_t, uid_t) -> void {
+            BatteryNotifier::getInstance().noteStopAudio(audio_id);
+        },
+        [](std::string flashlight_name, std::string, uid_t, uid_t, uid_t light_id, uid_t) -> void {
+            android::String8 name(flashlight_name.c_str());
+            BatteryNotifier::getInstance().noteFlashlightOn(name, light_id);
+        },
+        [](std::string flashlight_name, std::string, uid_t, uid_t, uid_t light_id, uid_t) -> void {
+            android::String8 name(flashlight_name.c_str());
+            BatteryNotifier::getInstance().noteFlashlightOff(name, light_id);
+        },
+        [](std::string, std::string camera_name, uid_t, uid_t, uid_t, uid_t camera_id) -> void {
+            android::String8 name(camera_name.c_str());
+            BatteryNotifier::getInstance().noteStartCamera(name, camera_id);
+        },
+        [](std::string, std::string camera_name, uid_t, uid_t, uid_t, uid_t camera_id) -> void {
+            android::String8 name(camera_name.c_str());
+            BatteryNotifier::getInstance().noteStopCamera(name, camera_id);
+        },
+};
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    FuzzedDataProvider data_provider(data, size);
+    std::string camera_name = data_provider.ConsumeRandomLengthString(kMaxStringLength);
+    std::string flashlight_name = data_provider.ConsumeRandomLengthString(kMaxStringLength);
+    uid_t video_id = data_provider.ConsumeIntegral<uid_t>();
+    uid_t audio_id = data_provider.ConsumeIntegral<uid_t>();
+    uid_t light_id = data_provider.ConsumeIntegral<uid_t>();
+    uid_t camera_id = data_provider.ConsumeIntegral<uid_t>();
+    size_t ops_run = 0;
+    while (data_provider.remaining_bytes() > 0 && ops_run++ < kMaxOperations) {
+        uint8_t op = data_provider.ConsumeIntegralInRange<uint8_t>(0, operations.size() - 1);
+        operations[op](flashlight_name, camera_name, video_id, audio_id, light_id, camera_id);
+    }
+    return 0;
+}
diff --git a/media/utils/fuzzers/SchedulingPolicyServiceFuzz.cpp b/media/utils/fuzzers/SchedulingPolicyServiceFuzz.cpp
new file mode 100644
index 0000000..4521853
--- /dev/null
+++ b/media/utils/fuzzers/SchedulingPolicyServiceFuzz.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2020 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 "BatteryNotifierFuzzer"
+#include <binder/IBatteryStats.h>
+#include <binder/IServiceManager.h>
+#include <utils/String16.h>
+#include <android/log.h>
+#include <mediautils/SchedulingPolicyService.h>
+#include "fuzzer/FuzzedDataProvider.h"
+using android::IBatteryStats;
+using android::IBinder;
+using android::IInterface;
+using android::IServiceManager;
+using android::sp;
+using android::String16;
+using android::defaultServiceManager;
+using android::requestCpusetBoost;
+using android::requestPriority;
+sp<IBatteryStats> getBatteryService() {
+    sp<IBatteryStats> batteryStatService;
+    const sp<IServiceManager> sm(defaultServiceManager());
+    if (sm != nullptr) {
+        const String16 name("batterystats");
+        batteryStatService = checked_interface_cast<IBatteryStats>(sm->checkService(name));
+        if (batteryStatService == nullptr) {
+            ALOGW("batterystats service unavailable!");
+            return nullptr;
+        }
+    }
+    return batteryStatService;
+}
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    FuzzedDataProvider data_provider(data, size);
+    sp<IBatteryStats> batteryStatService = getBatteryService();
+    // There is some state here, but it's mostly focused around thread-safety, so
+    // we won't worry about order.
+    int32_t priority = data_provider.ConsumeIntegral<int32_t>();
+    bool is_for_app = data_provider.ConsumeBool();
+    bool async = data_provider.ConsumeBool();
+    requestPriority(getpid(), gettid(), priority, is_for_app, async);
+    // TODO: Verify and re-enable in AOSP (R).
+    // bool enable = data_provider.ConsumeBool();
+    // We are just using batterystats to avoid the need
+    // to register a new service.
+    // requestCpusetBoost(enable, IInterface::asBinder(batteryStatService));
+    return 0;
+}
+
diff --git a/media/utils/fuzzers/ServiceUtilitiesFuzz.cpp b/media/utils/fuzzers/ServiceUtilitiesFuzz.cpp
new file mode 100644
index 0000000..20b3713
--- /dev/null
+++ b/media/utils/fuzzers/ServiceUtilitiesFuzz.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2020 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 <fcntl.h>
+
+#include <functional>
+
+#include "fuzzer/FuzzedDataProvider.h"
+#include "mediautils/ServiceUtilities.h"
+
+static constexpr int kMaxOperations = 50;
+static constexpr int kMaxStringLen = 256;
+
+const std::vector<std::function<void(FuzzedDataProvider*, android::MediaPackageManager)>>
+    operations = {
+        [](FuzzedDataProvider* data_provider, android::MediaPackageManager pm) -> void {
+            uid_t uid = data_provider->ConsumeIntegral<uid_t>();
+            pm.allowPlaybackCapture(uid);
+        },
+        [](FuzzedDataProvider* data_provider, android::MediaPackageManager pm) -> void {
+            int spaces = data_provider->ConsumeIntegral<int>();
+
+            // Dump everything into /dev/null
+            int fd = open("/dev/null", O_WRONLY);
+            pm.dump(fd, spaces);
+            close(fd);
+        },
+};
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    FuzzedDataProvider data_provider(data, size);
+    uid_t uid = data_provider.ConsumeIntegral<uid_t>();
+    pid_t pid = data_provider.ConsumeIntegral<pid_t>();
+
+    // There is not state here, and order is not significant,
+    // so we can simply call all of the target functions
+    android::isServiceUid(uid);
+    android::isAudioServerUid(uid);
+    android::isAudioServerOrSystemServerUid(uid);
+    android::isAudioServerOrMediaServerUid(uid);
+    std::string packageNameStr = data_provider.ConsumeRandomLengthString(kMaxStringLen);
+    android::String16 opPackageName(packageNameStr.c_str());
+    android::recordingAllowed(opPackageName, pid, uid);
+    android::startRecording(opPackageName, pid, uid, false);
+    android::finishRecording(opPackageName, uid, false);
+    android::captureAudioOutputAllowed(pid, uid);
+    android::captureMediaOutputAllowed(pid, uid);
+    android::captureHotwordAllowed(opPackageName, pid, uid);
+    android::modifyPhoneStateAllowed(uid, pid);
+    android::bypassInterruptionPolicyAllowed(uid, pid);
+    android::settingsAllowed();
+    android::modifyAudioRoutingAllowed();
+    android::modifyDefaultAudioEffectsAllowed();
+    android::dumpAllowed();
+
+    // MediaPackageManager does have state, so we need the fuzzer to decide order
+    android::MediaPackageManager packageManager;
+    size_t ops_run = 0;
+    while (data_provider.remaining_bytes() > 0 && ops_run++ < kMaxOperations) {
+        uint8_t op = data_provider.ConsumeIntegralInRange<uint8_t>(0, operations.size() - 1);
+        operations[op](&data_provider, packageManager);
+    }
+
+    return 0;
+}
diff --git a/media/utils/fuzzers/TimeCheckFuzz.cpp b/media/utils/fuzzers/TimeCheckFuzz.cpp
new file mode 100644
index 0000000..eeb6ba6
--- /dev/null
+++ b/media/utils/fuzzers/TimeCheckFuzz.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2020 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 <chrono>
+#include <thread>
+
+#include "fuzzer/FuzzedDataProvider.h"
+#include "mediautils/TimeCheck.h"
+
+static constexpr int kMaxStringLen = 256;
+
+// While it might be interesting to test long-running
+// jobs, it seems unlikely it'd lead to the types of crashes
+// we're looking for, and would mean a significant increase in fuzzer time.
+// Therefore, we are setting a low cap.
+static constexpr uint32_t kMaxTimeoutMs = 1000;
+static constexpr uint32_t kMinTimeoutMs = 200;
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    FuzzedDataProvider data_provider(data, size);
+
+    // There's essentially 5 operations that we can access in this class
+    // 1. The time it takes to run this operation. As mentioned above,
+    //    long-running tasks are not good for fuzzing, but there will be
+    //    some change in the run time.
+    uint32_t timeoutMs =
+        data_provider.ConsumeIntegralInRange<uint32_t>(kMinTimeoutMs, kMaxTimeoutMs);
+    uint8_t pid_size = data_provider.ConsumeIntegral<uint8_t>();
+    std::vector<pid_t> pids(pid_size);
+    for (auto& pid : pids) {
+        pid = data_provider.ConsumeIntegral<pid_t>();
+    }
+
+    // 2. We also have setAudioHalPids, which is populated with the pids set
+    // above.
+    android::TimeCheck::setAudioHalPids(pids);
+    std::string name = data_provider.ConsumeRandomLengthString(kMaxStringLen);
+
+    // 3. The constructor, which is fuzzed here:
+    android::TimeCheck timeCheck(name.c_str(), timeoutMs);
+    // We will leave some buffer to avoid sleeping too long
+    uint8_t sleep_amount_ms = data_provider.ConsumeIntegralInRange<uint8_t>(0, timeoutMs / 2);
+
+    // We want to make sure we can cover the time out functionality.
+    if (sleep_amount_ms) {
+        auto ms = std::chrono::milliseconds(sleep_amount_ms);
+        std::this_thread::sleep_for(ms);
+    }
+
+    // 4. Finally, the destructor on timecheck. These seem to be the only factors
+    // in play.
+    return 0;
+}
diff --git a/media/utils/include/mediautils/ServiceUtilities.h b/media/utils/include/mediautils/ServiceUtilities.h
index 431dd7a..c7d49fd 100644
--- a/media/utils/include/mediautils/ServiceUtilities.h
+++ b/media/utils/include/mediautils/ServiceUtilities.h
@@ -110,7 +110,7 @@
 private:
     static constexpr const char* nativePackageManagerName = "package_native";
     std::optional<bool> doIsAllowed(uid_t uid);
-    sp<content::pm::IPackageManagerNative> retreivePackageManager();
+    sp<content::pm::IPackageManagerNative> retrievePackageManager();
     sp<content::pm::IPackageManagerNative> mPackageManager; // To check apps manifest
     uint_t mPackageManagerErrors = 0;
     struct Package {
diff --git a/services/OWNERS b/services/OWNERS
index 66a4bcb..f0b5e2f 100644
--- a/services/OWNERS
+++ b/services/OWNERS
@@ -5,3 +5,5 @@
 gkasten@google.com
 hunga@google.com
 marcone@google.com
+nchalko@google.com
+quxiangfang@google.com
diff --git a/services/audioflinger/Android.bp b/services/audioflinger/Android.bp
index 3873600..3c9897d 100644
--- a/services/audioflinger/Android.bp
+++ b/services/audioflinger/Android.bp
@@ -1,5 +1,24 @@
 
 
+package {
+    default_applicable_licenses: [
+        "frameworks_av_services_audioflinger_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_services_audioflinger_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libaudioflinger",
 
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 764fdc3..4ac46b7 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -684,8 +684,8 @@
 
 sp<NBLog::Writer> AudioFlinger::newWriter_l(size_t size, const char *name)
 {
-    // If there is no memory allocated for logs, return a dummy writer that does nothing.
-    // Similarly if we can't contact the media.log service, also return a dummy writer.
+    // If there is no memory allocated for logs, return a no-op writer that does nothing.
+    // Similarly if we can't contact the media.log service, also return a no-op writer.
     if (mLogMemoryDealer == 0 || sMediaLogService == 0) {
         return new NBLog::Writer();
     }
@@ -711,7 +711,7 @@
             }
         }
         // Even after garbage-collecting all old writers, there is still not enough memory,
-        // so return a dummy writer
+        // so return a no-op writer
         return new NBLog::Writer();
     }
 success:
@@ -1284,9 +1284,9 @@
     }
 
     // Now set the master mute in each playback thread.  Playback threads
-    // assigned to HALs which do not have master mute support will apply master
-    // mute during the mix operation.  Threads with HALs which do support master
-    // mute will simply ignore the setting.
+    // assigned to HALs which do not have master mute support will apply master mute
+    // during the mix operation.  Threads with HALs which do support master mute
+    // will simply ignore the setting.
     Vector<VolumeInterface *> volumeInterfaces = getAllVolumeInterfaces_l();
     for (size_t i = 0; i < volumeInterfaces.size(); i++) {
         volumeInterfaces[i]->setMasterMute(muted);
@@ -1462,6 +1462,20 @@
     }
 }
 
+// Update downstream patches for all playback threads attached to an MSD module
+void AudioFlinger::updateDownStreamPatches_l(const struct audio_patch *patch,
+                                             const std::set<audio_io_handle_t> streams)
+{
+    for (const audio_io_handle_t stream : streams) {
+        PlaybackThread *playbackThread = checkPlaybackThread_l(stream);
+        if (playbackThread == nullptr || !playbackThread->isMsdDevice()) {
+            continue;
+        }
+        playbackThread->setDownStreamPatch(patch);
+        playbackThread->sendIoConfigEvent(AUDIO_OUTPUT_CONFIG_CHANGED);
+    }
+}
+
 // Filter reserved keys from setParameters() before forwarding to audio HAL or acting upon.
 // Some keys are used for audio routing and audio path configuration and should be reserved for use
 // by audio policy and audio flinger for functional, privacy and security reasons.
@@ -2534,7 +2548,11 @@
                       *output, thread.get());
             }
             mPlaybackThreads.add(*output, thread);
-            mPatchPanel.notifyStreamOpened(outHwDev, *output);
+            struct audio_patch patch;
+            mPatchPanel.notifyStreamOpened(outHwDev, *output, &patch);
+            if (thread->isMsdDevice()) {
+                thread->setDownStreamPatch(&patch);
+            }
             return thread;
         }
     }
@@ -3142,7 +3160,8 @@
 // dumpToThreadLog_l() must be called with AudioFlinger::mLock held
 void AudioFlinger::dumpToThreadLog_l(const sp<ThreadBase> &thread)
 {
-    audio_utils::FdToString fdToString;
+    constexpr int THREAD_DUMP_TIMEOUT_MS = 2;
+    audio_utils::FdToString fdToString("- ", THREAD_DUMP_TIMEOUT_MS);
     const int fd = fdToString.fd();
     if (fd >= 0) {
         thread->dump(fd, {} /* args */);
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index 20f561e..10d4029 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -320,6 +320,9 @@
     status_t removeEffectFromHal(audio_port_handle_t deviceId,
             audio_module_handle_t hwModuleId, sp<EffectHalInterface> effect);
 
+    void updateDownStreamPatches_l(const struct audio_patch *patch,
+                                   const std::set<audio_io_handle_t> streams);
+
 private:
     // FIXME The 400 is temporarily too high until a leak of writers in media.log is fixed.
     static const size_t kLogMemorySize = 400 * 1024;
@@ -405,7 +408,7 @@
         case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
             // Haptic channel mask is only applicable for channel position mask.
             const uint32_t channelCount = audio_channel_count_from_out_mask(
-                    channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL);
+                    static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
             const uint32_t maxChannelCount = kEnableExtendedChannels
                     ? AudioMixer::MAX_NUM_CHANNELS : FCC_2;
             if (channelCount < FCC_2 // mono is not supported at this time
@@ -642,6 +645,13 @@
         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
+                status_t    getDualMonoMode(audio_dual_mono_mode_t* mode) override;
+                status_t    setDualMonoMode(audio_dual_mono_mode_t mode) override;
+                status_t    getAudioDescriptionMixLevel(float* leveldB) override;
+                status_t    setAudioDescriptionMixLevel(float leveldB) override;
+                status_t    getPlaybackRateParameters(audio_playback_rate_t* playbackRate) override;
+                status_t    setPlaybackRateParameters(
+                        const audio_playback_rate_t& playbackRate) override;
 
         virtual status_t onTransact(
             uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
diff --git a/services/audioflinger/Effects.cpp b/services/audioflinger/Effects.cpp
index 3dfeb83..eebaa7e 100644
--- a/services/audioflinger/Effects.cpp
+++ b/services/audioflinger/Effects.cpp
@@ -292,6 +292,9 @@
         }
     }
 
+    // Prevent calls to process() and other functions on effect interface from now on.
+    // The effect engine will be released by the destructor when the last strong reference on
+    // this object is released which can happen after next process is called.
     if (mHandles.size() == 0 && !mPinned) {
         mState = DESTROYED;
     }
@@ -565,20 +568,6 @@
 
 }
 
-ssize_t AudioFlinger::EffectModule::removeHandle_l(EffectHandle *handle)
-{
-    ssize_t status = EffectBase::removeHandle_l(handle);
-
-    // Prevent calls to process() and other functions on effect interface from now on.
-    // The effect engine will be released by the destructor when the last strong reference on
-    // this object is released which can happen after next process is called.
-    if (status == 0 && !mPinned) {
-        mEffectInterface->close();
-    }
-
-    return status;
-}
-
 bool AudioFlinger::EffectModule::updateState() {
     Mutex::Autolock _l(mLock);
 
@@ -3005,7 +2994,7 @@
             __func__, port->type, port->ext.device.type,
             port->ext.device.address, port->id, patch.isSoftware());
     if (port->type != AUDIO_PORT_TYPE_DEVICE || port->ext.device.type != mDevice.mType
-        || port->ext.device.address != mDevice.mAddress) {
+        || port->ext.device.address != mDevice.address()) {
         return NAME_NOT_FOUND;
     }
     status_t status = NAME_NOT_FOUND;
diff --git a/services/audioflinger/Effects.h b/services/audioflinger/Effects.h
index 2826297..2c79ac5 100644
--- a/services/audioflinger/Effects.h
+++ b/services/audioflinger/Effects.h
@@ -144,7 +144,7 @@
     status_t addHandle(EffectHandle *handle);
     ssize_t disconnectHandle(EffectHandle *handle, bool unpinIfLast);
     ssize_t removeHandle(EffectHandle *handle);
-    virtual ssize_t removeHandle_l(EffectHandle *handle);
+    ssize_t removeHandle_l(EffectHandle *handle);
     EffectHandle* controlHandle_l();
     bool purgeHandles();
 
@@ -240,8 +240,6 @@
         return mOutBuffer != 0 ? reinterpret_cast<int16_t*>(mOutBuffer->ptr()) : NULL;
     }
 
-    ssize_t removeHandle_l(EffectHandle *handle) override;
-
     status_t         setDevices(const AudioDeviceTypeAddrVector &devices);
     status_t         setInputDevice(const AudioDeviceTypeAddr &device);
     status_t         setVolume(uint32_t *left, uint32_t *right, bool controller);
diff --git a/services/audioflinger/FastMixer.cpp b/services/audioflinger/FastMixer.cpp
index 3eacc8c..cd3c743 100644
--- a/services/audioflinger/FastMixer.cpp
+++ b/services/audioflinger/FastMixer.cpp
@@ -27,7 +27,6 @@
 
 #include "Configuration.h"
 #include <time.h>
-#include <utils/Debug.h>
 #include <utils/Log.h>
 #include <utils/Trace.h>
 #include <system/audio.h>
@@ -40,6 +39,7 @@
 #include <audio_utils/channels.h>
 #include <audio_utils/format.h>
 #include <audio_utils/mono_blend.h>
+#include <cutils/bitops.h>
 #include <media/AudioMixer.h>
 #include "FastMixer.h"
 #include "TypedLogger.h"
diff --git a/services/audioflinger/FastMixerDumpState.cpp b/services/audioflinger/FastMixerDumpState.cpp
index a42e09c..3f20282 100644
--- a/services/audioflinger/FastMixerDumpState.cpp
+++ b/services/audioflinger/FastMixerDumpState.cpp
@@ -24,7 +24,6 @@
 #include <cpustats/ThreadCpuUsage.h>
 #endif
 #endif
-#include <utils/Debug.h>
 #include <utils/Log.h>
 #include "FastMixerDumpState.h"
 
diff --git a/services/audioflinger/OWNERS b/services/audioflinger/OWNERS
index d02d9e0..034d161 100644
--- a/services/audioflinger/OWNERS
+++ b/services/audioflinger/OWNERS
@@ -1,4 +1,4 @@
+gkasten@google.com
 hunga@google.com
 jmtrivi@google.com
 mnaganov@google.com
-gkasten@google.com
diff --git a/services/audioflinger/PatchPanel.cpp b/services/audioflinger/PatchPanel.cpp
index b58fd8b..37aa13e 100644
--- a/services/audioflinger/PatchPanel.cpp
+++ b/services/audioflinger/PatchPanel.cpp
@@ -413,10 +413,10 @@
         *handle = (audio_patch_handle_t) mAudioFlinger.nextUniqueId(AUDIO_UNIQUE_ID_USE_PATCH);
         newPatch.mHalHandle = halHandle;
         mAudioFlinger.mDeviceEffectManager.createAudioPatch(*handle, newPatch);
-        mPatches.insert(std::make_pair(*handle, std::move(newPatch)));
         if (insertedModule != AUDIO_MODULE_HANDLE_NONE) {
-            addSoftwarePatchToInsertedModules(insertedModule, *handle);
+            addSoftwarePatchToInsertedModules(insertedModule, *handle, &newPatch.mAudioPatch);
         }
+        mPatches.insert(std::make_pair(*handle, std::move(newPatch)));
     } else {
         newPatch.clearConnections(this);
     }
@@ -781,10 +781,20 @@
 }
 
 void AudioFlinger::PatchPanel::notifyStreamOpened(
-        AudioHwDevice *audioHwDevice, audio_io_handle_t stream)
+        AudioHwDevice *audioHwDevice, audio_io_handle_t stream, struct audio_patch *patch)
 {
     if (audioHwDevice->isInsert()) {
         mInsertedModules[audioHwDevice->handle()].streams.insert(stream);
+        if (patch != nullptr) {
+            std::vector <SoftwarePatch> swPatches;
+            getDownstreamSoftwarePatches(stream, &swPatches);
+            if (swPatches.size() > 0) {
+                auto iter = mPatches.find(swPatches[0].getPatchHandle());
+                if (iter != mPatches.end()) {
+                    *patch = iter->second.mAudioPatch;
+                }
+            }
+        }
     }
 }
 
@@ -813,9 +823,13 @@
 }
 
 void AudioFlinger::PatchPanel::addSoftwarePatchToInsertedModules(
-        audio_module_handle_t module, audio_patch_handle_t handle)
+        audio_module_handle_t module, audio_patch_handle_t handle,
+        const struct audio_patch *patch)
 {
     mInsertedModules[module].sw_patches.insert(handle);
+    if (!mInsertedModules[module].streams.empty()) {
+        mAudioFlinger.updateDownStreamPatches_l(patch, mInsertedModules[module].streams);
+    }
 }
 
 void AudioFlinger::PatchPanel::removeSoftwarePatchFromInsertedModules(
diff --git a/services/audioflinger/PatchPanel.h b/services/audioflinger/PatchPanel.h
index 89d4eb1..ea38559 100644
--- a/services/audioflinger/PatchPanel.h
+++ b/services/audioflinger/PatchPanel.h
@@ -71,7 +71,8 @@
             std::vector<SoftwarePatch> *patches) const;
 
     // Notifies patch panel about all opened and closed streams.
-    void notifyStreamOpened(AudioHwDevice *audioHwDevice, audio_io_handle_t stream);
+    void notifyStreamOpened(AudioHwDevice *audioHwDevice, audio_io_handle_t stream,
+                            struct audio_patch *patch);
     void notifyStreamClosed(audio_io_handle_t stream);
 
     void dump(int fd) const;
@@ -226,7 +227,8 @@
     AudioHwDevice* findAudioHwDeviceByModule(audio_module_handle_t module);
     sp<DeviceHalInterface> findHwDeviceByModule(audio_module_handle_t module);
     void addSoftwarePatchToInsertedModules(
-            audio_module_handle_t module, audio_patch_handle_t handle);
+            audio_module_handle_t module, audio_patch_handle_t handle,
+            const struct audio_patch *patch);
     void removeSoftwarePatchFromInsertedModules(audio_patch_handle_t handle);
     void erasePatch(audio_patch_handle_t handle);
 
diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h
index a2df29b..7804822 100644
--- a/services/audioflinger/PlaybackTracks.h
+++ b/services/audioflinger/PlaybackTracks.h
@@ -117,6 +117,12 @@
             int         auxEffectId() const { return mAuxEffectId; }
     virtual status_t    getTimestamp(AudioTimestamp& timestamp);
             void        signal();
+            status_t    getDualMonoMode(audio_dual_mono_mode_t* mode);
+            status_t    setDualMonoMode(audio_dual_mono_mode_t mode);
+            status_t    getAudioDescriptionMixLevel(float* leveldB);
+            status_t    setAudioDescriptionMixLevel(float leveldB);
+            status_t    getPlaybackRateParameters(audio_playback_rate_t* playbackRate);
+            status_t    setPlaybackRateParameters(const audio_playback_rate_t& playbackRate);
 
 // implement FastMixerState::VolumeProvider interface
     virtual gain_minifloat_packed_t getVolumeLR();
@@ -148,7 +154,7 @@
      */
     bool            readAndClearHasChanged() { return !mChangeNotified.test_and_set(); }
 
-    using SourceMetadatas = std::vector<playback_track_metadata_t>;
+    using SourceMetadatas = std::vector<playback_track_metadata_v7_t>;
     using MetadataInserter = std::back_insert_iterator<SourceMetadatas>;
     /** Copy the track metadata in the provided iterator. Thread safe. */
     virtual void    copyMetadataTo(MetadataInserter& backInserter) const;
@@ -281,6 +287,10 @@
     /** How many frames should be in the buffer before the track is considered ready */
     const size_t        mFrameCountToBeReady;
 
+    audio_dual_mono_mode_t mDualMonoMode = AUDIO_DUAL_MONO_MODE_OFF;
+    float               mAudioDescriptionMixLevel = -std::numeric_limits<float>::infinity();
+    audio_playback_rate_t  mPlaybackRateParameters = AUDIO_PLAYBACK_RATE_INITIALIZER;
+
 private:
     void                interceptBuffer(const AudioBufferProvider::Buffer& buffer);
     template <class F>
diff --git a/services/audioflinger/SpdifStreamOut.cpp b/services/audioflinger/SpdifStreamOut.cpp
index c7aba79..0ce5681 100644
--- a/services/audioflinger/SpdifStreamOut.cpp
+++ b/services/audioflinger/SpdifStreamOut.cpp
@@ -39,7 +39,7 @@
         , mSpdifEncoder(this, format)
         , mApplicationFormat(AUDIO_FORMAT_DEFAULT)
         , mApplicationSampleRate(0)
-        , mApplicationChannelMask(0)
+        , mApplicationChannelMask(AUDIO_CHANNEL_NONE)
 {
 }
 
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index 1d0147d..927d87e 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -29,6 +29,7 @@
 #include <linux/futex.h>
 #include <sys/stat.h>
 #include <sys/syscall.h>
+#include <cutils/bitops.h>
 #include <cutils/properties.h>
 #include <media/AudioContainers.h>
 #include <media/AudioDeviceTypeAddr.h>
@@ -1863,7 +1864,8 @@
         // index 0 is reserved for normal mixer's submix
         mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
         mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
-        mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
+        mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
+        mDownStreamPatch{}
 {
     snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
     mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
@@ -1901,9 +1903,8 @@
                                        : AUDIO_DEVICE_NONE));
     }
 
-    // ++ operator does not compile
-    for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
-            stream = (audio_stream_type_t) (stream + 1)) {
+    for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
+        const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
         mStreamTypes[stream].volume = 0.0f;
         mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
     }
@@ -2632,12 +2633,16 @@
     ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
 
     desc->mIoHandle = mId;
+    struct audio_patch patch = mPatch;
+    if (isMsdDevice()) {
+        patch = mDownStreamPatch;
+    }
 
     switch (event) {
     case AUDIO_OUTPUT_OPENED:
     case AUDIO_OUTPUT_REGISTERED:
     case AUDIO_OUTPUT_CONFIG_CHANGED:
-        desc->mPatch = mPatch;
+        desc->mPatch = patch;
         desc->mChannelMask = mChannelMask;
         desc->mSamplingRate = mSampleRate;
         desc->mFormat = mFormat;
@@ -2647,7 +2652,7 @@
         desc->mLatency = latency_l();
         break;
     case AUDIO_CLIENT_STARTED:
-        desc->mPatch = mPatch;
+        desc->mPatch = patch;
         desc->mPortId = portId;
         break;
     case AUDIO_OUTPUT_CLOSED:
@@ -2868,8 +2873,8 @@
         (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
     }
 
-    mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
-    mChannelMask &= ~mHapticChannelMask;
+    mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
+    mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
     mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
     mChannelCount -= mHapticChannelCount;
 
@@ -3487,7 +3492,7 @@
                     // latency of 5 seconds).
                     const double minLatency = 0., maxLatency = 5000.;
                     if (latencyMs >= minLatency && latencyMs <= maxLatency) {
-                        ALOGV("new downstream latency %lf ms", latencyMs);
+                        ALOGVV("new downstream latency %lf ms", latencyMs);
                     } else {
                         ALOGD("out of range downstream latency %lf ms", latencyMs);
                         if (latencyMs < minLatency) latencyMs = minLatency;
@@ -3536,7 +3541,7 @@
                         mSampleRate);
 
                 if (isTimestampCorrectionEnabled()) {
-                    ALOGV("TS_BEFORE: %d %lld %lld", id(),
+                    ALOGVV("TS_BEFORE: %d %lld %lld", id(),
                             (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
                             (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
                     auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
@@ -3544,7 +3549,7 @@
                             = correctedTimestamp.mFrames;
                     timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
                             = correctedTimestamp.mTimeNs;
-                    ALOGV("TS_AFTER: %d %lld %lld", id(),
+                    ALOGVV("TS_AFTER: %d %lld %lld", id(),
                             (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
                             (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
 
@@ -4205,7 +4210,7 @@
                             "Enumerated device type(%#x) must not be used "
                             "as it does not support audio patches",
                             patch->sinks[i].ext.device.type);
-        type |= patch->sinks[i].ext.device.type;
+        type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
         deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
                 patch->sinks[i].ext.device.address));
     }
@@ -4455,8 +4460,9 @@
         // wrap the source side of the MonoPipe to make it an AudioBufferProvider
         fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
         fastTrack->mVolumeProvider = NULL;
-        fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
-                                                                     // audio to FastMixer
+        fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
+                mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
+                                                    // audio to FastMixer
         fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
         fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
         fastTrack->mHapticIntensity = AudioMixer::HAPTIC_SCALE_NONE;
@@ -4470,7 +4476,8 @@
         // specify sink channel mask when haptic channel mask present as it can not
         // be calculated directly from channel count
         state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
-                ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
+                ? AUDIO_CHANNEL_NONE
+                : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
         state->mCommand = FastMixerState::COLD_IDLE;
         // already done in constructor initialization list
         //mFastMixerFutex = 0;
@@ -6887,7 +6894,7 @@
     snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
     mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
 
-    if (mInput != nullptr && mInput->audioHwDev != nullptr) {
+    if (mInput->audioHwDev != nullptr) {
         mIsMsdDevice = strcmp(
                 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
     }
@@ -7318,7 +7325,7 @@
 
             const ssize_t availableToRead = mPipeSource->availableToRead();
             if (availableToRead >= 0) {
-                // PipeSource is the master clock.  It is up to the AudioRecord client to keep up.
+                // PipeSource is the primary clock.  It is up to the AudioRecord client to keep up.
                 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
                         "more frames to read than fifo size, %zd > %zu",
                         availableToRead, mPipeFramesP2);
@@ -7379,12 +7386,12 @@
 
                 // Correct timestamps
                 if (isTimestampCorrectionEnabled()) {
-                    ALOGV("TS_BEFORE: %d %lld %lld",
+                    ALOGVV("TS_BEFORE: %d %lld %lld",
                             id(), (long long)time, (long long)position);
                     auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
                     position = correctedTimestamp.mFrames;
                     time = correctedTimestamp.mTimeNs;
-                    ALOGV("TS_AFTER: %d %lld %lld",
+                    ALOGVV("TS_AFTER: %d %lld %lld",
                             id(), (long long)time, (long long)position);
                 }
 
@@ -7434,7 +7441,7 @@
                         (framesRead - part1) * mFrameSize);
             }
         }
-        rear = mRsmpInRear += framesRead;
+        mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
 
         size = activeTracks.size();
 
@@ -8054,10 +8061,15 @@
     StreamInHalInterface::SinkMetadata metadata;
     for (const sp<RecordTrack> &track : mActiveTracks) {
         // No track is invalid as this is called after prepareTrack_l in the same critical section
-        metadata.tracks.push_back({
+        record_track_metadata_v7_t trackMetadata;
+        trackMetadata.base = {
                 .source = track->attributes().source,
                 .gain = 1, // capture tracks do not have volumes
-        });
+        };
+        trackMetadata.channel_mask = track->channelMask(),
+        strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
+
+        metadata.tracks.push_back(trackMetadata);
     }
     mInput->stream->updateSinkMetadata(metadata);
 }
@@ -8562,7 +8574,7 @@
 
     // store new device and send to effects
     mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
-    mInDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
+    mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
     audio_port_handle_t deviceId = patch->sources[0].id;
     for (size_t i = 0; i < mEffectChains.size(); i++) {
         mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
@@ -8641,6 +8653,7 @@
 
 void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
 {
+    Mutex::Autolock _l(mLock);
     mOutDevices = outDevices;
     mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
     for (size_t i = 0; i < mEffectChains.size(); i++) {
@@ -9192,7 +9205,7 @@
                                 "Enumerated device type(%#x) must not be used "
                                 "as it does not support audio patches",
                                 patch->sinks[i].ext.device.type);
-            type |= patch->sinks[i].ext.device.type;
+            type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
             sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
                     patch->sinks[i].ext.device.address));
         }
@@ -9203,7 +9216,7 @@
         deviceId = patch->sources[0].id;
         numDevices = mPatch.num_sources;
         sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
-        sourceDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
+        sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
     }
 
     for (size_t i = 0; i < mEffectChains.size(); i++) {
@@ -9618,11 +9631,15 @@
     StreamOutHalInterface::SourceMetadata metadata;
     for (const sp<MmapTrack> &track : mActiveTracks) {
         // No track is invalid as this is called after prepareTrack_l in the same critical section
-        metadata.tracks.push_back({
+        playback_track_metadata_v7_t trackMetadata;
+        trackMetadata.base = {
                 .usage = track->attributes().usage,
                 .content_type = track->attributes().content_type,
                 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
-        });
+        };
+        trackMetadata.channel_mask = track->channelMask(),
+        strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
+        metadata.tracks.push_back(trackMetadata);
     }
     mOutput->stream->updateSourceMetadata(metadata);
 }
@@ -9729,10 +9746,14 @@
     StreamInHalInterface::SinkMetadata metadata;
     for (const sp<MmapTrack> &track : mActiveTracks) {
         // No track is invalid as this is called after prepareTrack_l in the same critical section
-        metadata.tracks.push_back({
+        record_track_metadata_v7_t trackMetadata;
+        trackMetadata.base = {
                 .source = track->attributes().source,
                 .gain = 1, // capture tracks do not have volumes
-        });
+        };
+        trackMetadata.channel_mask = track->channelMask(),
+        strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
+        metadata.tracks.push_back(trackMetadata);
     }
     mInput->stream->updateSinkMetadata(metadata);
 }
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index 6b33ad5..709a3cc 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -940,6 +940,11 @@
                                         && outDeviceTypes().count(mTimestampCorrectedDevice) != 0;
                             }
 
+                void setDownStreamPatch(const struct audio_patch *patch) {
+                    Mutex::Autolock _l(mLock);
+                    mDownStreamPatch = *patch;
+                }
+
 protected:
     // updated by readOutputParameters_l()
     size_t                          mNormalFrameCount;  // normal mixer and effects
@@ -1218,6 +1223,10 @@
                 // volumes last sent to audio HAL with stream->setVolume()
                 float mLeftVolFloat;
                 float mRightVolFloat;
+
+                // audio patch used by the downstream software patch.
+                // Only used if ThreadBase::mIsMsdDevice is true.
+                struct audio_patch mDownStreamPatch;
 };
 
 class MixerThread : public PlaybackThread {
diff --git a/services/audioflinger/TrackBase.h b/services/audioflinger/TrackBase.h
index 01d5345..38dab5b 100644
--- a/services/audioflinger/TrackBase.h
+++ b/services/audioflinger/TrackBase.h
@@ -253,6 +253,8 @@
     // Called to tally underrun frames in playback.
     virtual void tallyUnderrunFrames(size_t /* frames */) {}
 
+    audio_channel_mask_t channelMask() const { return mChannelMask; }
+
 protected:
     DISALLOW_COPY_AND_ASSIGN(TrackBase);
 
@@ -278,8 +280,6 @@
 
     size_t frameSize() const { return mFrameSize; }
 
-    audio_channel_mask_t channelMask() const { return mChannelMask; }
-
     virtual uint32_t sampleRate() const { return mSampleRate; }
 
     bool isStopped() const {
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index f286d8a..ee886d5 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -54,6 +54,60 @@
 
 namespace android {
 
+// Validation methods for input
+namespace {
+
+status_t validateAudioDescriptionMixLevel(float leveldB)
+{
+    constexpr float MAX_AUDIO_DESCRIPTION_MIX_LEVEL = 48.f;
+    return std::isnan(leveldB) || leveldB > MAX_AUDIO_DESCRIPTION_MIX_LEVEL ? BAD_VALUE : OK;
+}
+
+status_t validateDualMonoMode(audio_dual_mono_mode_t dualMonoMode)
+{
+    switch (dualMonoMode) {
+        case AUDIO_DUAL_MONO_MODE_OFF:
+        case AUDIO_DUAL_MONO_MODE_LR:
+        case AUDIO_DUAL_MONO_MODE_LL:
+        case AUDIO_DUAL_MONO_MODE_RR:
+        return OK;
+    }
+    return BAD_VALUE;
+}
+
+status_t validatePlaybackRateFallbackMode(
+        audio_timestretch_fallback_mode_t fallbackMode)
+{
+    switch (fallbackMode) {
+        case AUDIO_TIMESTRETCH_FALLBACK_CUT_REPEAT:
+            break; // warning if not listed.
+        case AUDIO_TIMESTRETCH_FALLBACK_DEFAULT:
+        case AUDIO_TIMESTRETCH_FALLBACK_MUTE:
+        case AUDIO_TIMESTRETCH_FALLBACK_FAIL:
+            return OK;
+    }
+    return BAD_VALUE;
+}
+
+status_t validatePlaybackRateStretchMode(audio_timestretch_stretch_mode_t stretchMode)
+{
+    switch (stretchMode) {
+        case AUDIO_TIMESTRETCH_STRETCH_DEFAULT:
+        case AUDIO_TIMESTRETCH_STRETCH_VOICE:
+            return OK;
+    }
+    return BAD_VALUE;
+}
+
+status_t validatePlaybackRate(const audio_playback_rate_t& playbackRate)
+{
+    if (playbackRate.mSpeed < 0.f || playbackRate.mPitch < 0.f) return BAD_VALUE;
+    return validatePlaybackRateFallbackMode(playbackRate.mFallbackMode) ?:
+            validatePlaybackRateStretchMode(playbackRate.mStretchMode);
+}
+
+} // namespace
+
 using media::VolumeShaper;
 // ----------------------------------------------------------------------------
 //      TrackBase
@@ -367,12 +421,45 @@
     return mTrack->getTimestamp(timestamp);
 }
 
-
 void AudioFlinger::TrackHandle::signal()
 {
     return mTrack->signal();
 }
 
+status_t AudioFlinger::TrackHandle::getDualMonoMode(audio_dual_mono_mode_t* mode)
+{
+    return mTrack->getDualMonoMode(mode);
+}
+
+status_t AudioFlinger::TrackHandle::setDualMonoMode(audio_dual_mono_mode_t mode)
+{
+    return validateDualMonoMode(mode) ?: mTrack->setDualMonoMode(mode);
+}
+
+status_t AudioFlinger::TrackHandle::getAudioDescriptionMixLevel(float* leveldB)
+{
+    return mTrack->getAudioDescriptionMixLevel(leveldB);
+}
+
+status_t AudioFlinger::TrackHandle::setAudioDescriptionMixLevel(float leveldB)
+{
+    return validateAudioDescriptionMixLevel(leveldB)
+            ?: mTrack->setAudioDescriptionMixLevel(leveldB);
+}
+
+status_t AudioFlinger::TrackHandle::getPlaybackRateParameters(
+        audio_playback_rate_t* playbackRate)
+{
+    return mTrack->getPlaybackRateParameters(playbackRate);
+}
+
+status_t AudioFlinger::TrackHandle::setPlaybackRateParameters(
+        const audio_playback_rate_t& playbackRate)
+{
+    return validatePlaybackRate(playbackRate)
+            ?: mTrack->setPlaybackRateParameters(playbackRate);
+}
+
 status_t AudioFlinger::TrackHandle::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
@@ -1266,11 +1353,15 @@
 
 void AudioFlinger::PlaybackThread::Track::copyMetadataTo(MetadataInserter& backInserter) const
 {
-    *backInserter++ = {
+    playback_track_metadata_v7_t metadata;
+    metadata.base = {
             .usage = mAttr.usage,
             .content_type = mAttr.content_type,
             .gain = mFinalVolume,
     };
+    metadata.channel_mask = mChannelMask,
+    strncpy(metadata.tags, mAttr.tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
+    *backInserter++ = metadata;
 }
 
 void AudioFlinger::PlaybackThread::Track::setTeePatches(TeePatches teePatches) {
@@ -1452,6 +1543,108 @@
     }
 }
 
+status_t AudioFlinger::PlaybackThread::Track::getDualMonoMode(audio_dual_mono_mode_t* mode)
+{
+    status_t status = INVALID_OPERATION;
+    if (isOffloadedOrDirect()) {
+        sp<ThreadBase> thread = mThread.promote();
+        if (thread != nullptr) {
+            PlaybackThread *t = (PlaybackThread *)thread.get();
+            Mutex::Autolock _l(t->mLock);
+            status = t->mOutput->stream->getDualMonoMode(mode);
+            ALOGD_IF((status == NO_ERROR) && (mDualMonoMode != *mode),
+                    "%s: mode %d inconsistent", __func__, mDualMonoMode);
+        }
+    }
+    return status;
+}
+
+status_t AudioFlinger::PlaybackThread::Track::setDualMonoMode(audio_dual_mono_mode_t mode)
+{
+    status_t status = INVALID_OPERATION;
+    if (isOffloadedOrDirect()) {
+        sp<ThreadBase> thread = mThread.promote();
+        if (thread != nullptr) {
+            auto t = static_cast<PlaybackThread *>(thread.get());
+            Mutex::Autolock lock(t->mLock);
+            status = t->mOutput->stream->setDualMonoMode(mode);
+            if (status == NO_ERROR) {
+                mDualMonoMode = mode;
+            }
+        }
+    }
+    return status;
+}
+
+status_t AudioFlinger::PlaybackThread::Track::getAudioDescriptionMixLevel(float* leveldB)
+{
+    status_t status = INVALID_OPERATION;
+    if (isOffloadedOrDirect()) {
+        sp<ThreadBase> thread = mThread.promote();
+        if (thread != nullptr) {
+            auto t = static_cast<PlaybackThread *>(thread.get());
+            Mutex::Autolock lock(t->mLock);
+            status = t->mOutput->stream->getAudioDescriptionMixLevel(leveldB);
+            ALOGD_IF((status == NO_ERROR) && (mAudioDescriptionMixLevel != *leveldB),
+                    "%s: level %.3f inconsistent", __func__, mAudioDescriptionMixLevel);
+        }
+    }
+    return status;
+}
+
+status_t AudioFlinger::PlaybackThread::Track::setAudioDescriptionMixLevel(float leveldB)
+{
+    status_t status = INVALID_OPERATION;
+    if (isOffloadedOrDirect()) {
+        sp<ThreadBase> thread = mThread.promote();
+        if (thread != nullptr) {
+            auto t = static_cast<PlaybackThread *>(thread.get());
+            Mutex::Autolock lock(t->mLock);
+            status = t->mOutput->stream->setAudioDescriptionMixLevel(leveldB);
+            if (status == NO_ERROR) {
+                mAudioDescriptionMixLevel = leveldB;
+            }
+        }
+    }
+    return status;
+}
+
+status_t AudioFlinger::PlaybackThread::Track::getPlaybackRateParameters(
+        audio_playback_rate_t* playbackRate)
+{
+    status_t status = INVALID_OPERATION;
+    if (isOffloadedOrDirect()) {
+        sp<ThreadBase> thread = mThread.promote();
+        if (thread != nullptr) {
+            auto t = static_cast<PlaybackThread *>(thread.get());
+            Mutex::Autolock lock(t->mLock);
+            status = t->mOutput->stream->getPlaybackRateParameters(playbackRate);
+            ALOGD_IF((status == NO_ERROR) &&
+                    !isAudioPlaybackRateEqual(mPlaybackRateParameters, *playbackRate),
+                    "%s: playbackRate inconsistent", __func__);
+        }
+    }
+    return status;
+}
+
+status_t AudioFlinger::PlaybackThread::Track::setPlaybackRateParameters(
+        const audio_playback_rate_t& playbackRate)
+{
+    status_t status = INVALID_OPERATION;
+    if (isOffloadedOrDirect()) {
+        sp<ThreadBase> thread = mThread.promote();
+        if (thread != nullptr) {
+            auto t = static_cast<PlaybackThread *>(thread.get());
+            Mutex::Autolock lock(t->mLock);
+            status = t->mOutput->stream->setPlaybackRateParameters(playbackRate);
+            if (status == NO_ERROR) {
+                mPlaybackRateParameters = playbackRate;
+            }
+        }
+    }
+    return status;
+}
+
 //To be called with thread lock held
 bool AudioFlinger::PlaybackThread::Track::isResumePending() {
 
@@ -1933,6 +2126,25 @@
 {
     mProxy->releaseBuffer(buffer);
     restartIfDisabled();
+
+    // Check if the PatchTrack has enough data to write once in releaseBuffer().
+    // If not, prevent an underrun from occurring by moving the track into FS_FILLING;
+    // this logic avoids glitches when suspending A2DP with AudioPlaybackCapture.
+    // TODO: perhaps underrun avoidance could be a track property checked in isReady() instead.
+    if (mFillingUpStatus == FS_ACTIVE
+            && audio_is_linear_pcm(mFormat)
+            && !isOffloadedOrDirect()) {
+        if (sp<ThreadBase> thread = mThread.promote();
+            thread != 0) {
+            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
+            const size_t frameCount = playbackThread->frameCount() * sampleRate()
+                    / playbackThread->sampleRate();
+            if (framesReady() < frameCount) {
+                ALOGD("%s(%d) Not enough data, wait for buffer to fill", __func__, mId);
+                mFillingUpStatus = FS_FILLING;
+            }
+        }
+    }
 }
 
 void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled()
diff --git a/services/audioflinger/TypedLogger.h b/services/audioflinger/TypedLogger.h
index 6ef19bf..feb71e3 100644
--- a/services/audioflinger/TypedLogger.h
+++ b/services/audioflinger/TypedLogger.h
@@ -80,7 +80,7 @@
 
 // TODO Permit disabling of logging at compile-time.
 
-// TODO A non-nullptr dummy implementation that is a nop would be faster than checking for nullptr
+// TODO A non-nullptr stub implementation that is a nop would be faster than checking for nullptr
 //      in the case when logging is enabled at compile-time and enabled at runtime, but it might be
 //      slower than nullptr check when logging is enabled at compile-time and disabled at runtime.
 
@@ -129,8 +129,8 @@
 
 namespace android {
 extern "C" {
-// TODO consider adding a thread_local NBLog::Writer tlDummyNBLogWriter and then
-// initialize below tlNBLogWriter to &tlDummyNBLogWriter to remove the need to
+// TODO consider adding a thread_local NBLog::Writer tlStubNBLogWriter and then
+// initialize below tlNBLogWriter to &tlStubNBLogWriter to remove the need to
 // check for nullptr every time. Also reduces the need to add a new logging macro above
 // each time we want to log a new type.
 extern thread_local NBLog::Writer *tlNBLogWriter;
diff --git a/services/audiopolicy/Android.bp b/services/audiopolicy/Android.bp
index a42b89f..e018dd3 100644
--- a/services/audiopolicy/Android.bp
+++ b/services/audiopolicy/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libaudiopolicymanager_interface_headers",
     host_supported: true,
diff --git a/services/audiopolicy/AudioPolicyInterface.h b/services/audiopolicy/AudioPolicyInterface.h
index 8d0e5db..93819f5 100644
--- a/services/audiopolicy/AudioPolicyInterface.h
+++ b/services/audiopolicy/AudioPolicyInterface.h
@@ -250,12 +250,12 @@
     virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes) = 0;
     virtual status_t unregisterPolicyMixes(Vector<AudioMix> mixes) = 0;
 
-    virtual status_t setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices)
+    virtual status_t setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAddrVector& devices)
             = 0;
     virtual status_t removeUidDeviceAffinities(uid_t uid) = 0;
 
     virtual status_t setUserIdDeviceAffinities(int userId,
-            const Vector<AudioDeviceTypeAddr>& devices) = 0;
+            const AudioDeviceTypeAddrVector& devices) = 0;
     virtual status_t removeUserIdDeviceAffinities(int userId) = 0;
 
     virtual status_t startAudioSource(const struct audio_port_config *source,
@@ -295,13 +295,36 @@
 
     virtual bool     isCallScreenModeSupported() = 0;
 
-    virtual status_t setPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   const AudioDeviceTypeAddr &device) = 0;
+    virtual status_t setDevicesRoleForStrategy(product_strategy_t strategy,
+                                               device_role_t role,
+                                               const AudioDeviceTypeAddrVector &devices) = 0;
 
-    virtual status_t removePreferredDeviceForStrategy(product_strategy_t strategy) = 0;
+    virtual status_t removeDevicesRoleForStrategy(product_strategy_t strategy,
+                                                  device_role_t role) = 0;
 
-    virtual status_t getPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   AudioDeviceTypeAddr &device) = 0;
+
+    virtual status_t getDevicesForRoleAndStrategy(product_strategy_t strategy,
+                                                  device_role_t role,
+                                                  AudioDeviceTypeAddrVector &devices) = 0;
+
+    virtual status_t setDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                    device_role_t role,
+                                                    const AudioDeviceTypeAddrVector &devices) = 0;
+
+    virtual status_t addDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                    device_role_t role,
+                                                    const AudioDeviceTypeAddrVector &devices) = 0;
+
+    virtual status_t removeDevicesRoleForCapturePreset(
+            audio_source_t audioSource, device_role_t role,
+            const AudioDeviceTypeAddrVector& devices) = 0;
+
+    virtual status_t clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                      device_role_t role) = 0;
+
+    virtual status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+                                                       device_role_t role,
+                                                       AudioDeviceTypeAddrVector &devices) = 0;
 };
 
 
diff --git a/services/audiopolicy/OWNERS b/services/audiopolicy/OWNERS
index a8483fa..da9d32f 100644
--- a/services/audiopolicy/OWNERS
+++ b/services/audiopolicy/OWNERS
@@ -1,3 +1,2 @@
 jmtrivi@google.com
-krocard@google.com
 mnaganov@google.com
diff --git a/services/audiopolicy/common/Android.bp b/services/audiopolicy/common/Android.bp
index 6e0d2f6..91701ad 100644
--- a/services/audiopolicy/common/Android.bp
+++ b/services/audiopolicy/common/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libaudiopolicycommon",
     header_libs: [
diff --git a/services/audiopolicy/common/include/Volume.h b/services/audiopolicy/common/include/Volume.h
index 7c8ce83..736f8b2 100644
--- a/services/audiopolicy/common/include/Volume.h
+++ b/services/audiopolicy/common/include/Volume.h
@@ -126,6 +126,7 @@
         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
         case AUDIO_DEVICE_OUT_USB_HEADSET:
+        case AUDIO_DEVICE_OUT_BLE_HEADSET:
             return DEVICE_CATEGORY_HEADSET;
         case AUDIO_DEVICE_OUT_HEARING_AID:
             return DEVICE_CATEGORY_HEARING_AID;
@@ -139,6 +140,7 @@
         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
         case AUDIO_DEVICE_OUT_USB_ACCESSORY:
         case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
+        case AUDIO_DEVICE_OUT_BLE_SPEAKER:
         default:
             return DEVICE_CATEGORY_SPEAKER;
         }
diff --git a/services/audiopolicy/common/managerdefinitions/Android.bp b/services/audiopolicy/common/managerdefinitions/Android.bp
index 57f0b5b..227c2d8 100644
--- a/services/audiopolicy/common/managerdefinitions/Android.bp
+++ b/services/audiopolicy/common/managerdefinitions/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_static {
     name: "libaudiopolicycomponents",
 
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h
index 39d1140..1d9223e 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h
@@ -498,11 +498,6 @@
      */
     bool isA2dpOffloadedOnPrimary() const;
 
-    /**
-     * returns true if A2DP is supported (either via hardware offload or software encoding)
-     */
-    bool isA2dpSupported() const;
-
     sp<SwAudioOutputDescriptor> getOutputFromId(audio_port_handle_t id) const;
 
     sp<SwAudioOutputDescriptor> getPrimaryOutput() const;
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioPolicyConfig.h b/services/audiopolicy/common/managerdefinitions/include/AudioPolicyConfig.h
index 395bc70..cf1f64c 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioPolicyConfig.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioPolicyConfig.h
@@ -33,6 +33,15 @@
 
 namespace android {
 
+// This class gathers together various bits of AudioPolicyManager
+// configuration, which are usually filled out as a result of parsing
+// the audio_policy_configuration.xml file.
+//
+// Note that AudioPolicyConfig doesn't own some of the data,
+// it simply proxies access to the fields of AudioPolicyManager
+// class. Be careful about the fields that are references,
+// e.g. 'mOutputDevices'. This also means that it's impossible
+// to implement "deep copying" of this class without re-designing it.
 class AudioPolicyConfig
 {
 public:
@@ -40,14 +49,24 @@
                       DeviceVector &outputDevices,
                       DeviceVector &inputDevices,
                       sp<DeviceDescriptor> &defaultOutputDevice)
-        : mEngineLibraryNameSuffix(kDefaultEngineLibraryNameSuffix),
-          mHwModules(hwModules),
+        : mHwModules(hwModules),
           mOutputDevices(outputDevices),
           mInputDevices(inputDevices),
-          mDefaultOutputDevice(defaultOutputDevice),
-          mIsSpeakerDrcEnabled(false),
-          mIsCallScreenModeSupported(false)
-    {}
+          mDefaultOutputDevice(defaultOutputDevice) {
+        clear();
+    }
+
+    void clear() {
+        mSource = {};
+        mEngineLibraryNameSuffix = kDefaultEngineLibraryNameSuffix;
+        mHwModules.clear();
+        mOutputDevices.clear();
+        mInputDevices.clear();
+        mDefaultOutputDevice.clear();
+        mIsSpeakerDrcEnabled = false;
+        mIsCallScreenModeSupported = false;
+        mSurroundFormats.clear();
+    }
 
     const std::string& getSource() const {
         return mSource;
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioPolicyMix.h b/services/audiopolicy/common/managerdefinitions/include/AudioPolicyMix.h
index b82305d..c6bdb04 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioPolicyMix.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioPolicyMix.h
@@ -101,7 +101,7 @@
      *    An example of failure is when there are already rules in place to restrict
      *    a mix to the given uid (i.e. when a MATCH_UID rule was set for it).
      */
-    status_t setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices);
+    status_t setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAddrVector& devices);
     status_t removeUidDeviceAffinities(uid_t uid);
     status_t getDevicesForUid(uid_t uid, Vector<AudioDeviceTypeAddr>& devices) const;
 
@@ -115,7 +115,7 @@
      *    An example of failure is when there are already rules in place to restrict
      *    a mix to the given userId (i.e. when a MATCH_USERID rule was set for it).
      */
-    status_t setUserIdDeviceAffinities(int userId, const Vector<AudioDeviceTypeAddr>& devices);
+    status_t setUserIdDeviceAffinities(int userId, const AudioDeviceTypeAddrVector& devices);
     status_t removeUserIdDeviceAffinities(int userId);
     status_t getDevicesForUserId(int userId, Vector<AudioDeviceTypeAddr>& devices) const;
 
diff --git a/services/audiopolicy/common/managerdefinitions/include/ClientDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/ClientDescriptor.h
index 923310c..ce97748 100644
--- a/services/audiopolicy/common/managerdefinitions/include/ClientDescriptor.h
+++ b/services/audiopolicy/common/managerdefinitions/include/ClientDescriptor.h
@@ -195,10 +195,18 @@
 
     ~SourceClientDescriptor() override = default;
 
+    void connect(audio_patch_handle_t patchHandle, const sp<DeviceDescriptor>& sinkDevice) {
+        mPatchHandle = patchHandle;
+        mSinkDevice = sinkDevice;
+    }
+    void disconnect() {
+        mPatchHandle = AUDIO_PATCH_HANDLE_NONE;
+        mSinkDevice = nullptr;
+    }
+    bool isConnected() const { return mPatchHandle != AUDIO_PATCH_HANDLE_NONE; }
     audio_patch_handle_t getPatchHandle() const { return mPatchHandle; }
-    void setPatchHandle(audio_patch_handle_t patchHandle) { mPatchHandle = patchHandle; }
-
     sp<DeviceDescriptor> srcDevice() const { return mSrcDevice; }
+    sp<DeviceDescriptor> sinkDevice() const { return mSinkDevice; }
     wp<SwAudioOutputDescriptor> swOutput() const { return mSwOutput; }
     void setSwOutput(const sp<SwAudioOutputDescriptor>& swOutput);
     wp<HwAudioOutputDescriptor> hwOutput() const { return mHwOutput; }
@@ -210,6 +218,7 @@
  private:
     audio_patch_handle_t mPatchHandle = AUDIO_PATCH_HANDLE_NONE;
     const sp<DeviceDescriptor> mSrcDevice;
+    sp<DeviceDescriptor> mSinkDevice;
     wp<SwAudioOutputDescriptor> mSwOutput;
     wp<HwAudioOutputDescriptor> mHwOutput;
 };
diff --git a/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h
index dd1499c..ca29591 100644
--- a/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h
+++ b/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h
@@ -65,6 +65,9 @@
 
     bool supportsFormat(audio_format_t format);
 
+    void setDynamic() { mIsDynamic = true; }
+    bool isDynamic() const { return mIsDynamic; }
+
     // PolicyAudioPortConfig
     virtual sp<PolicyAudioPort> getPolicyAudioPort() const {
         return static_cast<PolicyAudioPort*>(const_cast<DeviceDescriptor*>(this));
@@ -97,6 +100,8 @@
     std::string mTagName; // Unique human readable identifier for a device port found in conf file.
     FormatVector        mEncodedFormats;
     audio_format_t      mCurrentEncodedFormat;
+    bool                mIsDynamic = false;
+    const std::string   mDeclaredAddress; // Original device address
 };
 
 class DeviceVector : public SortedVector<sp<DeviceDescriptor> >
@@ -146,6 +151,15 @@
     //     4) the combination of all devices is invalid for selection
     sp<DeviceDescriptor> getDeviceForOpening() const;
 
+    // Return the device descriptor that matches the given AudioDeviceTypeAddr
+    sp<DeviceDescriptor> getDeviceFromDeviceTypeAddr(
+            const AudioDeviceTypeAddr& deviceTypeAddr) const;
+
+    // Return the device vector that contains device descriptor whose AudioDeviceTypeAddr appears
+    // in the given AudioDeviceTypeAddrVector
+    DeviceVector getDevicesFromDeviceTypeAddrVec(
+            const AudioDeviceTypeAddrVector& deviceTypeAddrVector) const;
+
     // If there are devices with the given type and the devices to add is not empty,
     // remove all the devices with the given type and add all the devices to add.
     void replaceDevicesByType(audio_devices_t typeToRemove, const DeviceVector &devicesToAdd);
@@ -248,7 +262,9 @@
         return String8("");
     }
 
-    std::string toString() const;
+    // Return a string to describe the DeviceVector. The sensitive information will only be
+    // added to the string if `includeSensitiveInfo` is true.
+    std::string toString(bool includeSensitiveInfo = false) const;
 
     void dump(String8 *dst, const String8 &tag, int spaces = 0, bool verbose = true) const;
 
diff --git a/services/audiopolicy/common/managerdefinitions/include/HwModule.h b/services/audiopolicy/common/managerdefinitions/include/HwModule.h
index 23f0c9a..9ba745a 100644
--- a/services/audiopolicy/common/managerdefinitions/include/HwModule.h
+++ b/services/audiopolicy/common/managerdefinitions/include/HwModule.h
@@ -52,8 +52,12 @@
         devices.merge(mDynamicDevices);
         return devices;
     }
+    std::string getTagForDevice(audio_devices_t device,
+                                const String8 &address = String8(),
+                                audio_format_t codec = AUDIO_FORMAT_DEFAULT);
     void addDynamicDevice(const sp<DeviceDescriptor> &device)
     {
+        device->setDynamic();
         mDynamicDevices.add(device);
     }
 
@@ -131,8 +135,17 @@
 public:
     sp<HwModule> getModuleFromName(const char *name) const;
 
+    /**
+     * @brief getModuleForDeviceType try to get a device from type / format on all modules
+     * @param device type to consider
+     * @param encodedFormat to consider
+     * @param[out] tagName if not null, if a matching device is found, will return the tagName
+     * of original device from XML file so that audio routes matchin rules work.
+     * @return valid module if considered device found, nullptr otherwise.
+     */
     sp<HwModule> getModuleForDeviceType(audio_devices_t device,
-                                        audio_format_t encodedFormat) const;
+                                        audio_format_t encodedFormat,
+                                        std::string *tagName = nullptr) const;
 
     sp<HwModule> getModuleForDevice(const sp<DeviceDescriptor> &device,
                                     audio_format_t encodedFormat) const;
diff --git a/services/audiopolicy/common/managerdefinitions/include/IOProfile.h b/services/audiopolicy/common/managerdefinitions/include/IOProfile.h
index 5f551d5..11d3a99 100644
--- a/services/audiopolicy/common/managerdefinitions/include/IOProfile.h
+++ b/services/audiopolicy/common/managerdefinitions/include/IOProfile.h
@@ -112,6 +112,19 @@
     }
 
     /**
+     * @brief getTag
+     * @param deviceTypes to be considered
+     * @return tagName of first matching device for the considered types, empty string otherwise.
+     */
+    std::string getTag(const DeviceTypeSet& deviceTypes) const
+    {
+        if (supportsDeviceTypes(deviceTypes)) {
+            return mSupportedDevices.getDevicesFromTypes(deviceTypes).itemAt(0)->getTagName();
+        }
+        return {};
+    }
+
+    /**
      * @brief supportsDevice
      * @param device to be checked against
      *        forceCheckOnAddress if true, check on type and address whatever the type, otherwise
@@ -150,6 +163,12 @@
     }
     void removeSupportedDevice(const sp<DeviceDescriptor> &device)
     {
+        ssize_t ret = mSupportedDevices.indexOf(device);
+        if (ret >= 0 && !mSupportedDevices.itemAt(ret)->isDynamic()) {
+            // devices equality checks only type, address, name and format
+            // Prevents from removing non dynamically added devices
+            return;
+        }
         mSupportedDevices.remove(device);
     }
     void setSupportedDevices(const DeviceVector &devices)
diff --git a/services/audiopolicy/common/managerdefinitions/include/PolicyAudioPort.h b/services/audiopolicy/common/managerdefinitions/include/PolicyAudioPort.h
index d2f6297..e6eef24 100644
--- a/services/audiopolicy/common/managerdefinitions/include/PolicyAudioPort.h
+++ b/services/audiopolicy/common/managerdefinitions/include/PolicyAudioPort.h
@@ -42,6 +42,11 @@
 
     virtual const std::string getTagName() const = 0;
 
+    bool equals(const sp<PolicyAudioPort> &right) const
+    {
+        return getTagName() == right->getTagName();
+    }
+
     virtual sp<AudioPort> asAudioPort() const = 0;
 
     virtual void setFlags(uint32_t flags)
diff --git a/services/audiopolicy/common/managerdefinitions/include/Serializer.h b/services/audiopolicy/common/managerdefinitions/include/Serializer.h
index 48c4147..b70c595 100644
--- a/services/audiopolicy/common/managerdefinitions/include/Serializer.h
+++ b/services/audiopolicy/common/managerdefinitions/include/Serializer.h
@@ -21,5 +21,9 @@
 namespace android {
 
 status_t deserializeAudioPolicyFile(const char *fileName, AudioPolicyConfig *config);
+// In VTS mode all vendor extensions are ignored. This is done because
+// VTS tests are built using AOSP code and thus can not use vendor overlays
+// of system libraries.
+status_t deserializeAudioPolicyFileForVts(const char *fileName, AudioPolicyConfig *config);
 
 } // namespace android
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp
index b963121..4922ebe 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioInputDescriptor.cpp
@@ -516,7 +516,7 @@
     dst->appendFormat(" Sampling rate: %d\n", mSamplingRate);
     dst->appendFormat(" Format: %d\n", mFormat);
     dst->appendFormat(" Channels: %08x\n", mChannelMask);
-    dst->appendFormat(" Devices %s\n", mDevice->toString().c_str());
+    dst->appendFormat(" Devices %s\n", mDevice->toString(true /*includeSensitiveInfo*/).c_str());
     mEnabledEffects.dump(dst, 1 /*spaces*/, false /*verbose*/);
     dst->append(" AudioRecord Clients:\n");
     ClientMapHandler<RecordClientDescriptor>::dump(dst);
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
index d6d472b..5c47d1b 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp
@@ -245,7 +245,7 @@
     dst->appendFormat(" Sampling rate: %d\n", mSamplingRate);
     dst->appendFormat(" Format: %08x\n", mFormat);
     dst->appendFormat(" Channels: %08x\n", mChannelMask);
-    dst->appendFormat(" Devices: %s\n", devices().toString().c_str());
+    dst->appendFormat(" Devices: %s\n", devices().toString(true /*includeSensitiveInfo*/).c_str());
     dst->appendFormat(" Global active count: %u\n", mGlobalActiveCount);
     for (const auto &iter : mRoutingActivities) {
         dst->appendFormat(" Product Strategy id: %d", iter.first);
@@ -505,6 +505,9 @@
         lConfig.offload_info.duration_us = -1;
         lConfig.offload_info.has_video = true; // conservative
         lConfig.offload_info.is_streaming = true; // likely
+        lConfig.offload_info.encapsulation_mode = lConfig.offload_info.encapsulation_mode;
+        lConfig.offload_info.content_id = lConfig.offload_info.content_id;
+        lConfig.offload_info.sync_id = lConfig.offload_info.sync_id;
     }
 
     mFlags = (audio_output_flags_t)(mFlags | flags);
@@ -764,11 +767,6 @@
     return false;
 }
 
-bool SwAudioOutputCollection::isA2dpSupported() const
-{
-    return (isA2dpOffloadedOnPrimary() || (getA2dpOutput() != 0));
-}
-
 sp<SwAudioOutputDescriptor> SwAudioOutputCollection::getPrimaryOutput() const
 {
     for (size_t i = 0; i < size(); i++) {
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioPolicyMix.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioPolicyMix.cpp
index b6de4be..fc1d0e2 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioPolicyMix.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioPolicyMix.cpp
@@ -463,7 +463,7 @@
 }
 
 status_t AudioPolicyMixCollection::setUidDeviceAffinities(uid_t uid,
-        const Vector<AudioDeviceTypeAddr>& devices) {
+        const AudioDeviceTypeAddrVector& devices) {
     // verify feasibility: for each player mix: if it already contains a
     //    "match uid" rule for this uid, return an error
     //    (adding a uid-device affinity would result in contradictory rules)
@@ -565,7 +565,7 @@
 }
 
 status_t AudioPolicyMixCollection::setUserIdDeviceAffinities(int userId,
-        const Vector<AudioDeviceTypeAddr>& devices) {
+        const AudioDeviceTypeAddrVector& devices) {
     // verify feasibility: for each player mix: if it already contains a
     //    "match userId" rule for this userId, return an error
     //    (adding a userId-device affinity would result in contradictory rules)
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioRoute.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioRoute.cpp
index 2a18f19..c8e4e76 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioRoute.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioRoute.cpp
@@ -39,12 +39,12 @@
 bool AudioRoute::supportsPatch(const sp<PolicyAudioPort> &srcPort,
                                const sp<PolicyAudioPort> &dstPort) const
 {
-    if (mSink == 0 || dstPort == 0 || dstPort != mSink) {
+    if (mSink == 0 || dstPort == 0 || !dstPort->equals(mSink)) {
         return false;
     }
     ALOGV("%s: sinks %s matching", __FUNCTION__, mSink->getTagName().c_str());
     for (const auto &sourcePort : mSources) {
-        if (sourcePort == srcPort) {
+        if (sourcePort->equals(srcPort)) {
             ALOGV("%s: sources %s matching", __FUNCTION__, sourcePort->getTagName().c_str());
             return true;
         }
diff --git a/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp
index a29e60e..f6859c7 100644
--- a/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp
@@ -49,10 +49,13 @@
 {
 }
 
+// Let DeviceDescriptorBase initialize the address since it handles specific cases like
+// legacy remote submix where "0" is added as default address.
 DeviceDescriptor::DeviceDescriptor(const AudioDeviceTypeAddr &deviceTypeAddr,
                                    const std::string &tagName,
                                    const FormatVector &encodedFormats) :
-        DeviceDescriptorBase(deviceTypeAddr), mTagName(tagName), mEncodedFormats(encodedFormats)
+        DeviceDescriptorBase(deviceTypeAddr), mTagName(tagName), mEncodedFormats(encodedFormats),
+        mDeclaredAddress(DeviceDescriptorBase::address())
 {
     mCurrentEncodedFormat = AUDIO_FORMAT_DEFAULT;
     /* If framework runs against a pre 5.0 Audio HAL, encoded formats are absent from the config.
@@ -75,6 +78,10 @@
 void DeviceDescriptor::detach() {
     mId = AUDIO_PORT_HANDLE_NONE;
     PolicyAudioPort::detach();
+    // The device address may have been overwritten on device connection
+    setAddress(mDeclaredAddress);
+    // Device Port does not have a name unless provided by setDeviceConnectionState
+    setName("");
 }
 
 template<typename T>
@@ -375,7 +382,7 @@
     if (isEmpty()) {
         // Return nullptr if this collection is empty.
         return nullptr;
-    } else if (areAllOfSameDeviceType(types(), audio_is_input_device)) {
+    } else if (areAllOfSameDeviceType(types(), audio_call_is_input_device)) {
         // For input case, return the first one when there is only one device.
         return size() > 1 ? nullptr : *begin();
     } else if (areAllOfSameDeviceType(types(), audio_is_output_device)) {
@@ -388,6 +395,24 @@
     return nullptr;
 }
 
+sp<DeviceDescriptor> DeviceVector::getDeviceFromDeviceTypeAddr(
+            const AudioDeviceTypeAddr& deviceTypeAddr) const {
+    return getDevice(deviceTypeAddr.mType, String8(deviceTypeAddr.getAddress()),
+            AUDIO_FORMAT_DEFAULT);
+}
+
+DeviceVector DeviceVector::getDevicesFromDeviceTypeAddrVec(
+        const AudioDeviceTypeAddrVector& deviceTypeAddrVector) const {
+    DeviceVector devices;
+    for (const auto& deviceTypeAddr : deviceTypeAddrVector) {
+        sp<DeviceDescriptor> device = getDeviceFromDeviceTypeAddr(deviceTypeAddr);
+        if (device != nullptr) {
+            devices.add(device);
+        }
+    }
+    return devices;
+}
+
 void DeviceVector::replaceDevicesByType(
         audio_devices_t typeToRemove, const DeviceVector &devicesToAdd) {
     DeviceVector devicesToRemove = getDevicesFromType(typeToRemove);
@@ -408,7 +433,7 @@
     }
 }
 
-std::string DeviceVector::toString() const
+std::string DeviceVector::toString(bool includeSensitiveInfo) const
 {
     if (isEmpty()) {
         return {"AUDIO_DEVICE_NONE"};
@@ -418,7 +443,7 @@
         if (device != *begin()) {
            result += ";";
         }
-        result += device->toString();
+        result += device->toString(includeSensitiveInfo);
     }
     return result + "}";
 }
diff --git a/services/audiopolicy/common/managerdefinitions/src/HwModule.cpp b/services/audiopolicy/common/managerdefinitions/src/HwModule.cpp
index d31e443..3a143b0 100644
--- a/services/audiopolicy/common/managerdefinitions/src/HwModule.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/HwModule.cpp
@@ -41,6 +41,14 @@
     }
 }
 
+std::string HwModule::getTagForDevice(audio_devices_t device, const String8 &address,
+                                          audio_format_t codec)
+{
+    DeviceVector declaredDevices = getDeclaredDevices();
+    sp<DeviceDescriptor> deviceDesc = declaredDevices.getDevice(device, address, codec);
+    return deviceDesc ? deviceDesc->getTagName() : std::string{};
+}
+
 status_t HwModule::addOutputProfile(const std::string& name, const audio_config_t *config,
                                     audio_devices_t device, const String8& address)
 {
@@ -49,7 +57,8 @@
     profile->addAudioProfile(new AudioProfile(config->format, config->channel_mask,
                                               config->sample_rate));
 
-    sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device, "" /*tagName*/, address.string());
+    sp<DeviceDescriptor> devDesc =
+            new DeviceDescriptor(device, getTagForDevice(device), address.string());
     addDynamicDevice(devDesc);
     // Reciprocally attach the device to the module
     devDesc->attach(this);
@@ -116,7 +125,8 @@
     profile->addAudioProfile(new AudioProfile(config->format, config->channel_mask,
                                               config->sample_rate));
 
-    sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device, "" /*tagName*/, address.string());
+    sp<DeviceDescriptor> devDesc =
+            new DeviceDescriptor(device, getTagForDevice(device), address.string());
     addDynamicDevice(devDesc);
     // Reciprocally attach the device to the module
     devDesc->attach(this);
@@ -271,8 +281,9 @@
     return nullptr;
 }
 
-sp <HwModule> HwModuleCollection::getModuleForDeviceType(audio_devices_t type,
-                                                         audio_format_t encodedFormat) const
+sp<HwModule> HwModuleCollection::getModuleForDeviceType(audio_devices_t type,
+                                                        audio_format_t encodedFormat,
+                                                        std::string *tagName) const
 {
     for (const auto& module : *this) {
         const auto& profiles = audio_is_output_device(type) ?
@@ -284,9 +295,15 @@
                     sp <DeviceDescriptor> deviceDesc =
                             declaredDevices.getDevice(type, String8(), encodedFormat);
                     if (deviceDesc) {
+                        if (tagName != nullptr) {
+                            *tagName = deviceDesc->getTagName();
+                        }
                         return module;
                     }
                 } else {
+                    if (tagName != nullptr) {
+                        *tagName = profile->getTag({type});
+                    }
                     return module;
                 }
             }
@@ -325,15 +342,32 @@
     }
 
     for (const auto& hwModule : *this) {
+        if (!allowToCreate) {
+            auto dynamicDevices = hwModule->getDynamicDevices();
+            auto dynamicDevice = dynamicDevices.getDevice(deviceType, devAddress, encodedFormat);
+            if (dynamicDevice) {
+                return dynamicDevice;
+            }
+        }
         DeviceVector moduleDevices = hwModule->getAllDevices();
         auto moduleDevice = moduleDevices.getDevice(deviceType, devAddress, encodedFormat);
+
+        // Prevent overwritting moduleDevice address if connected device does not have the same
+        // address (since getDevice with empty address ignores match on address), use dynamic device
+        if (moduleDevice && allowToCreate &&
+                (!moduleDevice->address().empty() &&
+                 (moduleDevice->address().compare(devAddress.c_str()) != 0))) {
+            break;
+        }
         if (moduleDevice) {
             if (encodedFormat != AUDIO_FORMAT_DEFAULT) {
                 moduleDevice->setEncodedFormat(encodedFormat);
             }
             if (allowToCreate) {
                 moduleDevice->attach(hwModule);
+                // Name may be overwritten, restored on detach.
                 moduleDevice->setAddress(devAddress.string());
+                // Name may be overwritten, restored on detach.
                 moduleDevice->setName(name);
             }
             return moduleDevice;
@@ -352,18 +386,19 @@
                                                       const char *name,
                                                       const audio_format_t encodedFormat) const
 {
-    sp<HwModule> hwModule = getModuleForDeviceType(type, encodedFormat);
+    std::string tagName = {};
+    sp<HwModule> hwModule = getModuleForDeviceType(type, encodedFormat, &tagName);
     if (hwModule == 0) {
         ALOGE("%s: could not find HW module for device %04x address %s", __FUNCTION__, type,
               address);
         return nullptr;
     }
 
-    sp<DeviceDescriptor> device = new DeviceDescriptor(type, name, address);
+    sp<DeviceDescriptor> device = new DeviceDescriptor(type, tagName, address);
     device->setName(name);
     device->setEncodedFormat(encodedFormat);
-
-  // Add the device to the list of dynamic devices
+    device->setDynamic();
+    // Add the device to the list of dynamic devices
     hwModule->addDynamicDevice(device);
     // Reciprocally attach the device to the module
     device->attach(hwModule);
@@ -375,7 +410,7 @@
     for (const auto &profile : profiles) {
         // Add the device as supported to all profile supporting "weakly" or not the device
         // according to its type
-        if (profile->supportsDevice(device, false /*matchAdress*/)) {
+        if (profile->supportsDevice(device, false /*matchAddress*/)) {
 
             // @todo quid of audio profile? import the profile from device of the same type?
             const auto &isoTypeDeviceForProfile =
@@ -406,10 +441,9 @@
 
         device->detach();
         // Only remove from dynamic list, not from declared list!!!
-        if (!hwModule->getDynamicDevices().contains(device)) {
+        if (!hwModule->removeDynamicDevice(device)) {
             return;
         }
-        hwModule->removeDynamicDevice(device);
         ALOGV("%s: removed dynamic device %s from module %s", __FUNCTION__,
               device->toString().c_str(), hwModule->getName());
 
diff --git a/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp b/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp
index bf1a0f7..ae92b40 100644
--- a/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp
@@ -17,7 +17,7 @@
 #define LOG_TAG "APM::IOProfile"
 //#define LOG_NDEBUG 0
 
-#include <system/audio-base.h>
+#include <system/audio.h>
 #include "IOProfile.h"
 #include "HwModule.h"
 #include "TypeConverter.h"
@@ -112,12 +112,11 @@
     dst->append(portStr.c_str());
 
     dst->appendFormat("    - flags: 0x%04x", getFlags());
-    std::string flagsLiteral;
-    if (getRole() == AUDIO_PORT_ROLE_SINK) {
-        InputFlagConverter::maskToString(getFlags(), flagsLiteral);
-    } else if (getRole() == AUDIO_PORT_ROLE_SOURCE) {
-        OutputFlagConverter::maskToString(getFlags(), flagsLiteral);
-    }
+    std::string flagsLiteral =
+            getRole() == AUDIO_PORT_ROLE_SINK ?
+            toString(static_cast<audio_input_flags_t>(getFlags())) :
+            getRole() == AUDIO_PORT_ROLE_SOURCE ?
+            toString(static_cast<audio_output_flags_t>(getFlags())) : "";
     if (!flagsLiteral.empty()) {
         dst->appendFormat(" (%s)", flagsLiteral.c_str());
     }
diff --git a/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp b/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp
index 883e713..562c213 100644
--- a/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp
@@ -20,8 +20,8 @@
 #include <memory>
 #include <string>
 #include <utility>
+#include <variant>
 
-#include <hidl/Status.h>
 #include <libxml/parser.h>
 #include <libxml/xinclude.h>
 #include <media/convert.h>
@@ -36,11 +36,14 @@
 
 namespace {
 
-// TODO(mnaganov): Consider finding an alternative for using HIDL code.
-using hardware::Return;
-using hardware::Status;
 using utilities::convertTo;
 
+static inline bool maybeVendorExtension(const std::string& s) {
+    // Only checks whether the string starts with the "vendor prefix".
+    static const std::string vendorPrefix = "VX_";
+    return s.size() > vendorPrefix.size() && s.substr(0, vendorPrefix.size()) == vendorPrefix;
+}
+
 template<typename E, typename C>
 struct AndroidCollectionTraits {
     typedef sp<E> Element;
@@ -89,7 +92,6 @@
 
     };
 
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
     // No children
 };
 
@@ -106,8 +108,6 @@
         static constexpr const char *format = "format";
         static constexpr const char *channelMasks = "channelMasks";
     };
-
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
 };
 
 struct MixPortTraits : public AndroidCollectionTraits<IOProfile, IOProfileCollection>
@@ -125,7 +125,6 @@
         static constexpr const char *maxActiveCount = "maxActiveCount";
     };
 
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
     // Children: GainTraits
 };
 
@@ -147,7 +146,6 @@
         static constexpr const char *encodedFormats = "encodedFormats";
     };
 
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
     // Children: GainTraits (optional)
 };
 
@@ -166,8 +164,6 @@
     };
 
     typedef HwModule *PtrSerializingCtx;
-
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
 };
 
 struct ModuleTraits : public AndroidCollectionTraits<HwModule, HwModuleCollection>
@@ -187,13 +183,14 @@
 
     typedef AudioPolicyConfig *PtrSerializingCtx;
 
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
     // Children: mixPortTraits, devicePortTraits, and routeTraits
     // Need to call deserialize on each child
 };
 
 struct GlobalConfigTraits
 {
+    typedef std::monostate Element;
+
     static constexpr const char *tag = "globalConfiguration";
 
     struct Attributes
@@ -203,14 +200,16 @@
         static constexpr const char *engineLibrarySuffix = "engine_library";
     };
 
-    static status_t deserialize(const xmlNode *root, AudioPolicyConfig *config);
+    typedef AudioPolicyConfig *PtrSerializingCtx;
 };
 
 struct SurroundSoundTraits
 {
+    typedef std::monostate Element;
+
     static constexpr const char *tag = "surroundSound";
 
-    static status_t deserialize(const xmlNode *root, AudioPolicyConfig *config);
+    typedef AudioPolicyConfig *PtrSerializingCtx;
     // Children: SurroundSoundFormatTraits
 };
 
@@ -224,28 +223,32 @@
         static constexpr const char *name = "name";
         static constexpr const char *subformats = "subformats";
     };
-
-    static Return<Element> deserialize(const xmlNode *cur, PtrSerializingCtx serializingContext);
 };
 
 class PolicySerializer
 {
 public:
-    PolicySerializer() : mVersion{std::to_string(gMajor) + "." + std::to_string(gMinor)}
-    {
-        ALOGV("%s: Version=%s Root=%s", __func__, mVersion.c_str(), rootName);
-    }
-    status_t deserialize(const char *configFile, AudioPolicyConfig *config);
+    status_t deserialize(const char *configFile, AudioPolicyConfig *config,
+            bool ignoreVendorExtensions = false);
+
+    template <class Trait>
+    status_t deserializeCollection(const xmlNode *cur,
+            typename Trait::Collection *collection,
+            typename Trait::PtrSerializingCtx serializingContext);
+    template <class Trait>
+    std::variant<status_t, typename Trait::Element> deserialize(const xmlNode *cur,
+            typename Trait::PtrSerializingCtx serializingContext);
 
 private:
     static constexpr const char *rootName = "audioPolicyConfiguration";
     static constexpr const char *versionAttribute = "version";
-    static constexpr uint32_t gMajor = 1; /**< the major number of the policy xml format version. */
-    static constexpr uint32_t gMinor = 0; /**< the minor number of the policy xml format version. */
 
     typedef AudioPolicyConfig Element;
 
-    const std::string mVersion;
+    bool mIgnoreVendorExtensions = false;
+    std::string mChannelMasksSeparator = ",";
+    std::string mSamplingRatesSeparator = ",";
+    std::string mFlagsSeparator = "|";
 
     // Children: ModulesTraits, VolumeTraits, SurroundSoundTraits (optional)
 };
@@ -254,9 +257,8 @@
 constexpr void (*xmlDeleter)(T* t);
 template <>
 constexpr auto xmlDeleter<xmlDoc> = xmlFreeDoc;
-// http://b/111067277 - Add back constexpr when we switch to C++17.
 template <>
-auto xmlDeleter<xmlChar> = [](xmlChar *s) { xmlFree(s); };
+constexpr auto xmlDeleter<xmlChar> = [](xmlChar *s) { xmlFree(s); };
 
 /** @return a unique_ptr with the correct deleter for the libxml2 object. */
 template <class T>
@@ -296,7 +298,7 @@
 }
 
 template <class Trait>
-status_t deserializeCollection(const xmlNode *cur,
+status_t PolicySerializer::deserializeCollection(const xmlNode *cur,
         typename Trait::Collection *collection,
         typename Trait::PtrSerializingCtx serializingContext)
 {
@@ -309,14 +311,17 @@
         }
         for (; child != NULL; child = child->next) {
             if (!xmlStrcmp(child->name, reinterpret_cast<const xmlChar*>(Trait::tag))) {
-                auto element = Trait::deserialize(child, serializingContext);
-                if (element.isOk()) {
-                    status_t status = Trait::addElementToCollection(element, collection);
+                auto maybeElement = deserialize<Trait>(child, serializingContext);
+                if (maybeElement.index() == 1) {
+                    status_t status = Trait::addElementToCollection(
+                            std::get<1>(maybeElement), collection);
                     if (status != NO_ERROR) {
                         ALOGE("%s: could not add element to %s collection", __func__,
                             Trait::collectionTag);
                         return status;
                     }
+                } else if (mIgnoreVendorExtensions && std::get<status_t>(maybeElement) == NO_INIT) {
+                    // Skip a vendor extension element.
                 } else {
                     return BAD_VALUE;
                 }
@@ -329,15 +334,18 @@
     return NO_ERROR;
 }
 
-Return<AudioGainTraits::Element> AudioGainTraits::deserialize(const xmlNode *cur,
-        PtrSerializingCtx /*serializingContext*/)
+template<>
+std::variant<status_t, AudioGainTraits::Element> PolicySerializer::deserialize<AudioGainTraits>(
+        const xmlNode *cur, AudioGainTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = AudioGainTraits::Attributes;
+
     static uint32_t index = 0;
-    Element gain = new AudioGain(index++, true);
+    AudioGainTraits::Element gain = new AudioGain(index++, true);
 
     std::string mode = getXmlAttribute(cur, Attributes::mode);
     if (!mode.empty()) {
-        gain->setMode(GainModeConverter::maskFromString(mode));
+        gain->setMode(GainModeConverter::maskFromString(mode, " "));
     }
 
     std::string channelsLiteral = getXmlAttribute(cur, Attributes::channelMask);
@@ -392,20 +400,28 @@
     if (gain->getMode() != 0) {
         return gain;
     } else {
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
 }
 
-Return<AudioProfileTraits::Element> AudioProfileTraits::deserialize(const xmlNode *cur,
-        PtrSerializingCtx /*serializingContext*/)
+template<>
+std::variant<status_t, AudioProfileTraits::Element>
+PolicySerializer::deserialize<AudioProfileTraits>(
+        const xmlNode *cur, AudioProfileTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = AudioProfileTraits::Attributes;
+
     std::string samplingRates = getXmlAttribute(cur, Attributes::samplingRates);
     std::string format = getXmlAttribute(cur, Attributes::format);
     std::string channels = getXmlAttribute(cur, Attributes::channelMasks);
 
-    Element profile = new AudioProfile(formatFromString(format, gDynamicFormat),
-            channelMasksFromString(channels, ","),
-            samplingRatesFromString(samplingRates, ","));
+    if (mIgnoreVendorExtensions && maybeVendorExtension(format)) {
+        ALOGI("%s: vendor extension format \"%s\" skipped", __func__, format.c_str());
+        return NO_INIT;
+    }
+    AudioProfileTraits::Element profile = new AudioProfile(formatFromString(format, gDynamicFormat),
+            channelMasksFromString(channels, mChannelMasksSeparator.c_str()),
+            samplingRatesFromString(samplingRates, mSamplingRatesSeparator.c_str()));
 
     profile->setDynamicFormat(profile->getFormat() == gDynamicFormat);
     profile->setDynamicChannels(profile->getChannels().empty());
@@ -414,30 +430,33 @@
     return profile;
 }
 
-Return<MixPortTraits::Element> MixPortTraits::deserialize(const xmlNode *child,
-        PtrSerializingCtx /*serializingContext*/)
+template<>
+std::variant<status_t, MixPortTraits::Element> PolicySerializer::deserialize<MixPortTraits>(
+        const xmlNode *child, MixPortTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = MixPortTraits::Attributes;
+
     std::string name = getXmlAttribute(child, Attributes::name);
     if (name.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::name);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
-    ALOGV("%s: %s %s=%s", __func__, tag, Attributes::name, name.c_str());
+    ALOGV("%s: %s %s=%s", __func__, MixPortTraits::tag, Attributes::name, name.c_str());
     std::string role = getXmlAttribute(child, Attributes::role);
     if (role.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::role);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
     ALOGV("%s: Role=%s", __func__, role.c_str());
     audio_port_role_t portRole = (role == Attributes::roleSource) ?
             AUDIO_PORT_ROLE_SOURCE : AUDIO_PORT_ROLE_SINK;
 
-    Element mixPort = new IOProfile(name, portRole);
+    MixPortTraits::Element mixPort = new IOProfile(name, portRole);
 
     AudioProfileTraits::Collection profiles;
     status_t status = deserializeCollection<AudioProfileTraits>(child, &profiles, NULL);
     if (status != NO_ERROR) {
-        return Status::fromStatusT(status);
+        return status;
     }
     if (profiles.empty()) {
         profiles.add(AudioProfile::createFullDynamic(gDynamicFormat));
@@ -451,10 +470,10 @@
     if (!flags.empty()) {
         // Source role
         if (portRole == AUDIO_PORT_ROLE_SOURCE) {
-            mixPort->setFlags(OutputFlagConverter::maskFromString(flags));
+            mixPort->setFlags(OutputFlagConverter::maskFromString(flags, mFlagsSeparator.c_str()));
         } else {
             // Sink role
-            mixPort->setFlags(InputFlagConverter::maskFromString(flags));
+            mixPort->setFlags(InputFlagConverter::maskFromString(flags, mFlagsSeparator.c_str()));
         }
     }
     std::string maxOpenCount = getXmlAttribute(child, Attributes::maxOpenCount);
@@ -469,43 +488,51 @@
     AudioGainTraits::Collection gains;
     status = deserializeCollection<AudioGainTraits>(child, &gains, NULL);
     if (status != NO_ERROR) {
-        return Status::fromStatusT(status);
+        return status;
     }
     mixPort->setGains(gains);
 
     return mixPort;
 }
 
-Return<DevicePortTraits::Element> DevicePortTraits::deserialize(const xmlNode *cur,
-        PtrSerializingCtx /*serializingContext*/)
+template<>
+std::variant<status_t, DevicePortTraits::Element> PolicySerializer::deserialize<DevicePortTraits>(
+        const xmlNode *cur, DevicePortTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = DevicePortTraits::Attributes;
+    auto& tag = DevicePortTraits::tag;
+
     std::string name = getXmlAttribute(cur, Attributes::tagName);
     if (name.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::tagName);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
     ALOGV("%s: %s %s=%s", __func__, tag, Attributes::tagName, name.c_str());
     std::string typeName = getXmlAttribute(cur, Attributes::type);
     if (typeName.empty()) {
         ALOGE("%s: no type for %s", __func__, name.c_str());
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
     ALOGV("%s: %s %s=%s", __func__, tag, Attributes::type, typeName.c_str());
     std::string role = getXmlAttribute(cur, Attributes::role);
     if (role.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::role);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
     ALOGV("%s: %s %s=%s", __func__, tag, Attributes::role, role.c_str());
     audio_port_role_t portRole = (role == Attributes::roleSource) ?
                 AUDIO_PORT_ROLE_SOURCE : AUDIO_PORT_ROLE_SINK;
 
+    if (mIgnoreVendorExtensions && maybeVendorExtension(typeName)) {
+        ALOGI("%s: vendor extension device type \"%s\" skipped", __func__, typeName.c_str());
+        return NO_INIT;
+    }
     audio_devices_t type = AUDIO_DEVICE_NONE;
-    if (!deviceFromString(typeName, type) ||
+    if (!DeviceConverter::fromString(typeName, type) ||
             (!audio_is_input_device(type) && portRole == AUDIO_PORT_ROLE_SOURCE) ||
             (!audio_is_output_devices(type) && portRole == AUDIO_PORT_ROLE_SINK)) {
         ALOGW("%s: bad type %08x", __func__, type);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
     std::string encodedFormatsLiteral = getXmlAttribute(cur, Attributes::encodedFormats);
     ALOGV("%s: %s %s=%s", __func__, tag, Attributes::encodedFormats, encodedFormatsLiteral.c_str());
@@ -514,12 +541,13 @@
         encodedFormats = formatsFromString(encodedFormatsLiteral, " ");
     }
     std::string address = getXmlAttribute(cur, Attributes::address);
-    Element deviceDesc = new DeviceDescriptor(type, name, address, encodedFormats);
+    DevicePortTraits::Element deviceDesc =
+            new DeviceDescriptor(type, name, address, encodedFormats);
 
     AudioProfileTraits::Collection profiles;
     status_t status = deserializeCollection<AudioProfileTraits>(cur, &profiles, NULL);
     if (status != NO_ERROR) {
-        return Status::fromStatusT(status);
+        return status;
     }
     if (profiles.empty()) {
         profiles.add(AudioProfile::createFullDynamic(gDynamicFormat));
@@ -532,43 +560,51 @@
     // Deserialize AudioGain children
     status = deserializeCollection<AudioGainTraits>(cur, &deviceDesc->mGains, NULL);
     if (status != NO_ERROR) {
-        return Status::fromStatusT(status);
+        return status;
     }
     ALOGV("%s: adding device tag %s type %08x address %s", __func__,
           deviceDesc->getName().c_str(), type, deviceDesc->address().c_str());
     return deviceDesc;
 }
 
-Return<RouteTraits::Element> RouteTraits::deserialize(const xmlNode *cur, PtrSerializingCtx ctx)
+template<>
+std::variant<status_t, RouteTraits::Element> PolicySerializer::deserialize<RouteTraits>(
+        const xmlNode *cur, RouteTraits::PtrSerializingCtx ctx)
 {
+    using Attributes = RouteTraits::Attributes;
+
     std::string type = getXmlAttribute(cur, Attributes::type);
     if (type.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::type);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
     audio_route_type_t routeType = (type == Attributes::typeMix) ?
                 AUDIO_ROUTE_MIX : AUDIO_ROUTE_MUX;
 
-    ALOGV("%s: %s %s=%s", __func__, tag, Attributes::type, type.c_str());
-    Element route = new AudioRoute(routeType);
+    ALOGV("%s: %s %s=%s", __func__, RouteTraits::tag, Attributes::type, type.c_str());
+    RouteTraits::Element route = new AudioRoute(routeType);
 
     std::string sinkAttr = getXmlAttribute(cur, Attributes::sink);
     if (sinkAttr.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::sink);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
     // Convert Sink name to port pointer
     sp<PolicyAudioPort> sink = ctx->findPortByTagName(sinkAttr);
-    if (sink == NULL) {
+    if (sink == NULL && !mIgnoreVendorExtensions) {
         ALOGE("%s: no sink found with name=%s", __func__, sinkAttr.c_str());
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
+    } else if (sink == NULL) {
+        ALOGW("Skipping route to sink \"%s\" as it likely has vendor extension type",
+                sinkAttr.c_str());
+        return NO_INIT;
     }
     route->setSink(sink);
 
     std::string sourcesAttr = getXmlAttribute(cur, Attributes::sources);
     if (sourcesAttr.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::sources);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
     // Tokenize and Convert Sources name to port pointer
     PolicyAudioPortVector sources;
@@ -578,11 +614,15 @@
     while (devTag != NULL) {
         if (strlen(devTag) != 0) {
             sp<PolicyAudioPort> source = ctx->findPortByTagName(devTag);
-            if (source == NULL) {
+            if (source == NULL && !mIgnoreVendorExtensions) {
                 ALOGE("%s: no source found with name=%s", __func__, devTag);
-                return Status::fromStatusT(BAD_VALUE);
+                return BAD_VALUE;
+            } else if (source == NULL) {
+                ALOGW("Skipping route source \"%s\" as it likely has vendor extension type",
+                        devTag);
+            } else {
+                sources.add(source);
             }
-            sources.add(source);
         }
         devTag = strtok(NULL, ",");
     }
@@ -596,12 +636,20 @@
     return route;
 }
 
-Return<ModuleTraits::Element> ModuleTraits::deserialize(const xmlNode *cur, PtrSerializingCtx ctx)
+template<>
+std::variant<status_t, ModuleTraits::Element> PolicySerializer::deserialize<ModuleTraits>(
+        const xmlNode *cur, ModuleTraits::PtrSerializingCtx ctx)
 {
+    using Attributes = ModuleTraits::Attributes;
+    auto& tag = ModuleTraits::tag;
+    auto& childAttachedDevicesTag = ModuleTraits::childAttachedDevicesTag;
+    auto& childAttachedDeviceTag = ModuleTraits::childAttachedDeviceTag;
+    auto& childDefaultOutputDeviceTag = ModuleTraits::childDefaultOutputDeviceTag;
+
     std::string name = getXmlAttribute(cur, Attributes::name);
     if (name.empty()) {
         ALOGE("%s: No %s found", __func__, Attributes::name);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
     uint32_t versionMajor = 0, versionMinor = 0;
     std::string versionLiteral = getXmlAttribute(cur, Attributes::version);
@@ -611,29 +659,29 @@
               versionMajor, versionMajor);
     }
 
-    ALOGV("%s: %s %s=%s", __func__, tag, Attributes::name, name.c_str());
+    ALOGV("%s: %s %s=%s", __func__, ModuleTraits::tag, Attributes::name, name.c_str());
 
-    Element module = new HwModule(name.c_str(), versionMajor, versionMinor);
+    ModuleTraits::Element module = new HwModule(name.c_str(), versionMajor, versionMinor);
 
-    // Deserialize childrens: Audio Mix Port, Audio Device Ports (Source/Sink), Audio Routes
+    // Deserialize children: Audio Mix Port, Audio Device Ports (Source/Sink), Audio Routes
     MixPortTraits::Collection mixPorts;
     status_t status = deserializeCollection<MixPortTraits>(cur, &mixPorts, NULL);
     if (status != NO_ERROR) {
-        return Status::fromStatusT(status);
+        return status;
     }
     module->setProfiles(mixPorts);
 
     DevicePortTraits::Collection devicePorts;
     status = deserializeCollection<DevicePortTraits>(cur, &devicePorts, NULL);
     if (status != NO_ERROR) {
-        return Status::fromStatusT(status);
+        return status;
     }
     module->setDeclaredDevices(devicePorts);
 
     RouteTraits::Collection routes;
     status = deserializeCollection<RouteTraits>(cur, &routes, module.get());
     if (status != NO_ERROR) {
-        return Status::fromStatusT(status);
+        return status;
     }
     module->setRoutes(routes);
 
@@ -653,6 +701,12 @@
                         sp<DeviceDescriptor> device = module->getDeclaredDevices().
                                 getDeviceFromTagName(std::string(reinterpret_cast<const char*>(
                                                         attachedDevice.get())));
+                        if (device == nullptr && mIgnoreVendorExtensions) {
+                            ALOGW("Skipped attached device \"%s\" because it likely uses a vendor"
+                                    "extension type",
+                                    reinterpret_cast<const char*>(attachedDevice.get()));
+                            continue;
+                        }
                         ctx->addDevice(device);
                     }
                 }
@@ -678,10 +732,15 @@
     return module;
 }
 
-status_t GlobalConfigTraits::deserialize(const xmlNode *root, AudioPolicyConfig *config)
+template<>
+std::variant<status_t, GlobalConfigTraits::Element>
+PolicySerializer::deserialize<GlobalConfigTraits>(
+        const xmlNode *root, GlobalConfigTraits::PtrSerializingCtx config)
 {
+    using Attributes = GlobalConfigTraits::Attributes;
+
     for (const xmlNode *cur = root->xmlChildrenNode; cur != NULL; cur = cur->next) {
-        if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>(tag))) {
+        if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>(GlobalConfigTraits::tag))) {
             bool value;
             std::string attr = getXmlAttribute(cur, Attributes::speakerDrcEnabled);
             if (!attr.empty() &&
@@ -703,12 +762,15 @@
     return NO_ERROR;
 }
 
-status_t SurroundSoundTraits::deserialize(const xmlNode *root, AudioPolicyConfig *config)
+template<>
+std::variant<status_t, SurroundSoundTraits::Element>
+PolicySerializer::deserialize<SurroundSoundTraits>(
+        const xmlNode *root, SurroundSoundTraits::PtrSerializingCtx config)
 {
     config->setDefaultSurroundFormats();
 
     for (const xmlNode *cur = root->xmlChildrenNode; cur != NULL; cur = cur->next) {
-        if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>(tag))) {
+        if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>(SurroundSoundTraits::tag))) {
             AudioPolicyConfig::SurroundFormats formats;
             status_t status = deserializeCollection<SurroundSoundFormatTraits>(
                     cur, &formats, nullptr);
@@ -721,20 +783,29 @@
     return NO_ERROR;
 }
 
-Return<SurroundSoundFormatTraits::Element> SurroundSoundFormatTraits::deserialize(
-        const xmlNode *cur, PtrSerializingCtx /*serializingContext*/)
+template<>
+std::variant<status_t, SurroundSoundFormatTraits::Element>
+PolicySerializer::deserialize<SurroundSoundFormatTraits>(
+        const xmlNode *cur, SurroundSoundFormatTraits::PtrSerializingCtx /*serializingContext*/)
 {
+    using Attributes = SurroundSoundFormatTraits::Attributes;
+
     std::string formatLiteral = getXmlAttribute(cur, Attributes::name);
     if (formatLiteral.empty()) {
         ALOGE("%s: No %s found for a surround format", __func__, Attributes::name);
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
+    }
+    if (mIgnoreVendorExtensions && maybeVendorExtension(formatLiteral)) {
+        ALOGI("%s: vendor extension format \"%s\" skipped", __func__, formatLiteral.c_str());
+        return NO_INIT;
     }
     audio_format_t format = formatFromString(formatLiteral);
     if (format == AUDIO_FORMAT_DEFAULT) {
         ALOGE("%s: Unrecognized format %s", __func__, formatLiteral.c_str());
-        return Status::fromStatusT(BAD_VALUE);
+        return BAD_VALUE;
     }
-    Element pair = std::make_pair(format, Collection::mapped_type{});
+    SurroundSoundFormatTraits::Element pair = std::make_pair(
+            format, SurroundSoundFormatTraits::Collection::mapped_type{});
 
     std::string subformatsLiteral = getXmlAttribute(cur, Attributes::subformats);
     if (subformatsLiteral.empty()) return pair;
@@ -743,14 +814,16 @@
         auto result = pair.second.insert(subformat);
         if (!result.second) {
             ALOGE("%s: could not add subformat %x to collection", __func__, subformat);
-            return Status::fromStatusT(BAD_VALUE);
+            return BAD_VALUE;
         }
     }
     return pair;
 }
 
-status_t PolicySerializer::deserialize(const char *configFile, AudioPolicyConfig *config)
+status_t PolicySerializer::deserialize(const char *configFile, AudioPolicyConfig *config,
+                                       bool ignoreVendorExtensions)
 {
+    mIgnoreVendorExtensions = ignoreVendorExtensions;
     auto doc = make_xmlUnique(xmlParseFile(configFile));
     if (doc == nullptr) {
         ALOGE("%s: Could not parse %s document.", __func__, configFile);
@@ -776,12 +849,14 @@
         ALOGE("%s: No version found in root node %s", __func__, rootName);
         return BAD_VALUE;
     }
-    if (version != mVersion) {
-        ALOGE("%s: Version does not match; expect %s got %s", __func__, mVersion.c_str(),
-              version.c_str());
+    if (version == "7.0") {
+        mChannelMasksSeparator = mSamplingRatesSeparator = mFlagsSeparator = " ";
+    } else if (version != "1.0") {
+        ALOGE("%s: Version does not match; expected \"1.0\" or \"7.0\" got \"%s\"",
+                __func__, version.c_str());
         return BAD_VALUE;
     }
-    // Lets deserialize children
+    // Let's deserialize children
     // Modules
     ModuleTraits::Collection modules;
     status_t status = deserializeCollection<ModuleTraits>(root, &modules, config);
@@ -791,10 +866,10 @@
     config->setHwModules(modules);
 
     // Global Configuration
-    GlobalConfigTraits::deserialize(root, config);
+    deserialize<GlobalConfigTraits>(root, config);
 
     // Surround configuration
-    SurroundSoundTraits::deserialize(root, config);
+    deserialize<SurroundSoundTraits>(root, config);
 
     return android::OK;
 }
@@ -804,7 +879,17 @@
 status_t deserializeAudioPolicyFile(const char *fileName, AudioPolicyConfig *config)
 {
     PolicySerializer serializer;
-    return serializer.deserialize(fileName, config);
+    status_t status = serializer.deserialize(fileName, config);
+    if (status != OK) config->clear();
+    return status;
+}
+
+status_t deserializeAudioPolicyFileForVts(const char *fileName, AudioPolicyConfig *config)
+{
+    PolicySerializer serializer;
+    status_t status = serializer.deserialize(fileName, config, true /*ignoreVendorExtensions*/);
+    if (status != OK) config->clear();
+    return status;
 }
 
 } // namespace android
diff --git a/services/audiopolicy/config/Android.bp b/services/audiopolicy/config/Android.bp
index f4610bb..671b30a 100644
--- a/services/audiopolicy/config/Android.bp
+++ b/services/audiopolicy/config/Android.bp
@@ -17,6 +17,15 @@
 soong_namespace {
 }
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "a2dp_in_audio_policy_configuration.xml",
     vendor: true,
diff --git a/services/audiopolicy/config/a2dp_audio_policy_configuration_7_0.xml b/services/audiopolicy/config/a2dp_audio_policy_configuration_7_0.xml
new file mode 100644
index 0000000..2d323f6
--- /dev/null
+++ b/services/audiopolicy/config/a2dp_audio_policy_configuration_7_0.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- A2dp Audio HAL Audio Policy Configuration file -->
+<module name="a2dp" halVersion="2.0">
+    <mixPorts>
+        <mixPort name="a2dp output" role="source"/>
+        <mixPort name="a2dp input" role="sink">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100 48000"
+                     channelMasks="AUDIO_CHANNEL_IN_MONO AUDIO_CHANNEL_IN_STEREO"/>
+        </mixPort>
+    </mixPorts>
+    <devicePorts>
+        <devicePort tagName="BT A2DP Out" type="AUDIO_DEVICE_OUT_BLUETOOTH_A2DP" role="sink">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100"
+                     channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </devicePort>
+        <devicePort tagName="BT A2DP Headphones" type="AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES" role="sink">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100"
+                     channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </devicePort>
+        <devicePort tagName="BT A2DP Speaker" type="AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER" role="sink">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100"
+                     channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </devicePort>
+        <devicePort tagName="BT A2DP In" type="AUDIO_DEVICE_IN_BLUETOOTH_A2DP" role="source">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100 48000"
+                     channelMasks="AUDIO_CHANNEL_IN_MONO AUDIO_CHANNEL_IN_STEREO"/>
+        </devicePort>
+    </devicePorts>
+    <routes>
+        <route type="mix" sink="BT A2DP Out"
+               sources="a2dp output"/>
+        <route type="mix" sink="BT A2DP Headphones"
+               sources="a2dp output"/>
+        <route type="mix" sink="BT A2DP Speaker"
+               sources="a2dp output"/>
+        <route type="mix" sink="a2dp input"
+               sources="BT A2DP In"/>
+    </routes>
+</module>
diff --git a/services/audiopolicy/config/a2dp_in_audio_policy_configuration_7_0.xml b/services/audiopolicy/config/a2dp_in_audio_policy_configuration_7_0.xml
new file mode 100644
index 0000000..d59ad70
--- /dev/null
+++ b/services/audiopolicy/config/a2dp_in_audio_policy_configuration_7_0.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Bluetooth Input Audio HAL Audio Policy Configuration file -->
+<module name="a2dp" halVersion="2.0">
+    <mixPorts>
+        <mixPort name="a2dp input" role="sink">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100 48000"
+                     channelMasks="AUDIO_CHANNEL_IN_MONO AUDIO_CHANNEL_IN_STEREO"/>
+        </mixPort>
+    </mixPorts>
+    <devicePorts>
+        <devicePort tagName="BT A2DP In" type="AUDIO_DEVICE_IN_BLUETOOTH_A2DP" role="source">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100 48000"
+                     channelMasks="AUDIO_CHANNEL_IN_MONO AUDIO_CHANNEL_IN_STEREO"/>
+        </devicePort>
+    </devicePorts>
+    <routes>
+        <route type="mix" sink="a2dp input"
+               sources="BT A2DP In"/>
+    </routes>
+</module>
diff --git a/services/audiopolicy/config/audio_policy_configuration.xml b/services/audiopolicy/config/audio_policy_configuration.xml
index b28381b..dcdc035 100644
--- a/services/audiopolicy/config/audio_policy_configuration.xml
+++ b/services/audiopolicy/config/audio_policy_configuration.xml
@@ -91,7 +91,7 @@
                 <!-- Output devices declaration, i.e. Sink DEVICE PORT -->
                 <devicePort tagName="Earpiece" type="AUDIO_DEVICE_OUT_EARPIECE" role="sink">
                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
-                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_MONO"/>
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_MONO"/>
                 </devicePort>
                 <devicePort tagName="Speaker" role="sink" type="AUDIO_DEVICE_OUT_SPEAKER" address="">
                     <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
diff --git a/services/audiopolicy/config/audio_policy_configuration_7_0.xml b/services/audiopolicy/config/audio_policy_configuration_7_0.xml
new file mode 100644
index 0000000..9961a00
--- /dev/null
+++ b/services/audiopolicy/config/audio_policy_configuration_7_0.xml
@@ -0,0 +1,211 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Copyright (C) 2019 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.
+-->
+
+<audioPolicyConfiguration version="7.0" xmlns:xi="http://www.w3.org/2001/XInclude">
+    <!-- version section contains a “version” tag in the form “major.minor” e.g version=”1.0” -->
+
+    <!-- Global configuration Decalaration -->
+    <globalConfiguration speaker_drc_enabled="true"/>
+
+
+    <!-- Modules section:
+        There is one section per audio HW module present on the platform.
+        Each module section will contains two mandatory tags for audio HAL “halVersion” and “name”.
+        The module names are the same as in current .conf file:
+                “primary”, “A2DP”, “remote_submix”, “USB”
+        Each module will contain the following sections:
+        “devicePorts”: a list of device descriptors for all input and output devices accessible via this
+        module.
+        This contains both permanently attached devices and removable devices.
+        “mixPorts”: listing all output and input streams exposed by the audio HAL
+        “routes”: list of possible connections between input and output devices or between stream and
+        devices.
+            "route": is defined by an attribute:
+                -"type": <mux|mix> means all sources are mutual exclusive (mux) or can be mixed (mix)
+                -"sink": the sink involved in this route
+                -"sources": all the sources than can be connected to the sink via vis route
+        “attachedDevices”: permanently attached devices.
+        The attachedDevices section is a list of devices names. The names correspond to device names
+        defined in <devicePorts> section.
+        “defaultOutputDevice”: device to be used by default when no policy rule applies
+    -->
+    <modules>
+        <!-- Primary Audio HAL -->
+        <module name="primary" halVersion="3.0">
+            <attachedDevices>
+                <item>Speaker</item>
+                <item>Built-In Mic</item>
+                <item>Built-In Back Mic</item>
+            </attachedDevices>
+            <defaultOutputDevice>Speaker</defaultOutputDevice>
+            <mixPorts>
+                <mixPort name="primary output" role="source" flags="AUDIO_OUTPUT_FLAG_PRIMARY">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="deep_buffer" role="source"
+                        flags="AUDIO_OUTPUT_FLAG_DEEP_BUFFER">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="compressed_offload" role="source"
+                         flags="AUDIO_OUTPUT_FLAG_DIRECT AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD AUDIO_OUTPUT_FLAG_NON_BLOCKING">
+                    <profile name="" format="AUDIO_FORMAT_MP3"
+                             samplingRates="8000 11025 12000 16000 22050 24000 32000 44100 48000"
+                             channelMasks="AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_MONO"/>
+                    <profile name="" format="AUDIO_FORMAT_AAC"
+                             samplingRates="8000 11025 12000 16000 22050 24000 32000 44100 48000"
+                             channelMasks="AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_MONO"/>
+                    <profile name="" format="AUDIO_FORMAT_AAC_LC"
+                             samplingRates="8000 11025 12000 16000 22050 24000 32000 44100 48000"
+                             channelMasks="AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_MONO"/>
+                </mixPort>
+                <mixPort name="voice_tx" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 16000" channelMasks="AUDIO_CHANNEL_OUT_MONO"/>
+                </mixPort>
+                <mixPort name="primary input" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 11025 12000 16000 22050 24000 32000 44100 48000"
+                             channelMasks="AUDIO_CHANNEL_IN_MONO AUDIO_CHANNEL_IN_STEREO AUDIO_CHANNEL_IN_FRONT_BACK"/>
+                </mixPort>
+                <mixPort name="voice_rx" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 16000" channelMasks="AUDIO_CHANNEL_IN_MONO"/>
+                </mixPort>
+            </mixPorts>
+            <devicePorts>
+                <!-- Output devices declaration, i.e. Sink DEVICE PORT -->
+                <devicePort tagName="Earpiece" type="AUDIO_DEVICE_OUT_EARPIECE" role="sink">
+                   <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_MONO"/>
+                </devicePort>
+                <devicePort tagName="Speaker" role="sink" type="AUDIO_DEVICE_OUT_SPEAKER" address="">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                    <gains>
+                        <gain name="gain_1" mode="AUDIO_GAIN_MODE_JOINT"
+                              minValueMB="-8400"
+                              maxValueMB="4000"
+                              defaultValueMB="0"
+                              stepValueMB="100"/>
+                    </gains>
+                </devicePort>
+                <devicePort tagName="Wired Headset" type="AUDIO_DEVICE_OUT_WIRED_HEADSET" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </devicePort>
+                <devicePort tagName="Wired Headphones" type="AUDIO_DEVICE_OUT_WIRED_HEADPHONE" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </devicePort>
+                <devicePort tagName="BT SCO" type="AUDIO_DEVICE_OUT_BLUETOOTH_SCO" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 16000" channelMasks="AUDIO_CHANNEL_OUT_MONO"/>
+                </devicePort>
+                <devicePort tagName="BT SCO Headset" type="AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 16000" channelMasks="AUDIO_CHANNEL_OUT_MONO"/>
+                </devicePort>
+                <devicePort tagName="BT SCO Car Kit" type="AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 16000" channelMasks="AUDIO_CHANNEL_OUT_MONO"/>
+                </devicePort>
+                <devicePort tagName="Telephony Tx" type="AUDIO_DEVICE_OUT_TELEPHONY_TX" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 16000" channelMasks="AUDIO_CHANNEL_OUT_MONO"/>
+                </devicePort>
+
+                <devicePort tagName="Built-In Mic" type="AUDIO_DEVICE_IN_BUILTIN_MIC" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 11025 12000 16000 22050 24000 32000 44100 48000"
+                             channelMasks="AUDIO_CHANNEL_IN_MONO AUDIO_CHANNEL_IN_STEREO AUDIO_CHANNEL_IN_FRONT_BACK"/>
+                </devicePort>
+                <devicePort tagName="Built-In Back Mic" type="AUDIO_DEVICE_IN_BACK_MIC" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 11025 12000 16000 22050 24000 32000 44100 48000"
+                             channelMasks="AUDIO_CHANNEL_IN_MONO AUDIO_CHANNEL_IN_STEREO AUDIO_CHANNEL_IN_FRONT_BACK"/>
+                </devicePort>
+                <devicePort tagName="Wired Headset Mic" type="AUDIO_DEVICE_IN_WIRED_HEADSET" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 11025 12000 16000 22050 24000 32000 44100 48000"
+                             channelMasks="AUDIO_CHANNEL_IN_MONO AUDIO_CHANNEL_IN_STEREO AUDIO_CHANNEL_IN_FRONT_BACK"/>
+                </devicePort>
+                <devicePort tagName="BT SCO Headset Mic" type="AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 16000" channelMasks="AUDIO_CHANNEL_IN_MONO"/>
+                </devicePort>
+                <devicePort tagName="Telephony Rx" type="AUDIO_DEVICE_IN_TELEPHONY_RX" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000 16000" channelMasks="AUDIO_CHANNEL_IN_MONO"/>
+                </devicePort>
+            </devicePorts>
+            <!-- route declaration, i.e. list all available sources for a given sink -->
+            <routes>
+                <route type="mix" sink="Earpiece"
+                       sources="primary output,deep_buffer,BT SCO Headset Mic"/>
+                <route type="mix" sink="Speaker"
+                       sources="primary output,deep_buffer,compressed_offload,BT SCO Headset Mic,Telephony Rx"/>
+                <route type="mix" sink="Wired Headset"
+                       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="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, voice_tx"/>
+                <route type="mix" sink="voice_rx"
+                       sources="Telephony Rx"/>
+            </routes>
+
+        </module>
+
+        <!-- A2dp Input Audio HAL -->
+        <xi:include href="a2dp_in_audio_policy_configuration_7_0.xml"/>
+
+        <!-- Usb Audio HAL -->
+        <xi:include href="usb_audio_policy_configuration.xml"/>
+
+        <!-- Remote Submix Audio HAL -->
+        <xi:include href="r_submix_audio_policy_configuration.xml"/>
+
+        <!-- Bluetooth Audio HAL -->
+        <xi:include href="bluetooth_audio_policy_configuration_7_0.xml"/>
+
+        <!-- MSD Audio HAL (optional) -->
+        <xi:include href="msd_audio_policy_configuration_7_0.xml"/>
+
+    </modules>
+    <!-- End of Modules section -->
+
+    <!-- Volume section:
+        IMPORTANT NOTE: Volume tables have been moved to engine configuration.
+                        Keep it here for legacy.
+                        Engine will fallback on these files if none are provided by engine.
+     -->
+
+    <xi:include href="audio_policy_volumes.xml"/>
+    <xi:include href="default_volume_tables.xml"/>
+
+    <!-- End of Volume section -->
+
+    <!-- Surround Sound configuration -->
+
+    <xi:include href="surround_sound_configuration_5_0.xml"/>
+
+    <!-- End of Surround Sound configuration -->
+
+</audioPolicyConfiguration>
diff --git a/services/audiopolicy/config/audio_policy_configuration_bluetooth_legacy_hal.xml b/services/audiopolicy/config/audio_policy_configuration_bluetooth_legacy_hal.xml
index b4cc1d3..5f4e5f2 100644
--- a/services/audiopolicy/config/audio_policy_configuration_bluetooth_legacy_hal.xml
+++ b/services/audiopolicy/config/audio_policy_configuration_bluetooth_legacy_hal.xml
@@ -185,6 +185,9 @@
         <!-- Hearing aid Audio HAL -->
         <xi:include href="hearing_aid_audio_policy_configuration.xml"/>
 
+        <!-- Le Audio Audio HAL -->
+        <xi:include href="le_audio_policy_configuration.xml"/>
+
         <!-- MSD Audio HAL (optional) -->
         <xi:include href="msd_audio_policy_configuration.xml"/>
 
diff --git a/services/audiopolicy/config/bluetooth_audio_policy_configuration.xml b/services/audiopolicy/config/bluetooth_audio_policy_configuration.xml
index ce78eb0..98415b7 100644
--- a/services/audiopolicy/config/bluetooth_audio_policy_configuration.xml
+++ b/services/audiopolicy/config/bluetooth_audio_policy_configuration.xml
@@ -10,6 +10,18 @@
                      samplingRates="24000,16000"
                      channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
         </mixPort>
+        <!-- Le Audio Audio Ports -->
+        <mixPort name="le audio output" role="source">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="8000,16000,24000,32000,44100,48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO,AUDIO_CHANNEL_OUT_STEREO"/>
+            <profile name="" format="AUDIO_FORMAT_PCM_24_BIT_PACKED"
+                     samplingRates="8000,16000,24000,32000,44100,48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO,AUDIO_CHANNEL_OUT_STEREO"/>
+            <profile name="" format="AUDIO_FORMAT_PCM_32_BIT"
+                     samplingRates="8000,16000,24000,32000,44100,48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO,AUDIO_CHANNEL_OUT_STEREO"/>
+        </mixPort>
     </mixPorts>
     <devicePorts>
         <!-- A2DP Audio Ports -->
@@ -30,6 +42,13 @@
         </devicePort>
         <!-- Hearing AIDs Audio Ports -->
         <devicePort tagName="BT Hearing Aid Out" type="AUDIO_DEVICE_OUT_HEARING_AID" role="sink"/>
+        <!-- BLE Audio Ports -->
+        <!-- Note that these device types are not valid in HAL versions < 7. Any device
+             running pre-V7 HAL and using this file will not pass VTS. Need to use
+             bluetooth_audio_policy_configuration_7_0.xml instead.
+        -->
+        <devicePort tagName="BLE Headset Out" type="AUDIO_DEVICE_OUT_BLE_HEADSET" role="sink"/>
+        <devicePort tagName="BLE Speaker Out" type="AUDIO_DEVICE_OUT_BLE_SPEAKER" role="sink"/>
     </devicePorts>
     <routes>
         <route type="mix" sink="BT A2DP Out"
@@ -40,5 +59,9 @@
                sources="a2dp output"/>
         <route type="mix" sink="BT Hearing Aid Out"
                sources="hearing aid output"/>
+        <route type="mix" sink="BLE Headset Out"
+               sources="le audio output"/>
+        <route type="mix" sink="BLE Speaker Out"
+               sources="le audio output"/>
     </routes>
 </module>
diff --git a/services/audiopolicy/config/bluetooth_audio_policy_configuration_7_0.xml b/services/audiopolicy/config/bluetooth_audio_policy_configuration_7_0.xml
new file mode 100644
index 0000000..fbe7571
--- /dev/null
+++ b/services/audiopolicy/config/bluetooth_audio_policy_configuration_7_0.xml
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Bluetooth Audio HAL Audio Policy Configuration file -->
+<module name="bluetooth" halVersion="2.0">
+    <mixPorts>
+        <!-- A2DP Audio Ports -->
+        <mixPort name="a2dp output" role="source"/>
+        <!-- Hearing AIDs Audio Ports -->
+        <mixPort name="hearing aid output" role="source">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="24000 16000"
+                     channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </mixPort>
+        <!-- Le Audio Audio Ports -->
+        <mixPort name="le audio output" role="source">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="8000 16000 24000 32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO"/>
+            <profile name="" format="AUDIO_FORMAT_PCM_24_BIT_PACKED"
+                     samplingRates="8000 16000 24000 32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO"/>
+            <profile name="" format="AUDIO_FORMAT_PCM_32_BIT"
+                     samplingRates="8000 16000 24000 32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO"/>
+        </mixPort>
+    </mixPorts>
+    <devicePorts>
+        <!-- A2DP Audio Ports -->
+        <devicePort tagName="BT A2DP Out" type="AUDIO_DEVICE_OUT_BLUETOOTH_A2DP" role="sink">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100 48000 88200 96000"
+                     channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </devicePort>
+        <devicePort tagName="BT A2DP Headphones" type="AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES" role="sink">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100 48000 88200 96000"
+                     channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </devicePort>
+        <devicePort tagName="BT A2DP Speaker" type="AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER" role="sink">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100 48000 88200 96000"
+                     channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </devicePort>
+        <!-- Hearing AIDs Audio Ports -->
+        <devicePort tagName="BT Hearing Aid Out" type="AUDIO_DEVICE_OUT_HEARING_AID" role="sink"/>
+        <!-- BLE Audio Ports -->
+        <devicePort tagName="BLE Headset Out" type="AUDIO_DEVICE_OUT_BLE_HEADSET" role="sink"/>
+        <devicePort tagName="BLE Speaker Out" type="AUDIO_DEVICE_OUT_BLE_SPEAKER" role="sink"/>
+    </devicePorts>
+    <routes>
+        <route type="mix" sink="BT A2DP Out"
+               sources="a2dp output"/>
+        <route type="mix" sink="BT A2DP Headphones"
+               sources="a2dp output"/>
+        <route type="mix" sink="BT A2DP Speaker"
+               sources="a2dp output"/>
+        <route type="mix" sink="BT Hearing Aid Out"
+               sources="hearing aid output"/>
+        <route type="mix" sink="BLE Headset Out"
+               sources="le audio output"/>
+        <route type="mix" sink="BLE Speaker Out"
+               sources="le audio output"/>
+    </routes>
+</module>
diff --git a/services/audiopolicy/config/hearing_aid_audio_policy_configuration_7_0.xml b/services/audiopolicy/config/hearing_aid_audio_policy_configuration_7_0.xml
new file mode 100644
index 0000000..8c364e4
--- /dev/null
+++ b/services/audiopolicy/config/hearing_aid_audio_policy_configuration_7_0.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Hearing aid Audio HAL Audio Policy Configuration file -->
+<module name="hearing_aid" halVersion="2.0">
+    <mixPorts>
+        <mixPort name="hearing aid output" role="source">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="24000 16000"
+                     channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </mixPort>
+    </mixPorts>
+    <devicePorts>
+        <devicePort tagName="BT Hearing Aid Out" type="AUDIO_DEVICE_OUT_HEARING_AID" role="sink"/>
+    </devicePorts>
+    <routes>
+        <route type="mix" sink="BT Hearing Aid Out" sources="hearing aid output"/>
+    </routes>
+</module>
diff --git a/services/audiopolicy/config/le_audio_policy_configuration.xml b/services/audiopolicy/config/le_audio_policy_configuration.xml
new file mode 100644
index 0000000..a3dc72b
--- /dev/null
+++ b/services/audiopolicy/config/le_audio_policy_configuration.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Le Audio HAL Audio Policy Configuration file -->
+<module name="bluetooth" halVersion="2.1">
+    <mixPorts>
+        <mixPort name="le audio output" role="source">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT,AUDIO_FORMAT_PCM_24_BIT,AUDIO_FORMAT_PCM_32_BIT"
+                     samplingRates="8000,16000,24000,32000,44100,48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO,AUDIO_CHANNEL_OUT_STEREO"/>
+        </mixPort>
+    </mixPorts>
+    <devicePorts>
+        <devicePort tagName="BLE Headset Out" type="AUDIO_DEVICE_OUT_BLE_HEADSET" role="sink"/>
+        <devicePort tagName="BLE Speaker Out" type="AUDIO_DEVICE_OUT_BLE_SPEAKER" role="sink"/>
+    </devicePorts>
+    <routes>
+        <route type="mix" sink="BLE Headset Out" sources="le audio output"/>
+        <route type="mix" sink="BLE Speaker Out" sources="le audio output"/>
+    </routes>
+</module>
diff --git a/services/audiopolicy/config/msd_audio_policy_configuration_7_0.xml b/services/audiopolicy/config/msd_audio_policy_configuration_7_0.xml
new file mode 100644
index 0000000..f167f0b
--- /dev/null
+++ b/services/audiopolicy/config/msd_audio_policy_configuration_7_0.xml
@@ -0,0 +1,78 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Copyright (C) 2017-2018 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.
+-->
+<!-- Multi Stream Decoder Audio Policy Configuration file -->
+<module name="msd" halVersion="2.0">
+    <attachedDevices>
+        <item>MS12 Input</item>
+        <item>MS12 Output</item>
+    </attachedDevices>
+    <mixPorts>
+        <mixPort name="ms12 input" role="source">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </mixPort>
+        <mixPort name="ms12 compressed input" role="source"
+                flags="AUDIO_OUTPUT_FLAG_DIRECT AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD AUDIO_OUTPUT_FLAG_NON_BLOCKING">
+            <profile name="" format="AUDIO_FORMAT_AC3"
+                     samplingRates="32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_5POINT1"/>
+            <profile name="" format="AUDIO_FORMAT_E_AC3"
+                     samplingRates="32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_5POINT1 AUDIO_CHANNEL_OUT_7POINT1"/>
+            <profile name="" format="AUDIO_FORMAT_E_AC3_JOC"
+                     samplingRates="32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_5POINT1 AUDIO_CHANNEL_OUT_7POINT1"/>
+            <profile name="" format="AUDIO_FORMAT_AC4"
+                     samplingRates="32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_5POINT1 AUDIO_CHANNEL_OUT_7POINT1"/>
+        </mixPort>
+        <!-- The HW AV Sync flag is not required, but is recommended -->
+        <mixPort name="ms12 output" role="sink" flags="AUDIO_INPUT_FLAG_HW_AV_SYNC AUDIO_INPUT_FLAG_DIRECT">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+            <profile name="" format="AUDIO_FORMAT_AC3"
+                     samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_5POINT1"/>
+            <profile name="" format="AUDIO_FORMAT_E_AC3"
+                     samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_5POINT1"/>
+        </mixPort>
+   </mixPorts>
+   <devicePorts>
+       <devicePort tagName="MS12 Input" type="AUDIO_DEVICE_OUT_BUS"  role="sink">
+           <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                    samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+           <profile name="" format="AUDIO_FORMAT_AC3"
+                    samplingRates="32000 44100 48000"
+                    channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_5POINT1"/>
+           <profile name="" format="AUDIO_FORMAT_E_AC3"
+                    samplingRates="32000 44100 48000"
+                    channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_5POINT1 AUDIO_CHANNEL_OUT_7POINT1"/>
+            <profile name="" format="AUDIO_FORMAT_E_AC3_JOC"
+                     samplingRates="32000 44100 48000"
+                     channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_5POINT1 AUDIO_CHANNEL_OUT_7POINT1"/>
+           <profile name="" format="AUDIO_FORMAT_AC4"
+                    samplingRates="32000 44100 48000"
+                    channelMasks="AUDIO_CHANNEL_OUT_MONO AUDIO_CHANNEL_OUT_STEREO AUDIO_CHANNEL_OUT_5POINT1 AUDIO_CHANNEL_OUT_7POINT1"/>
+       </devicePort>
+       <devicePort tagName="MS12 Output" type="AUDIO_DEVICE_IN_BUS"  role="source">
+           <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                    samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+        </devicePort>
+    </devicePorts>
+    <routes>
+        <route type="mix" sink="MS12 Input" sources="ms12 input,ms12 compressed input"/>
+        <route type="mix" sink="ms12 output" sources="MS12 Output"/>
+    </routes>
+</module>
diff --git a/services/audiopolicy/config/primary_audio_policy_configuration_7_0.xml b/services/audiopolicy/config/primary_audio_policy_configuration_7_0.xml
new file mode 100644
index 0000000..68a56b2
--- /dev/null
+++ b/services/audiopolicy/config/primary_audio_policy_configuration_7_0.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Default Primary Audio HAL Module Audio Policy Configuration include file -->
+<module name="primary" halVersion="2.0">
+    <attachedDevices>
+        <item>Speaker</item>
+        <item>Built-In Mic</item>
+    </attachedDevices>
+    <defaultOutputDevice>Speaker</defaultOutputDevice>
+    <mixPorts>
+        <mixPort name="primary output" role="source" flags="AUDIO_OUTPUT_FLAG_PRIMARY">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="44100" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+        </mixPort>
+        <mixPort name="primary input" role="sink">
+            <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                     samplingRates="8000 16000" channelMasks="AUDIO_CHANNEL_IN_MONO"/>
+        </mixPort>
+   </mixPorts>
+   <devicePorts>
+        <devicePort tagName="Speaker" type="AUDIO_DEVICE_OUT_SPEAKER" role="sink">
+        </devicePort>
+
+        <devicePort tagName="Built-In Mic" type="AUDIO_DEVICE_IN_BUILTIN_MIC" role="source">
+        </devicePort>
+    </devicePorts>
+    <routes>
+        <route type="mix" sink="Speaker"
+               sources="primary output"/>
+        <route type="mix" sink="primary input"
+               sources="Built-In Mic"/>
+    </routes>
+</module>
diff --git a/services/audiopolicy/engine/common/Android.bp b/services/audiopolicy/engine/common/Android.bp
old mode 100755
new mode 100644
index a1c69f2..50c5eab
--- a/services/audiopolicy/engine/common/Android.bp
+++ b/services/audiopolicy/engine/common/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libaudiopolicyengine_common_headers",
     host_supported: true,
diff --git a/services/audiopolicy/engine/common/include/EngineBase.h b/services/audiopolicy/engine/common/include/EngineBase.h
old mode 100755
new mode 100644
index 7f339dc..4510f63
--- a/services/audiopolicy/engine/common/include/EngineBase.h
+++ b/services/audiopolicy/engine/common/include/EngineBase.h
@@ -93,13 +93,13 @@
 
     void dump(String8 *dst) const override;
 
-    status_t setPreferredDeviceForStrategy(product_strategy_t strategy,
-            const AudioDeviceTypeAddr &device) override;
+    status_t setDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role,
+            const AudioDeviceTypeAddrVector &devices) override;
 
-    status_t removePreferredDeviceForStrategy(product_strategy_t strategy) override;
+    status_t removeDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role) override;
 
-    status_t getPreferredDeviceForStrategy(product_strategy_t strategy,
-            AudioDeviceTypeAddr &device) const override;
+    status_t getDevicesForRoleAndStrategy(product_strategy_t strategy, device_role_t role,
+            AudioDeviceTypeAddrVector &devices) const override;
 
     engineConfig::ParsingResult loadAudioPolicyEngineConfig();
 
@@ -127,11 +127,36 @@
 
     status_t restoreOriginVolumeCurve(audio_stream_type_t stream);
 
+    status_t setDevicesRoleForCapturePreset(audio_source_t audioSource, device_role_t role,
+            const AudioDeviceTypeAddrVector &devices) override;
+
+    status_t addDevicesRoleForCapturePreset(audio_source_t audioSource, device_role_t role,
+            const AudioDeviceTypeAddrVector &devices) override;
+
+    /**
+     * Remove devices role for capture preset. When `forceMatched` is true, the devices to be
+     * removed must all show as role for the capture preset. Otherwise, only devices that has shown
+     * as role for the capture preset will be remove.
+     */
+    status_t doRemoveDevicesRoleForCapturePreset(audio_source_t audioSource,
+            device_role_t role, const AudioDeviceTypeAddrVector& devices,
+            bool forceMatched=true);
+
+    status_t removeDevicesRoleForCapturePreset(audio_source_t audioSource,
+            device_role_t role, const AudioDeviceTypeAddrVector& devices) override;
+
+    status_t clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+            device_role_t role) override;
+
+    status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+            device_role_t role, AudioDeviceTypeAddrVector &devices) const override;
+
 private:
     AudioPolicyManagerObserver *mApmObserver = nullptr;
 
     ProductStrategyMap mProductStrategies;
     ProductStrategyPreferredRoutingMap mProductStrategyPreferredDevices;
+    CapturePresetDevicesRoleMap mCapturePresetDevicesRole;
     VolumeGroupMap mVolumeGroups;
     LastRemovableMediaDevices mLastRemovableMediaDevices;
     audio_mode_t mPhoneState = AUDIO_MODE_NORMAL;  /**< current phone state. */
diff --git a/services/audiopolicy/engine/common/include/LastRemovableMediaDevices.h b/services/audiopolicy/engine/common/include/LastRemovableMediaDevices.h
old mode 100755
new mode 100644
diff --git a/services/audiopolicy/engine/common/include/ProductStrategy.h b/services/audiopolicy/engine/common/include/ProductStrategy.h
index 3ebe7d1..c505456 100644
--- a/services/audiopolicy/engine/common/include/ProductStrategy.h
+++ b/services/audiopolicy/engine/common/include/ProductStrategy.h
@@ -28,8 +28,11 @@
 #include <utils/String8.h>
 #include <media/AudioAttributes.h>
 #include <media/AudioContainers.h>
+#include <media/AudioDeviceTypeAddr.h>
 #include <media/AudioPolicy.h>
 
+#include <vector>
+
 namespace android {
 
 /**
@@ -164,7 +167,8 @@
     product_strategy_t mDefaultStrategy = PRODUCT_STRATEGY_NONE;
 };
 
-class ProductStrategyPreferredRoutingMap : public std::map<product_strategy_t, AudioDeviceTypeAddr>
+class ProductStrategyPreferredRoutingMap : public std::map<product_strategy_t,
+                                                           AudioDeviceTypeAddrVector>
 {
 public:
     void dump(String8 *dst, int spaces = 0) const;
diff --git a/services/audiopolicy/engine/common/src/EngineBase.cpp b/services/audiopolicy/engine/common/src/EngineBase.cpp
index 1bc7fe3..8c7fb97 100644
--- a/services/audiopolicy/engine/common/src/EngineBase.cpp
+++ b/services/audiopolicy/engine/common/src/EngineBase.cpp
@@ -339,8 +339,8 @@
     return NO_ERROR;
 }
 
-status_t EngineBase::setPreferredDeviceForStrategy(product_strategy_t strategy,
-            const AudioDeviceTypeAddr &device)
+status_t EngineBase::setDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role,
+            const AudioDeviceTypeAddrVector &devices)
 {
     // verify strategy exists
     if (mProductStrategies.find(strategy) == mProductStrategies.end()) {
@@ -348,11 +348,24 @@
         return BAD_VALUE;
     }
 
-    mProductStrategyPreferredDevices[strategy] = device;
+    switch (role) {
+    case DEVICE_ROLE_PREFERRED:
+        mProductStrategyPreferredDevices[strategy] = devices;
+        break;
+    case DEVICE_ROLE_DISABLED:
+        // TODO: support set devices role as disabled for strategy.
+        ALOGI("%s no implemented for role as %d", __func__, role);
+        break;
+    case DEVICE_ROLE_NONE:
+        // Intentionally fall-through as it is no need to set device role as none for a strategy.
+    default:
+        ALOGE("%s invalid role %d", __func__, role);
+        return BAD_VALUE;
+    }
     return NO_ERROR;
 }
 
-status_t EngineBase::removePreferredDeviceForStrategy(product_strategy_t strategy)
+status_t EngineBase::removeDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role)
 {
     // verify strategy exists
     if (mProductStrategies.find(strategy) == mProductStrategies.end()) {
@@ -360,29 +373,218 @@
         return BAD_VALUE;
     }
 
-    if (mProductStrategyPreferredDevices.erase(strategy) == 0) {
-        // no preferred device was set
-        return NAME_NOT_FOUND;
+    switch (role) {
+    case DEVICE_ROLE_PREFERRED:
+        if (mProductStrategyPreferredDevices.erase(strategy) == 0) {
+            // no preferred device was set
+            return NAME_NOT_FOUND;
+        }
+        break;
+    case DEVICE_ROLE_DISABLED:
+        // TODO: support remove devices role as disabled for strategy.
+        ALOGI("%s no implemented for role as %d", __func__, role);
+        break;
+    case DEVICE_ROLE_NONE:
+        // Intentionally fall-through as it makes no sense to remove devices with
+        // role as DEVICE_ROLE_NONE for a strategy
+    default:
+        ALOGE("%s invalid role %d", __func__, role);
+        return BAD_VALUE;
     }
     return NO_ERROR;
 }
 
-status_t EngineBase::getPreferredDeviceForStrategy(product_strategy_t strategy,
-            AudioDeviceTypeAddr &device) const
+status_t EngineBase::getDevicesForRoleAndStrategy(product_strategy_t strategy, device_role_t role,
+            AudioDeviceTypeAddrVector &devices) const
 {
     // verify strategy exists
     if (mProductStrategies.find(strategy) == mProductStrategies.end()) {
         ALOGE("%s unknown strategy %u", __func__, strategy);
         return BAD_VALUE;
     }
-    // preferred device for this strategy?
-    auto devIt = mProductStrategyPreferredDevices.find(strategy);
-    if (devIt == mProductStrategyPreferredDevices.end()) {
-        ALOGV("%s no preferred device for strategy %u", __func__, strategy);
-        return NAME_NOT_FOUND;
+
+    switch (role) {
+    case DEVICE_ROLE_PREFERRED: {
+        // preferred device for this strategy?
+        auto devIt = mProductStrategyPreferredDevices.find(strategy);
+        if (devIt == mProductStrategyPreferredDevices.end()) {
+            ALOGV("%s no preferred device for strategy %u", __func__, strategy);
+            return NAME_NOT_FOUND;
+        }
+
+        devices = devIt->second;
+    } break;
+    case DEVICE_ROLE_NONE:
+        // Intentionally fall-through as the DEVICE_ROLE_NONE is never set
+    default:
+        ALOGE("%s invalid role %d", __func__, role);
+        return BAD_VALUE;
+    }
+    return NO_ERROR;
+}
+
+status_t EngineBase::setDevicesRoleForCapturePreset(audio_source_t audioSource, device_role_t role,
+        const AudioDeviceTypeAddrVector &devices)
+{
+    // verify if the audio source is valid
+    if (!audio_is_valid_audio_source(audioSource)) {
+        ALOGE("%s unknown audio source %u", __func__, audioSource);
     }
 
-    device = devIt->second;
+    switch (role) {
+    case DEVICE_ROLE_PREFERRED:
+        mCapturePresetDevicesRole[audioSource][role] = devices;
+        // When the devices are set as preferred devices, remove them from the disabled devices.
+        doRemoveDevicesRoleForCapturePreset(
+                audioSource, DEVICE_ROLE_DISABLED, devices, false /*forceMatched*/);
+        break;
+    case DEVICE_ROLE_DISABLED:
+        // TODO: support setting devices role as disabled for capture preset.
+        ALOGI("%s no implemented for role as %d", __func__, role);
+        break;
+    case DEVICE_ROLE_NONE:
+        // Intentionally fall-through as it is no need to set device role as none
+    default:
+        ALOGE("%s invalid role %d", __func__, role);
+        return BAD_VALUE;
+    }
+    return NO_ERROR;
+}
+
+status_t EngineBase::addDevicesRoleForCapturePreset(audio_source_t audioSource, device_role_t role,
+        const AudioDeviceTypeAddrVector &devices)
+{
+    // verify if the audio source is valid
+    if (!audio_is_valid_audio_source(audioSource)) {
+        ALOGE("%s unknown audio source %u", __func__, audioSource);
+    }
+
+    switch (role) {
+    case DEVICE_ROLE_PREFERRED:
+        mCapturePresetDevicesRole[audioSource][role] = excludeDeviceTypeAddrsFrom(
+                mCapturePresetDevicesRole[audioSource][role], devices);
+        for (const auto& device : devices) {
+            mCapturePresetDevicesRole[audioSource][role].push_back(device);
+        }
+        // When the devices are set as preferred devices, remove them from the disabled devices.
+        doRemoveDevicesRoleForCapturePreset(
+                audioSource, DEVICE_ROLE_DISABLED, devices, false /*forceMatched*/);
+        break;
+    case DEVICE_ROLE_DISABLED:
+        // TODO: support setting devices role as disabled for capture preset.
+        ALOGI("%s no implemented for role as %d", __func__, role);
+        break;
+    case DEVICE_ROLE_NONE:
+        // Intentionally fall-through as it is no need to set device role as none
+    default:
+        ALOGE("%s invalid role %d", __func__, role);
+        return BAD_VALUE;
+    }
+    return NO_ERROR;
+}
+
+status_t EngineBase::removeDevicesRoleForCapturePreset(
+        audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices) {
+    return doRemoveDevicesRoleForCapturePreset(audioSource, role, devices);
+}
+
+status_t EngineBase::doRemoveDevicesRoleForCapturePreset(audio_source_t audioSource,
+        device_role_t role, const AudioDeviceTypeAddrVector& devices, bool forceMatched)
+{
+    // verify if the audio source is valid
+    if (!audio_is_valid_audio_source(audioSource)) {
+        ALOGE("%s unknown audio source %u", __func__, audioSource);
+    }
+
+    switch (role) {
+    case DEVICE_ROLE_PREFERRED:
+    case DEVICE_ROLE_DISABLED: {
+        if (mCapturePresetDevicesRole.count(audioSource) == 0 ||
+                mCapturePresetDevicesRole[audioSource].count(role) == 0) {
+            return NAME_NOT_FOUND;
+        }
+        AudioDeviceTypeAddrVector remainingDevices = excludeDeviceTypeAddrsFrom(
+                mCapturePresetDevicesRole[audioSource][role], devices);
+        if (forceMatched && remainingDevices.size() !=
+                mCapturePresetDevicesRole[audioSource][role].size() - devices.size()) {
+            // There are some devices from `devicesToRemove` that are not shown in the cached record
+            return BAD_VALUE;
+        }
+        mCapturePresetDevicesRole[audioSource][role] = remainingDevices;
+        if (mCapturePresetDevicesRole[audioSource][role].empty()) {
+            // Remove the role when device list is empty
+            mCapturePresetDevicesRole[audioSource].erase(role);
+        }
+    } break;
+    case DEVICE_ROLE_NONE:
+        // Intentionally fall-through as it makes no sense to remove devices with
+        // role as DEVICE_ROLE_NONE
+    default:
+        ALOGE("%s invalid role %d", __func__, role);
+        return BAD_VALUE;
+    }
+    return NO_ERROR;
+}
+
+status_t EngineBase::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                      device_role_t role)
+{
+    // verify if the audio source is valid
+    if (!audio_is_valid_audio_source(audioSource)) {
+        ALOGE("%s unknown audio source %u", __func__, audioSource);
+    }
+
+    switch (role) {
+    case DEVICE_ROLE_PREFERRED:
+        if (mCapturePresetDevicesRole.count(audioSource) == 0 ||
+                mCapturePresetDevicesRole[audioSource].erase(role) == 0) {
+            // no preferred device for the given audio source
+            return NAME_NOT_FOUND;
+        }
+        break;
+    case DEVICE_ROLE_DISABLED:
+        // TODO: support remove devices role as disabled for strategy.
+        ALOGI("%s no implemented for role as %d", __func__, role);
+        break;
+    case DEVICE_ROLE_NONE:
+        // Intentionally fall-through as it makes no sense to remove devices with
+        // role as DEVICE_ROLE_NONE for a strategy
+    default:
+        ALOGE("%s invalid role %d", __func__, role);
+        return BAD_VALUE;
+    }
+    return NO_ERROR;
+}
+
+status_t EngineBase::getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+        device_role_t role, AudioDeviceTypeAddrVector &devices) const
+{
+    // verify if the audio source is valid
+    if (!audio_is_valid_audio_source(audioSource)) {
+        ALOGE("%s unknown audio source %u", __func__, audioSource);
+        return BAD_VALUE;
+    }
+
+    switch (role) {
+    case DEVICE_ROLE_PREFERRED:
+    case DEVICE_ROLE_DISABLED: {
+        if (mCapturePresetDevicesRole.count(audioSource) == 0) {
+            return NAME_NOT_FOUND;
+        }
+        auto devIt = mCapturePresetDevicesRole.at(audioSource).find(role);
+        if (devIt == mCapturePresetDevicesRole.at(audioSource).end()) {
+            ALOGV("%s no devices role(%d) for capture preset %u", __func__, role, audioSource);
+            return NAME_NOT_FOUND;
+        }
+
+        devices = devIt->second;
+    } break;
+    case DEVICE_ROLE_NONE:
+        // Intentionally fall-through as the DEVICE_ROLE_NONE is never set
+    default:
+        ALOGE("%s invalid role %d", __func__, role);
+        return BAD_VALUE;
+    }
     return NO_ERROR;
 }
 
diff --git a/services/audiopolicy/engine/common/src/EngineDefaultConfig.h b/services/audiopolicy/engine/common/src/EngineDefaultConfig.h
index 1821140..d39eff6 100644
--- a/services/audiopolicy/engine/common/src/EngineDefaultConfig.h
+++ b/services/audiopolicy/engine/common/src/EngineDefaultConfig.h
@@ -26,8 +26,8 @@
     {"STRATEGY_PHONE",
      {
          {"phone", AUDIO_STREAM_VOICE_CALL, "AUDIO_STREAM_VOICE_CALL",
-          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_SOURCE_DEFAULT, 0,
-            ""}},
+          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_SOURCE_DEFAULT,
+            AUDIO_FLAG_NONE, ""}},
          },
          {"sco", AUDIO_STREAM_BLUETOOTH_SCO, "AUDIO_STREAM_BLUETOOTH_SCO",
           {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_SCO,
@@ -39,10 +39,11 @@
      {
          {"ring", AUDIO_STREAM_RING, "AUDIO_STREAM_RING",
           {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE,
-            AUDIO_SOURCE_DEFAULT, 0, ""}}
+            AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}}
          },
          {"alarm", AUDIO_STREAM_ALARM, "AUDIO_STREAM_ALARM",
-          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ALARM, AUDIO_SOURCE_DEFAULT, 0, ""}},
+          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ALARM, AUDIO_SOURCE_DEFAULT,
+            AUDIO_FLAG_NONE, ""}},
          }
      },
     },
@@ -58,7 +59,7 @@
      {
          {"", AUDIO_STREAM_ACCESSIBILITY, "AUDIO_STREAM_ACCESSIBILITY",
           {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY,
-            AUDIO_SOURCE_DEFAULT, 0, ""}}
+            AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}}
          }
      },
     },
@@ -66,15 +67,16 @@
      {
          {"", AUDIO_STREAM_NOTIFICATION, "AUDIO_STREAM_NOTIFICATION",
           {
-              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION, AUDIO_SOURCE_DEFAULT, 0, ""},
+              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION, AUDIO_SOURCE_DEFAULT,
+               AUDIO_FLAG_NONE, ""},
               {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST,
-               AUDIO_SOURCE_DEFAULT, 0, ""},
+               AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
               {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT,
-               AUDIO_SOURCE_DEFAULT, 0, ""},
+               AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
               {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED,
-               AUDIO_SOURCE_DEFAULT, 0, ""},
+               AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
               {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION_EVENT,
-               AUDIO_SOURCE_DEFAULT, 0, ""}
+               AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}
           }
          }
      },
@@ -83,21 +85,25 @@
      {
          {"assistant", AUDIO_STREAM_ASSISTANT, "AUDIO_STREAM_ASSISTANT",
           {{AUDIO_CONTENT_TYPE_SPEECH, AUDIO_USAGE_ASSISTANT,
-            AUDIO_SOURCE_DEFAULT, 0, ""}}
+            AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}}
          },
          {"music", AUDIO_STREAM_MUSIC, "AUDIO_STREAM_MUSIC",
           {
-              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA, AUDIO_SOURCE_DEFAULT, 0, ""},
-              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_GAME, AUDIO_SOURCE_DEFAULT, 0, ""},
-              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ASSISTANT, AUDIO_SOURCE_DEFAULT, 0, ""},
+              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_MEDIA, AUDIO_SOURCE_DEFAULT,
+               AUDIO_FLAG_NONE, ""},
+              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_GAME, AUDIO_SOURCE_DEFAULT,
+               AUDIO_FLAG_NONE, ""},
+              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ASSISTANT, AUDIO_SOURCE_DEFAULT,
+               AUDIO_FLAG_NONE, ""},
               {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
-               AUDIO_SOURCE_DEFAULT, 0, ""},
-              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_DEFAULT, 0, ""}
+               AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
+              {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_DEFAULT,
+               AUDIO_FLAG_NONE, ""}
           },
          },
          {"system", AUDIO_STREAM_SYSTEM, "AUDIO_STREAM_SYSTEM",
           {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_ASSISTANCE_SONIFICATION,
-            AUDIO_SOURCE_DEFAULT, 0, ""}}
+            AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}}
          }
      },
     },
@@ -106,7 +112,7 @@
          {"", AUDIO_STREAM_DTMF, "AUDIO_STREAM_DTMF",
           {
               {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING,
-               AUDIO_SOURCE_DEFAULT, 0, ""}
+               AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}
           }
          }
      },
@@ -114,7 +120,8 @@
     {"STRATEGY_CALL_ASSISTANT",
      {
          {"", AUDIO_STREAM_CALL_ASSISTANT, "AUDIO_STREAM_CALL_ASSISTANT",
-          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_CALL_ASSISTANT, AUDIO_SOURCE_DEFAULT, 0, ""}}
+          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_CALL_ASSISTANT, AUDIO_SOURCE_DEFAULT,
+            AUDIO_FLAG_NONE, ""}}
          }
      },
     },
@@ -136,14 +143,16 @@
     {"rerouting",
      {
          {"", AUDIO_STREAM_REROUTING, "AUDIO_STREAM_REROUTING",
-          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_VIRTUAL_SOURCE, AUDIO_SOURCE_DEFAULT, 0, ""}}
+          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_VIRTUAL_SOURCE, AUDIO_SOURCE_DEFAULT,
+            AUDIO_FLAG_NONE, ""}}
          }
      },
     },
     {"patch",
      {
          {"", AUDIO_STREAM_PATCH, "AUDIO_STREAM_PATCH",
-          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_DEFAULT, 0, ""}}
+          {{AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, AUDIO_SOURCE_DEFAULT,
+            AUDIO_FLAG_NONE, ""}}
          }
      },
     }
diff --git a/services/audiopolicy/engine/common/src/LastRemovableMediaDevices.cpp b/services/audiopolicy/engine/common/src/LastRemovableMediaDevices.cpp
old mode 100755
new mode 100644
index 87b6aaf..96cc140
--- a/services/audiopolicy/engine/common/src/LastRemovableMediaDevices.cpp
+++ b/services/audiopolicy/engine/common/src/LastRemovableMediaDevices.cpp
@@ -69,6 +69,11 @@
     case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
     case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
     case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
+    // TODO (b/122931261): remove when preferred device for strategy media will be used instead of
+    //  AUDIO_POLICY_FORCE_NO_BT_A2DP.
+    case AUDIO_DEVICE_OUT_HEARING_AID:
+    case AUDIO_DEVICE_OUT_BLE_HEADSET:
+    case AUDIO_DEVICE_OUT_BLE_SPEAKER:
         return GROUP_BT_A2DP;
     default:
         return GROUP_NONE;
diff --git a/services/audiopolicy/engine/common/src/ProductStrategy.cpp b/services/audiopolicy/engine/common/src/ProductStrategy.cpp
index 151c7bb..060568a 100644
--- a/services/audiopolicy/engine/common/src/ProductStrategy.cpp
+++ b/services/audiopolicy/engine/common/src/ProductStrategy.cpp
@@ -321,10 +321,11 @@
 void ProductStrategyPreferredRoutingMap::dump(android::String8* dst, int spaces) const {
     dst->appendFormat("\n%*sPreferred devices per product strategy dump:", spaces, "");
     for (const auto& iter : *this) {
-        dst->appendFormat("\n%*sStrategy %u dev:%08x addr:%s",
+        dst->appendFormat("\n%*sStrategy %u %s",
                           spaces + 2, "",
                           (uint32_t) iter.first,
-                          iter.second.mType, iter.second.mAddress.c_str());
+                          dumpAudioDeviceTypeAddrVector(iter.second, true /*includeSensitiveInfo*/)
+                                  .c_str());
     }
     dst->appendFormat("\n");
 }
diff --git a/services/audiopolicy/engine/config/Android.bp b/services/audiopolicy/engine/config/Android.bp
index ff840f9..459cc78 100644
--- a/services/audiopolicy/engine/config/Android.bp
+++ b/services/audiopolicy/engine/config/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libaudiopolicyengine_config",
     export_include_dirs: ["include"],
diff --git a/services/audiopolicy/engine/config/TEST_MAPPING b/services/audiopolicy/engine/config/TEST_MAPPING
new file mode 100644
index 0000000..06ce111
--- /dev/null
+++ b/services/audiopolicy/engine/config/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+       "name": "audiopolicy_engineconfig_tests"
+    }
+  ]
+}
diff --git a/services/audiopolicy/engine/config/include/EngineConfig.h b/services/audiopolicy/engine/config/include/EngineConfig.h
index 5d22c24..c565926 100644
--- a/services/audiopolicy/engine/config/include/EngineConfig.h
+++ b/services/audiopolicy/engine/config/include/EngineConfig.h
@@ -111,6 +111,8 @@
  */
 ParsingResult parse(const char* path = DEFAULT_PATH);
 android::status_t parseLegacyVolumes(VolumeGroups &volumeGroups);
+// Exposed for testing.
+android::status_t parseLegacyVolumeFile(const char* path, VolumeGroups &volumeGroups);
 
 } // namespace engineConfig
 } // namespace android
diff --git a/services/audiopolicy/engine/config/src/EngineConfig.cpp b/services/audiopolicy/engine/config/src/EngineConfig.cpp
index 4842cb2..7cfef5b 100644
--- a/services/audiopolicy/engine/config/src/EngineConfig.cpp
+++ b/services/audiopolicy/engine/config/src/EngineConfig.cpp
@@ -228,7 +228,8 @@
             std::string flags = getXmlAttribute(cur, "value");
 
             ALOGV("%s flags %s",  __FUNCTION__, flags.c_str());
-            attributes.flags = AudioFlagConverter::maskFromString(flags, " ");
+            attributes.flags = static_cast<audio_flags_mask_t>(
+                    AudioFlagConverter::maskFromString(flags, " "));
         }
         if (!xmlStrcmp(cur->name, (const xmlChar *)("Bundle"))) {
             std::string bundleKey = getXmlAttribute(cur, "key");
@@ -588,6 +589,7 @@
             }
         }
     }
+    VolumeGroups tempVolumeGroups = volumeGroups;
     for (const auto &volumeMapIter : legacyVolumeMap) {
         // In order to let AudioService setting the min and max (compatibility), set Min and Max
         // to -1 except for private streams
@@ -598,8 +600,10 @@
         }
         int indexMin = streamType >= AUDIO_STREAM_PUBLIC_CNT ? 0 : -1;
         int indexMax = streamType >= AUDIO_STREAM_PUBLIC_CNT ? 100 : -1;
-        volumeGroups.push_back({ volumeMapIter.first, indexMin, indexMax, volumeMapIter.second });
+        tempVolumeGroups.push_back(
+                { volumeMapIter.first, indexMin, indexMax, volumeMapIter.second });
     }
+    std::swap(tempVolumeGroups, volumeGroups);
     return NO_ERROR;
 }
 
@@ -694,35 +698,14 @@
     return deserializeLegacyVolumeCollection(doc, cur, volumeGroups, nbSkippedElements);
 }
 
-static const int gApmXmlConfigFilePathMaxLength = 128;
-
-static constexpr const char *apmXmlConfigFileName = "audio_policy_configuration.xml";
-static constexpr const char *apmA2dpOffloadDisabledXmlConfigFileName =
-        "audio_policy_configuration_a2dp_offload_disabled.xml";
-
 android::status_t parseLegacyVolumes(VolumeGroups &volumeGroups) {
-    char audioPolicyXmlConfigFile[gApmXmlConfigFilePathMaxLength];
-    std::vector<const char *> fileNames;
-    status_t ret;
-
-    if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
-            property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
-        // A2DP offload supported but disabled: try to use special XML file
-        fileNames.push_back(apmA2dpOffloadDisabledXmlConfigFileName);
+    if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
+            !audioPolicyXmlConfigFile.empty()) {
+        return parseLegacyVolumeFile(audioPolicyXmlConfigFile.c_str(), volumeGroups);
+    } else {
+        ALOGE("No readable audio policy config file found");
+        return BAD_VALUE;
     }
-    fileNames.push_back(apmXmlConfigFileName);
-
-    for (const char* fileName : fileNames) {
-        for (const auto& path : audio_get_configuration_paths()) {
-            snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
-                     "%s/%s", path.c_str(), fileName);
-            ret = parseLegacyVolumeFile(audioPolicyXmlConfigFile, volumeGroups);
-            if (ret == NO_ERROR) {
-                return ret;
-            }
-        }
-    }
-    return BAD_VALUE;
 }
 
 } // namespace engineConfig
diff --git a/services/audiopolicy/engine/config/tests/Android.bp b/services/audiopolicy/engine/config/tests/Android.bp
new file mode 100644
index 0000000..5791f17
--- /dev/null
+++ b/services/audiopolicy/engine/config/tests/Android.bp
@@ -0,0 +1,34 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_test {
+    name: "audiopolicy_engineconfig_tests",
+
+    shared_libs: [
+        "libbase",
+        "liblog",
+        "libmedia_helper",
+        "libutils",
+        "libxml2",
+    ],
+    static_libs: [
+        "libaudiopolicyengine_config",
+    ],
+
+    srcs: ["engineconfig_tests.cpp"],
+
+    data: [":audiopolicy_engineconfig_files"],
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+
+    test_suites: ["device-tests"],
+}
diff --git a/services/audiopolicy/engine/config/tests/engineconfig_tests.cpp b/services/audiopolicy/engine/config/tests/engineconfig_tests.cpp
new file mode 100644
index 0000000..f61e02f
--- /dev/null
+++ b/services/audiopolicy/engine/config/tests/engineconfig_tests.cpp
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2020 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>
+
+#define LOG_TAG "APM_Test"
+#include <android-base/file.h>
+#include <log/log.h>
+
+#include "EngineConfig.h"
+
+using namespace android;
+
+TEST(EngineConfigTestInit, LegacyVolumeGroupsLoadingIsTransactional) {
+    engineConfig::VolumeGroups groups;
+    ASSERT_TRUE(groups.empty());
+    status_t status = engineConfig::parseLegacyVolumeFile(
+            (base::GetExecutableDirectory() + "/test_invalid_apm_volume_tables.xml").c_str(),
+            groups);
+    ASSERT_NE(NO_ERROR, status);
+    EXPECT_TRUE(groups.empty());
+    status = engineConfig::parseLegacyVolumeFile(
+            (base::GetExecutableDirectory() + "/test_apm_volume_tables.xml").c_str(),
+            groups);
+    ASSERT_EQ(NO_ERROR, status);
+    EXPECT_FALSE(groups.empty());
+}
diff --git a/services/audiopolicy/engine/config/tests/resources/Android.bp b/services/audiopolicy/engine/config/tests/resources/Android.bp
new file mode 100644
index 0000000..9cee978
--- /dev/null
+++ b/services/audiopolicy/engine/config/tests/resources/Android.bp
@@ -0,0 +1,16 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+filegroup {
+    name: "audiopolicy_engineconfig_files",
+    srcs: [
+        "test_apm_volume_tables.xml",
+        "test_invalid_apm_volume_tables.xml",
+    ],
+}
diff --git a/services/audiopolicy/engine/config/tests/resources/test_apm_volume_tables.xml b/services/audiopolicy/engine/config/tests/resources/test_apm_volume_tables.xml
new file mode 100644
index 0000000..16126b6
--- /dev/null
+++ b/services/audiopolicy/engine/config/tests/resources/test_apm_volume_tables.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<audioPolicyConfiguration version="1.0" xmlns:xi="http://www.w3.org/2001/XInclude">
+    <globalConfiguration speaker_drc_enabled="true"/>
+    <volumes>
+        <volume stream="AUDIO_STREAM_VOICE_CALL" deviceCategory="DEVICE_CATEGORY_HEADSET">
+            <point>0,-4200</point>
+            <point>33,-2800</point>
+            <point>66,-1400</point>
+            <point>100,0</point>
+        </volume>
+        <volume stream="AUDIO_STREAM_VOICE_CALL" deviceCategory="DEVICE_CATEGORY_SPEAKER">
+            <point>0,-2400</point>
+            <point>33,-1600</point>
+            <point>66,-800</point>
+            <point>100,0</point>
+        </volume>
+        <volume stream="AUDIO_STREAM_VOICE_CALL" deviceCategory="DEVICE_CATEGORY_HEARING_AID"
+                ref="FULL_SCALE_VOLUME_CURVE"/>
+    </volumes>
+    <volumes>
+        <reference name="FULL_SCALE_VOLUME_CURVE">
+            <!-- Full Scale reference Volume Curve -->
+            <point>0,0</point>
+            <point>100,0</point>
+        </reference>
+    </volumes>
+</audioPolicyConfiguration>
diff --git a/services/audiopolicy/engine/config/tests/resources/test_invalid_apm_volume_tables.xml b/services/audiopolicy/engine/config/tests/resources/test_invalid_apm_volume_tables.xml
new file mode 100644
index 0000000..3ec5d10
--- /dev/null
+++ b/services/audiopolicy/engine/config/tests/resources/test_invalid_apm_volume_tables.xml
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<!-- This file uses a non-existent audio stream name. -->
+<audioPolicyConfiguration version="1.0" xmlns:xi="http://www.w3.org/2001/XInclude">
+    <globalConfiguration speaker_drc_enabled="true"/>
+    <volumes>
+        <volume stream="AUDIO_STREAM_VOICE_CALL" deviceCategory="DEVICE_CATEGORY_HEADSET">
+            <point>0,-4200</point>
+            <point>33,-2800</point>
+            <point>66,-1400</point>
+            <point>100,0</point>
+        </volume>
+        <volume stream="AUDIO_STREAM_NON_EXISTING" deviceCategory="DEVICE_CATEGORY_SPEAKER">
+            <point>0,-2400</point>
+            <point>33,-1600</point>
+            <point>66,-800</point>
+            <point>100,0</point>
+        </volume>
+        <volume stream="AUDIO_STREAM_RING" deviceCategory="DEVICE_CATEGORY_HEADSET"
+                ref="FULL_SCALE_VOLUME_CURVE"/>
+        <volume stream="AUDIO_STREAM_MUSIC" deviceCategory="DEVICE_CATEGORY_HEADSET"
+                ref="FULL_SCALE_VOLUME_CURVE"/>
+        <volume stream="AUDIO_STREAM_ALARM" deviceCategory="DEVICE_CATEGORY_SPEAKER">
+            <point>0,-2970</point>
+            <point>33,-2010</point>
+            <point>66,-1020</point>
+            <point>100,0</point>
+        </volume>
+        <volume stream="AUDIO_STREAM_NOTIFICATION" deviceCategory="DEVICE_CATEGORY_HEADSET"
+                ref="FULL_SCALE_VOLUME_CURVE"/>
+        <volume stream="AUDIO_STREAM_BLUETOOTH_SCO" deviceCategory="DEVICE_CATEGORY_EXT_MEDIA"
+                ref="FULL_SCALE_VOLUME_CURVE"/>
+        <volume stream="AUDIO_STREAM_ENFORCED_AUDIBLE" deviceCategory="DEVICE_CATEGORY_HEARING_AID"
+                ref="FULL_SCALE_VOLUME_CURVE"/>
+        <volume stream="AUDIO_STREAM_DTMF" deviceCategory="DEVICE_CATEGORY_SPEAKER"
+                ref="FULL_SCALE_VOLUME_CURVE"/>
+    </volumes>
+    <volumes>
+        <reference name="FULL_SCALE_VOLUME_CURVE">
+            <!-- Full Scale reference Volume Curve -->
+            <point>0,0</point>
+            <point>100,0</point>
+        </reference>
+    </volumes>
+</audioPolicyConfiguration>
diff --git a/services/audiopolicy/engine/interface/Android.bp b/services/audiopolicy/engine/interface/Android.bp
index 2ea42b6..5dd5adb 100644
--- a/services/audiopolicy/engine/interface/Android.bp
+++ b/services/audiopolicy/engine/interface/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libaudiopolicyengine_interface_headers",
     host_supported: true,
diff --git a/services/audiopolicy/engine/interface/EngineInterface.h b/services/audiopolicy/engine/interface/EngineInterface.h
index dfb20b5..f64608d 100644
--- a/services/audiopolicy/engine/interface/EngineInterface.h
+++ b/services/audiopolicy/engine/interface/EngineInterface.h
@@ -34,6 +34,8 @@
 using DeviceStrategyMap = std::map<product_strategy_t, DeviceVector>;
 using StrategyVector = std::vector<product_strategy_t>;
 using VolumeGroupVector = std::vector<volume_group_t>;
+using CapturePresetDevicesRoleMap =
+        std::map<audio_source_t, std::map<device_role_t, AudioDeviceTypeAddrVector>>;
 
 /**
  * This interface is dedicated to the policy manager that a Policy Engine shall implement.
@@ -293,36 +295,113 @@
     virtual status_t listAudioVolumeGroups(AudioVolumeGroupVector &groups) const = 0;
 
     /**
-     * @brief setPreferredDeviceForStrategy sets the default device to be used for a
-     * strategy when available
+     * @brief setDevicesRoleForStrategy sets devices role for a strategy when available. To remove
+     * devices role, removeDevicesRoleForStrategy must be called. When devices role is set
+     * successfully, previously set devices for the same role and strategy will be removed.
      * @param strategy the audio strategy whose routing will be affected
-     * @param device the audio device to route to when available
-     * @return BAD_VALUE if the strategy is invalid,
-     *     or NO_ERROR if the preferred device was set
+     * @param role the role of the devices for the strategy. All device roles are defined at
+     *             system/media/audio/include/system/audio_policy.h. DEVICE_ROLE_NONE is invalid
+     *             for setting.
+     * @param devices the audio devices to be set
+     * @return BAD_VALUE if the strategy or role is invalid,
+     *     or NO_ERROR if the role of the devices for strategy was set
      */
-    virtual status_t setPreferredDeviceForStrategy(product_strategy_t strategy,
-            const AudioDeviceTypeAddr &device) = 0;
+    virtual status_t setDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role,
+            const AudioDeviceTypeAddrVector &devices) = 0;
 
     /**
-     * @brief removePreferredDeviceForStrategy removes the preferred device previously set
+     * @brief removeDevicesRoleForStrategy removes the role of device(s) previously set
      * for the given strategy
      * @param strategy the audio strategy whose routing will be affected
-     * @return BAD_VALUE if the strategy is invalid,
-     *     or NO_ERROR if the preferred device was removed
+     * @param role the role of the devices for strategy
+     * @return BAD_VALUE if the strategy or role is invalid,
+     *     or NO_ERROR if the devices for this role was removed
      */
-    virtual status_t removePreferredDeviceForStrategy(product_strategy_t strategy) = 0;
+    virtual status_t removeDevicesRoleForStrategy(product_strategy_t strategy,
+            device_role_t role) = 0;
 
     /**
-     * @brief getPreferredDeviceForStrategy queries which device is set as the
-     * preferred device for the given strategy
+     * @brief getDevicesForRoleAndStrategy queries which devices have the specified role for the
+     * specified strategy
      * @param strategy the strategy to query
-     * @param device returns configured as the preferred device if one was set
-     * @return BAD_VALUE if the strategy is invalid,
-     *     or NAME_NOT_FOUND if no preferred device was set
-     *     or NO_ERROR if the device parameter was initialized to the preferred device
+     * @param role the role of the devices to query
+     * @param devices returns list of devices with matching role for the specified strategy.
+     *                DEVICE_ROLE_NONE is invalid as input.
+     * @return BAD_VALUE if the strategy or role is invalid,
+     *     or NAME_NOT_FOUND if no device for the role and strategy was set
+     *     or NO_ERROR if the devices parameter contains a list of devices
      */
-    virtual status_t getPreferredDeviceForStrategy(product_strategy_t strategy,
-            AudioDeviceTypeAddr &device) const = 0;
+    virtual status_t getDevicesForRoleAndStrategy(product_strategy_t strategy, device_role_t role,
+            AudioDeviceTypeAddrVector &devices) const = 0;
+
+    /**
+     * @brief setDevicesRoleForCapturePreset sets devices role for a capture preset when available.
+     * To remove devices role, removeDevicesRoleForCapturePreset must be called. Calling
+     * clearDevicesRoleForCapturePreset will remove all devices as role. When devices role is set
+     * successfully, previously set devices for the same role and capture preset will be removed.
+     * @param audioSource the audio capture preset whose routing will be affected
+     * @param role the role of the devices for the capture preset. All device roles are defined at
+     *             system/media/audio/include/system/audio_policy.h. DEVICE_ROLE_NONE is invalid
+     *             for setting.
+     * @param devices the audio devices to be set
+     * @return BAD_VALUE if the capture preset or role is invalid,
+     *     or NO_ERROR if the role of the devices for capture preset was set
+     */
+    virtual status_t setDevicesRoleForCapturePreset(audio_source_t audioSource, device_role_t role,
+            const AudioDeviceTypeAddrVector &devices) = 0;
+
+    /**
+     * @brief addDevicesRoleForCapturePreset adds devices role for a capture preset when available.
+     * To remove devices role, removeDevicesRoleForCapturePreset must be called. Calling
+     * clearDevicesRoleForCapturePreset will remove all devices as role.
+     * @param audioSource the audio capture preset whose routing will be affected
+     * @param role the role of the devices for the capture preset. All device roles are defined at
+     *             system/media/audio/include/system/audio_policy.h. DEVICE_ROLE_NONE is invalid
+     *             for setting.
+     * @param devices the audio devices to be added
+     * @return BAD_VALUE if the capture preset or role is invalid,
+     *     or NO_ERROR if the role of the devices for capture preset was added
+     */
+    virtual status_t addDevicesRoleForCapturePreset(audio_source_t audioSource, device_role_t role,
+            const AudioDeviceTypeAddrVector &devices) = 0;
+
+    /**
+     * @brief removeDevicesRoleForCapturePreset removes the role of device(s) previously set
+     * for the given capture preset
+     * @param audioSource the audio capture preset whose routing will be affected
+     * @param role the role of the devices for the capture preset
+     * @param devices the devices to be removed
+     * @return BAD_VALUE if 1) the capture preset is invalid, 2) role is invalid or 3) the list of
+     *     devices to be removed are not all present as role for a capture preset
+     *     or NO_ERROR if the devices for this role was removed
+     */
+    virtual status_t removeDevicesRoleForCapturePreset(audio_source_t audioSource,
+            device_role_t role, const AudioDeviceTypeAddrVector& devices) = 0;
+
+    /**
+     * @brief clearDevicesRoleForCapturePreset removes the role of all device(s) previously set
+     * for the given capture preset
+     * @param audioSource the audio capture preset whose routing will be affected
+     * @param role the role of the devices for the capture preset
+     * @return BAD_VALUE if the capture preset or role is invalid,
+     *     or NO_ERROR if the devices for this role was removed
+     */
+    virtual status_t clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+            device_role_t role);
+
+    /**
+     * @brief getDevicesForRoleAndCapturePreset queries which devices have the specified role for
+     * the specified capture preset
+     * @param audioSource the capture preset to query
+     * @param role the role of the devices to query
+     * @param devices returns list of devices with matching role for the specified capture preset.
+     *                DEVICE_ROLE_NONE is invalid as input.
+     * @return BAD_VALUE if the capture preset or role is invalid,
+     *     or NAME_NOT_FOUND if no device for the role and capture preset was set
+     *     or NO_ERROR if the devices parameter contains a list of devices
+     */
+    virtual status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+            device_role_t role, AudioDeviceTypeAddrVector &devices) const = 0;
 
 
     virtual void dump(String8 *dst) const = 0;
diff --git a/services/audiopolicy/engineconfigurable/Android.bp b/services/audiopolicy/engineconfigurable/Android.bp
index 8f522f0..a747822 100644
--- a/services/audiopolicy/engineconfigurable/Android.bp
+++ b/services/audiopolicy/engineconfigurable/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_headers {
     name: "libaudiopolicyengineconfigurable_interface_headers",
     host_supported: true,
diff --git a/services/audiopolicy/engineconfigurable/config/Android.bp b/services/audiopolicy/engineconfigurable/config/Android.bp
index fe3eae0..b3d1f97 100644
--- a/services/audiopolicy/engineconfigurable/config/Android.bp
+++ b/services/audiopolicy/engineconfigurable/config/Android.bp
@@ -16,6 +16,15 @@
 
 // Root soong_namespace for common components
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "audio_policy_engine_criteria.xml",
     vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp b/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp
index f913a14..e46b60f 100644
--- a/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp
+++ b/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp
@@ -22,6 +22,15 @@
     ],
 }
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "audio_policy_engine_configuration.xml",
     vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp b/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp
index fae6b7b..ad6eeb1 100644
--- a/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp
+++ b/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp
@@ -23,6 +23,15 @@
     ],
 }
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "audio_policy_engine_configuration.xml",
     vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp b/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp
index 94d33bd..773a99a 100644
--- a/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp
+++ b/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp
@@ -22,6 +22,15 @@
     ],
 }
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "audio_policy_engine_configuration.xml",
     vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_product_strategies.xml b/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_product_strategies.xml
index a7388da..bc32416 100644
--- a/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_product_strategies.xml
+++ b/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_product_strategies.xml
@@ -65,6 +65,12 @@
     </ProductStrategy>
 
     <ProductStrategy name="STRATEGY_MEDIA">
+        <AttributesGroup streamType="AUDIO_STREAM_ASSISTANT" volumeGroup="assistant">
+            <Attributes>
+                <ContentType value="AUDIO_CONTENT_TYPE_SPEECH"/>
+                <Usage value="AUDIO_USAGE_ASSISTANT"/>
+            </Attributes>
+        </AttributesGroup>
          <AttributesGroup streamType="AUDIO_STREAM_MUSIC" volumeGroup="music">
             <Attributes> <Usage value="AUDIO_USAGE_MEDIA"/> </Attributes>
             <Attributes> <Usage value="AUDIO_USAGE_GAME"/> </Attributes>
@@ -72,12 +78,6 @@
             <Attributes> <Usage value="AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE"/> </Attributes>
             <Attributes></Attributes>
         </AttributesGroup>
-        <AttributesGroup streamType="AUDIO_STREAM_ASSISTANT" volumeGroup="assistant">
-            <Attributes>
-                <ContentType value="AUDIO_CONTENT_TYPE_SPEECH"/>
-                <Usage value="AUDIO_USAGE_ASSISTANT"/>
-            </Attributes>
-        </AttributesGroup>
         <AttributesGroup streamType="AUDIO_STREAM_SYSTEM" volumeGroup="system">
             <Attributes> <Usage value="AUDIO_USAGE_ASSISTANCE_SONIFICATION"/> </Attributes>
         </AttributesGroup>
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp
index 90ebffd..ee62d5e 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp
@@ -16,6 +16,15 @@
 
 // Root soong_namespace for common components
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "PolicyClass.xml",
     vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp
index 82b1b6d..2d57d4f 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp
@@ -26,6 +26,17 @@
 //
 // Generate Audio Policy Parameter Framework Product Strategies Structure file from template
 //
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    //   SPDX-license-identifier-Unicode-DFS
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "ProductStrategies.xml",
     vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp
index e4605b2..df31bb9 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp
@@ -27,6 +27,17 @@
 //
 // Generate Audio Policy Parameter Framework Product Strategies Structure file from template
 //
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    //   SPDX-license-identifier-Unicode-DFS
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "ProductStrategies.xml",
     vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp
index 61b54cf..65ab8b6 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp
@@ -26,6 +26,17 @@
 //
 // Generate Audio Policy Parameter Framework Product Strategies Structure file from template
 //
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    //   SPDX-license-identifier-Unicode-DFS
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "ProductStrategies.xml",
     vendor: true,
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp
index 9abcb70..90154ee 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp
@@ -23,6 +23,17 @@
     ],
 }
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    //   SPDX-license-identifier-Unicode-DFS
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "parameter-framework.policy",
     filename_from_src: true,
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp
index 27172a4..5b06852 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp
@@ -23,6 +23,17 @@
     ],
 }
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    //   SPDX-license-identifier-Unicode-DFS
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "parameter-framework.policy",
     filename_from_src: true,
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp
index 2685c6d..0398fc7 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libpolicy-subsystem",
     srcs: [
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/InputSource.cpp b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/InputSource.cpp
index f91f8d7..f8a6fc0 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/InputSource.cpp
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/InputSource.cpp
@@ -45,7 +45,7 @@
 
 bool InputSource::sendToHW(string & /*error*/)
 {
-    uint32_t applicableInputDevice;
+    audio_devices_t applicableInputDevice;
     blackboardRead(&applicableInputDevice, sizeof(applicableInputDevice));
     return mPolicyPluginInterface->setDeviceForInputSource(mId, applicableInputDevice);
 }
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/ProductStrategy.h b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/ProductStrategy.h
index 244f082..6c8eb65 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/ProductStrategy.h
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/ProductStrategy.h
@@ -32,7 +32,7 @@
 
     struct Device
     {
-        uint32_t applicableDevice; /**< applicable device for this strategy. */
+        audio_devices_t applicableDevice; /**< applicable device for this strategy. */
         char deviceAddress[mMaxStringSize]; /**< device address associated with this strategy. */
     } __attribute__((packed));
 
diff --git a/services/audiopolicy/engineconfigurable/src/InputSource.cpp b/services/audiopolicy/engineconfigurable/src/InputSource.cpp
index aa06ae3..f4645e6 100644
--- a/services/audiopolicy/engineconfigurable/src/InputSource.cpp
+++ b/services/audiopolicy/engineconfigurable/src/InputSource.cpp
@@ -51,7 +51,7 @@
         mApplicableDevices = devices;
         return NO_ERROR;
     }
-    devices |= AUDIO_DEVICE_BIT_IN;
+    devices = static_cast<audio_devices_t>(devices | AUDIO_DEVICE_BIT_IN);
     if (!audio_is_input_device(devices)) {
         ALOGE("%s: trying to set an invalid device 0x%X for input source %s",
               __FUNCTION__, devices, getName().c_str());
diff --git a/services/audiopolicy/engineconfigurable/tools/Android.bp b/services/audiopolicy/engineconfigurable/tools/Android.bp
index 3e47324..40efb3d 100644
--- a/services/audiopolicy/engineconfigurable/tools/Android.bp
+++ b/services/audiopolicy/engineconfigurable/tools/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 python_defaults {
     name: "tools_default",
     version: {
@@ -42,8 +51,8 @@
     cmd: "cp $(locations :audio_policy_configuration_files) $(genDir)/. && " +
          "cp $(location :audio_policy_configuration_top_file) $(genDir)/audio_policy_configuration.xml && " +
          "$(location buildPolicyCriterionTypes.py) " +
-         // @todo update if 1428659 is merged "--androidaudiobaseheader $(location :android_audio_base_header_file) " +
-         " --androidaudiobaseheader system/media/audio/include/system/audio-base.h " +
+         " --androidaudiobaseheader $(location :libaudio_system_audio_base) " +
+         " --androidaudiocommonbaseheader $(location :libaudio_system_audio_common_base) " +
          "--audiopolicyconfigurationfile $(genDir)/audio_policy_configuration.xml " +
          "--criteriontypes $(location :audio_policy_engine_criterion_types_template) " +
          "--outputfile $(out)",
@@ -51,6 +60,8 @@
         // The commented inputs must be provided to use this genrule_defaults
         // @todo uncomment if 1428659 is merged":android_audio_base_header_file",
         ":audio_policy_engine_criterion_types_template",
+        ":libaudio_system_audio_base",
+        ":libaudio_system_audio_common_base",
         // ":audio_policy_configuration_top_file",
         // ":audio_policy_configuration_files",
     ],
diff --git a/services/audiopolicy/engineconfigurable/tools/buildCommonTypesStructureFile.py b/services/audiopolicy/engineconfigurable/tools/buildCommonTypesStructureFile.py
index 9a7fa8f..5083b14 100755
--- a/services/audiopolicy/engineconfigurable/tools/buildCommonTypesStructureFile.py
+++ b/services/audiopolicy/engineconfigurable/tools/buildCommonTypesStructureFile.py
@@ -52,13 +52,19 @@
 def findBitPos(decimal):
     pos = 0
     i = 1
-    while i != decimal:
+    while i < decimal:
         i = i << 1
         pos = pos + 1
         if pos == 32:
             return -1
-    return pos
 
+    # TODO: b/168065706. This is just to fix the build. That the problem of devices with
+    # multiple bits set must be addressed more generally in the configurable audio policy
+    # and parameter framework.
+    if i > decimal:
+        logging.info("Device:{} which has multiple bits set is skipped. b/168065706".format(decimal))
+        return -2
+    return pos
 
 def generateXmlStructureFile(componentTypeDict, structureTypesFile, outputFile):
 
@@ -74,10 +80,12 @@
                 if bitparameters_node is not None:
                     ordered_values = OrderedDict(sorted(values_dict.items(), key=lambda x: x[1]))
                     for key, value in ordered_values.items():
-                        value_node = ET.SubElement(bitparameters_node, "BitParameter")
-                        value_node.set('Name', key)
-                        value_node.set('Size', "1")
-                        value_node.set('Pos', str(findBitPos(value)))
+                        pos = findBitPos(value)
+                        if pos >= 0:
+                            value_node = ET.SubElement(bitparameters_node, "BitParameter")
+                            value_node.set('Name', key)
+                            value_node.set('Size', "1")
+                            value_node.set('Pos', str(pos))
 
                 enum_parameter_node = component_type.find("EnumParameter")
                 if enum_parameter_node is not None:
@@ -118,9 +126,9 @@
     ignored_values = ['CNT', 'MAX', 'ALL', 'NONE']
 
     criteria_pattern = re.compile(
-        r"\s*(?P<type>(?:"+'|'.join(component_type_mapping_table.keys()) + "))_" \
-        r"(?P<literal>(?!" + '|'.join(ignored_values) + ")\w*)\s*=\s*" \
-        r"(?P<values>(?:0[xX])?[0-9a-fA-F]+)")
+        r"\s*V\((?P<type>(?:"+'|'.join(component_type_mapping_table.keys()) + "))_" \
+        r"(?P<literal>(?!" + '|'.join(ignored_values) + ")\w*)\s*,\s*" \
+        r"(?:AUDIO_DEVICE_BIT_IN \| )?(?P<values>(?:0[xX])[0-9a-fA-F]+|[0-9]+)")
 
     logging.info("Checking Android Header file {}".format(androidaudiobaseheaderFile))
 
@@ -156,6 +164,13 @@
 
             logging.debug("type:{}, literal:{}, values:{}.".format(component_type_name, component_type_literal, component_type_numerical_value))
 
+    if "stub" not in all_component_types["OutputDevicesMask"]:
+        all_component_types["OutputDevicesMask"]["stub"] = 0x40000000
+        logging.info("added stub output device mask")
+    if "stub" not in all_component_types["InputDevicesMask"]:
+        all_component_types["InputDevicesMask"]["stub"] = 0x40000000
+        logging.info("added stub input device mask")
+
     # Transform input source in inclusive criterion
     shift = len(all_component_types['OutputDevicesMask'])
     if shift > 32:
diff --git a/services/audiopolicy/engineconfigurable/tools/buildPolicyCriterionTypes.py b/services/audiopolicy/engineconfigurable/tools/buildPolicyCriterionTypes.py
index b8b60c1..b5885c0 100755
--- a/services/audiopolicy/engineconfigurable/tools/buildPolicyCriterionTypes.py
+++ b/services/audiopolicy/engineconfigurable/tools/buildPolicyCriterionTypes.py
@@ -55,6 +55,11 @@
                            metavar="ANDROID_AUDIO_BASE_HEADER",
                            type=argparse.FileType('r'),
                            required=True)
+    argparser.add_argument('--androidaudiocommonbaseheader',
+                           help="Android Audio CommonBase C header file, Mandatory.",
+                           metavar="ANDROID_AUDIO_COMMON_BASE_HEADER",
+                           type=argparse.FileType('r'),
+                           required=True)
     argparser.add_argument('--audiopolicyconfigurationfile',
                            help="Android Audio Policy Configuration file, Mandatory.",
                            metavar="(AUDIO_POLICY_CONFIGURATION_FILE)",
@@ -176,12 +181,12 @@
 #   -Output devices type
 #   -Input devices type
 #
-def parseAndroidAudioFile(androidaudiobaseheaderFile):
+def parseAndroidAudioFile(androidaudiobaseheaderFile, androidaudiocommonbaseheaderFile):
     #
     # Adaptation table between Android Enumeration prefix and Audio PFW Criterion type names
     #
     criterion_mapping_table = {
-        'AUDIO_MODE' : "AndroidModeType",
+        'HAL_AUDIO_MODE' : "AndroidModeType",
         'AUDIO_DEVICE_OUT' : "OutputDevicesMaskType",
         'AUDIO_DEVICE_IN' : "InputDevicesMaskType"}
 
@@ -196,9 +201,9 @@
     ignored_values = ['CNT', 'MAX', 'ALL', 'NONE']
 
     criteria_pattern = re.compile(
-        r"\s*(?P<type>(?:"+'|'.join(criterion_mapping_table.keys()) + "))_" \
-        r"(?P<literal>(?!" + '|'.join(ignored_values) + ")\w*)\s*=\s*" \
-        r"(?P<values>(?:0[xX])?[0-9a-fA-F]+)")
+        r"\s*V\((?P<type>(?:"+'|'.join(criterion_mapping_table.keys()) + "))_" \
+        r"(?P<literal>(?!" + '|'.join(ignored_values) + ")\w*)\s*,\s*" \
+        r"(?:AUDIO_DEVICE_BIT_IN \| )?(?P<values>(?:0[xX])?[0-9a-fA-F]+|[0-9]+)")
 
     logging.info("Checking Android Header file {}".format(androidaudiobaseheaderFile))
 
@@ -209,27 +214,91 @@
                 androidaudiobaseheaderFile.name, line_number, line))
 
             criterion_name = criterion_mapping_table[match.groupdict()['type']]
-            literal = ''.join((w.capitalize() for w in match.groupdict()['literal'].split('_')))
-            numerical_value = match.groupdict()['values']
+            criterion_literal = \
+                ''.join((w.capitalize() for w in match.groupdict()['literal'].split('_')))
+            criterion_numerical_value = match.groupdict()['values']
 
-            # for AUDIO_DEVICE_IN: need to remove sign bit
+            # for AUDIO_DEVICE_IN: need to remove sign bit / rename default to stub
             if criterion_name == "InputDevicesMaskType":
-                numerical_value = str(int(numerical_value, 0) & ~2147483648)
+                if criterion_literal == "Default":
+                    criterion_numerical_value = str(int("0x40000000", 0))
+                else:
+                    try:
+                        string_int = int(criterion_numerical_value, 0)
+                    except ValueError:
+                        # Handle the exception
+                        logging.info("value {}:{} for criterion {} is not a number, ignoring"
+                            .format(criterion_numerical_value, criterion_literal, criterion_name))
+                        continue
+                    criterion_numerical_value = str(int(criterion_numerical_value, 0) & ~2147483648)
+
+            if criterion_name == "OutputDevicesMaskType":
+                if criterion_literal == "Default":
+                    criterion_numerical_value = str(int("0x40000000", 0))
+
+            try:
+                string_int = int(criterion_numerical_value, 0)
+            except ValueError:
+                # Handle the exception
+                logging.info("The value {}:{} is for criterion {} is not a number, ignoring"
+                    .format(criterion_numerical_value, criterion_literal, criterion_name))
+                continue
 
             # Remove duplicated numerical values
-            if int(numerical_value, 0) in all_criteria[criterion_name].values():
+            if int(criterion_numerical_value, 0) in all_criteria[criterion_name].values():
                 logging.info("criterion {} duplicated values:".format(criterion_name))
-                logging.info("{}:{}".format(numerical_value, literal))
+                logging.info("{}:{}".format(criterion_numerical_value, criterion_literal))
                 logging.info("KEEPING LATEST")
                 for key in list(all_criteria[criterion_name]):
-                    if all_criteria[criterion_name][key] == int(numerical_value, 0):
+                    if all_criteria[criterion_name][key] == int(criterion_numerical_value, 0):
                         del all_criteria[criterion_name][key]
 
-            all_criteria[criterion_name][literal] = int(numerical_value, 0)
+            all_criteria[criterion_name][criterion_literal] = int(criterion_numerical_value, 0)
 
             logging.debug("type:{},".format(criterion_name))
-            logging.debug("iteral:{},".format(literal))
-            logging.debug("values:{}.".format(numerical_value))
+            logging.debug("iteral:{},".format(criterion_literal))
+            logging.debug("values:{}.".format(criterion_numerical_value))
+
+    logging.info("Checking Android Common Header file {}".format(androidaudiocommonbaseheaderFile))
+
+    criteria_pattern = re.compile(
+        r"\s*(?P<type>(?:"+'|'.join(criterion_mapping_table.keys()) + "))_" \
+        r"(?P<literal>(?!" + '|'.join(ignored_values) + ")\w*)\s*=\s*" \
+        r"(?:AUDIO_DEVICE_BIT_IN \| )?(?P<values>(?:0[xX])?[0-9a-fA-F]+|[0-9]+)")
+
+    for line_number, line in enumerate(androidaudiocommonbaseheaderFile):
+        match = criteria_pattern.match(line)
+        if match:
+            logging.debug("The following line is VALID: {}:{}\n{}".format(
+                androidaudiocommonbaseheaderFile.name, line_number, line))
+
+            criterion_name = criterion_mapping_table[match.groupdict()['type']]
+            criterion_literal = \
+                ''.join((w.capitalize() for w in match.groupdict()['literal'].split('_')))
+            criterion_numerical_value = match.groupdict()['values']
+
+            try:
+                string_int = int(criterion_numerical_value, 0)
+            except ValueError:
+                # Handle the exception
+                logging.info("The value {}:{} is for criterion {} is not a number, ignoring"
+                    .format(criterion_numerical_value, criterion_literal, criterion_name))
+                continue
+
+            # Remove duplicated numerical values
+            if int(criterion_numerical_value, 0) in all_criteria[criterion_name].values():
+                logging.info("criterion {} duplicated values:".format(criterion_name))
+                logging.info("{}:{}".format(criterion_numerical_value, criterion_literal))
+                logging.info("KEEPING LATEST")
+                for key in list(all_criteria[criterion_name]):
+                    if all_criteria[criterion_name][key] == int(criterion_numerical_value, 0):
+                        del all_criteria[criterion_name][key]
+
+            all_criteria[criterion_name][criterion_literal] = int(criterion_numerical_value, 0)
+
+            logging.debug("type:{},".format(criterion_name))
+            logging.debug("iteral:{},".format(criterion_literal))
+            logging.debug("values:{}.".format(criterion_numerical_value))
 
     return all_criteria
 
@@ -238,7 +307,8 @@
     logging.root.setLevel(logging.INFO)
     args = parseArgs()
 
-    all_criteria = parseAndroidAudioFile(args.androidaudiobaseheader)
+    all_criteria = parseAndroidAudioFile(args.androidaudiobaseheader,
+                                         args.androidaudiocommonbaseheader)
 
     address_criteria = parseAndroidAudioPolicyConfigurationFile(args.audiopolicyconfigurationfile)
 
diff --git a/services/audiopolicy/engineconfigurable/wrapper/Android.bp b/services/audiopolicy/engineconfigurable/wrapper/Android.bp
index 301ecc0..3e04b68 100644
--- a/services/audiopolicy/engineconfigurable/wrapper/Android.bp
+++ b/services/audiopolicy/engineconfigurable/wrapper/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library {
     name: "libaudiopolicyengineconfigurable_pfwwrapper",
     export_include_dirs: ["include"],
diff --git a/services/audiopolicy/enginedefault/Android.bp b/services/audiopolicy/enginedefault/Android.bp
index aaf4158..7f9c0ac 100644
--- a/services/audiopolicy/enginedefault/Android.bp
+++ b/services/audiopolicy/enginedefault/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libaudiopolicyenginedefault",
     srcs: [
diff --git a/services/audiopolicy/enginedefault/config/example/Android.bp b/services/audiopolicy/enginedefault/config/example/Android.bp
index 0bfcaa1..59a704b 100644
--- a/services/audiopolicy/enginedefault/config/example/Android.bp
+++ b/services/audiopolicy/enginedefault/config/example/Android.bp
@@ -19,6 +19,15 @@
 soong_namespace {
 }
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 prebuilt_etc {
     name: "audio_policy_engine_configuration.xml",
     vendor: true,
diff --git a/services/audiopolicy/enginedefault/config/example/phone/audio_policy_engine_product_strategies.xml b/services/audiopolicy/enginedefault/config/example/phone/audio_policy_engine_product_strategies.xml
index a7388da..bc32416 100644
--- a/services/audiopolicy/enginedefault/config/example/phone/audio_policy_engine_product_strategies.xml
+++ b/services/audiopolicy/enginedefault/config/example/phone/audio_policy_engine_product_strategies.xml
@@ -65,6 +65,12 @@
     </ProductStrategy>
 
     <ProductStrategy name="STRATEGY_MEDIA">
+        <AttributesGroup streamType="AUDIO_STREAM_ASSISTANT" volumeGroup="assistant">
+            <Attributes>
+                <ContentType value="AUDIO_CONTENT_TYPE_SPEECH"/>
+                <Usage value="AUDIO_USAGE_ASSISTANT"/>
+            </Attributes>
+        </AttributesGroup>
          <AttributesGroup streamType="AUDIO_STREAM_MUSIC" volumeGroup="music">
             <Attributes> <Usage value="AUDIO_USAGE_MEDIA"/> </Attributes>
             <Attributes> <Usage value="AUDIO_USAGE_GAME"/> </Attributes>
@@ -72,12 +78,6 @@
             <Attributes> <Usage value="AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE"/> </Attributes>
             <Attributes></Attributes>
         </AttributesGroup>
-        <AttributesGroup streamType="AUDIO_STREAM_ASSISTANT" volumeGroup="assistant">
-            <Attributes>
-                <ContentType value="AUDIO_CONTENT_TYPE_SPEECH"/>
-                <Usage value="AUDIO_USAGE_ASSISTANT"/>
-            </Attributes>
-        </AttributesGroup>
         <AttributesGroup streamType="AUDIO_STREAM_SYSTEM" volumeGroup="system">
             <Attributes> <Usage value="AUDIO_USAGE_ASSISTANCE_SONIFICATION"/> </Attributes>
         </AttributesGroup>
diff --git a/services/audiopolicy/enginedefault/src/Engine.cpp b/services/audiopolicy/enginedefault/src/Engine.cpp
old mode 100755
new mode 100644
index b14d2bb..e0a0bbb
--- a/services/audiopolicy/enginedefault/src/Engine.cpp
+++ b/services/audiopolicy/enginedefault/src/Engine.cpp
@@ -184,16 +184,7 @@
         break;
 
     case STRATEGY_DTMF:
-        if (!isInCall()) {
-            // when off call, DTMF strategy follows the same rules as MEDIA strategy
-            devices = getDevicesForStrategyInt(
-                    STRATEGY_MEDIA, availableOutputDevices, availableInputDevices, outputs);
-            break;
-        }
-        // when in call, DTMF and PHONE strategies follow the same rules
-        FALLTHROUGH_INTENDED;
-
-    case STRATEGY_PHONE:
+    case STRATEGY_PHONE: {
         // Force use of only devices on primary output if:
         // - in call AND
         //   - cannot route from voice call RX OR
@@ -216,75 +207,24 @@
                     availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_HEARING_AID));
 
             if ((availableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
-                    String8(""), AUDIO_FORMAT_DEFAULT) == nullptr) ||
-                    ((availPrimaryInputDevices.getDevice(
-                            txDevice, String8(""), AUDIO_FORMAT_DEFAULT) != nullptr) &&
-                            (primaryOutput->getPolicyAudioPort()->getModuleVersionMajor() < 3))) {
+                                                 String8(""), AUDIO_FORMAT_DEFAULT) == nullptr) ||
+                ((availPrimaryInputDevices.getDevice(
+                        txDevice, String8(""), AUDIO_FORMAT_DEFAULT) != nullptr) &&
+                 (primaryOutput->getPolicyAudioPort()->getModuleVersionMajor() < 3))) {
                 availableOutputDevices = availPrimaryOutputDevices;
             }
         }
-        // for phone strategy, we first consider the forced use and then the available devices by
-        // order of priority
-        switch (getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION)) {
-        case AUDIO_POLICY_FORCE_BT_SCO:
-            if (!isInCall() || strategy != STRATEGY_DTMF) {
-                devices = availableOutputDevices.getDevicesFromType(
-                        AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT);
-                if (!devices.isEmpty()) break;
-            }
-            devices = availableOutputDevices.getFirstDevicesFromTypes({
-                    AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, AUDIO_DEVICE_OUT_BLUETOOTH_SCO});
-            if (!devices.isEmpty()) break;
-            // if SCO device is requested but no SCO device is available, fall back to default case
-            FALLTHROUGH_INTENDED;
-
-        default:    // FORCE_NONE
-            devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_HEARING_AID);
-            if (!devices.isEmpty()) break;
-            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
-            if (!isInCall() &&
-                    (getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
-                     outputs.isA2dpSupported()) {
-                devices = availableOutputDevices.getFirstDevicesFromTypes({
-                        AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
-                        AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES});
-                if (!devices.isEmpty()) break;
-            }
-            devices = availableOutputDevices.getFirstDevicesFromTypes({
-                    AUDIO_DEVICE_OUT_WIRED_HEADPHONE, AUDIO_DEVICE_OUT_WIRED_HEADSET,
-                    AUDIO_DEVICE_OUT_LINE, AUDIO_DEVICE_OUT_USB_HEADSET,
-                    AUDIO_DEVICE_OUT_USB_DEVICE});
-            if (!devices.isEmpty()) break;
-            if (!isInCall()) {
-                devices = availableOutputDevices.getFirstDevicesFromTypes({
-                        AUDIO_DEVICE_OUT_USB_ACCESSORY, AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET,
-                        AUDIO_DEVICE_OUT_AUX_DIGITAL, AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET});
-                if (!devices.isEmpty()) break;
-            }
-            devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_EARPIECE);
-            break;
-
-        case AUDIO_POLICY_FORCE_SPEAKER:
-            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
-            // A2DP speaker when forcing to speaker output
-            if (!isInCall() &&
-                    (getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
-                     outputs.isA2dpSupported()) {
-                devices = availableOutputDevices.getDevicesFromType(
-                        AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER);
-                if (!devices.isEmpty()) break;
-            }
-            if (!isInCall()) {
-                devices = availableOutputDevices.getFirstDevicesFromTypes({
-                        AUDIO_DEVICE_OUT_USB_ACCESSORY, AUDIO_DEVICE_OUT_USB_DEVICE,
-                        AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, AUDIO_DEVICE_OUT_AUX_DIGITAL,
-                        AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET});
-                if (!devices.isEmpty()) break;
-            }
-            devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER);
-            break;
-        }
-    break;
+        devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_HEARING_AID);
+        if (!devices.isEmpty()) break;
+        devices = availableOutputDevices.getFirstDevicesFromTypes({
+                                                                  AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
+                                                                  AUDIO_DEVICE_OUT_WIRED_HEADSET,
+                                                                  AUDIO_DEVICE_OUT_LINE,
+                                                                  AUDIO_DEVICE_OUT_USB_HEADSET,
+                                                                  AUDIO_DEVICE_OUT_USB_DEVICE});
+        if (!devices.isEmpty()) break;
+        devices = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_EARPIECE);
+    } break;
 
     case STRATEGY_SONIFICATION:
 
@@ -327,7 +267,8 @@
                 }
             }
             // Use both Bluetooth SCO and phone default output when ringing in normal mode
-            if (getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) {
+            if (audio_is_bluetooth_out_sco_device(getPreferredDeviceTypeForLegacyStrategy(
+                    availableOutputDevices, STRATEGY_PHONE))) {
                 if (strategy == STRATEGY_SONIFICATION) {
                     devices.replaceDevicesByType(
                             AUDIO_DEVICE_OUT_SPEAKER,
@@ -386,18 +327,13 @@
                     STRATEGY_PHONE, availableOutputDevices, availableInputDevices, outputs);
             break;
         }
-        // FIXME: Find a better solution to prevent routing to BT hearing aid(b/122931261).
-        if ((devices2.isEmpty()) &&
-                (getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) != AUDIO_POLICY_FORCE_NO_BT_A2DP)) {
-            devices2 = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_HEARING_AID);
-        }
+
         if ((devices2.isEmpty()) &&
             (getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) == AUDIO_POLICY_FORCE_SPEAKER)) {
             devices2 = availableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER);
         }
         if (devices2.isEmpty() && (getLastRemovableMediaDevices().size() > 0)) {
-            if ((getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
-                    outputs.isA2dpSupported()) {
+            if ((getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) != AUDIO_POLICY_FORCE_NO_BT_A2DP)) {
                 // Get the last connected device of wired and bluetooth a2dp
                 devices2 = availableOutputDevices.getFirstDevicesFromTypes(
                         getLastRemovableMediaDevices());
@@ -502,20 +438,24 @@
         }
     }
 
+    audio_devices_t commDeviceType =
+        getPreferredDeviceTypeForLegacyStrategy(availableOutputDevices, STRATEGY_PHONE);
+
     switch (inputSource) {
     case AUDIO_SOURCE_DEFAULT:
     case AUDIO_SOURCE_MIC:
         device = availableDevices.getDevice(
                 AUDIO_DEVICE_IN_BLUETOOTH_A2DP, String8(""), AUDIO_FORMAT_DEFAULT);
         if (device != nullptr) break;
-        if (getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO) {
+        if (audio_is_bluetooth_out_sco_device(commDeviceType)) {
             device = availableDevices.getDevice(
                     AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, String8(""), AUDIO_FORMAT_DEFAULT);
             if (device != nullptr) break;
         }
         device = availableDevices.getFirstExistingDevice({
-                AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_IN_USB_HEADSET,
-                AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BUILTIN_MIC});
+                AUDIO_DEVICE_IN_BLE_HEADSET, AUDIO_DEVICE_IN_WIRED_HEADSET,
+                AUDIO_DEVICE_IN_USB_HEADSET, AUDIO_DEVICE_IN_USB_DEVICE,
+                AUDIO_DEVICE_IN_BLUETOOTH_BLE, AUDIO_DEVICE_IN_BUILTIN_MIC});
         break;
 
     case AUDIO_SOURCE_VOICE_COMMUNICATION:
@@ -528,46 +468,63 @@
             availableDevices = availablePrimaryDevices;
         }
 
-        switch (getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION)) {
-        case AUDIO_POLICY_FORCE_BT_SCO:
+        if (audio_is_bluetooth_out_sco_device(commDeviceType)) {
             // if SCO device is requested but no SCO device is available, fall back to default case
             device = availableDevices.getDevice(
                     AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, String8(""), AUDIO_FORMAT_DEFAULT);
             if (device != nullptr) {
                 break;
             }
-            FALLTHROUGH_INTENDED;
-
-        default:    // FORCE_NONE
-            device = availableDevices.getFirstExistingDevice({
-                    AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_IN_USB_HEADSET,
-                    AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BUILTIN_MIC});
+        }
+        switch (commDeviceType) {
+        case AUDIO_DEVICE_OUT_BLE_HEADSET:
+            device = availableDevices.getDevice(
+                    AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, String8(""), AUDIO_FORMAT_DEFAULT);
             break;
-
-        case AUDIO_POLICY_FORCE_SPEAKER:
+        case AUDIO_DEVICE_OUT_SPEAKER:
             device = availableDevices.getFirstExistingDevice({
                     AUDIO_DEVICE_IN_BACK_MIC, AUDIO_DEVICE_IN_BUILTIN_MIC});
             break;
+        default:    // FORCE_NONE
+            device = availableDevices.getFirstExistingDevice({
+                    AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_IN_USB_HEADSET,
+                    AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BLUETOOTH_BLE,
+                    AUDIO_DEVICE_IN_BUILTIN_MIC});
+            break;
+
         }
         break;
 
     case AUDIO_SOURCE_VOICE_RECOGNITION:
     case AUDIO_SOURCE_UNPROCESSED:
-    case AUDIO_SOURCE_HOTWORD:
-        if (inputSource == AUDIO_SOURCE_HOTWORD) {
-            // We should not use primary output criteria for Hotword but rather limit
-            // to devices attached to the same HW module as the build in mic
-            LOG_ALWAYS_FATAL_IF(availablePrimaryDevices.isEmpty(), "Primary devices not found");
-            availableDevices = availablePrimaryDevices;
+        if (audio_is_bluetooth_out_sco_device(commDeviceType)) {
+            device = availableDevices.getDevice(
+                    AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, String8(""), AUDIO_FORMAT_DEFAULT);
+            if (device != nullptr) break;
         }
-        if (getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO) {
+        // we need to make BLUETOOTH_BLE has higher priority than BUILTIN_MIC,
+        // because sometimes user want to do voice search by bt remote
+        // even if BUILDIN_MIC is available.
+        device = availableDevices.getFirstExistingDevice({
+                AUDIO_DEVICE_IN_BLE_HEADSET, AUDIO_DEVICE_IN_WIRED_HEADSET,
+                AUDIO_DEVICE_IN_USB_HEADSET, AUDIO_DEVICE_IN_USB_DEVICE,
+                AUDIO_DEVICE_IN_BLUETOOTH_BLE, AUDIO_DEVICE_IN_BUILTIN_MIC});
+
+        break;
+    case AUDIO_SOURCE_HOTWORD:
+        // We should not use primary output criteria for Hotword but rather limit
+        // to devices attached to the same HW module as the build in mic
+        LOG_ALWAYS_FATAL_IF(availablePrimaryDevices.isEmpty(), "Primary devices not found");
+        availableDevices = availablePrimaryDevices;
+        if (audio_is_bluetooth_out_sco_device(commDeviceType)) {
             device = availableDevices.getDevice(
                     AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, String8(""), AUDIO_FORMAT_DEFAULT);
             if (device != nullptr) break;
         }
         device = availableDevices.getFirstExistingDevice({
-                AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_IN_USB_HEADSET,
-                AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BUILTIN_MIC});
+                AUDIO_DEVICE_IN_BLE_HEADSET, AUDIO_DEVICE_IN_WIRED_HEADSET,
+                AUDIO_DEVICE_IN_USB_HEADSET, AUDIO_DEVICE_IN_USB_DEVICE,
+                AUDIO_DEVICE_IN_BUILTIN_MIC});
         break;
     case AUDIO_SOURCE_CAMCORDER:
         // For a device without built-in mic, adding usb device
@@ -584,7 +541,8 @@
     case AUDIO_SOURCE_VOICE_PERFORMANCE:
         device = availableDevices.getFirstExistingDevice({
                 AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_IN_USB_HEADSET,
-                AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BUILTIN_MIC});
+                AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_IN_BLUETOOTH_BLE,
+                AUDIO_DEVICE_IN_BUILTIN_MIC});
         break;
     case AUDIO_SOURCE_REMOTE_SUBMIX:
         device = availableDevices.getDevice(
@@ -609,6 +567,7 @@
         ALOGE_IF(device == nullptr,
                  "getDeviceForInputSource() no default device defined");
     }
+
     ALOGV_IF(device != nullptr,
              "getDeviceForInputSource()input source %d, device %08x",
              inputSource, device->type());
@@ -626,31 +585,66 @@
     }
 }
 
-DeviceVector Engine::getDevicesForProductStrategy(product_strategy_t strategy) const {
-    DeviceVector availableOutputDevices = getApmObserver()->getAvailableOutputDevices();
+product_strategy_t Engine::getProductStrategyFromLegacy(legacy_strategy legacyStrategy) const {
+    for (const auto& strategyMap : mLegacyStrategyMap) {
+        if (strategyMap.second == legacyStrategy) {
+            return strategyMap.first;
+        }
+    }
+    return PRODUCT_STRATEGY_NONE;
+}
 
-    // check if this strategy has a preferred device that is available,
-    // if yes, give priority to it
-    AudioDeviceTypeAddr preferredStrategyDevice;
-    const status_t status = getPreferredDeviceForStrategy(strategy, preferredStrategyDevice);
+audio_devices_t Engine::getPreferredDeviceTypeForLegacyStrategy(
+        const DeviceVector& availableOutputDevices, legacy_strategy legacyStrategy) const {
+    product_strategy_t strategy = getProductStrategyFromLegacy(legacyStrategy);
+    DeviceVector devices = getPreferredAvailableDevicesForProductStrategy(
+            availableOutputDevices, strategy);
+    if (devices.size() > 0) {
+        return devices[0]->type();
+    }
+    return AUDIO_DEVICE_NONE;
+}
+
+DeviceVector Engine::getPreferredAvailableDevicesForProductStrategy(
+        const DeviceVector& availableOutputDevices, product_strategy_t strategy) const {
+    DeviceVector preferredAvailableDevVec = {};
+    AudioDeviceTypeAddrVector preferredStrategyDevices;
+    const status_t status = getDevicesForRoleAndStrategy(
+            strategy, DEVICE_ROLE_PREFERRED, preferredStrategyDevices);
     if (status == NO_ERROR) {
         // there is a preferred device, is it available?
-        sp<DeviceDescriptor> preferredAvailableDevDescr = availableOutputDevices.getDevice(
-                preferredStrategyDevice.mType,
-                String8(preferredStrategyDevice.mAddress.c_str()),
-                AUDIO_FORMAT_DEFAULT);
-        if (preferredAvailableDevDescr != nullptr) {
-            ALOGVV("%s using pref device 0x%08x/%s for strategy %u",
-                   __func__, preferredStrategyDevice.mType,
-                   preferredStrategyDevice.mAddress.c_str(), strategy);
-            return DeviceVector(preferredAvailableDevDescr);
+        preferredAvailableDevVec =
+                availableOutputDevices.getDevicesFromDeviceTypeAddrVec(preferredStrategyDevices);
+        if (preferredAvailableDevVec.size() == preferredAvailableDevVec.size()) {
+            ALOGVV("%s using pref device %s for strategy %u",
+                   __func__, preferredAvailableDevVec.toString().c_str(), strategy);
+            return preferredAvailableDevVec;
         }
     }
+    return preferredAvailableDevVec;
+}
+
+DeviceVector Engine::getDevicesForProductStrategy(product_strategy_t strategy) const {
+    DeviceVector availableOutputDevices = getApmObserver()->getAvailableOutputDevices();
+    auto legacyStrategy = mLegacyStrategyMap.find(strategy) != end(mLegacyStrategyMap) ?
+                          mLegacyStrategyMap.at(strategy) : STRATEGY_NONE;
+
+    // When not in call, STRATEGY_PHONE and STRATEGY_DTMF follow STRATEGY_MEDIA
+    if (!isInCall() && (legacyStrategy == STRATEGY_PHONE || legacyStrategy == STRATEGY_DTMF)) {
+        legacyStrategy = STRATEGY_MEDIA;
+        strategy = getProductStrategyFromLegacy(STRATEGY_MEDIA);
+    }
+    // check if this strategy has a preferred device that is available,
+    // if yes, give priority to it.
+    DeviceVector preferredAvailableDevVec =
+            getPreferredAvailableDevicesForProductStrategy(availableOutputDevices, strategy);
+    if (!preferredAvailableDevVec.isEmpty()) {
+        return preferredAvailableDevVec;
+    }
 
     DeviceVector availableInputDevices = getApmObserver()->getAvailableInputDevices();
     const SwAudioOutputCollection& outputs = getApmObserver()->getOutputs();
-    auto legacyStrategy = mLegacyStrategyMap.find(strategy) != end(mLegacyStrategyMap) ?
-                          mLegacyStrategyMap.at(strategy) : STRATEGY_NONE;
+
     return getDevicesForStrategyInt(legacyStrategy,
                                     availableOutputDevices,
                                     availableInputDevices, outputs);
diff --git a/services/audiopolicy/enginedefault/src/Engine.h b/services/audiopolicy/enginedefault/src/Engine.h
index bb9e2df..6214fe7 100644
--- a/services/audiopolicy/enginedefault/src/Engine.h
+++ b/services/audiopolicy/enginedefault/src/Engine.h
@@ -83,6 +83,12 @@
 
     sp<DeviceDescriptor> getDeviceForInputSource(audio_source_t inputSource) const;
 
+    product_strategy_t getProductStrategyFromLegacy(legacy_strategy legacyStrategy) const;
+    audio_devices_t getPreferredDeviceTypeForLegacyStrategy(
+        const DeviceVector& availableOutputDevices, legacy_strategy legacyStrategy) const;
+    DeviceVector getPreferredAvailableDevicesForProductStrategy(
+        const DeviceVector& availableOutputDevices, product_strategy_t strategy) const;
+
     DeviceStrategyMap mDevicesForStrategies;
 
     std::map<product_strategy_t, legacy_strategy> mLegacyStrategyMap;
diff --git a/services/audiopolicy/manager/Android.mk b/services/audiopolicy/manager/Android.mk
index cae6cfa..6fc8388 100644
--- a/services/audiopolicy/manager/Android.mk
+++ b/services/audiopolicy/manager/Android.mk
@@ -24,6 +24,9 @@
 LOCAL_CFLAGS := -Wall -Werror
 
 LOCAL_MODULE:= libaudiopolicymanager
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/../../../NOTICE
 
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/services/audiopolicy/managerdefault/Android.bp b/services/audiopolicy/managerdefault/Android.bp
index 577b42f..5572beb 100644
--- a/services/audiopolicy/managerdefault/Android.bp
+++ b/services/audiopolicy/managerdefault/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_library_shared {
     name: "libaudiopolicymanagerdefault",
 
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index a592dea..5a042bd 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -29,29 +29,25 @@
 #define ALOGVV(a...) do { } while(0)
 #endif
 
-#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
-#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
-#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
-        "audio_policy_configuration_a2dp_offload_disabled.xml"
-#define AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME \
-        "audio_policy_configuration_bluetooth_legacy_hal.xml"
-
 #include <algorithm>
 #include <inttypes.h>
 #include <math.h>
 #include <set>
 #include <unordered_set>
 #include <vector>
+
+#include <Serializer.h>
+#include <cutils/bitops.h>
 #include <cutils/properties.h>
-#include <utils/Log.h>
 #include <media/AudioParameter.h>
+#include <policy.h>
 #include <private/android_filesystem_config.h>
 #include <system/audio.h>
 #include <system/audio_config.h>
+#include <utils/Log.h>
+
 #include "AudioPolicyManager.h"
-#include <Serializer.h>
 #include "TypeConverter.h"
-#include <policy.h>
 
 namespace android {
 
@@ -64,11 +60,11 @@
 constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
 
 // Compressed formats for MSD module, ordered from most preferred to least preferred.
-static const std::vector<audio_format_t> compressedFormatsOrder = {{
-        AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
+static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
+        AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
         AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
 // Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
-static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
+static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
         AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
         AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
         AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
@@ -246,6 +242,7 @@
                     if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
                             (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
                                 (desc->mDirectOpenCount == 0))) {
+                        clearAudioSourcesForOutput(output);
                         closeOutput(output);
                     }
                 }
@@ -356,7 +353,11 @@
             DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
             updateCallRouting(newDevices);
         }
-
+        // Reconnect Audio Source
+        for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
+            auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
+            checkAudioSourceForAttributes(attributes);
+        }
         if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
             cleanUpForDevice(device);
         }
@@ -441,7 +442,7 @@
     // Case 1: A2DP active device switches from primary to primary
     // module
     // Case 2: A2DP device config changes on primary module.
-    if (audio_is_a2dp_out_device(device)) {
+    if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
         sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
         audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
         if (availablePrimaryOutputDevices().contains(devDesc) &&
@@ -461,7 +462,16 @@
             }
         }
     }
-
+    auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
+    for (size_t i = 0; i < mOutputs.size(); i++) {
+       sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
+       // mute media strategies and delay device switch by the largest
+       // This avoid sending the music tail into the earpiece or headset.
+       setStrategyMute(musicStrategy, true, desc);
+       setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
+          mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
+                                              nullptr, true /*fromCache*/).types());
+    }
     // Toggle the device state: UNAVAILABLE -> AVAILABLE
     // This will force reading again the device configuration
     status = setDeviceConnectionState(device,
@@ -526,11 +536,7 @@
     ALOGV("updateCallRouting device rxDevice %s txDevice %s",
           rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
 
-    // release existing RX patch if any
-    if (mCallRxPatch != 0) {
-        releaseAudioPatchInternal(mCallRxPatch->getHandle());
-        mCallRxPatch.clear();
-    }
+    disconnectTelephonyRxAudioSource();
     // release TX patch if any
     if (mCallTxPatch != 0) {
         releaseAudioPatchInternal(mCallTxPatch->getHandle());
@@ -578,8 +584,7 @@
     if (!createRxPatch) {
         muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
     } else { // create RX path audio patch
-        mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
-
+        connectTelephonyRxAudioSource();
         // If the TX device is on the primary HW module but RX device is
         // on other HW module, SinkMetaData of telephony input should handle it
         // assuming the device uses audio HAL V5.0 and above
@@ -642,6 +647,24 @@
     return false;
 }
 
+void AudioPolicyManager::connectTelephonyRxAudioSource()
+{
+    disconnectTelephonyRxAudioSource();
+    const struct audio_port_config source = {
+        .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
+        .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
+    };
+    const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
+    status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
+    ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
+}
+
+void AudioPolicyManager::disconnectTelephonyRxAudioSource()
+{
+    stopAudioSource(mCallRxSourceClientPort);
+    mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
+}
+
 void AudioPolicyManager::setPhoneState(audio_mode_t state)
 {
     ALOGV("setPhoneState() state %d", state);
@@ -709,10 +732,7 @@
         if (state == AUDIO_MODE_IN_CALL) {
             updateCallRouting(rxDevices, delayMs);
         } else if (oldState == AUDIO_MODE_IN_CALL) {
-            if (mCallRxPatch != 0) {
-                releaseAudioPatchInternal(mCallRxPatch->getHandle());
-                mCallRxPatch.clear();
-            }
+            disconnectTelephonyRxAudioSource();
             if (mCallTxPatch != 0) {
                 releaseAudioPatchInternal(mCallTxPatch->getHandle());
                 mCallTxPatch.clear();
@@ -780,16 +800,7 @@
     }
 
     updateCallAndOutputRouting(forceVolumeReeval, delayMs);
-
-    for (const auto& activeDesc : mInputs.getActiveInputs()) {
-        auto newDevice = getNewInputDevice(activeDesc);
-        // Force new input selection if the new device can not be reached via current input
-        if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
-            setInputDevice(activeDesc->mIoHandle, newDevice);
-        } else {
-            closeInput(activeDesc->mIoHandle);
-        }
-    }
+    updateInputRouting();
 }
 
 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
@@ -893,7 +904,8 @@
     // Only honor audibility enforced when required. The client will be
     // forced to reconnect if the forced usage changes.
     if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
-        dstAttr->flags &= ~AUDIO_FLAG_AUDIBILITY_ENFORCED;
+        dstAttr->flags = static_cast<audio_flags_mask_t>(
+                dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
     }
 
     return NO_ERROR;
@@ -925,7 +937,7 @@
         return status;
     }
     if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
-        resultAttr->flags |= it->second;
+        resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
     }
     *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
 
@@ -1020,11 +1032,9 @@
     *output = AUDIO_IO_HANDLE_NONE;
     if (!msdDevices.isEmpty()) {
         *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
-        sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
-        if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
+        if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
             ALOGV("%s() Using MSD devices %s instead of devices %s",
                   __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
-            outputDevices = msdDevices;
         } else {
             *output = AUDIO_IO_HANDLE_NONE;
         }
@@ -1038,6 +1048,12 @@
     }
 
     *selectedDeviceId = getFirstDeviceId(outputDevices);
+    for (auto &outputDevice : outputDevices) {
+        if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
+            *selectedDeviceId = outputDevice->getId();
+            break;
+        }
+    }
 
     if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
         *outputType = API_OUTPUT_TELEPHONY_TX;
@@ -1180,24 +1196,9 @@
     sp<SwAudioOutputDescriptor> outputDesc =
             new SwAudioOutputDescriptor(profile, mpClientInterface);
 
-    String8 address = getFirstDeviceAddress(devices);
-
-    // MSD patch may be using the only output stream that can service this request. Release
-    // MSD patch to prioritize this request over any active output on MSD.
-    AudioPatchCollection msdPatches = getMsdPatches();
-    for (size_t i = 0; i < msdPatches.size(); i++) {
-        const auto& patch = msdPatches[i];
-        for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
-            const struct audio_port_config *sink = &patch->mPatch.sinks[j];
-            if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
-                    devices.containsDeviceWithType(sink->ext.device.type) &&
-                    (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
-                            AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
-                releaseAudioPatch(patch->getHandle(), mUidCached);
-                break;
-            }
-        }
-    }
+    // An MSD patch may be using the only output stream that can service this request. Release
+    // all MSD patches to prioritize this request over any active output on MSD.
+    releaseMsdOutputPatches(devices);
 
     status_t status = outputDesc->open(config, devices, stream, flags, output);
 
@@ -1243,7 +1244,8 @@
 
     // Discard haptic channel mask when forcing muting haptic channels.
     audio_channel_mask_t channelMask = forceMutingHaptic
-            ? (config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL) : config->channel_mask;
+            ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
+            : config->channel_mask;
 
     // open a direct output if required by specified parameters
     //force direct flag if offload flag is set: offloading implies a direct output stream
@@ -1319,7 +1321,7 @@
                                                         mAvailableOutputDevices);
 }
 
-const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
+const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
     AudioPatchCollection msdPatches;
     sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
     if (msdModule != 0) {
@@ -1337,49 +1339,47 @@
     return msdPatches;
 }
 
-status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
-        bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
-{
-    sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
-    if (msdModule == nullptr) {
-        ALOGE("%s() unable to get MSD module", __func__);
-        return NO_INIT;
-    }
-    sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
-    if (deviceModule == nullptr) {
-        ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
-        return NO_INIT;
-    }
-    const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
+status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
+                                            const InputProfileCollection &inputProfiles,
+                                            const OutputProfileCollection &outputProfiles,
+                                            const sp<DeviceDescriptor> &sourceDevice,
+                                            const sp<DeviceDescriptor> &sinkDevice,
+                                            AudioProfileVector& sourceProfiles,
+                                            AudioProfileVector& sinkProfiles) const {
     if (inputProfiles.isEmpty()) {
-        ALOGE("%s() no input profiles for MSD module", __func__);
+        ALOGE("%s() no input profiles for source module", __func__);
         return NO_INIT;
     }
-    const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
     if (outputProfiles.isEmpty()) {
-        ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
+        ALOGE("%s() no output profiles for sink module", __func__);
         return NO_INIT;
     }
-    AudioProfileVector msdProfiles;
-    // Each IOProfile represents a MixPort from audio_policy_configuration.xml
     for (const auto &inProfile : inputProfiles) {
-        if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
-            appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
+        if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
+                inProfile->supportsDevice(sourceDevice)) {
+            appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
         }
     }
-    AudioProfileVector deviceProfiles;
     for (const auto &outProfile : outputProfiles) {
-        if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
-            appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
+        if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
+                outProfile->supportsDevice(sinkDevice)) {
+            appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
         }
     }
+    return NO_ERROR;
+}
+
+status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
+        const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
+        audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
+{
     struct audio_config_base bestSinkConfig;
-    status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
-            compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
-            bestSinkConfig);
+    status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
+            msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
+            true /*preferHigherSamplingRates*/, bestSinkConfig);
     if (result != NO_ERROR) {
-        ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
-                __func__, outputDevice->toString().c_str(), hwAvSync);
+        ALOGD("%s() no matching config found for sink, hwAvSync: %d",
+                __func__, hwAvSync);
         return result;
     }
     sinkConfig->sample_rate = bestSinkConfig.sample_rate;
@@ -1390,7 +1390,7 @@
             sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
     if (audio_is_iec61937_compatible(sinkConfig->format)) {
         // For formats compatible with IEC61937 encapsulation, assume that
-        // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
+        // the input is IEC61937 framed (for proportional buffer sizing).
         // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
         // raw and IEC61937 framed streams.
         sinkConfig->flags.output = static_cast<audio_output_flags_t>(
@@ -1416,61 +1416,128 @@
     return NO_ERROR;
 }
 
-PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
+PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
+                                               const sp<DeviceDescriptor> &device) const
 {
     PatchBuilder patchBuilder;
-    patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
+    sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
+    ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
+    sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
+    if (deviceModule == nullptr) {
+        ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
+        return patchBuilder;
+    }
+    const InputProfileCollection inputProfiles = msdIsSource ?
+            msdModule->getInputProfiles() : deviceModule->getInputProfiles();
+    const OutputProfileCollection outputProfiles = msdIsSource ?
+            deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
+
+    const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
+    const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
+            device : getMsdAudioOutDevices().itemAt(0);
+    patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
+
     audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
     audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
+    AudioProfileVector sourceProfiles;
+    AudioProfileVector sinkProfiles;
     // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
     // For now, we just forcefully try with HwAvSync first.
-    status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
-            &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
-            getBestMsdAudioProfileFor(
-                    outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
-    if (res == NO_ERROR) {
-        // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
-        return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
+    for (auto hwAvSync : { true, false }) {
+        if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
+                sourceProfiles, sinkProfiles) != NO_ERROR) {
+            continue;
+        }
+        if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
+                &sinkConfig) == NO_ERROR) {
+            // Found a matching config. Re-create PatchBuilder with this config.
+            return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
+        }
     }
-    ALOGV("%s() no matching profile found. Fall through to default PCM patch"
+    ALOGV("%s() no matching config found. Fall through to default PCM patch"
             " supporting PCM format conversion.", __func__);
     return patchBuilder;
 }
 
-status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
-    sp<DeviceDescriptor> device = outputDevice;
-    if (device == nullptr) {
+status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
+    DeviceVector devices;
+    if (outputDevices != nullptr && outputDevices->size() > 0) {
+        devices.add(*outputDevices);
+    } else {
         // Use media strategy for unspecified output device. This should only
         // occur on checkForDeviceAndOutputChanges(). Device connection events may
         // therefore invalidate explicit routing requests.
-        DeviceVector devices = mEngine->getOutputDevicesForAttributes(
+        devices = mEngine->getOutputDevicesForAttributes(
                     attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
-        LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
-        device = devices.itemAt(0);
+        LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
     }
-    ALOGV("%s() for device %s", __func__, device->toString().c_str());
-    PatchBuilder patchBuilder = buildMsdPatch(device);
-    const struct audio_patch* patch = patchBuilder.patch();
-    const AudioPatchCollection msdPatches = getMsdPatches();
-    if (!msdPatches.isEmpty()) {
-        LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
-                "The current MSD prototype only supports one output patch");
-        sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
-        if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
-            return NO_ERROR;
+    std::vector<PatchBuilder> patchesToCreate;
+    for (auto i = 0u; i < devices.size(); ++i) {
+        ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
+        patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
+    }
+    // Retain only the MSD patches associated with outputDevices request.
+    // Tear down the others, and create new ones as needed.
+    AudioPatchCollection patchesToRemove = getMsdOutputPatches();
+    for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
+        auto retainedPatch = false;
+        for (auto i = 0u; i < patchesToRemove.size(); ++i) {
+            if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
+                patchesToRemove.removeItemsAt(i);
+                retainedPatch = true;
+                break;
+            }
         }
+        if (retainedPatch) {
+            it = patchesToCreate.erase(it);
+            continue;
+        }
+        ++it;
+    }
+    if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
+        return NO_ERROR;
+    }
+    for (auto i = 0u; i < patchesToRemove.size(); ++i) {
+        auto &currentPatch = patchesToRemove.valueAt(i);
         releaseAudioPatch(currentPatch->getHandle(), mUidCached);
     }
-    status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
-            patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
-    ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
-    ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
-           "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
-             device->toString().c_str(), patch->sources[0].format,
-             patch->sources[0].channel_mask, patch->sources[0].sample_rate);
+    status_t status = NO_ERROR;
+    for (const auto &p : patchesToCreate) {
+        auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
+                p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
+        char message[256];
+        snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
+            "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
+                currStatus == NO_ERROR ? "Success" : "Error",
+                p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
+                p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
+        if (currStatus == NO_ERROR) {
+            ALOGD("%s", message);
+        } else {
+            ALOGE("%s", message);
+            if (status == NO_ERROR) {
+                status = currStatus;
+            }
+        }
+    }
     return status;
 }
 
+void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
+    AudioPatchCollection msdPatches = getMsdOutputPatches();
+    for (size_t i = 0; i < msdPatches.size(); i++) {
+        const auto& patch = msdPatches[i];
+        for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
+            const struct audio_port_config *sink = &patch->mPatch.sinks[j];
+            if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
+                    String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
+                releaseAudioPatch(patch->getHandle(), mUidCached);
+                break;
+            }
+        }
+    }
+}
+
 audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
                                                        audio_output_flags_t flags,
                                                        audio_format_t format,
@@ -1765,7 +1832,8 @@
         checkAndSetVolume(curves, client->volumeSource(),
                           curves.getVolumeIndex(outputDesc->devices().types()),
                           outputDesc,
-                          outputDesc->devices().types());
+                          outputDesc->devices().types(), 0 /*delay*/,
+                          outputDesc->useHwGain() /*force*/);
 
         // update the outputs if starting an output with a stream that can affect notification
         // routing
@@ -3083,16 +3151,16 @@
 
 // Returns true if all devices types match the predicate and are supported by one HW module
 bool  AudioPolicyManager::areAllDevicesSupported(
-        const Vector<AudioDeviceTypeAddr>& devices,
+        const AudioDeviceTypeAddrVector& devices,
         std::function<bool(audio_devices_t)> predicate,
         const char *context) {
     for (size_t i = 0; i < devices.size(); i++) {
         sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
-                devices[i].mType, devices[i].mAddress.c_str(), String8(),
+                devices[i].mType, devices[i].getAddress(), String8(),
                 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
         if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
-            ALOGE("%s: device type %#x address %s not supported or not an output device",
-                    context, devices[i].mType, devices[i].mAddress.c_str());
+            ALOGE("%s: device type %#x address %s not supported or not match predicate",
+                    context, devices[i].mType, devices[i].getAddress());
             return false;
         }
     }
@@ -3100,7 +3168,7 @@
 }
 
 status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
-        const Vector<AudioDeviceTypeAddr>& devices) {
+        const AudioDeviceTypeAddrVector& devices) {
     ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
     if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
         return BAD_VALUE;
@@ -3132,25 +3200,35 @@
     return res;
 }
 
-status_t AudioPolicyManager::setPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   const AudioDeviceTypeAddr &device) {
-    ALOGV("%s() strategy=%d device=%08x addr=%s", __FUNCTION__,
-            strategy, device.mType, device.mAddress.c_str());
 
-    Vector<AudioDeviceTypeAddr> devices;
-    devices.add(device);
+status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
+                                                       device_role_t role,
+                                                       const AudioDeviceTypeAddrVector &devices) {
+    ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
+            dumpAudioDeviceTypeAddrVector(devices).c_str());
+
     if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
         return BAD_VALUE;
     }
-    status_t status = mEngine->setPreferredDeviceForStrategy(strategy, device);
+    status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
     if (status != NO_ERROR) {
-        ALOGW("Engine could not set preferred device %08x %s for strategy %d",
-                device.mType, device.mAddress.c_str(), strategy);
+        ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
+                dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
         return status;
     }
 
     checkForDeviceAndOutputChanges();
-    updateCallAndOutputRouting();
+
+    bool forceVolumeReeval = false;
+    // FIXME: workaround for truncated touch sounds
+    // to be removed when the problem is handled by system UI
+    uint32_t delayMs = 0;
+    if (strategy == mCommunnicationStrategy) {
+        forceVolumeReeval = true;
+        delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
+        updateInputRouting();
+    }
+    updateCallAndOutputRouting(forceVolumeReeval, delayMs);
 
     return NO_ERROR;
 }
@@ -3181,30 +3259,124 @@
     }
 }
 
-status_t AudioPolicyManager::removePreferredDeviceForStrategy(product_strategy_t strategy)
-{
-    ALOGI("%s() strategy=%d", __FUNCTION__, strategy);
+void AudioPolicyManager::updateInputRouting() {
+    for (const auto& activeDesc : mInputs.getActiveInputs()) {
+        auto newDevice = getNewInputDevice(activeDesc);
+        // Force new input selection if the new device can not be reached via current input
+        if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
+            setInputDevice(activeDesc->mIoHandle, newDevice);
+        } else {
+            closeInput(activeDesc->mIoHandle);
+        }
+    }
+}
 
-    status_t status = mEngine->removePreferredDeviceForStrategy(strategy);
+status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
+                                                          device_role_t role)
+{
+    ALOGI("%s() strategy=%d role=%d", __func__, strategy, role);
+
+    status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
     if (status != NO_ERROR) {
-        ALOGW("Engine could not remove preferred device for strategy %d", strategy);
+        ALOGV("Engine could not remove preferred device for strategy %d status %d",
+                strategy, status);
         return status;
     }
 
     checkForDeviceAndOutputChanges();
-    updateCallAndOutputRouting();
+
+    bool forceVolumeReeval = false;
+    // FIXME: workaround for truncated touch sounds
+    // to be removed when the problem is handled by system UI
+    uint32_t delayMs = 0;
+    if (strategy == mCommunnicationStrategy) {
+        forceVolumeReeval = true;
+        delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
+        updateInputRouting();
+    }
+    updateCallAndOutputRouting(forceVolumeReeval, delayMs);
 
     return NO_ERROR;
 }
 
-status_t AudioPolicyManager::getPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   AudioDeviceTypeAddr &device) {
-    return mEngine->getPreferredDeviceForStrategy(strategy, device);
+status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
+                                                          device_role_t role,
+                                                          AudioDeviceTypeAddrVector &devices) {
+    return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
+}
+
+status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
+        audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
+    ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
+            dumpAudioDeviceTypeAddrVector(devices).c_str());
+
+    if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
+        return BAD_VALUE;
+    }
+    status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
+    ALOGW_IF(status != NO_ERROR,
+            "Engine could not set preferred devices %s for audio source %d role %d",
+            dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
+
+    return status;
+}
+
+status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
+        audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
+    ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
+            dumpAudioDeviceTypeAddrVector(devices).c_str());
+
+    if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
+        return BAD_VALUE;
+    }
+    status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
+    ALOGW_IF(status != NO_ERROR,
+            "Engine could not add preferred devices %s for audio source %d role %d",
+            dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
+
+    updateInputRouting();
+    return status;
+}
+
+status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
+        audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
+{
+    ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
+            dumpAudioDeviceTypeAddrVector(devices).c_str());
+
+    if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
+        return BAD_VALUE;
+    }
+
+    status_t status = mEngine->removeDevicesRoleForCapturePreset(
+            audioSource, role, devices);
+    ALOGW_IF(status != NO_ERROR,
+            "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
+
+    updateInputRouting();
+    return status;
+}
+
+status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                              device_role_t role) {
+    ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
+
+    status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
+    ALOGW_IF(status != NO_ERROR,
+            "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
+
+    updateInputRouting();
+    return status;
+}
+
+status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
+        audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
+    return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
 }
 
 status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
-        const Vector<AudioDeviceTypeAddr>& devices) {
-    ALOGI("%s() userId=%d num devices %zu", __FUNCTION__, userId, devices.size());\
+        const AudioDeviceTypeAddrVector& devices) {
+    ALOGI("%s() userId=%d num devices %zu", __func__, userId, devices.size());
     if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
         return BAD_VALUE;
     }
@@ -3263,7 +3435,9 @@
     }
     dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
     dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
+    dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
     dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
+
     mAvailableOutputDevices.dump(dst, String8("Available output"));
     mAvailableInputDevices.dump(dst, String8("Available input"));
     mHwModulesAll.dump(dst);
@@ -3669,6 +3843,15 @@
             // be incomplete.
             PatchBuilder patchBuilder;
             audio_port_config sourcePortConfig = {};
+
+            // if first sink is to MSD, establish single MSD patch
+            if (getMsdAudioOutDevices().contains(
+                        mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
+                ALOGV("%s patching to MSD", __FUNCTION__);
+                patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
+                goto installPatch;
+            }
+
             srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
             patchBuilder.addSource(sourcePortConfig);
 
@@ -3686,6 +3869,41 @@
                 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
                 patchBuilder.addSink(sinkPortConfig);
 
+                // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
+                // volume management purpose (tracking activity)
+                // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
+                // in config XML to reach the sink so that is can be declared as available.
+                audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
+                sp<SwAudioOutputDescriptor> outputDesc = nullptr;
+                if (sourceDesc != nullptr) {
+                    // take care of dynamic routing for SwOutput selection,
+                    audio_attributes_t attributes = sourceDesc->attributes();
+                    audio_stream_type_t stream = sourceDesc->stream();
+                    audio_attributes_t resultAttr;
+                    audio_config_t config = AUDIO_CONFIG_INITIALIZER;
+                    config.sample_rate = sourceDesc->config().sample_rate;
+                    config.channel_mask = sourceDesc->config().channel_mask;
+                    config.format = sourceDesc->config().format;
+                    audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
+                    audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
+                    bool isRequestedDeviceForExclusiveUse = false;
+                    output_type_t outputType;
+                    getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
+                                        &stream, sourceDesc->uid(), &config, &flags,
+                                        &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
+                                        nullptr, &outputType);
+                    if (output == AUDIO_IO_HANDLE_NONE) {
+                        ALOGV("%s no output for device %s",
+                              __FUNCTION__, sinkDevice->toString().c_str());
+                        return INVALID_OPERATION;
+                    }
+                    outputDesc = mOutputs.valueFor(output);
+                    if (outputDesc->isDuplicated()) {
+                        ALOGE("%s output is duplicated", __func__);
+                        return INVALID_OPERATION;
+                    }
+                    sourceDesc->setSwOutput(outputDesc);
+                }
                 // create a software bridge in PatchPanel if:
                 // - source and sink devices are on different HW modules OR
                 // - audio HAL version is < 3.0
@@ -3701,49 +3919,25 @@
                     if (patch->num_sinks > 1) {
                         return INVALID_OPERATION;
                     }
-                    audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
-                    if (sourceDesc != nullptr) {
-                        // take care of dynamic routing for SwOutput selection,
-                        audio_attributes_t attributes = sourceDesc->attributes();
-                        audio_stream_type_t stream = sourceDesc->stream();
-                        audio_attributes_t resultAttr;
-                        audio_config_t config = AUDIO_CONFIG_INITIALIZER;
-                        config.sample_rate = sourceDesc->config().sample_rate;
-                        config.channel_mask = sourceDesc->config().channel_mask;
-                        config.format = sourceDesc->config().format;
-                        audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
-                        audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
-                        bool isRequestedDeviceForExclusiveUse = false;
-                        output_type_t outputType;
-                        getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
-                                            &stream, sourceDesc->uid(), &config, &flags,
-                                            &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
-                                            nullptr, &outputType);
-                        if (output == AUDIO_IO_HANDLE_NONE) {
-                            ALOGV("%s no output for device %s",
-                                  __FUNCTION__, sinkDevice->toString().c_str());
-                            return INVALID_OPERATION;
-                        }
-                    } else {
+                    if (sourceDesc == nullptr) {
                         SortedVector<audio_io_handle_t> outputs =
                                 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
                         // if the sink device is reachable via an opened output stream, request to
                         // go via this output stream by adding a second source to the patch
                         // description
                         output = selectOutput(outputs);
-                    }
-                    if (output != AUDIO_IO_HANDLE_NONE) {
-                        sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
-                        if (outputDesc->isDuplicated()) {
-                            ALOGV("%s output for device %s is duplicated",
-                                  __FUNCTION__, sinkDevice->toString().c_str());
-                            return INVALID_OPERATION;
+                        if (output != AUDIO_IO_HANDLE_NONE) {
+                            outputDesc = mOutputs.valueFor(output);
+                            if (outputDesc->isDuplicated()) {
+                                ALOGV("%s output for device %s is duplicated",
+                                      __FUNCTION__, sinkDevice->toString().c_str());
+                                return INVALID_OPERATION;
+                            }
                         }
+                    }
+                    if (outputDesc != nullptr) {
                         audio_port_config srcMixPortConfig = {};
                         outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
-                        if (sourceDesc != nullptr) {
-                            sourceDesc->setSwOutput(outputDesc);
-                        }
                         // for volume control, we may need a valid stream
                         srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
                                     sourceDesc->stream() : AUDIO_STREAM_PATCH;
@@ -3753,6 +3947,7 @@
             }
             // TODO: check from routing capabilities in config file and other conflicting patches
 
+installPatch:
             status_t status = installPatch(
                         __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
             if (status != NO_ERROR) {
@@ -3834,8 +4029,9 @@
                 sp<SwAudioOutputDescriptor> outputDesc =
                         mOutputs.getOutputFromId(patch->sources[1].id);
                 if (outputDesc == NULL) {
-                    ALOGE("%s output not found for id %d", __func__, patch->sources[0].id);
-                    return BAD_VALUE;
+                    ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
+                    // releaseOutput has already called closeOuput in case of direct output
+                    return NO_ERROR;
                 }
                 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
                     // force SwOutput patch removal as AF counter part patch has already gone.
@@ -4101,15 +4297,19 @@
     disconnectAudioSource(sourceDesc);
 
     audio_attributes_t attributes = sourceDesc->attributes();
-    sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
-
+    // May the device (dynamic) have been disconnected/reconnected, id has changed.
+    sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
+                sourceDesc->srcDevice()->type(),
+                String8(sourceDesc->srcDevice()->address().c_str()),
+                AUDIO_FORMAT_DEFAULT);
     DeviceVector sinkDevices =
-            mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
+            mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
     ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
     sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
-    ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
-                __FUNCTION__, sinkDevice->toString().c_str());
-
+    if (!mAvailableOutputDevices.contains(sinkDevice)) {
+        ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
+        return INVALID_OPERATION;
+    }
     PatchBuilder patchBuilder;
     patchBuilder.addSink(sinkDevice).addSource(srcDevice);
     audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
@@ -4119,7 +4319,7 @@
         ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
         return INVALID_OPERATION;
     }
-    sourceDesc->setPatchHandle(handle);
+    sourceDesc->connect(handle, sinkDevice);
     // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
     sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
     if (swOutput != 0) {
@@ -4402,6 +4602,10 @@
 status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
 {
     ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
+    if (!sourceDesc->isConnected()) {
+        ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
+        return NO_ERROR;
+    }
     sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
     if (swOutput != 0) {
         status_t status = stopSource(swOutput, sourceDesc);
@@ -4417,7 +4621,9 @@
             ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
         }
     }
-    return releaseAudioPatchInternal(sourceDesc->getPatchHandle());
+    status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
+    sourceDesc->disconnect();
+    return status;
 }
 
 sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
@@ -4445,37 +4651,15 @@
 }
 
 static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
-    char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
-    std::vector<const char*> fileNames;
-    status_t ret;
-
-    if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false)) {
-        if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false) &&
-            property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
-            // Both BluetoothAudio@2.0 and BluetoothA2dp@1.0 (Offlaod) are disabled, and uses
-            // the legacy hardware module for A2DP and hearing aid.
-            fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
-        } else if (property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
-            // A2DP offload supported but disabled: try to use special XML file
-            fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
+    if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
+            !audioPolicyXmlConfigFile.empty()) {
+        status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
+        if (ret == NO_ERROR) {
+            config.setSource(audioPolicyXmlConfigFile);
         }
-    } else if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false)) {
-        fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
+        return ret;
     }
-    fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
-
-    for (const char* fileName : fileNames) {
-        for (const auto& path : audio_get_configuration_paths()) {
-            snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
-                     "%s/%s", path.c_str(), fileName);
-            ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
-            if (ret == NO_ERROR) {
-                config.setSource(audioPolicyXmlConfigFile);
-                return ret;
-            }
-        }
-    }
-    return ret;
+    return BAD_VALUE;
 }
 
 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
@@ -4551,14 +4735,14 @@
         }
     }
 
-    if (mPrimaryOutput == 0) {
-        ALOGE("Failed to open primary output");
-        status = NO_INIT;
-    }
+    ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
 
     // Silence ALOGV statements
     property_set("log.tag." LOG_TAG, "D");
 
+    mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
+            mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
+
     updateDevicesAndOutputs();
     return status;
 }
@@ -4664,7 +4848,7 @@
                     setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
                 }
             }
-            if (mPrimaryOutput == 0 &&
+            if (mPrimaryOutput == nullptr &&
                     outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
                 mPrimaryOutput = outputDesc;
             }
@@ -4741,6 +4925,10 @@
 
 void AudioPolicyManager::removeOutput(audio_io_handle_t output)
 {
+    if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
+        ALOGV("%s: removing primary output", __func__);
+        mPrimaryOutput = nullptr;
+    }
     mOutputs.removeItem(output);
     selectOutputForMusicEffects();
 }
@@ -4899,6 +5087,11 @@
                             output = AUDIO_IO_HANDLE_NONE;
                         }
                     }
+                    if (mPrimaryOutput == nullptr
+		            && (profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
+                        ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
+                        mPrimaryOutput = desc;
+                    }
                 }
             } else {
                 output = AUDIO_IO_HANDLE_NONE;
@@ -5154,8 +5347,13 @@
             }
         }
         if (!directOutputOpen) {
-            ALOGV("no direct outputs open, reset MSD patch");
-            setMsdPatch();
+            ALOGV("no direct outputs open, reset MSD patches");
+            // TODO: The MSD patches to be established here may differ to current MSD patches due to
+            // how output devices for patching are resolved. Avoid by caching and reusing the
+            // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
+            // devices to patch to. This may be complicated by the fact that devices may become
+            // unavailable.
+            setMsdOutputPatches();
         }
     }
 }
@@ -5222,7 +5420,13 @@
     if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
     updateDevicesAndOutputs();
     if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
-        setMsdPatch();
+        // TODO: The MSD patches to be established here may differ to current MSD patches due to how
+        // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
+        // configuration changes will ultimately be rerouted correctly. We can still avoid
+        // unnecessary rerouting by caching and reusing the arguments to
+        // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
+        // This may be complicated by the fact that devices may become unavailable.
+        setMsdOutputPatches();
     }
 }
 
@@ -5233,6 +5437,29 @@
             mEngine->getProductStrategyForAttributes(rAttr);
 }
 
+void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
+{
+    for (size_t i = 0; i < mAudioSources.size(); i++)  {
+        sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
+        if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
+                && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
+                && !isCallRxAudioSource(sourceDesc)) {
+            connectAudioSource(sourceDesc);
+        }
+    }
+}
+
+void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
+{
+    for (size_t i = 0; i < mAudioSources.size(); i++)  {
+        sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
+        if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
+                && sourceDesc->swOutput().promote()->mIoHandle == output) {
+            disconnectAudioSource(sourceDesc);
+        }
+    }
+}
+
 void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
 {
     auto psId = mEngine->getProductStrategyForAttributes(attr);
@@ -5328,7 +5555,7 @@
                                 newDevices.types());
             }
             sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
-            if (source != 0){
+            if (source != nullptr && !isCallRxAudioSource(source)) {
                 connectAudioSource(source);
             }
         }
@@ -5351,6 +5578,7 @@
     for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
         auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
         checkOutputForAttributes(attributes);
+        checkAudioSourceForAttributes(attributes);
     }
 }
 
@@ -5386,6 +5614,17 @@
     }
 }
 
+bool AudioPolicyManager::isScoRequestedForComm() const {
+    AudioDeviceTypeAddrVector devices;
+    mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
+    for (const auto &device : devices) {
+        if (audio_is_bluetooth_out_sco_device(device.mType)) {
+            return true;
+        }
+    }
+    return false;
+}
+
 void AudioPolicyManager::checkA2dpSuspend()
 {
     audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
@@ -5397,23 +5636,21 @@
     bool isScoConnected =
             (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
              !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
+    bool isScoRequested = isScoRequestedForComm();
 
     // if suspended, restore A2DP output if:
     //      ((SCO device is NOT connected) ||
-    //       ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
+    //       ((SCO is not requested) &&
     //        (phone state is NOT in call) && (phone state is NOT ringing)))
     //
     // if not suspended, suspend A2DP output if:
     //      (SCO device is connected) &&
-    //       ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
+    //       ((SCO is requested) ||
     //       ((phone state is in call) || (phone state is ringing)))
     //
     if (mA2dpSuspended) {
         if (!isScoConnected ||
-             ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
-                     AUDIO_POLICY_FORCE_BT_SCO) &&
-              (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
-                      AUDIO_POLICY_FORCE_BT_SCO) &&
+             (!isScoRequested &&
               (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
               (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
 
@@ -5422,10 +5659,7 @@
         }
     } else {
         if (isScoConnected &&
-             ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
-                     AUDIO_POLICY_FORCE_BT_SCO) ||
-              (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
-                      AUDIO_POLICY_FORCE_BT_SCO) ||
+             (isScoRequested ||
               (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
               (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
 
@@ -5450,6 +5684,12 @@
         }
     }
 
+    // Do not retrieve engine device for outputs through MSD
+    // TODO: support explicit routing requests by resetting MSD patch to engine device.
+    if (outputDesc->devices() == getMsdAudioOutDevices()) {
+        return outputDesc->devices();
+    }
+
     // Honor explicit routing requests only if no client using default routing is active on this
     // input: a specific app can not force routing for other apps by setting a preferred device.
     bool active; // unused
@@ -5537,8 +5777,8 @@
     }
     DeviceVector activeDevices;
     DeviceVector devices;
-    for (audio_stream_type_t curStream = AUDIO_STREAM_MIN; curStream < AUDIO_STREAM_PUBLIC_CNT;
-         curStream = (audio_stream_type_t) (curStream + 1)) {
+    for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
+        const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
         if (!streamsMatchForvolume(stream, curStream)) {
             continue;
         }
@@ -6035,7 +6275,8 @@
     if (!Intersection(deviceTypes,
             {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
              AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
-             AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID}).empty() &&
+             AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
+             AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
             ((volumeSource == alarmVolumeSrc ||
               volumeSource == ringVolumeSrc) ||
              (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
@@ -6130,16 +6371,17 @@
     bool isVoiceVolSrc = callVolSrc == volumeSource;
     bool isBtScoVolSrc = btScoVolSrc == volumeSource;
 
-    audio_policy_forced_cfg_t forceUseForComm =
-            mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
+    bool isScoRequested = isScoRequestedForComm();
     // do not change in call volume if bluetooth is connected and vice versa
     // if sco and call follow same curves, bypass forceUseForComm
     if ((callVolSrc != btScoVolSrc) &&
-            ((isVoiceVolSrc && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
-             (isBtScoVolSrc && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO))) {
-        ALOGV("%s cannot set volume group %d volume with force use = %d for comm", __func__,
-             volumeSource, forceUseForComm);
-        return INVALID_OPERATION;
+            ((isVoiceVolSrc && isScoRequested) ||
+             (isBtScoVolSrc && !isScoRequested))) {
+        ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
+             volumeSource, isScoRequested ? " " : "n ot ");
+        // Do not return an error here as AudioService will always set both voice call
+        // and bluetooth SCO volumes due to stream aliasing.
+        return NO_ERROR;
     }
     if (deviceTypes.empty()) {
         deviceTypes = outputDesc->devices().types();
@@ -6308,9 +6550,10 @@
 {
     for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--)  {
         sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
-        if (sourceDesc->srcDevice()->equals(deviceDesc)) {
-            ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
-            stopAudioSource(sourceDesc->portId());
+        if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
+                                          sourceDesc->sinkDevice()->equals(deviceDesc))
+                && !isCallRxAudioSource(sourceDesc)) {
+            disconnectAudioSource(sourceDesc);
         }
     }
 
@@ -6324,10 +6567,14 @@
                 release = true;
             }
         }
+        const char *address = deviceDesc->address().c_str();
         for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++)  {
             const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
             if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
-                    sink->ext.device.type == deviceDesc->type()) {
+                    sink->ext.device.type == deviceDesc->type() &&
+                    (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
+                     || strncmp(sink->ext.device.address, address,
+                                 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
                 release = true;
             }
         }
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h
index b588f89..ed5be5e 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.h
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h
@@ -263,17 +263,42 @@
         virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes);
         virtual status_t unregisterPolicyMixes(Vector<AudioMix> mixes);
         virtual status_t setUidDeviceAffinities(uid_t uid,
-                const Vector<AudioDeviceTypeAddr>& devices);
+                const AudioDeviceTypeAddrVector& devices);
         virtual status_t removeUidDeviceAffinities(uid_t uid);
         virtual status_t setUserIdDeviceAffinities(int userId,
-                const Vector<AudioDeviceTypeAddr>& devices);
+                const AudioDeviceTypeAddrVector& devices);
         virtual status_t removeUserIdDeviceAffinities(int userId);
 
-        virtual status_t setPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   const AudioDeviceTypeAddr &device);
-        virtual status_t removePreferredDeviceForStrategy(product_strategy_t strategy);
-        virtual status_t getPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   AudioDeviceTypeAddr &device);
+        virtual status_t setDevicesRoleForStrategy(product_strategy_t strategy,
+                                                   device_role_t role,
+                                                   const AudioDeviceTypeAddrVector &devices);
+
+        virtual status_t removeDevicesRoleForStrategy(product_strategy_t strategy,
+                                                      device_role_t role);
+
+
+        virtual status_t getDevicesForRoleAndStrategy(product_strategy_t strategy,
+                                                      device_role_t role,
+                                                      AudioDeviceTypeAddrVector &devices);
+
+        virtual status_t setDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                        device_role_t role,
+                                                        const AudioDeviceTypeAddrVector &devices);
+
+        virtual status_t addDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                        device_role_t role,
+                                                        const AudioDeviceTypeAddrVector &devices);
+
+        virtual status_t removeDevicesRoleForCapturePreset(
+                audio_source_t audioSource, device_role_t role,
+                const AudioDeviceTypeAddrVector& devices);
+
+        virtual status_t clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                          device_role_t role);
+
+        virtual status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+                                                           device_role_t role,
+                                                           AudioDeviceTypeAddrVector &devices);
 
         virtual status_t startAudioSource(const struct audio_port_config *source,
                                           const audio_attributes_t *attributes,
@@ -531,6 +556,20 @@
          */
         void updateCallAndOutputRouting(bool forceVolumeReeval = true, uint32_t delayMs = 0);
 
+        bool isCallRxAudioSource(const sp<SourceClientDescriptor> &source) {
+            return mCallRxSourceClientPort != AUDIO_PORT_HANDLE_NONE
+                && source == mAudioSources.valueFor(mCallRxSourceClientPort);
+        }
+
+        void connectTelephonyRxAudioSource();
+
+        void disconnectTelephonyRxAudioSource();
+
+        /**
+         * @brief updates routing for all inputs.
+         */
+        void updateInputRouting();
+
         /**
          * @brief checkOutputForAttributes checks and if necessary changes outputs used for the
          * given audio attributes.
@@ -541,6 +580,16 @@
          */
         void checkOutputForAttributes(const audio_attributes_t &attr);
 
+        /**
+         * @brief checkAudioSourceForAttributes checks if any AudioSource following the same routing
+         * as the given audio attributes is not routed and try to connect it.
+         * It must be called once checkOutputForAttributes has been called for orphans AudioSource,
+         * aka AudioSource not attached to any Audio Output (e.g. AudioSource connected to direct
+         * Output which has been disconnected (and output closed) due to sink device unavailable).
+         * @param attr to be considered
+         */
+        void checkAudioSourceForAttributes(const audio_attributes_t &attr);
+
         bool followsSameRouting(const audio_attributes_t &lAttr,
                                 const audio_attributes_t &rAttr) const;
 
@@ -709,6 +758,7 @@
 
         sp<SourceClientDescriptor> getSourceForAttributesOnOutput(audio_io_handle_t output,
                                                                   const audio_attributes_t &attr);
+        void clearAudioSourcesForOutput(audio_io_handle_t output);
 
         void cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc);
 
@@ -755,7 +805,6 @@
         SoundTriggerSessionCollection mSoundTriggerSessions;
 
         sp<AudioPatch> mCallTxPatch;
-        sp<AudioPatch> mCallRxPatch;
 
         HwAudioOutputCollection mHwOutputs;
         SourceClientCollection mAudioSources;
@@ -787,6 +836,33 @@
         std::unordered_set<audio_format_t> mManualSurroundFormats;
 
         std::unordered_map<uid_t, audio_flags_mask_t> mAllowedCapturePolicies;
+
+        // Cached product strategy ID corresponding to legacy strategy STRATEGY_PHONE
+        product_strategy_t mCommunnicationStrategy;
+
+        // The port handle of the hardware audio source created internally for the Call RX audio
+        // end point.
+        audio_port_handle_t mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
+
+        // Support for Multi-Stream Decoder (MSD) module
+        sp<DeviceDescriptor> getMsdAudioInDevice() const;
+        DeviceVector getMsdAudioOutDevices() const;
+        const AudioPatchCollection getMsdOutputPatches() const;
+        status_t getMsdProfiles(bool hwAvSync,
+                const InputProfileCollection &inputProfiles,
+                const OutputProfileCollection &outputProfiles,
+                const sp<DeviceDescriptor> &sourceDevice,
+                const sp<DeviceDescriptor> &sinkDevice,
+                AudioProfileVector &sourceProfiles,
+                AudioProfileVector &sinkProfiles) const;
+        status_t getBestMsdConfig(bool hwAvSync,
+                const AudioProfileVector &sourceProfiles,
+                const AudioProfileVector &sinkProfiles,
+                audio_port_config *sourceConfig,
+                audio_port_config *sinkConfig) const;
+        PatchBuilder buildMsdPatch(bool msdIsSource, const sp<DeviceDescriptor> &device) const;
+        status_t setMsdOutputPatches(const DeviceVector *outputDevices = nullptr);
+        void releaseMsdOutputPatches(const DeviceVector& devices);
 private:
         void onNewAudioModulesAvailableInt(DeviceVector *newDevices);
 
@@ -794,17 +870,6 @@
         void modifySurroundFormats(const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr);
         void modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr);
 
-        // Support for Multi-Stream Decoder (MSD) module
-        sp<DeviceDescriptor> getMsdAudioInDevice() const;
-        DeviceVector getMsdAudioOutDevices() const;
-        const AudioPatchCollection getMsdPatches() const;
-        status_t getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
-                                           bool hwAvSync,
-                                           audio_port_config *sourceConfig,
-                                           audio_port_config *sinkConfig) const;
-        PatchBuilder buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const;
-        status_t setMsdPatch(const sp<DeviceDescriptor> &outputDevice = nullptr);
-
         // If any, resolve any "dynamic" fields of an Audio Profiles collection
         void updateAudioProfiles(const sp<DeviceDescriptor>& devDesc, audio_io_handle_t ioHandle,
                 AudioProfileVector &profiles);
@@ -938,10 +1003,11 @@
                 sp<AudioPatch> *patchDescPtr);
 
         bool areAllDevicesSupported(
-                const Vector<AudioDeviceTypeAddr>& devices,
+                const AudioDeviceTypeAddrVector& devices,
                 std::function<bool(audio_devices_t)> predicate,
                 const char* context);
 
+        bool isScoRequestedForComm() const;
 };
 
 };
diff --git a/services/audiopolicy/service/Android.mk b/services/audiopolicy/service/Android.mk
index 680b077..7015b7b 100644
--- a/services/audiopolicy/service/Android.mk
+++ b/services/audiopolicy/service/Android.mk
@@ -42,9 +42,11 @@
     libaudiopolicycomponents
 
 LOCAL_MODULE:= libaudiopolicyservice
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/../../../NOTICE
 
 LOCAL_CFLAGS += -fvisibility=hidden
 LOCAL_CFLAGS += -Wall -Werror -Wthread-safety
 
 include $(BUILD_SHARED_LIBRARY)
-
diff --git a/services/audiopolicy/service/AudioPolicyEffects.cpp b/services/audiopolicy/service/AudioPolicyEffects.cpp
index b738633..5dac55b 100644
--- a/services/audiopolicy/service/AudioPolicyEffects.cpp
+++ b/services/audiopolicy/service/AudioPolicyEffects.cpp
@@ -970,7 +970,7 @@
     for (const auto& deviceEffectsIter : mDeviceEffects) {
         const auto& deviceEffects =  deviceEffectsIter.second;
         for (const auto& effectDesc : deviceEffects->mEffectDescriptors->mEffects) {
-            auto fx = std::make_unique<AudioEffect>(String16("android"));
+            sp<AudioEffect> fx = new AudioEffect(String16("android"));
             fx->set(EFFECT_UUID_NULL, &effectDesc->mUuid, 0, nullptr,
                     nullptr, AUDIO_SESSION_DEVICE, AUDIO_IO_HANDLE_NONE,
                     AudioDeviceTypeAddr{deviceEffects->getDeviceType(),
@@ -987,7 +987,7 @@
             ALOGV("%s(): create Fx %s added on port type=%d address=%s", __func__,
                   effectDesc->mName, deviceEffects->getDeviceType(),
                   deviceEffects->getDeviceAddress().c_str());
-            deviceEffects->mEffects.push_back(std::move(fx));
+            deviceEffects->mEffects.push_back(fx);
         }
     }
 }
diff --git a/services/audiopolicy/service/AudioPolicyEffects.h b/services/audiopolicy/service/AudioPolicyEffects.h
index 81c728d..13d5d0c 100644
--- a/services/audiopolicy/service/AudioPolicyEffects.h
+++ b/services/audiopolicy/service/AudioPolicyEffects.h
@@ -207,7 +207,7 @@
             mDeviceType(device), mDeviceAddress(address) {}
         /*virtual*/ ~DeviceEffects() = default;
 
-        std::vector<std::unique_ptr<AudioEffect>> mEffects;
+        std::vector< sp<AudioEffect> > mEffects;
         audio_devices_t getDeviceType() const { return mDeviceType; }
         std::string getDeviceAddress() const { return mDeviceAddress; }
         const std::unique_ptr<EffectDescVector> mEffectDescriptors;
diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
index df27f6e..dcd30f6 100644
--- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
+++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
@@ -244,11 +244,12 @@
         uid = callingUid;
     }
     if (!mPackageManager.allowPlaybackCapture(uid)) {
-        attr->flags |= AUDIO_FLAG_NO_MEDIA_PROJECTION;
+        attr->flags = static_cast<audio_flags_mask_t>(attr->flags | AUDIO_FLAG_NO_MEDIA_PROJECTION);
     }
     if (((attr->flags & (AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY|AUDIO_FLAG_BYPASS_MUTE)) != 0)
             && !bypassInterruptionPolicyAllowed(pid, uid)) {
-        attr->flags &= ~(AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY|AUDIO_FLAG_BYPASS_MUTE);
+        attr->flags = static_cast<audio_flags_mask_t>(
+                attr->flags & ~(AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY|AUDIO_FLAG_BYPASS_MUTE));
     }
     AutoCallerClear acc;
     AudioPolicyInterface::output_type_t outputType;
@@ -1260,7 +1261,7 @@
 }
 
 status_t AudioPolicyService::setUidDeviceAffinities(uid_t uid,
-        const Vector<AudioDeviceTypeAddr>& devices) {
+        const AudioDeviceTypeAddrVector& devices) {
     Mutex::Autolock _l(mLock);
     if(!modifyAudioRoutingAllowed()) {
         return PERMISSION_DENIED;
@@ -1285,7 +1286,7 @@
 }
 
 status_t AudioPolicyService::setUserIdDeviceAffinities(int userId,
-        const Vector<AudioDeviceTypeAddr>& devices) {
+        const AudioDeviceTypeAddrVector& devices) {
     Mutex::Autolock _l(mLock);
     if(!modifyAudioRoutingAllowed()) {
         return PERMISSION_DENIED;
@@ -1497,33 +1498,36 @@
     return mAudioPolicyManager->isCallScreenModeSupported();
 }
 
-status_t AudioPolicyService::setPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   const AudioDeviceTypeAddr &device)
+status_t AudioPolicyService::setDevicesRoleForStrategy(product_strategy_t strategy,
+                                                       device_role_t role,
+                                                       const AudioDeviceTypeAddrVector &devices)
 {
     if (mAudioPolicyManager == NULL) {
         return NO_INIT;
     }
     Mutex::Autolock _l(mLock);
-    return mAudioPolicyManager->setPreferredDeviceForStrategy(strategy, device);
+    return mAudioPolicyManager->setDevicesRoleForStrategy(strategy, role, devices);
 }
 
-status_t AudioPolicyService::removePreferredDeviceForStrategy(product_strategy_t strategy)
+status_t AudioPolicyService::removeDevicesRoleForStrategy(product_strategy_t strategy,
+                                                          device_role_t role)
 {
     if (mAudioPolicyManager == NULL) {
         return NO_INIT;
     }
     Mutex::Autolock _l(mLock);
-    return mAudioPolicyManager->removePreferredDeviceForStrategy(strategy);
+    return mAudioPolicyManager->removeDevicesRoleForStrategy(strategy, role);
 }
 
-status_t AudioPolicyService::getPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   AudioDeviceTypeAddr &device)
+status_t AudioPolicyService::getDevicesForRoleAndStrategy(product_strategy_t strategy,
+                                                          device_role_t role,
+                                                          AudioDeviceTypeAddrVector &devices)
 {
     if (mAudioPolicyManager == NULL) {
         return NO_INIT;
     }
     Mutex::Autolock _l(mLock);
-    return mAudioPolicyManager->getPreferredDeviceForStrategy(strategy, device);
+    return mAudioPolicyManager->getDevicesForRoleAndStrategy(strategy, role, devices);
 }
 
 status_t AudioPolicyService::registerSoundTriggerCaptureStateListener(
@@ -1534,4 +1538,55 @@
     return NO_ERROR;
 }
 
+status_t AudioPolicyService::setDevicesRoleForCapturePreset(
+        audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices)
+{
+    if (mAudioPolicyManager == nullptr) {
+        return NO_INIT;
+    }
+    Mutex::Autolock _l(mLock);
+    return mAudioPolicyManager->setDevicesRoleForCapturePreset(audioSource, role, devices);
+}
+
+status_t AudioPolicyService::addDevicesRoleForCapturePreset(
+        audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices)
+{
+    if (mAudioPolicyManager == nullptr) {
+        return NO_INIT;
+    }
+    Mutex::Autolock _l(mLock);
+    return mAudioPolicyManager->addDevicesRoleForCapturePreset(audioSource, role, devices);
+}
+
+status_t AudioPolicyService::removeDevicesRoleForCapturePreset(
+        audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
+{
+    if (mAudioPolicyManager == nullptr) {
+        return NO_INIT;
+    }
+    Mutex::Autolock _l(mLock);
+    return mAudioPolicyManager->removeDevicesRoleForCapturePreset(audioSource, role, devices);
+}
+
+status_t AudioPolicyService::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                              device_role_t role)
+{
+    if (mAudioPolicyManager == nullptr) {
+        return NO_INIT;
+    }
+    Mutex::Autolock _l(mLock);
+    return mAudioPolicyManager->clearDevicesRoleForCapturePreset(audioSource, role);
+}
+
+status_t AudioPolicyService::getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+                                                               device_role_t role,
+                                                               AudioDeviceTypeAddrVector &devices)
+{
+    if (mAudioPolicyManager == nullptr) {
+        return NO_INIT;
+    }
+    Mutex::Autolock _l(mLock);
+    return mAudioPolicyManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
+}
+
 } // namespace android
diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h
index 869a963..0b218c2 100644
--- a/services/audiopolicy/service/AudioPolicyService.h
+++ b/services/audiopolicy/service/AudioPolicyService.h
@@ -226,19 +226,41 @@
 
     virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes, bool registration);
 
-    virtual status_t setUidDeviceAffinities(uid_t uid, const Vector<AudioDeviceTypeAddr>& devices);
+    virtual status_t setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAddrVector& devices);
 
     virtual status_t removeUidDeviceAffinities(uid_t uid);
 
-    virtual status_t setPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   const AudioDeviceTypeAddr &device);
+    virtual status_t setDevicesRoleForStrategy(product_strategy_t strategy,
+                                               device_role_t role,
+                                               const AudioDeviceTypeAddrVector &devices);
 
-    virtual status_t removePreferredDeviceForStrategy(product_strategy_t strategy);
+    virtual status_t removeDevicesRoleForStrategy(product_strategy_t strategy, device_role_t role);
 
+    virtual status_t getDevicesForRoleAndStrategy(product_strategy_t strategy,
+                                                  device_role_t role,
+                                                  AudioDeviceTypeAddrVector &devices);
 
-    virtual status_t getPreferredDeviceForStrategy(product_strategy_t strategy,
-                                                   AudioDeviceTypeAddr &device);
-    virtual status_t setUserIdDeviceAffinities(int userId, const Vector<AudioDeviceTypeAddr>& devices);
+    virtual status_t setDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                    device_role_t role,
+                                                    const AudioDeviceTypeAddrVector &devices);
+
+    virtual status_t addDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                    device_role_t role,
+                                                    const AudioDeviceTypeAddrVector &devices);
+
+    virtual status_t removeDevicesRoleForCapturePreset(
+            audio_source_t audioSource, device_role_t role,
+            const AudioDeviceTypeAddrVector& devices);
+
+    virtual status_t clearDevicesRoleForCapturePreset(audio_source_t audioSource,
+                                                      device_role_t role);
+
+    virtual status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource,
+                                                       device_role_t role,
+                                                       AudioDeviceTypeAddrVector &devices);
+
+    virtual status_t setUserIdDeviceAffinities(int userId,
+            const AudioDeviceTypeAddrVector& devices);
 
     virtual status_t removeUserIdDeviceAffinities(int userId);
 
diff --git a/services/audiopolicy/tests/Android.bp b/services/audiopolicy/tests/Android.bp
index efdb241..42f0342 100644
--- a/services/audiopolicy/tests/Android.bp
+++ b/services/audiopolicy/tests/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "audiopolicy_tests",
 
@@ -18,7 +27,10 @@
         "libxml2",
     ],
 
-    static_libs: ["libaudiopolicycomponents"],
+    static_libs: [
+        "libaudiopolicycomponents",
+        "libgmock"
+    ],
 
     header_libs: [
         "libaudiopolicycommon",
diff --git a/services/audiopolicy/tests/AudioPolicyManagerTestClient.h b/services/audiopolicy/tests/AudioPolicyManagerTestClient.h
index e1721ea..bdddf06 100644
--- a/services/audiopolicy/tests/AudioPolicyManagerTestClient.h
+++ b/services/audiopolicy/tests/AudioPolicyManagerTestClient.h
@@ -75,6 +75,10 @@
     status_t createAudioPatch(const struct audio_patch *patch,
                               audio_patch_handle_t *handle,
                               int /*delayMs*/) override {
+        auto iter = mActivePatches.find(*handle);
+        if (iter != mActivePatches.end()) {
+            mActivePatches.erase(*handle);
+        }
         *handle = mNextPatchHandle++;
         mActivePatches.insert(std::make_pair(*handle, *patch));
         return NO_ERROR;
diff --git a/services/audiopolicy/tests/AudioPolicyTestManager.h b/services/audiopolicy/tests/AudioPolicyTestManager.h
index 8bab020..6150206 100644
--- a/services/audiopolicy/tests/AudioPolicyTestManager.h
+++ b/services/audiopolicy/tests/AudioPolicyTestManager.h
@@ -29,6 +29,9 @@
     using AudioPolicyManager::getOutputs;
     using AudioPolicyManager::getAvailableOutputDevices;
     using AudioPolicyManager::getAvailableInputDevices;
+    using AudioPolicyManager::releaseMsdOutputPatches;
+    using AudioPolicyManager::setMsdOutputPatches;
+    using AudioPolicyManager::getAudioPatches;
     uint32_t getAudioPortGeneration() const { return mAudioPortGeneration; }
 };
 
diff --git a/services/audiopolicy/tests/audio_health_tests.cpp b/services/audiopolicy/tests/audio_health_tests.cpp
index b5c67a1..e1634cf 100644
--- a/services/audiopolicy/tests/audio_health_tests.cpp
+++ b/services/audiopolicy/tests/audio_health_tests.cpp
@@ -21,6 +21,7 @@
 #include <gtest/gtest.h>
 
 #include <media/AudioSystem.h>
+#include <media/TypeConverter.h>
 #include <system/audio.h>
 #include <utils/Log.h>
 
@@ -68,9 +69,18 @@
     ASSERT_NE("AudioPolicyConfig::setDefault", manager.getConfig().getSource());
 
     for (auto desc : manager.getConfig().getInputDevices()) {
-        ASSERT_NE(attachedDevices.end(), attachedDevices.find(desc->type()));
+        if (attachedDevices.find(desc->type()) == attachedDevices.end()) {
+            std::string deviceType;
+            (void)DeviceConverter::toString(desc->type(), deviceType);
+            ADD_FAILURE() << "Input device \"" << deviceType << "\" not found";
+        }
     }
     for (auto desc : manager.getConfig().getOutputDevices()) {
-        ASSERT_NE(attachedDevices.end(), attachedDevices.find(desc->type()));
+        if (attachedDevices.find(desc->type()) == attachedDevices.end()) {
+            std::string deviceType;
+            (void)DeviceConverter::toString(desc->type(), deviceType);
+            ADD_FAILURE() << "Output device \"" << deviceType << "\" not found";
+        }
     }
 }
+
diff --git a/services/audiopolicy/tests/audiopolicymanager_tests.cpp b/services/audiopolicy/tests/audiopolicymanager_tests.cpp
index a0074bc..a3d6db0 100644
--- a/services/audiopolicy/tests/audiopolicymanager_tests.cpp
+++ b/services/audiopolicy/tests/audiopolicymanager_tests.cpp
@@ -20,6 +20,7 @@
 #include <unistd.h>
 
 #include <gtest/gtest.h>
+#include <gmock/gmock.h>
 
 #define LOG_TAG "APM_Test"
 #include <Serializer.h>
@@ -36,6 +37,7 @@
 #include "AudioPolicyTestManager.h"
 
 using namespace android;
+using testing::UnorderedElementsAre;
 
 TEST(AudioPolicyManagerTestInit, EngineFailure) {
     AudioPolicyTestClient client;
@@ -56,6 +58,34 @@
     ASSERT_EQ(NO_INIT, manager.initCheck());
 }
 
+// Verifies that a failure while loading a config doesn't leave
+// APM config in a "dirty" state. Since AudioPolicyConfig object
+// is a proxy for the data hosted by APM, it isn't possible
+// to "deep copy" it, and thus we have to test its elements
+// individually.
+TEST(AudioPolicyManagerTestInit, ConfigLoadingIsTransactional) {
+    AudioPolicyTestClient client;
+    AudioPolicyTestManager manager(&client);
+    ASSERT_TRUE(manager.getConfig().getHwModules().isEmpty());
+    ASSERT_TRUE(manager.getConfig().getInputDevices().isEmpty());
+    ASSERT_TRUE(manager.getConfig().getOutputDevices().isEmpty());
+    status_t status = deserializeAudioPolicyFile(
+            (base::GetExecutableDirectory() +
+                    "/test_invalid_audio_policy_configuration.xml").c_str(),
+            &manager.getConfig());
+    ASSERT_NE(NO_ERROR, status);
+    EXPECT_TRUE(manager.getConfig().getHwModules().isEmpty());
+    EXPECT_TRUE(manager.getConfig().getInputDevices().isEmpty());
+    EXPECT_TRUE(manager.getConfig().getOutputDevices().isEmpty());
+    status = deserializeAudioPolicyFile(
+            (base::GetExecutableDirectory() + "/test_audio_policy_configuration.xml").c_str(),
+            &manager.getConfig());
+    ASSERT_EQ(NO_ERROR, status);
+    EXPECT_FALSE(manager.getConfig().getHwModules().isEmpty());
+    EXPECT_FALSE(manager.getConfig().getInputDevices().isEmpty());
+    EXPECT_FALSE(manager.getConfig().getOutputDevices().isEmpty());
+}
+
 
 class PatchCountCheck {
   public:
@@ -87,7 +117,7 @@
     void getOutputForAttr(
             audio_port_handle_t *selectedDeviceId,
             audio_format_t format,
-            int channelMask,
+            audio_channel_mask_t channelMask,
             int sampleRate,
             audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
             audio_io_handle_t *output = nullptr,
@@ -98,7 +128,7 @@
             audio_unique_id_t riid,
             audio_port_handle_t *selectedDeviceId,
             audio_format_t format,
-            int channelMask,
+            audio_channel_mask_t channelMask,
             int sampleRate,
             audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE,
             audio_port_handle_t *portId = nullptr);
@@ -164,7 +194,7 @@
 void AudioPolicyManagerTest::getOutputForAttr(
         audio_port_handle_t *selectedDeviceId,
         audio_format_t format,
-        int channelMask,
+        audio_channel_mask_t channelMask,
         int sampleRate,
         audio_output_flags_t flags,
         audio_io_handle_t *output,
@@ -194,7 +224,7 @@
         audio_unique_id_t riid,
         audio_port_handle_t *selectedDeviceId,
         audio_format_t format,
-        int channelMask,
+        audio_channel_mask_t channelMask,
         int sampleRate,
         audio_input_flags_t flags,
         audio_port_handle_t *portId) {
@@ -317,15 +347,46 @@
 
 // TODO: Add patch creation tests that involve already existing patch
 
-class AudioPolicyManagerTestMsd : public AudioPolicyManagerTest {
+enum
+{
+    MSD_AUDIO_PATCH_COUNT_NUM_AUDIO_PATCHES_INDEX = 0,
+    MSD_AUDIO_PATCH_COUNT_NAME_INDEX = 1
+};
+using MsdAudioPatchCountSpecification = std::tuple<size_t, std::string>;
+
+class AudioPolicyManagerTestMsd : public AudioPolicyManagerTest,
+        public ::testing::WithParamInterface<MsdAudioPatchCountSpecification> {
+  public:
+    AudioPolicyManagerTestMsd();
   protected:
     void SetUpManagerConfig() override;
     void TearDown() override;
 
     sp<DeviceDescriptor> mMsdOutputDevice;
     sp<DeviceDescriptor> mMsdInputDevice;
+    sp<DeviceDescriptor> mDefaultOutputDevice;
+
+    const size_t mExpectedAudioPatchCount;
+    sp<DeviceDescriptor> mSpdifDevice;
+
+    sp<DeviceDescriptor> mHdmiInputDevice;
 };
 
+AudioPolicyManagerTestMsd::AudioPolicyManagerTestMsd()
+    : mExpectedAudioPatchCount(std::get<MSD_AUDIO_PATCH_COUNT_NUM_AUDIO_PATCHES_INDEX>(
+            GetParam())) {}
+
+INSTANTIATE_TEST_CASE_P(
+        MsdAudioPatchCount,
+        AudioPolicyManagerTestMsd,
+        ::testing::Values(
+                MsdAudioPatchCountSpecification(1u, "single"),
+                MsdAudioPatchCountSpecification(2u, "dual")
+        ),
+        [](const ::testing::TestParamInfo<MsdAudioPatchCountSpecification> &info) {
+                return std::get<MSD_AUDIO_PATCH_COUNT_NAME_INDEX>(info.param); }
+);
+
 void AudioPolicyManagerTestMsd::SetUpManagerConfig() {
     // TODO: Consider using Serializer to load part of the config from a string.
     AudioPolicyManagerTest::SetUpManagerConfig();
@@ -335,8 +396,11 @@
             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, 48000);
     sp<AudioProfile> ac3OutputProfile = new AudioProfile(
             AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000);
+    sp<AudioProfile> iec958OutputProfile = new AudioProfile(
+            AUDIO_FORMAT_IEC60958, AUDIO_CHANNEL_OUT_STEREO, 48000);
     mMsdOutputDevice->addAudioProfile(pcmOutputProfile);
     mMsdOutputDevice->addAudioProfile(ac3OutputProfile);
+    mMsdOutputDevice->addAudioProfile(iec958OutputProfile);
     mMsdInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUS);
     // Match output profile from AudioPolicyConfig::setDefault.
     sp<AudioProfile> pcmInputProfile = new AudioProfile(
@@ -345,6 +409,19 @@
     config.addDevice(mMsdOutputDevice);
     config.addDevice(mMsdInputDevice);
 
+    if (mExpectedAudioPatchCount == 2) {
+        // Add SPDIF device with PCM output profile as a second device for dual MSD audio patching.
+        mSpdifDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPDIF);
+        mSpdifDevice->addAudioProfile(pcmOutputProfile);
+        config.addDevice(mSpdifDevice);
+
+        sp<OutputProfile> spdifOutputProfile = new OutputProfile("spdif output");
+        spdifOutputProfile->addAudioProfile(pcmOutputProfile);
+        spdifOutputProfile->addSupportedDevice(mSpdifDevice);
+        config.getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
+                addOutputProfile(spdifOutputProfile);
+    }
+
     sp<HwModule> msdModule = new HwModule(AUDIO_HARDWARE_MODULE_ID_MSD, 2 /*halVersionMajor*/);
     HwModuleCollection modules = config.getHwModules();
     modules.add(msdModule);
@@ -361,6 +438,11 @@
             AUDIO_OUTPUT_FLAG_NON_BLOCKING);
     msdCompressedOutputProfile->addSupportedDevice(mMsdOutputDevice);
     msdModule->addOutputProfile(msdCompressedOutputProfile);
+    sp<OutputProfile> msdIec958OutputProfile = new OutputProfile("msd iec958 input");
+    msdIec958OutputProfile->addAudioProfile(iec958OutputProfile);
+    msdIec958OutputProfile->setFlags(AUDIO_OUTPUT_FLAG_DIRECT);
+    msdIec958OutputProfile->addSupportedDevice(mMsdOutputDevice);
+    msdModule->addOutputProfile(msdIec958OutputProfile);
 
     sp<InputProfile> msdInputProfile = new InputProfile("msd output");
     msdInputProfile->addAudioProfile(pcmInputProfile);
@@ -378,62 +460,104 @@
     primaryEncodedOutputProfile->addSupportedDevice(config.getDefaultOutputDevice());
     config.getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
             addOutputProfile(primaryEncodedOutputProfile);
+
+    mDefaultOutputDevice = config.getDefaultOutputDevice();
+    if (mExpectedAudioPatchCount == 2) {
+        mSpdifDevice->addAudioProfile(dtsOutputProfile);
+        primaryEncodedOutputProfile->addSupportedDevice(mSpdifDevice);
+    }
+
+    // Add HDMI input device with IEC60958 profile for HDMI in -> MSD patching.
+    mHdmiInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_HDMI);
+    sp<AudioProfile> iec958InputProfile = new AudioProfile(
+            AUDIO_FORMAT_IEC60958, AUDIO_CHANNEL_IN_STEREO, 48000);
+    mHdmiInputDevice->addAudioProfile(iec958InputProfile);
+    config.addDevice(mHdmiInputDevice);
+    sp<InputProfile> hdmiInputProfile = new InputProfile("hdmi input");
+    hdmiInputProfile->addAudioProfile(iec958InputProfile);
+    hdmiInputProfile->setFlags(AUDIO_INPUT_FLAG_DIRECT);
+    hdmiInputProfile->addSupportedDevice(mHdmiInputDevice);
+    config.getHwModules().getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)->
+            addInputProfile(hdmiInputProfile);
 }
 
 void AudioPolicyManagerTestMsd::TearDown() {
     mMsdOutputDevice.clear();
     mMsdInputDevice.clear();
+    mDefaultOutputDevice.clear();
+    mSpdifDevice.clear();
+    mHdmiInputDevice.clear();
     AudioPolicyManagerTest::TearDown();
 }
 
-TEST_F(AudioPolicyManagerTestMsd, InitSuccess) {
+TEST_P(AudioPolicyManagerTestMsd, InitSuccess) {
     ASSERT_TRUE(mMsdOutputDevice);
     ASSERT_TRUE(mMsdInputDevice);
+    ASSERT_TRUE(mDefaultOutputDevice);
 }
 
-TEST_F(AudioPolicyManagerTestMsd, Dump) {
+TEST_P(AudioPolicyManagerTestMsd, Dump) {
     dumpToLog();
 }
 
-TEST_F(AudioPolicyManagerTestMsd, PatchCreationOnSetForceUse) {
+TEST_P(AudioPolicyManagerTestMsd, PatchCreationOnSetForceUse) {
     const PatchCountCheck patchCount = snapshotPatchCount();
     mManager->setForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND,
             AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS);
-    ASSERT_EQ(1, patchCount.deltaFromSnapshot());
+    ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
 }
 
-TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedRoutesToMsd) {
+TEST_P(AudioPolicyManagerTestMsd, PatchCreationSetReleaseMsdOutputPatches) {
+    const PatchCountCheck patchCount = snapshotPatchCount();
+    DeviceVector devices = mManager->getAvailableOutputDevices();
+    // Remove MSD output device to avoid patching to itself
+    devices.remove(mMsdOutputDevice);
+    ASSERT_EQ(mExpectedAudioPatchCount, devices.size());
+    mManager->setMsdOutputPatches(&devices);
+    ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
+    // Dual patch: exercise creating one new audio patch and reusing another existing audio patch.
+    DeviceVector singleDevice(devices[0]);
+    mManager->releaseMsdOutputPatches(singleDevice);
+    ASSERT_EQ(mExpectedAudioPatchCount - 1, patchCount.deltaFromSnapshot());
+    mManager->setMsdOutputPatches(&devices);
+    ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
+    mManager->releaseMsdOutputPatches(devices);
+    ASSERT_EQ(0, patchCount.deltaFromSnapshot());
+}
+
+TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedRoutesToMsd) {
     const PatchCountCheck patchCount = snapshotPatchCount();
     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
     getOutputForAttr(&selectedDeviceId,
             AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT);
-    ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
-    ASSERT_EQ(1, patchCount.deltaFromSnapshot());
+    ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
+    ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
 }
 
-TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrPcmRoutesToMsd) {
+TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrPcmRoutesToMsd) {
     const PatchCountCheck patchCount = snapshotPatchCount();
     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
     getOutputForAttr(&selectedDeviceId,
             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, 48000);
-    ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
-    ASSERT_EQ(1, patchCount.deltaFromSnapshot());
+    ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
+    ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
 }
 
-TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedPlusPcmRoutesToMsd) {
+TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrEncodedPlusPcmRoutesToMsd) {
     const PatchCountCheck patchCount = snapshotPatchCount();
     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
     getOutputForAttr(&selectedDeviceId,
             AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT);
-    ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
-    ASSERT_EQ(1, patchCount.deltaFromSnapshot());
+    ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
+    ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
+    selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
     getOutputForAttr(&selectedDeviceId,
             AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, 48000);
-    ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
-    ASSERT_EQ(1, patchCount.deltaFromSnapshot());
+    ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
+    ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
 }
 
-TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrUnsupportedFormatBypassesMsd) {
+TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrUnsupportedFormatBypassesMsd) {
     const PatchCountCheck patchCount = snapshotPatchCount();
     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
     getOutputForAttr(&selectedDeviceId,
@@ -442,7 +566,7 @@
     ASSERT_EQ(0, patchCount.deltaFromSnapshot());
 }
 
-TEST_F(AudioPolicyManagerTestMsd, GetOutputForAttrFormatSwitching) {
+TEST_P(AudioPolicyManagerTestMsd, GetOutputForAttrFormatSwitching) {
     // Switch between formats that are supported and not supported by MSD.
     {
         const PatchCountCheck patchCount = snapshotPatchCount();
@@ -451,10 +575,10 @@
         getOutputForAttr(&selectedDeviceId,
                 AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT,
                 nullptr /*output*/, &portId);
-        ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
-        ASSERT_EQ(1, patchCount.deltaFromSnapshot());
+        ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
+        ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
         mManager->releaseOutput(portId);
-        ASSERT_EQ(1, patchCount.deltaFromSnapshot());
+        ASSERT_EQ(mExpectedAudioPatchCount, patchCount.deltaFromSnapshot());
     }
     {
         const PatchCountCheck patchCount = snapshotPatchCount();
@@ -464,7 +588,7 @@
                 AUDIO_FORMAT_DTS, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT,
                 nullptr /*output*/, &portId);
         ASSERT_NE(selectedDeviceId, mMsdOutputDevice->getId());
-        ASSERT_EQ(-1, patchCount.deltaFromSnapshot());
+        ASSERT_EQ(-static_cast<int>(mExpectedAudioPatchCount), patchCount.deltaFromSnapshot());
         mManager->releaseOutput(portId);
         ASSERT_EQ(0, patchCount.deltaFromSnapshot());
     }
@@ -473,11 +597,39 @@
         audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
         getOutputForAttr(&selectedDeviceId,
                 AUDIO_FORMAT_AC3, AUDIO_CHANNEL_OUT_5POINT1, 48000, AUDIO_OUTPUT_FLAG_DIRECT);
-        ASSERT_EQ(selectedDeviceId, mMsdOutputDevice->getId());
+        ASSERT_EQ(selectedDeviceId, mDefaultOutputDevice->getId());
         ASSERT_EQ(0, patchCount.deltaFromSnapshot());
     }
 }
 
+TEST_P(AudioPolicyManagerTestMsd, PatchCreationFromHdmiInToMsd) {
+    audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
+    uid_t uid = 42;
+    const PatchCountCheck patchCount = snapshotPatchCount();
+    ASSERT_FALSE(mManager->getAvailableInputDevices().isEmpty());
+    PatchBuilder patchBuilder;
+    patchBuilder.
+            addSource(mManager->getAvailableInputDevices().
+                    getDevice(AUDIO_DEVICE_IN_HDMI, String8(""), AUDIO_FORMAT_DEFAULT)).
+            addSink(mManager->getAvailableOutputDevices().
+                    getDevice(AUDIO_DEVICE_OUT_BUS, String8(""), AUDIO_FORMAT_DEFAULT));
+    ASSERT_EQ(NO_ERROR, mManager->createAudioPatch(patchBuilder.patch(), &handle, uid));
+    ASSERT_NE(AUDIO_PATCH_HANDLE_NONE, handle);
+    AudioPatchCollection patches = mManager->getAudioPatches();
+    sp<AudioPatch> patch = patches.valueFor(handle);
+    ASSERT_EQ(1, patch->mPatch.num_sources);
+    ASSERT_EQ(1, patch->mPatch.num_sinks);
+    ASSERT_EQ(AUDIO_PORT_ROLE_SOURCE, patch->mPatch.sources[0].role);
+    ASSERT_EQ(AUDIO_PORT_ROLE_SINK, patch->mPatch.sinks[0].role);
+    ASSERT_EQ(AUDIO_FORMAT_IEC60958, patch->mPatch.sources[0].format);
+    ASSERT_EQ(AUDIO_FORMAT_IEC60958, patch->mPatch.sinks[0].format);
+    ASSERT_EQ(AUDIO_CHANNEL_IN_STEREO, patch->mPatch.sources[0].channel_mask);
+    ASSERT_EQ(AUDIO_CHANNEL_OUT_STEREO, patch->mPatch.sinks[0].channel_mask);
+    ASSERT_EQ(48000, patch->mPatch.sources[0].sample_rate);
+    ASSERT_EQ(48000, patch->mPatch.sinks[0].sample_rate);
+    ASSERT_EQ(1, patchCount.deltaFromSnapshot());
+}
+
 class AudioPolicyManagerTestWithConfigurationFile : public AudioPolicyManagerTest {
 protected:
     void SetUpManagerConfig() override;
@@ -707,7 +859,8 @@
 
     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
     audio_source_t source = AUDIO_SOURCE_REMOTE_SUBMIX;
-    audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, source, 0, ""};
+    audio_attributes_t attr = {
+        AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN, source, AUDIO_FLAG_NONE, ""};
     std::string tags = "addr=" + mMixAddress;
     strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
     getInputForAttr(attr, mTracker->getRiid(), &selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT,
@@ -757,9 +910,9 @@
         AudioPolicyManagerTestDPPlaybackReRouting,
         testing::Values(
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_MEDIA,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_ALARM,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""}
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}
                 )
         );
 
@@ -768,47 +921,47 @@
         AudioPolicyManagerTestDPPlaybackReRouting,
         testing::Values(
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_MEDIA,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_VOICE_COMMUNICATION,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
-                                     AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING,
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_ALARM,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_NOTIFICATION,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
-                                     AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE,
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
-                                     AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST,
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
-                                     AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT,
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
-                                     AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED,
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_NOTIFICATION_EVENT,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
-                                     AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY,
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
-                                     AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
-                                     AUDIO_USAGE_ASSISTANCE_SONIFICATION,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_USAGE_ASSISTANCE_SONIFICATION,
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_GAME,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_VIRTUAL_SOURCE,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_ASSISTANT,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"},
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_SPEECH, AUDIO_USAGE_ASSISTANT,
-                                     AUDIO_SOURCE_DEFAULT, 0, "addr=remote_submix_media"}
+                    AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, "addr=remote_submix_media"}
                 )
         );
 
@@ -817,41 +970,41 @@
         AudioPolicyManagerTestDPPlaybackReRouting,
         testing::Values(
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_VOICE_COMMUNICATION,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
                                      AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_NOTIFICATION,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
                                      AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
                                      AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
                                      AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
                                      AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_NOTIFICATION_EVENT,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
                                      AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
                                      AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC,
                                      AUDIO_USAGE_ASSISTANCE_SONIFICATION,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_GAME,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_MUSIC, AUDIO_USAGE_ASSISTANT,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""},
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_SPEECH, AUDIO_USAGE_ASSISTANT,
-                                     AUDIO_SOURCE_DEFAULT, 0, ""}
+                                     AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}
                 )
         );
 
@@ -892,7 +1045,8 @@
 
     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
     audio_usage_t usage = AUDIO_USAGE_VIRTUAL_SOURCE;
-    audio_attributes_t attr = {AUDIO_CONTENT_TYPE_UNKNOWN, usage, AUDIO_SOURCE_DEFAULT, 0, ""};
+    audio_attributes_t attr =
+            {AUDIO_CONTENT_TYPE_UNKNOWN, usage, AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""};
     std::string tags = std::string("addr=") + mMixAddress;
     strncpy(attr.tags, tags.c_str(), AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1);
     getOutputForAttr(&selectedDeviceId, AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO,
@@ -941,17 +1095,19 @@
         AudioPolicyManagerTestDPMixRecordInjection,
         testing::Values(
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_CAMCORDER, 0, ""},
+                                     AUDIO_SOURCE_CAMCORDER, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_CAMCORDER, 0, "addr=remote_submix_media"},
+                                     AUDIO_SOURCE_CAMCORDER, AUDIO_FLAG_NONE,
+                                     "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_MIC, 0, "addr=remote_submix_media"},
+                                     AUDIO_SOURCE_MIC, AUDIO_FLAG_NONE,
+                                     "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_MIC, 0, ""},
+                                     AUDIO_SOURCE_MIC, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_VOICE_COMMUNICATION, 0, ""},
+                                     AUDIO_SOURCE_VOICE_COMMUNICATION, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_VOICE_COMMUNICATION, 0,
+                                     AUDIO_SOURCE_VOICE_COMMUNICATION, AUDIO_FLAG_NONE,
                                      "addr=remote_submix_media"}
                 )
         );
@@ -962,14 +1118,15 @@
         AudioPolicyManagerTestDPMixRecordInjection,
         testing::Values(
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_VOICE_RECOGNITION, 0, ""},
+                                     AUDIO_SOURCE_VOICE_RECOGNITION, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_HOTWORD, 0, ""},
+                                     AUDIO_SOURCE_HOTWORD, AUDIO_FLAG_NONE, ""},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_VOICE_RECOGNITION, 0,
+                                     AUDIO_SOURCE_VOICE_RECOGNITION, AUDIO_FLAG_NONE,
                                      "addr=remote_submix_media"},
                 (audio_attributes_t){AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_UNKNOWN,
-                                     AUDIO_SOURCE_HOTWORD, 0, "addr=remote_submix_media"}
+                                     AUDIO_SOURCE_HOTWORD, AUDIO_FLAG_NONE,
+                                     "addr=remote_submix_media"}
                 )
         );
 
@@ -1188,3 +1345,109 @@
     EXPECT_GT(mClient->getAudioPortListUpdateCount(), prevAudioPortListUpdateCount);
     EXPECT_GT(mManager->getAudioPortGeneration(), prevAudioPortGeneration);
 }
+
+using DevicesRoleForCapturePresetParam = std::tuple<audio_source_t, device_role_t>;
+
+class AudioPolicyManagerDevicesRoleForCapturePresetTest
+        : public AudioPolicyManagerTestWithConfigurationFile,
+          public testing::WithParamInterface<DevicesRoleForCapturePresetParam> {
+protected:
+    // The `inputDevice` and `inputDevice2` indicate the audio devices type to be used for setting
+    // device role. They must be declared in the test_audio_policy_configuration.xml
+    AudioDeviceTypeAddr inputDevice = AudioDeviceTypeAddr(AUDIO_DEVICE_IN_BUILTIN_MIC, "");
+    AudioDeviceTypeAddr inputDevice2 = AudioDeviceTypeAddr(AUDIO_DEVICE_IN_HDMI, "");
+};
+
+TEST_P(AudioPolicyManagerDevicesRoleForCapturePresetTest, DevicesRoleForCapturePreset) {
+    const audio_source_t audioSource = std::get<0>(GetParam());
+    const device_role_t role = std::get<1>(GetParam());
+
+    // Test invalid device when setting
+    const AudioDeviceTypeAddr outputDevice(AUDIO_DEVICE_OUT_SPEAKER, "");
+    const AudioDeviceTypeAddrVector outputDevices = {outputDevice};
+    ASSERT_EQ(BAD_VALUE,
+              mManager->setDevicesRoleForCapturePreset(audioSource, role, outputDevices));
+    ASSERT_EQ(BAD_VALUE,
+              mManager->addDevicesRoleForCapturePreset(audioSource, role, outputDevices));
+    AudioDeviceTypeAddrVector devices;
+    ASSERT_EQ(NAME_NOT_FOUND,
+              mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
+    ASSERT_TRUE(devices.empty());
+    ASSERT_EQ(BAD_VALUE,
+              mManager->removeDevicesRoleForCapturePreset(audioSource, role, outputDevices));
+
+    // Without setting, call get/remove/clear must fail
+    ASSERT_EQ(NAME_NOT_FOUND,
+              mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
+    ASSERT_EQ(NAME_NOT_FOUND,
+              mManager->removeDevicesRoleForCapturePreset(audioSource, role, devices));
+    ASSERT_EQ(NAME_NOT_FOUND,
+              mManager->clearDevicesRoleForCapturePreset(audioSource, role));
+
+    // Test set/get devices role
+    const AudioDeviceTypeAddrVector inputDevices = {inputDevice};
+    ASSERT_EQ(NO_ERROR,
+              mManager->setDevicesRoleForCapturePreset(audioSource, role, inputDevices));
+    ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
+    EXPECT_THAT(devices, UnorderedElementsAre(inputDevice));
+
+    // Test setting will change the previously set devices
+    const AudioDeviceTypeAddrVector inputDevices2 = {inputDevice2};
+    ASSERT_EQ(NO_ERROR,
+              mManager->setDevicesRoleForCapturePreset(audioSource, role, inputDevices2));
+    devices.clear();
+    ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
+    EXPECT_THAT(devices, UnorderedElementsAre(inputDevice2));
+
+    // Test add devices
+    ASSERT_EQ(NO_ERROR,
+              mManager->addDevicesRoleForCapturePreset(audioSource, role, inputDevices));
+    devices.clear();
+    ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
+    EXPECT_THAT(devices, UnorderedElementsAre(inputDevice, inputDevice2));
+
+    // Test remove devices
+    ASSERT_EQ(NO_ERROR,
+              mManager->removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
+    devices.clear();
+    ASSERT_EQ(NO_ERROR, mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
+    EXPECT_THAT(devices, UnorderedElementsAre(inputDevice2));
+
+    // Test remove devices that are not set as the device role
+    ASSERT_EQ(BAD_VALUE,
+              mManager->removeDevicesRoleForCapturePreset(audioSource, role, inputDevices));
+
+    // Test clear devices
+    ASSERT_EQ(NO_ERROR,
+              mManager->clearDevicesRoleForCapturePreset(audioSource, role));
+    devices.clear();
+    ASSERT_EQ(NAME_NOT_FOUND,
+              mManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices));
+}
+
+INSTANTIATE_TEST_CASE_P(
+        DevicesRoleForCapturePresetOperation,
+        AudioPolicyManagerDevicesRoleForCapturePresetTest,
+        testing::Values(
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_MIC, DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_UPLINK,
+                                                  DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_DOWNLINK,
+                                                  DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_CALL, DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_CAMCORDER, DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_RECOGNITION,
+                                                  DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_COMMUNICATION,
+                                                  DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_REMOTE_SUBMIX,
+                                                  DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_UNPROCESSED, DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_VOICE_PERFORMANCE,
+                                                  DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_ECHO_REFERENCE,
+                                                  DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_FM_TUNER, DEVICE_ROLE_PREFERRED}),
+                DevicesRoleForCapturePresetParam({AUDIO_SOURCE_HOTWORD, DEVICE_ROLE_PREFERRED})
+                )
+        );
diff --git a/services/audiopolicy/tests/resources/Android.bp b/services/audiopolicy/tests/resources/Android.bp
index d9476d9..630bbcf 100644
--- a/services/audiopolicy/tests/resources/Android.bp
+++ b/services/audiopolicy/tests/resources/Android.bp
@@ -1,8 +1,20 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    //   SPDX-license-identifier-Unicode-DFS
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 filegroup {
     name: "audiopolicytest_configuration_files",
     srcs: [
         "test_audio_policy_configuration.xml",
         "test_audio_policy_primary_only_configuration.xml",
+        "test_invalid_audio_policy_configuration.xml",
         "test_tv_apm_configuration.xml",
     ],
 }
diff --git a/services/audiopolicy/tests/resources/test_invalid_audio_policy_configuration.xml b/services/audiopolicy/tests/resources/test_invalid_audio_policy_configuration.xml
new file mode 100644
index 0000000..25641d5
--- /dev/null
+++ b/services/audiopolicy/tests/resources/test_invalid_audio_policy_configuration.xml
@@ -0,0 +1,113 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<!-- This file contains an unnamed device port in the "r_submix" module section. -->
+<audioPolicyConfiguration version="1.0" xmlns:xi="http://www.w3.org/2001/XInclude">
+    <globalConfiguration speaker_drc_enabled="true"/>
+
+    <modules>
+        <!-- Primary module -->
+        <module name="primary" halVersion="2.0">
+            <attachedDevices>
+                <item>Speaker</item>
+                <item>Built-In Mic</item>
+            </attachedDevices>
+            <defaultOutputDevice>Speaker</defaultOutputDevice>
+            <mixPorts>
+                <mixPort name="primary output" role="source" flags="AUDIO_OUTPUT_FLAG_PRIMARY">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="primary input" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000"
+                             channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+                </mixPort>
+                <mixPort name="mixport_bt_hfp_output" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="mixport_bt_hfp_input" role="sink">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="8000,11025,16000,44100,48000"
+                             channelMasks="AUDIO_CHANNEL_IN_STEREO,AUDIO_CHANNEL_IN_MONO"/>
+                </mixPort>
+            </mixPorts>
+            <devicePorts>
+                <devicePort tagName="Speaker" type="AUDIO_DEVICE_OUT_SPEAKER" role="sink">
+                </devicePort>
+                <devicePort tagName="Built-In Mic" type="AUDIO_DEVICE_IN_BUILTIN_MIC" role="source">
+                </devicePort>
+                <devicePort tagName="Hdmi" type="AUDIO_DEVICE_OUT_HDMI" role="sink">
+                </devicePort>
+                <devicePort tagName="Hdmi-In Mic" type="AUDIO_DEVICE_IN_HDMI" role="source">
+                </devicePort>
+                <devicePort tagName="BT SCO" type="AUDIO_DEVICE_OUT_BLUETOOTH_SCO"
+                            role="sink" address="hfp_client_out">
+                </devicePort>
+                <devicePort tagName="BT SCO Headset Mic" type="AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET"
+                            role="source" address="hfp_client_in">
+                </devicePort>
+            </devicePorts>
+            <routes>
+                <route type="mix" sink="Speaker"
+                       sources="primary output"/>
+                <route type="mix" sink="primary input"
+                       sources="Built-In Mic,Hdmi-In Mic"/>
+                <route type="mix" sink="Hdmi"
+                       sources="primary output"/>
+                <route type="mix" sink="BT SCO"
+                       sources="mixport_bt_hfp_output"/>
+                <route type="mix" sink="mixport_bt_hfp_input"
+                       sources="BT SCO Headset Mic"/>
+            </routes>
+        </module>
+
+        <!-- Remote Submix module -->
+        <module name="r_submix" halVersion="2.0">
+            <attachedDevices>
+                <item>Remote Submix In</item>
+            </attachedDevices>
+            <mixPorts>
+                <mixPort name="r_submix output" role="source">
+                    <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                             samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+                </mixPort>
+                <mixPort name="r_submix input" role="sink">
+                   <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+                </mixPort>
+           </mixPorts>
+           <devicePorts>
+               <!-- This port is missing "tagName" attribute. -->
+               <devicePort type="AUDIO_DEVICE_OUT_REMOTE_SUBMIX"  role="sink">
+                   <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_OUT_STEREO"/>
+               </devicePort>
+               <devicePort tagName="Remote Submix In" type="AUDIO_DEVICE_IN_REMOTE_SUBMIX"  role="source">
+                   <profile name="" format="AUDIO_FORMAT_PCM_16_BIT"
+                            samplingRates="48000" channelMasks="AUDIO_CHANNEL_IN_STEREO"/>
+                </devicePort>
+            </devicePorts>
+            <routes>
+                <route type="mix" sink="Remote Submix Out"
+                       sources="r_submix output"/>
+                <route type="mix" sink="r_submix input"
+                       sources="Remote Submix In"/>
+            </routes>
+        </module>
+    </modules>
+</audioPolicyConfiguration>
diff --git a/services/camera/libcameraservice/Android.bp b/services/camera/libcameraservice/Android.bp
index 501d922..11df5f3 100644
--- a/services/camera/libcameraservice/Android.bp
+++ b/services/camera/libcameraservice/Android.bp
@@ -16,6 +16,25 @@
 // libcameraservice
 //
 
+package {
+    default_applicable_licenses: [
+        "frameworks_av_services_camera_libcameraservice_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_services_camera_libcameraservice_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libcameraservice",
 
@@ -159,4 +178,3 @@
     ],
 
 }
-
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index 24288d6..3d9998a 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -802,7 +802,7 @@
 
 Status CameraService::makeClient(const sp<CameraService>& cameraService,
         const sp<IInterface>& cameraCb, const String16& packageName,
-        const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
+        const std::optional<String16>& featureId, const String8& cameraId, int api1CameraId,
         int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
         int deviceVersion, apiLevel effectiveApiLevel,
         /*out*/sp<BasicClient>* client) {
@@ -958,7 +958,7 @@
     if (!(ret = connectHelper<ICameraClient,Client>(
             sp<ICameraClient>{nullptr}, id, cameraId,
             static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
-            internalPackageName, std::unique_ptr<String16>(), uid, USE_CALLING_PID,
+            internalPackageName, {}, uid, USE_CALLING_PID,
             API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
             ).isOk()) {
         ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
@@ -1476,7 +1476,7 @@
     String8 id = cameraIdIntToStr(api1CameraId);
     sp<Client> client = nullptr;
     ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
-            CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, std::unique_ptr<String16>(),
+            CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, {},
             clientUid, clientPid, API_1, /*shimUpdateOnly*/ false, /*out*/client);
 
     if(!ret.isOk()) {
@@ -1503,7 +1503,7 @@
     Status ret = Status::ok();
     sp<Client> client = nullptr;
     ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
-            clientPackageName, std::unique_ptr<String16>(), clientUid, USE_CALLING_PID, API_1,
+            clientPackageName, {}, clientUid, USE_CALLING_PID, API_1,
             /*shimUpdateOnly*/ false, /*out*/client);
 
     if(!ret.isOk()) {
@@ -1578,7 +1578,7 @@
         const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
         const String16& cameraId,
         const String16& clientPackageName,
-        const std::unique_ptr<String16>& clientFeatureId,
+        const std::optional<String16>& clientFeatureId,
         int clientUid,
         /*out*/
         sp<hardware::camera2::ICameraDeviceUser>* device) {
@@ -1612,7 +1612,7 @@
 template<class CALLBACK, class CLIENT>
 Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
         int api1CameraId, int halVersion, const String16& clientPackageName,
-        const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
+        const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
         apiLevel effectiveApiLevel, bool shimUpdateOnly,
         /*out*/sp<CLIENT>& device) {
     binder::Status ret = binder::Status::ok();
@@ -2714,7 +2714,7 @@
 CameraService::Client::Client(const sp<CameraService>& cameraService,
         const sp<ICameraClient>& cameraClient,
         const String16& clientPackageName,
-        const std::unique_ptr<String16>& clientFeatureId,
+        const std::optional<String16>& clientFeatureId,
         const String8& cameraIdStr,
         int api1CameraId, int cameraFacing,
         int clientPid, uid_t clientUid,
@@ -2751,24 +2751,18 @@
 
 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
         const sp<IBinder>& remoteCallback,
-        const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
+        const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
         const String8& cameraIdStr, int cameraFacing,
         int clientPid, uid_t clientUid,
         int servicePid):
         mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
-        mClientPackageName(clientPackageName),
+        mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
         mClientPid(clientPid), mClientUid(clientUid),
         mServicePid(servicePid),
         mDisconnected(false), mUidIsTrusted(false),
         mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
         mRemoteBinder(remoteCallback)
 {
-    if (clientFeatureId) {
-        mClientFeatureId = std::unique_ptr<String16>(new String16(*clientFeatureId));
-    } else {
-        mClientFeatureId = std::unique_ptr<String16>();
-    }
-
     if (sCameraService == nullptr) {
         sCameraService = cameraService;
     }
diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h
index 685ed5e..6771718 100644
--- a/services/camera/libcameraservice/CameraService.h
+++ b/services/camera/libcameraservice/CameraService.h
@@ -52,6 +52,7 @@
 #include <list>
 #include <map>
 #include <memory>
+#include <optional>
 #include <utility>
 #include <unordered_map>
 #include <unordered_set>
@@ -142,7 +143,7 @@
 
     virtual binder::Status     connectDevice(
             const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb, const String16& cameraId,
-            const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
+            const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
             int32_t clientUid,
             /*out*/
             sp<hardware::camera2::ICameraDeviceUser>* device);
@@ -299,7 +300,7 @@
         BasicClient(const sp<CameraService>& cameraService,
                 const sp<IBinder>& remoteCallback,
                 const String16& clientPackageName,
-                const std::unique_ptr<String16>& clientFeatureId,
+                const std::optional<String16>& clientFeatureId,
                 const String8& cameraIdStr,
                 int cameraFacing,
                 int clientPid,
@@ -319,7 +320,7 @@
         const String8                   mCameraIdStr;
         const int                       mCameraFacing;
         String16                        mClientPackageName;
-        std::unique_ptr<String16>       mClientFeatureId;
+        std::optional<String16>         mClientFeatureId;
         pid_t                           mClientPid;
         const uid_t                     mClientUid;
         const pid_t                     mServicePid;
@@ -391,7 +392,7 @@
         Client(const sp<CameraService>& cameraService,
                 const sp<hardware::ICameraClient>& cameraClient,
                 const String16& clientPackageName,
-                const std::unique_ptr<String16>& clientFeatureId,
+                const std::optional<String16>& clientFeatureId,
                 const String8& cameraIdStr,
                 int api1CameraId,
                 int cameraFacing,
@@ -729,7 +730,7 @@
     template<class CALLBACK, class CLIENT>
     binder::Status connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
             int api1CameraId, int halVersion, const String16& clientPackageName,
-            const std::unique_ptr<String16>& clientFeatureId, int clientUid, int clientPid,
+            const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
             apiLevel effectiveApiLevel, bool shimUpdateOnly, /*out*/sp<CLIENT>& device);
 
     // Lock guarding camera service state
@@ -1063,7 +1064,7 @@
 
     static binder::Status makeClient(const sp<CameraService>& cameraService,
             const sp<IInterface>& cameraCb, const String16& packageName,
-            const std::unique_ptr<String16>& featureId, const String8& cameraId, int api1CameraId,
+            const std::optional<String16>& featureId, const String8& cameraId, int api1CameraId,
             int facing, int clientPid, uid_t clientUid, int servicePid, int halVersion,
             int deviceVersion, apiLevel effectiveApiLevel,
             /*out*/sp<BasicClient>* client);
diff --git a/services/camera/libcameraservice/api1/Camera2Client.cpp b/services/camera/libcameraservice/api1/Camera2Client.cpp
index b043c0b..09e2c3f 100644
--- a/services/camera/libcameraservice/api1/Camera2Client.cpp
+++ b/services/camera/libcameraservice/api1/Camera2Client.cpp
@@ -50,7 +50,7 @@
 Camera2Client::Camera2Client(const sp<CameraService>& cameraService,
         const sp<hardware::ICameraClient>& cameraClient,
         const String16& clientPackageName,
-        const std::unique_ptr<String16>& clientFeatureId,
+        const std::optional<String16>& clientFeatureId,
         const String8& cameraDeviceId,
         int api1CameraId,
         int cameraFacing,
diff --git a/services/camera/libcameraservice/api1/Camera2Client.h b/services/camera/libcameraservice/api1/Camera2Client.h
index 03ca44a..f8da0b6 100644
--- a/services/camera/libcameraservice/api1/Camera2Client.h
+++ b/services/camera/libcameraservice/api1/Camera2Client.h
@@ -94,7 +94,7 @@
     Camera2Client(const sp<CameraService>& cameraService,
             const sp<hardware::ICameraClient>& cameraClient,
             const String16& clientPackageName,
-            const std::unique_ptr<String16>& clientFeatureId,
+            const std::optional<String16>& clientFeatureId,
             const String8& cameraDeviceId,
             int api1CameraId,
             int cameraFacing,
diff --git a/services/camera/libcameraservice/api1/CameraClient.cpp b/services/camera/libcameraservice/api1/CameraClient.cpp
index 892996c..b860ceb 100644
--- a/services/camera/libcameraservice/api1/CameraClient.cpp
+++ b/services/camera/libcameraservice/api1/CameraClient.cpp
@@ -34,7 +34,7 @@
 
 CameraClient::CameraClient(const sp<CameraService>& cameraService,
         const sp<hardware::ICameraClient>& cameraClient,
-        const String16& clientPackageName, const std::unique_ptr<String16>& clientFeatureId,
+        const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
         int cameraId, int cameraFacing,
         int clientPid, int clientUid,
         int servicePid):
diff --git a/services/camera/libcameraservice/api1/CameraClient.h b/services/camera/libcameraservice/api1/CameraClient.h
index a7eb960..aacb00e 100644
--- a/services/camera/libcameraservice/api1/CameraClient.h
+++ b/services/camera/libcameraservice/api1/CameraClient.h
@@ -68,7 +68,7 @@
     CameraClient(const sp<CameraService>& cameraService,
             const sp<hardware::ICameraClient>& cameraClient,
             const String16& clientPackageName,
-            const std::unique_ptr<String16>& clientFeatureId,
+            const std::optional<String16>& clientFeatureId,
             int cameraId,
             int cameraFacing,
             int clientPid,
diff --git a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
index e35b436..022d686 100644
--- a/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
+++ b/services/camera/libcameraservice/api2/CameraDeviceClient.cpp
@@ -54,7 +54,7 @@
         const sp<CameraService>& cameraService,
         const sp<hardware::camera2::ICameraDeviceCallbacks>& remoteCallback,
         const String16& clientPackageName,
-        const std::unique_ptr<String16>& clientFeatureId,
+        const std::optional<String16>& clientFeatureId,
         const String8& cameraId,
         int api1CameraId,
         int cameraFacing,
@@ -80,7 +80,7 @@
 CameraDeviceClient::CameraDeviceClient(const sp<CameraService>& cameraService,
         const sp<hardware::camera2::ICameraDeviceCallbacks>& remoteCallback,
         const String16& clientPackageName,
-        const std::unique_ptr<String16>& clientFeatureId,
+        const std::optional<String16>& clientFeatureId,
         const String8& cameraId,
         int cameraFacing,
         int clientPid,
diff --git a/services/camera/libcameraservice/api2/CameraDeviceClient.h b/services/camera/libcameraservice/api2/CameraDeviceClient.h
index 9d3874f..5cd16ee 100644
--- a/services/camera/libcameraservice/api2/CameraDeviceClient.h
+++ b/services/camera/libcameraservice/api2/CameraDeviceClient.h
@@ -50,7 +50,7 @@
     CameraDeviceClientBase(const sp<CameraService>& cameraService,
             const sp<hardware::camera2::ICameraDeviceCallbacks>& remoteCallback,
             const String16& clientPackageName,
-            const std::unique_ptr<String16>& clientFeatureId,
+            const std::optional<String16>& clientFeatureId,
             const String8& cameraId,
             int api1CameraId,
             int cameraFacing,
@@ -175,7 +175,7 @@
     CameraDeviceClient(const sp<CameraService>& cameraService,
             const sp<hardware::camera2::ICameraDeviceCallbacks>& remoteCallback,
             const String16& clientPackageName,
-            const std::unique_ptr<String16>& clientFeatureId,
+            const std::optional<String16>& clientFeatureId,
             const String8& cameraId,
             int cameraFacing,
             int clientPid,
diff --git a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h
index b67fcb3..03621c8 100644
--- a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h
+++ b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h
@@ -48,7 +48,7 @@
             const KeyedVector<sp<IBinder>, sp<CompositeStream>>& offlineCompositeStreamMap,
             const sp<ICameraDeviceCallbacks>& remoteCallback,
             const String16& clientPackageName,
-            const std::unique_ptr<String16>& clientFeatureId,
+            const std::optional<String16>& clientFeatureId,
             const String8& cameraIdStr, int cameraFacing,
             int clientPid, uid_t clientUid, int servicePid) :
             CameraService::BasicClient(
diff --git a/services/camera/libcameraservice/common/Camera2ClientBase.cpp b/services/camera/libcameraservice/common/Camera2ClientBase.cpp
index 0a41776..609698c 100644
--- a/services/camera/libcameraservice/common/Camera2ClientBase.cpp
+++ b/services/camera/libcameraservice/common/Camera2ClientBase.cpp
@@ -44,7 +44,7 @@
         const sp<CameraService>& cameraService,
         const sp<TCamCallbacks>& remoteCallback,
         const String16& clientPackageName,
-        const std::unique_ptr<String16>& clientFeatureId,
+        const std::optional<String16>& clientFeatureId,
         const String8& cameraId,
         int api1CameraId,
         int cameraFacing,
diff --git a/services/camera/libcameraservice/common/Camera2ClientBase.h b/services/camera/libcameraservice/common/Camera2ClientBase.h
index 042f5aa..d7506af 100644
--- a/services/camera/libcameraservice/common/Camera2ClientBase.h
+++ b/services/camera/libcameraservice/common/Camera2ClientBase.h
@@ -48,7 +48,7 @@
     Camera2ClientBase(const sp<CameraService>& cameraService,
                       const sp<TCamCallbacks>& remoteCallback,
                       const String16& clientPackageName,
-                      const std::unique_ptr<String16>& clientFeatureId,
+                      const std::optional<String16>& clientFeatureId,
                       const String8& cameraId,
                       int api1CameraId,
                       int cameraFacing,
diff --git a/services/camera/libcameraservice/device3/Camera3Device.cpp b/services/camera/libcameraservice/device3/Camera3Device.cpp
index d5f136b..ea6d59e 100644
--- a/services/camera/libcameraservice/device3/Camera3Device.cpp
+++ b/services/camera/libcameraservice/device3/Camera3Device.cpp
@@ -4675,15 +4675,21 @@
         }
         bool isStillCapture = false;
         bool isZslCapture = false;
+        const camera_metadata_t* settings = halRequest->settings;
+        bool shouldUnlockSettings = false;
+        if (settings == nullptr) {
+            shouldUnlockSettings = true;
+            settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
+        }
         if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
             camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
-            find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
+            find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
             if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
                 isStillCapture = true;
                 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
             }
 
-            find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
+            find_camera_metadata_ro_entry(settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
             if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
                 isZslCapture = true;
             }
@@ -4692,7 +4698,7 @@
                 totalNumBuffers, captureRequest->mResultExtras,
                 /*hasInput*/halRequest->input_buffer != NULL,
                 hasCallback,
-                calculateMaxExpectedDuration(halRequest->settings),
+                calculateMaxExpectedDuration(settings),
                 requestedPhysicalCameras, isStillCapture, isZslCapture,
                 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
                 (mUseHalBufManager) ? uniqueSurfaceIdMap :
@@ -4702,6 +4708,11 @@
                 __FUNCTION__,
                 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
                 captureRequest->mResultExtras.burstId);
+
+        if (shouldUnlockSettings) {
+            captureRequest->mSettingsList.begin()->metadata.unlock(settings);
+        }
+
         if (res != OK) {
             SET_ERR("RequestThread: Unable to register new in-flight request:"
                     " %s (%d)", strerror(-res), res);
diff --git a/services/camera/libcameraservice/fuzzer/Android.bp b/services/camera/libcameraservice/fuzzer/Android.bp
new file mode 100644
index 0000000..9a9a03b
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/Android.bp
@@ -0,0 +1,55 @@
+// Copyright 2020 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 {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_services_camera_libcameraservice_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_services_camera_libcameraservice_license",
+    ],
+}
+
+cc_defaults {
+    name: "libcameraservice_fuzz_defaults",
+    fuzz_config: {
+        componentid: 41727
+    },
+}
+
+cc_fuzz {
+    name: "libcameraservice_distortion_mapper_fuzzer",
+    defaults: ["libcameraservice_fuzz_defaults"],
+    srcs: [
+        "DistortionMapperFuzzer.cpp",
+    ],
+    shared_libs: [
+        "libcameraservice",
+        "libcamera_client",
+    ],
+}
+
+cc_fuzz {
+    name: "libcameraservice_depth_processor_fuzzer",
+    defaults: ["libcameraservice_fuzz_defaults"],
+    srcs: [
+        "DepthProcessorFuzzer.cpp",
+    ],
+    shared_libs: [
+        "libcameraservice",
+    ],
+    corpus: ["corpus/*.jpg"],
+}
diff --git a/services/camera/libcameraservice/fuzzer/DepthProcessorFuzzer.cpp b/services/camera/libcameraservice/fuzzer/DepthProcessorFuzzer.cpp
new file mode 100644
index 0000000..650ca91
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/DepthProcessorFuzzer.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2020 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 <array>
+#include <vector>
+
+#include <fuzzer/FuzzedDataProvider.h>
+
+#include "common/DepthPhotoProcessor.h"
+
+using namespace android;
+using namespace android::camera3;
+
+static const size_t kTestBufferWidth = 640;
+static const size_t kTestBufferHeight = 480;
+static const size_t kTestBufferDepthSize (kTestBufferWidth * kTestBufferHeight);
+
+void generateDepth16Buffer(const uint8_t* data, size_t size, std::array<uint16_t, kTestBufferDepthSize> *depth16Buffer /*out*/) {
+    FuzzedDataProvider dataProvider(data, size);
+    for (size_t i = 0; i < depth16Buffer->size(); i++) {
+        (*depth16Buffer)[i] = dataProvider.ConsumeIntegral<uint16_t>();
+    }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    DepthPhotoInputFrame inputFrame;
+    // Worst case both depth and confidence maps have the same size as the main color image.
+    inputFrame.mMaxJpegSize = inputFrame.mMainJpegSize * 3;
+
+    std::vector<uint8_t> depthPhotoBuffer(inputFrame.mMaxJpegSize);
+    size_t actualDepthPhotoSize = 0;
+
+    std::array<uint16_t, kTestBufferDepthSize> depth16Buffer;
+    generateDepth16Buffer(data, size, &depth16Buffer);
+
+    inputFrame.mMainJpegBuffer = reinterpret_cast<const char*> (data);
+    inputFrame.mMainJpegSize = size;
+    inputFrame.mDepthMapBuffer = depth16Buffer.data();
+    inputFrame.mDepthMapStride = kTestBufferWidth;
+    inputFrame.mDepthMapWidth = kTestBufferWidth;
+    inputFrame.mDepthMapHeight = kTestBufferHeight;
+    processDepthPhotoFrame(
+        inputFrame,
+        depthPhotoBuffer.size(),
+        depthPhotoBuffer.data(),
+        &actualDepthPhotoSize);
+
+  return 0;
+}
diff --git a/services/camera/libcameraservice/fuzzer/DistortionMapperFuzzer.cpp b/services/camera/libcameraservice/fuzzer/DistortionMapperFuzzer.cpp
new file mode 100644
index 0000000..96bab4e
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/DistortionMapperFuzzer.cpp
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2020 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 <vector>
+
+#include <fuzzer/FuzzedDataProvider.h>
+
+#include "device3/DistortionMapper.h"
+#include <camera/CameraMetadata.h>
+
+using namespace android;
+using namespace android::camera3;
+
+int32_t testActiveArray[] = {100, 100, 1000, 750};
+float testICal[] = { 1000.f, 1000.f, 500.f, 500.f, 0.f };
+float identityDistortion[] = { 0.f, 0.f, 0.f, 0.f, 0.f};
+
+void setupTestMapper(DistortionMapper *m,
+        float distortion[5], float intrinsics[5],
+        int32_t activeArray[4], int32_t preCorrectionActiveArray[4]) {
+    CameraMetadata deviceInfo;
+
+    deviceInfo.update(ANDROID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE,
+            preCorrectionActiveArray, 4);
+
+    deviceInfo.update(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE,
+            activeArray, 4);
+
+    deviceInfo.update(ANDROID_LENS_INTRINSIC_CALIBRATION,
+            intrinsics, 5);
+
+    deviceInfo.update(ANDROID_LENS_DISTORTION,
+            distortion, 5);
+
+    m->setupStaticInfo(deviceInfo);
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    FuzzedDataProvider fdp(data, size);
+
+    DistortionMapper m;
+    setupTestMapper(&m, identityDistortion, testICal,
+        /*activeArray*/ testActiveArray,
+        /*preCorrectionActiveArray*/ testActiveArray);
+
+    bool clamp = fdp.ConsumeBool();
+    bool simple = fdp.ConsumeBool();
+    std::vector<int32_t> input;
+    for (int index = 0; fdp.remaining_bytes() > 0; index++) {
+        input.push_back(fdp.ConsumeIntegral<int32_t>());
+    }
+
+    // The size argument counts how many coordinate pairs there are, so
+    // it is expected to be 1/2 the size of the input.
+    m.mapCorrectedToRaw(input.data(), input.size()/2,  clamp, simple);
+
+    return 0;
+}
diff --git a/services/camera/libcameraservice/fuzzer/corpus/Canon_MakerNote_variant_type_1.jpg b/services/camera/libcameraservice/fuzzer/corpus/Canon_MakerNote_variant_type_1.jpg
new file mode 100644
index 0000000..1eb37d0
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/corpus/Canon_MakerNote_variant_type_1.jpg
Binary files differ
diff --git a/services/camera/libcameraservice/fuzzer/corpus/Fuji_MakerNote_variant_type_1.jpg b/services/camera/libcameraservice/fuzzer/corpus/Fuji_MakerNote_variant_type_1.jpg
new file mode 100644
index 0000000..75e0371
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/corpus/Fuji_MakerNote_variant_type_1.jpg
Binary files differ
diff --git a/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_2.jpg b/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_2.jpg
new file mode 100644
index 0000000..461d613
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_2.jpg
Binary files differ
diff --git a/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_3.jpg b/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_3.jpg
new file mode 100644
index 0000000..42498e2
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_3.jpg
Binary files differ
diff --git a/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_4.jpg b/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_4.jpg
new file mode 100644
index 0000000..233ff78
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_4.jpg
Binary files differ
diff --git a/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_5.jpg b/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_5.jpg
new file mode 100644
index 0000000..f083f75
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/corpus/Olympus_MakerNote_variant_type_5.jpg
Binary files differ
diff --git a/services/camera/libcameraservice/fuzzer/corpus/Pentax_MakerNote_variant_type_2.jpg b/services/camera/libcameraservice/fuzzer/corpus/Pentax_MakerNote_variant_type_2.jpg
new file mode 100644
index 0000000..0ef0ef2
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/corpus/Pentax_MakerNote_variant_type_2.jpg
Binary files differ
diff --git a/services/camera/libcameraservice/fuzzer/corpus/Pentax_MakerNote_variant_type_3.jpg b/services/camera/libcameraservice/fuzzer/corpus/Pentax_MakerNote_variant_type_3.jpg
new file mode 100644
index 0000000..d93b86f
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/corpus/Pentax_MakerNote_variant_type_3.jpg
Binary files differ
diff --git a/services/camera/libcameraservice/fuzzer/corpus/Pentax_MakerNote_variant_type_4.jpg b/services/camera/libcameraservice/fuzzer/corpus/Pentax_MakerNote_variant_type_4.jpg
new file mode 100644
index 0000000..297ea1c
--- /dev/null
+++ b/services/camera/libcameraservice/fuzzer/corpus/Pentax_MakerNote_variant_type_4.jpg
Binary files differ
diff --git a/services/camera/libcameraservice/hidl/HidlCameraService.cpp b/services/camera/libcameraservice/hidl/HidlCameraService.cpp
index a46133e..9ea9526 100644
--- a/services/camera/libcameraservice/hidl/HidlCameraService.cpp
+++ b/services/camera/libcameraservice/hidl/HidlCameraService.cpp
@@ -103,7 +103,7 @@
     }
     sp<hardware::camera2::ICameraDeviceCallbacks> callbacks = hybridCallbacks;
     binder::Status serviceRet = mAidlICameraService->connectDevice(
-            callbacks, String16(cameraId.c_str()), String16(""), std::unique_ptr<String16>(),
+            callbacks, String16(cameraId.c_str()), String16(""), {},
             hardware::ICameraService::USE_CALLING_UID, /*out*/&deviceRemote);
     HStatus status = HStatus::NO_ERROR;
     if (!serviceRet.isOk()) {
diff --git a/services/camera/libcameraservice/libcameraservice_fuzzer/Android.bp b/services/camera/libcameraservice/libcameraservice_fuzzer/Android.bp
new file mode 100644
index 0000000..d06b2c5
--- /dev/null
+++ b/services/camera/libcameraservice/libcameraservice_fuzzer/Android.bp
@@ -0,0 +1,66 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2021 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_services_camera_libcameraservice_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_services_camera_libcameraservice_license",
+    ],
+}
+
+cc_fuzz {
+    name: "camera_service_fuzzer",
+    srcs: [
+        "camera_service_fuzzer.cpp",
+    ],
+    header_libs: [
+        "libmedia_headers",
+    ],
+    shared_libs: [
+        "libbinder",
+        "libbase",
+        "libutils",
+        "libcutils",
+        "libcameraservice",
+        "libcamera_client",
+        "libui",
+        "libgui",
+        "android.hardware.camera.common@1.0",
+        "android.hardware.camera.provider@2.4",
+        "android.hardware.camera.provider@2.5",
+        "android.hardware.camera.provider@2.6",
+        "android.hardware.camera.device@1.0",
+        "android.hardware.camera.device@3.2",
+        "android.hardware.camera.device@3.3",
+        "android.hardware.camera.device@3.4",
+        "android.hardware.camera.device@3.5",
+        "android.hardware.camera.device@3.6",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
diff --git a/services/camera/libcameraservice/libcameraservice_fuzzer/README.md b/services/camera/libcameraservice/libcameraservice_fuzzer/README.md
new file mode 100644
index 0000000..c703845
--- /dev/null
+++ b/services/camera/libcameraservice/libcameraservice_fuzzer/README.md
@@ -0,0 +1,59 @@
+# Fuzzer for libcameraservice
+
+## Plugin Design Considerations
+The fuzzer plugin is designed based on the understanding of the
+library and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+libcameraservice supports the following parameters:
+1. Camera Type (parameter name: `cameraType`)
+2. Camera API Version (parameter name: `cameraAPIVersion`)
+3. Event ID (parameter name: `eventId`)
+4. Camera Sound Kind (parameter name: `soundKind`)
+5. Shell Command (parameter name: `shellCommand`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `cameraType` | 0. `CAMERA_TYPE_BACKWARD_COMPATIBLE` 1. `CAMERA_TYPE_ALL` | Value obtained from FuzzedDataProvider |
+| `cameraAPIVersion` |  0. `API_VERSION_1` 1. `API_VERSION_2` | Value obtained from FuzzedDataProvider |
+| `eventId` |  0. `EVENT_USER_SWITCHED` 1. `EVENT_NONE` | Value obtained from FuzzedDataProvider |
+| `soundKind` |  0. `SOUND_SHUTTER` 1. `SOUND_RECORDING_START` 2. `SOUND_RECORDING_STOP`| Value obtained from FuzzedDataProvider |
+| `shellCommand` |  0. `set-uid-state` 1. `reset-uid-state` 2. `get-uid-state` 3. `set-rotate-and-crop` 4. `get-rotate-and-crop` 5. `help`| Value obtained from FuzzedDataProvider |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+##### Maximize utilization of input data
+The plugin tolerates any kind of input (empty, huge,
+malformed, etc) and doesn't `exit()` on any input and thereby increasing the
+chance of identifying vulnerabilities.
+
+## Build
+
+This describes steps to build camera_service_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) camera_service_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR
+```
+  $ adb shell mkdir CORPUS_DIR
+```
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/camera_service_fuzzer/camera_service_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/services/camera/libcameraservice/libcameraservice_fuzzer/camera_service_fuzzer.cpp b/services/camera/libcameraservice/libcameraservice_fuzzer/camera_service_fuzzer.cpp
new file mode 100644
index 0000000..54550a5
--- /dev/null
+++ b/services/camera/libcameraservice/libcameraservice_fuzzer/camera_service_fuzzer.cpp
@@ -0,0 +1,433 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2021 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include <CameraService.h>
+#include <android/hardware/ICameraServiceListener.h>
+#include <gui/Surface.h>
+#include <gui/SurfaceComposerClient.h>
+#include <private/android_filesystem_config.h>
+#include "fuzzer/FuzzedDataProvider.h"
+
+using namespace android;
+using namespace hardware;
+using namespace std;
+
+const int32_t kPreviewThreshold = 8;
+const nsecs_t kPreviewTimeout = 5000000000;  // .5 [s.]
+const nsecs_t kEventTimeout = 10000000000;   // 1 [s.]
+const size_t kMaxNumLines = USHRT_MAX;
+const size_t kMinArgs = 1;
+const size_t kMaxArgs = 5;
+const int32_t kCamType[] = {hardware::ICameraService::CAMERA_TYPE_BACKWARD_COMPATIBLE,
+                            hardware::ICameraService::CAMERA_TYPE_ALL};
+const int kCameraApiVersion[] = {android::CameraService::API_VERSION_1,
+                                 android::CameraService::API_VERSION_2};
+const int kLayerMetadata[] = {
+    0x00100000 /*GRALLOC_USAGE_RENDERSCRIPT*/, 0x00000003 /*GRALLOC_USAGE_SW_READ_OFTEN*/,
+    0x00000100 /*GRALLOC_USAGE_HW_TEXTURE*/,   0x00000800 /*GRALLOC_USAGE_HW_COMPOSER*/,
+    0x00000200 /*GRALLOC_USAGE_HW_RENDER*/,    0x00010000 /*GRALLOC_USAGE_HW_VIDEO_ENCODER*/};
+const int kCameraMsg[] = {0x001 /*CAMERA_MSG_ERROR*/,
+                          0x002 /*CAMERA_MSG_SHUTTER*/,
+                          0x004 /*CAMERA_MSG_FOCUS*/,
+                          0x008 /*CAMERA_MSG_ZOOM*/,
+                          0x010 /*CAMERA_MSG_PREVIEW_FRAME*/,
+                          0x020 /*CAMERA_MSG_VIDEO_FRAME */,
+                          0x040 /*CAMERA_MSG_POSTVIEW_FRAME*/,
+                          0x080 /*CAMERA_MSG_RAW_IMAGE */,
+                          0x100 /*CAMERA_MSG_COMPRESSED_IMAGE*/,
+                          0x200 /*CAMERA_MSG_RAW_IMAGE_NOTIFY*/,
+                          0x400 /*CAMERA_MSG_PREVIEW_METADATA*/,
+                          0x800 /*CAMERA_MSG_FOCUS_MOVE*/};
+const int32_t kEventId[] = {ICameraService::EVENT_USER_SWITCHED, ICameraService::EVENT_NONE};
+const android::CameraService::sound_kind kSoundKind[] = {
+    android::CameraService::SOUND_SHUTTER, android::CameraService::SOUND_RECORDING_START,
+    android::CameraService::SOUND_RECORDING_STOP};
+const String16 kShellCmd[] = {String16("set-uid-state"),       String16("reset-uid-state"),
+                              String16("get-uid-state"),       String16("set-rotate-and-crop"),
+                              String16("get-rotate-and-crop"), String16("help")};
+const size_t kNumLayerMetaData = size(kLayerMetadata);
+const size_t kNumCameraMsg = size(kCameraMsg);
+const size_t kNumSoundKind = size(kSoundKind);
+const size_t kNumShellCmd = size(kShellCmd);
+
+class CameraFuzzer : public ::android::hardware::BnCameraClient {
+   public:
+    CameraFuzzer() = default;
+    ~CameraFuzzer() { deInit(); }
+    bool init();
+    void process(const uint8_t *data, size_t size);
+    void deInit();
+
+   private:
+    FuzzedDataProvider *mFuzzedDataProvider = nullptr;
+    sp<CameraService> mCameraService = nullptr;
+    sp<SurfaceComposerClient> mComposerClient = nullptr;
+    int32_t mNumCameras = 0;
+    size_t mPreviewBufferCount = 0;
+    bool mAutoFocusMessage = false;
+    bool mSnapshotNotification = false;
+    mutable Mutex mPreviewLock;
+    mutable Condition mPreviewCondition;
+    mutable Mutex mAutoFocusLock;
+    mutable Condition mAutoFocusCondition;
+    mutable Mutex mSnapshotLock;
+    mutable Condition mSnapshotCondition;
+
+    void getNumCameras();
+    void getCameraInformation(int32_t cameraId);
+    void invokeCameraAPIs();
+    void invokeCameraSound();
+    void invokeDump();
+    void invokeShellCommand();
+    void invokeNotifyCalls();
+
+    // CameraClient interface
+    void notifyCallback(int32_t msgType, int32_t, int32_t) override;
+    void dataCallback(int32_t msgType, const sp<IMemory> &, camera_frame_metadata_t *) override;
+    void dataCallbackTimestamp(nsecs_t, int32_t, const sp<IMemory> &) override{};
+    void recordingFrameHandleCallbackTimestamp(nsecs_t, native_handle_t *) override{};
+    void recordingFrameHandleCallbackTimestampBatch(
+        const std::vector<nsecs_t> &, const std::vector<native_handle_t *> &) override{};
+    status_t waitForPreviewStart();
+    status_t waitForEvent(Mutex &mutex, Condition &condition, bool &flag);
+};
+
+void CameraFuzzer::notifyCallback(int32_t msgType, int32_t, int32_t) {
+    if (CAMERA_MSG_FOCUS == msgType) {
+        Mutex::Autolock l(mAutoFocusLock);
+        mAutoFocusMessage = true;
+        mAutoFocusCondition.broadcast();
+    }
+};
+
+void CameraFuzzer::dataCallback(int32_t msgType, const sp<IMemory> & /*data*/,
+                                camera_frame_metadata_t *) {
+    switch (msgType) {
+        case CAMERA_MSG_PREVIEW_FRAME: {
+            Mutex::Autolock l(mPreviewLock);
+            ++mPreviewBufferCount;
+            mPreviewCondition.broadcast();
+            break;
+        }
+        case CAMERA_MSG_COMPRESSED_IMAGE: {
+            Mutex::Autolock l(mSnapshotLock);
+            mSnapshotNotification = true;
+            mSnapshotCondition.broadcast();
+            break;
+        }
+        default:
+            break;
+    }
+};
+
+status_t CameraFuzzer::waitForPreviewStart() {
+    status_t rc = NO_ERROR;
+    Mutex::Autolock l(mPreviewLock);
+    mPreviewBufferCount = 0;
+
+    while (mPreviewBufferCount < kPreviewThreshold) {
+        rc = mPreviewCondition.waitRelative(mPreviewLock, kPreviewTimeout);
+        if (NO_ERROR != rc) {
+            break;
+        }
+    }
+
+    return rc;
+}
+
+status_t CameraFuzzer::waitForEvent(Mutex &mutex, Condition &condition, bool &flag) {
+    status_t rc = NO_ERROR;
+    Mutex::Autolock l(mutex);
+    flag = false;
+
+    while (!flag) {
+        rc = condition.waitRelative(mutex, kEventTimeout);
+        if (NO_ERROR != rc) {
+            break;
+        }
+    }
+
+    return rc;
+}
+
+bool CameraFuzzer::init() {
+    setuid(AID_MEDIA);
+    mCameraService = new CameraService();
+    if (mCameraService) {
+        return true;
+    }
+    return false;
+}
+
+void CameraFuzzer::deInit() {
+    if (mCameraService) {
+        mCameraService = nullptr;
+    }
+    if (mComposerClient) {
+        mComposerClient->dispose();
+    }
+}
+
+void CameraFuzzer::getNumCameras() {
+    bool shouldPassInvalidCamType = mFuzzedDataProvider->ConsumeBool();
+    int32_t camType;
+    if (shouldPassInvalidCamType) {
+        camType = mFuzzedDataProvider->ConsumeIntegral<int32_t>();
+    } else {
+        camType = kCamType[mFuzzedDataProvider->ConsumeBool()];
+    }
+    mCameraService->getNumberOfCameras(camType, &mNumCameras);
+}
+
+void CameraFuzzer::getCameraInformation(int32_t cameraId) {
+    String16 cameraIdStr = String16(String8::format("%d", cameraId));
+    bool isSupported = false;
+    mCameraService->supportsCameraApi(
+        cameraIdStr, kCameraApiVersion[mFuzzedDataProvider->ConsumeBool()], &isSupported);
+    mCameraService->isHiddenPhysicalCamera(cameraIdStr, &isSupported);
+
+    String16 parameters;
+    mCameraService->getLegacyParameters(cameraId, &parameters);
+
+    std::vector<hardware::camera2::utils::ConcurrentCameraIdCombination> concurrentCameraIds;
+    mCameraService->getConcurrentCameraIds(&concurrentCameraIds);
+
+    hardware::camera2::params::VendorTagDescriptorCache cache;
+    mCameraService->getCameraVendorTagCache(&cache);
+
+    CameraInfo cameraInfo;
+    mCameraService->getCameraInfo(cameraId, &cameraInfo);
+
+    CameraMetadata metadata;
+    mCameraService->getCameraCharacteristics(cameraIdStr, &metadata);
+}
+
+void CameraFuzzer::invokeCameraSound() {
+    mCameraService->increaseSoundRef();
+    mCameraService->decreaseSoundRef();
+    bool shouldPassInvalidPlaySound = mFuzzedDataProvider->ConsumeBool();
+    bool shouldPassInvalidLockSound = mFuzzedDataProvider->ConsumeBool();
+    android::CameraService::sound_kind playSound, lockSound;
+    if (shouldPassInvalidPlaySound) {
+        playSound = static_cast<android::CameraService::sound_kind>(
+            mFuzzedDataProvider->ConsumeIntegral<size_t>());
+    } else {
+        playSound =
+            kSoundKind[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(0, kNumSoundKind - 1)];
+    }
+
+    if (shouldPassInvalidLockSound) {
+        lockSound = static_cast<android::CameraService::sound_kind>(
+            mFuzzedDataProvider->ConsumeIntegral<size_t>());
+    } else {
+        lockSound =
+            kSoundKind[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(0, kNumSoundKind - 1)];
+    }
+    mCameraService->playSound(playSound);
+    mCameraService->loadSoundLocked(lockSound);
+}
+
+void CameraFuzzer::invokeDump() {
+    Vector<String16> args;
+    size_t numberOfLines = mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(0, kMaxNumLines);
+    for (size_t lineIdx = 0; lineIdx < numberOfLines; ++lineIdx) {
+        args.add(static_cast<String16>(mFuzzedDataProvider->ConsumeRandomLengthString().c_str()));
+    }
+    const char *fileName = "logDumpFile";
+    int fd = memfd_create(fileName, MFD_ALLOW_SEALING);
+    mCameraService->dump(fd, args);
+    close(fd);
+}
+
+void CameraFuzzer::invokeShellCommand() {
+    int in = mFuzzedDataProvider->ConsumeIntegral<int>();
+    int out = mFuzzedDataProvider->ConsumeIntegral<int>();
+    int err = mFuzzedDataProvider->ConsumeIntegral<int>();
+    Vector<String16> args;
+    size_t numArgs = mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(kMinArgs, kMaxArgs);
+    for (size_t argsIdx = 0; argsIdx < numArgs; ++argsIdx) {
+        bool shouldPassInvalidCommand = mFuzzedDataProvider->ConsumeBool();
+        if (shouldPassInvalidCommand) {
+            args.add(
+                static_cast<String16>(mFuzzedDataProvider->ConsumeRandomLengthString().c_str()));
+        } else {
+            args.add(kShellCmd[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(
+                0, kNumShellCmd - 1)]);
+        }
+    }
+    mCameraService->shellCommand(in, out, err, args);
+}
+
+void CameraFuzzer::invokeNotifyCalls() {
+    mCameraService->notifyMonitoredUids();
+    int64_t newState = mFuzzedDataProvider->ConsumeIntegral<int64_t>();
+    mCameraService->notifyDeviceStateChange(newState);
+    std::vector<int32_t> args;
+    size_t numArgs = mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(kMinArgs, kMaxArgs);
+    for (size_t argsIdx = 0; argsIdx < numArgs; ++argsIdx) {
+        args.push_back(mFuzzedDataProvider->ConsumeIntegral<int32_t>());
+    }
+    bool shouldPassInvalidEvent = mFuzzedDataProvider->ConsumeBool();
+    int32_t eventId;
+    if (shouldPassInvalidEvent) {
+        eventId = mFuzzedDataProvider->ConsumeIntegral<int32_t>();
+    } else {
+        eventId = kEventId[mFuzzedDataProvider->ConsumeBool()];
+    }
+    mCameraService->notifySystemEvent(eventId, args);
+}
+
+void CameraFuzzer::invokeCameraAPIs() {
+    for (int32_t cameraId = 0; cameraId < mNumCameras; ++cameraId) {
+        getCameraInformation(cameraId);
+
+        const String16 opPackageName("com.fuzzer.poc");
+        ::android::binder::Status rc;
+        sp<ICamera> cameraDevice;
+
+        rc = mCameraService->connect(this, cameraId, opPackageName, AID_MEDIA, AID_ROOT,
+                                     &cameraDevice);
+        if (!rc.isOk()) {
+            // camera not connected
+            return;
+        }
+        if (cameraDevice) {
+            sp<Surface> previewSurface;
+            sp<SurfaceControl> surfaceControl;
+            CameraParameters params(cameraDevice->getParameters());
+            String8 focusModes(params.get(CameraParameters::KEY_SUPPORTED_FOCUS_MODES));
+            bool isAFSupported = false;
+            const char *focusMode = nullptr;
+
+            if (focusModes.contains(CameraParameters::FOCUS_MODE_AUTO)) {
+                isAFSupported = true;
+            } else if (focusModes.contains(CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE)) {
+                isAFSupported = true;
+                focusMode = CameraParameters::FOCUS_MODE_CONTINUOUS_PICTURE;
+            } else if (focusModes.contains(CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO)) {
+                isAFSupported = true;
+                focusMode = CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO;
+            } else if (focusModes.contains(CameraParameters::FOCUS_MODE_MACRO)) {
+                isAFSupported = true;
+                focusMode = CameraParameters::FOCUS_MODE_MACRO;
+            }
+            if (nullptr != focusMode) {
+                params.set(CameraParameters::KEY_FOCUS_MODE, focusMode);
+                cameraDevice->setParameters(params.flatten());
+            }
+            int previewWidth, previewHeight;
+            params.getPreviewSize(&previewWidth, &previewHeight);
+
+            mComposerClient = new SurfaceComposerClient;
+            mComposerClient->initCheck();
+
+            bool shouldPassInvalidLayerMetaData = mFuzzedDataProvider->ConsumeBool();
+            int layerMetaData;
+            if (shouldPassInvalidLayerMetaData) {
+                layerMetaData = mFuzzedDataProvider->ConsumeIntegral<int>();
+            } else {
+                layerMetaData = kLayerMetadata[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(
+                    0, kNumLayerMetaData - 1)];
+            }
+            surfaceControl = mComposerClient->createSurface(
+                String8("Test Surface"), previewWidth, previewHeight,
+                CameraParameters::previewFormatToEnum(params.getPreviewFormat()), layerMetaData);
+
+            if (surfaceControl.get() != nullptr) {
+                SurfaceComposerClient::Transaction{}
+                    .setLayer(surfaceControl, 0x7fffffff)
+                    .show(surfaceControl)
+                    .apply();
+
+                previewSurface = surfaceControl->getSurface();
+                cameraDevice->setPreviewTarget(previewSurface->getIGraphicBufferProducer());
+            }
+            cameraDevice->setPreviewCallbackFlag(CAMERA_FRAME_CALLBACK_FLAG_CAMCORDER);
+
+            Vector<Size> pictureSizes;
+            params.getSupportedPictureSizes(pictureSizes);
+
+            for (size_t i = 0; i < pictureSizes.size(); ++i) {
+                params.setPictureSize(pictureSizes[i].width, pictureSizes[i].height);
+                cameraDevice->setParameters(params.flatten());
+                cameraDevice->startPreview();
+                waitForPreviewStart();
+                cameraDevice->autoFocus();
+                waitForEvent(mAutoFocusLock, mAutoFocusCondition, mAutoFocusMessage);
+                bool shouldPassInvalidCameraMsg = mFuzzedDataProvider->ConsumeBool();
+                int msgType;
+                if (shouldPassInvalidCameraMsg) {
+                    msgType = mFuzzedDataProvider->ConsumeIntegral<int>();
+                } else {
+                    msgType = kCameraMsg[mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(
+                        0, kNumCameraMsg - 1)];
+                }
+                cameraDevice->takePicture(msgType);
+
+                waitForEvent(mSnapshotLock, mSnapshotCondition, mSnapshotNotification);
+            }
+
+            Vector<Size> videoSizes;
+            params.getSupportedVideoSizes(videoSizes);
+
+            for (size_t i = 0; i < videoSizes.size(); ++i) {
+                params.setVideoSize(videoSizes[i].width, videoSizes[i].height);
+
+                cameraDevice->setParameters(params.flatten());
+                cameraDevice->startPreview();
+                waitForPreviewStart();
+                cameraDevice->setVideoBufferMode(
+                    android::hardware::BnCamera::VIDEO_BUFFER_MODE_BUFFER_QUEUE);
+                cameraDevice->setVideoTarget(previewSurface->getIGraphicBufferProducer());
+                cameraDevice->startRecording();
+                cameraDevice->stopRecording();
+            }
+            cameraDevice->stopPreview();
+            cameraDevice->disconnect();
+        }
+    }
+}
+
+void CameraFuzzer::process(const uint8_t *data, size_t size) {
+    mFuzzedDataProvider = new FuzzedDataProvider(data, size);
+    getNumCameras();
+    invokeCameraSound();
+    if (mNumCameras > 0) {
+        invokeCameraAPIs();
+    }
+    invokeDump();
+    invokeShellCommand();
+    invokeNotifyCalls();
+    delete mFuzzedDataProvider;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    if (size < 1) {
+        return 0;
+    }
+    sp<CameraFuzzer> camerafuzzer = new CameraFuzzer();
+    if (!camerafuzzer) {
+        return 0;
+    }
+    if (camerafuzzer->init()) {
+        camerafuzzer->process(data, size);
+    }
+    return 0;
+}
diff --git a/services/camera/libcameraservice/tests/Android.mk b/services/camera/libcameraservice/tests/Android.mk
index 3ead715..b530342 100644
--- a/services/camera/libcameraservice/tests/Android.mk
+++ b/services/camera/libcameraservice/tests/Android.mk
@@ -51,6 +51,9 @@
 LOCAL_SANITIZE := address
 
 LOCAL_MODULE:= cameraservice_test
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
+LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/../NOTICE
 LOCAL_COMPATIBILITY_SUITE := device-tests
 LOCAL_MODULE_TAGS := tests
 
diff --git a/services/mediacodec/Android.bp b/services/mediacodec/Android.bp
index c4efbaa..6788afb 100644
--- a/services/mediacodec/Android.bp
+++ b/services/mediacodec/Android.bp
@@ -1,3 +1,20 @@
+package {
+    default_applicable_licenses: ["frameworks_av_services_mediacodec_license"],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_services_mediacodec_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_binary {
     name: "mediaswcodec",
     vendor_available: true,
@@ -15,18 +32,6 @@
         "libmedia_codecserviceregistrant",
     ],
 
-    target: {
-        android: {
-            product_variables: {
-                malloc_not_svelte: {
-                    // Scudo increases memory footprint, so only enable on
-                    // non-svelte devices.
-                    shared_libs: ["libc_scudo"],
-                },
-            },
-        },
-    },
-
     header_libs: [
         "libmedia_headers",
     ],
diff --git a/services/mediacodec/registrant/Android.bp b/services/mediacodec/registrant/Android.bp
index 0441cfa..696b967 100644
--- a/services/mediacodec/registrant/Android.bp
+++ b/services/mediacodec/registrant/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_services_mediacodec_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_services_mediacodec_license"],
+}
+
 cc_library_shared {
     name: "libmedia_codecserviceregistrant",
     vendor_available: true,
@@ -55,4 +64,3 @@
         "libcodec2_soft_gsmdec",
     ],
 }
-
diff --git a/services/mediacodec/seccomp_policy/mediacodec-x86.policy b/services/mediacodec/seccomp_policy/mediacodec-x86.policy
index a9d32d6..4bcc077 100644
--- a/services/mediacodec/seccomp_policy/mediacodec-x86.policy
+++ b/services/mediacodec/seccomp_policy/mediacodec-x86.policy
@@ -27,6 +27,7 @@
 mmap: 1
 fstat64: 1
 fstat: 1
+stat: 1
 stat64: 1
 statfs64: 1
 madvise: 1
diff --git a/services/mediacodec/seccomp_policy/mediacodec-x86_64.policy b/services/mediacodec/seccomp_policy/mediacodec-x86_64.policy
index a9d32d6..4bcc077 100644
--- a/services/mediacodec/seccomp_policy/mediacodec-x86_64.policy
+++ b/services/mediacodec/seccomp_policy/mediacodec-x86_64.policy
@@ -27,6 +27,7 @@
 mmap: 1
 fstat64: 1
 fstat: 1
+stat: 1
 stat64: 1
 statfs64: 1
 madvise: 1
diff --git a/services/mediacodec/seccomp_policy/mediaswcodec-x86.policy b/services/mediacodec/seccomp_policy/mediaswcodec-x86.policy
index eb71e28..9bafe7b 100644
--- a/services/mediacodec/seccomp_policy/mediaswcodec-x86.policy
+++ b/services/mediacodec/seccomp_policy/mediaswcodec-x86.policy
@@ -27,6 +27,7 @@
 mmap: 1
 fstat64: 1
 fstat: 1
+stat: 1
 stat64: 1
 statfs64: 1
 madvise: 1
diff --git a/services/mediacodec/seccomp_policy/mediaswcodec-x86_64.policy b/services/mediacodec/seccomp_policy/mediaswcodec-x86_64.policy
index e72d4db..b0ed040 100644
--- a/services/mediacodec/seccomp_policy/mediaswcodec-x86_64.policy
+++ b/services/mediacodec/seccomp_policy/mediaswcodec-x86_64.policy
@@ -27,6 +27,7 @@
 mmap: 1
 fstat64: 1
 fstat: 1
+stat: 1
 stat64: 1
 statfs64: 1
 madvise: 1
diff --git a/services/mediaextractor/Android.bp b/services/mediaextractor/Android.bp
index 0b25d62..85ce110 100644
--- a/services/mediaextractor/Android.bp
+++ b/services/mediaextractor/Android.bp
@@ -1,4 +1,23 @@
 // service library
+package {
+    default_applicable_licenses: [
+        "frameworks_av_services_mediaextractor_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_services_mediaextractor_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libmediaextractorservice",
     cflags: [
@@ -35,20 +54,6 @@
         "liblog",
         "libavservices_minijail",
     ],
-    header_libs: [
-        "bionic_libc_platform_headers",
-    ],
-    target: {
-        android: {
-            product_variables: {
-                malloc_not_svelte: {
-                    // Scudo increases memory footprint, so only enable on
-                    // non-svelte devices.
-                    shared_libs: ["libc_scudo"],
-                },
-            },
-        },
-    },
     init_rc: ["mediaextractor.rc"],
 
     cflags: [
@@ -81,4 +86,3 @@
         "code_coverage.policy",
     ],
 }
-
diff --git a/services/mediaextractor/MediaExtractorService.cpp b/services/mediaextractor/MediaExtractorService.cpp
index 9992d1c..71a5bff 100644
--- a/services/mediaextractor/MediaExtractorService.cpp
+++ b/services/mediaextractor/MediaExtractorService.cpp
@@ -39,23 +39,23 @@
 
 ::android::binder::Status MediaExtractorService::makeExtractor(
         const ::android::sp<::android::IDataSource>& remoteSource,
-        const ::std::unique_ptr< ::std::string> &mime,
+        const ::std::optional< ::std::string> &mime,
         ::android::sp<::android::IMediaExtractor>* _aidl_return) {
-    ALOGV("@@@ MediaExtractorService::makeExtractor for %s", mime.get()->c_str());
+    ALOGV("@@@ MediaExtractorService::makeExtractor for %s", mime ? mime->c_str() : nullptr);
 
     sp<DataSource> localSource = CreateDataSourceFromIDataSource(remoteSource);
 
     MediaBuffer::useSharedMemory();
     sp<IMediaExtractor> extractor = MediaExtractorFactory::CreateFromService(
             localSource,
-            mime.get() ? mime.get()->c_str() : nullptr);
+            mime ? mime->c_str() : nullptr);
 
     ALOGV("extractor service created %p (%s)",
             extractor.get(),
             extractor == nullptr ? "" : extractor->name());
 
     if (extractor != nullptr) {
-        registerMediaExtractor(extractor, localSource, mime.get() ? mime.get()->c_str() : nullptr);
+        registerMediaExtractor(extractor, localSource, mime ? mime->c_str() : nullptr);
     }
     *_aidl_return = extractor;
     return binder::Status::ok();
diff --git a/services/mediaextractor/MediaExtractorService.h b/services/mediaextractor/MediaExtractorService.h
index 1b40bf9..0081e7e 100644
--- a/services/mediaextractor/MediaExtractorService.h
+++ b/services/mediaextractor/MediaExtractorService.h
@@ -33,7 +33,7 @@
 
     virtual ::android::binder::Status makeExtractor(
             const ::android::sp<::android::IDataSource>& source,
-            const ::std::unique_ptr< ::std::string> &mime,
+            const ::std::optional< ::std::string> &mime,
             ::android::sp<::android::IMediaExtractor>* _aidl_return);
 
     virtual ::android::binder::Status makeIDataSource(
diff --git a/services/mediaextractor/main_extractorservice.cpp b/services/mediaextractor/main_extractorservice.cpp
index f21574f..10b8135 100644
--- a/services/mediaextractor/main_extractorservice.cpp
+++ b/services/mediaextractor/main_extractorservice.cpp
@@ -15,6 +15,9 @@
 ** limitations under the License.
 */
 
+//#define LOG_NDEBUG 0
+#define LOG_TAG "main_extractorservice"
+
 #include <fcntl.h>
 #include <sys/prctl.h>
 #include <sys/wait.h>
@@ -26,10 +29,9 @@
 
 #include <android-base/logging.h>
 #include <android-base/properties.h>
+#include <utils/Log.h>
 #include <utils/misc.h>
 
-#include <bionic/reserved_signals.h>
-
 // from LOCAL_C_INCLUDES
 #include "MediaExtractorService.h"
 #include "minijail.h"
@@ -43,17 +45,19 @@
 
 int main(int argc __unused, char** argv)
 {
+
+#if __has_feature(hwaddress_sanitizer)
+    ALOGI("disable media.extractor memory limits (hwasan enabled)");
+#else
+    ALOGI("enable media.extractor memory limits");
     limitProcessMemory(
         "ro.media.maxmem", /* property that defines limit */
         SIZE_MAX, /* upper limit in bytes */
         20 /* upper limit as percentage of physical RAM */);
+#endif
 
     signal(SIGPIPE, SIG_IGN);
 
-    // Do not assist platform profilers (relevant only on debug builds).
-    // Otherwise, the signal handler can violate the seccomp policy.
-    signal(BIONIC_SIGNAL_PROFILER, SIG_IGN);
-
     //b/62255959: this forces libutis.so to dlopen vendor version of libutils.so
     //before minijail is on. This is dirty but required since some syscalls such
     //as pread64 are used by linker but aren't allowed in the minijail. By
diff --git a/services/medialog/Android.bp b/services/medialog/Android.bp
index 74b63d5..cfc4c40 100644
--- a/services/medialog/Android.bp
+++ b/services/medialog/Android.bp
@@ -1,4 +1,13 @@
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
     name: "libmedialogservice",
 
     srcs: [
diff --git a/services/medialog/fuzzer/Android.bp b/services/medialog/fuzzer/Android.bp
new file mode 100644
index 0000000..9ff0ce4
--- /dev/null
+++ b/services/medialog/fuzzer/Android.bp
@@ -0,0 +1,42 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_fuzz {
+    name: "media_log_fuzzer",
+    static_libs: [
+        "libmedialogservice",
+    ],
+    srcs: [
+        "media_log_fuzzer.cpp",
+    ],
+    header_libs: [
+        "libmedia_headers",
+    ],
+    shared_libs: [
+        "libaudioutils",
+        "libbinder",
+        "liblog",
+        "libmediautils",
+        "libnblog",
+        "libutils",
+    ],
+    include_dirs: [
+        "frameworks/av/services/medialog",
+    ],
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
diff --git a/services/medialog/fuzzer/README.md b/services/medialog/fuzzer/README.md
new file mode 100644
index 0000000..b79e5c8
--- /dev/null
+++ b/services/medialog/fuzzer/README.md
@@ -0,0 +1,50 @@
+# Fuzzer for libmedialogservice
+
+## Plugin Design Considerations
+The fuzzer plugin for libmedialogservice is designed based on the understanding of the
+service and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+medialogservice supports the following parameters:
+1. Writer name (parameter name: `writerNameIdx`)
+2. Log size (parameter name: `logSize`)
+3. Enable dump before unrgister API (parameter name: `shouldDumpBeforeUnregister`)
+5. size of string for log dump (parameter name: `numberOfLines`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `writerNameIdx` | 0. `0` 1. `1` | Value obtained from FuzzedDataProvider |
+| `logSize` | In the range `256 to 65536` | Value obtained from FuzzedDataProvider |
+| `shouldDumpBeforeUnregister` | 0. `0` 1. `1` | Value obtained from FuzzedDataProvider |
+| `numberOfLines` | In the range `0 to 65535` | Value obtained from FuzzedDataProvider |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+## Build
+
+This describes steps to build media_log_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) media_log_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/media_log_fuzzer/media_log_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/services/medialog/fuzzer/media_log_fuzzer.cpp b/services/medialog/fuzzer/media_log_fuzzer.cpp
new file mode 100644
index 0000000..bd50d0f
--- /dev/null
+++ b/services/medialog/fuzzer/media_log_fuzzer.cpp
@@ -0,0 +1,76 @@
+/**
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <binder/IMemory.h>
+#include <binder/MemoryDealer.h>
+#include <private/android_filesystem_config.h>
+#include "MediaLogService.h"
+#include "fuzzer/FuzzedDataProvider.h"
+
+constexpr const char* kWriterNames[2] = {"FastMixer", "FastCapture"};
+constexpr size_t kMinSize = 0x100;
+constexpr size_t kMaxSize = 0x10000;
+constexpr size_t kLogMemorySize = 400 * 1024;
+constexpr size_t kMaxNumLines = USHRT_MAX;
+
+using namespace android;
+
+class MediaLogFuzzer {
+   public:
+    void init();
+    void process(const uint8_t* data, size_t size);
+
+   private:
+    sp<MemoryDealer> mMemoryDealer = nullptr;
+    sp<MediaLogService> mService = nullptr;
+};
+
+void MediaLogFuzzer::init() {
+    setuid(AID_MEDIA);
+    mService = new MediaLogService();
+    mMemoryDealer = new MemoryDealer(kLogMemorySize, "MediaLogFuzzer", MemoryHeapBase::READ_ONLY);
+}
+
+void MediaLogFuzzer::process(const uint8_t* data, size_t size) {
+    FuzzedDataProvider fuzzedDataProvider(data, size);
+    size_t writerNameIdx =
+        fuzzedDataProvider.ConsumeIntegralInRange<size_t>(0, std::size(kWriterNames) - 1);
+    bool shouldDumpBeforeUnregister = fuzzedDataProvider.ConsumeBool();
+    size_t logSize = fuzzedDataProvider.ConsumeIntegralInRange<size_t>(kMinSize, kMaxSize);
+    sp<IMemory> logBuffer = mMemoryDealer->allocate(NBLog::Timeline::sharedSize(logSize));
+    Vector<String16> args;
+    size_t numberOfLines = fuzzedDataProvider.ConsumeIntegralInRange<size_t>(0, kMaxNumLines);
+    for (size_t lineIdx = 0; lineIdx < numberOfLines; ++lineIdx) {
+        args.add(static_cast<String16>(fuzzedDataProvider.ConsumeRandomLengthString().c_str()));
+    }
+    const char* fileName = "logDumpFile";
+    int fd = memfd_create(fileName, MFD_ALLOW_SEALING);
+    fuzzedDataProvider.ConsumeData(logBuffer->unsecurePointer(), logBuffer->size());
+    mService->registerWriter(logBuffer, logSize, kWriterNames[writerNameIdx]);
+    if (shouldDumpBeforeUnregister) {
+        mService->dump(fd, args);
+        mService->unregisterWriter(logBuffer);
+    } else {
+        mService->unregisterWriter(logBuffer);
+        mService->dump(fd, args);
+    }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    MediaLogFuzzer mediaLogFuzzer = MediaLogFuzzer();
+    mediaLogFuzzer.init();
+    mediaLogFuzzer.process(data, size);
+    return 0;
+}
diff --git a/services/mediametrics/Android.bp b/services/mediametrics/Android.bp
index 91590e1..b2a0cda 100644
--- a/services/mediametrics/Android.bp
+++ b/services/mediametrics/Android.bp
@@ -1,6 +1,15 @@
 // Media Statistics service
 //
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 tidy_errors = [
     // https://clang.llvm.org/extra/clang-tidy/checks/list.html
     // For many categories, the checks are too many to specify individually.
@@ -21,7 +30,7 @@
     "modernize-loop-convert",
     "modernize-make-shared",
     "modernize-make-unique",
-    "modernize-pass-by-value",
+    // "modernize-pass-by-value", // found in TimeMachine.h
     "modernize-raw-string-literal",
     "modernize-redundant-void-arg",
     "modernize-replace-auto-ptr",
@@ -29,13 +38,13 @@
     "modernize-return-braced-init-list",
     "modernize-shrink-to-fit",
     "modernize-unary-static-assert",
-    "modernize-use-auto",  // debatable - auto can obscure type
+    // "modernize-use-auto",  // found in MediaMetricsService.h, debatable - auto can obscure type
     "modernize-use-bool-literals",
     "modernize-use-default-member-init",
     "modernize-use-emplace",
     "modernize-use-equals-default",
     "modernize-use-equals-delete",
-    "modernize-use-nodiscard",
+    // "modernize-use-nodiscard", // found in TimeMachine.h
     "modernize-use-noexcept",
     "modernize-use-nullptr",
     "modernize-use-override",
@@ -48,6 +57,10 @@
     // Remove some pedantic stylistic requirements.
     "-google-readability-casting", // C++ casts not always necessary and may be verbose
     "-google-readability-todo",    // do not require TODO(info)
+
+    "-bugprone-unhandled-self-assignment", // found in TimeMachine.h
+    "-bugprone-suspicious-string-compare", // found in TimeMachine.h
+    "-cert-oop54-cpp", // found in TransactionLog.h
 ]
 
 cc_defaults {
@@ -79,8 +92,7 @@
     tidy_checks: tidy_errors,
     tidy_checks_as_errors: tidy_errors,
     tidy_flags: [
-      "-format-style='file'",
-      "--header-filter='frameworks/av/services/mediametrics/'",
+      "-format-style=file",
     ],
 }
 
@@ -111,7 +123,7 @@
     ],
 }
 
-cc_library_shared {
+cc_library {
     name: "libmediametricsservice",
     defaults: [
         "mediametrics_flags_defaults",
diff --git a/services/mediametrics/AudioPowerUsage.cpp b/services/mediametrics/AudioPowerUsage.cpp
index 33dfa8fa..34be0b9 100644
--- a/services/mediametrics/AudioPowerUsage.cpp
+++ b/services/mediametrics/AudioPowerUsage.cpp
@@ -28,7 +28,7 @@
 #include <cutils/properties.h>
 #include <statslog.h>
 #include <sys/timerfd.h>
-#include <system/audio-base.h>
+#include <system/audio.h>
 
 // property to disable audio power use metrics feature, default is enabled
 #define PROP_AUDIO_METRICS_DISABLED "persist.media.audio_metrics.power_usage_disabled"
diff --git a/services/mediametrics/benchmarks/Android.bp b/services/mediametrics/benchmarks/Android.bp
index b61f44f..68d4145 100644
--- a/services/mediametrics/benchmarks/Android.bp
+++ b/services/mediametrics/benchmarks/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "mediametrics_benchmarks",
     srcs: ["mediametrics_benchmarks.cpp"],
diff --git a/services/mediametrics/fuzzer/Android.bp b/services/mediametrics/fuzzer/Android.bp
new file mode 100644
index 0000000..3053666
--- /dev/null
+++ b/services/mediametrics/fuzzer/Android.bp
@@ -0,0 +1,68 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_fuzz {
+    name: "mediametrics_service_fuzzer",
+
+    srcs: [
+        "mediametrics_service_fuzzer.cpp",
+    ],
+
+    static_libs: [
+        "libmediametrics",
+        "libmediametricsservice",
+        "libplatformprotos",
+    ],
+
+    shared_libs: [
+        "libbase",
+        "libbinder",
+        "libcutils",
+        "liblog",
+        "libmedia_helper",
+        "libmediautils",
+        "libmemunreachable",
+        "libprotobuf-cpp-lite",
+        "libstagefright",
+        "libstatslog",
+        "libutils",
+    ],
+
+    include_dirs: [
+        "frameworks/av/services/mediametrics",
+        "system/media/audio_utils/include",
+    ],
+
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
diff --git a/services/mediametrics/fuzzer/README.md b/services/mediametrics/fuzzer/README.md
new file mode 100644
index 0000000..a13830e
--- /dev/null
+++ b/services/mediametrics/fuzzer/README.md
@@ -0,0 +1,54 @@
+# Fuzzer for libmediametricsservice
+
+## Plugin Design Considerations
+The fuzzer plugin for libmediametricsservice is designed based on the
+understanding of the service and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+Media Metrics Service contains the following modules:
+1. Media Metrics Item Manipulation (module name: `Item`)
+2. Media Metrics Time Machine Storage (module name: `TimeMachineStorage`)
+3. Media Metrics Transaction Log (module name: `TransactionLog`)
+4. Media Metrics Analytics Action (module name: `AnalyticsAction`)
+5. Media Metrics Audio Analytics (module name: `AudioAnalytics`)
+6. Media Metrics Timed Action (module name: `TimedAction`)
+
+| Module| Valid Input Values| Configured Value|
+|------------- |-------------| ----- |
+| `Item` | Key: `std::string`. Values: `INT32_MIN` to `INT32_MAX`, `INT64_MIN` to `INT64_MAX`, `std::string`, `double`, `pair<INT32_MIN to INT32_MAX, INT32_MIN to INT32_MAX>` | Value obtained from FuzzedDataProvider |
+| `TimeMachineStorage`   | Key: `std::string`. Values: `INT32_MIN` to `INT32_MAX`, `INT64_MIN` to `INT64_MAX`, `std::string`, `double`, `pair<INT32_MIN to INT32_MAX, INT32_MIN to INT32_MAX>` | Value obtained from FuzzedDataProvider |
+| `TranscationLog`   | `mediametrics::Item` | `mediametrics::Item` created by obtaining values from FuzzedDataProvider|
+| `AnalyticsAction`   | URL: `std::string` ending with .event, Value: `std::string`, action: A function | URL and Values obtained from FuzzedDataProvider, a placeholder function was passed as action|
+| `AudioAnalytics`   | `mediametrics::Item` | `mediametrics::Item` created by obtaining values from FuzzedDataProvider|
+| `TimedAction`   | time: `std::chrono::seconds`, function: `std::function` | `std::chrono::seconds` : value obtained from FuzzedDataProvider, `std::function`: a placeholder function was used. |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+## Build
+
+This describes steps to build mediametrics_service_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mediametrics_service_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/mediametrics_service_fuzzer/mediametrics_service_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/services/mediametrics/fuzzer/mediametrics_service_fuzzer.cpp b/services/mediametrics/fuzzer/mediametrics_service_fuzzer.cpp
new file mode 100644
index 0000000..0cb2594
--- /dev/null
+++ b/services/mediametrics/fuzzer/mediametrics_service_fuzzer.cpp
@@ -0,0 +1,372 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2020 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+#include <fuzzer/FuzzedDataProvider.h>
+#include <media/MediaMetricsItem.h>
+#include <stdio.h>
+#include <string.h>
+#include <utils/Log.h>
+#include <algorithm>
+
+#include "AudioTypes.h"
+#include "MediaMetricsService.h"
+#include "StringUtils.h"
+
+using namespace android;
+
+// low water mark
+constexpr size_t kLogItemsLowWater = 1;
+// high water mark
+constexpr size_t kLogItemsHighWater = 2;
+
+class MediaMetricsServiceFuzzer {
+   public:
+    void invokeStartsWith(const uint8_t *data, size_t size);
+    void invokeInstantiate(const uint8_t *data, size_t size);
+    void invokePackageInstallerCheck(const uint8_t *data, size_t size);
+    void invokeItemManipulation(const uint8_t *data, size_t size);
+    void invokeItemExpansion(const uint8_t *data, size_t size);
+    void invokeTimeMachineStorage(const uint8_t *data, size_t size);
+    void invokeTransactionLog(const uint8_t *data, size_t size);
+    void invokeAnalyticsAction(const uint8_t *data, size_t size);
+    void invokeAudioAnalytics(const uint8_t *data, size_t size);
+    void invokeTimedAction(const uint8_t *data, size_t size);
+    void process(const uint8_t *data, size_t size);
+};
+
+void MediaMetricsServiceFuzzer::invokeStartsWith(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+    while (fdp.remaining_bytes()) {
+        android::mediametrics::startsWith(fdp.ConsumeRandomLengthString(),
+                                          fdp.ConsumeRandomLengthString());
+    }
+}
+
+void MediaMetricsServiceFuzzer::invokeInstantiate(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+    sp mediaMetricsService = new MediaMetricsService();
+
+    while (fdp.remaining_bytes()) {
+        std::unique_ptr<mediametrics::Item> random_key(
+            mediametrics::Item::create(fdp.ConsumeRandomLengthString()));
+        mediaMetricsService->submit(random_key.get());
+        random_key->setInt32(fdp.ConsumeRandomLengthString().c_str(),
+                             fdp.ConsumeIntegral<int32_t>());
+        mediaMetricsService->submit(random_key.get());
+
+        std::unique_ptr<mediametrics::Item> audiotrack_key(
+            mediametrics::Item::create("audiotrack"));
+        mediaMetricsService->submit(audiotrack_key.get());
+        audiotrack_key->addInt32(fdp.ConsumeRandomLengthString().c_str(),
+                                 fdp.ConsumeIntegral<int32_t>());
+        mediaMetricsService->submit(audiotrack_key.get());
+    }
+}
+
+void MediaMetricsServiceFuzzer::invokePackageInstallerCheck(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+    while (fdp.remaining_bytes()) {
+        MediaMetricsService::useUidForPackage(fdp.ConsumeRandomLengthString().c_str(),
+                                              fdp.ConsumeRandomLengthString().c_str());
+    }
+}
+
+void MediaMetricsServiceFuzzer::invokeItemManipulation(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+
+    mediametrics::Item item(fdp.ConsumeRandomLengthString().c_str());
+    while (fdp.remaining_bytes()) {
+        const uint8_t action = fdp.ConsumeIntegralInRange<uint8_t>(0, 16);
+        const std::string key = fdp.ConsumeRandomLengthString();
+        if (fdp.remaining_bytes() < 1 || key.length() < 1) {
+            break;
+        }
+        switch (action) {
+            case 0: {
+                item.setInt32(key.c_str(), fdp.ConsumeIntegral<int32_t>());
+                break;
+            }
+            case 1: {
+                item.addInt32(key.c_str(), fdp.ConsumeIntegral<int32_t>());
+                break;
+            }
+            case 2: {
+                int32_t i32 = 0;
+                item.getInt32(key.c_str(), &i32);
+                break;
+            }
+            case 3: {
+                item.setInt64(key.c_str(), fdp.ConsumeIntegral<int64_t>());
+                break;
+            }
+            case 4: {
+                item.addInt64(key.c_str(), fdp.ConsumeIntegral<int64_t>());
+                break;
+            }
+            case 5: {
+                int64_t i64 = 0;
+                item.getInt64(key.c_str(), &i64);
+                break;
+            }
+            case 6: {
+                item.setDouble(key.c_str(), fdp.ConsumeFloatingPoint<double>());
+                break;
+            }
+            case 7: {
+                item.addDouble(key.c_str(), fdp.ConsumeFloatingPoint<double>());
+                break;
+            }
+            case 8: {
+                double d = 0;
+                item.getDouble(key.c_str(), &d);
+                break;
+            }
+            case 9: {
+                item.setCString(key.c_str(), fdp.ConsumeRandomLengthString().c_str());
+                break;
+            }
+            case 10: {
+                char *s = nullptr;
+                item.getCString(key.c_str(), &s);
+                if (s) free(s);
+                break;
+            }
+            case 11: {
+                std::string s;
+                item.getString(key.c_str(), &s);
+                break;
+            }
+            case 12: {
+                item.setRate(key.c_str(), fdp.ConsumeIntegral<int64_t>(),
+                             fdp.ConsumeIntegral<int64_t>());
+                break;
+            }
+            case 13: {
+                int64_t b = 0, h = 0;
+                double d = 0;
+                item.getRate(key.c_str(), &b, &h, &d);
+                break;
+            }
+            case 14: {
+                (void)item.filter(key.c_str());
+                break;
+            }
+            case 15: {
+                const char *arr[1] = {""};
+                arr[0] = const_cast<char *>(key.c_str());
+                (void)item.filterNot(1, arr);
+                break;
+            }
+            case 16: {
+                (void)item.toString().c_str();
+                break;
+            }
+        }
+    }
+
+    Parcel p;
+    mediametrics::Item item2;
+
+    (void)item.writeToParcel(&p);
+    p.setDataPosition(0);  // rewind for reading
+    (void)item2.readFromParcel(p);
+
+    char *byteData = nullptr;
+    size_t length = 0;
+    (void)item.writeToByteString(&byteData, &length);
+    (void)item2.readFromByteString(byteData, length);
+    if (byteData) {
+        free(byteData);
+    }
+
+    sp mediaMetricsService = new MediaMetricsService();
+    mediaMetricsService->submit(&item2);
+}
+
+void MediaMetricsServiceFuzzer::invokeItemExpansion(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+
+    mediametrics::LogItem<1> item("FuzzItem");
+    item.setPid(fdp.ConsumeIntegral<int16_t>()).setUid(fdp.ConsumeIntegral<int16_t>());
+
+    while (fdp.remaining_bytes()) {
+        int32_t i = fdp.ConsumeIntegral<int32_t>();
+        item.set(std::to_string(i).c_str(), (int32_t)i);
+    }
+    item.updateHeader();
+
+    mediametrics::Item item2;
+    (void)item2.readFromByteString(item.getBuffer(), item.getLength());
+
+    sp mediaMetricsService = new MediaMetricsService();
+    mediaMetricsService->submit(&item2);
+}
+
+void MediaMetricsServiceFuzzer::invokeTimeMachineStorage(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+
+    auto item = std::make_shared<mediametrics::Item>("FuzzKey");
+    int32_t i32 = fdp.ConsumeIntegral<int32_t>();
+    int64_t i64 = fdp.ConsumeIntegral<int64_t>();
+    double d = fdp.ConsumeFloatingPoint<double>();
+    std::string str = fdp.ConsumeRandomLengthString();
+    std::pair<int64_t, int64_t> pair(fdp.ConsumeIntegral<int64_t>(),
+                                     fdp.ConsumeIntegral<int64_t>());
+    (*item).set("i32", i32).set("i64", i64).set("double", d).set("string", str).set("rate", pair);
+
+    android::mediametrics::TimeMachine timeMachine;
+    timeMachine.put(item, true);
+
+    timeMachine.get("Key", "i32", &i32, -1);
+
+    timeMachine.get("Key", "i64", &i64, -1);
+
+    timeMachine.get("Key", "double", &d, -1);
+
+    timeMachine.get("Key", "string", &str, -1);
+
+    timeMachine.get("Key.i32", &i32, -1);
+
+    timeMachine.get("Key.i64", &i64, -1);
+
+    timeMachine.get("Key.double", &d, -1);
+
+    str.clear();
+    timeMachine.get("Key.string", &str, -1);
+}
+
+void MediaMetricsServiceFuzzer::invokeTransactionLog(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+
+    auto item = std::make_shared<mediametrics::Item>("Key1");
+    (*item)
+        .set("one", fdp.ConsumeIntegral<int32_t>())
+        .set("two", fdp.ConsumeIntegral<int32_t>())
+        .setTimestamp(fdp.ConsumeIntegral<int32_t>());
+
+    android::mediametrics::TransactionLog transactionLog(
+        kLogItemsLowWater, kLogItemsHighWater);  // keep at most 2 items
+    transactionLog.size();
+
+    transactionLog.put(item);
+    transactionLog.size();
+
+    auto item2 = std::make_shared<mediametrics::Item>("Key2");
+    (*item2)
+        .set("three", fdp.ConsumeIntegral<int32_t>())
+        .set("[Key1]three", fdp.ConsumeIntegral<int32_t>())
+        .setTimestamp(fdp.ConsumeIntegral<int32_t>());
+
+    transactionLog.put(item2);
+    transactionLog.size();
+
+    auto item3 = std::make_shared<mediametrics::Item>("Key3");
+    (*item3)
+        .set("six", fdp.ConsumeIntegral<int32_t>())
+        .set("[Key1]four", fdp.ConsumeIntegral<int32_t>())  // affects Key1
+        .set("[Key1]five", fdp.ConsumeIntegral<int32_t>())  // affects key1
+        .setTimestamp(fdp.ConsumeIntegral<int32_t>());
+
+    transactionLog.put(item3);
+    transactionLog.size();
+}
+
+void MediaMetricsServiceFuzzer::invokeAnalyticsAction(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+
+    mediametrics::AnalyticsActions analyticsActions;
+    bool action = false;
+
+    while (fdp.remaining_bytes()) {
+        analyticsActions.addAction(
+            (fdp.ConsumeRandomLengthString() + std::string(".event")).c_str(),
+            fdp.ConsumeRandomLengthString(),
+            std::make_shared<mediametrics::AnalyticsActions::Function>(
+                [&](const std::shared_ptr<const android::mediametrics::Item> &) {
+                    action = true;
+                }));
+    }
+
+    FuzzedDataProvider fdp2 = FuzzedDataProvider(data, size);
+
+    while (fdp2.remaining_bytes()) {
+        // make a test item
+        auto item = std::make_shared<mediametrics::Item>(fdp2.ConsumeRandomLengthString().c_str());
+        (*item).set("event", fdp2.ConsumeRandomLengthString().c_str());
+
+        // get the actions and execute them
+        auto actions = analyticsActions.getActionsForItem(item);
+        for (const auto &action : actions) {
+            action->operator()(item);
+        }
+    }
+}
+
+void MediaMetricsServiceFuzzer::invokeAudioAnalytics(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+    android::mediametrics::AudioAnalytics audioAnalytics;
+
+    while (fdp.remaining_bytes()) {
+        auto item = std::make_shared<mediametrics::Item>(fdp.ConsumeRandomLengthString().c_str());
+        int32_t transactionUid = fdp.ConsumeIntegral<int32_t>();  // arbitrary
+        (*item)
+            .set(fdp.ConsumeRandomLengthString().c_str(), fdp.ConsumeIntegral<int32_t>())
+            .set(fdp.ConsumeRandomLengthString().c_str(), fdp.ConsumeIntegral<int32_t>())
+            .set(AMEDIAMETRICS_PROP_ALLOWUID, transactionUid)
+            .setUid(transactionUid)
+            .setTimestamp(fdp.ConsumeIntegral<int32_t>());
+        audioAnalytics.submit(item, fdp.ConsumeBool());
+    }
+
+    audioAnalytics.dump(1000);
+}
+
+void MediaMetricsServiceFuzzer::invokeTimedAction(const uint8_t *data, size_t size) {
+    FuzzedDataProvider fdp = FuzzedDataProvider(data, size);
+    android::mediametrics::TimedAction timedAction;
+    std::atomic_int value = 0;
+
+    while (fdp.remaining_bytes()) {
+        timedAction.postIn(std::chrono::seconds(fdp.ConsumeIntegral<int32_t>()),
+                           [&value] { ++value; });
+        timedAction.size();
+    }
+}
+
+void MediaMetricsServiceFuzzer::process(const uint8_t *data, size_t size) {
+    invokeStartsWith(data, size);
+    invokeInstantiate(data, size);
+    invokePackageInstallerCheck(data, size);
+    invokeItemManipulation(data, size);
+    invokeItemExpansion(data, size);
+    invokeTimeMachineStorage(data, size);
+    invokeTransactionLog(data, size);
+    invokeAnalyticsAction(data, size);
+    invokeAudioAnalytics(data, size);
+    invokeTimedAction(data, size);
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+    if (size < 1) {
+        return 0;
+    }
+    MediaMetricsServiceFuzzer mediaMetricsServiceFuzzer;
+    mediaMetricsServiceFuzzer.process(data, size);
+    return 0;
+}
diff --git a/services/mediametrics/statsd_audiopolicy.cpp b/services/mediametrics/statsd_audiopolicy.cpp
index 393c6ae..6ef2f2c 100644
--- a/services/mediametrics/statsd_audiopolicy.cpp
+++ b/services/mediametrics/statsd_audiopolicy.cpp
@@ -32,7 +32,7 @@
 #include <statslog.h>
 
 #include "MediaMetricsService.h"
-#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h"
 #include "iface_statsd.h"
 
 namespace android {
diff --git a/services/mediametrics/statsd_audiorecord.cpp b/services/mediametrics/statsd_audiorecord.cpp
index 43feda1..76f4b59 100644
--- a/services/mediametrics/statsd_audiorecord.cpp
+++ b/services/mediametrics/statsd_audiorecord.cpp
@@ -32,7 +32,7 @@
 #include <statslog.h>
 
 #include "MediaMetricsService.h"
-#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h"
 #include "iface_statsd.h"
 
 namespace android {
diff --git a/services/mediametrics/statsd_audiothread.cpp b/services/mediametrics/statsd_audiothread.cpp
index e867f5b..2ad2562 100644
--- a/services/mediametrics/statsd_audiothread.cpp
+++ b/services/mediametrics/statsd_audiothread.cpp
@@ -32,7 +32,7 @@
 #include <statslog.h>
 
 #include "MediaMetricsService.h"
-#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h"
 #include "iface_statsd.h"
 
 namespace android {
diff --git a/services/mediametrics/statsd_audiotrack.cpp b/services/mediametrics/statsd_audiotrack.cpp
index ee5b9b2..6b08a78 100644
--- a/services/mediametrics/statsd_audiotrack.cpp
+++ b/services/mediametrics/statsd_audiotrack.cpp
@@ -32,7 +32,7 @@
 #include <statslog.h>
 
 #include "MediaMetricsService.h"
-#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h"
 #include "iface_statsd.h"
 
 namespace android {
diff --git a/services/mediametrics/statsd_codec.cpp b/services/mediametrics/statsd_codec.cpp
index ec9354f..d502b30 100644
--- a/services/mediametrics/statsd_codec.cpp
+++ b/services/mediametrics/statsd_codec.cpp
@@ -33,7 +33,7 @@
 
 #include "cleaner.h"
 #include "MediaMetricsService.h"
-#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h"
 #include "iface_statsd.h"
 
 namespace android {
diff --git a/services/mediametrics/statsd_extractor.cpp b/services/mediametrics/statsd_extractor.cpp
index fb0924c..4180e0c 100644
--- a/services/mediametrics/statsd_extractor.cpp
+++ b/services/mediametrics/statsd_extractor.cpp
@@ -32,7 +32,7 @@
 #include <statslog.h>
 
 #include "MediaMetricsService.h"
-#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h"
 #include "iface_statsd.h"
 
 namespace android {
diff --git a/services/mediametrics/statsd_mediaparser.cpp b/services/mediametrics/statsd_mediaparser.cpp
index 3258ebf..262b2ae 100644
--- a/services/mediametrics/statsd_mediaparser.cpp
+++ b/services/mediametrics/statsd_mediaparser.cpp
@@ -31,7 +31,7 @@
 #include <statslog.h>
 
 #include "MediaMetricsService.h"
-#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h"
 #include "iface_statsd.h"
 
 namespace android {
diff --git a/services/mediametrics/statsd_nuplayer.cpp b/services/mediametrics/statsd_nuplayer.cpp
index 488bdcb..a8d0f55 100644
--- a/services/mediametrics/statsd_nuplayer.cpp
+++ b/services/mediametrics/statsd_nuplayer.cpp
@@ -32,7 +32,7 @@
 #include <statslog.h>
 
 #include "MediaMetricsService.h"
-#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h"
 #include "iface_statsd.h"
 
 namespace android {
diff --git a/services/mediametrics/statsd_recorder.cpp b/services/mediametrics/statsd_recorder.cpp
index 6d5fca0..2e5ada4 100644
--- a/services/mediametrics/statsd_recorder.cpp
+++ b/services/mediametrics/statsd_recorder.cpp
@@ -32,7 +32,7 @@
 #include <statslog.h>
 
 #include "MediaMetricsService.h"
-#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h"
 #include "iface_statsd.h"
 
 namespace android {
diff --git a/services/mediametrics/tests/Android.bp b/services/mediametrics/tests/Android.bp
index c2e0759..3aee209 100644
--- a/services/mediametrics/tests/Android.bp
+++ b/services/mediametrics/tests/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "mediametrics_tests",
     test_suites: ["device-tests"],
diff --git a/services/mediaresourcemanager/Android.bp b/services/mediaresourcemanager/Android.bp
index a3519d5..e503885 100644
--- a/services/mediaresourcemanager/Android.bp
+++ b/services/mediaresourcemanager/Android.bp
@@ -1,6 +1,13 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
 
-
-cc_library_shared {
+cc_library {
     name: "libresourcemanagerservice",
 
     srcs: [
@@ -25,5 +32,4 @@
     ],
 
     export_include_dirs: ["."],
-
 }
diff --git a/services/mediaresourcemanager/ResourceManagerService.h b/services/mediaresourcemanager/ResourceManagerService.h
index 3972d23..7f18ed3 100644
--- a/services/mediaresourcemanager/ResourceManagerService.h
+++ b/services/mediaresourcemanager/ResourceManagerService.h
@@ -43,7 +43,7 @@
 using ::aidl::android::media::MediaResourcePolicyParcel;
 
 typedef std::map<std::tuple<
-        MediaResource::Type, MediaResource::SubType, std::vector<int8_t>>,
+        MediaResource::Type, MediaResource::SubType, std::vector<uint8_t>>,
         MediaResourceParcel> ResourceList;
 
 struct ResourceInfo {
diff --git a/services/mediaresourcemanager/fuzzer/Android.bp b/services/mediaresourcemanager/fuzzer/Android.bp
new file mode 100644
index 0000000..81c85e5
--- /dev/null
+++ b/services/mediaresourcemanager/fuzzer/Android.bp
@@ -0,0 +1,51 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2021 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_fuzz {
+    name: "mediaresourcemanager_fuzzer",
+    srcs: [
+        "mediaresourcemanager_fuzzer.cpp",
+    ],
+    static_libs: [
+        "liblog",
+        "libresourcemanagerservice",
+    ],
+    shared_libs: [
+        "libbinder",
+        "libbinder_ndk",
+        "libmedia",
+        "libutils",
+    ],
+    fuzz_config: {
+        cc: [
+            "android-media-fuzzing-reports@google.com",
+        ],
+        componentid: 155276,
+    },
+}
diff --git a/services/mediaresourcemanager/fuzzer/README.md b/services/mediaresourcemanager/fuzzer/README.md
new file mode 100644
index 0000000..c600be4
--- /dev/null
+++ b/services/mediaresourcemanager/fuzzer/README.md
@@ -0,0 +1,46 @@
+# Fuzzer for libresourcemanagerservice
+
+## Plugin Design Considerations
+The fuzzer plugin for libresourcemanagerservice is designed based on the
+understanding of the service and tries to achieve the following:
+
+##### Maximize code coverage
+The configuration parameters are not hardcoded, but instead selected based on
+incoming data. This ensures more code paths are reached by the fuzzer.
+
+Media Resource Manager supports the following parameters:
+1. Media Resource Type (parameter name: `mediaResourceType`)
+2. Media Resource SubType (parameter name: `mediaResourceSubType`)
+
+| Parameter| Valid Values| Configured Value|
+|------------- |-------------| ----- |
+| `mediaResourceType` | 0.`MediaResource::kSecureCodec` 1.`MediaResource::kNonSecureCodecC` 2.`MediaResource::kGraphicMemory` 3.`MediaResource::kCpuBoost`  4.`MediaResource::kBattery` 5.`MediaResource::kDrmSession`| Value obtained from FuzzedDataProvider |
+| `mediaResourceSubType`   | 0.`MediaResource::kAudioCodec` 1.`MediaResource::kVideoCodec` 2.`MediaResource::kUnspecifiedSubType`  | Value obtained from FuzzedDataProvider |
+
+This also ensures that the plugin is always deterministic for any given input.
+
+## Build
+
+This describes steps to build mediaresourcemanager_fuzzer binary.
+
+### Android
+
+#### Steps to build
+Build the fuzzer
+```
+  $ mm -j$(nproc) mediaresourcemanager_fuzzer
+```
+
+#### Steps to run
+Create a directory CORPUS_DIR and copy some files to that folder
+Push this directory to device.
+
+To run on device
+```
+  $ adb sync data
+  $ adb shell /data/fuzz/arm64/mediaresourcemanager_fuzzer/mediaresourcemanager_fuzzer CORPUS_DIR
+```
+
+## References:
+ * http://llvm.org/docs/LibFuzzer.html
+ * https://github.com/google/oss-fuzz
diff --git a/services/mediaresourcemanager/fuzzer/mediaresourcemanager_fuzzer.cpp b/services/mediaresourcemanager/fuzzer/mediaresourcemanager_fuzzer.cpp
new file mode 100644
index 0000000..6690b16
--- /dev/null
+++ b/services/mediaresourcemanager/fuzzer/mediaresourcemanager_fuzzer.cpp
@@ -0,0 +1,299 @@
+/******************************************************************************
+ *
+ * Copyright (C) 2021 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.
+ *
+ *****************************************************************************
+ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
+ */
+
+#include <ServiceLog.h>
+#include <aidl/android/media/BnResourceManagerClient.h>
+#include <media/MediaResource.h>
+#include <media/MediaResourcePolicy.h>
+#include <media/stagefright/ProcessInfoInterface.h>
+#include <media/stagefright/foundation/ADebug.h>
+#include "ResourceManagerService.h"
+#include "fuzzer/FuzzedDataProvider.h"
+
+using namespace std;
+using namespace android;
+using Status = ::ndk::ScopedAStatus;
+using ::aidl::android::media::BnResourceManagerClient;
+using ::aidl::android::media::IResourceManagerClient;
+using ::aidl::android::media::IResourceManagerService;
+using MedResType = aidl::android::media::MediaResourceType;
+using MedResSubType = aidl::android::media::MediaResourceSubType;
+
+const size_t kMaxStringLength = 100;
+const int32_t kMaxServiceLog = 100;
+const int32_t kMinServiceLog = 1;
+const int32_t kMinResourceType = 0;
+const int32_t kMaxResourceType = 10;
+const int32_t kMinThreadPairs = 1;
+const int32_t kMaxThreadPairs = 3;
+
+const string kPolicyType[] = {IResourceManagerService::kPolicySupportsMultipleSecureCodecs,
+                              IResourceManagerService::kPolicySupportsSecureWithNonSecureCodec};
+
+struct resourceThreadArgs {
+    int32_t pid;
+    int32_t uid;
+    int64_t testClientId;
+    shared_ptr<ResourceManagerService> service;
+    shared_ptr<IResourceManagerClient> testClient;
+    vector<MediaResourceParcel> mediaResource;
+};
+
+static int64_t getId(const shared_ptr<IResourceManagerClient>& client) {
+    return (int64_t)client.get();
+}
+
+struct TestProcessInfo : public ProcessInfoInterface {
+    TestProcessInfo() {}
+    virtual ~TestProcessInfo() {}
+
+    virtual bool getPriority(int pid, int* priority) {
+        // For testing, use pid as priority.
+        // Lower the value higher the priority.
+        *priority = pid;
+        return true;
+    }
+
+    virtual bool isValidPid(int /* pid */) { return true; }
+    virtual bool overrideProcessInfo(int /* pid */, int /*procState*/, int /*oomScore*/) {
+        return true;
+    }
+    virtual void removeProcessInfoOverride(int /* pid */) { return; }
+
+   private:
+    DISALLOW_EVIL_CONSTRUCTORS(TestProcessInfo);
+};
+
+struct TestSystemCallback : public ResourceManagerService::SystemCallbackInterface {
+    TestSystemCallback() : mLastEvent({EventType::INVALID, 0}), mEventCount(0) {}
+
+    enum EventType {
+        INVALID = -1,
+        VIDEO_ON = 0,
+        VIDEO_OFF = 1,
+        VIDEO_RESET = 2,
+        CPUSET_ENABLE = 3,
+        CPUSET_DISABLE = 4,
+    };
+
+    struct EventEntry {
+        EventType type;
+        int arg;
+    };
+
+    virtual void noteStartVideo(int uid) override {
+        mLastEvent = {EventType::VIDEO_ON, uid};
+        ++mEventCount;
+    }
+
+    virtual void noteStopVideo(int uid) override {
+        mLastEvent = {EventType::VIDEO_OFF, uid};
+        ++mEventCount;
+    }
+
+    virtual void noteResetVideo() override {
+        mLastEvent = {EventType::VIDEO_RESET, 0};
+        ++mEventCount;
+    }
+
+    virtual bool requestCpusetBoost(bool enable) override {
+        mLastEvent = {enable ? EventType::CPUSET_ENABLE : EventType::CPUSET_DISABLE, 0};
+        ++mEventCount;
+        return true;
+    }
+
+    size_t eventCount() { return mEventCount; }
+    EventType lastEventType() { return mLastEvent.type; }
+    EventEntry lastEvent() { return mLastEvent; }
+
+   protected:
+    virtual ~TestSystemCallback() {}
+
+   private:
+    EventEntry mLastEvent;
+    size_t mEventCount;
+
+    DISALLOW_EVIL_CONSTRUCTORS(TestSystemCallback);
+};
+
+struct TestClient : public BnResourceManagerClient {
+    TestClient(int pid, const shared_ptr<ResourceManagerService>& service)
+        : mReclaimed(false), mPid(pid), mService(service) {}
+
+    Status reclaimResource(bool* aidlReturn) override {
+        mService->removeClient(mPid, getId(ref<TestClient>()));
+        mReclaimed = true;
+        *aidlReturn = true;
+        return Status::ok();
+    }
+
+    Status getName(string* aidlReturn) override {
+        *aidlReturn = "test_client";
+        return Status::ok();
+    }
+
+    virtual ~TestClient() {}
+
+   private:
+    bool mReclaimed;
+    int mPid;
+    shared_ptr<ResourceManagerService> mService;
+    DISALLOW_EVIL_CONSTRUCTORS(TestClient);
+};
+
+class ResourceManagerServiceFuzzer {
+   public:
+    ResourceManagerServiceFuzzer() = default;
+    ~ResourceManagerServiceFuzzer() {
+        mService = nullptr;
+        delete mFuzzedDataProvider;
+    }
+    void process(const uint8_t* data, size_t size);
+
+   private:
+    void setConfig();
+    void setResources();
+    void setServiceLog();
+
+    static void* addResource(void* arg) {
+        resourceThreadArgs* tArgs = (resourceThreadArgs*)arg;
+        if (tArgs) {
+            (tArgs->service)
+                ->addResource(tArgs->pid, tArgs->uid, tArgs->testClientId, tArgs->testClient,
+                              tArgs->mediaResource);
+        }
+        return nullptr;
+    }
+
+    static void* removeResource(void* arg) {
+        resourceThreadArgs* tArgs = (resourceThreadArgs*)arg;
+        if (tArgs) {
+            bool result;
+            (tArgs->service)->markClientForPendingRemoval(tArgs->pid, tArgs->testClientId);
+            (tArgs->service)->removeResource(tArgs->pid, tArgs->testClientId, tArgs->mediaResource);
+            (tArgs->service)->reclaimResource(tArgs->pid, tArgs->mediaResource, &result);
+            (tArgs->service)->removeClient(tArgs->pid, tArgs->testClientId);
+            (tArgs->service)->overridePid(tArgs->pid, tArgs->pid - 1);
+        }
+        return nullptr;
+    }
+
+    shared_ptr<ResourceManagerService> mService =
+        ::ndk::SharedRefBase::make<ResourceManagerService>(new TestProcessInfo(),
+                                                           new TestSystemCallback());
+    FuzzedDataProvider* mFuzzedDataProvider = nullptr;
+};
+
+void ResourceManagerServiceFuzzer::process(const uint8_t* data, size_t size) {
+    mFuzzedDataProvider = new FuzzedDataProvider(data, size);
+    setConfig();
+    setResources();
+    setServiceLog();
+}
+
+void ResourceManagerServiceFuzzer::setConfig() {
+    bool policyTypeIndex = mFuzzedDataProvider->ConsumeBool();
+    string policyValue = mFuzzedDataProvider->ConsumeRandomLengthString(kMaxStringLength);
+    if (mService) {
+        vector<MediaResourcePolicyParcel> policies;
+        policies.push_back(MediaResourcePolicy(kPolicyType[policyTypeIndex], policyValue));
+        mService->config(policies);
+    }
+}
+
+void ResourceManagerServiceFuzzer::setResources() {
+    if (!mService) {
+        return;
+    }
+    size_t numThreadPairs =
+        mFuzzedDataProvider->ConsumeIntegralInRange<size_t>(kMinThreadPairs, kMaxThreadPairs);
+    // Make even number of threads
+    size_t numThreads = numThreadPairs * 2;
+    resourceThreadArgs threadArgs;
+    vector<MediaResourceParcel> mediaResource;
+    pthread_t pt[numThreads];
+    int i;
+    for (i = 0; i < numThreads - 1; i += 2) {
+        threadArgs.pid = mFuzzedDataProvider->ConsumeIntegral<int32_t>();
+        threadArgs.uid = mFuzzedDataProvider->ConsumeIntegral<int32_t>();
+        int32_t mediaResourceType = mFuzzedDataProvider->ConsumeIntegralInRange<int32_t>(
+            kMinResourceType, kMaxResourceType);
+        int32_t mediaResourceSubType = mFuzzedDataProvider->ConsumeIntegralInRange<int32_t>(
+            kMinResourceType, kMaxResourceType);
+        uint64_t mediaResourceValue = mFuzzedDataProvider->ConsumeIntegral<uint64_t>();
+        threadArgs.service = mService;
+        shared_ptr<IResourceManagerClient> testClient =
+            ::ndk::SharedRefBase::make<TestClient>(threadArgs.pid, mService);
+        threadArgs.testClient = testClient;
+        threadArgs.testClientId = getId(testClient);
+        mediaResource.push_back(MediaResource(static_cast<MedResType>(mediaResourceType),
+                                              static_cast<MedResSubType>(mediaResourceSubType),
+                                              mediaResourceValue));
+        threadArgs.mediaResource = mediaResource;
+        pthread_create(&pt[i], nullptr, addResource, &threadArgs);
+        pthread_create(&pt[i + 1], nullptr, removeResource, &threadArgs);
+        mediaResource.clear();
+    }
+
+    for (i = 0; i < numThreads; ++i) {
+        pthread_join(pt[i], nullptr);
+    }
+
+    // No resource was added with pid = 0
+    int32_t pidZero = 0;
+    shared_ptr<IResourceManagerClient> testClient =
+        ::ndk::SharedRefBase::make<TestClient>(pidZero, mService);
+    int32_t mediaResourceType =
+        mFuzzedDataProvider->ConsumeIntegralInRange<int32_t>(kMinResourceType, kMaxResourceType);
+    int32_t mediaResourceSubType =
+        mFuzzedDataProvider->ConsumeIntegralInRange<int32_t>(kMinResourceType, kMaxResourceType);
+    uint64_t mediaResourceValue = mFuzzedDataProvider->ConsumeIntegral<uint64_t>();
+    mediaResource.push_back(MediaResource(static_cast<MedResType>(mediaResourceType),
+                                          static_cast<MedResSubType>(mediaResourceSubType),
+                                          mediaResourceValue));
+    bool result;
+    mService->reclaimResource(pidZero, mediaResource, &result);
+    mService->removeResource(pidZero, getId(testClient), mediaResource);
+    mService->removeClient(pidZero, getId(testClient));
+    mediaResource.clear();
+}
+
+void ResourceManagerServiceFuzzer::setServiceLog() {
+    size_t maxNum =
+        mFuzzedDataProvider->ConsumeIntegralInRange<int32_t>(kMinServiceLog, kMaxServiceLog);
+    sp<ServiceLog> serviceLog = new ServiceLog(maxNum);
+    if (serviceLog) {
+        serviceLog->add(String8("log"));
+        serviceLog->toString();
+    }
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    if (size < 1) {
+        return 0;
+    }
+    ResourceManagerServiceFuzzer* rmFuzzer = new ResourceManagerServiceFuzzer();
+    if (!rmFuzzer) {
+        return 0;
+    }
+    rmFuzzer->process(data, size);
+    delete rmFuzzer;
+    return 0;
+}
diff --git a/services/mediaresourcemanager/test/Android.bp b/services/mediaresourcemanager/test/Android.bp
index b6c548c..0c5b8a2 100644
--- a/services/mediaresourcemanager/test/Android.bp
+++ b/services/mediaresourcemanager/test/Android.bp
@@ -1,14 +1,23 @@
 // Build the unit tests.
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 cc_test {
     name: "ResourceManagerService_test",
     srcs: ["ResourceManagerService_test.cpp"],
     test_suites: ["device-tests"],
+    static_libs: ["libresourcemanagerservice"],
     shared_libs: [
         "libbinder",
         "libbinder_ndk",
         "liblog",
         "libmedia",
-        "libresourcemanagerservice",
         "libutils",
     ],
     include_dirs: [
@@ -19,17 +28,16 @@
         "-Werror",
         "-Wall",
     ],
-    compile_multilib: "32",
 }
 
 cc_test {
     name: "ServiceLog_test",
     srcs: ["ServiceLog_test.cpp"],
     test_suites: ["device-tests"],
+    static_libs: ["libresourcemanagerservice"],
     shared_libs: [
         "liblog",
         "libmedia",
-        "libresourcemanagerservice",
         "libutils",
     ],
     include_dirs: [
@@ -40,5 +48,4 @@
         "-Werror",
         "-Wall",
     ],
-    compile_multilib: "32",
 }
diff --git a/services/mediaresourcemanager/test/ResourceManagerService_test.cpp b/services/mediaresourcemanager/test/ResourceManagerService_test.cpp
index a6ecc09..3a45dcf 100644
--- a/services/mediaresourcemanager/test/ResourceManagerService_test.cpp
+++ b/services/mediaresourcemanager/test/ResourceManagerService_test.cpp
@@ -27,14 +27,6 @@
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/ProcessInfoInterface.h>
 
-namespace aidl {
-namespace android {
-namespace media {
-bool operator== (const MediaResourceParcel& lhs, const MediaResourceParcel& rhs) {
-    return lhs.type == rhs.type && lhs.subType == rhs.subType &&
-            lhs.id == rhs.id && lhs.value == rhs.value;
-}}}}
-
 namespace android {
 
 using Status = ::ndk::ScopedAStatus;
diff --git a/services/mediatranscoding/Android.bp b/services/mediatranscoding/Android.bp
index 17347a9..a895071 100644
--- a/services/mediatranscoding/Android.bp
+++ b/services/mediatranscoding/Android.bp
@@ -1,4 +1,23 @@
 // service library
+package {
+    default_applicable_licenses: [
+        "frameworks_av_services_mediatranscoding_license",
+    ],
+}
+
+// Added automatically by a large-scale-change
+// See: http://go/android-license-faq
+license {
+    name: "frameworks_av_services_mediatranscoding_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+    ],
+    license_text: [
+        "NOTICE",
+    ],
+}
+
 cc_library_shared {
     name: "libmediatranscodingservice",
 
@@ -44,18 +63,6 @@
         "mediatranscoding_aidl_interface-ndk_platform",
     ],
 
-    target: {
-        android: {
-            product_variables: {
-                malloc_not_svelte: {
-                    // Scudo increases memory footprint, so only enable on
-                    // non-svelte devices.
-                    shared_libs: ["libc_scudo"],
-                },
-            },
-        },
-    },
-
     init_rc: ["mediatranscoding.rc"],
 
     cflags: [
diff --git a/services/mediatranscoding/tests/Android.bp b/services/mediatranscoding/tests/Android.bp
index e0e040c..86e047e 100644
--- a/services/mediatranscoding/tests/Android.bp
+++ b/services/mediatranscoding/tests/Android.bp
@@ -1,5 +1,16 @@
 // Build the unit tests for MediaTranscodingService
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_services_mediatranscoding_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: [
+        "frameworks_av_services_mediatranscoding_license",
+    ],
+}
+
 cc_defaults {
     name: "mediatranscodingservice_test_defaults",
 
@@ -32,4 +43,4 @@
     defaults: ["mediatranscodingservice_test_defaults"],
 
     srcs: ["mediatranscodingservice_tests.cpp"],
-}
\ No newline at end of file
+}
diff --git a/services/minijail/Android.bp b/services/minijail/Android.bp
index b057968..3a89e12 100644
--- a/services/minijail/Android.bp
+++ b/services/minijail/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
 minijail_common_cflags = [
     "-Wall",
     "-Werror",
diff --git a/services/oboeservice/AAudioServiceEndpoint.cpp b/services/oboeservice/AAudioServiceEndpoint.cpp
index ceefe93..b139be1 100644
--- a/services/oboeservice/AAudioServiceEndpoint.cpp
+++ b/services/oboeservice/AAudioServiceEndpoint.cpp
@@ -182,11 +182,12 @@
             : AUDIO_SOURCE_DEFAULT;
     audio_flags_mask_t flags;
     if (direction == AAUDIO_DIRECTION_OUTPUT) {
-        flags = AUDIO_FLAG_LOW_LATENCY
-            | AAudioConvert_allowCapturePolicyToAudioFlagsMask(params->getAllowedCapturePolicy());
+        flags = static_cast<audio_flags_mask_t>(AUDIO_FLAG_LOW_LATENCY
+                | AAudioConvert_allowCapturePolicyToAudioFlagsMask(
+                        params->getAllowedCapturePolicy()));
     } else {
-        flags = AUDIO_FLAG_LOW_LATENCY
-            | AAudioConvert_privacySensitiveToAudioFlagsMask(params->isPrivacySensitive());
+        flags = static_cast<audio_flags_mask_t>(AUDIO_FLAG_LOW_LATENCY
+                | AAudioConvert_privacySensitiveToAudioFlagsMask(params->isPrivacySensitive()));
     }
     return {
             .content_type = contentType,
diff --git a/services/oboeservice/AAudioServiceStreamShared.cpp b/services/oboeservice/AAudioServiceStreamShared.cpp
index 01b1c2e..f2cf016 100644
--- a/services/oboeservice/AAudioServiceStreamShared.cpp
+++ b/services/oboeservice/AAudioServiceStreamShared.cpp
@@ -105,7 +105,7 @@
     }
     int32_t capacityInFrames = numBursts * framesPerBurst;
 
-    // Final sanity check.
+    // Final range check.
     if (capacityInFrames > MAX_FRAMES_PER_BUFFER) {
         ALOGE("calculateBufferCapacity() calc capacity %d > max %d",
               capacityInFrames, MAX_FRAMES_PER_BUFFER);
diff --git a/services/oboeservice/Android.bp b/services/oboeservice/Android.bp
index 8b1e2c0..c40a79e 100644
--- a/services/oboeservice/Android.bp
+++ b/services/oboeservice/Android.bp
@@ -12,7 +12,16 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-cc_library_shared {
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_av_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_av_license"],
+}
+
+cc_library {
 
     name: "libaaudioservice",
 
diff --git a/services/oboeservice/SharedMemoryProxy.cpp b/services/oboeservice/SharedMemoryProxy.cpp
index c43ed22..78d4884 100644
--- a/services/oboeservice/SharedMemoryProxy.cpp
+++ b/services/oboeservice/SharedMemoryProxy.cpp
@@ -20,6 +20,7 @@
 
 #include <errno.h>
 #include <string.h>
+#include <unistd.h>
 
 #include <aaudio/AAudio.h>
 #include "SharedMemoryProxy.h"