Merge "AudioPolicy/AudioFlinger: Track AudioRecords via Record IDs" into qt-dev
diff --git a/camera/ndk/Android.bp b/camera/ndk/Android.bp
index d96f403..7786856 100644
--- a/camera/ndk/Android.bp
+++ b/camera/ndk/Android.bp
@@ -64,6 +64,10 @@
         "-Wextra",
         "-Werror",
     ],
+    // TODO: jchowdhary@, use header_libs instead b/131165718
+    include_dirs: [
+        "system/media/private/camera/include",
+    ],
     export_include_dirs: ["include"],
     export_shared_lib_headers: [
         "libnativewindow",
@@ -123,6 +127,10 @@
         "android.hardware.camera.common@1.0-helper",
         "libarect",
     ],
+    // TODO: jchowdhary@, use header_libs instead b/131165718
+    include_dirs: [
+        "system/media/private/camera/include",
+    ],
     product_variables: {
         pdk: {
             enabled: false,
diff --git a/camera/ndk/NdkCameraManager.cpp b/camera/ndk/NdkCameraManager.cpp
index 23d01ef..3d231a8 100644
--- a/camera/ndk/NdkCameraManager.cpp
+++ b/camera/ndk/NdkCameraManager.cpp
@@ -190,3 +190,17 @@
     }
     return mgr->openCamera(cameraId, callback, device);
 }
+
+#ifdef __ANDROID_VNDK__
+EXPORT
+camera_status_t ACameraManager_getTagFromName(ACameraManager *mgr, const char* cameraId,
+        const char *name, /*out*/uint32_t *tag) {
+    ATRACE_CALL();
+    if (mgr == nullptr || cameraId == nullptr || name == nullptr) {
+        ALOGE("%s: invalid argument! mgr %p cameraId %p name %p",
+                __FUNCTION__, mgr, cameraId, name);
+        return ACAMERA_ERROR_INVALID_PARAMETER;
+    }
+    return mgr->getTagFromName(cameraId, name, tag);
+}
+#endif
diff --git a/camera/ndk/include/camera/NdkCameraManager.h b/camera/ndk/include/camera/NdkCameraManager.h
index 5c810bb..2cc8a97 100644
--- a/camera/ndk/include/camera/NdkCameraManager.h
+++ b/camera/ndk/include/camera/NdkCameraManager.h
@@ -374,6 +374,23 @@
         ACameraManager* manager,
         const ACameraManager_ExtendedAvailabilityCallbacks* callback) __INTRODUCED_IN(29);
 
+#ifdef __ANDROID_VNDK__
+/**
+ * Retrieve the tag value, given the tag name and camera id.
+ * This method is device specific since some metadata might be defined by device manufacturers
+ * and might only be accessible for specific cameras.
+ * @param manager The {@link ACameraManager} of interest.
+ * @param cameraId The cameraId, which is used to query camera characteristics.
+ * @param name The name of the tag being queried.
+ * @param tag The output tag assigned by this method.
+ *
+ * @return ACAMERA_OK only if the function call was successful.
+ */
+camera_status_t ACameraManager_getTagFromName(ACameraManager *manager, const char* cameraId,
+        const char *name, /*out*/uint32_t *tag)
+        __INTRODUCED_IN(29);
+#endif
+
 #endif /* __ANDROID_API__ >= 29 */
 
 __END_DECLS
diff --git a/camera/ndk/include/camera/NdkCameraMetadataTags.h b/camera/ndk/include/camera/NdkCameraMetadataTags.h
index 4563b41..7cd832a 100644
--- a/camera/ndk/include/camera/NdkCameraMetadataTags.h
+++ b/camera/ndk/include/camera/NdkCameraMetadataTags.h
@@ -7511,18 +7511,19 @@
 
     /**
      * <p>The camera device supports capturing high-resolution images at &gt;= 20 frames per
-     * second, in at least the uncompressed YUV format, when post-processing settings are set
-     * to FAST. Additionally, maximum-resolution images can be captured at &gt;= 10 frames
-     * per second.  Here, 'high resolution' means at least 8 megapixels, or the maximum
-     * resolution of the device, whichever is smaller.</p>
+     * second, in at least the uncompressed YUV format, when post-processing settings are
+     * set to FAST. Additionally, all image resolutions less than 24 megapixels can be
+     * captured at &gt;= 10 frames per second. Here, 'high resolution' means at least 8
+     * megapixels, or the maximum resolution of the device, whichever is smaller.</p>
      * <p>More specifically, this means that at least one output {@link AIMAGE_FORMAT_YUV_420_888 } size listed in
      * {@link ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS }
      * is larger or equal to the 'high resolution' defined above, and can be captured at at
      * least 20 fps.  For the largest {@link AIMAGE_FORMAT_YUV_420_888 } size listed in
      * {@link ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS },
-     * camera device can capture this size for at least 10 frames per second.  Also the
-     * ACAMERA_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES entry lists at least one FPS range where
-     * the minimum FPS is &gt;= 1 / minimumFrameDuration for the largest YUV_420_888 size.</p>
+     * camera device can capture this size for at least 10 frames per second if the size is
+     * less than 24 megapixels. Also the ACAMERA_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES entry
+     * lists at least one FPS range where the minimum FPS is &gt;= 1 / minimumFrameDuration
+     * for the largest YUV_420_888 size.</p>
      * <p>If the device supports the {@link AIMAGE_FORMAT_RAW10 }, {@link AIMAGE_FORMAT_RAW12 }, {@link AIMAGE_FORMAT_Y8 }, then those can also be
      * captured at the same rate as the maximum-size YUV_420_888 resolution is.</p>
      * <p>In addition, the ACAMERA_SYNC_MAX_LATENCY field is guaranted to have a value between 0
diff --git a/camera/ndk/ndk_vendor/impl/ACameraDevice.cpp b/camera/ndk/ndk_vendor/impl/ACameraDevice.cpp
index b18c897..1fdff40 100644
--- a/camera/ndk/ndk_vendor/impl/ACameraDevice.cpp
+++ b/camera/ndk/ndk_vendor/impl/ACameraDevice.cpp
@@ -87,7 +87,7 @@
                 __FUNCTION__, strerror(-err), err);
         setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_DEVICE);
     }
-    mHandler = new CallbackHandler();
+    mHandler = new CallbackHandler(id);
     mCbLooper->registerHandler(mHandler);
 
     const CameraMetadata& metadata = mChars->getInternalData();
@@ -918,6 +918,8 @@
     return;
 }
 
+CameraDevice::CallbackHandler::CallbackHandler(const char *id) : mId(id) { }
+
 void CameraDevice::CallbackHandler::onMessageReceived(
         const sp<AMessage> &msg) {
     switch (msg->what()) {
@@ -1012,9 +1014,9 @@
                 return;
             }
             sp<ACameraCaptureSession> session(static_cast<ACameraCaptureSession*>(obj.get()));
-            ACameraDevice* device = session->getDevice();
             mCachedSessions.push(session);
             sp<CaptureRequest> requestSp = nullptr;
+            const char *id_cstr = mId.c_str();
             switch (msg->what()) {
                 case kWhatCaptureStart:
                 case kWhatCaptureResult:
@@ -1063,7 +1065,7 @@
                         ALOGE("%s: Cannot find timestamp!", __FUNCTION__);
                         return;
                     }
-                    ACaptureRequest* request = allocateACaptureRequest(requestSp, device->getId());
+                    ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
                     (*onStart)(context, session.get(), request, timestamp);
                     freeACaptureRequest(request);
                     break;
@@ -1086,7 +1088,7 @@
                         return;
                     }
                     sp<ACameraMetadata> result(static_cast<ACameraMetadata*>(obj.get()));
-                    ACaptureRequest* request = allocateACaptureRequest(requestSp, device->getId());
+                    ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
                     (*onResult)(context, session.get(), request, result.get());
                     freeACaptureRequest(request);
                     break;
@@ -1139,7 +1141,7 @@
                         physicalMetadataCopyPtrs.push_back(physicalMetadataCopy[i].get());
                     }
 
-                    ACaptureRequest* request = allocateACaptureRequest(requestSp, device->getId());
+                    ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
                     (*onResult)(context, session.get(), request, result.get(),
                             physicalResultInfo.size(), physicalCameraIdPtrs.data(),
                             physicalMetadataCopyPtrs.data());
@@ -1168,7 +1170,7 @@
                             static_cast<CameraCaptureFailure*>(obj.get()));
                     ACameraCaptureFailure* failure =
                             static_cast<ACameraCaptureFailure*>(failureSp.get());
-                    ACaptureRequest* request = allocateACaptureRequest(requestSp, device->getId());
+                    ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
                     (*onFail)(context, session.get(), request, failure);
                     freeACaptureRequest(request);
                     break;
@@ -1201,7 +1203,7 @@
                         failure.physicalCameraId = nullptr;
                     }
                     failure.captureFailure = *failureSp;
-                    ACaptureRequest* request = allocateACaptureRequest(requestSp, device->getId());
+                    ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
                     (*onFail)(context, session.get(), request, &failure);
                     freeACaptureRequest(request);
                     break;
@@ -1278,7 +1280,7 @@
                         return;
                     }
 
-                    ACaptureRequest* request = allocateACaptureRequest(requestSp, device->getId());
+                    ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
                     (*onBufferLost)(context, session.get(), request, anw, frameNumber);
                     freeACaptureRequest(request);
                     break;
diff --git a/camera/ndk/ndk_vendor/impl/ACameraDevice.h b/camera/ndk/ndk_vendor/impl/ACameraDevice.h
index 7036017..829b084 100644
--- a/camera/ndk/ndk_vendor/impl/ACameraDevice.h
+++ b/camera/ndk/ndk_vendor/impl/ACameraDevice.h
@@ -266,9 +266,11 @@
 
     class CallbackHandler : public AHandler {
       public:
+        explicit CallbackHandler(const char *id);
         void onMessageReceived(const sp<AMessage> &msg) override;
 
       private:
+        std::string mId;
         // This handler will cache all capture session sp until kWhatCleanUpSessions
         // is processed. This is used to guarantee the last session reference is always
         // being removed in callback thread without holding camera device lock
diff --git a/camera/ndk/ndk_vendor/impl/ACameraManager.cpp b/camera/ndk/ndk_vendor/impl/ACameraManager.cpp
index 575ee9d..70c887a 100644
--- a/camera/ndk/ndk_vendor/impl/ACameraManager.cpp
+++ b/camera/ndk/ndk_vendor/impl/ACameraManager.cpp
@@ -22,6 +22,8 @@
 #include "ACameraMetadata.h"
 #include "ndk_vendor/impl/ACameraDevice.h"
 #include "utils.h"
+#include <CameraMetadata.h>
+#include <camera_metadata_hidden.h>
 
 #include <utils/Vector.h>
 #include <cutils/properties.h>
@@ -587,6 +589,26 @@
     return ACAMERA_OK;
 }
 
+camera_status_t
+ACameraManager::getTagFromName(const char *cameraId, const char *name, uint32_t *tag) {
+    sp<ACameraMetadata> rawChars;
+    camera_status_t ret = getCameraCharacteristics(cameraId, &rawChars);
+    if (ret != ACAMERA_OK) {
+        ALOGE("%s, Cannot retrieve camera characteristics for camera id %s", __FUNCTION__,
+                cameraId);
+        return ACAMERA_ERROR_METADATA_NOT_FOUND;
+    }
+    const CameraMetadata& metadata = rawChars->getInternalData();
+    const camera_metadata_t *rawMetadata = metadata.getAndLock();
+    metadata_vendor_id_t vendorTagId = get_camera_metadata_vendor_id(rawMetadata);
+    metadata.unlock(rawMetadata);
+    sp<VendorTagDescriptorCache> vtCache = VendorTagDescriptorCache::getGlobalVendorTagCache();
+    sp<VendorTagDescriptor> vTags = nullptr;
+    vtCache->getVendorTagDescriptor(vendorTagId, &vTags);
+    status_t status= metadata.getTagFromName(name, vTags.get(), tag);
+    return status == OK ? ACAMERA_OK : ACAMERA_ERROR_METADATA_NOT_FOUND;
+}
+
 ACameraManager::~ACameraManager() {
 
 }
diff --git a/camera/ndk/ndk_vendor/impl/ACameraManager.h b/camera/ndk/ndk_vendor/impl/ACameraManager.h
index df69353..2c62d44 100644
--- a/camera/ndk/ndk_vendor/impl/ACameraManager.h
+++ b/camera/ndk/ndk_vendor/impl/ACameraManager.h
@@ -204,6 +204,7 @@
     camera_status_t openCamera(const char* cameraId,
                                ACameraDevice_StateCallbacks* callback,
                                /*out*/ACameraDevice** device);
