Merge "Benchmark: Fix for audio encoders on Android 9"
diff --git a/apex/testing/Android.bp b/apex/testing/Android.bp
index 477c371..376d3e4 100644
--- a/apex/testing/Android.bp
+++ b/apex/testing/Android.bp
@@ -12,7 +12,7 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-apex {
+apex_test {
     name: "test_com.android.media",
     manifest: "test_manifest.json",
     file_contexts: ":com.android.media-file_contexts",
@@ -20,7 +20,7 @@
     installable: false,
 }
 
-apex {
+apex_test {
     name: "test_com.android.media.swcodec",
     manifest: "test_manifest_codec.json",
     file_contexts: ":com.android.media.swcodec-file_contexts",
diff --git a/camera/include/camera/VendorTagDescriptor.h b/camera/include/camera/VendorTagDescriptor.h
index 6f55890..b2fbf3a 100644
--- a/camera/include/camera/VendorTagDescriptor.h
+++ b/camera/include/camera/VendorTagDescriptor.h
@@ -188,8 +188,8 @@
             sp<android::VendorTagDescriptor> *desc /*out*/);
 
     // Parcelable interface
-    status_t writeToParcel(Parcel* parcel) const override;
-    status_t readFromParcel(const Parcel* parcel) override;
+    status_t writeToParcel(android::Parcel* parcel) const override;
+    status_t readFromParcel(const android::Parcel* parcel) override;
 
     // Returns the number of vendor tags defined.
     int getTagCount(metadata_vendor_id_t id) const;
diff --git a/media/codec2/hidl/1.0/utils/Android.bp b/media/codec2/hidl/1.0/utils/Android.bp
index bdff29a..a2930a6 100644
--- a/media/codec2/hidl/1.0/utils/Android.bp
+++ b/media/codec2/hidl/1.0/utils/Android.bp
@@ -63,6 +63,7 @@
     ],
 
     header_libs: [
+        "libbinder_headers",
         "libsystem_headers",
         "libcodec2_internal", // private
     ],
diff --git a/media/codec2/hidl/client/client.cpp b/media/codec2/hidl/client/client.cpp
index c620bad..c747190 100644
--- a/media/codec2/hidl/client/client.cpp
+++ b/media/codec2/hidl/client/client.cpp
@@ -125,6 +125,9 @@
         if (!mClient) {
             mClient = Codec2Client::_CreateFromIndex(mIndex);
         }
+        CHECK(mClient) << "Failed to create Codec2Client to service \""
+                       << GetServiceNames()[mIndex] << "\". (Index = "
+                       << mIndex << ").";
         return mClient;
     }
 