+    camera_status_t getTagFromName(const char *cameraId, const char *name, uint32_t *tag);
 
   private:
     enum {
diff --git a/camera/ndk/ndk_vendor/tests/AImageReaderVendorTest.cpp b/camera/ndk/ndk_vendor/tests/AImageReaderVendorTest.cpp
index 7368775..37de30a 100644
--- a/camera/ndk/ndk_vendor/tests/AImageReaderVendorTest.cpp
+++ b/camera/ndk/ndk_vendor/tests/AImageReaderVendorTest.cpp
@@ -799,6 +799,15 @@
     bool isBC = isCapabilitySupported(staticMetadata,
             ACAMERA_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE);
 
+    uint32_t namedTag = 0;
+    // Test that ACameraMetadata_getTagFromName works as expected for public tag
+    // names
+    camera_status_t status = ACameraManager_getTagFromName(mCameraManager, cameraId,
+            "android.control.aeMode", &namedTag);
+
+    ASSERT_EQ(status, ACAMERA_OK);
+    ASSERT_EQ(namedTag, ACAMERA_CONTROL_AE_MODE);
+
     ACameraMetadata_free(staticMetadata);
 
     if (!isBC) {
diff --git a/media/codec2/components/vorbis/C2SoftVorbisDec.cpp b/media/codec2/components/vorbis/C2SoftVorbisDec.cpp
index e7393ee..e3bafd3 100644
--- a/media/codec2/components/vorbis/C2SoftVorbisDec.cpp
+++ b/media/codec2/components/vorbis/C2SoftVorbisDec.cpp
@@ -270,7 +270,8 @@
     const uint8_t *data = rView.data() + inOffset;
     int32_t numChannels  = mVi->channels;
     int32_t samplingRate = mVi->rate;
-    if (inSize > 7 && !memcmp(&data[1], "vorbis", 6)) {
+    /* Decode vorbis headers only once */
+    if (inSize > 7 && !memcmp(&data[1], "vorbis", 6) && (!mInfoUnpacked || !mBooksUnpacked)) {
         if ((data[0] != 1) && (data[0] != 5)) {
             ALOGE("unexpected type received %d", data[0]);
             mSignalledError = true;
diff --git a/media/codec2/hidl/1.0/utils/Android.bp b/media/codec2/hidl/1.0/utils/Android.bp
index b2a5fee..b73f0c8 100644
--- a/media/codec2/hidl/1.0/utils/Android.bp
+++ b/media/codec2/hidl/1.0/utils/Android.bp
@@ -99,6 +99,7 @@
     export_shared_lib_headers: [
         "android.hardware.media.c2@1.0",
         "libcodec2",
+        "libcodec2_vndk",
         "libhidlbase",
         "libstagefright_bufferpool@2.0",
         "libui",
diff --git a/media/codec2/hidl/client/Android.bp b/media/codec2/hidl/client/Android.bp
index a174008..6038a40 100644
--- a/media/codec2/hidl/client/Android.bp
+++ b/media/codec2/hidl/client/Android.bp
@@ -31,6 +31,7 @@
     export_shared_lib_headers: [
         "libcodec2",
         "libcodec2_hidl_client@1.0",
+        "libcodec2_vndk",
     ],
 
 }
diff --git a/media/codec2/hidl/client/client.cpp b/media/codec2/hidl/client/client.cpp
index 53adbbc..6aca4a3 100644
--- a/media/codec2/hidl/client/client.cpp
+++ b/media/codec2/hidl/client/client.cpp
@@ -75,82 +75,11 @@
 // c2_status_t value that corresponds to hwbinder transaction failure.
 constexpr c2_status_t C2_TRANSACTION_FAILED = C2_CORRUPTED;
 
-// Returns the list of IComponentStore service names that are available on the
-// device. This list is specified at the build time in manifest files.
-// Note: A software service will have "_software" as a suffix.
-std::vector<std::string> const& getServiceNames() {
-    static std::vector<std::string> sServiceNames{[]() {
-        using ::android::hardware::media::c2::V1_0::IComponentStore;
-        using ::android::hidl::manager::V1_2::IServiceManager;
-
-        while (true) {
-            sp<IServiceManager> serviceManager = IServiceManager::getService();
-            CHECK(serviceManager) << "Hardware service manager is not running.";
-
-            // There are three categories of services based on names.
-            std::vector<std::string> defaultNames; // Prefixed with "default"
-            std::vector<std::string> vendorNames;  // Prefixed with "vendor"
-            std::vector<std::string> otherNames;   // Others
-            Return<void> transResult;
-            transResult = serviceManager->listManifestByInterface(
-                    IComponentStore::descriptor,
-                    [&defaultNames, &vendorNames, &otherNames](
-                            hidl_vec<hidl_string> const& instanceNames) {
-                        for (hidl_string const& instanceName : instanceNames) {
-                            char const* name = instanceName.c_str();
-                            if (strncmp(name, "default", 7) == 0) {
-                                defaultNames.emplace_back(name);
-                            } else if (strncmp(name, "vendor", 6) == 0) {
-                                vendorNames.emplace_back(name);
-                            } else {
-                                otherNames.emplace_back(name);
-                            }
-                        }
-                    });
-            if (transResult.isOk()) {
-                // Sort service names in each category.
-                std::sort(defaultNames.begin(), defaultNames.end());
-                std::sort(vendorNames.begin(), vendorNames.end());
-                std::sort(otherNames.begin(), otherNames.end());
-
-                // Concatenate the three lists in this order: default, vendor,
-                // other.
-                std::vector<std::string>& names = defaultNames;
-                names.reserve(names.size() + vendorNames.size() + otherNames.size());
-                names.insert(names.end(),
-                             std::make_move_iterator(vendorNames.begin()),
-                             std::make_move_iterator(vendorNames.end()));
-                names.insert(names.end(),
-                             std::make_move_iterator(otherNames.begin()),
-                             std::make_move_iterator(otherNames.end()));
-
-                // Summarize to logcat.
-                if (names.empty()) {
-                    LOG(INFO) << "No Codec2 services declared in the manifest.";
-                } else {
-                    std::stringstream stringOutput;
-                    stringOutput << "Available Codec2 services:";
-                    for (std::string const& name : names) {
-                        stringOutput << " \"" << name << "\"";
-                    }
-                    LOG(INFO) << stringOutput.str();
-                }
-
-                return names;
-            }
-            LOG(ERROR) << "Could not retrieve the list of service instances of "
-                       << IComponentStore::descriptor
-                       << ". Retrying...";
-        }
-    }()};
-    return sServiceNames;
-}
-
-// Searches for a name in getServiceNames() and returns the index found. If the
+// Searches for a name in GetServiceNames() and returns the index found. If the
 // name is not found, the returned index will be equal to
-// getServiceNames().size().
+// GetServiceNames().size().
 size_t getServiceIndex(char const* name) {
-    std::vector<std::string> const& names = getServiceNames();
+    std::vector<std::string> const& names = Codec2Client::GetServiceNames();
     size_t i = 0;
     for (; i < names.size(); ++i) {
         if (name == names[i]) {
@@ -175,17 +104,14 @@
     std::vector<C2Component::Traits> mTraits;
     std::once_flag mTraitsInitializationFlag;
 
-    // The index of the service. This is based on getServiceNames().
+    // The index of the service. This is based on GetServiceNames().
     size_t mIndex;
-    // A "valid" cache object must have its mIndex set with init().
-    bool mValid{false};
     // Called by s() exactly once to initialize the cache. The index must be a
-    // valid index into the vector returned by getServiceNames(). Calling
+    // valid index into the vector returned by GetServiceNames(). Calling
     // init(index) will associate the cache to the service with name
-    // getServiceNames()[index].
+    // GetServiceNames()[index].
     void init(size_t index) {
         mIndex = index;
-        mValid = true;
     }
 
 public:
@@ -195,7 +121,6 @@
     // If the service is unavailable but listed in the manifest, this function
     // will block indefinitely.
     std::shared_ptr<Codec2Client> getClient() {
-        CHECK(mValid) << "Uninitialized cache";
         std::scoped_lock lock{mClientMutex};
         if (!mClient) {
             mClient = Codec2Client::_CreateFromIndex(mIndex);
@@ -208,7 +133,6 @@
     //
     // Note: This function is called only by ForAllServices().
     void invalidate() {
-        CHECK(mValid) << "Uninitialized cache";
         std::scoped_lock lock{mClientMutex};
         mClient = nullptr;
     }
@@ -216,7 +140,6 @@
     // Returns a list of traits for components supported by the service. This
     // list is cached.
     std::vector<C2Component::Traits> const& getTraits() {
-        CHECK(mValid) << "Uninitialized cache";
         std::call_once(mTraitsInitializationFlag, [this]() {
             bool success{false};
             // Spin until _listComponents() is successful.
@@ -229,7 +152,7 @@
                 using namespace std::chrono_literals;
                 static constexpr auto kServiceRetryPeriod = 5s;
                 LOG(INFO) << "Failed to retrieve component traits from service "
-                             "\"" << getServiceNames()[mIndex] << "\". "
+                             "\"" << GetServiceNames()[mIndex] << "\". "
                              "Retrying...";
                 std::this_thread::sleep_for(kServiceRetryPeriod);
             }
@@ -240,7 +163,7 @@
     // List() returns the list of all caches.
     static std::vector<Cache>& List() {
         static std::vector<Cache> sCaches{[]() {
-            size_t numServices = getServiceNames().size();
+            size_t numServices = GetServiceNames().size();
             std::vector<Cache> caches(numServices);
             for (size_t i = 0; i < numServices; ++i) {
                 caches[i].init(i);
@@ -610,8 +533,12 @@
     }
 }
 
+sp<Codec2Client::Base> const& Codec2Client::getBase() const {
+    return mBase;
+}
+
 std::string const& Codec2Client::getServiceName() const {
-    return getServiceNames()[mServiceIndex];
+    return GetServiceNames()[mServiceIndex];
 }
 
 c2_status_t Codec2Client::createComponent(
@@ -807,15 +734,94 @@
     return std::make_shared<SimpleParamReflector>(mBase);
 };
 
+std::vector<std::string> const& Codec2Client::GetServiceNames() {
+    static std::vector<std::string> sServiceNames{[]() {
+        using ::android::hardware::media::c2::V1_0::IComponentStore;
+        using ::android::hidl::manager::V1_2::IServiceManager;
+
+        while (true) {
+            sp<IServiceManager> serviceManager = IServiceManager::getService();
+            CHECK(serviceManager) << "Hardware service manager is not running.";
+
+            // There are three categories of services based on names.
+            std::vector<std::string> defaultNames; // Prefixed with "default"
+            std::vector<std::string> vendorNames;  // Prefixed with "vendor"
+            std::vector<std::string> otherNames;   // Others
+            Return<void> transResult;
+            transResult = serviceManager->listManifestByInterface(
+                    IComponentStore::descriptor,
+                    [&defaultNames, &vendorNames, &otherNames](
+                            hidl_vec<hidl_string> const& instanceNames) {
+                        for (hidl_string const& instanceName : instanceNames) {
+                            char const* name = instanceName.c_str();
+                            if (strncmp(name, "default", 7) == 0) {
+                                defaultNames.emplace_back(name);
+                            } else if (strncmp(name, "vendor", 6) == 0) {
+                                vendorNames.emplace_back(name);
+                            } else {
+                                otherNames.emplace_back(name);
+                            }
+                        }
+                    });
+            if (transResult.isOk()) {
+                // Sort service names in each category.
+                std::sort(defaultNames.begin(), defaultNames.end());
+                std::sort(vendorNames.begin(), vendorNames.end());
+                std::sort(otherNames.begin(), otherNames.end());
+
+                // Concatenate the three lists in this order: default, vendor,
+                // other.
+                std::vector<std::string>& names = defaultNames;
+                names.reserve(names.size() + vendorNames.size() + otherNames.size());
+                names.insert(names.end(),
+                             std::make_move_iterator(vendorNames.begin()),
+                             std::make_move_iterator(vendorNames.end()));
+                names.insert(names.end(),
+                             std::make_move_iterator(otherNames.begin()),
+                             std::make_move_iterator(otherNames.end()));
+
+                // Summarize to logcat.
+                if (names.empty()) {
+                    LOG(INFO) << "No Codec2 services declared in the manifest.";
+                } else {
+                    std::stringstream stringOutput;
+                    stringOutput << "Available Codec2 services:";
+                    for (std::string const& name : names) {
+                        stringOutput << " \"" << name << "\"";
+                    }
+                    LOG(INFO) << stringOutput.str();
+                }
+
+                return names;
+            }
+            LOG(ERROR) << "Could not retrieve the list of service instances of "
+                       << IComponentStore::descriptor
+                       << ". Retrying...";
+        }
+    }()};
+    return sServiceNames;
+}
+
 std::shared_ptr<Codec2Client> Codec2Client::CreateFromService(
         const char* name) {
     size_t index = getServiceIndex(name);
-    return index == getServiceNames().size() ?
+    return index == GetServiceNames().size() ?
             nullptr : _CreateFromIndex(index);
 }
 
+std::vector<std::shared_ptr<Codec2Client>> Codec2Client::
+        CreateFromAllServices() {
+    std::vector<std::shared_ptr<Codec2Client>> clients(
+            GetServiceNames().size());
+    for (size_t i = GetServiceNames().size(); i > 0; ) {
+        --i;
+        clients[i] = _CreateFromIndex(i);
+    }
+    return clients;
+}
+
 std::shared_ptr<Codec2Client> Codec2Client::_CreateFromIndex(size_t index) {
-    std::string const& name = getServiceNames()[index];
+    std::string const& name = GetServiceNames()[index];
     LOG(INFO) << "Creating a Codec2 client to service \"" << name << "\"";
     sp<Base> baseStore = Base::getService(name);
     CHECK(baseStore) << "Codec2 service \"" << name << "\""
@@ -958,17 +964,17 @@
     if (inputSurfaceSetting == 0) {
         return nullptr;
     }
-    size_t index = getServiceNames().size();
+    size_t index = GetServiceNames().size();
     if (serviceName) {
         index = getServiceIndex(serviceName);
-        if (index == getServiceNames().size()) {
+        if (index == GetServiceNames().size()) {
             LOG(DEBUG) << "CreateInputSurface -- invalid service name: \""
                        << serviceName << "\"";
         }
     }
 
     std::shared_ptr<Codec2Client::InputSurface> inputSurface;
-    if (index != getServiceNames().size()) {
+    if (index != GetServiceNames().size()) {
         std::shared_ptr<Codec2Client> client = Cache::List()[index].getClient();
         if (client->createInputSurface(&inputSurface) == C2_OK) {
             return inputSurface;
diff --git a/media/codec2/hidl/client/include/codec2/hidl/client.h b/media/codec2/hidl/client/include/codec2/hidl/client.h
index 1851752..03db515 100644
--- a/media/codec2/hidl/client/include/codec2/hidl/client.h
+++ b/media/codec2/hidl/client/include/codec2/hidl/client.h
@@ -143,6 +143,8 @@
 
     typedef Codec2Client Store;
 
+    sp<Base> const& getBase() const;
+
     std::string const& getServiceName() const;
 
     c2_status_t createComponent(
@@ -165,8 +167,17 @@
 
     std::shared_ptr<C2ParamReflector> getParamReflector();
 
+    // Returns the list of IComponentStore service names that are available on
+    // the device. This list is specified at the build time in manifest files.
+    // Note: A software service will have "_software" as a suffix.
+    static std::vector<std::string> const& GetServiceNames();
+
+    // Create a service with a given service name.
     static std::shared_ptr<Codec2Client> CreateFromService(char const* name);
 
+    // Get clients to all services.
+    static std::vector<std::shared_ptr<Codec2Client>> CreateFromAllServices();
+
     // Try to create a component with a given name from all known
     // IComponentStore services.
     static std::shared_ptr<Component> CreateComponentByName(
diff --git a/media/codec2/sfplugin/CCodecBufferChannel.cpp b/media/codec2/sfplugin/CCodecBufferChannel.cpp
index 90265de..715e78b 100644
--- a/media/codec2/sfplugin/CCodecBufferChannel.cpp
+++ b/media/codec2/sfplugin/CCodecBufferChannel.cpp
@@ -533,10 +533,12 @@
     feedInputBufferIfAvailable();
     if (!c2Buffer) {
         if (released) {
-            ALOGD("[%s] The app is calling releaseOutputBuffer() with "
-                  "timestamp or render=true with non-video buffers. Apps should "
-                  "call releaseOutputBuffer() with render=false for those.",
-                  mName);
+            std::call_once(mRenderWarningFlag, [this] {
+                ALOGW("[%s] The app is calling releaseOutputBuffer() with "
+                      "timestamp or render=true with non-video buffers. Apps should "
+                      "call releaseOutputBuffer() with render=false for those.",
+                      mName);
+            });
         }
         return INVALID_OPERATION;
     }
diff --git a/media/codec2/sfplugin/CCodecBufferChannel.h b/media/codec2/sfplugin/CCodecBufferChannel.h
index bc997e6..9aec82d 100644
--- a/media/codec2/sfplugin/CCodecBufferChannel.h
+++ b/media/codec2/sfplugin/CCodecBufferChannel.h
@@ -305,6 +305,7 @@
     Mutexed<ReorderStash> mReorderStash;
 
     std::atomic_bool mInputMetEos;
+    std::once_flag mRenderWarningFlag;
 
     inline bool hasCryptoOrDescrambler() {
         return mCrypto != nullptr || mDescrambler != nullptr;
diff --git a/media/codec2/vndk/C2Store.cpp b/media/codec2/vndk/C2Store.cpp
index e075849..10c4dcc 100644
--- a/media/codec2/vndk/C2Store.cpp
+++ b/media/codec2/vndk/C2Store.cpp
@@ -661,24 +661,27 @@
     ALOGV("in %s", __func__);
     ALOGV("loading dll");
     mLibHandle = dlopen(libPath.c_str(), RTLD_NOW|RTLD_NODELETE);
-    if (mLibHandle == nullptr) {
-        // could be access/symbol or simply not being there
-        ALOGD("could not dlopen %s: %s", libPath.c_str(), dlerror());
-        mInit = C2_CORRUPTED;
-    } else {
-        createFactory =
-            (C2ComponentFactory::CreateCodec2FactoryFunc)dlsym(mLibHandle, "CreateCodec2Factory");
-        destroyFactory =
-            (C2ComponentFactory::DestroyCodec2FactoryFunc)dlsym(mLibHandle, "DestroyCodec2Factory");
+    LOG_ALWAYS_FATAL_IF(mLibHandle == nullptr,
+            "could not dlopen %s: %s", libPath.c_str(), dlerror());
 
-        mComponentFactory = createFactory();
-        if (mComponentFactory == nullptr) {
-            ALOGD("could not create factory in %s", libPath.c_str());
-            mInit = C2_NO_MEMORY;
-        } else {
-            mInit = C2_OK;
-        }
+    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) {
+        ALOGD("could not create factory in %s", libPath.c_str());
+        mInit = C2_NO_MEMORY;
+    } else {
+        mInit = C2_OK;
     }
+
     if (mInit != C2_OK) {
         return mInit;
     }
diff --git a/media/extractors/flac/FLACExtractor.cpp b/media/extractors/flac/FLACExtractor.cpp
index 8854631..5329bd1 100644
--- a/media/extractors/flac/FLACExtractor.cpp
+++ b/media/extractors/flac/FLACExtractor.cpp
@@ -531,23 +531,9 @@
             return NO_INIT;
         }
         // check sample rate
-        switch (getSampleRate()) {
-        case  8000:
-        case 11025:
-        case 12000:
-        case 16000:
-        case 22050:
-        case 24000:
-        case 32000:
-        case 44100:
-        case 48000:
-        case 88200:
-        case 96000:
-        case 176400:
-        case 192000:
-            break;
-        default:
-            // Note: internally we support arbitrary sample rates from 8kHz to 192kHz.
+        // Note: flac supports arbitrary sample rates up to 655350 Hz, but Android
+        // supports sample rates from 8kHz to 192kHz, so use that as the limit.
+        if (getSampleRate() < 8000 || getSampleRate() > 192000) {
             ALOGE("unsupported sample rate %u", getSampleRate());
             return NO_INIT;
         }
diff --git a/media/extractors/wav/WAVExtractor.cpp b/media/extractors/wav/WAVExtractor.cpp
index 020951b..8b539c2ff 100644
--- a/media/extractors/wav/WAVExtractor.cpp
+++ b/media/extractors/wav/WAVExtractor.cpp
@@ -461,7 +461,7 @@
     }
 
     // maxBytesToRead may be reduced so that in-place data conversion will fit in buffer size.
-    const size_t bufferSize = buffer->size();
+    const size_t bufferSize = std::min(buffer->size(), kMaxFrameSize);
     size_t maxBytesToRead;
     if (mOutputFloat) { // destination is float at 4 bytes per sample, source may be less.
         maxBytesToRead = (mBitsPerSample / 8) * (bufferSize / 4);
diff --git a/media/img_utils/src/DngUtils.cpp b/media/img_utils/src/DngUtils.cpp
index 9304f53..7914030 100644
--- a/media/img_utils/src/DngUtils.cpp
+++ b/media/img_utils/src/DngUtils.cpp
@@ -173,8 +173,8 @@
 
     status_t err = addGainMap(/*top*/redTop,
                               /*left*/redLeft,
-                              /*bottom*/activeAreaHeight - 1,
-                              /*right*/activeAreaWidth - 1,
+                              /*bottom*/activeAreaHeight,
+                              /*right*/activeAreaWidth,
                               /*plane*/0,
                               /*planes*/1,
                               /*rowPitch*/2,
@@ -191,8 +191,8 @@
 
     err = addGainMap(/*top*/greenEvenTop,
                      /*left*/greenEvenLeft,
-                     /*bottom*/activeAreaHeight - 1,
-                     /*right*/activeAreaWidth - 1,
+                     /*bottom*/activeAreaHeight,
+                     /*right*/activeAreaWidth,
                      /*plane*/0,
                      /*planes*/1,
                      /*rowPitch*/2,
@@ -209,8 +209,8 @@
 
     err = addGainMap(/*top*/greenOddTop,
                      /*left*/greenOddLeft,
-                     /*bottom*/activeAreaHeight - 1,
-                     /*right*/activeAreaWidth - 1,
+                     /*bottom*/activeAreaHeight,
+                     /*right*/activeAreaWidth,
                      /*plane*/0,
                      /*planes*/1,
                      /*rowPitch*/2,
@@ -227,8 +227,8 @@
 
     err = addGainMap(/*top*/blueTop,
                      /*left*/blueLeft,
-                     /*bottom*/activeAreaHeight - 1,
-                     /*right*/activeAreaWidth - 1,
+                     /*bottom*/activeAreaHeight,
+                     /*right*/activeAreaWidth,
                      /*plane*/0,
                      /*planes*/1,
                      /*rowPitch*/2,
@@ -265,8 +265,8 @@
 
     status_t err = addGainMap(/*top*/0,
                               /*left*/0,
-                              /*bottom*/activeAreaHeight - 1,
-                              /*right*/activeAreaWidth - 1,
+                              /*bottom*/activeAreaHeight,
+                              /*right*/activeAreaWidth,
                               /*plane*/0,
                               /*planes*/1,
                               /*rowPitch*/1,
@@ -364,8 +364,8 @@
         return BAD_VALUE;
     }
 
-    double normalizedOCX = opticalCenterX / static_cast<double>(activeArrayWidth - 1);
-    double normalizedOCY = opticalCenterY / static_cast<double>(activeArrayHeight - 1);
+    double normalizedOCX = opticalCenterX / static_cast<double>(activeArrayWidth);
+    double normalizedOCY = opticalCenterY / static_cast<double>(activeArrayHeight);
 
     normalizedOCX = CLAMP(normalizedOCX, 0, 1);
     normalizedOCY = CLAMP(normalizedOCY, 0, 1);
diff --git a/media/libaaudio/src/client/AudioStreamInternal.cpp b/media/libaaudio/src/client/AudioStreamInternal.cpp
index db98d58..c7e8088 100644
--- a/media/libaaudio/src/client/AudioStreamInternal.cpp
+++ b/media/libaaudio/src/client/AudioStreamInternal.cpp
@@ -76,6 +76,7 @@
     aaudio_result_t result = AAUDIO_OK;
     int32_t capacity;
     int32_t framesPerBurst;
+    int32_t framesPerHardwareBurst;
     AAudioStreamRequest request;
     AAudioStreamConfiguration configurationOutput;
 
@@ -90,6 +91,9 @@
         return result;
     }
 
+    const int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
+    int32_t burstMicros = 0;
+
     // We have to do volume scaling. So we prefer FLOAT format.
     if (getFormat() == AUDIO_FORMAT_DEFAULT) {
         setFormat(AUDIO_FORMAT_PCM_FLOAT);
@@ -173,8 +177,22 @@
         goto error;
     }
 
-    // Validate result from server.
-    framesPerBurst = mEndpointDescriptor.dataQueueDescriptor.framesPerBurst;
+    framesPerHardwareBurst = mEndpointDescriptor.dataQueueDescriptor.framesPerBurst;
+
+    // Scale up the burst size to meet the minimum equivalent in microseconds.
+    // This is to avoid waking the CPU too often when the HW burst is very small
+    // or at high sample rates.
+    framesPerBurst = framesPerHardwareBurst;
+    do {
+        if (burstMicros > 0) {  // skip first loop
+            framesPerBurst *= 2;
+        }
+        burstMicros = framesPerBurst * static_cast<int64_t>(1000000) / getSampleRate();
+    } while (burstMicros < burstMinMicros);
+    ALOGD("%s() original HW burst = %d, minMicros = %d => SW burst = %d\n",
+          __func__, framesPerHardwareBurst, burstMinMicros, framesPerBurst);
+
+    // Validate final burst size.
     if (framesPerBurst < MIN_FRAMES_PER_BURST || framesPerBurst > MAX_FRAMES_PER_BURST) {
         ALOGE("%s - framesPerBurst out of range = %d", __func__, framesPerBurst);
         result = AAUDIO_ERROR_OUT_OF_RANGE;
@@ -190,7 +208,7 @@
     }
 
     mClockModel.setSampleRate(getSampleRate());
-    mClockModel.setFramesPerBurst(mFramesPerBurst);
+    mClockModel.setFramesPerBurst(framesPerHardwareBurst);
 
     if (isDataCallbackSet()) {
         mCallbackFrames = builder.getFramesPerDataCallback();
diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp
index 8d1f511..bd48f56 100644
--- a/media/libaudioclient/AudioTrack.cpp
+++ b/media/libaudioclient/AudioTrack.cpp
@@ -605,7 +605,10 @@
     mInUnderrun = false;
     mPreviousTimestampValid = false;
     mTimestampStartupGlitchReported = false;
-    mRetrogradeMotionReported = false;
+    mTimestampRetrogradePositionReported = false;
+    mTimestampRetrogradeTimeReported = false;
+    mTimestampStallReported = false;
+    mTimestampStaleTimeReported = false;
     mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
     mStartTs.mPosition = 0;
     mUnderrunCountOffset = 0;
@@ -656,7 +659,10 @@
         mPosition = 0;
         mPreviousTimestampValid = false;
         mTimestampStartupGlitchReported = false;
-        mRetrogradeMotionReported = false;
+        mTimestampRetrogradePositionReported = false;
+        mTimestampRetrogradeTimeReported = false;
+        mTimestampStallReported = false;
+        mTimestampStaleTimeReported = false;
         mPreviousLocation = ExtendedTimestamp::LOCATION_INVALID;
 
         if (!isOffloadedOrDirect_l()
@@ -2607,9 +2613,14 @@
                         // A better start time is now.  The retrograde check ensures
                         // timestamp monotonicity.
                         const int64_t nowNs = systemTime();
-                        ALOGD("%s(%d) device stall, using current time %lld",
-                                __func__, mPortId, (long long)nowNs);
+                        if (!mTimestampStallReported) {
+                            ALOGD("%s(%d): device stall time corrected using current time %lld",
+                                    __func__, mPortId, (long long)nowNs);
+                            mTimestampStallReported = true;
+                        }
                         timestamp.mTime = convertNsToTimespec(nowNs);
+                    }  else {
+                        mTimestampStallReported = false;
                     }
                 }
 
@@ -2762,12 +2773,17 @@
         const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
         const int64_t limitNs = mStartNs - lagNs;
         if (currentTimeNanos < limitNs) {
-            ALOGD("%s(%d): correcting timestamp time for pause, "
-                    "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
-                    __func__, mPortId,
-                    (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
+            if (!mTimestampStaleTimeReported) {
+                ALOGD("%s(%d): stale timestamp time corrected, "
+                        "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
+                        __func__, mPortId,
+                        (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
+                mTimestampStaleTimeReported = true;
+            }
             timestamp.mTime = convertNsToTimespec(limitNs);
             currentTimeNanos = limitNs;
+        } else {
+            mTimestampStaleTimeReported = false;
         }
 
         // previousTimestampValid is set to false when starting after a stop or flush.
@@ -2777,11 +2793,15 @@
 
             // retrograde check
             if (currentTimeNanos < previousTimeNanos) {
-                ALOGW("%s(%d): retrograde timestamp time corrected, %lld < %lld",
-                        __func__, mPortId,
-                        (long long)currentTimeNanos, (long long)previousTimeNanos);
+                if (!mTimestampRetrogradeTimeReported) {
+                    ALOGW("%s(%d): retrograde timestamp time corrected, %lld < %lld",
+                            __func__, mPortId,
+                            (long long)currentTimeNanos, (long long)previousTimeNanos);
+                    mTimestampRetrogradeTimeReported = true;
+                }
                 timestamp.mTime = mPreviousTimestamp.mTime;
-                // currentTimeNanos not used below.
+            } else {
+                mTimestampRetrogradeTimeReported = false;
             }
 
             // Looking at signed delta will work even when the timestamps
@@ -2790,16 +2810,16 @@
                     - mPreviousTimestamp.mPosition).signedValue();
             if (deltaPosition < 0) {
                 // Only report once per position instead of spamming the log.
-                if (!mRetrogradeMotionReported) {
+                if (!mTimestampRetrogradePositionReported) {
                     ALOGW("%s(%d): retrograde timestamp position corrected, %d = %u - %u",
                             __func__, mPortId,
                             deltaPosition,
                             timestamp.mPosition,
                             mPreviousTimestamp.mPosition);
-                    mRetrogradeMotionReported = true;
+                    mTimestampRetrogradePositionReported = true;
                 }
             } else {
-                mRetrogradeMotionReported = false;
+                mTimestampRetrogradePositionReported = false;
             }
             if (deltaPosition < 0) {
                 timestamp.mPosition = mPreviousTimestamp.mPosition;
diff --git a/media/libaudioclient/include/media/AudioTrack.h b/media/libaudioclient/include/media/AudioTrack.h
index 3926ead..df5eabc 100644
--- a/media/libaudioclient/include/media/AudioTrack.h
+++ b/media/libaudioclient/include/media/AudioTrack.h
@@ -1151,8 +1151,11 @@
                                                     // AudioTracks.
 
     bool                    mPreviousTimestampValid;// true if mPreviousTimestamp is valid
-    bool                    mTimestampStartupGlitchReported; // reduce log spam
-    bool                    mRetrogradeMotionReported; // reduce log spam
+    bool                    mTimestampStartupGlitchReported;      // reduce log spam
+    bool                    mTimestampRetrogradePositionReported; // reduce log spam
+    bool                    mTimestampRetrogradeTimeReported;     // reduce log spam
+    bool                    mTimestampStallReported;              // reduce log spam
+    bool                    mTimestampStaleTimeReported;          // reduce log spam
     AudioTimestamp          mPreviousTimestamp;     // used to detect retrograde motion
     ExtendedTimestamp::Location mPreviousLocation;  // location used for previous timestamp
 
diff --git a/media/libeffects/lvm/lib/Bundle/src/LVM_Buffers.c b/media/libeffects/lvm/lib/Bundle/src/LVM_Buffers.c
index 37272e3..bdca5e3 100644
--- a/media/libeffects/lvm/lib/Bundle/src/LVM_Buffers.c
+++ b/media/libeffects/lvm/lib/Bundle/src/LVM_Buffers.c
@@ -1128,6 +1128,11 @@
     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;
+    }
 #undef NrFrames
 #define NrFrames (*pNumSamples) // alias for clarity
 #else
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 5079634..a97acc9 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
@@ -24,9 +24,32 @@
 echo "testing lvm"
 adb shell mkdir -p $testdir
 adb push $ANDROID_BUILD_TOP/cts/tests/tests/media/res/raw/sinesweepraw.raw $testdir
-adb push $OUT/testcases/lvmtest/arm64/lvmtest $testdir
 adb push $OUT/testcases/snr/arm64/snr $testdir
 
+E_VAL=1
+if [ -z "$1" ]
+then
+    cmds=("adb push $OUT/testcases/lvmtest/arm64/lvmtest $testdir"
+          "adb push $OUT/testcases/lvmtest/arm/lvmtest $testdir"
+         )
+elif [ "$1" == "32" ]
+then
+    cmds="adb push $OUT/testcases/lvmtest/arm/lvmtest $testdir"
+elif [ "$1" == "64" ]
+then
+    cmds="adb push $OUT/testcases/lvmtest/arm64/lvmtest $testdir"
+else
+    echo ""
+    echo "Invalid \"val\""
+    echo "Usage:"
+    echo "      "$0" [val]"
+    echo "      where, val can be either 32 or 64."
+    echo ""
+    echo "      If val is not specified then both 32 bit and 64 bit binaries"
+    echo "      are tested."
+    exit $E_VAL
+fi
+
 flags_arr=(
     "-csE"
     "-eqE"
@@ -61,42 +84,45 @@
 # run multichannel effects at different configs, saving only the stereo channel
 # pair.
 error_count=0
-for flags in "${flags_arr[@]}"
+for cmd in "${cmds[@]}"
 do
-    for fs in ${fs_arr[*]}
+    $cmd
+    for flags in "${flags_arr[@]}"
     do
-        for chMask in {0..22}
+        for fs in ${fs_arr[*]}
         do
-            adb shell $testdir/lvmtest -i:$testdir/sinesweepraw.raw \
-                -o:$testdir/sinesweep_$((chMask))_$((fs)).raw -chMask:$chMask -fs:$fs $flags
+            for chMask in {0..22}
+            do
+                adb shell $testdir/lvmtest -i:$testdir/sinesweepraw.raw \
+                    -o:$testdir/sinesweep_$((chMask))_$((fs)).raw -chMask:$chMask -fs:$fs $flags
 
-            shell_ret=$?
-            if [ $shell_ret -ne 0 ]; then
-                echo "error: $shell_ret"
-                ((++error_count))
-            fi
+                shell_ret=$?
+                if [ $shell_ret -ne 0 ]; then
+                    echo "error: $shell_ret"
+                    ((++error_count))
+                fi
 
 
-            # two channel files should be identical to higher channel
-            # computation (first 2 channels).
-            # Do not compare cases where -bE is in flags (due to mono computation)
-            if [[ $flags != *"-bE"* ]] && [[ "$chMask" -gt 1 ]]
-            then
-                adb shell cmp $testdir/sinesweep_1_$((fs)).raw \
-                    $testdir/sinesweep_$((chMask))_$((fs)).raw
-            elif [[ $flags == *"-bE"* ]] && [[ "$chMask" -gt 1 ]]
-            then
-                adb shell $testdir/snr $testdir/sinesweep_1_$((fs)).raw \
-                    $testdir/sinesweep_$((chMask))_$((fs)).raw -thr:90.308998
-            fi
+                # two channel files should be identical to higher channel
+                # computation (first 2 channels).
+                # Do not compare cases where -bE is in flags (due to mono computation)
+                if [[ $flags != *"-bE"* ]] && [[ "$chMask" -gt 1 ]]
+                then
+                    adb shell cmp $testdir/sinesweep_1_$((fs)).raw \
+                        $testdir/sinesweep_$((chMask))_$((fs)).raw
+                elif [[ $flags == *"-bE"* ]] && [[ "$chMask" -gt 1 ]]
+                then
+                    adb shell $testdir/snr $testdir/sinesweep_1_$((fs)).raw \
+                        $testdir/sinesweep_$((chMask))_$((fs)).raw -thr:90.308998
+                fi
 
-            # both cmp and snr return EXIT_FAILURE on mismatch.
-            shell_ret=$?
-            if [ $shell_ret -ne 0 ]; then
-                echo "error: $shell_ret"
-                ((++error_count))
-            fi
-
+                # both cmp and snr return EXIT_FAILURE on mismatch.
+                shell_ret=$?
+                if [ $shell_ret -ne 0 ]; then
+                    echo "error: $shell_ret"
+                    ((++error_count))
+                fi
+            done
         done
     done
 done
diff --git a/media/libmediaplayerservice/Android.bp b/media/libmediaplayerservice/Android.bp
index 0776172..6709585 100644
--- a/media/libmediaplayerservice/Android.bp
+++ b/media/libmediaplayerservice/Android.bp
@@ -2,6 +2,7 @@
 
     srcs: [
         "ActivityManager.cpp",
+        "DeathNotifier.cpp",
         "MediaPlayerFactory.cpp",
         "MediaPlayerService.cpp",
         "MediaRecorderClient.cpp",
@@ -17,6 +18,7 @@
         "libaudioclient",
         "libbinder",
         "libcamera_client",
+        "libcodec2_client",
         "libcrypto",
         "libcutils",
         "libdl",
diff --git a/media/libmediaplayerservice/DeathNotifier.cpp b/media/libmediaplayerservice/DeathNotifier.cpp
new file mode 100644
index 0000000..d13bdf5
--- /dev/null
+++ b/media/libmediaplayerservice/DeathNotifier.cpp
@@ -0,0 +1,80 @@
+/*
+ * 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 "MediaPlayerService-DeathNotifier"
+#include <android-base/logging.h>
+
+#include "DeathNotifier.h"
+
+namespace android {
+
+class DeathNotifier::DeathRecipient :
+        public IBinder::DeathRecipient,
+        public hardware::hidl_death_recipient {
+public:
+    using Notify = DeathNotifier::Notify;
+
+    DeathRecipient(Notify const& notify): mNotify{notify} {
+    }
+
+    virtual void binderDied(wp<IBinder> const&) override {
+        mNotify();
+    }
+
+    virtual void serviceDied(uint64_t, wp<HBase> const&) override {
+        mNotify();
+    }
+
+private:
+    Notify mNotify;
+};
+
+DeathNotifier::DeathNotifier(sp<IBinder> const& service, Notify const& notify)
+      : mService{std::in_place_index<1>, service},
+        mDeathRecipient{new DeathRecipient(notify)} {
+    service->linkToDeath(mDeathRecipient);
+}
+
+DeathNotifier::DeathNotifier(sp<HBase> const& service, Notify const& notify)
+      : mService{std::in_place_index<2>, service},
+        mDeathRecipient{new DeathRecipient(notify)} {
+    service->linkToDeath(mDeathRecipient, 0);
+}
+
+DeathNotifier::DeathNotifier(DeathNotifier&& other)
+      : mService{other.mService}, mDeathRecipient{other.mDeathRecipient} {
+    other.mService.emplace<0>();
+    other.mDeathRecipient = nullptr;
+}
+
+DeathNotifier::~DeathNotifier() {
+    switch (mService.index()) {
+    case 0:
+        break;
+    case 1:
+        std::get<1>(mService)->unlinkToDeath(mDeathRecipient);
+        break;
+    case 2:
+        std::get<2>(mService)->unlinkToDeath(mDeathRecipient);
+        break;
+    default:
+        CHECK(false) << "Corrupted service type during destruction.";
+    }
+}
+
+} // namespace android
+
diff --git a/media/libmediaplayerservice/DeathNotifier.h b/media/libmediaplayerservice/DeathNotifier.h
new file mode 100644
index 0000000..7bc2611
--- /dev/null
+++ b/media/libmediaplayerservice/DeathNotifier.h
@@ -0,0 +1,48 @@
+/*
+ * 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 ANDROID_MEDIASERVICE_DEATHNOTIFIER_H
+#define ANDROID_MEDIASERVICE_DEATHNOTIFIER_H
+
+#include <android/hidl/base/1.0/IBase.h>
+#include <binder/Binder.h>
+#include <hidl/HidlSupport.h>
+
+#include <variant>
+
+namespace android {
+
+class DeathNotifier {
+public:
+    using HBase = hidl::base::V1_0::IBase;
+    using Notify = std::function<void()>;
+
+    DeathNotifier(sp<IBinder> const& service, Notify const& notify);
+    DeathNotifier(sp<HBase> const& service, Notify const& notify);
+    DeathNotifier(DeathNotifier&& other);
+    ~DeathNotifier();
+
+private:
+    std::variant<std::monostate, sp<IBinder>, sp<HBase>> mService;
+
+    class DeathRecipient;
+    sp<DeathRecipient> mDeathRecipient;
+};
+
+} // namespace android
+
+#endif // ANDROID_MEDIASERVICE_DEATHNOTIFIER_H
+
diff --git a/media/libmediaplayerservice/DeathRecipient.h b/media/libmediaplayerservice/DeathRecipient.h
new file mode 100644
index 0000000..bf5ae5c
--- /dev/null
+++ b/media/libmediaplayerservice/DeathRecipient.h
@@ -0,0 +1,59 @@
+/*
+ * 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 ANDROID_MEDIASERVICE_DEATHRECIPIENT_H
+#define ANDROID_MEDIASERVICE_DEATHRECIPIENT_H
+
+#include <binder/binder.h>
+#include <hidl/HidlSupport.h>
+
+#include <variant>
+
+class DeathNotifier :
+        public IBinder::DeathRecipient,
+        public ::android::hardware::hidl_death_recipient {
+public:
+    using Service = std::variant<
+            sp<IBinder> const&,
+            sp<android::hidl::base::V1_0::IBase> const&>;
+
+    DeathNotifier(std::variant<sp<IBinder> const&, 
+            const sp<IBinder>& service,
+            const sp<MediaPlayerBase>& listener,
+            int which,
+            const std::string& name);
+    DeathNotifier(
+            const sp<android::hidl::base::V1_0::IBase>& hService,
+            const sp<MediaPlayerBase>& listener,
+            int which,
+            const std::string& name);
+    virtual ~DeathNotifier() = default;
+    virtual void binderDied(const wp<IBinder>& who);
+    virtual void serviceDied(
+            uint64_t cookie,
+            const wp<::android::hidl::base::V1_0::IBase>& who);
+    void unlinkToDeath();
+
+private:
+    sp<IBinder> mService;
+    sp<android::hidl::base::V1_0::IBase> mHService; // HIDL service
+    wp<MediaPlayerBase> mListener;
+    int mWhich;
+    std::string mName;
+};
+
+#endif // ANDROID_MEDIASERVICE_DEATHRECIPIENT_H
+
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index 5061024..dfd3933 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -34,7 +34,7 @@
 
 #include <utils/misc.h>
 
-#include <android/hardware/media/omx/1.0/IOmxStore.h>
+#include <android/hardware/media/omx/1.0/IOmx.h>
 #include <android/hardware/media/c2/1.0/IComponentStore.h>
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
@@ -47,6 +47,7 @@
 #include <utils/Timers.h>
 #include <utils/Vector.h>
 
+#include <codec2/hidl/client.h>
 #include <media/IMediaHTTPService.h>
 #include <media/IRemoteDisplay.h>
 #include <media/IRemoteDisplayClient.h>
@@ -591,7 +592,6 @@
     if (mAudioAttributes != NULL) {
         free(mAudioAttributes);
     }
-    clearDeathNotifiers_l();
     mAudioDeviceUpdatedListener.clear();
 }
 
@@ -647,59 +647,6 @@
     return p;
 }
 
-MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
-        const sp<IBinder>& service,
-        const sp<MediaPlayerBase>& listener,
-        int which) {
-    mService = service;
-    mHService = nullptr;
-    mListener = listener;
-    mWhich = which;
-}
-
-MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier(
-        const sp<android::hidl::base::V1_0::IBase>& hService,
-        const sp<MediaPlayerBase>& listener,
-        int which) {
-    mService = nullptr;
-    mHService = hService;
-    mListener = listener;
-    mWhich = which;
-}
-
-MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() {
-}
-
-void MediaPlayerService::Client::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
-    sp<MediaPlayerBase> listener = mListener.promote();
-    if (listener != NULL) {
-        listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
-    } else {
-        ALOGW("listener for process %d death is gone", mWhich);
-    }
-}
-
-void MediaPlayerService::Client::ServiceDeathNotifier::serviceDied(
-        uint64_t /* cookie */,
-        const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
-    sp<MediaPlayerBase> listener = mListener.promote();
-    if (listener != NULL) {
-        listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
-    } else {
-        ALOGW("listener for process %d death is gone", mWhich);
-    }
-}
-
-void MediaPlayerService::Client::ServiceDeathNotifier::unlinkToDeath() {
-    if (mService != nullptr) {
-        mService->unlinkToDeath(this);
-        mService = nullptr;
-    } else if (mHService != nullptr) {
-        mHService->unlinkToDeath(this);
-        mHService = nullptr;
-    }
-}
-
 void MediaPlayerService::Client::AudioDeviceUpdatedNotifier::onAudioDeviceUpdate(
         audio_io_handle_t audioIo,
         audio_port_handle_t deviceId) {
@@ -711,19 +658,6 @@
     }
 }
 
-void MediaPlayerService::Client::clearDeathNotifiers_l() {
-    if (mExtractorDeathListener != nullptr) {
-        mExtractorDeathListener->unlinkToDeath();
-        mExtractorDeathListener = nullptr;
-    }
-    for (const sp<ServiceDeathNotifier>& codecDeathListener : mCodecDeathListeners) {
-        if (codecDeathListener != nullptr) {
-            codecDeathListener->unlinkToDeath();
-        }
-    }
-    mCodecDeathListeners.clear();
-}
-
 sp<MediaPlayerBase> MediaPlayerService::Client::setDataSource_pre(
         player_type playerType)
 {
@@ -735,66 +669,83 @@
         return p;
     }
 
+    std::vector<DeathNotifier> deathNotifiers;
+
+    // Listen to death of media.extractor service
     sp<IServiceManager> sm = defaultServiceManager();
     sp<IBinder> binder = sm->getService(String16("media.extractor"));
     if (binder == NULL) {
         ALOGE("extractor service not available");
         return NULL;
     }
-    sp<ServiceDeathNotifier> extractorDeathListener =
-            new ServiceDeathNotifier(binder, p, MEDIAEXTRACTOR_PROCESS_DEATH);
-    binder->linkToDeath(extractorDeathListener);
+    deathNotifiers.emplace_back(
+            binder, [l = wp<MediaPlayerBase>(p)]() {
+        sp<MediaPlayerBase> listener = l.promote();
+        if (listener) {
+            ALOGI("media.extractor died. Sending death notification.");
+            listener->sendEvent(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
+                                MEDIAEXTRACTOR_PROCESS_DEATH);
+        } else {
+            ALOGW("media.extractor died without a death handler.");
+        }
+    });
 
-    std::vector<sp<ServiceDeathNotifier>> codecDeathListeners;
     {
         using ::android::hidl::base::V1_0::IBase;
 
-        // Listen to OMX's IOmxStore/default
+        // Listen to death of OMX service
         {
-            sp<IBase> store = ::android::hardware::media::omx::V1_0::
-                    IOmxStore::getService();
-            if (store == nullptr) {
+            sp<IBase> base = ::android::hardware::media::omx::V1_0::
+                    IOmx::getService();
+            if (base == nullptr) {
                 ALOGD("OMX service is not available");
             } else {
-                sp<ServiceDeathNotifier> codecDeathListener =
-                        new ServiceDeathNotifier(store, p, MEDIACODEC_PROCESS_DEATH);
-                store->linkToDeath(codecDeathListener, 0);
-                codecDeathListeners.emplace_back(codecDeathListener);
+                deathNotifiers.emplace_back(
+                        base, [l = wp<MediaPlayerBase>(p)]() {
+                    sp<MediaPlayerBase> listener = l.promote();
+                    if (listener) {
+                        ALOGI("OMX service died. "
+                              "Sending death notification.");
+                        listener->sendEvent(
+                                MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
+                                MEDIACODEC_PROCESS_DEATH);
+                    } else {
+                        ALOGW("OMX service died without a death handler.");
+                    }
+                });
             }
         }
 
-        // Listen to Codec2's IComponentStore/software
-        // TODO: Listen to all Codec2 services.
+        // Listen to death of Codec2 services
         {
-            sp<IBase> store = ::android::hardware::media::c2::V1_0::
-                    IComponentStore::getService();
-            if (store == nullptr) {
-                ALOGD("Codec2 system service is not available");
-            } else {
-                sp<ServiceDeathNotifier> codecDeathListener =
-                        new ServiceDeathNotifier(store, p, MEDIACODEC_PROCESS_DEATH);
-                store->linkToDeath(codecDeathListener, 0);
-                codecDeathListeners.emplace_back(codecDeathListener);
-            }
-
-            store = ::android::hardware::media::c2::V1_0::
-                    IComponentStore::getService("software");
-            if (store == nullptr) {
-                ALOGD("Codec2 swcodec service is not available");
-            } else {
-                sp<ServiceDeathNotifier> codecDeathListener =
-                        new ServiceDeathNotifier(store, p, MEDIACODEC_PROCESS_DEATH);
-                store->linkToDeath(codecDeathListener, 0);
-                codecDeathListeners.emplace_back(codecDeathListener);
+            for (std::shared_ptr<Codec2Client> const& client :
+                    Codec2Client::CreateFromAllServices()) {
+                sp<IBase> base = client->getBase();
+                deathNotifiers.emplace_back(
+                        base, [l = wp<MediaPlayerBase>(p),
+                               name = std::string(client->getServiceName())]() {
+                    sp<MediaPlayerBase> listener = l.promote();
+                    if (listener) {
+                        ALOGI("Codec2 service \"%s\" died. "
+                              "Sending death notification.",
+                              name.c_str());
+                        listener->sendEvent(
+                                MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
+                                MEDIACODEC_PROCESS_DEATH);
+                    } else {
+                        ALOGW("Codec2 service \"%s\" died "
+                              "without a death handler.",
+                              name.c_str());
+                    }
+                });
             }
         }
     }
 
     Mutex::Autolock lock(mLock);
 
-    clearDeathNotifiers_l();
-    mExtractorDeathListener = extractorDeathListener;
-    mCodecDeathListeners.swap(codecDeathListeners);
+    mDeathNotifiers.clear();
+    mDeathNotifiers.swap(deathNotifiers);
     mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p);
 
     if (!p->hardwareOutput()) {
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index 26bfa71..49688ce 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -30,8 +30,6 @@
 #include <media/Metadata.h>
 #include <media/stagefright/foundation/ABase.h>
 
-#include <hidl/HidlSupport.h>
-
 #include <system/audio.h>
 
 namespace android {
@@ -39,6 +37,7 @@
 struct AudioPlaybackRate;
 class AudioTrack;
 struct AVSyncSettings;
+class DeathNotifier;
 class IDataSource;
 class IMediaRecorder;
 class IMediaMetadataRetriever;
@@ -388,33 +387,6 @@
         virtual status_t enableAudioDeviceCallback(bool enabled);
 
     private:
-        class ServiceDeathNotifier:
-                public IBinder::DeathRecipient,
-                public ::android::hardware::hidl_death_recipient
-        {
-        public:
-            ServiceDeathNotifier(
-                    const sp<IBinder>& service,
-                    const sp<MediaPlayerBase>& listener,
-                    int which);
-            ServiceDeathNotifier(
-                    const sp<android::hidl::base::V1_0::IBase>& hService,
-                    const sp<MediaPlayerBase>& listener,
-                    int which);
-            virtual ~ServiceDeathNotifier();
-            virtual void binderDied(const wp<IBinder>& who);
-            virtual void serviceDied(
-                    uint64_t cookie,
-                    const wp<::android::hidl::base::V1_0::IBase>& who);
-            void unlinkToDeath();
-
-        private:
-            int mWhich;
-            sp<IBinder> mService;
-            sp<android::hidl::base::V1_0::IBase> mHService; // HIDL service
-            wp<MediaPlayerBase> mListener;
-        };
-
         class AudioDeviceUpdatedNotifier: public AudioSystem::AudioDeviceCallback
         {
         public:
@@ -430,8 +402,6 @@
             wp<MediaPlayerBase> mListener;
         };
 
-        void clearDeathNotifiers_l();
-
         friend class MediaPlayerService;
                                 Client( const sp<MediaPlayerService>& service,
                                         pid_t pid,
@@ -506,8 +476,7 @@
         // getMetadata clears this set.
         media::Metadata::Filter mMetadataUpdated;  // protected by mLock
 
-        sp<ServiceDeathNotifier> mExtractorDeathListener;
-        std::vector<sp<ServiceDeathNotifier>> mCodecDeathListeners;
+        std::vector<DeathNotifier> mDeathNotifiers;
         sp<AudioDeviceUpdatedNotifier> mAudioDeviceUpdatedListener;
 #if CALLBACK_ANTAGONIZER
                     Antagonizer*                  mAntagonizer;
diff --git a/media/libmediaplayerservice/MediaRecorderClient.cpp b/media/libmediaplayerservice/MediaRecorderClient.cpp
index 9f4265b..703da4b 100644
--- a/media/libmediaplayerservice/MediaRecorderClient.cpp
+++ b/media/libmediaplayerservice/MediaRecorderClient.cpp
@@ -18,27 +18,28 @@
 #define LOG_TAG "MediaRecorderService"
 #include <utils/Log.h>
 
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <dirent.h>
-#include <unistd.h>
-#include <string.h>
-#include <cutils/atomic.h>
-#include <cutils/properties.h> // for property_get
+#include "MediaRecorderClient.h"
+#include "MediaPlayerService.h"
+#include "StagefrightRecorder.h"
+
+#include <android/hardware/media/omx/1.0/IOmx.h>
+#include <android/hardware/media/c2/1.0/IComponentStore.h>
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
 #include <binder/MemoryHeapBase.h>
 #include <binder/MemoryBase.h>
-
+#include <codec2/hidl/client.h>
+#include <cutils/atomic.h>
+#include <cutils/properties.h> // for property_get
+#include <gui/IGraphicBufferProducer.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <system/audio.h>
 #include <utils/String16.h>
 
-#include <system/audio.h>
-
-#include "MediaRecorderClient.h"
-#include "MediaPlayerService.h"
-
-#include "StagefrightRecorder.h"
-#include <gui/IGraphicBufferProducer.h>
+#include <dirent.h>
+#include <unistd.h>
+#include <string.h>
 
 namespace android {
 
@@ -339,7 +340,7 @@
         wp<MediaRecorderClient> client(this);
         mMediaPlayerService->removeMediaRecorderClient(client);
     }
-    clearDeathNotifiers_l();
+    mDeathNotifiers.clear();
     return NO_ERROR;
 }
 
@@ -358,59 +359,6 @@
     release();
 }
 
-MediaRecorderClient::ServiceDeathNotifier::ServiceDeathNotifier(
-        const sp<IBinder>& service,
-        const sp<IMediaRecorderClient>& listener,
-        int which) {
-    mService = service;
-    mOmx = nullptr;
-    mListener = listener;
-    mWhich = which;
-}
-
-MediaRecorderClient::ServiceDeathNotifier::ServiceDeathNotifier(
-        const sp<IOmx>& omx,
-        const sp<IMediaRecorderClient>& listener,
-        int which) {
-    mService = nullptr;
-    mOmx = omx;
-    mListener = listener;
-    mWhich = which;
-}
-
-MediaRecorderClient::ServiceDeathNotifier::~ServiceDeathNotifier() {
-}
-
-void MediaRecorderClient::ServiceDeathNotifier::binderDied(const wp<IBinder>& /*who*/) {
-    sp<IMediaRecorderClient> listener = mListener.promote();
-    if (listener != NULL) {
-        listener->notify(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
-    } else {
-        ALOGW("listener for process %d death is gone", mWhich);
-    }
-}
-
-void MediaRecorderClient::ServiceDeathNotifier::serviceDied(
-        uint64_t /* cookie */,
-        const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
-    sp<IMediaRecorderClient> listener = mListener.promote();
-    if (listener != NULL) {
-        listener->notify(MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED, mWhich);
-    } else {
-        ALOGW("listener for process %d death is gone", mWhich);
-    }
-}
-
-void MediaRecorderClient::ServiceDeathNotifier::unlinkToDeath() {
-    if (mService != nullptr) {
-        mService->unlinkToDeath(this);
-        mService = nullptr;
-    } else if (mOmx != nullptr) {
-        mOmx->unlinkToDeath(this);
-        mOmx = nullptr;
-    }
-}
-
 MediaRecorderClient::AudioDeviceUpdatedNotifier::AudioDeviceUpdatedNotifier(
         const sp<IMediaRecorderClient>& listener) {
     mListener = listener;
@@ -430,22 +378,11 @@
     }
 }
 
-void MediaRecorderClient::clearDeathNotifiers_l() {
-    if (mCameraDeathListener != nullptr) {
-        mCameraDeathListener->unlinkToDeath();
-        mCameraDeathListener = nullptr;
-    }
-    if (mCodecDeathListener != nullptr) {
-        mCodecDeathListener->unlinkToDeath();
-        mCodecDeathListener = nullptr;
-    }
-}
-
 status_t MediaRecorderClient::setListener(const sp<IMediaRecorderClient>& listener)
 {
     ALOGV("setListener");
     Mutex::Autolock lock(mLock);
-    clearDeathNotifiers_l();
+    mDeathNotifiers.clear();
     if (mRecorder == NULL) {
         ALOGE("recorder is not initialized");
         return NO_INIT;
@@ -463,20 +400,73 @@
     // If the device does not have a camera, do not create a death listener for it.
     if (binder != NULL) {
         sCameraVerified = true;
-        mCameraDeathListener = new ServiceDeathNotifier(binder, listener,
-                MediaPlayerService::CAMERA_PROCESS_DEATH);
-        binder->linkToDeath(mCameraDeathListener);
+        mDeathNotifiers.emplace_back(
+                binder, [l = wp<IMediaRecorderClient>(listener)](){
+            sp<IMediaRecorderClient> listener = l.promote();
+            if (listener) {
+                ALOGV("media.camera service died. "
+                      "Sending death notification.");
+                listener->notify(
+                        MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
+                        MediaPlayerService::CAMERA_PROCESS_DEATH);
+            } else {
+                ALOGW("media.camera service died without a death handler.");
+            }
+        });
     }
     sCameraChecked = true;
 
-    sp<IOmx> omx = IOmx::getService();
-    if (omx == nullptr) {
-        ALOGE("IOmx service is not available");
-        return NO_INIT;
+    {
+        using ::android::hidl::base::V1_0::IBase;
+
+        // Listen to OMX's IOmxStore/default
+        {
+            sp<IBase> base = ::android::hardware::media::omx::V1_0::
+                    IOmx::getService();
+            if (base == nullptr) {
+                ALOGD("OMX service is not available");
+            } else {
+                mDeathNotifiers.emplace_back(
+                        base, [l = wp<IMediaRecorderClient>(listener)](){
+                    sp<IMediaRecorderClient> listener = l.promote();
+                    if (listener) {
+                        ALOGV("OMX service died. "
+                              "Sending death notification.");
+                        listener->notify(
+                                MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
+                                MediaPlayerService::MEDIACODEC_PROCESS_DEATH);
+                    } else {
+                        ALOGW("OMX service died without a death handler.");
+                    }
+                });
+            }
+        }
+
+        // Listen to Codec2's IComponentStore instances
+        {
+            for (std::shared_ptr<Codec2Client> const& client :
+                    Codec2Client::CreateFromAllServices()) {
+                sp<IBase> base = client->getBase();
+                mDeathNotifiers.emplace_back(
+                        base, [l = wp<IMediaRecorderClient>(listener),
+                               name = std::string(client->getServiceName())]() {
+                    sp<IMediaRecorderClient> listener = l.promote();
+                    if (listener) {
+                        ALOGV("Codec2 service \"%s\" died. "
+                              "Sending death notification",
+                              name.c_str());
+                        listener->notify(
+                                MEDIA_ERROR, MEDIA_ERROR_SERVER_DIED,
+                                MediaPlayerService::MEDIACODEC_PROCESS_DEATH);
+                    } else {
+                        ALOGW("Codec2 service \"%s\" died "
+                              "without a death handler",
+                              name.c_str());
+                    }
+                });
+            }
+        }
     }
-    mCodecDeathListener = new ServiceDeathNotifier(omx, listener,
-            MediaPlayerService::MEDIACODEC_PROCESS_DEATH);
-    omx->linkToDeath(mCodecDeathListener, 0);
 
     mAudioDeviceUpdatedNotifier = new AudioDeviceUpdatedNotifier(listener);
     mRecorder->setAudioDeviceCallback(mAudioDeviceUpdatedNotifier);
diff --git a/media/libmediaplayerservice/MediaRecorderClient.h b/media/libmediaplayerservice/MediaRecorderClient.h
index e698819..9e0f877 100644
--- a/media/libmediaplayerservice/MediaRecorderClient.h
+++ b/media/libmediaplayerservice/MediaRecorderClient.h
@@ -18,10 +18,12 @@
 #ifndef ANDROID_MEDIARECORDERCLIENT_H
 #define ANDROID_MEDIARECORDERCLIENT_H
 
+#include "DeathNotifier.h"
+
 #include <media/AudioSystem.h>
 #include <media/IMediaRecorder.h>
 
-#include <android/hardware/media/omx/1.0/IOmx.h>
+#include <vector>
 
 namespace android {
 
@@ -31,34 +33,6 @@
 
 class MediaRecorderClient : public BnMediaRecorder
 {
-    typedef ::android::hardware::media::omx::V1_0::IOmx IOmx;
-
-    class ServiceDeathNotifier :
-            public IBinder::DeathRecipient,
-            public ::android::hardware::hidl_death_recipient
-    {
-    public:
-        ServiceDeathNotifier(
-                const sp<IBinder>& service,
-                const sp<IMediaRecorderClient>& listener,
-                int which);
-        ServiceDeathNotifier(
-                const sp<IOmx>& omx,
-                const sp<IMediaRecorderClient>& listener,
-                int which);
-        virtual ~ServiceDeathNotifier();
-        virtual void binderDied(const wp<IBinder>& who);
-        virtual void serviceDied(
-                uint64_t cookie,
-                const wp<::android::hidl::base::V1_0::IBase>& who);
-        void unlinkToDeath();
-    private:
-        int mWhich;
-        sp<IBinder> mService;
-        sp<IOmx> mOmx;
-        wp<IMediaRecorderClient> mListener;
-    };
-
     class AudioDeviceUpdatedNotifier: public AudioSystem::AudioDeviceCallback
     {
     public:
@@ -71,8 +45,6 @@
         wp<IMediaRecorderClient> mListener;
     };
 
-    void clearDeathNotifiers_l();
-
 public:
     virtual     status_t   setCamera(const sp<hardware::ICamera>& camera,
                                     const sp<ICameraRecordingProxy>& proxy);
@@ -122,8 +94,7 @@
                                                                const String16& opPackageName);
     virtual                ~MediaRecorderClient();
 
-    sp<ServiceDeathNotifier> mCameraDeathListener;
-    sp<ServiceDeathNotifier> mCodecDeathListener;
+    std::vector<DeathNotifier> mDeathNotifiers;
     sp<AudioDeviceUpdatedNotifier> mAudioDeviceUpdatedNotifier;
 
     pid_t                  mPid;
diff --git a/media/libstagefright/MediaExtractorFactory.cpp b/media/libstagefright/MediaExtractorFactory.cpp
index a309ee4..d97591f 100644
--- a/media/libstagefright/MediaExtractorFactory.cpp
+++ b/media/libstagefright/MediaExtractorFactory.cpp
@@ -19,6 +19,7 @@
 #include <utils/Log.h>
 
 #include <android/dlext.h>
+#include <android-base/logging.h>
 #include <binder/IPCThreadState.h>
 #include <binder/PermissionCache.h>
 #include <binder/IServiceManager.h>
@@ -244,20 +245,17 @@
             void *libHandle = android_dlopen_ext(
                     libPath.string(),
                     RTLD_NOW | RTLD_LOCAL, dlextinfo);
-            if (libHandle) {
-                GetExtractorDef getDef =
-                    (GetExtractorDef) dlsym(libHandle, "GETEXTRACTORDEF");
-                if (getDef) {
-                    ALOGV("registering sniffer for %s", libPath.string());
-                    RegisterExtractor(
-                            new ExtractorPlugin(getDef(), libHandle, libPath), pluginList);
-                } else {
-                    ALOGW("%s does not contain sniffer", libPath.string());
-                    dlclose(libHandle);
-                }
-            } else {
-                ALOGW("couldn't dlopen(%s) %s", libPath.string(), strerror(errno));
-            }
+            CHECK(libHandle != nullptr)
+                    << "couldn't dlopen(" << libPath.string() << ") " << strerror(errno);
+
+            GetExtractorDef getDef =
+                (GetExtractorDef) dlsym(libHandle, "GETEXTRACTORDEF");
+            CHECK(getDef != nullptr)
+                    << libPath.string() << " does not contain sniffer";
+
+            ALOGV("registering sniffer for %s", libPath.string());
+            RegisterExtractor(
+                    new ExtractorPlugin(getDef(), libHandle, libPath), pluginList);
         }
         closedir(libDir);
     } else {
diff --git a/media/libstagefright/VideoFrameSchedulerBase.cpp b/media/libstagefright/VideoFrameSchedulerBase.cpp
index 77107ff..0d1517b 100644
--- a/media/libstagefright/VideoFrameSchedulerBase.cpp
+++ b/media/libstagefright/VideoFrameSchedulerBase.cpp
@@ -115,6 +115,10 @@
 
 #endif
 
+// If overflow happens, the value is already incorrect, and no mater what value we get is OK.
+// And this part of calculation is not important, so it's OK to simply disable overflow check
+// instead of using double which makes code more complicated.
+__attribute__((no_sanitize("integer")))
 bool VideoFrameSchedulerBase::PLL::fit(
         nsecs_t phase, nsecs_t period, size_t numSamplesToUse,
         int64_t *a, int64_t *b, int64_t *err) {
diff --git a/media/libstagefright/rtsp/MyHandler.h b/media/libstagefright/rtsp/MyHandler.h
index b4515e4..48bc8ce 100644
--- a/media/libstagefright/rtsp/MyHandler.h
+++ b/media/libstagefright/rtsp/MyHandler.h
@@ -75,6 +75,8 @@
 // a new sequence.
 static int32_t kMaxAllowedStaleAccessUnits = 20;
 
+static int64_t kTearDownTimeoutUs = 3000000ll;
+
 namespace android {
 
 static bool GetAttribute(const char *s, const char *key, AString *value) {
@@ -930,6 +932,14 @@
                 request.append("\r\n");
 
                 mConn->sendRequest(request.c_str(), reply);
+
+                // If the response of teardown hasn't been received in 3 seconds,
+                // post 'tear' message to avoid ANR.
+                if (!msg->findInt32("reconnect", &reconnect) || !reconnect) {
+                    sp<AMessage> teardown = reply->dup();
+                    teardown->setInt32("result", -ECONNABORTED);
+                    teardown->post(kTearDownTimeoutUs);
+                }
                 break;
             }
 
diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h
index 4fd72a7..56be433 100644
--- a/services/audioflinger/PlaybackTracks.h
+++ b/services/audioflinger/PlaybackTracks.h
@@ -22,11 +22,16 @@
 // Checks and monitors OP_PLAY_AUDIO
 class OpPlayAudioMonitor : public RefBase {
 public:
-    OpPlayAudioMonitor(uid_t uid, audio_usage_t usage, int id, audio_stream_type_t streamType);
     ~OpPlayAudioMonitor() override;
     bool hasOpPlayAudio() const;
 
+    static sp<OpPlayAudioMonitor> createIfNeeded(
+            uid_t uid, audio_usage_t usage, int id, audio_stream_type_t streamType);
+
 private:
+    OpPlayAudioMonitor(uid_t uid, audio_usage_t usage, int id);
+    void onFirstRef() override;
+
     AppOpsManager mAppOpsManager;
 
     class PlayAudioOpCallback : public BnAppOpsCallback {
@@ -209,7 +214,9 @@
 
     int fastIndex() const { return mFastIndex; }
 
-    bool isPlaybackRestricted() const { return !mOpPlayAudioMonitor->hasOpPlayAudio(); }
+    bool isPlaybackRestricted() const {
+        // The monitor is only created for tracks that can be silenced.
+        return mOpPlayAudioMonitor ? !mOpPlayAudioMonitor->hasOpPlayAudio() : false; }
 
 protected:
 
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index 2ff80c6..8d59431 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -381,26 +381,28 @@
 // ----------------------------------------------------------------------------
 //      AppOp for audio playback
 // -------------------------------
-AudioFlinger::PlaybackThread::OpPlayAudioMonitor::OpPlayAudioMonitor(uid_t uid, audio_usage_t usage,
-        int id, audio_stream_type_t streamType)
-            : mHasOpPlayAudio(true), mUid(uid), mUsage((int32_t) usage), mId(id)
+
+// static
+sp<AudioFlinger::PlaybackThread::OpPlayAudioMonitor>
+AudioFlinger::PlaybackThread::OpPlayAudioMonitor::createIfNeeded(
+            uid_t uid, audio_usage_t usage, int id, audio_stream_type_t streamType)
 {
     if (isAudioServerOrRootUid(uid)) {
-        ALOGD("OpPlayAudio: not muting track:%d usage:%d root or audioserver", mId, usage);
-        return;
+        ALOGD("OpPlayAudio: not muting track:%d usage:%d root or audioserver", id, usage);
+        return nullptr;
     }
     // stream type has been filtered by audio policy to indicate whether it can be muted
     if (streamType == AUDIO_STREAM_ENFORCED_AUDIBLE) {
-        ALOGD("OpPlayAudio: not muting track:%d usage:%d ENFORCED_AUDIBLE", mId, usage);
-        return;
+        ALOGD("OpPlayAudio: not muting track:%d usage:%d ENFORCED_AUDIBLE", id, usage);
+        return nullptr;
     }
-    PermissionController permissionController;
-    permissionController.getPackagesForUid(uid, mPackages);
-    checkPlayAudioForUsage();
-    if (!mPackages.isEmpty()) {
-        mOpCallback = new PlayAudioOpCallback(this);
-        mAppOpsManager.startWatchingMode(AppOpsManager::OP_PLAY_AUDIO, mPackages[0], mOpCallback);
-    }
+    return new OpPlayAudioMonitor(uid, usage, id);
+}
+
+AudioFlinger::PlaybackThread::OpPlayAudioMonitor::OpPlayAudioMonitor(
+        uid_t uid, audio_usage_t usage, int id)
+        : mHasOpPlayAudio(true), mUid(uid), mUsage((int32_t) usage), mId(id)
+{
 }
 
 AudioFlinger::PlaybackThread::OpPlayAudioMonitor::~OpPlayAudioMonitor()
@@ -411,6 +413,17 @@
     mOpCallback.clear();
 }
 
+void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::onFirstRef()
+{
+    PermissionController permissionController;
+    permissionController.getPackagesForUid(mUid, mPackages);
+    checkPlayAudioForUsage();
+    if (!mPackages.isEmpty()) {
+        mOpCallback = new PlayAudioOpCallback(this);
+        mAppOpsManager.startWatchingMode(AppOpsManager::OP_PLAY_AUDIO, mPackages[0], mOpCallback);
+    }
+}
+
 bool AudioFlinger::PlaybackThread::OpPlayAudioMonitor::hasOpPlayAudio() const {
     return mHasOpPlayAudio.load();
 }
@@ -492,7 +505,7 @@
     mPresentationCompleteFrames(0),
     mFrameMap(16 /* sink-frame-to-track-frame map memory */),
     mVolumeHandler(new media::VolumeHandler(sampleRate)),
-    mOpPlayAudioMonitor(new OpPlayAudioMonitor(uid, attr.usage, id(), streamType)),
+    mOpPlayAudioMonitor(OpPlayAudioMonitor::createIfNeeded(uid, attr.usage, id(), streamType)),
     // mSinkTimestamp
     mFastIndex(-1),
     mCachedVolume(1.0),
diff --git a/services/audiopolicy/Android.bp b/services/audiopolicy/Android.bp
new file mode 100644
index 0000000..a42b89f
--- /dev/null
+++ b/services/audiopolicy/Android.bp
@@ -0,0 +1,5 @@
+cc_library_headers {
+    name: "libaudiopolicymanager_interface_headers",
+    host_supported: true,
+    export_include_dirs: ["."],
+}
diff --git a/services/audiopolicy/Android.mk b/services/audiopolicy/Android.mk
deleted file mode 100644
index 3badda1..0000000
--- a/services/audiopolicy/Android.mk
+++ /dev/null
@@ -1,136 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-    service/AudioPolicyService.cpp \
-    service/AudioPolicyEffects.cpp \
-    service/AudioPolicyInterfaceImpl.cpp \
-    service/AudioPolicyClientImpl.cpp
-
-LOCAL_C_INCLUDES := \
-    frameworks/av/services/audioflinger \
-    $(call include-path-for, audio-utils) \
-
-LOCAL_HEADER_LIBRARIES := \
-    libaudiopolicycommon \
-    libaudiopolicyengine_interface_headers \
-
-LOCAL_SHARED_LIBRARIES := \
-    libcutils \
-    libutils \
-    liblog \
-    libbinder \
-    libaudioclient \
-    libhardware_legacy \
-    libaudiopolicymanager \
-    libmedia_helper \
-    libmediametrics \
-    libmediautils \
-    libeffectsconfig \
-    libsensorprivacy
-
-LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := \
-    libsensorprivacy
-
-LOCAL_STATIC_LIBRARIES := \
-    libaudiopolicycomponents
-
-LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
-
-LOCAL_MODULE:= libaudiopolicyservice
-
-LOCAL_CFLAGS += -fvisibility=hidden
-LOCAL_CFLAGS += -Wall -Werror
-
-include $(BUILD_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= managerdefault/AudioPolicyManager.cpp
-
-LOCAL_SHARED_LIBRARIES := \
-    libcutils \
-    libutils \
-    liblog \
-    libaudiopolicy \
-    libsoundtrigger
-
-ifeq ($(USE_CONFIGURABLE_AUDIO_POLICY), 1)
-
-ifneq ($(USE_XML_AUDIO_POLICY_CONF), 1)
-$(error Configurable policy does not support legacy conf file)
-endif #ifneq ($(USE_XML_AUDIO_POLICY_CONF), 1)
-
-LOCAL_C_INCLUDES += frameworks/av/services/audiopolicy/engineconfigurable/include
-LOCAL_C_INCLUDES += frameworks/av/include
-
-LOCAL_SHARED_LIBRARIES += libaudiopolicyengineconfigurable
-
-else
-
-LOCAL_SHARED_LIBRARIES += libaudiopolicyenginedefault
-
-endif # ifeq ($(USE_CONFIGURABLE_AUDIO_POLICY), 1)
-
-LOCAL_C_INCLUDES += \
-    $(call include-path-for, audio-utils) \
-
-LOCAL_HEADER_LIBRARIES := \
-    libaudiopolicycommon \
-    libaudiopolicyengine_interface_headers
-
-LOCAL_STATIC_LIBRARIES := \
-    libaudiopolicycomponents
-
-LOCAL_SHARED_LIBRARIES += libmedia_helper
-LOCAL_SHARED_LIBRARIES += libmediametrics
-
-LOCAL_SHARED_LIBRARIES += libbinder libhidlbase libxml2
-
-ifeq ($(USE_XML_AUDIO_POLICY_CONF), 1)
-LOCAL_CFLAGS += -DUSE_XML_AUDIO_POLICY_CONF
-endif #ifeq ($(USE_XML_AUDIO_POLICY_CONF), 1)
-
-LOCAL_CFLAGS += -Wall -Werror
-
-LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
-
-LOCAL_MODULE:= libaudiopolicymanagerdefault
-
-include $(BUILD_SHARED_LIBRARY)
-
-ifneq ($(USE_CUSTOM_AUDIO_POLICY), 1)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-    manager/AudioPolicyFactory.cpp
-
-LOCAL_SHARED_LIBRARIES := \
-    libaudiopolicymanagerdefault
-
-LOCAL_STATIC_LIBRARIES := \
-    libaudiopolicycomponents
-
-LOCAL_C_INCLUDES += \
-    $(call include-path-for, audio-utils) \
-
-LOCAL_HEADER_LIBRARIES := \
-    libaudiopolicycommon \
-    libaudiopolicyengine_interface_headers
-
-LOCAL_CFLAGS := -Wall -Werror
-
-LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
-
-LOCAL_MODULE:= libaudiopolicymanager
-
-include $(BUILD_SHARED_LIBRARY)
-
-endif
-
-#######################################################################
-# Recursive call sub-folder Android.mk
-#
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/services/audiopolicy/common/managerdefinitions/Android.bp b/services/audiopolicy/common/managerdefinitions/Android.bp
index c9037a1..f02f3cf 100644
--- a/services/audiopolicy/common/managerdefinitions/Android.bp
+++ b/services/audiopolicy/common/managerdefinitions/Android.bp
@@ -34,6 +34,7 @@
     ],
     header_libs: [
         "libaudiopolicycommon",
+        "libaudiopolicymanager_interface_headers",
     ],
     export_header_lib_headers: ["libaudiopolicycommon"],
 
diff --git a/services/audiopolicy/engine/Android.mk b/services/audiopolicy/engine/Android.mk
deleted file mode 100644
index dcce8e3..0000000
--- a/services/audiopolicy/engine/Android.mk
+++ /dev/null
@@ -1,9 +0,0 @@
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-#######################################################################
-# Recursive call sub-folder Android.mk
-#
-include $(call all-makefiles-under,$(LOCAL_PATH))
-
diff --git a/services/audiopolicy/engineconfigurable/Android.bp b/services/audiopolicy/engineconfigurable/Android.bp
new file mode 100644
index 0000000..c27dc88
--- /dev/null
+++ b/services/audiopolicy/engineconfigurable/Android.bp
@@ -0,0 +1,44 @@
+cc_library_headers {
+    name: "libaudiopolicyengineconfigurable_interface_headers",
+    host_supported: true,
+    export_include_dirs: ["interface"],
+}
+
+cc_library_shared {
+    name: "libaudiopolicyengineconfigurable",
+    export_include_dirs: ["include"],
+    srcs: [
+        "src/Engine.cpp",
+        "src/EngineInstance.cpp",
+        "src/Stream.cpp",
+        "src/InputSource.cpp",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+    local_include_dirs: ["include"],
+    header_libs: [
+        "libbase_headers",
+        "libaudiopolicycommon",
+        "libaudiopolicyengine_interface_headers",
+        "libaudiopolicyengineconfigurable_interface_headers",
+    ],
+    static_libs: [
+        "libaudiopolicycomponents",
+        "libaudiopolicyengine_common",
+        "libaudiopolicyengine_config",
+        "libaudiopolicyengineconfigurable_pfwwrapper",
+
+    ],
+    shared_libs: [
+        "liblog",
+        "libcutils",
+        "libutils",
+        "libmedia_helper",
+        "libaudiopolicy",
+        "libparameter",
+        "libxml2",
+    ],
+}
diff --git a/services/audiopolicy/engineconfigurable/Android.mk b/services/audiopolicy/engineconfigurable/Android.mk
deleted file mode 100644
index 84a4422..0000000
--- a/services/audiopolicy/engineconfigurable/Android.mk
+++ /dev/null
@@ -1,67 +0,0 @@
-ifeq ($(USE_CONFIGURABLE_AUDIO_POLICY), 1)
-
-LOCAL_PATH := $(call my-dir)
-
-# Component build
-#######################################################################
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := \
-    src/Engine.cpp \
-    src/EngineInstance.cpp \
-    src/Stream.cpp \
-    src/InputSource.cpp \
-
-audio_policy_engine_includes_common := \
-    frameworks/av/services/audiopolicy/engineconfigurable/include \
-    frameworks/av/services/audiopolicy/engineconfigurable/interface
-
-LOCAL_CFLAGS += \
-    -Wall \
-    -Werror \
-    -Wextra \
-
-LOCAL_EXPORT_C_INCLUDE_DIRS := \
-    $(audio_policy_engine_includes_common)
-
-LOCAL_C_INCLUDES := \
-    $(audio_policy_engine_includes_common) \
-    $(TARGET_OUT_HEADERS)/hw \
-    $(call include-path-for, frameworks-av) \
-    $(call include-path-for, audio-utils)
-
-LOCAL_HEADER_LIBRARIES := \
-    libaudiopolicycommon \
-    libaudiopolicyengine_interface_headers
-
-LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
-
-LOCAL_MODULE := libaudiopolicyengineconfigurable
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_STATIC_LIBRARIES := \
-    libaudiopolicypfwwrapper \
-    libaudiopolicycomponents \
-    libaudiopolicyengine_common \
-    libaudiopolicyengine_config \
-
-LOCAL_SHARED_LIBRARIES := \
-    liblog \
-    libutils \
-    liblog \
-    libcutils \
-    libaudioutils \
-    libparameter \
-    libmedia_helper \
-    libaudiopolicy \
-    libxml2
-
-include $(BUILD_SHARED_LIBRARY)
-
-#######################################################################
-# Recursive call sub-folder Android.mk
-#
-include $(call all-makefiles-under,$(LOCAL_PATH))
-
-endif
diff --git a/services/audiopolicy/engineconfigurable/config/Android.mk b/services/audiopolicy/engineconfigurable/config/Android.mk
deleted file mode 100644
index dcce8e3..0000000
--- a/services/audiopolicy/engineconfigurable/config/Android.mk
+++ /dev/null
@@ -1,9 +0,0 @@
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-#######################################################################
-# Recursive call sub-folder Android.mk
-#
-include $(call all-makefiles-under,$(LOCAL_PATH))
-
diff --git a/services/audiopolicy/engineconfigurable/config/example/Android.mk b/services/audiopolicy/engineconfigurable/config/example/Android.mk
index 37271b5..a0f1a90 100644
--- a/services/audiopolicy/engineconfigurable/config/example/Android.mk
+++ b/services/audiopolicy/engineconfigurable/config/example/Android.mk
@@ -1,5 +1,7 @@
 LOCAL_PATH := $(call my-dir)
 
+ifdef BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION
+
 TOOLS := frameworks/av/services/audiopolicy/engineconfigurable/tools
 PROVISION_CRITERION_TYPES := $(TOOLS)/provision_criterion_types_from_android_headers.mk
 
@@ -137,9 +139,7 @@
 LOCAL_MODULE := audio_policy_engine_criterion_types.xml
 LOCAL_MODULE_CLASS := ETC
 LOCAL_VENDOR_MODULE := true
-LOCAL_ADDITIONAL_DEPENDENCIES := \
-    $(TARGET_OUT_VENDOR_ETC)/audio_policy_configuration.xml
-
+LOCAL_ADDITIONAL_DEPENDENCIES := $(TARGET_OUT_VENDOR_ETC)/primary_audio_policy_configuration.xml
 ANDROID_AUDIO_BASE_HEADER_FILE := system/media/audio/include/system/audio-base.h
 AUDIO_POLICY_CONFIGURATION_FILE := $(TARGET_OUT_VENDOR_ETC)/audio_policy_configuration.xml
 CRITERION_TYPES_FILE := $(LOCAL_PATH)/common/$(LOCAL_MODULE).in
@@ -147,3 +147,5 @@
 include $(PROVISION_CRITERION_TYPES)
 
 endif #ifeq ($(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),$(filter $(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),phone_configurable automotive_configurable caremu_configurable))
+
+endif #ifdef BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION
diff --git a/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_configuration.xml b/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_configuration.xml
index 4ca33b4..3faf9b9 100644
--- a/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_configuration.xml
+++ b/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_configuration.xml
@@ -17,6 +17,8 @@
 <configuration version="1.0" xmlns:xi="http://www.w3.org/2001/XInclude">
 
     <xi:include href="audio_policy_engine_product_strategies.xml"/>
+    <xi:include href="audio_policy_engine_criterion_types.xml"/>
+    <xi:include href="audio_policy_engine_criteria.xml"/>
     <xi:include href="audio_policy_engine_stream_volumes.xml"/>
     <xi:include href="audio_policy_engine_default_stream_volumes.xml"/>
 
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/Android.mk b/services/audiopolicy/engineconfigurable/parameter-framework/Android.mk
deleted file mode 100644
index c402fd5..0000000
--- a/services/audiopolicy/engineconfigurable/parameter-framework/Android.mk
+++ /dev/null
@@ -1,7 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-#######################################################################
-# Recursive call sub-folder Android.mk
-#######################################################################
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Android.mk b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Android.mk
index 782fe83..19f93b3 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Android.mk
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Android.mk
@@ -9,6 +9,8 @@
 
 LOCAL_PATH := $(call my-dir)
 
+ifdef BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION
+
 ifeq ($(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),$(filter $(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),phone_configurable automotive_configurable caremu_configurable no-output_configurable no-input_configurable))
 
 PFW_CORE := external/parameter-framework
@@ -38,14 +40,17 @@
 LOCAL_VENDOR_MODULE := true
 LOCAL_MODULE_RELATIVE_PATH := parameter-framework
 LOCAL_SRC_FILES := $(LOCAL_MODULE).in
+LOCAL_REQUIRED_MODULES := \
+    PolicySubsystem.xml \
+    PolicyClass.xml
 
 # external/parameter-framework prevents from using debug interface
 AUDIO_PATTERN = @TUNING_ALLOWED@
-#ifeq ($(TARGET_BUILD_VARIANT),user)
+ifeq ($(TARGET_BUILD_VARIANT),user)
 AUDIO_VALUE = false
-#else
-#AUDIO_VALUE = true
-#endif
+else
+AUDIO_VALUE = true
+endif
 
 LOCAL_POST_INSTALL_CMD := $(hide) sed -i -e 's|$(AUDIO_PATTERN)|$(AUDIO_VALUE)|g' $(TARGET_OUT_VENDOR_ETC)/$(LOCAL_MODULE_RELATIVE_PATH)/$(LOCAL_MODULE)
 
@@ -60,9 +65,7 @@
 LOCAL_VENDOR_MODULE := true
 LOCAL_REQUIRED_MODULES := \
     PolicySubsystem-CommonTypes.xml \
-    ProductStrategies.xml \
-    PolicySubsystem-Volume.xml \
-    libpolicy-subsystem \
+    ProductStrategies.xml
 
 LOCAL_MODULE_RELATIVE_PATH := parameter-framework/Structure/Policy
 LOCAL_SRC_FILES := common/Structure/$(LOCAL_MODULE)
@@ -92,7 +95,7 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_VENDOR_MODULE := true
 LOCAL_MODULE_RELATIVE_PATH := parameter-framework/Structure/Policy
-LOCAL_ADDITIONAL_DEPENDENCIES := $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_configuration.xml
+
 AUDIO_POLICY_ENGINE_CONFIGURATION_FILE := \
     $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_configuration.xml
 STRATEGIES_STRUCTURE_FILE := $(LOCAL_PATH)/common/Structure/$(LOCAL_MODULE).in
@@ -105,18 +108,30 @@
 ifeq ($(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),$(filter $(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),no-output_configurable no-input_configurable))
 
 include $(CLEAR_VARS)
-LOCAL_MODULE := PolicySubsystem-no-strategy.xml
-LOCAL_MODULE_STEM := PolicySubsystem.xml
+LOCAL_MODULE := PolicySubsystem.xml
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_CLASS := ETC
 LOCAL_VENDOR_MODULE := true
-LOCAL_REQUIRED_MODULES := \
-    PolicySubsystem-CommonTypes.xml \
-    PolicySubsystem-Volume.xml \
-    libpolicy-subsystem \
+LOCAL_REQUIRED_MODULES := PolicySubsystem-CommonTypes.xml
 
 LOCAL_MODULE_RELATIVE_PATH := parameter-framework/Structure/Policy
-LOCAL_SRC_FILES := common/Structure/$(LOCAL_MODULE_STEM)
+LOCAL_SRC_FILES := common/Structure/$(LOCAL_MODULE)
+include $(BUILD_PREBUILT)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := ParameterFrameworkConfigurationPolicy-no-strategy.xml
+LOCAL_MODULE_STEM := ParameterFrameworkConfigurationPolicy.xml
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_CLASS := ETC
+LOCAL_VENDOR_MODULE := true
+LOCAL_MODULE_RELATIVE_PATH := parameter-framework
+LOCAL_SRC_FILES := $(LOCAL_MODULE).in
+LOCAL_REQUIRED_MODULES := \
+    PolicySubsystem.xml \
+    PolicyClass.xml
+AUDIO_VALUE = false
+LOCAL_POST_INSTALL_CMD := $(hide) sed -i -e 's|$(AUDIO_PATTERN)|$(AUDIO_VALUE)|g' $(TARGET_OUT_VENDOR_ETC)/$(LOCAL_MODULE_RELATIVE_PATH)/$(LOCAL_MODULE)
+
 include $(BUILD_PREBUILT)
 
 endif # ifeq ($(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),$(filter $(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),no-output_configurable no-input_configurable))
@@ -130,12 +145,6 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_VENDOR_MODULE := true
 LOCAL_MODULE_RELATIVE_PATH := parameter-framework/Settings/Policy
-LOCAL_REQUIRED_MODULES := \
-    audio_policy_engine_criteria.xml \
-    audio_policy_engine_criterion_types.xml \
-    PolicySubsystem-no-strategy.xml \
-    PolicyClass.xml \
-    ParameterFrameworkConfigurationPolicy.xml
 
 PFW_TOPLEVEL_FILE := $(TARGET_OUT_VENDOR_ETC)/parameter-framework/ParameterFrameworkConfigurationPolicy.xml
 PFW_CRITERION_TYPES_FILE := $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_criterion_types.xml
@@ -143,9 +152,10 @@
 PFW_EDD_FILES := \
         $(LOCAL_PATH)/SettingsNoOutput/device_for_strategies.pfw \
         $(LOCAL_PATH)/Settings/device_for_input_source.pfw \
-        $(LOCAL_PATH)/Settings/volumes.pfw
-
+        $(LOCAL_PATH)/Settings/volumes.pfw        
+LOCAL_REQUIRED_MODULES := libpolicy-subsystem
 include $(BUILD_PFW_SETTINGS)
+
 endif # ifeq ($(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),no-output_configurable)
 ######### Policy PFW Settings - No Input #########
 ifeq ($(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),no-input_configurable)
@@ -156,12 +166,6 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_VENDOR_MODULE := true
 LOCAL_MODULE_RELATIVE_PATH := parameter-framework/Settings/Policy
-LOCAL_REQUIRED_MODULES := \
-    audio_policy_engine_criteria.xml \
-    audio_policy_engine_criterion_types.xml \
-    PolicySubsystem-no-strategy.xml \
-    PolicyClass.xml \
-    ParameterFrameworkConfigurationPolicy.xml
 
 PFW_TOPLEVEL_FILE := $(TARGET_OUT_VENDOR_ETC)/parameter-framework/ParameterFrameworkConfigurationPolicy.xml
 PFW_CRITERION_TYPES_FILE := $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_criterion_types.xml
@@ -169,7 +173,7 @@
 PFW_EDD_FILES := \
         $(LOCAL_PATH)/SettingsNoInput/device_for_input_source.pfw \
         $(LOCAL_PATH)/Settings/volumes.pfw
-
+LOCAL_REQUIRED_MODULES := libpolicy-subsystem
 include $(BUILD_PFW_SETTINGS)
 
 endif #ifeq ($(BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION),no-input_configurable)
@@ -179,4 +183,5 @@
 
 include $(call all-makefiles-under,$(LOCAL_PATH))
 
+endif #ifdef BUILD_AUDIO_POLICY_EXAMPLE_CONFIGURATION
 
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.mk b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.mk
index 20ca8e2..7304ec2 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.mk
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.mk
@@ -30,27 +30,16 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_VENDOR_MODULE := true
 LOCAL_MODULE_RELATIVE_PATH := parameter-framework/Settings/Policy
+LOCAL_REQUIRED_MODULES := libpolicy-subsystem
 
 PFW_EDD_FILES := \
-        $(LOCAL_PATH)/Settings/device_for_product_strategies.pfw \
-        $(LOCAL_PATH)/../Settings/device_for_input_source.pfw \
-        $(LOCAL_PATH)/../Settings/volumes.pfw
-
-LOCAL_ADDITIONAL_DEPENDENCIES := \
-    $(PFW_EDD_FILES)
-
-LOCAL_REQUIRED_MODULES := \
-    PolicySubsystem.xml \
-    PolicyClass.xml \
-    audio_policy_engine_criteria.xml \
-    audio_policy_engine_criterion_types.xml \
-    ParameterFrameworkConfigurationPolicy.xml
+    $(LOCAL_PATH)/Settings/device_for_product_strategies.pfw \
+    $(LOCAL_PATH)/../Settings/device_for_input_source.pfw \
+    $(LOCAL_PATH)/../Settings/volumes.pfw
 
 PFW_CRITERION_TYPES_FILE := $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_criterion_types.xml
 PFW_CRITERIA_FILE := $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_criteria.xml
-
 PFW_TOPLEVEL_FILE := $(TARGET_OUT_VENDOR_ETC)/parameter-framework/ParameterFrameworkConfigurationPolicy.xml
-
 PFW_SCHEMAS_DIR := $(PFW_DEFAULT_SCHEMAS_DIR)
 
 include $(BUILD_PFW_SETTINGS)
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.mk b/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.mk
index 8fa8f0a..f5eb7d1 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.mk
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.mk
@@ -30,27 +30,15 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_VENDOR_MODULE := true
 LOCAL_MODULE_RELATIVE_PATH := parameter-framework/Settings/Policy
+LOCAL_REQUIRED_MODULES := libpolicy-subsystem
 
 PFW_EDD_FILES := \
-        $(LOCAL_PATH)/Settings/device_for_product_strategies.pfw \
-        $(LOCAL_PATH)/../Settings/device_for_input_source.pfw \
-        $(LOCAL_PATH)/../Settings/volumes.pfw
-
-LOCAL_ADDITIONAL_DEPENDENCIES := \
-    $(PFW_EDD_FILES)
-
-LOCAL_REQUIRED_MODULES := \
-    PolicySubsystem.xml \
-    PolicyClass.xml \
-    audio_policy_engine_criteria.xml \
-    audio_policy_engine_criterion_types.xml \
-    ParameterFrameworkConfigurationPolicy.xml
-
+    $(LOCAL_PATH)/Settings/device_for_product_strategies.pfw \
+    $(LOCAL_PATH)/../Settings/device_for_input_source.pfw \
+    $(LOCAL_PATH)/../Settings/volumes.pfw
 PFW_CRITERION_TYPES_FILE := $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_criterion_types.xml
 PFW_CRITERIA_FILE := $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_criteria.xml
-
 PFW_TOPLEVEL_FILE := $(TARGET_OUT_VENDOR_ETC)/parameter-framework/ParameterFrameworkConfigurationPolicy.xml
-
 PFW_SCHEMAS_DIR := $(PFW_DEFAULT_SCHEMAS_DIR)
 
 include $(BUILD_PFW_SETTINGS)
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/ParameterFrameworkConfigurationPolicy.xml.in b/services/audiopolicy/engineconfigurable/parameter-framework/examples/ParameterFrameworkConfigurationPolicy.xml.in
index f80a07f..1be67dd 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/ParameterFrameworkConfigurationPolicy.xml.in
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/ParameterFrameworkConfigurationPolicy.xml.in
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <ParameterFrameworkConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-    SystemClassName="Policy" ServerPort="/dev/socket/audioserver/policy_debug"
+    SystemClassName="Policy" ServerPort="unix:///dev/socket/audioserver/policy_debug"
     TuningAllowed="@TUNING_ALLOWED@">
 
     <SubsystemPlugins>
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.mk b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.mk
index d1845b8..0b20781 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.mk
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.mk
@@ -29,6 +29,7 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_VENDOR_MODULE := true
 LOCAL_MODULE_RELATIVE_PATH := parameter-framework/Settings/Policy
+LOCAL_REQUIRED_MODULES := libpolicy-subsystem
 
 PFW_EDD_FILES := \
         $(LOCAL_PATH)/../Settings/device_for_input_source.pfw \
@@ -43,22 +44,9 @@
         $(LOCAL_PATH)/Settings/device_for_product_strategy_transmitted_through_speaker.pfw \
         $(LOCAL_PATH)/Settings/device_for_product_strategy_rerouting.pfw \
         $(LOCAL_PATH)/Settings/device_for_product_strategy_patch.pfw
-
-LOCAL_ADDITIONAL_DEPENDENCIES := \
-    $(PFW_EDD_FILES)
-
-LOCAL_REQUIRED_MODULES := \
-    PolicySubsystem.xml \
-    PolicyClass.xml \
-    audio_policy_engine_criteria.xml \
-    audio_policy_engine_criterion_types.xml \
-    ParameterFrameworkConfigurationPolicy.xml
-
 PFW_CRITERION_TYPES_FILE := $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_criterion_types.xml
 PFW_CRITERIA_FILE := $(TARGET_OUT_VENDOR_ETC)/audio_policy_engine_criteria.xml
-
 PFW_TOPLEVEL_FILE := $(TARGET_OUT_VENDOR_ETC)/parameter-framework/ParameterFrameworkConfigurationPolicy.xml
-
 PFW_SCHEMAS_DIR := $(PFW_DEFAULT_SCHEMAS_DIR)
 
 include $(BUILD_PFW_SETTINGS)
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/common/Structure/PolicySubsystem-CommonTypes.xml b/services/audiopolicy/engineconfigurable/parameter-framework/examples/common/Structure/PolicySubsystem-CommonTypes.xml
index 56c5ed3..d17c021 100644
--- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/common/Structure/PolicySubsystem-CommonTypes.xml
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/common/Structure/PolicySubsystem-CommonTypes.xml
@@ -74,6 +74,8 @@
             <BitParameter Name="proxy" Size="1" Pos="21"/>
             <BitParameter Name="usb_headset" Size="1" Pos="22"/>
             <BitParameter Name="bluetooth_ble" Size="1" Pos="23"/>
+            <BitParameter Name="hdmi_arc" Size="1" Pos="24"/>
+            <BitParameter Name="echo_reference" Size="1" Pos="25"/>
             <BitParameter Name="stub" Size="1" Pos="30"/>
         </BitParameterBlock>
     </ComponentType>
@@ -128,8 +130,10 @@
             <BitParameter Name="voice_communication" Size="1" Pos="7"/>
             <BitParameter Name="remote_submix" Size="1" Pos="8"/>
             <BitParameter Name="unprocessed" Size="1" Pos="9"/>
-            <BitParameter Name="fm_tuner" Size="1" Pos="10"/>
-            <BitParameter Name="hotword" Size="1" Pos="11"/>
+            <BitParameter Name="voice_performance" Size="1" Pos="10"/>
+            <BitParameter Name="echo_reference" Size="1" Pos="11"/>
+            <BitParameter Name="fm_tuner" Size="1" Pos="12"/>
+            <BitParameter Name="hotword" Size="1" Pos="13"/>
         </BitParameterBlock>
     </ComponentType>
 
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp
new file mode 100644
index 0000000..2685c6d
--- /dev/null
+++ b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp
@@ -0,0 +1,36 @@
+cc_library_shared {
+    name: "libpolicy-subsystem",
+    srcs: [
+        "PolicySubsystemBuilder.cpp",
+        "PolicySubsystem.cpp",
+        "InputSource.cpp",
+        "Stream.cpp",
+        "ProductStrategy.cpp",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+        "-fvisibility-inlines-hidden",
+        "-fvisibility=hidden",
+    ],
+    header_libs: [
+        "libbase_headers",
+        "libaudiopolicycommon",
+        "libaudioclient_headers",
+        "libaudiopolicyengine_interface_headers",
+        "libaudiopolicyengineconfigurable_interface_headers",
+    ],
+    static_libs: [
+        "libaudiopolicycomponents",
+        "libaudiopolicyengine_common",
+        "libpfw_utility",
+    ],
+    shared_libs: [
+        "libaudiopolicyengineconfigurable",
+        "liblog",
+        "libutils",
+        "libmedia_helper",
+        "libparameter"
+    ],
+}
diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.mk b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.mk
deleted file mode 100644
index 4706d7d..0000000
--- a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.mk
+++ /dev/null
@@ -1,48 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-ifneq ($(USE_CUSTOM_PARAMETER_FRAMEWORK), true)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-LOCAL_SRC_FILES := \
-    PolicySubsystemBuilder.cpp \
-    PolicySubsystem.cpp \
-    InputSource.cpp \
-    Stream.cpp \
-    ProductStrategy.cpp
-
-LOCAL_CFLAGS += \
-    -Wall \
-    -Werror \
-    -Wextra \
-    -fvisibility-inlines-hidden \
-    -fvisibility=hidden
-
-LOCAL_C_INCLUDES := \
-    frameworks/av/services/audiopolicy/engineconfigurable/include \
-    frameworks/av/services/audiopolicy/engineconfigurable/interface
-
-LOCAL_SHARED_LIBRARIES := \
-    libaudiopolicyengineconfigurable  \
-    libparameter \
-    libmedia_helper \
-    liblog \
-
-LOCAL_HEADER_LIBRARIES := \
-    libaudiopolicycommon \
-    libaudioclient_headers \
-    libbase_headers
-
-LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
-
-LOCAL_STATIC_LIBRARIES := \
-    libpfw_utility \
-    libaudiopolicycomponents
-
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE := libpolicy-subsystem
-
-include $(BUILD_SHARED_LIBRARY)
-
-endif # ifneq ($(USE_CUSTOM_PARAMETER_FRAMEWORK), true)
diff --git a/services/audiopolicy/engineconfigurable/tools/buildPolicyCriterionTypes.py b/services/audiopolicy/engineconfigurable/tools/buildPolicyCriterionTypes.py
index 0fb70a6..a63c858 100755
--- a/services/audiopolicy/engineconfigurable/tools/buildPolicyCriterionTypes.py
+++ b/services/audiopolicy/engineconfigurable/tools/buildPolicyCriterionTypes.py
@@ -101,8 +101,16 @@
         for criterion_name, values_list in addressCriteria.items():
             for criterion_type in criterion_types_root.findall('criterion_type'):
                 if criterion_type.get('name') == criterion_name:
-                    values_node = ET.SubElement(criterion_type, "values")
                     index = 0
+                    existing_values_node = criterion_type.find("values")
+                    if existing_values_node is not None:
+                        for existing_value in existing_values_node.findall('value'):
+                            if existing_value.get('numerical') == str(1 << index):
+                                index += 1
+                        values_node = existing_values_node
+                    else:
+                        values_node = ET.SubElement(criterion_type, "values")
+
                     for value in values_list:
                         value_node = ET.SubElement(values_node, "value", literal=value)
                         value_node.set('numerical', str(1 << index))
@@ -240,4 +248,4 @@
 
 # If this file is directly executed
 if __name__ == "__main__":
-    exit(main())
+    sys.exit(main())
diff --git a/services/audiopolicy/engineconfigurable/tools/buildStrategiesStructureFile.py b/services/audiopolicy/engineconfigurable/tools/buildStrategiesStructureFile.py
index ee70b26..af40602 100755
--- a/services/audiopolicy/engineconfigurable/tools/buildStrategiesStructureFile.py
+++ b/services/audiopolicy/engineconfigurable/tools/buildStrategiesStructureFile.py
@@ -136,4 +136,4 @@
 
 # If this file is directly executed
 if __name__ == "__main__":
-    exit(main())
+    sys.exit(main())
diff --git a/services/audiopolicy/engineconfigurable/tools/build_audio_pfw_settings.mk b/services/audiopolicy/engineconfigurable/tools/build_audio_pfw_settings.mk
index 2b86469..ac60ef7 100644
--- a/services/audiopolicy/engineconfigurable/tools/build_audio_pfw_settings.mk
+++ b/services/audiopolicy/engineconfigurable/tools/build_audio_pfw_settings.mk
@@ -1,10 +1,13 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_TAGS := optional
+LOCAL_ADDITIONAL_DEPENDENCIES += \
+    $(HOST_OUT_EXECUTABLES)/domainGeneratorPolicy.py \
+    $(PFW_TOPLEVEL_FILE) $(PFW_CRITERIA_FILE) $(PFW_CRITERION_TYPES_FILE)
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
 $(LOCAL_BUILT_MODULE): MY_CRITERION_TYPES_FILE := $(PFW_CRITERION_TYPES_FILE)
-$(LOCAL_BUILT_MODULE): MY_TOOL := domainGeneratorPolicy.py
+$(LOCAL_BUILT_MODULE): MY_TOOL := $(HOST_OUT_EXECUTABLES)/domainGeneratorPolicy.py
 $(LOCAL_BUILT_MODULE): MY_TOPLEVEL_FILE := $(PFW_TOPLEVEL_FILE)
 $(LOCAL_BUILT_MODULE): MY_CRITERIA_FILE := $(PFW_CRITERIA_FILE)
 $(LOCAL_BUILT_MODULE): MY_TUNING_FILE := $(PFW_TUNING_FILE)
@@ -12,7 +15,7 @@
 $(LOCAL_BUILT_MODULE): MY_DOMAIN_FILES := $(PFW_DOMAIN_FILES)
 $(LOCAL_BUILT_MODULE): MY_SCHEMAS_DIR := $(PFW_SCHEMAS_DIR)
 $(LOCAL_BUILT_MODULE): MY_CRITERION_TYPES_FILE := $(PFW_CRITERION_TYPES_FILE)
-$(LOCAL_BUILT_MODULE): $(LOCAL_REQUIRED_MODULES) $(LOCAL_ADDITIONAL_DEPENDENCIES) domainGeneratorPolicy.py
+$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
 
 	"$(MY_TOOL)" --validate \
 		--toplevel-config "$(MY_TOPLEVEL_FILE)" \
diff --git a/services/audiopolicy/engineconfigurable/tools/domainGeneratorPolicy.py b/services/audiopolicy/engineconfigurable/tools/domainGeneratorPolicy.py
index 7929402..4dec9a2 100755
--- a/services/audiopolicy/engineconfigurable/tools/domainGeneratorPolicy.py
+++ b/services/audiopolicy/engineconfigurable/tools/domainGeneratorPolicy.py
@@ -129,7 +129,7 @@
                 criterion_values = []
 
                 values_node = criterion_types.find('values')
-                if values_node:
+                if values_node is not None:
                     for value in values_node.findall('value'):
                         criterion_values.append(value.get('literal'))
 
@@ -265,4 +265,4 @@
 
 # If this file is directly executed
 if __name__ == "__main__":
-    exit(main())
+    sys.exit(main())
diff --git a/services/audiopolicy/engineconfigurable/tools/provision_criterion_types_from_android_headers.mk b/services/audiopolicy/engineconfigurable/tools/provision_criterion_types_from_android_headers.mk
index eebdfd6..dab5a0f 100644
--- a/services/audiopolicy/engineconfigurable/tools/provision_criterion_types_from_android_headers.mk
+++ b/services/audiopolicy/engineconfigurable/tools/provision_criterion_types_from_android_headers.mk
@@ -1,15 +1,17 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_TAGS := optional
+LOCAL_ADDITIONAL_DEPENDENCIES += \
+    $(HOST_OUT_EXECUTABLES)/buildPolicyCriterionTypes.py \
+    $(CRITERION_TYPES_FILE) $(AUDIO_POLICY_CONFIGURATION_FILE) \
+    $(ANDROID_AUDIO_BASE_HEADER_FILE)
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
 $(LOCAL_BUILT_MODULE): MY_CRITERION_TYPES_FILE := $(CRITERION_TYPES_FILE)
 $(LOCAL_BUILT_MODULE): MY_ANDROID_AUDIO_BASE_HEADER_FILE := $(ANDROID_AUDIO_BASE_HEADER_FILE)
 $(LOCAL_BUILT_MODULE): MY_AUDIO_POLICY_CONFIGURATION_FILE := $(AUDIO_POLICY_CONFIGURATION_FILE)
-$(LOCAL_BUILT_MODULE): MY_CRITERION_TOOL := $(HOST_OUT)/bin/buildPolicyCriterionTypes.py
-$(LOCAL_BUILT_MODULE): $(LOCAL_REQUIRED_MODULES) $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    $(CRITERION_TYPES_FILE) \
-    $(ANDROID_AUDIO_BASE_HEADER_FILE)
+$(LOCAL_BUILT_MODULE): MY_CRITERION_TOOL := $(HOST_OUT_EXECUTABLES)/buildPolicyCriterionTypes.py
+$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
 
 	"$(MY_CRITERION_TOOL)" \
 		--androidaudiobaseheader "$(MY_ANDROID_AUDIO_BASE_HEADER_FILE)" \
diff --git a/services/audiopolicy/engineconfigurable/tools/provision_strategies_structure.mk b/services/audiopolicy/engineconfigurable/tools/provision_strategies_structure.mk
index 72c938c..f2b1a19 100644
--- a/services/audiopolicy/engineconfigurable/tools/provision_strategies_structure.mk
+++ b/services/audiopolicy/engineconfigurable/tools/provision_strategies_structure.mk
@@ -1,15 +1,15 @@
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_TAGS := optional
+LOCAL_ADDITIONAL_DEPENDENCIES += \
+    $(HOST_OUT_EXECUTABLES)/buildStrategiesStructureFile.py \
+    $(STRATEGIES_STRUCTURE_FILE) $(AUDIO_POLICY_ENGINE_CONFIGURATION_FILE)
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
 $(LOCAL_BUILT_MODULE): MY_STRATEGIES_STRUCTURE_FILE := $(STRATEGIES_STRUCTURE_FILE)
 $(LOCAL_BUILT_MODULE): MY_AUDIO_POLICY_ENGINE_CONFIGURATION_FILE := $(AUDIO_POLICY_ENGINE_CONFIGURATION_FILE)
-$(LOCAL_BUILT_MODULE): MY_PROVISION_TOOL := $(HOST_OUT)/bin/buildStrategiesStructureFile.py
-$(LOCAL_BUILT_MODULE): $(LOCAL_REQUIRED_MODULES) $(LOCAL_ADDITIONAL_DEPENDENCIES) \
-    buildStrategiesStructureFile.py \
-    $(STRATEGIES_STRUCTURE_FILE) \
-    $(AUDIO_POLICY_ENGINE_CONFIGURATION_FILE)
+$(LOCAL_BUILT_MODULE): MY_PROVISION_TOOL := $(HOST_OUT_EXECUTABLES)/buildStrategiesStructureFile.py
+$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)
 
 	"$(MY_PROVISION_TOOL)" \
 		--audiopolicyengineconfigurationfile "$(MY_AUDIO_POLICY_ENGINE_CONFIGURATION_FILE)" \
diff --git a/services/audiopolicy/engineconfigurable/wrapper/Android.bp b/services/audiopolicy/engineconfigurable/wrapper/Android.bp
new file mode 100644
index 0000000..6f59487
--- /dev/null
+++ b/services/audiopolicy/engineconfigurable/wrapper/Android.bp
@@ -0,0 +1,21 @@
+cc_library {
+    name: "libaudiopolicyengineconfigurable_pfwwrapper",
+    export_include_dirs: ["include"],
+    srcs: ["ParameterManagerWrapper.cpp"],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+    header_libs: [
+        "libbase_headers",
+        "libaudiopolicycommon",
+    ],
+    static_libs: ["libaudiopolicycomponents"],
+    shared_libs: [
+        "liblog",
+        "libutils",
+        "libmedia_helper",
+        "libparameter",
+    ],
+}
diff --git a/services/audiopolicy/engineconfigurable/wrapper/Android.mk b/services/audiopolicy/engineconfigurable/wrapper/Android.mk
deleted file mode 100644
index c7d8d34..0000000
--- a/services/audiopolicy/engineconfigurable/wrapper/Android.mk
+++ /dev/null
@@ -1,39 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-
-##################################################################
-# WRAPPER LIBRARY
-##################################################################
-
-include $(CLEAR_VARS)
-
-LOCAL_C_INCLUDES := \
-    $(LOCAL_PATH)/include \
-    frameworks/av/services/audiopolicy/engineconfigurable/include \
-    frameworks/av/services/audiopolicy/engineconfigurable/interface \
-    external/libxml2/include \
-    external/icu/icu4c/source/common
-
-LOCAL_SRC_FILES:= \
-    ParameterManagerWrapper.cpp
-
-LOCAL_SHARED_LIBRARIES := \
-    libparameter \
-    libmedia_helper \
-    libxml2
-
-LOCAL_HEADER_LIBRARIES := \
-    libaudiopolicycommon
-
-LOCAL_STATIC_LIBRARIES := \
-    libaudiopolicycomponents
-
-LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
-
-LOCAL_MODULE:= libaudiopolicypfwwrapper
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-
-LOCAL_MODULE_TAGS := optional
-LOCAL_CFLAGS := -Wall -Werror -Wextra
-
-include $(BUILD_STATIC_LIBRARY)
-
diff --git a/services/audiopolicy/enginedefault/config/Android.mk b/services/audiopolicy/enginedefault/config/Android.mk
deleted file mode 100644
index dcce8e3..0000000
--- a/services/audiopolicy/enginedefault/config/Android.mk
+++ /dev/null
@@ -1,9 +0,0 @@
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-#######################################################################
-# Recursive call sub-folder Android.mk
-#
-include $(call all-makefiles-under,$(LOCAL_PATH))
-
diff --git a/services/audiopolicy/manager/Android.mk b/services/audiopolicy/manager/Android.mk
new file mode 100644
index 0000000..d6ca2f2
--- /dev/null
+++ b/services/audiopolicy/manager/Android.mk
@@ -0,0 +1,32 @@
+LOCAL_PATH:= $(call my-dir)
+
+ifneq ($(USE_CUSTOM_AUDIO_POLICY), 1)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+    AudioPolicyFactory.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+    libaudiopolicymanagerdefault
+
+LOCAL_STATIC_LIBRARIES := \
+    libaudiopolicycomponents
+
+LOCAL_C_INCLUDES += \
+    $(call include-path-for, audio-utils)
+
+LOCAL_HEADER_LIBRARIES := \
+    libaudiopolicycommon \
+    libaudiopolicyengine_interface_headers \
+    libaudiopolicymanager_interface_headers
+
+LOCAL_CFLAGS := -Wall -Werror
+
+LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
+
+LOCAL_MODULE:= libaudiopolicymanager
+
+include $(BUILD_SHARED_LIBRARY)
+
+endif #ifneq ($(USE_CUSTOM_AUDIO_POLICY), 1)
diff --git a/services/audiopolicy/manager/AudioPolicyFactory.cpp b/services/audiopolicy/manager/AudioPolicyFactory.cpp
index 3efa1b0..7aff6a9 100644
--- a/services/audiopolicy/manager/AudioPolicyFactory.cpp
+++ b/services/audiopolicy/manager/AudioPolicyFactory.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "managerdefault/AudioPolicyManager.h"
+#include <AudioPolicyManager.h>
 
 namespace android {
 
diff --git a/services/audiopolicy/managerdefault/Android.mk b/services/audiopolicy/managerdefault/Android.mk
new file mode 100644
index 0000000..684fc9f
--- /dev/null
+++ b/services/audiopolicy/managerdefault/Android.mk
@@ -0,0 +1,56 @@
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= AudioPolicyManager.cpp
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)
+
+LOCAL_SHARED_LIBRARIES := \
+    libcutils \
+    libutils \
+    liblog \
+    libaudiopolicy \
+    libsoundtrigger
+
+ifeq ($(USE_CONFIGURABLE_AUDIO_POLICY), 1)
+
+ifneq ($(USE_XML_AUDIO_POLICY_CONF), 1)
+$(error Configurable policy does not support legacy conf file)
+endif #ifneq ($(USE_XML_AUDIO_POLICY_CONF), 1)
+
+LOCAL_SHARED_LIBRARIES += libaudiopolicyengineconfigurable
+
+else
+
+LOCAL_SHARED_LIBRARIES += libaudiopolicyenginedefault
+
+endif # ifeq ($(USE_CONFIGURABLE_AUDIO_POLICY), 1)
+
+LOCAL_C_INCLUDES += \
+    $(call include-path-for, audio-utils)
+
+LOCAL_HEADER_LIBRARIES := \
+    libaudiopolicycommon \
+    libaudiopolicyengine_interface_headers \
+    libaudiopolicymanager_interface_headers
+
+LOCAL_STATIC_LIBRARIES := \
+    libaudiopolicycomponents
+
+LOCAL_SHARED_LIBRARIES += libmedia_helper
+LOCAL_SHARED_LIBRARIES += libmediametrics
+
+LOCAL_SHARED_LIBRARIES += libbinder libhidlbase libxml2
+
+ifeq ($(USE_XML_AUDIO_POLICY_CONF), 1)
+LOCAL_CFLAGS += -DUSE_XML_AUDIO_POLICY_CONF
+endif #ifeq ($(USE_XML_AUDIO_POLICY_CONF), 1)
+
+LOCAL_CFLAGS += -Wall -Werror
+
+LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
+
+LOCAL_MODULE:= libaudiopolicymanagerdefault
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index 066363f..c0ca440 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -273,8 +273,6 @@
 
     // handle input devices
     if (audio_is_input_device(deviceType)) {
-        SortedVector <audio_io_handle_t> inputs;
-
         ssize_t index = mAvailableInputDevices.indexOf(device);
         switch (state)
         {
@@ -284,11 +282,18 @@
                 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
                 return INVALID_OPERATION;
             }
+
+            if (mAvailableInputDevices.add(device) < 0) {
+                return NO_MEMORY;
+            }
+
             // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
             // parameters on newly connected devices (instead of opening the inputs...)
             broadcastDeviceConnectionState(device, state);
 
-            if (checkInputsForDevice(device, state, inputs) != NO_ERROR) {
+            if (checkInputsForDevice(device, state) != NO_ERROR) {
+                mAvailableInputDevices.remove(device);
+
                 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
 
                 mHwModules.cleanUpForDevice(device);
@@ -296,9 +301,6 @@
                 return INVALID_OPERATION;
             }
 
-            if (mAvailableInputDevices.add(device) < 0) {
-                return NO_MEMORY;
-            }
         } break;
 
         // handle input device disconnection
@@ -313,8 +315,9 @@
             // Set Disconnect to HALs
             broadcastDeviceConnectionState(device, state);
 
-            checkInputsForDevice(device, state, inputs);
             mAvailableInputDevices.remove(device);
+
+            checkInputsForDevice(device, state);
         } break;
 
         default:
@@ -325,7 +328,7 @@
         // Propagate device availability to Engine
         setEngineDeviceConnectionState(device, state);
 
-        closeAllInputs();
+        checkCloseInputs();
         // As the input device list can impact the output device selection, update
         // getDeviceForStrategy() cache
         updateDevicesAndOutputs();
@@ -2343,9 +2346,39 @@
     releaseInput(portId);
 }
 
-void AudioPolicyManager::closeAllInputs() {
-    while (mInputs.size() != 0) {
-        closeInput(mInputs.keyAt(0));
+void AudioPolicyManager::checkCloseInputs() {
+    // After connecting or disconnecting an input device, close input if:
+    // - it has no client (was just opened to check profile)  OR
+    // - none of its supported devices are connected anymore OR
+    // - one of its clients cannot be routed to one of its supported
+    // devices anymore. Otherwise update device selection
+    std::vector<audio_io_handle_t> inputsToClose;
+    for (size_t i = 0; i < mInputs.size(); i++) {
+        const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
+        if (input->clientsList().size() == 0
+                || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
+            inputsToClose.push_back(mInputs.keyAt(i));
+        } else {
+            bool close = false;
+            for (const auto& client : input->clientsList()) {
+                sp<DeviceDescriptor> device =
+                    mEngine->getInputDeviceForAttributes(client->attributes());
+                if (!input->supportedDevices().contains(device)) {
+                    close = true;
+                    break;
+                }
+            }
+            if (close) {
+                inputsToClose.push_back(mInputs.keyAt(i));
+            } else {
+                setInputDevice(input->mIoHandle, getNewInputDevice(input));
+            }
+        }
+    }
+
+    for (const audio_io_handle_t handle : inputsToClose) {
+        ALOGV("%s closing input %d", __func__, handle);
+        closeInput(handle);
     }
 }
 
@@ -4685,8 +4718,7 @@
 }
 
 status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
-                                                  audio_policy_dev_state_t state,
-                                                  SortedVector<audio_io_handle_t>& inputs)
+                                                  audio_policy_dev_state_t state)
 {
     sp<AudioInputDescriptor> desc;
 
@@ -4696,16 +4728,7 @@
     }
 
     if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
-        // first list already open inputs that can be routed to this device
-        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
-            desc = mInputs.valueAt(input_index);
-            if (desc->mProfile->supportsDeviceTypes(device->type())) {
-                ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
-               inputs.add(mInputs.keyAt(input_index));
-            }
-        }
-
-        // then look for input profiles that can be routed to this device
+        // look for input profiles that can be routed to this device
         SortedVector< sp<IOProfile> > profiles;
         for (const auto& hwModule : mHwModules) {
             for (size_t profile_index = 0;
@@ -4721,8 +4744,9 @@
             }
         }
 
-        if (profiles.isEmpty() && inputs.isEmpty()) {
-            ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
+        if (profiles.isEmpty()) {
+            ALOGW("%s: No input profile available for device %s",
+                __func__, device->toString().c_str());
             return BAD_VALUE;
         }
 
@@ -4775,7 +4799,7 @@
                     input = AUDIO_IO_HANDLE_NONE;
                 }
 
-                if (input != 0) {
+                if (input != AUDIO_IO_HANDLE_NONE) {
                     addInput(input, desc);
                 }
             } // endif input != 0
@@ -4786,7 +4810,6 @@
                 profiles.removeAt(profile_index);
                 profile_index--;
             } else {
-                inputs.add(input);
                 if (audio_device_is_digital(device->type())) {
                     device->importAudioPort(profile);
                 }
@@ -4800,15 +4823,6 @@
         }
     } else {
         // Disconnect
-        // check if one opened input is not needed any more after disconnecting one device
-        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
-            desc = mInputs.valueAt(input_index);
-            if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
-                ALOGV("checkInputsForDevice(): disconnecting adding input %d",
-                      mInputs.keyAt(input_index));
-                inputs.add(mInputs.keyAt(input_index));
-            }
-        }
         // Clear any profiles associated with the disconnected device.
         for (const auto& hwModule : mHwModules) {
             for (size_t profile_index = 0;
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h
index 835fbdc..612bd8f 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.h
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h
@@ -143,7 +143,7 @@
         // indicates to the audio policy manager that the input stops being used.
         virtual status_t stopInput(audio_port_handle_t portId);
         virtual void releaseInput(audio_port_handle_t portId);
-        virtual void closeAllInputs();
+        virtual void checkCloseInputs();
         /**
          * @brief initStreamVolume: even if the engine volume files provides min and max, keep this
          * api for compatibility reason.
@@ -487,8 +487,7 @@
                                        SortedVector<audio_io_handle_t>& outputs);
 
         status_t checkInputsForDevice(const sp<DeviceDescriptor>& device,
-                                      audio_policy_dev_state_t state,
-                                      SortedVector<audio_io_handle_t>& inputs);
+                                      audio_policy_dev_state_t state);
 
         // close an output and its companion duplicating output.
         void closeOutput(audio_io_handle_t output);
diff --git a/services/audiopolicy/service/Android.mk b/services/audiopolicy/service/Android.mk
new file mode 100644
index 0000000..c4f4c56
--- /dev/null
+++ b/services/audiopolicy/service/Android.mk
@@ -0,0 +1,49 @@
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+    AudioPolicyService.cpp \
+    AudioPolicyEffects.cpp \
+    AudioPolicyInterfaceImpl.cpp \
+    AudioPolicyClientImpl.cpp
+
+LOCAL_C_INCLUDES := \
+    frameworks/av/services/audioflinger \
+    $(call include-path-for, audio-utils)
+
+LOCAL_HEADER_LIBRARIES := \
+    libaudiopolicycommon \
+    libaudiopolicyengine_interface_headers \
+    libaudiopolicymanager_interface_headers
+
+LOCAL_SHARED_LIBRARIES := \
+    libcutils \
+    libutils \
+    liblog \
+    libbinder \
+    libaudioclient \
+    libaudioutils \
+    libhardware_legacy \
+    libaudiopolicymanager \
+    libmedia_helper \
+    libmediametrics \
+    libmediautils \
+    libeffectsconfig \
+    libsensorprivacy
+
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := \
+    libsensorprivacy
+
+LOCAL_STATIC_LIBRARIES := \
+    libaudiopolicycomponents
+
+LOCAL_MULTILIB := $(AUDIOSERVER_MULTILIB)
+
+LOCAL_MODULE:= libaudiopolicyservice
+
+LOCAL_CFLAGS += -fvisibility=hidden
+LOCAL_CFLAGS += -Wall -Werror
+
+include $(BUILD_SHARED_LIBRARY)
+
diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h
index be6d1ac..58256f7 100644
--- a/services/audiopolicy/service/AudioPolicyService.h
+++ b/services/audiopolicy/service/AudioPolicyService.h
@@ -33,7 +33,7 @@
 #include <media/AudioPolicy.h>
 #include <mediautils/ServiceUtilities.h>
 #include "AudioPolicyEffects.h"
-#include "managerdefault/AudioPolicyManager.h"
+#include <AudioPolicyInterface.h>
 #include <android/hardware/BnSensorPrivacyListener.h>
 
 #include <unordered_map>
diff --git a/services/audiopolicy/tests/Android.mk b/services/audiopolicy/tests/Android.mk
index 97be44c..ab9f78b 100644
--- a/services/audiopolicy/tests/Android.mk
+++ b/services/audiopolicy/tests/Android.mk
@@ -18,7 +18,8 @@
 
 LOCAL_HEADER_LIBRARIES := \
     libaudiopolicycommon \
-    libaudiopolicyengine_interface_headers
+    libaudiopolicyengine_interface_headers \
+    libaudiopolicymanager_interface_headers
 
 LOCAL_SRC_FILES := \
   audiopolicymanager_tests.cpp \
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index a1cb8ee..fc6d6be 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -1638,6 +1638,11 @@
         }
     }
 
+    int clientPid = CameraThreadState::getCallingPid();
+    const char *id_cstr = id.c_str();
+    const char *torchState = enabled ? "on" : "off";
+    ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
+    logTorchEvent(id_cstr, torchState , clientPid);
     return Status::ok();
 }
 
@@ -2122,6 +2127,12 @@
             cameraId, clientPackage, clientPid, reason));
 }
 
+void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
+    // Log torch event
+    logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
+            torchState, clientPid));
+}
+
 void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
         const std::set<userid_t>& newUserIds) {
     String8 newUsers = toString(newUserIds);
diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h
index a8c2606..b8cec2c 100644
--- a/services/camera/libcameraservice/CameraService.h
+++ b/services/camera/libcameraservice/CameraService.h
@@ -748,6 +748,11 @@
             const char* reason);
 
     /**
+     * Add an event log message when a client calls setTorchMode succesfully.
+     */
+    void logTorchEvent(const char* cameraId, const char *torchState, int clientPid);
+
+    /**
      * Add an event log message that the current device user has been switched.
      */
     void logUserSwitch(const std::set<userid_t>& oldUserIds,
diff --git a/services/camera/libcameraservice/utils/LatencyHistogram.cpp b/services/camera/libcameraservice/utils/LatencyHistogram.cpp
index 538bb6e..e2bdc43 100644
--- a/services/camera/libcameraservice/utils/LatencyHistogram.cpp
+++ b/services/camera/libcameraservice/utils/LatencyHistogram.cpp
@@ -46,7 +46,7 @@
 }
 
 void CameraLatencyHistogram::reset() {
-    mBins.clear();
+    memset(mBins.data(), 0, mBins.size() * sizeof(int64_t));
     mTotalCount = 0;
 }
 
diff --git a/services/oboeservice/AAudioServiceEndpointMMAP.cpp b/services/oboeservice/AAudioServiceEndpointMMAP.cpp
index 447f32c..b05baa4 100644
--- a/services/oboeservice/AAudioServiceEndpointMMAP.cpp
+++ b/services/oboeservice/AAudioServiceEndpointMMAP.cpp
@@ -77,9 +77,6 @@
     audio_config_base_t config;
     audio_port_handle_t deviceId;
 
-    int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
-    int32_t burstMicros = 0;
-
     copyFrom(request.getConstantConfiguration());
 
     aaudio_direction_t direction = getDirection();
@@ -235,24 +232,12 @@
     setFormat(config.format);
     setSampleRate(config.sample_rate);
 
-    // Scale up the burst size to meet the minimum equivalent in microseconds.
-    // This is to avoid waking the CPU too often when the HW burst is very small
-    // or at high sample rates.
-    do {
-        if (burstMicros > 0) {  // skip first loop
-            mFramesPerBurst *= 2;
-        }
-        burstMicros = mFramesPerBurst * static_cast<int64_t>(1000000) / getSampleRate();
-    } while (burstMicros < burstMinMicros);
+    ALOGD("%s() actual rate = %d, channels = %d"
+          ", deviceId = %d, capacity = %d\n",
+          __func__, getSampleRate(), getSamplesPerFrame(), deviceId, getBufferCapacity());
 
-    ALOGD("%s() original burst = %d, minMicros = %d => burst = %d\n",
-          __func__, mMmapBufferinfo.burst_size_frames, burstMinMicros, mFramesPerBurst);
-
-    ALOGD("%s() actual rate = %d, channels = %d, deviceId = %d\n",
-          __func__, getSampleRate(), getSamplesPerFrame(), deviceId);
-
-    ALOGD("%s() format = 0x%08x, frame size = %d",
-          __func__, getFormat(), calculateBytesPerFrame());
+    ALOGD("%s() format = 0x%08x, frame size = %d, burst size = %d",
+          __func__, getFormat(), calculateBytesPerFrame(), mFramesPerBurst);
 
     return result;