@@ -832,6 +835,7 @@
 
 c2_status_t Codec2Client::ForAllServices(
         const std::string &key,
+        size_t numberOfAttempts,
         std::function<c2_status_t(const std::shared_ptr<Codec2Client>&)>
             predicate) {
     c2_status_t status = C2_NO_INIT;  // no IComponentStores present
@@ -860,23 +864,31 @@
 
     for (size_t index : indices) {
         Cache& cache = Cache::List()[index];
-        std::shared_ptr<Codec2Client> client{cache.getClient()};
-        if (client) {
+        for (size_t tries = numberOfAttempts; tries > 0; --tries) {
+            std::shared_ptr<Codec2Client> client{cache.getClient()};
             status = predicate(client);
             if (status == C2_OK) {
                 std::scoped_lock lock{key2IndexMutex};
                 key2Index[key] = index; // update last known client index
                 return C2_OK;
+            } else if (status == C2_TRANSACTION_FAILED) {
+                LOG(WARNING) << "\"" << key << "\" failed for service \""
+                             << client->getName()
+                             << "\" due to transaction failure. "
+                             << "(Service may have crashed.)"
+                             << (tries > 1 ? " Retrying..." : "");
+                cache.invalidate();
+                continue;
             }
-        }
-        if (wasMapped) {
-            LOG(INFO) << "Could not find \"" << key << "\""
-                         " in the last instance. Retrying...";
-            wasMapped = false;
-            cache.invalidate();
+            if (wasMapped) {
+                LOG(INFO) << "\"" << key << "\" became invalid in service \""
+                          << client->getName() << "\". Retrying...";
+                wasMapped = false;
+            }
+            break;
         }
     }
-    return status;  // return the last status from a valid client
+    return status; // return the last status from a valid client
 }
 
 std::shared_ptr<Codec2Client::Component>
@@ -885,35 +897,37 @@
         const std::shared_ptr<Listener>& listener,
         std::shared_ptr<Codec2Client>* owner,
         size_t numberOfAttempts) {
-    while (true) {
-        std::shared_ptr<Component> component;
-        c2_status_t status = ForAllServices(
-                componentName,
-                [owner, &component, componentName, &listener](
-                        const std::shared_ptr<Codec2Client> &client)
-                            -> c2_status_t {
-                    c2_status_t status = client->createComponent(componentName,
-                                                                 listener,
-                                                                 &component);
-                    if (status == C2_OK) {
-                        if (owner) {
-                            *owner = client;
-                        }
-                    } else if (status != C2_NOT_FOUND) {
-                        LOG(DEBUG) << "IComponentStore("
-                                       << client->getServiceName()
-                                   << ")::createComponent(\"" << componentName
-                                   << "\") returned status = "
-                                   << status << ".";
+    std::string key{"create:"};
+    key.append(componentName);
+    std::shared_ptr<Component> component;
+    c2_status_t status = ForAllServices(
+            key,
+            numberOfAttempts,
+            [owner, &component, componentName, &listener](
+                    const std::shared_ptr<Codec2Client> &client)
+                        -> c2_status_t {
+                c2_status_t status = client->createComponent(componentName,
+                                                             listener,
+                                                             &component);
+                if (status == C2_OK) {
+                    if (owner) {
+                        *owner = client;
                     }
-                    return status;
-                });
-        if (numberOfAttempts > 0 && status == C2_TRANSACTION_FAILED) {
-            --numberOfAttempts;
-            continue;
-        }
-        return component;
+                } else if (status != C2_NOT_FOUND) {
+                    LOG(DEBUG) << "IComponentStore("
+                                   << client->getServiceName()
+                               << ")::createComponent(\"" << componentName
+                               << "\") returned status = "
+                               << status << ".";
+                }
+                return status;
+            });
+    if (status != C2_OK) {
+        LOG(DEBUG) << "Failed to create component \"" << componentName
+                   << "\" from all known services. "
+                      "Last returned status = " << status << ".";
     }
+    return component;
 }
 
 std::shared_ptr<Codec2Client::Interface>
@@ -921,34 +935,36 @@
         const char* interfaceName,
         std::shared_ptr<Codec2Client>* owner,
         size_t numberOfAttempts) {
-    while (true) {
-        std::shared_ptr<Interface> interface;
-        c2_status_t status = ForAllServices(
-                interfaceName,
-                [owner, &interface, interfaceName](
-                        const std::shared_ptr<Codec2Client> &client)
-                            -> c2_status_t {
-                    c2_status_t status = client->createInterface(interfaceName,
-                                                                 &interface);
-                    if (status == C2_OK) {
-                        if (owner) {
-                            *owner = client;
-                        }
-                    } else if (status != C2_NOT_FOUND) {
-                        LOG(DEBUG) << "IComponentStore("
-                                       << client->getServiceName()
-                                   << ")::createInterface(\"" << interfaceName
-                                   << "\") returned status = "
-                                   << status << ".";
+    std::string key{"create:"};
+    key.append(interfaceName);
+    std::shared_ptr<Interface> interface;
+    c2_status_t status = ForAllServices(
+            key,
+            numberOfAttempts,
+            [owner, &interface, interfaceName](
+                    const std::shared_ptr<Codec2Client> &client)
+                        -> c2_status_t {
+                c2_status_t status = client->createInterface(interfaceName,
+                                                             &interface);
+                if (status == C2_OK) {
+                    if (owner) {
+                        *owner = client;
                     }
-                    return status;
-                });
-        if (numberOfAttempts > 0 && status == C2_TRANSACTION_FAILED) {
-            --numberOfAttempts;
-            continue;
-        }
-        return interface;
+                } else if (status != C2_NOT_FOUND) {
+                    LOG(DEBUG) << "IComponentStore("
+                                   << client->getServiceName()
+                               << ")::createInterface(\"" << interfaceName
+                               << "\") returned status = "
+                               << status << ".";
+                }
+                return status;
+            });
+    if (status != C2_OK) {
+        LOG(DEBUG) << "Failed to create interface \"" << interfaceName
+                   << "\" from all known services. "
+                      "Last returned status = " << status << ".";
     }
+    return interface;
 }
 
 std::vector<C2Component::Traits> const& Codec2Client::ListComponents() {
diff --git a/media/codec2/hidl/client/include/codec2/hidl/client.h b/media/codec2/hidl/client/include/codec2/hidl/client.h
index 848901d..c37407f 100644
--- a/media/codec2/hidl/client/include/codec2/hidl/client.h
+++ b/media/codec2/hidl/client/include/codec2/hidl/client.h
@@ -208,11 +208,25 @@
 protected:
     sp<Base> mBase;
 
-    // Finds the first store where the predicate returns OK, and returns the last
-    // predicate result. Uses key to remember the last store found, and if cached,
-    // it tries that store before trying all stores (one retry).
+    // Finds the first store where the predicate returns C2_OK and returns the
+    // last predicate result. The predicate will be tried on all stores. The
+    // function will return C2_OK the first time the predicate returns C2_OK,
+    // or it will return the value from the last time that predicate is tried.
+    // (The latter case corresponds to a failure on every store.) The order of
+    // the stores to try is the same as the return value of GetServiceNames().
+    //
+    // key is used to remember the last store with which the predicate last
+    // succeeded. If the last successful store is cached, it will be tried
+    // first before all the stores are tried. Note that the last successful
+    // store will be tried twice---first before all the stores, and another time
+    // with all the stores.
+    //
+    // If an attempt to evaluate the predicate results in a transaction failure,
+    // repeated attempts will be made until the predicate returns without a
+    // transaction failure or numberOfAttempts attempts have been made.
     static c2_status_t ForAllServices(
             const std::string& key,
+            size_t numberOfAttempts,
             std::function<c2_status_t(std::shared_ptr<Codec2Client> const&)>
                 predicate);
 
diff --git a/media/codec2/vndk/Android.bp b/media/codec2/vndk/Android.bp
index 6fbad0a..52cc7ad 100644
--- a/media/codec2/vndk/Android.bp
+++ b/media/codec2/vndk/Android.bp
@@ -71,8 +71,6 @@
         "libutils",
     ],
 
-    tidy: false, // b/146435095, clang-tidy segmentation fault
-
     cflags: [
         "-Werror",
         "-Wall",
diff --git a/media/extractors/tests/AndroidTest.xml b/media/extractors/tests/AndroidTest.xml
new file mode 100644
index 0000000..6bb2c8a
--- /dev/null
+++ b/media/extractors/tests/AndroidTest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Test module config for extractor unit tests">
+    <option name="test-suite-tag" value="ExtractorUnitTest" />
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push" value="ExtractorUnitTest->/data/local/tmp/ExtractorUnitTest" />
+        <option name="push-file"
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/extractors/tests/extractor.zip?unzip=true"
+            value="/data/local/tmp/ExtractorUnitTestRes/" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="ExtractorUnitTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/ExtractorUnitTestRes/" />
+    </test>
+</configuration>
diff --git a/media/extractors/tests/README.md b/media/extractors/tests/README.md
index 6e02d3e..69538b6 100644
--- a/media/extractors/tests/README.md
+++ b/media/extractors/tests/README.md
@@ -22,8 +22,8 @@
 adb push ${OUT}/data/nativetest/ExtractorUnitTest/ExtractorUnitTest /data/local/tmp/
 ```
 
-The resource file for the tests is taken from [here](https://drive.google.com/drive/folders/1Z9nCIRB6pGLvb5mPkF8BURa5Nc6cY9pY). Push these files into device for testing.
-Download extractor folder and push all the files in this folder to /data/local/tmp/ on the device.
+The resource file for the tests is taken from [here](https://storage.googleapis.com/android_media/frameworks/av/media/extractors/tests/extractor.zip). Download, unzip and push these files into device for testing.
+
 ```
 adb push extractor /data/local/tmp/
 ```
@@ -32,3 +32,8 @@
 ```
 adb shell /data/local/tmp/ExtractorUnitTest -P /data/local/tmp/extractor/
 ```
+Alternatively, the test can also be run using atest command.
+
+```
+atest ExtractorUnitTest -- --enable-module-dynamic-download=true
+```
diff --git a/media/libaudiohal/Android.bp b/media/libaudiohal/Android.bp
index 74b48f3..1709d1e 100644
--- a/media/libaudiohal/Android.bp
+++ b/media/libaudiohal/Android.bp
@@ -4,6 +4,7 @@
     srcs: [
         "DevicesFactoryHalInterface.cpp",
         "EffectsFactoryHalInterface.cpp",
+        "FactoryHalHidl.cpp",
     ],
 
     cflags: [
@@ -12,11 +13,17 @@
         "-Werror",
     ],
 
-    shared_libs: [
+    required: [
         "libaudiohal@2.0",
         "libaudiohal@4.0",
         "libaudiohal@5.0",
         "libaudiohal@6.0",
+    ],
+
+    shared_libs: [
+        "libdl",
+        "libhidlbase",
+        "liblog",
         "libutils",
     ],
 
diff --git a/media/libaudiohal/DevicesFactoryHalInterface.cpp b/media/libaudiohal/DevicesFactoryHalInterface.cpp
index d5336fa..325a547 100644
--- a/media/libaudiohal/DevicesFactoryHalInterface.cpp
+++ b/media/libaudiohal/DevicesFactoryHalInterface.cpp
@@ -14,16 +14,15 @@
  * limitations under the License.
  */
 
-#include <libaudiohal/FactoryHalHidl.h>
-
 #include <media/audiohal/DevicesFactoryHalInterface.h>
+#include <media/audiohal/FactoryHalHidl.h>
 
 namespace android {
 
 // static
 sp<DevicesFactoryHalInterface> DevicesFactoryHalInterface::create() {
-    return createPreferedImpl<DevicesFactoryHalInterface>();
+    return createPreferredImpl<DevicesFactoryHalInterface>(
+            "android.hardware.audio", "IDevicesFactory");
 }
 
 } // namespace android
-
diff --git a/media/libaudiohal/EffectsFactoryHalInterface.cpp b/media/libaudiohal/EffectsFactoryHalInterface.cpp
index d15b14e..bc3b4c1 100644
--- a/media/libaudiohal/EffectsFactoryHalInterface.cpp
+++ b/media/libaudiohal/EffectsFactoryHalInterface.cpp
@@ -14,15 +14,15 @@
  * limitations under the License.
  */
 
-#include <libaudiohal/FactoryHalHidl.h>
-
 #include <media/audiohal/EffectsFactoryHalInterface.h>
+#include <media/audiohal/FactoryHalHidl.h>
 
 namespace android {
 
 // static
 sp<EffectsFactoryHalInterface> EffectsFactoryHalInterface::create() {
-    return createPreferedImpl<EffectsFactoryHalInterface>();
+    return createPreferredImpl<EffectsFactoryHalInterface>(
+            "android.hardware.audio.effect", "IEffectsFactory");
 }
 
 // static
diff --git a/media/libaudiohal/FactoryHalHidl.cpp b/media/libaudiohal/FactoryHalHidl.cpp
new file mode 100644
index 0000000..5985ef0
--- /dev/null
+++ b/media/libaudiohal/FactoryHalHidl.cpp
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "FactoryHalHidl"
+
+#include <media/audiohal/FactoryHalHidl.h>
+
+#include <dlfcn.h>
+
+#include <android/hidl/manager/1.0/IServiceManager.h>
+#include <hidl/ServiceManagement.h>
+#include <hidl/Status.h>
+#include <utils/Log.h>
+
+namespace android::detail {
+
+namespace {
+/** Supported HAL versions, in order of preference.
+ */
+const char* sAudioHALVersions[] = {
+    "6.0",
+    "5.0",
+    "4.0",
+    "2.0",
+    nullptr
+};
+
+bool createHalService(const std::string& version, const std::string& interface,
+        void** rawInterface) {
+    const std::string libName = "libaudiohal@" + version + ".so";
+    const std::string factoryFunctionName = "create" + interface;
+    constexpr int dlMode = RTLD_LAZY;
+    void* handle = nullptr;
+    dlerror(); // clear
+    handle = dlopen(libName.c_str(), dlMode);
+    if (handle == nullptr) {
+        const char* error = dlerror();
+        ALOGE("Failed to dlopen %s: %s", libName.c_str(),
+                error != nullptr ? error : "unknown error");
+        return false;
+    }
+    void* (*factoryFunction)();
+    *(void **)(&factoryFunction) = dlsym(handle, factoryFunctionName.c_str());
+    if (!factoryFunction) {
+        const char* error = dlerror();
+        ALOGE("Factory function %s not found in library %s: %s",
+                factoryFunctionName.c_str(), libName.c_str(),
+                error != nullptr ? error : "unknown error");
+        dlclose(handle);
+        return false;
+    }
+    *rawInterface = (*factoryFunction)();
+    ALOGW_IF(!*rawInterface, "Factory function %s from %s returned nullptr",
+            factoryFunctionName.c_str(), libName.c_str());
+    return true;
+}
+
+bool hasHalService(const std::string& package, const std::string& version,
+        const std::string& interface) {
+    using ::android::hidl::manager::V1_0::IServiceManager;
+    sp<IServiceManager> sm = ::android::hardware::defaultServiceManager();
+    if (!sm) {
+        ALOGE("Failed to obtain HIDL ServiceManager");
+        return false;
+    }
+    // Since audio HAL doesn't support multiple clients, avoid instantiating
+    // the interface right away. Instead, query the transport type for it.
+    using ::android::hardware::Return;
+    using Transport = IServiceManager::Transport;
+    const std::string fqName = package + "@" + version + "::" + interface;
+    const std::string instance = "default";
+    Return<Transport> transport = sm->getTransport(fqName, instance);
+    if (!transport.isOk()) {
+        ALOGE("Failed to obtain transport type for %s/%s: %s",
+                fqName.c_str(), instance.c_str(), transport.description().c_str());
+        return false;
+    }
+    return transport != Transport::EMPTY;
+}
+
+}  // namespace
+
+void* createPreferredImpl(const std::string& package, const std::string& interface) {
+    for (auto version = detail::sAudioHALVersions; version != nullptr; ++version) {
+        void* rawInterface = nullptr;
+        if (hasHalService(package, *version, interface)
+                && createHalService(*version, interface, &rawInterface)) {
+            return rawInterface;
+        }
+    }
+    return nullptr;
+}
+
+}  // namespace android::detail
diff --git a/media/libaudiohal/impl/Android.bp b/media/libaudiohal/impl/Android.bp
index e96a68c..967fba1 100644
--- a/media/libaudiohal/impl/Android.bp
+++ b/media/libaudiohal/impl/Android.bp
@@ -16,12 +16,11 @@
         "StreamHalHidl.cpp",
     ],
 
-    export_include_dirs: ["include"],
-
     cflags: [
         "-Wall",
         "-Wextra",
         "-Werror",
+        "-fvisibility=hidden",
     ],
     shared_libs: [
         "android.hardware.audio.common-util",
diff --git a/media/libaudiohal/impl/DevicesFactoryHalHidl.cpp b/media/libaudiohal/impl/DevicesFactoryHalHidl.cpp
index c30da3c..e6e9688 100644
--- a/media/libaudiohal/impl/DevicesFactoryHalHidl.cpp
+++ b/media/libaudiohal/impl/DevicesFactoryHalHidl.cpp
@@ -20,7 +20,7 @@
 #define LOG_TAG "DevicesFactoryHalHidl"
 //#define LOG_NDEBUG 0
 
-#include "android/hidl/manager/1.0/IServiceManager.h"
+#include <android/hidl/manager/1.0/IServiceManager.h>
 #include PATH(android/hardware/audio/FILE_VERSION/IDevice.h)
 #include <media/audiohal/hidl/HalDeathHandler.h>
 #include <utils/Log.h>
diff --git a/media/libaudiohal/impl/DevicesFactoryHalHybrid.cpp b/media/libaudiohal/impl/DevicesFactoryHalHybrid.cpp
index a5aef1b..52f150a 100644
--- a/media/libaudiohal/impl/DevicesFactoryHalHybrid.cpp
+++ b/media/libaudiohal/impl/DevicesFactoryHalHybrid.cpp
@@ -20,7 +20,6 @@
 #include "DevicesFactoryHalHidl.h"
 #include "DevicesFactoryHalHybrid.h"
 #include "DevicesFactoryHalLocal.h"
-#include <libaudiohal/FactoryHalHidl.h>
 
 namespace android {
 namespace CPP_VERSION {
@@ -47,8 +46,7 @@
 
 } // namespace CPP_VERSION
 
-template <>
-sp<DevicesFactoryHalInterface> createFactoryHal<AudioHALVersion::CPP_VERSION>() {
+extern "C" __attribute__((visibility("default"))) void* createIDevicesFactory() {
     auto service = hardware::audio::CPP_VERSION::IDevicesFactory::getService();
     return service ? new CPP_VERSION::DevicesFactoryHalHybrid(service) : nullptr;
 }
diff --git a/media/libaudiohal/impl/EffectsFactoryHalHidl.cpp b/media/libaudiohal/impl/EffectsFactoryHalHidl.cpp
index 867b72d..9192a31 100644
--- a/media/libaudiohal/impl/EffectsFactoryHalHidl.cpp
+++ b/media/libaudiohal/impl/EffectsFactoryHalHidl.cpp
@@ -24,7 +24,6 @@
 #include "EffectHalHidl.h"
 #include "EffectsFactoryHalHidl.h"
 #include "HidlUtils.h"
-#include <libaudiohal/FactoryHalHidl.h>
 
 using ::android::hardware::audio::common::CPP_VERSION::implementation::HidlUtils;
 using ::android::hardware::Return;
@@ -162,8 +161,7 @@
 } // namespace CPP_VERSION
 } // namespace effect
 
-template<>
-sp<EffectsFactoryHalInterface> createFactoryHal<AudioHALVersion::CPP_VERSION>() {
+extern "C" __attribute__((visibility("default"))) void* createIEffectsFactory() {
     auto service = hardware::audio::effect::CPP_VERSION::IEffectsFactory::getService();
     return service ? new effect::CPP_VERSION::EffectsFactoryHalHidl(service) : nullptr;
 }
diff --git a/media/libaudiohal/impl/include/libaudiohal/FactoryHalHidl.h b/media/libaudiohal/impl/include/libaudiohal/FactoryHalHidl.h
deleted file mode 100644
index 271bafc..0000000
--- a/media/libaudiohal/impl/include/libaudiohal/FactoryHalHidl.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_HARDWARE_FACTORY_HAL_HIDL_H
-#define ANDROID_HARDWARE_FACTORY_HAL_HIDL_H
-
-/** @file Library entry points to create the HAL factories. */
-
-#include <media/audiohal/DevicesFactoryHalInterface.h>
-#include <media/audiohal/EffectsFactoryHalInterface.h>
-#include <utils/StrongPointer.h>
-
-#include <array>
-#include <utility>
-
-namespace android {
-
-/** Supported HAL versions, in order of preference.
- * Implementation should use specialize the `create*FactoryHal` for their version.
- * Client should use `createPreferedImpl<*FactoryHal>()` to instantiate
- * the preferred available impl.
- */
-enum class AudioHALVersion {
-    V6_0,
-    V5_0,
-    V4_0,
-    V2_0,
-    end, // used for iterating over supported versions
-};
-
-/** Template function to fully specialized for each version and each Interface. */
-template <AudioHALVersion, class Interface>
-sp<Interface> createFactoryHal();
-
-/** @Return the preferred available implementation or nullptr if none are available. */
-template <class Interface, AudioHALVersion version = AudioHALVersion{}>
-static sp<Interface> createPreferedImpl() {
-    if constexpr (version == AudioHALVersion::end) {
-        return nullptr; // tried all version, all returned nullptr
-    } else {
-        if (auto created = createFactoryHal<version, Interface>(); created != nullptr) {
-           return created;
-        }
-
-        using Raw = std::underlying_type_t<AudioHALVersion>; // cast as enum class do not support ++
-        return createPreferedImpl<Interface, AudioHALVersion(Raw(version) + 1)>();
-    }
-}
-
-
-} // namespace android
-
-#endif // ANDROID_HARDWARE_FACTORY_HAL_HIDL_H
diff --git a/media/libaudiohal/include/media/audiohal/FactoryHalHidl.h b/media/libaudiohal/include/media/audiohal/FactoryHalHidl.h
new file mode 100644
index 0000000..d353ed0
--- /dev/null
+++ b/media/libaudiohal/include/media/audiohal/FactoryHalHidl.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_HARDWARE_FACTORY_HAL_HIDL_H
+#define ANDROID_HARDWARE_FACTORY_HAL_HIDL_H
+
+#include <string>
+
+#include <utils/StrongPointer.h>
+
+namespace android {
+
+namespace detail {
+
+void* createPreferredImpl(const std::string& package, const std::string& interface);
+
+}  // namespace detail
+
+/** @Return the preferred available implementation or nullptr if none are available. */
+template <class Interface>
+static sp<Interface> createPreferredImpl(const std::string& package, const std::string& interface) {
+    return sp<Interface>{static_cast<Interface*>(detail::createPreferredImpl(package, interface))};
+}
+
+} // namespace android
+
+#endif // ANDROID_HARDWARE_FACTORY_HAL_HIDL_H
diff --git a/media/libmedia/MidiIoWrapper.cpp b/media/libmedia/MidiIoWrapper.cpp
index 6d46363..e71ea2c 100644
--- a/media/libmedia/MidiIoWrapper.cpp
+++ b/media/libmedia/MidiIoWrapper.cpp
@@ -49,7 +49,7 @@
     mDataSource = nullptr;
 }
 
-class DataSourceUnwrapper {
+class MidiIoWrapper::DataSourceUnwrapper {
 
 public:
     explicit DataSourceUnwrapper(CDataSource *csource) {
diff --git a/media/libmedia/include/media/MidiIoWrapper.h b/media/libmedia/include/media/MidiIoWrapper.h
index b19d49e..d29949e 100644
--- a/media/libmedia/include/media/MidiIoWrapper.h
+++ b/media/libmedia/include/media/MidiIoWrapper.h
@@ -24,7 +24,6 @@
 namespace android {
 
 struct CDataSource;
-class DataSourceUnwrapper;
 
 class MidiIoWrapper {
 public:
@@ -43,6 +42,7 @@
     int mFd;
     off64_t mBase;
     int64_t  mLength;
+    class DataSourceUnwrapper;
     DataSourceUnwrapper *mDataSource;
     EAS_FILE mEasFile;
 };
diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp
index f130c9b..258bed8 100644
--- a/media/libstagefright/MPEG4Writer.cpp
+++ b/media/libstagefright/MPEG4Writer.cpp
@@ -613,8 +613,9 @@
 
     CHECK(source.get() != NULL);
 
-    const char *mime;
-    source->getFormat()->findCString(kKeyMIMEType, &mime);
+    const char *mime = NULL;
+    sp<MetaData> meta = source->getFormat();
+    meta->findCString(kKeyMIMEType, &mime);
 
     if (Track::getFourCCForMime(mime) == NULL) {
         ALOGE("Unsupported mime '%s'", mime);
diff --git a/media/libstagefright/MediaExtractorFactory.cpp b/media/libstagefright/MediaExtractorFactory.cpp
index 120f354..7689691 100644
--- a/media/libstagefright/MediaExtractorFactory.cpp
+++ b/media/libstagefright/MediaExtractorFactory.cpp
@@ -276,7 +276,7 @@
 
     std::shared_ptr<std::list<sp<ExtractorPlugin>>> newList(new std::list<sp<ExtractorPlugin>>());
 
-    android_namespace_t *mediaNs = android_get_exported_namespace("media");
+    android_namespace_t *mediaNs = android_get_exported_namespace("com.android.media");
     if (mediaNs != NULL) {
         const android_dlextinfo dlextinfo = {
             .flags = ANDROID_DLEXT_USE_NAMESPACE,
diff --git a/media/libstagefright/codecs/on2/enc/Android.bp b/media/libstagefright/codecs/on2/enc/Android.bp
index cd69e0d..705e554 100644
--- a/media/libstagefright/codecs/on2/enc/Android.bp
+++ b/media/libstagefright/codecs/on2/enc/Android.bp
@@ -21,4 +21,5 @@
     },
 
     shared_libs: ["libvpx"],
+    header_libs: ["libbase_headers"],
 }
diff --git a/media/libstagefright/foundation/Android.bp b/media/libstagefright/foundation/Android.bp
index b95f054..effbb4e 100644
--- a/media/libstagefright/foundation/Android.bp
+++ b/media/libstagefright/foundation/Android.bp
@@ -34,10 +34,6 @@
         "media_plugin_headers",
     ],
 
-    export_shared_lib_headers: [
-        "libbinder",
-    ],
-
     cflags: [
         "-Wno-multichar",
         "-Werror",
diff --git a/media/libstagefright/id3/ID3.cpp b/media/libstagefright/id3/ID3.cpp
index 792a68a..425468f 100644
--- a/media/libstagefright/id3/ID3.cpp
+++ b/media/libstagefright/id3/ID3.cpp
@@ -32,7 +32,7 @@
 
 static const size_t kMaxMetadataSize = 3 * 1024 * 1024;
 
-struct MemorySource : public DataSourceBase {
+struct ID3::MemorySource : public DataSourceBase {
     MemorySource(const uint8_t *data, size_t size)
         : mData(data),
           mSize(size) {
@@ -58,7 +58,7 @@
     DISALLOW_EVIL_CONSTRUCTORS(MemorySource);
 };
 
-class DataSourceUnwrapper : public DataSourceBase {
+class ID3::DataSourceUnwrapper : public DataSourceBase {
 
 public:
     explicit DataSourceUnwrapper(DataSourceHelper *sourcehelper) {
diff --git a/media/libstagefright/include/ID3.h b/media/libstagefright/include/ID3.h
index 5e433ea..2843a7a 100644
--- a/media/libstagefright/include/ID3.h
+++ b/media/libstagefright/include/ID3.h
@@ -77,6 +77,8 @@
     size_t rawSize() const { return mRawSize; }
 
 private:
+    class DataSourceUnwrapper;
+    struct MemorySource;
     bool mIsValid;
     uint8_t *mData;
     size_t mSize;
diff --git a/media/libstagefright/tests/writer/AndroidTest.xml b/media/libstagefright/tests/writer/AndroidTest.xml
new file mode 100644
index 0000000..d831555
--- /dev/null
+++ b/media/libstagefright/tests/writer/AndroidTest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Test module config for writer tests">
+    <option name="test-suite-tag" value="writerTest" />
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push" value="writerTest->/data/local/tmp/writerTest" />
+        <option name="push-file"
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/libstagefright/tests/writer/Writer.zip?unzip=true"
+            value="/data/local/tmp/writerTestRes/" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="writerTest" />
+        <option name="native-test-flag" value="-P /data/local/tmp/writerTestRes/" />
+    </test>
+</configuration>
diff --git a/media/tests/benchmark/MediaBenchmarkTest/AndroidTest.xml b/media/tests/benchmark/MediaBenchmarkTest/AndroidTest.xml
index 1179d6c..1890661 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/AndroidTest.xml
+++ b/media/tests/benchmark/MediaBenchmarkTest/AndroidTest.xml
@@ -14,6 +14,12 @@
      limitations under the License.
 -->
 <configuration description="Runs Media Benchmark Tests">
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push-file"
+            key="https://storage.googleapis.com/android_media/frameworks/av/media/tests/benchmark/MediaBenchmark.zip?unzip=true"
+            value="/data/local/tmp/MediaBenchmark/res/" />
+    </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.TestAppInstallSetup">
         <option name="cleanup-apks" value="false" />
         <option name="test-file-name" value="MediaBenchmarkTest.apk" />
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/DecoderTest.java b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/DecoderTest.java
index c41f198..afd70a3 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/DecoderTest.java
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/DecoderTest.java
@@ -78,7 +78,7 @@
                 {"bbb_44100hz_2ch_128kbps_mp3_30sec.mp3", false},
                 {"bbb_8000hz_1ch_8kbps_amrnb_30sec.3gp", false},
                 {"bbb_16000hz_1ch_9kbps_amrwb_30sec.3gp", false},
-                {"bbb_44100hz_2ch_80kbps_vorbis_30sec.mp4", false},
+                {"bbb_44100hz_2ch_80kbps_vorbis_30sec.webm", false},
                 {"bbb_44100hz_2ch_600kbps_flac_30sec.mp4", false},
                 {"bbb_48000hz_2ch_100kbps_opus_30sec.webm", false},
                 // Audio Async Test
@@ -86,7 +86,7 @@
                 {"bbb_44100hz_2ch_128kbps_mp3_30sec.mp3", true},
                 {"bbb_8000hz_1ch_8kbps_amrnb_30sec.3gp", true},
                 {"bbb_16000hz_1ch_9kbps_amrwb_30sec.3gp", true},
-                {"bbb_44100hz_2ch_80kbps_vorbis_30sec.mp4", true},
+                {"bbb_44100hz_2ch_80kbps_vorbis_30sec.webm", true},
                 {"bbb_44100hz_2ch_600kbps_flac_30sec.mp4", true},
                 {"bbb_48000hz_2ch_100kbps_opus_30sec.webm", true},
                 // Video Sync Test
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/EncoderTest.java b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/EncoderTest.java
index 831467a..48e1422 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/EncoderTest.java
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/EncoderTest.java
@@ -19,6 +19,9 @@
 import android.content.Context;
 import android.media.MediaCodec;
 import android.media.MediaFormat;
+
+import static android.media.MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible;
+
 import android.util.Log;
 
 import androidx.test.platform.app.InstrumentationRegistry;
@@ -65,6 +68,7 @@
     private static final int ENCODE_DEFAULT_FRAME_RATE = 25;
     private static final int ENCODE_DEFAULT_BIT_RATE = 8000000 /* 8 Mbps */;
     private static final int ENCODE_MIN_BIT_RATE = 600000 /* 600 Kbps */;
+    private static final int ENCODE_DEFAULT_AUDIO_BIT_RATE = 128000 /* 128 Kbps */;
     private String mInputFile;
 
     @Parameterized.Parameters
@@ -98,7 +102,7 @@
     }
 
     @Test(timeout = PER_TEST_TIMEOUT_MS)
-    public void sampleEncoderTest() throws Exception {
+    public void testEncoder() throws Exception {
         int status;
         int frameSize;
         //Parameters for video
@@ -107,6 +111,7 @@
         int profile = 0;
         int level = 0;
         int frameRate = 0;
+
         //Parameters for audio
         int bitRate = 0;
         int sampleRate = 0;
@@ -122,6 +127,7 @@
         ArrayList<ByteBuffer> inputBuffer = new ArrayList<>();
         ArrayList<MediaCodec.BufferInfo> frameInfo = new ArrayList<>();
         for (int currentTrack = 0; currentTrack < trackCount; currentTrack++) {
+            int colorFormat = COLOR_FormatYUV420Flexible;
             extractor.selectExtractorTrack(currentTrack);
             MediaFormat format = extractor.getFormat(currentTrack);
             // Get samples from extractor
@@ -148,6 +154,7 @@
             status = decoder.decode(inputBuffer, frameInfo, false, format, "");
             assertEquals("Decoder returned error " + status + " for file: " + mInputFile, 0,
                     status);
+            MediaFormat decoderFormat = decoder.getFormat();
             decoder.deInitCodec();
             extractor.unselectExtractorTrack(currentTrack);
             inputBuffer.clear();
@@ -203,10 +210,17 @@
                         if (format.containsKey(MediaFormat.KEY_PROFILE)) {
                             level = format.getInteger(MediaFormat.KEY_LEVEL);
                         }
+                        if (decoderFormat.containsKey(MediaFormat.KEY_COLOR_FORMAT)) {
+                            colorFormat = decoderFormat.getInteger(MediaFormat.KEY_COLOR_FORMAT);
+                        }
                     } else {
                         sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
                         numChannels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
-                        bitRate = sampleRate * numChannels * 16;
+                        if (decoderFormat.containsKey(MediaFormat.KEY_BIT_RATE)) {
+                            bitRate = decoderFormat.getInteger(MediaFormat.KEY_BIT_RATE);
+                        } else {
+                            bitRate = ENCODE_DEFAULT_AUDIO_BIT_RATE;
+                        }
                     }
                     /*Setup Encode Format*/
                     MediaFormat encodeFormat;
@@ -219,6 +233,7 @@
                         encodeFormat.setInteger(MediaFormat.KEY_LEVEL, level);
                         encodeFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
                         encodeFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, frameSize);
+                        encodeFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat);
                     } else {
                         encodeFormat = MediaFormat.createAudioFormat(mime, sampleRate, numChannels);
                         encodeFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
@@ -255,7 +270,7 @@
         fileInput.close();
     }
 
-    @Test
+    @Test(timeout = PER_TEST_TIMEOUT_MS)
     public void testNativeEncoder() throws Exception {
         File inputFile = new File(mInputFilePath + mInputFile);
         assertTrue("Cannot find " + mInputFile + " in directory " + mInputFilePath,
@@ -275,8 +290,8 @@
             // Encoding the decoder's output
             for (String codecName : mediaCodecs) {
                 Native nativeEncoder = new Native();
-                int status = nativeEncoder.Encode(
-                        mInputFilePath, mInputFile, mDecodedFile, mStatsFile, codecName);
+                int status = nativeEncoder
+                        .Encode(mInputFilePath, mInputFile, mDecodedFile, mStatsFile, codecName);
                 assertEquals(
                         codecName + " encoder returned error " + status + " for " + "file:" + " " +
                                 mInputFile, 0, status);
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/ExtractorTest.java b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/ExtractorTest.java
index 6b7aad1..4d026c1 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/ExtractorTest.java
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/ExtractorTest.java
@@ -70,7 +70,7 @@
                 {"bbb_44100hz_2ch_600kbps_flac_5mins.flac", 0},
                 {"bbb_8000hz_1ch_8kbps_amrnb_5mins.3gp", 0},
                 {"bbb_16000hz_1ch_9kbps_amrwb_5mins.3gp", 0},
-                {"bbb_44100hz_2ch_80kbps_vorbis_5mins.mp4", 0},
+                {"bbb_44100hz_2ch_80kbps_vorbis_5mins.webm", 0},
                 {"bbb_48000hz_2ch_100kbps_opus_5mins.webm", 0}});
     }
 
@@ -88,7 +88,7 @@
     }
 
     @Test
-    public void sampleExtractTest() throws IOException {
+    public void testExtractor() throws IOException {
         File inputFile = new File(mInputFilePath + mInputFileName);
         assertTrue("Cannot find " + mInputFileName + " in directory " + mInputFilePath,
                 inputFile.exists());
@@ -107,7 +107,7 @@
     }
 
     @Test
-    public void sampleExtractNativeTest() throws IOException {
+    public void testNativeExtractor() throws IOException {
         Native nativeExtractor = new Native();
         File inputFile = new File(mInputFilePath + mInputFileName);
         assertTrue("Cannot find " + mInputFileName + " in directory " + mInputFilePath,
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/MuxerTest.java b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/MuxerTest.java
index 2efdba2..21ba957 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/MuxerTest.java
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/androidTest/java/com/android/media/benchmark/tests/MuxerTest.java
@@ -86,7 +86,7 @@
                 {"crowd_1920x1080_25fps_6700kbps_h264.ts", "3gpp"},
                 {"crowd_1920x1080_25fps_4000kbps_h265.mkv", "3gpp"},
                 {"bbb_48000hz_2ch_100kbps_opus_5mins.webm", "ogg"},
-                {"bbb_44100hz_2ch_80kbps_vorbis_5mins.mp4", "webm"},
+                {"bbb_44100hz_2ch_80kbps_vorbis_5mins.webm", "webm"},
                 {"bbb_48000hz_2ch_100kbps_opus_5mins.webm", "webm"},
                 {"bbb_44100hz_2ch_128kbps_aac_5mins.mp4", "mp4"},
                 {"bbb_8000hz_1ch_8kbps_amrnb_5mins.3gp", "mp4"},
@@ -110,7 +110,7 @@
     }
 
     @Test
-    public void sampleMuxerTest() throws IOException {
+    public void testMuxer() throws IOException {
         File inputFile = new File(mInputFilePath + mInputFileName);
         assertTrue("Cannot find " + mInputFileName + " in directory " + mInputFilePath,
                 inputFile.exists());
@@ -159,7 +159,7 @@
     }
 
     @Test
-    public void sampleMuxerNativeTest() {
+    public void testNativeMuxer() {
         Native nativeMuxer = new Native();
         File inputFile = new File(mInputFilePath + mInputFileName);
         assertTrue("Cannot find " + mInputFileName + " in directory " + mInputFilePath,
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/NativeEncoder.cpp b/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/NativeEncoder.cpp
index 271b852..1277c8b 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/NativeEncoder.cpp
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/NativeEncoder.cpp
@@ -18,9 +18,9 @@
 #define LOG_TAG "NativeEncoder"
 
 #include <jni.h>
+#include <sys/stat.h>
 #include <fstream>
 #include <iostream>
-#include <sys/stat.h>
 
 #include <android/log.h>
 
@@ -29,6 +29,11 @@
 
 #include <stdio.h>
 
+constexpr int32_t ENCODE_DEFAULT_FRAME_RATE = 25;
+constexpr int32_t ENCODE_DEFAULT_AUDIO_BIT_RATE = 128000 /* 128 Kbps */;
+constexpr int32_t ENCODE_DEFAULT_BIT_RATE = 8000000 /* 8 Mbps */;
+constexpr int32_t ENCODE_MIN_BIT_RATE = 600000 /* 600 Kbps */;
+
 extern "C" JNIEXPORT int JNICALL Java_com_android_media_benchmark_library_Native_Encode(
         JNIEnv *env, jobject thiz, jstring jFilePath, jstring jFileName, jstring jOutFilePath,
         jstring jStatsFile, jstring jCodecName) {
@@ -72,7 +77,7 @@
             ALOGE("Track Format invalid");
             return -1;
         }
-        uint8_t *inputBuffer = (uint8_t *) malloc(fileSize);
+        uint8_t *inputBuffer = (uint8_t *)malloc(fileSize);
         if (!inputBuffer) {
             ALOGE("Insufficient memory");
             return -1;
@@ -110,6 +115,8 @@
             free(inputBuffer);
             return -1;
         }
+
+        AMediaFormat *decoderFormat = decoder->getFormat();
         AMediaFormat *format = extractor->getFormat();
         if (inputBuffer) {
             free(inputBuffer);
@@ -146,29 +153,34 @@
                 AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_FRAME_RATE, &encParams.frameRate);
                 AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_BIT_RATE, &encParams.bitrate);
                 if (encParams.bitrate <= 0 || encParams.frameRate <= 0) {
-                    encParams.frameRate = 25;
+                    encParams.frameRate = ENCODE_DEFAULT_FRAME_RATE;
                     if (!strcmp(mime, "video/3gpp") || !strcmp(mime, "video/mp4v-es")) {
-                        encParams.bitrate = 600000 /* 600 Kbps */;
+                        encParams.bitrate = ENCODE_MIN_BIT_RATE /* 600 Kbps */;
                     } else {
-                        encParams.bitrate = 8000000 /* 8 Mbps */;
+                        encParams.bitrate = ENCODE_DEFAULT_BIT_RATE /* 8 Mbps */;
                     }
                 }
                 AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_PROFILE, &encParams.profile);
                 AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_LEVEL, &encParams.level);
+                AMediaFormat_getInt32(decoderFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT,
+                                      &encParams.colorFormat);
             } else {
                 AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, &encParams.sampleRate);
                 AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT,
                                       &encParams.numChannels);
-                encParams.bitrate =
-                        encParams.sampleRate * encParams.numChannels * 16 /* bitsPerSample */;
+                encParams.bitrate = ENCODE_DEFAULT_AUDIO_BIT_RATE;
             }
             Encoder *encoder = new Encoder();
             encoder->setupEncoder();
             status = encoder->encode(sCodecName, eleStream, eleSize, asyncMode[i], encParams,
-                                     (char *) mime);
+                                     (char *)mime);
+            if (status != AMEDIA_OK) {
+                ALOGE("Encoder returned error");
+                return -1;
+            }
+            ALOGV("Encoding complete with codec %s for asyncMode = %d", sCodecName.c_str(),
+                  asyncMode[i]);
             encoder->deInitCodec();
-            cout << "codec : " << codecName << endl;
-            ALOGV(" asyncMode = %d \n", asyncMode[i]);
             const char *statsFile = env->GetStringUTFChars(jStatsFile, nullptr);
             encoder->dumpStatistics(sInputReference, extractor->getClipDuration(), sCodecName,
                                     (asyncMode[i] ? "async" : "sync"), statsFile);
@@ -189,6 +201,10 @@
             AMediaFormat_delete(format);
             format = nullptr;
         }
+        if (decoderFormat) {
+            AMediaFormat_delete(decoderFormat);
+            decoderFormat = nullptr;
+        }
         decoder->deInitCodec();
         decoder->resetDecoder();
     }
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Decoder.java b/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Decoder.java
index 3b1eed4..66fee33 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Decoder.java
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Decoder.java
@@ -134,7 +134,6 @@
                     mStats.addOutputTime();
                     onOutputAvailable(mediaCodec, outputBufferId, bufferInfo);
                     if (mSawOutputEOS) {
-                        Log.i(TAG, "Saw output EOS");
                         synchronized (mLock) { mLock.notify(); }
                     }
                 }
@@ -211,9 +210,6 @@
                     }
                     onOutputAvailable(mCodec, outputBufferId, outputBufferInfo);
                 }
-                if (outputBufferInfo.flags == MediaCodec.BUFFER_FLAG_END_OF_STREAM) {
-                    Log.i(TAG, "Saw output EOS");
-                }
             }
         }
         mInputBuffer.clear();
@@ -256,14 +252,21 @@
      */
     public void resetDecoder() { mStats.reset(); }
 
+    /**
+     * Returns the format of the output buffers
+     */
+    public MediaFormat getFormat() {
+        return mCodec.getOutputFormat();
+    }
+
     private void onInputAvailable(int inputBufferId, MediaCodec mediaCodec) {
         if ((inputBufferId >= 0) && !mSawInputEOS) {
             ByteBuffer inputCodecBuffer = mediaCodec.getInputBuffer(inputBufferId);
             BufferInfo bufInfo = mInputBufferInfo.get(mIndex);
             inputCodecBuffer.put(mInputBuffer.get(mIndex).array());
             mIndex++;
-            if (bufInfo.flags == MediaCodec.BUFFER_FLAG_END_OF_STREAM) {
-                mSawInputEOS = true;
+            mSawInputEOS = (bufInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0;
+            if (mSawInputEOS) {
                 Log.i(TAG, "Saw input EOS");
             }
             mStats.addFrameSize(bufInfo.size);
@@ -301,6 +304,9 @@
             }
         }
         mediaCodec.releaseOutputBuffer(outputBufferId, false);
-        mSawOutputEOS = (outputBufferInfo.flags == MediaCodec.BUFFER_FLAG_END_OF_STREAM);
+        mSawOutputEOS = (outputBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0;
+        if (mSawOutputEOS) {
+            Log.i(TAG, "Saw output EOS");
+        }
     }
 }
diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Encoder.java b/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Encoder.java
index 72f501d..45e5574 100644
--- a/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Encoder.java
+++ b/media/tests/benchmark/MediaBenchmarkTest/src/main/java/com/android/media/benchmark/library/Encoder.java
@@ -262,12 +262,12 @@
         }
         mStats.addFrameSize(outputBuffer.remaining());
         mediaCodec.releaseOutputBuffer(outputBufferId, false);
-        mSawOutputEOS = (outputBufferInfo.flags == MediaCodec.BUFFER_FLAG_END_OF_STREAM);
+        mSawOutputEOS = (outputBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0;
     }
 
     private void onInputAvailable(MediaCodec mediaCodec, int inputBufferId) throws IOException {
-        if (mSawOutputEOS || inputBufferId < 0) {
-            if (mSawOutputEOS) {
+        if (mSawInputEOS || inputBufferId < 0) {
+            if (mSawInputEOS) {
                 Log.i(TAG, "Saw input EOS");
             }
             return;
diff --git a/media/tests/benchmark/src/native/decoder/Decoder.cpp b/media/tests/benchmark/src/native/decoder/Decoder.cpp
index 2171589..090f3e1 100644
--- a/media/tests/benchmark/src/native/decoder/Decoder.cpp
+++ b/media/tests/benchmark/src/native/decoder/Decoder.cpp
@@ -63,8 +63,8 @@
         ssize_t bytesRead = 0;
         uint32_t flag = 0;
         int64_t presentationTimeUs = 0;
-        tie(bytesRead, flag, presentationTimeUs) = readSampleData(
-                mInputBuffer, mOffset, mFrameMetaData, buf, mNumInputFrame, bufSize);
+        tie(bytesRead, flag, presentationTimeUs) =
+                readSampleData(mInputBuffer, mOffset, mFrameMetaData, buf, mNumInputFrame, bufSize);
         if (flag == AMEDIA_ERROR_MALFORMED) {
             mErrorCode = (media_status_t)flag;
             mSignalledError = true;
@@ -144,6 +144,11 @@
     if (!mFormat) mFormat = mExtractor->getFormat();
 }
 
+AMediaFormat *Decoder::getFormat() {
+    ALOGV("In %s", __func__);
+    return AMediaCodec_getOutputFormat(mCodec);
+}
+
 int32_t Decoder::decode(uint8_t *inputBuffer, vector<AMediaCodecBufferInfo> &frameInfo,
                         string &codecName, bool asyncMode, FILE *outFp) {
     ALOGV("In %s", __func__);
diff --git a/media/tests/benchmark/src/native/decoder/Decoder.h b/media/tests/benchmark/src/native/decoder/Decoder.h
index f3fa6a1..e619cb4 100644
--- a/media/tests/benchmark/src/native/decoder/Decoder.h
+++ b/media/tests/benchmark/src/native/decoder/Decoder.h
@@ -57,6 +57,8 @@
 
     void resetDecoder();
 
+    AMediaFormat *getFormat();
+
     // Async callback APIs
     void onInputAvailable(AMediaCodec *codec, int32_t index) override;
 
diff --git a/media/tests/benchmark/src/native/encoder/Encoder.cpp b/media/tests/benchmark/src/native/encoder/Encoder.cpp
index 9843e86..26fb1b9 100644
--- a/media/tests/benchmark/src/native/encoder/Encoder.cpp
+++ b/media/tests/benchmark/src/native/encoder/Encoder.cpp
@@ -188,8 +188,8 @@
     mStats->dumpStatistics(operation, inputReference, durationUs, componentName, mode, statsFile);
 }
 
-int32_t Encoder::encode(string &codecName, ifstream &eleStream, size_t eleSize,
-                        bool asyncMode, encParameter encParams, char *mime) {
+int32_t Encoder::encode(string &codecName, ifstream &eleStream, size_t eleSize, bool asyncMode,
+                        encParameter encParams, char *mime) {
     ALOGV("In %s", __func__);
     mEleStream = &eleStream;
     mInputBufferSize = eleSize;
@@ -209,6 +209,7 @@
             AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_PROFILE, mParams.profile);
             AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_LEVEL, mParams.level);
         }
+        AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT, mParams.colorFormat);
     } else {
         AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_SAMPLE_RATE, mParams.sampleRate);
         AMediaFormat_setInt32(mFormat, AMEDIAFORMAT_KEY_CHANNEL_COUNT, mParams.numChannels);
diff --git a/media/tests/benchmark/src/native/encoder/Encoder.h b/media/tests/benchmark/src/native/encoder/Encoder.h
index 3d12600..5ad142b 100644
--- a/media/tests/benchmark/src/native/encoder/Encoder.h
+++ b/media/tests/benchmark/src/native/encoder/Encoder.h
@@ -23,9 +23,11 @@
 #include <queue>
 #include <thread>
 
+#include "media/NdkImage.h"
 #include "BenchmarkCommon.h"
 #include "Stats.h"
 
+
 struct encParameter {
     int32_t bitrate = -1;
     int32_t numFrames = -1;
@@ -38,6 +40,7 @@
     int32_t frameRate = -1;
     int32_t profile = 0;
     int32_t level = 0;
+    int32_t colorFormat = AIMAGE_FORMAT_YUV_420_888;
 };
 
 class Encoder : public CallBackHandle {
diff --git a/media/tests/benchmark/tests/C2DecoderTest.cpp b/media/tests/benchmark/tests/C2DecoderTest.cpp
index ecd9759..dedc743 100644
--- a/media/tests/benchmark/tests/C2DecoderTest.cpp
+++ b/media/tests/benchmark/tests/C2DecoderTest.cpp
@@ -157,7 +157,7 @@
                           make_pair("bbb_44100hz_2ch_128kbps_mp3_30sec.mp3", "mp3"),
                           make_pair("bbb_8000hz_1ch_8kbps_amrnb_30sec.3gp", "amrnb"),
                           make_pair("bbb_16000hz_1ch_9kbps_amrwb_30sec.3gp", "amrnb"),
-                          make_pair("bbb_44100hz_2ch_80kbps_vorbis_30sec.mp4", "vorbis"),
+                          make_pair("bbb_44100hz_2ch_80kbps_vorbis_30sec.webm", "vorbis"),
                           make_pair("bbb_44100hz_2ch_600kbps_flac_30sec.mp4", "flac"),
                           make_pair("bbb_48000hz_2ch_100kbps_opus_30sec.webm", "opus")));
 
diff --git a/media/tests/benchmark/tests/DecoderTest.cpp b/media/tests/benchmark/tests/DecoderTest.cpp
index 5c6aa5b..9f96d3b 100644
--- a/media/tests/benchmark/tests/DecoderTest.cpp
+++ b/media/tests/benchmark/tests/DecoderTest.cpp
@@ -101,7 +101,7 @@
                           make_tuple("bbb_44100hz_2ch_128kbps_mp3_30sec.mp3", "", false),
                           make_tuple("bbb_8000hz_1ch_8kbps_amrnb_30sec.3gp", "", false),
                           make_tuple("bbb_16000hz_1ch_9kbps_amrwb_30sec.3gp", "", false),
-                          make_tuple("bbb_44100hz_2ch_80kbps_vorbis_30sec.mp4", "", false),
+                          make_tuple("bbb_44100hz_2ch_80kbps_vorbis_30sec.webm", "", false),
                           make_tuple("bbb_44100hz_2ch_600kbps_flac_30sec.mp4", "", false),
                           make_tuple("bbb_48000hz_2ch_100kbps_opus_30sec.webm", "", false)));
 
@@ -111,7 +111,7 @@
                           make_tuple("bbb_44100hz_2ch_128kbps_mp3_30sec.mp3", "", true),
                           make_tuple("bbb_8000hz_1ch_8kbps_amrnb_30sec.3gp", "", true),
                           make_tuple("bbb_16000hz_1ch_9kbps_amrwb_30sec.3gp", "", true),
-                          make_tuple("bbb_44100hz_2ch_80kbps_vorbis_30sec.mp4", "", true),
+                          make_tuple("bbb_44100hz_2ch_80kbps_vorbis_30sec.webm", "", true),
                           make_tuple("bbb_44100hz_2ch_600kbps_flac_30sec.mp4", "", true),
                           make_tuple("bbb_48000hz_2ch_100kbps_opus_30sec.webm", "", true)));
 
diff --git a/media/tests/benchmark/tests/ExtractorTest.cpp b/media/tests/benchmark/tests/ExtractorTest.cpp
index c2d72ff..ad8f1e6 100644
--- a/media/tests/benchmark/tests/ExtractorTest.cpp
+++ b/media/tests/benchmark/tests/ExtractorTest.cpp
@@ -69,7 +69,7 @@
                                            make_pair("bbb_44100hz_2ch_600kbps_flac_5mins.flac", 0),
                                            make_pair("bbb_8000hz_1ch_8kbps_amrnb_5mins.3gp", 0),
                                            make_pair("bbb_16000hz_1ch_9kbps_amrwb_5mins.3gp", 0),
-                                           make_pair("bbb_44100hz_2ch_80kbps_vorbis_5mins.mp4", 0),
+                                           make_pair("bbb_44100hz_2ch_80kbps_vorbis_5mins.webm", 0),
                                            make_pair("bbb_48000hz_2ch_100kbps_opus_5mins.webm",
                                                      0)));
 
diff --git a/media/tests/benchmark/tests/MuxerTest.cpp b/media/tests/benchmark/tests/MuxerTest.cpp
index 7b01732..fa2635d 100644
--- a/media/tests/benchmark/tests/MuxerTest.cpp
+++ b/media/tests/benchmark/tests/MuxerTest.cpp
@@ -136,7 +136,7 @@
                           make_pair("crowd_1920x1080_25fps_6700kbps_h264.ts", "3gpp"),
                           make_pair("crowd_1920x1080_25fps_4000kbps_h265.mkv", "3gpp"),
                           make_pair("bbb_48000hz_2ch_100kbps_opus_5mins.webm", "ogg"),
-                          make_pair("bbb_44100hz_2ch_80kbps_vorbis_5mins.mp4", "webm"),
+                          make_pair("bbb_44100hz_2ch_80kbps_vorbis_5mins.webm", "webm"),
                           make_pair("bbb_48000hz_2ch_100kbps_opus_5mins.webm", "webm"),
                           make_pair("bbb_44100hz_2ch_128kbps_aac_5mins.mp4", "mp4"),
                           make_pair("bbb_8000hz_1ch_8kbps_amrnb_5mins.3gp", "mp4"),
diff --git a/services/audioflinger/Android.bp b/services/audioflinger/Android.bp
index 46472c9..c58360d 100644
--- a/services/audioflinger/Android.bp
+++ b/services/audioflinger/Android.bp
@@ -3,8 +3,6 @@
 cc_library_shared {
     name: "libaudioflinger",
 
-    tidy: false, // b/146435095, segmentation fault with Effects.cpp
-
     srcs: [
         "AudioFlinger.cpp",
         "AudioHwDevice.cpp",
diff --git a/services/audiopolicy/engine/common/src/EngineBase.cpp b/services/audiopolicy/engine/common/src/EngineBase.cpp
index 525e965..b46a50a 100644
--- a/services/audiopolicy/engine/common/src/EngineBase.cpp
+++ b/services/audiopolicy/engine/common/src/EngineBase.cpp
@@ -107,6 +107,14 @@
 engineConfig::ParsingResult EngineBase::loadAudioPolicyEngineConfig()
 {
     auto loadVolumeConfig = [](auto &volumeGroups, auto &volumeConfig) {
+        // Ensure name unicity to prevent duplicate
+        const auto &iter = std::find_if(std::begin(volumeGroups), std::end(volumeGroups),
+                                     [&volumeConfig](const auto &volumeGroup) {
+                return volumeConfig.name == volumeGroup.second->getName(); });
+        LOG_ALWAYS_FATAL_IF(iter != std::end(volumeGroups),
+                            "group name %s defined twice, review the configuration",
+                            volumeConfig.name.c_str());
+
         sp<VolumeGroup> volumeGroup = new VolumeGroup(volumeConfig.name, volumeConfig.indexMin,
                                                       volumeConfig.indexMax);
         volumeGroups[volumeGroup->getId()] = volumeGroup;
@@ -125,13 +133,21 @@
         }
         return volumeGroup;
     };
-    auto addSupportedStreamAttributes = [](auto &group, auto &volumeGroup, auto &strategy) {
-        volumeGroup->addSupportedStream(group.stream);
+    auto addSupportedAttributesToGroup = [](auto &group, auto &volumeGroup, auto &strategy) {
         for (const auto &attr : group.attributesVect) {
             strategy->addAttributes({group.stream, volumeGroup->getId(), attr});
             volumeGroup->addSupportedAttributes(attr);
         }
     };
+    auto checkStreamForGroups = [](auto streamType, const auto &volumeGroups) {
+        const auto &iter = std::find_if(std::begin(volumeGroups), std::end(volumeGroups),
+                                     [&streamType](const auto &volumeGroup) {
+            const auto& streams = volumeGroup.second->getStreamTypes();
+            return std::find(std::begin(streams), std::end(streams), streamType) !=
+                    std::end(streams);
+        });
+        return iter != end(volumeGroups);
+    };
 
     auto result = engineConfig::parse();
     if (result.parsedConfig == nullptr) {
@@ -140,24 +156,30 @@
         android::status_t ret = engineConfig::parseLegacyVolumes(config.volumeGroups);
         result = {std::make_unique<engineConfig::Config>(config),
                   static_cast<size_t>(ret == NO_ERROR ? 0 : 1)};
+    } else {
+        // Append for internal use only volume groups (e.g. rerouting/patch)
+        result.parsedConfig->volumeGroups.insert(
+                    std::end(result.parsedConfig->volumeGroups),
+                    std::begin(gSystemVolumeGroups), std::end(gSystemVolumeGroups));
     }
-    // Append for internal use only strategies/volume groups (e.g. rerouting/patch)
+    // Append for internal use only strategies (e.g. rerouting/patch)
     result.parsedConfig->productStrategies.insert(
                 std::end(result.parsedConfig->productStrategies),
                 std::begin(gOrderedSystemStrategies), std::end(gOrderedSystemStrategies));
 
-    result.parsedConfig->volumeGroups.insert(
-                std::end(result.parsedConfig->volumeGroups),
-                std::begin(gSystemVolumeGroups), std::end(gSystemVolumeGroups));
 
     ALOGE_IF(result.nbSkippedElement != 0, "skipped %zu elements", result.nbSkippedElement);
 
     engineConfig::VolumeGroup defaultVolumeConfig;
+    engineConfig::VolumeGroup defaultSystemVolumeConfig;
     for (auto &volumeConfig : result.parsedConfig->volumeGroups) {
         // save default volume config for streams not defined in configuration
         if (volumeConfig.name.compare("AUDIO_STREAM_MUSIC") == 0) {
             defaultVolumeConfig = volumeConfig;
         }
+        if (volumeConfig.name.compare("AUDIO_STREAM_PATCH") == 0) {
+            defaultSystemVolumeConfig = volumeConfig;
+        }
         loadVolumeConfig(mVolumeGroups, volumeConfig);
     }
     for (auto& strategyConfig : result.parsedConfig->productStrategies) {
@@ -166,18 +188,31 @@
             const auto &iter = std::find_if(begin(mVolumeGroups), end(mVolumeGroups),
                                          [&group](const auto &volumeGroup) {
                     return group.volumeGroup == volumeGroup.second->getName(); });
-            if (group.stream != AUDIO_STREAM_DEFAULT) {
-                if (iter == end(mVolumeGroups)) {
-                    ALOGW("%s: No configuration of %s found, using default volume configuration"
-                            , __FUNCTION__, group.volumeGroup.c_str());
-                    defaultVolumeConfig.name = group.volumeGroup;
-                    sp<VolumeGroup> volumeGroup =
-                            loadVolumeConfig(mVolumeGroups, defaultVolumeConfig);
-                    addSupportedStreamAttributes(group, volumeGroup, strategy);
+            sp<VolumeGroup> volumeGroup = nullptr;
+            // If no volume group provided for this strategy, creates a new one using
+            // Music Volume Group configuration (considered as the default)
+            if (iter == end(mVolumeGroups)) {
+                engineConfig::VolumeGroup volumeConfig;
+                if (group.stream >= AUDIO_STREAM_PUBLIC_CNT) {
+                    volumeConfig = defaultSystemVolumeConfig;
                 } else {
-                    addSupportedStreamAttributes(group, iter->second, strategy);
+                    volumeConfig = defaultVolumeConfig;
                 }
+                ALOGW("%s: No configuration of %s found, using default volume configuration"
+                        , __FUNCTION__, group.volumeGroup.c_str());
+                volumeConfig.name = group.volumeGroup;
+                volumeGroup = loadVolumeConfig(mVolumeGroups, volumeConfig);
+            } else {
+                volumeGroup = iter->second;
             }
+            if (group.stream != AUDIO_STREAM_DEFAULT) {
+                // A legacy stream can be assigned once to a volume group
+                LOG_ALWAYS_FATAL_IF(checkStreamForGroups(group.stream, mVolumeGroups),
+                                    "stream %s already assigned to a volume group, "
+                                    "review the configuration", toString(group.stream).c_str());
+                volumeGroup->addSupportedStream(group.stream);
+            }
+            addSupportedAttributesToGroup(group, volumeGroup, strategy);
         }
         product_strategy_t strategyId = strategy->getId();
         mProductStrategies[strategyId] = strategy;
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index 632c356..b747dd6 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -2512,15 +2512,29 @@
         if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
             curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
         }
-
+        if (!(desc->isActive(vs) || isInCall())) {
+            continue;
+        }
+        if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
+                curDevices.find(device) == curDevices.end()) {
+            continue;
+        }
+        bool applyVolume = false;
+        if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
+            curSrcDevices.insert(device);
+            applyVolume = (curSrcDevices.find(
+                    Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
+        } else {
+            applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
+        }
+        if (!applyVolume) {
+            continue; // next output
+        }
         // Inter / intra volume group priority management: Loop on strategies arranged by priority
         // If a higher priority strategy is active, and the output is routed to a device with a
         // HW Gain management, do not change the volume
-        bool applyVolume = false;
         if (desc->useHwGain()) {
-            if (!(desc->isActive(toVolumeSource(group)) || isInCall())) {
-                continue;
-            }
+            applyVolume = false;
             for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
                 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
                                                        false /*preferredDevice*/);
@@ -2554,39 +2568,16 @@
             if (!applyVolume) {
                 continue; // next output
             }
-            status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
-                                                   (vs == toVolumeSource(AUDIO_STREAM_SYSTEM)?
-                                                        TOUCH_SOUND_FIXED_DELAY_MS : 0));
-            if (volStatus != NO_ERROR) {
-                status = volStatus;
-            }
-            continue;
         }
-        if (!(desc->isActive(vs) || isInCall())) {
-            continue;
-        }
-        if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
-                curDevices.find(device) == curDevices.end()) {
-            continue;
-        }
-        if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
-            curSrcDevices.insert(device);
-            applyVolume = (curSrcDevices.find(
-                    Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
-        } else {
-            applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
-        }
-        if (applyVolume) {
-            //FIXME: workaround for truncated touch sounds
-            // delayed volume change for system stream to be removed when the problem is
-            // handled by system UI
-            status_t volStatus = checkAndSetVolume(
-                        curves, vs, index, desc, curDevices,
-                        ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
-                             TOUCH_SOUND_FIXED_DELAY_MS : 0));
-            if (volStatus != NO_ERROR) {
-                status = volStatus;
-            }
+        //FIXME: workaround for truncated touch sounds
+        // delayed volume change for system stream to be removed when the problem is
+        // handled by system UI
+        status_t volStatus = checkAndSetVolume(
+                    curves, vs, index, desc, curDevices,
+                    ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
+                         TOUCH_SOUND_FIXED_DELAY_MS : 0));
+        if (volStatus != NO_ERROR) {
+            status = volStatus;
         }
     }
     mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
diff --git a/services/camera/libcameraservice/Android.bp b/services/camera/libcameraservice/Android.bp
index c50a3c6..072afd2 100644
--- a/services/camera/libcameraservice/Android.bp
+++ b/services/camera/libcameraservice/Android.bp
@@ -112,6 +112,10 @@
         "android.hardware.camera.device@3.5",
     ],
 
+    static_libs: [
+        "libbinderthreadstateutils",
+    ],
+
     export_shared_lib_headers: [
         "libbinder",
         "libcamera_client",
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index 6e5c979..c566485 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -43,6 +43,7 @@
 #include <binder/PermissionController.h>
 #include <binder/ProcessInfoService.h>
 #include <binder/IResultReceiver.h>
+#include <binderthreadstate/CallerUtils.h>
 #include <cutils/atomic.h>
 #include <cutils/properties.h>
 #include <cutils/misc.h>
@@ -1029,7 +1030,7 @@
 
     // Only allow clients who are being used by the current foreground device user, unless calling
     // from our own process OR the caller is using the cameraserver's HIDL interface.
-    if (!hardware::IPCThreadState::self()->isServingCall() && callingPid != getpid() &&
+    if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
             (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
         ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
                 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
@@ -1350,7 +1351,7 @@
     // If the thread serving this call is not a hwbinder thread and the caller
     // isn't the cameraserver itself, and the camera id being requested is to be
     // publically hidden, we should reject the connection.
-    if (!hardware::IPCThreadState::self()->isServingCall() &&
+    if (getCurrentServingCall() != BinderCallType::HWBINDER &&
             CameraThreadState::getCallingPid() != getpid() &&
             isPublicallyHiddenSecureCamera(cameraId)) {
         return true;
@@ -1371,7 +1372,8 @@
     String8 id = String8(cameraId);
     sp<CameraDeviceClient> client = nullptr;
     String16 clientPackageNameAdj = clientPackageName;
-    if (hardware::IPCThreadState::self()->isServingCall()) {
+
+    if (getCurrentServingCall() == BinderCallType::HWBINDER) {
         std::string vendorClient =
                 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
         clientPackageNameAdj = String16(vendorClient.c_str());
@@ -2404,7 +2406,7 @@
         }
         mClientPackageName = packages[0];
     }
-    if (!hardware::IPCThreadState::self()->isServingCall()) {
+    if (getCurrentServingCall() != BinderCallType::HWBINDER) {
         mAppOpsManager = std::make_unique<AppOpsManager>();
     }
 }
@@ -3027,7 +3029,7 @@
         const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
         int32_t state) {
 
-    bool isVendorClient = hardware::IPCThreadState::self()->isServingCall();
+    bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
     int32_t score_adj = isVendorClient ? kVendorClientScore : score;
     int32_t state_adj = isVendorClient ? kVendorClientState: state;
 
diff --git a/services/camera/libcameraservice/utils/CameraThreadState.cpp b/services/camera/libcameraservice/utils/CameraThreadState.cpp
index b9e344b..2352b80 100644
--- a/services/camera/libcameraservice/utils/CameraThreadState.cpp
+++ b/services/camera/libcameraservice/utils/CameraThreadState.cpp
@@ -17,33 +17,34 @@
 #include "CameraThreadState.h"
 #include <binder/IPCThreadState.h>
 #include <hwbinder/IPCThreadState.h>
+#include <binderthreadstate/CallerUtils.h>
 #include <unistd.h>
 
 namespace android {
 
 int CameraThreadState::getCallingUid() {
-    if (hardware::IPCThreadState::self()->isServingCall()) {
+    if (getCurrentServingCall() == BinderCallType::HWBINDER) {
         return hardware::IPCThreadState::self()->getCallingUid();
     }
     return IPCThreadState::self()->getCallingUid();
 }
 
 int CameraThreadState::getCallingPid() {
-    if (hardware::IPCThreadState::self()->isServingCall()) {
+    if (getCurrentServingCall() == BinderCallType::HWBINDER) {
         return hardware::IPCThreadState::self()->getCallingPid();
     }
     return IPCThreadState::self()->getCallingPid();
 }
 
 int64_t CameraThreadState::clearCallingIdentity() {
-    if (hardware::IPCThreadState::self()->isServingCall()) {
+    if (getCurrentServingCall() == BinderCallType::HWBINDER) {
         return hardware::IPCThreadState::self()->clearCallingIdentity();
     }
     return IPCThreadState::self()->clearCallingIdentity();
 }
 
 void CameraThreadState::restoreCallingIdentity(int64_t token) {
-    if (hardware::IPCThreadState::self()->isServingCall()) {
+    if (getCurrentServingCall() == BinderCallType::HWBINDER) {
         hardware::IPCThreadState::self()->restoreCallingIdentity(token);
     } else {
         IPCThreadState::self()->restoreCallingIdentity(token);
diff --git a/services/camera/libcameraservice/utils/ClientManager.h b/services/camera/libcameraservice/utils/ClientManager.h
index ec6f01c..35d25bf 100644
--- a/services/camera/libcameraservice/utils/ClientManager.h
+++ b/services/camera/libcameraservice/utils/ClientManager.h
@@ -35,7 +35,7 @@
 public:
     /**
      * Choosing to set mIsVendorClient through a parameter instead of calling
-     * hardware::IPCThreadState::self()->isServingCall() to protect against the
+     * getCurrentServingCall() == BinderCallType::HWBINDER to protect against the
      * case where the construction is offloaded to another thread which isn't a
      * hwbinder thread.
      */
@@ -237,7 +237,7 @@
     // We don't use the usual copy constructor here since we want to remember
     // whether a client is a vendor client or not. This could have been wiped
     // off in the incoming priority argument since an AIDL thread might have
-    // called hardware::IPCThreadState::self()->isServingCall() after refreshing
+    // called getCurrentServingCall() == BinderCallType::HWBINDER after refreshing
     // priorities for old clients through ProcessInfoService::getProcessStatesScoresFromPids().
     mPriority.setScore(priority.getScore());
     mPriority.setState(priority.getState());
diff --git a/services/mediaextractor/Android.bp b/services/mediaextractor/Android.bp
index e906500..16b036f 100644
--- a/services/mediaextractor/Android.bp
+++ b/services/mediaextractor/Android.bp
@@ -29,6 +29,9 @@
         "liblog",
         "libavservices_minijail",
     ],
+    header_libs: [
+        "bionic_libc_platform_headers",
+    ],
     target: {
         android: {
             product_variables: {
diff --git a/services/mediaextractor/main_extractorservice.cpp b/services/mediaextractor/main_extractorservice.cpp
index 3c4125b..afb7692 100644
--- a/services/mediaextractor/main_extractorservice.cpp
+++ b/services/mediaextractor/main_extractorservice.cpp
@@ -28,6 +28,8 @@
 #include <android-base/properties.h>
 #include <utils/misc.h>
 
+#include <bionic/reserved_signals.h>
+
 // from LOCAL_C_INCLUDES
 #include "MediaExtractorService.h"
 #include "MediaUtils.h"
@@ -49,6 +51,10 @@
 
     signal(SIGPIPE, SIG_IGN);
 
+    // Do not assist platform profilers (relevant only on debug builds).
+    // Otherwise, the signal handler can violate the seccomp policy.
+    signal(BIONIC_SIGNAL_PROFILER, SIG_IGN);
+
     //b/62255959: this forces libutis.so to dlopen vendor version of libutils.so
     //before minijail is on. This is dirty but required since some syscalls such
     //as pread64 are used by linker but aren't allowed in the minijail. By